mirror of
https://github.com/OPCFoundation/UA-.NETStandard.git
synced 2026-10-17 05:11:13 +08:00
466c5cb982
Follow-ups to #4165, plus the work that followed from re-checking this branch against the specification. Everything started as a defect found by review or by probing the running code; the specification is unchanged except where noted. The TLS certificate lifetime fix (#4196) and the OpenUSD work (#4198) were both merged into this branch. #4196 has since landed on master, so it no longer appears in this diff. #4198 was closed in favour of this PR and its content is here. The MCP trim/AOT work (#4228), the `DataGenerator` null `NodeId` fix (#4227) and the NodeSet external-parent import fix (#4229) have since been merged in as well. All three are closed in favour of this PR and their content is here, described under *Making the MCP libraries trim and AOT clean*, *A generator that returned the value you opted out of* and *A NodeSet parent that lived outside the import batch* below. ## A two-arm cell could not be built `IntentExecution` carried no controller identity, and there was effectively one `IIntentExecutor` per server. An executor handed an execution therefore could not tell **which arm** it was for, so a cell with two `IntentControllerType` instances — an ordinary configuration — was not expressible through the builder or DI. Both halves are addressed: - `IntentExecution` now carries `ControllerId` (`NodeId`, the OPC UA identity) and `ControllerName`, so one shared executor can discriminate; - DI gained per-controller registration — `AddRobotIntentExecutor<TExecutor>(controllerBrowseName)` and an instance overload — so two genuinely different executors can coexist. Resolution order is `WithExecutor` → per-controller DI registration → the single DI executor → a build-time throw. There is still **no silent fallback** to a rejecting executor; that was a Critical defect fixed in #4165 and it stays fixed. `IIntentExecutor` is unchanged, so this is purely additive. ## Declarations that were quietly untrue - **`Accepts<T>` silently discarded a redeclaration.** Declaring an intent type twice — say to narrow `cancelSupported` on the second call — kept the first, wider declaration and said nothing. That is the same class of defect as the capability-honesty problems #4165 fixed (`PauseSupported` declaring a pause the host could not perform; `Aborting` degrading silently to `Buffered`). Identical redeclarations remain idempotent; conflicting ones now throw `BadInvalidArgument`. - **`RI-Interop-40010` assumed Annex B item 3 rather than checking it.** It now requires exact set equality between the OPC 40010 `TaskProgramName` values and the Robot Intent `ProgramType.ProgramId` values. Both sides are readable from the address space without commanding the robot, which is what makes the requirement structural under §12.1. ## Two things the specification requires that this did not do Re-checking the implementation against the merged draft revision turned up two genuine violations. Both are fixed, and the NodeSet is untouched by either. - **Every graphed mission reported `Failed` on success.** `MissionRules.SelectTransition` returned `null` for two different situations — a graph *terminus*, which is the normal success path, and a branch point whose conditions all evaluated false — and the caller collapsed both into `Failed`/`NoTransition`. A three-way result (`Terminus` / `Selected` / `NoConditionMatched`) separates them, so a mission that runs to its end now completes. The failure reason surfaces through the inherited Part 10 result container rather than a new member. - **Facet URIs were never published.** An upstream `may` became a `shall` in the revision this branch adopts. `RobotIntentConformanceUris.Facets` held 31 URIs with **zero** production references — the set existed but nothing emitted it. The published set is now derived from `RobotIntentFacetCalculator`, the same authority that already computed `SupportedFacets`, rather than from a second hand-maintained list that could drift; a reflection test pins the two together. ## An easy client mistake `RequestAuthorityAsync` returns a lease the caller must remember to inspect. Forgetting makes every later submission fail with `ControlNotOwned` for reasons that are invisible at the call site. `RequireAuthorityAsync` throws instead, and names the current owner. `RequestAuthorityAsync` is untouched — inspecting and branching is legitimate. ## Letting an agent drive the robot New `tools/Opc.Ua.Mcp.Robotics` gives a language model the intent API as MCP tools: 36 across discovery, monitoring, direct control and missions, behind a `Robotics` tool profile, composable into any MCP host exactly as the existing OPC UA tool packages are. The `IntentViewerClient` sample hosts them behind `--mcp` (stdio by default, HTTP when `--view`, since MCP stdio and the in-process viewer would otherwise share stdout), and the sample gained a pallet scene so an agent can pick and stack parts and watch the result in the OpenUSD viewer. All the scene logic is server-side — no viewer or connector changes. Four gaps in the client API had to be filled first, since the tools are a thin layer over it and could not have been written honestly without them: `ReadStateAsync`, `ListOperationsAsync`/`ListMissionsAsync`, controller-level `CancelIntent`/`CancelAll`/`Pause`/`Resume`/`Retry`/`ReleaseControl`, and `WaitForCompletionAsync`. The tools refuse rather than paper over: a refusal from the server is returned with its `IntentFailureEnum` and never retried, and command authority is never acquired as a side effect of a tool call. **One defect this surfaced:** `--profile robotics` shipped 36 tools that could not do anything. Every robotics tool resolves a named OPC UA session and only the connection tools can open one, so with no `Connect` in the catalogue the whole profile failed. A test had pinned the defect in place, asserting the profile did *not* contain `Connect` on the line below the `diagnostics` assertion requiring it. Each package now declares its own requirement in its registration extension rather than the host special-casing it, so an application embedding `Opc.Ua.Mcp.Robotics` directly gets a usable catalogue without reproducing the host's pairing. `Full` still takes the connection tools from the core package, so they are never registered twice. The replacement test states the invariant — a profile exposing session-scoped tools must expose the tools that open a session — rather than the instance. ## Making the MCP libraries trim and AOT clean *Merged from #4228.* `Opc.Ua.Mcp.Core` is now `IsAotCompatible` on `net10.0`, and the reflection the analysers then reported is gone. Turning the analysers on is the point: until now they were not running on these libraries at all — including on the tool library this branch adds. - **`OpcUaJsonHelper.Serialize`** went through `JsonSerializer` (IL2026 / IL3050). The conversion helpers in that class already reduce every OPC UA value to a closed set — `null`, the primitive scalars, `string`, `Dictionary<string, object?>` and lists thereof — so the JSON is now written directly with a `Utf8JsonWriter`. Output is unchanged, and that is asserted rather than assumed: `OpcUaJsonHelperTests.SerializeMatchesTheReflectionBasedSerializer` compares the new writer byte for byte against `JsonSerializer` for every shape the helpers emit, including all numeric widths, the custom-formatted scalars, nested sequences and strings that force the encoder to escape. One deliberate contract change: arbitrary object graphs are no longer accepted. Serializing them needs reflection, so `Serialize` now throws `NotSupportedException` naming the type instead of silently stringifying it. No call site in the repository passes anything outside the closed set. - **`McpSchemaFilters`** used `JsonSerializer.SerializeToElement` on a `JsonObject`; it now parses the node's own text, which needs no reflection. `Opc.Ua.Mcp.Diagnostics` is deliberately **not** marked. It depends on SharpPcap and on the reflective service-call dissection in `Opc.Ua.Core.Diagnostics`, neither of which is trim safe — which is why that package does not opt in either. Two improvements are kept regardless: `PacketDecodeTools` serializes `DecodedServiceCall` through a source-generated `JsonSerializerContext`, and `PacketCaptureTools.ListInterfaces` now carries the `RequiresUnreferencedCode` / `RequiresDynamicCode` annotations that `NetworkInterfaceEnumerator.ListLocalInterfaces` already declares, so the constraint is visible to callers instead of implicit. Nothing is suppressed. Marking an assembly `IsAotCompatible` only proves its own IL is clean; it says nothing about whether the library still functions once reflection is gone. So `Opc.Ua.Aot.Tests` references `Opc.Ua.Mcp.Core` and exercises it with JSON reflection disabled, stating what is and is not true today: - tool **results** serialize without reflection — this would fail outright if the `Utf8JsonWriter` change regressed; - tool **registration** still requires reflection, because the MCP SDK builds each tool's input schema by asking `JsonSchemaExporter` for a `JsonTypeInfo` of every parameter type. Without a source-generated context covering the tool signatures — and with the injected `OpcUaSessionManager` being described rather than treated as a service — that throws `NotSupportedException`. The second test asserts the throw. It documents the remaining gap and turns red the moment someone closes it, rather than leaving it to be found in a published binary. The package README says the same thing in prose. **Two pre-existing issues this surfaced, both outside this PR:** pulling `Opc.Ua.Mcp.Diagnostics` into an AOT publish reports `IL2046` / `IL3051` on `NicCaptureSource.StartAsync`, which is annotated `RequiresUnreferencedCode` / `RequiresDynamicCode` while the `ICaptureSource.StartAsync` it implements is not, and `IL2075` on `ServiceCallReassembler.GetCollectionCount` / `GetPropertyString`, which call `Type.GetProperty` on the result of `GetType()`. Happy to file these separately if useful. ## A generator that returned the value you opted out of *Merged from #4227. Fixes #4226.* `GetRandomNodeId(useBoundaryValues: false)` could still return `NodeId.Null` — one of the boundary values the same method offers when boundary values *are* requested. A caller that opted out should not receive one, and `GetRandomExpandedNodeId` builds on it and inherited the same behaviour. The `IdType.Opaque` branch is the practical path: `GetRandomByteString()` draws its length with `NextInt32(MaxStringLength)`, which is inclusive of zero, and a zero-length opaque identifier in namespace 0 satisfies `NodeId.IsNull`. With three namespaces and `MaxStringLength` at 10 that is roughly **one call in 130**. A numeric identifier of `0` in namespace 0 is null too, at around one in four billion. The draw is now repeated while the result is null and boundary values were not requested. Guarding the result rather than the individual branches covers every identifier type, including the numeric case, rather than only the one that happens to be reachable today. The `useBoundaryValues: true` path is untouched, so boundary values remain available when they are asked for. Four tests in `tests/Opc.Ua.Core.Tests/Types/DataGeneratorTests.cs` loop 20,000 draws, because at one call in 130 a single draw proves nothing. Against the **unmodified** generator they fail on draw 93 and draw 1346. Two of the four exist to keep the fix honest rather than to test the bug: `GetRandomNodeIdStillProducesEveryIdentifierType` catches a "fix" that simply stopped emitting opaque identifiers, which would satisfy the null assertions while silently narrowing the generator, and `GetRandomNodeIdWithBoundaryValuesStillYieldsThem` confirms the leak was closed rather than the feature removed. **How it was found:** an intermittent downstream test failure. A test server initialising a static `NodeId`-valued variable via `TestDataSystem.ReadValue` occasionally stored `NodeId.Null`; the encoder correctly writes that as JSON `null`, and a consumer asserting a value was present failed about one run in five — never reproducibly in isolation. It only surfaced under load because `UnsecureRandom.Shared` is a fixed-seed, process-global generator shared between `DataGenerator` and OPC UA transport jitter, so the number of draws preceding address-space initialisation depends on what else is running in the process. ## A NodeSet parent that lived outside the import batch *Merged from #4229.* `UANodeSetHelpers.LinkParentChildRelationships` builds its lookup table from **only the nodes in the current import batch**, links a child when the parent is found — and then cleared `instance.Handle` **unconditionally**, which is exactly where `Import` had stashed the authored `ParentNodeId`. A node whose parent lives in another NodeSet, or is owned by another NodeManager, therefore lost that parent **silently** at import, and nothing downstream could recover it. `RuntimeNodeSetNodeManager.CreateAddressSpaceAsync` already has a step that wires references to external node managers; the parent link never reached it. Such a parent is now recorded rather than discarded, and exposed through `UANodeSet.TryGetUnresolvedParentNodeId`. A parent that resolved normally inside the batch is **not** recorded, so a caller does not re-wire references that already exist. The record lives in a `ConditionalWeakTable`, so it does not keep an imported node alive and does not widen `NodeState` — whose `Handle` is a general-purpose slot a caller may legitimately use for its own purposes, and so is not a safe place to leave the value. `RuntimeNodeSetNodeManager` consumes it to report the one case that cannot be repaired automatically. In NodeSet2 the `ParentNodeId` attribute is a *hint*; the authoritative edge is the entry under `<References>`, which the reverse-reference pass already turns into an external reference. A node that names an out-of-manager parent but carries **no such Reference** materializes with no path from that parent, and no ReferenceType can be inferred to synthesise one — so it is reported as an authoring defect rather than guessed at or silently accepted. This is deliberately **not** a fix for a specific address-space symptom. It removes a silent loss of authored information and gives callers the means to act on it. Whether any particular orphaned-node report is caused by this path, or by namespace-index translation elsewhere, still needs separate diagnosis. **Changed while merging.** As authored in #4229 the accessor was `GetUnresolvedParentNodeId`, returning `NodeId?`. `NodeId` is a readonly struct implementing `INullable`, so that was a `System.Nullable<NodeId>` wrapped around a type that already carries its own null representation — which this repository excludes in favour of an `IsNull` check, and it asks for `TryGet` over casting on struct types. The tests correspondingly asserted `Is.Null` against a struct, which the testing rules also exclude. It is now `bool TryGetUnresolvedParentNodeId(NodeState, out NodeId)`, yielding `NodeId.Null` when there is no unresolved parent. The API is unshipped — it arrives with this branch — so nothing depended on the previous shape. Both tests were re-verified by mutation after the rewrite: disabling the record in `LinkParentChildRelationships` still fails `ImportKeepsAParentThatIsNotInTheSameBatch`. ## Dependencies - **OpenUSD to `0.7.0-alpha`.** All 11 issues we filed upstream are fixed, so the workarounds they justified are gone and the parts of the pump and generator samples that were blocked on them are implemented. - **ModelContextProtocol to `2.1.0`** across all five MCP tool libraries and the executable. No code changes were needed — the surface we use is unchanged in 2.x — but central package management required a cascade of pins, each commented where it sits. Both transports were verified against a running server rather than assumed. MCP 2.x is stateless (no `initialize`, no `Mcp-Session-Id`); an OPC UA session is application state addressed by a caller-supplied name, which fits that model but does assume process affinity, and that assumption is now written down rather than implied. ## Infrastructure The `code coverage` gate was measuring nothing on this branch and reporting success. It is fixed and now enforced, which immediately exposed real gaps — most usefully `RoboticsIntentJson`, which parses agent-supplied JSON (untrusted input from a language model) and had no tests at all. It is now at full line coverage in CI. Patch coverage is **90.20%** against a 75% floor. The `netstandard2.1` build leg was also failing. The MCP projects build as empty shells under a legacy `CustomTestTarget`, and the viewer sample referenced them on the target framework alone, so it tried to resolve a net10.0 shell from net8.0. The sample now derives MCP support from whether those projects are actually being built. ## From review A review pass over the branch found two real defects, both fixed. `RoboticsIntentJson` parses JSON written by a language model, so every malformed shape it can be handed is reachable input; it indexed pose arrays without checking their length and enumerated properties without checking their kind, so a short or wrongly-typed array escaped as `IndexOutOfRangeException` or `InvalidOperationException` rather than the argument error the tool descriptions promise the agent. Separately, `IntentOperationHandle` treated a zero `QueuePosition` as "not observed" and discarded it, so a handle kept reporting the last queued position after the server had said the operation left the queue. The pose validation immediately caught a latent test defect: the pallet scenario interpolated doubles into JSON with the current culture, so under a comma-decimal culture `[0.12, 0.16, 0.28]` became a six-element array. It passed only because that submission is expected to be refused for want of authority, so the wrong coordinates were never used. A third review finding — that a default-constructed `RobotIntentControllerState` hands out a null `NodeId` — was checked and rejected: `NodeId`, `QualifiedName` and `LocalizedText` are readonly structs here, so `default` is the null value and `IsNull` is `true`. The tests asserting that invariant are kept. A second review pass over the merged branch found two more, both fixed and both about an error surfacing as the wrong kind of failure rather than about a wrong result: - **Malformed agent JSON did not arrive as an argument error.** `RoboticsIntentJson` turns every *validation* failure into an `ArgumentException` — a wrong root kind, a missing property, a short pose array — but three `JsonDocument.Parse` calls and the NodeId parse were unguarded. A syntax error escaped as `JsonException` and an unparseable NodeId as `ServiceResultException`, which are the two shapes a language model is most likely to produce. That is the same defect class as the pose/kind checking above: a caller separating bad input from a genuine fault had to know to catch three unrelated exception types. Parsing now goes through one helper that reports a syntax error as an `ArgumentException` naming the argument, keeping the `JsonException` as the inner exception so the position is not lost, and the NodeId goes through `NodeId.TryParse` rather than `Parse`, collapsing its two failure modes into one. `MalformedIntentJsonIsRejected` had asserted `InstanceOf<JsonException>`, pinning the behaviour rather than the intended contract; it now asserts `ArgumentException` like every neighbouring test, and three tests cover the newly guarded paths. - **`ConditionalWeakTable.Add` throws on a duplicate key.** Not reachable today, but `TryGetUnresolvedParentNodeId` documents `Handle` as a general-purpose slot a caller may use for its own purposes — and a caller doing exactly that before re-importing into the same collection would take a hard throw from inside the import pipeline. Removing first makes the most recent import win. `AddOrUpdate` would say this more directly but does not exist on `netstandard2.0`. ## Deliberately not fixed here `FastenIntentDataType.Joint` is refused when the Server exposes no OPC 40450/40451 model, and a client cannot discover that before calling. That is **not fixable in this repository**: §5.4.2 makes `Joint` the defining mechanism while §11.3 says the parameters otherwise stand alone, and `IntentCapabilityDataType` declares capabilities at intent-type granularity with no member-level mechanism anywhere in the model. It is a specification gap, raised as S4 on [marcschier/opcua-drafts#60](https://github.com/marcschier/opcua-drafts/pull/60) rather than worked around with a bespoke mechanism the spec does not define. ## Validation `dotnet build UA.slnx -c Release` on the merged branch — **0 errors, 0 warnings**, with the AOT analysers now running over `Opc.Ua.Mcp.Core`. | Suite (net10.0) | Tests | |---|---| | `Opc.Ua.Core.Tests` | 4247 (86 skipped) | | `Opc.Ua.Robotics.Tests` | 540 | | `Opc.Ua.OpenUsd.Tests` | 909 | | `Opc.Ua.Tools.Tests` | 419 | | `Opc.Ua.Server.Tests` — `RuntimeNodeSet` | 94 | | `Opc.Ua.Robotics.Intent.Tests` | 22 | | `Opc.Ua.Aot.Tests` — `McpAotTests` | 3 | 0 failures. `Opc.Ua.Tools.Tests` rose from 409 to 419 with the serializer-equivalence tests from #4228 and the malformed-JSON tests from the second review pass, and `Opc.Ua.Core.Tests` covers the `DataGenerator` tests from #4227 and the import tests from #4229. `UANodeSetHelpers` also passes on **net48** (5/5). The MCP agent-usability grader scores Core 100 / Full 100. --------- Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com> Copilot-Session: a248a589-9a20-4372-868e-5d347e57001b Copilot-Session: 9e6a5abf-3299-4cd1-9855-010fedbf0ad8 Copilot-Session: a0718e8a-a158-45c5-929d-e1d6c0982431
688 lines
29 KiB
C#
688 lines
29 KiB
C#
/* ========================================================================
|
|
* Copyright (c) 2005-2026 The OPC Foundation, Inc. All rights reserved.
|
|
*
|
|
* OPC Foundation MIT License 1.00
|
|
*
|
|
* Permission is hereby granted, free of charge, to any person
|
|
* obtaining a copy of this software and associated documentation
|
|
* files (the "Software"), to deal in the Software without
|
|
* restriction, including without limitation the rights to use,
|
|
* copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
* copies of the Software, and to permit persons to whom the
|
|
* Software is furnished to do so, subject to the following
|
|
* conditions:
|
|
*
|
|
* The above copyright notice and this permission notice shall be
|
|
* included in all copies or substantial portions of the Software.
|
|
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
|
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
|
|
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
|
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
|
|
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
|
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
|
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
|
|
* OTHER DEALINGS IN THE SOFTWARE.
|
|
*
|
|
* The complete license agreement can be found here:
|
|
* http://opcfoundation.org/License/MIT/1.00/
|
|
* ======================================================================*/
|
|
|
|
using System;
|
|
using System.Collections.Generic;
|
|
using System.Threading;
|
|
using System.Threading.Tasks;
|
|
using Microsoft.Extensions.Logging;
|
|
using Opc.Ua;
|
|
using Opc.Ua.Robotics.Server;
|
|
using Opc.Ua.Robotics.Server.Builders;
|
|
using Opc.Ua.RobotIntent;
|
|
using Opc.Ua.Server;
|
|
using Robotics.IntentEnabledRobot.Kinematics;
|
|
using Robotics.IntentEnabledRobot.Simulation;
|
|
using ThreeDCartesianCoordinates = Opc.Ua.ThreeDCartesianCoordinates;
|
|
using ThreeDFrame = Opc.Ua.ThreeDFrame;
|
|
using ThreeDOrientation = Opc.Ua.ThreeDOrientation;
|
|
|
|
namespace Robotics.IntentEnabledRobot
|
|
{
|
|
/// <summary>
|
|
/// Builds the minimal Robot Intent sample cell.
|
|
/// </summary>
|
|
public sealed partial class IntentRobotCell : IDisposable
|
|
{
|
|
/// <summary>
|
|
/// Creates the sample cell configurator.
|
|
/// </summary>
|
|
public IntentRobotCell(
|
|
ILogger<IntentRobotCell> logger,
|
|
SimulatedArmExecutor executor,
|
|
SampleSafetySource safetySource)
|
|
{
|
|
m_logger = logger ?? throw new ArgumentNullException(nameof(logger));
|
|
m_executor = executor ?? throw new ArgumentNullException(nameof(executor));
|
|
m_safetySource = safetySource ?? throw new ArgumentNullException(nameof(safetySource));
|
|
m_executor.SnapshotChanged += OnSnapshotChanged;
|
|
}
|
|
|
|
internal AsyncCustomNodeManager Manager => m_manager ??
|
|
throw new InvalidOperationException(
|
|
"IntentRobotCell has not been attached to a Robot Intent build context.");
|
|
|
|
internal ServerSystemContext SystemContext => m_systemContext ??
|
|
throw new InvalidOperationException(
|
|
"IntentRobotCell has not been attached to a Robot Intent build context.");
|
|
|
|
internal IIntentControllerBuilder Controller => m_controller ??
|
|
throw new InvalidOperationException(
|
|
"The intent controller has not been materialised.");
|
|
|
|
internal IEnumerable<global::Opc.Ua.RobotIntent.AxisState> Axes => m_axes;
|
|
|
|
internal IEnumerable<global::Opc.Ua.RobotIntent.LocationState> Locations => m_locations;
|
|
|
|
internal IReadOnlyDictionary<string, NodeId> LocationNodes => m_locationNodes;
|
|
|
|
/// <summary>
|
|
/// Configures Robot Intent and OpenUSD nodes.
|
|
/// </summary>
|
|
public async ValueTask ConfigureAsync(IRobotIntentBuildContext context, CancellationToken cancellationToken)
|
|
{
|
|
if (context == null)
|
|
{
|
|
throw new ArgumentNullException(nameof(context));
|
|
}
|
|
|
|
m_manager = context.Manager;
|
|
m_systemContext = context.Manager.SystemContext;
|
|
await MaterialiseOpenUsdFacilityAsync(cancellationToken).ConfigureAwait(false);
|
|
m_controller = await context.AddIntentControllerAsync(
|
|
"UR5eIntentController",
|
|
ConfigureController,
|
|
cancellationToken).ConfigureAwait(false);
|
|
await MaterialiseRepresentationsAsync(cancellationToken).ConfigureAwait(false);
|
|
PublishSnapshot(m_executor.CurrentSnapshot);
|
|
ArrayOf<string> facets = m_controller.ComputeFacets();
|
|
m_logger.IntentCellReady(m_axes.Count, m_locations.Count, facets);
|
|
}
|
|
|
|
/// <inheritdoc/>
|
|
public void Dispose()
|
|
{
|
|
m_executor.SnapshotChanged -= OnSnapshotChanged;
|
|
}
|
|
|
|
private void ConfigureController(IIntentControllerBuilder controller)
|
|
{
|
|
controller
|
|
.WithOperationalMode(OperationalModeEnum.AutomaticExternal)
|
|
.WithReady(true)
|
|
.WithMaxQueueDepth(16)
|
|
.Accepts<JointMoveIntentDataType>(cancelSupported: true)
|
|
.Accepts<LinearMoveIntentDataType>(cancelSupported: true, pauseSupported: true)
|
|
.Accepts<CircularMoveIntentDataType>(cancelSupported: true)
|
|
.Accepts<TrajectoryIntentDataType>(cancelSupported: true)
|
|
.Accepts<CartesianPathIntentDataType>(cancelSupported: true)
|
|
.Accepts<GraspIntentDataType>(cancelSupported: false)
|
|
.Accepts<ReleaseIntentDataType>(cancelSupported: true)
|
|
.Accepts<PickIntentDataType>(cancelSupported: false)
|
|
.Accepts<PlaceIntentDataType>(cancelSupported: true)
|
|
.Accepts<ToolChangeIntentDataType>(cancelSupported: false)
|
|
.Accepts<WaitIntentDataType>(cancelSupported: true, pauseSupported: true, retrySupported: true)
|
|
.WithSafetyState(m_safetySource);
|
|
|
|
controller.State.Capabilities!.MissionsSupported!.Value = true;
|
|
controller.State.Capabilities.MissionHorizonSupported!.Value = true;
|
|
controller.State.Capabilities.MissionBranchingSupported!.Value = true;
|
|
controller.State.Capabilities.BlendingSupported!.Value = false;
|
|
controller.State.Capabilities.ForceControlSupported!.Value = false;
|
|
controller.State.Capabilities.MaxTrajectoryPoints!.Value = 64u;
|
|
|
|
IIntentFrameBuilder world = controller.AddFrame(
|
|
"World",
|
|
WorldFrameId,
|
|
FrameRoleEnum.World,
|
|
Pose(WorldFrameId, 0.0, 0.0, 0.0));
|
|
IIntentFrameBuilder @base = controller.AddFrame(
|
|
"Base",
|
|
BaseFrameId,
|
|
FrameRoleEnum.Base,
|
|
Pose(WorldFrameId, 0.0, 0.0, 0.829),
|
|
frame => frame.WithParent(world));
|
|
IIntentFrameBuilder flange = controller.AddFrame(
|
|
"MechanicalInterface",
|
|
FlangeFrameId,
|
|
FrameRoleEnum.MechanicalInterface,
|
|
Pose(BaseFrameId, 0.0, 0.0, 0.1625),
|
|
frame => frame.WithParent(@base));
|
|
IIntentFrameBuilder tool = controller.AddFrame(
|
|
"GripperTcp",
|
|
ToolFrameId,
|
|
FrameRoleEnum.Tool,
|
|
Pose(FlangeFrameId, 0.0, 0.0, 0.115),
|
|
frame => frame.WithParent(flange));
|
|
controller.AddTool("ParallelGripper", tool, fitted: true);
|
|
|
|
for (uint index = 0; index < s_axisUsd.Length; index++)
|
|
{
|
|
IIntentAxisBuilder axis = controller.AddAxis(s_axisUsd[index].Name, index, AxisKindEnum.Revolute);
|
|
ConfigureAxis(axis.State, index == 2 ? -Math.PI : -FullTurn, index == 2 ? Math.PI : FullTurn);
|
|
m_axes.Add(axis.State);
|
|
}
|
|
|
|
foreach ((string name, string _, double x, double y, double z, double rz) in s_locations)
|
|
{
|
|
uint capacity = string.Equals(name, "Bin", StringComparison.Ordinal) ||
|
|
string.Equals(name, "Fixture", StringComparison.Ordinal)
|
|
? PayloadSlotCount
|
|
: 1u;
|
|
IIntentLocationBuilder location = controller.AddLocation(
|
|
name,
|
|
Pose(WorldFrameId, x, y, z, rz),
|
|
builder => builder.WithOccupancy(string.Equals(name, "Bin", StringComparison.Ordinal), capacity));
|
|
m_locations.Add(location.State);
|
|
m_locationNodes[name] = location.State.NodeId;
|
|
}
|
|
|
|
IIntentOutputSignalBuilder gripperOpen = controller.AddOutput(
|
|
"GripperOpen",
|
|
Opc.Ua.DataTypeIds.Boolean,
|
|
ToVariant(true));
|
|
IIntentOutputSignalBuilder benchLight = controller.AddOutput(
|
|
"BenchLight",
|
|
Opc.Ua.DataTypeIds.Boolean,
|
|
ToVariant(false));
|
|
IIntentOutputSignalBuilder heldPartPosition = controller.AddOutput(
|
|
"HeldPartPosition",
|
|
Opc.Ua.DataTypeIds.Double,
|
|
ToVariant(m_executor.CurrentSnapshot.HeldPartPosition));
|
|
IIntentOutputSignalBuilder heldPartVisible = controller.AddOutput(
|
|
"HeldPartVisible",
|
|
Opc.Ua.DataTypeIds.Boolean,
|
|
ToVariant(false));
|
|
m_gripperOpenValue = gripperOpen.State.Value;
|
|
m_benchLightValue = benchLight.State.Value;
|
|
m_heldPartPositionValue = heldPartPosition.State.Value;
|
|
m_heldPartVisibleValue = heldPartVisible.State.Value;
|
|
|
|
for (int ii = 0; ii < PayloadSlotCount; ii++)
|
|
{
|
|
IIntentOutputSignalBuilder slotFilled = controller.AddOutput(
|
|
$"PayloadSlot{ii + 1:00}Filled",
|
|
Opc.Ua.DataTypeIds.Boolean,
|
|
ToVariant(false));
|
|
m_payloadSlotFilledValues.Add(slotFilled.State.Value);
|
|
}
|
|
|
|
controller.AddRealTimeChannel(
|
|
"JointTelemetry", "joint-telemetry", RealTimeTransportEnum.OpcUaFx, "udp://239.0.0.40:4840");
|
|
controller.WithDescription(description => description
|
|
.WithKinematicChain(CreateKinematicChain())
|
|
.WithLimits(
|
|
SimulatedArmKinematics.Reach,
|
|
payloadLimit: 5.0,
|
|
maxCartesianSpeed: 0.25,
|
|
maxCartesianAcceleration: 0.7));
|
|
}
|
|
|
|
private void ConfigureAxis(global::Opc.Ua.RobotIntent.AxisState axis, double min, double max)
|
|
{
|
|
axis.CreateOrReplaceMinPosition(SystemContext, null!).Value = min;
|
|
axis.CreateOrReplaceMaxPosition(SystemContext, null!).Value = max;
|
|
axis.CreateOrReplaceMaxSpeed(SystemContext, null!).Value = 2.0;
|
|
if (axis.Position != null)
|
|
{
|
|
axis.Position.Value = 0.0;
|
|
}
|
|
}
|
|
|
|
private ArrayOf<KinematicJointDataType> CreateKinematicChain()
|
|
{
|
|
var joints = new KinematicJointDataType[s_axisUsd.Length];
|
|
for (int ii = 0; ii < joints.Length; ii++)
|
|
{
|
|
joints[ii] = new KinematicJointDataType
|
|
{
|
|
AxisId = s_axisUsd[ii].Name,
|
|
Kind = AxisKindEnum.Revolute,
|
|
OriginTransform = Pose(
|
|
ii == 0 ? BaseFrameId : s_axisUsd[ii - 1].Name, 0.0, 0.0, ii == 0 ? 0.1625 : 0.12),
|
|
AxisVector = s_axisUsd[ii].AxisVector
|
|
};
|
|
}
|
|
return joints.ToArrayOf();
|
|
}
|
|
|
|
private void OnSnapshotChanged(object? sender, SimulatedArmSnapshot snapshot)
|
|
{
|
|
PublishSnapshot(snapshot);
|
|
}
|
|
|
|
private void PublishSnapshot(SimulatedArmSnapshot snapshot)
|
|
{
|
|
for (int ii = 0; ii < m_axes.Count && ii < snapshot.JointAngles.Count; ii++)
|
|
{
|
|
global::Opc.Ua.RobotIntent.AxisState axis = m_axes[ii];
|
|
if (axis.Position != null)
|
|
{
|
|
axis.Position.Value = snapshot.JointAngles[ii] * 180.0 / Math.PI;
|
|
axis.Position.ClearChangeMasks(SystemContext, true);
|
|
}
|
|
}
|
|
if (m_gripperOpenValue != null)
|
|
{
|
|
m_gripperOpenValue.Value = snapshot.GripperOpening > 0.04;
|
|
m_gripperOpenValue.ClearChangeMasks(SystemContext, true);
|
|
}
|
|
if (m_benchLightValue != null)
|
|
{
|
|
m_benchLightValue.Value = snapshot.HasObject;
|
|
m_benchLightValue.ClearChangeMasks(SystemContext, true);
|
|
}
|
|
if (m_heldPartPositionValue != null)
|
|
{
|
|
m_heldPartPositionValue.Value = snapshot.HeldPartPosition;
|
|
m_heldPartPositionValue.ClearChangeMasks(SystemContext, true);
|
|
}
|
|
if (m_heldPartVisibleValue != null)
|
|
{
|
|
m_heldPartVisibleValue.Value = snapshot.HasObject;
|
|
m_heldPartVisibleValue.ClearChangeMasks(SystemContext, true);
|
|
}
|
|
int filledCount = 0;
|
|
for (int ii = 0; ii < m_payloadSlotFilledValues.Count && ii < snapshot.StackSlotsFilled.Count; ii++)
|
|
{
|
|
bool filled = snapshot.StackSlotsFilled[ii];
|
|
if (filled)
|
|
{
|
|
filledCount++;
|
|
}
|
|
BaseVariableState? slot = m_payloadSlotFilledValues[ii];
|
|
if (slot != null)
|
|
{
|
|
slot.Value = filled;
|
|
slot.ClearChangeMasks(SystemContext, true);
|
|
}
|
|
}
|
|
UpdateLocationOccupancy("Bin", filledCount < PayloadSlotCount || snapshot.HasObject);
|
|
UpdateLocationOccupancy("Fixture", filledCount > 0);
|
|
}
|
|
|
|
private void UpdateLocationOccupancy(string name, bool occupied)
|
|
{
|
|
global::Opc.Ua.RobotIntent.LocationState? location = FindLocation(name);
|
|
if (location?.Occupied != null)
|
|
{
|
|
location.Occupied.Value = occupied;
|
|
location.Occupied.ClearChangeMasks(SystemContext, true);
|
|
}
|
|
}
|
|
|
|
private static Pose3DDataType Pose(string frameId, double x, double y, double z, double rzDegrees = 0.0)
|
|
{
|
|
return PoseMath.FromThreeDFrame(
|
|
new ThreeDFrame
|
|
{
|
|
CartesianCoordinates = new ThreeDCartesianCoordinates
|
|
{
|
|
X = x,
|
|
Y = y,
|
|
Z = z
|
|
},
|
|
Orientation = new ThreeDOrientation
|
|
{
|
|
C = rzDegrees * Math.PI / 180.0
|
|
}
|
|
},
|
|
frameId);
|
|
}
|
|
|
|
private static ArrayOf<double> Vector(double x, double y, double z)
|
|
{
|
|
return new[] { x, y, z }.ToArrayOf();
|
|
}
|
|
|
|
private static Variant ToVariant(bool value)
|
|
{
|
|
var builder = new VariantBuilder();
|
|
return ((IVariantBuilder<bool>)builder).WithValue(value);
|
|
}
|
|
|
|
private static Variant ToVariant(double value)
|
|
{
|
|
var builder = new VariantBuilder();
|
|
return ((IVariantBuilder<double>)builder).WithValue(value);
|
|
}
|
|
|
|
private static Variant ToVariant(ArrayOf<double> value)
|
|
{
|
|
var builder = new VariantBuilder();
|
|
return ((IVariantBuilder<ArrayOf<double>>)builder).WithValue(value);
|
|
}
|
|
|
|
private static Guid GuidFor(string key)
|
|
{
|
|
byte[] hash;
|
|
#pragma warning disable CA1850 // Prefer static HashData (net48/netstandard2.0 compatibility)
|
|
using (var sha = System.Security.Cryptography.SHA256.Create())
|
|
{
|
|
hash = sha.ComputeHash(System.Text.Encoding.UTF8.GetBytes("minimal-intent:" + key));
|
|
}
|
|
#pragma warning restore CA1850
|
|
byte[] guidBytes = new byte[16];
|
|
Array.Copy(hash, guidBytes, guidBytes.Length);
|
|
return new Guid(guidBytes);
|
|
}
|
|
|
|
private const string WorldFrameId = "world";
|
|
private const string BaseFrameId = "ur5e-base";
|
|
private const string FlangeFrameId = "ur5e-flange";
|
|
private const string ToolFrameId = "parallel-gripper-tcp";
|
|
private const double FullTurn = Math.PI * 2.0;
|
|
private const int PayloadSlotCount = 8;
|
|
|
|
private static readonly (string Name, string PrimPath, double X, double Y, double Z, double Rz)[] s_locations =
|
|
[
|
|
("Bin", "/World/Targets/Bin", 0.41, -0.28, 0.829, 0.0),
|
|
("Fixture", "/World/Targets/Fixture", 0.48, 0.26, 0.829, 25.0),
|
|
("Inspect", "/World/Targets/Inspect", -0.25, 0.30, 0.829, -20.0),
|
|
("Handoff", "/World/Targets/Handoff", -0.46, -0.26, 0.829, 40.0)
|
|
];
|
|
|
|
private static readonly (string Name, string PrimPath, string RotateOp, ArrayOf<double> AxisVector)[]
|
|
s_axisUsd =
|
|
[
|
|
("J1", "/Arm/Base/J1", "xformOp:rotateZ", Vector(0.0, 0.0, 1.0)),
|
|
("J2", "/Arm/Base/J1/J2", "xformOp:rotateY", Vector(0.0, 1.0, 0.0)),
|
|
("J3", "/Arm/Base/J1/J2/J3", "xformOp:rotateY", Vector(0.0, 1.0, 0.0)),
|
|
("J4", "/Arm/Base/J1/J2/J3/J4", "xformOp:rotateY", Vector(0.0, 1.0, 0.0)),
|
|
("J5", "/Arm/Base/J1/J2/J3/J4/J5", "xformOp:rotateZ", Vector(0.0, 0.0, 1.0)),
|
|
("J6", "/Arm/Base/J1/J2/J3/J4/J5/J6", "xformOp:rotateY", Vector(0.0, 1.0, 0.0))
|
|
];
|
|
|
|
private readonly ILogger<IntentRobotCell> m_logger;
|
|
private readonly SimulatedArmExecutor m_executor;
|
|
private readonly SampleSafetySource m_safetySource;
|
|
private readonly List<global::Opc.Ua.RobotIntent.AxisState> m_axes = [];
|
|
private readonly List<global::Opc.Ua.RobotIntent.LocationState> m_locations = [];
|
|
private readonly Dictionary<string, NodeId> m_locationNodes = new(StringComparer.Ordinal);
|
|
private readonly List<BaseVariableState?> m_payloadSlotFilledValues = [];
|
|
private AsyncCustomNodeManager? m_manager;
|
|
private ServerSystemContext? m_systemContext;
|
|
private IIntentControllerBuilder? m_controller;
|
|
private BaseVariableState? m_gripperOpenValue;
|
|
private BaseVariableState? m_benchLightValue;
|
|
private BaseVariableState? m_heldPartPositionValue;
|
|
private BaseVariableState? m_heldPartVisibleValue;
|
|
}
|
|
|
|
internal static partial class IntentRobotCellLog
|
|
{
|
|
[LoggerMessage(EventId = IntentEnabledRobotEventIds.IntentRobotCell + 1,
|
|
Level = LogLevel.Information,
|
|
Message = "Materialised IntentEnabledRobot ({AxisCount} axes, " +
|
|
"{LocationCount} locations, facets {Facets}).")]
|
|
public static partial void IntentCellReady(
|
|
this ILogger logger, int axisCount, int locationCount, ArrayOf<string> facets);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Mutable read-only safety source driven by the console sample commands.
|
|
/// </summary>
|
|
public sealed class SampleSafetySource : IRobotIntentSafetySource
|
|
{
|
|
/// <inheritdoc/>
|
|
public ValueTask<RobotIntentSafetySnapshot> ReadAsync(CancellationToken cancellationToken)
|
|
{
|
|
cancellationToken.ThrowIfCancellationRequested();
|
|
lock (m_lock)
|
|
{
|
|
return ValueTask.FromResult(m_snapshot);
|
|
}
|
|
}
|
|
|
|
internal void Reset()
|
|
{
|
|
Set(new RobotIntentSafetySnapshot(
|
|
SafeMotionFunctionEnum.None,
|
|
EmergencyStopActive: false,
|
|
ProtectiveStopActive: false,
|
|
SafeSpeedLimitActive: false,
|
|
SafeSpeedLimit: 0.0,
|
|
SafetyControllerOk: true,
|
|
LastStopReason: LocalizedText.Null));
|
|
}
|
|
|
|
internal void TripProtectiveStop()
|
|
{
|
|
Set(new RobotIntentSafetySnapshot(
|
|
SafeMotionFunctionEnum.Ss1,
|
|
EmergencyStopActive: false,
|
|
ProtectiveStopActive: true,
|
|
SafeSpeedLimitActive: false,
|
|
SafeSpeedLimit: 0.0,
|
|
SafetyControllerOk: true,
|
|
LastStopReason: LocalizedText.From("Simulated protective stop")));
|
|
}
|
|
|
|
internal void LimitSpeed(double limit)
|
|
{
|
|
Set(new RobotIntentSafetySnapshot(
|
|
SafeMotionFunctionEnum.Sls,
|
|
EmergencyStopActive: false,
|
|
ProtectiveStopActive: false,
|
|
SafeSpeedLimitActive: true,
|
|
SafeSpeedLimit: limit,
|
|
SafetyControllerOk: true,
|
|
LastStopReason: LocalizedText.From($"Simulated safe speed limit {limit:0.###} m/s")));
|
|
}
|
|
|
|
private void Set(RobotIntentSafetySnapshot snapshot)
|
|
{
|
|
lock (m_lock)
|
|
{
|
|
m_snapshot = snapshot;
|
|
}
|
|
}
|
|
|
|
private readonly Lock m_lock = new();
|
|
|
|
private RobotIntentSafetySnapshot m_snapshot = new(
|
|
SafeMotionFunctionEnum.None,
|
|
EmergencyStopActive: false,
|
|
ProtectiveStopActive: false,
|
|
SafeSpeedLimitActive: false,
|
|
SafeSpeedLimit: 0.0,
|
|
SafetyControllerOk: true,
|
|
LastStopReason: LocalizedText.Null);
|
|
}
|
|
|
|
internal sealed class SafetyAwareArmExecutor : IIntentExecutor
|
|
{
|
|
public SafetyAwareArmExecutor(SimulatedArmExecutor inner, SampleSafetySource safety)
|
|
{
|
|
m_inner = inner ?? throw new ArgumentNullException(nameof(inner));
|
|
m_safety = safety ?? throw new ArgumentNullException(nameof(safety));
|
|
}
|
|
|
|
public async ValueTask<IntentOutcome> ExecuteAsync(
|
|
IntentExecution execution,
|
|
CancellationToken cancellationToken)
|
|
{
|
|
RobotIntentSafetySnapshot safety = await m_safety.ReadAsync(cancellationToken).ConfigureAwait(false);
|
|
if (safety.ProtectiveStopActive || safety.EmergencyStopActive || !safety.SafetyControllerOk)
|
|
{
|
|
return IntentOutcome.Fail(
|
|
IntentFailureEnum.NotPermittedInMode,
|
|
safety.LastStopReason.Text ?? "The simulated safety system is stopping motion.");
|
|
}
|
|
if (safety.SafeSpeedLimitActive &&
|
|
safety.SafeSpeedLimit > 0.0 &&
|
|
ExceedsSafeSpeed(execution.Intent, safety.SafeSpeedLimit))
|
|
{
|
|
return IntentOutcome.Fail(
|
|
IntentFailureEnum.SafetyLimitExceeded,
|
|
$"The requested speed exceeds the simulated safe limit of {safety.SafeSpeedLimit:0.###} m/s.");
|
|
}
|
|
if (execution.Intent is LinearMoveIntentDataType linear)
|
|
{
|
|
IntentOutcome approach = await MoveToApproachAsync(
|
|
execution,
|
|
linear,
|
|
cancellationToken).ConfigureAwait(false);
|
|
if (approach.State != ExecutionStateEnum.Succeeded)
|
|
{
|
|
return approach;
|
|
}
|
|
}
|
|
return await m_inner.ExecuteAsync(execution, cancellationToken).ConfigureAwait(false);
|
|
}
|
|
|
|
public bool CanCancel(IntentExecution execution)
|
|
{
|
|
return m_inner.CanCancel(execution);
|
|
}
|
|
|
|
private async ValueTask<IntentOutcome> MoveToApproachAsync(
|
|
IntentExecution execution,
|
|
LinearMoveIntentDataType linear,
|
|
CancellationToken cancellationToken)
|
|
{
|
|
Pose3DDataType target = linear.Target;
|
|
ReadOnlySpan<double> position = target.Position.Span;
|
|
if (position.Length != 3)
|
|
{
|
|
return IntentOutcome.Fail(
|
|
IntentFailureEnum.ParameterInvalid,
|
|
"A linear move target must carry a 3D position.");
|
|
}
|
|
var approach = new Pose3DDataType
|
|
{
|
|
FrameId = target.FrameId,
|
|
Position = new[]
|
|
{
|
|
position[0],
|
|
position[1],
|
|
position[2] - TargetApproachOffset
|
|
}.ToArrayOf(),
|
|
Orientation = target.Orientation.IsNull
|
|
? ArrayOf<double>.Empty
|
|
: target.Orientation.Span.ToArray().ToArrayOf()
|
|
};
|
|
var jointMove = new JointMoveIntentDataType
|
|
{
|
|
IntentId = execution.IntentId + "-approach",
|
|
Label = LocalizedText.From("Approach " + linear.Label.Text),
|
|
Constraints = linear.Constraints
|
|
};
|
|
if (m_kinematics.TrySelectNearest(
|
|
approach,
|
|
m_inner.CurrentSnapshot.JointAngles.Span,
|
|
out SimulatedArmIkSolution? solution,
|
|
out SimulatedArmKinematicFailure failure))
|
|
{
|
|
jointMove.HasJointTargets = true;
|
|
jointMove.JointTargets = solution.JointAngles;
|
|
}
|
|
else
|
|
{
|
|
return IntentOutcome.Fail(
|
|
SimulatedArmKinematics.ToIntentFailure(failure),
|
|
"The target approach pose cannot be reached.");
|
|
}
|
|
var approachExecution = new IntentExecution(
|
|
execution.IntentId + "-approach",
|
|
jointMove,
|
|
execution.Progress)
|
|
{
|
|
MissionId = execution.MissionId
|
|
};
|
|
return await m_inner.ExecuteAsync(approachExecution, cancellationToken).ConfigureAwait(false);
|
|
}
|
|
|
|
private static bool ExceedsSafeSpeed(IntentDataType intent, double safeSpeedLimit)
|
|
{
|
|
return intent is MotionIntentDataType motion &&
|
|
motion.Constraints.CartesianSpeed > 0.0 &&
|
|
motion.Constraints.CartesianSpeed > safeSpeedLimit;
|
|
}
|
|
|
|
private const double TargetApproachOffset = 0.05;
|
|
|
|
private readonly SimulatedArmExecutor m_inner;
|
|
private readonly SimulatedArmKinematics m_kinematics = new();
|
|
private readonly SampleSafetySource m_safety;
|
|
}
|
|
|
|
internal sealed class SafetyConsoleService : Microsoft.Extensions.Hosting.BackgroundService
|
|
{
|
|
public SafetyConsoleService(SampleSafetySource safety, ILogger<SafetyConsoleService> logger)
|
|
{
|
|
m_safety = safety ?? throw new ArgumentNullException(nameof(safety));
|
|
m_logger = logger ?? throw new ArgumentNullException(nameof(logger));
|
|
}
|
|
|
|
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
|
|
{
|
|
m_logger.SafetyCommandsReady();
|
|
while (!stoppingToken.IsCancellationRequested)
|
|
{
|
|
string? line = await Console.In.ReadLineAsync(stoppingToken).ConfigureAwait(false);
|
|
if (line == null)
|
|
{
|
|
return;
|
|
}
|
|
ApplyCommand(line.Trim());
|
|
}
|
|
}
|
|
|
|
private void ApplyCommand(string command)
|
|
{
|
|
if (command.Equals("stop", StringComparison.OrdinalIgnoreCase))
|
|
{
|
|
m_safety.TripProtectiveStop();
|
|
m_logger.ProtectiveStopActive();
|
|
}
|
|
else if (command.StartsWith("limit", StringComparison.OrdinalIgnoreCase))
|
|
{
|
|
string[] parts = command.Split(
|
|
' ', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
|
|
double limit = parts.Length > 1 && double.TryParse(parts[1], out double parsed) ? parsed : 0.05;
|
|
m_safety.LimitSpeed(limit);
|
|
m_logger.SafeSpeedLimitActive(limit);
|
|
}
|
|
else if (command.Equals("reset", StringComparison.OrdinalIgnoreCase))
|
|
{
|
|
m_safety.Reset();
|
|
m_logger.SafetyReset();
|
|
}
|
|
}
|
|
|
|
private readonly SampleSafetySource m_safety;
|
|
private readonly ILogger<SafetyConsoleService> m_logger;
|
|
}
|
|
|
|
internal static partial class SafetyConsoleLog
|
|
{
|
|
[LoggerMessage(EventId = IntentEnabledRobotEventIds.SafetyConsole + 1,
|
|
Level = LogLevel.Information,
|
|
Message = "Safety commands: type 'stop', 'limit <m/s>' or 'reset' in the console.")]
|
|
public static partial void SafetyCommandsReady(this ILogger logger);
|
|
|
|
[LoggerMessage(EventId = IntentEnabledRobotEventIds.SafetyConsole + 2,
|
|
Level = LogLevel.Warning,
|
|
Message = "Simulated protective stop is active; submitted intents are refused with NotPermittedInMode.")]
|
|
public static partial void ProtectiveStopActive(this ILogger logger);
|
|
|
|
[LoggerMessage(EventId = IntentEnabledRobotEventIds.SafetyConsole + 3,
|
|
Level = LogLevel.Warning,
|
|
Message = "Simulated safe speed limit is {Limit} m/s; faster motions are refused " +
|
|
"with SafetyLimitExceeded.")]
|
|
public static partial void SafeSpeedLimitActive(this ILogger logger, double limit);
|
|
|
|
[LoggerMessage(EventId = IntentEnabledRobotEventIds.SafetyConsole + 4,
|
|
Level = LogLevel.Information,
|
|
Message = "Simulated safety state reset to nominal.")]
|
|
public static partial void SafetyReset(this ILogger logger);
|
|
}
|
|
}
|