using Opc.Ua; using Opc.Ua.Server; using System.Collections.Concurrent; using Timer = System.Timers.Timer; namespace Lab505.Sim; /// /// RcsNodeManager - OPC UA Simulation Node Manager /// NodeId values mirror RCSNodeIds.g.cs (Lab505.Infrastructure.Protocols.OpcUa.RCSNodeIds). /// Numeric IDs use the registered namespace index; string IDs use method browse-names. /// public class RcsNodeManager : CustomNodeManager2, IDisposable { private readonly ushort _ns; /// Counter reserved only for method InputArguments/OutputArguments property nodes. private uint _argId = 60000; private Timer? _timer; private readonly Random _rand = new(); private readonly ConcurrentDictionary _resetTokens = new(); private readonly ConcurrentDictionary _motionTokens = new(); #region Node References — mirrors RCSNodeIds.g.cs structure // Objects (numeric IDs from RCSNodeIds) private BaseObjectState? _imr; // 50265 private BaseObjectState? _navigation; // 50231 private BaseObjectState? _conveyorBelts; // 50286 private BaseObjectState? _dobot; // 50266 private BaseObjectState? _slam; // 50510 private BaseObjectState? _monitoring; // 50261 private BaseObjectState? _robotPose; // 50221 // Navigation (RCSNodeIds: StatusString=50253, StatusEnum=50254, Feedback=50255) private BaseDataVariableState? _navStatusString; private BaseDataVariableState? _navStatusEnum; private BaseDataVariableState? _feedback; // ConveyorBelts (RCSNodeIds: StatusString_2=50293, StatusEnum_2=50294) private BaseDataVariableState? _beltStatusString; private BaseDataVariableState? _beltStatusEnum; // Dobot (RCSNodeIds: StateString=50280, StateEnum=50281, DobotStatusCode=50285, // DobotMode=50284, CountOK=50282, CountNG=50283, HaveGoods=50295) private BaseDataVariableState? _stateString; private BaseDataVariableState? _stateEnum; private BaseDataVariableState? _dobotStatusCode; private BaseDataVariableState? _dobotMode; private BaseDataVariableState? _countOK; private BaseDataVariableState? _countNG; private BaseDataVariableState? _haveGoods; // SLAM / RobotPose (RCSNodeIds: X=50222, Y=50223, Yaw=50224, // CurrentActiveMap=50225, SlamState=50226, WorkingDirectories=50227) private BaseDataVariableState? _x; private BaseDataVariableState? _y; private BaseDataVariableState? _yaw; private BaseDataVariableState? _slamState; private BaseDataVariableState? _currentActiveMap; private BaseDataVariableState? _workingDirectories; // Monitoring (RCSNodeIds: Vx=50262, Vy=50263, Omega=50264) private BaseDataVariableState? _vx; private BaseDataVariableState? _vy; private BaseDataVariableState? _omega; #endregion // NodeId helpers — values match RCSNodeIds.g.cs constants private NodeId N(uint id) => new(id, _ns); private NodeId S(string name) => new(name, _ns); public RcsNodeManager(IServerInternal server, ApplicationConfiguration configuration) : base(server, configuration, ["http://lab505/rcs"]) { SystemContext.NodeIdFactory = this; _ns = (ushort)NamespaceIndexes[0]; Console.WriteLine($"[RcsNodeManager] namespace='{NamespaceUris.ToArray()[0]}' index={_ns}"); } #region Address Space Creation public override void CreateAddressSpace(IDictionary> externalReferences) { lock (Lock) { // ── Root object ────────────────────────────────────────── _imr = CreateObject("IMR", N(50265)); AddToObjectsFolder(_imr, externalReferences); _navigation = CreateChild(_imr, "Navigation", N(50231)); _conveyorBelts = CreateChild(_imr, "ConveyorBelts", N(50286)); _dobot = CreateChild(_imr, "Dobot", N(50266)); _slam = CreateChild(_imr, "SLAM", N(50510)); _monitoring = CreateChild(_imr, "Monitoring", N(50261)); // ── Navigation ─────────────────────────────────────────── _navStatusString = CreateVariable(_navigation, "StatusString", N(50253), "Idle"); _navStatusEnum = CreateVariable(_navigation, "StatusEnum", N(50254), 0u); _feedback = CreateVariable(_navigation, "Feedback", N(50255), ""); CreateNavigationMethods(); // ── ConveyorBelts ───────────────────────────────────────── _beltStatusString = CreateVariable(_conveyorBelts, "StatusString_2", N(50293), "Idle"); _beltStatusEnum = CreateVariable(_conveyorBelts, "StatusEnum_2", N(50294), 0u); CreateConveyorMethods(); // ── Dobot ───────────────────────────────────────────────── _stateString = CreateVariable(_dobot, "StateString", N(50280), "Idle"); _stateEnum = CreateVariable(_dobot, "StateEnum", N(50281), 0u); _dobotStatusCode = CreateVariable(_dobot, "DobotStatusCode", N(50285), 0u); _dobotMode = CreateVariable(_dobot, "DobotMode", N(50284), 0u); _countOK = CreateVariable(_dobot, "CountOK", N(50282), 0u); _countNG = CreateVariable(_dobot, "CountNG", N(50283), 0u); _haveGoods = CreateVariable(_dobot, "HaveGoods", N(50295), false); CreateDobotMethods(); // ── SLAM / RobotPose ────────────────────────────────────── _robotPose = CreateChild(_slam, "RobotPose", N(50221)); _x = CreateVariable(_robotPose, "X", N(50222), 0.0); _y = CreateVariable(_robotPose, "Y", N(50223), 0.0); _yaw = CreateVariable(_robotPose, "Yaw", N(50224), 0.0); _currentActiveMap = CreateVariable(_slam, "CurrentActiveMap", N(50225), ""); _slamState = CreateVariable(_slam, "SlamState", N(50226), "IDLE"); _workingDirectories = CreateArrayVariable(_slam, "WorkingDirectories", N(50227), Array.Empty()); // ── Monitoring ──────────────────────────────────────────── _vx = CreateVariable(_monitoring, "Vx", N(50262), 0.0); _vy = CreateVariable(_monitoring, "Vy", N(50263), 0.0); _omega = CreateVariable(_monitoring, "Omega", N(50264), 0.0); _timer = new Timer(1000) { AutoReset = true }; _timer.Elapsed += TimerElapsed; _timer.Start(); Console.WriteLine("[RcsNodeManager] Address space created"); } } private void CreateNavigationMethods() { // RCSNodeIds: MoveStraight = new NodeId("MoveStraight", 1) CreateMethod(_navigation!, "MoveStraight", S("MoveStraight"), MoveStraightHandler, inArgs: [ new Argument { Name = "Distance", DataType = DataTypeIds.Double, ValueRank = ValueRanks.Scalar }, new Argument { Name = "Velocity", DataType = DataTypeIds.Double, ValueRank = ValueRanks.Scalar } ], outArgs: [ new Argument { Name = "Code", DataType = DataTypeIds.UInt32, ValueRank = ValueRanks.Scalar }, new Argument { Name = "Message", DataType = DataTypeIds.String, ValueRank = ValueRanks.Scalar } ]); // RCSNodeIds: MoveToNode = new NodeId("MoveToNode", 1) CreateMethod(_navigation!, "MoveToNode", S("MoveToNode"), MoveToNodeHandler, inArgs: [ new Argument { Name = "NodeId", DataType = DataTypeIds.UInt32, ValueRank = ValueRanks.Scalar }, new Argument { Name = "Spline", DataType = DataTypeIds.Double, ValueRank = ValueRanks.TwoDimensions } ], outArgs: [ new Argument { Name = "Code", DataType = DataTypeIds.UInt32, ValueRank = ValueRanks.Scalar }, new Argument { Name = "Message", DataType = DataTypeIds.String, ValueRank = ValueRanks.Scalar } ]); // RCSNodeIds: MoveToPickup = new NodeId("MoveToPickup", 1) CreateMethod(_navigation!, "MoveToPickup", S("MoveToPickup"), MoveToPickupHandler, inArgs: [ new Argument { Name = "PickupId", DataType = DataTypeIds.UInt32, ValueRank = ValueRanks.Scalar }, new Argument { Name = "Spline", DataType = DataTypeIds.Double, ValueRank = ValueRanks.OneDimension } ], outArgs: [ new Argument { Name = "Code", DataType = DataTypeIds.UInt32, ValueRank = ValueRanks.Scalar }, new Argument { Name = "Message", DataType = DataTypeIds.String, ValueRank = ValueRanks.Scalar } ]); // RCSNodeIds: MoveToDropDown = new NodeId("MoveToDropDown", 1) CreateMethod(_navigation!, "MoveToDropDown", S("MoveToDropDown"), MoveToDropDownHandler, inArgs: [ new Argument { Name = "DropId", DataType = DataTypeIds.UInt32, ValueRank = ValueRanks.Scalar }, new Argument { Name = "Spline", DataType = DataTypeIds.Double, ValueRank = ValueRanks.OneDimension } ], outArgs: [ new Argument { Name = "Code", DataType = DataTypeIds.UInt32, ValueRank = ValueRanks.Scalar }, new Argument { Name = "Message", DataType = DataTypeIds.String, ValueRank = ValueRanks.Scalar } ]); // RCSNodeIds: InitialPose = new NodeId("Initial Pose", 1) CreateMethod(_navigation!, "Initial Pose", S("Initial Pose"), InitialPoseHandler, inArgs: [ new Argument { Name = "X", DataType = DataTypeIds.Double, ValueRank = ValueRanks.Scalar }, new Argument { Name = "Y", DataType = DataTypeIds.Double, ValueRank = ValueRanks.Scalar }, new Argument { Name = "Yaw", DataType = DataTypeIds.Double, ValueRank = ValueRanks.Scalar } ], outArgs: [ new Argument { Name = "Code", DataType = DataTypeIds.UInt32, ValueRank = ValueRanks.Scalar }, new Argument { Name = "Message", DataType = DataTypeIds.String, ValueRank = ValueRanks.Scalar } ]); // RCSNodeIds: RotateTo = new NodeId("RotateTo", 1) CreateMethod(_navigation!, "RotateTo", S("RotateTo"), RotateToHandler, inArgs: [ new Argument { Name = "Angle", DataType = DataTypeIds.Double, ValueRank = ValueRanks.Scalar }, new Argument { Name = "Tolerance", DataType = DataTypeIds.Double, ValueRank = ValueRanks.Scalar } ], outArgs: [ new Argument { Name = "Code", DataType = DataTypeIds.UInt32, ValueRank = ValueRanks.Scalar }, new Argument { Name = "Message", DataType = DataTypeIds.String, ValueRank = ValueRanks.Scalar } ]); // RCSNodeIds: MutedSafety = new NodeId("Muted Safety", 1) CreateMethod(_navigation!, "Muted Safety", S("Muted Safety"), MutedSafetyHandler, inArgs: [ new Argument { Name = "Enabled", DataType = DataTypeIds.Boolean, ValueRank = ValueRanks.Scalar } ], outArgs: [ new Argument { Name = "Code", DataType = DataTypeIds.UInt32, ValueRank = ValueRanks.Scalar }, new Argument { Name = "Message", DataType = DataTypeIds.String, ValueRank = ValueRanks.Scalar } ]); // RCSNodeIds: ActivateMap = new NodeId("ActivateMap", 1) CreateMethod(_navigation!, "ActivateMap", S("ActivateMap"), ActivateMapHandler, inArgs: [ new Argument { Name = "MapName", DataType = DataTypeIds.String, ValueRank = ValueRanks.Scalar } ], outArgs: [ new Argument { Name = "Code", DataType = DataTypeIds.UInt32, ValueRank = ValueRanks.Scalar }, new Argument { Name = "Message", DataType = DataTypeIds.String, ValueRank = ValueRanks.Scalar } ]); // RCSNodeIds: GetMapFiles = new NodeId("GetMapFiles", 1) CreateMethod(_navigation!, "GetMapFiles", S("GetMapFiles"), GetMapFilesHandler, outArgs: [ new Argument { Name = "Maps", DataType = DataTypeIds.String, ValueRank = ValueRanks.OneDimension }, new Argument { Name = "Message", DataType = DataTypeIds.String, ValueRank = ValueRanks.Scalar } ]); // Simple no-arg methods // RCSNodeIds: Cancel="Cancel", Pause="Pause", Resume="Resume", Reset="Reset" CreateMethod(_navigation!, "Cancel", S("Cancel"), CancelNavHandler); CreateMethod(_navigation!, "Pause", S("Pause"), PauseHandler); CreateMethod(_navigation!, "Resume", S("Resume"), ResumeHandler); CreateMethod(_navigation!, "Reset", S("Reset"), ResetNavHandler); } private void CreateConveyorMethods() { // RCSNodeIds: Load="Load", UnLoad="UnLoad", ResetBelt="ResetBelt" CreateMethod(_conveyorBelts!, "Load", S("Load"), LoadBeltHandler); CreateMethod(_conveyorBelts!, "UnLoad", S("UnLoad"), UnloadBeltHandler); CreateMethod(_conveyorBelts!, "ResetBelt", S("ResetBelt"), ResetBeltHandler); } private void CreateDobotMethods() { // RCSNodeIds: CancelDobot, ContinueDobot, PowerOnDobot, GoHomeDobot CreateMethod(_dobot!, "CancelDobot", S("CancelDobot"), CancelDobotHandler); CreateMethod(_dobot!, "ContinueDobot", S("ContinueDobot"), ContinueDobotHandler); CreateMethod(_dobot!, "PowerOnDobot", S("PowerOnDobot"), PowerOnDobotHandler); CreateMethod(_dobot!, "GoHomeDobot", S("GoHomeDobot"), GoHomeDobotHandler); // RCSNodeIds: PickUp = new NodeId("PickUp", 1) CreateMethod(_dobot!, "PickUp", S("PickUp"), PickUpHandler, inArgs: [ new Argument { Name = "CountOk", DataType = DataTypeIds.Int32, ValueRank = ValueRanks.Scalar, Description = new LocalizedText("Number of OK items") }, new Argument { Name = "CountNg", DataType = DataTypeIds.Int32, ValueRank = ValueRanks.Scalar, Description = new LocalizedText("Number of NG items") } ], outArgs: [ new Argument { Name = "Code", DataType = DataTypeIds.UInt32, ValueRank = ValueRanks.Scalar }, new Argument { Name = "Message", DataType = DataTypeIds.String, ValueRank = ValueRanks.Scalar } ]); // RCSNodeIds: SetQuantityOfGoods = new NodeId("SetQuantityOfGoods", 1) CreateMethod(_dobot!, "SetQuantityOfGoods", S("SetQuantityOfGoods"), SetQuantityOfGoodsHandler, inArgs: [ new Argument { Name = "OK", DataType = DataTypeIds.UInt32, ValueRank = ValueRanks.Scalar }, new Argument { Name = "NG", DataType = DataTypeIds.UInt32, ValueRank = ValueRanks.Scalar } ], outArgs: [ new Argument { Name = "Code", DataType = DataTypeIds.UInt32, ValueRank = ValueRanks.Scalar }, new Argument { Name = "Message", DataType = DataTypeIds.String, ValueRank = ValueRanks.Scalar } ]); } #endregion #region Node Creation Helpers private BaseObjectState CreateObject(string name, NodeId nodeId) { var node = new BaseObjectState(null) { NodeId = nodeId, BrowseName = new QualifiedName(name, _ns), DisplayName = name, TypeDefinitionId = ObjectTypeIds.BaseObjectType }; AddPredefinedNode(SystemContext, node); return node; } private BaseObjectState CreateChild(BaseObjectState parent, string name, NodeId nodeId) { var node = new BaseObjectState(parent) { NodeId = nodeId, BrowseName = new QualifiedName(name, _ns), DisplayName = name, TypeDefinitionId = ObjectTypeIds.BaseObjectType }; AddPredefinedNode(SystemContext, node); parent.AddReference(ReferenceTypeIds.Organizes, false, node.NodeId); node.AddReference(ReferenceTypeIds.Organizes, true, parent.NodeId); parent.AddChild(node); return node; } private void AddToObjectsFolder(BaseObjectState node, IDictionary> externalRefs) { if (!externalRefs.TryGetValue(ObjectIds.ObjectsFolder, out var refs)) { refs = new List(); externalRefs[ObjectIds.ObjectsFolder] = refs; } refs.Add(new NodeStateReference(ReferenceTypeIds.Organizes, false, node.NodeId)); node.AddReference(ReferenceTypeIds.Organizes, true, ObjectIds.ObjectsFolder); } private BaseDataVariableState CreateVariable(BaseObjectState parent, string name, NodeId nodeId, T initialValue) { var node = new BaseDataVariableState(parent) { NodeId = nodeId, BrowseName = new QualifiedName(name, _ns), DisplayName = name, TypeDefinitionId = VariableTypeIds.BaseDataVariableType, DataType = TypeInfo.GetDataTypeId(typeof(T)), ValueRank = ValueRanks.Scalar, AccessLevel = AccessLevels.CurrentReadOrWrite, UserAccessLevel = AccessLevels.CurrentReadOrWrite, Value = initialValue, StatusCode = StatusCodes.Good, Timestamp = DateTime.UtcNow }; AddPredefinedNode(SystemContext, node); parent.AddReference(ReferenceTypeIds.HasComponent, false, node.NodeId); node.AddReference(ReferenceTypeIds.HasComponent, true, parent.NodeId); parent.AddChild(node); return node; } private BaseDataVariableState CreateArrayVariable(BaseObjectState parent, string name, NodeId nodeId, T[] initialValue) { var node = new BaseDataVariableState(parent) { NodeId = nodeId, BrowseName = new QualifiedName(name, _ns), DisplayName = name, TypeDefinitionId = VariableTypeIds.BaseDataVariableType, DataType = TypeInfo.GetDataTypeId(typeof(T)), ValueRank = ValueRanks.OneDimension, ArrayDimensions = null, AccessLevel = AccessLevels.CurrentReadOrWrite, UserAccessLevel = AccessLevels.CurrentReadOrWrite, Value = initialValue, StatusCode = StatusCodes.Good, Timestamp = DateTime.UtcNow }; AddPredefinedNode(SystemContext, node); parent.AddReference(ReferenceTypeIds.HasComponent, false, node.NodeId); node.AddReference(ReferenceTypeIds.HasComponent, true, parent.NodeId); parent.AddChild(node); return node; } private MethodState CreateMethod( BaseObjectState parent, string displayName, NodeId nodeId, GenericMethodCalledEventHandler handler, Argument[]? inArgs = null, Argument[]? outArgs = null) { var method = new MethodState(parent) { NodeId = nodeId, BrowseName = new QualifiedName(displayName, _ns), DisplayName = displayName, Executable = true, UserExecutable = true }; AddPredefinedNode(SystemContext, method); parent.AddReference(ReferenceTypeIds.HasComponent, false, method.NodeId); method.AddReference(ReferenceTypeIds.HasComponent, true, parent.NodeId); parent.AddChild(method); method.OnCallMethod = handler; if (inArgs is { Length: > 0 }) { var prop = new PropertyState(method) { NodeId = new NodeId(_argId++, _ns), BrowseName = BrowseNames.InputArguments, DisplayName = "InputArguments", TypeDefinitionId = VariableTypeIds.PropertyType, DataType = DataTypeIds.Argument, ValueRank = ValueRanks.OneDimension, AccessLevel = AccessLevels.CurrentRead, UserAccessLevel = AccessLevels.CurrentRead, Value = inArgs }; AddPredefinedNode(SystemContext, prop); method.AddReference(ReferenceTypeIds.HasProperty, false, prop.NodeId); prop.AddReference(ReferenceTypeIds.HasProperty, true, method.NodeId); method.InputArguments = prop; method.AddChild(prop); } if (outArgs is { Length: > 0 }) { var prop = new PropertyState(method) { NodeId = new NodeId(_argId++, _ns), BrowseName = BrowseNames.OutputArguments, DisplayName = "OutputArguments", TypeDefinitionId = VariableTypeIds.PropertyType, DataType = DataTypeIds.Argument, ValueRank = ValueRanks.OneDimension, AccessLevel = AccessLevels.CurrentRead, UserAccessLevel = AccessLevels.CurrentRead, Value = outArgs }; AddPredefinedNode(SystemContext, prop); method.AddReference(ReferenceTypeIds.HasProperty, false, prop.NodeId); prop.AddReference(ReferenceTypeIds.HasProperty, true, method.NodeId); method.OutputArguments = prop; method.AddChild(prop); } return method; } #endregion #region Navigation Handlers private ServiceResult MoveStraightHandler(ISystemContext context, MethodState method, IList input, IList output) { Console.WriteLine("[OPC-SIM] MoveStraight called"); if (input.Count < 2 || !TryToDouble(input[0], out var distance) || !TryToDouble(input[1], out var velocity)) return BadArgs(output, "Distance and Velocity required"); Console.WriteLine($"[OPC-SIM] MoveStraight: distance={distance}, velocity={velocity}"); return RunModuleMotion(output, _navStatusString!, _navStatusEnum!, "nav", $"MoveStraight({distance:F2}m, {velocity:F2}m/s)"); } private ServiceResult MoveToNodeHandler(ISystemContext context, MethodState method, IList input, IList output) { Console.WriteLine("[OPC-SIM] MoveToNode called"); if (input.Count < 2 || !TryToUInt(input[0], out var nodeId)) return BadArgs(output, "NodeId required"); var spline = CoerceToDouble2D(input[1]); double targetX = 0, targetY = 0; if (spline.GetLength(0) > 0 && spline.GetLength(1) >= 2) { int last = spline.GetLength(0) - 1; targetX = spline[last, 0]; targetY = spline[last, 1]; } Console.WriteLine($"[OPC-SIM] MoveToNode: nodeId={nodeId}, target=({targetX:F2}, {targetY:F2})"); return RunModuleMotion(output, _navStatusString!, _navStatusEnum!, "nav", $"MoveToNode({nodeId})", targetX, targetY); } private ServiceResult MoveToPickupHandler(ISystemContext context, MethodState method, IList input, IList output) { Console.WriteLine("[OPC-SIM] MoveToPickup called"); if (input.Count < 1 || !TryToUInt(input[0], out var pickupId)) return BadArgs(output, "PickupId required"); Console.WriteLine($"[OPC-SIM] MoveToPickup: pickupId={pickupId}"); return RunModuleMotion(output, _navStatusString!, _navStatusEnum!, "nav", $"MoveToPickup({pickupId})"); } private ServiceResult MoveToDropDownHandler(ISystemContext context, MethodState method, IList input, IList output) { Console.WriteLine("[OPC-SIM] MoveToDropDown called"); if (input.Count < 1 || !TryToUInt(input[0], out var dropId)) return BadArgs(output, "DropId required"); Console.WriteLine($"[OPC-SIM] MoveToDropDown: dropId={dropId}"); return RunModuleMotion(output, _navStatusString!, _navStatusEnum!, "nav", $"MoveToDropDown({dropId})"); } private ServiceResult InitialPoseHandler(ISystemContext context, MethodState method, IList input, IList output) { Console.WriteLine("[OPC-SIM] InitialPose called"); if (input.Count < 3 || !TryToDouble(input[0], out var px) || !TryToDouble(input[1], out var py) || !TryToDouble(input[2], out var pyaw)) return BadArgs(output, "X, Y, Yaw required"); Console.WriteLine($"[OPC-SIM] InitialPose: ({px:F2}, {py:F2}, {pyaw:F2})"); _x!.Value = px; _y!.Value = py; _yaw!.Value = pyaw; UpdateTimestamp(_x, _y, _yaw); SetState(_navStatusString!, _navStatusEnum!, "INITIALIZED", 3); output.Clear(); output.Add(0u); output.Add("InitialPose applied"); return ServiceResult.Good; } private ServiceResult RotateToHandler(ISystemContext context, MethodState method, IList input, IList output) { Console.WriteLine("[OPC-SIM] RotateTo called"); if (input.Count < 2 || !TryToDouble(input[0], out var angle) || !TryToDouble(input[1], out var tolerance)) return BadArgs(output, "Angle and Tolerance required"); Console.WriteLine($"[OPC-SIM] RotateTo: angle={angle}, tolerance={tolerance}"); return RunModuleMotion(output, _navStatusString!, _navStatusEnum!, "nav", $"RotateTo({angle:F1}±{tolerance:F1})"); } private ServiceResult MutedSafetyHandler(ISystemContext context, MethodState method, IList input, IList output) { Console.WriteLine("[OPC-SIM] MutedSafety called"); if (input.Count < 1 || !TryToBool(input[0], out var enabled)) return BadArgs(output, "Enabled required"); Console.WriteLine($"[OPC-SIM] MutedSafety: enabled={enabled}"); SetState(_navStatusString!, _navStatusEnum!, enabled ? "MUTED-SAFETY" : "RUNNING", enabled ? 11u : 8u); output.Clear(); output.Add(0u); output.Add($"MutedSafety = {enabled}"); return ServiceResult.Good; } private ServiceResult ActivateMapHandler(ISystemContext context, MethodState method, IList input, IList output) { Console.WriteLine("[OPC-SIM] ActivateMap called"); if (input.Count < 1 || input[0] is not string mapName) return BadArgs(output, "MapName required"); Console.WriteLine($"[OPC-SIM] ActivateMap: map='{mapName}'"); _currentActiveMap!.Value = mapName; _slamState!.Value = "MAP_ACTIVE"; UpdateTimestamp(_currentActiveMap, _slamState); output.Clear(); output.Add(0u); output.Add($"Map '{mapName}' activated"); return ServiceResult.Good; } private ServiceResult GetMapFilesHandler(ISystemContext context, MethodState method, IList input, IList output) { Console.WriteLine("[OPC-SIM] GetMapFiles called"); var maps = _workingDirectories?.Value ?? []; output.Clear(); output.Add(maps.Length > 0 ? maps : new[] { "map_sim_01.yaml", "map_sim_02.yaml" }); output.Add("OK"); return ServiceResult.Good; } private ServiceResult CancelNavHandler(ISystemContext context, MethodState method, IList input, IList output) { Console.WriteLine("[OPC-SIM] Cancel (Navigation) called"); return RunCancel(output, _navStatusString!, _navStatusEnum!, "nav"); } private ServiceResult PauseHandler(ISystemContext context, MethodState method, IList input, IList output) { Console.WriteLine("[OPC-SIM] Pause called"); SetState(_navStatusString!, _navStatusEnum!, "PAUSED", 7); output.Clear(); output.Add(0u); output.Add("Paused"); return ServiceResult.Good; } private ServiceResult ResumeHandler(ISystemContext context, MethodState method, IList input, IList output) { Console.WriteLine("[OPC-SIM] Resume called"); SetState(_navStatusString!, _navStatusEnum!, "RUNNING", 8); output.Clear(); output.Add(0u); output.Add("Resumed"); return ServiceResult.Good; } private ServiceResult ResetNavHandler(ISystemContext context, MethodState method, IList input, IList output) { Console.WriteLine("[OPC-SIM] Reset (Navigation) called"); CancelMotion("nav"); SetState(_navStatusString!, _navStatusEnum!, "IDLE", 0); output.Clear(); output.Add(0u); output.Add("Navigation reset"); return ServiceResult.Good; } #endregion #region Conveyor Handlers private ServiceResult LoadBeltHandler(ISystemContext context, MethodState method, IList input, IList output) { Console.WriteLine("[OPC-SIM] Load (Belt) called"); return RunModuleMotion(output, _beltStatusString!, _beltStatusEnum!, "belt", "Load"); } private ServiceResult UnloadBeltHandler(ISystemContext context, MethodState method, IList input, IList output) { Console.WriteLine("[OPC-SIM] UnLoad (Belt) called"); return RunModuleMotion(output, _beltStatusString!, _beltStatusEnum!, "belt", "UnLoad"); } private ServiceResult ResetBeltHandler(ISystemContext context, MethodState method, IList input, IList output) { Console.WriteLine("[OPC-SIM] ResetBelt called"); CancelMotion("belt"); SetState(_beltStatusString!, _beltStatusEnum!, "IDLE", 0); output.Clear(); output.Add(0u); output.Add("Belt reset"); return ServiceResult.Good; } #endregion #region Dobot Handlers private ServiceResult CancelDobotHandler(ISystemContext context, MethodState method, IList input, IList output) { Console.WriteLine("[OPC-SIM] CancelDobot called"); return RunCancel(output, _stateString!, _stateEnum!, "dobot"); } private ServiceResult ContinueDobotHandler(ISystemContext context, MethodState method, IList input, IList output) { Console.WriteLine("[OPC-SIM] ContinueDobot called"); return RunModuleMotion(output, _stateString!, _stateEnum!, "dobot", "ContinueDobot"); } private ServiceResult PowerOnDobotHandler(ISystemContext context, MethodState method, IList input, IList output) { Console.WriteLine("[OPC-SIM] PowerOnDobot called"); return RunModuleMotion(output, _stateString!, _stateEnum!, "dobot", "PowerOnDobot", controllingMs: 500); } private ServiceResult GoHomeDobotHandler(ISystemContext context, MethodState method, IList input, IList output) { Console.WriteLine("[OPC-SIM] GoHomeDobot called"); return RunModuleMotion(output, _stateString!, _stateEnum!, "dobot", "GoHomeDobot"); } private ServiceResult PickUpHandler(ISystemContext context, MethodState method, IList input, IList output) { Console.WriteLine($"[OPC-SIM] PickUp called with {input?.Count ?? 0} arguments"); int countOk = 0, countNg = 0; if (input?.Count >= 2) { TryToInt(input[0], out countOk); TryToInt(input[1], out countNg); } Console.WriteLine($"[OPC-SIM] PickUp: CountOk={countOk}, CountNg={countNg}"); _countOK!.Value = (uint)Math.Max(0, countOk); _countNG!.Value = (uint)Math.Max(0, countNg); _dobotStatusCode!.Value = (uint)(countOk + countNg); _haveGoods!.Value = (countOk + countNg) > 0; UpdateTimestamp(_countOK, _countNG, _dobotStatusCode, _haveGoods); return RunModuleMotion(output, _stateString!, _stateEnum!, "dobot", $"PickUp(OK:{countOk}, NG:{countNg})"); } private ServiceResult SetQuantityOfGoodsHandler(ISystemContext context, MethodState method, IList input, IList output) { Console.WriteLine("[OPC-SIM] SetQuantityOfGoods called"); if (input?.Count < 2 || !TryToUInt(input![0], out var ok) || !TryToUInt(input[1], out var ng)) return BadArgs(output, "OK and NG required"); Console.WriteLine($"[OPC-SIM] SetQuantityOfGoods: OK={ok}, NG={ng}"); _countOK!.Value = ok; _countNG!.Value = ng; _stateEnum!.Value = 5; _dobotStatusCode!.Value = 1; UpdateTimestamp(_countOK, _countNG, _stateEnum, _dobotStatusCode); output.Clear(); output.Add(0u); output.Add("Set quantity applied"); return ServiceResult.Good; } #endregion #region Motion Simulation Helpers private ServiceResult RunModuleMotion( IList output, BaseDataVariableState statusString, BaseDataVariableState statusEnum, string moduleKey, string actionName, double? targetX = null, double? targetY = null, int controllingMs = 2000) { CancelMotion(moduleKey); SetState(statusString, statusEnum, "RUNNING", 1); var motionCts = new CancellationTokenSource(); _motionTokens[moduleKey] = motionCts; _ = Task.Run(async () => { var moveCts = new CancellationTokenSource(); try { if (targetX.HasValue && targetY.HasValue && _x != null && _y != null) { _ = Task.Run(async () => { try { double currX = _x.Value; double currY = _y.Value; while (!moveCts.IsCancellationRequested) { double dx = targetX.Value - currX; double dy = targetY.Value - currY; double dist = Math.Sqrt(dx * dx + dy * dy); if (dist < 0.05) break; double step = 0.05; currX += (dx / dist) * step + (_rand.NextDouble() * 0.005 - 0.0025); currY += (dy / dist) * step + (_rand.NextDouble() * 0.005 - 0.0025); _x.Value = currX; _y.Value = currY; UpdateTimestamp(_x, _y); await Task.Delay(100, moveCts.Token); } } catch { } }, moveCts.Token); } await Task.Delay(controllingMs, motionCts.Token); if (motionCts.IsCancellationRequested) { moveCts.Cancel(); SetState(statusString, statusEnum, "CANCELED", 99); return; } moveCts.Cancel(); if (targetX.HasValue && targetY.HasValue && _x != null && _y != null) { _x.Value = targetX.Value; _y.Value = targetY.Value; UpdateTimestamp(_x, _y); } SetState(statusString, statusEnum, "FINISHED", 2); StartAutoReset(moduleKey, statusString, statusEnum); } catch (TaskCanceledException) { moveCts.Cancel(); SetState(statusString, statusEnum, "CANCELED", 99); } }, motionCts.Token); output.Clear(); output.Add(0u); output.Add($"{actionName} accepted"); return ServiceResult.Good; } private ServiceResult RunCancel( IList output, BaseDataVariableState statusString, BaseDataVariableState statusEnum, string moduleKey) { CancelMotion(moduleKey); SetState(statusString, statusEnum, "CANCELED", 99); output.Clear(); output.Add(0u); output.Add("Canceled"); return ServiceResult.Good; } private void CancelMotion(string moduleKey) { if (_motionTokens.TryRemove(moduleKey, out var cts)) try { cts.Cancel(); } catch { } if (_resetTokens.TryRemove(moduleKey, out var reset)) try { reset.Cancel(); } catch { } } private void StartAutoReset( string moduleKey, BaseDataVariableState statusString, BaseDataVariableState statusEnum, int delayMs = 3000) { if (_resetTokens.TryGetValue(moduleKey, out var previous)) try { previous.Cancel(); } catch { } var cts = new CancellationTokenSource(); _resetTokens[moduleKey] = cts; _ = Task.Run(async () => { try { await Task.Delay(delayMs, cts.Token); if (!cts.IsCancellationRequested) SetState(statusString, statusEnum, "IDLE", 0); } catch (TaskCanceledException) { } }, cts.Token); } #endregion #region State & Timer Helpers private void SetState( BaseDataVariableState statusString, BaseDataVariableState statusEnum, string str, uint code) { statusString.Value = str; statusEnum.Value = code; UpdateTimestamp(statusString, statusEnum); } private void UpdateTimestamp(params BaseDataVariableState[] variables) { var now = DateTime.UtcNow; foreach (var v in variables) { v.Timestamp = now; v.ClearChangeMasks(SystemContext, false); } } private void TimerElapsed(object? sender, System.Timers.ElapsedEventArgs e) { try { if (_yaw != null) { _yaw.Value += _rand.NextDouble() * 2 - 1; UpdateTimestamp(_yaw); } if (_vx != null && _vy != null && _omega != null) { _vx.Value = _rand.NextDouble() * 1.5; _vy.Value = _rand.NextDouble() * 0.5; _omega.Value = _rand.NextDouble() * 2.0; UpdateTimestamp(_vx, _vy, _omega); } } catch (Exception ex) { Console.WriteLine($"[RcsNodeManager] TimerElapsed error: {ex.Message}"); } } #endregion #region Type Conversion Helpers private static ServiceResult BadArgs(IList output, string message) { output.Clear(); output.Add(1u); output.Add(message); return ServiceResult.Create(StatusCodes.BadInvalidArgument, message); } private static bool TryToDouble(object? obj, out double value) { value = default; if (obj == null) return false; if (obj is double d) { value = d; return true; } if (obj is float f) { value = f; return true; } try { value = Convert.ToDouble(obj); return true; } catch { return false; } } private static bool TryToInt(object? obj, out int value) { value = default; if (obj == null) return false; if (obj is int i) { value = i; return true; } try { value = Convert.ToInt32(obj); return true; } catch { return false; } } private static bool TryToUInt(object? obj, out uint value) { value = default; if (obj == null) return false; if (obj is uint u) { value = u; return true; } if (obj is int i && i >= 0) { value = (uint)i; return true; } try { value = Convert.ToUInt32(obj); return true; } catch { return false; } } private static bool TryToBool(object? obj, out bool value) { value = default; if (obj == null) return false; if (obj is bool b) { value = b; return true; } try { value = Convert.ToBoolean(obj); return true; } catch { return false; } } private static double[,] CoerceToDouble2D(object? obj) { if (obj is double[,] d2) return d2; if (obj is IList list && list.Count > 0) { try { int rows = list.Count; var result = new double[rows, 2]; for (int r = 0; r < rows; r++) { if (list[r] is IList row && row.Count >= 2) { result[r, 0] = Convert.ToDouble(row[0]); result[r, 1] = Convert.ToDouble(row[1]); } } return result; } catch { } } return new double[0, 0]; } #endregion #region IDisposable public new void Dispose() { _timer?.Stop(); _timer?.Dispose(); foreach (var kv in _motionTokens) try { kv.Value.Cancel(); } catch { } foreach (var kv in _resetTokens) try { kv.Value.Cancel(); } catch { } GC.SuppressFinalize(this); } #endregion }