chore: organize solution into module folders (Core/Server/Drivers/Client/Tooling)
Group all 69 projects into category subfolders under src/ and tests/ so the Rider Solution Explorer mirrors the module structure. Folders: Core, Server, Drivers (with a nested Driver CLIs subfolder), Client, Tooling. - Move every project folder on disk with git mv (history preserved as renames). - Recompute relative paths in 57 .csproj files: cross-category ProjectReferences, the lib/ HintPath+None refs in Driver.Historian.Wonderware, and the external mxaccessgw refs in Driver.Galaxy and its test project. - Rebuild ZB.MOM.WW.OtOpcUa.slnx with nested solution folders. - Re-prefix project paths in functional scripts (e2e, compliance, smoke SQL, integration, install). Build green (0 errors); unit tests pass. Docs left for a separate pass. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
124
src/Client/ZB.MOM.WW.OtOpcUa.Client.CLI/CommandBase.cs
Normal file
124
src/Client/ZB.MOM.WW.OtOpcUa.Client.CLI/CommandBase.cs
Normal file
@@ -0,0 +1,124 @@
|
||||
using CliFx;
|
||||
using CliFx.Attributes;
|
||||
using CliFx.Infrastructure;
|
||||
using Serilog;
|
||||
using ZB.MOM.WW.OtOpcUa.Client.Shared;
|
||||
using ZB.MOM.WW.OtOpcUa.Client.Shared.Helpers;
|
||||
using ZB.MOM.WW.OtOpcUa.Client.Shared.Models;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.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;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a CLI command with the shared OPC UA client factory used to create per-command sessions.
|
||||
/// </summary>
|
||||
/// <param name="factory">The factory that creates the shared client service for the command execution.</param>
|
||||
protected CommandBase(IOpcUaClientServiceFactory factory)
|
||||
{
|
||||
_factory = factory;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the primary OPC UA endpoint URL the command should connect to.
|
||||
/// </summary>
|
||||
[CommandOption("url", 'u', Description = "OPC UA server endpoint URL", IsRequired = true)]
|
||||
public string Url { get; init; } = default!;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the optional username used for authenticated OPC UA sessions.
|
||||
/// </summary>
|
||||
[CommandOption("username", 'U', Description = "Username for authentication")]
|
||||
public string? Username { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the optional password paired with <see cref="Username" /> for authenticated OPC UA sessions.
|
||||
/// </summary>
|
||||
[CommandOption("password", 'P', Description = "Password for authentication")]
|
||||
public string? Password { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the transport security mode requested by the operator for this CLI session.
|
||||
/// </summary>
|
||||
[CommandOption("security", 'S',
|
||||
Description = "Transport security: none, sign, encrypt, signandencrypt (default: none)")]
|
||||
public string Security { get; init; } = "none";
|
||||
|
||||
/// <summary>
|
||||
/// Gets the optional comma-separated failover endpoints that should be tried if the primary endpoint is unavailable.
|
||||
/// </summary>
|
||||
[CommandOption("failover-urls", 'F', Description = "Comma-separated failover endpoint URLs for redundancy")]
|
||||
public string? FailoverUrls { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets a value indicating whether verbose Serilog output should be enabled for troubleshooting.
|
||||
/// </summary>
|
||||
[CommandOption("verbose", Description = "Enable verbose/debug logging")]
|
||||
public bool Verbose { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Executes the command-specific workflow against the configured OPC UA endpoint.
|
||||
/// </summary>
|
||||
/// <param name="console">The CLI console used for output and cancellation handling.</param>
|
||||
public abstract ValueTask ExecuteAsync(IConsole console);
|
||||
|
||||
/// <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>
|
||||
/// <param name="ct">The cancellation token that aborts connection setup for the command.</param>
|
||||
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();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
using CliFx.Attributes;
|
||||
using CliFx.Infrastructure;
|
||||
using ZB.MOM.WW.OtOpcUa.Client.CLI.Helpers;
|
||||
using ZB.MOM.WW.OtOpcUa.Client.Shared;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Client.CLI.Commands;
|
||||
|
||||
[Command("alarms", Description = "Subscribe to alarm events")]
|
||||
public class AlarmsCommand : CommandBase
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates the alarm-monitoring command used to stream OPC UA condition events to the terminal.
|
||||
/// </summary>
|
||||
/// <param name="factory">The factory that creates the shared client service for the command run.</param>
|
||||
public AlarmsCommand(IOpcUaClientServiceFactory factory) : base(factory)
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the optional source node whose alarm events should be monitored instead of the server root.
|
||||
/// </summary>
|
||||
[CommandOption("node", 'n', Description = "Node ID to monitor for events (default: Server node)")]
|
||||
public string? NodeId { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the publishing interval, in milliseconds, for the alarm subscription.
|
||||
/// </summary>
|
||||
[CommandOption("interval", 'i', Description = "Publishing interval in milliseconds")]
|
||||
public int Interval { get; init; } = 1000;
|
||||
|
||||
/// <summary>
|
||||
/// Gets a value indicating whether retained alarm conditions should be refreshed immediately after subscribing.
|
||||
/// </summary>
|
||||
[CommandOption("refresh", Description = "Request a ConditionRefresh after subscribing")]
|
||||
public bool Refresh { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Connects to the server, subscribes to alarm events, and streams operator-facing alarm state changes to the console.
|
||||
/// </summary>
|
||||
/// <param name="console">The CLI console used for output and cancellation handling.</param>
|
||||
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();
|
||||
await console.Output.WriteLineAsync("Unsubscribed.");
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (service != null)
|
||||
{
|
||||
await service.DisconnectAsync();
|
||||
service.Dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
using CliFx.Attributes;
|
||||
using CliFx.Infrastructure;
|
||||
using Opc.Ua;
|
||||
using ZB.MOM.WW.OtOpcUa.Client.CLI.Helpers;
|
||||
using ZB.MOM.WW.OtOpcUa.Client.Shared;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Client.CLI.Commands;
|
||||
|
||||
[Command("browse", Description = "Browse the OPC UA address space")]
|
||||
public class BrowseCommand : CommandBase
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates the browse command used to inspect the server address space from the terminal.
|
||||
/// </summary>
|
||||
/// <param name="factory">The factory that creates the shared client service for the command run.</param>
|
||||
public BrowseCommand(IOpcUaClientServiceFactory factory) : base(factory)
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the optional starting node for the browse, defaulting to the Objects folder.
|
||||
/// </summary>
|
||||
[CommandOption("node", 'n', Description = "Node ID to browse (default: Objects folder)")]
|
||||
public string? NodeId { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the maximum browse depth the command should traverse.
|
||||
/// </summary>
|
||||
[CommandOption("depth", 'd', Description = "Maximum browse depth")]
|
||||
public int Depth { get; init; } = 1;
|
||||
|
||||
/// <summary>
|
||||
/// Gets a value indicating whether child nodes should be traversed recursively.
|
||||
/// </summary>
|
||||
[CommandOption("recursive", 'r', Description = "Browse recursively (uses --depth as max depth)")]
|
||||
public bool Recursive { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Connects to the server and prints a tree view of the requested address-space branch.
|
||||
/// </summary>
|
||||
/// <param name="console">The CLI console used for output and cancellation handling.</param>
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
using CliFx.Attributes;
|
||||
using CliFx.Infrastructure;
|
||||
using ZB.MOM.WW.OtOpcUa.Client.Shared;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Client.CLI.Commands;
|
||||
|
||||
[Command("connect", Description = "Test connection to an OPC UA server")]
|
||||
public class ConnectCommand : CommandBase
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates the connectivity test command used to verify endpoint reachability and negotiated security settings.
|
||||
/// </summary>
|
||||
/// <param name="factory">The factory that creates the shared client service for the command run.</param>
|
||||
public ConnectCommand(IOpcUaClientServiceFactory factory) : base(factory)
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Connects to the server and prints the negotiated endpoint details for operator verification.
|
||||
/// </summary>
|
||||
/// <param name="console">The CLI console used for output and cancellation handling.</param>
|
||||
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();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
using CliFx.Attributes;
|
||||
using CliFx.Infrastructure;
|
||||
using Opc.Ua;
|
||||
using ZB.MOM.WW.OtOpcUa.Client.CLI.Helpers;
|
||||
using ZB.MOM.WW.OtOpcUa.Client.Shared;
|
||||
using ZB.MOM.WW.OtOpcUa.Client.Shared.Models;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Client.CLI.Commands;
|
||||
|
||||
[Command("historyread", Description = "Read historical data from a node")]
|
||||
public class HistoryReadCommand : CommandBase
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates the historical-data command used to inspect raw or aggregate history for a node.
|
||||
/// </summary>
|
||||
/// <param name="factory">The factory that creates the shared client service for the command run.</param>
|
||||
public HistoryReadCommand(IOpcUaClientServiceFactory factory) : base(factory)
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the historized node to query.
|
||||
/// </summary>
|
||||
[CommandOption("node", 'n', Description = "Node ID (e.g. ns=2;s=MyNode)", IsRequired = true)]
|
||||
public string NodeId { get; init; } = default!;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the optional history start time string supplied by the operator.
|
||||
/// </summary>
|
||||
[CommandOption("start", Description = "Start time (ISO 8601 or date string, default: 24 hours ago)")]
|
||||
public string? StartTime { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the optional history end time string supplied by the operator.
|
||||
/// </summary>
|
||||
[CommandOption("end", Description = "End time (ISO 8601 or date string, default: now)")]
|
||||
public string? EndTime { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the maximum number of raw values the command should print.
|
||||
/// </summary>
|
||||
[CommandOption("max", Description = "Maximum number of values to return")]
|
||||
public int MaxValues { get; init; } = 1000;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the optional aggregate name used when the operator wants processed history instead of raw samples.
|
||||
/// </summary>
|
||||
[CommandOption("aggregate", Description = "Aggregate function: Average, Minimum, Maximum, Count, Start, End, StandardDeviation")]
|
||||
public string? Aggregate { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the aggregate bucket interval, in milliseconds, for processed history reads.
|
||||
/// </summary>
|
||||
[CommandOption("interval", Description = "Processing interval in milliseconds for aggregates")]
|
||||
public double IntervalMs { get; init; } = 3600000;
|
||||
|
||||
/// <summary>
|
||||
/// Connects to the server and prints raw or processed historical values for the requested node.
|
||||
/// </summary>
|
||||
/// <param name="console">The CLI console used for output and cancellation handling.</param>
|
||||
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,
|
||||
"standarddeviation" or "stddev" or "stdev" => AggregateType.StandardDeviation,
|
||||
_ => throw new ArgumentException(
|
||||
$"Unknown aggregate: '{name}'. Supported: Average, Minimum, Maximum, Count, Start, End, StandardDeviation")
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
using CliFx.Attributes;
|
||||
using CliFx.Infrastructure;
|
||||
using ZB.MOM.WW.OtOpcUa.Client.CLI.Helpers;
|
||||
using ZB.MOM.WW.OtOpcUa.Client.Shared;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Client.CLI.Commands;
|
||||
|
||||
[Command("read", Description = "Read a value from a node")]
|
||||
public class ReadCommand : CommandBase
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates the point-read command used to inspect the current value of a node.
|
||||
/// </summary>
|
||||
/// <param name="factory">The factory that creates the shared client service for the command run.</param>
|
||||
public ReadCommand(IOpcUaClientServiceFactory factory) : base(factory)
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the node whose current value should be read.
|
||||
/// </summary>
|
||||
[CommandOption("node", 'n', Description = "Node ID (e.g. ns=2;s=MyNode)", IsRequired = true)]
|
||||
public string NodeId { get; init; } = default!;
|
||||
|
||||
/// <summary>
|
||||
/// Connects to the server and prints the current value, status, and timestamps for the requested node.
|
||||
/// </summary>
|
||||
/// <param name="console">The CLI console used for output and cancellation handling.</param>
|
||||
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,53 @@
|
||||
using CliFx.Attributes;
|
||||
using CliFx.Infrastructure;
|
||||
using ZB.MOM.WW.OtOpcUa.Client.Shared;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Client.CLI.Commands;
|
||||
|
||||
[Command("redundancy", Description = "Read redundancy state from an OPC UA server")]
|
||||
public class RedundancyCommand : CommandBase
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates the redundancy-inspection command used to display service-level and partner-server status.
|
||||
/// </summary>
|
||||
/// <param name="factory">The factory that creates the shared client service for the command run.</param>
|
||||
public RedundancyCommand(IOpcUaClientServiceFactory factory) : base(factory)
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Connects to the server and prints redundancy mode, service level, and partner-server identity data.
|
||||
/// </summary>
|
||||
/// <param name="console">The CLI console used for output and cancellation handling.</param>
|
||||
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,203 @@
|
||||
using System.Collections.Concurrent;
|
||||
using CliFx.Attributes;
|
||||
using CliFx.Infrastructure;
|
||||
using Opc.Ua;
|
||||
using ZB.MOM.WW.OtOpcUa.Client.CLI.Helpers;
|
||||
using ZB.MOM.WW.OtOpcUa.Client.Shared;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Client.CLI.Commands;
|
||||
|
||||
[Command("subscribe", Description = "Monitor a node for value changes")]
|
||||
public class SubscribeCommand : CommandBase
|
||||
{
|
||||
public SubscribeCommand(IOpcUaClientServiceFactory factory) : base(factory)
|
||||
{
|
||||
}
|
||||
|
||||
[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;
|
||||
|
||||
[CommandOption("recursive", 'r', Description = "Browse recursively from --node and subscribe to every Variable found")]
|
||||
public bool Recursive { get; init; }
|
||||
|
||||
[CommandOption("max-depth", Description = "Maximum recursion depth when --recursive is set")]
|
||||
public int MaxDepth { get; init; } = 10;
|
||||
|
||||
[CommandOption("quiet", 'q', Description = "Suppress per-update output; only print a final summary on Ctrl+C")]
|
||||
public bool Quiet { get; init; }
|
||||
|
||||
[CommandOption("duration", Description = "Auto-exit after N seconds and print summary (0 = run until Ctrl+C)")]
|
||||
public int DurationSeconds { get; init; } = 0;
|
||||
|
||||
[CommandOption("summary-file", Description = "Write summary to this file path on exit (in addition to stdout)")]
|
||||
public string? SummaryFile { get; init; }
|
||||
|
||||
public override async ValueTask ExecuteAsync(IConsole console)
|
||||
{
|
||||
ConfigureLogging();
|
||||
IOpcUaClientService? service = null;
|
||||
try
|
||||
{
|
||||
var ct = console.RegisterCancellationHandler();
|
||||
(service, _) = await CreateServiceAndConnectAsync(ct);
|
||||
|
||||
var rootNodeId = NodeIdParser.ParseRequired(NodeId);
|
||||
|
||||
var targets = new List<(NodeId nodeId, string displayPath)>();
|
||||
if (Recursive)
|
||||
{
|
||||
await console.Output.WriteLineAsync($"Browsing subtree of {NodeId} (max depth {MaxDepth})...");
|
||||
await CollectVariablesAsync(service, rootNodeId, NodeId, MaxDepth, 0, targets, ct);
|
||||
await console.Output.WriteLineAsync($"Found {targets.Count} variable nodes.");
|
||||
}
|
||||
else
|
||||
{
|
||||
targets.Add((rootNodeId, NodeId));
|
||||
}
|
||||
|
||||
var lastStatus = new ConcurrentDictionary<string, (StatusCode Status, DateTime LastUpdate, object? Value)>();
|
||||
var updateCount = new ConcurrentDictionary<string, int>();
|
||||
var everBad = new ConcurrentDictionary<string, byte>();
|
||||
var displayNameByNodeId = targets.ToDictionary(t => t.nodeId.ToString(), t => t.displayPath);
|
||||
|
||||
service.DataChanged += (_, e) =>
|
||||
{
|
||||
var key = e.NodeId.ToString();
|
||||
lastStatus[key] = (e.Value.StatusCode, DateTime.UtcNow, e.Value.Value);
|
||||
updateCount.AddOrUpdate(key, 1, (_, v) => v + 1);
|
||||
if (!StatusCode.IsGood(e.Value.StatusCode))
|
||||
everBad.TryAdd(key, 0);
|
||||
if (!Quiet)
|
||||
{
|
||||
console.Output.WriteLine(
|
||||
$"[{e.Value.SourceTimestamp:O}] {displayNameByNodeId.GetValueOrDefault(key, key)} = {e.Value.Value} ({e.Value.StatusCode})");
|
||||
}
|
||||
};
|
||||
|
||||
var subscribed = 0;
|
||||
foreach (var (nodeId, _) in targets)
|
||||
{
|
||||
try
|
||||
{
|
||||
await service.SubscribeAsync(nodeId, Interval, ct);
|
||||
subscribed++;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
await console.Output.WriteLineAsync($" FAILED to subscribe {nodeId}: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
await console.Output.WriteLineAsync(
|
||||
$"Subscribed to {subscribed}/{targets.Count} nodes (interval: {Interval}ms). Press Ctrl+C to stop and print summary.");
|
||||
|
||||
try
|
||||
{
|
||||
if (DurationSeconds > 0)
|
||||
await Task.Delay(TimeSpan.FromSeconds(DurationSeconds), ct);
|
||||
else
|
||||
await Task.Delay(Timeout.Infinite, ct);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
}
|
||||
|
||||
// Summary
|
||||
var summary = new List<string>();
|
||||
summary.Add("");
|
||||
summary.Add("==================== SUMMARY ====================");
|
||||
var good = new List<string>();
|
||||
var bad = new List<string>();
|
||||
var never = new List<string>();
|
||||
foreach (var (nodeId, display) in targets)
|
||||
{
|
||||
var key = nodeId.ToString();
|
||||
if (!lastStatus.TryGetValue(key, out var entry))
|
||||
{
|
||||
never.Add(display);
|
||||
continue;
|
||||
}
|
||||
if (StatusCode.IsGood(entry.Status))
|
||||
good.Add($"{display} = {entry.Value} ({entry.Status})");
|
||||
else
|
||||
bad.Add($"{display} = {entry.Value} ({entry.Status})");
|
||||
}
|
||||
|
||||
var neverWentBad = targets
|
||||
.Where(t => !everBad.ContainsKey(t.nodeId.ToString()))
|
||||
.Select(t => t.displayPath)
|
||||
.ToList();
|
||||
var didGoBad = targets.Count - neverWentBad.Count;
|
||||
|
||||
summary.Add($"Total subscribed: {targets.Count}");
|
||||
summary.Add($" Ever went BAD during window: {didGoBad}");
|
||||
summary.Add($" NEVER went bad (suspect): {neverWentBad.Count}");
|
||||
summary.Add($" Last status GOOD: {good.Count}");
|
||||
summary.Add($" Last status NOT-GOOD: {bad.Count}");
|
||||
summary.Add($" No update received at all: {never.Count}");
|
||||
|
||||
if (neverWentBad.Count > 0 && neverWentBad.Count < targets.Count)
|
||||
{
|
||||
summary.Add("");
|
||||
summary.Add("--- Nodes that NEVER received a bad-quality update (suspect) ---");
|
||||
foreach (var line in neverWentBad) summary.Add($" {line}");
|
||||
}
|
||||
if (never.Count > 0)
|
||||
{
|
||||
summary.Add("");
|
||||
summary.Add("--- Nodes that never received an update at all ---");
|
||||
foreach (var line in never) summary.Add($" {line}");
|
||||
}
|
||||
|
||||
foreach (var line in summary) await console.Output.WriteLineAsync(line);
|
||||
if (!string.IsNullOrEmpty(SummaryFile))
|
||||
{
|
||||
try { await File.WriteAllLinesAsync(SummaryFile, summary); }
|
||||
catch (Exception ex) { await console.Output.WriteLineAsync($"Failed to write summary file: {ex.Message}"); }
|
||||
}
|
||||
|
||||
foreach (var (nodeId, _) in targets)
|
||||
{
|
||||
try { await service.UnsubscribeAsync(nodeId); } catch { /* ignore */ }
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (service != null)
|
||||
{
|
||||
await service.DisconnectAsync();
|
||||
service.Dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task CollectVariablesAsync(
|
||||
IOpcUaClientService service,
|
||||
NodeId? parent,
|
||||
string parentPath,
|
||||
int maxDepth,
|
||||
int currentDepth,
|
||||
List<(NodeId nodeId, string displayPath)> into,
|
||||
CancellationToken ct)
|
||||
{
|
||||
if (currentDepth >= maxDepth) return;
|
||||
var children = await service.BrowseAsync(parent, ct);
|
||||
foreach (var child in children)
|
||||
{
|
||||
var nodeId = NodeIdParser.Parse(child.NodeId);
|
||||
if (nodeId is null) continue;
|
||||
var childPath = $"{parentPath}/{child.DisplayName}";
|
||||
if (child.NodeClass == "Variable")
|
||||
{
|
||||
into.Add((nodeId, childPath));
|
||||
}
|
||||
if (child.HasChildren)
|
||||
{
|
||||
await CollectVariablesAsync(service, nodeId, childPath, maxDepth, currentDepth + 1, into, ct);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
using CliFx.Attributes;
|
||||
using CliFx.Infrastructure;
|
||||
using Opc.Ua;
|
||||
using ZB.MOM.WW.OtOpcUa.Client.CLI.Helpers;
|
||||
using ZB.MOM.WW.OtOpcUa.Client.Shared;
|
||||
using ZB.MOM.WW.OtOpcUa.Client.Shared.Helpers;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Client.CLI.Commands;
|
||||
|
||||
[Command("write", Description = "Write a value to a node")]
|
||||
public class WriteCommand : CommandBase
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates the write command used to update a node from the terminal.
|
||||
/// </summary>
|
||||
/// <param name="factory">The factory that creates the shared client service for the command run.</param>
|
||||
public WriteCommand(IOpcUaClientServiceFactory factory) : base(factory)
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the node whose value should be updated.
|
||||
/// </summary>
|
||||
[CommandOption("node", 'n', Description = "Node ID (e.g. ns=2;s=MyNode)", IsRequired = true)]
|
||||
public string NodeId { get; init; } = default!;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the raw operator-entered value that will be converted to the node's runtime type before writing.
|
||||
/// </summary>
|
||||
[CommandOption("value", 'v', Description = "Value to write", IsRequired = true)]
|
||||
public string Value { get; init; } = default!;
|
||||
|
||||
/// <summary>
|
||||
/// Connects to the server, converts the supplied value to the node's current data type, and issues the write.
|
||||
/// </summary>
|
||||
/// <param name="console">The CLI console used for output and cancellation handling.</param>
|
||||
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();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
using Opc.Ua;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.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;
|
||||
}
|
||||
}
|
||||
15
src/Client/ZB.MOM.WW.OtOpcUa.Client.CLI/Program.cs
Normal file
15
src/Client/ZB.MOM.WW.OtOpcUa.Client.CLI/Program.cs
Normal file
@@ -0,0 +1,15 @@
|
||||
using CliFx;
|
||||
using ZB.MOM.WW.OtOpcUa.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("otopcua-cli")
|
||||
.SetDescription("OtOpcUa CLI - command-line client for the OtOpcUa 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.OtOpcUa.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.OtOpcUa.Client.Shared\ZB.MOM.WW.OtOpcUa.Client.Shared.csproj"/>
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,73 @@
|
||||
using Opc.Ua;
|
||||
using Opc.Ua.Configuration;
|
||||
using Serilog;
|
||||
using ZB.MOM.WW.OtOpcUa.Client.Shared.Models;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.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 = "OtOpcUaClient",
|
||||
ApplicationUri = "urn:localhost:OtOpcUaClient",
|
||||
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 != SecurityMode.None)
|
||||
{
|
||||
var app = new ApplicationInstance
|
||||
{
|
||||
ApplicationName = "OtOpcUaClient",
|
||||
ApplicationType = ApplicationType.Client,
|
||||
ApplicationConfiguration = config
|
||||
};
|
||||
await app.CheckApplicationInstanceCertificatesAsync(false, 2048);
|
||||
}
|
||||
|
||||
Logger.Debug("ApplicationConfiguration created for {EndpointUrl}", settings.EndpointUrl);
|
||||
return config;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
using Opc.Ua;
|
||||
using Opc.Ua.Client;
|
||||
using Serilog;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.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,279 @@
|
||||
using Opc.Ua;
|
||||
using Opc.Ua.Client;
|
||||
using Serilog;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.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;
|
||||
|
||||
/// <summary>
|
||||
/// Wraps a live OPC UA session so the shared client can issue runtime operations through a testable adapter surface.
|
||||
/// </summary>
|
||||
/// <param name="session">The connected OPC UA session used for browsing, reads, writes, history, and subscriptions.</param>
|
||||
public DefaultSessionAdapter(Session session)
|
||||
{
|
||||
_session = session;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool Connected => _session.Connected;
|
||||
|
||||
/// <inheritdoc />
|
||||
public string SessionId => _session.SessionId?.ToString() ?? string.Empty;
|
||||
|
||||
/// <inheritdoc />
|
||||
public string SessionName => _session.SessionName ?? string.Empty;
|
||||
|
||||
/// <inheritdoc />
|
||||
public string EndpointUrl => _session.Endpoint?.EndpointUrl ?? string.Empty;
|
||||
|
||||
/// <inheritdoc />
|
||||
public string ServerName => _session.Endpoint?.Server?.ApplicationName?.Text ?? string.Empty;
|
||||
|
||||
/// <inheritdoc />
|
||||
public string SecurityMode => _session.Endpoint?.SecurityMode.ToString() ?? string.Empty;
|
||||
|
||||
/// <inheritdoc />
|
||||
public string SecurityPolicyUri => _session.Endpoint?.SecurityPolicyUri ?? string.Empty;
|
||||
|
||||
/// <inheritdoc />
|
||||
public NamespaceTable NamespaceUris => _session.NamespaceUris;
|
||||
|
||||
/// <inheritdoc />
|
||||
public void RegisterKeepAliveHandler(Action<bool> callback)
|
||||
{
|
||||
_session.KeepAlive += (_, e) =>
|
||||
{
|
||||
var isGood = e.Status == null || ServiceResult.IsGood(e.Status);
|
||||
callback(isGood);
|
||||
};
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<DataValue> ReadValueAsync(NodeId nodeId, CancellationToken ct)
|
||||
{
|
||||
return await _session.ReadValueAsync(nodeId, ct);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
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];
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
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 ?? []);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<(byte[]? ContinuationPoint, ReferenceDescriptionCollection References)> BrowseNextAsync(
|
||||
byte[] continuationPoint, CancellationToken ct)
|
||||
{
|
||||
var (_, nextCp, nextRefs) = await _session.BrowseNextAsync(null, false, continuationPoint);
|
||||
return (nextCp, nextRefs ?? []);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
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;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
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;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
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 = [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;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
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);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task CloseAsync(CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (_session.Connected) _session.Close();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Logger.Warning(ex, "Error closing session");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Releases the wrapped OPC UA session when the shared client shuts down or swaps endpoints during failover.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
try
|
||||
{
|
||||
if (_session.Connected) _session.Close();
|
||||
}
|
||||
catch
|
||||
{
|
||||
}
|
||||
|
||||
_session.Dispose();
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<IList<object>?> CallMethodAsync(NodeId objectId, NodeId methodId, object[] inputArguments,
|
||||
CancellationToken ct = default)
|
||||
{
|
||||
var result = await _session.CallAsync(
|
||||
null,
|
||||
new CallMethodRequestCollection
|
||||
{
|
||||
new()
|
||||
{
|
||||
ObjectId = objectId,
|
||||
MethodId = methodId,
|
||||
InputArguments = new VariantCollection(inputArguments.Select(a => new Variant(a)))
|
||||
}
|
||||
},
|
||||
ct);
|
||||
|
||||
var callResult = result.Results[0];
|
||||
if (StatusCode.IsBad(callResult.StatusCode))
|
||||
throw new ServiceResultException(callResult.StatusCode);
|
||||
|
||||
return callResult.OutputArguments?.Select(v => v.Value).ToList();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
using Opc.Ua;
|
||||
using Opc.Ua.Client;
|
||||
using Serilog;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.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,133 @@
|
||||
using Opc.Ua;
|
||||
using Opc.Ua.Client;
|
||||
using Serilog;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.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 Dictionary<uint, MonitoredItem> _monitoredItems = new();
|
||||
private readonly Subscription _subscription;
|
||||
|
||||
/// <summary>
|
||||
/// Wraps a live OPC UA subscription so client code can manage monitored items through a testable abstraction.
|
||||
/// </summary>
|
||||
/// <param name="subscription">The underlying OPC UA subscription that owns monitored items for this client workflow.</param>
|
||||
public DefaultSubscriptionAdapter(Subscription subscription)
|
||||
{
|
||||
_subscription = subscription;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public uint SubscriptionId => _subscription.Id;
|
||||
|
||||
/// <inheritdoc />
|
||||
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;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
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);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
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;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task ConditionRefreshAsync(CancellationToken ct)
|
||||
{
|
||||
await _subscription.ConditionRefreshAsync(ct);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task DeleteAsync(CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
await _subscription.DeleteAsync(true);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Logger.Warning(ex, "Error deleting subscription");
|
||||
}
|
||||
|
||||
_monitoredItems.Clear();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Releases the wrapped OPC UA subscription and clears tracked monitored items held by the adapter.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
try
|
||||
{
|
||||
_subscription.Delete(true);
|
||||
}
|
||||
catch
|
||||
{
|
||||
}
|
||||
|
||||
_monitoredItems.Clear();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
using Opc.Ua;
|
||||
using ZB.MOM.WW.OtOpcUa.Client.Shared.Models;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.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,16 @@
|
||||
using Opc.Ua;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.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,140 @@
|
||||
using Opc.Ua;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Client.Shared.Adapters;
|
||||
|
||||
/// <summary>
|
||||
/// Abstracts the OPC UA session for read, write, browse, history, and subscription operations.
|
||||
/// </summary>
|
||||
internal interface ISessionAdapter : IDisposable
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets a value indicating whether the underlying OPC UA session is currently usable for client operations.
|
||||
/// </summary>
|
||||
bool Connected { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the server-assigned session identifier for diagnostics and failover reporting.
|
||||
/// </summary>
|
||||
string SessionId { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the friendly session name presented to the OPC UA server.
|
||||
/// </summary>
|
||||
string SessionName { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the active endpoint URL that this adapter is connected to.
|
||||
/// </summary>
|
||||
string EndpointUrl { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the server name reported by the connected OPC UA endpoint.
|
||||
/// </summary>
|
||||
string ServerName { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the negotiated OPC UA message security mode for the session.
|
||||
/// </summary>
|
||||
string SecurityMode { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the negotiated OPC UA security policy URI for the session.
|
||||
/// </summary>
|
||||
string SecurityPolicyUri { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the namespace table used to resolve expanded node identifiers returned by browse operations.
|
||||
/// </summary>
|
||||
NamespaceTable NamespaceUris { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Registers a keep-alive callback. The callback receives true when the session is healthy, false on failure.
|
||||
/// </summary>
|
||||
/// <param name="callback">The callback used by higher-level clients to trigger reconnect or failover behavior.</param>
|
||||
void RegisterKeepAliveHandler(Action<bool> callback);
|
||||
|
||||
/// <summary>
|
||||
/// Reads the current value for a node from the connected OPC UA server.
|
||||
/// </summary>
|
||||
/// <param name="nodeId">The node whose current runtime value should be read.</param>
|
||||
/// <param name="ct">The cancellation token that aborts the server read if the client cancels the request.</param>
|
||||
Task<DataValue> ReadValueAsync(NodeId nodeId, CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// Writes a typed value to a node on the connected OPC UA server.
|
||||
/// </summary>
|
||||
/// <param name="nodeId">The node whose value should be updated.</param>
|
||||
/// <param name="value">The typed OPC UA data value to write to the server.</param>
|
||||
/// <param name="ct">The cancellation token that aborts the write if the client cancels the request.</param>
|
||||
Task<StatusCode> WriteValueAsync(NodeId nodeId, DataValue value, CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// Browses forward hierarchical references from the given node.
|
||||
/// Returns (continuationPoint, references).
|
||||
/// </summary>
|
||||
/// <param name="nodeId">The starting node for the hierarchical browse.</param>
|
||||
/// <param name="nodeClassMask">The node classes that should be returned to the caller.</param>
|
||||
/// <param name="ct">The cancellation token that aborts the browse request.</param>
|
||||
Task<(byte[]? ContinuationPoint, ReferenceDescriptionCollection References)> BrowseAsync(
|
||||
NodeId nodeId, uint nodeClassMask = 0, CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// Continues a browse from a continuation point.
|
||||
/// </summary>
|
||||
/// <param name="continuationPoint">The continuation token returned by a prior browse result page.</param>
|
||||
/// <param name="ct">The cancellation token that aborts the browse-next request.</param>
|
||||
Task<(byte[]? ContinuationPoint, ReferenceDescriptionCollection References)> BrowseNextAsync(
|
||||
byte[] continuationPoint, CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// Checks whether a node has any forward hierarchical child references.
|
||||
/// </summary>
|
||||
/// <param name="nodeId">The node to inspect for child objects or variables.</param>
|
||||
/// <param name="ct">The cancellation token that aborts the child lookup.</param>
|
||||
Task<bool> HasChildrenAsync(NodeId nodeId, CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// Reads raw historical data.
|
||||
/// </summary>
|
||||
/// <param name="nodeId">The historized node whose raw samples should be retrieved.</param>
|
||||
/// <param name="startTime">The inclusive start of the requested history window.</param>
|
||||
/// <param name="endTime">The inclusive end of the requested history window.</param>
|
||||
/// <param name="maxValues">The maximum number of raw samples to return to the client.</param>
|
||||
/// <param name="ct">The cancellation token that aborts the history read.</param>
|
||||
Task<IReadOnlyList<DataValue>> HistoryReadRawAsync(NodeId nodeId, DateTime startTime, DateTime endTime,
|
||||
int maxValues, CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// Reads processed/aggregate historical data.
|
||||
/// </summary>
|
||||
/// <param name="nodeId">The historized node whose processed values should be retrieved.</param>
|
||||
/// <param name="startTime">The inclusive start of the requested processed-history window.</param>
|
||||
/// <param name="endTime">The inclusive end of the requested processed-history window.</param>
|
||||
/// <param name="aggregateId">The OPC UA aggregate function to evaluate over the history window.</param>
|
||||
/// <param name="intervalMs">The processing interval, in milliseconds, for each aggregate bucket.</param>
|
||||
/// <param name="ct">The cancellation token that aborts the aggregate history read.</param>
|
||||
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>
|
||||
/// <param name="publishingIntervalMs">The requested publishing interval for monitored items on the new subscription.</param>
|
||||
/// <param name="ct">The cancellation token that aborts subscription creation.</param>
|
||||
Task<ISubscriptionAdapter> CreateSubscriptionAsync(int publishingIntervalMs, CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// Calls an OPC UA method node with the provided input arguments.
|
||||
/// </summary>
|
||||
/// <param name="objectId">The object node that owns the target method.</param>
|
||||
/// <param name="methodId">The method node to invoke.</param>
|
||||
/// <param name="inputArguments">The ordered input arguments supplied to the server method call.</param>
|
||||
/// <param name="ct">The cancellation token that aborts the method invocation.</param>
|
||||
Task<IList<object>?> CallMethodAsync(NodeId objectId, NodeId methodId, object[] inputArguments, CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// Closes the underlying session gracefully before the adapter is disposed or replaced during failover.
|
||||
/// </summary>
|
||||
/// <param name="ct">The cancellation token that aborts the close request.</param>
|
||||
Task CloseAsync(CancellationToken ct = default);
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
using Opc.Ua;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.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,56 @@
|
||||
using Opc.Ua;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Client.Shared.Adapters;
|
||||
|
||||
/// <summary>
|
||||
/// Abstracts OPC UA subscription and monitored item management.
|
||||
/// </summary>
|
||||
internal interface ISubscriptionAdapter : IDisposable
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the server-assigned subscription identifier for diagnostics and reconnect workflows.
|
||||
/// </summary>
|
||||
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>
|
||||
/// <param name="clientHandle">The client handle returned when the monitored item was created.</param>
|
||||
/// <param name="ct">The cancellation token that aborts the monitored-item removal.</param>
|
||||
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>
|
||||
/// <param name="ct">The cancellation token that aborts the condition refresh request.</param>
|
||||
Task ConditionRefreshAsync(CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// Removes all monitored items and deletes the subscription.
|
||||
/// </summary>
|
||||
/// <param name="ct">The cancellation token that aborts subscription deletion.</param>
|
||||
Task DeleteAsync(CancellationToken ct = default);
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
namespace ZB.MOM.WW.OtOpcUa.Client.Shared;
|
||||
|
||||
/// <summary>
|
||||
/// Resolves the canonical under-LocalAppData folder for the shared OPC UA client's PKI
|
||||
/// store + persisted settings. Renamed from <c>LmxOpcUaClient</c> to <c>OtOpcUaClient</c>
|
||||
/// in task #208; a one-shot migration shim moves a pre-rename folder in place on first
|
||||
/// resolution so existing developer boxes keep their trusted server certs + saved
|
||||
/// connection settings on upgrade.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Thread-safe: the rename uses <see cref="Directory.Move"/> which is atomic on NTFS
|
||||
/// within the same volume. The lock guarantees the migration runs at most once per
|
||||
/// process even under concurrent first-touch from CLI + UI.
|
||||
/// </remarks>
|
||||
public static class ClientStoragePaths
|
||||
{
|
||||
/// <summary>Canonical client folder name. Post-#208.</summary>
|
||||
public const string CanonicalFolderName = "OtOpcUaClient";
|
||||
|
||||
/// <summary>Pre-#208 folder name. Used only by the migration shim.</summary>
|
||||
public const string LegacyFolderName = "LmxOpcUaClient";
|
||||
|
||||
private static readonly Lock _migrationLock = new();
|
||||
private static bool _migrationChecked;
|
||||
|
||||
/// <summary>
|
||||
/// Absolute path to the client's top-level folder under LocalApplicationData. Runs the
|
||||
/// one-shot legacy-folder migration before returning so callers that depend on this
|
||||
/// path (PKI store, settings file) find their existing state at the canonical name.
|
||||
/// </summary>
|
||||
public static string GetRoot()
|
||||
{
|
||||
var localAppData = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
|
||||
var canonical = Path.Combine(localAppData, CanonicalFolderName);
|
||||
MigrateLegacyFolderIfNeeded(localAppData, canonical);
|
||||
return canonical;
|
||||
}
|
||||
|
||||
/// <summary>Subfolder for the application's PKI store — used by both CLI + UI.</summary>
|
||||
public static string GetPkiPath() => Path.Combine(GetRoot(), "pki");
|
||||
|
||||
/// <summary>
|
||||
/// Expose the migration probe for tests + for callers that want to check whether the
|
||||
/// legacy folder still exists without forcing the rename. Returns true when a legacy
|
||||
/// folder existed + was moved to canonical, false when no migration was needed or
|
||||
/// canonical was already present.
|
||||
/// </summary>
|
||||
public static bool TryRunLegacyMigration()
|
||||
{
|
||||
var localAppData = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
|
||||
var canonical = Path.Combine(localAppData, CanonicalFolderName);
|
||||
return MigrateLegacyFolderIfNeeded(localAppData, canonical);
|
||||
}
|
||||
|
||||
private static bool MigrateLegacyFolderIfNeeded(string localAppData, string canonical)
|
||||
{
|
||||
// Fast-path out of the lock when the migration has already been attempted this process
|
||||
// — saves the IO on every subsequent call, + the migration is idempotent within the
|
||||
// same process anyway.
|
||||
if (_migrationChecked) return false;
|
||||
|
||||
lock (_migrationLock)
|
||||
{
|
||||
if (_migrationChecked) return false;
|
||||
_migrationChecked = true;
|
||||
|
||||
var legacy = Path.Combine(localAppData, LegacyFolderName);
|
||||
|
||||
// Only migrate when the legacy folder is present + canonical isn't. Either of the
|
||||
// other three combinations (neither / only-canonical / both) means migration
|
||||
// should NOT run: no-op fresh install, already-migrated, or manual state the
|
||||
// developer has set up — don't clobber.
|
||||
if (!Directory.Exists(legacy)) return false;
|
||||
if (Directory.Exists(canonical)) return false;
|
||||
|
||||
try
|
||||
{
|
||||
Directory.Move(legacy, canonical);
|
||||
return true;
|
||||
}
|
||||
catch (IOException)
|
||||
{
|
||||
// Concurrent another-process-moved-it or volume-boundary or permissions — leave
|
||||
// the legacy folder alone; callers that need it can either re-run migration
|
||||
// manually or point CertificateStorePath explicitly.
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
using Opc.Ua;
|
||||
using ZB.MOM.WW.OtOpcUa.Client.Shared.Models;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.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,
|
||||
AggregateType.StandardDeviation => ObjectIds.AggregateFunction_StandardDeviationPopulation,
|
||||
_ => throw new ArgumentOutOfRangeException(nameof(aggregate), aggregate, "Unknown AggregateType value.")
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
namespace ZB.MOM.WW.OtOpcUa.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 [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 [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.OtOpcUa.Client.Shared.Models;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.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.OtOpcUa.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
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
using Opc.Ua;
|
||||
using ZB.MOM.WW.OtOpcUa.Client.Shared.Models;
|
||||
using BrowseResult = ZB.MOM.WW.OtOpcUa.Client.Shared.Models.BrowseResult;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Client.Shared;
|
||||
|
||||
/// <summary>
|
||||
/// Shared OPC UA client service contract for CLI and UI consumers.
|
||||
/// </summary>
|
||||
public interface IOpcUaClientService : IDisposable
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets a value indicating whether the client is currently connected to an OPC UA endpoint.
|
||||
/// </summary>
|
||||
bool IsConnected { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the current connection metadata shown to CLI and UI operators after a successful connect or failover.
|
||||
/// </summary>
|
||||
ConnectionInfo? CurrentConnectionInfo { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Connects the client to the configured OPC UA endpoint set, including failover-capable endpoints when provided.
|
||||
/// </summary>
|
||||
/// <param name="settings">The endpoint, security, and authentication settings used to establish the session.</param>
|
||||
/// <param name="ct">The cancellation token that aborts the connect workflow.</param>
|
||||
Task<ConnectionInfo> ConnectAsync(ConnectionSettings settings, CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// Disconnects from the active OPC UA endpoint and tears down subscriptions owned by the client.
|
||||
/// </summary>
|
||||
/// <param name="ct">The cancellation token that aborts disconnect cleanup.</param>
|
||||
Task DisconnectAsync(CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// Reads the current value of an OPC UA node.
|
||||
/// </summary>
|
||||
/// <param name="nodeId">The node whose value should be retrieved.</param>
|
||||
/// <param name="ct">The cancellation token that aborts the read request.</param>
|
||||
Task<DataValue> ReadValueAsync(NodeId nodeId, CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// Writes an operator-supplied value to an OPC UA node after applying client-side type conversion when needed.
|
||||
/// </summary>
|
||||
/// <param name="nodeId">The node whose value should be updated.</param>
|
||||
/// <param name="value">The raw value supplied by the CLI or UI workflow.</param>
|
||||
/// <param name="ct">The cancellation token that aborts the write request.</param>
|
||||
Task<StatusCode> WriteValueAsync(NodeId nodeId, object value, CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// Browses the children of a node so the client can build an address-space tree for operators.
|
||||
/// </summary>
|
||||
/// <param name="parentNodeId">The node to browse, or <see cref="ObjectIds.ObjectsFolder"/> when omitted.</param>
|
||||
/// <param name="ct">The cancellation token that aborts the browse request.</param>
|
||||
Task<IReadOnlyList<BrowseResult>> BrowseAsync(NodeId? parentNodeId = null, CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// Subscribes to live data changes for a node.
|
||||
/// </summary>
|
||||
/// <param name="nodeId">The node whose value changes should be monitored.</param>
|
||||
/// <param name="intervalMs">The monitored-item sampling and publishing interval in milliseconds.</param>
|
||||
/// <param name="ct">The cancellation token that aborts subscription creation.</param>
|
||||
Task SubscribeAsync(NodeId nodeId, int intervalMs = 1000, CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// Removes a previously created live-data subscription for a node.
|
||||
/// </summary>
|
||||
/// <param name="nodeId">The node whose live-data subscription should be removed.</param>
|
||||
/// <param name="ct">The cancellation token that aborts the unsubscribe request.</param>
|
||||
Task UnsubscribeAsync(NodeId nodeId, CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// Subscribes to OPC UA alarm and condition events for a source node or the server root.
|
||||
/// </summary>
|
||||
/// <param name="sourceNodeId">The event source to monitor, or the server object when omitted.</param>
|
||||
/// <param name="intervalMs">The publishing interval in milliseconds for the alarm subscription.</param>
|
||||
/// <param name="ct">The cancellation token that aborts alarm subscription creation.</param>
|
||||
Task SubscribeAlarmsAsync(NodeId? sourceNodeId = null, int intervalMs = 1000, CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// Removes the active alarm subscription.
|
||||
/// </summary>
|
||||
/// <param name="ct">The cancellation token that aborts alarm subscription cleanup.</param>
|
||||
Task UnsubscribeAlarmsAsync(CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// Requests retained alarm conditions again so a client can repopulate its alarm list after reconnecting.
|
||||
/// </summary>
|
||||
/// <param name="ct">The cancellation token that aborts the condition refresh request.</param>
|
||||
Task RequestConditionRefreshAsync(CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// Acknowledges an active condition using the event identifier returned by an alarm notification.
|
||||
/// </summary>
|
||||
/// <param name="conditionNodeId">The condition node associated with the alarm event being acknowledged.</param>
|
||||
/// <param name="eventId">The event identifier returned by the OPC UA server for the alarm event.</param>
|
||||
/// <param name="comment">The operator acknowledgment comment to write with the method call.</param>
|
||||
/// <param name="ct">The cancellation token that aborts the acknowledgment request.</param>
|
||||
Task<StatusCode> AcknowledgeAlarmAsync(string conditionNodeId, byte[] eventId, string comment, CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// Reads raw historical samples for a historized node.
|
||||
/// </summary>
|
||||
/// <param name="nodeId">The historized node whose samples should be read.</param>
|
||||
/// <param name="startTime">The inclusive start of the requested history range.</param>
|
||||
/// <param name="endTime">The inclusive end of the requested history range.</param>
|
||||
/// <param name="maxValues">The maximum number of raw values to return.</param>
|
||||
/// <param name="ct">The cancellation token that aborts the history read.</param>
|
||||
Task<IReadOnlyList<DataValue>> HistoryReadRawAsync(NodeId nodeId, DateTime startTime, DateTime endTime,
|
||||
int maxValues = 1000, CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// Reads aggregate historical values for a historized node using an OPC UA aggregate function.
|
||||
/// </summary>
|
||||
/// <param name="nodeId">The historized node whose processed values should be read.</param>
|
||||
/// <param name="startTime">The inclusive start of the requested processed-history range.</param>
|
||||
/// <param name="endTime">The inclusive end of the requested processed-history range.</param>
|
||||
/// <param name="aggregate">The aggregate function the operator selected for processed history.</param>
|
||||
/// <param name="intervalMs">The processing interval, in milliseconds, for each aggregate bucket.</param>
|
||||
/// <param name="ct">The cancellation token that aborts the processed history request.</param>
|
||||
Task<IReadOnlyList<DataValue>> HistoryReadAggregateAsync(NodeId nodeId, DateTime startTime, DateTime endTime,
|
||||
AggregateType aggregate, double intervalMs = 3600000, CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// Reads redundancy status data such as redundancy mode, service level, and partner endpoint URIs.
|
||||
/// </summary>
|
||||
/// <param name="ct">The cancellation token that aborts redundancy inspection.</param>
|
||||
Task<RedundancyInfo> GetRedundancyInfoAsync(CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// Raised when a subscribed node produces a new live data value.
|
||||
/// </summary>
|
||||
event EventHandler<DataChangedEventArgs>? DataChanged;
|
||||
|
||||
/// <summary>
|
||||
/// Raised when an alarm or condition event is received from the server.
|
||||
/// </summary>
|
||||
event EventHandler<AlarmEventArgs>? AlarmEvent;
|
||||
|
||||
/// <summary>
|
||||
/// Raised when the client changes connection state during connect, disconnect, or failover.
|
||||
/// </summary>
|
||||
event EventHandler<ConnectionStateChangedEventArgs>? ConnectionStateChanged;
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
namespace ZB.MOM.WW.OtOpcUa.Client.Shared;
|
||||
|
||||
/// <summary>
|
||||
/// Factory for creating <see cref="IOpcUaClientService" /> instances.
|
||||
/// </summary>
|
||||
public interface IOpcUaClientServiceFactory
|
||||
{
|
||||
IOpcUaClientService Create();
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
namespace ZB.MOM.WW.OtOpcUa.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,
|
||||
|
||||
/// <summary>Population standard deviation of values in the interval.</summary>
|
||||
StandardDeviation
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
namespace ZB.MOM.WW.OtOpcUa.Client.Shared.Models;
|
||||
|
||||
/// <summary>
|
||||
/// Event data for an alarm or condition notification from the OPC UA server.
|
||||
/// </summary>
|
||||
public sealed class AlarmEventArgs : EventArgs
|
||||
{
|
||||
public AlarmEventArgs(
|
||||
string sourceName,
|
||||
string conditionName,
|
||||
ushort severity,
|
||||
string message,
|
||||
bool retain,
|
||||
bool activeState,
|
||||
bool ackedState,
|
||||
DateTime time,
|
||||
byte[]? eventId = null,
|
||||
string? conditionNodeId = null,
|
||||
string? operatorComment = null,
|
||||
DateTime? originalRaiseTimestampUtc = null,
|
||||
string? alarmCategory = null)
|
||||
{
|
||||
SourceName = sourceName;
|
||||
ConditionName = conditionName;
|
||||
Severity = severity;
|
||||
Message = message;
|
||||
Retain = retain;
|
||||
ActiveState = activeState;
|
||||
AckedState = ackedState;
|
||||
Time = time;
|
||||
EventId = eventId;
|
||||
ConditionNodeId = conditionNodeId;
|
||||
OperatorComment = operatorComment;
|
||||
OriginalRaiseTimestampUtc = originalRaiseTimestampUtc;
|
||||
AlarmCategory = alarmCategory;
|
||||
}
|
||||
|
||||
/// <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; }
|
||||
|
||||
/// <summary>The EventId used for alarm acknowledgment.</summary>
|
||||
public byte[]? EventId { get; }
|
||||
|
||||
/// <summary>The NodeId of the condition instance (SourceNode), used for acknowledgment.</summary>
|
||||
public string? ConditionNodeId { get; }
|
||||
|
||||
/// <summary>
|
||||
/// PR E.7 — Operator-supplied comment recorded by the upstream alarm system on
|
||||
/// Acknowledge transitions. Null on raise / clear, or when the upstream path
|
||||
/// can't surface the comment (sub-attribute fallback path collapses comments
|
||||
/// into a single string write).
|
||||
/// </summary>
|
||||
public string? OperatorComment { get; }
|
||||
|
||||
/// <summary>
|
||||
/// PR E.7 — When the alarm originally entered the active state. Preserved
|
||||
/// across Acknowledge transitions so OPC UA Part 9 conditions keep the
|
||||
/// original raise time. Null when the upstream path doesn't surface it.
|
||||
/// </summary>
|
||||
public DateTime? OriginalRaiseTimestampUtc { get; }
|
||||
|
||||
/// <summary>
|
||||
/// PR E.7 — Upstream alarm taxonomy bucket (e.g. <c>Process</c> /
|
||||
/// <c>Safety</c> / <c>Diagnostics</c>). Null when not surfaced.
|
||||
/// </summary>
|
||||
public string? AlarmCategory { get; }
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
namespace ZB.MOM.WW.OtOpcUa.Client.Shared.Models;
|
||||
|
||||
/// <summary>
|
||||
/// Represents a single node in the browse result set.
|
||||
/// </summary>
|
||||
public sealed class BrowseResult
|
||||
{
|
||||
public BrowseResult(string nodeId, string displayName, string nodeClass, bool hasChildren)
|
||||
{
|
||||
NodeId = nodeId;
|
||||
DisplayName = displayName;
|
||||
NodeClass = nodeClass;
|
||||
HasChildren = hasChildren;
|
||||
}
|
||||
|
||||
/// <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; }
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
namespace ZB.MOM.WW.OtOpcUa.Client.Shared.Models;
|
||||
|
||||
/// <summary>
|
||||
/// Information about the current OPC UA session.
|
||||
/// </summary>
|
||||
public sealed class ConnectionInfo
|
||||
{
|
||||
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;
|
||||
}
|
||||
|
||||
/// <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; }
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
namespace ZB.MOM.WW.OtOpcUa.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
|
||||
/// resolved via <see cref="ClientStoragePaths"/> so the one-shot legacy-folder migration
|
||||
/// runs before the path is returned.
|
||||
/// </summary>
|
||||
public string CertificateStorePath { get; set; } = ClientStoragePaths.GetPkiPath();
|
||||
|
||||
/// <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.OtOpcUa.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.OtOpcUa.Client.Shared.Models;
|
||||
|
||||
/// <summary>
|
||||
/// Event data raised when the client connection state changes.
|
||||
/// </summary>
|
||||
public sealed class ConnectionStateChangedEventArgs : EventArgs
|
||||
{
|
||||
public ConnectionStateChangedEventArgs(ConnectionState oldState, ConnectionState newState, string endpointUrl)
|
||||
{
|
||||
OldState = oldState;
|
||||
NewState = newState;
|
||||
EndpointUrl = endpointUrl;
|
||||
}
|
||||
|
||||
/// <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; }
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
using Opc.Ua;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Client.Shared.Models;
|
||||
|
||||
/// <summary>
|
||||
/// Event data for a monitored data value change.
|
||||
/// </summary>
|
||||
public sealed class DataChangedEventArgs : EventArgs
|
||||
{
|
||||
public DataChangedEventArgs(string nodeId, DataValue value)
|
||||
{
|
||||
NodeId = nodeId;
|
||||
Value = value;
|
||||
}
|
||||
|
||||
/// <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; }
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
namespace ZB.MOM.WW.OtOpcUa.Client.Shared.Models;
|
||||
|
||||
/// <summary>
|
||||
/// Redundancy information read from the server.
|
||||
/// </summary>
|
||||
public sealed class RedundancyInfo
|
||||
{
|
||||
public RedundancyInfo(string mode, byte serviceLevel, string[] serverUris, string applicationUri)
|
||||
{
|
||||
Mode = mode;
|
||||
ServiceLevel = serviceLevel;
|
||||
ServerUris = serverUris;
|
||||
ApplicationUri = applicationUri;
|
||||
}
|
||||
|
||||
/// <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; }
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
namespace ZB.MOM.WW.OtOpcUa.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
|
||||
}
|
||||
698
src/Client/ZB.MOM.WW.OtOpcUa.Client.Shared/OpcUaClientService.cs
Normal file
698
src/Client/ZB.MOM.WW.OtOpcUa.Client.Shared/OpcUaClientService.cs
Normal file
@@ -0,0 +1,698 @@
|
||||
using System.Text;
|
||||
using Opc.Ua;
|
||||
using Serilog;
|
||||
using ZB.MOM.WW.OtOpcUa.Client.Shared.Adapters;
|
||||
using ZB.MOM.WW.OtOpcUa.Client.Shared.Helpers;
|
||||
using ZB.MOM.WW.OtOpcUa.Client.Shared.Models;
|
||||
using BrowseResult = ZB.MOM.WW.OtOpcUa.Client.Shared.Models.BrowseResult;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.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>();
|
||||
|
||||
// Track active data subscriptions for replay after failover
|
||||
private readonly Dictionary<string, (NodeId NodeId, int IntervalMs, uint Handle)> _activeDataSubscriptions = new();
|
||||
|
||||
private readonly IApplicationConfigurationFactory _configFactory;
|
||||
private readonly IEndpointDiscovery _endpointDiscovery;
|
||||
|
||||
private readonly ISessionFactory _sessionFactory;
|
||||
|
||||
// Track alarm subscription state for replay after failover
|
||||
private (NodeId? SourceNodeId, int IntervalMs)? _activeAlarmSubscription;
|
||||
private ISubscriptionAdapter? _alarmSubscription;
|
||||
private string[]? _allEndpointUrls;
|
||||
private int _currentEndpointIndex;
|
||||
private ISubscriptionAdapter? _dataSubscription;
|
||||
private bool _disposed;
|
||||
|
||||
private ISessionAdapter? _session;
|
||||
private ConnectionSettings? _settings;
|
||||
private ConnectionState _state = ConnectionState.Disconnected;
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new OpcUaClientService with the specified adapter dependencies.
|
||||
/// </summary>
|
||||
/// <param name="configFactory">Builds the application configuration and certificate settings for the client session.</param>
|
||||
/// <param name="endpointDiscovery">Selects the best matching endpoint for the requested URL and security mode.</param>
|
||||
/// <param name="sessionFactory">Creates the underlying OPC UA session used for runtime operations.</param>
|
||||
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())
|
||||
{
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public event EventHandler<DataChangedEventArgs>? DataChanged;
|
||||
|
||||
/// <inheritdoc />
|
||||
public event EventHandler<AlarmEventArgs>? AlarmEvent;
|
||||
|
||||
/// <inheritdoc />
|
||||
public event EventHandler<ConnectionStateChangedEventArgs>? ConnectionStateChanged;
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool IsConnected => _state == ConnectionState.Connected && _session?.Connected == true;
|
||||
|
||||
/// <inheritdoc />
|
||||
public ConnectionInfo? CurrentConnectionInfo { get; private set; }
|
||||
|
||||
/// <inheritdoc />
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<DataValue> ReadValueAsync(NodeId nodeId, CancellationToken ct = default)
|
||||
{
|
||||
ThrowIfDisposed();
|
||||
ThrowIfNotConnected();
|
||||
return await _session!.ReadValueAsync(nodeId, ct);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
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
|
||||
var 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);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<IReadOnlyList<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<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 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;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
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);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
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);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
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);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
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");
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
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");
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<StatusCode> AcknowledgeAlarmAsync(string conditionNodeId, byte[] eventId, string comment,
|
||||
CancellationToken ct = default)
|
||||
{
|
||||
ThrowIfDisposed();
|
||||
ThrowIfNotConnected();
|
||||
|
||||
// The Acknowledge method lives on the .Condition child node, not the source node itself
|
||||
var conditionObjId = conditionNodeId.EndsWith(".Condition")
|
||||
? NodeId.Parse(conditionNodeId)
|
||||
: NodeId.Parse(conditionNodeId + ".Condition");
|
||||
var acknowledgeMethodId = MethodIds.AcknowledgeableConditionType_Acknowledge;
|
||||
|
||||
await _session!.CallMethodAsync(
|
||||
conditionObjId,
|
||||
acknowledgeMethodId,
|
||||
[eventId, new LocalizedText(comment)],
|
||||
ct);
|
||||
|
||||
Logger.Debug("Acknowledged alarm on {ConditionId}", conditionNodeId);
|
||||
return StatusCodes.Good;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
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);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
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);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
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 = [];
|
||||
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
|
||||
}
|
||||
|
||||
var 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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Releases the current session and any active monitored-item subscriptions held by the client service.
|
||||
/// </summary>
|
||||
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);
|
||||
|
||||
var identity = settings.Username != null
|
||||
? new UserIdentity(settings.Username, Encoding.UTF8.GetBytes(settings.Password ?? ""))
|
||||
: new UserIdentity();
|
||||
|
||||
var sessionTimeoutMs = (uint)(settings.SessionTimeoutSeconds * 1000);
|
||||
return await _sessionFactory.CreateSessionAsync(config, endpoint, "OtOpcUaClient", 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 (var 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 eventId = fields.Count > 0 ? fields[0].Value as byte[] : null;
|
||||
var sourceName = fields.Count > 2 ? fields[2].Value as string ?? string.Empty : string.Empty;
|
||||
var time = DateTime.MinValue;
|
||||
if (fields.Count > 3 && fields[3].Value != null)
|
||||
{
|
||||
if (fields[3].Value is DateTime dt)
|
||||
time = dt;
|
||||
else if (DateTime.TryParse(fields[3].Value.ToString(), out var parsed))
|
||||
time = parsed;
|
||||
}
|
||||
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 && ParseBool(fields[7].Value);
|
||||
var conditionNodeId = fields.Count > 12 ? fields[12].Value?.ToString() : null;
|
||||
|
||||
// Try standard OPC UA ActiveState/AckedState fields first
|
||||
bool? ackedField = fields.Count > 8 && fields[8].Value != null ? ParseBool(fields[8].Value) : null;
|
||||
bool? activeField = fields.Count > 9 && fields[9].Value != null ? ParseBool(fields[9].Value) : null;
|
||||
|
||||
var ackedState = ackedField ?? false;
|
||||
var activeState = activeField ?? false;
|
||||
|
||||
// Fallback: read InAlarm/Acked from condition node Galaxy attributes
|
||||
// when the server doesn't populate standard event fields.
|
||||
// Must run on a background thread to avoid deadlocking the notification thread.
|
||||
if (ackedField == null && activeField == null && conditionNodeId != null && _session != null)
|
||||
{
|
||||
var session = _session;
|
||||
var capturedConditionNodeId = conditionNodeId;
|
||||
var capturedMessage = message;
|
||||
_ = Task.Run(async () =>
|
||||
{
|
||||
try
|
||||
{
|
||||
var inAlarmValue = await session.ReadValueAsync(NodeId.Parse($"{capturedConditionNodeId}.InAlarm"));
|
||||
if (inAlarmValue.Value is bool inAlarm) activeState = inAlarm;
|
||||
|
||||
var ackedValue = await session.ReadValueAsync(NodeId.Parse($"{capturedConditionNodeId}.Acked"));
|
||||
if (ackedValue.Value is bool acked) ackedState = acked;
|
||||
|
||||
if (time == DateTime.MinValue && activeState)
|
||||
{
|
||||
var timeValue = await session.ReadValueAsync(NodeId.Parse($"{capturedConditionNodeId}.TimeAlarmOn"));
|
||||
if (timeValue.Value is DateTime alarmTime && alarmTime != DateTime.MinValue)
|
||||
time = alarmTime;
|
||||
}
|
||||
|
||||
// Read alarm description to use as message
|
||||
try
|
||||
{
|
||||
var descValue = await session.ReadValueAsync(NodeId.Parse($"{capturedConditionNodeId}.DescAttrName"));
|
||||
if (descValue.Value is string desc && !string.IsNullOrEmpty(desc))
|
||||
capturedMessage = desc;
|
||||
}
|
||||
catch { /* DescAttrName may not exist */ }
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Supplemental read failed; use defaults
|
||||
}
|
||||
|
||||
AlarmEvent?.Invoke(this, new AlarmEventArgs(
|
||||
sourceName, conditionName, severity, capturedMessage, retain, activeState, ackedState, time,
|
||||
eventId, capturedConditionNodeId));
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
AlarmEvent?.Invoke(this, new AlarmEventArgs(
|
||||
sourceName, conditionName, severity, message, retain, activeState, ackedState, time,
|
||||
eventId, conditionNodeId));
|
||||
}
|
||||
|
||||
private static bool ParseBool(object? value)
|
||||
{
|
||||
if (value == null) return false;
|
||||
if (value is bool b) return b;
|
||||
try { return Convert.ToBoolean(value); }
|
||||
catch { return false; }
|
||||
}
|
||||
|
||||
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");
|
||||
// 12: SourceNode (ConditionId for acknowledgment)
|
||||
filter.AddSelectClause(ObjectTypeIds.BaseEventType, BrowseNames.SourceNode);
|
||||
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.OtOpcUa.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.OtOpcUa.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.OtOpcUa.Client.Shared.Tests"/>
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
9
src/Client/ZB.MOM.WW.OtOpcUa.Client.UI/App.axaml
Normal file
9
src/Client/ZB.MOM.WW.OtOpcUa.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.OtOpcUa.Client.UI.App"
|
||||
RequestedThemeVariant="Light">
|
||||
<Application.Styles>
|
||||
<FluentTheme />
|
||||
<StyleInclude Source="avares://Avalonia.Controls.DataGrid/Themes/Fluent.xaml" />
|
||||
</Application.Styles>
|
||||
</Application>
|
||||
33
src/Client/ZB.MOM.WW.OtOpcUa.Client.UI/App.axaml.cs
Normal file
33
src/Client/ZB.MOM.WW.OtOpcUa.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.OtOpcUa.Client.Shared;
|
||||
using ZB.MOM.WW.OtOpcUa.Client.UI.Services;
|
||||
using ZB.MOM.WW.OtOpcUa.Client.UI.ViewModels;
|
||||
using ZB.MOM.WW.OtOpcUa.Client.UI.Views;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Client.UI;
|
||||
|
||||
public 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();
|
||||
}
|
||||
}
|
||||
18
src/Client/ZB.MOM.WW.OtOpcUa.Client.UI/Assets/app-icon.svg
Normal file
18
src/Client/ZB.MOM.WW.OtOpcUa.Client.UI/Assets/app-icon.svg
Normal file
@@ -0,0 +1,18 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" width="64" height="64">
|
||||
<!-- Server/network icon for OPC UA -->
|
||||
<rect x="8" y="6" width="48" height="36" rx="4" fill="#2563eb" stroke="#1d4ed8" stroke-width="2"/>
|
||||
<rect x="14" y="12" width="36" height="24" rx="2" fill="#dbeafe"/>
|
||||
<!-- Network nodes -->
|
||||
<circle cx="24" cy="24" r="4" fill="#2563eb"/>
|
||||
<circle cx="40" cy="20" r="3" fill="#3b82f6"/>
|
||||
<circle cx="36" cy="30" r="3" fill="#3b82f6"/>
|
||||
<!-- Connection lines -->
|
||||
<line x1="24" y1="24" x2="40" y2="20" stroke="#60a5fa" stroke-width="1.5"/>
|
||||
<line x1="24" y1="24" x2="36" y2="30" stroke="#60a5fa" stroke-width="1.5"/>
|
||||
<line x1="40" y1="20" x2="36" y2="30" stroke="#60a5fa" stroke-width="1.5"/>
|
||||
<!-- Base stand -->
|
||||
<rect x="24" y="42" width="16" height="4" rx="1" fill="#6b7280"/>
|
||||
<rect x="20" y="46" width="24" height="4" rx="2" fill="#9ca3af"/>
|
||||
<!-- UA text -->
|
||||
<text x="32" y="60" text-anchor="middle" font-family="Arial,sans-serif" font-size="8" font-weight="bold" fill="#1d4ed8">UA</text>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 1.0 KiB |
@@ -0,0 +1,27 @@
|
||||
<UserControl xmlns="https://github.com/avaloniaui"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
x:Class="ZB.MOM.WW.OtOpcUa.Client.UI.Controls.DateTimeRangePicker">
|
||||
<StackPanel Orientation="Horizontal" Spacing="8">
|
||||
<StackPanel Spacing="2">
|
||||
<TextBlock Text="Start (UTC)" FontSize="11" Foreground="Gray" />
|
||||
<TextBox Name="StartInput" Width="170" FontFamily="Consolas,monospace" FontSize="13"
|
||||
Watermark="yyyy-MM-dd HH:mm:ss (UTC)"
|
||||
Text="{Binding StartText, RelativeSource={RelativeSource AncestorType=UserControl}}" />
|
||||
</StackPanel>
|
||||
<TextBlock Text="to" VerticalAlignment="Bottom" Margin="0,0,0,6" />
|
||||
<StackPanel Spacing="2">
|
||||
<TextBlock Text="End (UTC)" FontSize="11" Foreground="Gray" />
|
||||
<TextBox Name="EndInput" Width="170" FontFamily="Consolas,monospace" FontSize="13"
|
||||
Watermark="yyyy-MM-dd HH:mm:ss (UTC)"
|
||||
Text="{Binding EndText, RelativeSource={RelativeSource AncestorType=UserControl}}" />
|
||||
</StackPanel>
|
||||
<Border Background="#F0F0F0" CornerRadius="4" Padding="4,2" VerticalAlignment="Bottom" Margin="0,0,0,2">
|
||||
<StackPanel Orientation="Horizontal" Spacing="4">
|
||||
<Button Name="Last5MinBtn" Content="5m" Padding="8,3" FontSize="11" />
|
||||
<Button Name="LastHourBtn" Content="1h" Padding="8,3" FontSize="11" />
|
||||
<Button Name="LastDayBtn" Content="1d" Padding="8,3" FontSize="11" />
|
||||
<Button Name="LastWeekBtn" Content="1w" Padding="8,3" FontSize="11" />
|
||||
</StackPanel>
|
||||
</Border>
|
||||
</StackPanel>
|
||||
</UserControl>
|
||||
@@ -0,0 +1,187 @@
|
||||
using System;
|
||||
using System.Globalization;
|
||||
using Avalonia;
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Interactivity;
|
||||
using Avalonia.Media;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Client.UI.Controls;
|
||||
|
||||
/// <summary>
|
||||
/// A date/time range picker using formatted text boxes and preset duration buttons.
|
||||
/// Text properties are two-way bound to TextBoxes via XAML; DateTime properties
|
||||
/// are synced in code-behind.
|
||||
/// </summary>
|
||||
public partial class DateTimeRangePicker : UserControl
|
||||
{
|
||||
private const string Format = "yyyy-MM-dd HH:mm:ss";
|
||||
|
||||
public static readonly StyledProperty<DateTimeOffset?> StartDateTimeProperty =
|
||||
AvaloniaProperty.Register<DateTimeRangePicker, DateTimeOffset?>(
|
||||
nameof(StartDateTime), defaultBindingMode: Avalonia.Data.BindingMode.TwoWay);
|
||||
|
||||
public static readonly StyledProperty<DateTimeOffset?> EndDateTimeProperty =
|
||||
AvaloniaProperty.Register<DateTimeRangePicker, DateTimeOffset?>(
|
||||
nameof(EndDateTime), defaultBindingMode: Avalonia.Data.BindingMode.TwoWay);
|
||||
|
||||
public static readonly StyledProperty<string> StartTextProperty =
|
||||
AvaloniaProperty.Register<DateTimeRangePicker, string>(nameof(StartText), defaultValue: "");
|
||||
|
||||
public static readonly StyledProperty<string> EndTextProperty =
|
||||
AvaloniaProperty.Register<DateTimeRangePicker, string>(nameof(EndText), defaultValue: "");
|
||||
|
||||
public static readonly StyledProperty<DateTimeOffset?> MinDateTimeProperty =
|
||||
AvaloniaProperty.Register<DateTimeRangePicker, DateTimeOffset?>(nameof(MinDateTime));
|
||||
|
||||
public static readonly StyledProperty<DateTimeOffset?> MaxDateTimeProperty =
|
||||
AvaloniaProperty.Register<DateTimeRangePicker, DateTimeOffset?>(nameof(MaxDateTime));
|
||||
|
||||
private bool _isUpdating;
|
||||
|
||||
public DateTimeRangePicker()
|
||||
{
|
||||
InitializeComponent();
|
||||
}
|
||||
|
||||
public DateTimeOffset? StartDateTime
|
||||
{
|
||||
get => GetValue(StartDateTimeProperty);
|
||||
set => SetValue(StartDateTimeProperty, value);
|
||||
}
|
||||
|
||||
public DateTimeOffset? EndDateTime
|
||||
{
|
||||
get => GetValue(EndDateTimeProperty);
|
||||
set => SetValue(EndDateTimeProperty, value);
|
||||
}
|
||||
|
||||
public string StartText
|
||||
{
|
||||
get => GetValue(StartTextProperty);
|
||||
set => SetValue(StartTextProperty, value);
|
||||
}
|
||||
|
||||
public string EndText
|
||||
{
|
||||
get => GetValue(EndTextProperty);
|
||||
set => SetValue(EndTextProperty, value);
|
||||
}
|
||||
|
||||
public DateTimeOffset? MinDateTime
|
||||
{
|
||||
get => GetValue(MinDateTimeProperty);
|
||||
set => SetValue(MinDateTimeProperty, value);
|
||||
}
|
||||
|
||||
public DateTimeOffset? MaxDateTime
|
||||
{
|
||||
get => GetValue(MaxDateTimeProperty);
|
||||
set => SetValue(MaxDateTimeProperty, value);
|
||||
}
|
||||
|
||||
protected override void OnLoaded(RoutedEventArgs e)
|
||||
{
|
||||
base.OnLoaded(e);
|
||||
|
||||
var startInput = this.FindControl<TextBox>("StartInput");
|
||||
var endInput = this.FindControl<TextBox>("EndInput");
|
||||
|
||||
if (startInput != null) startInput.LostFocus += OnStartLostFocus;
|
||||
if (endInput != null) endInput.LostFocus += OnEndLostFocus;
|
||||
|
||||
var last5Min = this.FindControl<Button>("Last5MinBtn");
|
||||
var lastHour = this.FindControl<Button>("LastHourBtn");
|
||||
var lastDay = this.FindControl<Button>("LastDayBtn");
|
||||
var lastWeek = this.FindControl<Button>("LastWeekBtn");
|
||||
|
||||
if (last5Min != null) last5Min.Click += (_, _) => ApplyPreset(TimeSpan.FromMinutes(5));
|
||||
if (lastHour != null) lastHour.Click += (_, _) => ApplyPreset(TimeSpan.FromHours(1));
|
||||
if (lastDay != null) lastDay.Click += (_, _) => ApplyPreset(TimeSpan.FromDays(1));
|
||||
if (lastWeek != null) lastWeek.Click += (_, _) => ApplyPreset(TimeSpan.FromDays(7));
|
||||
}
|
||||
|
||||
protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
|
||||
{
|
||||
base.OnPropertyChanged(change);
|
||||
if (_isUpdating) return;
|
||||
|
||||
if (change.Property == StartDateTimeProperty)
|
||||
{
|
||||
_isUpdating = true;
|
||||
StartText = StartDateTime?.UtcDateTime.ToString(Format) ?? "";
|
||||
_isUpdating = false;
|
||||
}
|
||||
else if (change.Property == EndDateTimeProperty)
|
||||
{
|
||||
_isUpdating = true;
|
||||
EndText = EndDateTime?.UtcDateTime.ToString(Format) ?? "";
|
||||
_isUpdating = false;
|
||||
}
|
||||
}
|
||||
|
||||
private void OnStartLostFocus(object? sender, RoutedEventArgs e)
|
||||
{
|
||||
var startInput = this.FindControl<TextBox>("StartInput");
|
||||
if (startInput == null) return;
|
||||
|
||||
if (TryParseDateTime(startInput.Text, out var dt))
|
||||
{
|
||||
_isUpdating = true;
|
||||
StartDateTime = dt;
|
||||
_isUpdating = false;
|
||||
startInput.Foreground = null;
|
||||
}
|
||||
else if (!string.IsNullOrWhiteSpace(startInput.Text))
|
||||
{
|
||||
startInput.Foreground = Brushes.Red;
|
||||
}
|
||||
}
|
||||
|
||||
private void OnEndLostFocus(object? sender, RoutedEventArgs e)
|
||||
{
|
||||
var endInput = this.FindControl<TextBox>("EndInput");
|
||||
if (endInput == null) return;
|
||||
|
||||
if (TryParseDateTime(endInput.Text, out var dt))
|
||||
{
|
||||
_isUpdating = true;
|
||||
EndDateTime = dt;
|
||||
_isUpdating = false;
|
||||
endInput.Foreground = null;
|
||||
}
|
||||
else if (!string.IsNullOrWhiteSpace(endInput.Text))
|
||||
{
|
||||
endInput.Foreground = Brushes.Red;
|
||||
}
|
||||
}
|
||||
|
||||
private void ApplyPreset(TimeSpan span)
|
||||
{
|
||||
_isUpdating = true;
|
||||
try
|
||||
{
|
||||
var now = DateTimeOffset.UtcNow;
|
||||
StartDateTime = now - span;
|
||||
EndDateTime = now;
|
||||
StartText = StartDateTime.Value.UtcDateTime.ToString(Format);
|
||||
EndText = EndDateTime.Value.UtcDateTime.ToString(Format);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_isUpdating = false;
|
||||
}
|
||||
}
|
||||
|
||||
private static bool TryParseDateTime(string? text, out DateTimeOffset result)
|
||||
{
|
||||
result = default;
|
||||
if (string.IsNullOrWhiteSpace(text)) return false;
|
||||
|
||||
if (DateTimeOffset.TryParseExact(text, Format, CultureInfo.InvariantCulture,
|
||||
DateTimeStyles.AssumeUniversal, out result))
|
||||
return true;
|
||||
|
||||
return DateTimeOffset.TryParse(text, CultureInfo.InvariantCulture,
|
||||
DateTimeStyles.AssumeUniversal, out result);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
using Opc.Ua;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Client.UI.Helpers;
|
||||
|
||||
/// <summary>
|
||||
/// Formats OPC UA status codes as "0xHEX (description)".
|
||||
/// </summary>
|
||||
internal static class StatusCodeFormatter
|
||||
{
|
||||
public static string Format(StatusCode statusCode)
|
||||
{
|
||||
var code = statusCode.Code;
|
||||
var hex = $"0x{code:X8}";
|
||||
|
||||
// Try the SDK's browse name lookup first
|
||||
var name = StatusCodes.GetBrowseName(code);
|
||||
if (!string.IsNullOrEmpty(name))
|
||||
return $"{hex} ({name})";
|
||||
|
||||
// Try masking to just the main code (top 16 bits) for sub-status codes
|
||||
var mainCode = code & 0xFFFF0000;
|
||||
if (mainCode != code)
|
||||
{
|
||||
name = StatusCodes.GetBrowseName(mainCode);
|
||||
if (!string.IsNullOrEmpty(name))
|
||||
return $"{hex} ({name})";
|
||||
}
|
||||
|
||||
// Fallback to severity category
|
||||
if (StatusCode.IsGood(statusCode))
|
||||
return $"{hex} (Good)";
|
||||
if (StatusCode.IsBad(statusCode))
|
||||
return $"{hex} (Bad)";
|
||||
return $"{hex} (Uncertain)";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
using System.Collections;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Client.UI.Helpers;
|
||||
|
||||
/// <summary>
|
||||
/// Formats OPC UA values for display, with array support.
|
||||
/// </summary>
|
||||
internal static class ValueFormatter
|
||||
{
|
||||
public static string Format(object? value)
|
||||
{
|
||||
if (value is null) return "(null)";
|
||||
if (value is Array array) return FormatArray(array);
|
||||
if (value is IEnumerable enumerable and not string) return FormatEnumerable(enumerable);
|
||||
return value.ToString() ?? "(null)";
|
||||
}
|
||||
|
||||
private static string FormatArray(Array array)
|
||||
{
|
||||
var elements = new string[array.Length];
|
||||
for (var i = 0; i < array.Length; i++)
|
||||
elements[i] = array.GetValue(i)?.ToString() ?? "null";
|
||||
return $"[{string.Join(",", elements)}]";
|
||||
}
|
||||
|
||||
private static string FormatEnumerable(IEnumerable enumerable)
|
||||
{
|
||||
var items = new List<string>();
|
||||
foreach (var item in enumerable)
|
||||
items.Add(item?.ToString() ?? "null");
|
||||
return $"[{string.Join(",", items)}]";
|
||||
}
|
||||
}
|
||||
21
src/Client/ZB.MOM.WW.OtOpcUa.Client.UI/Program.cs
Normal file
21
src/Client/ZB.MOM.WW.OtOpcUa.Client.UI/Program.cs
Normal file
@@ -0,0 +1,21 @@
|
||||
using Avalonia;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Client.UI;
|
||||
|
||||
public class Program
|
||||
{
|
||||
[STAThread]
|
||||
public static void Main(string[] args)
|
||||
{
|
||||
BuildAvaloniaApp()
|
||||
.StartWithClassicDesktopLifetime(args);
|
||||
}
|
||||
|
||||
public static AppBuilder BuildAvaloniaApp()
|
||||
{
|
||||
return AppBuilder.Configure<App>()
|
||||
.UsePlatformDetect()
|
||||
.WithInterFont()
|
||||
.LogToTrace();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
using Avalonia.Threading;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
namespace ZB.MOM.WW.OtOpcUa.Client.UI.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Loads and saves user settings.
|
||||
/// </summary>
|
||||
public interface ISettingsService
|
||||
{
|
||||
UserSettings Load();
|
||||
void Save(UserSettings settings);
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
namespace ZB.MOM.WW.OtOpcUa.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,51 @@
|
||||
using System.Text.Json;
|
||||
using ZB.MOM.WW.OtOpcUa.Client.Shared;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Client.UI.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Persists user settings to a JSON file under LocalApplicationData.
|
||||
/// </summary>
|
||||
public sealed class JsonSettingsService : ISettingsService
|
||||
{
|
||||
// ClientStoragePaths.GetRoot runs the one-shot legacy-folder migration so pre-#208
|
||||
// developer boxes pick up their existing settings.json on first launch post-rename.
|
||||
private static readonly string SettingsDir = ClientStoragePaths.GetRoot();
|
||||
|
||||
private static readonly string SettingsPath = Path.Combine(SettingsDir, "settings.json");
|
||||
|
||||
private static readonly JsonSerializerOptions JsonOptions = new()
|
||||
{
|
||||
WriteIndented = true
|
||||
};
|
||||
|
||||
public UserSettings Load()
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!File.Exists(SettingsPath))
|
||||
return new UserSettings();
|
||||
|
||||
var json = File.ReadAllText(SettingsPath);
|
||||
return JsonSerializer.Deserialize<UserSettings>(json, JsonOptions) ?? new UserSettings();
|
||||
}
|
||||
catch
|
||||
{
|
||||
return new UserSettings();
|
||||
}
|
||||
}
|
||||
|
||||
public void Save(UserSettings settings)
|
||||
{
|
||||
try
|
||||
{
|
||||
Directory.CreateDirectory(SettingsDir);
|
||||
var json = JsonSerializer.Serialize(settings, JsonOptions);
|
||||
File.WriteAllText(SettingsPath, json);
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Best-effort save; don't crash the app
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
namespace ZB.MOM.WW.OtOpcUa.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,59 @@
|
||||
using ZB.MOM.WW.OtOpcUa.Client.Shared.Models;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Client.UI.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Persisted user connection settings.
|
||||
/// </summary>
|
||||
public sealed class UserSettings
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets or sets the last OPC UA endpoint URL entered by the user.
|
||||
/// </summary>
|
||||
public string EndpointUrl { get; set; } = "opc.tcp://localhost:4840";
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the persisted username for authenticated sessions.
|
||||
/// </summary>
|
||||
public string? Username { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the persisted password for authenticated sessions.
|
||||
/// </summary>
|
||||
public string? Password { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the transport security mode selected by the user.
|
||||
/// </summary>
|
||||
public SecurityMode SecurityMode { get; set; } = SecurityMode.None;
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the raw failover endpoint list entered in the UI.
|
||||
/// </summary>
|
||||
public string? FailoverUrls { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the persisted session timeout, in seconds, for new client connections.
|
||||
/// </summary>
|
||||
public int SessionTimeoutSeconds { get; set; } = 60;
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets a value indicating whether untrusted server certificates should be auto-accepted.
|
||||
/// </summary>
|
||||
public bool AutoAcceptCertificates { get; set; } = true;
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the certificate store path used for client certificates and trust lists.
|
||||
/// </summary>
|
||||
public string? CertificateStorePath { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the node IDs that should be re-subscribed when the UI reconnects.
|
||||
/// </summary>
|
||||
public List<string> SubscribedNodes { get; set; } = [];
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the alarm source node that should be restored when the UI reconnects.
|
||||
/// </summary>
|
||||
public string? AlarmSourceNodeId { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Client.UI.ViewModels;
|
||||
|
||||
/// <summary>
|
||||
/// Represents a single alarm event row.
|
||||
/// </summary>
|
||||
public class AlarmEventViewModel : ObservableObject
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates an alarm row model from an OPC UA condition event so the alarms tab can display and acknowledge it.
|
||||
/// </summary>
|
||||
/// <param name="sourceName">The source object or variable name associated with the alarm.</param>
|
||||
/// <param name="conditionName">The OPC UA condition name reported by the server.</param>
|
||||
/// <param name="severity">The alarm severity value presented to the operator.</param>
|
||||
/// <param name="message">The alarm message text shown in the UI.</param>
|
||||
/// <param name="retain">Indicates whether the server is retaining the alarm condition.</param>
|
||||
/// <param name="activeState">Indicates whether the alarm is currently active.</param>
|
||||
/// <param name="ackedState">Indicates whether the alarm has already been acknowledged.</param>
|
||||
/// <param name="time">The event timestamp associated with the alarm state.</param>
|
||||
/// <param name="eventId">The OPC UA event identifier used for acknowledgment calls.</param>
|
||||
/// <param name="conditionNodeId">The condition node identifier used when acknowledging the alarm.</param>
|
||||
public AlarmEventViewModel(
|
||||
string sourceName,
|
||||
string conditionName,
|
||||
ushort severity,
|
||||
string message,
|
||||
bool retain,
|
||||
bool activeState,
|
||||
bool ackedState,
|
||||
DateTime time,
|
||||
byte[]? eventId = null,
|
||||
string? conditionNodeId = null)
|
||||
{
|
||||
SourceName = sourceName;
|
||||
ConditionName = conditionName;
|
||||
Severity = severity;
|
||||
Message = message;
|
||||
Retain = retain;
|
||||
ActiveState = activeState;
|
||||
AckedState = ackedState;
|
||||
Time = time;
|
||||
EventId = eventId;
|
||||
ConditionNodeId = conditionNodeId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the source object or variable name associated with the alarm.
|
||||
/// </summary>
|
||||
public string SourceName { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the OPC UA condition name reported for the alarm event.
|
||||
/// </summary>
|
||||
public string ConditionName { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the severity value shown to the operator.
|
||||
/// </summary>
|
||||
public ushort Severity { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the alarm message text shown in the UI.
|
||||
/// </summary>
|
||||
public string Message { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets a value indicating whether the server is retaining the condition.
|
||||
/// </summary>
|
||||
public bool Retain { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets a value indicating whether the alarm is currently active.
|
||||
/// </summary>
|
||||
public bool ActiveState { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets a value indicating whether the alarm has already been acknowledged.
|
||||
/// </summary>
|
||||
public bool AckedState { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the event timestamp displayed for the alarm row.
|
||||
/// </summary>
|
||||
public DateTime Time { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the OPC UA event identifier needed to acknowledge the alarm.
|
||||
/// </summary>
|
||||
public byte[]? EventId { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the condition node identifier used for acknowledgment method calls.
|
||||
/// </summary>
|
||||
public string? ConditionNodeId { get; }
|
||||
|
||||
/// <summary>Whether this alarm can be acknowledged (active, not yet acked, has EventId).</summary>
|
||||
public bool CanAcknowledge => ActiveState && !AckedState && EventId != null && ConditionNodeId != null;
|
||||
}
|
||||
@@ -0,0 +1,225 @@
|
||||
using System.Collections.ObjectModel;
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using CommunityToolkit.Mvvm.Input;
|
||||
using Opc.Ua;
|
||||
using ZB.MOM.WW.OtOpcUa.Client.Shared;
|
||||
using ZB.MOM.WW.OtOpcUa.Client.Shared.Models;
|
||||
using ZB.MOM.WW.OtOpcUa.Client.UI.Services;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Client.UI.ViewModels;
|
||||
|
||||
/// <summary>
|
||||
/// ViewModel for the alarms panel.
|
||||
/// </summary>
|
||||
public partial class AlarmsViewModel : ObservableObject
|
||||
{
|
||||
private readonly IUiDispatcher _dispatcher;
|
||||
private readonly IOpcUaClientService _service;
|
||||
|
||||
[ObservableProperty] private int _interval = 1000;
|
||||
|
||||
[ObservableProperty]
|
||||
[NotifyCanExecuteChangedFor(nameof(SubscribeCommand))]
|
||||
[NotifyCanExecuteChangedFor(nameof(UnsubscribeCommand))]
|
||||
[NotifyCanExecuteChangedFor(nameof(RefreshCommand))]
|
||||
private bool _isConnected;
|
||||
|
||||
[ObservableProperty]
|
||||
[NotifyCanExecuteChangedFor(nameof(SubscribeCommand))]
|
||||
[NotifyCanExecuteChangedFor(nameof(UnsubscribeCommand))]
|
||||
[NotifyCanExecuteChangedFor(nameof(RefreshCommand))]
|
||||
private bool _isSubscribed;
|
||||
|
||||
[ObservableProperty] private string? _monitoredNodeIdText;
|
||||
|
||||
[ObservableProperty] private int _activeAlarmCount;
|
||||
|
||||
public AlarmsViewModel(IOpcUaClientService service, IUiDispatcher dispatcher)
|
||||
{
|
||||
_service = service;
|
||||
_dispatcher = dispatcher;
|
||||
_service.AlarmEvent += OnAlarmEvent;
|
||||
}
|
||||
|
||||
/// <summary>Received alarm events.</summary>
|
||||
public ObservableCollection<AlarmEventViewModel> AlarmEvents { get; } = [];
|
||||
|
||||
private void OnAlarmEvent(object? sender, AlarmEventArgs e)
|
||||
{
|
||||
// Only display alarm/condition events (those with a ConditionName), not generic events
|
||||
if (string.IsNullOrEmpty(e.ConditionName)) return;
|
||||
|
||||
_dispatcher.Post(() =>
|
||||
{
|
||||
// Find existing row by source + condition and update it, or add new
|
||||
var existing = AlarmEvents.FirstOrDefault(a =>
|
||||
a.SourceName == e.SourceName && a.ConditionName == e.ConditionName);
|
||||
|
||||
if (existing != null)
|
||||
{
|
||||
var index = AlarmEvents.IndexOf(existing);
|
||||
AlarmEvents[index] = new AlarmEventViewModel(
|
||||
e.SourceName, e.ConditionName, e.Severity, e.Message,
|
||||
e.Retain, e.ActiveState, e.AckedState, e.Time,
|
||||
e.EventId, e.ConditionNodeId);
|
||||
|
||||
// Remove alarms that are no longer retained
|
||||
if (!e.Retain)
|
||||
AlarmEvents.RemoveAt(index);
|
||||
}
|
||||
else if (e.Retain)
|
||||
{
|
||||
AlarmEvents.Add(new AlarmEventViewModel(
|
||||
e.SourceName, e.ConditionName, e.Severity, e.Message,
|
||||
e.Retain, e.ActiveState, e.AckedState, e.Time,
|
||||
e.EventId, e.ConditionNodeId));
|
||||
}
|
||||
|
||||
ActiveAlarmCount = AlarmEvents.Count(a => a.ActiveState && !a.AckedState);
|
||||
});
|
||||
}
|
||||
|
||||
private bool CanSubscribe()
|
||||
{
|
||||
return IsConnected && !IsSubscribed;
|
||||
}
|
||||
|
||||
[RelayCommand(CanExecute = nameof(CanSubscribe))]
|
||||
private async Task SubscribeAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
var sourceNodeId = string.IsNullOrWhiteSpace(MonitoredNodeIdText)
|
||||
? null
|
||||
: NodeId.Parse(MonitoredNodeIdText);
|
||||
|
||||
await _service.SubscribeAlarmsAsync(sourceNodeId, Interval);
|
||||
IsSubscribed = true;
|
||||
|
||||
try
|
||||
{
|
||||
await _service.RequestConditionRefreshAsync();
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Refresh not supported
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Subscribe failed
|
||||
}
|
||||
}
|
||||
|
||||
private bool CanUnsubscribe()
|
||||
{
|
||||
return 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>
|
||||
/// Acknowledges an alarm and returns (success, message).
|
||||
/// </summary>
|
||||
public async Task<(bool Success, string Message)> AcknowledgeAlarmAsync(AlarmEventViewModel alarm, string comment)
|
||||
{
|
||||
if (!IsConnected || alarm.EventId == null || alarm.ConditionNodeId == null)
|
||||
return (false, "Alarm cannot be acknowledged (missing EventId or ConditionId).");
|
||||
|
||||
try
|
||||
{
|
||||
var result = await _service.AcknowledgeAlarmAsync(alarm.ConditionNodeId, alarm.EventId, comment);
|
||||
if (Opc.Ua.StatusCode.IsGood(result))
|
||||
return (true, "Alarm acknowledged successfully.");
|
||||
return (false, $"Acknowledge failed: {Helpers.StatusCodeFormatter.Format(result)}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return (false, $"Error: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns the monitored node ID for persistence, or null if not subscribed.
|
||||
/// </summary>
|
||||
public string? GetAlarmSourceNodeId()
|
||||
{
|
||||
return IsSubscribed ? MonitoredNodeIdText : null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Restores an alarm subscription and requests a condition refresh.
|
||||
/// </summary>
|
||||
public async Task RestoreAlarmSubscriptionAsync(string? sourceNodeId)
|
||||
{
|
||||
if (!IsConnected || string.IsNullOrWhiteSpace(sourceNodeId)) return;
|
||||
|
||||
MonitoredNodeIdText = sourceNodeId;
|
||||
|
||||
try
|
||||
{
|
||||
var nodeId = string.IsNullOrWhiteSpace(sourceNodeId)
|
||||
? null
|
||||
: NodeId.Parse(sourceNodeId);
|
||||
|
||||
await _service.SubscribeAlarmsAsync(nodeId, Interval);
|
||||
IsSubscribed = true;
|
||||
|
||||
try
|
||||
{
|
||||
await _service.RequestConditionRefreshAsync();
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Refresh not supported
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Subscribe failed
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Clears alarm events and resets state.
|
||||
/// </summary>
|
||||
public void Clear()
|
||||
{
|
||||
AlarmEvents.Clear();
|
||||
IsSubscribed = false;
|
||||
ActiveAlarmCount = 0;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Unhooks event handlers from the service.
|
||||
/// </summary>
|
||||
public void Teardown()
|
||||
{
|
||||
_service.AlarmEvent -= OnAlarmEvent;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
using System.Collections.ObjectModel;
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using ZB.MOM.WW.OtOpcUa.Client.Shared;
|
||||
using ZB.MOM.WW.OtOpcUa.Client.UI.Services;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Client.UI.ViewModels;
|
||||
|
||||
/// <summary>
|
||||
/// ViewModel for the OPC UA browse tree panel.
|
||||
/// </summary>
|
||||
public class BrowseTreeViewModel : ObservableObject
|
||||
{
|
||||
private readonly IUiDispatcher _dispatcher;
|
||||
private readonly IOpcUaClientService _service;
|
||||
|
||||
public BrowseTreeViewModel(IOpcUaClientService service, IUiDispatcher dispatcher)
|
||||
{
|
||||
_service = service;
|
||||
_dispatcher = dispatcher;
|
||||
}
|
||||
|
||||
/// <summary>Top-level nodes in the browse tree.</summary>
|
||||
public ObservableCollection<TreeNodeViewModel> RootNodes { get; } = [];
|
||||
|
||||
/// <summary>
|
||||
/// Loads root nodes by browsing with a null parent.
|
||||
/// </summary>
|
||||
public async Task LoadRootsAsync()
|
||||
{
|
||||
var results = await _service.BrowseAsync();
|
||||
|
||||
_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.OtOpcUa.Client.UI.ViewModels;
|
||||
|
||||
/// <summary>
|
||||
/// Represents a single historical value row.
|
||||
/// </summary>
|
||||
public class HistoryValueViewModel : ObservableObject
|
||||
{
|
||||
public HistoryValueViewModel(string value, string status, string sourceTimestamp, string serverTimestamp)
|
||||
{
|
||||
Value = value;
|
||||
Status = status;
|
||||
SourceTimestamp = sourceTimestamp;
|
||||
ServerTimestamp = serverTimestamp;
|
||||
}
|
||||
|
||||
public string Value { get; }
|
||||
public string Status { get; }
|
||||
public string SourceTimestamp { get; }
|
||||
public string ServerTimestamp { get; }
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
using System.Collections.ObjectModel;
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using CommunityToolkit.Mvvm.Input;
|
||||
using Opc.Ua;
|
||||
using ZB.MOM.WW.OtOpcUa.Client.Shared;
|
||||
using ZB.MOM.WW.OtOpcUa.Client.Shared.Models;
|
||||
using ZB.MOM.WW.OtOpcUa.Client.UI.Services;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Client.UI.ViewModels;
|
||||
|
||||
/// <summary>
|
||||
/// ViewModel for the history panel.
|
||||
/// </summary>
|
||||
public partial class HistoryViewModel : ObservableObject
|
||||
{
|
||||
private readonly IUiDispatcher _dispatcher;
|
||||
private readonly IOpcUaClientService _service;
|
||||
|
||||
[ObservableProperty] private DateTimeOffset? _endTime = DateTimeOffset.UtcNow;
|
||||
|
||||
[ObservableProperty] private double _intervalMs = 3600000;
|
||||
|
||||
[ObservableProperty] [NotifyCanExecuteChangedFor(nameof(ReadHistoryCommand))]
|
||||
private bool _isConnected;
|
||||
|
||||
[ObservableProperty] private bool _isLoading;
|
||||
|
||||
[ObservableProperty] private int _maxValues = 1000;
|
||||
|
||||
[ObservableProperty] private AggregateType? _selectedAggregateType;
|
||||
|
||||
[ObservableProperty] [NotifyCanExecuteChangedFor(nameof(ReadHistoryCommand))]
|
||||
private string? _selectedNodeId;
|
||||
|
||||
[ObservableProperty] private DateTimeOffset? _startTime = DateTimeOffset.UtcNow.AddHours(-1);
|
||||
|
||||
public HistoryViewModel(IOpcUaClientService service, IUiDispatcher dispatcher)
|
||||
{
|
||||
_service = service;
|
||||
_dispatcher = dispatcher;
|
||||
}
|
||||
|
||||
/// <summary>Available aggregate types (null means "Raw").</summary>
|
||||
public IReadOnlyList<AggregateType?> AggregateTypes { get; } =
|
||||
[
|
||||
null,
|
||||
AggregateType.Average,
|
||||
AggregateType.Minimum,
|
||||
AggregateType.Maximum,
|
||||
AggregateType.Count,
|
||||
AggregateType.Start,
|
||||
AggregateType.End,
|
||||
AggregateType.StandardDeviation
|
||||
];
|
||||
|
||||
public bool IsAggregateRead => SelectedAggregateType != null;
|
||||
|
||||
/// <summary>History read results.</summary>
|
||||
public ObservableCollection<HistoryValueViewModel> Results { get; } = [];
|
||||
|
||||
partial void OnSelectedAggregateTypeChanged(AggregateType? value)
|
||||
{
|
||||
OnPropertyChanged(nameof(IsAggregateRead));
|
||||
}
|
||||
|
||||
private bool CanReadHistory()
|
||||
{
|
||||
return 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;
|
||||
|
||||
var start = (StartTime ?? DateTimeOffset.UtcNow.AddHours(-1)).UtcDateTime;
|
||||
var end = (EndTime ?? DateTimeOffset.UtcNow).UtcDateTime;
|
||||
|
||||
if (SelectedAggregateType != null)
|
||||
values = await _service.HistoryReadAggregateAsync(
|
||||
nodeId,
|
||||
start,
|
||||
end,
|
||||
SelectedAggregateType.Value,
|
||||
IntervalMs);
|
||||
else
|
||||
values = await _service.HistoryReadRawAsync(
|
||||
nodeId,
|
||||
start,
|
||||
end,
|
||||
MaxValues);
|
||||
|
||||
_dispatcher.Post(() =>
|
||||
{
|
||||
foreach (var dv in values)
|
||||
Results.Add(new HistoryValueViewModel(
|
||||
Helpers.ValueFormatter.Format(dv.Value),
|
||||
Helpers.StatusCodeFormatter.Format(dv.StatusCode),
|
||||
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,419 @@
|
||||
using System.Collections.ObjectModel;
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using CommunityToolkit.Mvvm.Input;
|
||||
using ZB.MOM.WW.OtOpcUa.Client.Shared;
|
||||
using ZB.MOM.WW.OtOpcUa.Client.Shared.Models;
|
||||
using ZB.MOM.WW.OtOpcUa.Client.UI.Services;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Client.UI.ViewModels;
|
||||
|
||||
/// <summary>
|
||||
/// Main window ViewModel coordinating all panels.
|
||||
/// </summary>
|
||||
public partial class MainWindowViewModel : ObservableObject
|
||||
{
|
||||
private readonly IUiDispatcher _dispatcher;
|
||||
private readonly IOpcUaClientServiceFactory _factory;
|
||||
private readonly ISettingsService _settingsService;
|
||||
private IOpcUaClientService? _service;
|
||||
private List<string> _savedSubscribedNodes = [];
|
||||
private string? _savedAlarmSourceNodeId;
|
||||
|
||||
[ObservableProperty] private bool _autoAcceptCertificates = true;
|
||||
|
||||
[ObservableProperty] private string _certificateStorePath = ClientStoragePaths.GetPkiPath();
|
||||
|
||||
[ObservableProperty]
|
||||
[NotifyCanExecuteChangedFor(nameof(ConnectCommand))]
|
||||
[NotifyCanExecuteChangedFor(nameof(DisconnectCommand))]
|
||||
private ConnectionState _connectionState = ConnectionState.Disconnected;
|
||||
|
||||
[ObservableProperty] private string _endpointUrl = "opc.tcp://localhost:4840";
|
||||
|
||||
[ObservableProperty] private string? _failoverUrls;
|
||||
|
||||
[ObservableProperty] private bool _isHistoryEnabledForSelection;
|
||||
|
||||
[ObservableProperty] private string? _password;
|
||||
|
||||
[ObservableProperty] private RedundancyInfo? _redundancyInfo;
|
||||
|
||||
[ObservableProperty] private SecurityMode _selectedSecurityMode = SecurityMode.None;
|
||||
|
||||
[ObservableProperty] private int _selectedTabIndex;
|
||||
|
||||
[ObservableProperty] private TreeNodeViewModel? _selectedTreeNode;
|
||||
|
||||
[ObservableProperty] private string _sessionLabel = string.Empty;
|
||||
|
||||
[ObservableProperty] private int _sessionTimeoutSeconds = 60;
|
||||
|
||||
[ObservableProperty] private string _statusMessage = "Disconnected";
|
||||
|
||||
[ObservableProperty] private int _subscriptionCount;
|
||||
|
||||
[ObservableProperty] private int _activeAlarmCount;
|
||||
|
||||
[ObservableProperty] private string? _username;
|
||||
|
||||
/// <summary>
|
||||
/// Creates the main shell view model that coordinates connection state, browsing, subscriptions, alarms, history, and persisted settings.
|
||||
/// </summary>
|
||||
/// <param name="factory">Creates the shared OPC UA client service used by all panels.</param>
|
||||
/// <param name="dispatcher">Marshals service callbacks back onto the UI thread.</param>
|
||||
/// <param name="settingsService">Loads and saves persisted user connection settings.</param>
|
||||
public MainWindowViewModel(IOpcUaClientServiceFactory factory, IUiDispatcher dispatcher,
|
||||
ISettingsService? settingsService = null)
|
||||
{
|
||||
_factory = factory;
|
||||
_dispatcher = dispatcher;
|
||||
_settingsService = settingsService ?? new JsonSettingsService();
|
||||
|
||||
LoadSettings();
|
||||
}
|
||||
|
||||
/// <summary>All available security modes.</summary>
|
||||
public IReadOnlyList<SecurityMode> SecurityModes { get; } = Enum.GetValues<SecurityMode>();
|
||||
|
||||
/// <summary>
|
||||
/// Gets a value indicating whether the shell is currently connected to an OPC UA endpoint.
|
||||
/// </summary>
|
||||
public bool IsConnected => ConnectionState == ConnectionState.Connected;
|
||||
|
||||
/// <summary>The currently selected tree nodes (supports multi-select).</summary>
|
||||
public ObservableCollection<TreeNodeViewModel> SelectedTreeNodes { get; } = [];
|
||||
|
||||
/// <summary>
|
||||
/// Gets the browse-tree panel view model for the address-space explorer.
|
||||
/// </summary>
|
||||
public BrowseTreeViewModel? BrowseTree { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the read/write panel view model for point operations against the selected node.
|
||||
/// </summary>
|
||||
public ReadWriteViewModel? ReadWrite { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the subscriptions panel view model for live data monitoring.
|
||||
/// </summary>
|
||||
public SubscriptionsViewModel? Subscriptions { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the alarms panel view model for active-condition monitoring and acknowledgment.
|
||||
/// </summary>
|
||||
public AlarmsViewModel? Alarms { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the history panel view model for raw and aggregate history queries.
|
||||
/// </summary>
|
||||
public HistoryViewModel? History { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the subscriptions tab header, including the current active subscription count when nonzero.
|
||||
/// </summary>
|
||||
public string SubscriptionsTabHeader => SubscriptionCount > 0
|
||||
? $"Subscriptions ({SubscriptionCount})"
|
||||
: "Subscriptions";
|
||||
|
||||
/// <summary>
|
||||
/// Gets the alarms tab header, including the current active alarm count when nonzero.
|
||||
/// </summary>
|
||||
public string AlarmsTabHeader => ActiveAlarmCount > 0
|
||||
? $"Alarms ({ActiveAlarmCount})"
|
||||
: "Alarms";
|
||||
|
||||
private void InitializeService()
|
||||
{
|
||||
if (_service != null) return;
|
||||
|
||||
_service = _factory.Create();
|
||||
_service.ConnectionStateChanged += OnConnectionStateChanged;
|
||||
|
||||
BrowseTree = new BrowseTreeViewModel(_service, _dispatcher);
|
||||
ReadWrite = new ReadWriteViewModel(_service, _dispatcher);
|
||||
Subscriptions = new SubscriptionsViewModel(_service, _dispatcher);
|
||||
Alarms = new AlarmsViewModel(_service, _dispatcher);
|
||||
Alarms.PropertyChanged += (_, args) =>
|
||||
{
|
||||
if (args.PropertyName == nameof(AlarmsViewModel.ActiveAlarmCount))
|
||||
_dispatcher.Post(() => ActiveAlarmCount = Alarms.ActiveAlarmCount);
|
||||
};
|
||||
History = new HistoryViewModel(_service, _dispatcher);
|
||||
|
||||
OnPropertyChanged(nameof(BrowseTree));
|
||||
OnPropertyChanged(nameof(ReadWrite));
|
||||
OnPropertyChanged(nameof(Subscriptions));
|
||||
OnPropertyChanged(nameof(Alarms));
|
||||
OnPropertyChanged(nameof(History));
|
||||
}
|
||||
|
||||
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;
|
||||
if (ReadWrite != null) ReadWrite.IsConnected = connected;
|
||||
if (Subscriptions != null) Subscriptions.IsConnected = connected;
|
||||
if (Alarms != null) Alarms.IsConnected = connected;
|
||||
if (History != null) 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;
|
||||
ActiveAlarmCount = 0;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
partial void OnSelectedTreeNodeChanged(TreeNodeViewModel? value)
|
||||
{
|
||||
if (ReadWrite != null) ReadWrite.SelectedNodeId = value?.NodeId;
|
||||
if (History != null) History.SelectedNodeId = value?.NodeId;
|
||||
}
|
||||
|
||||
partial void OnSubscriptionCountChanged(int value)
|
||||
{
|
||||
OnPropertyChanged(nameof(SubscriptionsTabHeader));
|
||||
}
|
||||
|
||||
partial void OnActiveAlarmCountChanged(int value)
|
||||
{
|
||||
OnPropertyChanged(nameof(AlarmsTabHeader));
|
||||
}
|
||||
|
||||
private bool CanConnect()
|
||||
{
|
||||
return ConnectionState == ConnectionState.Disconnected;
|
||||
}
|
||||
|
||||
[RelayCommand(CanExecute = nameof(CanConnect))]
|
||||
private async Task ConnectAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
ConnectionState = ConnectionState.Connecting;
|
||||
StatusMessage = "Connecting...";
|
||||
|
||||
InitializeService();
|
||||
|
||||
var settings = new ConnectionSettings
|
||||
{
|
||||
EndpointUrl = EndpointUrl,
|
||||
Username = Username,
|
||||
Password = Password,
|
||||
SecurityMode = SelectedSecurityMode,
|
||||
FailoverUrls = ParseFailoverUrls(FailoverUrls),
|
||||
SessionTimeoutSeconds = SessionTimeoutSeconds,
|
||||
AutoAcceptCertificates = AutoAcceptCertificates,
|
||||
CertificateStorePath = CertificateStorePath
|
||||
};
|
||||
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();
|
||||
|
||||
// Restore saved subscriptions
|
||||
if (_savedSubscribedNodes.Count > 0 && Subscriptions != null)
|
||||
{
|
||||
await Subscriptions.RestoreSubscriptionsAsync(_savedSubscribedNodes);
|
||||
SubscriptionCount = Subscriptions.SubscriptionCount;
|
||||
}
|
||||
|
||||
// Restore saved alarm subscription
|
||||
if (!string.IsNullOrEmpty(_savedAlarmSourceNodeId) && Alarms != null)
|
||||
await Alarms.RestoreAlarmSubscriptionAsync(_savedAlarmSourceNodeId);
|
||||
|
||||
SaveSettings();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_dispatcher.Post(() =>
|
||||
{
|
||||
ConnectionState = ConnectionState.Disconnected;
|
||||
StatusMessage = $"Connection failed: {ex.Message}";
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private bool CanDisconnect()
|
||||
{
|
||||
return ConnectionState == ConnectionState.Connected
|
||||
|| ConnectionState == ConnectionState.Reconnecting;
|
||||
}
|
||||
|
||||
[RelayCommand(CanExecute = nameof(CanDisconnect))]
|
||||
private async Task DisconnectAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
SaveSettings();
|
||||
Subscriptions?.Teardown();
|
||||
Alarms?.Teardown();
|
||||
await _service!.DisconnectAsync();
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Best-effort disconnect
|
||||
}
|
||||
finally
|
||||
{
|
||||
_dispatcher.Post(() => { ConnectionState = ConnectionState.Disconnected; });
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Subscribes all selected tree nodes and switches to the Subscriptions tab.
|
||||
/// </summary>
|
||||
[RelayCommand]
|
||||
private async Task SubscribeSelectedNodesAsync()
|
||||
{
|
||||
if (SelectedTreeNodes.Count == 0 || !IsConnected) return;
|
||||
|
||||
if (Subscriptions == null) return;
|
||||
|
||||
var nodes = SelectedTreeNodes.ToList();
|
||||
foreach (var node in nodes)
|
||||
await Subscriptions.AddSubscriptionRecursiveAsync(node.NodeId, node.NodeClass);
|
||||
|
||||
SubscriptionCount = Subscriptions.SubscriptionCount;
|
||||
SelectedTabIndex = 1; // Subscriptions tab
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets the history tab's selected node and switches to the History tab.
|
||||
/// </summary>
|
||||
[RelayCommand]
|
||||
private void ViewHistoryForSelectedNode()
|
||||
{
|
||||
if (SelectedTreeNodes.Count == 0 || !IsConnected) return;
|
||||
|
||||
var node = SelectedTreeNodes[0];
|
||||
History.SelectedNodeId = node.NodeId;
|
||||
SelectedTabIndex = 3; // History tab
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Stops any active alarm subscription, subscribes to alarms on the selected node,
|
||||
/// and switches to the Alarms tab.
|
||||
/// </summary>
|
||||
[RelayCommand]
|
||||
private async Task MonitorAlarmsForSelectedNodeAsync()
|
||||
{
|
||||
if (SelectedTreeNodes.Count == 0 || !IsConnected || Alarms == null) return;
|
||||
|
||||
var node = SelectedTreeNodes[0];
|
||||
|
||||
// Stop existing alarm subscription if active
|
||||
if (Alarms.IsSubscribed)
|
||||
{
|
||||
try { await _service!.UnsubscribeAlarmsAsync(); }
|
||||
catch { /* best effort */ }
|
||||
Alarms.Clear();
|
||||
}
|
||||
|
||||
// Subscribe to the selected node
|
||||
Alarms.MonitoredNodeIdText = node.NodeId;
|
||||
await Alarms.SubscribeCommand.ExecuteAsync(null);
|
||||
|
||||
SelectedTabIndex = 2; // Alarms tab
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Updates whether "View History" should be enabled based on the selected node's type.
|
||||
/// Only Variable nodes can have history.
|
||||
/// </summary>
|
||||
public void UpdateHistoryEnabledForSelection()
|
||||
{
|
||||
IsHistoryEnabledForSelection = IsConnected
|
||||
&& SelectedTreeNodes.Count > 0
|
||||
&& SelectedTreeNodes[0].NodeClass == "Variable";
|
||||
}
|
||||
|
||||
private void LoadSettings()
|
||||
{
|
||||
var s = _settingsService.Load();
|
||||
EndpointUrl = s.EndpointUrl;
|
||||
Username = s.Username;
|
||||
Password = s.Password;
|
||||
SelectedSecurityMode = s.SecurityMode;
|
||||
FailoverUrls = s.FailoverUrls;
|
||||
SessionTimeoutSeconds = s.SessionTimeoutSeconds;
|
||||
AutoAcceptCertificates = s.AutoAcceptCertificates;
|
||||
if (!string.IsNullOrEmpty(s.CertificateStorePath))
|
||||
CertificateStorePath = s.CertificateStorePath;
|
||||
_savedSubscribedNodes = s.SubscribedNodes;
|
||||
_savedAlarmSourceNodeId = s.AlarmSourceNodeId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Persists the current connection, subscription, and alarm-monitoring settings for the next UI session.
|
||||
/// </summary>
|
||||
public void SaveSettings()
|
||||
{
|
||||
_settingsService.Save(new UserSettings
|
||||
{
|
||||
EndpointUrl = EndpointUrl,
|
||||
Username = Username,
|
||||
Password = Password,
|
||||
SecurityMode = SelectedSecurityMode,
|
||||
FailoverUrls = FailoverUrls,
|
||||
SessionTimeoutSeconds = SessionTimeoutSeconds,
|
||||
AutoAcceptCertificates = AutoAcceptCertificates,
|
||||
CertificateStorePath = CertificateStorePath,
|
||||
SubscribedNodes = Subscriptions?.GetSubscribedNodeIds() ?? _savedSubscribedNodes,
|
||||
AlarmSourceNodeId = Alarms?.GetAlarmSourceNodeId() ?? _savedAlarmSourceNodeId
|
||||
});
|
||||
}
|
||||
|
||||
private static string[]? ParseFailoverUrls(string? csv)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(csv))
|
||||
return null;
|
||||
|
||||
return csv.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)
|
||||
.Where(u => !string.IsNullOrEmpty(u))
|
||||
.ToArray();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using CommunityToolkit.Mvvm.Input;
|
||||
using Opc.Ua;
|
||||
using ZB.MOM.WW.OtOpcUa.Client.Shared;
|
||||
using ZB.MOM.WW.OtOpcUa.Client.UI.Services;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Client.UI.ViewModels;
|
||||
|
||||
/// <summary>
|
||||
/// ViewModel for the read/write panel.
|
||||
/// </summary>
|
||||
public partial class ReadWriteViewModel : ObservableObject
|
||||
{
|
||||
private readonly IUiDispatcher _dispatcher;
|
||||
private readonly IOpcUaClientService _service;
|
||||
|
||||
[ObservableProperty] private string? _currentStatus;
|
||||
|
||||
[ObservableProperty] private string? _currentValue;
|
||||
|
||||
[ObservableProperty]
|
||||
[NotifyCanExecuteChangedFor(nameof(ReadCommand))]
|
||||
[NotifyCanExecuteChangedFor(nameof(WriteCommand))]
|
||||
private bool _isConnected;
|
||||
|
||||
[ObservableProperty]
|
||||
[NotifyCanExecuteChangedFor(nameof(ReadCommand))]
|
||||
[NotifyCanExecuteChangedFor(nameof(WriteCommand))]
|
||||
private string? _selectedNodeId;
|
||||
|
||||
[ObservableProperty] private string? _serverTimestamp;
|
||||
|
||||
[ObservableProperty] private string? _sourceTimestamp;
|
||||
|
||||
[ObservableProperty] private string? _writeStatus;
|
||||
|
||||
[ObservableProperty] private string? _writeValue;
|
||||
|
||||
public ReadWriteViewModel(IOpcUaClientService service, IUiDispatcher dispatcher)
|
||||
{
|
||||
_service = service;
|
||||
_dispatcher = dispatcher;
|
||||
}
|
||||
|
||||
public bool IsNodeSelected => !string.IsNullOrEmpty(SelectedNodeId);
|
||||
|
||||
partial void OnSelectedNodeIdChanged(string? value)
|
||||
{
|
||||
OnPropertyChanged(nameof(IsNodeSelected));
|
||||
if (!string.IsNullOrEmpty(value) && IsConnected) _ = ExecuteReadAsync();
|
||||
}
|
||||
|
||||
private bool CanReadOrWrite()
|
||||
{
|
||||
return 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 = Helpers.ValueFormatter.Format(dataValue.Value);
|
||||
CurrentStatus = Helpers.StatusCodeFormatter.Format(dataValue.StatusCode);
|
||||
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,27 @@
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Client.UI.ViewModels;
|
||||
|
||||
/// <summary>
|
||||
/// Represents a single active subscription row.
|
||||
/// </summary>
|
||||
public partial class SubscriptionItemViewModel : ObservableObject
|
||||
{
|
||||
[ObservableProperty] private string? _status;
|
||||
|
||||
[ObservableProperty] private string? _timestamp;
|
||||
|
||||
[ObservableProperty] private string? _value;
|
||||
|
||||
public SubscriptionItemViewModel(string nodeId, int intervalMs)
|
||||
{
|
||||
NodeId = nodeId;
|
||||
IntervalMs = intervalMs;
|
||||
}
|
||||
|
||||
/// <summary>The monitored NodeId.</summary>
|
||||
public string NodeId { get; }
|
||||
|
||||
/// <summary>The subscription interval in milliseconds.</summary>
|
||||
public int IntervalMs { get; }
|
||||
}
|
||||
@@ -0,0 +1,275 @@
|
||||
using System.Collections.ObjectModel;
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using CommunityToolkit.Mvvm.Input;
|
||||
using Opc.Ua;
|
||||
using ZB.MOM.WW.OtOpcUa.Client.Shared;
|
||||
using ZB.MOM.WW.OtOpcUa.Client.Shared.Models;
|
||||
using ZB.MOM.WW.OtOpcUa.Client.UI.Services;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Client.UI.ViewModels;
|
||||
|
||||
/// <summary>
|
||||
/// ViewModel for the subscriptions panel.
|
||||
/// </summary>
|
||||
public partial class SubscriptionsViewModel : ObservableObject
|
||||
{
|
||||
private readonly IUiDispatcher _dispatcher;
|
||||
private readonly IOpcUaClientService _service;
|
||||
|
||||
[ObservableProperty]
|
||||
[NotifyCanExecuteChangedFor(nameof(AddSubscriptionCommand))]
|
||||
[NotifyCanExecuteChangedFor(nameof(RemoveSubscriptionCommand))]
|
||||
private bool _isConnected;
|
||||
|
||||
[ObservableProperty] private int _newInterval = 1000;
|
||||
|
||||
[ObservableProperty] [NotifyCanExecuteChangedFor(nameof(AddSubscriptionCommand))]
|
||||
private string? _newNodeIdText;
|
||||
|
||||
[ObservableProperty] [NotifyCanExecuteChangedFor(nameof(RemoveSubscriptionCommand))]
|
||||
private SubscriptionItemViewModel? _selectedSubscription;
|
||||
|
||||
[ObservableProperty] private int _subscriptionCount;
|
||||
|
||||
/// <summary>
|
||||
/// Creates the subscriptions panel view model used to manage live data subscriptions and ad hoc writes from the UI.
|
||||
/// </summary>
|
||||
/// <param name="service">The shared client service that performs subscribe, unsubscribe, read, and write operations.</param>
|
||||
/// <param name="dispatcher">Marshals data-change callbacks back onto the UI thread.</param>
|
||||
public SubscriptionsViewModel(IOpcUaClientService service, IUiDispatcher dispatcher)
|
||||
{
|
||||
_service = service;
|
||||
_dispatcher = dispatcher;
|
||||
_service.DataChanged += OnDataChanged;
|
||||
}
|
||||
|
||||
/// <summary>Currently active subscriptions.</summary>
|
||||
public ObservableCollection<SubscriptionItemViewModel> ActiveSubscriptions { get; } = [];
|
||||
|
||||
/// <summary>Currently selected subscriptions (for multi-select remove).</summary>
|
||||
public List<SubscriptionItemViewModel> SelectedSubscriptions { get; } = [];
|
||||
|
||||
private void OnDataChanged(object? sender, DataChangedEventArgs e)
|
||||
{
|
||||
_dispatcher.Post(() =>
|
||||
{
|
||||
foreach (var item in ActiveSubscriptions)
|
||||
if (item.NodeId == e.NodeId)
|
||||
{
|
||||
item.Value = Helpers.ValueFormatter.Format(e.Value.Value);
|
||||
item.Status = Helpers.StatusCodeFormatter.Format(e.Value.StatusCode);
|
||||
item.Timestamp = e.Value.SourceTimestamp.ToString("O");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private bool CanAddSubscription()
|
||||
{
|
||||
return 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()
|
||||
{
|
||||
return IsConnected && (SelectedSubscriptions.Count > 0 || SelectedSubscription != null);
|
||||
}
|
||||
|
||||
[RelayCommand(CanExecute = nameof(CanRemoveSubscription))]
|
||||
private async Task RemoveSubscriptionAsync()
|
||||
{
|
||||
var itemsToRemove = SelectedSubscriptions.Count > 0
|
||||
? SelectedSubscriptions.ToList()
|
||||
: SelectedSubscription != null ? [SelectedSubscription] : [];
|
||||
|
||||
if (itemsToRemove.Count == 0) return;
|
||||
|
||||
foreach (var item in itemsToRemove)
|
||||
{
|
||||
try
|
||||
{
|
||||
var nodeId = NodeId.Parse(item.NodeId);
|
||||
await _service.UnsubscribeAsync(nodeId);
|
||||
|
||||
_dispatcher.Post(() => ActiveSubscriptions.Remove(item));
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Unsubscribe failed for this item; continue with others
|
||||
}
|
||||
}
|
||||
|
||||
_dispatcher.Post(() => SubscriptionCount = ActiveSubscriptions.Count);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Subscribes to a node by ID (used by context menu). Skips if already subscribed.
|
||||
/// </summary>
|
||||
/// <param name="nodeIdStr">The node ID to subscribe to from the browse tree or persisted settings.</param>
|
||||
/// <param name="intervalMs">The monitored-item interval, in milliseconds, for the subscription.</param>
|
||||
public async Task AddSubscriptionForNodeAsync(string nodeIdStr, int intervalMs = 1000)
|
||||
{
|
||||
if (!IsConnected || string.IsNullOrWhiteSpace(nodeIdStr)) return;
|
||||
|
||||
// Skip if already subscribed
|
||||
if (ActiveSubscriptions.Any(s => s.NodeId == nodeIdStr)) return;
|
||||
|
||||
try
|
||||
{
|
||||
var nodeId = NodeId.Parse(nodeIdStr);
|
||||
await _service.SubscribeAsync(nodeId, intervalMs);
|
||||
|
||||
_dispatcher.Post(() =>
|
||||
{
|
||||
ActiveSubscriptions.Add(new SubscriptionItemViewModel(nodeIdStr, intervalMs));
|
||||
SubscriptionCount = ActiveSubscriptions.Count;
|
||||
});
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Subscription failed
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Subscribes to a node and all its Variable descendants recursively.
|
||||
/// Object nodes are browsed for children; Variable nodes are subscribed directly.
|
||||
/// </summary>
|
||||
/// <param name="nodeIdStr">The root node whose variables should be subscribed recursively.</param>
|
||||
/// <param name="nodeClass">The node class of the starting node so variables can be subscribed immediately.</param>
|
||||
/// <param name="intervalMs">The monitored-item interval, in milliseconds, used for created subscriptions.</param>
|
||||
public Task AddSubscriptionRecursiveAsync(string nodeIdStr, string nodeClass, int intervalMs = 1000)
|
||||
{
|
||||
return AddSubscriptionRecursiveAsync(nodeIdStr, nodeClass, intervalMs, maxDepth: 10, currentDepth: 0);
|
||||
}
|
||||
|
||||
private async Task AddSubscriptionRecursiveAsync(string nodeIdStr, string nodeClass, int intervalMs, int maxDepth, int currentDepth)
|
||||
{
|
||||
if (!IsConnected || string.IsNullOrWhiteSpace(nodeIdStr)) return;
|
||||
if (currentDepth >= maxDepth) return;
|
||||
|
||||
if (nodeClass == "Variable")
|
||||
{
|
||||
await AddSubscriptionForNodeAsync(nodeIdStr, intervalMs);
|
||||
return;
|
||||
}
|
||||
|
||||
// Browse children and recurse
|
||||
try
|
||||
{
|
||||
var nodeId = NodeId.Parse(nodeIdStr);
|
||||
var children = await _service.BrowseAsync(nodeId);
|
||||
|
||||
foreach (var child in children)
|
||||
await AddSubscriptionRecursiveAsync(child.NodeId, child.NodeClass, intervalMs, maxDepth, currentDepth + 1);
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Browse failed for this node; skip it
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns the node IDs of all active subscriptions for persistence.
|
||||
/// </summary>
|
||||
public List<string> GetSubscribedNodeIds()
|
||||
{
|
||||
return ActiveSubscriptions.Select(s => s.NodeId).ToList();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Restores subscriptions from a saved list of node IDs.
|
||||
/// </summary>
|
||||
/// <param name="nodeIds">The node IDs persisted from a prior UI session.</param>
|
||||
public async Task RestoreSubscriptionsAsync(IEnumerable<string> nodeIds)
|
||||
{
|
||||
foreach (var nodeId in nodeIds)
|
||||
await AddSubscriptionForNodeAsync(nodeId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads the current value of a node to determine its type, validates that the raw
|
||||
/// input can be parsed to that type, writes the value, and returns (success, message).
|
||||
/// </summary>
|
||||
/// <param name="nodeIdStr">The node ID the operator wants to write.</param>
|
||||
/// <param name="rawValue">The raw text value entered by the operator.</param>
|
||||
public async Task<(bool Success, string Message)> ValidateAndWriteAsync(string nodeIdStr, string rawValue)
|
||||
{
|
||||
try
|
||||
{
|
||||
var nodeId = NodeId.Parse(nodeIdStr);
|
||||
|
||||
// Read current value to determine target type
|
||||
var currentDataValue = await _service.ReadValueAsync(nodeId);
|
||||
var currentValue = currentDataValue.Value;
|
||||
|
||||
// Try parsing to the target type before writing
|
||||
try
|
||||
{
|
||||
Shared.Helpers.ValueConverter.ConvertValue(rawValue, currentValue);
|
||||
}
|
||||
catch (FormatException ex)
|
||||
{
|
||||
var typeName = currentValue?.GetType().Name ?? "unknown";
|
||||
return (false, $"Cannot parse \"{rawValue}\" as {typeName}: {ex.Message}");
|
||||
}
|
||||
catch (OverflowException ex)
|
||||
{
|
||||
var typeName = currentValue?.GetType().Name ?? "unknown";
|
||||
return (false, $"Value \"{rawValue}\" is out of range for {typeName}: {ex.Message}");
|
||||
}
|
||||
|
||||
var result = await _service.WriteValueAsync(nodeId, rawValue);
|
||||
var statusText = Helpers.StatusCodeFormatter.Format(result);
|
||||
|
||||
if (Opc.Ua.StatusCode.IsGood(result))
|
||||
return (true, statusText);
|
||||
|
||||
return (false, $"Write failed: {statusText}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return (false, $"Error: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
/// <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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
using System.Collections.ObjectModel;
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using ZB.MOM.WW.OtOpcUa.Client.Shared;
|
||||
using ZB.MOM.WW.OtOpcUa.Client.UI.Services;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.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 IUiDispatcher? _dispatcher;
|
||||
|
||||
private readonly IOpcUaClientService? _service;
|
||||
private bool _hasLoadedChildren;
|
||||
|
||||
[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);
|
||||
}
|
||||
|
||||
/// <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; } = [];
|
||||
|
||||
/// <summary>
|
||||
/// Returns whether this node instance is the placeholder sentinel.
|
||||
/// </summary>
|
||||
internal bool IsPlaceholder => ReferenceEquals(this, 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
<Window xmlns="https://github.com/avaloniaui"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
x:Class="ZB.MOM.WW.OtOpcUa.Client.UI.Views.AckAlarmWindow"
|
||||
Title="Acknowledge Alarm"
|
||||
Width="420"
|
||||
SizeToContent="Height"
|
||||
MinHeight="240"
|
||||
WindowStartupLocation="CenterOwner"
|
||||
CanResize="False">
|
||||
<StackPanel Margin="16" Spacing="12">
|
||||
<TextBlock Text="Acknowledge Alarm" FontWeight="Bold" FontSize="16" />
|
||||
|
||||
<StackPanel Spacing="4">
|
||||
<TextBlock Text="Source:" FontSize="12" Foreground="Gray" />
|
||||
<TextBlock Name="SourceText" FontWeight="SemiBold" />
|
||||
</StackPanel>
|
||||
|
||||
<StackPanel Spacing="4">
|
||||
<TextBlock Text="Condition:" FontSize="12" Foreground="Gray" />
|
||||
<TextBlock Name="ConditionText" />
|
||||
</StackPanel>
|
||||
|
||||
<StackPanel Spacing="4">
|
||||
<TextBlock Text="Comment:" FontSize="12" Foreground="Gray" />
|
||||
<TextBox Name="CommentInput"
|
||||
Watermark="Enter acknowledgment comment"
|
||||
AcceptsReturn="True"
|
||||
Height="60"
|
||||
TextWrapping="Wrap" />
|
||||
</StackPanel>
|
||||
|
||||
<TextBlock Name="ResultText" Foreground="Gray" />
|
||||
|
||||
<StackPanel Orientation="Horizontal" Spacing="8" HorizontalAlignment="Right">
|
||||
<Button Name="AckButton" Content="Acknowledge" />
|
||||
<Button Name="CancelButton" Content="Cancel" />
|
||||
</StackPanel>
|
||||
</StackPanel>
|
||||
</Window>
|
||||
@@ -0,0 +1,67 @@
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Interactivity;
|
||||
using Avalonia.Media;
|
||||
using ZB.MOM.WW.OtOpcUa.Client.UI.ViewModels;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Client.UI.Views;
|
||||
|
||||
public partial class AckAlarmWindow : Window
|
||||
{
|
||||
private readonly AlarmsViewModel _alarmsVm;
|
||||
private readonly AlarmEventViewModel _alarm;
|
||||
|
||||
public AckAlarmWindow()
|
||||
{
|
||||
InitializeComponent();
|
||||
_alarmsVm = null!;
|
||||
_alarm = null!;
|
||||
}
|
||||
|
||||
public AckAlarmWindow(AlarmsViewModel alarmsVm, AlarmEventViewModel alarm)
|
||||
{
|
||||
InitializeComponent();
|
||||
_alarmsVm = alarmsVm;
|
||||
_alarm = alarm;
|
||||
|
||||
var sourceText = this.FindControl<TextBlock>("SourceText");
|
||||
if (sourceText != null) sourceText.Text = alarm.SourceName;
|
||||
|
||||
var conditionText = this.FindControl<TextBlock>("ConditionText");
|
||||
if (conditionText != null) conditionText.Text = $"{alarm.ConditionName} (Severity: {alarm.Severity})";
|
||||
|
||||
var ackButton = this.FindControl<Button>("AckButton");
|
||||
if (ackButton != null) ackButton.Click += OnAckClicked;
|
||||
|
||||
var cancelButton = this.FindControl<Button>("CancelButton");
|
||||
if (cancelButton != null) cancelButton.Click += OnCancelClicked;
|
||||
}
|
||||
|
||||
private async void OnAckClicked(object? sender, RoutedEventArgs e)
|
||||
{
|
||||
var commentInput = this.FindControl<TextBox>("CommentInput");
|
||||
var resultText = this.FindControl<TextBlock>("ResultText");
|
||||
if (commentInput == null || resultText == null) return;
|
||||
|
||||
var comment = commentInput.Text ?? string.Empty;
|
||||
|
||||
resultText.Foreground = Brushes.Gray;
|
||||
resultText.Text = "Acknowledging...";
|
||||
|
||||
var (success, message) = await _alarmsVm.AcknowledgeAlarmAsync(_alarm, comment);
|
||||
|
||||
if (success)
|
||||
{
|
||||
Close();
|
||||
}
|
||||
else
|
||||
{
|
||||
resultText.Foreground = Brushes.Red;
|
||||
resultText.Text = message;
|
||||
}
|
||||
}
|
||||
|
||||
private void OnCancelClicked(object? sender, RoutedEventArgs e)
|
||||
{
|
||||
Close();
|
||||
}
|
||||
}
|
||||
@@ -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.OtOpcUa.Client.UI.ViewModels"
|
||||
x:Class="ZB.MOM.WW.OtOpcUa.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 Name="AlarmsGrid"
|
||||
ItemsSource="{Binding AlarmEvents}"
|
||||
AutoGenerateColumns="False"
|
||||
IsReadOnly="True"
|
||||
HorizontalScrollBarVisibility="Auto"
|
||||
Margin="0,8,0,0"
|
||||
LoadingRow="OnDataGridLoadingRow">
|
||||
<DataGrid.Columns>
|
||||
<DataGridTextColumn Header="Time" Binding="{Binding Time, StringFormat='{}{0:yyyy-MM-dd HH:mm:ss}'}" Width="Auto" />
|
||||
<DataGridTextColumn Header="Source" Binding="{Binding SourceName}" Width="Auto" />
|
||||
<DataGridTextColumn Header="Condition" Binding="{Binding ConditionName}" Width="Auto" />
|
||||
<DataGridTextColumn Header="Severity" Binding="{Binding Severity}" Width="Auto" />
|
||||
<DataGridTextColumn Header="Message" Binding="{Binding Message}" Width="Auto" />
|
||||
<DataGridCheckBoxColumn Header="Active" Binding="{Binding ActiveState}" Width="Auto" />
|
||||
<DataGridCheckBoxColumn Header="Acked" Binding="{Binding AckedState}" Width="Auto" />
|
||||
<DataGridCheckBoxColumn Header="Retain" Binding="{Binding Retain}" Width="Auto" />
|
||||
</DataGrid.Columns>
|
||||
</DataGrid>
|
||||
</DockPanel>
|
||||
</UserControl>
|
||||
@@ -0,0 +1,79 @@
|
||||
using System.ComponentModel;
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Interactivity;
|
||||
using Avalonia.Media;
|
||||
using Avalonia.VisualTree;
|
||||
using ZB.MOM.WW.OtOpcUa.Client.UI.ViewModels;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Client.UI.Views;
|
||||
|
||||
public partial class AlarmsView : UserControl
|
||||
{
|
||||
// Severity color bands (OPC UA severity 0-1000)
|
||||
private static readonly IBrush InactiveBrush = new SolidColorBrush(Color.Parse("#F0F0F0")); // light grey
|
||||
private static readonly IBrush LowBrush = new SolidColorBrush(Color.Parse("#DBEAFE")); // light blue (1-332)
|
||||
private static readonly IBrush MediumBrush = new SolidColorBrush(Color.Parse("#FEF3C7")); // light yellow (333-665)
|
||||
private static readonly IBrush HighBrush = new SolidColorBrush(Color.Parse("#FEE2E2")); // light red (666-899)
|
||||
private static readonly IBrush CriticalBrush = new SolidColorBrush(Color.Parse("#FECACA")); // red (900-1000)
|
||||
|
||||
public AlarmsView()
|
||||
{
|
||||
InitializeComponent();
|
||||
}
|
||||
|
||||
protected override void OnLoaded(RoutedEventArgs e)
|
||||
{
|
||||
base.OnLoaded(e);
|
||||
|
||||
var grid = this.FindControl<DataGrid>("AlarmsGrid");
|
||||
if (grid == null) return;
|
||||
|
||||
var contextMenu = new ContextMenu();
|
||||
var ackItem = new MenuItem { Header = "Acknowledge..." };
|
||||
ackItem.Click += OnAcknowledgeClicked;
|
||||
contextMenu.Items.Add(ackItem);
|
||||
contextMenu.Opening += OnContextMenuOpening;
|
||||
grid.ContextMenu = contextMenu;
|
||||
}
|
||||
|
||||
private void OnDataGridLoadingRow(object? sender, DataGridRowEventArgs e)
|
||||
{
|
||||
if (e.Row.DataContext is AlarmEventViewModel alarm)
|
||||
e.Row.Background = GetSeverityBrush(alarm);
|
||||
}
|
||||
|
||||
private static IBrush GetSeverityBrush(AlarmEventViewModel alarm)
|
||||
{
|
||||
if (!alarm.ActiveState)
|
||||
return InactiveBrush;
|
||||
|
||||
return alarm.Severity switch
|
||||
{
|
||||
>= 900 => CriticalBrush,
|
||||
>= 666 => HighBrush,
|
||||
>= 333 => MediumBrush,
|
||||
_ => LowBrush
|
||||
};
|
||||
}
|
||||
|
||||
private void OnContextMenuOpening(object? sender, CancelEventArgs e)
|
||||
{
|
||||
var grid = this.FindControl<DataGrid>("AlarmsGrid");
|
||||
if (grid?.SelectedItem is not AlarmEventViewModel alarm || !alarm.CanAcknowledge)
|
||||
e.Cancel = true;
|
||||
}
|
||||
|
||||
private void OnAcknowledgeClicked(object? sender, RoutedEventArgs e)
|
||||
{
|
||||
if (DataContext is not AlarmsViewModel vm) return;
|
||||
|
||||
var grid = this.FindControl<DataGrid>("AlarmsGrid");
|
||||
if (grid?.SelectedItem is not AlarmEventViewModel alarm || !alarm.CanAcknowledge) return;
|
||||
|
||||
var parentWindow = this.FindAncestorOfType<Window>();
|
||||
if (parentWindow == null) return;
|
||||
|
||||
var ackWindow = new AckAlarmWindow(vm, alarm);
|
||||
ackWindow.ShowDialog(parentWindow);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
<UserControl xmlns="https://github.com/avaloniaui"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:vm="using:ZB.MOM.WW.OtOpcUa.Client.UI.ViewModels"
|
||||
x:Class="ZB.MOM.WW.OtOpcUa.Client.UI.Views.BrowseTreeView"
|
||||
x:DataType="vm:BrowseTreeViewModel">
|
||||
<TreeView ItemsSource="{Binding RootNodes}"
|
||||
Name="BrowseTree"
|
||||
SelectionMode="Multiple">
|
||||
<TreeView.Styles>
|
||||
<Style Selector="TreeViewItem" x:DataType="vm:TreeNodeViewModel">
|
||||
<Setter Property="IsExpanded" Value="{Binding IsExpanded, Mode=TwoWay}" />
|
||||
</Style>
|
||||
</TreeView.Styles>
|
||||
<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.OtOpcUa.Client.UI.Views;
|
||||
|
||||
public partial class BrowseTreeView : UserControl
|
||||
{
|
||||
public BrowseTreeView()
|
||||
{
|
||||
InitializeComponent();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
<UserControl xmlns="https://github.com/avaloniaui"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:vm="using:ZB.MOM.WW.OtOpcUa.Client.UI.ViewModels"
|
||||
xmlns:controls="using:ZB.MOM.WW.OtOpcUa.Client.UI.Controls"
|
||||
x:Class="ZB.MOM.WW.OtOpcUa.Client.UI.Views.HistoryView"
|
||||
x:DataType="vm:HistoryViewModel">
|
||||
<DockPanel Margin="8">
|
||||
<!-- Controls -->
|
||||
<StackPanel DockPanel.Dock="Top" Spacing="10">
|
||||
<TextBlock Text="History Read" FontWeight="Bold" />
|
||||
<TextBlock Text="{Binding SelectedNodeId, FallbackValue='(no node selected)'}"
|
||||
Foreground="Gray" />
|
||||
|
||||
<!-- Row 1: Time range -->
|
||||
<controls:DateTimeRangePicker StartDateTime="{Binding StartTime, Mode=TwoWay}"
|
||||
EndDateTime="{Binding EndTime, Mode=TwoWay}" />
|
||||
|
||||
<!-- Row 2: Aggregate, Interval, Max Values, Read button -->
|
||||
<StackPanel Orientation="Horizontal" Spacing="12">
|
||||
<StackPanel Spacing="2">
|
||||
<TextBlock Text="Aggregate" FontSize="11" Foreground="Gray" />
|
||||
<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" Foreground="Gray" />
|
||||
<NumericUpDown Value="{Binding IntervalMs}" Minimum="1000" Maximum="86400000" Width="150" />
|
||||
</StackPanel>
|
||||
<StackPanel Spacing="2">
|
||||
<TextBlock Text="Max Values" FontSize="11" Foreground="Gray" />
|
||||
<NumericUpDown Value="{Binding MaxValues}" Minimum="1" Maximum="100000" Width="120" />
|
||||
</StackPanel>
|
||||
<Button Content="Read History"
|
||||
Command="{Binding ReadHistoryCommand}"
|
||||
VerticalAlignment="Bottom"
|
||||
Padding="16,6" />
|
||||
</StackPanel>
|
||||
|
||||
<ProgressBar IsIndeterminate="True"
|
||||
IsVisible="{Binding IsLoading}"
|
||||
Height="4" />
|
||||
</StackPanel>
|
||||
|
||||
<!-- Results -->
|
||||
<DataGrid ItemsSource="{Binding Results}"
|
||||
AutoGenerateColumns="False"
|
||||
IsReadOnly="True"
|
||||
HorizontalScrollBarVisibility="Auto"
|
||||
Margin="0,8,0,0">
|
||||
<DataGrid.Columns>
|
||||
<DataGridTextColumn Header="Value" Binding="{Binding Value}" Width="Auto" />
|
||||
<DataGridTextColumn Header="Status" Binding="{Binding Status}" Width="Auto" />
|
||||
<DataGridTextColumn Header="Source Timestamp" Binding="{Binding SourceTimestamp}" Width="Auto" />
|
||||
<DataGridTextColumn Header="Server Timestamp" Binding="{Binding ServerTimestamp}" Width="Auto" />
|
||||
</DataGrid.Columns>
|
||||
</DataGrid>
|
||||
</DockPanel>
|
||||
</UserControl>
|
||||
@@ -0,0 +1,11 @@
|
||||
using Avalonia.Controls;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Client.UI.Views;
|
||||
|
||||
public partial class HistoryView : UserControl
|
||||
{
|
||||
public HistoryView()
|
||||
{
|
||||
InitializeComponent();
|
||||
}
|
||||
}
|
||||
162
src/Client/ZB.MOM.WW.OtOpcUa.Client.UI/Views/MainWindow.axaml
Normal file
162
src/Client/ZB.MOM.WW.OtOpcUa.Client.UI/Views/MainWindow.axaml
Normal file
@@ -0,0 +1,162 @@
|
||||
<Window xmlns="https://github.com/avaloniaui"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:vm="using:ZB.MOM.WW.OtOpcUa.Client.UI.ViewModels"
|
||||
xmlns:views="using:ZB.MOM.WW.OtOpcUa.Client.UI.Views"
|
||||
x:Class="ZB.MOM.WW.OtOpcUa.Client.UI.Views.MainWindow"
|
||||
x:DataType="vm:MainWindowViewModel"
|
||||
Title="OPC UA Client"
|
||||
Width="1200"
|
||||
Height="800">
|
||||
<DockPanel>
|
||||
<!-- Top Connection Bar -->
|
||||
<Border DockPanel.Dock="Top" Background="#F0F0F0" Padding="12">
|
||||
<StackPanel Spacing="4">
|
||||
<!-- Always visible: URL + Connect/Disconnect -->
|
||||
<StackPanel Orientation="Horizontal" Spacing="8">
|
||||
<StackPanel Spacing="2" VerticalAlignment="Bottom">
|
||||
<TextBlock Text="Endpoint URL" FontSize="11" Foreground="Gray" />
|
||||
<TextBox Text="{Binding EndpointUrl}"
|
||||
Width="400"
|
||||
Watermark="opc.tcp://host:port" />
|
||||
</StackPanel>
|
||||
<Button Content="Connect"
|
||||
Command="{Binding ConnectCommand}"
|
||||
VerticalAlignment="Bottom" Padding="16,6" />
|
||||
<Button Content="Disconnect"
|
||||
Command="{Binding DisconnectCommand}"
|
||||
VerticalAlignment="Bottom" Padding="16,6" />
|
||||
</StackPanel>
|
||||
|
||||
<!-- Expandable settings -->
|
||||
<Expander Header="Connection Settings" Padding="0,4">
|
||||
<StackPanel Spacing="10" Margin="4,8,4,4">
|
||||
<!-- Row 1: Authentication -->
|
||||
<StackPanel Orientation="Horizontal" Spacing="12">
|
||||
<StackPanel Spacing="2">
|
||||
<TextBlock Text="Username" FontSize="11" Foreground="Gray" />
|
||||
<TextBox Text="{Binding Username}"
|
||||
Width="160"
|
||||
Watermark="(anonymous)" />
|
||||
</StackPanel>
|
||||
<StackPanel Spacing="2">
|
||||
<TextBlock Text="Password" FontSize="11" Foreground="Gray" />
|
||||
<TextBox Text="{Binding Password}"
|
||||
Width="160"
|
||||
Watermark="(none)"
|
||||
PasswordChar="*" />
|
||||
</StackPanel>
|
||||
<StackPanel Spacing="2">
|
||||
<TextBlock Text="Security Mode" FontSize="11" Foreground="Gray" />
|
||||
<ComboBox ItemsSource="{Binding SecurityModes}"
|
||||
SelectedItem="{Binding SelectedSecurityMode}"
|
||||
Width="160" />
|
||||
</StackPanel>
|
||||
</StackPanel>
|
||||
|
||||
<!-- Row 2: Failover + Session -->
|
||||
<StackPanel Orientation="Horizontal" Spacing="12">
|
||||
<StackPanel Spacing="2">
|
||||
<TextBlock Text="Failover URLs (comma-separated)" FontSize="11" Foreground="Gray" />
|
||||
<TextBox Text="{Binding FailoverUrls}"
|
||||
Width="400"
|
||||
Watermark="opc.tcp://backup1:4840, opc.tcp://backup2:4840" />
|
||||
</StackPanel>
|
||||
<StackPanel Spacing="2">
|
||||
<TextBlock Text="Session Timeout (s)" FontSize="11" Foreground="Gray" />
|
||||
<NumericUpDown Value="{Binding SessionTimeoutSeconds}"
|
||||
Minimum="1" Maximum="3600"
|
||||
Width="120"
|
||||
FormatString="0" />
|
||||
</StackPanel>
|
||||
</StackPanel>
|
||||
|
||||
<!-- Row 3: Certificates -->
|
||||
<StackPanel Orientation="Horizontal" Spacing="12">
|
||||
<StackPanel Spacing="2">
|
||||
<TextBlock Text="Certificate Store Path" FontSize="11" Foreground="Gray" />
|
||||
<StackPanel Orientation="Horizontal" Spacing="4">
|
||||
<TextBox Text="{Binding CertificateStorePath}"
|
||||
Width="370"
|
||||
IsReadOnly="True"
|
||||
Watermark="(default: AppData/LmxOpcUaClient/pki)" />
|
||||
<Button Name="BrowseCertPathButton"
|
||||
Content="..."
|
||||
Width="30"
|
||||
ToolTip.Tip="Browse for folder" />
|
||||
</StackPanel>
|
||||
</StackPanel>
|
||||
<CheckBox IsChecked="{Binding AutoAcceptCertificates}"
|
||||
Content="Auto-accept untrusted server certificates"
|
||||
VerticalAlignment="Bottom"
|
||||
Margin="0,0,0,4" />
|
||||
</StackPanel>
|
||||
</StackPanel>
|
||||
</Expander>
|
||||
|
||||
<!-- Redundancy Info -->
|
||||
<StackPanel Orientation="Horizontal"
|
||||
Spacing="16"
|
||||
IsVisible="{Binding RedundancyInfo, Converter={x:Static ObjectConverters.IsNotNull}}"
|
||||
Margin="0,2,0,0">
|
||||
<TextBlock Text="{Binding RedundancyInfo.Mode, StringFormat='Redundancy: {0}'}"
|
||||
FontSize="11" Foreground="Gray" />
|
||||
<TextBlock Text="{Binding RedundancyInfo.ServiceLevel, StringFormat='Service Level: {0}'}"
|
||||
FontSize="11" Foreground="Gray" />
|
||||
<TextBlock Text="{Binding RedundancyInfo.ApplicationUri, StringFormat='URI: {0}'}"
|
||||
FontSize="11" Foreground="Gray" />
|
||||
</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">
|
||||
<views:BrowseTreeView.ContextMenu>
|
||||
<ContextMenu Name="TreeContextMenu">
|
||||
<MenuItem Header="Subscribe" Name="SubscribeMenuItem" />
|
||||
<MenuItem Header="View History" Name="ViewHistoryMenuItem" />
|
||||
<Separator />
|
||||
<MenuItem Header="Monitor Alarms" Name="MonitorAlarmsMenuItem" />
|
||||
</ContextMenu>
|
||||
</views:BrowseTreeView.ContextMenu>
|
||||
</views:BrowseTreeView>
|
||||
</DockPanel>
|
||||
</Border>
|
||||
|
||||
<!-- Splitter -->
|
||||
<GridSplitter Grid.Column="1" Width="8" Background="Transparent" />
|
||||
|
||||
<!-- Right: Tab panels -->
|
||||
<TabControl Grid.Column="2"
|
||||
IsEnabled="{Binding IsConnected}"
|
||||
SelectedIndex="{Binding SelectedTabIndex}">
|
||||
<TabItem Header="Read/Write">
|
||||
<views:ReadWriteView DataContext="{Binding ReadWrite}" />
|
||||
</TabItem>
|
||||
<TabItem Header="{Binding SubscriptionsTabHeader}">
|
||||
<views:SubscriptionsView DataContext="{Binding Subscriptions}" />
|
||||
</TabItem>
|
||||
<TabItem Header="{Binding AlarmsTabHeader}">
|
||||
<views:AlarmsView DataContext="{Binding Alarms}" />
|
||||
</TabItem>
|
||||
<TabItem Header="History">
|
||||
<views:HistoryView DataContext="{Binding History}" />
|
||||
</TabItem>
|
||||
</TabControl>
|
||||
</Grid>
|
||||
</DockPanel>
|
||||
</Window>
|
||||
146
src/Client/ZB.MOM.WW.OtOpcUa.Client.UI/Views/MainWindow.axaml.cs
Normal file
146
src/Client/ZB.MOM.WW.OtOpcUa.Client.UI/Views/MainWindow.axaml.cs
Normal file
@@ -0,0 +1,146 @@
|
||||
using System.ComponentModel;
|
||||
using System.Reflection;
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Interactivity;
|
||||
using SkiaSharp;
|
||||
using Svg.Skia;
|
||||
using ZB.MOM.WW.OtOpcUa.Client.UI.ViewModels;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Client.UI.Views;
|
||||
|
||||
public partial class MainWindow : Window
|
||||
{
|
||||
public MainWindow()
|
||||
{
|
||||
InitializeComponent();
|
||||
LoadIcon();
|
||||
}
|
||||
|
||||
private void LoadIcon()
|
||||
{
|
||||
try
|
||||
{
|
||||
var assembly = Assembly.GetExecutingAssembly();
|
||||
using var stream = assembly.GetManifestResourceStream("ZB.MOM.WW.OtOpcUa.Client.UI.Assets.app-icon.svg");
|
||||
if (stream == null) return;
|
||||
|
||||
using var svg = new SKSvg();
|
||||
svg.Load(stream);
|
||||
if (svg.Picture == null) return;
|
||||
|
||||
var size = 64;
|
||||
using var bitmap = new SKBitmap(size, size);
|
||||
using var canvas = new SKCanvas(bitmap);
|
||||
canvas.Clear(SKColors.Transparent);
|
||||
|
||||
var bounds = svg.Picture.CullRect;
|
||||
var scale = Math.Min(size / bounds.Width, size / bounds.Height);
|
||||
canvas.Translate((size - bounds.Width * scale) / 2, (size - bounds.Height * scale) / 2);
|
||||
canvas.Scale(scale);
|
||||
canvas.DrawPicture(svg.Picture);
|
||||
|
||||
using var image = SKImage.FromBitmap(bitmap);
|
||||
using var data = image.Encode(SKEncodedImageFormat.Png, 100);
|
||||
using var pngStream = new MemoryStream(data.ToArray());
|
||||
Icon = new WindowIcon(pngStream);
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Icon loading is best-effort
|
||||
}
|
||||
}
|
||||
|
||||
protected override void OnLoaded(RoutedEventArgs e)
|
||||
{
|
||||
base.OnLoaded(e);
|
||||
|
||||
var browseTreeView = this.FindControl<BrowseTreeView>("BrowseTreePanel");
|
||||
var treeView = browseTreeView?.FindControl<TreeView>("BrowseTree");
|
||||
if (treeView != null) treeView.SelectionChanged += OnTreeSelectionChanged;
|
||||
|
||||
var contextMenu = this.FindControl<ContextMenu>("TreeContextMenu");
|
||||
if (contextMenu != null) contextMenu.Opening += OnTreeContextMenuOpening;
|
||||
|
||||
var subscribeItem = this.FindControl<MenuItem>("SubscribeMenuItem");
|
||||
if (subscribeItem != null) subscribeItem.Click += OnSubscribeClicked;
|
||||
|
||||
var viewHistoryItem = this.FindControl<MenuItem>("ViewHistoryMenuItem");
|
||||
if (viewHistoryItem != null) viewHistoryItem.Click += OnViewHistoryClicked;
|
||||
|
||||
var monitorAlarmsItem = this.FindControl<MenuItem>("MonitorAlarmsMenuItem");
|
||||
if (monitorAlarmsItem != null) monitorAlarmsItem.Click += OnMonitorAlarmsClicked;
|
||||
|
||||
var browseCertPath = this.FindControl<Button>("BrowseCertPathButton");
|
||||
if (browseCertPath != null) browseCertPath.Click += OnBrowseCertPathClicked;
|
||||
}
|
||||
|
||||
private void OnTreeSelectionChanged(object? sender, SelectionChangedEventArgs e)
|
||||
{
|
||||
if (DataContext is not MainWindowViewModel vm || sender is not TreeView treeView) return;
|
||||
|
||||
vm.SelectedTreeNode = treeView.SelectedItem as TreeNodeViewModel;
|
||||
|
||||
vm.SelectedTreeNodes.Clear();
|
||||
foreach (var item in treeView.SelectedItems)
|
||||
if (item is TreeNodeViewModel node)
|
||||
vm.SelectedTreeNodes.Add(node);
|
||||
}
|
||||
|
||||
private void OnTreeContextMenuOpening(object? sender, CancelEventArgs e)
|
||||
{
|
||||
if (DataContext is not MainWindowViewModel vm) return;
|
||||
|
||||
vm.UpdateHistoryEnabledForSelection();
|
||||
|
||||
var subscribeItem = this.FindControl<MenuItem>("SubscribeMenuItem");
|
||||
var viewHistoryItem = this.FindControl<MenuItem>("ViewHistoryMenuItem");
|
||||
var monitorAlarmsItem = this.FindControl<MenuItem>("MonitorAlarmsMenuItem");
|
||||
|
||||
if (subscribeItem != null)
|
||||
subscribeItem.IsEnabled = vm.IsConnected && vm.SelectedTreeNodes.Count > 0;
|
||||
if (viewHistoryItem != null)
|
||||
viewHistoryItem.IsEnabled = vm.IsHistoryEnabledForSelection;
|
||||
if (monitorAlarmsItem != null)
|
||||
monitorAlarmsItem.IsEnabled = vm.IsConnected && vm.SelectedTreeNodes.Count > 0;
|
||||
}
|
||||
|
||||
private async void OnSubscribeClicked(object? sender, RoutedEventArgs e)
|
||||
{
|
||||
if (DataContext is MainWindowViewModel vm)
|
||||
await vm.SubscribeSelectedNodesCommand.ExecuteAsync(null);
|
||||
}
|
||||
|
||||
private void OnViewHistoryClicked(object? sender, RoutedEventArgs e)
|
||||
{
|
||||
if (DataContext is MainWindowViewModel vm)
|
||||
vm.ViewHistoryForSelectedNodeCommand.Execute(null);
|
||||
}
|
||||
|
||||
private async void OnMonitorAlarmsClicked(object? sender, RoutedEventArgs e)
|
||||
{
|
||||
if (DataContext is MainWindowViewModel vm)
|
||||
await vm.MonitorAlarmsForSelectedNodeCommand.ExecuteAsync(null);
|
||||
}
|
||||
|
||||
private async void OnBrowseCertPathClicked(object? sender, RoutedEventArgs e)
|
||||
{
|
||||
if (DataContext is not MainWindowViewModel vm) return;
|
||||
|
||||
var dialog = new OpenFolderDialog
|
||||
{
|
||||
Title = "Select Certificate Store Folder",
|
||||
Directory = vm.CertificateStorePath
|
||||
};
|
||||
|
||||
var result = await dialog.ShowAsync(this);
|
||||
if (!string.IsNullOrEmpty(result))
|
||||
vm.CertificateStorePath = result;
|
||||
}
|
||||
|
||||
protected override void OnClosing(WindowClosingEventArgs e)
|
||||
{
|
||||
if (DataContext is MainWindowViewModel vm)
|
||||
vm.SaveSettings();
|
||||
base.OnClosing(e);
|
||||
}
|
||||
}
|
||||
@@ -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.OtOpcUa.Client.UI.ViewModels"
|
||||
x:Class="ZB.MOM.WW.OtOpcUa.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.OtOpcUa.Client.UI.Views;
|
||||
|
||||
public partial class ReadWriteView : UserControl
|
||||
{
|
||||
public ReadWriteView()
|
||||
{
|
||||
InitializeComponent();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
<UserControl xmlns="https://github.com/avaloniaui"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:vm="using:ZB.MOM.WW.OtOpcUa.Client.UI.ViewModels"
|
||||
x:Class="ZB.MOM.WW.OtOpcUa.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 Name="SubscriptionsGrid"
|
||||
ItemsSource="{Binding ActiveSubscriptions}"
|
||||
SelectedItem="{Binding SelectedSubscription}"
|
||||
SelectionMode="Extended"
|
||||
AutoGenerateColumns="False"
|
||||
IsReadOnly="True"
|
||||
HorizontalScrollBarVisibility="Auto"
|
||||
Margin="0,8,0,0">
|
||||
<DataGrid.Columns>
|
||||
<DataGridTextColumn Header="Node ID" Binding="{Binding NodeId}" Width="Auto" />
|
||||
<DataGridTextColumn Header="Value" Binding="{Binding Value}" Width="Auto" />
|
||||
<DataGridTextColumn Header="Status" Binding="{Binding Status}" Width="Auto" />
|
||||
<DataGridTextColumn Header="Timestamp" Binding="{Binding Timestamp}" Width="Auto" />
|
||||
</DataGrid.Columns>
|
||||
</DataGrid>
|
||||
</DockPanel>
|
||||
</UserControl>
|
||||
@@ -0,0 +1,51 @@
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Input;
|
||||
using Avalonia.Interactivity;
|
||||
using Avalonia.VisualTree;
|
||||
using ZB.MOM.WW.OtOpcUa.Client.UI.ViewModels;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Client.UI.Views;
|
||||
|
||||
public partial class SubscriptionsView : UserControl
|
||||
{
|
||||
public SubscriptionsView()
|
||||
{
|
||||
InitializeComponent();
|
||||
}
|
||||
|
||||
protected override void OnLoaded(RoutedEventArgs e)
|
||||
{
|
||||
base.OnLoaded(e);
|
||||
|
||||
var grid = this.FindControl<DataGrid>("SubscriptionsGrid");
|
||||
if (grid != null)
|
||||
{
|
||||
grid.DoubleTapped += OnGridDoubleTapped;
|
||||
grid.SelectionChanged += OnGridSelectionChanged;
|
||||
}
|
||||
}
|
||||
|
||||
private void OnGridSelectionChanged(object? sender, SelectionChangedEventArgs e)
|
||||
{
|
||||
if (DataContext is not SubscriptionsViewModel vm || sender is not DataGrid grid) return;
|
||||
|
||||
vm.SelectedSubscriptions.Clear();
|
||||
foreach (var item in grid.SelectedItems)
|
||||
if (item is SubscriptionItemViewModel sub)
|
||||
vm.SelectedSubscriptions.Add(sub);
|
||||
|
||||
vm.RemoveSubscriptionCommand.NotifyCanExecuteChanged();
|
||||
}
|
||||
|
||||
private void OnGridDoubleTapped(object? sender, TappedEventArgs e)
|
||||
{
|
||||
if (DataContext is not SubscriptionsViewModel vm) return;
|
||||
if (vm.SelectedSubscription is not { } item) return;
|
||||
|
||||
var parentWindow = this.FindAncestorOfType<Window>();
|
||||
if (parentWindow == null) return;
|
||||
|
||||
var writeWindow = new WriteValueWindow(vm, item.NodeId, item.Value);
|
||||
writeWindow.ShowDialog(parentWindow);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
<Window xmlns="https://github.com/avaloniaui"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
x:Class="ZB.MOM.WW.OtOpcUa.Client.UI.Views.WriteValueWindow"
|
||||
Title="Write Value"
|
||||
Width="420"
|
||||
SizeToContent="Height"
|
||||
MinHeight="280"
|
||||
WindowStartupLocation="CenterOwner"
|
||||
CanResize="False">
|
||||
<StackPanel Margin="16" Spacing="12">
|
||||
<TextBlock Text="Write Value to Node" FontWeight="Bold" FontSize="16" />
|
||||
|
||||
<StackPanel Spacing="4">
|
||||
<TextBlock Text="Node ID:" FontSize="12" Foreground="Gray" />
|
||||
<TextBlock Name="NodeIdText" FontWeight="SemiBold" />
|
||||
</StackPanel>
|
||||
|
||||
<StackPanel Spacing="4">
|
||||
<TextBlock Text="Current Value:" FontSize="12" Foreground="Gray" />
|
||||
<TextBlock Name="CurrentValueText" />
|
||||
</StackPanel>
|
||||
|
||||
<StackPanel Spacing="4">
|
||||
<TextBlock Text="New Value:" FontSize="12" Foreground="Gray" />
|
||||
<TextBox Name="WriteValueInput" Watermark="Enter value to write" />
|
||||
</StackPanel>
|
||||
|
||||
<StackPanel Spacing="4">
|
||||
<TextBlock Name="ResultText" Foreground="Gray" />
|
||||
</StackPanel>
|
||||
|
||||
<StackPanel Orientation="Horizontal" Spacing="8" HorizontalAlignment="Right">
|
||||
<Button Name="WriteButton" Content="Write" />
|
||||
<Button Name="CloseButton" Content="Close" />
|
||||
</StackPanel>
|
||||
</StackPanel>
|
||||
</Window>
|
||||
@@ -0,0 +1,77 @@
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Interactivity;
|
||||
using Avalonia.Media;
|
||||
using ZB.MOM.WW.OtOpcUa.Client.UI.ViewModels;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Client.UI.Views;
|
||||
|
||||
public partial class WriteValueWindow : Window
|
||||
{
|
||||
private readonly SubscriptionsViewModel _subscriptionsVm;
|
||||
private readonly string _nodeId;
|
||||
|
||||
public WriteValueWindow()
|
||||
{
|
||||
InitializeComponent();
|
||||
_subscriptionsVm = null!;
|
||||
_nodeId = string.Empty;
|
||||
}
|
||||
|
||||
public WriteValueWindow(SubscriptionsViewModel subscriptionsVm, string nodeId, string? currentValue)
|
||||
{
|
||||
InitializeComponent();
|
||||
_subscriptionsVm = subscriptionsVm;
|
||||
_nodeId = nodeId;
|
||||
|
||||
var nodeIdText = this.FindControl<TextBlock>("NodeIdText");
|
||||
if (nodeIdText != null) nodeIdText.Text = nodeId;
|
||||
|
||||
var currentValueText = this.FindControl<TextBlock>("CurrentValueText");
|
||||
if (currentValueText != null) currentValueText.Text = currentValue ?? "(null)";
|
||||
|
||||
// Pre-fill the write input with the current value
|
||||
var writeInput = this.FindControl<TextBox>("WriteValueInput");
|
||||
if (writeInput != null) writeInput.Text = currentValue ?? "";
|
||||
|
||||
var writeButton = this.FindControl<Button>("WriteButton");
|
||||
if (writeButton != null) writeButton.Click += OnWriteClicked;
|
||||
|
||||
var closeButton = this.FindControl<Button>("CloseButton");
|
||||
if (closeButton != null) closeButton.Click += OnCloseClicked;
|
||||
}
|
||||
|
||||
private async void OnWriteClicked(object? sender, RoutedEventArgs e)
|
||||
{
|
||||
var input = this.FindControl<TextBox>("WriteValueInput");
|
||||
var resultText = this.FindControl<TextBlock>("ResultText");
|
||||
if (input == null || resultText == null) return;
|
||||
|
||||
var rawValue = input.Text;
|
||||
if (string.IsNullOrEmpty(rawValue))
|
||||
{
|
||||
resultText.Foreground = Brushes.Red;
|
||||
resultText.Text = "Please enter a value.";
|
||||
return;
|
||||
}
|
||||
|
||||
resultText.Foreground = Brushes.Gray;
|
||||
resultText.Text = "Writing...";
|
||||
|
||||
var (success, message) = await _subscriptionsVm.ValidateAndWriteAsync(_nodeId, rawValue);
|
||||
|
||||
if (success)
|
||||
{
|
||||
Close();
|
||||
}
|
||||
else
|
||||
{
|
||||
resultText.Foreground = Brushes.Red;
|
||||
resultText.Text = message;
|
||||
}
|
||||
}
|
||||
|
||||
private void OnCloseClicked(object? sender, RoutedEventArgs e)
|
||||
{
|
||||
Close();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>WinExe</OutputType>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<RootNamespace>ZB.MOM.WW.OtOpcUa.Client.UI</RootNamespace>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Avalonia" Version="11.2.7"/>
|
||||
<PackageReference Include="Avalonia.Desktop" Version="11.2.7"/>
|
||||
<PackageReference Include="Avalonia.Svg.Skia" Version="11.2.0.2"/>
|
||||
<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="Avalonia.Diagnostics" 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.OtOpcUa.Client.Shared\ZB.MOM.WW.OtOpcUa.Client.Shared.csproj"/>
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<InternalsVisibleTo Include="ZB.MOM.WW.OtOpcUa.Client.UI.Tests"/>
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<AvaloniaResource Include="Assets\**" Exclude="Assets\app-icon.svg" />
|
||||
<EmbeddedResource Include="Assets\app-icon.svg" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
Reference in New Issue
Block a user