using CliFx.Attributes; using CliFx.Infrastructure; using Opc.Ua; using ZB.MOM.WW.OtOpcUa.Client.CLI.Helpers; using ZB.MOM.WW.OtOpcUa.Client.Shared; using ZB.MOM.WW.OtOpcUa.Client.Shared.Helpers; namespace ZB.MOM.WW.OtOpcUa.Client.CLI.Commands; [Command("write", Description = "Write a value to a node")] public class WriteCommand : CommandBase { /// /// Creates the write command used to update a node from the terminal. /// /// The factory that creates the shared client service for the command run. public WriteCommand(IOpcUaClientServiceFactory factory) : base(factory) { } /// /// Gets the node whose value should be updated. /// [CommandOption("node", 'n', Description = "Node ID (e.g. ns=2;s=MyNode)", IsRequired = true)] public string NodeId { get; init; } = default!; /// /// Gets the raw operator-entered value that will be converted to the node's runtime type before writing. /// [CommandOption("value", 'v', Description = "Value to write", IsRequired = true)] public string Value { get; init; } = default!; /// /// Connects to the server, converts the supplied value to the node's current data type, and issues the write. /// /// The CLI console used for output and cancellation handling. public override async ValueTask ExecuteAsync(IConsole console) { ConfigureLogging(); IOpcUaClientService? service = null; try { var ct = console.RegisterCancellationHandler(); (service, _) = await CreateServiceAndConnectAsync(ct); var nodeId = NodeIdParser.ParseRequired(NodeId); // Read current value to determine type for conversion var currentValue = await service.ReadValueAsync(nodeId, ct); var typedValue = ValueConverter.ConvertValue(Value, currentValue.Value); var statusCode = await service.WriteValueAsync(nodeId, typedValue, ct); if (StatusCode.IsGood(statusCode)) await console.Output.WriteLineAsync($"Write successful: {NodeId} = {typedValue}"); else await console.Output.WriteLineAsync($"Write failed: {statusCode}"); } finally { if (service != null) { await service.DisconnectAsync(); service.Dispose(); } } } }