Add cross-platform OPC UA client stack: shared library, CLI tool, and Avalonia UI
Implements Client.Shared (IOpcUaClientService with connection lifecycle, failover, browse, read/write, subscriptions, alarms, history, redundancy), Client.CLI (8 CliFx commands mirroring tools/opcuacli-dotnet), and Client.UI (Avalonia desktop app with tree browser, read/write, subscriptions, alarms, and history tabs). All three target .NET 10 and are covered by 249 unit tests. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
99
src/ZB.MOM.WW.LmxOpcUa.Client.CLI/CommandBase.cs
Normal file
99
src/ZB.MOM.WW.LmxOpcUa.Client.CLI/CommandBase.cs
Normal file
@@ -0,0 +1,99 @@
|
||||
using CliFx;
|
||||
using CliFx.Attributes;
|
||||
using CliFx.Infrastructure;
|
||||
using Serilog;
|
||||
using ZB.MOM.WW.LmxOpcUa.Client.Shared;
|
||||
using ZB.MOM.WW.LmxOpcUa.Client.Shared.Helpers;
|
||||
using ZB.MOM.WW.LmxOpcUa.Client.Shared.Models;
|
||||
|
||||
namespace ZB.MOM.WW.LmxOpcUa.Client.CLI;
|
||||
|
||||
/// <summary>
|
||||
/// Abstract base class for all CLI commands providing common connection options and helpers.
|
||||
/// </summary>
|
||||
public abstract class CommandBase : ICommand
|
||||
{
|
||||
internal static readonly IOpcUaClientServiceFactory DefaultFactory = new OpcUaClientServiceFactory();
|
||||
|
||||
private readonly IOpcUaClientServiceFactory _factory;
|
||||
|
||||
protected CommandBase(IOpcUaClientServiceFactory factory)
|
||||
{
|
||||
_factory = factory;
|
||||
}
|
||||
|
||||
[CommandOption("url", 'u', Description = "OPC UA server endpoint URL", IsRequired = true)]
|
||||
public string Url { get; init; } = default!;
|
||||
|
||||
[CommandOption("username", 'U', Description = "Username for authentication")]
|
||||
public string? Username { get; init; }
|
||||
|
||||
[CommandOption("password", 'P', Description = "Password for authentication")]
|
||||
public string? Password { get; init; }
|
||||
|
||||
[CommandOption("security", 'S', Description = "Transport security: none, sign, encrypt, signandencrypt (default: none)")]
|
||||
public string Security { get; init; } = "none";
|
||||
|
||||
[CommandOption("failover-urls", 'F', Description = "Comma-separated failover endpoint URLs for redundancy")]
|
||||
public string? FailoverUrls { get; init; }
|
||||
|
||||
[CommandOption("verbose", Description = "Enable verbose/debug logging")]
|
||||
public bool Verbose { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Creates a <see cref="ConnectionSettings"/> from the common command options.
|
||||
/// </summary>
|
||||
protected ConnectionSettings CreateConnectionSettings()
|
||||
{
|
||||
var securityMode = SecurityModeMapper.FromString(Security);
|
||||
var failoverUrls = !string.IsNullOrWhiteSpace(FailoverUrls)
|
||||
? FailoverUrlParser.Parse(Url, FailoverUrls)
|
||||
: null;
|
||||
|
||||
var settings = new ConnectionSettings
|
||||
{
|
||||
EndpointUrl = Url,
|
||||
FailoverUrls = failoverUrls,
|
||||
Username = Username,
|
||||
Password = Password,
|
||||
SecurityMode = securityMode,
|
||||
AutoAcceptCertificates = true
|
||||
};
|
||||
|
||||
return settings;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="IOpcUaClientService"/>, connects it using the common options,
|
||||
/// and returns both the service and the connection info.
|
||||
/// </summary>
|
||||
protected async Task<(IOpcUaClientService Service, ConnectionInfo Info)> CreateServiceAndConnectAsync(CancellationToken ct)
|
||||
{
|
||||
var service = _factory.Create();
|
||||
var settings = CreateConnectionSettings();
|
||||
var info = await service.ConnectAsync(settings, ct);
|
||||
return (service, info);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Configures Serilog based on the verbose flag.
|
||||
/// </summary>
|
||||
protected void ConfigureLogging()
|
||||
{
|
||||
var config = new LoggerConfiguration();
|
||||
if (Verbose)
|
||||
{
|
||||
config.MinimumLevel.Debug()
|
||||
.WriteTo.Console();
|
||||
}
|
||||
else
|
||||
{
|
||||
config.MinimumLevel.Warning()
|
||||
.WriteTo.Console();
|
||||
}
|
||||
|
||||
Log.Logger = config.CreateLogger();
|
||||
}
|
||||
|
||||
public abstract ValueTask ExecuteAsync(IConsole console);
|
||||
}
|
||||
86
src/ZB.MOM.WW.LmxOpcUa.Client.CLI/Commands/AlarmsCommand.cs
Normal file
86
src/ZB.MOM.WW.LmxOpcUa.Client.CLI/Commands/AlarmsCommand.cs
Normal file
@@ -0,0 +1,86 @@
|
||||
using CliFx.Attributes;
|
||||
using CliFx.Infrastructure;
|
||||
using ZB.MOM.WW.LmxOpcUa.Client.CLI.Helpers;
|
||||
using ZB.MOM.WW.LmxOpcUa.Client.Shared;
|
||||
|
||||
namespace ZB.MOM.WW.LmxOpcUa.Client.CLI.Commands;
|
||||
|
||||
[Command("alarms", Description = "Subscribe to alarm events")]
|
||||
public class AlarmsCommand : CommandBase
|
||||
{
|
||||
[CommandOption("node", 'n', Description = "Node ID to monitor for events (default: Server node)")]
|
||||
public string? NodeId { get; init; }
|
||||
|
||||
[CommandOption("interval", 'i', Description = "Publishing interval in milliseconds")]
|
||||
public int Interval { get; init; } = 1000;
|
||||
|
||||
[CommandOption("refresh", Description = "Request a ConditionRefresh after subscribing")]
|
||||
public bool Refresh { get; init; }
|
||||
|
||||
public AlarmsCommand(IOpcUaClientServiceFactory factory) : base(factory) { }
|
||||
|
||||
public override async ValueTask ExecuteAsync(IConsole console)
|
||||
{
|
||||
ConfigureLogging();
|
||||
IOpcUaClientService? service = null;
|
||||
try
|
||||
{
|
||||
var ct = console.RegisterCancellationHandler();
|
||||
(service, _) = await CreateServiceAndConnectAsync(ct);
|
||||
|
||||
var sourceNodeId = NodeIdParser.Parse(NodeId);
|
||||
|
||||
service.AlarmEvent += (_, e) =>
|
||||
{
|
||||
console.Output.WriteLine($"[{e.Time:O}] ALARM {e.SourceName}");
|
||||
console.Output.WriteLine($" Condition: {e.ConditionName}");
|
||||
var activeStr = e.ActiveState ? "Active" : "Inactive";
|
||||
var ackedStr = e.AckedState ? "Acknowledged" : "Unacknowledged";
|
||||
console.Output.WriteLine($" State: {activeStr}, {ackedStr}");
|
||||
console.Output.WriteLine($" Severity: {e.Severity}");
|
||||
if (!string.IsNullOrEmpty(e.Message))
|
||||
console.Output.WriteLine($" Message: {e.Message}");
|
||||
console.Output.WriteLine($" Retain: {e.Retain}");
|
||||
console.Output.WriteLine();
|
||||
};
|
||||
|
||||
await service.SubscribeAlarmsAsync(sourceNodeId, Interval, ct);
|
||||
await console.Output.WriteLineAsync(
|
||||
$"Subscribed to alarm events (interval: {Interval}ms). Press Ctrl+C to stop.");
|
||||
|
||||
if (Refresh)
|
||||
{
|
||||
try
|
||||
{
|
||||
await service.RequestConditionRefreshAsync(ct);
|
||||
await console.Output.WriteLineAsync("Condition refresh requested.");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
await console.Output.WriteLineAsync($"Condition refresh not supported: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
// Wait until cancellation
|
||||
try
|
||||
{
|
||||
await Task.Delay(Timeout.Infinite, ct);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
// Expected on Ctrl+C
|
||||
}
|
||||
|
||||
await service.UnsubscribeAlarmsAsync(default);
|
||||
await console.Output.WriteLineAsync("Unsubscribed.");
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (service != null)
|
||||
{
|
||||
await service.DisconnectAsync();
|
||||
service.Dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
79
src/ZB.MOM.WW.LmxOpcUa.Client.CLI/Commands/BrowseCommand.cs
Normal file
79
src/ZB.MOM.WW.LmxOpcUa.Client.CLI/Commands/BrowseCommand.cs
Normal file
@@ -0,0 +1,79 @@
|
||||
using CliFx.Attributes;
|
||||
using CliFx.Infrastructure;
|
||||
using Opc.Ua;
|
||||
using ZB.MOM.WW.LmxOpcUa.Client.CLI.Helpers;
|
||||
using ZB.MOM.WW.LmxOpcUa.Client.Shared;
|
||||
using BrowseResult = ZB.MOM.WW.LmxOpcUa.Client.Shared.Models.BrowseResult;
|
||||
|
||||
namespace ZB.MOM.WW.LmxOpcUa.Client.CLI.Commands;
|
||||
|
||||
[Command("browse", Description = "Browse the OPC UA address space")]
|
||||
public class BrowseCommand : CommandBase
|
||||
{
|
||||
[CommandOption("node", 'n', Description = "Node ID to browse (default: Objects folder)")]
|
||||
public string? NodeId { get; init; }
|
||||
|
||||
[CommandOption("depth", 'd', Description = "Maximum browse depth")]
|
||||
public int Depth { get; init; } = 1;
|
||||
|
||||
[CommandOption("recursive", 'r', Description = "Browse recursively (uses --depth as max depth)")]
|
||||
public bool Recursive { get; init; }
|
||||
|
||||
public BrowseCommand(IOpcUaClientServiceFactory factory) : base(factory) { }
|
||||
|
||||
public override async ValueTask ExecuteAsync(IConsole console)
|
||||
{
|
||||
ConfigureLogging();
|
||||
IOpcUaClientService? service = null;
|
||||
try
|
||||
{
|
||||
var ct = console.RegisterCancellationHandler();
|
||||
(service, _) = await CreateServiceAndConnectAsync(ct);
|
||||
|
||||
var startNode = NodeIdParser.Parse(NodeId);
|
||||
var maxDepth = Recursive ? Depth : 1;
|
||||
|
||||
await BrowseNodeAsync(service, console, startNode, maxDepth, 0, ct);
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (service != null)
|
||||
{
|
||||
await service.DisconnectAsync();
|
||||
service.Dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task BrowseNodeAsync(
|
||||
IOpcUaClientService service,
|
||||
IConsole console,
|
||||
NodeId? nodeId,
|
||||
int maxDepth,
|
||||
int currentDepth,
|
||||
CancellationToken ct)
|
||||
{
|
||||
var indent = new string(' ', currentDepth * 2);
|
||||
var results = await service.BrowseAsync(nodeId, ct);
|
||||
|
||||
foreach (var result in results)
|
||||
{
|
||||
var marker = result.NodeClass switch
|
||||
{
|
||||
"Object" => "[Object]",
|
||||
"Variable" => "[Variable]",
|
||||
"Method" => "[Method]",
|
||||
_ => $"[{result.NodeClass}]"
|
||||
};
|
||||
|
||||
await console.Output.WriteLineAsync(
|
||||
$"{indent}{marker} {result.DisplayName} (NodeId: {result.NodeId})");
|
||||
|
||||
if (currentDepth + 1 < maxDepth && result.HasChildren)
|
||||
{
|
||||
var childNodeId = NodeIdParser.Parse(result.NodeId);
|
||||
await BrowseNodeAsync(service, console, childNodeId, maxDepth, currentDepth + 1, ct);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
35
src/ZB.MOM.WW.LmxOpcUa.Client.CLI/Commands/ConnectCommand.cs
Normal file
35
src/ZB.MOM.WW.LmxOpcUa.Client.CLI/Commands/ConnectCommand.cs
Normal file
@@ -0,0 +1,35 @@
|
||||
using CliFx.Attributes;
|
||||
using CliFx.Infrastructure;
|
||||
using ZB.MOM.WW.LmxOpcUa.Client.Shared;
|
||||
|
||||
namespace ZB.MOM.WW.LmxOpcUa.Client.CLI.Commands;
|
||||
|
||||
[Command("connect", Description = "Test connection to an OPC UA server")]
|
||||
public class ConnectCommand : CommandBase
|
||||
{
|
||||
public ConnectCommand(IOpcUaClientServiceFactory factory) : base(factory) { }
|
||||
|
||||
public override async ValueTask ExecuteAsync(IConsole console)
|
||||
{
|
||||
ConfigureLogging();
|
||||
IOpcUaClientService? service = null;
|
||||
try
|
||||
{
|
||||
(service, var info) = await CreateServiceAndConnectAsync(console.RegisterCancellationHandler());
|
||||
|
||||
await console.Output.WriteLineAsync($"Connected to: {info.EndpointUrl}");
|
||||
await console.Output.WriteLineAsync($"Server: {info.ServerName}");
|
||||
await console.Output.WriteLineAsync($"Security Mode: {info.SecurityMode}");
|
||||
await console.Output.WriteLineAsync($"Security Policy: {info.SecurityPolicyUri}");
|
||||
await console.Output.WriteLineAsync("Connection successful.");
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (service != null)
|
||||
{
|
||||
await service.DisconnectAsync();
|
||||
service.Dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
106
src/ZB.MOM.WW.LmxOpcUa.Client.CLI/Commands/HistoryReadCommand.cs
Normal file
106
src/ZB.MOM.WW.LmxOpcUa.Client.CLI/Commands/HistoryReadCommand.cs
Normal file
@@ -0,0 +1,106 @@
|
||||
using CliFx.Attributes;
|
||||
using CliFx.Infrastructure;
|
||||
using Opc.Ua;
|
||||
using ZB.MOM.WW.LmxOpcUa.Client.CLI.Helpers;
|
||||
using ZB.MOM.WW.LmxOpcUa.Client.Shared;
|
||||
using ZB.MOM.WW.LmxOpcUa.Client.Shared.Models;
|
||||
|
||||
namespace ZB.MOM.WW.LmxOpcUa.Client.CLI.Commands;
|
||||
|
||||
[Command("historyread", Description = "Read historical data from a node")]
|
||||
public class HistoryReadCommand : CommandBase
|
||||
{
|
||||
[CommandOption("node", 'n', Description = "Node ID (e.g. ns=2;s=MyNode)", IsRequired = true)]
|
||||
public string NodeId { get; init; } = default!;
|
||||
|
||||
[CommandOption("start", Description = "Start time (ISO 8601 or date string, default: 24 hours ago)")]
|
||||
public string? StartTime { get; init; }
|
||||
|
||||
[CommandOption("end", Description = "End time (ISO 8601 or date string, default: now)")]
|
||||
public string? EndTime { get; init; }
|
||||
|
||||
[CommandOption("max", Description = "Maximum number of values to return")]
|
||||
public int MaxValues { get; init; } = 1000;
|
||||
|
||||
[CommandOption("aggregate", Description = "Aggregate function: Average, Minimum, Maximum, Count, Start, End")]
|
||||
public string? Aggregate { get; init; }
|
||||
|
||||
[CommandOption("interval", Description = "Processing interval in milliseconds for aggregates")]
|
||||
public double IntervalMs { get; init; } = 3600000;
|
||||
|
||||
public HistoryReadCommand(IOpcUaClientServiceFactory factory) : base(factory) { }
|
||||
|
||||
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);
|
||||
var start = string.IsNullOrEmpty(StartTime)
|
||||
? DateTime.UtcNow.AddHours(-24)
|
||||
: DateTime.Parse(StartTime).ToUniversalTime();
|
||||
var end = string.IsNullOrEmpty(EndTime)
|
||||
? DateTime.UtcNow
|
||||
: DateTime.Parse(EndTime).ToUniversalTime();
|
||||
|
||||
IReadOnlyList<DataValue> values;
|
||||
|
||||
if (string.IsNullOrEmpty(Aggregate))
|
||||
{
|
||||
await console.Output.WriteLineAsync(
|
||||
$"History for {NodeId} ({start:yyyy-MM-dd HH:mm} -> {end:yyyy-MM-dd HH:mm})");
|
||||
values = await service.HistoryReadRawAsync(nodeId, start, end, MaxValues, ct);
|
||||
}
|
||||
else
|
||||
{
|
||||
var aggregateType = ParseAggregateType(Aggregate);
|
||||
await console.Output.WriteLineAsync(
|
||||
$"History for {NodeId} ({Aggregate}, interval={IntervalMs}ms)");
|
||||
values = await service.HistoryReadAggregateAsync(
|
||||
nodeId, start, end, aggregateType, IntervalMs, ct);
|
||||
}
|
||||
|
||||
await console.Output.WriteLineAsync();
|
||||
await console.Output.WriteLineAsync($"{"Timestamp",-35} {"Value",-15} {"Status"}");
|
||||
|
||||
foreach (var dv in values)
|
||||
{
|
||||
var status = StatusCode.IsGood(dv.StatusCode) ? "Good"
|
||||
: StatusCode.IsBad(dv.StatusCode) ? "Bad"
|
||||
: "Uncertain";
|
||||
await console.Output.WriteLineAsync(
|
||||
$"{dv.SourceTimestamp.ToString("O"),-35} {dv.Value,-15} {status}");
|
||||
}
|
||||
|
||||
await console.Output.WriteLineAsync();
|
||||
await console.Output.WriteLineAsync($"{values.Count} values returned.");
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (service != null)
|
||||
{
|
||||
await service.DisconnectAsync();
|
||||
service.Dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static AggregateType ParseAggregateType(string name)
|
||||
{
|
||||
return name.Trim().ToLowerInvariant() switch
|
||||
{
|
||||
"average" or "avg" => AggregateType.Average,
|
||||
"minimum" or "min" => AggregateType.Minimum,
|
||||
"maximum" or "max" => AggregateType.Maximum,
|
||||
"count" => AggregateType.Count,
|
||||
"start" or "first" => AggregateType.Start,
|
||||
"end" or "last" => AggregateType.End,
|
||||
_ => throw new ArgumentException(
|
||||
$"Unknown aggregate: '{name}'. Supported: Average, Minimum, Maximum, Count, Start, End")
|
||||
};
|
||||
}
|
||||
}
|
||||
43
src/ZB.MOM.WW.LmxOpcUa.Client.CLI/Commands/ReadCommand.cs
Normal file
43
src/ZB.MOM.WW.LmxOpcUa.Client.CLI/Commands/ReadCommand.cs
Normal file
@@ -0,0 +1,43 @@
|
||||
using CliFx.Attributes;
|
||||
using CliFx.Infrastructure;
|
||||
using ZB.MOM.WW.LmxOpcUa.Client.CLI.Helpers;
|
||||
using ZB.MOM.WW.LmxOpcUa.Client.Shared;
|
||||
|
||||
namespace ZB.MOM.WW.LmxOpcUa.Client.CLI.Commands;
|
||||
|
||||
[Command("read", Description = "Read a value from a node")]
|
||||
public class ReadCommand : CommandBase
|
||||
{
|
||||
[CommandOption("node", 'n', Description = "Node ID (e.g. ns=2;s=MyNode)", IsRequired = true)]
|
||||
public string NodeId { get; init; } = default!;
|
||||
|
||||
public ReadCommand(IOpcUaClientServiceFactory factory) : base(factory) { }
|
||||
|
||||
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);
|
||||
var value = await service.ReadValueAsync(nodeId, ct);
|
||||
|
||||
await console.Output.WriteLineAsync($"Node: {NodeId}");
|
||||
await console.Output.WriteLineAsync($"Value: {value.Value}");
|
||||
await console.Output.WriteLineAsync($"Status: {value.StatusCode}");
|
||||
await console.Output.WriteLineAsync($"Source Time: {value.SourceTimestamp:O}");
|
||||
await console.Output.WriteLineAsync($"Server Time: {value.ServerTimestamp:O}");
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (service != null)
|
||||
{
|
||||
await service.DisconnectAsync();
|
||||
service.Dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
using CliFx.Attributes;
|
||||
using CliFx.Infrastructure;
|
||||
using ZB.MOM.WW.LmxOpcUa.Client.Shared;
|
||||
|
||||
namespace ZB.MOM.WW.LmxOpcUa.Client.CLI.Commands;
|
||||
|
||||
[Command("redundancy", Description = "Read redundancy state from an OPC UA server")]
|
||||
public class RedundancyCommand : CommandBase
|
||||
{
|
||||
public RedundancyCommand(IOpcUaClientServiceFactory factory) : base(factory) { }
|
||||
|
||||
public override async ValueTask ExecuteAsync(IConsole console)
|
||||
{
|
||||
ConfigureLogging();
|
||||
IOpcUaClientService? service = null;
|
||||
try
|
||||
{
|
||||
var ct = console.RegisterCancellationHandler();
|
||||
(service, _) = await CreateServiceAndConnectAsync(ct);
|
||||
|
||||
var info = await service.GetRedundancyInfoAsync(ct);
|
||||
|
||||
await console.Output.WriteLineAsync($"Redundancy Mode: {info.Mode}");
|
||||
await console.Output.WriteLineAsync($"Service Level: {info.ServiceLevel}");
|
||||
|
||||
if (info.ServerUris.Length > 0)
|
||||
{
|
||||
await console.Output.WriteLineAsync("Server URIs:");
|
||||
foreach (var uri in info.ServerUris)
|
||||
{
|
||||
await console.Output.WriteLineAsync($" - {uri}");
|
||||
}
|
||||
}
|
||||
|
||||
await console.Output.WriteLineAsync($"Application URI: {info.ApplicationUri}");
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (service != null)
|
||||
{
|
||||
await service.DisconnectAsync();
|
||||
service.Dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
using CliFx.Attributes;
|
||||
using CliFx.Infrastructure;
|
||||
using ZB.MOM.WW.LmxOpcUa.Client.CLI.Helpers;
|
||||
using ZB.MOM.WW.LmxOpcUa.Client.Shared;
|
||||
|
||||
namespace ZB.MOM.WW.LmxOpcUa.Client.CLI.Commands;
|
||||
|
||||
[Command("subscribe", Description = "Monitor a node for value changes")]
|
||||
public class SubscribeCommand : CommandBase
|
||||
{
|
||||
[CommandOption("node", 'n', Description = "Node ID to monitor", IsRequired = true)]
|
||||
public string NodeId { get; init; } = default!;
|
||||
|
||||
[CommandOption("interval", 'i', Description = "Sampling interval in milliseconds")]
|
||||
public int Interval { get; init; } = 1000;
|
||||
|
||||
public SubscribeCommand(IOpcUaClientServiceFactory factory) : base(factory) { }
|
||||
|
||||
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);
|
||||
|
||||
service.DataChanged += (_, e) =>
|
||||
{
|
||||
console.Output.WriteLine(
|
||||
$"[{e.Value.SourceTimestamp:O}] {e.NodeId} = {e.Value.Value} ({e.Value.StatusCode})");
|
||||
};
|
||||
|
||||
await service.SubscribeAsync(nodeId, Interval, ct);
|
||||
await console.Output.WriteLineAsync(
|
||||
$"Subscribed to {NodeId} (interval: {Interval}ms). Press Ctrl+C to stop.");
|
||||
|
||||
// Wait until cancellation
|
||||
try
|
||||
{
|
||||
await Task.Delay(Timeout.Infinite, ct);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
// Expected on Ctrl+C
|
||||
}
|
||||
|
||||
await service.UnsubscribeAsync(nodeId, default);
|
||||
await console.Output.WriteLineAsync("Unsubscribed.");
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (service != null)
|
||||
{
|
||||
await service.DisconnectAsync();
|
||||
service.Dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
52
src/ZB.MOM.WW.LmxOpcUa.Client.CLI/Commands/WriteCommand.cs
Normal file
52
src/ZB.MOM.WW.LmxOpcUa.Client.CLI/Commands/WriteCommand.cs
Normal file
@@ -0,0 +1,52 @@
|
||||
using CliFx.Attributes;
|
||||
using CliFx.Infrastructure;
|
||||
using Opc.Ua;
|
||||
using ZB.MOM.WW.LmxOpcUa.Client.CLI.Helpers;
|
||||
using ZB.MOM.WW.LmxOpcUa.Client.Shared;
|
||||
using ZB.MOM.WW.LmxOpcUa.Client.Shared.Helpers;
|
||||
|
||||
namespace ZB.MOM.WW.LmxOpcUa.Client.CLI.Commands;
|
||||
|
||||
[Command("write", Description = "Write a value to a node")]
|
||||
public class WriteCommand : CommandBase
|
||||
{
|
||||
[CommandOption("node", 'n', Description = "Node ID (e.g. ns=2;s=MyNode)", IsRequired = true)]
|
||||
public string NodeId { get; init; } = default!;
|
||||
|
||||
[CommandOption("value", 'v', Description = "Value to write", IsRequired = true)]
|
||||
public string Value { get; init; } = default!;
|
||||
|
||||
public WriteCommand(IOpcUaClientServiceFactory factory) : base(factory) { }
|
||||
|
||||
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();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
61
src/ZB.MOM.WW.LmxOpcUa.Client.CLI/Helpers/NodeIdParser.cs
Normal file
61
src/ZB.MOM.WW.LmxOpcUa.Client.CLI/Helpers/NodeIdParser.cs
Normal file
@@ -0,0 +1,61 @@
|
||||
using Opc.Ua;
|
||||
|
||||
namespace ZB.MOM.WW.LmxOpcUa.Client.CLI.Helpers;
|
||||
|
||||
/// <summary>
|
||||
/// Parses node ID strings into OPC UA <see cref="NodeId"/> objects.
|
||||
/// Supports standard OPC UA format (e.g., "ns=2;s=MyNode", "i=85") and bare numeric IDs.
|
||||
/// </summary>
|
||||
public static class NodeIdParser
|
||||
{
|
||||
/// <summary>
|
||||
/// Parses a string into a <see cref="NodeId"/>. Returns <c>null</c> if the input is null or empty.
|
||||
/// </summary>
|
||||
/// <param name="nodeIdString">The node ID string to parse.</param>
|
||||
/// <returns>A parsed <see cref="NodeId"/>, or <c>null</c> if input is null/empty.</returns>
|
||||
/// <exception cref="FormatException">Thrown when the string cannot be parsed as a valid NodeId.</exception>
|
||||
public static NodeId? Parse(string? nodeIdString)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(nodeIdString))
|
||||
return null;
|
||||
|
||||
var trimmed = nodeIdString.Trim();
|
||||
|
||||
// Standard OPC UA format: ns=X;s=..., ns=X;i=..., ns=X;g=..., ns=X;b=...
|
||||
// Also: s=..., i=..., g=..., b=... (namespace 0 implied)
|
||||
if (trimmed.Contains('='))
|
||||
{
|
||||
try
|
||||
{
|
||||
return NodeId.Parse(trimmed);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
throw new FormatException($"Invalid node ID format: '{nodeIdString}'", ex);
|
||||
}
|
||||
}
|
||||
|
||||
// Bare numeric: treat as namespace 0, numeric identifier
|
||||
if (uint.TryParse(trimmed, out var numericId))
|
||||
{
|
||||
return new NodeId(numericId);
|
||||
}
|
||||
|
||||
throw new FormatException($"Invalid node ID format: '{nodeIdString}'. Expected format like 'ns=2;s=MyNode', 'i=85', or a numeric ID.");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Parses a string into a <see cref="NodeId"/>, throwing if the input is null or empty.
|
||||
/// </summary>
|
||||
/// <param name="nodeIdString">The node ID string to parse.</param>
|
||||
/// <returns>A parsed <see cref="NodeId"/>.</returns>
|
||||
/// <exception cref="ArgumentException">Thrown when the input is null or empty.</exception>
|
||||
/// <exception cref="FormatException">Thrown when the string cannot be parsed as a valid NodeId.</exception>
|
||||
public static NodeId ParseRequired(string? nodeIdString)
|
||||
{
|
||||
var result = Parse(nodeIdString);
|
||||
if (result == null)
|
||||
throw new ArgumentException("Node ID is required but was not provided.");
|
||||
return result;
|
||||
}
|
||||
}
|
||||
18
src/ZB.MOM.WW.LmxOpcUa.Client.CLI/Program.cs
Normal file
18
src/ZB.MOM.WW.LmxOpcUa.Client.CLI/Program.cs
Normal file
@@ -0,0 +1,18 @@
|
||||
using CliFx;
|
||||
using ZB.MOM.WW.LmxOpcUa.Client.CLI;
|
||||
|
||||
return await new CliApplicationBuilder()
|
||||
.AddCommandsFromThisAssembly()
|
||||
.UseTypeActivator(type =>
|
||||
{
|
||||
// Inject the default factory into commands that derive from CommandBase
|
||||
if (type.IsSubclassOf(typeof(CommandBase)))
|
||||
{
|
||||
return Activator.CreateInstance(type, CommandBase.DefaultFactory)!;
|
||||
}
|
||||
return Activator.CreateInstance(type)!;
|
||||
})
|
||||
.SetExecutableName("lmxopcua-cli")
|
||||
.SetDescription("LmxOpcUa CLI - command-line client for the LmxOpcUa OPC UA server")
|
||||
.Build()
|
||||
.RunAsync(args);
|
||||
@@ -0,0 +1,21 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<RootNamespace>ZB.MOM.WW.LmxOpcUa.Client.CLI</RootNamespace>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="CliFx" Version="2.3.6" />
|
||||
<PackageReference Include="Serilog" Version="4.2.0" />
|
||||
<PackageReference Include="Serilog.Sinks.Console" Version="6.0.0" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\ZB.MOM.WW.LmxOpcUa.Client.Shared\ZB.MOM.WW.LmxOpcUa.Client.Shared.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,75 @@
|
||||
using Opc.Ua;
|
||||
using Opc.Ua.Configuration;
|
||||
using Serilog;
|
||||
using ZB.MOM.WW.LmxOpcUa.Client.Shared.Models;
|
||||
|
||||
namespace ZB.MOM.WW.LmxOpcUa.Client.Shared.Adapters;
|
||||
|
||||
/// <summary>
|
||||
/// Production implementation that builds a real OPC UA ApplicationConfiguration.
|
||||
/// </summary>
|
||||
internal sealed class DefaultApplicationConfigurationFactory : IApplicationConfigurationFactory
|
||||
{
|
||||
private static readonly ILogger Logger = Log.ForContext<DefaultApplicationConfigurationFactory>();
|
||||
|
||||
public async Task<ApplicationConfiguration> CreateAsync(ConnectionSettings settings, CancellationToken ct)
|
||||
{
|
||||
var storePath = settings.CertificateStorePath;
|
||||
|
||||
var config = new ApplicationConfiguration
|
||||
{
|
||||
ApplicationName = "LmxOpcUaClient",
|
||||
ApplicationUri = "urn:localhost:LmxOpcUaClient",
|
||||
ApplicationType = ApplicationType.Client,
|
||||
SecurityConfiguration = new SecurityConfiguration
|
||||
{
|
||||
ApplicationCertificate = new CertificateIdentifier
|
||||
{
|
||||
StoreType = CertificateStoreType.Directory,
|
||||
StorePath = Path.Combine(storePath, "own")
|
||||
},
|
||||
TrustedIssuerCertificates = new CertificateTrustList
|
||||
{
|
||||
StoreType = CertificateStoreType.Directory,
|
||||
StorePath = Path.Combine(storePath, "issuer")
|
||||
},
|
||||
TrustedPeerCertificates = new CertificateTrustList
|
||||
{
|
||||
StoreType = CertificateStoreType.Directory,
|
||||
StorePath = Path.Combine(storePath, "trusted")
|
||||
},
|
||||
RejectedCertificateStore = new CertificateTrustList
|
||||
{
|
||||
StoreType = CertificateStoreType.Directory,
|
||||
StorePath = Path.Combine(storePath, "rejected")
|
||||
},
|
||||
AutoAcceptUntrustedCertificates = settings.AutoAcceptCertificates
|
||||
},
|
||||
ClientConfiguration = new ClientConfiguration
|
||||
{
|
||||
DefaultSessionTimeout = settings.SessionTimeoutSeconds * 1000
|
||||
}
|
||||
};
|
||||
|
||||
await config.Validate(ApplicationType.Client);
|
||||
|
||||
if (settings.AutoAcceptCertificates)
|
||||
{
|
||||
config.CertificateValidator.CertificateValidation += (_, e) => e.Accept = true;
|
||||
}
|
||||
|
||||
if (settings.SecurityMode != Models.SecurityMode.None)
|
||||
{
|
||||
var app = new ApplicationInstance
|
||||
{
|
||||
ApplicationName = "LmxOpcUaClient",
|
||||
ApplicationType = ApplicationType.Client,
|
||||
ApplicationConfiguration = config
|
||||
};
|
||||
await app.CheckApplicationInstanceCertificatesAsync(false, 2048);
|
||||
}
|
||||
|
||||
Logger.Debug("ApplicationConfiguration created for {EndpointUrl}", settings.EndpointUrl);
|
||||
return config;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
using Opc.Ua;
|
||||
using Opc.Ua.Client;
|
||||
using Serilog;
|
||||
|
||||
namespace ZB.MOM.WW.LmxOpcUa.Client.Shared.Adapters;
|
||||
|
||||
/// <summary>
|
||||
/// Production endpoint discovery that queries the real server.
|
||||
/// </summary>
|
||||
internal sealed class DefaultEndpointDiscovery : IEndpointDiscovery
|
||||
{
|
||||
private static readonly ILogger Logger = Log.ForContext<DefaultEndpointDiscovery>();
|
||||
|
||||
public EndpointDescription SelectEndpoint(ApplicationConfiguration config, string endpointUrl, MessageSecurityMode requestedMode)
|
||||
{
|
||||
if (requestedMode == MessageSecurityMode.None)
|
||||
{
|
||||
#pragma warning disable CS0618 // Acceptable for endpoint selection
|
||||
return CoreClientUtils.SelectEndpoint(config, endpointUrl, false);
|
||||
#pragma warning restore CS0618
|
||||
}
|
||||
|
||||
using var client = DiscoveryClient.Create(new Uri(endpointUrl));
|
||||
var allEndpoints = client.GetEndpoints(null);
|
||||
|
||||
EndpointDescription? best = null;
|
||||
|
||||
foreach (var ep in allEndpoints)
|
||||
{
|
||||
if (ep.SecurityMode != requestedMode)
|
||||
continue;
|
||||
|
||||
if (best == null)
|
||||
{
|
||||
best = ep;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (ep.SecurityPolicyUri == SecurityPolicies.Basic256Sha256)
|
||||
best = ep;
|
||||
}
|
||||
|
||||
if (best == null)
|
||||
{
|
||||
var available = string.Join(", ", allEndpoints.Select(e => $"{e.SecurityMode}/{e.SecurityPolicyUri}"));
|
||||
throw new InvalidOperationException(
|
||||
$"No endpoint found with security mode '{requestedMode}'. Available endpoints: {available}");
|
||||
}
|
||||
|
||||
// Rewrite endpoint URL hostname to match user-supplied hostname
|
||||
var serverUri = new Uri(best.EndpointUrl);
|
||||
var requestedUri = new Uri(endpointUrl);
|
||||
if (serverUri.Host != requestedUri.Host)
|
||||
{
|
||||
var builder = new UriBuilder(best.EndpointUrl) { Host = requestedUri.Host };
|
||||
best.EndpointUrl = builder.ToString();
|
||||
Logger.Debug("Rewrote endpoint host from {ServerHost} to {RequestedHost}", serverUri.Host, requestedUri.Host);
|
||||
}
|
||||
|
||||
return best;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,230 @@
|
||||
using Opc.Ua;
|
||||
using Opc.Ua.Client;
|
||||
using Serilog;
|
||||
|
||||
namespace ZB.MOM.WW.LmxOpcUa.Client.Shared.Adapters;
|
||||
|
||||
/// <summary>
|
||||
/// Production session adapter wrapping a real OPC UA Session.
|
||||
/// </summary>
|
||||
internal sealed class DefaultSessionAdapter : ISessionAdapter
|
||||
{
|
||||
private static readonly ILogger Logger = Log.ForContext<DefaultSessionAdapter>();
|
||||
private readonly Session _session;
|
||||
|
||||
public DefaultSessionAdapter(Session session)
|
||||
{
|
||||
_session = session;
|
||||
}
|
||||
|
||||
public bool Connected => _session.Connected;
|
||||
public string SessionId => _session.SessionId?.ToString() ?? string.Empty;
|
||||
public string SessionName => _session.SessionName ?? string.Empty;
|
||||
public string EndpointUrl => _session.Endpoint?.EndpointUrl ?? string.Empty;
|
||||
public string ServerName => _session.Endpoint?.Server?.ApplicationName?.Text ?? string.Empty;
|
||||
public string SecurityMode => _session.Endpoint?.SecurityMode.ToString() ?? string.Empty;
|
||||
public string SecurityPolicyUri => _session.Endpoint?.SecurityPolicyUri ?? string.Empty;
|
||||
public NamespaceTable NamespaceUris => _session.NamespaceUris;
|
||||
|
||||
public void RegisterKeepAliveHandler(Action<bool> callback)
|
||||
{
|
||||
_session.KeepAlive += (_, e) =>
|
||||
{
|
||||
var isGood = e.Status == null || ServiceResult.IsGood(e.Status);
|
||||
callback(isGood);
|
||||
};
|
||||
}
|
||||
|
||||
public async Task<DataValue> ReadValueAsync(NodeId nodeId, CancellationToken ct)
|
||||
{
|
||||
return await _session.ReadValueAsync(nodeId, ct);
|
||||
}
|
||||
|
||||
public async Task<StatusCode> WriteValueAsync(NodeId nodeId, DataValue value, CancellationToken ct)
|
||||
{
|
||||
var writeValue = new WriteValue
|
||||
{
|
||||
NodeId = nodeId,
|
||||
AttributeId = Attributes.Value,
|
||||
Value = value
|
||||
};
|
||||
|
||||
var writeCollection = new WriteValueCollection { writeValue };
|
||||
var response = await _session.WriteAsync(null, writeCollection, ct);
|
||||
return response.Results[0];
|
||||
}
|
||||
|
||||
public async Task<(byte[]? ContinuationPoint, ReferenceDescriptionCollection References)> BrowseAsync(
|
||||
NodeId nodeId, uint nodeClassMask, CancellationToken ct)
|
||||
{
|
||||
var (_, continuationPoint, references) = await _session.BrowseAsync(
|
||||
null,
|
||||
null,
|
||||
nodeId,
|
||||
0u,
|
||||
BrowseDirection.Forward,
|
||||
ReferenceTypeIds.HierarchicalReferences,
|
||||
true,
|
||||
nodeClassMask);
|
||||
|
||||
return (continuationPoint, references ?? new ReferenceDescriptionCollection());
|
||||
}
|
||||
|
||||
public async Task<(byte[]? ContinuationPoint, ReferenceDescriptionCollection References)> BrowseNextAsync(
|
||||
byte[] continuationPoint, CancellationToken ct)
|
||||
{
|
||||
var (_, nextCp, nextRefs) = await _session.BrowseNextAsync(null, false, continuationPoint);
|
||||
return (nextCp, nextRefs ?? new ReferenceDescriptionCollection());
|
||||
}
|
||||
|
||||
public async Task<bool> HasChildrenAsync(NodeId nodeId, CancellationToken ct)
|
||||
{
|
||||
var (_, _, references) = await _session.BrowseAsync(
|
||||
null,
|
||||
null,
|
||||
nodeId,
|
||||
1u,
|
||||
BrowseDirection.Forward,
|
||||
ReferenceTypeIds.HierarchicalReferences,
|
||||
true,
|
||||
0u);
|
||||
|
||||
return references != null && references.Count > 0;
|
||||
}
|
||||
|
||||
public async Task<IReadOnlyList<DataValue>> HistoryReadRawAsync(
|
||||
NodeId nodeId, DateTime startTime, DateTime endTime, int maxValues, CancellationToken ct)
|
||||
{
|
||||
var details = new ReadRawModifiedDetails
|
||||
{
|
||||
StartTime = startTime,
|
||||
EndTime = endTime,
|
||||
NumValuesPerNode = (uint)maxValues,
|
||||
IsReadModified = false,
|
||||
ReturnBounds = false
|
||||
};
|
||||
|
||||
var nodesToRead = new HistoryReadValueIdCollection
|
||||
{
|
||||
new HistoryReadValueId { NodeId = nodeId }
|
||||
};
|
||||
|
||||
var allValues = new List<DataValue>();
|
||||
byte[]? continuationPoint = null;
|
||||
|
||||
do
|
||||
{
|
||||
if (continuationPoint != null)
|
||||
nodesToRead[0].ContinuationPoint = continuationPoint;
|
||||
|
||||
_session.HistoryRead(
|
||||
null,
|
||||
new ExtensionObject(details),
|
||||
TimestampsToReturn.Source,
|
||||
continuationPoint != null,
|
||||
nodesToRead,
|
||||
out var results,
|
||||
out _);
|
||||
|
||||
if (results == null || results.Count == 0)
|
||||
break;
|
||||
|
||||
var result = results[0];
|
||||
if (StatusCode.IsBad(result.StatusCode))
|
||||
break;
|
||||
|
||||
if (result.HistoryData is ExtensionObject ext && ext.Body is HistoryData historyData)
|
||||
{
|
||||
allValues.AddRange(historyData.DataValues);
|
||||
}
|
||||
|
||||
continuationPoint = result.ContinuationPoint;
|
||||
}
|
||||
while (continuationPoint != null && continuationPoint.Length > 0 && allValues.Count < maxValues);
|
||||
|
||||
return allValues;
|
||||
}
|
||||
|
||||
public async Task<IReadOnlyList<DataValue>> HistoryReadAggregateAsync(
|
||||
NodeId nodeId, DateTime startTime, DateTime endTime, NodeId aggregateId, double intervalMs, CancellationToken ct)
|
||||
{
|
||||
var details = new ReadProcessedDetails
|
||||
{
|
||||
StartTime = startTime,
|
||||
EndTime = endTime,
|
||||
ProcessingInterval = intervalMs,
|
||||
AggregateType = new NodeIdCollection { aggregateId }
|
||||
};
|
||||
|
||||
var nodesToRead = new HistoryReadValueIdCollection
|
||||
{
|
||||
new HistoryReadValueId { NodeId = nodeId }
|
||||
};
|
||||
|
||||
_session.HistoryRead(
|
||||
null,
|
||||
new ExtensionObject(details),
|
||||
TimestampsToReturn.Source,
|
||||
false,
|
||||
nodesToRead,
|
||||
out var results,
|
||||
out _);
|
||||
|
||||
var allValues = new List<DataValue>();
|
||||
|
||||
if (results != null && results.Count > 0)
|
||||
{
|
||||
var result = results[0];
|
||||
if (!StatusCode.IsBad(result.StatusCode) &&
|
||||
result.HistoryData is ExtensionObject ext &&
|
||||
ext.Body is HistoryData historyData)
|
||||
{
|
||||
allValues.AddRange(historyData.DataValues);
|
||||
}
|
||||
}
|
||||
|
||||
return allValues;
|
||||
}
|
||||
|
||||
public async Task<ISubscriptionAdapter> CreateSubscriptionAsync(int publishingIntervalMs, CancellationToken ct)
|
||||
{
|
||||
var subscription = new Subscription(_session.DefaultSubscription)
|
||||
{
|
||||
PublishingInterval = publishingIntervalMs,
|
||||
DisplayName = "ClientShared_Subscription"
|
||||
};
|
||||
|
||||
_session.AddSubscription(subscription);
|
||||
await subscription.CreateAsync(ct);
|
||||
|
||||
return new DefaultSubscriptionAdapter(subscription);
|
||||
}
|
||||
|
||||
public async Task CloseAsync(CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (_session.Connected)
|
||||
{
|
||||
_session.Close();
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Logger.Warning(ex, "Error closing session");
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
try
|
||||
{
|
||||
if (_session.Connected)
|
||||
{
|
||||
_session.Close();
|
||||
}
|
||||
}
|
||||
catch { }
|
||||
_session.Dispose();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
using Opc.Ua;
|
||||
using Opc.Ua.Client;
|
||||
using Serilog;
|
||||
|
||||
namespace ZB.MOM.WW.LmxOpcUa.Client.Shared.Adapters;
|
||||
|
||||
/// <summary>
|
||||
/// Production session factory that creates real OPC UA sessions.
|
||||
/// </summary>
|
||||
internal sealed class DefaultSessionFactory : ISessionFactory
|
||||
{
|
||||
private static readonly ILogger Logger = Log.ForContext<DefaultSessionFactory>();
|
||||
|
||||
public async Task<ISessionAdapter> CreateSessionAsync(
|
||||
ApplicationConfiguration config,
|
||||
EndpointDescription endpoint,
|
||||
string sessionName,
|
||||
uint sessionTimeoutMs,
|
||||
UserIdentity identity,
|
||||
CancellationToken ct)
|
||||
{
|
||||
var endpointConfig = EndpointConfiguration.Create(config);
|
||||
var configuredEndpoint = new ConfiguredEndpoint(null, endpoint, endpointConfig);
|
||||
|
||||
var session = await Session.Create(
|
||||
config,
|
||||
configuredEndpoint,
|
||||
false,
|
||||
sessionName,
|
||||
sessionTimeoutMs,
|
||||
identity,
|
||||
null);
|
||||
|
||||
Logger.Information("Session created: {SessionName} -> {EndpointUrl}", sessionName, endpoint.EndpointUrl);
|
||||
return new DefaultSessionAdapter(session);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
using Opc.Ua;
|
||||
using Opc.Ua.Client;
|
||||
using Serilog;
|
||||
|
||||
namespace ZB.MOM.WW.LmxOpcUa.Client.Shared.Adapters;
|
||||
|
||||
/// <summary>
|
||||
/// Production subscription adapter wrapping a real OPC UA Subscription.
|
||||
/// </summary>
|
||||
internal sealed class DefaultSubscriptionAdapter : ISubscriptionAdapter
|
||||
{
|
||||
private static readonly ILogger Logger = Log.ForContext<DefaultSubscriptionAdapter>();
|
||||
private readonly Subscription _subscription;
|
||||
private readonly Dictionary<uint, MonitoredItem> _monitoredItems = new();
|
||||
|
||||
public DefaultSubscriptionAdapter(Subscription subscription)
|
||||
{
|
||||
_subscription = subscription;
|
||||
}
|
||||
|
||||
public uint SubscriptionId => _subscription.Id;
|
||||
|
||||
public async Task<uint> AddDataChangeMonitoredItemAsync(
|
||||
NodeId nodeId, int samplingIntervalMs, Action<string, DataValue> onDataChange, CancellationToken ct)
|
||||
{
|
||||
var item = new MonitoredItem(_subscription.DefaultItem)
|
||||
{
|
||||
StartNodeId = nodeId,
|
||||
DisplayName = nodeId.ToString(),
|
||||
SamplingInterval = samplingIntervalMs
|
||||
};
|
||||
|
||||
item.Notification += (_, e) =>
|
||||
{
|
||||
if (e.NotificationValue is MonitoredItemNotification notification)
|
||||
{
|
||||
onDataChange(nodeId.ToString(), notification.Value);
|
||||
}
|
||||
};
|
||||
|
||||
_subscription.AddItem(item);
|
||||
await _subscription.ApplyChangesAsync(ct);
|
||||
|
||||
var handle = item.ClientHandle;
|
||||
_monitoredItems[handle] = item;
|
||||
|
||||
Logger.Debug("Added data change monitored item for {NodeId}, handle={Handle}", nodeId, handle);
|
||||
return handle;
|
||||
}
|
||||
|
||||
public async Task RemoveMonitoredItemAsync(uint clientHandle, CancellationToken ct)
|
||||
{
|
||||
if (!_monitoredItems.TryGetValue(clientHandle, out var item))
|
||||
return;
|
||||
|
||||
_subscription.RemoveItem(item);
|
||||
await _subscription.ApplyChangesAsync(ct);
|
||||
_monitoredItems.Remove(clientHandle);
|
||||
|
||||
Logger.Debug("Removed monitored item handle={Handle}", clientHandle);
|
||||
}
|
||||
|
||||
public async Task<uint> AddEventMonitoredItemAsync(
|
||||
NodeId nodeId, int samplingIntervalMs, EventFilter filter, Action<EventFieldList> onEvent, CancellationToken ct)
|
||||
{
|
||||
var item = new MonitoredItem(_subscription.DefaultItem)
|
||||
{
|
||||
StartNodeId = nodeId,
|
||||
DisplayName = "AlarmMonitor",
|
||||
SamplingInterval = samplingIntervalMs,
|
||||
NodeClass = NodeClass.Object,
|
||||
AttributeId = Attributes.EventNotifier,
|
||||
Filter = filter
|
||||
};
|
||||
|
||||
item.Notification += (_, e) =>
|
||||
{
|
||||
if (e.NotificationValue is EventFieldList eventFields)
|
||||
{
|
||||
onEvent(eventFields);
|
||||
}
|
||||
};
|
||||
|
||||
_subscription.AddItem(item);
|
||||
await _subscription.ApplyChangesAsync(ct);
|
||||
|
||||
var handle = item.ClientHandle;
|
||||
_monitoredItems[handle] = item;
|
||||
|
||||
Logger.Debug("Added event monitored item for {NodeId}, handle={Handle}", nodeId, handle);
|
||||
return handle;
|
||||
}
|
||||
|
||||
public async Task ConditionRefreshAsync(CancellationToken ct)
|
||||
{
|
||||
await _subscription.ConditionRefreshAsync(ct);
|
||||
}
|
||||
|
||||
public async Task DeleteAsync(CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
await _subscription.DeleteAsync(true);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Logger.Warning(ex, "Error deleting subscription");
|
||||
}
|
||||
_monitoredItems.Clear();
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
try
|
||||
{
|
||||
_subscription.Delete(true);
|
||||
}
|
||||
catch { }
|
||||
_monitoredItems.Clear();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
using Opc.Ua;
|
||||
using ZB.MOM.WW.LmxOpcUa.Client.Shared.Models;
|
||||
|
||||
namespace ZB.MOM.WW.LmxOpcUa.Client.Shared.Adapters;
|
||||
|
||||
/// <summary>
|
||||
/// Creates and configures an OPC UA ApplicationConfiguration.
|
||||
/// </summary>
|
||||
internal interface IApplicationConfigurationFactory
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a validated ApplicationConfiguration for the given connection settings.
|
||||
/// </summary>
|
||||
Task<ApplicationConfiguration> CreateAsync(ConnectionSettings settings, CancellationToken ct = default);
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
using Opc.Ua;
|
||||
|
||||
namespace ZB.MOM.WW.LmxOpcUa.Client.Shared.Adapters;
|
||||
|
||||
/// <summary>
|
||||
/// Abstracts OPC UA endpoint discovery for testability.
|
||||
/// </summary>
|
||||
internal interface IEndpointDiscovery
|
||||
{
|
||||
/// <summary>
|
||||
/// Discovers endpoints at the given URL and returns the best match for the requested security mode.
|
||||
/// Also rewrites the endpoint URL hostname to match the requested URL when they differ.
|
||||
/// </summary>
|
||||
EndpointDescription SelectEndpoint(ApplicationConfiguration config, string endpointUrl, MessageSecurityMode requestedMode);
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
using Opc.Ua;
|
||||
|
||||
namespace ZB.MOM.WW.LmxOpcUa.Client.Shared.Adapters;
|
||||
|
||||
/// <summary>
|
||||
/// Abstracts the OPC UA session for read, write, browse, history, and subscription operations.
|
||||
/// </summary>
|
||||
internal interface ISessionAdapter : IDisposable
|
||||
{
|
||||
bool Connected { get; }
|
||||
string SessionId { get; }
|
||||
string SessionName { get; }
|
||||
string EndpointUrl { get; }
|
||||
string ServerName { get; }
|
||||
string SecurityMode { get; }
|
||||
string SecurityPolicyUri { get; }
|
||||
NamespaceTable NamespaceUris { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Registers a keep-alive callback. The callback receives true when the session is healthy, false on failure.
|
||||
/// </summary>
|
||||
void RegisterKeepAliveHandler(Action<bool> callback);
|
||||
|
||||
Task<DataValue> ReadValueAsync(NodeId nodeId, CancellationToken ct = default);
|
||||
Task<StatusCode> WriteValueAsync(NodeId nodeId, DataValue value, CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// Browses forward hierarchical references from the given node.
|
||||
/// Returns (continuationPoint, references).
|
||||
/// </summary>
|
||||
Task<(byte[]? ContinuationPoint, ReferenceDescriptionCollection References)> BrowseAsync(
|
||||
NodeId nodeId, uint nodeClassMask = 0, CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// Continues a browse from a continuation point.
|
||||
/// </summary>
|
||||
Task<(byte[]? ContinuationPoint, ReferenceDescriptionCollection References)> BrowseNextAsync(
|
||||
byte[] continuationPoint, CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// Checks whether a node has any forward hierarchical child references.
|
||||
/// </summary>
|
||||
Task<bool> HasChildrenAsync(NodeId nodeId, CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// Reads raw historical data.
|
||||
/// </summary>
|
||||
Task<IReadOnlyList<DataValue>> HistoryReadRawAsync(NodeId nodeId, DateTime startTime, DateTime endTime, int maxValues, CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// Reads processed/aggregate historical data.
|
||||
/// </summary>
|
||||
Task<IReadOnlyList<DataValue>> HistoryReadAggregateAsync(NodeId nodeId, DateTime startTime, DateTime endTime, NodeId aggregateId, double intervalMs, CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// Creates a subscription adapter for this session.
|
||||
/// </summary>
|
||||
Task<ISubscriptionAdapter> CreateSubscriptionAsync(int publishingIntervalMs, CancellationToken ct = default);
|
||||
|
||||
Task CloseAsync(CancellationToken ct = default);
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
using Opc.Ua;
|
||||
|
||||
namespace ZB.MOM.WW.LmxOpcUa.Client.Shared.Adapters;
|
||||
|
||||
/// <summary>
|
||||
/// Creates OPC UA sessions from a configured endpoint.
|
||||
/// </summary>
|
||||
internal interface ISessionFactory
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a session to the given endpoint.
|
||||
/// </summary>
|
||||
/// <param name="config">The application configuration.</param>
|
||||
/// <param name="endpoint">The configured endpoint.</param>
|
||||
/// <param name="sessionName">The session name.</param>
|
||||
/// <param name="sessionTimeoutMs">Session timeout in milliseconds.</param>
|
||||
/// <param name="identity">The user identity.</param>
|
||||
/// <param name="ct">Cancellation token.</param>
|
||||
/// <returns>A session adapter wrapping the created session.</returns>
|
||||
Task<ISessionAdapter> CreateSessionAsync(
|
||||
ApplicationConfiguration config,
|
||||
EndpointDescription endpoint,
|
||||
string sessionName,
|
||||
uint sessionTimeoutMs,
|
||||
UserIdentity identity,
|
||||
CancellationToken ct = default);
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
using Opc.Ua;
|
||||
|
||||
namespace ZB.MOM.WW.LmxOpcUa.Client.Shared.Adapters;
|
||||
|
||||
/// <summary>
|
||||
/// Abstracts OPC UA subscription and monitored item management.
|
||||
/// </summary>
|
||||
internal interface ISubscriptionAdapter : IDisposable
|
||||
{
|
||||
uint SubscriptionId { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Adds a data-change monitored item and returns its client handle for tracking.
|
||||
/// </summary>
|
||||
/// <param name="nodeId">The node to monitor.</param>
|
||||
/// <param name="samplingIntervalMs">The sampling interval in milliseconds.</param>
|
||||
/// <param name="onDataChange">Callback when data changes. Receives (nodeIdString, DataValue).</param>
|
||||
/// <param name="ct">Cancellation token.</param>
|
||||
/// <returns>A client handle that can be used to remove the item.</returns>
|
||||
Task<uint> AddDataChangeMonitoredItemAsync(NodeId nodeId, int samplingIntervalMs, Action<string, DataValue> onDataChange, CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// Removes a previously added monitored item by its client handle.
|
||||
/// </summary>
|
||||
Task RemoveMonitoredItemAsync(uint clientHandle, CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// Adds an event monitored item with the given event filter.
|
||||
/// </summary>
|
||||
/// <param name="nodeId">The node to monitor for events.</param>
|
||||
/// <param name="samplingIntervalMs">The sampling interval.</param>
|
||||
/// <param name="filter">The event filter defining which fields to select.</param>
|
||||
/// <param name="onEvent">Callback when events arrive. Receives the event field list.</param>
|
||||
/// <param name="ct">Cancellation token.</param>
|
||||
/// <returns>A client handle for the monitored item.</returns>
|
||||
Task<uint> AddEventMonitoredItemAsync(NodeId nodeId, int samplingIntervalMs, EventFilter filter, Action<EventFieldList> onEvent, CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// Requests a condition refresh for this subscription.
|
||||
/// </summary>
|
||||
Task ConditionRefreshAsync(CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// Removes all monitored items and deletes the subscription.
|
||||
/// </summary>
|
||||
Task DeleteAsync(CancellationToken ct = default);
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
using Opc.Ua;
|
||||
using ZB.MOM.WW.LmxOpcUa.Client.Shared.Models;
|
||||
|
||||
namespace ZB.MOM.WW.LmxOpcUa.Client.Shared.Helpers;
|
||||
|
||||
/// <summary>
|
||||
/// Maps the library's AggregateType enum to OPC UA aggregate function NodeIds.
|
||||
/// </summary>
|
||||
public static class AggregateTypeMapper
|
||||
{
|
||||
/// <summary>
|
||||
/// Returns the OPC UA NodeId for the specified aggregate type.
|
||||
/// </summary>
|
||||
public static NodeId ToNodeId(AggregateType aggregate)
|
||||
{
|
||||
return aggregate switch
|
||||
{
|
||||
AggregateType.Average => ObjectIds.AggregateFunction_Average,
|
||||
AggregateType.Minimum => ObjectIds.AggregateFunction_Minimum,
|
||||
AggregateType.Maximum => ObjectIds.AggregateFunction_Maximum,
|
||||
AggregateType.Count => ObjectIds.AggregateFunction_Count,
|
||||
AggregateType.Start => ObjectIds.AggregateFunction_Start,
|
||||
AggregateType.End => ObjectIds.AggregateFunction_End,
|
||||
_ => throw new ArgumentOutOfRangeException(nameof(aggregate), aggregate, "Unknown AggregateType value.")
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
namespace ZB.MOM.WW.LmxOpcUa.Client.Shared.Helpers;
|
||||
|
||||
/// <summary>
|
||||
/// Parses and normalizes failover URL sets for redundant OPC UA connections.
|
||||
/// </summary>
|
||||
public static class FailoverUrlParser
|
||||
{
|
||||
/// <summary>
|
||||
/// Parses a comma-separated failover URL string, prepending the primary URL.
|
||||
/// Trims whitespace and deduplicates.
|
||||
/// </summary>
|
||||
/// <param name="primaryUrl">The primary endpoint URL.</param>
|
||||
/// <param name="failoverCsv">Optional comma-separated failover URLs.</param>
|
||||
/// <returns>An array with the primary URL first, followed by unique failover URLs.</returns>
|
||||
public static string[] Parse(string primaryUrl, string? failoverCsv)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(failoverCsv))
|
||||
return new[] { primaryUrl };
|
||||
|
||||
var urls = new List<string> { primaryUrl };
|
||||
foreach (var url in failoverCsv.Split(',', StringSplitOptions.RemoveEmptyEntries))
|
||||
{
|
||||
var trimmed = url.Trim();
|
||||
if (!string.IsNullOrEmpty(trimmed) && !urls.Contains(trimmed, StringComparer.OrdinalIgnoreCase))
|
||||
urls.Add(trimmed);
|
||||
}
|
||||
return urls.ToArray();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds a failover URL set from the primary URL and an optional array of failover URLs.
|
||||
/// </summary>
|
||||
/// <param name="primaryUrl">The primary endpoint URL.</param>
|
||||
/// <param name="failoverUrls">Optional failover URLs.</param>
|
||||
/// <returns>An array with the primary URL first, followed by unique failover URLs.</returns>
|
||||
public static string[] Parse(string primaryUrl, string[]? failoverUrls)
|
||||
{
|
||||
if (failoverUrls == null || failoverUrls.Length == 0)
|
||||
return new[] { primaryUrl };
|
||||
|
||||
var urls = new List<string> { primaryUrl };
|
||||
foreach (var url in failoverUrls)
|
||||
{
|
||||
var trimmed = url?.Trim();
|
||||
if (!string.IsNullOrEmpty(trimmed) && !urls.Contains(trimmed, StringComparer.OrdinalIgnoreCase))
|
||||
urls.Add(trimmed);
|
||||
}
|
||||
return urls.ToArray();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
using Opc.Ua;
|
||||
using ZB.MOM.WW.LmxOpcUa.Client.Shared.Models;
|
||||
|
||||
namespace ZB.MOM.WW.LmxOpcUa.Client.Shared.Helpers;
|
||||
|
||||
/// <summary>
|
||||
/// Maps between the library's SecurityMode enum and OPC UA SDK MessageSecurityMode.
|
||||
/// </summary>
|
||||
public static class SecurityModeMapper
|
||||
{
|
||||
/// <summary>
|
||||
/// Converts a <see cref="SecurityMode"/> to an OPC UA <see cref="MessageSecurityMode"/>.
|
||||
/// </summary>
|
||||
public static MessageSecurityMode ToMessageSecurityMode(SecurityMode mode)
|
||||
{
|
||||
return mode switch
|
||||
{
|
||||
SecurityMode.None => MessageSecurityMode.None,
|
||||
SecurityMode.Sign => MessageSecurityMode.Sign,
|
||||
SecurityMode.SignAndEncrypt => MessageSecurityMode.SignAndEncrypt,
|
||||
_ => throw new ArgumentOutOfRangeException(nameof(mode), mode, "Unknown SecurityMode value.")
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Parses a string to a <see cref="SecurityMode"/> value, case-insensitively.
|
||||
/// </summary>
|
||||
/// <param name="value">The string to parse (e.g., "none", "sign", "encrypt", "signandencrypt").</param>
|
||||
/// <returns>The corresponding SecurityMode.</returns>
|
||||
/// <exception cref="ArgumentException">Thrown for unrecognized values.</exception>
|
||||
public static SecurityMode FromString(string value)
|
||||
{
|
||||
return (value ?? "none").Trim().ToLowerInvariant() switch
|
||||
{
|
||||
"none" => SecurityMode.None,
|
||||
"sign" => SecurityMode.Sign,
|
||||
"encrypt" or "signandencrypt" => SecurityMode.SignAndEncrypt,
|
||||
_ => throw new ArgumentException(
|
||||
$"Unknown security mode '{value}'. Valid values: none, sign, encrypt, signandencrypt")
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
namespace ZB.MOM.WW.LmxOpcUa.Client.Shared.Helpers;
|
||||
|
||||
/// <summary>
|
||||
/// Converts raw string values into typed values based on the current value's runtime type.
|
||||
/// Ported from the CLI tool's OpcUaHelper.ConvertValue.
|
||||
/// </summary>
|
||||
public static class ValueConverter
|
||||
{
|
||||
/// <summary>
|
||||
/// Converts a raw string value into the runtime type expected by the target node.
|
||||
/// </summary>
|
||||
/// <param name="rawValue">The raw string supplied by the user.</param>
|
||||
/// <param name="currentValue">The current node value used to infer the target type. May be null.</param>
|
||||
/// <returns>A typed value suitable for an OPC UA write request.</returns>
|
||||
public static object ConvertValue(string rawValue, object? currentValue)
|
||||
{
|
||||
return currentValue switch
|
||||
{
|
||||
bool => bool.Parse(rawValue),
|
||||
byte => byte.Parse(rawValue),
|
||||
short => short.Parse(rawValue),
|
||||
ushort => ushort.Parse(rawValue),
|
||||
int => int.Parse(rawValue),
|
||||
uint => uint.Parse(rawValue),
|
||||
long => long.Parse(rawValue),
|
||||
ulong => ulong.Parse(rawValue),
|
||||
float => float.Parse(rawValue),
|
||||
double => double.Parse(rawValue),
|
||||
_ => rawValue
|
||||
};
|
||||
}
|
||||
}
|
||||
36
src/ZB.MOM.WW.LmxOpcUa.Client.Shared/IOpcUaClientService.cs
Normal file
36
src/ZB.MOM.WW.LmxOpcUa.Client.Shared/IOpcUaClientService.cs
Normal file
@@ -0,0 +1,36 @@
|
||||
using Opc.Ua;
|
||||
using ZB.MOM.WW.LmxOpcUa.Client.Shared.Models;
|
||||
|
||||
namespace ZB.MOM.WW.LmxOpcUa.Client.Shared;
|
||||
|
||||
/// <summary>
|
||||
/// Shared OPC UA client service contract for CLI and UI consumers.
|
||||
/// </summary>
|
||||
public interface IOpcUaClientService : IDisposable
|
||||
{
|
||||
Task<ConnectionInfo> ConnectAsync(ConnectionSettings settings, CancellationToken ct = default);
|
||||
Task DisconnectAsync(CancellationToken ct = default);
|
||||
bool IsConnected { get; }
|
||||
ConnectionInfo? CurrentConnectionInfo { get; }
|
||||
|
||||
Task<DataValue> ReadValueAsync(NodeId nodeId, CancellationToken ct = default);
|
||||
Task<StatusCode> WriteValueAsync(NodeId nodeId, object value, CancellationToken ct = default);
|
||||
|
||||
Task<IReadOnlyList<Models.BrowseResult>> BrowseAsync(NodeId? parentNodeId = null, CancellationToken ct = default);
|
||||
|
||||
Task SubscribeAsync(NodeId nodeId, int intervalMs = 1000, CancellationToken ct = default);
|
||||
Task UnsubscribeAsync(NodeId nodeId, CancellationToken ct = default);
|
||||
|
||||
Task SubscribeAlarmsAsync(NodeId? sourceNodeId = null, int intervalMs = 1000, CancellationToken ct = default);
|
||||
Task UnsubscribeAlarmsAsync(CancellationToken ct = default);
|
||||
Task RequestConditionRefreshAsync(CancellationToken ct = default);
|
||||
|
||||
Task<IReadOnlyList<DataValue>> HistoryReadRawAsync(NodeId nodeId, DateTime startTime, DateTime endTime, int maxValues = 1000, CancellationToken ct = default);
|
||||
Task<IReadOnlyList<DataValue>> HistoryReadAggregateAsync(NodeId nodeId, DateTime startTime, DateTime endTime, AggregateType aggregate, double intervalMs = 3600000, CancellationToken ct = default);
|
||||
|
||||
Task<RedundancyInfo> GetRedundancyInfoAsync(CancellationToken ct = default);
|
||||
|
||||
event EventHandler<DataChangedEventArgs>? DataChanged;
|
||||
event EventHandler<AlarmEventArgs>? AlarmEvent;
|
||||
event EventHandler<ConnectionStateChangedEventArgs>? ConnectionStateChanged;
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
namespace ZB.MOM.WW.LmxOpcUa.Client.Shared;
|
||||
|
||||
/// <summary>
|
||||
/// Factory for creating <see cref="IOpcUaClientService"/> instances.
|
||||
/// </summary>
|
||||
public interface IOpcUaClientServiceFactory
|
||||
{
|
||||
IOpcUaClientService Create();
|
||||
}
|
||||
25
src/ZB.MOM.WW.LmxOpcUa.Client.Shared/Models/AggregateType.cs
Normal file
25
src/ZB.MOM.WW.LmxOpcUa.Client.Shared/Models/AggregateType.cs
Normal file
@@ -0,0 +1,25 @@
|
||||
namespace ZB.MOM.WW.LmxOpcUa.Client.Shared.Models;
|
||||
|
||||
/// <summary>
|
||||
/// Aggregate functions for processed history reads.
|
||||
/// </summary>
|
||||
public enum AggregateType
|
||||
{
|
||||
/// <summary>Average of values in the interval.</summary>
|
||||
Average,
|
||||
|
||||
/// <summary>Minimum value in the interval.</summary>
|
||||
Minimum,
|
||||
|
||||
/// <summary>Maximum value in the interval.</summary>
|
||||
Maximum,
|
||||
|
||||
/// <summary>Count of values in the interval.</summary>
|
||||
Count,
|
||||
|
||||
/// <summary>First value in the interval.</summary>
|
||||
Start,
|
||||
|
||||
/// <summary>Last value in the interval.</summary>
|
||||
End
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
namespace ZB.MOM.WW.LmxOpcUa.Client.Shared.Models;
|
||||
|
||||
/// <summary>
|
||||
/// Event data for an alarm or condition notification from the OPC UA server.
|
||||
/// </summary>
|
||||
public sealed class AlarmEventArgs : EventArgs
|
||||
{
|
||||
/// <summary>The name of the source object that raised the alarm.</summary>
|
||||
public string SourceName { get; }
|
||||
|
||||
/// <summary>The condition type name.</summary>
|
||||
public string ConditionName { get; }
|
||||
|
||||
/// <summary>The alarm severity (0-1000).</summary>
|
||||
public ushort Severity { get; }
|
||||
|
||||
/// <summary>Human-readable alarm message.</summary>
|
||||
public string Message { get; }
|
||||
|
||||
/// <summary>Whether the alarm should be retained in the display.</summary>
|
||||
public bool Retain { get; }
|
||||
|
||||
/// <summary>Whether the alarm condition is currently active.</summary>
|
||||
public bool ActiveState { get; }
|
||||
|
||||
/// <summary>Whether the alarm has been acknowledged.</summary>
|
||||
public bool AckedState { get; }
|
||||
|
||||
/// <summary>The time the event occurred.</summary>
|
||||
public DateTime Time { get; }
|
||||
|
||||
public AlarmEventArgs(
|
||||
string sourceName,
|
||||
string conditionName,
|
||||
ushort severity,
|
||||
string message,
|
||||
bool retain,
|
||||
bool activeState,
|
||||
bool ackedState,
|
||||
DateTime time)
|
||||
{
|
||||
SourceName = sourceName;
|
||||
ConditionName = conditionName;
|
||||
Severity = severity;
|
||||
Message = message;
|
||||
Retain = retain;
|
||||
ActiveState = activeState;
|
||||
AckedState = ackedState;
|
||||
Time = time;
|
||||
}
|
||||
}
|
||||
35
src/ZB.MOM.WW.LmxOpcUa.Client.Shared/Models/BrowseResult.cs
Normal file
35
src/ZB.MOM.WW.LmxOpcUa.Client.Shared/Models/BrowseResult.cs
Normal file
@@ -0,0 +1,35 @@
|
||||
namespace ZB.MOM.WW.LmxOpcUa.Client.Shared.Models;
|
||||
|
||||
/// <summary>
|
||||
/// Represents a single node in the browse result set.
|
||||
/// </summary>
|
||||
public sealed class BrowseResult
|
||||
{
|
||||
/// <summary>
|
||||
/// The string representation of the node's NodeId.
|
||||
/// </summary>
|
||||
public string NodeId { get; }
|
||||
|
||||
/// <summary>
|
||||
/// The display name of the node.
|
||||
/// </summary>
|
||||
public string DisplayName { get; }
|
||||
|
||||
/// <summary>
|
||||
/// The node class (e.g., "Object", "Variable", "Method").
|
||||
/// </summary>
|
||||
public string NodeClass { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Whether the node has child references.
|
||||
/// </summary>
|
||||
public bool HasChildren { get; }
|
||||
|
||||
public BrowseResult(string nodeId, string displayName, string nodeClass, bool hasChildren)
|
||||
{
|
||||
NodeId = nodeId;
|
||||
DisplayName = displayName;
|
||||
NodeClass = nodeClass;
|
||||
HasChildren = hasChildren;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
namespace ZB.MOM.WW.LmxOpcUa.Client.Shared.Models;
|
||||
|
||||
/// <summary>
|
||||
/// Information about the current OPC UA session.
|
||||
/// </summary>
|
||||
public sealed class ConnectionInfo
|
||||
{
|
||||
/// <summary>The endpoint URL of the connected server.</summary>
|
||||
public string EndpointUrl { get; }
|
||||
|
||||
/// <summary>The server application name.</summary>
|
||||
public string ServerName { get; }
|
||||
|
||||
/// <summary>The security mode in use (e.g., "None", "Sign", "SignAndEncrypt").</summary>
|
||||
public string SecurityMode { get; }
|
||||
|
||||
/// <summary>The security policy URI (e.g., "http://opcfoundation.org/UA/SecurityPolicy#None").</summary>
|
||||
public string SecurityPolicyUri { get; }
|
||||
|
||||
/// <summary>The session identifier.</summary>
|
||||
public string SessionId { get; }
|
||||
|
||||
/// <summary>The session name.</summary>
|
||||
public string SessionName { get; }
|
||||
|
||||
public ConnectionInfo(
|
||||
string endpointUrl,
|
||||
string serverName,
|
||||
string securityMode,
|
||||
string securityPolicyUri,
|
||||
string sessionId,
|
||||
string sessionName)
|
||||
{
|
||||
EndpointUrl = endpointUrl;
|
||||
ServerName = serverName;
|
||||
SecurityMode = securityMode;
|
||||
SecurityPolicyUri = securityPolicyUri;
|
||||
SessionId = sessionId;
|
||||
SessionName = sessionName;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
namespace ZB.MOM.WW.LmxOpcUa.Client.Shared.Models;
|
||||
|
||||
/// <summary>
|
||||
/// Settings for establishing an OPC UA client connection.
|
||||
/// </summary>
|
||||
public sealed class ConnectionSettings
|
||||
{
|
||||
/// <summary>
|
||||
/// The primary OPC UA endpoint URL.
|
||||
/// </summary>
|
||||
public string EndpointUrl { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// Optional failover endpoint URLs for redundancy.
|
||||
/// </summary>
|
||||
public string[]? FailoverUrls { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Optional username for authentication.
|
||||
/// </summary>
|
||||
public string? Username { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Optional password for authentication.
|
||||
/// </summary>
|
||||
public string? Password { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Transport security mode. Defaults to <see cref="Models.SecurityMode.None"/>.
|
||||
/// </summary>
|
||||
public SecurityMode SecurityMode { get; set; } = SecurityMode.None;
|
||||
|
||||
/// <summary>
|
||||
/// Session timeout in seconds. Defaults to 60.
|
||||
/// </summary>
|
||||
public int SessionTimeoutSeconds { get; set; } = 60;
|
||||
|
||||
/// <summary>
|
||||
/// Whether to automatically accept untrusted server certificates. Defaults to true.
|
||||
/// </summary>
|
||||
public bool AutoAcceptCertificates { get; set; } = true;
|
||||
|
||||
/// <summary>
|
||||
/// Path to the certificate store. Defaults to a subdirectory under LocalApplicationData.
|
||||
/// </summary>
|
||||
public string CertificateStorePath { get; set; } = Path.Combine(
|
||||
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
|
||||
"LmxOpcUaClient", "pki");
|
||||
|
||||
/// <summary>
|
||||
/// Validates the settings and throws if any required values are missing or invalid.
|
||||
/// </summary>
|
||||
/// <exception cref="ArgumentException">Thrown when settings are invalid.</exception>
|
||||
public void Validate()
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(EndpointUrl))
|
||||
throw new ArgumentException("EndpointUrl must not be null or empty.", nameof(EndpointUrl));
|
||||
|
||||
if (SessionTimeoutSeconds <= 0)
|
||||
throw new ArgumentException("SessionTimeoutSeconds must be greater than zero.", nameof(SessionTimeoutSeconds));
|
||||
|
||||
if (SessionTimeoutSeconds > 3600)
|
||||
throw new ArgumentException("SessionTimeoutSeconds must not exceed 3600.", nameof(SessionTimeoutSeconds));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
namespace ZB.MOM.WW.LmxOpcUa.Client.Shared.Models;
|
||||
|
||||
/// <summary>
|
||||
/// Represents the current state of the OPC UA client connection.
|
||||
/// </summary>
|
||||
public enum ConnectionState
|
||||
{
|
||||
/// <summary>Not connected to any server.</summary>
|
||||
Disconnected,
|
||||
|
||||
/// <summary>Connection attempt is in progress.</summary>
|
||||
Connecting,
|
||||
|
||||
/// <summary>Successfully connected to a server.</summary>
|
||||
Connected,
|
||||
|
||||
/// <summary>Connection was lost and reconnection is in progress.</summary>
|
||||
Reconnecting
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
namespace ZB.MOM.WW.LmxOpcUa.Client.Shared.Models;
|
||||
|
||||
/// <summary>
|
||||
/// Event data raised when the client connection state changes.
|
||||
/// </summary>
|
||||
public sealed class ConnectionStateChangedEventArgs : EventArgs
|
||||
{
|
||||
/// <summary>The previous connection state.</summary>
|
||||
public ConnectionState OldState { get; }
|
||||
|
||||
/// <summary>The new connection state.</summary>
|
||||
public ConnectionState NewState { get; }
|
||||
|
||||
/// <summary>The endpoint URL associated with the state change.</summary>
|
||||
public string EndpointUrl { get; }
|
||||
|
||||
public ConnectionStateChangedEventArgs(ConnectionState oldState, ConnectionState newState, string endpointUrl)
|
||||
{
|
||||
OldState = oldState;
|
||||
NewState = newState;
|
||||
EndpointUrl = endpointUrl;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
using Opc.Ua;
|
||||
|
||||
namespace ZB.MOM.WW.LmxOpcUa.Client.Shared.Models;
|
||||
|
||||
/// <summary>
|
||||
/// Event data for a monitored data value change.
|
||||
/// </summary>
|
||||
public sealed class DataChangedEventArgs : EventArgs
|
||||
{
|
||||
/// <summary>The string representation of the node that changed.</summary>
|
||||
public string NodeId { get; }
|
||||
|
||||
/// <summary>The new data value from the server.</summary>
|
||||
public DataValue Value { get; }
|
||||
|
||||
public DataChangedEventArgs(string nodeId, DataValue value)
|
||||
{
|
||||
NodeId = nodeId;
|
||||
Value = value;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
namespace ZB.MOM.WW.LmxOpcUa.Client.Shared.Models;
|
||||
|
||||
/// <summary>
|
||||
/// Redundancy information read from the server.
|
||||
/// </summary>
|
||||
public sealed class RedundancyInfo
|
||||
{
|
||||
/// <summary>The redundancy mode (e.g., "None", "Cold", "Warm", "Hot").</summary>
|
||||
public string Mode { get; }
|
||||
|
||||
/// <summary>The server's current service level (0-255).</summary>
|
||||
public byte ServiceLevel { get; }
|
||||
|
||||
/// <summary>URIs of all servers in the redundant set.</summary>
|
||||
public string[] ServerUris { get; }
|
||||
|
||||
/// <summary>The application URI of the connected server.</summary>
|
||||
public string ApplicationUri { get; }
|
||||
|
||||
public RedundancyInfo(string mode, byte serviceLevel, string[] serverUris, string applicationUri)
|
||||
{
|
||||
Mode = mode;
|
||||
ServiceLevel = serviceLevel;
|
||||
ServerUris = serverUris;
|
||||
ApplicationUri = applicationUri;
|
||||
}
|
||||
}
|
||||
16
src/ZB.MOM.WW.LmxOpcUa.Client.Shared/Models/SecurityMode.cs
Normal file
16
src/ZB.MOM.WW.LmxOpcUa.Client.Shared/Models/SecurityMode.cs
Normal file
@@ -0,0 +1,16 @@
|
||||
namespace ZB.MOM.WW.LmxOpcUa.Client.Shared.Models;
|
||||
|
||||
/// <summary>
|
||||
/// Transport security mode for the OPC UA connection.
|
||||
/// </summary>
|
||||
public enum SecurityMode
|
||||
{
|
||||
/// <summary>No transport security.</summary>
|
||||
None,
|
||||
|
||||
/// <summary>Messages are signed but not encrypted.</summary>
|
||||
Sign,
|
||||
|
||||
/// <summary>Messages are signed and encrypted.</summary>
|
||||
SignAndEncrypt
|
||||
}
|
||||
572
src/ZB.MOM.WW.LmxOpcUa.Client.Shared/OpcUaClientService.cs
Normal file
572
src/ZB.MOM.WW.LmxOpcUa.Client.Shared/OpcUaClientService.cs
Normal file
@@ -0,0 +1,572 @@
|
||||
using Opc.Ua;
|
||||
using Serilog;
|
||||
using ZB.MOM.WW.LmxOpcUa.Client.Shared.Adapters;
|
||||
using ZB.MOM.WW.LmxOpcUa.Client.Shared.Helpers;
|
||||
using ZB.MOM.WW.LmxOpcUa.Client.Shared.Models;
|
||||
|
||||
namespace ZB.MOM.WW.LmxOpcUa.Client.Shared;
|
||||
|
||||
/// <summary>
|
||||
/// Full implementation of <see cref="IOpcUaClientService"/> using adapter abstractions for testability.
|
||||
/// </summary>
|
||||
public sealed class OpcUaClientService : IOpcUaClientService
|
||||
{
|
||||
private static readonly ILogger Logger = Log.ForContext<OpcUaClientService>();
|
||||
|
||||
private readonly IApplicationConfigurationFactory _configFactory;
|
||||
private readonly IEndpointDiscovery _endpointDiscovery;
|
||||
private readonly ISessionFactory _sessionFactory;
|
||||
|
||||
private ISessionAdapter? _session;
|
||||
private ISubscriptionAdapter? _dataSubscription;
|
||||
private ISubscriptionAdapter? _alarmSubscription;
|
||||
private ConnectionState _state = ConnectionState.Disconnected;
|
||||
private ConnectionSettings? _settings;
|
||||
private string[]? _allEndpointUrls;
|
||||
private int _currentEndpointIndex;
|
||||
private bool _disposed;
|
||||
|
||||
// Track active data subscriptions for replay after failover
|
||||
private readonly Dictionary<string, (NodeId NodeId, int IntervalMs, uint Handle)> _activeDataSubscriptions = new();
|
||||
// Track alarm subscription state for replay after failover
|
||||
private (NodeId? SourceNodeId, int IntervalMs)? _activeAlarmSubscription;
|
||||
|
||||
public event EventHandler<DataChangedEventArgs>? DataChanged;
|
||||
public event EventHandler<AlarmEventArgs>? AlarmEvent;
|
||||
public event EventHandler<ConnectionStateChangedEventArgs>? ConnectionStateChanged;
|
||||
|
||||
public bool IsConnected => _state == ConnectionState.Connected && _session?.Connected == true;
|
||||
public ConnectionInfo? CurrentConnectionInfo { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new OpcUaClientService with the specified adapter dependencies.
|
||||
/// </summary>
|
||||
internal OpcUaClientService(
|
||||
IApplicationConfigurationFactory configFactory,
|
||||
IEndpointDiscovery endpointDiscovery,
|
||||
ISessionFactory sessionFactory)
|
||||
{
|
||||
_configFactory = configFactory;
|
||||
_endpointDiscovery = endpointDiscovery;
|
||||
_sessionFactory = sessionFactory;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new OpcUaClientService with default production adapters.
|
||||
/// </summary>
|
||||
public OpcUaClientService()
|
||||
: this(
|
||||
new DefaultApplicationConfigurationFactory(),
|
||||
new DefaultEndpointDiscovery(),
|
||||
new DefaultSessionFactory())
|
||||
{
|
||||
}
|
||||
|
||||
public async Task<ConnectionInfo> ConnectAsync(ConnectionSettings settings, CancellationToken ct = default)
|
||||
{
|
||||
ThrowIfDisposed();
|
||||
settings.Validate();
|
||||
|
||||
_settings = settings;
|
||||
_allEndpointUrls = FailoverUrlParser.Parse(settings.EndpointUrl, settings.FailoverUrls);
|
||||
_currentEndpointIndex = 0;
|
||||
|
||||
TransitionState(ConnectionState.Connecting, settings.EndpointUrl);
|
||||
|
||||
try
|
||||
{
|
||||
var session = await ConnectToEndpointAsync(settings, _allEndpointUrls[0], ct);
|
||||
_session = session;
|
||||
|
||||
session.RegisterKeepAliveHandler(isGood =>
|
||||
{
|
||||
if (!isGood)
|
||||
{
|
||||
_ = HandleKeepAliveFailureAsync();
|
||||
}
|
||||
});
|
||||
|
||||
CurrentConnectionInfo = BuildConnectionInfo(session);
|
||||
TransitionState(ConnectionState.Connected, session.EndpointUrl);
|
||||
Logger.Information("Connected to {EndpointUrl}", session.EndpointUrl);
|
||||
return CurrentConnectionInfo;
|
||||
}
|
||||
catch
|
||||
{
|
||||
TransitionState(ConnectionState.Disconnected, settings.EndpointUrl);
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
public async Task DisconnectAsync(CancellationToken ct = default)
|
||||
{
|
||||
if (_state == ConnectionState.Disconnected)
|
||||
return;
|
||||
|
||||
var endpointUrl = _session?.EndpointUrl ?? _settings?.EndpointUrl ?? string.Empty;
|
||||
|
||||
try
|
||||
{
|
||||
if (_dataSubscription != null)
|
||||
{
|
||||
await _dataSubscription.DeleteAsync(ct);
|
||||
_dataSubscription = null;
|
||||
}
|
||||
if (_alarmSubscription != null)
|
||||
{
|
||||
await _alarmSubscription.DeleteAsync(ct);
|
||||
_alarmSubscription = null;
|
||||
}
|
||||
if (_session != null)
|
||||
{
|
||||
await _session.CloseAsync(ct);
|
||||
_session.Dispose();
|
||||
_session = null;
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Logger.Warning(ex, "Error during disconnect");
|
||||
}
|
||||
finally
|
||||
{
|
||||
_activeDataSubscriptions.Clear();
|
||||
_activeAlarmSubscription = null;
|
||||
CurrentConnectionInfo = null;
|
||||
TransitionState(ConnectionState.Disconnected, endpointUrl);
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<DataValue> ReadValueAsync(NodeId nodeId, CancellationToken ct = default)
|
||||
{
|
||||
ThrowIfDisposed();
|
||||
ThrowIfNotConnected();
|
||||
return await _session!.ReadValueAsync(nodeId, ct);
|
||||
}
|
||||
|
||||
public async Task<StatusCode> WriteValueAsync(NodeId nodeId, object value, CancellationToken ct = default)
|
||||
{
|
||||
ThrowIfDisposed();
|
||||
ThrowIfNotConnected();
|
||||
|
||||
// Read current value for type coercion when value is a string
|
||||
object typedValue = value;
|
||||
if (value is string rawString)
|
||||
{
|
||||
var currentDataValue = await _session!.ReadValueAsync(nodeId, ct);
|
||||
typedValue = ValueConverter.ConvertValue(rawString, currentDataValue.Value);
|
||||
}
|
||||
|
||||
var dataValue = new DataValue(new Variant(typedValue));
|
||||
return await _session!.WriteValueAsync(nodeId, dataValue, ct);
|
||||
}
|
||||
|
||||
public async Task<IReadOnlyList<Models.BrowseResult>> BrowseAsync(NodeId? parentNodeId = null, CancellationToken ct = default)
|
||||
{
|
||||
ThrowIfDisposed();
|
||||
ThrowIfNotConnected();
|
||||
|
||||
var startNode = parentNodeId ?? ObjectIds.ObjectsFolder;
|
||||
var nodeClassMask = (uint)NodeClass.Object | (uint)NodeClass.Variable | (uint)NodeClass.Method;
|
||||
var results = new List<Models.BrowseResult>();
|
||||
|
||||
var (continuationPoint, references) = await _session!.BrowseAsync(startNode, nodeClassMask, ct);
|
||||
|
||||
while (references.Count > 0)
|
||||
{
|
||||
foreach (var reference in references)
|
||||
{
|
||||
var childNodeId = ExpandedNodeId.ToNodeId(reference.NodeId, _session.NamespaceUris);
|
||||
var hasChildren = reference.NodeClass == NodeClass.Object &&
|
||||
await _session.HasChildrenAsync(childNodeId, ct);
|
||||
|
||||
results.Add(new Models.BrowseResult(
|
||||
reference.NodeId.ToString(),
|
||||
reference.DisplayName?.Text ?? string.Empty,
|
||||
reference.NodeClass.ToString(),
|
||||
hasChildren));
|
||||
}
|
||||
|
||||
if (continuationPoint != null && continuationPoint.Length > 0)
|
||||
{
|
||||
(continuationPoint, references) = await _session.BrowseNextAsync(continuationPoint, ct);
|
||||
}
|
||||
else
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return results;
|
||||
}
|
||||
|
||||
public async Task SubscribeAsync(NodeId nodeId, int intervalMs = 1000, CancellationToken ct = default)
|
||||
{
|
||||
ThrowIfDisposed();
|
||||
ThrowIfNotConnected();
|
||||
|
||||
var nodeIdStr = nodeId.ToString();
|
||||
if (_activeDataSubscriptions.ContainsKey(nodeIdStr))
|
||||
return; // Already subscribed
|
||||
|
||||
if (_dataSubscription == null)
|
||||
{
|
||||
_dataSubscription = await _session!.CreateSubscriptionAsync(intervalMs, ct);
|
||||
}
|
||||
|
||||
var handle = await _dataSubscription.AddDataChangeMonitoredItemAsync(
|
||||
nodeId, intervalMs, OnDataChangeNotification, ct);
|
||||
|
||||
_activeDataSubscriptions[nodeIdStr] = (nodeId, intervalMs, handle);
|
||||
Logger.Debug("Subscribed to data changes on {NodeId}", nodeId);
|
||||
}
|
||||
|
||||
public async Task UnsubscribeAsync(NodeId nodeId, CancellationToken ct = default)
|
||||
{
|
||||
ThrowIfDisposed();
|
||||
|
||||
var nodeIdStr = nodeId.ToString();
|
||||
if (!_activeDataSubscriptions.TryGetValue(nodeIdStr, out var sub))
|
||||
return; // Not subscribed, safe to ignore
|
||||
|
||||
if (_dataSubscription != null)
|
||||
{
|
||||
await _dataSubscription.RemoveMonitoredItemAsync(sub.Handle, ct);
|
||||
}
|
||||
|
||||
_activeDataSubscriptions.Remove(nodeIdStr);
|
||||
Logger.Debug("Unsubscribed from data changes on {NodeId}", nodeId);
|
||||
}
|
||||
|
||||
public async Task SubscribeAlarmsAsync(NodeId? sourceNodeId = null, int intervalMs = 1000, CancellationToken ct = default)
|
||||
{
|
||||
ThrowIfDisposed();
|
||||
ThrowIfNotConnected();
|
||||
|
||||
if (_alarmSubscription != null)
|
||||
return; // Already subscribed to alarms
|
||||
|
||||
var monitorNode = sourceNodeId ?? ObjectIds.Server;
|
||||
_alarmSubscription = await _session!.CreateSubscriptionAsync(intervalMs, ct);
|
||||
|
||||
var filter = CreateAlarmEventFilter();
|
||||
await _alarmSubscription.AddEventMonitoredItemAsync(
|
||||
monitorNode, intervalMs, filter, OnAlarmEventNotification, ct);
|
||||
|
||||
_activeAlarmSubscription = (sourceNodeId, intervalMs);
|
||||
Logger.Debug("Subscribed to alarm events on {NodeId}", monitorNode);
|
||||
}
|
||||
|
||||
public async Task UnsubscribeAlarmsAsync(CancellationToken ct = default)
|
||||
{
|
||||
ThrowIfDisposed();
|
||||
|
||||
if (_alarmSubscription == null)
|
||||
return;
|
||||
|
||||
await _alarmSubscription.DeleteAsync(ct);
|
||||
_alarmSubscription = null;
|
||||
_activeAlarmSubscription = null;
|
||||
Logger.Debug("Unsubscribed from alarm events");
|
||||
}
|
||||
|
||||
public async Task RequestConditionRefreshAsync(CancellationToken ct = default)
|
||||
{
|
||||
ThrowIfDisposed();
|
||||
ThrowIfNotConnected();
|
||||
|
||||
if (_alarmSubscription == null)
|
||||
throw new InvalidOperationException("No alarm subscription is active.");
|
||||
|
||||
await _alarmSubscription.ConditionRefreshAsync(ct);
|
||||
Logger.Debug("Condition refresh requested");
|
||||
}
|
||||
|
||||
public async Task<IReadOnlyList<DataValue>> HistoryReadRawAsync(
|
||||
NodeId nodeId, DateTime startTime, DateTime endTime, int maxValues = 1000, CancellationToken ct = default)
|
||||
{
|
||||
ThrowIfDisposed();
|
||||
ThrowIfNotConnected();
|
||||
return await _session!.HistoryReadRawAsync(nodeId, startTime, endTime, maxValues, ct);
|
||||
}
|
||||
|
||||
public async Task<IReadOnlyList<DataValue>> HistoryReadAggregateAsync(
|
||||
NodeId nodeId, DateTime startTime, DateTime endTime, AggregateType aggregate,
|
||||
double intervalMs = 3600000, CancellationToken ct = default)
|
||||
{
|
||||
ThrowIfDisposed();
|
||||
ThrowIfNotConnected();
|
||||
var aggregateNodeId = AggregateTypeMapper.ToNodeId(aggregate);
|
||||
return await _session!.HistoryReadAggregateAsync(nodeId, startTime, endTime, aggregateNodeId, intervalMs, ct);
|
||||
}
|
||||
|
||||
public async Task<RedundancyInfo> GetRedundancyInfoAsync(CancellationToken ct = default)
|
||||
{
|
||||
ThrowIfDisposed();
|
||||
ThrowIfNotConnected();
|
||||
|
||||
var redundancySupportValue = await _session!.ReadValueAsync(VariableIds.Server_ServerRedundancy_RedundancySupport, ct);
|
||||
var redundancyMode = ((RedundancySupport)(int)redundancySupportValue.Value).ToString();
|
||||
|
||||
var serviceLevelValue = await _session.ReadValueAsync(VariableIds.Server_ServiceLevel, ct);
|
||||
var serviceLevel = (byte)serviceLevelValue.Value;
|
||||
|
||||
string[] serverUris = Array.Empty<string>();
|
||||
try
|
||||
{
|
||||
var serverUriArrayValue = await _session.ReadValueAsync(VariableIds.Server_ServerRedundancy_ServerUriArray, ct);
|
||||
if (serverUriArrayValue.Value is string[] uris)
|
||||
serverUris = uris;
|
||||
}
|
||||
catch
|
||||
{
|
||||
// ServerUriArray may not be present when RedundancySupport is None
|
||||
}
|
||||
|
||||
string applicationUri = string.Empty;
|
||||
try
|
||||
{
|
||||
var serverArrayValue = await _session.ReadValueAsync(VariableIds.Server_ServerArray, ct);
|
||||
if (serverArrayValue.Value is string[] serverArray && serverArray.Length > 0)
|
||||
applicationUri = serverArray[0];
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Informational only
|
||||
}
|
||||
|
||||
return new RedundancyInfo(redundancyMode, serviceLevel, serverUris, applicationUri);
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (_disposed) return;
|
||||
_disposed = true;
|
||||
|
||||
_dataSubscription?.Dispose();
|
||||
_alarmSubscription?.Dispose();
|
||||
_session?.Dispose();
|
||||
_activeDataSubscriptions.Clear();
|
||||
_activeAlarmSubscription = null;
|
||||
CurrentConnectionInfo = null;
|
||||
_state = ConnectionState.Disconnected;
|
||||
}
|
||||
|
||||
// --- Private helpers ---
|
||||
|
||||
private async Task<ISessionAdapter> ConnectToEndpointAsync(ConnectionSettings settings, string endpointUrl, CancellationToken ct)
|
||||
{
|
||||
// Create a settings copy with the current endpoint URL
|
||||
var effectiveSettings = new ConnectionSettings
|
||||
{
|
||||
EndpointUrl = endpointUrl,
|
||||
SecurityMode = settings.SecurityMode,
|
||||
SessionTimeoutSeconds = settings.SessionTimeoutSeconds,
|
||||
AutoAcceptCertificates = settings.AutoAcceptCertificates,
|
||||
CertificateStorePath = settings.CertificateStorePath,
|
||||
Username = settings.Username,
|
||||
Password = settings.Password
|
||||
};
|
||||
|
||||
var config = await _configFactory.CreateAsync(effectiveSettings, ct);
|
||||
var requestedMode = SecurityModeMapper.ToMessageSecurityMode(settings.SecurityMode);
|
||||
var endpoint = _endpointDiscovery.SelectEndpoint(config, endpointUrl, requestedMode);
|
||||
|
||||
UserIdentity identity = settings.Username != null
|
||||
? new UserIdentity(settings.Username, System.Text.Encoding.UTF8.GetBytes(settings.Password ?? ""))
|
||||
: new UserIdentity();
|
||||
|
||||
var sessionTimeoutMs = (uint)(settings.SessionTimeoutSeconds * 1000);
|
||||
return await _sessionFactory.CreateSessionAsync(config, endpoint, "LmxOpcUaClient", sessionTimeoutMs, identity, ct);
|
||||
}
|
||||
|
||||
private async Task HandleKeepAliveFailureAsync()
|
||||
{
|
||||
if (_state == ConnectionState.Reconnecting || _state == ConnectionState.Disconnected)
|
||||
return;
|
||||
|
||||
var oldEndpoint = _session?.EndpointUrl ?? string.Empty;
|
||||
TransitionState(ConnectionState.Reconnecting, oldEndpoint);
|
||||
Logger.Warning("Session lost on {EndpointUrl}. Attempting failover...", oldEndpoint);
|
||||
|
||||
// Close old session
|
||||
if (_session != null)
|
||||
{
|
||||
try { _session.Dispose(); } catch { }
|
||||
_session = null;
|
||||
}
|
||||
_dataSubscription = null;
|
||||
_alarmSubscription = null;
|
||||
|
||||
if (_settings == null || _allEndpointUrls == null)
|
||||
{
|
||||
TransitionState(ConnectionState.Disconnected, oldEndpoint);
|
||||
return;
|
||||
}
|
||||
|
||||
// Try each endpoint
|
||||
for (int attempt = 0; attempt < _allEndpointUrls.Length; attempt++)
|
||||
{
|
||||
_currentEndpointIndex = (_currentEndpointIndex + 1) % _allEndpointUrls.Length;
|
||||
var url = _allEndpointUrls[_currentEndpointIndex];
|
||||
|
||||
try
|
||||
{
|
||||
Logger.Information("Failover attempt to {EndpointUrl}", url);
|
||||
var session = await ConnectToEndpointAsync(_settings, url, CancellationToken.None);
|
||||
_session = session;
|
||||
|
||||
session.RegisterKeepAliveHandler(isGood =>
|
||||
{
|
||||
if (!isGood) { _ = HandleKeepAliveFailureAsync(); }
|
||||
});
|
||||
|
||||
CurrentConnectionInfo = BuildConnectionInfo(session);
|
||||
TransitionState(ConnectionState.Connected, url);
|
||||
Logger.Information("Failover succeeded to {EndpointUrl}", url);
|
||||
|
||||
// Replay subscriptions
|
||||
await ReplaySubscriptionsAsync();
|
||||
return;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Logger.Warning(ex, "Failover to {EndpointUrl} failed", url);
|
||||
}
|
||||
}
|
||||
|
||||
Logger.Error("All failover endpoints unreachable");
|
||||
TransitionState(ConnectionState.Disconnected, oldEndpoint);
|
||||
}
|
||||
|
||||
private async Task ReplaySubscriptionsAsync()
|
||||
{
|
||||
// Replay data subscriptions
|
||||
if (_activeDataSubscriptions.Count > 0)
|
||||
{
|
||||
var subscriptions = _activeDataSubscriptions.ToList();
|
||||
_activeDataSubscriptions.Clear();
|
||||
|
||||
foreach (var (nodeIdStr, (nodeId, intervalMs, _)) in subscriptions)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (_dataSubscription == null)
|
||||
_dataSubscription = await _session!.CreateSubscriptionAsync(intervalMs, CancellationToken.None);
|
||||
|
||||
var handle = await _dataSubscription.AddDataChangeMonitoredItemAsync(
|
||||
nodeId, intervalMs, OnDataChangeNotification, CancellationToken.None);
|
||||
_activeDataSubscriptions[nodeIdStr] = (nodeId, intervalMs, handle);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Logger.Warning(ex, "Failed to replay data subscription for {NodeId}", nodeIdStr);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Replay alarm subscription
|
||||
if (_activeAlarmSubscription.HasValue)
|
||||
{
|
||||
var (sourceNodeId, intervalMs) = _activeAlarmSubscription.Value;
|
||||
_activeAlarmSubscription = null;
|
||||
try
|
||||
{
|
||||
var monitorNode = sourceNodeId ?? ObjectIds.Server;
|
||||
_alarmSubscription = await _session!.CreateSubscriptionAsync(intervalMs, CancellationToken.None);
|
||||
var filter = CreateAlarmEventFilter();
|
||||
await _alarmSubscription.AddEventMonitoredItemAsync(
|
||||
monitorNode, intervalMs, filter, OnAlarmEventNotification, CancellationToken.None);
|
||||
_activeAlarmSubscription = (sourceNodeId, intervalMs);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Logger.Warning(ex, "Failed to replay alarm subscription");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void OnDataChangeNotification(string nodeId, DataValue value)
|
||||
{
|
||||
DataChanged?.Invoke(this, new DataChangedEventArgs(nodeId, value));
|
||||
}
|
||||
|
||||
private void OnAlarmEventNotification(EventFieldList eventFields)
|
||||
{
|
||||
var fields = eventFields.EventFields;
|
||||
if (fields == null || fields.Count < 6)
|
||||
return;
|
||||
|
||||
var sourceName = fields.Count > 2 ? fields[2].Value as string ?? string.Empty : string.Empty;
|
||||
var time = fields.Count > 3 ? fields[3].Value as DateTime? ?? DateTime.MinValue : DateTime.MinValue;
|
||||
var message = fields.Count > 4 ? (fields[4].Value as LocalizedText)?.Text ?? string.Empty : string.Empty;
|
||||
var severity = fields.Count > 5 ? Convert.ToUInt16(fields[5].Value) : (ushort)0;
|
||||
var conditionName = fields.Count > 6 ? fields[6].Value as string ?? string.Empty : string.Empty;
|
||||
var retain = fields.Count > 7 ? fields[7].Value as bool? ?? false : false;
|
||||
var ackedState = fields.Count > 8 ? fields[8].Value as bool? ?? false : false;
|
||||
var activeState = fields.Count > 9 ? fields[9].Value as bool? ?? false : false;
|
||||
|
||||
AlarmEvent?.Invoke(this, new AlarmEventArgs(
|
||||
sourceName, conditionName, severity, message, retain, activeState, ackedState, time));
|
||||
}
|
||||
|
||||
private static EventFilter CreateAlarmEventFilter()
|
||||
{
|
||||
var filter = new EventFilter();
|
||||
// 0: EventId
|
||||
filter.AddSelectClause(ObjectTypeIds.BaseEventType, BrowseNames.EventId);
|
||||
// 1: EventType
|
||||
filter.AddSelectClause(ObjectTypeIds.BaseEventType, BrowseNames.EventType);
|
||||
// 2: SourceName
|
||||
filter.AddSelectClause(ObjectTypeIds.BaseEventType, BrowseNames.SourceName);
|
||||
// 3: Time
|
||||
filter.AddSelectClause(ObjectTypeIds.BaseEventType, BrowseNames.Time);
|
||||
// 4: Message
|
||||
filter.AddSelectClause(ObjectTypeIds.BaseEventType, BrowseNames.Message);
|
||||
// 5: Severity
|
||||
filter.AddSelectClause(ObjectTypeIds.BaseEventType, BrowseNames.Severity);
|
||||
// 6: ConditionName
|
||||
filter.AddSelectClause(ObjectTypeIds.ConditionType, BrowseNames.ConditionName);
|
||||
// 7: Retain
|
||||
filter.AddSelectClause(ObjectTypeIds.ConditionType, BrowseNames.Retain);
|
||||
// 8: AckedState/Id
|
||||
filter.AddSelectClause(ObjectTypeIds.AcknowledgeableConditionType, "AckedState/Id");
|
||||
// 9: ActiveState/Id
|
||||
filter.AddSelectClause(ObjectTypeIds.AlarmConditionType, "ActiveState/Id");
|
||||
// 10: EnabledState/Id
|
||||
filter.AddSelectClause(ObjectTypeIds.AlarmConditionType, "EnabledState/Id");
|
||||
// 11: SuppressedOrShelved
|
||||
filter.AddSelectClause(ObjectTypeIds.AlarmConditionType, "SuppressedOrShelved");
|
||||
return filter;
|
||||
}
|
||||
|
||||
private static ConnectionInfo BuildConnectionInfo(ISessionAdapter session)
|
||||
{
|
||||
return new ConnectionInfo(
|
||||
session.EndpointUrl,
|
||||
session.ServerName,
|
||||
session.SecurityMode,
|
||||
session.SecurityPolicyUri,
|
||||
session.SessionId,
|
||||
session.SessionName);
|
||||
}
|
||||
|
||||
private void TransitionState(ConnectionState newState, string endpointUrl)
|
||||
{
|
||||
var oldState = _state;
|
||||
if (oldState == newState) return;
|
||||
_state = newState;
|
||||
ConnectionStateChanged?.Invoke(this, new ConnectionStateChangedEventArgs(oldState, newState, endpointUrl));
|
||||
}
|
||||
|
||||
private void ThrowIfDisposed()
|
||||
{
|
||||
if (_disposed) throw new ObjectDisposedException(nameof(OpcUaClientService));
|
||||
}
|
||||
|
||||
private void ThrowIfNotConnected()
|
||||
{
|
||||
if (_state != ConnectionState.Connected || _session == null)
|
||||
throw new InvalidOperationException("Not connected to an OPC UA server.");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
namespace ZB.MOM.WW.LmxOpcUa.Client.Shared;
|
||||
|
||||
/// <summary>
|
||||
/// Default factory that creates <see cref="OpcUaClientService"/> instances with production adapters.
|
||||
/// </summary>
|
||||
public sealed class OpcUaClientServiceFactory : IOpcUaClientServiceFactory
|
||||
{
|
||||
public IOpcUaClientService Create()
|
||||
{
|
||||
return new OpcUaClientService();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<RootNamespace>ZB.MOM.WW.LmxOpcUa.Client.Shared</RootNamespace>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="OPCFoundation.NetStandard.Opc.Ua.Client" Version="1.5.378.106" />
|
||||
<PackageReference Include="Serilog" Version="4.2.0" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<InternalsVisibleTo Include="ZB.MOM.WW.LmxOpcUa.Client.Shared.Tests" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
9
src/ZB.MOM.WW.LmxOpcUa.Client.UI/App.axaml
Normal file
9
src/ZB.MOM.WW.LmxOpcUa.Client.UI/App.axaml
Normal file
@@ -0,0 +1,9 @@
|
||||
<Application xmlns="https://github.com/avaloniaui"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
x:Class="ZB.MOM.WW.LmxOpcUa.Client.UI.App"
|
||||
RequestedThemeVariant="Light">
|
||||
<Application.Styles>
|
||||
<FluentTheme />
|
||||
<StyleInclude Source="avares://Avalonia.Controls.DataGrid/Themes/Fluent.xaml" />
|
||||
</Application.Styles>
|
||||
</Application>
|
||||
33
src/ZB.MOM.WW.LmxOpcUa.Client.UI/App.axaml.cs
Normal file
33
src/ZB.MOM.WW.LmxOpcUa.Client.UI/App.axaml.cs
Normal file
@@ -0,0 +1,33 @@
|
||||
using Avalonia;
|
||||
using Avalonia.Controls.ApplicationLifetimes;
|
||||
using Avalonia.Markup.Xaml;
|
||||
using ZB.MOM.WW.LmxOpcUa.Client.Shared;
|
||||
using ZB.MOM.WW.LmxOpcUa.Client.UI.Services;
|
||||
using ZB.MOM.WW.LmxOpcUa.Client.UI.ViewModels;
|
||||
using ZB.MOM.WW.LmxOpcUa.Client.UI.Views;
|
||||
|
||||
namespace ZB.MOM.WW.LmxOpcUa.Client.UI;
|
||||
|
||||
public partial class App : Application
|
||||
{
|
||||
public override void Initialize()
|
||||
{
|
||||
AvaloniaXamlLoader.Load(this);
|
||||
}
|
||||
|
||||
public override void OnFrameworkInitializationCompleted()
|
||||
{
|
||||
if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
|
||||
{
|
||||
var factory = new OpcUaClientServiceFactory();
|
||||
var dispatcher = new AvaloniaUiDispatcher();
|
||||
var viewModel = new MainWindowViewModel(factory, dispatcher);
|
||||
desktop.MainWindow = new MainWindow
|
||||
{
|
||||
DataContext = viewModel
|
||||
};
|
||||
}
|
||||
|
||||
base.OnFrameworkInitializationCompleted();
|
||||
}
|
||||
}
|
||||
16
src/ZB.MOM.WW.LmxOpcUa.Client.UI/Program.cs
Normal file
16
src/ZB.MOM.WW.LmxOpcUa.Client.UI/Program.cs
Normal file
@@ -0,0 +1,16 @@
|
||||
using Avalonia;
|
||||
|
||||
namespace ZB.MOM.WW.LmxOpcUa.Client.UI;
|
||||
|
||||
class Program
|
||||
{
|
||||
[STAThread]
|
||||
public static void Main(string[] args) => BuildAvaloniaApp()
|
||||
.StartWithClassicDesktopLifetime(args);
|
||||
|
||||
public static AppBuilder BuildAvaloniaApp()
|
||||
=> AppBuilder.Configure<App>()
|
||||
.UsePlatformDetect()
|
||||
.WithInterFont()
|
||||
.LogToTrace();
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
using Avalonia.Threading;
|
||||
|
||||
namespace ZB.MOM.WW.LmxOpcUa.Client.UI.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Dispatches actions to the Avalonia UI thread.
|
||||
/// </summary>
|
||||
public sealed class AvaloniaUiDispatcher : IUiDispatcher
|
||||
{
|
||||
public void Post(Action action)
|
||||
{
|
||||
Dispatcher.UIThread.Post(action);
|
||||
}
|
||||
}
|
||||
12
src/ZB.MOM.WW.LmxOpcUa.Client.UI/Services/IUiDispatcher.cs
Normal file
12
src/ZB.MOM.WW.LmxOpcUa.Client.UI/Services/IUiDispatcher.cs
Normal file
@@ -0,0 +1,12 @@
|
||||
namespace ZB.MOM.WW.LmxOpcUa.Client.UI.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Abstraction for dispatching actions to the UI thread.
|
||||
/// </summary>
|
||||
public interface IUiDispatcher
|
||||
{
|
||||
/// <summary>
|
||||
/// Posts an action to be executed on the UI thread.
|
||||
/// </summary>
|
||||
void Post(Action action);
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
namespace ZB.MOM.WW.LmxOpcUa.Client.UI.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Dispatcher that executes actions synchronously on the calling thread.
|
||||
/// Used for unit testing where no UI thread is available.
|
||||
/// </summary>
|
||||
public sealed class SynchronousUiDispatcher : IUiDispatcher
|
||||
{
|
||||
public void Post(Action action)
|
||||
{
|
||||
action();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
|
||||
namespace ZB.MOM.WW.LmxOpcUa.Client.UI.ViewModels;
|
||||
|
||||
/// <summary>
|
||||
/// Represents a single alarm event row.
|
||||
/// </summary>
|
||||
public partial class AlarmEventViewModel : ObservableObject
|
||||
{
|
||||
public string SourceName { get; }
|
||||
public string ConditionName { get; }
|
||||
public ushort Severity { get; }
|
||||
public string Message { get; }
|
||||
public bool Retain { get; }
|
||||
public bool ActiveState { get; }
|
||||
public bool AckedState { get; }
|
||||
public DateTime Time { get; }
|
||||
|
||||
public AlarmEventViewModel(
|
||||
string sourceName,
|
||||
string conditionName,
|
||||
ushort severity,
|
||||
string message,
|
||||
bool retain,
|
||||
bool activeState,
|
||||
bool ackedState,
|
||||
DateTime time)
|
||||
{
|
||||
SourceName = sourceName;
|
||||
ConditionName = conditionName;
|
||||
Severity = severity;
|
||||
Message = message;
|
||||
Retain = retain;
|
||||
ActiveState = activeState;
|
||||
AckedState = ackedState;
|
||||
Time = time;
|
||||
}
|
||||
}
|
||||
128
src/ZB.MOM.WW.LmxOpcUa.Client.UI/ViewModels/AlarmsViewModel.cs
Normal file
128
src/ZB.MOM.WW.LmxOpcUa.Client.UI/ViewModels/AlarmsViewModel.cs
Normal file
@@ -0,0 +1,128 @@
|
||||
using System.Collections.ObjectModel;
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using CommunityToolkit.Mvvm.Input;
|
||||
using Opc.Ua;
|
||||
using ZB.MOM.WW.LmxOpcUa.Client.Shared;
|
||||
using ZB.MOM.WW.LmxOpcUa.Client.Shared.Models;
|
||||
using ZB.MOM.WW.LmxOpcUa.Client.UI.Services;
|
||||
|
||||
namespace ZB.MOM.WW.LmxOpcUa.Client.UI.ViewModels;
|
||||
|
||||
/// <summary>
|
||||
/// ViewModel for the alarms panel.
|
||||
/// </summary>
|
||||
public partial class AlarmsViewModel : ObservableObject
|
||||
{
|
||||
private readonly IOpcUaClientService _service;
|
||||
private readonly IUiDispatcher _dispatcher;
|
||||
|
||||
/// <summary>Received alarm events.</summary>
|
||||
public ObservableCollection<AlarmEventViewModel> AlarmEvents { get; } = new();
|
||||
|
||||
[ObservableProperty]
|
||||
private string? _monitoredNodeIdText;
|
||||
|
||||
[ObservableProperty]
|
||||
private int _interval = 1000;
|
||||
|
||||
[ObservableProperty]
|
||||
[NotifyCanExecuteChangedFor(nameof(SubscribeCommand))]
|
||||
[NotifyCanExecuteChangedFor(nameof(UnsubscribeCommand))]
|
||||
[NotifyCanExecuteChangedFor(nameof(RefreshCommand))]
|
||||
private bool _isSubscribed;
|
||||
|
||||
[ObservableProperty]
|
||||
[NotifyCanExecuteChangedFor(nameof(SubscribeCommand))]
|
||||
[NotifyCanExecuteChangedFor(nameof(UnsubscribeCommand))]
|
||||
[NotifyCanExecuteChangedFor(nameof(RefreshCommand))]
|
||||
private bool _isConnected;
|
||||
|
||||
public AlarmsViewModel(IOpcUaClientService service, IUiDispatcher dispatcher)
|
||||
{
|
||||
_service = service;
|
||||
_dispatcher = dispatcher;
|
||||
_service.AlarmEvent += OnAlarmEvent;
|
||||
}
|
||||
|
||||
private void OnAlarmEvent(object? sender, AlarmEventArgs e)
|
||||
{
|
||||
_dispatcher.Post(() =>
|
||||
{
|
||||
AlarmEvents.Add(new AlarmEventViewModel(
|
||||
e.SourceName,
|
||||
e.ConditionName,
|
||||
e.Severity,
|
||||
e.Message,
|
||||
e.Retain,
|
||||
e.ActiveState,
|
||||
e.AckedState,
|
||||
e.Time));
|
||||
});
|
||||
}
|
||||
|
||||
private bool CanSubscribe() => IsConnected && !IsSubscribed;
|
||||
|
||||
[RelayCommand(CanExecute = nameof(CanSubscribe))]
|
||||
private async Task SubscribeAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
NodeId? sourceNodeId = string.IsNullOrWhiteSpace(MonitoredNodeIdText)
|
||||
? null
|
||||
: NodeId.Parse(MonitoredNodeIdText);
|
||||
|
||||
await _service.SubscribeAlarmsAsync(sourceNodeId, Interval);
|
||||
IsSubscribed = true;
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Subscribe failed
|
||||
}
|
||||
}
|
||||
|
||||
private bool CanUnsubscribe() => IsConnected && IsSubscribed;
|
||||
|
||||
[RelayCommand(CanExecute = nameof(CanUnsubscribe))]
|
||||
private async Task UnsubscribeAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
await _service.UnsubscribeAlarmsAsync();
|
||||
IsSubscribed = false;
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Unsubscribe failed
|
||||
}
|
||||
}
|
||||
|
||||
[RelayCommand(CanExecute = nameof(CanUnsubscribe))]
|
||||
private async Task RefreshAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
await _service.RequestConditionRefreshAsync();
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Refresh failed
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Clears alarm events and resets state.
|
||||
/// </summary>
|
||||
public void Clear()
|
||||
{
|
||||
AlarmEvents.Clear();
|
||||
IsSubscribed = false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Unhooks event handlers from the service.
|
||||
/// </summary>
|
||||
public void Teardown()
|
||||
{
|
||||
_service.AlarmEvent -= OnAlarmEvent;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
using System.Collections.ObjectModel;
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using ZB.MOM.WW.LmxOpcUa.Client.Shared;
|
||||
using ZB.MOM.WW.LmxOpcUa.Client.UI.Services;
|
||||
|
||||
namespace ZB.MOM.WW.LmxOpcUa.Client.UI.ViewModels;
|
||||
|
||||
/// <summary>
|
||||
/// ViewModel for the OPC UA browse tree panel.
|
||||
/// </summary>
|
||||
public partial class BrowseTreeViewModel : ObservableObject
|
||||
{
|
||||
private readonly IOpcUaClientService _service;
|
||||
private readonly IUiDispatcher _dispatcher;
|
||||
|
||||
/// <summary>Top-level nodes in the browse tree.</summary>
|
||||
public ObservableCollection<TreeNodeViewModel> RootNodes { get; } = new();
|
||||
|
||||
public BrowseTreeViewModel(IOpcUaClientService service, IUiDispatcher dispatcher)
|
||||
{
|
||||
_service = service;
|
||||
_dispatcher = dispatcher;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Loads root nodes by browsing with a null parent.
|
||||
/// </summary>
|
||||
public async Task LoadRootsAsync()
|
||||
{
|
||||
var results = await _service.BrowseAsync(null);
|
||||
|
||||
_dispatcher.Post(() =>
|
||||
{
|
||||
RootNodes.Clear();
|
||||
foreach (var result in results)
|
||||
{
|
||||
RootNodes.Add(new TreeNodeViewModel(
|
||||
result.NodeId,
|
||||
result.DisplayName,
|
||||
result.NodeClass,
|
||||
result.HasChildren,
|
||||
_service,
|
||||
_dispatcher));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Clears all root nodes from the tree.
|
||||
/// </summary>
|
||||
public void Clear()
|
||||
{
|
||||
RootNodes.Clear();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
|
||||
namespace ZB.MOM.WW.LmxOpcUa.Client.UI.ViewModels;
|
||||
|
||||
/// <summary>
|
||||
/// Represents a single historical value row.
|
||||
/// </summary>
|
||||
public partial class HistoryValueViewModel : ObservableObject
|
||||
{
|
||||
public string Value { get; }
|
||||
public string Status { get; }
|
||||
public string SourceTimestamp { get; }
|
||||
public string ServerTimestamp { get; }
|
||||
|
||||
public HistoryValueViewModel(string value, string status, string sourceTimestamp, string serverTimestamp)
|
||||
{
|
||||
Value = value;
|
||||
Status = status;
|
||||
SourceTimestamp = sourceTimestamp;
|
||||
ServerTimestamp = serverTimestamp;
|
||||
}
|
||||
}
|
||||
140
src/ZB.MOM.WW.LmxOpcUa.Client.UI/ViewModels/HistoryViewModel.cs
Normal file
140
src/ZB.MOM.WW.LmxOpcUa.Client.UI/ViewModels/HistoryViewModel.cs
Normal file
@@ -0,0 +1,140 @@
|
||||
using System.Collections.ObjectModel;
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using CommunityToolkit.Mvvm.Input;
|
||||
using Opc.Ua;
|
||||
using ZB.MOM.WW.LmxOpcUa.Client.Shared;
|
||||
using ZB.MOM.WW.LmxOpcUa.Client.Shared.Models;
|
||||
using ZB.MOM.WW.LmxOpcUa.Client.UI.Services;
|
||||
|
||||
namespace ZB.MOM.WW.LmxOpcUa.Client.UI.ViewModels;
|
||||
|
||||
/// <summary>
|
||||
/// ViewModel for the history panel.
|
||||
/// </summary>
|
||||
public partial class HistoryViewModel : ObservableObject
|
||||
{
|
||||
private readonly IOpcUaClientService _service;
|
||||
private readonly IUiDispatcher _dispatcher;
|
||||
|
||||
[ObservableProperty]
|
||||
[NotifyCanExecuteChangedFor(nameof(ReadHistoryCommand))]
|
||||
private string? _selectedNodeId;
|
||||
|
||||
[ObservableProperty]
|
||||
private DateTimeOffset _startTime = DateTimeOffset.UtcNow.AddHours(-1);
|
||||
|
||||
[ObservableProperty]
|
||||
private DateTimeOffset _endTime = DateTimeOffset.UtcNow;
|
||||
|
||||
[ObservableProperty]
|
||||
private int _maxValues = 1000;
|
||||
|
||||
[ObservableProperty]
|
||||
private AggregateType? _selectedAggregateType;
|
||||
|
||||
/// <summary>Available aggregate types (null means "Raw").</summary>
|
||||
public IReadOnlyList<AggregateType?> AggregateTypes { get; } = new AggregateType?[]
|
||||
{
|
||||
null,
|
||||
AggregateType.Average,
|
||||
AggregateType.Minimum,
|
||||
AggregateType.Maximum,
|
||||
AggregateType.Count,
|
||||
AggregateType.Start,
|
||||
AggregateType.End
|
||||
};
|
||||
|
||||
[ObservableProperty]
|
||||
private double _intervalMs = 3600000;
|
||||
|
||||
public bool IsAggregateRead => SelectedAggregateType != null;
|
||||
|
||||
[ObservableProperty]
|
||||
private bool _isLoading;
|
||||
|
||||
[ObservableProperty]
|
||||
[NotifyCanExecuteChangedFor(nameof(ReadHistoryCommand))]
|
||||
private bool _isConnected;
|
||||
|
||||
/// <summary>History read results.</summary>
|
||||
public ObservableCollection<HistoryValueViewModel> Results { get; } = new();
|
||||
|
||||
public HistoryViewModel(IOpcUaClientService service, IUiDispatcher dispatcher)
|
||||
{
|
||||
_service = service;
|
||||
_dispatcher = dispatcher;
|
||||
}
|
||||
|
||||
partial void OnSelectedAggregateTypeChanged(AggregateType? value)
|
||||
{
|
||||
OnPropertyChanged(nameof(IsAggregateRead));
|
||||
}
|
||||
|
||||
private bool CanReadHistory() => IsConnected && !string.IsNullOrEmpty(SelectedNodeId);
|
||||
|
||||
[RelayCommand(CanExecute = nameof(CanReadHistory))]
|
||||
private async Task ReadHistoryAsync()
|
||||
{
|
||||
if (string.IsNullOrEmpty(SelectedNodeId)) return;
|
||||
|
||||
IsLoading = true;
|
||||
_dispatcher.Post(() => Results.Clear());
|
||||
|
||||
try
|
||||
{
|
||||
var nodeId = NodeId.Parse(SelectedNodeId);
|
||||
IReadOnlyList<DataValue> values;
|
||||
|
||||
if (SelectedAggregateType != null)
|
||||
{
|
||||
values = await _service.HistoryReadAggregateAsync(
|
||||
nodeId,
|
||||
StartTime.UtcDateTime,
|
||||
EndTime.UtcDateTime,
|
||||
SelectedAggregateType.Value,
|
||||
IntervalMs);
|
||||
}
|
||||
else
|
||||
{
|
||||
values = await _service.HistoryReadRawAsync(
|
||||
nodeId,
|
||||
StartTime.UtcDateTime,
|
||||
EndTime.UtcDateTime,
|
||||
MaxValues);
|
||||
}
|
||||
|
||||
_dispatcher.Post(() =>
|
||||
{
|
||||
foreach (var dv in values)
|
||||
{
|
||||
Results.Add(new HistoryValueViewModel(
|
||||
dv.Value?.ToString() ?? "(null)",
|
||||
dv.StatusCode.ToString(),
|
||||
dv.SourceTimestamp.ToString("O"),
|
||||
dv.ServerTimestamp.ToString("O")));
|
||||
}
|
||||
});
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_dispatcher.Post(() =>
|
||||
{
|
||||
Results.Add(new HistoryValueViewModel(
|
||||
$"Error: {ex.Message}", string.Empty, string.Empty, string.Empty));
|
||||
});
|
||||
}
|
||||
finally
|
||||
{
|
||||
_dispatcher.Post(() => IsLoading = false);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Clears results and resets state.
|
||||
/// </summary>
|
||||
public void Clear()
|
||||
{
|
||||
Results.Clear();
|
||||
SelectedNodeId = null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,198 @@
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using CommunityToolkit.Mvvm.Input;
|
||||
using ZB.MOM.WW.LmxOpcUa.Client.Shared;
|
||||
using ZB.MOM.WW.LmxOpcUa.Client.Shared.Models;
|
||||
using ZB.MOM.WW.LmxOpcUa.Client.UI.Services;
|
||||
|
||||
namespace ZB.MOM.WW.LmxOpcUa.Client.UI.ViewModels;
|
||||
|
||||
/// <summary>
|
||||
/// Main window ViewModel coordinating all panels.
|
||||
/// </summary>
|
||||
public partial class MainWindowViewModel : ObservableObject
|
||||
{
|
||||
private readonly IOpcUaClientService _service;
|
||||
private readonly IUiDispatcher _dispatcher;
|
||||
|
||||
[ObservableProperty]
|
||||
private string _endpointUrl = "opc.tcp://localhost:4840";
|
||||
|
||||
[ObservableProperty]
|
||||
private string? _username;
|
||||
|
||||
[ObservableProperty]
|
||||
private string? _password;
|
||||
|
||||
[ObservableProperty]
|
||||
private SecurityMode _selectedSecurityMode = SecurityMode.None;
|
||||
|
||||
/// <summary>All available security modes.</summary>
|
||||
public IReadOnlyList<SecurityMode> SecurityModes { get; } = Enum.GetValues<SecurityMode>();
|
||||
|
||||
[ObservableProperty]
|
||||
[NotifyCanExecuteChangedFor(nameof(ConnectCommand))]
|
||||
[NotifyCanExecuteChangedFor(nameof(DisconnectCommand))]
|
||||
private ConnectionState _connectionState = ConnectionState.Disconnected;
|
||||
|
||||
public bool IsConnected => ConnectionState == ConnectionState.Connected;
|
||||
|
||||
[ObservableProperty]
|
||||
private TreeNodeViewModel? _selectedTreeNode;
|
||||
|
||||
[ObservableProperty]
|
||||
private RedundancyInfo? _redundancyInfo;
|
||||
|
||||
[ObservableProperty]
|
||||
private string _statusMessage = "Disconnected";
|
||||
|
||||
[ObservableProperty]
|
||||
private string _sessionLabel = string.Empty;
|
||||
|
||||
[ObservableProperty]
|
||||
private int _subscriptionCount;
|
||||
|
||||
public BrowseTreeViewModel BrowseTree { get; }
|
||||
public ReadWriteViewModel ReadWrite { get; }
|
||||
public SubscriptionsViewModel Subscriptions { get; }
|
||||
public AlarmsViewModel Alarms { get; }
|
||||
public HistoryViewModel History { get; }
|
||||
|
||||
public MainWindowViewModel(IOpcUaClientServiceFactory factory, IUiDispatcher dispatcher)
|
||||
{
|
||||
_service = factory.Create();
|
||||
_dispatcher = dispatcher;
|
||||
|
||||
BrowseTree = new BrowseTreeViewModel(_service, dispatcher);
|
||||
ReadWrite = new ReadWriteViewModel(_service, dispatcher);
|
||||
Subscriptions = new SubscriptionsViewModel(_service, dispatcher);
|
||||
Alarms = new AlarmsViewModel(_service, dispatcher);
|
||||
History = new HistoryViewModel(_service, dispatcher);
|
||||
|
||||
_service.ConnectionStateChanged += OnConnectionStateChanged;
|
||||
}
|
||||
|
||||
private void OnConnectionStateChanged(object? sender, ConnectionStateChangedEventArgs e)
|
||||
{
|
||||
_dispatcher.Post(() =>
|
||||
{
|
||||
ConnectionState = e.NewState;
|
||||
});
|
||||
}
|
||||
|
||||
partial void OnConnectionStateChanged(ConnectionState value)
|
||||
{
|
||||
OnPropertyChanged(nameof(IsConnected));
|
||||
|
||||
var connected = value == ConnectionState.Connected;
|
||||
ReadWrite.IsConnected = connected;
|
||||
Subscriptions.IsConnected = connected;
|
||||
Alarms.IsConnected = connected;
|
||||
History.IsConnected = connected;
|
||||
|
||||
switch (value)
|
||||
{
|
||||
case ConnectionState.Connected:
|
||||
StatusMessage = $"Connected to {EndpointUrl}";
|
||||
break;
|
||||
case ConnectionState.Reconnecting:
|
||||
StatusMessage = "Reconnecting...";
|
||||
break;
|
||||
case ConnectionState.Connecting:
|
||||
StatusMessage = "Connecting...";
|
||||
break;
|
||||
case ConnectionState.Disconnected:
|
||||
StatusMessage = "Disconnected";
|
||||
SessionLabel = string.Empty;
|
||||
RedundancyInfo = null;
|
||||
BrowseTree.Clear();
|
||||
ReadWrite.Clear();
|
||||
Subscriptions.Clear();
|
||||
Alarms.Clear();
|
||||
History.Clear();
|
||||
SubscriptionCount = 0;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
partial void OnSelectedTreeNodeChanged(TreeNodeViewModel? value)
|
||||
{
|
||||
ReadWrite.SelectedNodeId = value?.NodeId;
|
||||
History.SelectedNodeId = value?.NodeId;
|
||||
}
|
||||
|
||||
private bool CanConnect() => ConnectionState == ConnectionState.Disconnected;
|
||||
|
||||
[RelayCommand(CanExecute = nameof(CanConnect))]
|
||||
private async Task ConnectAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
ConnectionState = ConnectionState.Connecting;
|
||||
StatusMessage = "Connecting...";
|
||||
|
||||
var settings = new ConnectionSettings
|
||||
{
|
||||
EndpointUrl = EndpointUrl,
|
||||
Username = Username,
|
||||
Password = Password,
|
||||
SecurityMode = SelectedSecurityMode
|
||||
};
|
||||
settings.Validate();
|
||||
|
||||
var info = await _service.ConnectAsync(settings);
|
||||
|
||||
_dispatcher.Post(() =>
|
||||
{
|
||||
ConnectionState = ConnectionState.Connected;
|
||||
SessionLabel = $"{info.ServerName} | Session: {info.SessionName} ({info.SessionId})";
|
||||
});
|
||||
|
||||
// Load redundancy info
|
||||
try
|
||||
{
|
||||
var redundancy = await _service.GetRedundancyInfoAsync();
|
||||
_dispatcher.Post(() => RedundancyInfo = redundancy);
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Redundancy info not available
|
||||
}
|
||||
|
||||
// Load root nodes
|
||||
await BrowseTree.LoadRootsAsync();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_dispatcher.Post(() =>
|
||||
{
|
||||
ConnectionState = ConnectionState.Disconnected;
|
||||
StatusMessage = $"Connection failed: {ex.Message}";
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private bool CanDisconnect() => ConnectionState == ConnectionState.Connected
|
||||
|| ConnectionState == ConnectionState.Reconnecting;
|
||||
|
||||
[RelayCommand(CanExecute = nameof(CanDisconnect))]
|
||||
private async Task DisconnectAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
Subscriptions.Teardown();
|
||||
Alarms.Teardown();
|
||||
await _service.DisconnectAsync();
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Best-effort disconnect
|
||||
}
|
||||
finally
|
||||
{
|
||||
_dispatcher.Post(() =>
|
||||
{
|
||||
ConnectionState = ConnectionState.Disconnected;
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using CommunityToolkit.Mvvm.Input;
|
||||
using Opc.Ua;
|
||||
using ZB.MOM.WW.LmxOpcUa.Client.Shared;
|
||||
using ZB.MOM.WW.LmxOpcUa.Client.UI.Services;
|
||||
|
||||
namespace ZB.MOM.WW.LmxOpcUa.Client.UI.ViewModels;
|
||||
|
||||
/// <summary>
|
||||
/// ViewModel for the read/write panel.
|
||||
/// </summary>
|
||||
public partial class ReadWriteViewModel : ObservableObject
|
||||
{
|
||||
private readonly IOpcUaClientService _service;
|
||||
private readonly IUiDispatcher _dispatcher;
|
||||
|
||||
[ObservableProperty]
|
||||
[NotifyCanExecuteChangedFor(nameof(ReadCommand))]
|
||||
[NotifyCanExecuteChangedFor(nameof(WriteCommand))]
|
||||
private string? _selectedNodeId;
|
||||
|
||||
[ObservableProperty]
|
||||
private string? _currentValue;
|
||||
|
||||
[ObservableProperty]
|
||||
private string? _currentStatus;
|
||||
|
||||
[ObservableProperty]
|
||||
private string? _sourceTimestamp;
|
||||
|
||||
[ObservableProperty]
|
||||
private string? _serverTimestamp;
|
||||
|
||||
[ObservableProperty]
|
||||
private string? _writeValue;
|
||||
|
||||
[ObservableProperty]
|
||||
private string? _writeStatus;
|
||||
|
||||
[ObservableProperty]
|
||||
[NotifyCanExecuteChangedFor(nameof(ReadCommand))]
|
||||
[NotifyCanExecuteChangedFor(nameof(WriteCommand))]
|
||||
private bool _isConnected;
|
||||
|
||||
public bool IsNodeSelected => !string.IsNullOrEmpty(SelectedNodeId);
|
||||
|
||||
public ReadWriteViewModel(IOpcUaClientService service, IUiDispatcher dispatcher)
|
||||
{
|
||||
_service = service;
|
||||
_dispatcher = dispatcher;
|
||||
}
|
||||
|
||||
partial void OnSelectedNodeIdChanged(string? value)
|
||||
{
|
||||
OnPropertyChanged(nameof(IsNodeSelected));
|
||||
if (!string.IsNullOrEmpty(value) && IsConnected)
|
||||
{
|
||||
_ = ExecuteReadAsync();
|
||||
}
|
||||
}
|
||||
|
||||
private bool CanReadOrWrite() => IsConnected && !string.IsNullOrEmpty(SelectedNodeId);
|
||||
|
||||
[RelayCommand(CanExecute = nameof(CanReadOrWrite))]
|
||||
private async Task ReadAsync()
|
||||
{
|
||||
await ExecuteReadAsync();
|
||||
}
|
||||
|
||||
private async Task ExecuteReadAsync()
|
||||
{
|
||||
if (string.IsNullOrEmpty(SelectedNodeId)) return;
|
||||
|
||||
try
|
||||
{
|
||||
var nodeId = NodeId.Parse(SelectedNodeId);
|
||||
var dataValue = await _service.ReadValueAsync(nodeId);
|
||||
|
||||
_dispatcher.Post(() =>
|
||||
{
|
||||
CurrentValue = dataValue.Value?.ToString() ?? "(null)";
|
||||
CurrentStatus = dataValue.StatusCode.ToString();
|
||||
SourceTimestamp = dataValue.SourceTimestamp.ToString("O");
|
||||
ServerTimestamp = dataValue.ServerTimestamp.ToString("O");
|
||||
});
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_dispatcher.Post(() =>
|
||||
{
|
||||
CurrentValue = null;
|
||||
CurrentStatus = $"Error: {ex.Message}";
|
||||
SourceTimestamp = null;
|
||||
ServerTimestamp = null;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
[RelayCommand(CanExecute = nameof(CanReadOrWrite))]
|
||||
private async Task WriteAsync()
|
||||
{
|
||||
if (string.IsNullOrEmpty(SelectedNodeId) || WriteValue == null) return;
|
||||
|
||||
try
|
||||
{
|
||||
var nodeId = NodeId.Parse(SelectedNodeId);
|
||||
var statusCode = await _service.WriteValueAsync(nodeId, WriteValue);
|
||||
|
||||
_dispatcher.Post(() =>
|
||||
{
|
||||
WriteStatus = statusCode.ToString();
|
||||
});
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_dispatcher.Post(() =>
|
||||
{
|
||||
WriteStatus = $"Error: {ex.Message}";
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Clears all displayed values.
|
||||
/// </summary>
|
||||
public void Clear()
|
||||
{
|
||||
SelectedNodeId = null;
|
||||
CurrentValue = null;
|
||||
CurrentStatus = null;
|
||||
SourceTimestamp = null;
|
||||
ServerTimestamp = null;
|
||||
WriteValue = null;
|
||||
WriteStatus = null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
|
||||
namespace ZB.MOM.WW.LmxOpcUa.Client.UI.ViewModels;
|
||||
|
||||
/// <summary>
|
||||
/// Represents a single active subscription row.
|
||||
/// </summary>
|
||||
public partial class SubscriptionItemViewModel : ObservableObject
|
||||
{
|
||||
/// <summary>The monitored NodeId.</summary>
|
||||
public string NodeId { get; }
|
||||
|
||||
/// <summary>The subscription interval in milliseconds.</summary>
|
||||
public int IntervalMs { get; }
|
||||
|
||||
[ObservableProperty]
|
||||
private string? _value;
|
||||
|
||||
[ObservableProperty]
|
||||
private string? _status;
|
||||
|
||||
[ObservableProperty]
|
||||
private string? _timestamp;
|
||||
|
||||
public SubscriptionItemViewModel(string nodeId, int intervalMs)
|
||||
{
|
||||
NodeId = nodeId;
|
||||
IntervalMs = intervalMs;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
using System.Collections.ObjectModel;
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using CommunityToolkit.Mvvm.Input;
|
||||
using Opc.Ua;
|
||||
using ZB.MOM.WW.LmxOpcUa.Client.Shared;
|
||||
using ZB.MOM.WW.LmxOpcUa.Client.Shared.Models;
|
||||
using ZB.MOM.WW.LmxOpcUa.Client.UI.Services;
|
||||
|
||||
namespace ZB.MOM.WW.LmxOpcUa.Client.UI.ViewModels;
|
||||
|
||||
/// <summary>
|
||||
/// ViewModel for the subscriptions panel.
|
||||
/// </summary>
|
||||
public partial class SubscriptionsViewModel : ObservableObject
|
||||
{
|
||||
private readonly IOpcUaClientService _service;
|
||||
private readonly IUiDispatcher _dispatcher;
|
||||
|
||||
/// <summary>Currently active subscriptions.</summary>
|
||||
public ObservableCollection<SubscriptionItemViewModel> ActiveSubscriptions { get; } = new();
|
||||
|
||||
[ObservableProperty]
|
||||
[NotifyCanExecuteChangedFor(nameof(AddSubscriptionCommand))]
|
||||
private string? _newNodeIdText;
|
||||
|
||||
[ObservableProperty]
|
||||
private int _newInterval = 1000;
|
||||
|
||||
[ObservableProperty]
|
||||
[NotifyCanExecuteChangedFor(nameof(AddSubscriptionCommand))]
|
||||
[NotifyCanExecuteChangedFor(nameof(RemoveSubscriptionCommand))]
|
||||
private bool _isConnected;
|
||||
|
||||
[ObservableProperty]
|
||||
private int _subscriptionCount;
|
||||
|
||||
[ObservableProperty]
|
||||
[NotifyCanExecuteChangedFor(nameof(RemoveSubscriptionCommand))]
|
||||
private SubscriptionItemViewModel? _selectedSubscription;
|
||||
|
||||
public SubscriptionsViewModel(IOpcUaClientService service, IUiDispatcher dispatcher)
|
||||
{
|
||||
_service = service;
|
||||
_dispatcher = dispatcher;
|
||||
_service.DataChanged += OnDataChanged;
|
||||
}
|
||||
|
||||
private void OnDataChanged(object? sender, DataChangedEventArgs e)
|
||||
{
|
||||
_dispatcher.Post(() =>
|
||||
{
|
||||
foreach (var item in ActiveSubscriptions)
|
||||
{
|
||||
if (item.NodeId == e.NodeId)
|
||||
{
|
||||
item.Value = e.Value.Value?.ToString() ?? "(null)";
|
||||
item.Status = e.Value.StatusCode.ToString();
|
||||
item.Timestamp = e.Value.SourceTimestamp.ToString("O");
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private bool CanAddSubscription() => IsConnected && !string.IsNullOrWhiteSpace(NewNodeIdText);
|
||||
|
||||
[RelayCommand(CanExecute = nameof(CanAddSubscription))]
|
||||
private async Task AddSubscriptionAsync()
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(NewNodeIdText)) return;
|
||||
|
||||
var nodeIdStr = NewNodeIdText;
|
||||
var interval = NewInterval;
|
||||
|
||||
try
|
||||
{
|
||||
var nodeId = NodeId.Parse(nodeIdStr);
|
||||
await _service.SubscribeAsync(nodeId, interval);
|
||||
|
||||
_dispatcher.Post(() =>
|
||||
{
|
||||
ActiveSubscriptions.Add(new SubscriptionItemViewModel(nodeIdStr, interval));
|
||||
SubscriptionCount = ActiveSubscriptions.Count;
|
||||
});
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Subscription failed; no item added
|
||||
}
|
||||
}
|
||||
|
||||
private bool CanRemoveSubscription() => IsConnected && SelectedSubscription != null;
|
||||
|
||||
[RelayCommand(CanExecute = nameof(CanRemoveSubscription))]
|
||||
private async Task RemoveSubscriptionAsync()
|
||||
{
|
||||
if (SelectedSubscription == null) return;
|
||||
|
||||
var item = SelectedSubscription;
|
||||
|
||||
try
|
||||
{
|
||||
var nodeId = NodeId.Parse(item.NodeId);
|
||||
await _service.UnsubscribeAsync(nodeId);
|
||||
|
||||
_dispatcher.Post(() =>
|
||||
{
|
||||
ActiveSubscriptions.Remove(item);
|
||||
SubscriptionCount = ActiveSubscriptions.Count;
|
||||
});
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Unsubscribe failed
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Clears all subscriptions and resets state.
|
||||
/// </summary>
|
||||
public void Clear()
|
||||
{
|
||||
ActiveSubscriptions.Clear();
|
||||
SubscriptionCount = 0;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Unhooks event handlers from the service.
|
||||
/// </summary>
|
||||
public void Teardown()
|
||||
{
|
||||
_service.DataChanged -= OnDataChanged;
|
||||
}
|
||||
}
|
||||
122
src/ZB.MOM.WW.LmxOpcUa.Client.UI/ViewModels/TreeNodeViewModel.cs
Normal file
122
src/ZB.MOM.WW.LmxOpcUa.Client.UI/ViewModels/TreeNodeViewModel.cs
Normal file
@@ -0,0 +1,122 @@
|
||||
using System.Collections.ObjectModel;
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using Opc.Ua;
|
||||
using ZB.MOM.WW.LmxOpcUa.Client.Shared;
|
||||
using ZB.MOM.WW.LmxOpcUa.Client.UI.Services;
|
||||
|
||||
namespace ZB.MOM.WW.LmxOpcUa.Client.UI.ViewModels;
|
||||
|
||||
/// <summary>
|
||||
/// Represents a single node in the OPC UA browse tree with lazy-load support.
|
||||
/// </summary>
|
||||
public partial class TreeNodeViewModel : ObservableObject
|
||||
{
|
||||
private static readonly TreeNodeViewModel PlaceholderSentinel = new();
|
||||
|
||||
private readonly IOpcUaClientService? _service;
|
||||
private readonly IUiDispatcher? _dispatcher;
|
||||
private bool _hasLoadedChildren;
|
||||
|
||||
/// <summary>The string NodeId of this node.</summary>
|
||||
public string NodeId { get; }
|
||||
|
||||
/// <summary>The display name shown in the tree.</summary>
|
||||
public string DisplayName { get; }
|
||||
|
||||
/// <summary>The OPC UA node class (Object, Variable, etc.).</summary>
|
||||
public string NodeClass { get; }
|
||||
|
||||
/// <summary>Whether this node has child references.</summary>
|
||||
public bool HasChildren { get; }
|
||||
|
||||
/// <summary>Child nodes (may contain a placeholder sentinel before first expand).</summary>
|
||||
public ObservableCollection<TreeNodeViewModel> Children { get; } = new();
|
||||
|
||||
[ObservableProperty]
|
||||
private bool _isExpanded;
|
||||
|
||||
[ObservableProperty]
|
||||
private bool _isLoading;
|
||||
|
||||
/// <summary>
|
||||
/// Private constructor for the placeholder sentinel only.
|
||||
/// </summary>
|
||||
private TreeNodeViewModel()
|
||||
{
|
||||
NodeId = string.Empty;
|
||||
DisplayName = "Loading...";
|
||||
NodeClass = string.Empty;
|
||||
HasChildren = false;
|
||||
}
|
||||
|
||||
public TreeNodeViewModel(
|
||||
string nodeId,
|
||||
string displayName,
|
||||
string nodeClass,
|
||||
bool hasChildren,
|
||||
IOpcUaClientService service,
|
||||
IUiDispatcher dispatcher)
|
||||
{
|
||||
NodeId = nodeId;
|
||||
DisplayName = displayName;
|
||||
NodeClass = nodeClass;
|
||||
HasChildren = hasChildren;
|
||||
_service = service;
|
||||
_dispatcher = dispatcher;
|
||||
|
||||
if (hasChildren)
|
||||
{
|
||||
Children.Add(PlaceholderSentinel);
|
||||
}
|
||||
}
|
||||
|
||||
partial void OnIsExpandedChanged(bool value)
|
||||
{
|
||||
if (value && !_hasLoadedChildren && HasChildren)
|
||||
{
|
||||
_ = LoadChildrenAsync();
|
||||
}
|
||||
}
|
||||
|
||||
private async Task LoadChildrenAsync()
|
||||
{
|
||||
if (_service == null || _dispatcher == null) return;
|
||||
|
||||
_hasLoadedChildren = true;
|
||||
IsLoading = true;
|
||||
|
||||
try
|
||||
{
|
||||
var nodeId = Opc.Ua.NodeId.Parse(NodeId);
|
||||
var results = await _service.BrowseAsync(nodeId);
|
||||
|
||||
_dispatcher.Post(() =>
|
||||
{
|
||||
Children.Clear();
|
||||
foreach (var result in results)
|
||||
{
|
||||
Children.Add(new TreeNodeViewModel(
|
||||
result.NodeId,
|
||||
result.DisplayName,
|
||||
result.NodeClass,
|
||||
result.HasChildren,
|
||||
_service,
|
||||
_dispatcher));
|
||||
}
|
||||
});
|
||||
}
|
||||
catch
|
||||
{
|
||||
_dispatcher.Post(() => Children.Clear());
|
||||
}
|
||||
finally
|
||||
{
|
||||
_dispatcher.Post(() => IsLoading = false);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns whether this node instance is the placeholder sentinel.
|
||||
/// </summary>
|
||||
internal bool IsPlaceholder => ReferenceEquals(this, PlaceholderSentinel);
|
||||
}
|
||||
36
src/ZB.MOM.WW.LmxOpcUa.Client.UI/Views/AlarmsView.axaml
Normal file
36
src/ZB.MOM.WW.LmxOpcUa.Client.UI/Views/AlarmsView.axaml
Normal file
@@ -0,0 +1,36 @@
|
||||
<UserControl xmlns="https://github.com/avaloniaui"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:vm="using:ZB.MOM.WW.LmxOpcUa.Client.UI.ViewModels"
|
||||
x:Class="ZB.MOM.WW.LmxOpcUa.Client.UI.Views.AlarmsView"
|
||||
x:DataType="vm:AlarmsViewModel">
|
||||
<DockPanel Margin="8">
|
||||
<!-- Controls -->
|
||||
<StackPanel DockPanel.Dock="Top" Spacing="8">
|
||||
<TextBlock Text="Alarm Monitoring" FontWeight="Bold" />
|
||||
<StackPanel Orientation="Horizontal" Spacing="8">
|
||||
<TextBox Text="{Binding MonitoredNodeIdText}" Width="250" Watermark="Source Node ID (optional)" />
|
||||
<NumericUpDown Value="{Binding Interval}" Minimum="100" Maximum="60000" Width="120" />
|
||||
<Button Content="Subscribe" Command="{Binding SubscribeCommand}" />
|
||||
<Button Content="Unsubscribe" Command="{Binding UnsubscribeCommand}" />
|
||||
<Button Content="Refresh" Command="{Binding RefreshCommand}" />
|
||||
</StackPanel>
|
||||
</StackPanel>
|
||||
|
||||
<!-- Alarm Events -->
|
||||
<DataGrid ItemsSource="{Binding AlarmEvents}"
|
||||
AutoGenerateColumns="False"
|
||||
IsReadOnly="True"
|
||||
Margin="0,8,0,0">
|
||||
<DataGrid.Columns>
|
||||
<DataGridTextColumn Header="Time" Binding="{Binding Time}" Width="180" />
|
||||
<DataGridTextColumn Header="Source" Binding="{Binding SourceName}" Width="120" />
|
||||
<DataGridTextColumn Header="Condition" Binding="{Binding ConditionName}" Width="120" />
|
||||
<DataGridTextColumn Header="Severity" Binding="{Binding Severity}" Width="80" />
|
||||
<DataGridTextColumn Header="Message" Binding="{Binding Message}" Width="200" />
|
||||
<DataGridCheckBoxColumn Header="Active" Binding="{Binding ActiveState}" Width="60" />
|
||||
<DataGridCheckBoxColumn Header="Acked" Binding="{Binding AckedState}" Width="60" />
|
||||
<DataGridCheckBoxColumn Header="Retain" Binding="{Binding Retain}" Width="60" />
|
||||
</DataGrid.Columns>
|
||||
</DataGrid>
|
||||
</DockPanel>
|
||||
</UserControl>
|
||||
11
src/ZB.MOM.WW.LmxOpcUa.Client.UI/Views/AlarmsView.axaml.cs
Normal file
11
src/ZB.MOM.WW.LmxOpcUa.Client.UI/Views/AlarmsView.axaml.cs
Normal file
@@ -0,0 +1,11 @@
|
||||
using Avalonia.Controls;
|
||||
|
||||
namespace ZB.MOM.WW.LmxOpcUa.Client.UI.Views;
|
||||
|
||||
public partial class AlarmsView : UserControl
|
||||
{
|
||||
public AlarmsView()
|
||||
{
|
||||
InitializeComponent();
|
||||
}
|
||||
}
|
||||
25
src/ZB.MOM.WW.LmxOpcUa.Client.UI/Views/BrowseTreeView.axaml
Normal file
25
src/ZB.MOM.WW.LmxOpcUa.Client.UI/Views/BrowseTreeView.axaml
Normal file
@@ -0,0 +1,25 @@
|
||||
<UserControl xmlns="https://github.com/avaloniaui"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:vm="using:ZB.MOM.WW.LmxOpcUa.Client.UI.ViewModels"
|
||||
x:Class="ZB.MOM.WW.LmxOpcUa.Client.UI.Views.BrowseTreeView"
|
||||
x:DataType="vm:BrowseTreeViewModel">
|
||||
<TreeView ItemsSource="{Binding RootNodes}"
|
||||
Name="BrowseTree">
|
||||
<TreeView.ItemTemplate>
|
||||
<TreeDataTemplate ItemsSource="{Binding Children}">
|
||||
<StackPanel Orientation="Horizontal" Spacing="6">
|
||||
<TextBlock Text="{Binding DisplayName}" VerticalAlignment="Center" />
|
||||
<TextBlock Text="{Binding NodeClass}"
|
||||
FontSize="10"
|
||||
Foreground="Gray"
|
||||
VerticalAlignment="Center" />
|
||||
<ProgressBar IsIndeterminate="True"
|
||||
IsVisible="{Binding IsLoading}"
|
||||
Width="50"
|
||||
Height="8"
|
||||
VerticalAlignment="Center" />
|
||||
</StackPanel>
|
||||
</TreeDataTemplate>
|
||||
</TreeView.ItemTemplate>
|
||||
</TreeView>
|
||||
</UserControl>
|
||||
@@ -0,0 +1,11 @@
|
||||
using Avalonia.Controls;
|
||||
|
||||
namespace ZB.MOM.WW.LmxOpcUa.Client.UI.Views;
|
||||
|
||||
public partial class BrowseTreeView : UserControl
|
||||
{
|
||||
public BrowseTreeView()
|
||||
{
|
||||
InitializeComponent();
|
||||
}
|
||||
}
|
||||
68
src/ZB.MOM.WW.LmxOpcUa.Client.UI/Views/HistoryView.axaml
Normal file
68
src/ZB.MOM.WW.LmxOpcUa.Client.UI/Views/HistoryView.axaml
Normal file
@@ -0,0 +1,68 @@
|
||||
<UserControl xmlns="https://github.com/avaloniaui"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:vm="using:ZB.MOM.WW.LmxOpcUa.Client.UI.ViewModels"
|
||||
x:Class="ZB.MOM.WW.LmxOpcUa.Client.UI.Views.HistoryView"
|
||||
x:DataType="vm:HistoryViewModel">
|
||||
<DockPanel Margin="8">
|
||||
<!-- Controls -->
|
||||
<StackPanel DockPanel.Dock="Top" Spacing="8">
|
||||
<TextBlock Text="History Read" FontWeight="Bold" />
|
||||
<TextBlock Text="{Binding SelectedNodeId, FallbackValue='(no node selected)'}"
|
||||
Foreground="Gray" />
|
||||
|
||||
<StackPanel Orientation="Horizontal" Spacing="8">
|
||||
<StackPanel Spacing="2">
|
||||
<TextBlock Text="Start Time" FontSize="11" />
|
||||
<DatePicker SelectedDate="{Binding StartTime}" />
|
||||
</StackPanel>
|
||||
<StackPanel Spacing="2">
|
||||
<TextBlock Text="End Time" FontSize="11" />
|
||||
<DatePicker SelectedDate="{Binding EndTime}" />
|
||||
</StackPanel>
|
||||
<StackPanel Spacing="2">
|
||||
<TextBlock Text="Max Values" FontSize="11" />
|
||||
<NumericUpDown Value="{Binding MaxValues}" Minimum="1" Maximum="100000" Width="120" />
|
||||
</StackPanel>
|
||||
</StackPanel>
|
||||
|
||||
<StackPanel Orientation="Horizontal" Spacing="8">
|
||||
<StackPanel Spacing="2">
|
||||
<TextBlock Text="Aggregate" FontSize="11" />
|
||||
<ComboBox ItemsSource="{Binding AggregateTypes}"
|
||||
SelectedItem="{Binding SelectedAggregateType}"
|
||||
Width="150">
|
||||
<ComboBox.ItemTemplate>
|
||||
<DataTemplate>
|
||||
<TextBlock Text="{Binding, TargetNullValue='Raw'}" />
|
||||
</DataTemplate>
|
||||
</ComboBox.ItemTemplate>
|
||||
</ComboBox>
|
||||
</StackPanel>
|
||||
<StackPanel Spacing="2" IsVisible="{Binding IsAggregateRead}">
|
||||
<TextBlock Text="Interval (ms)" FontSize="11" />
|
||||
<NumericUpDown Value="{Binding IntervalMs}" Minimum="1000" Maximum="86400000" Width="150" />
|
||||
</StackPanel>
|
||||
<Button Content="Read History"
|
||||
Command="{Binding ReadHistoryCommand}"
|
||||
VerticalAlignment="Bottom" />
|
||||
</StackPanel>
|
||||
|
||||
<ProgressBar IsIndeterminate="True"
|
||||
IsVisible="{Binding IsLoading}"
|
||||
Height="4" />
|
||||
</StackPanel>
|
||||
|
||||
<!-- Results -->
|
||||
<DataGrid ItemsSource="{Binding Results}"
|
||||
AutoGenerateColumns="False"
|
||||
IsReadOnly="True"
|
||||
Margin="0,8,0,0">
|
||||
<DataGrid.Columns>
|
||||
<DataGridTextColumn Header="Value" Binding="{Binding Value}" Width="200" />
|
||||
<DataGridTextColumn Header="Status" Binding="{Binding Status}" Width="120" />
|
||||
<DataGridTextColumn Header="Source Timestamp" Binding="{Binding SourceTimestamp}" Width="220" />
|
||||
<DataGridTextColumn Header="Server Timestamp" Binding="{Binding ServerTimestamp}" Width="220" />
|
||||
</DataGrid.Columns>
|
||||
</DataGrid>
|
||||
</DockPanel>
|
||||
</UserControl>
|
||||
11
src/ZB.MOM.WW.LmxOpcUa.Client.UI/Views/HistoryView.axaml.cs
Normal file
11
src/ZB.MOM.WW.LmxOpcUa.Client.UI/Views/HistoryView.axaml.cs
Normal file
@@ -0,0 +1,11 @@
|
||||
using Avalonia.Controls;
|
||||
|
||||
namespace ZB.MOM.WW.LmxOpcUa.Client.UI.Views;
|
||||
|
||||
public partial class HistoryView : UserControl
|
||||
{
|
||||
public HistoryView()
|
||||
{
|
||||
InitializeComponent();
|
||||
}
|
||||
}
|
||||
89
src/ZB.MOM.WW.LmxOpcUa.Client.UI/Views/MainWindow.axaml
Normal file
89
src/ZB.MOM.WW.LmxOpcUa.Client.UI/Views/MainWindow.axaml
Normal file
@@ -0,0 +1,89 @@
|
||||
<Window xmlns="https://github.com/avaloniaui"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:vm="using:ZB.MOM.WW.LmxOpcUa.Client.UI.ViewModels"
|
||||
xmlns:views="using:ZB.MOM.WW.LmxOpcUa.Client.UI.Views"
|
||||
x:Class="ZB.MOM.WW.LmxOpcUa.Client.UI.Views.MainWindow"
|
||||
x:DataType="vm:MainWindowViewModel"
|
||||
Title="LmxOpcUa Client"
|
||||
Width="1200"
|
||||
Height="800">
|
||||
<DockPanel>
|
||||
<!-- Top Connection Bar -->
|
||||
<Border DockPanel.Dock="Top" Background="#F0F0F0" Padding="8">
|
||||
<StackPanel Spacing="8">
|
||||
<StackPanel Orientation="Horizontal" Spacing="8">
|
||||
<TextBox Text="{Binding EndpointUrl}"
|
||||
Width="300"
|
||||
Watermark="opc.tcp://host:port" />
|
||||
<TextBox Text="{Binding Username}"
|
||||
Width="120"
|
||||
Watermark="Username" />
|
||||
<TextBox Text="{Binding Password}"
|
||||
Width="120"
|
||||
Watermark="Password"
|
||||
PasswordChar="*" />
|
||||
<ComboBox ItemsSource="{Binding SecurityModes}"
|
||||
SelectedItem="{Binding SelectedSecurityMode}"
|
||||
Width="140" />
|
||||
<Button Content="Connect"
|
||||
Command="{Binding ConnectCommand}" />
|
||||
<Button Content="Disconnect"
|
||||
Command="{Binding DisconnectCommand}" />
|
||||
</StackPanel>
|
||||
|
||||
<!-- Redundancy Info -->
|
||||
<StackPanel Orientation="Horizontal"
|
||||
Spacing="12"
|
||||
IsVisible="{Binding RedundancyInfo, Converter={x:Static ObjectConverters.IsNotNull}}">
|
||||
<TextBlock Text="{Binding RedundancyInfo.Mode, StringFormat='Redundancy: {0}'}"
|
||||
FontSize="11" />
|
||||
<TextBlock Text="{Binding RedundancyInfo.ServiceLevel, StringFormat='Service Level: {0}'}"
|
||||
FontSize="11" />
|
||||
<TextBlock Text="{Binding RedundancyInfo.ApplicationUri, StringFormat='URI: {0}'}"
|
||||
FontSize="11" />
|
||||
</StackPanel>
|
||||
</StackPanel>
|
||||
</Border>
|
||||
|
||||
<!-- Bottom Status Bar -->
|
||||
<Border DockPanel.Dock="Bottom" Background="#F0F0F0" Padding="8,4">
|
||||
<StackPanel Orientation="Horizontal" Spacing="20">
|
||||
<TextBlock Text="{Binding StatusMessage}" />
|
||||
<TextBlock Text="{Binding SessionLabel}" Foreground="Gray" />
|
||||
<TextBlock Text="{Binding SubscriptionCount, StringFormat='Subscriptions: {0}'}" />
|
||||
</StackPanel>
|
||||
</Border>
|
||||
|
||||
<!-- Main Content -->
|
||||
<Grid ColumnDefinitions="300,8,*">
|
||||
<!-- Left: Browse Tree -->
|
||||
<Border Grid.Column="0" BorderBrush="#CCCCCC" BorderThickness="0,0,1,0">
|
||||
<DockPanel>
|
||||
<TextBlock DockPanel.Dock="Top" Text="Browse Tree" FontWeight="Bold" Margin="8,8,8,4" />
|
||||
<views:BrowseTreeView DataContext="{Binding BrowseTree}"
|
||||
Name="BrowseTreePanel" />
|
||||
</DockPanel>
|
||||
</Border>
|
||||
|
||||
<!-- Splitter -->
|
||||
<GridSplitter Grid.Column="1" Width="8" Background="Transparent" />
|
||||
|
||||
<!-- Right: Tab panels -->
|
||||
<TabControl Grid.Column="2"
|
||||
IsEnabled="{Binding IsConnected}">
|
||||
<TabItem Header="Read/Write">
|
||||
<views:ReadWriteView DataContext="{Binding ReadWrite}" />
|
||||
</TabItem>
|
||||
<TabItem Header="Subscriptions">
|
||||
<views:SubscriptionsView DataContext="{Binding Subscriptions}" />
|
||||
</TabItem>
|
||||
<TabItem Header="Alarms">
|
||||
<views:AlarmsView DataContext="{Binding Alarms}" />
|
||||
</TabItem>
|
||||
<TabItem Header="History">
|
||||
<views:HistoryView DataContext="{Binding History}" />
|
||||
</TabItem>
|
||||
</TabControl>
|
||||
</Grid>
|
||||
</DockPanel>
|
||||
</Window>
|
||||
34
src/ZB.MOM.WW.LmxOpcUa.Client.UI/Views/MainWindow.axaml.cs
Normal file
34
src/ZB.MOM.WW.LmxOpcUa.Client.UI/Views/MainWindow.axaml.cs
Normal file
@@ -0,0 +1,34 @@
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Interactivity;
|
||||
using ZB.MOM.WW.LmxOpcUa.Client.UI.ViewModels;
|
||||
|
||||
namespace ZB.MOM.WW.LmxOpcUa.Client.UI.Views;
|
||||
|
||||
public partial class MainWindow : Window
|
||||
{
|
||||
public MainWindow()
|
||||
{
|
||||
InitializeComponent();
|
||||
}
|
||||
|
||||
protected override void OnLoaded(RoutedEventArgs e)
|
||||
{
|
||||
base.OnLoaded(e);
|
||||
|
||||
// Wire up tree selection to the main ViewModel
|
||||
var browseTreeView = this.FindControl<BrowseTreeView>("BrowseTreePanel");
|
||||
var treeView = browseTreeView?.FindControl<TreeView>("BrowseTree");
|
||||
if (treeView != null)
|
||||
{
|
||||
treeView.SelectionChanged += OnTreeSelectionChanged;
|
||||
}
|
||||
}
|
||||
|
||||
private void OnTreeSelectionChanged(object? sender, SelectionChangedEventArgs e)
|
||||
{
|
||||
if (DataContext is MainWindowViewModel vm && sender is TreeView treeView)
|
||||
{
|
||||
vm.SelectedTreeNode = treeView.SelectedItem as TreeNodeViewModel;
|
||||
}
|
||||
}
|
||||
}
|
||||
39
src/ZB.MOM.WW.LmxOpcUa.Client.UI/Views/ReadWriteView.axaml
Normal file
39
src/ZB.MOM.WW.LmxOpcUa.Client.UI/Views/ReadWriteView.axaml
Normal file
@@ -0,0 +1,39 @@
|
||||
<UserControl xmlns="https://github.com/avaloniaui"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:vm="using:ZB.MOM.WW.LmxOpcUa.Client.UI.ViewModels"
|
||||
x:Class="ZB.MOM.WW.LmxOpcUa.Client.UI.Views.ReadWriteView"
|
||||
x:DataType="vm:ReadWriteViewModel">
|
||||
<StackPanel Spacing="8" Margin="8">
|
||||
<!-- Selected Node -->
|
||||
<TextBlock Text="Selected Node" FontWeight="Bold" />
|
||||
<TextBlock Text="{Binding SelectedNodeId, FallbackValue='(none)'}"
|
||||
Foreground="Gray" />
|
||||
|
||||
<!-- Read Section -->
|
||||
<Separator />
|
||||
<TextBlock Text="Read Value" FontWeight="Bold" />
|
||||
<Button Content="Read" Command="{Binding ReadCommand}" />
|
||||
<Grid ColumnDefinitions="Auto,*" RowDefinitions="Auto,Auto,Auto,Auto" Margin="0,4,0,0">
|
||||
<TextBlock Grid.Row="0" Grid.Column="0" Text="Value: " FontWeight="SemiBold" />
|
||||
<TextBlock Grid.Row="0" Grid.Column="1" Text="{Binding CurrentValue}" TextWrapping="Wrap" />
|
||||
|
||||
<TextBlock Grid.Row="1" Grid.Column="0" Text="Status: " FontWeight="SemiBold" />
|
||||
<TextBlock Grid.Row="1" Grid.Column="1" Text="{Binding CurrentStatus}" />
|
||||
|
||||
<TextBlock Grid.Row="2" Grid.Column="0" Text="Source Time: " FontWeight="SemiBold" />
|
||||
<TextBlock Grid.Row="2" Grid.Column="1" Text="{Binding SourceTimestamp}" />
|
||||
|
||||
<TextBlock Grid.Row="3" Grid.Column="0" Text="Server Time: " FontWeight="SemiBold" />
|
||||
<TextBlock Grid.Row="3" Grid.Column="1" Text="{Binding ServerTimestamp}" />
|
||||
</Grid>
|
||||
|
||||
<!-- Write Section -->
|
||||
<Separator />
|
||||
<TextBlock Text="Write Value" FontWeight="Bold" />
|
||||
<StackPanel Orientation="Horizontal" Spacing="8">
|
||||
<TextBox Text="{Binding WriteValue}" Width="200" Watermark="Value to write" />
|
||||
<Button Content="Write" Command="{Binding WriteCommand}" />
|
||||
</StackPanel>
|
||||
<TextBlock Text="{Binding WriteStatus}" Foreground="Gray" />
|
||||
</StackPanel>
|
||||
</UserControl>
|
||||
@@ -0,0 +1,11 @@
|
||||
using Avalonia.Controls;
|
||||
|
||||
namespace ZB.MOM.WW.LmxOpcUa.Client.UI.Views;
|
||||
|
||||
public partial class ReadWriteView : UserControl
|
||||
{
|
||||
public ReadWriteView()
|
||||
{
|
||||
InitializeComponent();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
<UserControl xmlns="https://github.com/avaloniaui"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:vm="using:ZB.MOM.WW.LmxOpcUa.Client.UI.ViewModels"
|
||||
x:Class="ZB.MOM.WW.LmxOpcUa.Client.UI.Views.SubscriptionsView"
|
||||
x:DataType="vm:SubscriptionsViewModel">
|
||||
<DockPanel Margin="8">
|
||||
<!-- Add/Remove Controls -->
|
||||
<StackPanel DockPanel.Dock="Top" Spacing="8">
|
||||
<TextBlock Text="Subscriptions" FontWeight="Bold" />
|
||||
<StackPanel Orientation="Horizontal" Spacing="8">
|
||||
<TextBox Text="{Binding NewNodeIdText}" Width="250" Watermark="Node ID (e.g., ns=2;s=MyNode)" />
|
||||
<NumericUpDown Value="{Binding NewInterval}" Minimum="100" Maximum="60000" Width="120" />
|
||||
<Button Content="Add" Command="{Binding AddSubscriptionCommand}" />
|
||||
<Button Content="Remove" Command="{Binding RemoveSubscriptionCommand}" />
|
||||
</StackPanel>
|
||||
</StackPanel>
|
||||
|
||||
<!-- Active Subscriptions List -->
|
||||
<DataGrid ItemsSource="{Binding ActiveSubscriptions}"
|
||||
SelectedItem="{Binding SelectedSubscription}"
|
||||
AutoGenerateColumns="False"
|
||||
IsReadOnly="True"
|
||||
Margin="0,8,0,0">
|
||||
<DataGrid.Columns>
|
||||
<DataGridTextColumn Header="Node ID" Binding="{Binding NodeId}" Width="250" />
|
||||
<DataGridTextColumn Header="Value" Binding="{Binding Value}" Width="150" />
|
||||
<DataGridTextColumn Header="Status" Binding="{Binding Status}" Width="120" />
|
||||
<DataGridTextColumn Header="Timestamp" Binding="{Binding Timestamp}" Width="200" />
|
||||
</DataGrid.Columns>
|
||||
</DataGrid>
|
||||
</DockPanel>
|
||||
</UserControl>
|
||||
@@ -0,0 +1,11 @@
|
||||
using Avalonia.Controls;
|
||||
|
||||
namespace ZB.MOM.WW.LmxOpcUa.Client.UI.Views;
|
||||
|
||||
public partial class SubscriptionsView : UserControl
|
||||
{
|
||||
public SubscriptionsView()
|
||||
{
|
||||
InitializeComponent();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>WinExe</OutputType>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<RootNamespace>ZB.MOM.WW.LmxOpcUa.Client.UI</RootNamespace>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Avalonia" Version="11.2.7" />
|
||||
<PackageReference Include="Avalonia.Desktop" Version="11.2.7" />
|
||||
<PackageReference Include="Avalonia.Themes.Fluent" Version="11.2.7" />
|
||||
<PackageReference Include="Avalonia.Fonts.Inter" Version="11.2.7" />
|
||||
<PackageReference Include="Avalonia.Controls.DataGrid" Version="11.2.7" />
|
||||
<PackageReference Include="CommunityToolkit.Mvvm" Version="8.4.0" />
|
||||
<PackageReference Include="Serilog" Version="4.2.0" />
|
||||
<PackageReference Include="Serilog.Sinks.Console" Version="6.0.0" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\ZB.MOM.WW.LmxOpcUa.Client.Shared\ZB.MOM.WW.LmxOpcUa.Client.Shared.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<InternalsVisibleTo Include="ZB.MOM.WW.LmxOpcUa.Client.UI.Tests" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
Reference in New Issue
Block a user