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:
Joseph Doherty
2026-04-17 13:57:47 -04:00
parent 5b8d708c58
commit 3b2defd94f
293 changed files with 841 additions and 722 deletions

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.OtOpcUa.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.OtOpcUa.Client.Shared;
using ZB.MOM.WW.OtOpcUa.Client.UI.Services;
using ZB.MOM.WW.OtOpcUa.Client.UI.ViewModels;
using ZB.MOM.WW.OtOpcUa.Client.UI.Views;
namespace ZB.MOM.WW.OtOpcUa.Client.UI;
public class App : Application
{
public override void Initialize()
{
AvaloniaXamlLoader.Load(this);
}
public override void OnFrameworkInitializationCompleted()
{
if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
{
var factory = new OpcUaClientServiceFactory();
var dispatcher = new AvaloniaUiDispatcher();
var viewModel = new MainWindowViewModel(factory, dispatcher);
desktop.MainWindow = new MainWindow
{
DataContext = viewModel
};
}
base.OnFrameworkInitializationCompleted();
}
}

View File

@@ -0,0 +1,18 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" width="64" height="64">
<!-- Server/network icon for OPC UA -->
<rect x="8" y="6" width="48" height="36" rx="4" fill="#2563eb" stroke="#1d4ed8" stroke-width="2"/>
<rect x="14" y="12" width="36" height="24" rx="2" fill="#dbeafe"/>
<!-- Network nodes -->
<circle cx="24" cy="24" r="4" fill="#2563eb"/>
<circle cx="40" cy="20" r="3" fill="#3b82f6"/>
<circle cx="36" cy="30" r="3" fill="#3b82f6"/>
<!-- Connection lines -->
<line x1="24" y1="24" x2="40" y2="20" stroke="#60a5fa" stroke-width="1.5"/>
<line x1="24" y1="24" x2="36" y2="30" stroke="#60a5fa" stroke-width="1.5"/>
<line x1="40" y1="20" x2="36" y2="30" stroke="#60a5fa" stroke-width="1.5"/>
<!-- Base stand -->
<rect x="24" y="42" width="16" height="4" rx="1" fill="#6b7280"/>
<rect x="20" y="46" width="24" height="4" rx="2" fill="#9ca3af"/>
<!-- UA text -->
<text x="32" y="60" text-anchor="middle" font-family="Arial,sans-serif" font-size="8" font-weight="bold" fill="#1d4ed8">UA</text>
</svg>

After

Width:  |  Height:  |  Size: 1.0 KiB

View File

@@ -0,0 +1,27 @@
<UserControl xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="ZB.MOM.WW.OtOpcUa.Client.UI.Controls.DateTimeRangePicker">
<StackPanel Orientation="Horizontal" Spacing="8">
<StackPanel Spacing="2">
<TextBlock Text="Start (UTC)" FontSize="11" Foreground="Gray" />
<TextBox Name="StartInput" Width="170" FontFamily="Consolas,monospace" FontSize="13"
Watermark="yyyy-MM-dd HH:mm:ss (UTC)"
Text="{Binding StartText, RelativeSource={RelativeSource AncestorType=UserControl}}" />
</StackPanel>
<TextBlock Text="to" VerticalAlignment="Bottom" Margin="0,0,0,6" />
<StackPanel Spacing="2">
<TextBlock Text="End (UTC)" FontSize="11" Foreground="Gray" />
<TextBox Name="EndInput" Width="170" FontFamily="Consolas,monospace" FontSize="13"
Watermark="yyyy-MM-dd HH:mm:ss (UTC)"
Text="{Binding EndText, RelativeSource={RelativeSource AncestorType=UserControl}}" />
</StackPanel>
<Border Background="#F0F0F0" CornerRadius="4" Padding="4,2" VerticalAlignment="Bottom" Margin="0,0,0,2">
<StackPanel Orientation="Horizontal" Spacing="4">
<Button Name="Last5MinBtn" Content="5m" Padding="8,3" FontSize="11" />
<Button Name="LastHourBtn" Content="1h" Padding="8,3" FontSize="11" />
<Button Name="LastDayBtn" Content="1d" Padding="8,3" FontSize="11" />
<Button Name="LastWeekBtn" Content="1w" Padding="8,3" FontSize="11" />
</StackPanel>
</Border>
</StackPanel>
</UserControl>

View File

@@ -0,0 +1,187 @@
using System;
using System.Globalization;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Interactivity;
using Avalonia.Media;
namespace ZB.MOM.WW.OtOpcUa.Client.UI.Controls;
/// <summary>
/// A date/time range picker using formatted text boxes and preset duration buttons.
/// Text properties are two-way bound to TextBoxes via XAML; DateTime properties
/// are synced in code-behind.
/// </summary>
public partial class DateTimeRangePicker : UserControl
{
private const string Format = "yyyy-MM-dd HH:mm:ss";
public static readonly StyledProperty<DateTimeOffset?> StartDateTimeProperty =
AvaloniaProperty.Register<DateTimeRangePicker, DateTimeOffset?>(
nameof(StartDateTime), defaultBindingMode: Avalonia.Data.BindingMode.TwoWay);
public static readonly StyledProperty<DateTimeOffset?> EndDateTimeProperty =
AvaloniaProperty.Register<DateTimeRangePicker, DateTimeOffset?>(
nameof(EndDateTime), defaultBindingMode: Avalonia.Data.BindingMode.TwoWay);
public static readonly StyledProperty<string> StartTextProperty =
AvaloniaProperty.Register<DateTimeRangePicker, string>(nameof(StartText), defaultValue: "");
public static readonly StyledProperty<string> EndTextProperty =
AvaloniaProperty.Register<DateTimeRangePicker, string>(nameof(EndText), defaultValue: "");
public static readonly StyledProperty<DateTimeOffset?> MinDateTimeProperty =
AvaloniaProperty.Register<DateTimeRangePicker, DateTimeOffset?>(nameof(MinDateTime));
public static readonly StyledProperty<DateTimeOffset?> MaxDateTimeProperty =
AvaloniaProperty.Register<DateTimeRangePicker, DateTimeOffset?>(nameof(MaxDateTime));
private bool _isUpdating;
public DateTimeRangePicker()
{
InitializeComponent();
}
public DateTimeOffset? StartDateTime
{
get => GetValue(StartDateTimeProperty);
set => SetValue(StartDateTimeProperty, value);
}
public DateTimeOffset? EndDateTime
{
get => GetValue(EndDateTimeProperty);
set => SetValue(EndDateTimeProperty, value);
}
public string StartText
{
get => GetValue(StartTextProperty);
set => SetValue(StartTextProperty, value);
}
public string EndText
{
get => GetValue(EndTextProperty);
set => SetValue(EndTextProperty, value);
}
public DateTimeOffset? MinDateTime
{
get => GetValue(MinDateTimeProperty);
set => SetValue(MinDateTimeProperty, value);
}
public DateTimeOffset? MaxDateTime
{
get => GetValue(MaxDateTimeProperty);
set => SetValue(MaxDateTimeProperty, value);
}
protected override void OnLoaded(RoutedEventArgs e)
{
base.OnLoaded(e);
var startInput = this.FindControl<TextBox>("StartInput");
var endInput = this.FindControl<TextBox>("EndInput");
if (startInput != null) startInput.LostFocus += OnStartLostFocus;
if (endInput != null) endInput.LostFocus += OnEndLostFocus;
var last5Min = this.FindControl<Button>("Last5MinBtn");
var lastHour = this.FindControl<Button>("LastHourBtn");
var lastDay = this.FindControl<Button>("LastDayBtn");
var lastWeek = this.FindControl<Button>("LastWeekBtn");
if (last5Min != null) last5Min.Click += (_, _) => ApplyPreset(TimeSpan.FromMinutes(5));
if (lastHour != null) lastHour.Click += (_, _) => ApplyPreset(TimeSpan.FromHours(1));
if (lastDay != null) lastDay.Click += (_, _) => ApplyPreset(TimeSpan.FromDays(1));
if (lastWeek != null) lastWeek.Click += (_, _) => ApplyPreset(TimeSpan.FromDays(7));
}
protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
{
base.OnPropertyChanged(change);
if (_isUpdating) return;
if (change.Property == StartDateTimeProperty)
{
_isUpdating = true;
StartText = StartDateTime?.UtcDateTime.ToString(Format) ?? "";
_isUpdating = false;
}
else if (change.Property == EndDateTimeProperty)
{
_isUpdating = true;
EndText = EndDateTime?.UtcDateTime.ToString(Format) ?? "";
_isUpdating = false;
}
}
private void OnStartLostFocus(object? sender, RoutedEventArgs e)
{
var startInput = this.FindControl<TextBox>("StartInput");
if (startInput == null) return;
if (TryParseDateTime(startInput.Text, out var dt))
{
_isUpdating = true;
StartDateTime = dt;
_isUpdating = false;
startInput.Foreground = null;
}
else if (!string.IsNullOrWhiteSpace(startInput.Text))
{
startInput.Foreground = Brushes.Red;
}
}
private void OnEndLostFocus(object? sender, RoutedEventArgs e)
{
var endInput = this.FindControl<TextBox>("EndInput");
if (endInput == null) return;
if (TryParseDateTime(endInput.Text, out var dt))
{
_isUpdating = true;
EndDateTime = dt;
_isUpdating = false;
endInput.Foreground = null;
}
else if (!string.IsNullOrWhiteSpace(endInput.Text))
{
endInput.Foreground = Brushes.Red;
}
}
private void ApplyPreset(TimeSpan span)
{
_isUpdating = true;
try
{
var now = DateTimeOffset.UtcNow;
StartDateTime = now - span;
EndDateTime = now;
StartText = StartDateTime.Value.UtcDateTime.ToString(Format);
EndText = EndDateTime.Value.UtcDateTime.ToString(Format);
}
finally
{
_isUpdating = false;
}
}
private static bool TryParseDateTime(string? text, out DateTimeOffset result)
{
result = default;
if (string.IsNullOrWhiteSpace(text)) return false;
if (DateTimeOffset.TryParseExact(text, Format, CultureInfo.InvariantCulture,
DateTimeStyles.AssumeUniversal, out result))
return true;
return DateTimeOffset.TryParse(text, CultureInfo.InvariantCulture,
DateTimeStyles.AssumeUniversal, out result);
}
}

View File

@@ -0,0 +1,36 @@
using Opc.Ua;
namespace ZB.MOM.WW.OtOpcUa.Client.UI.Helpers;
/// <summary>
/// Formats OPC UA status codes as "0xHEX (description)".
/// </summary>
internal static class StatusCodeFormatter
{
public static string Format(StatusCode statusCode)
{
var code = statusCode.Code;
var hex = $"0x{code:X8}";
// Try the SDK's browse name lookup first
var name = StatusCodes.GetBrowseName(code);
if (!string.IsNullOrEmpty(name))
return $"{hex} ({name})";
// Try masking to just the main code (top 16 bits) for sub-status codes
var mainCode = code & 0xFFFF0000;
if (mainCode != code)
{
name = StatusCodes.GetBrowseName(mainCode);
if (!string.IsNullOrEmpty(name))
return $"{hex} ({name})";
}
// Fallback to severity category
if (StatusCode.IsGood(statusCode))
return $"{hex} (Good)";
if (StatusCode.IsBad(statusCode))
return $"{hex} (Bad)";
return $"{hex} (Uncertain)";
}
}

View File

@@ -0,0 +1,33 @@
using System.Collections;
namespace ZB.MOM.WW.OtOpcUa.Client.UI.Helpers;
/// <summary>
/// Formats OPC UA values for display, with array support.
/// </summary>
internal static class ValueFormatter
{
public static string Format(object? value)
{
if (value is null) return "(null)";
if (value is Array array) return FormatArray(array);
if (value is IEnumerable enumerable and not string) return FormatEnumerable(enumerable);
return value.ToString() ?? "(null)";
}
private static string FormatArray(Array array)
{
var elements = new string[array.Length];
for (var i = 0; i < array.Length; i++)
elements[i] = array.GetValue(i)?.ToString() ?? "null";
return $"[{string.Join(",", elements)}]";
}
private static string FormatEnumerable(IEnumerable enumerable)
{
var items = new List<string>();
foreach (var item in enumerable)
items.Add(item?.ToString() ?? "null");
return $"[{string.Join(",", items)}]";
}
}

View File

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

View File

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

View File

@@ -0,0 +1,10 @@
namespace ZB.MOM.WW.OtOpcUa.Client.UI.Services;
/// <summary>
/// Loads and saves user settings.
/// </summary>
public interface ISettingsService
{
UserSettings Load();
void Save(UserSettings settings);
}

View File

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

View File

@@ -0,0 +1,50 @@
using System.Text.Json;
namespace ZB.MOM.WW.OtOpcUa.Client.UI.Services;
/// <summary>
/// Persists user settings to a JSON file under LocalApplicationData.
/// </summary>
public sealed class JsonSettingsService : ISettingsService
{
private static readonly string SettingsDir = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
"LmxOpcUaClient");
private static readonly string SettingsPath = Path.Combine(SettingsDir, "settings.json");
private static readonly JsonSerializerOptions JsonOptions = new()
{
WriteIndented = true
};
public UserSettings Load()
{
try
{
if (!File.Exists(SettingsPath))
return new UserSettings();
var json = File.ReadAllText(SettingsPath);
return JsonSerializer.Deserialize<UserSettings>(json, JsonOptions) ?? new UserSettings();
}
catch
{
return new UserSettings();
}
}
public void Save(UserSettings settings)
{
try
{
Directory.CreateDirectory(SettingsDir);
var json = JsonSerializer.Serialize(settings, JsonOptions);
File.WriteAllText(SettingsPath, json);
}
catch
{
// Best-effort save; don't crash the app
}
}
}

View File

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

View File

@@ -0,0 +1,59 @@
using ZB.MOM.WW.OtOpcUa.Client.Shared.Models;
namespace ZB.MOM.WW.OtOpcUa.Client.UI.Services;
/// <summary>
/// Persisted user connection settings.
/// </summary>
public sealed class UserSettings
{
/// <summary>
/// Gets or sets the last OPC UA endpoint URL entered by the user.
/// </summary>
public string EndpointUrl { get; set; } = "opc.tcp://localhost:4840";
/// <summary>
/// Gets or sets the persisted username for authenticated sessions.
/// </summary>
public string? Username { get; set; }
/// <summary>
/// Gets or sets the persisted password for authenticated sessions.
/// </summary>
public string? Password { get; set; }
/// <summary>
/// Gets or sets the transport security mode selected by the user.
/// </summary>
public SecurityMode SecurityMode { get; set; } = SecurityMode.None;
/// <summary>
/// Gets or sets the raw failover endpoint list entered in the UI.
/// </summary>
public string? FailoverUrls { get; set; }
/// <summary>
/// Gets or sets the persisted session timeout, in seconds, for new client connections.
/// </summary>
public int SessionTimeoutSeconds { get; set; } = 60;
/// <summary>
/// Gets or sets a value indicating whether untrusted server certificates should be auto-accepted.
/// </summary>
public bool AutoAcceptCertificates { get; set; } = true;
/// <summary>
/// Gets or sets the certificate store path used for client certificates and trust lists.
/// </summary>
public string? CertificateStorePath { get; set; }
/// <summary>
/// Gets or sets the node IDs that should be re-subscribed when the UI reconnects.
/// </summary>
public List<string> SubscribedNodes { get; set; } = [];
/// <summary>
/// Gets or sets the alarm source node that should be restored when the UI reconnects.
/// </summary>
public string? AlarmSourceNodeId { get; set; }
}

View File

@@ -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;
}

View 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;
}
}

View File

@@ -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();
}
}

View File

@@ -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; }
}

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.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;
}
}

View File

@@ -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();
}
}

View 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;
}
}

View File

@@ -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; }
}

View File

@@ -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;
}
}

View 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);
}
}
}

View File

@@ -0,0 +1,39 @@
<Window xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="ZB.MOM.WW.OtOpcUa.Client.UI.Views.AckAlarmWindow"
Title="Acknowledge Alarm"
Width="420"
SizeToContent="Height"
MinHeight="240"
WindowStartupLocation="CenterOwner"
CanResize="False">
<StackPanel Margin="16" Spacing="12">
<TextBlock Text="Acknowledge Alarm" FontWeight="Bold" FontSize="16" />
<StackPanel Spacing="4">
<TextBlock Text="Source:" FontSize="12" Foreground="Gray" />
<TextBlock Name="SourceText" FontWeight="SemiBold" />
</StackPanel>
<StackPanel Spacing="4">
<TextBlock Text="Condition:" FontSize="12" Foreground="Gray" />
<TextBlock Name="ConditionText" />
</StackPanel>
<StackPanel Spacing="4">
<TextBlock Text="Comment:" FontSize="12" Foreground="Gray" />
<TextBox Name="CommentInput"
Watermark="Enter acknowledgment comment"
AcceptsReturn="True"
Height="60"
TextWrapping="Wrap" />
</StackPanel>
<TextBlock Name="ResultText" Foreground="Gray" />
<StackPanel Orientation="Horizontal" Spacing="8" HorizontalAlignment="Right">
<Button Name="AckButton" Content="Acknowledge" />
<Button Name="CancelButton" Content="Cancel" />
</StackPanel>
</StackPanel>
</Window>

View File

@@ -0,0 +1,67 @@
using Avalonia.Controls;
using Avalonia.Interactivity;
using Avalonia.Media;
using ZB.MOM.WW.OtOpcUa.Client.UI.ViewModels;
namespace ZB.MOM.WW.OtOpcUa.Client.UI.Views;
public partial class AckAlarmWindow : Window
{
private readonly AlarmsViewModel _alarmsVm;
private readonly AlarmEventViewModel _alarm;
public AckAlarmWindow()
{
InitializeComponent();
_alarmsVm = null!;
_alarm = null!;
}
public AckAlarmWindow(AlarmsViewModel alarmsVm, AlarmEventViewModel alarm)
{
InitializeComponent();
_alarmsVm = alarmsVm;
_alarm = alarm;
var sourceText = this.FindControl<TextBlock>("SourceText");
if (sourceText != null) sourceText.Text = alarm.SourceName;
var conditionText = this.FindControl<TextBlock>("ConditionText");
if (conditionText != null) conditionText.Text = $"{alarm.ConditionName} (Severity: {alarm.Severity})";
var ackButton = this.FindControl<Button>("AckButton");
if (ackButton != null) ackButton.Click += OnAckClicked;
var cancelButton = this.FindControl<Button>("CancelButton");
if (cancelButton != null) cancelButton.Click += OnCancelClicked;
}
private async void OnAckClicked(object? sender, RoutedEventArgs e)
{
var commentInput = this.FindControl<TextBox>("CommentInput");
var resultText = this.FindControl<TextBlock>("ResultText");
if (commentInput == null || resultText == null) return;
var comment = commentInput.Text ?? string.Empty;
resultText.Foreground = Brushes.Gray;
resultText.Text = "Acknowledging...";
var (success, message) = await _alarmsVm.AcknowledgeAlarmAsync(_alarm, comment);
if (success)
{
Close();
}
else
{
resultText.Foreground = Brushes.Red;
resultText.Text = message;
}
}
private void OnCancelClicked(object? sender, RoutedEventArgs e)
{
Close();
}
}

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.OtOpcUa.Client.UI.ViewModels"
x:Class="ZB.MOM.WW.OtOpcUa.Client.UI.Views.AlarmsView"
x:DataType="vm:AlarmsViewModel">
<DockPanel Margin="8">
<!-- Controls -->
<StackPanel DockPanel.Dock="Top" Spacing="8">
<TextBlock Text="Alarm Monitoring" FontWeight="Bold" />
<StackPanel Orientation="Horizontal" Spacing="8">
<TextBox Text="{Binding MonitoredNodeIdText}" Width="250" Watermark="Source Node ID (optional)" />
<NumericUpDown Value="{Binding Interval}" Minimum="100" Maximum="60000" Width="120" />
<Button Content="Subscribe" Command="{Binding SubscribeCommand}" />
<Button Content="Unsubscribe" Command="{Binding UnsubscribeCommand}" />
<Button Content="Refresh" Command="{Binding RefreshCommand}" />
</StackPanel>
</StackPanel>
<!-- Alarm Events -->
<DataGrid Name="AlarmsGrid"
ItemsSource="{Binding AlarmEvents}"
AutoGenerateColumns="False"
IsReadOnly="True"
HorizontalScrollBarVisibility="Auto"
Margin="0,8,0,0"
LoadingRow="OnDataGridLoadingRow">
<DataGrid.Columns>
<DataGridTextColumn Header="Time" Binding="{Binding Time, StringFormat='{}{0:yyyy-MM-dd HH:mm:ss}'}" Width="Auto" />
<DataGridTextColumn Header="Source" Binding="{Binding SourceName}" Width="Auto" />
<DataGridTextColumn Header="Condition" Binding="{Binding ConditionName}" Width="Auto" />
<DataGridTextColumn Header="Severity" Binding="{Binding Severity}" Width="Auto" />
<DataGridTextColumn Header="Message" Binding="{Binding Message}" Width="Auto" />
<DataGridCheckBoxColumn Header="Active" Binding="{Binding ActiveState}" Width="Auto" />
<DataGridCheckBoxColumn Header="Acked" Binding="{Binding AckedState}" Width="Auto" />
<DataGridCheckBoxColumn Header="Retain" Binding="{Binding Retain}" Width="Auto" />
</DataGrid.Columns>
</DataGrid>
</DockPanel>
</UserControl>

View File

@@ -0,0 +1,79 @@
using System.ComponentModel;
using Avalonia.Controls;
using Avalonia.Interactivity;
using Avalonia.Media;
using Avalonia.VisualTree;
using ZB.MOM.WW.OtOpcUa.Client.UI.ViewModels;
namespace ZB.MOM.WW.OtOpcUa.Client.UI.Views;
public partial class AlarmsView : UserControl
{
// Severity color bands (OPC UA severity 0-1000)
private static readonly IBrush InactiveBrush = new SolidColorBrush(Color.Parse("#F0F0F0")); // light grey
private static readonly IBrush LowBrush = new SolidColorBrush(Color.Parse("#DBEAFE")); // light blue (1-332)
private static readonly IBrush MediumBrush = new SolidColorBrush(Color.Parse("#FEF3C7")); // light yellow (333-665)
private static readonly IBrush HighBrush = new SolidColorBrush(Color.Parse("#FEE2E2")); // light red (666-899)
private static readonly IBrush CriticalBrush = new SolidColorBrush(Color.Parse("#FECACA")); // red (900-1000)
public AlarmsView()
{
InitializeComponent();
}
protected override void OnLoaded(RoutedEventArgs e)
{
base.OnLoaded(e);
var grid = this.FindControl<DataGrid>("AlarmsGrid");
if (grid == null) return;
var contextMenu = new ContextMenu();
var ackItem = new MenuItem { Header = "Acknowledge..." };
ackItem.Click += OnAcknowledgeClicked;
contextMenu.Items.Add(ackItem);
contextMenu.Opening += OnContextMenuOpening;
grid.ContextMenu = contextMenu;
}
private void OnDataGridLoadingRow(object? sender, DataGridRowEventArgs e)
{
if (e.Row.DataContext is AlarmEventViewModel alarm)
e.Row.Background = GetSeverityBrush(alarm);
}
private static IBrush GetSeverityBrush(AlarmEventViewModel alarm)
{
if (!alarm.ActiveState)
return InactiveBrush;
return alarm.Severity switch
{
>= 900 => CriticalBrush,
>= 666 => HighBrush,
>= 333 => MediumBrush,
_ => LowBrush
};
}
private void OnContextMenuOpening(object? sender, CancelEventArgs e)
{
var grid = this.FindControl<DataGrid>("AlarmsGrid");
if (grid?.SelectedItem is not AlarmEventViewModel alarm || !alarm.CanAcknowledge)
e.Cancel = true;
}
private void OnAcknowledgeClicked(object? sender, RoutedEventArgs e)
{
if (DataContext is not AlarmsViewModel vm) return;
var grid = this.FindControl<DataGrid>("AlarmsGrid");
if (grid?.SelectedItem is not AlarmEventViewModel alarm || !alarm.CanAcknowledge) return;
var parentWindow = this.FindAncestorOfType<Window>();
if (parentWindow == null) return;
var ackWindow = new AckAlarmWindow(vm, alarm);
ackWindow.ShowDialog(parentWindow);
}
}

View File

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

View File

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

View File

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

View File

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

View File

@@ -0,0 +1,162 @@
<Window xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:vm="using:ZB.MOM.WW.OtOpcUa.Client.UI.ViewModels"
xmlns:views="using:ZB.MOM.WW.OtOpcUa.Client.UI.Views"
x:Class="ZB.MOM.WW.OtOpcUa.Client.UI.Views.MainWindow"
x:DataType="vm:MainWindowViewModel"
Title="OPC UA Client"
Width="1200"
Height="800">
<DockPanel>
<!-- Top Connection Bar -->
<Border DockPanel.Dock="Top" Background="#F0F0F0" Padding="12">
<StackPanel Spacing="4">
<!-- Always visible: URL + Connect/Disconnect -->
<StackPanel Orientation="Horizontal" Spacing="8">
<StackPanel Spacing="2" VerticalAlignment="Bottom">
<TextBlock Text="Endpoint URL" FontSize="11" Foreground="Gray" />
<TextBox Text="{Binding EndpointUrl}"
Width="400"
Watermark="opc.tcp://host:port" />
</StackPanel>
<Button Content="Connect"
Command="{Binding ConnectCommand}"
VerticalAlignment="Bottom" Padding="16,6" />
<Button Content="Disconnect"
Command="{Binding DisconnectCommand}"
VerticalAlignment="Bottom" Padding="16,6" />
</StackPanel>
<!-- Expandable settings -->
<Expander Header="Connection Settings" Padding="0,4">
<StackPanel Spacing="10" Margin="4,8,4,4">
<!-- Row 1: Authentication -->
<StackPanel Orientation="Horizontal" Spacing="12">
<StackPanel Spacing="2">
<TextBlock Text="Username" FontSize="11" Foreground="Gray" />
<TextBox Text="{Binding Username}"
Width="160"
Watermark="(anonymous)" />
</StackPanel>
<StackPanel Spacing="2">
<TextBlock Text="Password" FontSize="11" Foreground="Gray" />
<TextBox Text="{Binding Password}"
Width="160"
Watermark="(none)"
PasswordChar="*" />
</StackPanel>
<StackPanel Spacing="2">
<TextBlock Text="Security Mode" FontSize="11" Foreground="Gray" />
<ComboBox ItemsSource="{Binding SecurityModes}"
SelectedItem="{Binding SelectedSecurityMode}"
Width="160" />
</StackPanel>
</StackPanel>
<!-- Row 2: Failover + Session -->
<StackPanel Orientation="Horizontal" Spacing="12">
<StackPanel Spacing="2">
<TextBlock Text="Failover URLs (comma-separated)" FontSize="11" Foreground="Gray" />
<TextBox Text="{Binding FailoverUrls}"
Width="400"
Watermark="opc.tcp://backup1:4840, opc.tcp://backup2:4840" />
</StackPanel>
<StackPanel Spacing="2">
<TextBlock Text="Session Timeout (s)" FontSize="11" Foreground="Gray" />
<NumericUpDown Value="{Binding SessionTimeoutSeconds}"
Minimum="1" Maximum="3600"
Width="120"
FormatString="0" />
</StackPanel>
</StackPanel>
<!-- Row 3: Certificates -->
<StackPanel Orientation="Horizontal" Spacing="12">
<StackPanel Spacing="2">
<TextBlock Text="Certificate Store Path" FontSize="11" Foreground="Gray" />
<StackPanel Orientation="Horizontal" Spacing="4">
<TextBox Text="{Binding CertificateStorePath}"
Width="370"
IsReadOnly="True"
Watermark="(default: AppData/LmxOpcUaClient/pki)" />
<Button Name="BrowseCertPathButton"
Content="..."
Width="30"
ToolTip.Tip="Browse for folder" />
</StackPanel>
</StackPanel>
<CheckBox IsChecked="{Binding AutoAcceptCertificates}"
Content="Auto-accept untrusted server certificates"
VerticalAlignment="Bottom"
Margin="0,0,0,4" />
</StackPanel>
</StackPanel>
</Expander>
<!-- Redundancy Info -->
<StackPanel Orientation="Horizontal"
Spacing="16"
IsVisible="{Binding RedundancyInfo, Converter={x:Static ObjectConverters.IsNotNull}}"
Margin="0,2,0,0">
<TextBlock Text="{Binding RedundancyInfo.Mode, StringFormat='Redundancy: {0}'}"
FontSize="11" Foreground="Gray" />
<TextBlock Text="{Binding RedundancyInfo.ServiceLevel, StringFormat='Service Level: {0}'}"
FontSize="11" Foreground="Gray" />
<TextBlock Text="{Binding RedundancyInfo.ApplicationUri, StringFormat='URI: {0}'}"
FontSize="11" Foreground="Gray" />
</StackPanel>
</StackPanel>
</Border>
<!-- Bottom Status Bar -->
<Border DockPanel.Dock="Bottom" Background="#F0F0F0" Padding="8,4">
<StackPanel Orientation="Horizontal" Spacing="20">
<TextBlock Text="{Binding StatusMessage}" />
<TextBlock Text="{Binding SessionLabel}" Foreground="Gray" />
<TextBlock Text="{Binding SubscriptionCount, StringFormat='Subscriptions: {0}'}" />
</StackPanel>
</Border>
<!-- Main Content -->
<Grid ColumnDefinitions="300,8,*">
<!-- Left: Browse Tree -->
<Border Grid.Column="0" BorderBrush="#CCCCCC" BorderThickness="0,0,1,0">
<DockPanel>
<TextBlock DockPanel.Dock="Top" Text="Browse Tree" FontWeight="Bold" Margin="8,8,8,4" />
<views:BrowseTreeView DataContext="{Binding BrowseTree}"
Name="BrowseTreePanel">
<views:BrowseTreeView.ContextMenu>
<ContextMenu Name="TreeContextMenu">
<MenuItem Header="Subscribe" Name="SubscribeMenuItem" />
<MenuItem Header="View History" Name="ViewHistoryMenuItem" />
<Separator />
<MenuItem Header="Monitor Alarms" Name="MonitorAlarmsMenuItem" />
</ContextMenu>
</views:BrowseTreeView.ContextMenu>
</views:BrowseTreeView>
</DockPanel>
</Border>
<!-- Splitter -->
<GridSplitter Grid.Column="1" Width="8" Background="Transparent" />
<!-- Right: Tab panels -->
<TabControl Grid.Column="2"
IsEnabled="{Binding IsConnected}"
SelectedIndex="{Binding SelectedTabIndex}">
<TabItem Header="Read/Write">
<views:ReadWriteView DataContext="{Binding ReadWrite}" />
</TabItem>
<TabItem Header="{Binding SubscriptionsTabHeader}">
<views:SubscriptionsView DataContext="{Binding Subscriptions}" />
</TabItem>
<TabItem Header="{Binding AlarmsTabHeader}">
<views:AlarmsView DataContext="{Binding Alarms}" />
</TabItem>
<TabItem Header="History">
<views:HistoryView DataContext="{Binding History}" />
</TabItem>
</TabControl>
</Grid>
</DockPanel>
</Window>

View File

@@ -0,0 +1,146 @@
using System.ComponentModel;
using System.Reflection;
using Avalonia.Controls;
using Avalonia.Interactivity;
using SkiaSharp;
using Svg.Skia;
using ZB.MOM.WW.OtOpcUa.Client.UI.ViewModels;
namespace ZB.MOM.WW.OtOpcUa.Client.UI.Views;
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
LoadIcon();
}
private void LoadIcon()
{
try
{
var assembly = Assembly.GetExecutingAssembly();
using var stream = assembly.GetManifestResourceStream("ZB.MOM.WW.OtOpcUa.Client.UI.Assets.app-icon.svg");
if (stream == null) return;
using var svg = new SKSvg();
svg.Load(stream);
if (svg.Picture == null) return;
var size = 64;
using var bitmap = new SKBitmap(size, size);
using var canvas = new SKCanvas(bitmap);
canvas.Clear(SKColors.Transparent);
var bounds = svg.Picture.CullRect;
var scale = Math.Min(size / bounds.Width, size / bounds.Height);
canvas.Translate((size - bounds.Width * scale) / 2, (size - bounds.Height * scale) / 2);
canvas.Scale(scale);
canvas.DrawPicture(svg.Picture);
using var image = SKImage.FromBitmap(bitmap);
using var data = image.Encode(SKEncodedImageFormat.Png, 100);
using var pngStream = new MemoryStream(data.ToArray());
Icon = new WindowIcon(pngStream);
}
catch
{
// Icon loading is best-effort
}
}
protected override void OnLoaded(RoutedEventArgs e)
{
base.OnLoaded(e);
var browseTreeView = this.FindControl<BrowseTreeView>("BrowseTreePanel");
var treeView = browseTreeView?.FindControl<TreeView>("BrowseTree");
if (treeView != null) treeView.SelectionChanged += OnTreeSelectionChanged;
var contextMenu = this.FindControl<ContextMenu>("TreeContextMenu");
if (contextMenu != null) contextMenu.Opening += OnTreeContextMenuOpening;
var subscribeItem = this.FindControl<MenuItem>("SubscribeMenuItem");
if (subscribeItem != null) subscribeItem.Click += OnSubscribeClicked;
var viewHistoryItem = this.FindControl<MenuItem>("ViewHistoryMenuItem");
if (viewHistoryItem != null) viewHistoryItem.Click += OnViewHistoryClicked;
var monitorAlarmsItem = this.FindControl<MenuItem>("MonitorAlarmsMenuItem");
if (monitorAlarmsItem != null) monitorAlarmsItem.Click += OnMonitorAlarmsClicked;
var browseCertPath = this.FindControl<Button>("BrowseCertPathButton");
if (browseCertPath != null) browseCertPath.Click += OnBrowseCertPathClicked;
}
private void OnTreeSelectionChanged(object? sender, SelectionChangedEventArgs e)
{
if (DataContext is not MainWindowViewModel vm || sender is not TreeView treeView) return;
vm.SelectedTreeNode = treeView.SelectedItem as TreeNodeViewModel;
vm.SelectedTreeNodes.Clear();
foreach (var item in treeView.SelectedItems)
if (item is TreeNodeViewModel node)
vm.SelectedTreeNodes.Add(node);
}
private void OnTreeContextMenuOpening(object? sender, CancelEventArgs e)
{
if (DataContext is not MainWindowViewModel vm) return;
vm.UpdateHistoryEnabledForSelection();
var subscribeItem = this.FindControl<MenuItem>("SubscribeMenuItem");
var viewHistoryItem = this.FindControl<MenuItem>("ViewHistoryMenuItem");
var monitorAlarmsItem = this.FindControl<MenuItem>("MonitorAlarmsMenuItem");
if (subscribeItem != null)
subscribeItem.IsEnabled = vm.IsConnected && vm.SelectedTreeNodes.Count > 0;
if (viewHistoryItem != null)
viewHistoryItem.IsEnabled = vm.IsHistoryEnabledForSelection;
if (monitorAlarmsItem != null)
monitorAlarmsItem.IsEnabled = vm.IsConnected && vm.SelectedTreeNodes.Count > 0;
}
private async void OnSubscribeClicked(object? sender, RoutedEventArgs e)
{
if (DataContext is MainWindowViewModel vm)
await vm.SubscribeSelectedNodesCommand.ExecuteAsync(null);
}
private void OnViewHistoryClicked(object? sender, RoutedEventArgs e)
{
if (DataContext is MainWindowViewModel vm)
vm.ViewHistoryForSelectedNodeCommand.Execute(null);
}
private async void OnMonitorAlarmsClicked(object? sender, RoutedEventArgs e)
{
if (DataContext is MainWindowViewModel vm)
await vm.MonitorAlarmsForSelectedNodeCommand.ExecuteAsync(null);
}
private async void OnBrowseCertPathClicked(object? sender, RoutedEventArgs e)
{
if (DataContext is not MainWindowViewModel vm) return;
var dialog = new OpenFolderDialog
{
Title = "Select Certificate Store Folder",
Directory = vm.CertificateStorePath
};
var result = await dialog.ShowAsync(this);
if (!string.IsNullOrEmpty(result))
vm.CertificateStorePath = result;
}
protected override void OnClosing(WindowClosingEventArgs e)
{
if (DataContext is MainWindowViewModel vm)
vm.SaveSettings();
base.OnClosing(e);
}
}

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

View File

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

View File

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

View File

@@ -0,0 +1,51 @@
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.VisualTree;
using ZB.MOM.WW.OtOpcUa.Client.UI.ViewModels;
namespace ZB.MOM.WW.OtOpcUa.Client.UI.Views;
public partial class SubscriptionsView : UserControl
{
public SubscriptionsView()
{
InitializeComponent();
}
protected override void OnLoaded(RoutedEventArgs e)
{
base.OnLoaded(e);
var grid = this.FindControl<DataGrid>("SubscriptionsGrid");
if (grid != null)
{
grid.DoubleTapped += OnGridDoubleTapped;
grid.SelectionChanged += OnGridSelectionChanged;
}
}
private void OnGridSelectionChanged(object? sender, SelectionChangedEventArgs e)
{
if (DataContext is not SubscriptionsViewModel vm || sender is not DataGrid grid) return;
vm.SelectedSubscriptions.Clear();
foreach (var item in grid.SelectedItems)
if (item is SubscriptionItemViewModel sub)
vm.SelectedSubscriptions.Add(sub);
vm.RemoveSubscriptionCommand.NotifyCanExecuteChanged();
}
private void OnGridDoubleTapped(object? sender, TappedEventArgs e)
{
if (DataContext is not SubscriptionsViewModel vm) return;
if (vm.SelectedSubscription is not { } item) return;
var parentWindow = this.FindAncestorOfType<Window>();
if (parentWindow == null) return;
var writeWindow = new WriteValueWindow(vm, item.NodeId, item.Value);
writeWindow.ShowDialog(parentWindow);
}
}

View File

@@ -0,0 +1,37 @@
<Window xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="ZB.MOM.WW.OtOpcUa.Client.UI.Views.WriteValueWindow"
Title="Write Value"
Width="420"
SizeToContent="Height"
MinHeight="280"
WindowStartupLocation="CenterOwner"
CanResize="False">
<StackPanel Margin="16" Spacing="12">
<TextBlock Text="Write Value to Node" FontWeight="Bold" FontSize="16" />
<StackPanel Spacing="4">
<TextBlock Text="Node ID:" FontSize="12" Foreground="Gray" />
<TextBlock Name="NodeIdText" FontWeight="SemiBold" />
</StackPanel>
<StackPanel Spacing="4">
<TextBlock Text="Current Value:" FontSize="12" Foreground="Gray" />
<TextBlock Name="CurrentValueText" />
</StackPanel>
<StackPanel Spacing="4">
<TextBlock Text="New Value:" FontSize="12" Foreground="Gray" />
<TextBox Name="WriteValueInput" Watermark="Enter value to write" />
</StackPanel>
<StackPanel Spacing="4">
<TextBlock Name="ResultText" Foreground="Gray" />
</StackPanel>
<StackPanel Orientation="Horizontal" Spacing="8" HorizontalAlignment="Right">
<Button Name="WriteButton" Content="Write" />
<Button Name="CloseButton" Content="Close" />
</StackPanel>
</StackPanel>
</Window>

View File

@@ -0,0 +1,77 @@
using Avalonia.Controls;
using Avalonia.Interactivity;
using Avalonia.Media;
using ZB.MOM.WW.OtOpcUa.Client.UI.ViewModels;
namespace ZB.MOM.WW.OtOpcUa.Client.UI.Views;
public partial class WriteValueWindow : Window
{
private readonly SubscriptionsViewModel _subscriptionsVm;
private readonly string _nodeId;
public WriteValueWindow()
{
InitializeComponent();
_subscriptionsVm = null!;
_nodeId = string.Empty;
}
public WriteValueWindow(SubscriptionsViewModel subscriptionsVm, string nodeId, string? currentValue)
{
InitializeComponent();
_subscriptionsVm = subscriptionsVm;
_nodeId = nodeId;
var nodeIdText = this.FindControl<TextBlock>("NodeIdText");
if (nodeIdText != null) nodeIdText.Text = nodeId;
var currentValueText = this.FindControl<TextBlock>("CurrentValueText");
if (currentValueText != null) currentValueText.Text = currentValue ?? "(null)";
// Pre-fill the write input with the current value
var writeInput = this.FindControl<TextBox>("WriteValueInput");
if (writeInput != null) writeInput.Text = currentValue ?? "";
var writeButton = this.FindControl<Button>("WriteButton");
if (writeButton != null) writeButton.Click += OnWriteClicked;
var closeButton = this.FindControl<Button>("CloseButton");
if (closeButton != null) closeButton.Click += OnCloseClicked;
}
private async void OnWriteClicked(object? sender, RoutedEventArgs e)
{
var input = this.FindControl<TextBox>("WriteValueInput");
var resultText = this.FindControl<TextBlock>("ResultText");
if (input == null || resultText == null) return;
var rawValue = input.Text;
if (string.IsNullOrEmpty(rawValue))
{
resultText.Foreground = Brushes.Red;
resultText.Text = "Please enter a value.";
return;
}
resultText.Foreground = Brushes.Gray;
resultText.Text = "Writing...";
var (success, message) = await _subscriptionsVm.ValidateAndWriteAsync(_nodeId, rawValue);
if (success)
{
Close();
}
else
{
resultText.Foreground = Brushes.Red;
resultText.Text = message;
}
}
private void OnCloseClicked(object? sender, RoutedEventArgs e)
{
Close();
}
}

View File

@@ -0,0 +1,37 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<RootNamespace>ZB.MOM.WW.OtOpcUa.Client.UI</RootNamespace>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="11.2.7"/>
<PackageReference Include="Avalonia.Desktop" Version="11.2.7"/>
<PackageReference Include="Avalonia.Svg.Skia" Version="11.2.0.2"/>
<PackageReference Include="Avalonia.Themes.Fluent" Version="11.2.7"/>
<PackageReference Include="Avalonia.Fonts.Inter" Version="11.2.7"/>
<PackageReference Include="Avalonia.Controls.DataGrid" Version="11.2.7"/>
<PackageReference Include="Avalonia.Diagnostics" Version="11.2.7"/>
<PackageReference Include="CommunityToolkit.Mvvm" Version="8.4.0"/>
<PackageReference Include="Serilog" Version="4.2.0"/>
<PackageReference Include="Serilog.Sinks.Console" Version="6.0.0"/>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\ZB.MOM.WW.OtOpcUa.Client.Shared\ZB.MOM.WW.OtOpcUa.Client.Shared.csproj"/>
</ItemGroup>
<ItemGroup>
<InternalsVisibleTo Include="ZB.MOM.WW.OtOpcUa.Client.UI.Tests"/>
</ItemGroup>
<ItemGroup>
<AvaloniaResource Include="Assets\**" Exclude="Assets\app-icon.svg" />
<EmbeddedResource Include="Assets\app-icon.svg" />
</ItemGroup>
</Project>