Phase 0 — mechanical rename ZB.MOM.WW.LmxOpcUa.* → ZB.MOM.WW.OtOpcUa.*
Renames all 11 projects (5 src + 6 tests), the .slnx solution file, all source-file namespaces, all axaml namespace references, and all v1 documentation references in CLAUDE.md and docs/*.md (excluding docs/v2/ which is already in OtOpcUa form). Also updates the TopShelf service registration name from "LmxOpcUa" to "OtOpcUa" per Phase 0 Task 0.6.
Preserves runtime identifiers per Phase 0 Out-of-Scope rules to avoid breaking v1/v2 client trust during coexistence: OPC UA `ApplicationUri` defaults (`urn:{GalaxyName}:LmxOpcUa`), server `EndpointPath` (`/LmxOpcUa`), `ServerName` default (feeds cert subject CN), `MxAccessConfiguration.ClientName` default (defensive — stays "LmxOpcUa" for MxAccess audit-trail consistency), client OPC UA identifiers (`ApplicationName = "LmxOpcUaClient"`, `ApplicationUri = "urn:localhost:LmxOpcUaClient"`, cert directory `%LocalAppData%\LmxOpcUaClient\pki\`), and the `LmxOpcUaServer` class name (class rename out of Phase 0 scope per Task 0.5 sed pattern; happens in Phase 1 alongside `LmxNodeManager → GenericDriverNodeManager` Core extraction). 23 LmxOpcUa references retained, all enumerated and justified in `docs/v2/implementation/exit-gate-phase-0.md`.
Build clean: 0 errors, 30 warnings (lower than baseline 167). Tests at strict improvement over baseline: 821 passing / 1 failing vs baseline 820 / 2 (one flaky pre-existing failure passed this run; the other still fails — both pre-existing and unrelated to the rename). `Client.UI.Tests`, `Historian.Aveva.Tests`, `Client.Shared.Tests`, `IntegrationTests` all match baseline exactly. Exit gate compliance results recorded in `docs/v2/implementation/exit-gate-phase-0.md` with all 7 checks PASS or DEFERRED-to-PR-review (#7 service install verification needs Windows service permissions on the reviewer's box).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,99 @@
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Client.UI.ViewModels;
|
||||
|
||||
/// <summary>
|
||||
/// Represents a single alarm event row.
|
||||
/// </summary>
|
||||
public class AlarmEventViewModel : ObservableObject
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates an alarm row model from an OPC UA condition event so the alarms tab can display and acknowledge it.
|
||||
/// </summary>
|
||||
/// <param name="sourceName">The source object or variable name associated with the alarm.</param>
|
||||
/// <param name="conditionName">The OPC UA condition name reported by the server.</param>
|
||||
/// <param name="severity">The alarm severity value presented to the operator.</param>
|
||||
/// <param name="message">The alarm message text shown in the UI.</param>
|
||||
/// <param name="retain">Indicates whether the server is retaining the alarm condition.</param>
|
||||
/// <param name="activeState">Indicates whether the alarm is currently active.</param>
|
||||
/// <param name="ackedState">Indicates whether the alarm has already been acknowledged.</param>
|
||||
/// <param name="time">The event timestamp associated with the alarm state.</param>
|
||||
/// <param name="eventId">The OPC UA event identifier used for acknowledgment calls.</param>
|
||||
/// <param name="conditionNodeId">The condition node identifier used when acknowledging the alarm.</param>
|
||||
public AlarmEventViewModel(
|
||||
string sourceName,
|
||||
string conditionName,
|
||||
ushort severity,
|
||||
string message,
|
||||
bool retain,
|
||||
bool activeState,
|
||||
bool ackedState,
|
||||
DateTime time,
|
||||
byte[]? eventId = null,
|
||||
string? conditionNodeId = null)
|
||||
{
|
||||
SourceName = sourceName;
|
||||
ConditionName = conditionName;
|
||||
Severity = severity;
|
||||
Message = message;
|
||||
Retain = retain;
|
||||
ActiveState = activeState;
|
||||
AckedState = ackedState;
|
||||
Time = time;
|
||||
EventId = eventId;
|
||||
ConditionNodeId = conditionNodeId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the source object or variable name associated with the alarm.
|
||||
/// </summary>
|
||||
public string SourceName { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the OPC UA condition name reported for the alarm event.
|
||||
/// </summary>
|
||||
public string ConditionName { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the severity value shown to the operator.
|
||||
/// </summary>
|
||||
public ushort Severity { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the alarm message text shown in the UI.
|
||||
/// </summary>
|
||||
public string Message { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets a value indicating whether the server is retaining the condition.
|
||||
/// </summary>
|
||||
public bool Retain { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets a value indicating whether the alarm is currently active.
|
||||
/// </summary>
|
||||
public bool ActiveState { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets a value indicating whether the alarm has already been acknowledged.
|
||||
/// </summary>
|
||||
public bool AckedState { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the event timestamp displayed for the alarm row.
|
||||
/// </summary>
|
||||
public DateTime Time { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the OPC UA event identifier needed to acknowledge the alarm.
|
||||
/// </summary>
|
||||
public byte[]? EventId { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the condition node identifier used for acknowledgment method calls.
|
||||
/// </summary>
|
||||
public string? ConditionNodeId { get; }
|
||||
|
||||
/// <summary>Whether this alarm can be acknowledged (active, not yet acked, has EventId).</summary>
|
||||
public bool CanAcknowledge => ActiveState && !AckedState && EventId != null && ConditionNodeId != null;
|
||||
}
|
||||
225
src/ZB.MOM.WW.OtOpcUa.Client.UI/ViewModels/AlarmsViewModel.cs
Normal file
225
src/ZB.MOM.WW.OtOpcUa.Client.UI/ViewModels/AlarmsViewModel.cs
Normal file
@@ -0,0 +1,225 @@
|
||||
using System.Collections.ObjectModel;
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using CommunityToolkit.Mvvm.Input;
|
||||
using Opc.Ua;
|
||||
using ZB.MOM.WW.OtOpcUa.Client.Shared;
|
||||
using ZB.MOM.WW.OtOpcUa.Client.Shared.Models;
|
||||
using ZB.MOM.WW.OtOpcUa.Client.UI.Services;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Client.UI.ViewModels;
|
||||
|
||||
/// <summary>
|
||||
/// ViewModel for the alarms panel.
|
||||
/// </summary>
|
||||
public partial class AlarmsViewModel : ObservableObject
|
||||
{
|
||||
private readonly IUiDispatcher _dispatcher;
|
||||
private readonly IOpcUaClientService _service;
|
||||
|
||||
[ObservableProperty] private int _interval = 1000;
|
||||
|
||||
[ObservableProperty]
|
||||
[NotifyCanExecuteChangedFor(nameof(SubscribeCommand))]
|
||||
[NotifyCanExecuteChangedFor(nameof(UnsubscribeCommand))]
|
||||
[NotifyCanExecuteChangedFor(nameof(RefreshCommand))]
|
||||
private bool _isConnected;
|
||||
|
||||
[ObservableProperty]
|
||||
[NotifyCanExecuteChangedFor(nameof(SubscribeCommand))]
|
||||
[NotifyCanExecuteChangedFor(nameof(UnsubscribeCommand))]
|
||||
[NotifyCanExecuteChangedFor(nameof(RefreshCommand))]
|
||||
private bool _isSubscribed;
|
||||
|
||||
[ObservableProperty] private string? _monitoredNodeIdText;
|
||||
|
||||
[ObservableProperty] private int _activeAlarmCount;
|
||||
|
||||
public AlarmsViewModel(IOpcUaClientService service, IUiDispatcher dispatcher)
|
||||
{
|
||||
_service = service;
|
||||
_dispatcher = dispatcher;
|
||||
_service.AlarmEvent += OnAlarmEvent;
|
||||
}
|
||||
|
||||
/// <summary>Received alarm events.</summary>
|
||||
public ObservableCollection<AlarmEventViewModel> AlarmEvents { get; } = [];
|
||||
|
||||
private void OnAlarmEvent(object? sender, AlarmEventArgs e)
|
||||
{
|
||||
// Only display alarm/condition events (those with a ConditionName), not generic events
|
||||
if (string.IsNullOrEmpty(e.ConditionName)) return;
|
||||
|
||||
_dispatcher.Post(() =>
|
||||
{
|
||||
// Find existing row by source + condition and update it, or add new
|
||||
var existing = AlarmEvents.FirstOrDefault(a =>
|
||||
a.SourceName == e.SourceName && a.ConditionName == e.ConditionName);
|
||||
|
||||
if (existing != null)
|
||||
{
|
||||
var index = AlarmEvents.IndexOf(existing);
|
||||
AlarmEvents[index] = new AlarmEventViewModel(
|
||||
e.SourceName, e.ConditionName, e.Severity, e.Message,
|
||||
e.Retain, e.ActiveState, e.AckedState, e.Time,
|
||||
e.EventId, e.ConditionNodeId);
|
||||
|
||||
// Remove alarms that are no longer retained
|
||||
if (!e.Retain)
|
||||
AlarmEvents.RemoveAt(index);
|
||||
}
|
||||
else if (e.Retain)
|
||||
{
|
||||
AlarmEvents.Add(new AlarmEventViewModel(
|
||||
e.SourceName, e.ConditionName, e.Severity, e.Message,
|
||||
e.Retain, e.ActiveState, e.AckedState, e.Time,
|
||||
e.EventId, e.ConditionNodeId));
|
||||
}
|
||||
|
||||
ActiveAlarmCount = AlarmEvents.Count(a => a.ActiveState && !a.AckedState);
|
||||
});
|
||||
}
|
||||
|
||||
private bool CanSubscribe()
|
||||
{
|
||||
return IsConnected && !IsSubscribed;
|
||||
}
|
||||
|
||||
[RelayCommand(CanExecute = nameof(CanSubscribe))]
|
||||
private async Task SubscribeAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
var sourceNodeId = string.IsNullOrWhiteSpace(MonitoredNodeIdText)
|
||||
? null
|
||||
: NodeId.Parse(MonitoredNodeIdText);
|
||||
|
||||
await _service.SubscribeAlarmsAsync(sourceNodeId, Interval);
|
||||
IsSubscribed = true;
|
||||
|
||||
try
|
||||
{
|
||||
await _service.RequestConditionRefreshAsync();
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Refresh not supported
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Subscribe failed
|
||||
}
|
||||
}
|
||||
|
||||
private bool CanUnsubscribe()
|
||||
{
|
||||
return IsConnected && IsSubscribed;
|
||||
}
|
||||
|
||||
[RelayCommand(CanExecute = nameof(CanUnsubscribe))]
|
||||
private async Task UnsubscribeAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
await _service.UnsubscribeAlarmsAsync();
|
||||
IsSubscribed = false;
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Unsubscribe failed
|
||||
}
|
||||
}
|
||||
|
||||
[RelayCommand(CanExecute = nameof(CanUnsubscribe))]
|
||||
private async Task RefreshAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
await _service.RequestConditionRefreshAsync();
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Refresh failed
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Acknowledges an alarm and returns (success, message).
|
||||
/// </summary>
|
||||
public async Task<(bool Success, string Message)> AcknowledgeAlarmAsync(AlarmEventViewModel alarm, string comment)
|
||||
{
|
||||
if (!IsConnected || alarm.EventId == null || alarm.ConditionNodeId == null)
|
||||
return (false, "Alarm cannot be acknowledged (missing EventId or ConditionId).");
|
||||
|
||||
try
|
||||
{
|
||||
var result = await _service.AcknowledgeAlarmAsync(alarm.ConditionNodeId, alarm.EventId, comment);
|
||||
if (Opc.Ua.StatusCode.IsGood(result))
|
||||
return (true, "Alarm acknowledged successfully.");
|
||||
return (false, $"Acknowledge failed: {Helpers.StatusCodeFormatter.Format(result)}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return (false, $"Error: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns the monitored node ID for persistence, or null if not subscribed.
|
||||
/// </summary>
|
||||
public string? GetAlarmSourceNodeId()
|
||||
{
|
||||
return IsSubscribed ? MonitoredNodeIdText : null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Restores an alarm subscription and requests a condition refresh.
|
||||
/// </summary>
|
||||
public async Task RestoreAlarmSubscriptionAsync(string? sourceNodeId)
|
||||
{
|
||||
if (!IsConnected || string.IsNullOrWhiteSpace(sourceNodeId)) return;
|
||||
|
||||
MonitoredNodeIdText = sourceNodeId;
|
||||
|
||||
try
|
||||
{
|
||||
var nodeId = string.IsNullOrWhiteSpace(sourceNodeId)
|
||||
? null
|
||||
: NodeId.Parse(sourceNodeId);
|
||||
|
||||
await _service.SubscribeAlarmsAsync(nodeId, Interval);
|
||||
IsSubscribed = true;
|
||||
|
||||
try
|
||||
{
|
||||
await _service.RequestConditionRefreshAsync();
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Refresh not supported
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Subscribe failed
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Clears alarm events and resets state.
|
||||
/// </summary>
|
||||
public void Clear()
|
||||
{
|
||||
AlarmEvents.Clear();
|
||||
IsSubscribed = false;
|
||||
ActiveAlarmCount = 0;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Unhooks event handlers from the service.
|
||||
/// </summary>
|
||||
public void Teardown()
|
||||
{
|
||||
_service.AlarmEvent -= OnAlarmEvent;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
using System.Collections.ObjectModel;
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using ZB.MOM.WW.OtOpcUa.Client.Shared;
|
||||
using ZB.MOM.WW.OtOpcUa.Client.UI.Services;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Client.UI.ViewModels;
|
||||
|
||||
/// <summary>
|
||||
/// ViewModel for the OPC UA browse tree panel.
|
||||
/// </summary>
|
||||
public class BrowseTreeViewModel : ObservableObject
|
||||
{
|
||||
private readonly IUiDispatcher _dispatcher;
|
||||
private readonly IOpcUaClientService _service;
|
||||
|
||||
public BrowseTreeViewModel(IOpcUaClientService service, IUiDispatcher dispatcher)
|
||||
{
|
||||
_service = service;
|
||||
_dispatcher = dispatcher;
|
||||
}
|
||||
|
||||
/// <summary>Top-level nodes in the browse tree.</summary>
|
||||
public ObservableCollection<TreeNodeViewModel> RootNodes { get; } = [];
|
||||
|
||||
/// <summary>
|
||||
/// Loads root nodes by browsing with a null parent.
|
||||
/// </summary>
|
||||
public async Task LoadRootsAsync()
|
||||
{
|
||||
var results = await _service.BrowseAsync();
|
||||
|
||||
_dispatcher.Post(() =>
|
||||
{
|
||||
RootNodes.Clear();
|
||||
foreach (var result in results)
|
||||
RootNodes.Add(new TreeNodeViewModel(
|
||||
result.NodeId,
|
||||
result.DisplayName,
|
||||
result.NodeClass,
|
||||
result.HasChildren,
|
||||
_service,
|
||||
_dispatcher));
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Clears all root nodes from the tree.
|
||||
/// </summary>
|
||||
public void Clear()
|
||||
{
|
||||
RootNodes.Clear();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Client.UI.ViewModels;
|
||||
|
||||
/// <summary>
|
||||
/// Represents a single historical value row.
|
||||
/// </summary>
|
||||
public class HistoryValueViewModel : ObservableObject
|
||||
{
|
||||
public HistoryValueViewModel(string value, string status, string sourceTimestamp, string serverTimestamp)
|
||||
{
|
||||
Value = value;
|
||||
Status = status;
|
||||
SourceTimestamp = sourceTimestamp;
|
||||
ServerTimestamp = serverTimestamp;
|
||||
}
|
||||
|
||||
public string Value { get; }
|
||||
public string Status { get; }
|
||||
public string SourceTimestamp { get; }
|
||||
public string ServerTimestamp { get; }
|
||||
}
|
||||
133
src/ZB.MOM.WW.OtOpcUa.Client.UI/ViewModels/HistoryViewModel.cs
Normal file
133
src/ZB.MOM.WW.OtOpcUa.Client.UI/ViewModels/HistoryViewModel.cs
Normal file
@@ -0,0 +1,133 @@
|
||||
using System.Collections.ObjectModel;
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using CommunityToolkit.Mvvm.Input;
|
||||
using Opc.Ua;
|
||||
using ZB.MOM.WW.OtOpcUa.Client.Shared;
|
||||
using ZB.MOM.WW.OtOpcUa.Client.Shared.Models;
|
||||
using ZB.MOM.WW.OtOpcUa.Client.UI.Services;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Client.UI.ViewModels;
|
||||
|
||||
/// <summary>
|
||||
/// ViewModel for the history panel.
|
||||
/// </summary>
|
||||
public partial class HistoryViewModel : ObservableObject
|
||||
{
|
||||
private readonly IUiDispatcher _dispatcher;
|
||||
private readonly IOpcUaClientService _service;
|
||||
|
||||
[ObservableProperty] private DateTimeOffset? _endTime = DateTimeOffset.UtcNow;
|
||||
|
||||
[ObservableProperty] private double _intervalMs = 3600000;
|
||||
|
||||
[ObservableProperty] [NotifyCanExecuteChangedFor(nameof(ReadHistoryCommand))]
|
||||
private bool _isConnected;
|
||||
|
||||
[ObservableProperty] private bool _isLoading;
|
||||
|
||||
[ObservableProperty] private int _maxValues = 1000;
|
||||
|
||||
[ObservableProperty] private AggregateType? _selectedAggregateType;
|
||||
|
||||
[ObservableProperty] [NotifyCanExecuteChangedFor(nameof(ReadHistoryCommand))]
|
||||
private string? _selectedNodeId;
|
||||
|
||||
[ObservableProperty] private DateTimeOffset? _startTime = DateTimeOffset.UtcNow.AddHours(-1);
|
||||
|
||||
public HistoryViewModel(IOpcUaClientService service, IUiDispatcher dispatcher)
|
||||
{
|
||||
_service = service;
|
||||
_dispatcher = dispatcher;
|
||||
}
|
||||
|
||||
/// <summary>Available aggregate types (null means "Raw").</summary>
|
||||
public IReadOnlyList<AggregateType?> AggregateTypes { get; } =
|
||||
[
|
||||
null,
|
||||
AggregateType.Average,
|
||||
AggregateType.Minimum,
|
||||
AggregateType.Maximum,
|
||||
AggregateType.Count,
|
||||
AggregateType.Start,
|
||||
AggregateType.End,
|
||||
AggregateType.StandardDeviation
|
||||
];
|
||||
|
||||
public bool IsAggregateRead => SelectedAggregateType != null;
|
||||
|
||||
/// <summary>History read results.</summary>
|
||||
public ObservableCollection<HistoryValueViewModel> Results { get; } = [];
|
||||
|
||||
partial void OnSelectedAggregateTypeChanged(AggregateType? value)
|
||||
{
|
||||
OnPropertyChanged(nameof(IsAggregateRead));
|
||||
}
|
||||
|
||||
private bool CanReadHistory()
|
||||
{
|
||||
return IsConnected && !string.IsNullOrEmpty(SelectedNodeId);
|
||||
}
|
||||
|
||||
[RelayCommand(CanExecute = nameof(CanReadHistory))]
|
||||
private async Task ReadHistoryAsync()
|
||||
{
|
||||
if (string.IsNullOrEmpty(SelectedNodeId)) return;
|
||||
|
||||
IsLoading = true;
|
||||
_dispatcher.Post(() => Results.Clear());
|
||||
|
||||
try
|
||||
{
|
||||
var nodeId = NodeId.Parse(SelectedNodeId);
|
||||
IReadOnlyList<DataValue> values;
|
||||
|
||||
var start = (StartTime ?? DateTimeOffset.UtcNow.AddHours(-1)).UtcDateTime;
|
||||
var end = (EndTime ?? DateTimeOffset.UtcNow).UtcDateTime;
|
||||
|
||||
if (SelectedAggregateType != null)
|
||||
values = await _service.HistoryReadAggregateAsync(
|
||||
nodeId,
|
||||
start,
|
||||
end,
|
||||
SelectedAggregateType.Value,
|
||||
IntervalMs);
|
||||
else
|
||||
values = await _service.HistoryReadRawAsync(
|
||||
nodeId,
|
||||
start,
|
||||
end,
|
||||
MaxValues);
|
||||
|
||||
_dispatcher.Post(() =>
|
||||
{
|
||||
foreach (var dv in values)
|
||||
Results.Add(new HistoryValueViewModel(
|
||||
Helpers.ValueFormatter.Format(dv.Value),
|
||||
Helpers.StatusCodeFormatter.Format(dv.StatusCode),
|
||||
dv.SourceTimestamp.ToString("O"),
|
||||
dv.ServerTimestamp.ToString("O")));
|
||||
});
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_dispatcher.Post(() =>
|
||||
{
|
||||
Results.Add(new HistoryValueViewModel(
|
||||
$"Error: {ex.Message}", string.Empty, string.Empty, string.Empty));
|
||||
});
|
||||
}
|
||||
finally
|
||||
{
|
||||
_dispatcher.Post(() => IsLoading = false);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Clears results and resets state.
|
||||
/// </summary>
|
||||
public void Clear()
|
||||
{
|
||||
Results.Clear();
|
||||
SelectedNodeId = null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,421 @@
|
||||
using System.Collections.ObjectModel;
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using CommunityToolkit.Mvvm.Input;
|
||||
using ZB.MOM.WW.OtOpcUa.Client.Shared;
|
||||
using ZB.MOM.WW.OtOpcUa.Client.Shared.Models;
|
||||
using ZB.MOM.WW.OtOpcUa.Client.UI.Services;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Client.UI.ViewModels;
|
||||
|
||||
/// <summary>
|
||||
/// Main window ViewModel coordinating all panels.
|
||||
/// </summary>
|
||||
public partial class MainWindowViewModel : ObservableObject
|
||||
{
|
||||
private readonly IUiDispatcher _dispatcher;
|
||||
private readonly IOpcUaClientServiceFactory _factory;
|
||||
private readonly ISettingsService _settingsService;
|
||||
private IOpcUaClientService? _service;
|
||||
private List<string> _savedSubscribedNodes = [];
|
||||
private string? _savedAlarmSourceNodeId;
|
||||
|
||||
[ObservableProperty] private bool _autoAcceptCertificates = true;
|
||||
|
||||
[ObservableProperty] private string _certificateStorePath = Path.Combine(
|
||||
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
|
||||
"LmxOpcUaClient", "pki");
|
||||
|
||||
[ObservableProperty]
|
||||
[NotifyCanExecuteChangedFor(nameof(ConnectCommand))]
|
||||
[NotifyCanExecuteChangedFor(nameof(DisconnectCommand))]
|
||||
private ConnectionState _connectionState = ConnectionState.Disconnected;
|
||||
|
||||
[ObservableProperty] private string _endpointUrl = "opc.tcp://localhost:4840";
|
||||
|
||||
[ObservableProperty] private string? _failoverUrls;
|
||||
|
||||
[ObservableProperty] private bool _isHistoryEnabledForSelection;
|
||||
|
||||
[ObservableProperty] private string? _password;
|
||||
|
||||
[ObservableProperty] private RedundancyInfo? _redundancyInfo;
|
||||
|
||||
[ObservableProperty] private SecurityMode _selectedSecurityMode = SecurityMode.None;
|
||||
|
||||
[ObservableProperty] private int _selectedTabIndex;
|
||||
|
||||
[ObservableProperty] private TreeNodeViewModel? _selectedTreeNode;
|
||||
|
||||
[ObservableProperty] private string _sessionLabel = string.Empty;
|
||||
|
||||
[ObservableProperty] private int _sessionTimeoutSeconds = 60;
|
||||
|
||||
[ObservableProperty] private string _statusMessage = "Disconnected";
|
||||
|
||||
[ObservableProperty] private int _subscriptionCount;
|
||||
|
||||
[ObservableProperty] private int _activeAlarmCount;
|
||||
|
||||
[ObservableProperty] private string? _username;
|
||||
|
||||
/// <summary>
|
||||
/// Creates the main shell view model that coordinates connection state, browsing, subscriptions, alarms, history, and persisted settings.
|
||||
/// </summary>
|
||||
/// <param name="factory">Creates the shared OPC UA client service used by all panels.</param>
|
||||
/// <param name="dispatcher">Marshals service callbacks back onto the UI thread.</param>
|
||||
/// <param name="settingsService">Loads and saves persisted user connection settings.</param>
|
||||
public MainWindowViewModel(IOpcUaClientServiceFactory factory, IUiDispatcher dispatcher,
|
||||
ISettingsService? settingsService = null)
|
||||
{
|
||||
_factory = factory;
|
||||
_dispatcher = dispatcher;
|
||||
_settingsService = settingsService ?? new JsonSettingsService();
|
||||
|
||||
LoadSettings();
|
||||
}
|
||||
|
||||
/// <summary>All available security modes.</summary>
|
||||
public IReadOnlyList<SecurityMode> SecurityModes { get; } = Enum.GetValues<SecurityMode>();
|
||||
|
||||
/// <summary>
|
||||
/// Gets a value indicating whether the shell is currently connected to an OPC UA endpoint.
|
||||
/// </summary>
|
||||
public bool IsConnected => ConnectionState == ConnectionState.Connected;
|
||||
|
||||
/// <summary>The currently selected tree nodes (supports multi-select).</summary>
|
||||
public ObservableCollection<TreeNodeViewModel> SelectedTreeNodes { get; } = [];
|
||||
|
||||
/// <summary>
|
||||
/// Gets the browse-tree panel view model for the address-space explorer.
|
||||
/// </summary>
|
||||
public BrowseTreeViewModel? BrowseTree { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the read/write panel view model for point operations against the selected node.
|
||||
/// </summary>
|
||||
public ReadWriteViewModel? ReadWrite { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the subscriptions panel view model for live data monitoring.
|
||||
/// </summary>
|
||||
public SubscriptionsViewModel? Subscriptions { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the alarms panel view model for active-condition monitoring and acknowledgment.
|
||||
/// </summary>
|
||||
public AlarmsViewModel? Alarms { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the history panel view model for raw and aggregate history queries.
|
||||
/// </summary>
|
||||
public HistoryViewModel? History { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the subscriptions tab header, including the current active subscription count when nonzero.
|
||||
/// </summary>
|
||||
public string SubscriptionsTabHeader => SubscriptionCount > 0
|
||||
? $"Subscriptions ({SubscriptionCount})"
|
||||
: "Subscriptions";
|
||||
|
||||
/// <summary>
|
||||
/// Gets the alarms tab header, including the current active alarm count when nonzero.
|
||||
/// </summary>
|
||||
public string AlarmsTabHeader => ActiveAlarmCount > 0
|
||||
? $"Alarms ({ActiveAlarmCount})"
|
||||
: "Alarms";
|
||||
|
||||
private void InitializeService()
|
||||
{
|
||||
if (_service != null) return;
|
||||
|
||||
_service = _factory.Create();
|
||||
_service.ConnectionStateChanged += OnConnectionStateChanged;
|
||||
|
||||
BrowseTree = new BrowseTreeViewModel(_service, _dispatcher);
|
||||
ReadWrite = new ReadWriteViewModel(_service, _dispatcher);
|
||||
Subscriptions = new SubscriptionsViewModel(_service, _dispatcher);
|
||||
Alarms = new AlarmsViewModel(_service, _dispatcher);
|
||||
Alarms.PropertyChanged += (_, args) =>
|
||||
{
|
||||
if (args.PropertyName == nameof(AlarmsViewModel.ActiveAlarmCount))
|
||||
_dispatcher.Post(() => ActiveAlarmCount = Alarms.ActiveAlarmCount);
|
||||
};
|
||||
History = new HistoryViewModel(_service, _dispatcher);
|
||||
|
||||
OnPropertyChanged(nameof(BrowseTree));
|
||||
OnPropertyChanged(nameof(ReadWrite));
|
||||
OnPropertyChanged(nameof(Subscriptions));
|
||||
OnPropertyChanged(nameof(Alarms));
|
||||
OnPropertyChanged(nameof(History));
|
||||
}
|
||||
|
||||
private void OnConnectionStateChanged(object? sender, ConnectionStateChangedEventArgs e)
|
||||
{
|
||||
_dispatcher.Post(() => { ConnectionState = e.NewState; });
|
||||
}
|
||||
|
||||
partial void OnConnectionStateChanged(ConnectionState value)
|
||||
{
|
||||
OnPropertyChanged(nameof(IsConnected));
|
||||
|
||||
var connected = value == ConnectionState.Connected;
|
||||
if (ReadWrite != null) ReadWrite.IsConnected = connected;
|
||||
if (Subscriptions != null) Subscriptions.IsConnected = connected;
|
||||
if (Alarms != null) Alarms.IsConnected = connected;
|
||||
if (History != null) History.IsConnected = connected;
|
||||
|
||||
switch (value)
|
||||
{
|
||||
case ConnectionState.Connected:
|
||||
StatusMessage = $"Connected to {EndpointUrl}";
|
||||
break;
|
||||
case ConnectionState.Reconnecting:
|
||||
StatusMessage = "Reconnecting...";
|
||||
break;
|
||||
case ConnectionState.Connecting:
|
||||
StatusMessage = "Connecting...";
|
||||
break;
|
||||
case ConnectionState.Disconnected:
|
||||
StatusMessage = "Disconnected";
|
||||
SessionLabel = string.Empty;
|
||||
RedundancyInfo = null;
|
||||
BrowseTree?.Clear();
|
||||
ReadWrite?.Clear();
|
||||
Subscriptions?.Clear();
|
||||
Alarms?.Clear();
|
||||
History?.Clear();
|
||||
SubscriptionCount = 0;
|
||||
ActiveAlarmCount = 0;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
partial void OnSelectedTreeNodeChanged(TreeNodeViewModel? value)
|
||||
{
|
||||
if (ReadWrite != null) ReadWrite.SelectedNodeId = value?.NodeId;
|
||||
if (History != null) History.SelectedNodeId = value?.NodeId;
|
||||
}
|
||||
|
||||
partial void OnSubscriptionCountChanged(int value)
|
||||
{
|
||||
OnPropertyChanged(nameof(SubscriptionsTabHeader));
|
||||
}
|
||||
|
||||
partial void OnActiveAlarmCountChanged(int value)
|
||||
{
|
||||
OnPropertyChanged(nameof(AlarmsTabHeader));
|
||||
}
|
||||
|
||||
private bool CanConnect()
|
||||
{
|
||||
return ConnectionState == ConnectionState.Disconnected;
|
||||
}
|
||||
|
||||
[RelayCommand(CanExecute = nameof(CanConnect))]
|
||||
private async Task ConnectAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
ConnectionState = ConnectionState.Connecting;
|
||||
StatusMessage = "Connecting...";
|
||||
|
||||
InitializeService();
|
||||
|
||||
var settings = new ConnectionSettings
|
||||
{
|
||||
EndpointUrl = EndpointUrl,
|
||||
Username = Username,
|
||||
Password = Password,
|
||||
SecurityMode = SelectedSecurityMode,
|
||||
FailoverUrls = ParseFailoverUrls(FailoverUrls),
|
||||
SessionTimeoutSeconds = SessionTimeoutSeconds,
|
||||
AutoAcceptCertificates = AutoAcceptCertificates,
|
||||
CertificateStorePath = CertificateStorePath
|
||||
};
|
||||
settings.Validate();
|
||||
|
||||
var info = await _service!.ConnectAsync(settings);
|
||||
|
||||
_dispatcher.Post(() =>
|
||||
{
|
||||
ConnectionState = ConnectionState.Connected;
|
||||
SessionLabel = $"{info.ServerName} | Session: {info.SessionName} ({info.SessionId})";
|
||||
});
|
||||
|
||||
// Load redundancy info
|
||||
try
|
||||
{
|
||||
var redundancy = await _service!.GetRedundancyInfoAsync();
|
||||
_dispatcher.Post(() => RedundancyInfo = redundancy);
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Redundancy info not available
|
||||
}
|
||||
|
||||
// Load root nodes
|
||||
await BrowseTree.LoadRootsAsync();
|
||||
|
||||
// Restore saved subscriptions
|
||||
if (_savedSubscribedNodes.Count > 0 && Subscriptions != null)
|
||||
{
|
||||
await Subscriptions.RestoreSubscriptionsAsync(_savedSubscribedNodes);
|
||||
SubscriptionCount = Subscriptions.SubscriptionCount;
|
||||
}
|
||||
|
||||
// Restore saved alarm subscription
|
||||
if (!string.IsNullOrEmpty(_savedAlarmSourceNodeId) && Alarms != null)
|
||||
await Alarms.RestoreAlarmSubscriptionAsync(_savedAlarmSourceNodeId);
|
||||
|
||||
SaveSettings();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_dispatcher.Post(() =>
|
||||
{
|
||||
ConnectionState = ConnectionState.Disconnected;
|
||||
StatusMessage = $"Connection failed: {ex.Message}";
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private bool CanDisconnect()
|
||||
{
|
||||
return ConnectionState == ConnectionState.Connected
|
||||
|| ConnectionState == ConnectionState.Reconnecting;
|
||||
}
|
||||
|
||||
[RelayCommand(CanExecute = nameof(CanDisconnect))]
|
||||
private async Task DisconnectAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
SaveSettings();
|
||||
Subscriptions?.Teardown();
|
||||
Alarms?.Teardown();
|
||||
await _service!.DisconnectAsync();
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Best-effort disconnect
|
||||
}
|
||||
finally
|
||||
{
|
||||
_dispatcher.Post(() => { ConnectionState = ConnectionState.Disconnected; });
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Subscribes all selected tree nodes and switches to the Subscriptions tab.
|
||||
/// </summary>
|
||||
[RelayCommand]
|
||||
private async Task SubscribeSelectedNodesAsync()
|
||||
{
|
||||
if (SelectedTreeNodes.Count == 0 || !IsConnected) return;
|
||||
|
||||
if (Subscriptions == null) return;
|
||||
|
||||
var nodes = SelectedTreeNodes.ToList();
|
||||
foreach (var node in nodes)
|
||||
await Subscriptions.AddSubscriptionRecursiveAsync(node.NodeId, node.NodeClass);
|
||||
|
||||
SubscriptionCount = Subscriptions.SubscriptionCount;
|
||||
SelectedTabIndex = 1; // Subscriptions tab
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets the history tab's selected node and switches to the History tab.
|
||||
/// </summary>
|
||||
[RelayCommand]
|
||||
private void ViewHistoryForSelectedNode()
|
||||
{
|
||||
if (SelectedTreeNodes.Count == 0 || !IsConnected) return;
|
||||
|
||||
var node = SelectedTreeNodes[0];
|
||||
History.SelectedNodeId = node.NodeId;
|
||||
SelectedTabIndex = 3; // History tab
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Stops any active alarm subscription, subscribes to alarms on the selected node,
|
||||
/// and switches to the Alarms tab.
|
||||
/// </summary>
|
||||
[RelayCommand]
|
||||
private async Task MonitorAlarmsForSelectedNodeAsync()
|
||||
{
|
||||
if (SelectedTreeNodes.Count == 0 || !IsConnected || Alarms == null) return;
|
||||
|
||||
var node = SelectedTreeNodes[0];
|
||||
|
||||
// Stop existing alarm subscription if active
|
||||
if (Alarms.IsSubscribed)
|
||||
{
|
||||
try { await _service!.UnsubscribeAlarmsAsync(); }
|
||||
catch { /* best effort */ }
|
||||
Alarms.Clear();
|
||||
}
|
||||
|
||||
// Subscribe to the selected node
|
||||
Alarms.MonitoredNodeIdText = node.NodeId;
|
||||
await Alarms.SubscribeCommand.ExecuteAsync(null);
|
||||
|
||||
SelectedTabIndex = 2; // Alarms tab
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Updates whether "View History" should be enabled based on the selected node's type.
|
||||
/// Only Variable nodes can have history.
|
||||
/// </summary>
|
||||
public void UpdateHistoryEnabledForSelection()
|
||||
{
|
||||
IsHistoryEnabledForSelection = IsConnected
|
||||
&& SelectedTreeNodes.Count > 0
|
||||
&& SelectedTreeNodes[0].NodeClass == "Variable";
|
||||
}
|
||||
|
||||
private void LoadSettings()
|
||||
{
|
||||
var s = _settingsService.Load();
|
||||
EndpointUrl = s.EndpointUrl;
|
||||
Username = s.Username;
|
||||
Password = s.Password;
|
||||
SelectedSecurityMode = s.SecurityMode;
|
||||
FailoverUrls = s.FailoverUrls;
|
||||
SessionTimeoutSeconds = s.SessionTimeoutSeconds;
|
||||
AutoAcceptCertificates = s.AutoAcceptCertificates;
|
||||
if (!string.IsNullOrEmpty(s.CertificateStorePath))
|
||||
CertificateStorePath = s.CertificateStorePath;
|
||||
_savedSubscribedNodes = s.SubscribedNodes;
|
||||
_savedAlarmSourceNodeId = s.AlarmSourceNodeId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Persists the current connection, subscription, and alarm-monitoring settings for the next UI session.
|
||||
/// </summary>
|
||||
public void SaveSettings()
|
||||
{
|
||||
_settingsService.Save(new UserSettings
|
||||
{
|
||||
EndpointUrl = EndpointUrl,
|
||||
Username = Username,
|
||||
Password = Password,
|
||||
SecurityMode = SelectedSecurityMode,
|
||||
FailoverUrls = FailoverUrls,
|
||||
SessionTimeoutSeconds = SessionTimeoutSeconds,
|
||||
AutoAcceptCertificates = AutoAcceptCertificates,
|
||||
CertificateStorePath = CertificateStorePath,
|
||||
SubscribedNodes = Subscriptions?.GetSubscribedNodeIds() ?? _savedSubscribedNodes,
|
||||
AlarmSourceNodeId = Alarms?.GetAlarmSourceNodeId() ?? _savedAlarmSourceNodeId
|
||||
});
|
||||
}
|
||||
|
||||
private static string[]? ParseFailoverUrls(string? csv)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(csv))
|
||||
return null;
|
||||
|
||||
return csv.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)
|
||||
.Where(u => !string.IsNullOrEmpty(u))
|
||||
.ToArray();
|
||||
}
|
||||
}
|
||||
124
src/ZB.MOM.WW.OtOpcUa.Client.UI/ViewModels/ReadWriteViewModel.cs
Normal file
124
src/ZB.MOM.WW.OtOpcUa.Client.UI/ViewModels/ReadWriteViewModel.cs
Normal file
@@ -0,0 +1,124 @@
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using CommunityToolkit.Mvvm.Input;
|
||||
using Opc.Ua;
|
||||
using ZB.MOM.WW.OtOpcUa.Client.Shared;
|
||||
using ZB.MOM.WW.OtOpcUa.Client.UI.Services;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Client.UI.ViewModels;
|
||||
|
||||
/// <summary>
|
||||
/// ViewModel for the read/write panel.
|
||||
/// </summary>
|
||||
public partial class ReadWriteViewModel : ObservableObject
|
||||
{
|
||||
private readonly IUiDispatcher _dispatcher;
|
||||
private readonly IOpcUaClientService _service;
|
||||
|
||||
[ObservableProperty] private string? _currentStatus;
|
||||
|
||||
[ObservableProperty] private string? _currentValue;
|
||||
|
||||
[ObservableProperty]
|
||||
[NotifyCanExecuteChangedFor(nameof(ReadCommand))]
|
||||
[NotifyCanExecuteChangedFor(nameof(WriteCommand))]
|
||||
private bool _isConnected;
|
||||
|
||||
[ObservableProperty]
|
||||
[NotifyCanExecuteChangedFor(nameof(ReadCommand))]
|
||||
[NotifyCanExecuteChangedFor(nameof(WriteCommand))]
|
||||
private string? _selectedNodeId;
|
||||
|
||||
[ObservableProperty] private string? _serverTimestamp;
|
||||
|
||||
[ObservableProperty] private string? _sourceTimestamp;
|
||||
|
||||
[ObservableProperty] private string? _writeStatus;
|
||||
|
||||
[ObservableProperty] private string? _writeValue;
|
||||
|
||||
public ReadWriteViewModel(IOpcUaClientService service, IUiDispatcher dispatcher)
|
||||
{
|
||||
_service = service;
|
||||
_dispatcher = dispatcher;
|
||||
}
|
||||
|
||||
public bool IsNodeSelected => !string.IsNullOrEmpty(SelectedNodeId);
|
||||
|
||||
partial void OnSelectedNodeIdChanged(string? value)
|
||||
{
|
||||
OnPropertyChanged(nameof(IsNodeSelected));
|
||||
if (!string.IsNullOrEmpty(value) && IsConnected) _ = ExecuteReadAsync();
|
||||
}
|
||||
|
||||
private bool CanReadOrWrite()
|
||||
{
|
||||
return IsConnected && !string.IsNullOrEmpty(SelectedNodeId);
|
||||
}
|
||||
|
||||
[RelayCommand(CanExecute = nameof(CanReadOrWrite))]
|
||||
private async Task ReadAsync()
|
||||
{
|
||||
await ExecuteReadAsync();
|
||||
}
|
||||
|
||||
private async Task ExecuteReadAsync()
|
||||
{
|
||||
if (string.IsNullOrEmpty(SelectedNodeId)) return;
|
||||
|
||||
try
|
||||
{
|
||||
var nodeId = NodeId.Parse(SelectedNodeId);
|
||||
var dataValue = await _service.ReadValueAsync(nodeId);
|
||||
|
||||
_dispatcher.Post(() =>
|
||||
{
|
||||
CurrentValue = Helpers.ValueFormatter.Format(dataValue.Value);
|
||||
CurrentStatus = Helpers.StatusCodeFormatter.Format(dataValue.StatusCode);
|
||||
SourceTimestamp = dataValue.SourceTimestamp.ToString("O");
|
||||
ServerTimestamp = dataValue.ServerTimestamp.ToString("O");
|
||||
});
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_dispatcher.Post(() =>
|
||||
{
|
||||
CurrentValue = null;
|
||||
CurrentStatus = $"Error: {ex.Message}";
|
||||
SourceTimestamp = null;
|
||||
ServerTimestamp = null;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
[RelayCommand(CanExecute = nameof(CanReadOrWrite))]
|
||||
private async Task WriteAsync()
|
||||
{
|
||||
if (string.IsNullOrEmpty(SelectedNodeId) || WriteValue == null) return;
|
||||
|
||||
try
|
||||
{
|
||||
var nodeId = NodeId.Parse(SelectedNodeId);
|
||||
var statusCode = await _service.WriteValueAsync(nodeId, WriteValue);
|
||||
|
||||
_dispatcher.Post(() => { WriteStatus = statusCode.ToString(); });
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_dispatcher.Post(() => { WriteStatus = $"Error: {ex.Message}"; });
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Clears all displayed values.
|
||||
/// </summary>
|
||||
public void Clear()
|
||||
{
|
||||
SelectedNodeId = null;
|
||||
CurrentValue = null;
|
||||
CurrentStatus = null;
|
||||
SourceTimestamp = null;
|
||||
ServerTimestamp = null;
|
||||
WriteValue = null;
|
||||
WriteStatus = null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Client.UI.ViewModels;
|
||||
|
||||
/// <summary>
|
||||
/// Represents a single active subscription row.
|
||||
/// </summary>
|
||||
public partial class SubscriptionItemViewModel : ObservableObject
|
||||
{
|
||||
[ObservableProperty] private string? _status;
|
||||
|
||||
[ObservableProperty] private string? _timestamp;
|
||||
|
||||
[ObservableProperty] private string? _value;
|
||||
|
||||
public SubscriptionItemViewModel(string nodeId, int intervalMs)
|
||||
{
|
||||
NodeId = nodeId;
|
||||
IntervalMs = intervalMs;
|
||||
}
|
||||
|
||||
/// <summary>The monitored NodeId.</summary>
|
||||
public string NodeId { get; }
|
||||
|
||||
/// <summary>The subscription interval in milliseconds.</summary>
|
||||
public int IntervalMs { get; }
|
||||
}
|
||||
@@ -0,0 +1,275 @@
|
||||
using System.Collections.ObjectModel;
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using CommunityToolkit.Mvvm.Input;
|
||||
using Opc.Ua;
|
||||
using ZB.MOM.WW.OtOpcUa.Client.Shared;
|
||||
using ZB.MOM.WW.OtOpcUa.Client.Shared.Models;
|
||||
using ZB.MOM.WW.OtOpcUa.Client.UI.Services;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Client.UI.ViewModels;
|
||||
|
||||
/// <summary>
|
||||
/// ViewModel for the subscriptions panel.
|
||||
/// </summary>
|
||||
public partial class SubscriptionsViewModel : ObservableObject
|
||||
{
|
||||
private readonly IUiDispatcher _dispatcher;
|
||||
private readonly IOpcUaClientService _service;
|
||||
|
||||
[ObservableProperty]
|
||||
[NotifyCanExecuteChangedFor(nameof(AddSubscriptionCommand))]
|
||||
[NotifyCanExecuteChangedFor(nameof(RemoveSubscriptionCommand))]
|
||||
private bool _isConnected;
|
||||
|
||||
[ObservableProperty] private int _newInterval = 1000;
|
||||
|
||||
[ObservableProperty] [NotifyCanExecuteChangedFor(nameof(AddSubscriptionCommand))]
|
||||
private string? _newNodeIdText;
|
||||
|
||||
[ObservableProperty] [NotifyCanExecuteChangedFor(nameof(RemoveSubscriptionCommand))]
|
||||
private SubscriptionItemViewModel? _selectedSubscription;
|
||||
|
||||
[ObservableProperty] private int _subscriptionCount;
|
||||
|
||||
/// <summary>
|
||||
/// Creates the subscriptions panel view model used to manage live data subscriptions and ad hoc writes from the UI.
|
||||
/// </summary>
|
||||
/// <param name="service">The shared client service that performs subscribe, unsubscribe, read, and write operations.</param>
|
||||
/// <param name="dispatcher">Marshals data-change callbacks back onto the UI thread.</param>
|
||||
public SubscriptionsViewModel(IOpcUaClientService service, IUiDispatcher dispatcher)
|
||||
{
|
||||
_service = service;
|
||||
_dispatcher = dispatcher;
|
||||
_service.DataChanged += OnDataChanged;
|
||||
}
|
||||
|
||||
/// <summary>Currently active subscriptions.</summary>
|
||||
public ObservableCollection<SubscriptionItemViewModel> ActiveSubscriptions { get; } = [];
|
||||
|
||||
/// <summary>Currently selected subscriptions (for multi-select remove).</summary>
|
||||
public List<SubscriptionItemViewModel> SelectedSubscriptions { get; } = [];
|
||||
|
||||
private void OnDataChanged(object? sender, DataChangedEventArgs e)
|
||||
{
|
||||
_dispatcher.Post(() =>
|
||||
{
|
||||
foreach (var item in ActiveSubscriptions)
|
||||
if (item.NodeId == e.NodeId)
|
||||
{
|
||||
item.Value = Helpers.ValueFormatter.Format(e.Value.Value);
|
||||
item.Status = Helpers.StatusCodeFormatter.Format(e.Value.StatusCode);
|
||||
item.Timestamp = e.Value.SourceTimestamp.ToString("O");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private bool CanAddSubscription()
|
||||
{
|
||||
return IsConnected && !string.IsNullOrWhiteSpace(NewNodeIdText);
|
||||
}
|
||||
|
||||
[RelayCommand(CanExecute = nameof(CanAddSubscription))]
|
||||
private async Task AddSubscriptionAsync()
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(NewNodeIdText)) return;
|
||||
|
||||
var nodeIdStr = NewNodeIdText;
|
||||
var interval = NewInterval;
|
||||
|
||||
try
|
||||
{
|
||||
var nodeId = NodeId.Parse(nodeIdStr);
|
||||
await _service.SubscribeAsync(nodeId, interval);
|
||||
|
||||
_dispatcher.Post(() =>
|
||||
{
|
||||
ActiveSubscriptions.Add(new SubscriptionItemViewModel(nodeIdStr, interval));
|
||||
SubscriptionCount = ActiveSubscriptions.Count;
|
||||
});
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Subscription failed; no item added
|
||||
}
|
||||
}
|
||||
|
||||
private bool CanRemoveSubscription()
|
||||
{
|
||||
return IsConnected && (SelectedSubscriptions.Count > 0 || SelectedSubscription != null);
|
||||
}
|
||||
|
||||
[RelayCommand(CanExecute = nameof(CanRemoveSubscription))]
|
||||
private async Task RemoveSubscriptionAsync()
|
||||
{
|
||||
var itemsToRemove = SelectedSubscriptions.Count > 0
|
||||
? SelectedSubscriptions.ToList()
|
||||
: SelectedSubscription != null ? [SelectedSubscription] : [];
|
||||
|
||||
if (itemsToRemove.Count == 0) return;
|
||||
|
||||
foreach (var item in itemsToRemove)
|
||||
{
|
||||
try
|
||||
{
|
||||
var nodeId = NodeId.Parse(item.NodeId);
|
||||
await _service.UnsubscribeAsync(nodeId);
|
||||
|
||||
_dispatcher.Post(() => ActiveSubscriptions.Remove(item));
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Unsubscribe failed for this item; continue with others
|
||||
}
|
||||
}
|
||||
|
||||
_dispatcher.Post(() => SubscriptionCount = ActiveSubscriptions.Count);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Subscribes to a node by ID (used by context menu). Skips if already subscribed.
|
||||
/// </summary>
|
||||
/// <param name="nodeIdStr">The node ID to subscribe to from the browse tree or persisted settings.</param>
|
||||
/// <param name="intervalMs">The monitored-item interval, in milliseconds, for the subscription.</param>
|
||||
public async Task AddSubscriptionForNodeAsync(string nodeIdStr, int intervalMs = 1000)
|
||||
{
|
||||
if (!IsConnected || string.IsNullOrWhiteSpace(nodeIdStr)) return;
|
||||
|
||||
// Skip if already subscribed
|
||||
if (ActiveSubscriptions.Any(s => s.NodeId == nodeIdStr)) return;
|
||||
|
||||
try
|
||||
{
|
||||
var nodeId = NodeId.Parse(nodeIdStr);
|
||||
await _service.SubscribeAsync(nodeId, intervalMs);
|
||||
|
||||
_dispatcher.Post(() =>
|
||||
{
|
||||
ActiveSubscriptions.Add(new SubscriptionItemViewModel(nodeIdStr, intervalMs));
|
||||
SubscriptionCount = ActiveSubscriptions.Count;
|
||||
});
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Subscription failed
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Subscribes to a node and all its Variable descendants recursively.
|
||||
/// Object nodes are browsed for children; Variable nodes are subscribed directly.
|
||||
/// </summary>
|
||||
/// <param name="nodeIdStr">The root node whose variables should be subscribed recursively.</param>
|
||||
/// <param name="nodeClass">The node class of the starting node so variables can be subscribed immediately.</param>
|
||||
/// <param name="intervalMs">The monitored-item interval, in milliseconds, used for created subscriptions.</param>
|
||||
public Task AddSubscriptionRecursiveAsync(string nodeIdStr, string nodeClass, int intervalMs = 1000)
|
||||
{
|
||||
return AddSubscriptionRecursiveAsync(nodeIdStr, nodeClass, intervalMs, maxDepth: 10, currentDepth: 0);
|
||||
}
|
||||
|
||||
private async Task AddSubscriptionRecursiveAsync(string nodeIdStr, string nodeClass, int intervalMs, int maxDepth, int currentDepth)
|
||||
{
|
||||
if (!IsConnected || string.IsNullOrWhiteSpace(nodeIdStr)) return;
|
||||
if (currentDepth >= maxDepth) return;
|
||||
|
||||
if (nodeClass == "Variable")
|
||||
{
|
||||
await AddSubscriptionForNodeAsync(nodeIdStr, intervalMs);
|
||||
return;
|
||||
}
|
||||
|
||||
// Browse children and recurse
|
||||
try
|
||||
{
|
||||
var nodeId = NodeId.Parse(nodeIdStr);
|
||||
var children = await _service.BrowseAsync(nodeId);
|
||||
|
||||
foreach (var child in children)
|
||||
await AddSubscriptionRecursiveAsync(child.NodeId, child.NodeClass, intervalMs, maxDepth, currentDepth + 1);
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Browse failed for this node; skip it
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns the node IDs of all active subscriptions for persistence.
|
||||
/// </summary>
|
||||
public List<string> GetSubscribedNodeIds()
|
||||
{
|
||||
return ActiveSubscriptions.Select(s => s.NodeId).ToList();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Restores subscriptions from a saved list of node IDs.
|
||||
/// </summary>
|
||||
/// <param name="nodeIds">The node IDs persisted from a prior UI session.</param>
|
||||
public async Task RestoreSubscriptionsAsync(IEnumerable<string> nodeIds)
|
||||
{
|
||||
foreach (var nodeId in nodeIds)
|
||||
await AddSubscriptionForNodeAsync(nodeId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads the current value of a node to determine its type, validates that the raw
|
||||
/// input can be parsed to that type, writes the value, and returns (success, message).
|
||||
/// </summary>
|
||||
/// <param name="nodeIdStr">The node ID the operator wants to write.</param>
|
||||
/// <param name="rawValue">The raw text value entered by the operator.</param>
|
||||
public async Task<(bool Success, string Message)> ValidateAndWriteAsync(string nodeIdStr, string rawValue)
|
||||
{
|
||||
try
|
||||
{
|
||||
var nodeId = NodeId.Parse(nodeIdStr);
|
||||
|
||||
// Read current value to determine target type
|
||||
var currentDataValue = await _service.ReadValueAsync(nodeId);
|
||||
var currentValue = currentDataValue.Value;
|
||||
|
||||
// Try parsing to the target type before writing
|
||||
try
|
||||
{
|
||||
Shared.Helpers.ValueConverter.ConvertValue(rawValue, currentValue);
|
||||
}
|
||||
catch (FormatException ex)
|
||||
{
|
||||
var typeName = currentValue?.GetType().Name ?? "unknown";
|
||||
return (false, $"Cannot parse \"{rawValue}\" as {typeName}: {ex.Message}");
|
||||
}
|
||||
catch (OverflowException ex)
|
||||
{
|
||||
var typeName = currentValue?.GetType().Name ?? "unknown";
|
||||
return (false, $"Value \"{rawValue}\" is out of range for {typeName}: {ex.Message}");
|
||||
}
|
||||
|
||||
var result = await _service.WriteValueAsync(nodeId, rawValue);
|
||||
var statusText = Helpers.StatusCodeFormatter.Format(result);
|
||||
|
||||
if (Opc.Ua.StatusCode.IsGood(result))
|
||||
return (true, statusText);
|
||||
|
||||
return (false, $"Write failed: {statusText}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return (false, $"Error: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Clears all subscriptions and resets state.
|
||||
/// </summary>
|
||||
public void Clear()
|
||||
{
|
||||
ActiveSubscriptions.Clear();
|
||||
SubscriptionCount = 0;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Unhooks event handlers from the service.
|
||||
/// </summary>
|
||||
public void Teardown()
|
||||
{
|
||||
_service.DataChanged -= OnDataChanged;
|
||||
}
|
||||
}
|
||||
111
src/ZB.MOM.WW.OtOpcUa.Client.UI/ViewModels/TreeNodeViewModel.cs
Normal file
111
src/ZB.MOM.WW.OtOpcUa.Client.UI/ViewModels/TreeNodeViewModel.cs
Normal file
@@ -0,0 +1,111 @@
|
||||
using System.Collections.ObjectModel;
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using ZB.MOM.WW.OtOpcUa.Client.Shared;
|
||||
using ZB.MOM.WW.OtOpcUa.Client.UI.Services;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Client.UI.ViewModels;
|
||||
|
||||
/// <summary>
|
||||
/// Represents a single node in the OPC UA browse tree with lazy-load support.
|
||||
/// </summary>
|
||||
public partial class TreeNodeViewModel : ObservableObject
|
||||
{
|
||||
private static readonly TreeNodeViewModel PlaceholderSentinel = new();
|
||||
private readonly IUiDispatcher? _dispatcher;
|
||||
|
||||
private readonly IOpcUaClientService? _service;
|
||||
private bool _hasLoadedChildren;
|
||||
|
||||
[ObservableProperty] private bool _isExpanded;
|
||||
|
||||
[ObservableProperty] private bool _isLoading;
|
||||
|
||||
/// <summary>
|
||||
/// Private constructor for the placeholder sentinel only.
|
||||
/// </summary>
|
||||
private TreeNodeViewModel()
|
||||
{
|
||||
NodeId = string.Empty;
|
||||
DisplayName = "Loading...";
|
||||
NodeClass = string.Empty;
|
||||
HasChildren = false;
|
||||
}
|
||||
|
||||
public TreeNodeViewModel(
|
||||
string nodeId,
|
||||
string displayName,
|
||||
string nodeClass,
|
||||
bool hasChildren,
|
||||
IOpcUaClientService service,
|
||||
IUiDispatcher dispatcher)
|
||||
{
|
||||
NodeId = nodeId;
|
||||
DisplayName = displayName;
|
||||
NodeClass = nodeClass;
|
||||
HasChildren = hasChildren;
|
||||
_service = service;
|
||||
_dispatcher = dispatcher;
|
||||
|
||||
if (hasChildren) Children.Add(PlaceholderSentinel);
|
||||
}
|
||||
|
||||
/// <summary>The string NodeId of this node.</summary>
|
||||
public string NodeId { get; }
|
||||
|
||||
/// <summary>The display name shown in the tree.</summary>
|
||||
public string DisplayName { get; }
|
||||
|
||||
/// <summary>The OPC UA node class (Object, Variable, etc.).</summary>
|
||||
public string NodeClass { get; }
|
||||
|
||||
/// <summary>Whether this node has child references.</summary>
|
||||
public bool HasChildren { get; }
|
||||
|
||||
/// <summary>Child nodes (may contain a placeholder sentinel before first expand).</summary>
|
||||
public ObservableCollection<TreeNodeViewModel> Children { get; } = [];
|
||||
|
||||
/// <summary>
|
||||
/// Returns whether this node instance is the placeholder sentinel.
|
||||
/// </summary>
|
||||
internal bool IsPlaceholder => ReferenceEquals(this, PlaceholderSentinel);
|
||||
|
||||
partial void OnIsExpandedChanged(bool value)
|
||||
{
|
||||
if (value && !_hasLoadedChildren && HasChildren) _ = LoadChildrenAsync();
|
||||
}
|
||||
|
||||
private async Task LoadChildrenAsync()
|
||||
{
|
||||
if (_service == null || _dispatcher == null) return;
|
||||
|
||||
_hasLoadedChildren = true;
|
||||
IsLoading = true;
|
||||
|
||||
try
|
||||
{
|
||||
var nodeId = Opc.Ua.NodeId.Parse(NodeId);
|
||||
var results = await _service.BrowseAsync(nodeId);
|
||||
|
||||
_dispatcher.Post(() =>
|
||||
{
|
||||
Children.Clear();
|
||||
foreach (var result in results)
|
||||
Children.Add(new TreeNodeViewModel(
|
||||
result.NodeId,
|
||||
result.DisplayName,
|
||||
result.NodeClass,
|
||||
result.HasChildren,
|
||||
_service,
|
||||
_dispatcher));
|
||||
});
|
||||
}
|
||||
catch
|
||||
{
|
||||
_dispatcher.Post(() => Children.Clear());
|
||||
}
|
||||
finally
|
||||
{
|
||||
_dispatcher.Post(() => IsLoading = false);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user