Add cross-platform OPC UA client stack: shared library, CLI tool, and Avalonia UI

Implements Client.Shared (IOpcUaClientService with connection lifecycle, failover,
browse, read/write, subscriptions, alarms, history, redundancy), Client.CLI (8 CliFx
commands mirroring tools/opcuacli-dotnet), and Client.UI (Avalonia desktop app with
tree browser, read/write, subscriptions, alarms, and history tabs). All three target
.NET 10 and are covered by 249 unit tests.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
Joseph Doherty
2026-03-30 15:49:42 -04:00
parent 50b85d41bd
commit a2883b82d9
109 changed files with 8571 additions and 0 deletions

View File

@@ -1,9 +1,15 @@
<Solution>
<Folder Name="/src/">
<Project Path="src/ZB.MOM.WW.LmxOpcUa.Host/ZB.MOM.WW.LmxOpcUa.Host.csproj" />
<Project Path="src/ZB.MOM.WW.LmxOpcUa.Client.Shared/ZB.MOM.WW.LmxOpcUa.Client.Shared.csproj" />
<Project Path="src/ZB.MOM.WW.LmxOpcUa.Client.CLI/ZB.MOM.WW.LmxOpcUa.Client.CLI.csproj" />
<Project Path="src/ZB.MOM.WW.LmxOpcUa.Client.UI/ZB.MOM.WW.LmxOpcUa.Client.UI.csproj" />
</Folder>
<Folder Name="/tests/">
<Project Path="tests/ZB.MOM.WW.LmxOpcUa.Tests/ZB.MOM.WW.LmxOpcUa.Tests.csproj" />
<Project Path="tests/ZB.MOM.WW.LmxOpcUa.IntegrationTests/ZB.MOM.WW.LmxOpcUa.IntegrationTests.csproj" />
<Project Path="tests/ZB.MOM.WW.LmxOpcUa.Client.Shared.Tests/ZB.MOM.WW.LmxOpcUa.Client.Shared.Tests.csproj" />
<Project Path="tests/ZB.MOM.WW.LmxOpcUa.Client.CLI.Tests/ZB.MOM.WW.LmxOpcUa.Client.CLI.Tests.csproj" />
<Project Path="tests/ZB.MOM.WW.LmxOpcUa.Client.UI.Tests/ZB.MOM.WW.LmxOpcUa.Client.UI.Tests.csproj" />
</Folder>
</Solution>

227
docs/ClientRequirements.md Normal file
View File

@@ -0,0 +1,227 @@
# OPC UA Client Requirements
## Overview
Three new .NET 10 cross-platform projects providing a shared OPC UA client library, a CLI tool, and an Avalonia desktop UI. All projects target Windows and macOS.
## Projects
| Project | Type | Purpose |
|---------|------|---------|
| `ZB.MOM.WW.LmxOpcUa.Client.Shared` | Class library | Core OPC UA client, models, interfaces |
| `ZB.MOM.WW.LmxOpcUa.Client.CLI` | Console app | Command-line interface using CliFx |
| `ZB.MOM.WW.LmxOpcUa.Client.UI` | Avalonia app | Desktop UI with tree browser, subscriptions, alarms |
| `ZB.MOM.WW.LmxOpcUa.Client.Shared.Tests` | Test project | Unit tests for shared library |
| `ZB.MOM.WW.LmxOpcUa.Client.CLI.Tests` | Test project | Unit tests for CLI commands |
| `ZB.MOM.WW.LmxOpcUa.Client.UI.Tests` | Test project | Unit tests for UI view models |
## Technology Stack
- .NET 10, C#
- OPC UA: OPCFoundation.NetStandard.Opc.Ua.Client
- Logging: Serilog
- CLI: CliFx
- UI: Avalonia 11.x with CommunityToolkit.Mvvm
- Tests: xUnit 3, Shouldly, Microsoft.Testing.Platform runner
## Client.Shared
### ConnectionSettings Model
```
EndpointUrl: string (required)
FailoverUrls: string[] (optional)
Username: string? (optional, first-class property)
Password: string? (optional, first-class property)
SecurityMode: enum (None, Sign, SignAndEncrypt) — default None
SessionTimeoutSeconds: int — default 60
AutoAcceptCertificates: bool — default true
CertificateStorePath: string? — default platform-appropriate location
```
### IOpcUaClientService Interface
Single service interface covering all OPC UA operations:
**Lifecycle:**
- `ConnectAsync(ConnectionSettings)` — connect to server, handle endpoint discovery, security, auth
- `DisconnectAsync()` — close session cleanly
- `IsConnected` property
**Read/Write:**
- `ReadValueAsync(NodeId)` — returns DataValue (value, status, timestamps)
- `WriteValueAsync(NodeId, object value)` — auto-detects target type, returns StatusCode
**Browse:**
- `BrowseAsync(NodeId? parent)` — returns list of BrowseResult (NodeId, DisplayName, NodeClass)
- Lazy-load compatible (browse one level at a time)
**Subscribe:**
- `SubscribeAsync(NodeId, int intervalMs)` — create monitored item subscription
- `UnsubscribeAsync(NodeId)` — remove monitored item
- `event DataChanged` — fires on value change with (NodeId, DataValue)
**Alarms:**
- `SubscribeAlarmsAsync(NodeId? source, int intervalMs)` — subscribe to alarm events
- `UnsubscribeAlarmsAsync()` — remove alarm subscription
- `RequestConditionRefreshAsync()` — trigger condition refresh
- `event AlarmEvent` — fires on alarm state change with AlarmEventArgs
**History:**
- `HistoryReadRawAsync(NodeId, DateTime start, DateTime end, int maxValues)` — raw historical values
- `HistoryReadAggregateAsync(NodeId, DateTime start, DateTime end, AggregateType, double intervalMs)` — aggregated values
**Redundancy:**
- `GetRedundancyInfoAsync()` — returns RedundancyInfo (mode, service level, server URIs, app URI)
**Failover:**
- Automatic failover across FailoverUrls with keep-alive monitoring
- `event ConnectionStateChanged` — fires on connect/disconnect/failover
### Models
- `BrowseResult`: NodeId, DisplayName, NodeClass, HasChildren
- `AlarmEventArgs`: SourceName, ConditionName, Severity, Message, Retain, ActiveState, AckedState, Time
- `RedundancyInfo`: Mode, ServiceLevel, ServerUris, ApplicationUri
- `ConnectionState`: enum (Disconnected, Connecting, Connected, Reconnecting)
- `AggregateType`: enum (Average, Minimum, Maximum, Count, Start, End)
### Type Conversion
Port the existing `ConvertValue` logic from the CLI tool: reads the current node value to determine the target type, then coerces the input value.
### Certificate Management
- Cross-platform certificate store path (default: `{AppData}/LmxOpcUaClient/pki/`)
- Auto-generate client certificate on first use
- Auto-accept untrusted server certificates (configurable)
### Logging
Serilog with `ILogger` passed via constructor or `Log.ForContext<T>()`. No sinks configured in the library — consumers configure sinks.
## Client.CLI
### Commands
Port all 8 commands from the existing `tools/opcuacli-dotnet/`:
| Command | Description |
|---------|-------------|
| `connect` | Test server connectivity |
| `read` | Read a node value |
| `write` | Write a value to a node |
| `browse` | Browse address space (with depth/recursive) |
| `subscribe` | Monitor node for value changes |
| `historyread` | Read historical data (raw + aggregates) |
| `alarms` | Subscribe to alarm events |
| `redundancy` | Query redundancy state |
All commands use the shared `IOpcUaClientService`. Each command:
1. Creates `ConnectionSettings` from CLI options
2. Creates `OpcUaClientService`
3. Calls the appropriate method
4. Formats and prints results
### Common Options (all commands)
- `-u, --url` (required): Endpoint URL
- `-U, --username`: Username
- `-P, --password`: Password
- `-S, --security`: Security mode (none/sign/encrypt)
- `-F, --failover-urls`: Comma-separated failover endpoints
### Logging
Serilog console sink at Warning level by default, with `--verbose` flag for Debug.
## Client.UI
### Window Layout
Single-window Avalonia application:
```
┌─────────────────────────────────────────────────────────┐
│ [Endpoint URL] [User] [Pass] [Security▼] [Connect] │
│ Redundancy: Mode=Warm ServiceLevel=200 AppUri=... │
├──────────────┬──────────────────────────────────────────┤
│ │ ┌─Read/Write─┬─Subscriptions─┬─Alarms─┬─History─┐│
│ Address │ │ Node: ns=3;s=Tag.Attr ││
│ Space │ │ Value: 42.5 ││
│ Tree │ │ Status: Good ││
│ Browser │ │ [Write: ____] [Send] ││
│ │ │ ││
│ (lazy-load) │ │ ││
│ │ └──────────────────────────────────────┘│
├──────────────┴──────────────────────────────────────────┤
│ Status: Connected | Session: abc123 | 3 subscriptions │
└─────────────────────────────────────────────────────────┘
```
### Views and ViewModels (CommunityToolkit.Mvvm)
**MainWindowViewModel:**
- Connection settings properties (bound to top bar inputs)
- ConnectCommand / DisconnectCommand (RelayCommand)
- ConnectionState property
- RedundancyInfo property
- SelectedTreeNode property
- StatusMessage property
**BrowseTreeViewModel:**
- Root nodes collection (ObservableCollection)
- Lazy-load children on expand via `BrowseAsync`
- TreeNodeViewModel: NodeId, DisplayName, NodeClass, Children, IsExpanded, HasChildren
**ReadWriteViewModel:**
- SelectedNode (from tree selection)
- CurrentValue, Status, SourceTimestamp
- WriteValue input + WriteCommand
- Auto-read on node selection
**SubscriptionsViewModel:**
- ActiveSubscriptions collection (ObservableCollection)
- AddSubscription / RemoveSubscription commands
- Live value updates dispatched to UI thread
- Columns: NodeId, Value, Status, Timestamp
**AlarmsViewModel:**
- AlarmEvents collection (ObservableCollection)
- SubscribeCommand / UnsubscribeCommand / RefreshCommand
- MonitoredNode property
- Live alarm events dispatched to UI thread
**HistoryViewModel:**
- SelectedNode (from tree selection)
- StartTime, EndTime, MaxValues, AggregateType, Interval
- ReadCommand
- Results collection (ObservableCollection)
- Columns: Timestamp, Value, Status
### UI Thread Dispatch
All events from `IOpcUaClientService` must be dispatched to the Avalonia UI thread via `Dispatcher.UIThread.Post()` before updating ObservableCollections.
## Test Projects
### Client.Shared.Tests
- ConnectionSettings validation
- Type conversion (ConvertValue)
- BrowseResult model construction
- AlarmEventArgs model construction
- FailoverUrl parsing
### Client.CLI.Tests
- Command option parsing (via CliFx test infrastructure)
- Output formatting
### Client.UI.Tests
- ViewModel property change notifications
- Command can-execute logic
- Tree node lazy-load behavior (with mocked IOpcUaClientService)
### Test Framework
- xUnit 3 with Microsoft.Testing.Platform runner
- Shouldly for assertions
- No live OPC UA server required — mock IOpcUaClientService for unit tests

View File

@@ -0,0 +1,99 @@
using CliFx;
using CliFx.Attributes;
using CliFx.Infrastructure;
using Serilog;
using ZB.MOM.WW.LmxOpcUa.Client.Shared;
using ZB.MOM.WW.LmxOpcUa.Client.Shared.Helpers;
using ZB.MOM.WW.LmxOpcUa.Client.Shared.Models;
namespace ZB.MOM.WW.LmxOpcUa.Client.CLI;
/// <summary>
/// Abstract base class for all CLI commands providing common connection options and helpers.
/// </summary>
public abstract class CommandBase : ICommand
{
internal static readonly IOpcUaClientServiceFactory DefaultFactory = new OpcUaClientServiceFactory();
private readonly IOpcUaClientServiceFactory _factory;
protected CommandBase(IOpcUaClientServiceFactory factory)
{
_factory = factory;
}
[CommandOption("url", 'u', Description = "OPC UA server endpoint URL", IsRequired = true)]
public string Url { get; init; } = default!;
[CommandOption("username", 'U', Description = "Username for authentication")]
public string? Username { get; init; }
[CommandOption("password", 'P', Description = "Password for authentication")]
public string? Password { get; init; }
[CommandOption("security", 'S', Description = "Transport security: none, sign, encrypt, signandencrypt (default: none)")]
public string Security { get; init; } = "none";
[CommandOption("failover-urls", 'F', Description = "Comma-separated failover endpoint URLs for redundancy")]
public string? FailoverUrls { get; init; }
[CommandOption("verbose", Description = "Enable verbose/debug logging")]
public bool Verbose { get; init; }
/// <summary>
/// Creates a <see cref="ConnectionSettings"/> from the common command options.
/// </summary>
protected ConnectionSettings CreateConnectionSettings()
{
var securityMode = SecurityModeMapper.FromString(Security);
var failoverUrls = !string.IsNullOrWhiteSpace(FailoverUrls)
? FailoverUrlParser.Parse(Url, FailoverUrls)
: null;
var settings = new ConnectionSettings
{
EndpointUrl = Url,
FailoverUrls = failoverUrls,
Username = Username,
Password = Password,
SecurityMode = securityMode,
AutoAcceptCertificates = true
};
return settings;
}
/// <summary>
/// Creates a new <see cref="IOpcUaClientService"/>, connects it using the common options,
/// and returns both the service and the connection info.
/// </summary>
protected async Task<(IOpcUaClientService Service, ConnectionInfo Info)> CreateServiceAndConnectAsync(CancellationToken ct)
{
var service = _factory.Create();
var settings = CreateConnectionSettings();
var info = await service.ConnectAsync(settings, ct);
return (service, info);
}
/// <summary>
/// Configures Serilog based on the verbose flag.
/// </summary>
protected void ConfigureLogging()
{
var config = new LoggerConfiguration();
if (Verbose)
{
config.MinimumLevel.Debug()
.WriteTo.Console();
}
else
{
config.MinimumLevel.Warning()
.WriteTo.Console();
}
Log.Logger = config.CreateLogger();
}
public abstract ValueTask ExecuteAsync(IConsole console);
}

View File

@@ -0,0 +1,86 @@
using CliFx.Attributes;
using CliFx.Infrastructure;
using ZB.MOM.WW.LmxOpcUa.Client.CLI.Helpers;
using ZB.MOM.WW.LmxOpcUa.Client.Shared;
namespace ZB.MOM.WW.LmxOpcUa.Client.CLI.Commands;
[Command("alarms", Description = "Subscribe to alarm events")]
public class AlarmsCommand : CommandBase
{
[CommandOption("node", 'n', Description = "Node ID to monitor for events (default: Server node)")]
public string? NodeId { get; init; }
[CommandOption("interval", 'i', Description = "Publishing interval in milliseconds")]
public int Interval { get; init; } = 1000;
[CommandOption("refresh", Description = "Request a ConditionRefresh after subscribing")]
public bool Refresh { get; init; }
public AlarmsCommand(IOpcUaClientServiceFactory factory) : base(factory) { }
public override async ValueTask ExecuteAsync(IConsole console)
{
ConfigureLogging();
IOpcUaClientService? service = null;
try
{
var ct = console.RegisterCancellationHandler();
(service, _) = await CreateServiceAndConnectAsync(ct);
var sourceNodeId = NodeIdParser.Parse(NodeId);
service.AlarmEvent += (_, e) =>
{
console.Output.WriteLine($"[{e.Time:O}] ALARM {e.SourceName}");
console.Output.WriteLine($" Condition: {e.ConditionName}");
var activeStr = e.ActiveState ? "Active" : "Inactive";
var ackedStr = e.AckedState ? "Acknowledged" : "Unacknowledged";
console.Output.WriteLine($" State: {activeStr}, {ackedStr}");
console.Output.WriteLine($" Severity: {e.Severity}");
if (!string.IsNullOrEmpty(e.Message))
console.Output.WriteLine($" Message: {e.Message}");
console.Output.WriteLine($" Retain: {e.Retain}");
console.Output.WriteLine();
};
await service.SubscribeAlarmsAsync(sourceNodeId, Interval, ct);
await console.Output.WriteLineAsync(
$"Subscribed to alarm events (interval: {Interval}ms). Press Ctrl+C to stop.");
if (Refresh)
{
try
{
await service.RequestConditionRefreshAsync(ct);
await console.Output.WriteLineAsync("Condition refresh requested.");
}
catch (Exception ex)
{
await console.Output.WriteLineAsync($"Condition refresh not supported: {ex.Message}");
}
}
// Wait until cancellation
try
{
await Task.Delay(Timeout.Infinite, ct);
}
catch (OperationCanceledException)
{
// Expected on Ctrl+C
}
await service.UnsubscribeAlarmsAsync(default);
await console.Output.WriteLineAsync("Unsubscribed.");
}
finally
{
if (service != null)
{
await service.DisconnectAsync();
service.Dispose();
}
}
}
}

View File

@@ -0,0 +1,79 @@
using CliFx.Attributes;
using CliFx.Infrastructure;
using Opc.Ua;
using ZB.MOM.WW.LmxOpcUa.Client.CLI.Helpers;
using ZB.MOM.WW.LmxOpcUa.Client.Shared;
using BrowseResult = ZB.MOM.WW.LmxOpcUa.Client.Shared.Models.BrowseResult;
namespace ZB.MOM.WW.LmxOpcUa.Client.CLI.Commands;
[Command("browse", Description = "Browse the OPC UA address space")]
public class BrowseCommand : CommandBase
{
[CommandOption("node", 'n', Description = "Node ID to browse (default: Objects folder)")]
public string? NodeId { get; init; }
[CommandOption("depth", 'd', Description = "Maximum browse depth")]
public int Depth { get; init; } = 1;
[CommandOption("recursive", 'r', Description = "Browse recursively (uses --depth as max depth)")]
public bool Recursive { get; init; }
public BrowseCommand(IOpcUaClientServiceFactory factory) : base(factory) { }
public override async ValueTask ExecuteAsync(IConsole console)
{
ConfigureLogging();
IOpcUaClientService? service = null;
try
{
var ct = console.RegisterCancellationHandler();
(service, _) = await CreateServiceAndConnectAsync(ct);
var startNode = NodeIdParser.Parse(NodeId);
var maxDepth = Recursive ? Depth : 1;
await BrowseNodeAsync(service, console, startNode, maxDepth, 0, ct);
}
finally
{
if (service != null)
{
await service.DisconnectAsync();
service.Dispose();
}
}
}
private static async Task BrowseNodeAsync(
IOpcUaClientService service,
IConsole console,
NodeId? nodeId,
int maxDepth,
int currentDepth,
CancellationToken ct)
{
var indent = new string(' ', currentDepth * 2);
var results = await service.BrowseAsync(nodeId, ct);
foreach (var result in results)
{
var marker = result.NodeClass switch
{
"Object" => "[Object]",
"Variable" => "[Variable]",
"Method" => "[Method]",
_ => $"[{result.NodeClass}]"
};
await console.Output.WriteLineAsync(
$"{indent}{marker} {result.DisplayName} (NodeId: {result.NodeId})");
if (currentDepth + 1 < maxDepth && result.HasChildren)
{
var childNodeId = NodeIdParser.Parse(result.NodeId);
await BrowseNodeAsync(service, console, childNodeId, maxDepth, currentDepth + 1, ct);
}
}
}
}

View File

@@ -0,0 +1,35 @@
using CliFx.Attributes;
using CliFx.Infrastructure;
using ZB.MOM.WW.LmxOpcUa.Client.Shared;
namespace ZB.MOM.WW.LmxOpcUa.Client.CLI.Commands;
[Command("connect", Description = "Test connection to an OPC UA server")]
public class ConnectCommand : CommandBase
{
public ConnectCommand(IOpcUaClientServiceFactory factory) : base(factory) { }
public override async ValueTask ExecuteAsync(IConsole console)
{
ConfigureLogging();
IOpcUaClientService? service = null;
try
{
(service, var info) = await CreateServiceAndConnectAsync(console.RegisterCancellationHandler());
await console.Output.WriteLineAsync($"Connected to: {info.EndpointUrl}");
await console.Output.WriteLineAsync($"Server: {info.ServerName}");
await console.Output.WriteLineAsync($"Security Mode: {info.SecurityMode}");
await console.Output.WriteLineAsync($"Security Policy: {info.SecurityPolicyUri}");
await console.Output.WriteLineAsync("Connection successful.");
}
finally
{
if (service != null)
{
await service.DisconnectAsync();
service.Dispose();
}
}
}
}

View File

@@ -0,0 +1,106 @@
using CliFx.Attributes;
using CliFx.Infrastructure;
using Opc.Ua;
using ZB.MOM.WW.LmxOpcUa.Client.CLI.Helpers;
using ZB.MOM.WW.LmxOpcUa.Client.Shared;
using ZB.MOM.WW.LmxOpcUa.Client.Shared.Models;
namespace ZB.MOM.WW.LmxOpcUa.Client.CLI.Commands;
[Command("historyread", Description = "Read historical data from a node")]
public class HistoryReadCommand : CommandBase
{
[CommandOption("node", 'n', Description = "Node ID (e.g. ns=2;s=MyNode)", IsRequired = true)]
public string NodeId { get; init; } = default!;
[CommandOption("start", Description = "Start time (ISO 8601 or date string, default: 24 hours ago)")]
public string? StartTime { get; init; }
[CommandOption("end", Description = "End time (ISO 8601 or date string, default: now)")]
public string? EndTime { get; init; }
[CommandOption("max", Description = "Maximum number of values to return")]
public int MaxValues { get; init; } = 1000;
[CommandOption("aggregate", Description = "Aggregate function: Average, Minimum, Maximum, Count, Start, End")]
public string? Aggregate { get; init; }
[CommandOption("interval", Description = "Processing interval in milliseconds for aggregates")]
public double IntervalMs { get; init; } = 3600000;
public HistoryReadCommand(IOpcUaClientServiceFactory factory) : base(factory) { }
public override async ValueTask ExecuteAsync(IConsole console)
{
ConfigureLogging();
IOpcUaClientService? service = null;
try
{
var ct = console.RegisterCancellationHandler();
(service, _) = await CreateServiceAndConnectAsync(ct);
var nodeId = NodeIdParser.ParseRequired(NodeId);
var start = string.IsNullOrEmpty(StartTime)
? DateTime.UtcNow.AddHours(-24)
: DateTime.Parse(StartTime).ToUniversalTime();
var end = string.IsNullOrEmpty(EndTime)
? DateTime.UtcNow
: DateTime.Parse(EndTime).ToUniversalTime();
IReadOnlyList<DataValue> values;
if (string.IsNullOrEmpty(Aggregate))
{
await console.Output.WriteLineAsync(
$"History for {NodeId} ({start:yyyy-MM-dd HH:mm} -> {end:yyyy-MM-dd HH:mm})");
values = await service.HistoryReadRawAsync(nodeId, start, end, MaxValues, ct);
}
else
{
var aggregateType = ParseAggregateType(Aggregate);
await console.Output.WriteLineAsync(
$"History for {NodeId} ({Aggregate}, interval={IntervalMs}ms)");
values = await service.HistoryReadAggregateAsync(
nodeId, start, end, aggregateType, IntervalMs, ct);
}
await console.Output.WriteLineAsync();
await console.Output.WriteLineAsync($"{"Timestamp",-35} {"Value",-15} {"Status"}");
foreach (var dv in values)
{
var status = StatusCode.IsGood(dv.StatusCode) ? "Good"
: StatusCode.IsBad(dv.StatusCode) ? "Bad"
: "Uncertain";
await console.Output.WriteLineAsync(
$"{dv.SourceTimestamp.ToString("O"),-35} {dv.Value,-15} {status}");
}
await console.Output.WriteLineAsync();
await console.Output.WriteLineAsync($"{values.Count} values returned.");
}
finally
{
if (service != null)
{
await service.DisconnectAsync();
service.Dispose();
}
}
}
private static AggregateType ParseAggregateType(string name)
{
return name.Trim().ToLowerInvariant() switch
{
"average" or "avg" => AggregateType.Average,
"minimum" or "min" => AggregateType.Minimum,
"maximum" or "max" => AggregateType.Maximum,
"count" => AggregateType.Count,
"start" or "first" => AggregateType.Start,
"end" or "last" => AggregateType.End,
_ => throw new ArgumentException(
$"Unknown aggregate: '{name}'. Supported: Average, Minimum, Maximum, Count, Start, End")
};
}
}

View File

@@ -0,0 +1,43 @@
using CliFx.Attributes;
using CliFx.Infrastructure;
using ZB.MOM.WW.LmxOpcUa.Client.CLI.Helpers;
using ZB.MOM.WW.LmxOpcUa.Client.Shared;
namespace ZB.MOM.WW.LmxOpcUa.Client.CLI.Commands;
[Command("read", Description = "Read a value from a node")]
public class ReadCommand : CommandBase
{
[CommandOption("node", 'n', Description = "Node ID (e.g. ns=2;s=MyNode)", IsRequired = true)]
public string NodeId { get; init; } = default!;
public ReadCommand(IOpcUaClientServiceFactory factory) : base(factory) { }
public override async ValueTask ExecuteAsync(IConsole console)
{
ConfigureLogging();
IOpcUaClientService? service = null;
try
{
var ct = console.RegisterCancellationHandler();
(service, _) = await CreateServiceAndConnectAsync(ct);
var nodeId = NodeIdParser.ParseRequired(NodeId);
var value = await service.ReadValueAsync(nodeId, ct);
await console.Output.WriteLineAsync($"Node: {NodeId}");
await console.Output.WriteLineAsync($"Value: {value.Value}");
await console.Output.WriteLineAsync($"Status: {value.StatusCode}");
await console.Output.WriteLineAsync($"Source Time: {value.SourceTimestamp:O}");
await console.Output.WriteLineAsync($"Server Time: {value.ServerTimestamp:O}");
}
finally
{
if (service != null)
{
await service.DisconnectAsync();
service.Dispose();
}
}
}
}

View File

@@ -0,0 +1,46 @@
using CliFx.Attributes;
using CliFx.Infrastructure;
using ZB.MOM.WW.LmxOpcUa.Client.Shared;
namespace ZB.MOM.WW.LmxOpcUa.Client.CLI.Commands;
[Command("redundancy", Description = "Read redundancy state from an OPC UA server")]
public class RedundancyCommand : CommandBase
{
public RedundancyCommand(IOpcUaClientServiceFactory factory) : base(factory) { }
public override async ValueTask ExecuteAsync(IConsole console)
{
ConfigureLogging();
IOpcUaClientService? service = null;
try
{
var ct = console.RegisterCancellationHandler();
(service, _) = await CreateServiceAndConnectAsync(ct);
var info = await service.GetRedundancyInfoAsync(ct);
await console.Output.WriteLineAsync($"Redundancy Mode: {info.Mode}");
await console.Output.WriteLineAsync($"Service Level: {info.ServiceLevel}");
if (info.ServerUris.Length > 0)
{
await console.Output.WriteLineAsync("Server URIs:");
foreach (var uri in info.ServerUris)
{
await console.Output.WriteLineAsync($" - {uri}");
}
}
await console.Output.WriteLineAsync($"Application URI: {info.ApplicationUri}");
}
finally
{
if (service != null)
{
await service.DisconnectAsync();
service.Dispose();
}
}
}
}

View File

@@ -0,0 +1,62 @@
using CliFx.Attributes;
using CliFx.Infrastructure;
using ZB.MOM.WW.LmxOpcUa.Client.CLI.Helpers;
using ZB.MOM.WW.LmxOpcUa.Client.Shared;
namespace ZB.MOM.WW.LmxOpcUa.Client.CLI.Commands;
[Command("subscribe", Description = "Monitor a node for value changes")]
public class SubscribeCommand : CommandBase
{
[CommandOption("node", 'n', Description = "Node ID to monitor", IsRequired = true)]
public string NodeId { get; init; } = default!;
[CommandOption("interval", 'i', Description = "Sampling interval in milliseconds")]
public int Interval { get; init; } = 1000;
public SubscribeCommand(IOpcUaClientServiceFactory factory) : base(factory) { }
public override async ValueTask ExecuteAsync(IConsole console)
{
ConfigureLogging();
IOpcUaClientService? service = null;
try
{
var ct = console.RegisterCancellationHandler();
(service, _) = await CreateServiceAndConnectAsync(ct);
var nodeId = NodeIdParser.ParseRequired(NodeId);
service.DataChanged += (_, e) =>
{
console.Output.WriteLine(
$"[{e.Value.SourceTimestamp:O}] {e.NodeId} = {e.Value.Value} ({e.Value.StatusCode})");
};
await service.SubscribeAsync(nodeId, Interval, ct);
await console.Output.WriteLineAsync(
$"Subscribed to {NodeId} (interval: {Interval}ms). Press Ctrl+C to stop.");
// Wait until cancellation
try
{
await Task.Delay(Timeout.Infinite, ct);
}
catch (OperationCanceledException)
{
// Expected on Ctrl+C
}
await service.UnsubscribeAsync(nodeId, default);
await console.Output.WriteLineAsync("Unsubscribed.");
}
finally
{
if (service != null)
{
await service.DisconnectAsync();
service.Dispose();
}
}
}
}

View File

@@ -0,0 +1,52 @@
using CliFx.Attributes;
using CliFx.Infrastructure;
using Opc.Ua;
using ZB.MOM.WW.LmxOpcUa.Client.CLI.Helpers;
using ZB.MOM.WW.LmxOpcUa.Client.Shared;
using ZB.MOM.WW.LmxOpcUa.Client.Shared.Helpers;
namespace ZB.MOM.WW.LmxOpcUa.Client.CLI.Commands;
[Command("write", Description = "Write a value to a node")]
public class WriteCommand : CommandBase
{
[CommandOption("node", 'n', Description = "Node ID (e.g. ns=2;s=MyNode)", IsRequired = true)]
public string NodeId { get; init; } = default!;
[CommandOption("value", 'v', Description = "Value to write", IsRequired = true)]
public string Value { get; init; } = default!;
public WriteCommand(IOpcUaClientServiceFactory factory) : base(factory) { }
public override async ValueTask ExecuteAsync(IConsole console)
{
ConfigureLogging();
IOpcUaClientService? service = null;
try
{
var ct = console.RegisterCancellationHandler();
(service, _) = await CreateServiceAndConnectAsync(ct);
var nodeId = NodeIdParser.ParseRequired(NodeId);
// Read current value to determine type for conversion
var currentValue = await service.ReadValueAsync(nodeId, ct);
var typedValue = ValueConverter.ConvertValue(Value, currentValue.Value);
var statusCode = await service.WriteValueAsync(nodeId, typedValue, ct);
if (StatusCode.IsGood(statusCode))
await console.Output.WriteLineAsync($"Write successful: {NodeId} = {typedValue}");
else
await console.Output.WriteLineAsync($"Write failed: {statusCode}");
}
finally
{
if (service != null)
{
await service.DisconnectAsync();
service.Dispose();
}
}
}
}

View File

@@ -0,0 +1,61 @@
using Opc.Ua;
namespace ZB.MOM.WW.LmxOpcUa.Client.CLI.Helpers;
/// <summary>
/// Parses node ID strings into OPC UA <see cref="NodeId"/> objects.
/// Supports standard OPC UA format (e.g., "ns=2;s=MyNode", "i=85") and bare numeric IDs.
/// </summary>
public static class NodeIdParser
{
/// <summary>
/// Parses a string into a <see cref="NodeId"/>. Returns <c>null</c> if the input is null or empty.
/// </summary>
/// <param name="nodeIdString">The node ID string to parse.</param>
/// <returns>A parsed <see cref="NodeId"/>, or <c>null</c> if input is null/empty.</returns>
/// <exception cref="FormatException">Thrown when the string cannot be parsed as a valid NodeId.</exception>
public static NodeId? Parse(string? nodeIdString)
{
if (string.IsNullOrWhiteSpace(nodeIdString))
return null;
var trimmed = nodeIdString.Trim();
// Standard OPC UA format: ns=X;s=..., ns=X;i=..., ns=X;g=..., ns=X;b=...
// Also: s=..., i=..., g=..., b=... (namespace 0 implied)
if (trimmed.Contains('='))
{
try
{
return NodeId.Parse(trimmed);
}
catch (Exception ex)
{
throw new FormatException($"Invalid node ID format: '{nodeIdString}'", ex);
}
}
// Bare numeric: treat as namespace 0, numeric identifier
if (uint.TryParse(trimmed, out var numericId))
{
return new NodeId(numericId);
}
throw new FormatException($"Invalid node ID format: '{nodeIdString}'. Expected format like 'ns=2;s=MyNode', 'i=85', or a numeric ID.");
}
/// <summary>
/// Parses a string into a <see cref="NodeId"/>, throwing if the input is null or empty.
/// </summary>
/// <param name="nodeIdString">The node ID string to parse.</param>
/// <returns>A parsed <see cref="NodeId"/>.</returns>
/// <exception cref="ArgumentException">Thrown when the input is null or empty.</exception>
/// <exception cref="FormatException">Thrown when the string cannot be parsed as a valid NodeId.</exception>
public static NodeId ParseRequired(string? nodeIdString)
{
var result = Parse(nodeIdString);
if (result == null)
throw new ArgumentException("Node ID is required but was not provided.");
return result;
}
}

View File

@@ -0,0 +1,18 @@
using CliFx;
using ZB.MOM.WW.LmxOpcUa.Client.CLI;
return await new CliApplicationBuilder()
.AddCommandsFromThisAssembly()
.UseTypeActivator(type =>
{
// Inject the default factory into commands that derive from CommandBase
if (type.IsSubclassOf(typeof(CommandBase)))
{
return Activator.CreateInstance(type, CommandBase.DefaultFactory)!;
}
return Activator.CreateInstance(type)!;
})
.SetExecutableName("lmxopcua-cli")
.SetDescription("LmxOpcUa CLI - command-line client for the LmxOpcUa OPC UA server")
.Build()
.RunAsync(args);

View File

@@ -0,0 +1,21 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<RootNamespace>ZB.MOM.WW.LmxOpcUa.Client.CLI</RootNamespace>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="CliFx" Version="2.3.6" />
<PackageReference Include="Serilog" Version="4.2.0" />
<PackageReference Include="Serilog.Sinks.Console" Version="6.0.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\ZB.MOM.WW.LmxOpcUa.Client.Shared\ZB.MOM.WW.LmxOpcUa.Client.Shared.csproj" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,75 @@
using Opc.Ua;
using Opc.Ua.Configuration;
using Serilog;
using ZB.MOM.WW.LmxOpcUa.Client.Shared.Models;
namespace ZB.MOM.WW.LmxOpcUa.Client.Shared.Adapters;
/// <summary>
/// Production implementation that builds a real OPC UA ApplicationConfiguration.
/// </summary>
internal sealed class DefaultApplicationConfigurationFactory : IApplicationConfigurationFactory
{
private static readonly ILogger Logger = Log.ForContext<DefaultApplicationConfigurationFactory>();
public async Task<ApplicationConfiguration> CreateAsync(ConnectionSettings settings, CancellationToken ct)
{
var storePath = settings.CertificateStorePath;
var config = new ApplicationConfiguration
{
ApplicationName = "LmxOpcUaClient",
ApplicationUri = "urn:localhost:LmxOpcUaClient",
ApplicationType = ApplicationType.Client,
SecurityConfiguration = new SecurityConfiguration
{
ApplicationCertificate = new CertificateIdentifier
{
StoreType = CertificateStoreType.Directory,
StorePath = Path.Combine(storePath, "own")
},
TrustedIssuerCertificates = new CertificateTrustList
{
StoreType = CertificateStoreType.Directory,
StorePath = Path.Combine(storePath, "issuer")
},
TrustedPeerCertificates = new CertificateTrustList
{
StoreType = CertificateStoreType.Directory,
StorePath = Path.Combine(storePath, "trusted")
},
RejectedCertificateStore = new CertificateTrustList
{
StoreType = CertificateStoreType.Directory,
StorePath = Path.Combine(storePath, "rejected")
},
AutoAcceptUntrustedCertificates = settings.AutoAcceptCertificates
},
ClientConfiguration = new ClientConfiguration
{
DefaultSessionTimeout = settings.SessionTimeoutSeconds * 1000
}
};
await config.Validate(ApplicationType.Client);
if (settings.AutoAcceptCertificates)
{
config.CertificateValidator.CertificateValidation += (_, e) => e.Accept = true;
}
if (settings.SecurityMode != Models.SecurityMode.None)
{
var app = new ApplicationInstance
{
ApplicationName = "LmxOpcUaClient",
ApplicationType = ApplicationType.Client,
ApplicationConfiguration = config
};
await app.CheckApplicationInstanceCertificatesAsync(false, 2048);
}
Logger.Debug("ApplicationConfiguration created for {EndpointUrl}", settings.EndpointUrl);
return config;
}
}

View File

@@ -0,0 +1,62 @@
using Opc.Ua;
using Opc.Ua.Client;
using Serilog;
namespace ZB.MOM.WW.LmxOpcUa.Client.Shared.Adapters;
/// <summary>
/// Production endpoint discovery that queries the real server.
/// </summary>
internal sealed class DefaultEndpointDiscovery : IEndpointDiscovery
{
private static readonly ILogger Logger = Log.ForContext<DefaultEndpointDiscovery>();
public EndpointDescription SelectEndpoint(ApplicationConfiguration config, string endpointUrl, MessageSecurityMode requestedMode)
{
if (requestedMode == MessageSecurityMode.None)
{
#pragma warning disable CS0618 // Acceptable for endpoint selection
return CoreClientUtils.SelectEndpoint(config, endpointUrl, false);
#pragma warning restore CS0618
}
using var client = DiscoveryClient.Create(new Uri(endpointUrl));
var allEndpoints = client.GetEndpoints(null);
EndpointDescription? best = null;
foreach (var ep in allEndpoints)
{
if (ep.SecurityMode != requestedMode)
continue;
if (best == null)
{
best = ep;
continue;
}
if (ep.SecurityPolicyUri == SecurityPolicies.Basic256Sha256)
best = ep;
}
if (best == null)
{
var available = string.Join(", ", allEndpoints.Select(e => $"{e.SecurityMode}/{e.SecurityPolicyUri}"));
throw new InvalidOperationException(
$"No endpoint found with security mode '{requestedMode}'. Available endpoints: {available}");
}
// Rewrite endpoint URL hostname to match user-supplied hostname
var serverUri = new Uri(best.EndpointUrl);
var requestedUri = new Uri(endpointUrl);
if (serverUri.Host != requestedUri.Host)
{
var builder = new UriBuilder(best.EndpointUrl) { Host = requestedUri.Host };
best.EndpointUrl = builder.ToString();
Logger.Debug("Rewrote endpoint host from {ServerHost} to {RequestedHost}", serverUri.Host, requestedUri.Host);
}
return best;
}
}

View File

@@ -0,0 +1,230 @@
using Opc.Ua;
using Opc.Ua.Client;
using Serilog;
namespace ZB.MOM.WW.LmxOpcUa.Client.Shared.Adapters;
/// <summary>
/// Production session adapter wrapping a real OPC UA Session.
/// </summary>
internal sealed class DefaultSessionAdapter : ISessionAdapter
{
private static readonly ILogger Logger = Log.ForContext<DefaultSessionAdapter>();
private readonly Session _session;
public DefaultSessionAdapter(Session session)
{
_session = session;
}
public bool Connected => _session.Connected;
public string SessionId => _session.SessionId?.ToString() ?? string.Empty;
public string SessionName => _session.SessionName ?? string.Empty;
public string EndpointUrl => _session.Endpoint?.EndpointUrl ?? string.Empty;
public string ServerName => _session.Endpoint?.Server?.ApplicationName?.Text ?? string.Empty;
public string SecurityMode => _session.Endpoint?.SecurityMode.ToString() ?? string.Empty;
public string SecurityPolicyUri => _session.Endpoint?.SecurityPolicyUri ?? string.Empty;
public NamespaceTable NamespaceUris => _session.NamespaceUris;
public void RegisterKeepAliveHandler(Action<bool> callback)
{
_session.KeepAlive += (_, e) =>
{
var isGood = e.Status == null || ServiceResult.IsGood(e.Status);
callback(isGood);
};
}
public async Task<DataValue> ReadValueAsync(NodeId nodeId, CancellationToken ct)
{
return await _session.ReadValueAsync(nodeId, ct);
}
public async Task<StatusCode> WriteValueAsync(NodeId nodeId, DataValue value, CancellationToken ct)
{
var writeValue = new WriteValue
{
NodeId = nodeId,
AttributeId = Attributes.Value,
Value = value
};
var writeCollection = new WriteValueCollection { writeValue };
var response = await _session.WriteAsync(null, writeCollection, ct);
return response.Results[0];
}
public async Task<(byte[]? ContinuationPoint, ReferenceDescriptionCollection References)> BrowseAsync(
NodeId nodeId, uint nodeClassMask, CancellationToken ct)
{
var (_, continuationPoint, references) = await _session.BrowseAsync(
null,
null,
nodeId,
0u,
BrowseDirection.Forward,
ReferenceTypeIds.HierarchicalReferences,
true,
nodeClassMask);
return (continuationPoint, references ?? new ReferenceDescriptionCollection());
}
public async Task<(byte[]? ContinuationPoint, ReferenceDescriptionCollection References)> BrowseNextAsync(
byte[] continuationPoint, CancellationToken ct)
{
var (_, nextCp, nextRefs) = await _session.BrowseNextAsync(null, false, continuationPoint);
return (nextCp, nextRefs ?? new ReferenceDescriptionCollection());
}
public async Task<bool> HasChildrenAsync(NodeId nodeId, CancellationToken ct)
{
var (_, _, references) = await _session.BrowseAsync(
null,
null,
nodeId,
1u,
BrowseDirection.Forward,
ReferenceTypeIds.HierarchicalReferences,
true,
0u);
return references != null && references.Count > 0;
}
public async Task<IReadOnlyList<DataValue>> HistoryReadRawAsync(
NodeId nodeId, DateTime startTime, DateTime endTime, int maxValues, CancellationToken ct)
{
var details = new ReadRawModifiedDetails
{
StartTime = startTime,
EndTime = endTime,
NumValuesPerNode = (uint)maxValues,
IsReadModified = false,
ReturnBounds = false
};
var nodesToRead = new HistoryReadValueIdCollection
{
new HistoryReadValueId { NodeId = nodeId }
};
var allValues = new List<DataValue>();
byte[]? continuationPoint = null;
do
{
if (continuationPoint != null)
nodesToRead[0].ContinuationPoint = continuationPoint;
_session.HistoryRead(
null,
new ExtensionObject(details),
TimestampsToReturn.Source,
continuationPoint != null,
nodesToRead,
out var results,
out _);
if (results == null || results.Count == 0)
break;
var result = results[0];
if (StatusCode.IsBad(result.StatusCode))
break;
if (result.HistoryData is ExtensionObject ext && ext.Body is HistoryData historyData)
{
allValues.AddRange(historyData.DataValues);
}
continuationPoint = result.ContinuationPoint;
}
while (continuationPoint != null && continuationPoint.Length > 0 && allValues.Count < maxValues);
return allValues;
}
public async Task<IReadOnlyList<DataValue>> HistoryReadAggregateAsync(
NodeId nodeId, DateTime startTime, DateTime endTime, NodeId aggregateId, double intervalMs, CancellationToken ct)
{
var details = new ReadProcessedDetails
{
StartTime = startTime,
EndTime = endTime,
ProcessingInterval = intervalMs,
AggregateType = new NodeIdCollection { aggregateId }
};
var nodesToRead = new HistoryReadValueIdCollection
{
new HistoryReadValueId { NodeId = nodeId }
};
_session.HistoryRead(
null,
new ExtensionObject(details),
TimestampsToReturn.Source,
false,
nodesToRead,
out var results,
out _);
var allValues = new List<DataValue>();
if (results != null && results.Count > 0)
{
var result = results[0];
if (!StatusCode.IsBad(result.StatusCode) &&
result.HistoryData is ExtensionObject ext &&
ext.Body is HistoryData historyData)
{
allValues.AddRange(historyData.DataValues);
}
}
return allValues;
}
public async Task<ISubscriptionAdapter> CreateSubscriptionAsync(int publishingIntervalMs, CancellationToken ct)
{
var subscription = new Subscription(_session.DefaultSubscription)
{
PublishingInterval = publishingIntervalMs,
DisplayName = "ClientShared_Subscription"
};
_session.AddSubscription(subscription);
await subscription.CreateAsync(ct);
return new DefaultSubscriptionAdapter(subscription);
}
public async Task CloseAsync(CancellationToken ct)
{
try
{
if (_session.Connected)
{
_session.Close();
}
}
catch (Exception ex)
{
Logger.Warning(ex, "Error closing session");
}
}
public void Dispose()
{
try
{
if (_session.Connected)
{
_session.Close();
}
}
catch { }
_session.Dispose();
}
}

View File

@@ -0,0 +1,37 @@
using Opc.Ua;
using Opc.Ua.Client;
using Serilog;
namespace ZB.MOM.WW.LmxOpcUa.Client.Shared.Adapters;
/// <summary>
/// Production session factory that creates real OPC UA sessions.
/// </summary>
internal sealed class DefaultSessionFactory : ISessionFactory
{
private static readonly ILogger Logger = Log.ForContext<DefaultSessionFactory>();
public async Task<ISessionAdapter> CreateSessionAsync(
ApplicationConfiguration config,
EndpointDescription endpoint,
string sessionName,
uint sessionTimeoutMs,
UserIdentity identity,
CancellationToken ct)
{
var endpointConfig = EndpointConfiguration.Create(config);
var configuredEndpoint = new ConfiguredEndpoint(null, endpoint, endpointConfig);
var session = await Session.Create(
config,
configuredEndpoint,
false,
sessionName,
sessionTimeoutMs,
identity,
null);
Logger.Information("Session created: {SessionName} -> {EndpointUrl}", sessionName, endpoint.EndpointUrl);
return new DefaultSessionAdapter(session);
}
}

View File

@@ -0,0 +1,121 @@
using Opc.Ua;
using Opc.Ua.Client;
using Serilog;
namespace ZB.MOM.WW.LmxOpcUa.Client.Shared.Adapters;
/// <summary>
/// Production subscription adapter wrapping a real OPC UA Subscription.
/// </summary>
internal sealed class DefaultSubscriptionAdapter : ISubscriptionAdapter
{
private static readonly ILogger Logger = Log.ForContext<DefaultSubscriptionAdapter>();
private readonly Subscription _subscription;
private readonly Dictionary<uint, MonitoredItem> _monitoredItems = new();
public DefaultSubscriptionAdapter(Subscription subscription)
{
_subscription = subscription;
}
public uint SubscriptionId => _subscription.Id;
public async Task<uint> AddDataChangeMonitoredItemAsync(
NodeId nodeId, int samplingIntervalMs, Action<string, DataValue> onDataChange, CancellationToken ct)
{
var item = new MonitoredItem(_subscription.DefaultItem)
{
StartNodeId = nodeId,
DisplayName = nodeId.ToString(),
SamplingInterval = samplingIntervalMs
};
item.Notification += (_, e) =>
{
if (e.NotificationValue is MonitoredItemNotification notification)
{
onDataChange(nodeId.ToString(), notification.Value);
}
};
_subscription.AddItem(item);
await _subscription.ApplyChangesAsync(ct);
var handle = item.ClientHandle;
_monitoredItems[handle] = item;
Logger.Debug("Added data change monitored item for {NodeId}, handle={Handle}", nodeId, handle);
return handle;
}
public async Task RemoveMonitoredItemAsync(uint clientHandle, CancellationToken ct)
{
if (!_monitoredItems.TryGetValue(clientHandle, out var item))
return;
_subscription.RemoveItem(item);
await _subscription.ApplyChangesAsync(ct);
_monitoredItems.Remove(clientHandle);
Logger.Debug("Removed monitored item handle={Handle}", clientHandle);
}
public async Task<uint> AddEventMonitoredItemAsync(
NodeId nodeId, int samplingIntervalMs, EventFilter filter, Action<EventFieldList> onEvent, CancellationToken ct)
{
var item = new MonitoredItem(_subscription.DefaultItem)
{
StartNodeId = nodeId,
DisplayName = "AlarmMonitor",
SamplingInterval = samplingIntervalMs,
NodeClass = NodeClass.Object,
AttributeId = Attributes.EventNotifier,
Filter = filter
};
item.Notification += (_, e) =>
{
if (e.NotificationValue is EventFieldList eventFields)
{
onEvent(eventFields);
}
};
_subscription.AddItem(item);
await _subscription.ApplyChangesAsync(ct);
var handle = item.ClientHandle;
_monitoredItems[handle] = item;
Logger.Debug("Added event monitored item for {NodeId}, handle={Handle}", nodeId, handle);
return handle;
}
public async Task ConditionRefreshAsync(CancellationToken ct)
{
await _subscription.ConditionRefreshAsync(ct);
}
public async Task DeleteAsync(CancellationToken ct)
{
try
{
await _subscription.DeleteAsync(true);
}
catch (Exception ex)
{
Logger.Warning(ex, "Error deleting subscription");
}
_monitoredItems.Clear();
}
public void Dispose()
{
try
{
_subscription.Delete(true);
}
catch { }
_monitoredItems.Clear();
}
}

View File

@@ -0,0 +1,15 @@
using Opc.Ua;
using ZB.MOM.WW.LmxOpcUa.Client.Shared.Models;
namespace ZB.MOM.WW.LmxOpcUa.Client.Shared.Adapters;
/// <summary>
/// Creates and configures an OPC UA ApplicationConfiguration.
/// </summary>
internal interface IApplicationConfigurationFactory
{
/// <summary>
/// Creates a validated ApplicationConfiguration for the given connection settings.
/// </summary>
Task<ApplicationConfiguration> CreateAsync(ConnectionSettings settings, CancellationToken ct = default);
}

View File

@@ -0,0 +1,15 @@
using Opc.Ua;
namespace ZB.MOM.WW.LmxOpcUa.Client.Shared.Adapters;
/// <summary>
/// Abstracts OPC UA endpoint discovery for testability.
/// </summary>
internal interface IEndpointDiscovery
{
/// <summary>
/// Discovers endpoints at the given URL and returns the best match for the requested security mode.
/// Also rewrites the endpoint URL hostname to match the requested URL when they differ.
/// </summary>
EndpointDescription SelectEndpoint(ApplicationConfiguration config, string endpointUrl, MessageSecurityMode requestedMode);
}

View File

@@ -0,0 +1,61 @@
using Opc.Ua;
namespace ZB.MOM.WW.LmxOpcUa.Client.Shared.Adapters;
/// <summary>
/// Abstracts the OPC UA session for read, write, browse, history, and subscription operations.
/// </summary>
internal interface ISessionAdapter : IDisposable
{
bool Connected { get; }
string SessionId { get; }
string SessionName { get; }
string EndpointUrl { get; }
string ServerName { get; }
string SecurityMode { get; }
string SecurityPolicyUri { get; }
NamespaceTable NamespaceUris { get; }
/// <summary>
/// Registers a keep-alive callback. The callback receives true when the session is healthy, false on failure.
/// </summary>
void RegisterKeepAliveHandler(Action<bool> callback);
Task<DataValue> ReadValueAsync(NodeId nodeId, CancellationToken ct = default);
Task<StatusCode> WriteValueAsync(NodeId nodeId, DataValue value, CancellationToken ct = default);
/// <summary>
/// Browses forward hierarchical references from the given node.
/// Returns (continuationPoint, references).
/// </summary>
Task<(byte[]? ContinuationPoint, ReferenceDescriptionCollection References)> BrowseAsync(
NodeId nodeId, uint nodeClassMask = 0, CancellationToken ct = default);
/// <summary>
/// Continues a browse from a continuation point.
/// </summary>
Task<(byte[]? ContinuationPoint, ReferenceDescriptionCollection References)> BrowseNextAsync(
byte[] continuationPoint, CancellationToken ct = default);
/// <summary>
/// Checks whether a node has any forward hierarchical child references.
/// </summary>
Task<bool> HasChildrenAsync(NodeId nodeId, CancellationToken ct = default);
/// <summary>
/// Reads raw historical data.
/// </summary>
Task<IReadOnlyList<DataValue>> HistoryReadRawAsync(NodeId nodeId, DateTime startTime, DateTime endTime, int maxValues, CancellationToken ct = default);
/// <summary>
/// Reads processed/aggregate historical data.
/// </summary>
Task<IReadOnlyList<DataValue>> HistoryReadAggregateAsync(NodeId nodeId, DateTime startTime, DateTime endTime, NodeId aggregateId, double intervalMs, CancellationToken ct = default);
/// <summary>
/// Creates a subscription adapter for this session.
/// </summary>
Task<ISubscriptionAdapter> CreateSubscriptionAsync(int publishingIntervalMs, CancellationToken ct = default);
Task CloseAsync(CancellationToken ct = default);
}

View File

@@ -0,0 +1,27 @@
using Opc.Ua;
namespace ZB.MOM.WW.LmxOpcUa.Client.Shared.Adapters;
/// <summary>
/// Creates OPC UA sessions from a configured endpoint.
/// </summary>
internal interface ISessionFactory
{
/// <summary>
/// Creates a session to the given endpoint.
/// </summary>
/// <param name="config">The application configuration.</param>
/// <param name="endpoint">The configured endpoint.</param>
/// <param name="sessionName">The session name.</param>
/// <param name="sessionTimeoutMs">Session timeout in milliseconds.</param>
/// <param name="identity">The user identity.</param>
/// <param name="ct">Cancellation token.</param>
/// <returns>A session adapter wrapping the created session.</returns>
Task<ISessionAdapter> CreateSessionAsync(
ApplicationConfiguration config,
EndpointDescription endpoint,
string sessionName,
uint sessionTimeoutMs,
UserIdentity identity,
CancellationToken ct = default);
}

View File

@@ -0,0 +1,47 @@
using Opc.Ua;
namespace ZB.MOM.WW.LmxOpcUa.Client.Shared.Adapters;
/// <summary>
/// Abstracts OPC UA subscription and monitored item management.
/// </summary>
internal interface ISubscriptionAdapter : IDisposable
{
uint SubscriptionId { get; }
/// <summary>
/// Adds a data-change monitored item and returns its client handle for tracking.
/// </summary>
/// <param name="nodeId">The node to monitor.</param>
/// <param name="samplingIntervalMs">The sampling interval in milliseconds.</param>
/// <param name="onDataChange">Callback when data changes. Receives (nodeIdString, DataValue).</param>
/// <param name="ct">Cancellation token.</param>
/// <returns>A client handle that can be used to remove the item.</returns>
Task<uint> AddDataChangeMonitoredItemAsync(NodeId nodeId, int samplingIntervalMs, Action<string, DataValue> onDataChange, CancellationToken ct = default);
/// <summary>
/// Removes a previously added monitored item by its client handle.
/// </summary>
Task RemoveMonitoredItemAsync(uint clientHandle, CancellationToken ct = default);
/// <summary>
/// Adds an event monitored item with the given event filter.
/// </summary>
/// <param name="nodeId">The node to monitor for events.</param>
/// <param name="samplingIntervalMs">The sampling interval.</param>
/// <param name="filter">The event filter defining which fields to select.</param>
/// <param name="onEvent">Callback when events arrive. Receives the event field list.</param>
/// <param name="ct">Cancellation token.</param>
/// <returns>A client handle for the monitored item.</returns>
Task<uint> AddEventMonitoredItemAsync(NodeId nodeId, int samplingIntervalMs, EventFilter filter, Action<EventFieldList> onEvent, CancellationToken ct = default);
/// <summary>
/// Requests a condition refresh for this subscription.
/// </summary>
Task ConditionRefreshAsync(CancellationToken ct = default);
/// <summary>
/// Removes all monitored items and deletes the subscription.
/// </summary>
Task DeleteAsync(CancellationToken ct = default);
}

View File

@@ -0,0 +1,27 @@
using Opc.Ua;
using ZB.MOM.WW.LmxOpcUa.Client.Shared.Models;
namespace ZB.MOM.WW.LmxOpcUa.Client.Shared.Helpers;
/// <summary>
/// Maps the library's AggregateType enum to OPC UA aggregate function NodeIds.
/// </summary>
public static class AggregateTypeMapper
{
/// <summary>
/// Returns the OPC UA NodeId for the specified aggregate type.
/// </summary>
public static NodeId ToNodeId(AggregateType aggregate)
{
return aggregate switch
{
AggregateType.Average => ObjectIds.AggregateFunction_Average,
AggregateType.Minimum => ObjectIds.AggregateFunction_Minimum,
AggregateType.Maximum => ObjectIds.AggregateFunction_Maximum,
AggregateType.Count => ObjectIds.AggregateFunction_Count,
AggregateType.Start => ObjectIds.AggregateFunction_Start,
AggregateType.End => ObjectIds.AggregateFunction_End,
_ => throw new ArgumentOutOfRangeException(nameof(aggregate), aggregate, "Unknown AggregateType value.")
};
}
}

View File

@@ -0,0 +1,50 @@
namespace ZB.MOM.WW.LmxOpcUa.Client.Shared.Helpers;
/// <summary>
/// Parses and normalizes failover URL sets for redundant OPC UA connections.
/// </summary>
public static class FailoverUrlParser
{
/// <summary>
/// Parses a comma-separated failover URL string, prepending the primary URL.
/// Trims whitespace and deduplicates.
/// </summary>
/// <param name="primaryUrl">The primary endpoint URL.</param>
/// <param name="failoverCsv">Optional comma-separated failover URLs.</param>
/// <returns>An array with the primary URL first, followed by unique failover URLs.</returns>
public static string[] Parse(string primaryUrl, string? failoverCsv)
{
if (string.IsNullOrWhiteSpace(failoverCsv))
return new[] { primaryUrl };
var urls = new List<string> { primaryUrl };
foreach (var url in failoverCsv.Split(',', StringSplitOptions.RemoveEmptyEntries))
{
var trimmed = url.Trim();
if (!string.IsNullOrEmpty(trimmed) && !urls.Contains(trimmed, StringComparer.OrdinalIgnoreCase))
urls.Add(trimmed);
}
return urls.ToArray();
}
/// <summary>
/// Builds a failover URL set from the primary URL and an optional array of failover URLs.
/// </summary>
/// <param name="primaryUrl">The primary endpoint URL.</param>
/// <param name="failoverUrls">Optional failover URLs.</param>
/// <returns>An array with the primary URL first, followed by unique failover URLs.</returns>
public static string[] Parse(string primaryUrl, string[]? failoverUrls)
{
if (failoverUrls == null || failoverUrls.Length == 0)
return new[] { primaryUrl };
var urls = new List<string> { primaryUrl };
foreach (var url in failoverUrls)
{
var trimmed = url?.Trim();
if (!string.IsNullOrEmpty(trimmed) && !urls.Contains(trimmed, StringComparer.OrdinalIgnoreCase))
urls.Add(trimmed);
}
return urls.ToArray();
}
}

View File

@@ -0,0 +1,42 @@
using Opc.Ua;
using ZB.MOM.WW.LmxOpcUa.Client.Shared.Models;
namespace ZB.MOM.WW.LmxOpcUa.Client.Shared.Helpers;
/// <summary>
/// Maps between the library's SecurityMode enum and OPC UA SDK MessageSecurityMode.
/// </summary>
public static class SecurityModeMapper
{
/// <summary>
/// Converts a <see cref="SecurityMode"/> to an OPC UA <see cref="MessageSecurityMode"/>.
/// </summary>
public static MessageSecurityMode ToMessageSecurityMode(SecurityMode mode)
{
return mode switch
{
SecurityMode.None => MessageSecurityMode.None,
SecurityMode.Sign => MessageSecurityMode.Sign,
SecurityMode.SignAndEncrypt => MessageSecurityMode.SignAndEncrypt,
_ => throw new ArgumentOutOfRangeException(nameof(mode), mode, "Unknown SecurityMode value.")
};
}
/// <summary>
/// Parses a string to a <see cref="SecurityMode"/> value, case-insensitively.
/// </summary>
/// <param name="value">The string to parse (e.g., "none", "sign", "encrypt", "signandencrypt").</param>
/// <returns>The corresponding SecurityMode.</returns>
/// <exception cref="ArgumentException">Thrown for unrecognized values.</exception>
public static SecurityMode FromString(string value)
{
return (value ?? "none").Trim().ToLowerInvariant() switch
{
"none" => SecurityMode.None,
"sign" => SecurityMode.Sign,
"encrypt" or "signandencrypt" => SecurityMode.SignAndEncrypt,
_ => throw new ArgumentException(
$"Unknown security mode '{value}'. Valid values: none, sign, encrypt, signandencrypt")
};
}
}

View File

@@ -0,0 +1,32 @@
namespace ZB.MOM.WW.LmxOpcUa.Client.Shared.Helpers;
/// <summary>
/// Converts raw string values into typed values based on the current value's runtime type.
/// Ported from the CLI tool's OpcUaHelper.ConvertValue.
/// </summary>
public static class ValueConverter
{
/// <summary>
/// Converts a raw string value into the runtime type expected by the target node.
/// </summary>
/// <param name="rawValue">The raw string supplied by the user.</param>
/// <param name="currentValue">The current node value used to infer the target type. May be null.</param>
/// <returns>A typed value suitable for an OPC UA write request.</returns>
public static object ConvertValue(string rawValue, object? currentValue)
{
return currentValue switch
{
bool => bool.Parse(rawValue),
byte => byte.Parse(rawValue),
short => short.Parse(rawValue),
ushort => ushort.Parse(rawValue),
int => int.Parse(rawValue),
uint => uint.Parse(rawValue),
long => long.Parse(rawValue),
ulong => ulong.Parse(rawValue),
float => float.Parse(rawValue),
double => double.Parse(rawValue),
_ => rawValue
};
}
}

View File

@@ -0,0 +1,36 @@
using Opc.Ua;
using ZB.MOM.WW.LmxOpcUa.Client.Shared.Models;
namespace ZB.MOM.WW.LmxOpcUa.Client.Shared;
/// <summary>
/// Shared OPC UA client service contract for CLI and UI consumers.
/// </summary>
public interface IOpcUaClientService : IDisposable
{
Task<ConnectionInfo> ConnectAsync(ConnectionSettings settings, CancellationToken ct = default);
Task DisconnectAsync(CancellationToken ct = default);
bool IsConnected { get; }
ConnectionInfo? CurrentConnectionInfo { get; }
Task<DataValue> ReadValueAsync(NodeId nodeId, CancellationToken ct = default);
Task<StatusCode> WriteValueAsync(NodeId nodeId, object value, CancellationToken ct = default);
Task<IReadOnlyList<Models.BrowseResult>> BrowseAsync(NodeId? parentNodeId = null, CancellationToken ct = default);
Task SubscribeAsync(NodeId nodeId, int intervalMs = 1000, CancellationToken ct = default);
Task UnsubscribeAsync(NodeId nodeId, CancellationToken ct = default);
Task SubscribeAlarmsAsync(NodeId? sourceNodeId = null, int intervalMs = 1000, CancellationToken ct = default);
Task UnsubscribeAlarmsAsync(CancellationToken ct = default);
Task RequestConditionRefreshAsync(CancellationToken ct = default);
Task<IReadOnlyList<DataValue>> HistoryReadRawAsync(NodeId nodeId, DateTime startTime, DateTime endTime, int maxValues = 1000, CancellationToken ct = default);
Task<IReadOnlyList<DataValue>> HistoryReadAggregateAsync(NodeId nodeId, DateTime startTime, DateTime endTime, AggregateType aggregate, double intervalMs = 3600000, CancellationToken ct = default);
Task<RedundancyInfo> GetRedundancyInfoAsync(CancellationToken ct = default);
event EventHandler<DataChangedEventArgs>? DataChanged;
event EventHandler<AlarmEventArgs>? AlarmEvent;
event EventHandler<ConnectionStateChangedEventArgs>? ConnectionStateChanged;
}

View File

@@ -0,0 +1,9 @@
namespace ZB.MOM.WW.LmxOpcUa.Client.Shared;
/// <summary>
/// Factory for creating <see cref="IOpcUaClientService"/> instances.
/// </summary>
public interface IOpcUaClientServiceFactory
{
IOpcUaClientService Create();
}

View File

@@ -0,0 +1,25 @@
namespace ZB.MOM.WW.LmxOpcUa.Client.Shared.Models;
/// <summary>
/// Aggregate functions for processed history reads.
/// </summary>
public enum AggregateType
{
/// <summary>Average of values in the interval.</summary>
Average,
/// <summary>Minimum value in the interval.</summary>
Minimum,
/// <summary>Maximum value in the interval.</summary>
Maximum,
/// <summary>Count of values in the interval.</summary>
Count,
/// <summary>First value in the interval.</summary>
Start,
/// <summary>Last value in the interval.</summary>
End
}

View File

@@ -0,0 +1,51 @@
namespace ZB.MOM.WW.LmxOpcUa.Client.Shared.Models;
/// <summary>
/// Event data for an alarm or condition notification from the OPC UA server.
/// </summary>
public sealed class AlarmEventArgs : EventArgs
{
/// <summary>The name of the source object that raised the alarm.</summary>
public string SourceName { get; }
/// <summary>The condition type name.</summary>
public string ConditionName { get; }
/// <summary>The alarm severity (0-1000).</summary>
public ushort Severity { get; }
/// <summary>Human-readable alarm message.</summary>
public string Message { get; }
/// <summary>Whether the alarm should be retained in the display.</summary>
public bool Retain { get; }
/// <summary>Whether the alarm condition is currently active.</summary>
public bool ActiveState { get; }
/// <summary>Whether the alarm has been acknowledged.</summary>
public bool AckedState { get; }
/// <summary>The time the event occurred.</summary>
public DateTime Time { get; }
public AlarmEventArgs(
string sourceName,
string conditionName,
ushort severity,
string message,
bool retain,
bool activeState,
bool ackedState,
DateTime time)
{
SourceName = sourceName;
ConditionName = conditionName;
Severity = severity;
Message = message;
Retain = retain;
ActiveState = activeState;
AckedState = ackedState;
Time = time;
}
}

View File

@@ -0,0 +1,35 @@
namespace ZB.MOM.WW.LmxOpcUa.Client.Shared.Models;
/// <summary>
/// Represents a single node in the browse result set.
/// </summary>
public sealed class BrowseResult
{
/// <summary>
/// The string representation of the node's NodeId.
/// </summary>
public string NodeId { get; }
/// <summary>
/// The display name of the node.
/// </summary>
public string DisplayName { get; }
/// <summary>
/// The node class (e.g., "Object", "Variable", "Method").
/// </summary>
public string NodeClass { get; }
/// <summary>
/// Whether the node has child references.
/// </summary>
public bool HasChildren { get; }
public BrowseResult(string nodeId, string displayName, string nodeClass, bool hasChildren)
{
NodeId = nodeId;
DisplayName = displayName;
NodeClass = nodeClass;
HasChildren = hasChildren;
}
}

View File

@@ -0,0 +1,41 @@
namespace ZB.MOM.WW.LmxOpcUa.Client.Shared.Models;
/// <summary>
/// Information about the current OPC UA session.
/// </summary>
public sealed class ConnectionInfo
{
/// <summary>The endpoint URL of the connected server.</summary>
public string EndpointUrl { get; }
/// <summary>The server application name.</summary>
public string ServerName { get; }
/// <summary>The security mode in use (e.g., "None", "Sign", "SignAndEncrypt").</summary>
public string SecurityMode { get; }
/// <summary>The security policy URI (e.g., "http://opcfoundation.org/UA/SecurityPolicy#None").</summary>
public string SecurityPolicyUri { get; }
/// <summary>The session identifier.</summary>
public string SessionId { get; }
/// <summary>The session name.</summary>
public string SessionName { get; }
public ConnectionInfo(
string endpointUrl,
string serverName,
string securityMode,
string securityPolicyUri,
string sessionId,
string sessionName)
{
EndpointUrl = endpointUrl;
ServerName = serverName;
SecurityMode = securityMode;
SecurityPolicyUri = securityPolicyUri;
SessionId = sessionId;
SessionName = sessionName;
}
}

View File

@@ -0,0 +1,65 @@
namespace ZB.MOM.WW.LmxOpcUa.Client.Shared.Models;
/// <summary>
/// Settings for establishing an OPC UA client connection.
/// </summary>
public sealed class ConnectionSettings
{
/// <summary>
/// The primary OPC UA endpoint URL.
/// </summary>
public string EndpointUrl { get; set; } = string.Empty;
/// <summary>
/// Optional failover endpoint URLs for redundancy.
/// </summary>
public string[]? FailoverUrls { get; set; }
/// <summary>
/// Optional username for authentication.
/// </summary>
public string? Username { get; set; }
/// <summary>
/// Optional password for authentication.
/// </summary>
public string? Password { get; set; }
/// <summary>
/// Transport security mode. Defaults to <see cref="Models.SecurityMode.None"/>.
/// </summary>
public SecurityMode SecurityMode { get; set; } = SecurityMode.None;
/// <summary>
/// Session timeout in seconds. Defaults to 60.
/// </summary>
public int SessionTimeoutSeconds { get; set; } = 60;
/// <summary>
/// Whether to automatically accept untrusted server certificates. Defaults to true.
/// </summary>
public bool AutoAcceptCertificates { get; set; } = true;
/// <summary>
/// Path to the certificate store. Defaults to a subdirectory under LocalApplicationData.
/// </summary>
public string CertificateStorePath { get; set; } = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
"LmxOpcUaClient", "pki");
/// <summary>
/// Validates the settings and throws if any required values are missing or invalid.
/// </summary>
/// <exception cref="ArgumentException">Thrown when settings are invalid.</exception>
public void Validate()
{
if (string.IsNullOrWhiteSpace(EndpointUrl))
throw new ArgumentException("EndpointUrl must not be null or empty.", nameof(EndpointUrl));
if (SessionTimeoutSeconds <= 0)
throw new ArgumentException("SessionTimeoutSeconds must be greater than zero.", nameof(SessionTimeoutSeconds));
if (SessionTimeoutSeconds > 3600)
throw new ArgumentException("SessionTimeoutSeconds must not exceed 3600.", nameof(SessionTimeoutSeconds));
}
}

View File

@@ -0,0 +1,19 @@
namespace ZB.MOM.WW.LmxOpcUa.Client.Shared.Models;
/// <summary>
/// Represents the current state of the OPC UA client connection.
/// </summary>
public enum ConnectionState
{
/// <summary>Not connected to any server.</summary>
Disconnected,
/// <summary>Connection attempt is in progress.</summary>
Connecting,
/// <summary>Successfully connected to a server.</summary>
Connected,
/// <summary>Connection was lost and reconnection is in progress.</summary>
Reconnecting
}

View File

@@ -0,0 +1,23 @@
namespace ZB.MOM.WW.LmxOpcUa.Client.Shared.Models;
/// <summary>
/// Event data raised when the client connection state changes.
/// </summary>
public sealed class ConnectionStateChangedEventArgs : EventArgs
{
/// <summary>The previous connection state.</summary>
public ConnectionState OldState { get; }
/// <summary>The new connection state.</summary>
public ConnectionState NewState { get; }
/// <summary>The endpoint URL associated with the state change.</summary>
public string EndpointUrl { get; }
public ConnectionStateChangedEventArgs(ConnectionState oldState, ConnectionState newState, string endpointUrl)
{
OldState = oldState;
NewState = newState;
EndpointUrl = endpointUrl;
}
}

View File

@@ -0,0 +1,21 @@
using Opc.Ua;
namespace ZB.MOM.WW.LmxOpcUa.Client.Shared.Models;
/// <summary>
/// Event data for a monitored data value change.
/// </summary>
public sealed class DataChangedEventArgs : EventArgs
{
/// <summary>The string representation of the node that changed.</summary>
public string NodeId { get; }
/// <summary>The new data value from the server.</summary>
public DataValue Value { get; }
public DataChangedEventArgs(string nodeId, DataValue value)
{
NodeId = nodeId;
Value = value;
}
}

View File

@@ -0,0 +1,27 @@
namespace ZB.MOM.WW.LmxOpcUa.Client.Shared.Models;
/// <summary>
/// Redundancy information read from the server.
/// </summary>
public sealed class RedundancyInfo
{
/// <summary>The redundancy mode (e.g., "None", "Cold", "Warm", "Hot").</summary>
public string Mode { get; }
/// <summary>The server's current service level (0-255).</summary>
public byte ServiceLevel { get; }
/// <summary>URIs of all servers in the redundant set.</summary>
public string[] ServerUris { get; }
/// <summary>The application URI of the connected server.</summary>
public string ApplicationUri { get; }
public RedundancyInfo(string mode, byte serviceLevel, string[] serverUris, string applicationUri)
{
Mode = mode;
ServiceLevel = serviceLevel;
ServerUris = serverUris;
ApplicationUri = applicationUri;
}
}

View File

@@ -0,0 +1,16 @@
namespace ZB.MOM.WW.LmxOpcUa.Client.Shared.Models;
/// <summary>
/// Transport security mode for the OPC UA connection.
/// </summary>
public enum SecurityMode
{
/// <summary>No transport security.</summary>
None,
/// <summary>Messages are signed but not encrypted.</summary>
Sign,
/// <summary>Messages are signed and encrypted.</summary>
SignAndEncrypt
}

View File

@@ -0,0 +1,572 @@
using Opc.Ua;
using Serilog;
using ZB.MOM.WW.LmxOpcUa.Client.Shared.Adapters;
using ZB.MOM.WW.LmxOpcUa.Client.Shared.Helpers;
using ZB.MOM.WW.LmxOpcUa.Client.Shared.Models;
namespace ZB.MOM.WW.LmxOpcUa.Client.Shared;
/// <summary>
/// Full implementation of <see cref="IOpcUaClientService"/> using adapter abstractions for testability.
/// </summary>
public sealed class OpcUaClientService : IOpcUaClientService
{
private static readonly ILogger Logger = Log.ForContext<OpcUaClientService>();
private readonly IApplicationConfigurationFactory _configFactory;
private readonly IEndpointDiscovery _endpointDiscovery;
private readonly ISessionFactory _sessionFactory;
private ISessionAdapter? _session;
private ISubscriptionAdapter? _dataSubscription;
private ISubscriptionAdapter? _alarmSubscription;
private ConnectionState _state = ConnectionState.Disconnected;
private ConnectionSettings? _settings;
private string[]? _allEndpointUrls;
private int _currentEndpointIndex;
private bool _disposed;
// Track active data subscriptions for replay after failover
private readonly Dictionary<string, (NodeId NodeId, int IntervalMs, uint Handle)> _activeDataSubscriptions = new();
// Track alarm subscription state for replay after failover
private (NodeId? SourceNodeId, int IntervalMs)? _activeAlarmSubscription;
public event EventHandler<DataChangedEventArgs>? DataChanged;
public event EventHandler<AlarmEventArgs>? AlarmEvent;
public event EventHandler<ConnectionStateChangedEventArgs>? ConnectionStateChanged;
public bool IsConnected => _state == ConnectionState.Connected && _session?.Connected == true;
public ConnectionInfo? CurrentConnectionInfo { get; private set; }
/// <summary>
/// Creates a new OpcUaClientService with the specified adapter dependencies.
/// </summary>
internal OpcUaClientService(
IApplicationConfigurationFactory configFactory,
IEndpointDiscovery endpointDiscovery,
ISessionFactory sessionFactory)
{
_configFactory = configFactory;
_endpointDiscovery = endpointDiscovery;
_sessionFactory = sessionFactory;
}
/// <summary>
/// Creates a new OpcUaClientService with default production adapters.
/// </summary>
public OpcUaClientService()
: this(
new DefaultApplicationConfigurationFactory(),
new DefaultEndpointDiscovery(),
new DefaultSessionFactory())
{
}
public async Task<ConnectionInfo> ConnectAsync(ConnectionSettings settings, CancellationToken ct = default)
{
ThrowIfDisposed();
settings.Validate();
_settings = settings;
_allEndpointUrls = FailoverUrlParser.Parse(settings.EndpointUrl, settings.FailoverUrls);
_currentEndpointIndex = 0;
TransitionState(ConnectionState.Connecting, settings.EndpointUrl);
try
{
var session = await ConnectToEndpointAsync(settings, _allEndpointUrls[0], ct);
_session = session;
session.RegisterKeepAliveHandler(isGood =>
{
if (!isGood)
{
_ = HandleKeepAliveFailureAsync();
}
});
CurrentConnectionInfo = BuildConnectionInfo(session);
TransitionState(ConnectionState.Connected, session.EndpointUrl);
Logger.Information("Connected to {EndpointUrl}", session.EndpointUrl);
return CurrentConnectionInfo;
}
catch
{
TransitionState(ConnectionState.Disconnected, settings.EndpointUrl);
throw;
}
}
public async Task DisconnectAsync(CancellationToken ct = default)
{
if (_state == ConnectionState.Disconnected)
return;
var endpointUrl = _session?.EndpointUrl ?? _settings?.EndpointUrl ?? string.Empty;
try
{
if (_dataSubscription != null)
{
await _dataSubscription.DeleteAsync(ct);
_dataSubscription = null;
}
if (_alarmSubscription != null)
{
await _alarmSubscription.DeleteAsync(ct);
_alarmSubscription = null;
}
if (_session != null)
{
await _session.CloseAsync(ct);
_session.Dispose();
_session = null;
}
}
catch (Exception ex)
{
Logger.Warning(ex, "Error during disconnect");
}
finally
{
_activeDataSubscriptions.Clear();
_activeAlarmSubscription = null;
CurrentConnectionInfo = null;
TransitionState(ConnectionState.Disconnected, endpointUrl);
}
}
public async Task<DataValue> ReadValueAsync(NodeId nodeId, CancellationToken ct = default)
{
ThrowIfDisposed();
ThrowIfNotConnected();
return await _session!.ReadValueAsync(nodeId, ct);
}
public async Task<StatusCode> WriteValueAsync(NodeId nodeId, object value, CancellationToken ct = default)
{
ThrowIfDisposed();
ThrowIfNotConnected();
// Read current value for type coercion when value is a string
object typedValue = value;
if (value is string rawString)
{
var currentDataValue = await _session!.ReadValueAsync(nodeId, ct);
typedValue = ValueConverter.ConvertValue(rawString, currentDataValue.Value);
}
var dataValue = new DataValue(new Variant(typedValue));
return await _session!.WriteValueAsync(nodeId, dataValue, ct);
}
public async Task<IReadOnlyList<Models.BrowseResult>> BrowseAsync(NodeId? parentNodeId = null, CancellationToken ct = default)
{
ThrowIfDisposed();
ThrowIfNotConnected();
var startNode = parentNodeId ?? ObjectIds.ObjectsFolder;
var nodeClassMask = (uint)NodeClass.Object | (uint)NodeClass.Variable | (uint)NodeClass.Method;
var results = new List<Models.BrowseResult>();
var (continuationPoint, references) = await _session!.BrowseAsync(startNode, nodeClassMask, ct);
while (references.Count > 0)
{
foreach (var reference in references)
{
var childNodeId = ExpandedNodeId.ToNodeId(reference.NodeId, _session.NamespaceUris);
var hasChildren = reference.NodeClass == NodeClass.Object &&
await _session.HasChildrenAsync(childNodeId, ct);
results.Add(new Models.BrowseResult(
reference.NodeId.ToString(),
reference.DisplayName?.Text ?? string.Empty,
reference.NodeClass.ToString(),
hasChildren));
}
if (continuationPoint != null && continuationPoint.Length > 0)
{
(continuationPoint, references) = await _session.BrowseNextAsync(continuationPoint, ct);
}
else
{
break;
}
}
return results;
}
public async Task SubscribeAsync(NodeId nodeId, int intervalMs = 1000, CancellationToken ct = default)
{
ThrowIfDisposed();
ThrowIfNotConnected();
var nodeIdStr = nodeId.ToString();
if (_activeDataSubscriptions.ContainsKey(nodeIdStr))
return; // Already subscribed
if (_dataSubscription == null)
{
_dataSubscription = await _session!.CreateSubscriptionAsync(intervalMs, ct);
}
var handle = await _dataSubscription.AddDataChangeMonitoredItemAsync(
nodeId, intervalMs, OnDataChangeNotification, ct);
_activeDataSubscriptions[nodeIdStr] = (nodeId, intervalMs, handle);
Logger.Debug("Subscribed to data changes on {NodeId}", nodeId);
}
public async Task UnsubscribeAsync(NodeId nodeId, CancellationToken ct = default)
{
ThrowIfDisposed();
var nodeIdStr = nodeId.ToString();
if (!_activeDataSubscriptions.TryGetValue(nodeIdStr, out var sub))
return; // Not subscribed, safe to ignore
if (_dataSubscription != null)
{
await _dataSubscription.RemoveMonitoredItemAsync(sub.Handle, ct);
}
_activeDataSubscriptions.Remove(nodeIdStr);
Logger.Debug("Unsubscribed from data changes on {NodeId}", nodeId);
}
public async Task SubscribeAlarmsAsync(NodeId? sourceNodeId = null, int intervalMs = 1000, CancellationToken ct = default)
{
ThrowIfDisposed();
ThrowIfNotConnected();
if (_alarmSubscription != null)
return; // Already subscribed to alarms
var monitorNode = sourceNodeId ?? ObjectIds.Server;
_alarmSubscription = await _session!.CreateSubscriptionAsync(intervalMs, ct);
var filter = CreateAlarmEventFilter();
await _alarmSubscription.AddEventMonitoredItemAsync(
monitorNode, intervalMs, filter, OnAlarmEventNotification, ct);
_activeAlarmSubscription = (sourceNodeId, intervalMs);
Logger.Debug("Subscribed to alarm events on {NodeId}", monitorNode);
}
public async Task UnsubscribeAlarmsAsync(CancellationToken ct = default)
{
ThrowIfDisposed();
if (_alarmSubscription == null)
return;
await _alarmSubscription.DeleteAsync(ct);
_alarmSubscription = null;
_activeAlarmSubscription = null;
Logger.Debug("Unsubscribed from alarm events");
}
public async Task RequestConditionRefreshAsync(CancellationToken ct = default)
{
ThrowIfDisposed();
ThrowIfNotConnected();
if (_alarmSubscription == null)
throw new InvalidOperationException("No alarm subscription is active.");
await _alarmSubscription.ConditionRefreshAsync(ct);
Logger.Debug("Condition refresh requested");
}
public async Task<IReadOnlyList<DataValue>> HistoryReadRawAsync(
NodeId nodeId, DateTime startTime, DateTime endTime, int maxValues = 1000, CancellationToken ct = default)
{
ThrowIfDisposed();
ThrowIfNotConnected();
return await _session!.HistoryReadRawAsync(nodeId, startTime, endTime, maxValues, ct);
}
public async Task<IReadOnlyList<DataValue>> HistoryReadAggregateAsync(
NodeId nodeId, DateTime startTime, DateTime endTime, AggregateType aggregate,
double intervalMs = 3600000, CancellationToken ct = default)
{
ThrowIfDisposed();
ThrowIfNotConnected();
var aggregateNodeId = AggregateTypeMapper.ToNodeId(aggregate);
return await _session!.HistoryReadAggregateAsync(nodeId, startTime, endTime, aggregateNodeId, intervalMs, ct);
}
public async Task<RedundancyInfo> GetRedundancyInfoAsync(CancellationToken ct = default)
{
ThrowIfDisposed();
ThrowIfNotConnected();
var redundancySupportValue = await _session!.ReadValueAsync(VariableIds.Server_ServerRedundancy_RedundancySupport, ct);
var redundancyMode = ((RedundancySupport)(int)redundancySupportValue.Value).ToString();
var serviceLevelValue = await _session.ReadValueAsync(VariableIds.Server_ServiceLevel, ct);
var serviceLevel = (byte)serviceLevelValue.Value;
string[] serverUris = Array.Empty<string>();
try
{
var serverUriArrayValue = await _session.ReadValueAsync(VariableIds.Server_ServerRedundancy_ServerUriArray, ct);
if (serverUriArrayValue.Value is string[] uris)
serverUris = uris;
}
catch
{
// ServerUriArray may not be present when RedundancySupport is None
}
string applicationUri = string.Empty;
try
{
var serverArrayValue = await _session.ReadValueAsync(VariableIds.Server_ServerArray, ct);
if (serverArrayValue.Value is string[] serverArray && serverArray.Length > 0)
applicationUri = serverArray[0];
}
catch
{
// Informational only
}
return new RedundancyInfo(redundancyMode, serviceLevel, serverUris, applicationUri);
}
public void Dispose()
{
if (_disposed) return;
_disposed = true;
_dataSubscription?.Dispose();
_alarmSubscription?.Dispose();
_session?.Dispose();
_activeDataSubscriptions.Clear();
_activeAlarmSubscription = null;
CurrentConnectionInfo = null;
_state = ConnectionState.Disconnected;
}
// --- Private helpers ---
private async Task<ISessionAdapter> ConnectToEndpointAsync(ConnectionSettings settings, string endpointUrl, CancellationToken ct)
{
// Create a settings copy with the current endpoint URL
var effectiveSettings = new ConnectionSettings
{
EndpointUrl = endpointUrl,
SecurityMode = settings.SecurityMode,
SessionTimeoutSeconds = settings.SessionTimeoutSeconds,
AutoAcceptCertificates = settings.AutoAcceptCertificates,
CertificateStorePath = settings.CertificateStorePath,
Username = settings.Username,
Password = settings.Password
};
var config = await _configFactory.CreateAsync(effectiveSettings, ct);
var requestedMode = SecurityModeMapper.ToMessageSecurityMode(settings.SecurityMode);
var endpoint = _endpointDiscovery.SelectEndpoint(config, endpointUrl, requestedMode);
UserIdentity identity = settings.Username != null
? new UserIdentity(settings.Username, System.Text.Encoding.UTF8.GetBytes(settings.Password ?? ""))
: new UserIdentity();
var sessionTimeoutMs = (uint)(settings.SessionTimeoutSeconds * 1000);
return await _sessionFactory.CreateSessionAsync(config, endpoint, "LmxOpcUaClient", sessionTimeoutMs, identity, ct);
}
private async Task HandleKeepAliveFailureAsync()
{
if (_state == ConnectionState.Reconnecting || _state == ConnectionState.Disconnected)
return;
var oldEndpoint = _session?.EndpointUrl ?? string.Empty;
TransitionState(ConnectionState.Reconnecting, oldEndpoint);
Logger.Warning("Session lost on {EndpointUrl}. Attempting failover...", oldEndpoint);
// Close old session
if (_session != null)
{
try { _session.Dispose(); } catch { }
_session = null;
}
_dataSubscription = null;
_alarmSubscription = null;
if (_settings == null || _allEndpointUrls == null)
{
TransitionState(ConnectionState.Disconnected, oldEndpoint);
return;
}
// Try each endpoint
for (int attempt = 0; attempt < _allEndpointUrls.Length; attempt++)
{
_currentEndpointIndex = (_currentEndpointIndex + 1) % _allEndpointUrls.Length;
var url = _allEndpointUrls[_currentEndpointIndex];
try
{
Logger.Information("Failover attempt to {EndpointUrl}", url);
var session = await ConnectToEndpointAsync(_settings, url, CancellationToken.None);
_session = session;
session.RegisterKeepAliveHandler(isGood =>
{
if (!isGood) { _ = HandleKeepAliveFailureAsync(); }
});
CurrentConnectionInfo = BuildConnectionInfo(session);
TransitionState(ConnectionState.Connected, url);
Logger.Information("Failover succeeded to {EndpointUrl}", url);
// Replay subscriptions
await ReplaySubscriptionsAsync();
return;
}
catch (Exception ex)
{
Logger.Warning(ex, "Failover to {EndpointUrl} failed", url);
}
}
Logger.Error("All failover endpoints unreachable");
TransitionState(ConnectionState.Disconnected, oldEndpoint);
}
private async Task ReplaySubscriptionsAsync()
{
// Replay data subscriptions
if (_activeDataSubscriptions.Count > 0)
{
var subscriptions = _activeDataSubscriptions.ToList();
_activeDataSubscriptions.Clear();
foreach (var (nodeIdStr, (nodeId, intervalMs, _)) in subscriptions)
{
try
{
if (_dataSubscription == null)
_dataSubscription = await _session!.CreateSubscriptionAsync(intervalMs, CancellationToken.None);
var handle = await _dataSubscription.AddDataChangeMonitoredItemAsync(
nodeId, intervalMs, OnDataChangeNotification, CancellationToken.None);
_activeDataSubscriptions[nodeIdStr] = (nodeId, intervalMs, handle);
}
catch (Exception ex)
{
Logger.Warning(ex, "Failed to replay data subscription for {NodeId}", nodeIdStr);
}
}
}
// Replay alarm subscription
if (_activeAlarmSubscription.HasValue)
{
var (sourceNodeId, intervalMs) = _activeAlarmSubscription.Value;
_activeAlarmSubscription = null;
try
{
var monitorNode = sourceNodeId ?? ObjectIds.Server;
_alarmSubscription = await _session!.CreateSubscriptionAsync(intervalMs, CancellationToken.None);
var filter = CreateAlarmEventFilter();
await _alarmSubscription.AddEventMonitoredItemAsync(
monitorNode, intervalMs, filter, OnAlarmEventNotification, CancellationToken.None);
_activeAlarmSubscription = (sourceNodeId, intervalMs);
}
catch (Exception ex)
{
Logger.Warning(ex, "Failed to replay alarm subscription");
}
}
}
private void OnDataChangeNotification(string nodeId, DataValue value)
{
DataChanged?.Invoke(this, new DataChangedEventArgs(nodeId, value));
}
private void OnAlarmEventNotification(EventFieldList eventFields)
{
var fields = eventFields.EventFields;
if (fields == null || fields.Count < 6)
return;
var sourceName = fields.Count > 2 ? fields[2].Value as string ?? string.Empty : string.Empty;
var time = fields.Count > 3 ? fields[3].Value as DateTime? ?? DateTime.MinValue : DateTime.MinValue;
var message = fields.Count > 4 ? (fields[4].Value as LocalizedText)?.Text ?? string.Empty : string.Empty;
var severity = fields.Count > 5 ? Convert.ToUInt16(fields[5].Value) : (ushort)0;
var conditionName = fields.Count > 6 ? fields[6].Value as string ?? string.Empty : string.Empty;
var retain = fields.Count > 7 ? fields[7].Value as bool? ?? false : false;
var ackedState = fields.Count > 8 ? fields[8].Value as bool? ?? false : false;
var activeState = fields.Count > 9 ? fields[9].Value as bool? ?? false : false;
AlarmEvent?.Invoke(this, new AlarmEventArgs(
sourceName, conditionName, severity, message, retain, activeState, ackedState, time));
}
private static EventFilter CreateAlarmEventFilter()
{
var filter = new EventFilter();
// 0: EventId
filter.AddSelectClause(ObjectTypeIds.BaseEventType, BrowseNames.EventId);
// 1: EventType
filter.AddSelectClause(ObjectTypeIds.BaseEventType, BrowseNames.EventType);
// 2: SourceName
filter.AddSelectClause(ObjectTypeIds.BaseEventType, BrowseNames.SourceName);
// 3: Time
filter.AddSelectClause(ObjectTypeIds.BaseEventType, BrowseNames.Time);
// 4: Message
filter.AddSelectClause(ObjectTypeIds.BaseEventType, BrowseNames.Message);
// 5: Severity
filter.AddSelectClause(ObjectTypeIds.BaseEventType, BrowseNames.Severity);
// 6: ConditionName
filter.AddSelectClause(ObjectTypeIds.ConditionType, BrowseNames.ConditionName);
// 7: Retain
filter.AddSelectClause(ObjectTypeIds.ConditionType, BrowseNames.Retain);
// 8: AckedState/Id
filter.AddSelectClause(ObjectTypeIds.AcknowledgeableConditionType, "AckedState/Id");
// 9: ActiveState/Id
filter.AddSelectClause(ObjectTypeIds.AlarmConditionType, "ActiveState/Id");
// 10: EnabledState/Id
filter.AddSelectClause(ObjectTypeIds.AlarmConditionType, "EnabledState/Id");
// 11: SuppressedOrShelved
filter.AddSelectClause(ObjectTypeIds.AlarmConditionType, "SuppressedOrShelved");
return filter;
}
private static ConnectionInfo BuildConnectionInfo(ISessionAdapter session)
{
return new ConnectionInfo(
session.EndpointUrl,
session.ServerName,
session.SecurityMode,
session.SecurityPolicyUri,
session.SessionId,
session.SessionName);
}
private void TransitionState(ConnectionState newState, string endpointUrl)
{
var oldState = _state;
if (oldState == newState) return;
_state = newState;
ConnectionStateChanged?.Invoke(this, new ConnectionStateChangedEventArgs(oldState, newState, endpointUrl));
}
private void ThrowIfDisposed()
{
if (_disposed) throw new ObjectDisposedException(nameof(OpcUaClientService));
}
private void ThrowIfNotConnected()
{
if (_state != ConnectionState.Connected || _session == null)
throw new InvalidOperationException("Not connected to an OPC UA server.");
}
}

View File

@@ -0,0 +1,12 @@
namespace ZB.MOM.WW.LmxOpcUa.Client.Shared;
/// <summary>
/// Default factory that creates <see cref="OpcUaClientService"/> instances with production adapters.
/// </summary>
public sealed class OpcUaClientServiceFactory : IOpcUaClientServiceFactory
{
public IOpcUaClientService Create()
{
return new OpcUaClientService();
}
}

View File

@@ -0,0 +1,19 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<RootNamespace>ZB.MOM.WW.LmxOpcUa.Client.Shared</RootNamespace>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="OPCFoundation.NetStandard.Opc.Ua.Client" Version="1.5.378.106" />
<PackageReference Include="Serilog" Version="4.2.0" />
</ItemGroup>
<ItemGroup>
<InternalsVisibleTo Include="ZB.MOM.WW.LmxOpcUa.Client.Shared.Tests" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,9 @@
<Application xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="ZB.MOM.WW.LmxOpcUa.Client.UI.App"
RequestedThemeVariant="Light">
<Application.Styles>
<FluentTheme />
<StyleInclude Source="avares://Avalonia.Controls.DataGrid/Themes/Fluent.xaml" />
</Application.Styles>
</Application>

View File

@@ -0,0 +1,33 @@
using Avalonia;
using Avalonia.Controls.ApplicationLifetimes;
using Avalonia.Markup.Xaml;
using ZB.MOM.WW.LmxOpcUa.Client.Shared;
using ZB.MOM.WW.LmxOpcUa.Client.UI.Services;
using ZB.MOM.WW.LmxOpcUa.Client.UI.ViewModels;
using ZB.MOM.WW.LmxOpcUa.Client.UI.Views;
namespace ZB.MOM.WW.LmxOpcUa.Client.UI;
public partial class App : Application
{
public override void Initialize()
{
AvaloniaXamlLoader.Load(this);
}
public override void OnFrameworkInitializationCompleted()
{
if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
{
var factory = new OpcUaClientServiceFactory();
var dispatcher = new AvaloniaUiDispatcher();
var viewModel = new MainWindowViewModel(factory, dispatcher);
desktop.MainWindow = new MainWindow
{
DataContext = viewModel
};
}
base.OnFrameworkInitializationCompleted();
}
}

View File

@@ -0,0 +1,16 @@
using Avalonia;
namespace ZB.MOM.WW.LmxOpcUa.Client.UI;
class Program
{
[STAThread]
public static void Main(string[] args) => BuildAvaloniaApp()
.StartWithClassicDesktopLifetime(args);
public static AppBuilder BuildAvaloniaApp()
=> AppBuilder.Configure<App>()
.UsePlatformDetect()
.WithInterFont()
.LogToTrace();
}

View File

@@ -0,0 +1,14 @@
using Avalonia.Threading;
namespace ZB.MOM.WW.LmxOpcUa.Client.UI.Services;
/// <summary>
/// Dispatches actions to the Avalonia UI thread.
/// </summary>
public sealed class AvaloniaUiDispatcher : IUiDispatcher
{
public void Post(Action action)
{
Dispatcher.UIThread.Post(action);
}
}

View File

@@ -0,0 +1,12 @@
namespace ZB.MOM.WW.LmxOpcUa.Client.UI.Services;
/// <summary>
/// Abstraction for dispatching actions to the UI thread.
/// </summary>
public interface IUiDispatcher
{
/// <summary>
/// Posts an action to be executed on the UI thread.
/// </summary>
void Post(Action action);
}

View File

@@ -0,0 +1,13 @@
namespace ZB.MOM.WW.LmxOpcUa.Client.UI.Services;
/// <summary>
/// Dispatcher that executes actions synchronously on the calling thread.
/// Used for unit testing where no UI thread is available.
/// </summary>
public sealed class SynchronousUiDispatcher : IUiDispatcher
{
public void Post(Action action)
{
action();
}
}

View File

@@ -0,0 +1,38 @@
using CommunityToolkit.Mvvm.ComponentModel;
namespace ZB.MOM.WW.LmxOpcUa.Client.UI.ViewModels;
/// <summary>
/// Represents a single alarm event row.
/// </summary>
public partial class AlarmEventViewModel : ObservableObject
{
public string SourceName { get; }
public string ConditionName { get; }
public ushort Severity { get; }
public string Message { get; }
public bool Retain { get; }
public bool ActiveState { get; }
public bool AckedState { get; }
public DateTime Time { get; }
public AlarmEventViewModel(
string sourceName,
string conditionName,
ushort severity,
string message,
bool retain,
bool activeState,
bool ackedState,
DateTime time)
{
SourceName = sourceName;
ConditionName = conditionName;
Severity = severity;
Message = message;
Retain = retain;
ActiveState = activeState;
AckedState = ackedState;
Time = time;
}
}

View File

@@ -0,0 +1,128 @@
using System.Collections.ObjectModel;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using Opc.Ua;
using ZB.MOM.WW.LmxOpcUa.Client.Shared;
using ZB.MOM.WW.LmxOpcUa.Client.Shared.Models;
using ZB.MOM.WW.LmxOpcUa.Client.UI.Services;
namespace ZB.MOM.WW.LmxOpcUa.Client.UI.ViewModels;
/// <summary>
/// ViewModel for the alarms panel.
/// </summary>
public partial class AlarmsViewModel : ObservableObject
{
private readonly IOpcUaClientService _service;
private readonly IUiDispatcher _dispatcher;
/// <summary>Received alarm events.</summary>
public ObservableCollection<AlarmEventViewModel> AlarmEvents { get; } = new();
[ObservableProperty]
private string? _monitoredNodeIdText;
[ObservableProperty]
private int _interval = 1000;
[ObservableProperty]
[NotifyCanExecuteChangedFor(nameof(SubscribeCommand))]
[NotifyCanExecuteChangedFor(nameof(UnsubscribeCommand))]
[NotifyCanExecuteChangedFor(nameof(RefreshCommand))]
private bool _isSubscribed;
[ObservableProperty]
[NotifyCanExecuteChangedFor(nameof(SubscribeCommand))]
[NotifyCanExecuteChangedFor(nameof(UnsubscribeCommand))]
[NotifyCanExecuteChangedFor(nameof(RefreshCommand))]
private bool _isConnected;
public AlarmsViewModel(IOpcUaClientService service, IUiDispatcher dispatcher)
{
_service = service;
_dispatcher = dispatcher;
_service.AlarmEvent += OnAlarmEvent;
}
private void OnAlarmEvent(object? sender, AlarmEventArgs e)
{
_dispatcher.Post(() =>
{
AlarmEvents.Add(new AlarmEventViewModel(
e.SourceName,
e.ConditionName,
e.Severity,
e.Message,
e.Retain,
e.ActiveState,
e.AckedState,
e.Time));
});
}
private bool CanSubscribe() => IsConnected && !IsSubscribed;
[RelayCommand(CanExecute = nameof(CanSubscribe))]
private async Task SubscribeAsync()
{
try
{
NodeId? sourceNodeId = string.IsNullOrWhiteSpace(MonitoredNodeIdText)
? null
: NodeId.Parse(MonitoredNodeIdText);
await _service.SubscribeAlarmsAsync(sourceNodeId, Interval);
IsSubscribed = true;
}
catch
{
// Subscribe failed
}
}
private bool CanUnsubscribe() => IsConnected && IsSubscribed;
[RelayCommand(CanExecute = nameof(CanUnsubscribe))]
private async Task UnsubscribeAsync()
{
try
{
await _service.UnsubscribeAlarmsAsync();
IsSubscribed = false;
}
catch
{
// Unsubscribe failed
}
}
[RelayCommand(CanExecute = nameof(CanUnsubscribe))]
private async Task RefreshAsync()
{
try
{
await _service.RequestConditionRefreshAsync();
}
catch
{
// Refresh failed
}
}
/// <summary>
/// Clears alarm events and resets state.
/// </summary>
public void Clear()
{
AlarmEvents.Clear();
IsSubscribed = false;
}
/// <summary>
/// Unhooks event handlers from the service.
/// </summary>
public void Teardown()
{
_service.AlarmEvent -= OnAlarmEvent;
}
}

View File

@@ -0,0 +1,55 @@
using System.Collections.ObjectModel;
using CommunityToolkit.Mvvm.ComponentModel;
using ZB.MOM.WW.LmxOpcUa.Client.Shared;
using ZB.MOM.WW.LmxOpcUa.Client.UI.Services;
namespace ZB.MOM.WW.LmxOpcUa.Client.UI.ViewModels;
/// <summary>
/// ViewModel for the OPC UA browse tree panel.
/// </summary>
public partial class BrowseTreeViewModel : ObservableObject
{
private readonly IOpcUaClientService _service;
private readonly IUiDispatcher _dispatcher;
/// <summary>Top-level nodes in the browse tree.</summary>
public ObservableCollection<TreeNodeViewModel> RootNodes { get; } = new();
public BrowseTreeViewModel(IOpcUaClientService service, IUiDispatcher dispatcher)
{
_service = service;
_dispatcher = dispatcher;
}
/// <summary>
/// Loads root nodes by browsing with a null parent.
/// </summary>
public async Task LoadRootsAsync()
{
var results = await _service.BrowseAsync(null);
_dispatcher.Post(() =>
{
RootNodes.Clear();
foreach (var result in results)
{
RootNodes.Add(new TreeNodeViewModel(
result.NodeId,
result.DisplayName,
result.NodeClass,
result.HasChildren,
_service,
_dispatcher));
}
});
}
/// <summary>
/// Clears all root nodes from the tree.
/// </summary>
public void Clear()
{
RootNodes.Clear();
}
}

View File

@@ -0,0 +1,22 @@
using CommunityToolkit.Mvvm.ComponentModel;
namespace ZB.MOM.WW.LmxOpcUa.Client.UI.ViewModels;
/// <summary>
/// Represents a single historical value row.
/// </summary>
public partial class HistoryValueViewModel : ObservableObject
{
public string Value { get; }
public string Status { get; }
public string SourceTimestamp { get; }
public string ServerTimestamp { get; }
public HistoryValueViewModel(string value, string status, string sourceTimestamp, string serverTimestamp)
{
Value = value;
Status = status;
SourceTimestamp = sourceTimestamp;
ServerTimestamp = serverTimestamp;
}
}

View File

@@ -0,0 +1,140 @@
using System.Collections.ObjectModel;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using Opc.Ua;
using ZB.MOM.WW.LmxOpcUa.Client.Shared;
using ZB.MOM.WW.LmxOpcUa.Client.Shared.Models;
using ZB.MOM.WW.LmxOpcUa.Client.UI.Services;
namespace ZB.MOM.WW.LmxOpcUa.Client.UI.ViewModels;
/// <summary>
/// ViewModel for the history panel.
/// </summary>
public partial class HistoryViewModel : ObservableObject
{
private readonly IOpcUaClientService _service;
private readonly IUiDispatcher _dispatcher;
[ObservableProperty]
[NotifyCanExecuteChangedFor(nameof(ReadHistoryCommand))]
private string? _selectedNodeId;
[ObservableProperty]
private DateTimeOffset _startTime = DateTimeOffset.UtcNow.AddHours(-1);
[ObservableProperty]
private DateTimeOffset _endTime = DateTimeOffset.UtcNow;
[ObservableProperty]
private int _maxValues = 1000;
[ObservableProperty]
private AggregateType? _selectedAggregateType;
/// <summary>Available aggregate types (null means "Raw").</summary>
public IReadOnlyList<AggregateType?> AggregateTypes { get; } = new AggregateType?[]
{
null,
AggregateType.Average,
AggregateType.Minimum,
AggregateType.Maximum,
AggregateType.Count,
AggregateType.Start,
AggregateType.End
};
[ObservableProperty]
private double _intervalMs = 3600000;
public bool IsAggregateRead => SelectedAggregateType != null;
[ObservableProperty]
private bool _isLoading;
[ObservableProperty]
[NotifyCanExecuteChangedFor(nameof(ReadHistoryCommand))]
private bool _isConnected;
/// <summary>History read results.</summary>
public ObservableCollection<HistoryValueViewModel> Results { get; } = new();
public HistoryViewModel(IOpcUaClientService service, IUiDispatcher dispatcher)
{
_service = service;
_dispatcher = dispatcher;
}
partial void OnSelectedAggregateTypeChanged(AggregateType? value)
{
OnPropertyChanged(nameof(IsAggregateRead));
}
private bool CanReadHistory() => IsConnected && !string.IsNullOrEmpty(SelectedNodeId);
[RelayCommand(CanExecute = nameof(CanReadHistory))]
private async Task ReadHistoryAsync()
{
if (string.IsNullOrEmpty(SelectedNodeId)) return;
IsLoading = true;
_dispatcher.Post(() => Results.Clear());
try
{
var nodeId = NodeId.Parse(SelectedNodeId);
IReadOnlyList<DataValue> values;
if (SelectedAggregateType != null)
{
values = await _service.HistoryReadAggregateAsync(
nodeId,
StartTime.UtcDateTime,
EndTime.UtcDateTime,
SelectedAggregateType.Value,
IntervalMs);
}
else
{
values = await _service.HistoryReadRawAsync(
nodeId,
StartTime.UtcDateTime,
EndTime.UtcDateTime,
MaxValues);
}
_dispatcher.Post(() =>
{
foreach (var dv in values)
{
Results.Add(new HistoryValueViewModel(
dv.Value?.ToString() ?? "(null)",
dv.StatusCode.ToString(),
dv.SourceTimestamp.ToString("O"),
dv.ServerTimestamp.ToString("O")));
}
});
}
catch (Exception ex)
{
_dispatcher.Post(() =>
{
Results.Add(new HistoryValueViewModel(
$"Error: {ex.Message}", string.Empty, string.Empty, string.Empty));
});
}
finally
{
_dispatcher.Post(() => IsLoading = false);
}
}
/// <summary>
/// Clears results and resets state.
/// </summary>
public void Clear()
{
Results.Clear();
SelectedNodeId = null;
}
}

View File

@@ -0,0 +1,198 @@
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using ZB.MOM.WW.LmxOpcUa.Client.Shared;
using ZB.MOM.WW.LmxOpcUa.Client.Shared.Models;
using ZB.MOM.WW.LmxOpcUa.Client.UI.Services;
namespace ZB.MOM.WW.LmxOpcUa.Client.UI.ViewModels;
/// <summary>
/// Main window ViewModel coordinating all panels.
/// </summary>
public partial class MainWindowViewModel : ObservableObject
{
private readonly IOpcUaClientService _service;
private readonly IUiDispatcher _dispatcher;
[ObservableProperty]
private string _endpointUrl = "opc.tcp://localhost:4840";
[ObservableProperty]
private string? _username;
[ObservableProperty]
private string? _password;
[ObservableProperty]
private SecurityMode _selectedSecurityMode = SecurityMode.None;
/// <summary>All available security modes.</summary>
public IReadOnlyList<SecurityMode> SecurityModes { get; } = Enum.GetValues<SecurityMode>();
[ObservableProperty]
[NotifyCanExecuteChangedFor(nameof(ConnectCommand))]
[NotifyCanExecuteChangedFor(nameof(DisconnectCommand))]
private ConnectionState _connectionState = ConnectionState.Disconnected;
public bool IsConnected => ConnectionState == ConnectionState.Connected;
[ObservableProperty]
private TreeNodeViewModel? _selectedTreeNode;
[ObservableProperty]
private RedundancyInfo? _redundancyInfo;
[ObservableProperty]
private string _statusMessage = "Disconnected";
[ObservableProperty]
private string _sessionLabel = string.Empty;
[ObservableProperty]
private int _subscriptionCount;
public BrowseTreeViewModel BrowseTree { get; }
public ReadWriteViewModel ReadWrite { get; }
public SubscriptionsViewModel Subscriptions { get; }
public AlarmsViewModel Alarms { get; }
public HistoryViewModel History { get; }
public MainWindowViewModel(IOpcUaClientServiceFactory factory, IUiDispatcher dispatcher)
{
_service = factory.Create();
_dispatcher = dispatcher;
BrowseTree = new BrowseTreeViewModel(_service, dispatcher);
ReadWrite = new ReadWriteViewModel(_service, dispatcher);
Subscriptions = new SubscriptionsViewModel(_service, dispatcher);
Alarms = new AlarmsViewModel(_service, dispatcher);
History = new HistoryViewModel(_service, dispatcher);
_service.ConnectionStateChanged += OnConnectionStateChanged;
}
private void OnConnectionStateChanged(object? sender, ConnectionStateChangedEventArgs e)
{
_dispatcher.Post(() =>
{
ConnectionState = e.NewState;
});
}
partial void OnConnectionStateChanged(ConnectionState value)
{
OnPropertyChanged(nameof(IsConnected));
var connected = value == ConnectionState.Connected;
ReadWrite.IsConnected = connected;
Subscriptions.IsConnected = connected;
Alarms.IsConnected = connected;
History.IsConnected = connected;
switch (value)
{
case ConnectionState.Connected:
StatusMessage = $"Connected to {EndpointUrl}";
break;
case ConnectionState.Reconnecting:
StatusMessage = "Reconnecting...";
break;
case ConnectionState.Connecting:
StatusMessage = "Connecting...";
break;
case ConnectionState.Disconnected:
StatusMessage = "Disconnected";
SessionLabel = string.Empty;
RedundancyInfo = null;
BrowseTree.Clear();
ReadWrite.Clear();
Subscriptions.Clear();
Alarms.Clear();
History.Clear();
SubscriptionCount = 0;
break;
}
}
partial void OnSelectedTreeNodeChanged(TreeNodeViewModel? value)
{
ReadWrite.SelectedNodeId = value?.NodeId;
History.SelectedNodeId = value?.NodeId;
}
private bool CanConnect() => ConnectionState == ConnectionState.Disconnected;
[RelayCommand(CanExecute = nameof(CanConnect))]
private async Task ConnectAsync()
{
try
{
ConnectionState = ConnectionState.Connecting;
StatusMessage = "Connecting...";
var settings = new ConnectionSettings
{
EndpointUrl = EndpointUrl,
Username = Username,
Password = Password,
SecurityMode = SelectedSecurityMode
};
settings.Validate();
var info = await _service.ConnectAsync(settings);
_dispatcher.Post(() =>
{
ConnectionState = ConnectionState.Connected;
SessionLabel = $"{info.ServerName} | Session: {info.SessionName} ({info.SessionId})";
});
// Load redundancy info
try
{
var redundancy = await _service.GetRedundancyInfoAsync();
_dispatcher.Post(() => RedundancyInfo = redundancy);
}
catch
{
// Redundancy info not available
}
// Load root nodes
await BrowseTree.LoadRootsAsync();
}
catch (Exception ex)
{
_dispatcher.Post(() =>
{
ConnectionState = ConnectionState.Disconnected;
StatusMessage = $"Connection failed: {ex.Message}";
});
}
}
private bool CanDisconnect() => ConnectionState == ConnectionState.Connected
|| ConnectionState == ConnectionState.Reconnecting;
[RelayCommand(CanExecute = nameof(CanDisconnect))]
private async Task DisconnectAsync()
{
try
{
Subscriptions.Teardown();
Alarms.Teardown();
await _service.DisconnectAsync();
}
catch
{
// Best-effort disconnect
}
finally
{
_dispatcher.Post(() =>
{
ConnectionState = ConnectionState.Disconnected;
});
}
}
}

View File

@@ -0,0 +1,136 @@
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using Opc.Ua;
using ZB.MOM.WW.LmxOpcUa.Client.Shared;
using ZB.MOM.WW.LmxOpcUa.Client.UI.Services;
namespace ZB.MOM.WW.LmxOpcUa.Client.UI.ViewModels;
/// <summary>
/// ViewModel for the read/write panel.
/// </summary>
public partial class ReadWriteViewModel : ObservableObject
{
private readonly IOpcUaClientService _service;
private readonly IUiDispatcher _dispatcher;
[ObservableProperty]
[NotifyCanExecuteChangedFor(nameof(ReadCommand))]
[NotifyCanExecuteChangedFor(nameof(WriteCommand))]
private string? _selectedNodeId;
[ObservableProperty]
private string? _currentValue;
[ObservableProperty]
private string? _currentStatus;
[ObservableProperty]
private string? _sourceTimestamp;
[ObservableProperty]
private string? _serverTimestamp;
[ObservableProperty]
private string? _writeValue;
[ObservableProperty]
private string? _writeStatus;
[ObservableProperty]
[NotifyCanExecuteChangedFor(nameof(ReadCommand))]
[NotifyCanExecuteChangedFor(nameof(WriteCommand))]
private bool _isConnected;
public bool IsNodeSelected => !string.IsNullOrEmpty(SelectedNodeId);
public ReadWriteViewModel(IOpcUaClientService service, IUiDispatcher dispatcher)
{
_service = service;
_dispatcher = dispatcher;
}
partial void OnSelectedNodeIdChanged(string? value)
{
OnPropertyChanged(nameof(IsNodeSelected));
if (!string.IsNullOrEmpty(value) && IsConnected)
{
_ = ExecuteReadAsync();
}
}
private bool CanReadOrWrite() => IsConnected && !string.IsNullOrEmpty(SelectedNodeId);
[RelayCommand(CanExecute = nameof(CanReadOrWrite))]
private async Task ReadAsync()
{
await ExecuteReadAsync();
}
private async Task ExecuteReadAsync()
{
if (string.IsNullOrEmpty(SelectedNodeId)) return;
try
{
var nodeId = NodeId.Parse(SelectedNodeId);
var dataValue = await _service.ReadValueAsync(nodeId);
_dispatcher.Post(() =>
{
CurrentValue = dataValue.Value?.ToString() ?? "(null)";
CurrentStatus = dataValue.StatusCode.ToString();
SourceTimestamp = dataValue.SourceTimestamp.ToString("O");
ServerTimestamp = dataValue.ServerTimestamp.ToString("O");
});
}
catch (Exception ex)
{
_dispatcher.Post(() =>
{
CurrentValue = null;
CurrentStatus = $"Error: {ex.Message}";
SourceTimestamp = null;
ServerTimestamp = null;
});
}
}
[RelayCommand(CanExecute = nameof(CanReadOrWrite))]
private async Task WriteAsync()
{
if (string.IsNullOrEmpty(SelectedNodeId) || WriteValue == null) return;
try
{
var nodeId = NodeId.Parse(SelectedNodeId);
var statusCode = await _service.WriteValueAsync(nodeId, WriteValue);
_dispatcher.Post(() =>
{
WriteStatus = statusCode.ToString();
});
}
catch (Exception ex)
{
_dispatcher.Post(() =>
{
WriteStatus = $"Error: {ex.Message}";
});
}
}
/// <summary>
/// Clears all displayed values.
/// </summary>
public void Clear()
{
SelectedNodeId = null;
CurrentValue = null;
CurrentStatus = null;
SourceTimestamp = null;
ServerTimestamp = null;
WriteValue = null;
WriteStatus = null;
}
}

View File

@@ -0,0 +1,30 @@
using CommunityToolkit.Mvvm.ComponentModel;
namespace ZB.MOM.WW.LmxOpcUa.Client.UI.ViewModels;
/// <summary>
/// Represents a single active subscription row.
/// </summary>
public partial class SubscriptionItemViewModel : ObservableObject
{
/// <summary>The monitored NodeId.</summary>
public string NodeId { get; }
/// <summary>The subscription interval in milliseconds.</summary>
public int IntervalMs { get; }
[ObservableProperty]
private string? _value;
[ObservableProperty]
private string? _status;
[ObservableProperty]
private string? _timestamp;
public SubscriptionItemViewModel(string nodeId, int intervalMs)
{
NodeId = nodeId;
IntervalMs = intervalMs;
}
}

View File

@@ -0,0 +1,133 @@
using System.Collections.ObjectModel;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using Opc.Ua;
using ZB.MOM.WW.LmxOpcUa.Client.Shared;
using ZB.MOM.WW.LmxOpcUa.Client.Shared.Models;
using ZB.MOM.WW.LmxOpcUa.Client.UI.Services;
namespace ZB.MOM.WW.LmxOpcUa.Client.UI.ViewModels;
/// <summary>
/// ViewModel for the subscriptions panel.
/// </summary>
public partial class SubscriptionsViewModel : ObservableObject
{
private readonly IOpcUaClientService _service;
private readonly IUiDispatcher _dispatcher;
/// <summary>Currently active subscriptions.</summary>
public ObservableCollection<SubscriptionItemViewModel> ActiveSubscriptions { get; } = new();
[ObservableProperty]
[NotifyCanExecuteChangedFor(nameof(AddSubscriptionCommand))]
private string? _newNodeIdText;
[ObservableProperty]
private int _newInterval = 1000;
[ObservableProperty]
[NotifyCanExecuteChangedFor(nameof(AddSubscriptionCommand))]
[NotifyCanExecuteChangedFor(nameof(RemoveSubscriptionCommand))]
private bool _isConnected;
[ObservableProperty]
private int _subscriptionCount;
[ObservableProperty]
[NotifyCanExecuteChangedFor(nameof(RemoveSubscriptionCommand))]
private SubscriptionItemViewModel? _selectedSubscription;
public SubscriptionsViewModel(IOpcUaClientService service, IUiDispatcher dispatcher)
{
_service = service;
_dispatcher = dispatcher;
_service.DataChanged += OnDataChanged;
}
private void OnDataChanged(object? sender, DataChangedEventArgs e)
{
_dispatcher.Post(() =>
{
foreach (var item in ActiveSubscriptions)
{
if (item.NodeId == e.NodeId)
{
item.Value = e.Value.Value?.ToString() ?? "(null)";
item.Status = e.Value.StatusCode.ToString();
item.Timestamp = e.Value.SourceTimestamp.ToString("O");
}
}
});
}
private bool CanAddSubscription() => IsConnected && !string.IsNullOrWhiteSpace(NewNodeIdText);
[RelayCommand(CanExecute = nameof(CanAddSubscription))]
private async Task AddSubscriptionAsync()
{
if (string.IsNullOrWhiteSpace(NewNodeIdText)) return;
var nodeIdStr = NewNodeIdText;
var interval = NewInterval;
try
{
var nodeId = NodeId.Parse(nodeIdStr);
await _service.SubscribeAsync(nodeId, interval);
_dispatcher.Post(() =>
{
ActiveSubscriptions.Add(new SubscriptionItemViewModel(nodeIdStr, interval));
SubscriptionCount = ActiveSubscriptions.Count;
});
}
catch
{
// Subscription failed; no item added
}
}
private bool CanRemoveSubscription() => IsConnected && SelectedSubscription != null;
[RelayCommand(CanExecute = nameof(CanRemoveSubscription))]
private async Task RemoveSubscriptionAsync()
{
if (SelectedSubscription == null) return;
var item = SelectedSubscription;
try
{
var nodeId = NodeId.Parse(item.NodeId);
await _service.UnsubscribeAsync(nodeId);
_dispatcher.Post(() =>
{
ActiveSubscriptions.Remove(item);
SubscriptionCount = ActiveSubscriptions.Count;
});
}
catch
{
// Unsubscribe failed
}
}
/// <summary>
/// Clears all subscriptions and resets state.
/// </summary>
public void Clear()
{
ActiveSubscriptions.Clear();
SubscriptionCount = 0;
}
/// <summary>
/// Unhooks event handlers from the service.
/// </summary>
public void Teardown()
{
_service.DataChanged -= OnDataChanged;
}
}

View File

@@ -0,0 +1,122 @@
using System.Collections.ObjectModel;
using CommunityToolkit.Mvvm.ComponentModel;
using Opc.Ua;
using ZB.MOM.WW.LmxOpcUa.Client.Shared;
using ZB.MOM.WW.LmxOpcUa.Client.UI.Services;
namespace ZB.MOM.WW.LmxOpcUa.Client.UI.ViewModels;
/// <summary>
/// Represents a single node in the OPC UA browse tree with lazy-load support.
/// </summary>
public partial class TreeNodeViewModel : ObservableObject
{
private static readonly TreeNodeViewModel PlaceholderSentinel = new();
private readonly IOpcUaClientService? _service;
private readonly IUiDispatcher? _dispatcher;
private bool _hasLoadedChildren;
/// <summary>The string NodeId of this node.</summary>
public string NodeId { get; }
/// <summary>The display name shown in the tree.</summary>
public string DisplayName { get; }
/// <summary>The OPC UA node class (Object, Variable, etc.).</summary>
public string NodeClass { get; }
/// <summary>Whether this node has child references.</summary>
public bool HasChildren { get; }
/// <summary>Child nodes (may contain a placeholder sentinel before first expand).</summary>
public ObservableCollection<TreeNodeViewModel> Children { get; } = new();
[ObservableProperty]
private bool _isExpanded;
[ObservableProperty]
private bool _isLoading;
/// <summary>
/// Private constructor for the placeholder sentinel only.
/// </summary>
private TreeNodeViewModel()
{
NodeId = string.Empty;
DisplayName = "Loading...";
NodeClass = string.Empty;
HasChildren = false;
}
public TreeNodeViewModel(
string nodeId,
string displayName,
string nodeClass,
bool hasChildren,
IOpcUaClientService service,
IUiDispatcher dispatcher)
{
NodeId = nodeId;
DisplayName = displayName;
NodeClass = nodeClass;
HasChildren = hasChildren;
_service = service;
_dispatcher = dispatcher;
if (hasChildren)
{
Children.Add(PlaceholderSentinel);
}
}
partial void OnIsExpandedChanged(bool value)
{
if (value && !_hasLoadedChildren && HasChildren)
{
_ = LoadChildrenAsync();
}
}
private async Task LoadChildrenAsync()
{
if (_service == null || _dispatcher == null) return;
_hasLoadedChildren = true;
IsLoading = true;
try
{
var nodeId = Opc.Ua.NodeId.Parse(NodeId);
var results = await _service.BrowseAsync(nodeId);
_dispatcher.Post(() =>
{
Children.Clear();
foreach (var result in results)
{
Children.Add(new TreeNodeViewModel(
result.NodeId,
result.DisplayName,
result.NodeClass,
result.HasChildren,
_service,
_dispatcher));
}
});
}
catch
{
_dispatcher.Post(() => Children.Clear());
}
finally
{
_dispatcher.Post(() => IsLoading = false);
}
}
/// <summary>
/// Returns whether this node instance is the placeholder sentinel.
/// </summary>
internal bool IsPlaceholder => ReferenceEquals(this, PlaceholderSentinel);
}

View File

@@ -0,0 +1,36 @@
<UserControl xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:vm="using:ZB.MOM.WW.LmxOpcUa.Client.UI.ViewModels"
x:Class="ZB.MOM.WW.LmxOpcUa.Client.UI.Views.AlarmsView"
x:DataType="vm:AlarmsViewModel">
<DockPanel Margin="8">
<!-- Controls -->
<StackPanel DockPanel.Dock="Top" Spacing="8">
<TextBlock Text="Alarm Monitoring" FontWeight="Bold" />
<StackPanel Orientation="Horizontal" Spacing="8">
<TextBox Text="{Binding MonitoredNodeIdText}" Width="250" Watermark="Source Node ID (optional)" />
<NumericUpDown Value="{Binding Interval}" Minimum="100" Maximum="60000" Width="120" />
<Button Content="Subscribe" Command="{Binding SubscribeCommand}" />
<Button Content="Unsubscribe" Command="{Binding UnsubscribeCommand}" />
<Button Content="Refresh" Command="{Binding RefreshCommand}" />
</StackPanel>
</StackPanel>
<!-- Alarm Events -->
<DataGrid ItemsSource="{Binding AlarmEvents}"
AutoGenerateColumns="False"
IsReadOnly="True"
Margin="0,8,0,0">
<DataGrid.Columns>
<DataGridTextColumn Header="Time" Binding="{Binding Time}" Width="180" />
<DataGridTextColumn Header="Source" Binding="{Binding SourceName}" Width="120" />
<DataGridTextColumn Header="Condition" Binding="{Binding ConditionName}" Width="120" />
<DataGridTextColumn Header="Severity" Binding="{Binding Severity}" Width="80" />
<DataGridTextColumn Header="Message" Binding="{Binding Message}" Width="200" />
<DataGridCheckBoxColumn Header="Active" Binding="{Binding ActiveState}" Width="60" />
<DataGridCheckBoxColumn Header="Acked" Binding="{Binding AckedState}" Width="60" />
<DataGridCheckBoxColumn Header="Retain" Binding="{Binding Retain}" Width="60" />
</DataGrid.Columns>
</DataGrid>
</DockPanel>
</UserControl>

View File

@@ -0,0 +1,11 @@
using Avalonia.Controls;
namespace ZB.MOM.WW.LmxOpcUa.Client.UI.Views;
public partial class AlarmsView : UserControl
{
public AlarmsView()
{
InitializeComponent();
}
}

View File

@@ -0,0 +1,25 @@
<UserControl xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:vm="using:ZB.MOM.WW.LmxOpcUa.Client.UI.ViewModels"
x:Class="ZB.MOM.WW.LmxOpcUa.Client.UI.Views.BrowseTreeView"
x:DataType="vm:BrowseTreeViewModel">
<TreeView ItemsSource="{Binding RootNodes}"
Name="BrowseTree">
<TreeView.ItemTemplate>
<TreeDataTemplate ItemsSource="{Binding Children}">
<StackPanel Orientation="Horizontal" Spacing="6">
<TextBlock Text="{Binding DisplayName}" VerticalAlignment="Center" />
<TextBlock Text="{Binding NodeClass}"
FontSize="10"
Foreground="Gray"
VerticalAlignment="Center" />
<ProgressBar IsIndeterminate="True"
IsVisible="{Binding IsLoading}"
Width="50"
Height="8"
VerticalAlignment="Center" />
</StackPanel>
</TreeDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
</UserControl>

View File

@@ -0,0 +1,11 @@
using Avalonia.Controls;
namespace ZB.MOM.WW.LmxOpcUa.Client.UI.Views;
public partial class BrowseTreeView : UserControl
{
public BrowseTreeView()
{
InitializeComponent();
}
}

View File

@@ -0,0 +1,68 @@
<UserControl xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:vm="using:ZB.MOM.WW.LmxOpcUa.Client.UI.ViewModels"
x:Class="ZB.MOM.WW.LmxOpcUa.Client.UI.Views.HistoryView"
x:DataType="vm:HistoryViewModel">
<DockPanel Margin="8">
<!-- Controls -->
<StackPanel DockPanel.Dock="Top" Spacing="8">
<TextBlock Text="History Read" FontWeight="Bold" />
<TextBlock Text="{Binding SelectedNodeId, FallbackValue='(no node selected)'}"
Foreground="Gray" />
<StackPanel Orientation="Horizontal" Spacing="8">
<StackPanel Spacing="2">
<TextBlock Text="Start Time" FontSize="11" />
<DatePicker SelectedDate="{Binding StartTime}" />
</StackPanel>
<StackPanel Spacing="2">
<TextBlock Text="End Time" FontSize="11" />
<DatePicker SelectedDate="{Binding EndTime}" />
</StackPanel>
<StackPanel Spacing="2">
<TextBlock Text="Max Values" FontSize="11" />
<NumericUpDown Value="{Binding MaxValues}" Minimum="1" Maximum="100000" Width="120" />
</StackPanel>
</StackPanel>
<StackPanel Orientation="Horizontal" Spacing="8">
<StackPanel Spacing="2">
<TextBlock Text="Aggregate" FontSize="11" />
<ComboBox ItemsSource="{Binding AggregateTypes}"
SelectedItem="{Binding SelectedAggregateType}"
Width="150">
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding, TargetNullValue='Raw'}" />
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
</StackPanel>
<StackPanel Spacing="2" IsVisible="{Binding IsAggregateRead}">
<TextBlock Text="Interval (ms)" FontSize="11" />
<NumericUpDown Value="{Binding IntervalMs}" Minimum="1000" Maximum="86400000" Width="150" />
</StackPanel>
<Button Content="Read History"
Command="{Binding ReadHistoryCommand}"
VerticalAlignment="Bottom" />
</StackPanel>
<ProgressBar IsIndeterminate="True"
IsVisible="{Binding IsLoading}"
Height="4" />
</StackPanel>
<!-- Results -->
<DataGrid ItemsSource="{Binding Results}"
AutoGenerateColumns="False"
IsReadOnly="True"
Margin="0,8,0,0">
<DataGrid.Columns>
<DataGridTextColumn Header="Value" Binding="{Binding Value}" Width="200" />
<DataGridTextColumn Header="Status" Binding="{Binding Status}" Width="120" />
<DataGridTextColumn Header="Source Timestamp" Binding="{Binding SourceTimestamp}" Width="220" />
<DataGridTextColumn Header="Server Timestamp" Binding="{Binding ServerTimestamp}" Width="220" />
</DataGrid.Columns>
</DataGrid>
</DockPanel>
</UserControl>

View File

@@ -0,0 +1,11 @@
using Avalonia.Controls;
namespace ZB.MOM.WW.LmxOpcUa.Client.UI.Views;
public partial class HistoryView : UserControl
{
public HistoryView()
{
InitializeComponent();
}
}

View File

@@ -0,0 +1,89 @@
<Window xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:vm="using:ZB.MOM.WW.LmxOpcUa.Client.UI.ViewModels"
xmlns:views="using:ZB.MOM.WW.LmxOpcUa.Client.UI.Views"
x:Class="ZB.MOM.WW.LmxOpcUa.Client.UI.Views.MainWindow"
x:DataType="vm:MainWindowViewModel"
Title="LmxOpcUa Client"
Width="1200"
Height="800">
<DockPanel>
<!-- Top Connection Bar -->
<Border DockPanel.Dock="Top" Background="#F0F0F0" Padding="8">
<StackPanel Spacing="8">
<StackPanel Orientation="Horizontal" Spacing="8">
<TextBox Text="{Binding EndpointUrl}"
Width="300"
Watermark="opc.tcp://host:port" />
<TextBox Text="{Binding Username}"
Width="120"
Watermark="Username" />
<TextBox Text="{Binding Password}"
Width="120"
Watermark="Password"
PasswordChar="*" />
<ComboBox ItemsSource="{Binding SecurityModes}"
SelectedItem="{Binding SelectedSecurityMode}"
Width="140" />
<Button Content="Connect"
Command="{Binding ConnectCommand}" />
<Button Content="Disconnect"
Command="{Binding DisconnectCommand}" />
</StackPanel>
<!-- Redundancy Info -->
<StackPanel Orientation="Horizontal"
Spacing="12"
IsVisible="{Binding RedundancyInfo, Converter={x:Static ObjectConverters.IsNotNull}}">
<TextBlock Text="{Binding RedundancyInfo.Mode, StringFormat='Redundancy: {0}'}"
FontSize="11" />
<TextBlock Text="{Binding RedundancyInfo.ServiceLevel, StringFormat='Service Level: {0}'}"
FontSize="11" />
<TextBlock Text="{Binding RedundancyInfo.ApplicationUri, StringFormat='URI: {0}'}"
FontSize="11" />
</StackPanel>
</StackPanel>
</Border>
<!-- Bottom Status Bar -->
<Border DockPanel.Dock="Bottom" Background="#F0F0F0" Padding="8,4">
<StackPanel Orientation="Horizontal" Spacing="20">
<TextBlock Text="{Binding StatusMessage}" />
<TextBlock Text="{Binding SessionLabel}" Foreground="Gray" />
<TextBlock Text="{Binding SubscriptionCount, StringFormat='Subscriptions: {0}'}" />
</StackPanel>
</Border>
<!-- Main Content -->
<Grid ColumnDefinitions="300,8,*">
<!-- Left: Browse Tree -->
<Border Grid.Column="0" BorderBrush="#CCCCCC" BorderThickness="0,0,1,0">
<DockPanel>
<TextBlock DockPanel.Dock="Top" Text="Browse Tree" FontWeight="Bold" Margin="8,8,8,4" />
<views:BrowseTreeView DataContext="{Binding BrowseTree}"
Name="BrowseTreePanel" />
</DockPanel>
</Border>
<!-- Splitter -->
<GridSplitter Grid.Column="1" Width="8" Background="Transparent" />
<!-- Right: Tab panels -->
<TabControl Grid.Column="2"
IsEnabled="{Binding IsConnected}">
<TabItem Header="Read/Write">
<views:ReadWriteView DataContext="{Binding ReadWrite}" />
</TabItem>
<TabItem Header="Subscriptions">
<views:SubscriptionsView DataContext="{Binding Subscriptions}" />
</TabItem>
<TabItem Header="Alarms">
<views:AlarmsView DataContext="{Binding Alarms}" />
</TabItem>
<TabItem Header="History">
<views:HistoryView DataContext="{Binding History}" />
</TabItem>
</TabControl>
</Grid>
</DockPanel>
</Window>

View File

@@ -0,0 +1,34 @@
using Avalonia.Controls;
using Avalonia.Interactivity;
using ZB.MOM.WW.LmxOpcUa.Client.UI.ViewModels;
namespace ZB.MOM.WW.LmxOpcUa.Client.UI.Views;
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
protected override void OnLoaded(RoutedEventArgs e)
{
base.OnLoaded(e);
// Wire up tree selection to the main ViewModel
var browseTreeView = this.FindControl<BrowseTreeView>("BrowseTreePanel");
var treeView = browseTreeView?.FindControl<TreeView>("BrowseTree");
if (treeView != null)
{
treeView.SelectionChanged += OnTreeSelectionChanged;
}
}
private void OnTreeSelectionChanged(object? sender, SelectionChangedEventArgs e)
{
if (DataContext is MainWindowViewModel vm && sender is TreeView treeView)
{
vm.SelectedTreeNode = treeView.SelectedItem as TreeNodeViewModel;
}
}
}

View File

@@ -0,0 +1,39 @@
<UserControl xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:vm="using:ZB.MOM.WW.LmxOpcUa.Client.UI.ViewModels"
x:Class="ZB.MOM.WW.LmxOpcUa.Client.UI.Views.ReadWriteView"
x:DataType="vm:ReadWriteViewModel">
<StackPanel Spacing="8" Margin="8">
<!-- Selected Node -->
<TextBlock Text="Selected Node" FontWeight="Bold" />
<TextBlock Text="{Binding SelectedNodeId, FallbackValue='(none)'}"
Foreground="Gray" />
<!-- Read Section -->
<Separator />
<TextBlock Text="Read Value" FontWeight="Bold" />
<Button Content="Read" Command="{Binding ReadCommand}" />
<Grid ColumnDefinitions="Auto,*" RowDefinitions="Auto,Auto,Auto,Auto" Margin="0,4,0,0">
<TextBlock Grid.Row="0" Grid.Column="0" Text="Value: " FontWeight="SemiBold" />
<TextBlock Grid.Row="0" Grid.Column="1" Text="{Binding CurrentValue}" TextWrapping="Wrap" />
<TextBlock Grid.Row="1" Grid.Column="0" Text="Status: " FontWeight="SemiBold" />
<TextBlock Grid.Row="1" Grid.Column="1" Text="{Binding CurrentStatus}" />
<TextBlock Grid.Row="2" Grid.Column="0" Text="Source Time: " FontWeight="SemiBold" />
<TextBlock Grid.Row="2" Grid.Column="1" Text="{Binding SourceTimestamp}" />
<TextBlock Grid.Row="3" Grid.Column="0" Text="Server Time: " FontWeight="SemiBold" />
<TextBlock Grid.Row="3" Grid.Column="1" Text="{Binding ServerTimestamp}" />
</Grid>
<!-- Write Section -->
<Separator />
<TextBlock Text="Write Value" FontWeight="Bold" />
<StackPanel Orientation="Horizontal" Spacing="8">
<TextBox Text="{Binding WriteValue}" Width="200" Watermark="Value to write" />
<Button Content="Write" Command="{Binding WriteCommand}" />
</StackPanel>
<TextBlock Text="{Binding WriteStatus}" Foreground="Gray" />
</StackPanel>
</UserControl>

View File

@@ -0,0 +1,11 @@
using Avalonia.Controls;
namespace ZB.MOM.WW.LmxOpcUa.Client.UI.Views;
public partial class ReadWriteView : UserControl
{
public ReadWriteView()
{
InitializeComponent();
}
}

View File

@@ -0,0 +1,32 @@
<UserControl xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:vm="using:ZB.MOM.WW.LmxOpcUa.Client.UI.ViewModels"
x:Class="ZB.MOM.WW.LmxOpcUa.Client.UI.Views.SubscriptionsView"
x:DataType="vm:SubscriptionsViewModel">
<DockPanel Margin="8">
<!-- Add/Remove Controls -->
<StackPanel DockPanel.Dock="Top" Spacing="8">
<TextBlock Text="Subscriptions" FontWeight="Bold" />
<StackPanel Orientation="Horizontal" Spacing="8">
<TextBox Text="{Binding NewNodeIdText}" Width="250" Watermark="Node ID (e.g., ns=2;s=MyNode)" />
<NumericUpDown Value="{Binding NewInterval}" Minimum="100" Maximum="60000" Width="120" />
<Button Content="Add" Command="{Binding AddSubscriptionCommand}" />
<Button Content="Remove" Command="{Binding RemoveSubscriptionCommand}" />
</StackPanel>
</StackPanel>
<!-- Active Subscriptions List -->
<DataGrid ItemsSource="{Binding ActiveSubscriptions}"
SelectedItem="{Binding SelectedSubscription}"
AutoGenerateColumns="False"
IsReadOnly="True"
Margin="0,8,0,0">
<DataGrid.Columns>
<DataGridTextColumn Header="Node ID" Binding="{Binding NodeId}" Width="250" />
<DataGridTextColumn Header="Value" Binding="{Binding Value}" Width="150" />
<DataGridTextColumn Header="Status" Binding="{Binding Status}" Width="120" />
<DataGridTextColumn Header="Timestamp" Binding="{Binding Timestamp}" Width="200" />
</DataGrid.Columns>
</DataGrid>
</DockPanel>
</UserControl>

View File

@@ -0,0 +1,11 @@
using Avalonia.Controls;
namespace ZB.MOM.WW.LmxOpcUa.Client.UI.Views;
public partial class SubscriptionsView : UserControl
{
public SubscriptionsView()
{
InitializeComponent();
}
}

View File

@@ -0,0 +1,30 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<RootNamespace>ZB.MOM.WW.LmxOpcUa.Client.UI</RootNamespace>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="11.2.7" />
<PackageReference Include="Avalonia.Desktop" Version="11.2.7" />
<PackageReference Include="Avalonia.Themes.Fluent" Version="11.2.7" />
<PackageReference Include="Avalonia.Fonts.Inter" Version="11.2.7" />
<PackageReference Include="Avalonia.Controls.DataGrid" Version="11.2.7" />
<PackageReference Include="CommunityToolkit.Mvvm" Version="8.4.0" />
<PackageReference Include="Serilog" Version="4.2.0" />
<PackageReference Include="Serilog.Sinks.Console" Version="6.0.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\ZB.MOM.WW.LmxOpcUa.Client.Shared\ZB.MOM.WW.LmxOpcUa.Client.Shared.csproj" />
</ItemGroup>
<ItemGroup>
<InternalsVisibleTo Include="ZB.MOM.WW.LmxOpcUa.Client.UI.Tests" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,168 @@
using Shouldly;
using Xunit;
using ZB.MOM.WW.LmxOpcUa.Client.CLI.Commands;
using ZB.MOM.WW.LmxOpcUa.Client.CLI.Tests.Fakes;
namespace ZB.MOM.WW.LmxOpcUa.Client.CLI.Tests;
public class AlarmsCommandTests
{
[Fact]
public async Task Execute_SubscribesToAlarms()
{
var fakeService = new FakeOpcUaClientService();
var factory = new FakeOpcUaClientServiceFactory(fakeService);
var command = new AlarmsCommand(factory)
{
Url = "opc.tcp://localhost:4840",
Interval = 2000
};
using var console = TestConsoleHelper.CreateConsole();
var task = Task.Run(async () =>
{
await command.ExecuteAsync(console);
});
await Task.Delay(100);
console.RequestCancellation();
await task;
fakeService.SubscribeAlarmsCalls.Count.ShouldBe(1);
fakeService.SubscribeAlarmsCalls[0].IntervalMs.ShouldBe(2000);
fakeService.SubscribeAlarmsCalls[0].SourceNodeId.ShouldBeNull();
}
[Fact]
public async Task Execute_WithNode_PassesSourceNodeId()
{
var fakeService = new FakeOpcUaClientService();
var factory = new FakeOpcUaClientServiceFactory(fakeService);
var command = new AlarmsCommand(factory)
{
Url = "opc.tcp://localhost:4840",
NodeId = "ns=2;s=AlarmSource"
};
using var console = TestConsoleHelper.CreateConsole();
var task = Task.Run(async () =>
{
await command.ExecuteAsync(console);
});
await Task.Delay(100);
console.RequestCancellation();
await task;
fakeService.SubscribeAlarmsCalls.Count.ShouldBe(1);
fakeService.SubscribeAlarmsCalls[0].SourceNodeId.ShouldNotBeNull();
fakeService.SubscribeAlarmsCalls[0].SourceNodeId!.Identifier.ShouldBe("AlarmSource");
}
[Fact]
public async Task Execute_WithRefresh_RequestsConditionRefresh()
{
var fakeService = new FakeOpcUaClientService();
var factory = new FakeOpcUaClientServiceFactory(fakeService);
var command = new AlarmsCommand(factory)
{
Url = "opc.tcp://localhost:4840",
Refresh = true
};
using var console = TestConsoleHelper.CreateConsole();
var task = Task.Run(async () =>
{
await command.ExecuteAsync(console);
});
await Task.Delay(100);
console.RequestCancellation();
await task;
fakeService.RequestConditionRefreshCalled.ShouldBeTrue();
var output = TestConsoleHelper.GetOutput(console);
output.ShouldContain("Condition refresh requested.");
}
[Fact]
public async Task Execute_RefreshFailure_PrintsError()
{
var fakeService = new FakeOpcUaClientService
{
ConditionRefreshException = new NotSupportedException("Not supported")
};
var factory = new FakeOpcUaClientServiceFactory(fakeService);
var command = new AlarmsCommand(factory)
{
Url = "opc.tcp://localhost:4840",
Refresh = true
};
using var console = TestConsoleHelper.CreateConsole();
var task = Task.Run(async () =>
{
await command.ExecuteAsync(console);
});
await Task.Delay(100);
console.RequestCancellation();
await task;
var output = TestConsoleHelper.GetOutput(console);
output.ShouldContain("Condition refresh not supported:");
}
[Fact]
public async Task Execute_UnsubscribesOnCancellation()
{
var fakeService = new FakeOpcUaClientService();
var factory = new FakeOpcUaClientServiceFactory(fakeService);
var command = new AlarmsCommand(factory)
{
Url = "opc.tcp://localhost:4840"
};
using var console = TestConsoleHelper.CreateConsole();
var task = Task.Run(async () =>
{
await command.ExecuteAsync(console);
});
await Task.Delay(100);
console.RequestCancellation();
await task;
fakeService.UnsubscribeAlarmsCalled.ShouldBeTrue();
}
[Fact]
public async Task Execute_DisconnectsInFinally()
{
var fakeService = new FakeOpcUaClientService();
var factory = new FakeOpcUaClientServiceFactory(fakeService);
var command = new AlarmsCommand(factory)
{
Url = "opc.tcp://localhost:4840"
};
using var console = TestConsoleHelper.CreateConsole();
var task = Task.Run(async () =>
{
await command.ExecuteAsync(console);
});
await Task.Delay(100);
console.RequestCancellation();
await task;
fakeService.DisconnectCalled.ShouldBeTrue();
fakeService.DisposeCalled.ShouldBeTrue();
}
}

View File

@@ -0,0 +1,146 @@
using Shouldly;
using Xunit;
using ZB.MOM.WW.LmxOpcUa.Client.CLI.Commands;
using ZB.MOM.WW.LmxOpcUa.Client.CLI.Tests.Fakes;
using ZB.MOM.WW.LmxOpcUa.Client.Shared.Models;
using BrowseResult = ZB.MOM.WW.LmxOpcUa.Client.Shared.Models.BrowseResult;
namespace ZB.MOM.WW.LmxOpcUa.Client.CLI.Tests;
public class BrowseCommandTests
{
[Fact]
public async Task Execute_PrintsBrowseResults()
{
var fakeService = new FakeOpcUaClientService
{
BrowseResults = new List<BrowseResult>
{
new BrowseResult("ns=2;s=Obj1", "Object1", "Object", true),
new BrowseResult("ns=2;s=Var1", "Variable1", "Variable", false),
new BrowseResult("ns=2;s=Meth1", "Method1", "Method", false)
}
};
var factory = new FakeOpcUaClientServiceFactory(fakeService);
var command = new BrowseCommand(factory)
{
Url = "opc.tcp://localhost:4840"
};
using var console = TestConsoleHelper.CreateConsole();
await command.ExecuteAsync(console);
var output = TestConsoleHelper.GetOutput(console);
output.ShouldContain("[Object] Object1 (NodeId: ns=2;s=Obj1)");
output.ShouldContain("[Variable] Variable1 (NodeId: ns=2;s=Var1)");
output.ShouldContain("[Method] Method1 (NodeId: ns=2;s=Meth1)");
}
[Fact]
public async Task Execute_BrowsesFromSpecifiedNode()
{
var fakeService = new FakeOpcUaClientService
{
BrowseResults = new List<BrowseResult>()
};
var factory = new FakeOpcUaClientServiceFactory(fakeService);
var command = new BrowseCommand(factory)
{
Url = "opc.tcp://localhost:4840",
NodeId = "ns=2;s=StartNode"
};
using var console = TestConsoleHelper.CreateConsole();
await command.ExecuteAsync(console);
fakeService.BrowseNodeIds.Count.ShouldBe(1);
fakeService.BrowseNodeIds[0].ShouldNotBeNull();
fakeService.BrowseNodeIds[0]!.Identifier.ShouldBe("StartNode");
}
[Fact]
public async Task Execute_DefaultBrowsesFromNull()
{
var fakeService = new FakeOpcUaClientService
{
BrowseResults = new List<BrowseResult>()
};
var factory = new FakeOpcUaClientServiceFactory(fakeService);
var command = new BrowseCommand(factory)
{
Url = "opc.tcp://localhost:4840"
};
using var console = TestConsoleHelper.CreateConsole();
await command.ExecuteAsync(console);
fakeService.BrowseNodeIds.Count.ShouldBe(1);
fakeService.BrowseNodeIds[0].ShouldBeNull();
}
[Fact]
public async Task Execute_NonRecursive_BrowsesSingleLevel()
{
var fakeService = new FakeOpcUaClientService
{
BrowseResults = new List<BrowseResult>
{
new BrowseResult("ns=2;s=Child", "Child", "Object", true)
}
};
var factory = new FakeOpcUaClientServiceFactory(fakeService);
var command = new BrowseCommand(factory)
{
Url = "opc.tcp://localhost:4840",
Depth = 5 // Should be ignored without recursive flag
};
using var console = TestConsoleHelper.CreateConsole();
await command.ExecuteAsync(console);
// Only the root level browse should happen, not child
fakeService.BrowseNodeIds.Count.ShouldBe(1);
}
[Fact]
public async Task Execute_Recursive_BrowsesChildren()
{
var fakeService = new FakeOpcUaClientService();
// Override browse to return children only on first call
// We can't easily do this with the simple fake, but the default returns results with HasChildren=true
// which will trigger child browse with recursive=true, depth=2
var factory = new FakeOpcUaClientServiceFactory(fakeService);
var command = new BrowseCommand(factory)
{
Url = "opc.tcp://localhost:4840",
Recursive = true,
Depth = 2
};
using var console = TestConsoleHelper.CreateConsole();
await command.ExecuteAsync(console);
// Root browse + child browse (for Node1 which HasChildren=true)
fakeService.BrowseNodeIds.Count.ShouldBeGreaterThan(1);
}
[Fact]
public async Task Execute_DisconnectsInFinally()
{
var fakeService = new FakeOpcUaClientService
{
BrowseResults = new List<BrowseResult>()
};
var factory = new FakeOpcUaClientServiceFactory(fakeService);
var command = new BrowseCommand(factory)
{
Url = "opc.tcp://localhost:4840"
};
using var console = TestConsoleHelper.CreateConsole();
await command.ExecuteAsync(console);
fakeService.DisconnectCalled.ShouldBeTrue();
fakeService.DisposeCalled.ShouldBeTrue();
}
}

View File

@@ -0,0 +1,90 @@
using CliFx.Infrastructure;
using Shouldly;
using Xunit;
using ZB.MOM.WW.LmxOpcUa.Client.CLI.Commands;
using ZB.MOM.WW.LmxOpcUa.Client.CLI.Tests.Fakes;
using ZB.MOM.WW.LmxOpcUa.Client.Shared.Models;
namespace ZB.MOM.WW.LmxOpcUa.Client.CLI.Tests;
public class CommandBaseTests
{
[Fact]
public async Task CommonOptions_MapToConnectionSettings_Correctly()
{
var fakeService = new FakeOpcUaClientService();
var factory = new FakeOpcUaClientServiceFactory(fakeService);
var command = new ConnectCommand(factory)
{
Url = "opc.tcp://myserver:4840",
Username = "admin",
Password = "secret",
Security = "sign",
FailoverUrls = "opc.tcp://backup1:4840,opc.tcp://backup2:4840"
};
using var console = TestConsoleHelper.CreateConsole();
await command.ExecuteAsync(console);
var settings = fakeService.LastConnectionSettings;
settings.ShouldNotBeNull();
settings.EndpointUrl.ShouldBe("opc.tcp://myserver:4840");
settings.Username.ShouldBe("admin");
settings.Password.ShouldBe("secret");
settings.SecurityMode.ShouldBe(SecurityMode.Sign);
settings.FailoverUrls.ShouldNotBeNull();
settings.FailoverUrls!.Length.ShouldBe(3); // primary + 2 failover
settings.FailoverUrls[0].ShouldBe("opc.tcp://myserver:4840");
settings.AutoAcceptCertificates.ShouldBeTrue();
}
[Fact]
public async Task SecurityOption_Encrypt_MapsToSignAndEncrypt()
{
var fakeService = new FakeOpcUaClientService();
var factory = new FakeOpcUaClientServiceFactory(fakeService);
var command = new ConnectCommand(factory)
{
Url = "opc.tcp://localhost:4840",
Security = "encrypt"
};
using var console = TestConsoleHelper.CreateConsole();
await command.ExecuteAsync(console);
fakeService.LastConnectionSettings!.SecurityMode.ShouldBe(SecurityMode.SignAndEncrypt);
}
[Fact]
public async Task SecurityOption_None_MapsToNone()
{
var fakeService = new FakeOpcUaClientService();
var factory = new FakeOpcUaClientServiceFactory(fakeService);
var command = new ConnectCommand(factory)
{
Url = "opc.tcp://localhost:4840",
Security = "none"
};
using var console = TestConsoleHelper.CreateConsole();
await command.ExecuteAsync(console);
fakeService.LastConnectionSettings!.SecurityMode.ShouldBe(SecurityMode.None);
}
[Fact]
public async Task NoFailoverUrls_FailoverUrlsIsNull()
{
var fakeService = new FakeOpcUaClientService();
var factory = new FakeOpcUaClientServiceFactory(fakeService);
var command = new ConnectCommand(factory)
{
Url = "opc.tcp://localhost:4840"
};
using var console = TestConsoleHelper.CreateConsole();
await command.ExecuteAsync(console);
fakeService.LastConnectionSettings!.FailoverUrls.ShouldBeNull();
}
}

View File

@@ -0,0 +1,78 @@
using Shouldly;
using Xunit;
using ZB.MOM.WW.LmxOpcUa.Client.CLI.Commands;
using ZB.MOM.WW.LmxOpcUa.Client.CLI.Tests.Fakes;
using ZB.MOM.WW.LmxOpcUa.Client.Shared.Models;
namespace ZB.MOM.WW.LmxOpcUa.Client.CLI.Tests;
public class ConnectCommandTests
{
[Fact]
public async Task Execute_PrintsConnectionInfo()
{
var fakeService = new FakeOpcUaClientService
{
ConnectionInfoResult = new ConnectionInfo(
"opc.tcp://testhost:4840",
"MyServer",
"SignAndEncrypt",
"http://opcfoundation.org/UA/SecurityPolicy#Basic256Sha256",
"session-42",
"MySession")
};
var factory = new FakeOpcUaClientServiceFactory(fakeService);
var command = new ConnectCommand(factory)
{
Url = "opc.tcp://testhost:4840"
};
using var console = TestConsoleHelper.CreateConsole();
await command.ExecuteAsync(console);
var output = TestConsoleHelper.GetOutput(console);
output.ShouldContain("Connected to: opc.tcp://testhost:4840");
output.ShouldContain("Server: MyServer");
output.ShouldContain("Security Mode: SignAndEncrypt");
output.ShouldContain("Security Policy: http://opcfoundation.org/UA/SecurityPolicy#Basic256Sha256");
output.ShouldContain("Connection successful.");
}
[Fact]
public async Task Execute_CallsConnectAndDisconnect()
{
var fakeService = new FakeOpcUaClientService();
var factory = new FakeOpcUaClientServiceFactory(fakeService);
var command = new ConnectCommand(factory)
{
Url = "opc.tcp://localhost:4840"
};
using var console = TestConsoleHelper.CreateConsole();
await command.ExecuteAsync(console);
fakeService.ConnectCalled.ShouldBeTrue();
fakeService.DisconnectCalled.ShouldBeTrue();
fakeService.DisposeCalled.ShouldBeTrue();
}
[Fact]
public async Task Execute_DisconnectsOnError()
{
var fakeService = new FakeOpcUaClientService
{
ConnectException = new InvalidOperationException("Connection refused")
};
var factory = new FakeOpcUaClientServiceFactory(fakeService);
var command = new ConnectCommand(factory)
{
Url = "opc.tcp://localhost:4840"
};
using var console = TestConsoleHelper.CreateConsole();
// The command should propagate the exception but still clean up.
// Since connect fails, service is null in finally, so no disconnect.
await Should.ThrowAsync<InvalidOperationException>(
async () => await command.ExecuteAsync(console));
}
}

View File

@@ -0,0 +1,184 @@
using Opc.Ua;
using ZB.MOM.WW.LmxOpcUa.Client.Shared;
using ZB.MOM.WW.LmxOpcUa.Client.Shared.Models;
using BrowseResult = ZB.MOM.WW.LmxOpcUa.Client.Shared.Models.BrowseResult;
namespace ZB.MOM.WW.LmxOpcUa.Client.CLI.Tests.Fakes;
/// <summary>
/// Fake implementation of <see cref="IOpcUaClientService"/> for unit testing commands.
/// Records all method calls and returns configurable results.
/// </summary>
public sealed class FakeOpcUaClientService : IOpcUaClientService
{
// Track calls
public bool ConnectCalled { get; private set; }
public ConnectionSettings? LastConnectionSettings { get; private set; }
public bool DisconnectCalled { get; private set; }
public bool DisposeCalled { get; private set; }
public List<NodeId> ReadNodeIds { get; } = new();
public List<(NodeId NodeId, object Value)> WriteValues { get; } = new();
public List<NodeId?> BrowseNodeIds { get; } = new();
public List<(NodeId NodeId, int IntervalMs)> SubscribeCalls { get; } = new();
public List<NodeId> UnsubscribeCalls { get; } = new();
public List<(NodeId? SourceNodeId, int IntervalMs)> SubscribeAlarmsCalls { get; } = new();
public bool UnsubscribeAlarmsCalled { get; private set; }
public bool RequestConditionRefreshCalled { get; private set; }
public List<(NodeId NodeId, DateTime Start, DateTime End, int MaxValues)> HistoryReadRawCalls { get; } = new();
public List<(NodeId NodeId, DateTime Start, DateTime End, AggregateType Aggregate, double IntervalMs)> HistoryReadAggregateCalls { get; } = new();
public bool GetRedundancyInfoCalled { get; private set; }
// Configurable results
public ConnectionInfo ConnectionInfoResult { get; set; } = new ConnectionInfo(
"opc.tcp://localhost:4840",
"TestServer",
"None",
"http://opcfoundation.org/UA/SecurityPolicy#None",
"session-1",
"TestSession");
public DataValue ReadValueResult { get; set; } = new DataValue(
new Variant(42),
StatusCodes.Good,
DateTime.UtcNow,
DateTime.UtcNow);
public StatusCode WriteStatusCodeResult { get; set; } = StatusCodes.Good;
public IReadOnlyList<BrowseResult> BrowseResults { get; set; } = new List<BrowseResult>
{
new BrowseResult("ns=2;s=Node1", "Node1", "Object", true),
new BrowseResult("ns=2;s=Node2", "Node2", "Variable", false)
};
public IReadOnlyList<DataValue> HistoryReadResult { get; set; } = new List<DataValue>
{
new DataValue(new Variant(10.0), StatusCodes.Good, DateTime.UtcNow.AddHours(-1), DateTime.UtcNow),
new DataValue(new Variant(20.0), StatusCodes.Good, DateTime.UtcNow, DateTime.UtcNow)
};
public RedundancyInfo RedundancyInfoResult { get; set; } = new RedundancyInfo(
"Warm", 200, new[] { "urn:server1", "urn:server2" }, "urn:app:test");
public Exception? ConnectException { get; set; }
public Exception? ReadException { get; set; }
public Exception? WriteException { get; set; }
public Exception? ConditionRefreshException { get; set; }
// IOpcUaClientService implementation
public bool IsConnected => ConnectCalled && !DisconnectCalled;
public ConnectionInfo? CurrentConnectionInfo => ConnectCalled ? ConnectionInfoResult : null;
public event EventHandler<DataChangedEventArgs>? DataChanged;
public event EventHandler<AlarmEventArgs>? AlarmEvent;
public event EventHandler<ConnectionStateChangedEventArgs>? ConnectionStateChanged;
public Task<ConnectionInfo> ConnectAsync(ConnectionSettings settings, CancellationToken ct = default)
{
ConnectCalled = true;
LastConnectionSettings = settings;
if (ConnectException != null) throw ConnectException;
return Task.FromResult(ConnectionInfoResult);
}
public Task DisconnectAsync(CancellationToken ct = default)
{
DisconnectCalled = true;
return Task.CompletedTask;
}
public Task<DataValue> ReadValueAsync(NodeId nodeId, CancellationToken ct = default)
{
ReadNodeIds.Add(nodeId);
if (ReadException != null) throw ReadException;
return Task.FromResult(ReadValueResult);
}
public Task<StatusCode> WriteValueAsync(NodeId nodeId, object value, CancellationToken ct = default)
{
WriteValues.Add((nodeId, value));
if (WriteException != null) throw WriteException;
return Task.FromResult(WriteStatusCodeResult);
}
public Task<IReadOnlyList<BrowseResult>> BrowseAsync(NodeId? parentNodeId = null, CancellationToken ct = default)
{
BrowseNodeIds.Add(parentNodeId);
return Task.FromResult(BrowseResults);
}
public Task SubscribeAsync(NodeId nodeId, int intervalMs = 1000, CancellationToken ct = default)
{
SubscribeCalls.Add((nodeId, intervalMs));
return Task.CompletedTask;
}
public Task UnsubscribeAsync(NodeId nodeId, CancellationToken ct = default)
{
UnsubscribeCalls.Add(nodeId);
return Task.CompletedTask;
}
public Task SubscribeAlarmsAsync(NodeId? sourceNodeId = null, int intervalMs = 1000, CancellationToken ct = default)
{
SubscribeAlarmsCalls.Add((sourceNodeId, intervalMs));
return Task.CompletedTask;
}
public Task UnsubscribeAlarmsAsync(CancellationToken ct = default)
{
UnsubscribeAlarmsCalled = true;
return Task.CompletedTask;
}
public Task RequestConditionRefreshAsync(CancellationToken ct = default)
{
RequestConditionRefreshCalled = true;
if (ConditionRefreshException != null) throw ConditionRefreshException;
return Task.CompletedTask;
}
public Task<IReadOnlyList<DataValue>> HistoryReadRawAsync(
NodeId nodeId, DateTime startTime, DateTime endTime, int maxValues = 1000, CancellationToken ct = default)
{
HistoryReadRawCalls.Add((nodeId, startTime, endTime, maxValues));
return Task.FromResult(HistoryReadResult);
}
public Task<IReadOnlyList<DataValue>> HistoryReadAggregateAsync(
NodeId nodeId, DateTime startTime, DateTime endTime, AggregateType aggregate,
double intervalMs = 3600000, CancellationToken ct = default)
{
HistoryReadAggregateCalls.Add((nodeId, startTime, endTime, aggregate, intervalMs));
return Task.FromResult(HistoryReadResult);
}
public Task<RedundancyInfo> GetRedundancyInfoAsync(CancellationToken ct = default)
{
GetRedundancyInfoCalled = true;
return Task.FromResult(RedundancyInfoResult);
}
/// <summary>Raises the DataChanged event for testing subscribe commands.</summary>
public void RaiseDataChanged(string nodeId, DataValue value)
{
DataChanged?.Invoke(this, new DataChangedEventArgs(nodeId, value));
}
/// <summary>Raises the AlarmEvent for testing alarm commands.</summary>
public void RaiseAlarmEvent(AlarmEventArgs args)
{
AlarmEvent?.Invoke(this, args);
}
/// <summary>Raises the ConnectionStateChanged event for testing.</summary>
public void RaiseConnectionStateChanged(ConnectionState oldState, ConnectionState newState, string endpointUrl)
{
ConnectionStateChanged?.Invoke(this, new ConnectionStateChangedEventArgs(oldState, newState, endpointUrl));
}
public void Dispose()
{
DisposeCalled = true;
}
}

View File

@@ -0,0 +1,18 @@
using ZB.MOM.WW.LmxOpcUa.Client.Shared;
namespace ZB.MOM.WW.LmxOpcUa.Client.CLI.Tests.Fakes;
/// <summary>
/// Fake factory that returns a pre-configured <see cref="FakeOpcUaClientService"/> for testing.
/// </summary>
public sealed class FakeOpcUaClientServiceFactory : IOpcUaClientServiceFactory
{
private readonly FakeOpcUaClientService _service;
public FakeOpcUaClientServiceFactory(FakeOpcUaClientService service)
{
_service = service;
}
public IOpcUaClientService Create() => _service;
}

View File

@@ -0,0 +1,141 @@
using Opc.Ua;
using Shouldly;
using Xunit;
using ZB.MOM.WW.LmxOpcUa.Client.CLI.Commands;
using ZB.MOM.WW.LmxOpcUa.Client.CLI.Tests.Fakes;
using ZB.MOM.WW.LmxOpcUa.Client.Shared.Models;
namespace ZB.MOM.WW.LmxOpcUa.Client.CLI.Tests;
public class HistoryReadCommandTests
{
[Fact]
public async Task Execute_RawRead_PrintsValues()
{
var time1 = new DateTime(2025, 6, 15, 10, 0, 0, DateTimeKind.Utc);
var time2 = new DateTime(2025, 6, 15, 11, 0, 0, DateTimeKind.Utc);
var fakeService = new FakeOpcUaClientService
{
HistoryReadResult = new List<DataValue>
{
new DataValue(new Variant(10.5), StatusCodes.Good, time1, time1),
new DataValue(new Variant(20.3), StatusCodes.Good, time2, time2)
}
};
var factory = new FakeOpcUaClientServiceFactory(fakeService);
var command = new HistoryReadCommand(factory)
{
Url = "opc.tcp://localhost:4840",
NodeId = "ns=2;s=HistNode",
StartTime = "2025-06-15T00:00:00Z",
EndTime = "2025-06-15T23:59:59Z"
};
using var console = TestConsoleHelper.CreateConsole();
await command.ExecuteAsync(console);
var output = TestConsoleHelper.GetOutput(console);
output.ShouldContain("History for ns=2;s=HistNode");
output.ShouldContain("Timestamp");
output.ShouldContain("Value");
output.ShouldContain("Status");
output.ShouldContain("2 values returned.");
}
[Fact]
public async Task Execute_RawRead_CallsHistoryReadRaw()
{
var fakeService = new FakeOpcUaClientService();
var factory = new FakeOpcUaClientServiceFactory(fakeService);
var command = new HistoryReadCommand(factory)
{
Url = "opc.tcp://localhost:4840",
NodeId = "ns=2;s=HistNode",
MaxValues = 500
};
using var console = TestConsoleHelper.CreateConsole();
await command.ExecuteAsync(console);
fakeService.HistoryReadRawCalls.Count.ShouldBe(1);
fakeService.HistoryReadRawCalls[0].MaxValues.ShouldBe(500);
fakeService.HistoryReadRawCalls[0].NodeId.Identifier.ShouldBe("HistNode");
}
[Fact]
public async Task Execute_AggregateRead_CallsHistoryReadAggregate()
{
var fakeService = new FakeOpcUaClientService();
var factory = new FakeOpcUaClientServiceFactory(fakeService);
var command = new HistoryReadCommand(factory)
{
Url = "opc.tcp://localhost:4840",
NodeId = "ns=2;s=HistNode",
Aggregate = "Average",
IntervalMs = 60000
};
using var console = TestConsoleHelper.CreateConsole();
await command.ExecuteAsync(console);
fakeService.HistoryReadAggregateCalls.Count.ShouldBe(1);
fakeService.HistoryReadAggregateCalls[0].Aggregate.ShouldBe(AggregateType.Average);
fakeService.HistoryReadAggregateCalls[0].IntervalMs.ShouldBe(60000);
}
[Fact]
public async Task Execute_AggregateRead_PrintsAggregateInfo()
{
var fakeService = new FakeOpcUaClientService();
var factory = new FakeOpcUaClientServiceFactory(fakeService);
var command = new HistoryReadCommand(factory)
{
Url = "opc.tcp://localhost:4840",
NodeId = "ns=2;s=HistNode",
Aggregate = "Maximum",
IntervalMs = 7200000
};
using var console = TestConsoleHelper.CreateConsole();
await command.ExecuteAsync(console);
var output = TestConsoleHelper.GetOutput(console);
output.ShouldContain("Maximum");
output.ShouldContain("7200000");
}
[Fact]
public async Task Execute_InvalidAggregate_ThrowsArgumentException()
{
var fakeService = new FakeOpcUaClientService();
var factory = new FakeOpcUaClientServiceFactory(fakeService);
var command = new HistoryReadCommand(factory)
{
Url = "opc.tcp://localhost:4840",
NodeId = "ns=2;s=HistNode",
Aggregate = "InvalidAgg"
};
using var console = TestConsoleHelper.CreateConsole();
await Should.ThrowAsync<ArgumentException>(
async () => await command.ExecuteAsync(console));
}
[Fact]
public async Task Execute_DisconnectsInFinally()
{
var fakeService = new FakeOpcUaClientService();
var factory = new FakeOpcUaClientServiceFactory(fakeService);
var command = new HistoryReadCommand(factory)
{
Url = "opc.tcp://localhost:4840",
NodeId = "ns=2;s=HistNode"
};
using var console = TestConsoleHelper.CreateConsole();
await command.ExecuteAsync(console);
fakeService.DisconnectCalled.ShouldBeTrue();
fakeService.DisposeCalled.ShouldBeTrue();
}
}

View File

@@ -0,0 +1,87 @@
using Opc.Ua;
using Shouldly;
using Xunit;
using ZB.MOM.WW.LmxOpcUa.Client.CLI.Helpers;
namespace ZB.MOM.WW.LmxOpcUa.Client.CLI.Tests;
public class NodeIdParserTests
{
[Fact]
public void Parse_NullInput_ReturnsNull()
{
NodeIdParser.Parse(null).ShouldBeNull();
}
[Fact]
public void Parse_EmptyString_ReturnsNull()
{
NodeIdParser.Parse("").ShouldBeNull();
}
[Fact]
public void Parse_WhitespaceOnly_ReturnsNull()
{
NodeIdParser.Parse(" ").ShouldBeNull();
}
[Fact]
public void Parse_StandardStringFormat_ReturnsNodeId()
{
var result = NodeIdParser.Parse("ns=2;s=MyNode");
result.ShouldNotBeNull();
result.NamespaceIndex.ShouldBe((ushort)2);
result.Identifier.ShouldBe("MyNode");
}
[Fact]
public void Parse_NumericFormat_ReturnsNodeId()
{
var result = NodeIdParser.Parse("i=85");
result.ShouldNotBeNull();
result.IdType.ShouldBe(IdType.Numeric);
}
[Fact]
public void Parse_BareNumeric_ReturnsNamespace0NumericNodeId()
{
var result = NodeIdParser.Parse("85");
result.ShouldNotBeNull();
result.NamespaceIndex.ShouldBe((ushort)0);
result.Identifier.ShouldBe((uint)85);
}
[Fact]
public void Parse_WithWhitespacePadding_Trims()
{
var result = NodeIdParser.Parse(" ns=2;s=MyNode ");
result.ShouldNotBeNull();
result.Identifier.ShouldBe("MyNode");
}
[Fact]
public void Parse_InvalidFormat_ThrowsFormatException()
{
Should.Throw<FormatException>(() => NodeIdParser.Parse("not-a-node-id"));
}
[Fact]
public void ParseRequired_NullInput_ThrowsArgumentException()
{
Should.Throw<ArgumentException>(() => NodeIdParser.ParseRequired(null));
}
[Fact]
public void ParseRequired_EmptyInput_ThrowsArgumentException()
{
Should.Throw<ArgumentException>(() => NodeIdParser.ParseRequired(""));
}
[Fact]
public void ParseRequired_ValidInput_ReturnsNodeId()
{
var result = NodeIdParser.ParseRequired("ns=2;s=TestNode");
result.ShouldNotBeNull();
result.Identifier.ShouldBe("TestNode");
}
}

View File

@@ -0,0 +1 @@
// This file intentionally left empty. Real tests are in separate files.

View File

@@ -0,0 +1,99 @@
using Opc.Ua;
using Shouldly;
using Xunit;
using ZB.MOM.WW.LmxOpcUa.Client.CLI.Commands;
using ZB.MOM.WW.LmxOpcUa.Client.CLI.Tests.Fakes;
namespace ZB.MOM.WW.LmxOpcUa.Client.CLI.Tests;
public class ReadCommandTests
{
[Fact]
public async Task Execute_PrintsReadValue()
{
var sourceTime = new DateTime(2025, 6, 15, 10, 30, 0, DateTimeKind.Utc);
var serverTime = new DateTime(2025, 6, 15, 10, 30, 1, DateTimeKind.Utc);
var fakeService = new FakeOpcUaClientService
{
ReadValueResult = new DataValue(
new Variant("Hello"),
StatusCodes.Good,
sourceTime,
serverTime)
};
var factory = new FakeOpcUaClientServiceFactory(fakeService);
var command = new ReadCommand(factory)
{
Url = "opc.tcp://localhost:4840",
NodeId = "ns=2;s=TestNode"
};
using var console = TestConsoleHelper.CreateConsole();
await command.ExecuteAsync(console);
var output = TestConsoleHelper.GetOutput(console);
output.ShouldContain("Node: ns=2;s=TestNode");
output.ShouldContain("Value: Hello");
output.ShouldContain("Status:");
output.ShouldContain("Source Time:");
output.ShouldContain("Server Time:");
}
[Fact]
public async Task Execute_CallsReadValueWithCorrectNodeId()
{
var fakeService = new FakeOpcUaClientService();
var factory = new FakeOpcUaClientServiceFactory(fakeService);
var command = new ReadCommand(factory)
{
Url = "opc.tcp://localhost:4840",
NodeId = "ns=2;s=MyVariable"
};
using var console = TestConsoleHelper.CreateConsole();
await command.ExecuteAsync(console);
fakeService.ReadNodeIds.Count.ShouldBe(1);
fakeService.ReadNodeIds[0].Identifier.ShouldBe("MyVariable");
}
[Fact]
public async Task Execute_DisconnectsInFinally()
{
var fakeService = new FakeOpcUaClientService();
var factory = new FakeOpcUaClientServiceFactory(fakeService);
var command = new ReadCommand(factory)
{
Url = "opc.tcp://localhost:4840",
NodeId = "ns=2;s=TestNode"
};
using var console = TestConsoleHelper.CreateConsole();
await command.ExecuteAsync(console);
fakeService.DisconnectCalled.ShouldBeTrue();
fakeService.DisposeCalled.ShouldBeTrue();
}
[Fact]
public async Task Execute_DisconnectsEvenOnReadError()
{
var fakeService = new FakeOpcUaClientService
{
ReadException = new InvalidOperationException("Read failed")
};
var factory = new FakeOpcUaClientServiceFactory(fakeService);
var command = new ReadCommand(factory)
{
Url = "opc.tcp://localhost:4840",
NodeId = "ns=2;s=TestNode"
};
using var console = TestConsoleHelper.CreateConsole();
await Should.ThrowAsync<InvalidOperationException>(
async () => await command.ExecuteAsync(console));
fakeService.DisconnectCalled.ShouldBeTrue();
fakeService.DisposeCalled.ShouldBeTrue();
}
}

View File

@@ -0,0 +1,93 @@
using Shouldly;
using Xunit;
using ZB.MOM.WW.LmxOpcUa.Client.CLI.Commands;
using ZB.MOM.WW.LmxOpcUa.Client.CLI.Tests.Fakes;
using ZB.MOM.WW.LmxOpcUa.Client.Shared.Models;
namespace ZB.MOM.WW.LmxOpcUa.Client.CLI.Tests;
public class RedundancyCommandTests
{
[Fact]
public async Task Execute_PrintsRedundancyInfo()
{
var fakeService = new FakeOpcUaClientService
{
RedundancyInfoResult = new RedundancyInfo(
"Hot", 250, new[] { "urn:server:primary", "urn:server:secondary" }, "urn:app:myserver")
};
var factory = new FakeOpcUaClientServiceFactory(fakeService);
var command = new RedundancyCommand(factory)
{
Url = "opc.tcp://localhost:4840"
};
using var console = TestConsoleHelper.CreateConsole();
await command.ExecuteAsync(console);
var output = TestConsoleHelper.GetOutput(console);
output.ShouldContain("Redundancy Mode: Hot");
output.ShouldContain("Service Level: 250");
output.ShouldContain("Server URIs:");
output.ShouldContain(" - urn:server:primary");
output.ShouldContain(" - urn:server:secondary");
output.ShouldContain("Application URI: urn:app:myserver");
}
[Fact]
public async Task Execute_NoServerUris_OmitsUriSection()
{
var fakeService = new FakeOpcUaClientService
{
RedundancyInfoResult = new RedundancyInfo(
"None", 100, Array.Empty<string>(), "urn:app:standalone")
};
var factory = new FakeOpcUaClientServiceFactory(fakeService);
var command = new RedundancyCommand(factory)
{
Url = "opc.tcp://localhost:4840"
};
using var console = TestConsoleHelper.CreateConsole();
await command.ExecuteAsync(console);
var output = TestConsoleHelper.GetOutput(console);
output.ShouldContain("Redundancy Mode: None");
output.ShouldContain("Service Level: 100");
output.ShouldNotContain("Server URIs:");
output.ShouldContain("Application URI: urn:app:standalone");
}
[Fact]
public async Task Execute_CallsGetRedundancyInfo()
{
var fakeService = new FakeOpcUaClientService();
var factory = new FakeOpcUaClientServiceFactory(fakeService);
var command = new RedundancyCommand(factory)
{
Url = "opc.tcp://localhost:4840"
};
using var console = TestConsoleHelper.CreateConsole();
await command.ExecuteAsync(console);
fakeService.GetRedundancyInfoCalled.ShouldBeTrue();
}
[Fact]
public async Task Execute_DisconnectsInFinally()
{
var fakeService = new FakeOpcUaClientService();
var factory = new FakeOpcUaClientServiceFactory(fakeService);
var command = new RedundancyCommand(factory)
{
Url = "opc.tcp://localhost:4840"
};
using var console = TestConsoleHelper.CreateConsole();
await command.ExecuteAsync(console);
fakeService.DisconnectCalled.ShouldBeTrue();
fakeService.DisposeCalled.ShouldBeTrue();
}
}

View File

@@ -0,0 +1,120 @@
using Opc.Ua;
using Shouldly;
using Xunit;
using ZB.MOM.WW.LmxOpcUa.Client.CLI.Commands;
using ZB.MOM.WW.LmxOpcUa.Client.CLI.Tests.Fakes;
namespace ZB.MOM.WW.LmxOpcUa.Client.CLI.Tests;
public class SubscribeCommandTests
{
[Fact]
public async Task Execute_SubscribesWithCorrectParameters()
{
var fakeService = new FakeOpcUaClientService();
var factory = new FakeOpcUaClientServiceFactory(fakeService);
var command = new SubscribeCommand(factory)
{
Url = "opc.tcp://localhost:4840",
NodeId = "ns=2;s=TestVar",
Interval = 500
};
using var console = TestConsoleHelper.CreateConsole();
// The subscribe command waits for cancellation. We need to cancel it.
// Use the console's cancellation to trigger stop.
var task = Task.Run(async () =>
{
await command.ExecuteAsync(console);
});
// Give it a moment to subscribe, then cancel
await Task.Delay(100);
console.RequestCancellation();
await task;
fakeService.SubscribeCalls.Count.ShouldBe(1);
fakeService.SubscribeCalls[0].IntervalMs.ShouldBe(500);
fakeService.SubscribeCalls[0].NodeId.Identifier.ShouldBe("TestVar");
}
[Fact]
public async Task Execute_UnsubscribesOnCancellation()
{
var fakeService = new FakeOpcUaClientService();
var factory = new FakeOpcUaClientServiceFactory(fakeService);
var command = new SubscribeCommand(factory)
{
Url = "opc.tcp://localhost:4840",
NodeId = "ns=2;s=TestVar"
};
using var console = TestConsoleHelper.CreateConsole();
var task = Task.Run(async () =>
{
await command.ExecuteAsync(console);
});
await Task.Delay(100);
console.RequestCancellation();
await task;
fakeService.UnsubscribeCalls.Count.ShouldBe(1);
}
[Fact]
public async Task Execute_DisconnectsInFinally()
{
var fakeService = new FakeOpcUaClientService();
var factory = new FakeOpcUaClientServiceFactory(fakeService);
var command = new SubscribeCommand(factory)
{
Url = "opc.tcp://localhost:4840",
NodeId = "ns=2;s=TestVar"
};
using var console = TestConsoleHelper.CreateConsole();
var task = Task.Run(async () =>
{
await command.ExecuteAsync(console);
});
await Task.Delay(100);
console.RequestCancellation();
await task;
fakeService.DisconnectCalled.ShouldBeTrue();
fakeService.DisposeCalled.ShouldBeTrue();
}
[Fact]
public async Task Execute_PrintsSubscriptionMessage()
{
var fakeService = new FakeOpcUaClientService();
var factory = new FakeOpcUaClientServiceFactory(fakeService);
var command = new SubscribeCommand(factory)
{
Url = "opc.tcp://localhost:4840",
NodeId = "ns=2;s=TestVar",
Interval = 2000
};
using var console = TestConsoleHelper.CreateConsole();
var task = Task.Run(async () =>
{
await command.ExecuteAsync(console);
});
await Task.Delay(100);
console.RequestCancellation();
await task;
var output = TestConsoleHelper.GetOutput(console);
output.ShouldContain("Subscribed to ns=2;s=TestVar (interval: 2000ms)");
output.ShouldContain("Unsubscribed.");
}
}

View File

@@ -0,0 +1,35 @@
using CliFx.Infrastructure;
namespace ZB.MOM.WW.LmxOpcUa.Client.CLI.Tests;
/// <summary>
/// Helper for creating CliFx <see cref="FakeInMemoryConsole"/> instances and reading their output.
/// </summary>
public static class TestConsoleHelper
{
/// <summary>
/// Creates a new <see cref="FakeInMemoryConsole"/> for testing.
/// </summary>
public static FakeInMemoryConsole CreateConsole()
{
return new FakeInMemoryConsole();
}
/// <summary>
/// Reads all text written to the console's standard output.
/// </summary>
public static string GetOutput(FakeInMemoryConsole console)
{
console.Output.Flush();
return console.ReadOutputString();
}
/// <summary>
/// Reads all text written to the console's standard error.
/// </summary>
public static string GetError(FakeInMemoryConsole console)
{
console.Error.Flush();
return console.ReadErrorString();
}
}

View File

@@ -0,0 +1,103 @@
using Opc.Ua;
using Shouldly;
using Xunit;
using ZB.MOM.WW.LmxOpcUa.Client.CLI.Commands;
using ZB.MOM.WW.LmxOpcUa.Client.CLI.Tests.Fakes;
namespace ZB.MOM.WW.LmxOpcUa.Client.CLI.Tests;
public class WriteCommandTests
{
[Fact]
public async Task Execute_WritesSuccessfully()
{
var fakeService = new FakeOpcUaClientService
{
ReadValueResult = new DataValue(new Variant(42)),
WriteStatusCodeResult = StatusCodes.Good
};
var factory = new FakeOpcUaClientServiceFactory(fakeService);
var command = new WriteCommand(factory)
{
Url = "opc.tcp://localhost:4840",
NodeId = "ns=2;s=MyVar",
Value = "100"
};
using var console = TestConsoleHelper.CreateConsole();
await command.ExecuteAsync(console);
var output = TestConsoleHelper.GetOutput(console);
output.ShouldContain("Write successful: ns=2;s=MyVar = 100");
}
[Fact]
public async Task Execute_ReportsFailure()
{
var fakeService = new FakeOpcUaClientService
{
ReadValueResult = new DataValue(new Variant("current")),
WriteStatusCodeResult = StatusCodes.BadNotWritable
};
var factory = new FakeOpcUaClientServiceFactory(fakeService);
var command = new WriteCommand(factory)
{
Url = "opc.tcp://localhost:4840",
NodeId = "ns=2;s=ReadOnly",
Value = "newvalue"
};
using var console = TestConsoleHelper.CreateConsole();
await command.ExecuteAsync(console);
var output = TestConsoleHelper.GetOutput(console);
output.ShouldContain("Write failed:");
}
[Fact]
public async Task Execute_ReadsCurrentValueThenWrites()
{
var fakeService = new FakeOpcUaClientService
{
ReadValueResult = new DataValue(new Variant(3.14)),
WriteStatusCodeResult = StatusCodes.Good
};
var factory = new FakeOpcUaClientServiceFactory(fakeService);
var command = new WriteCommand(factory)
{
Url = "opc.tcp://localhost:4840",
NodeId = "ns=2;s=FloatVar",
Value = "2.718"
};
using var console = TestConsoleHelper.CreateConsole();
await command.ExecuteAsync(console);
// Should read first to get current type, then write
fakeService.ReadNodeIds.Count.ShouldBe(1);
fakeService.WriteValues.Count.ShouldBe(1);
fakeService.WriteValues[0].Value.ShouldBeOfType<double>();
}
[Fact]
public async Task Execute_DisconnectsInFinally()
{
var fakeService = new FakeOpcUaClientService
{
ReadValueResult = new DataValue(new Variant("test"))
};
var factory = new FakeOpcUaClientServiceFactory(fakeService);
var command = new WriteCommand(factory)
{
Url = "opc.tcp://localhost:4840",
NodeId = "ns=2;s=Node",
Value = "value"
};
using var console = TestConsoleHelper.CreateConsole();
await command.ExecuteAsync(console);
fakeService.DisconnectCalled.ShouldBeTrue();
fakeService.DisposeCalled.ShouldBeTrue();
}
}

View File

@@ -0,0 +1,27 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<IsPackable>false</IsPackable>
<IsTestProject>true</IsTestProject>
<RootNamespace>ZB.MOM.WW.LmxOpcUa.Client.CLI.Tests</RootNamespace>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="xunit.v3" Version="1.1.0" />
<PackageReference Include="Shouldly" Version="4.3.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.12.0" />
<PackageReference Include="CliFx" Version="2.3.6" />
<PackageReference Include="xunit.runner.visualstudio" Version="3.0.2">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\ZB.MOM.WW.LmxOpcUa.Client.CLI\ZB.MOM.WW.LmxOpcUa.Client.CLI.csproj" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,38 @@
using Opc.Ua;
using ZB.MOM.WW.LmxOpcUa.Client.Shared.Adapters;
using ZB.MOM.WW.LmxOpcUa.Client.Shared.Models;
namespace ZB.MOM.WW.LmxOpcUa.Client.Shared.Tests.Fakes;
internal sealed class FakeApplicationConfigurationFactory : IApplicationConfigurationFactory
{
public bool ThrowOnCreate { get; set; }
public int CreateCallCount { get; private set; }
public ConnectionSettings? LastSettings { get; private set; }
public Task<ApplicationConfiguration> CreateAsync(ConnectionSettings settings, CancellationToken ct)
{
CreateCallCount++;
LastSettings = settings;
if (ThrowOnCreate)
throw new InvalidOperationException("FakeApplicationConfigurationFactory configured to fail.");
var config = new ApplicationConfiguration
{
ApplicationName = "FakeClient",
ApplicationUri = "urn:localhost:FakeClient",
ApplicationType = ApplicationType.Client,
SecurityConfiguration = new SecurityConfiguration
{
AutoAcceptUntrustedCertificates = true
},
ClientConfiguration = new ClientConfiguration
{
DefaultSessionTimeout = settings.SessionTimeoutSeconds * 1000
}
};
return Task.FromResult(config);
}
}

View File

@@ -0,0 +1,34 @@
using Opc.Ua;
using ZB.MOM.WW.LmxOpcUa.Client.Shared.Adapters;
namespace ZB.MOM.WW.LmxOpcUa.Client.Shared.Tests.Fakes;
internal sealed class FakeEndpointDiscovery : IEndpointDiscovery
{
public bool ThrowOnSelect { get; set; }
public int SelectCallCount { get; private set; }
public string? LastEndpointUrl { get; private set; }
public EndpointDescription SelectEndpoint(ApplicationConfiguration config, string endpointUrl, MessageSecurityMode requestedMode)
{
SelectCallCount++;
LastEndpointUrl = endpointUrl;
if (ThrowOnSelect)
throw new InvalidOperationException($"No endpoint found for {endpointUrl}");
return new EndpointDescription
{
EndpointUrl = endpointUrl,
SecurityMode = requestedMode,
SecurityPolicyUri = requestedMode == MessageSecurityMode.None
? SecurityPolicies.None
: SecurityPolicies.Basic256Sha256,
Server = new ApplicationDescription
{
ApplicationName = "FakeServer",
ApplicationUri = "urn:localhost:FakeServer"
}
};
}
}

View File

@@ -0,0 +1,150 @@
using Opc.Ua;
using ZB.MOM.WW.LmxOpcUa.Client.Shared.Adapters;
namespace ZB.MOM.WW.LmxOpcUa.Client.Shared.Tests.Fakes;
internal sealed class FakeSessionAdapter : ISessionAdapter
{
private Action<bool>? _keepAliveCallback;
private readonly List<FakeSubscriptionAdapter> _createdSubscriptions = new();
public bool Connected { get; set; } = true;
public string SessionId { get; set; } = "ns=0;i=12345";
public string SessionName { get; set; } = "FakeSession";
public string EndpointUrl { get; set; } = "opc.tcp://localhost:4840";
public string ServerName { get; set; } = "FakeServer";
public string SecurityMode { get; set; } = "None";
public string SecurityPolicyUri { get; set; } = "http://opcfoundation.org/UA/SecurityPolicy#None";
public NamespaceTable NamespaceUris { get; set; } = new();
public bool Closed { get; private set; }
public bool Disposed { get; private set; }
public int ReadCount { get; private set; }
public int WriteCount { get; private set; }
public int BrowseCount { get; private set; }
public int BrowseNextCount { get; private set; }
public int HasChildrenCount { get; private set; }
public int HistoryReadRawCount { get; private set; }
public int HistoryReadAggregateCount { get; private set; }
// Configurable responses
public DataValue? ReadResponse { get; set; }
public Func<NodeId, DataValue>? ReadResponseFunc { get; set; }
public StatusCode WriteResponse { get; set; } = StatusCodes.Good;
public bool ThrowOnRead { get; set; }
public bool ThrowOnWrite { get; set; }
public bool ThrowOnBrowse { get; set; }
public ReferenceDescriptionCollection BrowseResponse { get; set; } = new();
public byte[]? BrowseContinuationPoint { get; set; }
public ReferenceDescriptionCollection BrowseNextResponse { get; set; } = new();
public byte[]? BrowseNextContinuationPoint { get; set; }
public bool HasChildrenResponse { get; set; } = false;
public List<DataValue> HistoryReadRawResponse { get; set; } = new();
public List<DataValue> HistoryReadAggregateResponse { get; set; } = new();
public bool ThrowOnHistoryReadRaw { get; set; }
public bool ThrowOnHistoryReadAggregate { get; set; }
/// <summary>
/// The next FakeSubscriptionAdapter to return from CreateSubscriptionAsync.
/// If null, a new one is created automatically.
/// </summary>
public FakeSubscriptionAdapter? NextSubscription { get; set; }
public IReadOnlyList<FakeSubscriptionAdapter> CreatedSubscriptions => _createdSubscriptions;
public void RegisterKeepAliveHandler(Action<bool> callback)
{
_keepAliveCallback = callback;
}
/// <summary>
/// Simulates a keep-alive event.
/// </summary>
public void SimulateKeepAlive(bool isGood)
{
_keepAliveCallback?.Invoke(isGood);
}
public Task<DataValue> ReadValueAsync(NodeId nodeId, CancellationToken ct)
{
ReadCount++;
if (ThrowOnRead)
throw new ServiceResultException(StatusCodes.BadNodeIdUnknown, "Node not found");
if (ReadResponseFunc != null)
return Task.FromResult(ReadResponseFunc(nodeId));
return Task.FromResult(ReadResponse ?? new DataValue(new Variant(0), StatusCodes.Good));
}
public Task<StatusCode> WriteValueAsync(NodeId nodeId, DataValue value, CancellationToken ct)
{
WriteCount++;
if (ThrowOnWrite)
throw new ServiceResultException(StatusCodes.BadNodeIdUnknown, "Node not found");
return Task.FromResult(WriteResponse);
}
public Task<(byte[]? ContinuationPoint, ReferenceDescriptionCollection References)> BrowseAsync(
NodeId nodeId, uint nodeClassMask, CancellationToken ct)
{
BrowseCount++;
if (ThrowOnBrowse)
throw new ServiceResultException(StatusCodes.BadNodeIdUnknown, "Node not found");
return Task.FromResult((BrowseContinuationPoint, BrowseResponse));
}
public Task<(byte[]? ContinuationPoint, ReferenceDescriptionCollection References)> BrowseNextAsync(
byte[] continuationPoint, CancellationToken ct)
{
BrowseNextCount++;
return Task.FromResult((BrowseNextContinuationPoint, BrowseNextResponse));
}
public Task<bool> HasChildrenAsync(NodeId nodeId, CancellationToken ct)
{
HasChildrenCount++;
return Task.FromResult(HasChildrenResponse);
}
public Task<IReadOnlyList<DataValue>> HistoryReadRawAsync(
NodeId nodeId, DateTime startTime, DateTime endTime, int maxValues, CancellationToken ct)
{
HistoryReadRawCount++;
if (ThrowOnHistoryReadRaw)
throw new ServiceResultException(StatusCodes.BadHistoryOperationUnsupported, "History not supported");
return Task.FromResult<IReadOnlyList<DataValue>>(HistoryReadRawResponse);
}
public Task<IReadOnlyList<DataValue>> HistoryReadAggregateAsync(
NodeId nodeId, DateTime startTime, DateTime endTime, NodeId aggregateId, double intervalMs, CancellationToken ct)
{
HistoryReadAggregateCount++;
if (ThrowOnHistoryReadAggregate)
throw new ServiceResultException(StatusCodes.BadHistoryOperationUnsupported, "History not supported");
return Task.FromResult<IReadOnlyList<DataValue>>(HistoryReadAggregateResponse);
}
public Task<ISubscriptionAdapter> CreateSubscriptionAsync(int publishingIntervalMs, CancellationToken ct)
{
var sub = NextSubscription ?? new FakeSubscriptionAdapter();
NextSubscription = null;
_createdSubscriptions.Add(sub);
return Task.FromResult<ISubscriptionAdapter>(sub);
}
public Task CloseAsync(CancellationToken ct)
{
Closed = true;
Connected = false;
return Task.CompletedTask;
}
public void Dispose()
{
Disposed = true;
Connected = false;
}
}

View File

@@ -0,0 +1,56 @@
using Opc.Ua;
using ZB.MOM.WW.LmxOpcUa.Client.Shared.Adapters;
namespace ZB.MOM.WW.LmxOpcUa.Client.Shared.Tests.Fakes;
internal sealed class FakeSessionFactory : ISessionFactory
{
private readonly Queue<FakeSessionAdapter> _sessions = new();
private readonly List<FakeSessionAdapter> _createdSessions = new();
public int CreateCallCount { get; private set; }
public bool ThrowOnCreate { get; set; }
public string? LastEndpointUrl { get; private set; }
/// <summary>
/// Enqueues a session adapter to be returned on the next call to CreateSessionAsync.
/// </summary>
public void EnqueueSession(FakeSessionAdapter session)
{
_sessions.Enqueue(session);
}
public IReadOnlyList<FakeSessionAdapter> CreatedSessions => _createdSessions;
public Task<ISessionAdapter> CreateSessionAsync(
ApplicationConfiguration config, EndpointDescription endpoint, string sessionName,
uint sessionTimeoutMs, UserIdentity identity, CancellationToken ct)
{
CreateCallCount++;
LastEndpointUrl = endpoint.EndpointUrl;
if (ThrowOnCreate)
throw new InvalidOperationException("FakeSessionFactory configured to fail.");
FakeSessionAdapter session;
if (_sessions.Count > 0)
{
session = _sessions.Dequeue();
}
else
{
session = new FakeSessionAdapter
{
EndpointUrl = endpoint.EndpointUrl,
ServerName = endpoint.Server?.ApplicationName?.Text ?? "FakeServer",
SecurityMode = endpoint.SecurityMode.ToString(),
SecurityPolicyUri = endpoint.SecurityPolicyUri ?? string.Empty
};
}
// Ensure endpoint URL matches
session.EndpointUrl = endpoint.EndpointUrl;
_createdSessions.Add(session);
return Task.FromResult<ISessionAdapter>(session);
}
}

View File

@@ -0,0 +1,88 @@
using Opc.Ua;
using ZB.MOM.WW.LmxOpcUa.Client.Shared.Adapters;
namespace ZB.MOM.WW.LmxOpcUa.Client.Shared.Tests.Fakes;
internal sealed class FakeSubscriptionAdapter : ISubscriptionAdapter
{
private uint _nextHandle = 100;
private readonly Dictionary<uint, (NodeId NodeId, Action<string, DataValue>? DataCallback, Action<EventFieldList>? EventCallback)> _items = new();
public uint SubscriptionId { get; set; } = 42;
public bool Deleted { get; private set; }
public bool ConditionRefreshCalled { get; private set; }
public bool ThrowOnConditionRefresh { get; set; }
public int AddDataChangeCount { get; private set; }
public int AddEventCount { get; private set; }
public int RemoveCount { get; private set; }
public Task<uint> AddDataChangeMonitoredItemAsync(NodeId nodeId, int samplingIntervalMs, Action<string, DataValue> onDataChange, CancellationToken ct)
{
AddDataChangeCount++;
var handle = _nextHandle++;
_items[handle] = (nodeId, onDataChange, null);
return Task.FromResult(handle);
}
public Task RemoveMonitoredItemAsync(uint clientHandle, CancellationToken ct)
{
RemoveCount++;
_items.Remove(clientHandle);
return Task.CompletedTask;
}
public Task<uint> AddEventMonitoredItemAsync(NodeId nodeId, int samplingIntervalMs, EventFilter filter, Action<EventFieldList> onEvent, CancellationToken ct)
{
AddEventCount++;
var handle = _nextHandle++;
_items[handle] = (nodeId, null, onEvent);
return Task.FromResult(handle);
}
public Task ConditionRefreshAsync(CancellationToken ct)
{
ConditionRefreshCalled = true;
if (ThrowOnConditionRefresh)
throw new InvalidOperationException("Condition refresh not supported");
return Task.CompletedTask;
}
public Task DeleteAsync(CancellationToken ct)
{
Deleted = true;
_items.Clear();
return Task.CompletedTask;
}
public void Dispose()
{
_items.Clear();
}
/// <summary>
/// Simulates a data change notification for testing.
/// </summary>
public void SimulateDataChange(uint handle, DataValue value)
{
if (_items.TryGetValue(handle, out var item) && item.DataCallback != null)
{
item.DataCallback(item.NodeId.ToString(), value);
}
}
/// <summary>
/// Simulates an event notification for testing.
/// </summary>
public void SimulateEvent(uint handle, EventFieldList eventFields)
{
if (_items.TryGetValue(handle, out var item) && item.EventCallback != null)
{
item.EventCallback(eventFields);
}
}
/// <summary>
/// Gets the handles of all active items.
/// </summary>
public IReadOnlyCollection<uint> ActiveHandles => _items.Keys.ToList();
}

View File

@@ -0,0 +1,67 @@
using Opc.Ua;
using Shouldly;
using Xunit;
using ZB.MOM.WW.LmxOpcUa.Client.Shared.Helpers;
using ZB.MOM.WW.LmxOpcUa.Client.Shared.Models;
namespace ZB.MOM.WW.LmxOpcUa.Client.Shared.Tests.Helpers;
public class AggregateTypeMapperTests
{
[Theory]
[InlineData(AggregateType.Average)]
[InlineData(AggregateType.Minimum)]
[InlineData(AggregateType.Maximum)]
[InlineData(AggregateType.Count)]
[InlineData(AggregateType.Start)]
[InlineData(AggregateType.End)]
public void ToNodeId_ReturnsNonNullForAllValues(AggregateType aggregate)
{
var nodeId = AggregateTypeMapper.ToNodeId(aggregate);
nodeId.ShouldNotBeNull();
nodeId.IsNullNodeId.ShouldBeFalse();
}
[Fact]
public void ToNodeId_Average_MapsCorrectly()
{
AggregateTypeMapper.ToNodeId(AggregateType.Average).ShouldBe(ObjectIds.AggregateFunction_Average);
}
[Fact]
public void ToNodeId_Minimum_MapsCorrectly()
{
AggregateTypeMapper.ToNodeId(AggregateType.Minimum).ShouldBe(ObjectIds.AggregateFunction_Minimum);
}
[Fact]
public void ToNodeId_Maximum_MapsCorrectly()
{
AggregateTypeMapper.ToNodeId(AggregateType.Maximum).ShouldBe(ObjectIds.AggregateFunction_Maximum);
}
[Fact]
public void ToNodeId_Count_MapsCorrectly()
{
AggregateTypeMapper.ToNodeId(AggregateType.Count).ShouldBe(ObjectIds.AggregateFunction_Count);
}
[Fact]
public void ToNodeId_Start_MapsCorrectly()
{
AggregateTypeMapper.ToNodeId(AggregateType.Start).ShouldBe(ObjectIds.AggregateFunction_Start);
}
[Fact]
public void ToNodeId_End_MapsCorrectly()
{
AggregateTypeMapper.ToNodeId(AggregateType.End).ShouldBe(ObjectIds.AggregateFunction_End);
}
[Fact]
public void ToNodeId_InvalidValue_Throws()
{
Should.Throw<ArgumentOutOfRangeException>(() =>
AggregateTypeMapper.ToNodeId((AggregateType)99));
}
}

View File

@@ -0,0 +1,110 @@
using Shouldly;
using Xunit;
using ZB.MOM.WW.LmxOpcUa.Client.Shared.Helpers;
namespace ZB.MOM.WW.LmxOpcUa.Client.Shared.Tests.Helpers;
public class FailoverUrlParserTests
{
[Fact]
public void Parse_CsvNull_ReturnsPrimaryOnly()
{
var result = FailoverUrlParser.Parse("opc.tcp://primary:4840", (string?)null);
result.ShouldBe(new[] { "opc.tcp://primary:4840" });
}
[Fact]
public void Parse_CsvEmpty_ReturnsPrimaryOnly()
{
var result = FailoverUrlParser.Parse("opc.tcp://primary:4840", "");
result.ShouldBe(new[] { "opc.tcp://primary:4840" });
}
[Fact]
public void Parse_CsvWhitespace_ReturnsPrimaryOnly()
{
var result = FailoverUrlParser.Parse("opc.tcp://primary:4840", " ");
result.ShouldBe(new[] { "opc.tcp://primary:4840" });
}
[Fact]
public void Parse_SingleFailover_ReturnsBoth()
{
var result = FailoverUrlParser.Parse("opc.tcp://primary:4840", "opc.tcp://backup:4840");
result.ShouldBe(new[] { "opc.tcp://primary:4840", "opc.tcp://backup:4840" });
}
[Fact]
public void Parse_MultipleFailovers_ReturnsAll()
{
var result = FailoverUrlParser.Parse("opc.tcp://primary:4840", "opc.tcp://backup1:4840,opc.tcp://backup2:4840");
result.ShouldBe(new[] { "opc.tcp://primary:4840", "opc.tcp://backup1:4840", "opc.tcp://backup2:4840" });
}
[Fact]
public void Parse_TrimsWhitespace()
{
var result = FailoverUrlParser.Parse("opc.tcp://primary:4840", " opc.tcp://backup:4840 ");
result.ShouldBe(new[] { "opc.tcp://primary:4840", "opc.tcp://backup:4840" });
}
[Fact]
public void Parse_DeduplicatesPrimaryInFailoverList()
{
var result = FailoverUrlParser.Parse("opc.tcp://primary:4840", "opc.tcp://primary:4840,opc.tcp://backup:4840");
result.ShouldBe(new[] { "opc.tcp://primary:4840", "opc.tcp://backup:4840" });
}
[Fact]
public void Parse_DeduplicatesCaseInsensitive()
{
var result = FailoverUrlParser.Parse("opc.tcp://Primary:4840", "opc.tcp://primary:4840");
result.ShouldBe(new[] { "opc.tcp://Primary:4840" });
}
[Fact]
public void Parse_ArrayNull_ReturnsPrimaryOnly()
{
var result = FailoverUrlParser.Parse("opc.tcp://primary:4840", (string[]?)null);
result.ShouldBe(new[] { "opc.tcp://primary:4840" });
}
[Fact]
public void Parse_ArrayEmpty_ReturnsPrimaryOnly()
{
var result = FailoverUrlParser.Parse("opc.tcp://primary:4840", Array.Empty<string>());
result.ShouldBe(new[] { "opc.tcp://primary:4840" });
}
[Fact]
public void Parse_ArrayWithUrls_ReturnsAll()
{
var result = FailoverUrlParser.Parse("opc.tcp://primary:4840",
new[] { "opc.tcp://backup1:4840", "opc.tcp://backup2:4840" });
result.ShouldBe(new[] { "opc.tcp://primary:4840", "opc.tcp://backup1:4840", "opc.tcp://backup2:4840" });
}
[Fact]
public void Parse_ArrayDeduplicates()
{
var result = FailoverUrlParser.Parse("opc.tcp://primary:4840",
new[] { "opc.tcp://primary:4840", "opc.tcp://backup:4840" });
result.ShouldBe(new[] { "opc.tcp://primary:4840", "opc.tcp://backup:4840" });
}
[Fact]
public void Parse_ArrayTrimsWhitespace()
{
var result = FailoverUrlParser.Parse("opc.tcp://primary:4840",
new[] { " opc.tcp://backup:4840 " });
result.ShouldBe(new[] { "opc.tcp://primary:4840", "opc.tcp://backup:4840" });
}
[Fact]
public void Parse_ArraySkipsNullAndEmpty()
{
var result = FailoverUrlParser.Parse("opc.tcp://primary:4840",
new[] { null!, "", "opc.tcp://backup:4840" });
result.ShouldBe(new[] { "opc.tcp://primary:4840", "opc.tcp://backup:4840" });
}
}

View File

@@ -0,0 +1,58 @@
using Opc.Ua;
using Shouldly;
using Xunit;
using ZB.MOM.WW.LmxOpcUa.Client.Shared.Helpers;
using ZB.MOM.WW.LmxOpcUa.Client.Shared.Models;
namespace ZB.MOM.WW.LmxOpcUa.Client.Shared.Tests.Helpers;
public class SecurityModeMapperTests
{
[Theory]
[InlineData(SecurityMode.None, MessageSecurityMode.None)]
[InlineData(SecurityMode.Sign, MessageSecurityMode.Sign)]
[InlineData(SecurityMode.SignAndEncrypt, MessageSecurityMode.SignAndEncrypt)]
public void ToMessageSecurityMode_MapsCorrectly(SecurityMode input, MessageSecurityMode expected)
{
SecurityModeMapper.ToMessageSecurityMode(input).ShouldBe(expected);
}
[Fact]
public void ToMessageSecurityMode_InvalidValue_Throws()
{
Should.Throw<ArgumentOutOfRangeException>(() =>
SecurityModeMapper.ToMessageSecurityMode((SecurityMode)99));
}
[Theory]
[InlineData("none", SecurityMode.None)]
[InlineData("None", SecurityMode.None)]
[InlineData("NONE", SecurityMode.None)]
[InlineData("sign", SecurityMode.Sign)]
[InlineData("Sign", SecurityMode.Sign)]
[InlineData("encrypt", SecurityMode.SignAndEncrypt)]
[InlineData("signandencrypt", SecurityMode.SignAndEncrypt)]
[InlineData("SignAndEncrypt", SecurityMode.SignAndEncrypt)]
public void FromString_ParsesCorrectly(string input, SecurityMode expected)
{
SecurityModeMapper.FromString(input).ShouldBe(expected);
}
[Fact]
public void FromString_WithWhitespace_ParsesCorrectly()
{
SecurityModeMapper.FromString(" sign ").ShouldBe(SecurityMode.Sign);
}
[Fact]
public void FromString_UnknownValue_Throws()
{
Should.Throw<ArgumentException>(() => SecurityModeMapper.FromString("invalid"));
}
[Fact]
public void FromString_Null_DefaultsToNone()
{
SecurityModeMapper.FromString(null!).ShouldBe(SecurityMode.None);
}
}

View File

@@ -0,0 +1,110 @@
using Shouldly;
using Xunit;
using ZB.MOM.WW.LmxOpcUa.Client.Shared.Helpers;
namespace ZB.MOM.WW.LmxOpcUa.Client.Shared.Tests.Helpers;
public class ValueConverterTests
{
[Fact]
public void ConvertValue_Bool_True()
{
ValueConverter.ConvertValue("True", true).ShouldBe(true);
}
[Fact]
public void ConvertValue_Bool_False()
{
ValueConverter.ConvertValue("False", false).ShouldBe(false);
}
[Fact]
public void ConvertValue_Byte()
{
ValueConverter.ConvertValue("255", (byte)0).ShouldBe((byte)255);
}
[Fact]
public void ConvertValue_Short()
{
ValueConverter.ConvertValue("-100", (short)0).ShouldBe((short)-100);
}
[Fact]
public void ConvertValue_UShort()
{
ValueConverter.ConvertValue("65535", (ushort)0).ShouldBe((ushort)65535);
}
[Fact]
public void ConvertValue_Int()
{
ValueConverter.ConvertValue("42", 0).ShouldBe(42);
}
[Fact]
public void ConvertValue_UInt()
{
ValueConverter.ConvertValue("42", 0u).ShouldBe(42u);
}
[Fact]
public void ConvertValue_Long()
{
ValueConverter.ConvertValue("9999999999", 0L).ShouldBe(9999999999L);
}
[Fact]
public void ConvertValue_ULong()
{
ValueConverter.ConvertValue("18446744073709551615", 0UL).ShouldBe(ulong.MaxValue);
}
[Fact]
public void ConvertValue_Float()
{
ValueConverter.ConvertValue("3.14", 0f).ShouldBe(3.14f);
}
[Fact]
public void ConvertValue_Double()
{
ValueConverter.ConvertValue("3.14159", 0.0).ShouldBe(3.14159);
}
[Fact]
public void ConvertValue_String_WhenCurrentIsString()
{
ValueConverter.ConvertValue("hello", "").ShouldBe("hello");
}
[Fact]
public void ConvertValue_String_WhenCurrentIsNull()
{
ValueConverter.ConvertValue("hello", null).ShouldBe("hello");
}
[Fact]
public void ConvertValue_String_WhenCurrentIsUnknownType()
{
ValueConverter.ConvertValue("hello", new object()).ShouldBe("hello");
}
[Fact]
public void ConvertValue_InvalidBool_Throws()
{
Should.Throw<FormatException>(() => ValueConverter.ConvertValue("notabool", true));
}
[Fact]
public void ConvertValue_InvalidInt_Throws()
{
Should.Throw<FormatException>(() => ValueConverter.ConvertValue("notanint", 0));
}
[Fact]
public void ConvertValue_Overflow_Throws()
{
Should.Throw<OverflowException>(() => ValueConverter.ConvertValue("256", (byte)0));
}
}

View File

@@ -0,0 +1,95 @@
using Shouldly;
using Xunit;
using ZB.MOM.WW.LmxOpcUa.Client.Shared.Models;
namespace ZB.MOM.WW.LmxOpcUa.Client.Shared.Tests.Models;
public class ConnectionSettingsTests
{
[Fact]
public void Defaults_AreCorrect()
{
var settings = new ConnectionSettings();
settings.EndpointUrl.ShouldBe(string.Empty);
settings.FailoverUrls.ShouldBeNull();
settings.Username.ShouldBeNull();
settings.Password.ShouldBeNull();
settings.SecurityMode.ShouldBe(SecurityMode.None);
settings.SessionTimeoutSeconds.ShouldBe(60);
settings.AutoAcceptCertificates.ShouldBeTrue();
settings.CertificateStorePath.ShouldContain("LmxOpcUaClient");
settings.CertificateStorePath.ShouldContain("pki");
}
[Fact]
public void Validate_ThrowsOnNullEndpointUrl()
{
var settings = new ConnectionSettings { EndpointUrl = null! };
Should.Throw<ArgumentException>(() => settings.Validate())
.ParamName.ShouldBe("EndpointUrl");
}
[Fact]
public void Validate_ThrowsOnEmptyEndpointUrl()
{
var settings = new ConnectionSettings { EndpointUrl = "" };
Should.Throw<ArgumentException>(() => settings.Validate())
.ParamName.ShouldBe("EndpointUrl");
}
[Fact]
public void Validate_ThrowsOnWhitespaceEndpointUrl()
{
var settings = new ConnectionSettings { EndpointUrl = " " };
Should.Throw<ArgumentException>(() => settings.Validate())
.ParamName.ShouldBe("EndpointUrl");
}
[Fact]
public void Validate_ThrowsOnZeroTimeout()
{
var settings = new ConnectionSettings
{
EndpointUrl = "opc.tcp://localhost:4840",
SessionTimeoutSeconds = 0
};
Should.Throw<ArgumentException>(() => settings.Validate())
.ParamName.ShouldBe("SessionTimeoutSeconds");
}
[Fact]
public void Validate_ThrowsOnNegativeTimeout()
{
var settings = new ConnectionSettings
{
EndpointUrl = "opc.tcp://localhost:4840",
SessionTimeoutSeconds = -1
};
Should.Throw<ArgumentException>(() => settings.Validate())
.ParamName.ShouldBe("SessionTimeoutSeconds");
}
[Fact]
public void Validate_ThrowsOnTimeoutAbove3600()
{
var settings = new ConnectionSettings
{
EndpointUrl = "opc.tcp://localhost:4840",
SessionTimeoutSeconds = 3601
};
Should.Throw<ArgumentException>(() => settings.Validate())
.ParamName.ShouldBe("SessionTimeoutSeconds");
}
[Fact]
public void Validate_SucceedsWithValidSettings()
{
var settings = new ConnectionSettings
{
EndpointUrl = "opc.tcp://localhost:4840",
SessionTimeoutSeconds = 120
};
Should.NotThrow(() => settings.Validate());
}
}

View File

@@ -0,0 +1,129 @@
using Opc.Ua;
using Shouldly;
using Xunit;
using ZB.MOM.WW.LmxOpcUa.Client.Shared.Models;
namespace ZB.MOM.WW.LmxOpcUa.Client.Shared.Tests.Models;
public class ModelConstructionTests
{
[Fact]
public void BrowseResult_ConstructsCorrectly()
{
var result = new ZB.MOM.WW.LmxOpcUa.Client.Shared.Models.BrowseResult("ns=2;s=MyNode", "MyNode", "Variable", true);
result.NodeId.ShouldBe("ns=2;s=MyNode");
result.DisplayName.ShouldBe("MyNode");
result.NodeClass.ShouldBe("Variable");
result.HasChildren.ShouldBeTrue();
}
[Fact]
public void BrowseResult_WithoutChildren()
{
var result = new ZB.MOM.WW.LmxOpcUa.Client.Shared.Models.BrowseResult("ns=2;s=Leaf", "Leaf", "Variable", false);
result.HasChildren.ShouldBeFalse();
}
[Fact]
public void AlarmEventArgs_ConstructsCorrectly()
{
var time = new DateTime(2026, 1, 15, 10, 30, 0, DateTimeKind.Utc);
var args = new AlarmEventArgs("Source1", "HighTemp", 500, "Temperature high", true, true, false, time);
args.SourceName.ShouldBe("Source1");
args.ConditionName.ShouldBe("HighTemp");
args.Severity.ShouldBe((ushort)500);
args.Message.ShouldBe("Temperature high");
args.Retain.ShouldBeTrue();
args.ActiveState.ShouldBeTrue();
args.AckedState.ShouldBeFalse();
args.Time.ShouldBe(time);
}
[Fact]
public void RedundancyInfo_ConstructsCorrectly()
{
var uris = new[] { "urn:server1", "urn:server2" };
var info = new RedundancyInfo("Warm", 200, uris, "urn:server1");
info.Mode.ShouldBe("Warm");
info.ServiceLevel.ShouldBe((byte)200);
info.ServerUris.ShouldBe(uris);
info.ApplicationUri.ShouldBe("urn:server1");
}
[Fact]
public void RedundancyInfo_WithEmptyUris()
{
var info = new RedundancyInfo("None", 0, Array.Empty<string>(), string.Empty);
info.ServerUris.ShouldBeEmpty();
info.ApplicationUri.ShouldBeEmpty();
}
[Fact]
public void DataChangedEventArgs_ConstructsCorrectly()
{
var value = new DataValue(new Variant(42), StatusCodes.Good);
var args = new DataChangedEventArgs("ns=2;s=Temp", value);
args.NodeId.ShouldBe("ns=2;s=Temp");
args.Value.ShouldBe(value);
args.Value.Value.ShouldBe(42);
}
[Fact]
public void ConnectionStateChangedEventArgs_ConstructsCorrectly()
{
var args = new ConnectionStateChangedEventArgs(
ConnectionState.Disconnected, ConnectionState.Connected, "opc.tcp://localhost:4840");
args.OldState.ShouldBe(ConnectionState.Disconnected);
args.NewState.ShouldBe(ConnectionState.Connected);
args.EndpointUrl.ShouldBe("opc.tcp://localhost:4840");
}
[Fact]
public void ConnectionInfo_ConstructsCorrectly()
{
var info = new ConnectionInfo(
"opc.tcp://localhost:4840",
"TestServer",
"None",
"http://opcfoundation.org/UA/SecurityPolicy#None",
"ns=0;i=12345",
"TestSession");
info.EndpointUrl.ShouldBe("opc.tcp://localhost:4840");
info.ServerName.ShouldBe("TestServer");
info.SecurityMode.ShouldBe("None");
info.SecurityPolicyUri.ShouldBe("http://opcfoundation.org/UA/SecurityPolicy#None");
info.SessionId.ShouldBe("ns=0;i=12345");
info.SessionName.ShouldBe("TestSession");
}
[Fact]
public void SecurityMode_Enum_HasExpectedValues()
{
Enum.GetValues<SecurityMode>().Length.ShouldBe(3);
((int)SecurityMode.None).ShouldBe(0);
((int)SecurityMode.Sign).ShouldBe(1);
((int)SecurityMode.SignAndEncrypt).ShouldBe(2);
}
[Fact]
public void ConnectionState_Enum_HasExpectedValues()
{
Enum.GetValues<ConnectionState>().Length.ShouldBe(4);
((int)ConnectionState.Disconnected).ShouldBe(0);
((int)ConnectionState.Connecting).ShouldBe(1);
((int)ConnectionState.Connected).ShouldBe(2);
((int)ConnectionState.Reconnecting).ShouldBe(3);
}
[Fact]
public void AggregateType_Enum_HasExpectedValues()
{
Enum.GetValues<AggregateType>().Length.ShouldBe(6);
}
}

View File

@@ -0,0 +1,816 @@
using Opc.Ua;
using Shouldly;
using Xunit;
using ZB.MOM.WW.LmxOpcUa.Client.Shared.Models;
using ZB.MOM.WW.LmxOpcUa.Client.Shared.Tests.Fakes;
namespace ZB.MOM.WW.LmxOpcUa.Client.Shared.Tests;
public class OpcUaClientServiceTests : IDisposable
{
private readonly FakeApplicationConfigurationFactory _configFactory = new();
private readonly FakeEndpointDiscovery _endpointDiscovery = new();
private readonly FakeSessionFactory _sessionFactory = new();
private readonly OpcUaClientService _service;
public OpcUaClientServiceTests()
{
_service = new OpcUaClientService(_configFactory, _endpointDiscovery, _sessionFactory);
}
public void Dispose()
{
_service.Dispose();
}
private ConnectionSettings ValidSettings(string url = "opc.tcp://localhost:4840") => new()
{
EndpointUrl = url,
SessionTimeoutSeconds = 60
};
// --- Connection tests ---
[Fact]
public async Task ConnectAsync_ValidSettings_ReturnsConnectionInfo()
{
var info = await _service.ConnectAsync(ValidSettings());
info.ShouldNotBeNull();
info.EndpointUrl.ShouldBe("opc.tcp://localhost:4840");
_service.IsConnected.ShouldBeTrue();
_service.CurrentConnectionInfo.ShouldBe(info);
}
[Fact]
public async Task ConnectAsync_InvalidSettings_ThrowsBeforeCreatingSession()
{
var settings = new ConnectionSettings { EndpointUrl = "" };
await Should.ThrowAsync<ArgumentException>(() => _service.ConnectAsync(settings));
_sessionFactory.CreateCallCount.ShouldBe(0);
_service.IsConnected.ShouldBeFalse();
}
[Fact]
public async Task ConnectAsync_PopulatesConnectionInfo()
{
var session = new FakeSessionAdapter
{
ServerName = "MyServer",
SecurityMode = "Sign",
SecurityPolicyUri = "http://opcfoundation.org/UA/SecurityPolicy#Basic256Sha256",
SessionId = "ns=0;i=999",
SessionName = "TestSession"
};
_sessionFactory.EnqueueSession(session);
var info = await _service.ConnectAsync(ValidSettings());
info.ServerName.ShouldBe("MyServer");
info.SecurityMode.ShouldBe("Sign");
info.SecurityPolicyUri.ShouldBe("http://opcfoundation.org/UA/SecurityPolicy#Basic256Sha256");
info.SessionId.ShouldBe("ns=0;i=999");
info.SessionName.ShouldBe("TestSession");
}
[Fact]
public async Task ConnectAsync_RaisesConnectionStateChangedEvents()
{
var events = new List<ConnectionStateChangedEventArgs>();
_service.ConnectionStateChanged += (_, e) => events.Add(e);
await _service.ConnectAsync(ValidSettings());
events.Count.ShouldBe(2);
events[0].OldState.ShouldBe(ConnectionState.Disconnected);
events[0].NewState.ShouldBe(ConnectionState.Connecting);
events[1].OldState.ShouldBe(ConnectionState.Connecting);
events[1].NewState.ShouldBe(ConnectionState.Connected);
}
[Fact]
public async Task ConnectAsync_SessionFactoryFails_TransitionsToDisconnected()
{
_sessionFactory.ThrowOnCreate = true;
var events = new List<ConnectionStateChangedEventArgs>();
_service.ConnectionStateChanged += (_, e) => events.Add(e);
await Should.ThrowAsync<InvalidOperationException>(() => _service.ConnectAsync(ValidSettings()));
_service.IsConnected.ShouldBeFalse();
events.Last().NewState.ShouldBe(ConnectionState.Disconnected);
}
[Fact]
public async Task ConnectAsync_WithUsername_PassesThroughToFactory()
{
var settings = ValidSettings();
settings.Username = "admin";
settings.Password = "secret";
await _service.ConnectAsync(settings);
_configFactory.LastSettings!.Username.ShouldBe("admin");
_configFactory.LastSettings!.Password.ShouldBe("secret");
}
// --- Disconnect tests ---
[Fact]
public async Task DisconnectAsync_WhenConnected_ClosesSession()
{
await _service.ConnectAsync(ValidSettings());
var session = _sessionFactory.CreatedSessions[0];
await _service.DisconnectAsync();
session.Closed.ShouldBeTrue();
_service.IsConnected.ShouldBeFalse();
_service.CurrentConnectionInfo.ShouldBeNull();
}
[Fact]
public async Task DisconnectAsync_WhenNotConnected_IsIdempotent()
{
await _service.DisconnectAsync(); // Should not throw
_service.IsConnected.ShouldBeFalse();
}
[Fact]
public async Task DisconnectAsync_CalledTwice_IsIdempotent()
{
await _service.ConnectAsync(ValidSettings());
await _service.DisconnectAsync();
await _service.DisconnectAsync(); // Should not throw
}
// --- Read tests ---
[Fact]
public async Task ReadValueAsync_WhenConnected_ReturnsValue()
{
var session = new FakeSessionAdapter
{
ReadResponse = new DataValue(new Variant(42), StatusCodes.Good)
};
_sessionFactory.EnqueueSession(session);
await _service.ConnectAsync(ValidSettings());
var result = await _service.ReadValueAsync(new NodeId("ns=2;s=MyNode"));
result.Value.ShouldBe(42);
session.ReadCount.ShouldBe(1);
}
[Fact]
public async Task ReadValueAsync_WhenDisconnected_Throws()
{
await Should.ThrowAsync<InvalidOperationException>(() =>
_service.ReadValueAsync(new NodeId("ns=2;s=MyNode")));
}
[Fact]
public async Task ReadValueAsync_SessionThrows_PropagatesException()
{
var session = new FakeSessionAdapter { ThrowOnRead = true };
_sessionFactory.EnqueueSession(session);
await _service.ConnectAsync(ValidSettings());
await Should.ThrowAsync<ServiceResultException>(() =>
_service.ReadValueAsync(new NodeId("ns=2;s=MyNode")));
}
// --- Write tests ---
[Fact]
public async Task WriteValueAsync_WhenConnected_WritesValue()
{
var session = new FakeSessionAdapter
{
ReadResponse = new DataValue(new Variant(0), StatusCodes.Good),
WriteResponse = StatusCodes.Good
};
_sessionFactory.EnqueueSession(session);
await _service.ConnectAsync(ValidSettings());
var result = await _service.WriteValueAsync(new NodeId("ns=2;s=MyNode"), 42);
result.ShouldBe(StatusCodes.Good);
session.WriteCount.ShouldBe(1);
}
[Fact]
public async Task WriteValueAsync_StringValue_CoercesToTargetType()
{
var session = new FakeSessionAdapter
{
ReadResponse = new DataValue(new Variant(0), StatusCodes.Good) // int type
};
_sessionFactory.EnqueueSession(session);
await _service.ConnectAsync(ValidSettings());
await _service.WriteValueAsync(new NodeId("ns=2;s=MyNode"), "42");
session.WriteCount.ShouldBe(1);
session.ReadCount.ShouldBe(1); // Read for type inference
}
[Fact]
public async Task WriteValueAsync_NonStringValue_WritesDirectly()
{
var session = new FakeSessionAdapter();
_sessionFactory.EnqueueSession(session);
await _service.ConnectAsync(ValidSettings());
await _service.WriteValueAsync(new NodeId("ns=2;s=MyNode"), 42);
session.WriteCount.ShouldBe(1);
session.ReadCount.ShouldBe(0); // No read for non-string values
}
[Fact]
public async Task WriteValueAsync_WhenDisconnected_Throws()
{
await Should.ThrowAsync<InvalidOperationException>(() =>
_service.WriteValueAsync(new NodeId("ns=2;s=MyNode"), 42));
}
// --- Browse tests ---
[Fact]
public async Task BrowseAsync_WhenConnected_ReturnsMappedResults()
{
var session = new FakeSessionAdapter
{
BrowseResponse = new ReferenceDescriptionCollection
{
new ReferenceDescription
{
NodeId = new ExpandedNodeId("ns=2;s=Child1"),
DisplayName = new LocalizedText("Child1"),
NodeClass = NodeClass.Variable
}
}
};
_sessionFactory.EnqueueSession(session);
await _service.ConnectAsync(ValidSettings());
var results = await _service.BrowseAsync();
results.Count.ShouldBe(1);
results[0].DisplayName.ShouldBe("Child1");
results[0].NodeClass.ShouldBe("Variable");
results[0].HasChildren.ShouldBeFalse(); // Variable nodes don't check HasChildren
}
[Fact]
public async Task BrowseAsync_NullParent_UsesObjectsFolder()
{
var session = new FakeSessionAdapter
{
BrowseResponse = new ReferenceDescriptionCollection()
};
_sessionFactory.EnqueueSession(session);
await _service.ConnectAsync(ValidSettings());
await _service.BrowseAsync(null);
session.BrowseCount.ShouldBe(1);
}
[Fact]
public async Task BrowseAsync_ObjectNode_ChecksHasChildren()
{
var session = new FakeSessionAdapter
{
BrowseResponse = new ReferenceDescriptionCollection
{
new ReferenceDescription
{
NodeId = new ExpandedNodeId("ns=2;s=Folder1"),
DisplayName = new LocalizedText("Folder1"),
NodeClass = NodeClass.Object
}
},
HasChildrenResponse = true
};
_sessionFactory.EnqueueSession(session);
await _service.ConnectAsync(ValidSettings());
var results = await _service.BrowseAsync();
results[0].HasChildren.ShouldBeTrue();
session.HasChildrenCount.ShouldBe(1);
}
[Fact]
public async Task BrowseAsync_WithContinuationPoint_FollowsIt()
{
var session = new FakeSessionAdapter
{
BrowseResponse = new ReferenceDescriptionCollection
{
new ReferenceDescription
{
NodeId = new ExpandedNodeId("ns=2;s=A"),
DisplayName = new LocalizedText("A"),
NodeClass = NodeClass.Variable
}
},
BrowseContinuationPoint = new byte[] { 1, 2, 3 },
BrowseNextResponse = new ReferenceDescriptionCollection
{
new ReferenceDescription
{
NodeId = new ExpandedNodeId("ns=2;s=B"),
DisplayName = new LocalizedText("B"),
NodeClass = NodeClass.Variable
}
},
BrowseNextContinuationPoint = null
};
_sessionFactory.EnqueueSession(session);
await _service.ConnectAsync(ValidSettings());
var results = await _service.BrowseAsync();
results.Count.ShouldBe(2);
session.BrowseNextCount.ShouldBe(1);
}
[Fact]
public async Task BrowseAsync_WhenDisconnected_Throws()
{
await Should.ThrowAsync<InvalidOperationException>(() => _service.BrowseAsync());
}
// --- Subscribe tests ---
[Fact]
public async Task SubscribeAsync_CreatesSubscription()
{
var session = new FakeSessionAdapter();
_sessionFactory.EnqueueSession(session);
await _service.ConnectAsync(ValidSettings());
await _service.SubscribeAsync(new NodeId("ns=2;s=MyNode"), 500);
session.CreatedSubscriptions.Count.ShouldBe(1);
session.CreatedSubscriptions[0].AddDataChangeCount.ShouldBe(1);
}
[Fact]
public async Task SubscribeAsync_DuplicateNode_IsIdempotent()
{
var session = new FakeSessionAdapter();
_sessionFactory.EnqueueSession(session);
await _service.ConnectAsync(ValidSettings());
await _service.SubscribeAsync(new NodeId("ns=2;s=MyNode"));
await _service.SubscribeAsync(new NodeId("ns=2;s=MyNode")); // duplicate
session.CreatedSubscriptions[0].AddDataChangeCount.ShouldBe(1);
}
[Fact]
public async Task SubscribeAsync_RaisesDataChangedEvent()
{
var fakeSub = new FakeSubscriptionAdapter();
var session = new FakeSessionAdapter { NextSubscription = fakeSub };
_sessionFactory.EnqueueSession(session);
await _service.ConnectAsync(ValidSettings());
DataChangedEventArgs? received = null;
_service.DataChanged += (_, e) => received = e;
await _service.SubscribeAsync(new NodeId("ns=2;s=MyNode"), 500);
// Simulate data change
var handle = fakeSub.ActiveHandles.First();
fakeSub.SimulateDataChange(handle, new DataValue(new Variant(99), StatusCodes.Good));
received.ShouldNotBeNull();
received!.NodeId.ShouldBe("ns=2;s=MyNode");
received.Value.Value.ShouldBe(99);
}
[Fact]
public async Task UnsubscribeAsync_RemovesMonitoredItem()
{
var fakeSub = new FakeSubscriptionAdapter();
var session = new FakeSessionAdapter { NextSubscription = fakeSub };
_sessionFactory.EnqueueSession(session);
await _service.ConnectAsync(ValidSettings());
await _service.SubscribeAsync(new NodeId("ns=2;s=MyNode"));
await _service.UnsubscribeAsync(new NodeId("ns=2;s=MyNode"));
fakeSub.RemoveCount.ShouldBe(1);
}
[Fact]
public async Task UnsubscribeAsync_WhenNotSubscribed_DoesNotThrow()
{
var session = new FakeSessionAdapter();
_sessionFactory.EnqueueSession(session);
await _service.ConnectAsync(ValidSettings());
await _service.UnsubscribeAsync(new NodeId("ns=2;s=NotSubscribed"));
// Should not throw
}
[Fact]
public async Task SubscribeAsync_WhenDisconnected_Throws()
{
await Should.ThrowAsync<InvalidOperationException>(() =>
_service.SubscribeAsync(new NodeId("ns=2;s=MyNode")));
}
// --- Alarm subscription tests ---
[Fact]
public async Task SubscribeAlarmsAsync_CreatesEventSubscription()
{
var session = new FakeSessionAdapter();
_sessionFactory.EnqueueSession(session);
await _service.ConnectAsync(ValidSettings());
await _service.SubscribeAlarmsAsync(null, 1000);
session.CreatedSubscriptions.Count.ShouldBe(1);
session.CreatedSubscriptions[0].AddEventCount.ShouldBe(1);
}
[Fact]
public async Task SubscribeAlarmsAsync_Duplicate_IsIdempotent()
{
var session = new FakeSessionAdapter();
_sessionFactory.EnqueueSession(session);
await _service.ConnectAsync(ValidSettings());
await _service.SubscribeAlarmsAsync();
await _service.SubscribeAlarmsAsync(); // duplicate
session.CreatedSubscriptions.Count.ShouldBe(1);
}
[Fact]
public async Task SubscribeAlarmsAsync_RaisesAlarmEvent()
{
var fakeSub = new FakeSubscriptionAdapter();
var session = new FakeSessionAdapter { NextSubscription = fakeSub };
_sessionFactory.EnqueueSession(session);
await _service.ConnectAsync(ValidSettings());
AlarmEventArgs? received = null;
_service.AlarmEvent += (_, e) => received = e;
await _service.SubscribeAlarmsAsync();
// Simulate alarm event with proper field count
var handle = fakeSub.ActiveHandles.First();
var fields = new EventFieldList
{
EventFields = new VariantCollection
{
new Variant(new byte[] { 1, 2, 3 }), // 0: EventId
new Variant(ObjectTypeIds.AlarmConditionType), // 1: EventType
new Variant("Source1"), // 2: SourceName
new Variant(DateTime.UtcNow), // 3: Time
new Variant(new LocalizedText("High temp")), // 4: Message
new Variant((ushort)500), // 5: Severity
new Variant("HighTemp"), // 6: ConditionName
new Variant(true), // 7: Retain
new Variant(false), // 8: AckedState
new Variant(true), // 9: ActiveState
new Variant(true), // 10: EnabledState
new Variant(false) // 11: SuppressedOrShelved
}
};
fakeSub.SimulateEvent(handle, fields);
received.ShouldNotBeNull();
received!.SourceName.ShouldBe("Source1");
received.ConditionName.ShouldBe("HighTemp");
received.Severity.ShouldBe((ushort)500);
received.Message.ShouldBe("High temp");
received.Retain.ShouldBeTrue();
received.ActiveState.ShouldBeTrue();
received.AckedState.ShouldBeFalse();
}
[Fact]
public async Task UnsubscribeAlarmsAsync_DeletesSubscription()
{
var fakeSub = new FakeSubscriptionAdapter();
var session = new FakeSessionAdapter { NextSubscription = fakeSub };
_sessionFactory.EnqueueSession(session);
await _service.ConnectAsync(ValidSettings());
await _service.SubscribeAlarmsAsync();
await _service.UnsubscribeAlarmsAsync();
fakeSub.Deleted.ShouldBeTrue();
}
[Fact]
public async Task UnsubscribeAlarmsAsync_WhenNoSubscription_DoesNotThrow()
{
var session = new FakeSessionAdapter();
_sessionFactory.EnqueueSession(session);
await _service.ConnectAsync(ValidSettings());
await _service.UnsubscribeAlarmsAsync(); // Should not throw
}
[Fact]
public async Task RequestConditionRefreshAsync_CallsAdapter()
{
var fakeSub = new FakeSubscriptionAdapter();
var session = new FakeSessionAdapter { NextSubscription = fakeSub };
_sessionFactory.EnqueueSession(session);
await _service.ConnectAsync(ValidSettings());
await _service.SubscribeAlarmsAsync();
await _service.RequestConditionRefreshAsync();
fakeSub.ConditionRefreshCalled.ShouldBeTrue();
}
[Fact]
public async Task RequestConditionRefreshAsync_NoAlarmSubscription_Throws()
{
var session = new FakeSessionAdapter();
_sessionFactory.EnqueueSession(session);
await _service.ConnectAsync(ValidSettings());
await Should.ThrowAsync<InvalidOperationException>(() =>
_service.RequestConditionRefreshAsync());
}
[Fact]
public async Task SubscribeAlarmsAsync_WhenDisconnected_Throws()
{
await Should.ThrowAsync<InvalidOperationException>(() =>
_service.SubscribeAlarmsAsync());
}
// --- History read tests ---
[Fact]
public async Task HistoryReadRawAsync_ReturnsValues()
{
var expectedValues = new List<DataValue>
{
new DataValue(new Variant(1.0), StatusCodes.Good),
new DataValue(new Variant(2.0), StatusCodes.Good)
};
var session = new FakeSessionAdapter { HistoryReadRawResponse = expectedValues };
_sessionFactory.EnqueueSession(session);
await _service.ConnectAsync(ValidSettings());
var results = await _service.HistoryReadRawAsync(
new NodeId("ns=2;s=Temp"), DateTime.UtcNow.AddHours(-1), DateTime.UtcNow);
results.Count.ShouldBe(2);
session.HistoryReadRawCount.ShouldBe(1);
}
[Fact]
public async Task HistoryReadRawAsync_WhenDisconnected_Throws()
{
await Should.ThrowAsync<InvalidOperationException>(() =>
_service.HistoryReadRawAsync(new NodeId("ns=2;s=Temp"), DateTime.UtcNow.AddHours(-1), DateTime.UtcNow));
}
[Fact]
public async Task HistoryReadRawAsync_SessionThrows_PropagatesException()
{
var session = new FakeSessionAdapter { ThrowOnHistoryReadRaw = true };
_sessionFactory.EnqueueSession(session);
await _service.ConnectAsync(ValidSettings());
await Should.ThrowAsync<ServiceResultException>(() =>
_service.HistoryReadRawAsync(new NodeId("ns=2;s=Temp"), DateTime.UtcNow.AddHours(-1), DateTime.UtcNow));
}
[Fact]
public async Task HistoryReadAggregateAsync_ReturnsValues()
{
var expectedValues = new List<DataValue>
{
new DataValue(new Variant(1.5), StatusCodes.Good)
};
var session = new FakeSessionAdapter { HistoryReadAggregateResponse = expectedValues };
_sessionFactory.EnqueueSession(session);
await _service.ConnectAsync(ValidSettings());
var results = await _service.HistoryReadAggregateAsync(
new NodeId("ns=2;s=Temp"), DateTime.UtcNow.AddHours(-1), DateTime.UtcNow,
AggregateType.Average);
results.Count.ShouldBe(1);
session.HistoryReadAggregateCount.ShouldBe(1);
}
[Fact]
public async Task HistoryReadAggregateAsync_WhenDisconnected_Throws()
{
await Should.ThrowAsync<InvalidOperationException>(() =>
_service.HistoryReadAggregateAsync(
new NodeId("ns=2;s=Temp"), DateTime.UtcNow.AddHours(-1), DateTime.UtcNow,
AggregateType.Average));
}
[Fact]
public async Task HistoryReadAggregateAsync_SessionThrows_PropagatesException()
{
var session = new FakeSessionAdapter { ThrowOnHistoryReadAggregate = true };
_sessionFactory.EnqueueSession(session);
await _service.ConnectAsync(ValidSettings());
await Should.ThrowAsync<ServiceResultException>(() =>
_service.HistoryReadAggregateAsync(
new NodeId("ns=2;s=Temp"), DateTime.UtcNow.AddHours(-1), DateTime.UtcNow,
AggregateType.Average));
}
// --- Redundancy tests ---
[Fact]
public async Task GetRedundancyInfoAsync_ReturnsInfo()
{
var session = new FakeSessionAdapter
{
ReadResponseFunc = nodeId =>
{
if (nodeId == VariableIds.Server_ServerRedundancy_RedundancySupport)
return new DataValue(new Variant((int)RedundancySupport.Warm), StatusCodes.Good);
if (nodeId == VariableIds.Server_ServiceLevel)
return new DataValue(new Variant((byte)200), StatusCodes.Good);
if (nodeId == VariableIds.Server_ServerRedundancy_ServerUriArray)
return new DataValue(new Variant(new[] { "urn:server1", "urn:server2" }), StatusCodes.Good);
if (nodeId == VariableIds.Server_ServerArray)
return new DataValue(new Variant(new[] { "urn:server1" }), StatusCodes.Good);
return new DataValue(StatusCodes.BadNodeIdUnknown);
}
};
_sessionFactory.EnqueueSession(session);
await _service.ConnectAsync(ValidSettings());
var info = await _service.GetRedundancyInfoAsync();
info.Mode.ShouldBe("Warm");
info.ServiceLevel.ShouldBe((byte)200);
info.ServerUris.ShouldBe(new[] { "urn:server1", "urn:server2" });
info.ApplicationUri.ShouldBe("urn:server1");
}
[Fact]
public async Task GetRedundancyInfoAsync_MissingOptionalArrays_ReturnsGracefully()
{
int readCallIndex = 0;
var session = new FakeSessionAdapter
{
ReadResponseFunc = nodeId =>
{
if (nodeId == VariableIds.Server_ServerRedundancy_RedundancySupport)
return new DataValue(new Variant((int)RedundancySupport.None), StatusCodes.Good);
if (nodeId == VariableIds.Server_ServiceLevel)
return new DataValue(new Variant((byte)100), StatusCodes.Good);
// Throw for optional reads
throw new ServiceResultException(StatusCodes.BadNodeIdUnknown);
}
};
_sessionFactory.EnqueueSession(session);
await _service.ConnectAsync(ValidSettings());
var info = await _service.GetRedundancyInfoAsync();
info.Mode.ShouldBe("None");
info.ServiceLevel.ShouldBe((byte)100);
info.ServerUris.ShouldBeEmpty();
info.ApplicationUri.ShouldBeEmpty();
}
[Fact]
public async Task GetRedundancyInfoAsync_WhenDisconnected_Throws()
{
await Should.ThrowAsync<InvalidOperationException>(() =>
_service.GetRedundancyInfoAsync());
}
// --- Failover tests ---
[Fact]
public async Task KeepAliveFailure_TriggersFailover()
{
var session1 = new FakeSessionAdapter { EndpointUrl = "opc.tcp://primary:4840" };
var session2 = new FakeSessionAdapter { EndpointUrl = "opc.tcp://backup:4840" };
_sessionFactory.EnqueueSession(session1);
_sessionFactory.EnqueueSession(session2);
var settings = ValidSettings("opc.tcp://primary:4840");
settings.FailoverUrls = new[] { "opc.tcp://backup:4840" };
var stateChanges = new List<ConnectionStateChangedEventArgs>();
_service.ConnectionStateChanged += (_, e) => stateChanges.Add(e);
await _service.ConnectAsync(settings);
// Simulate keep-alive failure
session1.SimulateKeepAlive(false);
// Give async failover time to complete
await Task.Delay(200);
// Should have reconnected
stateChanges.ShouldContain(e => e.NewState == ConnectionState.Reconnecting);
stateChanges.ShouldContain(e => e.NewState == ConnectionState.Connected &&
e.EndpointUrl == "opc.tcp://backup:4840");
}
[Fact]
public async Task KeepAliveFailure_UpdatesConnectionInfo()
{
var session1 = new FakeSessionAdapter { EndpointUrl = "opc.tcp://primary:4840" };
var session2 = new FakeSessionAdapter
{
EndpointUrl = "opc.tcp://backup:4840",
ServerName = "BackupServer"
};
_sessionFactory.EnqueueSession(session1);
_sessionFactory.EnqueueSession(session2);
var settings = ValidSettings("opc.tcp://primary:4840");
settings.FailoverUrls = new[] { "opc.tcp://backup:4840" };
await _service.ConnectAsync(settings);
session1.SimulateKeepAlive(false);
await Task.Delay(200);
_service.CurrentConnectionInfo!.EndpointUrl.ShouldBe("opc.tcp://backup:4840");
_service.CurrentConnectionInfo.ServerName.ShouldBe("BackupServer");
}
[Fact]
public async Task KeepAliveFailure_AllEndpointsFail_TransitionsToDisconnected()
{
var session1 = new FakeSessionAdapter();
_sessionFactory.EnqueueSession(session1);
await _service.ConnectAsync(ValidSettings());
// After the first session, make factory fail
_sessionFactory.ThrowOnCreate = true;
session1.SimulateKeepAlive(false);
await Task.Delay(200);
_service.IsConnected.ShouldBeFalse();
}
// --- Dispose tests ---
[Fact]
public async Task Dispose_CleansUpResources()
{
var session = new FakeSessionAdapter();
_sessionFactory.EnqueueSession(session);
await _service.ConnectAsync(ValidSettings());
_service.Dispose();
session.Disposed.ShouldBeTrue();
_service.CurrentConnectionInfo.ShouldBeNull();
}
[Fact]
public void Dispose_WhenNotConnected_DoesNotThrow()
{
_service.Dispose(); // Should not throw
}
[Fact]
public async Task OperationsAfterDispose_Throw()
{
_service.Dispose();
await Should.ThrowAsync<ObjectDisposedException>(() =>
_service.ConnectAsync(ValidSettings()));
await Should.ThrowAsync<ObjectDisposedException>(() =>
_service.ReadValueAsync(new NodeId("ns=2;s=X")));
}
// --- Factory tests ---
[Fact]
public void OpcUaClientServiceFactory_CreatesService()
{
var factory = new OpcUaClientServiceFactory();
var service = factory.Create();
service.ShouldNotBeNull();
service.ShouldBeAssignableTo<IOpcUaClientService>();
service.Dispose();
}
}

View File

@@ -0,0 +1,26 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<IsPackable>false</IsPackable>
<IsTestProject>true</IsTestProject>
<RootNamespace>ZB.MOM.WW.LmxOpcUa.Client.Shared.Tests</RootNamespace>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="xunit.v3" Version="1.1.0" />
<PackageReference Include="Shouldly" Version="4.3.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.12.0" />
<PackageReference Include="xunit.runner.visualstudio" Version="3.0.2">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\ZB.MOM.WW.LmxOpcUa.Client.Shared\ZB.MOM.WW.LmxOpcUa.Client.Shared.csproj" />
</ItemGroup>
</Project>

Some files were not shown because too many files have changed in this diff Show More