Tutorial: Plugin page
A plugin page is an entry in the navigation rail with a page of its own, like the NTP server or Edge storage. Behind it runs a core plugin: a service inside the OADM server that keeps state, talks to the devices and answers the page.
In this tutorial you create AXIS OS overview: a page with the AXIS OS version of the devices the user chooses. The Choose devices button picks them (All devices, tags or single devices); the server then reads them, 16 at a time, and the table fills in as soon as the read is done, on every client that shows the page.
1. Create it
Section titled “1. Create it”You need the .NET 10 SDK and an editor. Run:
dotnet new install Oadm.Plugin.Templatesdotnet new oadm-page -n MyCoolPagecd MyCoolPagedotnet tool restoredotnet buildThis creates the tutorial’s plugin under your name. It builds, its tests pass, and it runs. The code below is the
original; in your copy every FirmwareOverview reads MyCoolPage and the id is community.my-cool-page.
DirectoryMyCoolPage/
- MyCoolPage.slnx
DirectoryMyCoolPage/ the server part: the service
- MyCoolPage.csproj
- FirmwareModels.cs the rows, the state and the method names both parts share
- MyCoolPagePlugin.cs the service
DirectoryMyCoolPage.Client/ the client part: the page
- MyCoolPage.Client.csproj
- MyCoolPagePage.cs the rail entry
- MyCoolPageViewModel.cs
- MyCoolPageView.axaml
- MyCoolPageView.axaml.cs
DirectoryMyCoolPage.Tests/
- Fakes.cs the page’s context without a network
- MyCoolPageTests.cs
Directory.oadm/plugins/community.my-cool-page/ after a build: the plugin folder OADM loads
- …
2. How a page talks to its service
Section titled “2. How a page talks to its service”sequenceDiagram
participant Page as Page (client)
participant Plugin as Core plugin (server)
participant Devices
Page->>Plugin: WatchEventsAsync() (subscribe first)
Page->>Plugin: InvokeAsync("getState")
Plugin-->>Page: the whole state as JSON
Page->>Plugin: InvokeAsync("refresh", the chosen devices or "all")
Plugin-->>Page: returns at once
par in the background, 16 devices at a time
Plugin->>Devices: basicdeviceinfo
Devices-->>Plugin: AXIS OS version
end
Plugin-->>Page: Events.Publish("state", json), to the pages of the user's devices
- The page calls methods of the server part by name, with JSON in and out (
InvokeAsync). Every call carries the user:caller. - The server part pushes events to the pages that show it (
Events.Publish). Users with the same devices (all devices, or one device group) and several windows of one user all see the same table. - Events can be lost when the connection drops. So the page always subscribes, reads the whole state, then applies events, and starts over after a drop. A version number in the state lets the page ignore anything older than what it shows.
- Long work never blocks a method: the method starts it and returns; the result arrives as an event.
3. The project files
Section titled “3. The project files”Both projects use the plugin project SDK Oadm.Plugin.Sdk (the template writes the version you installed). It compiles
against the OADM SDK but never copies it: OADM provides it at runtime. The server project’s properties become the
plugin’s plugin.json: the OadmPluginId is the plugin’s key everywhere and never changes, the display name and
description are its row on the Plugins page, where administrators turn it on and off.
<Project Sdk="Oadm.Plugin.Sdk/x.y.z"> <!-- The server part: FirmwareOverview.Server.dll and its plugin.json, written from these properties. --> <PropertyGroup> <OadmPluginId>acme.firmware-overview</OadmPluginId> <Version>1.0.0</Version> <OadmDisplayName>AXIS OS overview</OadmDisplayName> <OadmDescription>The AXIS OS version of every device on one page.</OadmDescription> </PropertyGroup></Project>Add <OadmEnabledByDefault>false</OadmEnabledByDefault> when the plugin works in the background or is not for
everyone: it then stays off until an administrator turns it on.
The client project names the same plugin id and references the server project to share the models. The SDK adds Avalonia; the data grid comes without a version, the SDK takes the one of the OADM client.
<Project Sdk="Oadm.Plugin.Sdk/x.y.z"> <!-- The client part: FirmwareOverview.Client.dll in the same plugin folder as the server part. --> <PropertyGroup> <OadmPluginId>acme.firmware-overview</OadmPluginId> </PropertyGroup>
<ItemGroup> <PackageReference Include="Avalonia.Controls.DataGrid" /> <ProjectReference Include="..\FirmwareOverview\FirmwareOverview.csproj" /> </ItemGroup></Project>4. The contract
Section titled “4. The contract”The page and the service agree on three things: the method names, the event topic and the JSON of the state. Keeping them in one file of the server project means a typo cannot break the page.
using System.Text.Json;
namespace FirmwareOverview;
/// <summary>One row of the page: a device and its AXIS OS, or why it could not be read.</summary>public sealed record FirmwareRow(Guid DeviceId, string Address, string Model, string? Version, string? Error);
/// <summary>What the page asks to read: every device, or the chosen ones (the page never sends every id for "all").</summary>public sealed record RefreshRequest(bool All, IReadOnlyList<Guid> DeviceIds);
/// <summary>Everything the page shows. Version goes up with every change, so the page can ignore older states.</summary>public sealed record FirmwareState(int Version, bool Reading, IReadOnlyList<FirmwareRow> Rows);
/// <summary>The contract between the server part and the page: method names, the event topic and the JSON format.</summary>public static class FirmwareOverview{ public const string PluginId = "acme.firmware-overview";
public const string GetState = "getState"; public const string Refresh = "refresh"; public const string StateTopic = "state";
public const string NothingChosen = "Choose devices first.";
public static readonly JsonSerializerOptions Json = new(JsonSerializerDefaults.Web);}5. The service
Section titled “5. The service”Id,DisplayName,IconKey,Group: the rail entry.Groupplaces it under a heading of the rail (here Maintenance).StartAsyncruns when the server starts and when an administrator turns the plugin on. Keep the context and return at once; never wait for devices here.InvokeAsync(caller, ...)is the page’s backend.calleris the user of the call: a user may be limited to a device group, andcaller.Devicesandcaller.Vapixreach only that user’s devices. ThrowArgumentExceptionfor bad input andInvalidOperationExceptionfor a wrong state: the page gets the message. The overload withoutcallerstays only because the interface needs it.- One table per group: the state is kept by
caller.DeviceScopeKey(“all” or the group’s id), so users of one group share a table and never see another group’s devices. refreshchecks the request first: the page sends “all” or the chosen ids, never nothing. “All” iscaller.Devices.ListAsync, the user’s devices. An id the user cannot see is refused like an unknown one (DevicesNotAvailableException), before any request. A server can manage 100,000 devices, so a page never reads every device by itself.ctx.Jobs.Startruns the read after the call returns. The job reaches the devices throughjob.Owner, the user who started it; OADM ends it when the plugin stops or that user’s devices change.ReadAsyncreads the chosen devices with at most 16 at a time and 5 seconds each: never one by one, and never all at once.DeviceMessages.Refusalskips devices OADM must not contact: a changed certificate, a rejected password, no password yet, or not answering. The row says why, in the same words as the rest of OADM.owner.Vapix.CreateAsyncgives a client that is already logged in to the device. The server keeps it; never dispose it.Publishstores the new state with the next version and sends it to the pages of that group (PluginEventAudience.DeviceScope). When an administrator changes or deletes a group,DeviceScopes.Changedempties its table.InGroupkeeps only rows of devices the group has now (DeviceScopes.Contains(scope, id), a few lookups): a tag or site change can move a device out of the group beforeChangedcomes. The read skips such a device, and the published and the answered state leave it out.
using System.Collections.Concurrent;using System.Text.Json;
using Oadm.Sdk.Devices;using Oadm.Sdk.Plugins;
namespace FirmwareOverview;
/// <summary>/// The server part: keeps one table per device group (users with all devices share one), reads the devices the page/// chose when it asks, and pushes every new state to the pages of that group./// </summary>public sealed class FirmwareOverviewPlugin : ICorePlugin{ private readonly Lock _gate = new(); // reentrant private readonly Dictionary<string, FirmwareState> _states = []; // by caller.DeviceScopeKey private ICorePluginContext? _ctx; private int _version;
public string Id => FirmwareOverview.PluginId; public string DisplayName => "AXIS OS overview"; public string? IconKey => "firmware"; public CorePluginGroup Group => CorePluginGroup.Maintenance; public IReadOnlyList<ITaskPlugin> TaskPlugins => [];
public Task StartAsync(ICorePluginContext ctx, CancellationToken ct) { _ctx = ctx; ctx.DeviceScopes!.Changed += OnGroupChanged; return Task.CompletedTask; // nothing to start: the page asks for a read }
public Task StopAsync(CancellationToken ct) { _ctx!.DeviceScopes!.Changed -= OnGroupChanged; return Task.CompletedTask; // running reads are jobs: OADM ends them }
// OADM calls the overload with the user's call (below). public Task<string?> InvokeAsync(string method, string? payloadJson, CancellationToken ct) => throw new NotSupportedException("The page needs the user's call.");
public async Task<string?> InvokeAsync(ICallContext caller, string method, string? payloadJson, CancellationToken ct) { var scope = caller.DeviceScopeKey; switch (method) { case FirmwareOverview.GetState: return Serialize(InGroup(scope, StateOf(scope)));
case FirmwareOverview.Refresh: // Check the request before anything starts: the page sends "all" or the chosen ids, never nothing. var request = JsonSerializer.Deserialize<RefreshRequest>(payloadJson ?? "null", FirmwareOverview.Json); if (request is null || (!request.All && (request.DeviceIds is null || request.DeviceIds.Count == 0))) { throw new ArgumentException(FirmwareOverview.NothingChosen); }
// Only the user's devices: "all" are the devices the user sees, any other id is refused. var devices = request.All ? await caller.Devices.ListAsync(ct) : await FindAsync(caller, request.DeviceIds, ct); if (!TryBeginRead(scope)) { throw new InvalidOperationException("The devices are being read already."); }
// The read takes a while: a job runs it after the call, and the page follows it through events. try { _ctx!.Jobs!.Start(caller, "read", (job, token) => ReadAsync(job.Owner, scope, devices, token)); } catch { Publish(scope, StateOf(scope) with { Reading = false }); // no job: never "reading" for ever throw; }
return null;
default: throw new ArgumentException("Unknown method " + method); } }
/// <summary>The chosen devices; an id the user cannot see is refused like an unknown one, before any request.</summary> private static async Task<List<IDeviceInfo>> FindAsync(ICallContext caller, IReadOnlyList<Guid> ids, CancellationToken ct) { var devices = new List<IDeviceInfo>(ids.Count); foreach (var id in ids.Distinct()) { devices.Add(await caller.Devices.FindAsync(id, ct) ?? throw new DevicesNotAvailableException()); }
return devices; }
/// <summary>Reads the devices, 16 at a time, 5 s each, through the owner's call; devices OADM cannot log in to are not contacted.</summary> private async Task ReadAsync(ICallContext owner, string scope, IReadOnlyList<IDeviceInfo> devices, CancellationToken ct) { var rows = new ConcurrentBag<FirmwareRow>(); try { await Parallel.ForEachAsync(devices, new ParallelOptions { MaxDegreeOfParallelism = 16, CancellationToken = ct }, async (device, token) => { if (InGroup(scope, device.Id)) // a device that left the group meanwhile is not read { rows.Add(await ReadAsync(owner, device, token)); } }); } catch (OperationCanceledException) { Publish(scope, StateOf(scope) with { Reading = false }); // the job ended early: keep the old table return; }
Publish(scope, StateOf(scope) with { Reading = false, Rows = [.. rows.OrderBy(r => r.Address, StringComparer.OrdinalIgnoreCase)] }); }
private static async Task<FirmwareRow> ReadAsync(ICallContext owner, IDeviceInfo device, CancellationToken ct) { var model = device.Model ?? ""; if (DeviceMessages.Refusal(device, refuseUnreachable: true) is { } refusal) { return new FirmwareRow(device.Id, device.Address, model, null, refusal); }
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct); timeout.CancelAfter(TimeSpan.FromSeconds(5)); try { var vapix = await owner.Vapix.CreateAsync(device.Id, timeout.Token); var info = await vapix.GetBasicDeviceInfoAsync(timeout.Token); return new FirmwareRow(device.Id, device.Address, model, info.Version, null); } catch (OperationCanceledException) when (!ct.IsCancellationRequested) { return new FirmwareRow(device.Id, device.Address, model, null, DeviceMessages.TimedOut); } catch (Exception ex) when (ex is not OperationCanceledException) { return new FirmwareRow(device.Id, device.Address, model, null, ex.Message); } }
/// <summary>Whether the device is in the group now (a few lookups, no request): a tag or site change can move it out.</summary> private bool InGroup(string scope, Guid deviceId) => _ctx!.DeviceScopes!.Contains(scope, deviceId);
/// <summary>The state with only the rows of devices the group has now.</summary> private FirmwareState InGroup(string scope, FirmwareState state) => state with { Rows = [.. state.Rows.Where(r => InGroup(scope, r.DeviceId))] };
/// <summary> /// A group's devices changed or the group was deleted: its table may show devices it no longer has. A read that runs /// keeps running (and the page keeps showing it), so only the rows go. /// </summary> private void OnGroupChanged(object? sender, string scope) => Publish(scope, StateOf(scope) with { Rows = [] });
private FirmwareState StateOf(string scope) { lock (_gate) { return _states.GetValueOrDefault(scope) ?? new FirmwareState(_version, false, []); } }
private bool TryBeginRead(string scope) { lock (_gate) { var state = StateOf(scope); if (state.Reading) { return false; }
Publish(scope, state with { Reading = true }); return true; } }
/// <summary>Stores the new state with the next version and sends it to the pages of the group (only its devices).</summary> private void Publish(string scope, FirmwareState state) { string json; lock (_gate) { state = InGroup(scope, state) with { Version = ++_version }; _states[scope] = state; json = Serialize(state); }
_ctx?.Events?.Publish(FirmwareOverview.StateTopic, json, PluginEventAudience.DeviceScope(scope)); }
private static string Serialize(FirmwareState state) => JsonSerializer.Serialize(state, FirmwareOverview.Json);}The context offers more: Settings (stored JSON of the plugin, e.g. its configuration), Secrets (encrypt passwords you
store), DataDirectory (a private folder for files) and Logger (the server log). The call offers caller.Tasks (start
tasks on the user’s devices, which show in the tasks pane) and caller.Has(permission).
6. The page
Section titled “6. The page”The client loader finds the class that implements ICorePluginPage with your plugin id and adds the rail entry.
CreateView runs for every view of the page: the rail and each Open in new window get their own context and view
model, so keep all state in the view model.
using Avalonia.Controls;
using Oadm.Sdk.Client;
namespace FirmwareOverview.Client;
/// <summary>Found by the client loader: the rail entry and its page.</summary>public sealed class FirmwareOverviewPage : ICorePluginPage{ public string PluginId => FirmwareOverview.PluginId;
public string Title => "AXIS OS overview";
// Called for every view of the page (the rail page and each "Open in new window"), each with its own context. public Control CreateView(ICorePluginClientContext ctx) => new FirmwareOverviewView { DataContext = new FirmwareOverviewViewModel(ctx) };}The view model holds the page’s state. RunAsync is the subscribe, read, apply loop described above; the SDK runs it
(ctx.RunAsync of PluginEventWatch: it waits 2 s after a drop and starts over). GuardedRun.RunAsync returns the
text of a failed call instead of throwing. The rows go into a RangeObservableCollection and are replaced in one step,
which keeps the grid fast with thousands of rows.
PageDeviceChoice is the device choice of the page: it starts with the Devices page selection, else the last choice on
this computer, else with nothing. While nothing is chosen the page reads nothing and Refresh is off. ButtonText is the
text of the device choice button (“Choose devices”, “Selected devices: Tag Building A”); Resolve() gives the devices of the
choice now. All devices goes to the server as “all”, not as every id.
using System.Text.Json;
using CommunityToolkit.Mvvm.ComponentModel;using CommunityToolkit.Mvvm.Input;
using Oadm.Sdk.Client;using Oadm.Sdk.Client.Collections;using Oadm.Sdk.Client.Controls;using Oadm.Sdk.Devices;
namespace FirmwareOverview.Client;
/// <summary>/// The page: reads the state from the server part, then follows its events. The devices come from the page's device/// choice (the Devices page selection to start with); nothing is read before one. Refresh asks for a new read./// </summary>public sealed partial class FirmwareOverviewViewModel : ObservableObject, IDisposable{ private readonly ICorePluginClientContext _ctx; private readonly CancellationTokenSource _stop = new(); private Task? _run; private int _version = -1;
public FirmwareOverviewViewModel(ICorePluginClientContext ctx) { _ctx = ctx; Devices = new PageDeviceChoice(ctx); Devices.PropertyChanged += (_, _) => RefreshCommand.NotifyCanExecuteChanged(); }
/// <summary>The devices the page reads: the purple button "Choose devices" / "Selected devices: Tag Building A".</summary> public PageDeviceChoice Devices { get; }
/// <summary>Opens the device picker; set by the view, which knows the window.</summary> public Func<Task<bool>>? PickDevices { get; set; }
/// <summary>The table. One reset per update, also with thousands of devices.</summary> public RangeObservableCollection<FirmwareRow> Rows { get; } = [];
[ObservableProperty] [NotifyCanExecuteChangedFor(nameof(RefreshCommand))] public partial bool IsReading { get; private set; }
[ObservableProperty] public partial string? ErrorText { get; private set; }
/// <summary>"12 devices, 2 not read".</summary> [ObservableProperty] public partial string Summary { get; private set; } = "";
/// <summary>Starts once, when the view is shown first.</summary> public void Start() => _run ??= RunAsync();
/// <summary> /// Subscribe, read the whole state, apply the events; after a dropped connection wait 2 s and do it again. The SDK /// runs the loop (<see cref="PluginEventWatch"/>) until the page is disposed. /// </summary> private Task RunAsync() => _ctx.RunAsync( async ct => Apply(await _ctx.InvokeAsync(FirmwareOverview.GetState, null, ct)), item => { if (item.Topic == FirmwareOverview.StateTopic) { Apply(item.PayloadJson); } }, new PluginEventWatchOptions { Failed = ex => ErrorText = ServerErrors.Message(ex) }, _stop.Token);
/// <summary>The purple button: choose the devices, then read them.</summary> [RelayCommand] private async Task ChooseDevicesAsync() { if (PickDevices is { } pick && await pick() && CanRefresh()) { await RefreshAsync(); } }
[RelayCommand(CanExecute = nameof(CanRefresh))] private async Task RefreshAsync() { ErrorText = null;
// Whatever goes wrong comes back as the text to show (the server's reason), never as a crash of the page. ErrorText = await GuardedRun.RunAsync( () => { // All devices go as "all", not as every id: one short request also at the device limit. var request = Devices.Choice.Kind == DeviceChoiceKind.All ? new RefreshRequest(true, []) : new RefreshRequest(false, [.. Devices.Resolve().Select(d => d.Id)]); return _ctx.InvokeAsync(FirmwareOverview.Refresh, JsonSerializer.Serialize(request, FirmwareOverview.Json), _stop.Token); }, GuardedCancel.Ignore); }
private bool CanRefresh() => !IsReading && !Devices.IsEmpty;
/// <summary>Shows a state from the server, unless an equal or newer one is shown already.</summary> public void Apply(string? json) { if (json is null || JsonSerializer.Deserialize<FirmwareState>(json, FirmwareOverview.Json) is not { } state || state.Version <= _version) { return; }
_version = state.Version; IsReading = state.Reading; ErrorText = null; Rows.ReplaceAll(state.Rows); var failed = state.Rows.Count(r => r.Error is not null); Summary = state.Rows.Count switch { 0 when Devices.IsEmpty => "Choose devices to read their AXIS OS.", 0 => "Click Refresh to read the devices.", 1 => "1 device", _ => $"{state.Rows.Count:N0} devices", } + (failed > 0 ? $", {failed:N0} not read" : ""); }
public void Dispose() { _stop.Cancel(); _stop.Dispose(); }}The view uses the shared controls: the device choice button first (ui:ToolbarButton with the devices icon), a toolbar button, the progress row, a status chip for problems, the error text below
the table. ui:PageHeader.Subtitle puts one short sentence next to the page title; the page itself starts with its
content. No colors or sizes of its own, so the page looks right in dark and light.
<UserControl xmlns="https://github.com/avaloniaui" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:ui="using:Oadm.Sdk.Client.Controls" xmlns:vm="using:FirmwareOverview.Client" xmlns:m="using:FirmwareOverview" x:Class="FirmwareOverview.Client.FirmwareOverviewView" x:DataType="vm:FirmwareOverviewViewModel" ui:PageHeader.Subtitle="The AXIS OS of the chosen devices."> <Grid RowDefinitions="Auto,Auto,*,Auto"> <StackPanel Grid.Row="0" Orientation="Horizontal" Spacing="12"> <ui:ToolbarButton IconKey="devices" Text="{Binding Devices.ButtonText}" Command="{Binding ChooseDevicesCommand}" IsEnabled="{Binding !IsReading}" /> <ui:ToolbarButton IconKey="refresh" Text="Refresh" Command="{Binding RefreshCommand}" /> <TextBlock Classes="secondary" VerticalAlignment="Center" Text="{Binding Summary}" /> </StackPanel>
<ui:ProgressRow Grid.Row="1" Margin="0,8,0,0" Text="Reading devices" IsActive="{Binding IsReading}" IsVisible="{Binding IsReading}" />
<DataGrid Grid.Row="2" Margin="0,8,0,0" ItemsSource="{Binding Rows}" IsReadOnly="True" CanUserSortColumns="True"> <DataGrid.Columns> <DataGridTextColumn Header="Address" Width="180" Binding="{Binding Address}" x:DataType="m:FirmwareRow" /> <DataGridTextColumn Header="Model" Width="160" Binding="{Binding Model}" x:DataType="m:FirmwareRow" /> <DataGridTextColumn Header="AXIS OS" Width="140" Binding="{Binding Version}" x:DataType="m:FirmwareRow" /> <DataGridTemplateColumn Header="Problem" Width="*"> <DataGridTemplateColumn.CellTemplate> <DataTemplate x:DataType="m:FirmwareRow"> <ui:StatusChip Margin="10,0" Text="{Binding Error}" IsError="True" IsVisible="{Binding Error, Converter={x:Static ObjectConverters.IsNotNull}}" /> </DataTemplate> </DataGridTemplateColumn.CellTemplate> </DataGridTemplateColumn> </DataGrid.Columns> </DataGrid>
<TextBlock Grid.Row="3" Margin="0,8,0,0" Classes="error" TextWrapping="Wrap" Text="{Binding ErrorText}" IsVisible="{Binding ErrorText, Converter={x:Static ObjectConverters.IsNotNull}}" /> </Grid></UserControl>The device picker needs the window, so the view hands the view model a way to open it (PickDevices).
using Avalonia;using Avalonia.Controls;using Avalonia.Markup.Xaml;
namespace FirmwareOverview.Client;
public sealed partial class FirmwareOverviewView : UserControl{ public FirmwareOverviewView() => AvaloniaXamlLoader.Load(this);
// The picker needs the window: the view hands the view model a way to open it. protected override void OnDataContextChanged(EventArgs e) { base.OnDataContextChanged(e); if (DataContext is FirmwareOverviewViewModel vm) { vm.PickDevices = async () => TopLevel.GetTopLevel(this) is Window owner && await vm.Devices.PickAsync(owner, "Choose devices"); } }
// The host disposes the view model when the page or its window closes; that ends the watch. protected override void OnAttachedToVisualTree(VisualTreeAttachmentEventArgs e) { base.OnAttachedToVisualTree(e); (DataContext as FirmwareOverviewViewModel)?.Start(); }}7. The tests
Section titled “7. The tests”FakeCoreContext of the package Oadm.Sdk.Testing stands in for the server: a device list, a FakeCamera per device,
and a channel that collects the published events. server.InvokeAsync(plugin, call, ...) calls the service like OADM
does, as server.CallAsAllDevices() or server.CallAsGroup([ids]). FakePageContext connects the page straight to the
service, so the page test runs the whole round trip without a network.
using System.Runtime.CompilerServices;
using Oadm.Sdk.Client;using Oadm.Sdk.Devices;using Oadm.Sdk.Plugins;using Oadm.Sdk.Testing;
namespace FirmwareOverview.Tests;
/// <summary>The page's context: calls go straight to the server part, events come from the server's fake context (Oadm.Sdk.Testing).</summary>internal sealed class FakePageContext(FirmwareOverviewPlugin plugin, FakeCoreContext server) : ICorePluginClientContext{ public IReadOnlyList<IDeviceInfo> Devices => server.DeviceList;
/// <summary>The Devices page selection: the page's device choice starts with it.</summary> public IReadOnlyList<IDeviceInfo> SelectedDevices { get; set; } = [];
/// <summary>Calls the server part like OADM does, as a user with all devices.</summary> public Task<string?> InvokeAsync(string method, string? payloadJson, CancellationToken ct) => server.InvokeAsync(plugin, server.CallAsAllDevices(), method, payloadJson, ct);
public async IAsyncEnumerable<PluginEvent> WatchEventsAsync([EnumeratorCancellation] CancellationToken ct) { await foreach (var item in server.Published.Reader.ReadAllAsync(ct)) { yield return item; } }}Test the read of the chosen devices, “all” and a request without devices, the devices that must not be contacted, a bad
method, that the page reads nothing before a choice, that it ignores older states, and what a user with a device group
reads and sees. The canary (PluginCanary) calls every method as a user whose group holds one device, with a device
outside the group and an unknown id in every id field: name each method once, see
Device groups.
using System.Text.Json;
using FirmwareOverview.Client;using Oadm.Sdk.Devices;using Oadm.Sdk.Plugins;using Oadm.Sdk.Testing;
namespace FirmwareOverview.Tests;
public sealed class FirmwareOverviewTests{ [Fact] public async Task Refresh_reads_the_chosen_devices_and_publishes_the_table() { var (plugin, server) = await StartAsync(("10.0.0.48", DeviceStatus.Ok, "12.11.77"), ("10.0.0.49", DeviceStatus.Ok, "11.11.124"), ("10.0.0.50", DeviceStatus.Ok, "10.12.1")); var chosen = server.DeviceList.Take(2).Select(d => d.Id).ToList();
await CallAsync(server, plugin, FirmwareOverview.Refresh, new RefreshRequest(false, chosen)); var state = await NextStateAsync(server, s => !s.Reading);
Assert.Equal(["10.0.0.48 12.11.77", "10.0.0.49 11.11.124"], state.Rows.Select(r => $"{r.Address} {r.Version}")); Assert.All(state.Rows, r => Assert.Null(r.Error)); Assert.Equal(0, server.Cameras[server.DeviceList[2].Id].Reads); // not chosen: not contacted }
[Fact] public async Task All_devices_is_one_short_request_and_nothing_chosen_is_refused() { var (plugin, server) = await StartAsync(("10.0.0.48", DeviceStatus.Ok, "12.11.77"), ("10.0.0.49", DeviceStatus.Ok, "11.11.124"));
await CallAsync(server, plugin, FirmwareOverview.Refresh, new RefreshRequest(true, [])); Assert.Equal(2, (await NextStateAsync(server, s => !s.Reading)).Rows.Count);
var refused = await Assert.ThrowsAsync<ArgumentException>(() => CallAsync(server, plugin, FirmwareOverview.Refresh, new RefreshRequest(false, []))); Assert.Equal(FirmwareOverview.NothingChosen, refused.Message); await Assert.ThrowsAsync<ArgumentException>(() => CallAsync(server, plugin, FirmwareOverview.Refresh, null)); }
[Fact] public async Task Devices_OADM_cannot_log_in_to_are_not_contacted() { var (plugin, server) = await StartAsync(("10.0.0.50", DeviceStatus.CredentialsRequired, "12.11.77"));
await CallAsync(server, plugin, FirmwareOverview.Refresh, new RefreshRequest(true, [])); var row = Assert.Single((await NextStateAsync(server, s => !s.Reading)).Rows);
Assert.Equal(DeviceMessages.CredentialsRequired, row.Error); Assert.Equal(0, server.Cameras.Values.Single().Reads); }
[Fact] public async Task A_read_the_host_refuses_to_start_leaves_the_table_ready_for_the_next_one() { var (plugin, server) = await StartAsync(("10.0.0.48", DeviceStatus.Ok, "12.11.77")); server.FakeJobs.StartFailure = new InvalidOperationException("Too many jobs.");
await Assert.ThrowsAsync<InvalidOperationException>(() => CallAsync(server, plugin, FirmwareOverview.Refresh, new RefreshRequest(true, []))); Assert.False((await NextStateAsync(server, s => !s.Reading)).Reading);
server.FakeJobs.StartFailure = null; await CallAsync(server, plugin, FirmwareOverview.Refresh, new RefreshRequest(true, [])); // not "being read already" Assert.Single((await NextStateAsync(server, s => !s.Reading && s.Rows.Count > 0)).Rows); }
[Fact] public async Task An_unknown_method_is_refused() { var (plugin, server) = await StartAsync(); await Assert.ThrowsAsync<ArgumentException>(() => CallAsync(server, plugin, "format", null)); }
[Fact] public async Task The_page_reads_nothing_before_a_choice() { var (plugin, server) = await StartAsync(("10.0.0.48", DeviceStatus.Ok, "12.11.77")); using var page = new FirmwareOverviewViewModel(new FakePageContext(plugin, server));
Assert.True(page.Devices.IsEmpty); Assert.Equal("Choose devices", page.Devices.ButtonText); Assert.False(page.RefreshCommand.CanExecute(null)); }
[Fact] public async Task The_page_shows_the_table_and_ignores_older_states() { var (plugin, server) = await StartAsync(("10.0.0.48", DeviceStatus.Ok, "12.11.77")); var ctx = new FakePageContext(plugin, server) { SelectedDevices = [server.DeviceList[0]] }; using var page = new FirmwareOverviewViewModel(ctx); // starts with the Devices page selection
Assert.Equal("Selected devices: 10.0.0.48", page.Devices.ButtonText); await page.RefreshCommand.ExecuteAsync(null); var state = await NextStateAsync(server, s => !s.Reading); page.Apply(JsonSerializer.Serialize(state, FirmwareOverview.Json)); page.Apply(JsonSerializer.Serialize(state with { Version = 1, Rows = [] }, FirmwareOverview.Json)); // older: ignored
Assert.Equal("12.11.77", Assert.Single(page.Rows).Version); Assert.Equal("1 device", page.Summary); Assert.False(page.IsReading); }
[Fact] public async Task A_user_with_a_device_group_reads_and_sees_only_its_devices() { var (plugin, server) = await StartAsync(("10.0.0.48", DeviceStatus.Ok, "12.11.77"), ("10.0.0.49", DeviceStatus.Ok, "11.11.124")); var key = server.FakeScopes.Add("Building B", [server.DeviceList[0].Id]); var operatorB = FakeCallContext.WithGroup(server, [server.DeviceList[0].Id], groupId: key);
await CallAsync(server, plugin, FirmwareOverview.Refresh, new RefreshRequest(true, []), operatorB); var state = await NextStateAsync(server, s => !s.Reading);
Assert.Equal("10.0.0.48", Assert.Single(state.Rows).Address); // "all" = the user's devices Assert.Equal(0, server.Cameras[server.DeviceList[1].Id].Reads); Assert.Empty(server.EventsSeenBy(server.CallAsAllDevices())); // the table of the group goes to its users only }
[Fact] public async Task A_device_that_left_the_group_drops_out_of_its_table() { var (plugin, server) = await StartAsync(("10.0.0.48", DeviceStatus.Ok, "12.11.77"), ("10.0.0.49", DeviceStatus.Ok, "11.11.124")); var ids = server.DeviceList.Select(d => d.Id).ToList(); var key = server.FakeScopes.Add("Building B", ids); await CallAsync(server, plugin, FirmwareOverview.Refresh, new RefreshRequest(true, []), FakeCallContext.WithGroup(server, ids, groupId: key)); Assert.Equal(2, (await NextStateAsync(server, s => !s.Reading)).Rows.Count);
// A tag change moves 10.0.0.49 out of the group; the plugin has not been told yet. server.FakeScopes.Add("Building B", [ids[0]], key); var now = FakeCallContext.WithGroup(server, [ids[0]], groupId: key); var state = JsonSerializer.Deserialize<FirmwareState>((await server.InvokeAsync(plugin, now, FirmwareOverview.GetState, null))!, FirmwareOverview.Json)!;
Assert.Equal("10.0.0.48", Assert.Single(state.Rows).Address); }
[Fact] public async Task A_group_change_during_a_read_keeps_the_page_reading() { var server = new FakeCoreContext(); var camera = new HeldCamera(); server.Add(new FakeDevice { Address = "10.0.0.48", Status = DeviceStatus.Ok }, camera); var plugin = new FirmwareOverviewPlugin(); await plugin.StartAsync(server, CancellationToken.None); var ids = server.DeviceList.Select(d => d.Id).ToList(); var key = server.FakeScopes.Add("Building B", ids);
await CallAsync(server, plugin, FirmwareOverview.Refresh, new RefreshRequest(true, []), FakeCallContext.WithGroup(server, ids, groupId: key)); await NextStateAsync(server, s => s.Reading); await camera.Started.Task.WaitAsync(TimeSpan.FromSeconds(30)); // the read is on the camera now
// The group changes while the read runs: the old rows go, the page keeps showing that it reads. server.FakeScopes.Delete(key); var changed = await NextStateAsync(server, _ => true); Assert.True(changed.Reading); Assert.Empty(changed.Rows);
camera.Release.SetResult(); Assert.False((await NextStateAsync(server, s => !s.Reading)).Reading); }
/// <summary>A camera whose firmware read waits until the test releases it (no timeout can end it first).</summary> private sealed class HeldCamera : FakeCamera { public TaskCompletionSource Started { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
public TaskCompletionSource Release { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
public override async Task<Oadm.Sdk.Vapix.BasicDeviceInfo> GetBasicDeviceInfoAsync(CancellationToken ct) { Started.TrySetResult(); await Release.Task; return Info; } }
/// <summary>The canary: a user whose group holds only "inside" calls every method with "outside" and with an unknown id.</summary> [Fact] public async Task No_method_reaches_a_device_outside_the_users_group() { var (plugin, server) = await StartAsync(("10.0.0.48", DeviceStatus.Ok, "12.11.77"), ("10.0.0.49", DeviceStatus.Ok, "11.11.124"));
await new PluginCanary(server, plugin, inside: server.DeviceList[0], outside: server.DeviceList[1]) .Method(FirmwareOverview.Refresh, """{"all":false,"deviceIds":["{inside}","{device}"]}""") .WithoutDevices(FirmwareOverview.GetState, "the table of the user's devices") .RunAsync(); }
private static async Task<(FirmwareOverviewPlugin Plugin, FakeCoreContext Server)> StartAsync(params (string Address, DeviceStatus Status, string Version)[] devices) { var server = new FakeCoreContext(); foreach (var (address, status, version) in devices) { var camera = new FakeCamera(); camera.Info = camera.Info with { Version = version }; server.Add(new FakeDevice { Address = address, Status = status }, camera); }
var plugin = new FirmwareOverviewPlugin(); await plugin.StartAsync(server, CancellationToken.None); return (plugin, server); }
/// <summary>Calls the server part like OADM does: as <paramref name="user"/>, else as a user with all devices.</summary> private static Task<string?> CallAsync(FakeCoreContext server, FirmwareOverviewPlugin plugin, string method, RefreshRequest? request, ICallContext? user = null) => server.InvokeAsync(plugin, user ?? server.CallAsAllDevices(), method, request is null ? null : JsonSerializer.Serialize(request, FirmwareOverview.Json));
/// <summary>The next published state that matches, within 30 s (a busy test machine may be slow).</summary> private static async Task<FirmwareState> NextStateAsync(FakeCoreContext server, Func<FirmwareState, bool> match) { using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(30)); await foreach (var item in server.Published.Reader.ReadAllAsync(timeout.Token)) { var state = JsonSerializer.Deserialize<FirmwareState>(item.PayloadJson!, FirmwareOverview.Json)!; if (match(state)) { return state; } }
throw new TimeoutException(); }}8. Run it
Section titled “8. Run it”dotnet testdotnet oadm dev startdev start runs an OADM server for development in this terminal, with its own data in .oadm/, and loads your plugin;
a new build restarts it. In a second terminal, dotnet oadm dev client opens the client against it: create the
administrator on the first start and add a few cameras. The rail shows MyCoolPage under Maintenance. Click Choose devices and choose some: the progress row shows while
the server reads, then the table fills in. Open the page in a second window from the rail entry’s context menu and refresh again: both update.
9. Make it yours
Section titled “9. Make it yours”- The rail entry:
DisplayName,IconKey,Group. - The state: the row and state records, and what
ReadAsyncreads per device. - The methods: one constant per method, one case in
InvokeAsync, one command in the view model, one line in the canary. - The view: columns, buttons, a card layout of your own (set
HasOwnCardsin the page class). - Settings that stay: store them with
ctx.Settings.SetAsync("config", json, ct)and read them inStartAsync. - The tests: one per method and per kind of device answer.
10. Share it
Section titled “10. Share it”dotnet oadm deploy --installed puts it into the OADM installed on your computer; dotnet oadm pack writes the
.oadmplugin file for others. Both are explained in Develop with the .NET SDK.
To ship it with OADM, open a pull request on GitHub with the plugin, its tests and a README.md in its folder that says
what it does and on which devices you tried it.