Compare commits

...

6 Commits

Author SHA1 Message Date
Joseph Doherty c4435e4fd6 feat(runtime): route driver values to folder-scoped equipment NodeIds (live-value delivery)
v2-ci / build (push) Failing after 44s
v2-ci / unit-tests (tests/Core/ZB.MOM.WW.OtOpcUa.Cluster.Tests) (push) Has been skipped
v2-ci / unit-tests (tests/Server/ZB.MOM.WW.OtOpcUa.ControlPlane.Tests) (push) Has been skipped
v2-ci / unit-tests (tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests) (push) Has been skipped
v2-ci / unit-tests (tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests) (push) Has been skipped
v2-ci / unit-tests (tests/Server/ZB.MOM.WW.OtOpcUa.Security.Tests) (push) Has been skipped
v2-ci / integration (tests/Server/ZB.MOM.WW.OtOpcUa.Host.IntegrationTests) (push) Has been skipped
v2-ci / integration (tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests) (push) Has been skipped
2026-06-13 06:32:38 -04:00
Joseph Doherty 5432d8a021 refactor(opcua): repoint Phase7Applier + VirtualTagHostActor to shared EquipmentNodeIds 2026-06-13 06:31:44 -04:00
Joseph Doherty da1accceff feat(runtime): carry DriverInstanceId on AttributeValuePublished (live-value routing key) 2026-06-13 06:27:52 -04:00
Joseph Doherty 26816fd17e feat(commons): EquipmentNodeIds — single source of truth for folder-scoped equipment NodeIds 2026-06-13 06:26:59 -04:00
Joseph Doherty 891f875f6a docs(live-values): Phase plan — equipment-tag live-value delivery (6 tasks)
Shared EquipmentNodeIds helper → repoint Phase7Applier+VirtualTagHostActor →
DriverInstanceId on AttributeValuePublished → DriverHostActor (DriverInstanceId,
FullName)->NodeId[] map + ForwardToMux resolution + TestKit → live Modbus /run.
Runtime-only, no migration. Co-located .tasks.json.
2026-06-13 06:24:38 -04:00
Joseph Doherty 7e9eb5d17a docs(live-values): design — equipment-tag live-value delivery (FullName→NodeId router)
Mirror VirtualTagHostActor's _nodeIdByVtag pattern for driver values: a shared
EquipmentNodeIds helper (kills the duplicated formula), DriverInstanceId on
AttributeValuePublished, and a (DriverInstanceId,FullName)->NodeId[] map built +
resolved in DriverHostActor.ForwardToMux. No OpcUaPublishActor change.
Driver-value delivery only; native alarms + historian remain separate.
2026-06-13 06:21:40 -04:00
12 changed files with 764 additions and 49 deletions
@@ -0,0 +1,81 @@
# Equipment-tag live-value delivery — Design
**Date:** 2026-06-13
**Status:** Approved — ready for implementation planning
**Scope:** Deliver a **driver's published value to its materialised equipment-tag OPC UA variable.** This is the load-bearing milestone deferred from the Galaxy-standard-driver work (`docs/plans/2026-06-12-galaxy-standard-driver-design.md`).
## Goal
Make a driver-published value land on the correct equipment-tag variable so it stops showing `BadWaitingForInitialData`. This benefits **every** equipment-tag driver (Modbus/S7/AbCip/…/Galaxy), not just Galaxy.
## The gap (root cause, confirmed in code)
The live-value publish chain is:
```
driver OnDataChange
→ DriverInstanceActor.AttributeValuePublished(FullReference, Value, Quality, Ts) [DriverInstanceActor.cs:65,449]
→ DriverHostActor.ForwardToMux [DriverHostActor.cs:379]
• _dependencyMux?.Tell(msg) (VirtualTag inputs — correct, keep)
• _opcUaPublishActor?.Tell(AttributeValueUpdate(NodeId = msg.FullReference, …)) [DriverHostActor.cs:391]
→ OpcUaPublishActor.HandleAttributeUpdate → _sink.WriteValue(msg.NodeId, …) [OpcUaPublishActor.cs:159,163]
→ OtOpcUaNodeManager.WriteValue → _variables.TryGetValue(nodeId) [OtOpcUaNodeManager.cs:89]
```
But equipment variables are materialised with **folder-scoped NodeIds** (`{parent}/{Name}`, `parent = IsNullOrWhiteSpace(FolderPath) ? EquipmentId : "{EquipmentId}/{FolderPath}"`) — *not* the `FullName` — because a driver wire-ref (e.g. Modbus register 40001) is **not unique across identical machines** (`Phase7Applier.MaterialiseEquipmentTags` :180-192). So `WriteValue(FullReference)` misses `_variables` and (worse) `OtOpcUaNodeManager.WriteValue` **lazily creates an orphan variable** keyed by the raw FullReference (`OtOpcUaNodeManager.cs:97-101`). The value never reaches the real, browseable variable.
`AttributeValuePublished` / `AttributeValueUpdate` also don't carry `DriverInstanceId`, which a `FullName→NodeId` router needs (FullName is unique only *within* a driver instance).
## Chosen approach — mirror the proven VirtualTag pattern
`VirtualTagHostActor` **already solves the identical problem** for VirtualTags: it rebuilds a `vtagId → folder-scoped NodeId` map (`_nodeIdByVtag`) every apply via `NodeIdFor(plan)` and resolves it **before** publishing `AttributeValueUpdate` (`VirtualTagHostActor.cs:42,85-88,121-131,149-153`). VirtualTag values therefore already land correctly. We mirror this for driver equipment-tag values.
### Components
1. **Shared NodeId helper (kills duplication + the drift risk this milestone depends on).**
The `{parent}/{Name}` formula is currently copied in `Phase7Applier.EquipmentSubFolderNodeId`/inline and `VirtualTagHostActor.NodeIdFor`, each with a "MUST match" doc-comment. Extract one helper — e.g. `ZB.MOM.WW.OtOpcUa.Commons.OpcUa.EquipmentNodeIds.Variable(equipmentId, folderPath, name)` + `SubFolder(equipmentId, folderPath)` (Commons is referenced by both OpcUaServer and Runtime). Repoint `Phase7Applier` + `VirtualTagHostActor` to it (byte-identical output). The new driver map uses the **same** helper, guaranteeing the router's NodeId equals the materialised NodeId.
2. **Carry `DriverInstanceId` on the publish message.**
Add `DriverInstanceId` to `DriverInstanceActor.AttributeValuePublished` (the actor already holds `_driverInstanceId`, :77/169) and populate it at the raise site (:449).
3. **Driver `(DriverInstanceId, FullName) → NodeId[]` map + resolution in `DriverHostActor`.**
- Build `_nodeIdByDriverRef` from `composition.EquipmentTags` (each carries `DriverInstanceId`, `FullName`, `EquipmentId`, `FolderPath`, `Name`) using the shared helper. Rebuild it every apply — the natural place is `PushDesiredSubscriptions` (which already iterates `EquipmentTags` grouping by driver, runs after `RebuildAddressSpace` in the apply pass). Mirror `_nodeIdByVtag`'s clear-and-repopulate.
- In `ForwardToMux`: keep `_dependencyMux?.Tell(msg)` unchanged; then resolve `(msg.DriverInstanceId, msg.FullReference) → NodeId[]` and `Tell` an `AttributeValueUpdate(nodeId, …)` **per** resolved NodeId. On no-match, skip the OPC UA push (debug-log) — **do not** create orphan variables.
- Value is `List<NodeId>` to handle the 1→many case (two tags on one driver sharing a FullName).
No change to `OpcUaPublishActor` (the existing `AttributeValueUpdate` is reused exactly as VirtualTags use it).
### Data flow (after)
```
driver value (FullReference) → AttributeValuePublished(DriverInstanceId, FullReference, …)
→ ForwardToMux:
_dependencyMux.Tell(msg) (unchanged)
_nodeIdByDriverRef[(DriverInstanceId, FullReference)] → [folder-scoped NodeId, …]
→ for each: _opcUaPublishActor.Tell(AttributeValueUpdate(nodeId, value, quality, ts))
→ WriteValue(folder-scoped nodeId) → hits the real variable → value displays
```
## Error handling / edge cases
- **No-match** (a published ref not in the map): skip the OPC UA push, debug-log; never lazily create an orphan variable. (Optionally tighten `OtOpcUaNodeManager.WriteValue` to not auto-create on miss — but leave that as-is to avoid touching the alarm/vtag callers; the router simply doesn't call it for unmatched refs.)
- **1→many**: write to every NodeId the `(driver, FullName)` maps to.
- **Rebuild lifecycle**: `_nodeIdByDriverRef` is cleared + repopulated every apply (matches the address-space rebuild that clears `_variables`).
- **Multi-node / redundancy**: the path runs on every node (each materialises its own variables + builds its own map). No Primary-gating — values flow on all nodes, same as today's vtag path.
- **FullName uniqueness**: globally non-unique across identical machines, but unique within a driver instance → keying on `(DriverInstanceId, FullName)` is correct. (Galaxy `tag_name`s are globally unique anyway.)
## Testing (no bUnit)
- **Unit (xUnit + Shouldly):** the shared `EquipmentNodeIds` helper (formula incl. null/empty FolderPath); `Phase7Applier` + `VirtualTagHostActor` produce byte-identical NodeIds after repointing (golden/parity assertion).
- **DriverHostActor resolution (Akka.TestKit):** an apply with a composition containing an equipment tag → a subsequent `AttributeValuePublished(driverId, FullName, …)` results in an `AttributeValueUpdate(folder-scoped NodeId, …)` reaching the publish actor (probe); two equipments sharing one `(driver, FullName)` → both NodeIds written; an unmatched ref → no OPC UA push (still forwarded to the mux). Extract the resolution into a testable method if it eases TestKit assertions.
- **Live docker-dev `/run` (agent-driven; dev login disabled):** author a Modbus (live sim on `10.100.0.35:5020`) equipment tag → confirm its variable shows a **live value** over OPC UA (Client.CLI `read`/`subscribe`), not `BadWaitingForInitialData`. (Galaxy needs a real mxaccessgw to show data, so Modbus is the cleaner live proof; the routing is driver-agnostic.)
## Out of scope (separate milestones)
- **Phase B** — native `IAlarmSource` alarms on the equipment-tag path.
- **Phase C** — server-side `HistoryRead` backend.
- Tightening `OtOpcUaNodeManager.WriteValue`'s lazy-create-on-miss (latent smell; not required here).
## Hard rules
Stage by path; never `git add .`; never stage `sql_login.txt` / `src/Server/.../Host/pki/` / `pending.md` / `current.md`. Never echo the gateway API key / historian SharedSecret into a tracked file. No force-push, no `--no-verify`. No Configuration entity/EF migration change (this is runtime-only). Build on a feature branch off master.
@@ -0,0 +1,299 @@
# Equipment-tag Live-Value Delivery — Implementation Plan
> **For Claude:** REQUIRED SUB-SKILL: Use superpowers-extended-cc:executing-plans to implement this plan task-by-task.
**Goal:** Route a driver's published value (keyed by `FullName`) to its materialised equipment-tag OPC UA variable (keyed by a folder-scoped NodeId), so equipment tags stop showing `BadWaitingForInitialData`.
**Architecture:** Mirror the proven `VirtualTagHostActor._nodeIdByVtag` pattern for **driver** values. Extract one shared `EquipmentNodeIds` NodeId-formula helper (kills the duplicated formula the router depends on), carry `DriverInstanceId` on the publish message, and have `DriverHostActor` build a `(DriverInstanceId, FullName) → NodeId[]` map each apply and resolve it in `ForwardToMux` before sending the existing `AttributeValueUpdate`. No `OpcUaPublishActor` change. Runtime-only — **no EF/Configuration change.**
**Tech Stack:** .NET 10, Akka.NET (+ Akka.TestKit), OPC UA Foundation stack, xUnit + Shouldly. Design: `docs/plans/2026-06-13-equipment-tag-live-values-design.md` (master `7e9eb5d1`).
**Branch:** `feat/equipment-tag-live-values` off master `7e9eb5d1`.
---
## Hard rules (every task)
- Stage by path; never `git add .`. Never stage `sql_login.txt`, `src/Server/ZB.MOM.WW.OtOpcUa.Host/pki/`, `pending.md`, or `current.md`.
- Never echo the gateway API key / historian `SharedSecret` into a tracked file. No force-push, no `--no-verify`. No Configuration entity/EF migration change.
## Dependency spine
T0 → {T1, T3} (disjoint files, parallel). T2 needs T1. T4 needs T1 + T3. T5 (verify) needs all.
| Task | Files | Class | Parallelizable with |
|---|---|---|---|
| T0 branch | git | trivial | — |
| T1 EquipmentNodeIds helper | Commons (new) + Commons.Tests | small | T3 |
| T2 repoint formula + parity test | Phase7Applier, VirtualTagHostActor, OpcUaServer.Tests | standard | T3 |
| T3 AttributeValuePublished + DriverInstanceId | DriverInstanceActor | small | T1, T2 |
| T4 DriverHostActor map + resolve + TestKit | DriverHostActor, Runtime.Tests | high-risk | — |
| T5 verify + live /run | none | verification | — |
---
### Task 0: Create feature branch
**Classification:** trivial
**Estimated implement time:** ~1 min
**Parallelizable with:** none
**Files:** git only
```bash
git checkout master && git rev-parse HEAD # expect 7e9eb5d1...
git checkout -b feat/equipment-tag-live-values
```
Confirm clean tree (ignore untracked `pending.md` / `current.md` / `sql_login.txt` / `pki/`).
---
### Task 1: Shared `EquipmentNodeIds` NodeId-formula helper
**Classification:** small
**Estimated implement time:** ~4 min
**Parallelizable with:** Task 3
**Files:**
- Create: `src/Core/ZB.MOM.WW.OtOpcUa.Commons/OpcUa/EquipmentNodeIds.cs`
- Test: `tests/Core/ZB.MOM.WW.OtOpcUa.Commons.Tests/OpcUa/EquipmentNodeIdsTests.cs`
**Context:** The folder-scoped NodeId formula is currently copied in `Phase7Applier` and `VirtualTagHostActor` (each with a "MUST match" warning). This is the single source of truth both — and the new driver router — will use, guaranteeing the router's NodeId equals the materialised NodeId. Confirm the test project name first: `ls tests/Core | grep -i Commons` (it's `ZB.MOM.WW.OtOpcUa.Commons.Tests`).
**Step 1: Write the failing tests**
```csharp
using Shouldly;
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
using Xunit;
namespace ZB.MOM.WW.OtOpcUa.Commons.Tests.OpcUa;
public class EquipmentNodeIdsTests
{
[Fact]
public void Variable_with_no_folder_is_equipment_slash_name()
=> EquipmentNodeIds.Variable("eq-1", "", "speed").ShouldBe("eq-1/speed");
[Fact]
public void Variable_with_null_folder_is_equipment_slash_name()
=> EquipmentNodeIds.Variable("eq-1", null, "speed").ShouldBe("eq-1/speed");
[Fact]
public void Variable_with_folder_is_equipment_slash_folder_slash_name()
=> EquipmentNodeIds.Variable("eq-1", "registers", "speed").ShouldBe("eq-1/registers/speed");
[Fact]
public void SubFolder_is_equipment_slash_folder()
=> EquipmentNodeIds.SubFolder("eq-1", "registers").ShouldBe("eq-1/registers");
}
```
**Step 2: Run — expect FAIL** (`EquipmentNodeIds` not defined).
`dotnet test tests/Core/ZB.MOM.WW.OtOpcUa.Commons.Tests --filter "FullyQualifiedName~EquipmentNodeIds"`
**Step 3: Implement**
```csharp
namespace ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
/// <summary>
/// Single source of truth for equipment-namespace OPC UA NodeId strings. The variable NodeId is
/// FOLDER-SCOPED (<c>{parent}/{Name}</c>), NOT the driver-side FullName — a driver wire ref is not
/// unique across identical machines, so FullName-as-NodeId would collide in the sink. Used by the
/// materialiser (Phase7Applier), the VirtualTag publish map, and the driver live-value router so all
/// three agree on the exact NodeId a variable was placed at.
/// </summary>
public static class EquipmentNodeIds
{
/// <summary>The sub-folder NodeId under an equipment for a non-empty FolderPath: <c>{equipmentId}/{folderPath}</c>.</summary>
/// <param name="equipmentId">The owning equipment's NodeId.</param>
/// <param name="folderPath">The tag/vtag FolderPath (must be non-empty for this to be meaningful).</param>
/// <returns>The sub-folder NodeId string.</returns>
public static string SubFolder(string equipmentId, string folderPath) => $"{equipmentId}/{folderPath}";
/// <summary>
/// The folder-scoped variable NodeId: <c>{parent}/{name}</c> where <c>parent = equipmentId</c> when
/// <paramref name="folderPath"/> is null/empty, else <see cref="SubFolder"/>.
/// </summary>
/// <param name="equipmentId">The owning equipment's NodeId.</param>
/// <param name="folderPath">The tag/vtag FolderPath, or null/empty for "directly under the equipment".</param>
/// <param name="name">The tag/vtag Name (the leaf browse segment).</param>
/// <returns>The folder-scoped variable NodeId string.</returns>
public static string Variable(string equipmentId, string? folderPath, string name)
{
var parent = string.IsNullOrWhiteSpace(folderPath) ? equipmentId : SubFolder(equipmentId, folderPath);
return $"{parent}/{name}";
}
}
```
**Step 4: Run — expect PASS.**
**Step 5: Commit**
```bash
git add src/Core/ZB.MOM.WW.OtOpcUa.Commons/OpcUa/EquipmentNodeIds.cs tests/Core/ZB.MOM.WW.OtOpcUa.Commons.Tests/OpcUa/EquipmentNodeIdsTests.cs
git commit -m "feat(commons): EquipmentNodeIds — single source of truth for folder-scoped equipment NodeIds"
```
---
### Task 2: Repoint Phase7Applier + VirtualTagHostActor to `EquipmentNodeIds` (+ parity test)
**Classification:** standard
**Estimated implement time:** ~5 min
**Parallelizable with:** Task 3
**blockedBy:** Task 1
**Files:**
- Modify: `src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/Phase7Applier.cs` (`EquipmentSubFolderNodeId` :280; the inline `{parent}/{Name}` in `MaterialiseEquipmentTags` :189-191 and `MaterialiseEquipmentVirtualTags` :236-237)
- Modify: `src/Server/ZB.MOM.WW.OtOpcUa.Runtime/VirtualTags/VirtualTagHostActor.cs` (`NodeIdFor` :149-153 + the `using`)
- Test: `tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/` (a small parity test asserting both produce `EquipmentNodeIds.Variable(...)`)
**Context:** Replace the two copied formulas with the shared helper — **byte-identical output**. `Phase7Applier` is in OpcUaServer, `VirtualTagHostActor` in Runtime; both reference Commons. Read each before editing.
**Step 1 (test first):** Add a parity/golden test (OpcUaServer.Tests) that pins the formula and proves both call sites match the helper — e.g. for an equipment tag with `FolderPath=null` the materialised NodeId equals `EquipmentNodeIds.Variable(eqId, null, name)`, and with a FolderPath it equals `EquipmentNodeIds.Variable(eqId, folder, name)`. (If an existing materialiser test already asserts concrete NodeIds like `eq-1/speed`, extend it; otherwise add one that drives `MaterialiseEquipmentTags` against a recording sink and asserts the variable NodeIds.) Run — should pass before AND after the repoint (the change is behaviour-preserving); its job is to lock the formula against future drift.
**Step 2:** In `Phase7Applier`: replace `EquipmentSubFolderNodeId(eq, fp)` body (or its call sites) with `EquipmentNodeIds.SubFolder(eq, fp)`, and replace the inline `var nodeId = $"{parent}/{tag.Name}";` (tags :191 and vtags :237) with `var nodeId = EquipmentNodeIds.Variable(tag.EquipmentId, tag.FolderPath, tag.Name);` (and the vtag equivalent `v.EquipmentId, v.FolderPath, v.Name`). You may delete the private `EquipmentSubFolderNodeId` if all call sites move to the helper, or keep it as a thin forwarder — implementer's choice, but no behaviour change. Add `using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;`.
**Step 3:** In `VirtualTagHostActor.NodeIdFor`, return `EquipmentNodeIds.Variable(p.EquipmentId, p.FolderPath, p.Name)`; add the `using`. Keep the "MUST match" doc-comment but update it to say the formula now lives in `EquipmentNodeIds`.
**Step 4:** Build + test:
```bash
dotnet build src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer
dotnet build src/Server/ZB.MOM.WW.OtOpcUa.Runtime
dotnet test tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests --filter "FullyQualifiedName~Phase7Applier"
```
Expect 0 errors; existing applier + vtag tests still green (byte-identical NodeIds).
**Step 5: Commit** (both files + the test).
---
### Task 3: Carry `DriverInstanceId` on `AttributeValuePublished`
**Classification:** small
**Estimated implement time:** ~3 min
**Parallelizable with:** Task 1, Task 2
**Files:**
- Modify: `src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverInstanceActor.cs` (record :65; raise site :449)
**Context:** The router needs to key on `(DriverInstanceId, FullName)`. The actor already holds `_driverInstanceId` (:77, set :169). Add it as the **first** parameter so the message self-identifies its source driver.
**Step 1:** Change the record (`:65`):
```csharp
public sealed record AttributeValuePublished(string DriverInstanceId, string FullReference, object? Value, OpcUaQuality Quality, DateTime TimestampUtc);
```
**Step 2:** Update the raise site (`:449`):
```csharp
Context.Parent.Tell(new AttributeValuePublished(_driverInstanceId, msg.FullReference, msg.Snapshot.Value, quality, ts));
```
**Step 3:** Fix every other construction/consumer of `AttributeValuePublished` so it compiles — grep first:
`grep -rn "AttributeValuePublished" src tests --include=*.cs | grep -v /obj/ | grep -v /bin/`
The known consumer is `DriverHostActor.ForwardToMux` (Task 4 handles the resolution; here just make it compile — it can pass `msg` through to `_dependencyMux` unchanged). Update any test that constructs `AttributeValuePublished` to pass a `DriverInstanceId`.
**Step 4:** Build Runtime: `dotnet build src/Server/ZB.MOM.WW.OtOpcUa.Runtime` → 0 errors. Run any DriverInstanceActor tests.
**Step 5: Commit.**
---
### Task 4: `DriverHostActor` — driver-ref→NodeId map + `ForwardToMux` resolution
**Classification:** high-risk
**Estimated implement time:** ~5 min
**Parallelizable with:** none
**blockedBy:** Task 1, Task 3
**Files:**
- Modify: `src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverHostActor.cs` (add `_nodeIdByDriverRef` field; build it in `PushDesiredSubscriptions` :558-607; resolve in `ForwardToMux` :379-392; `using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;`)
- Test: `tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/` (new Akka.TestKit test — find the existing DriverHostActor test file pattern first)
**Context:** Mirror `VirtualTagHostActor`. Build the map every apply from `composition.EquipmentTags` (each carries `DriverInstanceId`, `FullName`, `EquipmentId`, `FolderPath`, `Name`) using `EquipmentNodeIds.Variable`. Value is a `List<string>` for the 1→many case. Resolve in `ForwardToMux` and emit one `AttributeValueUpdate` per NodeId; on no-match, skip the OPC UA push (still forward to `_dependencyMux`) and debug-log.
**Step 1: Write the failing tests (Akka.TestKit).** Read an existing DriverHostActor test to copy the harness (how it constructs the actor with `opcUaPublishActor` + `dependencyMux` probes and triggers an apply, or how `PushDesiredSubscriptions` is exercised). Then:
- `Published_driver_value_routes_to_folder_scoped_nodeid`: after an apply whose composition has equipment tag `{EquipmentId="eq-1", DriverInstanceId="drv-1", FullName="40001", FolderPath=null, Name="speed"}`, send the host a `DriverInstanceActor.AttributeValuePublished("drv-1", "40001", 42.0, OpcUaQuality.Good, ts)`; the opcUaPublish probe receives `AttributeValueUpdate("eq-1/speed", 42.0, …)`.
- `Same_ref_on_two_equipments_writes_both`: two equipment tags `(drv-1, "40001")` on `eq-1` and `eq-2`; one publish → probe receives BOTH `eq-1/speed` and `eq-2/speed`.
- `Unmatched_ref_no_opcua_push_but_still_to_mux`: publish `(drv-1, "59999")` (not in composition) → opcUaPublish probe gets nothing (ExpectNoMsg), but the dependency-mux probe still receives the raw `AttributeValuePublished`.
Run — expect FAIL.
**Step 2: Implement.**
- Field: `private readonly Dictionary<(string DriverInstanceId, string FullName), List<string>> _nodeIdByDriverRef = new();`
- In `PushDesiredSubscriptions`, right where it has the `composition` (alongside building `refsByDriver`), rebuild the map:
```csharp
_nodeIdByDriverRef.Clear();
foreach (var t in composition.EquipmentTags)
{
var key = (t.DriverInstanceId, t.FullName);
var nodeId = EquipmentNodeIds.Variable(t.EquipmentId, t.FolderPath, t.Name);
if (!_nodeIdByDriverRef.TryGetValue(key, out var list))
_nodeIdByDriverRef[key] = list = new List<string>();
if (!list.Contains(nodeId)) list.Add(nodeId);
}
```
- In `ForwardToMux`:
```csharp
private void ForwardToMux(DriverInstanceActor.AttributeValuePublished msg)
{
_dependencyMux?.Tell(msg); // VirtualTag inputs — keyed by FullReference, unchanged
if (_opcUaPublishActor is null) return;
if (_nodeIdByDriverRef.TryGetValue((msg.DriverInstanceId, msg.FullReference), out var nodeIds))
{
foreach (var nodeId in nodeIds)
_opcUaPublishActor.Tell(new ZB.MOM.WW.OtOpcUa.Runtime.OpcUa.OpcUaPublishActor.AttributeValueUpdate(
nodeId, msg.Value, msg.Quality, msg.TimestampUtc));
}
else
{
_log.Debug("DriverHost {Node}: no equipment-tag NodeId for ({Driver},{Ref}) — value dropped",
_localNode, msg.DriverInstanceId, msg.FullReference);
}
}
```
Update the stale `ForwardToMux` comment block (the "live values milestone… until then BadWaitingForInitialData" note) to describe the now-wired routing. Add the `using`.
**Step 3:** Run the new tests — expect PASS.
**Step 4:** Build + full Runtime suite:
```bash
dotnet build src/Server/ZB.MOM.WW.OtOpcUa.Runtime
dotnet test tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests --filter "FullyQualifiedName~DriverHost"
```
**Step 5: Commit** (DriverHostActor + the TestKit test).
---
### Task 5: Verify — build, test, agent-driven live `/run`
**Classification:** verification
**Estimated implement time:** ~5 min + live
**Parallelizable with:** none
**blockedBy:** all
**Files:** none
**Step 1:** Full solution build + the touched suites:
```bash
dotnet build ZB.MOM.WW.OtOpcUa.slnx
dotnet test tests/Core/ZB.MOM.WW.OtOpcUa.Commons.Tests
dotnet test tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests
dotnet test tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests
```
Expect 0 errors; all green.
**Step 2: Live docker-dev `/run` (agent drives; dev login DISABLED — no sign-in).** The routing is driver-agnostic; **Modbus** is the cleanest live proof (live sim at `10.100.0.35:5020`; Galaxy would need a real mxaccessgw).
- Rebuild central nodes on this branch: `docker compose -f docker-dev/docker-compose.yml up -d --build migrator central-1 central-2` (no new migration here, but the rebuild ships the branch code).
- In the AdminUI (`http://localhost:9200`): create a `ModbusTcp` driver under the `nw-uns` Equipment namespace (endpoint `10.100.0.35:5020`), author an equipment tag on an equipment bound to it (a valid Modbus FullName/register), and **deploy** (`POST http://localhost:9200/api/deployments`, header `X-Api-Key: docker-dev-deploy-key`, or the UI deploy).
- Confirm the tag's OPC UA variable shows a **live value** (not `BadWaitingForInitialData`): `dotnet run --project src/Client/ZB.MOM.WW.OtOpcUa.Client.CLI -- read -u opc.tcp://localhost:4840 -n "ns=2;s=<equipmentId>/<name>"` (or `subscribe`). Browse first (`-r -d 4`) to find the NodeId.
- Sanity: the central logs show no `WriteValue threw` / no-match storms.
**Step 3:** On green, finish via `superpowers-extended-cc:finishing-a-development-branch` (intent: merge-to-master + push, confirm).
---
## Out of scope
Native `IAlarmSource` alarms on the equipment path (Phase B) and the server-side `HistoryRead` backend (Phase C) — separate milestones in the design doc.
@@ -0,0 +1,12 @@
{
"planPath": "docs/plans/2026-06-13-equipment-tag-live-values-plan.md",
"tasks": [
{"id": 332, "subject": "Task 0: Create feature branch", "status": "pending"},
{"id": 333, "subject": "Task 1: EquipmentNodeIds shared helper", "status": "pending", "blockedBy": [332]},
{"id": 334, "subject": "Task 2: Repoint Phase7Applier + VirtualTagHostActor to EquipmentNodeIds", "status": "pending", "blockedBy": [333]},
{"id": 335, "subject": "Task 3: AttributeValuePublished gains DriverInstanceId", "status": "pending", "blockedBy": [332]},
{"id": 336, "subject": "Task 4: DriverHostActor map + ForwardToMux resolution", "status": "pending", "blockedBy": [333, 335]},
{"id": 337, "subject": "Task 5: Verify — build, test, live /run", "status": "pending", "blockedBy": [334, 336]}
],
"lastUpdated": "2026-06-13"
}
@@ -0,0 +1,31 @@
namespace ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
/// <summary>
/// Single source of truth for equipment-namespace OPC UA NodeId strings. The variable NodeId is
/// FOLDER-SCOPED (<c>{parent}/{Name}</c>), NOT the driver-side FullName — a driver wire ref is not
/// unique across identical machines, so FullName-as-NodeId would collide in the sink. Used by the
/// materialiser (Phase7Applier), the VirtualTag publish map, and the driver live-value router so all
/// three agree on the exact NodeId a variable was placed at.
/// </summary>
public static class EquipmentNodeIds
{
/// <summary>The sub-folder NodeId under an equipment for a non-empty FolderPath: <c>{equipmentId}/{folderPath}</c>.</summary>
/// <param name="equipmentId">The owning equipment's NodeId.</param>
/// <param name="folderPath">The tag/vtag FolderPath (must be non-empty for this to be meaningful).</param>
/// <returns>The sub-folder NodeId string.</returns>
public static string SubFolder(string equipmentId, string folderPath) => $"{equipmentId}/{folderPath}";
/// <summary>
/// The folder-scoped variable NodeId: <c>{parent}/{name}</c> where <c>parent = equipmentId</c> when
/// <paramref name="folderPath"/> is null/empty, else <see cref="SubFolder"/>.
/// </summary>
/// <param name="equipmentId">The owning equipment's NodeId.</param>
/// <param name="folderPath">The tag/vtag FolderPath, or null/empty for "directly under the equipment".</param>
/// <param name="name">The tag/vtag Name (the leaf browse segment).</param>
/// <returns>The folder-scoped variable NodeId string.</returns>
public static string Variable(string equipmentId, string? folderPath, string name)
{
var parent = string.IsNullOrWhiteSpace(folderPath) ? equipmentId : SubFolder(equipmentId, folderPath);
return $"{parent}/{name}";
}
}
@@ -172,7 +172,7 @@ public sealed class Phase7Applier
foreach (var tag in composition.EquipmentTags)
{
if (string.IsNullOrWhiteSpace(tag.FolderPath)) continue;
var folderNodeId = EquipmentSubFolderNodeId(tag.EquipmentId, tag.FolderPath);
var folderNodeId = EquipmentNodeIds.SubFolder(tag.EquipmentId, tag.FolderPath);
if (!foldersCreated.Add(folderNodeId)) continue;
SafeEnsureFolder(folderNodeId, parentNodeId: tag.EquipmentId, displayName: tag.FolderPath);
}
@@ -187,8 +187,8 @@ public sealed class Phase7Applier
{
var parent = string.IsNullOrWhiteSpace(tag.FolderPath)
? tag.EquipmentId
: EquipmentSubFolderNodeId(tag.EquipmentId, tag.FolderPath);
var nodeId = $"{parent}/{tag.Name}";
: EquipmentNodeIds.SubFolder(tag.EquipmentId, tag.FolderPath);
var nodeId = EquipmentNodeIds.Variable(tag.EquipmentId, tag.FolderPath, tag.Name);
SafeEnsureVariable(nodeId, parent, tag.Name, tag.DataType);
}
@@ -223,7 +223,7 @@ public sealed class Phase7Applier
foreach (var v in composition.EquipmentVirtualTags)
{
if (string.IsNullOrWhiteSpace(v.FolderPath)) continue;
var folderNodeId = EquipmentSubFolderNodeId(v.EquipmentId, v.FolderPath);
var folderNodeId = EquipmentNodeIds.SubFolder(v.EquipmentId, v.FolderPath);
if (!foldersCreated.Add(folderNodeId)) continue;
SafeEnsureFolder(folderNodeId, parentNodeId: v.EquipmentId, displayName: v.FolderPath);
}
@@ -234,8 +234,8 @@ public sealed class Phase7Applier
{
var parent = string.IsNullOrWhiteSpace(v.FolderPath)
? v.EquipmentId
: EquipmentSubFolderNodeId(v.EquipmentId, v.FolderPath);
var nodeId = $"{parent}/{v.Name}";
: EquipmentNodeIds.SubFolder(v.EquipmentId, v.FolderPath);
var nodeId = EquipmentNodeIds.Variable(v.EquipmentId, v.FolderPath, v.Name);
SafeEnsureVariable(nodeId, parent, v.Name, v.DataType);
}
@@ -275,11 +275,6 @@ public sealed class Phase7Applier
.Select(a => a.EquipmentId).Distinct(StringComparer.Ordinal).Count());
}
/// <summary>Deterministic NodeId for a tag's FolderPath sub-folder, scoped under its equipment
/// folder so two equipments' identically-named sub-folders never collide.</summary>
private static string EquipmentSubFolderNodeId(string equipmentId, string folderPath) =>
$"{equipmentId}/{folderPath}";
private void SafeEnsureFolder(string nodeId, string? parentNodeId, string displayName)
{
try { _sink.EnsureFolder(nodeId, parentNodeId, displayName); }
@@ -11,6 +11,7 @@ using ZB.MOM.WW.OtOpcUa.Commons.Messages.Admin;
using ZB.MOM.WW.OtOpcUa.Commons.Messages.Deploy;
using ZB.MOM.WW.OtOpcUa.Commons.Messages.Fleet;
using ZB.MOM.WW.OtOpcUa.Commons.Observability;
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
using ZB.MOM.WW.OtOpcUa.Commons.Types;
using ZB.MOM.WW.OtOpcUa.Configuration;
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
@@ -85,6 +86,16 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers
private readonly Dictionary<string, ChildEntry> _children = new(StringComparer.Ordinal);
/// <summary>
/// Driver live-value routing map: <c>(DriverInstanceId, FullName) → folder-scoped equipment
/// NodeId(s)</c>. Rebuilt every apply by <see cref="PushDesiredSubscriptions"/> from the
/// composition's <c>EquipmentTags</c> (mirroring <c>VirtualTagHostActor._nodeIdByVtag</c>), and
/// resolved in <see cref="ForwardToMux"/> so a driver value published by wire-ref FullName lands
/// on the variable's actual folder-scoped NodeId. A list because the same driver ref can back
/// several equipment variables (e.g. identical machines sharing a register).
/// </summary>
private readonly Dictionary<(string DriverInstanceId, string FullName), List<string>> _nodeIdByDriverRef = new();
private sealed record ChildEntry(IActorRef Actor, DriverInstanceSpec Spec, bool Stubbed)
{
// Convenience accessors for sites that don't need the full spec.
@@ -378,18 +389,32 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers
private void ForwardToMux(DriverInstanceActor.AttributeValuePublished msg)
{
// Pass driver-published values to the dependency mux when one is wired (VirtualTag inputs).
// Without a mux, VirtualTagActor evaluation can't fire — that's the dev/Mac path (no virtual
// tags registered); production binds the mux via the RuntimeActors extension.
// Pass driver-published values to the dependency mux when one is wired (VirtualTag inputs,
// keyed by FullReference). Without a mux, VirtualTagActor evaluation can't fire — that's the
// dev/Mac path (no virtual tags registered); production binds the mux via the RuntimeActors
// extension. KEEP this unchanged — VirtualTag inputs are still keyed by FullReference.
_dependencyMux?.Tell(msg);
// Also push the value to the OPC UA sink. NOTE: equipment-tag variables are materialised with
// folder-scoped NodeIds (EquipmentId/FolderPath/Name), while the driver publishes keyed by
// FullReference (the tag's FullName). The value therefore only lands on the variable once the
// FullName→NodeId routing — the equipment-tag "live values" milestone — is wired; until then
// the variable stays BadWaitingForInitialData.
_opcUaPublishActor?.Tell(new ZB.MOM.WW.OtOpcUa.Runtime.OpcUa.OpcUaPublishActor.AttributeValueUpdate(
msg.FullReference, msg.Value, msg.Quality, msg.TimestampUtc));
if (_opcUaPublishActor is null) return;
// Route the value to the OPC UA sink at the variable's ACTUAL NodeId. Equipment-tag variables
// are materialised with folder-scoped NodeIds (EquipmentId/FolderPath/Name), while the driver
// publishes keyed by its wire-ref FullName (FullReference). The _nodeIdByDriverRef map — built
// each apply from the composition's EquipmentTags — resolves (DriverInstanceId, FullName) to
// the folder-scoped NodeId(s) the materialiser placed the variable(s) at, so the value lands
// instead of leaving the variable at BadWaitingForInitialData. One driver ref can back several
// equipment variables (identical machines sharing a register), hence the fan-out.
if (_nodeIdByDriverRef.TryGetValue((msg.DriverInstanceId, msg.FullReference), out var nodeIds))
{
foreach (var nodeId in nodeIds)
_opcUaPublishActor.Tell(new ZB.MOM.WW.OtOpcUa.Runtime.OpcUa.OpcUaPublishActor.AttributeValueUpdate(
nodeId, msg.Value, msg.Quality, msg.TimestampUtc));
}
else
{
_log.Debug("DriverHost {Node}: no equipment-tag NodeId for ({Driver},{Ref}) — value dropped",
_localNode, msg.DriverInstanceId, msg.FullReference);
}
}
private void Stale()
@@ -592,6 +617,21 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers
.ToArray(),
StringComparer.Ordinal);
// Rebuild the driver live-value routing map from the SAME EquipmentTags pass (mirrors
// VirtualTagHostActor._nodeIdByVtag): map each tag's (DriverInstanceId, FullName) wire-ref to
// the folder-scoped equipment NodeId the materialiser placed its variable at, so ForwardToMux
// can land driver values on the right node. Clear-and-repopulate every apply so renames
// (Name/FolderPath/EquipmentId changes) and removals are reflected.
_nodeIdByDriverRef.Clear();
foreach (var t in composition.EquipmentTags)
{
var key = (t.DriverInstanceId, t.FullName);
var nodeId = EquipmentNodeIds.Variable(t.EquipmentId, t.FolderPath, t.Name);
if (!_nodeIdByDriverRef.TryGetValue(key, out var list))
_nodeIdByDriverRef[key] = list = new List<string>();
if (!list.Contains(nodeId)) list.Add(nodeId);
}
var total = 0;
foreach (var (driverId, entry) in _children)
{
@@ -62,7 +62,7 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
public sealed record ForceReconnect;
/// <summary>Published to the actor's parent whenever the subscribed IDriver fires
/// <see cref="ISubscribable.OnDataChange"/>. The parent forwards to OpcUaPublishActor.</summary>
public sealed record AttributeValuePublished(string FullReference, object? Value, OpcUaQuality Quality, DateTime TimestampUtc);
public sealed record AttributeValuePublished(string DriverInstanceId, string FullReference, object? Value, OpcUaQuality Quality, DateTime TimestampUtc);
private sealed record DataChangeForward(string FullReference, DataValueSnapshot Snapshot);
public sealed class RetryConnect
{
@@ -446,7 +446,7 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
{
var quality = QualityFromStatus(msg.Snapshot.StatusCode);
var ts = msg.Snapshot.SourceTimestampUtc ?? msg.Snapshot.ServerTimestampUtc;
Context.Parent.Tell(new AttributeValuePublished(msg.FullReference, msg.Snapshot.Value, quality, ts));
Context.Parent.Tell(new AttributeValuePublished(_driverInstanceId, msg.FullReference, msg.Snapshot.Value, quality, ts));
}
/// <summary>Translate an OPC UA status code to the 3-state <see cref="OpcUaQuality"/> projection
@@ -17,10 +17,9 @@ namespace ZB.MOM.WW.OtOpcUa.Runtime.VirtualTags;
/// already-materialised Variable node (currently BadWaitingForInitialData) reflects the value.
///
/// <para>
/// The published NodeId is computed with the <b>identical</b> formula
/// <c>Phase7Applier.MaterialiseEquipmentVirtualTags</c> uses to materialise the variable —
/// <c>{parent}/{Name}</c> where <c>parent = IsNullOrWhiteSpace(FolderPath) ? EquipmentId :
/// {EquipmentId}/{FolderPath}</c> — or the value would land on a NodeId that does not exist.
/// The published NodeId is computed by the shared <see cref="EquipmentNodeIds.Variable"/> —
/// the single source of truth <c>Phase7Applier.MaterialiseEquipmentVirtualTags</c> also
/// materialises against — so the value always lands on a NodeId that exists.
/// </para>
/// </summary>
public sealed class VirtualTagHostActor : ReceiveActor
@@ -143,14 +142,9 @@ public sealed class VirtualTagHostActor : ReceiveActor
}
}
/// <summary>Folder-scoped NodeId for a VirtualTag plan — MUST match
/// <c>Phase7Applier.MaterialiseEquipmentVirtualTags</c> exactly, or the published value lands on a
/// NodeId that was never materialised.</summary>
private static string NodeIdFor(EquipmentVirtualTagPlan p)
{
var parent = string.IsNullOrWhiteSpace(p.FolderPath)
? p.EquipmentId
: $"{p.EquipmentId}/{p.FolderPath}";
return $"{parent}/{p.Name}";
}
/// <summary>Folder-scoped NodeId for a VirtualTag plan. The formula now lives in the shared
/// <see cref="EquipmentNodeIds"/> (the single source of truth that <c>Phase7Applier</c> also
/// materialises against), so the published value always lands on the NodeId that was materialised.</summary>
private static string NodeIdFor(EquipmentVirtualTagPlan p) =>
EquipmentNodeIds.Variable(p.EquipmentId, p.FolderPath, p.Name);
}
@@ -0,0 +1,24 @@
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
namespace ZB.MOM.WW.OtOpcUa.Commons.Tests.OpcUa;
public class EquipmentNodeIdsTests
{
[Fact]
public void Variable_with_no_folder_is_equipment_slash_name()
=> EquipmentNodeIds.Variable("eq-1", "", "speed").ShouldBe("eq-1/speed");
[Fact]
public void Variable_with_null_folder_is_equipment_slash_name()
=> EquipmentNodeIds.Variable("eq-1", null, "speed").ShouldBe("eq-1/speed");
[Fact]
public void Variable_with_folder_is_equipment_slash_folder_slash_name()
=> EquipmentNodeIds.Variable("eq-1", "registers", "speed").ShouldBe("eq-1/registers/speed");
[Fact]
public void SubFolder_is_equipment_slash_folder()
=> EquipmentNodeIds.SubFolder("eq-1", "registers").ShouldBe("eq-1/registers");
}
@@ -139,6 +139,8 @@ public sealed class Phase7ApplierTests
sink.FolderCalls.ShouldBeEmpty(); // equipment folder already exists; no sub-folder needed
sink.VariableCalls.ShouldHaveSingleItem().ShouldBe(("eq-1/Speed", "eq-1", "Speed", "Float"));
// Parity: the materialiser's NodeId is the shared EquipmentNodeIds formula (null/empty FolderPath).
sink.VariableCalls.Single().NodeId.ShouldBe(EquipmentNodeIds.Variable("eq-1", "", "Speed"));
}
/// <summary>Verifies a FolderPath on an equipment tag becomes a sub-folder UNDER the equipment
@@ -163,6 +165,8 @@ public sealed class Phase7ApplierTests
sink.FolderCalls.ShouldHaveSingleItem().ShouldBe(("eq-1/Diagnostics", "eq-1", "Diagnostics"));
sink.VariableCalls.ShouldHaveSingleItem().ShouldBe(("eq-1/Diagnostics/Temp", "eq-1/Diagnostics", "Temp", "Float"));
// Parity: the materialiser's NodeId is the shared EquipmentNodeIds formula (with FolderPath).
sink.VariableCalls.Single().NodeId.ShouldBe(EquipmentNodeIds.Variable("eq-1", "Diagnostics", "Temp"));
}
/// <summary>Regression for the FullName-as-NodeId collision: two identical machines exposing the
@@ -215,6 +219,47 @@ public sealed class Phase7ApplierTests
sink.FolderCalls.ShouldBeEmpty(); // equipment folder already exists; no sub-folder needed
sink.VariableCalls.ShouldHaveSingleItem().ShouldBe(("eq-1/speed-rpm", "eq-1", "speed-rpm", "Float64"));
// Parity: the vtag materialiser's NodeId is the shared EquipmentNodeIds formula.
sink.VariableCalls.Single().NodeId.ShouldBe(EquipmentNodeIds.Variable("eq-1", "", "speed-rpm"));
}
/// <summary>Golden/parity guard: the materialiser's Variable NodeId for BOTH the equipment-tag and
/// the equipment-VirtualTag pass is byte-identical to <see cref="EquipmentNodeIds.Variable"/> — the
/// single source of truth Phase7Applier + VirtualTagHostActor both point at. Covers null/empty
/// FolderPath (directly under equipment) and a non-empty FolderPath (sub-folder scoped). This test
/// LOCKS the formula against drift: any change to the materialiser NodeId that diverges from the
/// shared helper fails here.</summary>
[Fact]
public void Materialised_variable_node_ids_match_shared_EquipmentNodeIds_formula()
{
var sink = new RecordingSink();
var applier = new Phase7Applier(sink, NullLogger<Phase7Applier>.Instance);
var composition = new Phase7CompositionResult(
Array.Empty<EquipmentNode>(), Array.Empty<DriverInstancePlan>(), Array.Empty<ScriptedAlarmPlan>())
{
EquipmentTags = new[]
{
new EquipmentTagPlan("tag-flat", "eq-1", "drv", FolderPath: "", Name: "Speed", DataType: "Float", FullName: "40001"),
new EquipmentTagPlan("tag-nested", "eq-1", "drv", FolderPath: "Diagnostics", Name: "Temp", DataType: "Float", FullName: "40002"),
},
EquipmentVirtualTags = new[]
{
new EquipmentVirtualTagPlan("vt-flat", "eq-2", FolderPath: "", Name: "Efficiency", DataType: "Float64",
Expression: "ctx.GetTag(\"a\")", DependencyRefs: new[] { "a" }),
new EquipmentVirtualTagPlan("vt-nested", "eq-2", FolderPath: "Calc", Name: "Avg", DataType: "Float64",
Expression: "ctx.GetTag(\"b\")", DependencyRefs: new[] { "b" }),
},
};
applier.MaterialiseEquipmentTags(composition);
applier.MaterialiseEquipmentVirtualTags(composition);
var nodeIds = sink.VariableCalls.Select(v => v.NodeId).ToList();
nodeIds.ShouldContain(EquipmentNodeIds.Variable("eq-1", "", "Speed"));
nodeIds.ShouldContain(EquipmentNodeIds.Variable("eq-1", "Diagnostics", "Temp"));
nodeIds.ShouldContain(EquipmentNodeIds.Variable("eq-2", "", "Efficiency"));
nodeIds.ShouldContain(EquipmentNodeIds.Variable("eq-2", "Calc", "Avg"));
}
/// <summary>Two VirtualTags under the SAME equipment produce two distinct folder-scoped variables
@@ -0,0 +1,194 @@
using System.Text.Json;
using Akka.Actor;
using Microsoft.EntityFrameworkCore;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Commons.Engines;
using ZB.MOM.WW.OtOpcUa.Commons.Messages.Deploy;
using ZB.MOM.WW.OtOpcUa.Commons.Messages.Fleet;
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
using ZB.MOM.WW.OtOpcUa.Commons.Types;
using ZB.MOM.WW.OtOpcUa.Configuration;
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
using ZB.MOM.WW.OtOpcUa.Configuration.Enums;
using ZB.MOM.WW.OtOpcUa.Runtime.Drivers;
using ZB.MOM.WW.OtOpcUa.Runtime.OpcUa;
using ZB.MOM.WW.OtOpcUa.Runtime.Tests.Harness;
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.Drivers;
/// <summary>
/// Verifies the equipment-tag <b>live-value routing</b> wired into <see cref="DriverHostActor"/>:
/// a driver publishes a value keyed by its wire-ref <c>FullName</c>, but the equipment variable was
/// materialised under a FOLDER-SCOPED NodeId (<c>{equipmentId}/{folderPath}/{name}</c>). After an
/// apply, the host's <c>_nodeIdByDriverRef</c> map resolves <c>(DriverInstanceId, FullName)</c> to
/// that folder-scoped NodeId, so <c>ForwardToMux</c> lands the value on the right node (and still
/// forwards the raw value to the dependency mux for VirtualTag inputs).
///
/// <para>
/// Drives a real apply through the existing harness: the seeded artifact carries the
/// <c>Namespaces</c> / <c>DriverInstances</c> / <c>Tags</c> arrays that
/// <c>DeploymentArtifact.BuildEquipmentTagPlans</c> needs to project equipment tags, and a
/// <c>DispatchDeployment</c> triggers the <c>ApplyAndAck → PushDesiredSubscriptions</c> pass
/// that builds the map. The OPC UA sink and the dependency mux are injected as
/// <see cref="Akka.TestKit.TestProbe"/>s.
/// </para>
/// </summary>
public sealed class DriverHostActorLiveValueTests : RuntimeActorTestBase
{
private static readonly NodeId TestNode = NodeId.Parse("driver-lv-test");
private static readonly RevisionHash RevA = RevisionHash.Parse(new string('a', 64));
private static readonly DateTime Ts = new(2026, 6, 13, 10, 0, 0, DateTimeKind.Utc);
/// <summary>A driver value published by FullName lands on the equipment variable's folder-scoped
/// NodeId (here <c>eq-1/speed</c>, no sub-folder), carrying the value/quality/timestamp.</summary>
[Fact]
public void Driver_value_routes_to_folder_scoped_equipment_NodeId()
{
var db = NewInMemoryDbFactory();
// One equipment tag: eq-1, drv-1, FullName "40001", no folder, Name "speed".
var deploymentId = SeedDeploymentWithEquipmentTags(db, RevA,
(Equip: "eq-1", Driver: "drv-1", FullName: "40001", Folder: null, Name: "speed"));
var (actor, publish, mux) = SpawnHostAndApply(db, deploymentId);
actor.Tell(new DriverInstanceActor.AttributeValuePublished(
"drv-1", "40001", 42.0, OpcUaQuality.Good, Ts));
var update = publish.ExpectMsg<OpcUaPublishActor.AttributeValueUpdate>(TimeSpan.FromSeconds(5));
update.NodeId.ShouldBe("eq-1/speed");
update.Value.ShouldBe(42.0);
update.Quality.ShouldBe(OpcUaQuality.Good);
update.TimestampUtc.ShouldBe(Ts);
// The raw value is still forwarded to the dependency mux (VirtualTag inputs, keyed by FullName).
mux.ExpectMsg<DriverInstanceActor.AttributeValuePublished>(TimeSpan.FromSeconds(5))
.FullReference.ShouldBe("40001");
}
/// <summary>The same driver ref backing two equipments fans out: a single publish produces one
/// <see cref="OpcUaPublishActor.AttributeValueUpdate"/> per equipment variable NodeId.</summary>
[Fact]
public void Same_ref_on_two_equipments_fans_out_to_both_NodeIds()
{
var db = NewInMemoryDbFactory();
// Same (drv-1, "40001") wire-ref backs eq-1/speed AND eq-2/speed (identical machines).
var deploymentId = SeedDeploymentWithEquipmentTags(db, RevA,
(Equip: "eq-1", Driver: "drv-1", FullName: "40001", Folder: null, Name: "speed"),
(Equip: "eq-2", Driver: "drv-1", FullName: "40001", Folder: null, Name: "speed"));
var (actor, publish, _) = SpawnHostAndApply(db, deploymentId);
actor.Tell(new DriverInstanceActor.AttributeValuePublished(
"drv-1", "40001", 7.0, OpcUaQuality.Good, Ts));
// One publish → two updates. Assert the SET of NodeIds (order is not contractual).
var first = publish.ExpectMsg<OpcUaPublishActor.AttributeValueUpdate>(TimeSpan.FromSeconds(5));
var second = publish.ExpectMsg<OpcUaPublishActor.AttributeValueUpdate>(TimeSpan.FromSeconds(5));
new[] { first.NodeId, second.NodeId }.ShouldBe(
new[] { "eq-1/speed", "eq-2/speed" }, ignoreOrder: true);
first.Value.ShouldBe(7.0);
second.Value.ShouldBe(7.0);
}
/// <summary>A value for a ref not in the composition is NOT pushed to the OPC UA sink (no matching
/// NodeId), but is still forwarded to the dependency mux.</summary>
[Fact]
public void Unmatched_ref_is_dropped_from_sink_but_still_forwarded_to_mux()
{
var db = NewInMemoryDbFactory();
var deploymentId = SeedDeploymentWithEquipmentTags(db, RevA,
(Equip: "eq-1", Driver: "drv-1", FullName: "40001", Folder: null, Name: "speed"));
var (actor, publish, mux) = SpawnHostAndApply(db, deploymentId);
actor.Tell(new DriverInstanceActor.AttributeValuePublished(
"drv-1", "59999", 99.0, OpcUaQuality.Good, Ts));
// No equipment-tag NodeId for ("drv-1","59999") → nothing reaches the sink.
publish.ExpectNoMsg(TimeSpan.FromMilliseconds(500));
// The raw publish still reaches the dependency mux.
mux.ExpectMsg<DriverInstanceActor.AttributeValuePublished>(TimeSpan.FromSeconds(5))
.FullReference.ShouldBe("59999");
}
/// <summary>Spawns the host with publish + mux probes, dispatches the deployment, and waits for the
/// Applied ACK so the apply (and thus the map build in PushDesiredSubscriptions) has completed
/// before the test publishes a value. A VirtualTag-host probe is injected so the real host isn't
/// spawned (it would consume the mux-forwarded publishes otherwise — see SpawnVirtualTagHost).</summary>
private (IActorRef Actor, Akka.TestKit.TestProbe Publish, Akka.TestKit.TestProbe Mux) SpawnHostAndApply(
IDbContextFactory<OtOpcUaConfigDbContext> db, DeploymentId deploymentId)
{
var coordinator = CreateTestProbe();
var publish = CreateTestProbe();
var mux = CreateTestProbe();
var vtHost = CreateTestProbe();
var actor = Sys.ActorOf(DriverHostActor.Props(
db, TestNode, coordinator.Ref,
localRoles: new HashSet<string> { "driver" },
dependencyMux: mux.Ref,
opcUaPublishActor: publish.Ref,
virtualTagEvaluator: NullVirtualTagEvaluator.Instance,
virtualTagHostOverride: vtHost.Ref));
actor.Tell(new DispatchDeployment(deploymentId, RevA, CorrelationId.NewId()));
coordinator.ExpectMsg<ApplyAck>(TimeSpan.FromSeconds(5)).Outcome.ShouldBe(ApplyAckOutcome.Applied);
// RebuildAddressSpace also lands on the publish probe during apply; drain it so the test's
// ExpectMsg<AttributeValueUpdate> assertions see only value updates.
publish.ExpectMsg<OpcUaPublishActor.RebuildAddressSpace>(TimeSpan.FromSeconds(5));
return (actor, publish, mux);
}
/// <summary>
/// Seeds a Sealed deployment whose artifact carries the minimal arrays
/// <c>DeploymentArtifact.BuildEquipmentTagPlans</c> needs to project equipment tags:
/// <c>Namespaces</c> (one Equipment-kind ns), <c>DriverInstances</c> (each driver bound to that
/// ns), and <c>Tags</c> (each with a non-null EquipmentId + a TagConfig blob carrying FullName).
/// </summary>
private static DeploymentId SeedDeploymentWithEquipmentTags(
IDbContextFactory<OtOpcUaConfigDbContext> db, RevisionHash rev,
params (string Equip, string Driver, string FullName, string? Folder, string Name)[] tags)
{
var driverIds = tags.Select(t => t.Driver).Distinct(StringComparer.Ordinal).ToArray();
var artifact = JsonSerializer.SerializeToUtf8Bytes(new
{
Namespaces = new[]
{
new { NamespaceId = "ns-eq", Kind = 0 }, // NamespaceKind.Equipment = 0
},
DriverInstances = driverIds.Select(d => new
{
DriverInstanceId = d,
NamespaceId = "ns-eq",
}).ToArray(),
Tags = tags.Select((t, i) => new
{
TagId = $"tag-{i}",
EquipmentId = t.Equip,
DriverInstanceId = t.Driver,
Name = t.Name,
FolderPath = t.Folder,
DataType = "Double",
TagConfig = JsonSerializer.Serialize(new { FullName = t.FullName }),
}).ToArray(),
});
var id = DeploymentId.NewId();
using var ctx = db.CreateDbContext();
ctx.Deployments.Add(new Deployment
{
DeploymentId = id.Value,
RevisionHash = rev.Value,
Status = DeploymentStatus.Sealed,
CreatedBy = "test",
SealedAtUtc = DateTime.UtcNow,
ArtifactBlob = artifact,
});
ctx.SaveChanges();
return id;
}
}
@@ -21,9 +21,9 @@ public sealed class DependencyMuxActorTests : RuntimeActorTestBase
mux.Tell(new DependencyMuxActor.RegisterInterest(new[] { "tag-1", "tag-2" }, subA.Ref));
mux.Tell(new DependencyMuxActor.RegisterInterest(new[] { "tag-2", "tag-3" }, subB.Ref));
mux.Tell(new DriverInstanceActor.AttributeValuePublished("tag-1", 10, OpcUaQuality.Good, DateTime.UtcNow));
mux.Tell(new DriverInstanceActor.AttributeValuePublished("tag-3", 30, OpcUaQuality.Good, DateTime.UtcNow));
mux.Tell(new DriverInstanceActor.AttributeValuePublished("tag-2", 20, OpcUaQuality.Good, DateTime.UtcNow));
mux.Tell(new DriverInstanceActor.AttributeValuePublished("driver-1", "tag-1", 10, OpcUaQuality.Good, DateTime.UtcNow));
mux.Tell(new DriverInstanceActor.AttributeValuePublished("driver-1", "tag-3", 30, OpcUaQuality.Good, DateTime.UtcNow));
mux.Tell(new DriverInstanceActor.AttributeValuePublished("driver-1", "tag-2", 20, OpcUaQuality.Good, DateTime.UtcNow));
// subA hears tag-1 + tag-2.
var aMsgs = new[]
@@ -53,7 +53,7 @@ public sealed class DependencyMuxActorTests : RuntimeActorTestBase
var sub = CreateTestProbe();
mux.Tell(new DependencyMuxActor.RegisterInterest(new[] { "tag-1" }, sub.Ref));
mux.Tell(new DriverInstanceActor.AttributeValuePublished("nobody-cares", 99, OpcUaQuality.Good, DateTime.UtcNow));
mux.Tell(new DriverInstanceActor.AttributeValuePublished("driver-1", "nobody-cares", 99, OpcUaQuality.Good, DateTime.UtcNow));
sub.ExpectNoMsg(TimeSpan.FromMilliseconds(200));
}
@@ -66,11 +66,11 @@ public sealed class DependencyMuxActorTests : RuntimeActorTestBase
var sub = CreateTestProbe();
mux.Tell(new DependencyMuxActor.RegisterInterest(new[] { "tag-1" }, sub.Ref));
mux.Tell(new DriverInstanceActor.AttributeValuePublished("tag-1", 10, OpcUaQuality.Good, DateTime.UtcNow));
mux.Tell(new DriverInstanceActor.AttributeValuePublished("driver-1", "tag-1", 10, OpcUaQuality.Good, DateTime.UtcNow));
sub.ExpectMsg<VirtualTagActor.DependencyValueChanged>();
mux.Tell(new DependencyMuxActor.UnregisterInterest(sub.Ref));
mux.Tell(new DriverInstanceActor.AttributeValuePublished("tag-1", 20, OpcUaQuality.Good, DateTime.UtcNow));
mux.Tell(new DriverInstanceActor.AttributeValuePublished("driver-1", "tag-1", 20, OpcUaQuality.Good, DateTime.UtcNow));
sub.ExpectNoMsg(TimeSpan.FromMilliseconds(200));
}
@@ -84,10 +84,10 @@ public sealed class DependencyMuxActorTests : RuntimeActorTestBase
mux.Tell(new DependencyMuxActor.RegisterInterest(new[] { "tag-1" }, sub.Ref));
mux.Tell(new DependencyMuxActor.RegisterInterest(new[] { "tag-2" }, sub.Ref)); // replaces tag-1
mux.Tell(new DriverInstanceActor.AttributeValuePublished("tag-1", 10, OpcUaQuality.Good, DateTime.UtcNow));
mux.Tell(new DriverInstanceActor.AttributeValuePublished("driver-1", "tag-1", 10, OpcUaQuality.Good, DateTime.UtcNow));
sub.ExpectNoMsg(TimeSpan.FromMilliseconds(200));
mux.Tell(new DriverInstanceActor.AttributeValuePublished("tag-2", 20, OpcUaQuality.Good, DateTime.UtcNow));
mux.Tell(new DriverInstanceActor.AttributeValuePublished("driver-1", "tag-2", 20, OpcUaQuality.Good, DateTime.UtcNow));
sub.ExpectMsg<VirtualTagActor.DependencyValueChanged>().TagId.ShouldBe("tag-2");
}
@@ -110,17 +110,17 @@ public sealed class DependencyMuxActorTests : RuntimeActorTestBase
AwaitAssert(() =>
{
mux.Tell(new DriverInstanceActor.AttributeValuePublished(
"ref-a", 10, OpcUaQuality.Good, DateTime.UtcNow));
"driver-1", "ref-a", 10, OpcUaQuality.Good, DateTime.UtcNow));
parent.ExpectMsg<VirtualTagActor.EvaluationResult>(TimeSpan.FromMilliseconds(200))
.Value.ShouldBe(10);
}, duration: TimeSpan.FromSeconds(3));
// From here the actor is wired — second publish drives the sum.
mux.Tell(new DriverInstanceActor.AttributeValuePublished("ref-b", 32, OpcUaQuality.Good, DateTime.UtcNow));
mux.Tell(new DriverInstanceActor.AttributeValuePublished("driver-1", "ref-b", 32, OpcUaQuality.Good, DateTime.UtcNow));
parent.ExpectMsg<VirtualTagActor.EvaluationResult>(TimeSpan.FromSeconds(2)).Value.ShouldBe(42);
// Unrelated ref shouldn't fire eval.
mux.Tell(new DriverInstanceActor.AttributeValuePublished("ref-unrelated", 99, OpcUaQuality.Good, DateTime.UtcNow));
mux.Tell(new DriverInstanceActor.AttributeValuePublished("driver-1", "ref-unrelated", 99, OpcUaQuality.Good, DateTime.UtcNow));
parent.ExpectNoMsg(TimeSpan.FromMilliseconds(200));
}
@@ -144,7 +144,7 @@ public sealed class DependencyMuxActorTests : RuntimeActorTestBase
// Tell the host an AttributeValuePublished — it should fan out to the mux + subscriber.
hostActor.Tell(new DriverInstanceActor.AttributeValuePublished(
"ref-1", 42, OpcUaQuality.Good, DateTime.UtcNow));
"driver-1", "ref-1", 42, OpcUaQuality.Good, DateTime.UtcNow));
subscriber.ExpectMsg<VirtualTagActor.DependencyValueChanged>().TagId.ShouldBe("ref-1");
}