Repository navigation
Expand file tree
/
Copy pathPickProcessor.cs
More file actions
270 lines (253 loc) · 11.6 KB
/
Copy pathPickProcessor.cs
File metadata and controls
270 lines (253 loc) · 11.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
/* ========================================================================
* 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.Globalization;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Opc.Ua;
using Opc.Ua.Client;
using Opc.Ua.Robotics.Client.Intent;
using Opc.Ua.RobotIntent;
namespace IntentViewerClient
{
internal sealed partial class PickProcessor : IDisposable
{
public PickProcessor(
RobotIntentControllerClient controller,
ISession session,
IReadOnlyList<TargetLocation> targets,
ILogger logger,
bool canCommand)
{
m_controller = controller;
m_session = session;
m_targets = targets;
m_logger = logger;
m_canCommand = canCommand;
}
public async Task ProcessPickAsync(string primPath, CancellationToken cancellationToken)
{
await m_pickGate.WaitAsync(cancellationToken).ConfigureAwait(false);
try
{
await ProcessPickCoreAsync(primPath, cancellationToken).ConfigureAwait(false);
}
finally
{
m_pickGate.Release();
}
}
public void Dispose()
{
m_pickGate.Dispose();
}
private async Task ProcessPickCoreAsync(string primPath, CancellationToken cancellationToken)
{
TargetLocation? target = m_targets.FirstOrDefault(
t => string.Equals(t.PrimPath, primPath, StringComparison.Ordinal));
if (target is null)
{
Console.Error.WriteLine($"Picked {primPath}, but the server did not publish a LocationType mapping for it.");
return;
}
Console.Error.WriteLine($"Picked {target.Name} at {target.PrimPath}; reading {target.LocationNodeId} Pose.");
Pose3DDataType pose;
try
{
pose = await Program.ReadLocationPoseForProcessorAsync(
m_session, target.LocationNodeId, cancellationToken).ConfigureAwait(false);
}
catch (ServiceResultException exception) when (exception.StatusCode == StatusCodes.BadUnexpectedError)
{
Console.Error.WriteLine(
$"Location {target.Name} ({target.LocationNodeId}) published a Pose value this " +
"client could not decode; skipping that target.");
return;
}
if (!m_canCommand)
{
Console.Error.WriteLine(
"Read-only mode: the client discovered and decoded the target, but did not submit an " +
"intent because command authority was not granted.");
return;
}
LinearMoveIntentDataType intent = RobotIntentBuilder
.LinearMove(pose, 0.35).CartesianSpeed(0.20).Exact().Build();
IntentSubmissionResult submission = await m_controller.TrySubmitIntentAsync(intent, cancellationToken)
.ConfigureAwait(false);
if (!submission.Accepted)
{
PrintRefusal(submission.Failure, submission.Message);
LogPickRefused(m_logger, target.PrimPath, submission.Failure, submission.Message.Text ?? string.Empty);
return;
}
Console.Error.WriteLine($"Intent admitted: {submission.IntentId}; operation {submission.Operation}.");
LogPickSubmitted(m_logger, target.PrimPath, submission.IntentId);
IntentOperationHandle handle = await m_controller.TrackOperationAsync(
submission.IntentId, submission.Operation, cancellationToken).ConfigureAwait(false);
await using (handle.ConfigureAwait(false))
{
handle.Changed += PrintSnapshot;
using var cancelWatchCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
Task cancelTask = WatchForCancelKeyAsync(handle, cancelWatchCts.Token);
IntentResultDataType result = await handle.Completion
.WaitAsync(cancellationToken).ConfigureAwait(false);
await cancelWatchCts.CancelAsync().ConfigureAwait(false);
await ObserveCancelWatchAsync(cancelTask).ConfigureAwait(false);
Console.Error.WriteLine("Operation terminal result:");
PrintResult(result);
LogPickCompleted(m_logger, submission.IntentId, handle.Current.ExecutionState);
}
}
private static async Task ObserveCancelWatchAsync(Task task)
{
try
{
await task.ConfigureAwait(false);
}
catch (OperationCanceledException)
{
}
}
private static async Task WatchForCancelKeyAsync(
IntentOperationHandle handle,
CancellationToken cancellationToken)
{
if (Console.IsInputRedirected)
{
return;
}
Console.Error.WriteLine("Press C while the robot is moving to request CancelIntent.");
while (!cancellationToken.IsCancellationRequested)
{
await Task.Delay(100, cancellationToken).ConfigureAwait(false);
if (!Console.KeyAvailable)
{
continue;
}
ConsoleKeyInfo key = Console.ReadKey(intercept: true);
if (key.Key != ConsoleKey.C)
{
continue;
}
IntentCommandOutcome outcome = await handle.CancelAsync(StopModeEnum.ProcessStop, cancellationToken)
.ConfigureAwait(false);
if (outcome.Accepted)
{
Console.Error.WriteLine(
"CancelIntent accepted. Waiting for ExecutionState=Cancelled; " +
"Cancelling is not terminal motion.");
}
else
{
Console.Error.WriteLine("CancelIntent refused by the server; continuing to observe the operation.");
}
return;
}
}
private static void PrintSnapshot(IntentOperationSnapshot snapshot)
{
string pose = FormatPose(snapshot.CurrentPose);
Console.Error.WriteLine(string.Format(
CultureInfo.InvariantCulture,
"State={0}; progress={1:0.0}%; pose={2}",
snapshot.ExecutionState,
snapshot.Progress,
pose));
if (snapshot.ExecutionState == ExecutionStateEnum.Cancelling)
{
Console.Error.WriteLine("ExecutionState=Cancelling is still in motion; waiting for Cancelled.");
}
}
private static void PrintResult(IntentResultDataType result)
{
Console.Error.WriteLine($" Failure: {result.Failure}");
Console.Error.WriteLine($" Message: {result.Message.Text}");
if (result.HasAchievedPose)
{
Console.Error.WriteLine($" AchievedPose: {FormatPose(result.AchievedPose)}");
}
}
private static void PrintRefusal(IntentFailureEnum failure, LocalizedText message)
{
Console.Error.WriteLine($"Intent refused: {failure} - {message.Text}");
string action = failure switch
{
IntentFailureEnum.SafetyStop or IntentFailureEnum.SafetyLimitExceeded =>
"Safety system refused the motion; this client observed that decision and will not override it.",
IntentFailureEnum.ControlNotOwned =>
"Retry after obtaining command authority or ask the current operator to release control.",
IntentFailureEnum.CapabilityNotSupported =>
"Re-plan with an intent the controller capability declaration accepts.",
IntentFailureEnum.ParameterInvalid =>
"Re-plan with slower or less restrictive motion constraints.",
IntentFailureEnum.QueueFull =>
"Retry after the controller drains its queue.",
_ =>
"Escalate to the operator with the server's refusal message."
};
Console.Error.WriteLine($"Decision: {action}");
}
private static string FormatPose(Pose3DDataType pose)
{
string frame = string.IsNullOrEmpty(pose.FrameId) ? "<default>" : pose.FrameId;
if (pose.Position.Count < 3)
{
return $"frame={frame}; position=<unavailable>";
}
return FormattableString.Invariant(
$"frame={frame}; x={pose.Position[0]:0.###}, y={pose.Position[1]:0.###}, z={pose.Position[2]:0.###}");
}
[LoggerMessage(EventId = IntentViewerClientEventIds.PickSubmitted, Level = LogLevel.Information,
Message = "Submitted pick {PrimPath} as intent {IntentId}.")]
private static partial void LogPickSubmitted(ILogger logger, string primPath, string intentId);
[LoggerMessage(EventId = IntentViewerClientEventIds.PickCompleted, Level = LogLevel.Information,
Message = "Intent {IntentId} completed in state {ExecutionState}.")]
private static partial void LogPickCompleted(
ILogger logger,
string intentId,
ExecutionStateEnum executionState);
[LoggerMessage(EventId = IntentViewerClientEventIds.PickRefused, Level = LogLevel.Warning,
Message = "Pick {PrimPath} was refused with {Failure}: {Message}.")]
private static partial void LogPickRefused(
ILogger logger,
string primPath,
IntentFailureEnum failure,
string message);
private readonly RobotIntentControllerClient m_controller;
private readonly ISession m_session;
private readonly IReadOnlyList<TargetLocation> m_targets;
private readonly ILogger m_logger;
private readonly bool m_canCommand;
private readonly SemaphoreSlim m_pickGate = new(1, 1);
}
}