Compare commits

...

13 Commits

Author SHA1 Message Date
Joseph Doherty f9be38430c fix(alarms): route native alarms by ConditionId (dotted FullName), not bare SourceNodeId (integration review)
v2-ci / build (push) Failing after 46s
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-14 04:09:01 -04:00
Joseph Doherty 7e86fa7099 fix(alarms): normalise native TransitionKind to canonical EmissionKind vocabulary (review) 2026-06-14 03:58:46 -04:00
Joseph Doherty 8736fcc37c feat(alarms): Primary-gated AlarmTransitionEvent fan-out for native alarms (Phase B WS-5) 2026-06-14 03:48:41 -04:00
Joseph Doherty b50ef9fc2d feat(alarms): materialise a Part 9 condition for an alarm equipment tag (Phase B WS-3) 2026-06-14 03:37:51 -04:00
Joseph Doherty 4c56a1719b feat(alarms): DriverHostActor routes native alarm transitions to Part 9 conditions (Phase B WS-4c) 2026-06-14 03:34:25 -04:00
Joseph Doherty b0e83902b8 docs(alarms): native driver-alarm TagConfig schema (Phase B) 2026-06-14 03:28:55 -04:00
Joseph Doherty 422e5b7db2 refactor(alarms): harden ExtractTagAlarm severity parse (TryGetInt32) + trim projector prior-state (review nits) 2026-06-14 03:27:03 -04:00
Joseph Doherty 25c3bd16ba feat(alarms): DriverInstanceActor forwards native OnAlarmEvent to parent (Phase B WS-4b) 2026-06-14 03:24:24 -04:00
Joseph Doherty c1aeafaaf3 feat(alarms): NativeAlarmProjector maps transitions to condition snapshots (Phase B WS-4a) 2026-06-14 03:16:44 -04:00
Joseph Doherty e1ccd99ea2 feat(alarms): EquipmentTagPlan.Alarm parsed byte-parity from TagConfig (Phase B WS-2) 2026-06-14 03:12:48 -04:00
Joseph Doherty f44d8d1e6b feat(alarms): carry transition Kind on AlarmEventArgs; Galaxy populates it (Phase B WS-1) 2026-06-14 03:04:44 -04:00
Joseph Doherty a996f03b5b docs(galaxy): Phase B native-alarms implementation plan + tasks 2026-06-14 02:58:12 -04:00
Joseph Doherty 90096e9c00 docs(galaxy): Phase B native-alarms design (equipment-tag path) 2026-06-14 02:50:34 -04:00
23 changed files with 2194 additions and 23 deletions
+65
View File
@@ -111,6 +111,71 @@ Two mapping notes specific to this adapter:
- `SubscribeAlarmsAsync` accepts a list of source-node-id filters, interpreted as Equipment-path prefixes. Empty list matches every alarm. Each emission is matched against every live subscription — the adapter keeps no per-subscription cursor.
- `IAlarmSource.AcknowledgeAsync` does not carry a user identity. The adapter defaults the audit user to `"opcua-client"` so callers using the base interface still produce an audit entry. The server's Part 9 method handlers call the engine's richer `AcknowledgeAsync` / `ConfirmAsync` / `OneShotShelveAsync` / `TimedShelveAsync` / `UnshelveAsync` / `AddCommentAsync` directly with the authenticated principal instead.
## Native driver alarms (equipment-tag path)
> Design reference: [docs/plans/2026-06-14-galaxy-phase-b-native-alarms-design.md](plans/2026-06-14-galaxy-phase-b-native-alarms-design.md)
A native driver alarm is an authored equipment `Tag` bound to an `IAlarmSource`
driver (today: Galaxy `GalaxyMxGateway`) whose `TagConfig` carries an `"alarm"`
object alongside the usual `"FullName"`:
```json
{ "FullName": "TestMachine_002.HiAlarm", "alarm": { "alarmType": "OffNormalAlarm", "severity": 700 } }
```
`"alarm"` **absent** → the tag materialises as an ordinary value variable
(unchanged behaviour). `"alarm"` **present** → the tag materialises as a Part 9
`AlarmConditionState` under its equipment folder **instead of** a value variable.
No EF/schema change is required; the intent rides in the schemaless `TagConfig`
blob and is parsed byte-parity in both the compose (`Phase7Composer`) and deploy
(`DeploymentArtifact`) paths.
### TagConfig alarm fields
| Field | Values | Default |
|---|---|---|
| `alarmType` | `"AlarmCondition"`, `"OffNormalAlarm"`, `"DiscreteAlarm"`, `"LimitAlarm"` | `"AlarmCondition"` |
| `severity` | OPC UA 1–1000 scale | `500` |
An unknown `alarmType` string falls back to the base `AlarmCondition` OPC UA
ObjectType. `severity` seeds the condition's initial severity at materialisation;
the driver's live alarm events may carry a different severity that overrides it at
runtime.
### Runtime flow
The driver's live `IAlarmSource.OnAlarmEvent` is the sole input. Transition kinds
(`Raise`, `Clear`, `Acknowledge`, `Retrigger`) drive the condition's Active /
Acknowledged / Severity / Message fields via `NativeAlarmProjector`, a pure
per-condition state projector. The projected `AlarmConditionSnapshot` is forwarded
through `DriverHostActor` → `OpcUaPublishActor.AlarmStateUpdate` →
`OtOpcUaNodeManager.WriteAlarmCondition` — the same delta-gated Part 9
condition-event path that scripted alarms use, reused verbatim.
The same `AlarmTransitionEvent` that scripted alarms publish is emitted to the
cluster `alerts` topic, so the AdminUI `/alerts` page and the Historian sink see
native alarm transitions identically. Publication to the `alerts` topic is
**Primary-gated** (only the redundancy Primary publishes cluster-wide transitions);
the OPC UA condition-node write is ungated on all nodes so a Secondary stays warm
for failover.
The alarm is authored on the `Tags` tab of the equipment page (`/uns/equipment/{id}`)
by editing the tag's raw `TagConfig` JSON to include the `"alarm"` object. No
other configuration is required.
### Deferred follow-ups
Two items are explicitly out of scope for Phase B:
1. **Inbound device-ack**: an OPC UA client `Acknowledge` currently updates the
local `AlarmConditionState` but does **not** yet propagate back to the device
via `IAlarmSource.AcknowledgeAsync` (→ AVEVA). Device-ack round-trip is a
deferred follow-up.
2. **AdminUI Galaxy address-picker pre-fill**: the `alarm` object must be authored
by editing the tag's raw `TagConfig` JSON today; a future picker enhancement
could pre-fill `alarmType` / `severity` from driver discovery
(`DriverAttributeInfo.IsAlarm`).
## Inbound operator ack/shelve
Operators interact with active scripted alarms through two surfaces — both converge on the same `alarm-commands` DPS topic consumed by `ScriptedAlarmHostActor`.
@@ -0,0 +1,265 @@
# Galaxy Phase B — Native Alarms on the Equipment-Tag Path — Design
**Date:** 2026-06-14
**Status:** Approved (brainstorming) — ready for implementation planning
**Scope:** Phase B of the Galaxy standard-driver design
(`docs/plans/2026-06-12-galaxy-standard-driver-design.md`). Restores native
`IAlarmSource` alarms in the post-Phase-A Equipment model, delivered over a new
driver→server alarm seam that mirrors the scripted-alarm seam.
**Builds on:** master (Milestone 1b complete — equipment-tag live values + write
pipeline shipped). Feature branch off master.
## Goal
A Galaxy equipment `Tag` bound to `GalaxyMxGateway` and marked as a **native
alarm** materializes a real OPC UA Part 9 `AlarmConditionState` under its
equipment folder, and the driver's live `IAlarmSource.OnAlarmEvent` transitions
drive that condition (active / severity / message / ack-state) and fan out to the
`alerts` topic (AdminUI `/alerts` + historian), exactly as scripted alarms do
today. **No EF/schema migration.**
## Why this is needed (the gap, grounded in current code)
Phase A retired the `SystemPlatform` mirror (`MaterialiseGalaxyTags` +
`GenericDriverNodeManager`), which was the **only** path that wired native
alarms. Three concrete consequences, all verified against current code:
1. **No cross-actor transport for native alarms.** In the fused-host actor model,
`DriverInstanceActor` subscribes the driver's `ISubscribable.OnDataChange`
(value seam) but **never** subscribes `IAlarmSource.OnAlarmEvent`. No actor
message carries an alarm transition. `GenericDriverNodeManager`
(`src/Core/.../OpcUa/GenericDriverNodeManager.cs`) subscribed `OnAlarmEvent`
**in-process**; it is now orphaned (only tests construct it).
2. **No condition-update sink survives.** There is no production
`IAlarmConditionSink.OnTransition` implementation anymore — only the interface
(`IAddressSpaceBuilder.cs:115`) and an empty CLI stub
(`TwinCAT.Cli/.../BrowseCommand.cs:150`). The real sink lived in the mirror's
builder and died with it. The surviving condition path is the **snapshot**
path: `OpcUaPublishActor.AlarmStateUpdate` → `OtOpcUaNodeManager.WriteAlarmCondition`.
3. **Authored tags carry no alarm flag.** Native-alarm metadata came from driver
discovery (`DriverAttributeInfo.IsAlarm`), but Phase 7 composes from authored
`Tag` rows only. `EquipmentTagPlan` carries `{TagId, EquipmentId,
DriverInstanceId, FolderPath, Name, DataType, FullName, Writable}` — **no
alarm field**. The `Tag` entity has no alarm column.
**Decisive design fact:** `AlarmEventArgs` (the `OnAlarmEvent` payload) does
**not** carry the transition kind. `GalaxyAlarmTransition` has an explicit
`GalaxyAlarmTransitionKind {Raise, Acknowledge, Clear, Retrigger}`, but
`GalaxyDriver.OnAlarmFeedTransition` drops it when building `AlarmEventArgs`. A
consumer therefore cannot tell raise-from-clear. Phase B fixes this at the source
(additive contract change) rather than guessing.
## Locked decisions (from brainstorming)
| Decision | Choice |
|---|---|
| How the server learns a tag is a native alarm | **TagConfig JSON (no migration).** The alarm intent rides in the schemaless `TagConfig` blob — `{"FullName":"…","alarm":{"alarmType":"OffNormalAlarm","severity":500}}` — parsed byte-parity in `Phase7Composer` + `DeploymentArtifact`, exactly as `FullName` is today. No EF/schema change. |
| Phase B scope line | **Live condition + alerts fan-out; defer device-ack.** Trip → Part 9 condition + `/alerts` + historian (Primary-gated). A client Acknowledge updates the **local** condition state; routing it back to the driver's `IAlarmSource.AcknowledgeAsync` (→ AVEVA) is a deferred follow-up. |
| Transition→state model | **Snapshot projection.** Reuse the scripted-alarm sink path (`WriteAlarmCondition` + delta-gate + `ReportConditionEvent` + Part-9 ack mechanics) unchanged; a new pure projector derives an `AlarmConditionSnapshot` from each transition. The retired `OnTransition` sink path is **not** resurrected. |
| Transition-kind plumbing | **Additive contract change.** Add `AlarmTransitionKind Kind` to `AlarmEventArgs` (default `Unspecified`); `GalaxyDriver` populates it from the kind it already has. A record default keeps every other `IAlarmSource` implementer compiling. |
### Approaches considered and rejected
- **Resurrect the `IAlarmConditionSink`/`OnTransition` builder path.** Rejected:
reintroduces a second condition-state mechanism alongside the live, delta-gated,
ack-wired `WriteAlarmCondition` path. The snapshot path is the one that works
for scripted alarms today.
- **Auto-discover the alarm flag at deploy** (query driver `DriverAttributeInfo`
during composition). Rejected (this session): couples Phase 7 composition to a
cross-process discovery query; larger and higher-risk than reading the authored
blob. The TagConfig route matches the protocol-linkage precedent.
- **Extend the `Tag` entity with `IsAlarm`/`AlarmType` columns.** Rejected:
requires a Configuration/EF migration, out of scope for this phase.
- **Infer raise/clear from `AlarmEventArgs` heuristically.** Rejected: the record
has no active flag; inference is fragile and wrong. Fix the contract instead.
## Architecture (target end-state)
```
Author Tag{Equipment, GalaxyMxGateway, TagConfig={FullName, alarm:{alarmType,severity}}}
→ Phase7Composer / DeploymentArtifact (ExtractTagAlarm, byte-parity)
→ EquipmentTagPlan.Alarm != null
→ Phase7Applier.MaterialiseEquipmentTags
• Alarm == null : SafeEnsureVariable (today's value variable, unchanged)
• Alarm != null : SafeMaterialiseAlarmCondition(nodeId, equip, name, alarmType, severity)
→ real Part 9 AlarmConditionState under the equipment folder (reused)
Runtime (the NEW seam — mirrors the scripted-alarm seam):
GalaxyDriver.OnAlarmEvent (AlarmEventArgs{SourceNodeId=FullName, Kind, Severity, …})
→ DriverInstanceActor (subscribes OnAlarmEvent; marshals via Self.Tell)
→ AttributeAlarmPublished(DriverInstanceId, AlarmEventArgs) [NEW msg, parallels AttributeValuePublished]
→ DriverHostActor.ForwardNativeAlarm
• resolve (DriverInstanceId, SourceNodeId) → condition NodeId(s) via _alarmNodeIdByDriverRef [NEW map]
• NativeAlarmProjector.Project(nodeId, args) → AlarmConditionSnapshot [NEW pure helper]
• Tell OpcUaPublishActor.AlarmStateUpdate(nodeId, snapshot, ts) (UNGATED — warm on all nodes) [REUSED]
• Publish AlarmTransitionEvent → `alerts` topic (Primary-gated — reuse _localRole) [REUSED]
→ OtOpcUaNodeManager.WriteAlarmCondition → delta-gate → ReportConditionEvent (real Part 9 event) [REUSED]
```
`OpcUaPublishActor` and `OtOpcUaNodeManager` are **unchanged** — Phase B reuses
`AlarmStateUpdate` → `WriteAlarmCondition` verbatim.
## Components / workstreams
### WS-1 — Transition-kind contract (additive, Core.Abstractions)
- New enum `AlarmTransitionKind { Unspecified = 0, Raise, Acknowledge, Clear, Retrigger }`
(mirrors the internal `GalaxyAlarmTransitionKind`).
- `AlarmEventArgs` gains a trailing `AlarmTransitionKind Kind = AlarmTransitionKind.Unspecified`
param (record default → all existing implementers compile untouched).
- `GalaxyDriver.OnAlarmFeedTransition` (`GalaxyDriver.cs:~1128-1167`) populates
`Kind` from `transition.TransitionKind`.
### WS-2 — Alarm intent in TagConfig + compose plan (no EF)
- New never-throw `ExtractTagAlarm(string tagConfig) → EquipmentTagAlarmInfo?`
(parses the optional `"alarm"` object: `alarmType` default `"AlarmCondition"`,
`severity` default `500`; absent/malformed → null). Lives next to
`ExtractTagFullName`; **used by both** `Phase7Composer` and `DeploymentArtifact`.
- `EquipmentTagPlan` (`Phase7Composer.cs:~80`) gains `EquipmentTagAlarmInfo? Alarm`
(`record EquipmentTagAlarmInfo(string AlarmType, int Severity)`); null ⇒ plain
variable. Populated in `Phase7Composer` `Select(...)` **and**
`DeploymentArtifact.BuildEquipmentTagPlans` — **byte-parity invariant**, covered
by a round-trip test.
### WS-3 — Materialize the condition node (reuse)
- `Phase7Applier.MaterialiseEquipmentTags` (`:~162-199`) branches per tag:
`tag.Alarm is not null` → `SafeMaterialiseAlarmCondition(nodeId, parentEquipment,
tag.Name, tag.Alarm.AlarmType, tag.Alarm.Severity)` (the **same** method scripted
alarms use; condition NodeId = the tag's equipment-scoped NodeId); else →
`SafeEnsureVariable(...)` (today). `RebuildAddressSpace` already clears
`_alarmConditions`, so redeploy teardown is covered.
### WS-4 — The driver→server alarm seam (the new plumbing)
- **`DriverInstanceActor`**: on connect, if `_driver is IAlarmSource src`, subscribe
`src.OnAlarmEvent += handler`; the handler marshals to the actor thread via
`Self.Tell(new NativeAlarmRaised(e))` (mirrors the `_dataChangeHandler` pattern,
`:409/:456`). `Receive<NativeAlarmRaised>` → `Context.Parent.Tell(new
AttributeAlarmPublished(DriverInstanceId, Args))`. Unsubscribe on
disconnect/teardown (mirror the `OnDataChange` unsubscribe). New messages
`NativeAlarmRaised` (internal) + `AttributeAlarmPublished` (parallels
`AttributeValuePublished`, `:65`). Phase B follows the mirror's model: subscribe
the event and let the server filter by `SourceNodeId`; it does **not** drive
`SubscribeAlarmsAsync` (Galaxy's feed auto-starts session-less in
`InitializeAsync` and fires `OnAlarmEvent` regardless). Driving
`SubscribeAlarmsAsync` from the materialized alarm-ref set, for drivers that gate
on it, is a noted follow-up.
- **`DriverHostActor`**: build `_alarmNodeIdByDriverRef: (DriverInstanceId,
FullName) → HashSet<NodeId>` from equipment-tag plans where `Alarm != null`
(alongside the existing `_nodeIdByDriverRef`, in the same apply pass). Add
`Receive<AttributeAlarmPublished>` in the steady + applying states. Handler
`ForwardNativeAlarm`: resolve nodeIds (unknown ref → drop silently, mirror
behavior); per nodeId `NativeAlarmProjector.Project(...)` → snapshot →
`_publishActor.Tell(AlarmStateUpdate(nodeId, snapshot, ts))` **ungated**; then
publish `AlarmTransitionEvent` to `alerts` **Primary-gated** via the existing
`_localRole` the write-routing already tracks.
- **`NativeAlarmProjector`** (new pure class; unit-tested): per-condition-NodeId
prior-state `(Active, Acked, Severity, Message)`; `Project(nodeId, AlarmEventArgs)
→ AlarmConditionSnapshot` by `Kind`:
- `Raise`/`Retrigger` → `Active=true, Acked=false`, severity+message from event.
- `Acknowledge` → `Acked=true` (keep prior Active), carry `OperatorComment`.
- `Clear` → `Active=false` (keep prior Acked).
- `Unspecified` → keep prior Active/Acked, refresh severity+message.
- `Enabled=true`, `Confirmed=true`, `Shelving=Unshelved` (shelving is a
server/local concern). Severity: `AlarmSeverity` 4-bucket → 1..1000 ushort
(Low→200, Medium→500, High→700, Critical→900).
### WS-5 — Historian / alerts parity (reuse)
- The `AlarmTransitionEvent` published in WS-4 is the same contract
`ScriptedAlarmHostActor` publishes; `HistorianAdapterActor` + AdminUI `/alerts`
consume it unchanged. Populate `AlarmId` = condition NodeId, `EquipmentPath` +
`AlarmName` from the plan, `TransitionKind` = `Kind.ToString()`, `AlarmTypeName`
= the configured OPC UA alarm type, `User`/`Comment` from the event.
## Data type / severity mapping
- OPC UA alarm subtype string → SDK type via the existing
`CreateAlarmConditionOfType` (`OffNormalAlarm`/`DiscreteAlarm`/`LimitAlarm`/base).
- `AlarmSeverity` (4-bucket) → 1..1000 via the projector map above; the authored
`severity` seeds the condition's initial severity at materialization
(`MaterialiseAlarmCondition`'s `MapSeverity`).
## Error handling / edge cases
- **Unknown `SourceNodeId`** (no materialized condition for the ref): drop
silently — preserves `GenericDriverNodeManager`'s documented behavior.
- **Byte-parity** between `Phase7Composer` and `DeploymentArtifact` for alarm tags:
parity round-trip test (the established invariant).
- **Redeploy double-delivery**: `DriverInstanceActor` unsubscribes `OnAlarmEvent`
on teardown; `WriteAlarmCondition`'s delta-gate independently suppresses
duplicate events; `RebuildAddressSpace` clears `_alarmConditions`.
- **Transition before condition materialized / after rebuild**: unknown-ref drop
handles it; the projector's prior-state dict is keyed by NodeId and tolerates a
cold start (first event seeds state).
- **A tag with both a value and an alarm intent**: Phase B treats an `alarm`-marked
tag as a **condition node only** (not also a plain variable) — matching the
retired mirror, where an alarm attribute surfaced as a condition.
## Testing (no bUnit)
**xUnit + Shouldly (offline):**
- `ExtractTagAlarm`: present / absent / malformed / defaults / unknown-keys-preserved.
- `Phase7Composer` ↔ `DeploymentArtifact` byte-parity with alarm-bearing equipment tags.
- `NativeAlarmProjector`: Raise→active+unacked, Acknowledge→acked, Clear→inactive,
Retrigger, Unspecified, severity-bucket map, prior-state carry.
- `GalaxyDriver.OnAlarmFeedTransition` populates `Kind`.
- Akka.TestKit — `DriverInstanceActor`: a fake `IAlarmSource` driver fires
`OnAlarmEvent` → the actor publishes `AttributeAlarmPublished` to its parent;
unsubscribes on teardown.
- Akka.TestKit — `DriverHostActor`: `AttributeAlarmPublished` resolves the ref →
Tells `AlarmStateUpdate` with the projected snapshot; unknown ref dropped;
`alerts` publish is Primary-gated (secondary suppresses).
**Live docker-dev `/run` (user-driven; the agent does NOT sign in)** — the gate:
- Author a Galaxy alarm equipment tag (raw `TagConfig` carrying the `alarm` object)
on the live-gateway-backed `MAIN-galaxy-eq`; deploy.
- Trip the Galaxy alarm → a Part 9 `AlarmConditionState` appears active under the
equipment via Client.CLI `alarms` (and `read`); the AdminUI `/alerts` row appears.
- Clear → condition goes inactive. (Device-ack round-trip is the deferred
follow-up, not part of this gate.)
## Suggested slicing (for the plan)
1. **WS-1** — `AlarmTransitionKind` + `AlarmEventArgs.Kind` + Galaxy populates it
(small/standard; touches a Core.Abstractions contract → ripples to implementers).
2. **WS-2** — `ExtractTagAlarm` + `EquipmentTagPlan.Alarm` in both composer +
artifact + parity test (high-risk: data-contract byte-parity).
3. **WS-3** — `MaterialiseEquipmentTags` alarm branch (standard; reuses
`MaterialiseAlarmCondition`).
4. **WS-4a** — `NativeAlarmProjector` (standard; pure, fully TDD-able offline).
5. **WS-4b** — `DriverInstanceActor` `OnAlarmEvent` subscription + publish (high-risk:
actor state machine + driver-thread marshaling).
6. **WS-4c** — `DriverHostActor` alarm map + `ForwardNativeAlarm` + Primary-gated
alerts publish (high-risk: actor/concurrency/redundancy gate).
7. **WS-5** — wire `AlarmTransitionEvent` fields (folds into WS-4c; verify historian
+ `/alerts` consume it).
8. **Docs** — document the `TagConfig` `alarm` schema (a Galaxy/alarms doc note).
9. **Live `/run`** — the gate above (user-driven).
## Deferred follow-ups (explicitly out of Phase B)
- **Inbound device-ack**: client Acknowledge → `IAlarmSource.AcknowledgeAsync` →
AVEVA (its own inbound pipeline, mirrors the write-through work).
- **`SubscribeAlarmsAsync` from the materialized alarm-ref set** for drivers that
gate their feed on it (Galaxy doesn't).
- **AdminUI Galaxy picker pre-fill** of the `alarm` object from discovery
(`IsAlarm`/`SecurityClass` already known) — a UI convenience; raw-JSON authoring
works without it and avoids live-only Razor binding risk.
- Carrying the raw OPC UA severity (vs. the 4-bucket) end-to-end.
## Hard rules (carried into implementation)
- Stage by path; never `git add .`. Never stage `sql_login.txt`,
`src/Server/ZB.MOM.WW.OtOpcUa.Host/pki/`, `pending.md`, `current.md`, or
`docker-dev/docker-compose.yml`.
- Never echo the gateway API key or any secret into a tracked file.
- No force-push, no `--no-verify`.
- **No Configuration entity / EF migration change** (the TagConfig route is chosen
specifically to honor this).
- No bUnit; Razor/JS proven only by live `/run`.
- Build on a feature branch off master.
## Authoritative touched-code list (for planning)
- `src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/IAlarmSource.cs` (`AlarmEventArgs.Kind`, new enum)
- `src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy/GalaxyDriver.cs` (`OnAlarmFeedTransition` populates `Kind`)
- `src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/Phase7Composer.cs` (`EquipmentTagPlan.Alarm`, `ExtractTagAlarm`)
- `src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DeploymentArtifact.cs` (`BuildEquipmentTagPlans` parity)
- `src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/Phase7Applier.cs` (`MaterialiseEquipmentTags` alarm branch)
- `src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverInstanceActor.cs` (`OnAlarmEvent` sub + publish)
- `src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverHostActor.cs` (alarm map + `ForwardNativeAlarm` + gated publish)
- NEW `NativeAlarmProjector` (Runtime or Commons) + its tests
- `OpcUaPublishActor` / `OtOpcUaNodeManager` — **no change** (reuse `AlarmStateUpdate`/`WriteAlarmCondition`)
- A docs note for the `TagConfig` `alarm` schema
```
@@ -0,0 +1,622 @@
# Galaxy Phase B — Native Alarms on the Equipment-Tag Path — Implementation Plan
> **For Claude:** REQUIRED SUB-SKILL: Use superpowers-extended-cc:executing-plans (or subagent-driven-development) to implement this plan task-by-task.
**Goal:** A Galaxy equipment `Tag` marked as a native alarm (via its `TagConfig` JSON) materializes a real OPC UA Part 9 `AlarmConditionState` under its equipment folder, and the driver's live `IAlarmSource.OnAlarmEvent` transitions drive that condition (active/severity/message/ack) and fan out to the `alerts` topic — mirroring the scripted-alarm seam. **No EF/schema migration.**
**Architecture:** Three reused layers + one new seam. (1) Alarm intent rides in the schemaless `TagConfig` blob, parsed byte-parity in `Phase7Composer` + `DeploymentArtifact` (`EquipmentTagPlan.Alarm`). (2) `Phase7Applier.MaterialiseEquipmentTags` branches: alarm tag → the existing `MaterialiseAlarmCondition` (reused verbatim), else the existing `EnsureVariable`. (3) A new driver→server alarm seam: `DriverInstanceActor` subscribes `IAlarmSource.OnAlarmEvent` (mirroring its `OnDataChange` subscription) and publishes `AttributeAlarmPublished` to `DriverHostActor`, which projects each transition into the existing `AlarmConditionSnapshot` (`NativeAlarmProjector`) and Tells the unchanged `OpcUaPublishActor.AlarmStateUpdate` → `OtOpcUaNodeManager.WriteAlarmCondition`, plus a Primary-gated `AlarmTransitionEvent` to `alerts`. A small additive contract change adds the transition `Kind` to `AlarmEventArgs` (the driver already has it; the record's surviving consumers compile via a default).
**Tech Stack:** C#/.NET 10, Akka.NET (fused-host actors, Akka.TestKit.Xunit2 — **xUnit v2**, use `CancellationToken.None` not `TestContext.Current`), xUnit + Shouldly, OPC Foundation UA stack. No bUnit — Razor/live paths proven only by the user-driven docker-dev `/run` gate.
**Design:** `docs/plans/2026-06-14-galaxy-phase-b-native-alarms-design.md` (master `90096e9c`).
**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`, `current.md`, `docker-dev/docker-compose.yml`; never echo secrets; no force-push, no `--no-verify`; **NO Configuration entity / EF migration change**; no bUnit. Commit per task by path.
---
### Task 0: Feature branch
**Classification:** trivial
**Estimated implement time:** ~1 min
**Parallelizable with:** none
**Step 1:** From master at `90096e9c`:
```bash
cd /Users/dohertj2/Desktop/OtOpcUa
git checkout master && git rev-parse --short HEAD # expect 90096e9c
git checkout -b feat/galaxy-phase-b-native-alarms
```
No code change. Do NOT touch the working-tree `docker-dev/docker-compose.yml` or `pending.md`.
---
### Task 1: Transition-kind contract (`AlarmEventArgs.Kind`) + Galaxy populates it — WS-1
**Classification:** standard
**Estimated implement time:** ~4 min
**Parallelizable with:** Task 2
**Files:**
- Modify: `src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/IAlarmSource.cs` (add enum `AlarmTransitionKind`; add trailing `Kind` param to `AlarmEventArgs`)
- Modify: `src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy/GalaxyDriver.cs:~1128-1167` (`OnAlarmFeedTransition` maps `transition.TransitionKind` → `Kind`)
- Test: `tests/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions.Tests/` (new `AlarmEventArgsTests.cs`)
- Test: `tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Tests/` (extend the existing alarm-feed/transition test, or add `GalaxyAlarmTransitionKindTests.cs`)
**Context:** `GalaxyAlarmTransition` (`Driver.Galaxy/Runtime/GalaxyAlarmTransition.cs`) carries `GalaxyAlarmTransitionKind {Unspecified=0, Raise=1, Acknowledge=2, Clear=3, Retrigger=4}` but `OnAlarmFeedTransition` drops it when building `AlarmEventArgs`. Other `IAlarmSource` implementers (FOCAS/OpcUaClient/AbCip/ScriptedAlarmSource) construct `AlarmEventArgs` without a kind — a record default keeps them compiling untouched.
**Step 1 (failing test — contract):** In `AlarmEventArgsTests.cs`:
```csharp
using Shouldly;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using Xunit;
namespace ZB.MOM.WW.OtOpcUa.Core.Abstractions.Tests;
public class AlarmEventArgsTests
{
private static AlarmEventArgs Make(AlarmTransitionKind? kind = null) =>
kind is null
? new AlarmEventArgs(new FakeHandle(), "Tank1.Hi", "c1", "LimitAlarm.Hi", "msg", AlarmSeverity.High, DateTime.UnixEpoch)
: new AlarmEventArgs(new FakeHandle(), "Tank1.Hi", "c1", "LimitAlarm.Hi", "msg", AlarmSeverity.High, DateTime.UnixEpoch, Kind: kind.Value);
[Fact]
public void Kind_defaults_to_Unspecified_so_existing_callers_compile()
=> Make().Kind.ShouldBe(AlarmTransitionKind.Unspecified);
[Fact]
public void Kind_round_trips_when_supplied()
=> Make(AlarmTransitionKind.Raise).Kind.ShouldBe(AlarmTransitionKind.Raise);
private sealed class FakeHandle : IAlarmSubscriptionHandle { public string DiagnosticId => "t"; }
}
```
Run: `dotnet test tests/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions.Tests --filter AlarmEventArgsTests` → FAIL (no `Kind`, no `AlarmTransitionKind`).
**Step 2 (implement contract):** In `IAlarmSource.cs`, add the enum (next to `AlarmSeverity`) and the `Kind` param as the **last** parameter of `AlarmEventArgs` (after `AlarmCategory`):
```csharp
/// <summary>The kind of alarm state change. Mirrors the driver-internal transition kinds so a
/// consumer can derive Part 9 active/ack state without a separate value subscription. Defaults to
/// <see cref="Unspecified"/> so existing <see cref="IAlarmSource"/> implementers compile unchanged.</summary>
public enum AlarmTransitionKind { Unspecified = 0, Raise, Acknowledge, Clear, Retrigger }
```
```csharp
// …existing params…
string? AlarmCategory = null,
AlarmTransitionKind Kind = AlarmTransitionKind.Unspecified);
```
Add a `/// <param name="Kind">…</param>` doc line to the record's XML doc (the project sets `TreatWarningsAsErrors` — a missing `<param>` for a documented record is a build error).
**Step 3 (failing test — Galaxy mapping):** Confirm how the existing Galaxy tests feed a `GalaxyAlarmTransition` onto `OnAlarmEvent` (grep `OnAlarmFeedTransition`/`OnAlarmEvent` in `tests/Drivers/.../Driver.Galaxy.Tests`). Add a test that, for each `GalaxyAlarmTransitionKind`, the surfaced `AlarmEventArgs.Kind` equals the matching `AlarmTransitionKind`. If the test harness can't reach the private `OnAlarmFeedTransition`, extract a tiny `internal static AlarmTransitionKind MapKind(GalaxyAlarmTransitionKind)` and test that directly (mark `Driver.Galaxy` `InternalsVisibleTo` the test project if not already — grep for it first).
Run → FAIL.
**Step 4 (implement Galaxy mapping):** In `GalaxyDriver.OnAlarmFeedTransition`, add `Kind:` to the `new AlarmEventArgs(...)`:
```csharp
Kind: transition.TransitionKind switch
{
GalaxyAlarmTransitionKind.Raise => AlarmTransitionKind.Raise,
GalaxyAlarmTransitionKind.Acknowledge => AlarmTransitionKind.Acknowledge,
GalaxyAlarmTransitionKind.Clear => AlarmTransitionKind.Clear,
GalaxyAlarmTransitionKind.Retrigger => AlarmTransitionKind.Retrigger,
_ => AlarmTransitionKind.Unspecified,
});
```
**Step 5:** `dotnet build src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions` then run both test filters → PASS. Build the full solution (`dotnet build ZB.MOM.WW.OtOpcUa.slnx`) to confirm no other `IAlarmSource` implementer broke.
**Step 6 (commit):**
```bash
git add src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/IAlarmSource.cs \
src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy/GalaxyDriver.cs \
tests/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions.Tests/AlarmEventArgsTests.cs \
tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Tests/<the test file>
git commit -m "feat(alarms): carry transition Kind on AlarmEventArgs; Galaxy populates it (Phase B WS-1)"
```
---
### Task 2: Alarm intent in TagConfig → `EquipmentTagPlan.Alarm` (byte-parity) — WS-2
**Classification:** high-risk
**Estimated implement time:** ~5 min
**Parallelizable with:** Task 1
**Files:**
- Modify: `src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/Phase7Composer.cs` (`EquipmentTagPlan` record `:80-88`; new `EquipmentTagAlarmInfo`; `Select(...)` `:323-331`; new `ExtractTagAlarm` next to `ExtractTagFullName` `:432`)
- Modify: `src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DeploymentArtifact.cs` (`BuildEquipmentTagPlans` `:440-448`; new `ExtractTagAlarm` mirror next to `ExtractTagFullName` `:637`)
- Test: `tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/` (new `ExtractTagAlarmTests.cs`; extend the existing composer↔artifact parity test)
**Context — the byte-parity invariant:** `Phase7Composer` (compose from DB rows) and `DeploymentArtifact.BuildEquipmentTagPlans` (decode the deployment artifact JSON) MUST produce identical `EquipmentTagPlan`s for the same input — there is an existing parity test (grep `EquipmentTagPlan` in `OpcUaServer.Tests` for the parity fixture). The `alarm` object rides in the same `TagConfig` blob `FullName` already does, so both sides parse it the same way. Absent/malformed `alarm` ⇒ `null` (plain variable). TagConfig shape:
```json
{ "FullName": "TestMachine_002.HiAlarm", "alarm": { "alarmType": "OffNormalAlarm", "severity": 700 } }
```
`alarmType` default `"AlarmCondition"`, `severity` default `500` (mirrors `ScriptedAlarm` defaults). Valid `alarmType` strings are whatever `OtOpcUaNodeManager.CreateAlarmConditionOfType` accepts (`OffNormalAlarm`/`DiscreteAlarm`/`LimitAlarm`/`AlarmCondition`); an unknown string falls back to the base type downstream — do not validate here.
**Step 1 (failing test — `ExtractTagAlarm`):** In `ExtractTagAlarmTests.cs` (test the composer's private helper via `[InternalsVisibleTo]` if present, else assert through `ComposeAsync`/the plan; prefer a thin `internal static` so both helpers can be unit-tested):
```csharp
[Theory]
[InlineData("{\"FullName\":\"X.Y\"}", false, null, 0)] // no alarm ⇒ null
[InlineData("{\"FullName\":\"X.Y\",\"alarm\":{}}", true, "AlarmCondition", 500)] // defaults
[InlineData("{\"FullName\":\"X.Y\",\"alarm\":{\"alarmType\":\"OffNormalAlarm\",\"severity\":700}}", true, "OffNormalAlarm", 700)]
[InlineData("not json", false, null, 0)] // malformed ⇒ null
[InlineData("{\"FullName\":\"X.Y\",\"alarm\":\"oops\"}", false, null, 0)] // wrong kind ⇒ null
public void ExtractTagAlarm_parses_or_returns_null(string cfg, bool present, string? type, int sev)
{
var info = Phase7Composer.ExtractTagAlarm(cfg); // make it internal static
if (!present) { info.ShouldBeNull(); return; }
info!.AlarmType.ShouldBe(type);
info.Severity.ShouldBe(sev);
}
```
Run → FAIL.
**Step 2 (implement `EquipmentTagAlarmInfo` + `EquipmentTagPlan.Alarm`):** In `Phase7Composer.cs`, next to `EquipmentTagPlan`:
```csharp
/// <summary>Native-alarm intent parsed from an equipment tag's <c>TagConfig.alarm</c> object. Null ⇒
/// the tag is a plain value variable. <see cref="AlarmType"/> is an OPC UA Part 9 subtype string
/// (OffNormalAlarm/DiscreteAlarm/LimitAlarm/AlarmCondition); <see cref="Severity"/> is the 1..1000 scale.</summary>
public sealed record EquipmentTagAlarmInfo(string AlarmType, int Severity);
```
Add `EquipmentTagAlarmInfo? Alarm` as the **last** field of `EquipmentTagPlan` (after `Writable`). Update the record's XML doc with a `<see cref="Alarm"/>` sentence.
**Step 3 (implement `ExtractTagAlarm` — composer):** Next to `ExtractTagFullName`:
```csharp
/// <summary>Parses the optional <c>alarm</c> object from a tag's <c>TagConfig</c> JSON. Returns null
/// when absent, non-object, or non-JSON (the tag is then a plain variable). Never throws. The
/// artifact-decode side (<c>DeploymentArtifact.ExtractTagAlarm</c>) MUST parse identically (byte-parity).</summary>
internal static EquipmentTagAlarmInfo? ExtractTagAlarm(string? tagConfig)
{
if (string.IsNullOrWhiteSpace(tagConfig)) return null;
try
{
using var doc = JsonDocument.Parse(tagConfig);
if (doc.RootElement.ValueKind != JsonValueKind.Object) return null;
if (!doc.RootElement.TryGetProperty("alarm", out var a) || a.ValueKind != JsonValueKind.Object) return null;
var type = a.TryGetProperty("alarmType", out var tEl) && tEl.ValueKind == JsonValueKind.String
? (tEl.GetString() ?? "AlarmCondition") : "AlarmCondition";
var sev = a.TryGetProperty("severity", out var sEl) && sEl.ValueKind == JsonValueKind.Number
? sEl.GetInt32() : 500;
return new EquipmentTagAlarmInfo(type, sev);
}
catch (JsonException) { return null; }
}
```
Wire it into the `Select(...)` at `:331` (add after `Writable:`):
```csharp
Writable: t.AccessLevel == TagAccessLevel.ReadWrite,
Alarm: ExtractTagAlarm(t.TagConfig)))
```
**Step 4 (implement `ExtractTagAlarm` — artifact mirror, byte-identical):** In `DeploymentArtifact.cs`, add a private `ExtractTagAlarm(string? tagConfig)` with the **same body** (it constructs the same `EquipmentTagAlarmInfo` — Runtime already references the assembly defining `EquipmentTagPlan`, so the type is in scope). Wire into `BuildEquipmentTagPlans` `:448`:
```csharp
Writable: writable,
Alarm: ExtractTagAlarm(tagConfig)));
```
**Step 5 (failing test — parity):** Extend the existing composer↔artifact parity fixture with an alarm-bearing equipment tag (TagConfig carrying the `alarm` object) and assert the composed `EquipmentTagPlan.Alarm` equals the artifact-decoded one (record equality covers it). Run the parity test → it now exercises `Alarm`.
**Step 6:** `dotnet test tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests --filter "ExtractTagAlarm|Parity"` → PASS. Full build clean.
**Step 7 (commit):**
```bash
git add src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/Phase7Composer.cs \
src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DeploymentArtifact.cs \
tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/ExtractTagAlarmTests.cs \
tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/<parity fixture file>
git commit -m "feat(alarms): EquipmentTagPlan.Alarm parsed byte-parity from TagConfig (Phase B WS-2)"
```
---
### Task 3: Materialize a condition node for an alarm tag — WS-3
**Classification:** standard
**Estimated implement time:** ~3 min
**Parallelizable with:** Task 4, Task 5
**Files:**
- Modify: `src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/Phase7Applier.cs:186-193` (`MaterialiseEquipmentTags` variable loop)
- Test: `tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/` (extend the Phase7Applier materialise tests)
**Context:** `MaterialiseEquipmentTags` currently calls `SafeEnsureVariable(...)` for every tag (`:192`). `SafeMaterialiseAlarmCondition(alarmNodeId, equipmentNodeId, displayName, alarmType, severity)` already exists (`:309`) — the same one scripted alarms use. An alarm tag becomes a **condition node only** (not also a variable). The condition NodeId = the tag's folder-scoped NodeId (`EquipmentNodeIds.Variable(...)`, same formula). Use the **sub-folder** as the condition's parent when `FolderPath` is set (the variable loop already computes `parent`).
**Step 1 (failing test):** With the existing test sink (grep the materialise tests for the fake/recording `IOpcUaAddressSpaceSink`), feed a composition whose `EquipmentTags` contains one plain tag and one `Alarm != null` tag; assert the plain one called `EnsureVariable` and the alarm one called `MaterialiseAlarmCondition` (with the matching nodeId/type/severity) and did **not** call `EnsureVariable`. Run → FAIL.
**Step 2 (implement the branch):** Replace the `SafeEnsureVariable(...)` call at `:192` with:
```csharp
if (tag.Alarm is not null)
{
// Native alarm tag → a real Part 9 condition node (reuses the scripted-alarm path),
// NOT a value variable. Parent is the sub-folder when set, else the equipment folder.
SafeMaterialiseAlarmCondition(nodeId, parent, tag.Name, tag.Alarm.AlarmType, tag.Alarm.Severity);
}
else
{
SafeEnsureVariable(nodeId, parent, tag.Name, tag.DataType, tag.Writable);
}
```
**Step 3:** `dotnet test tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests --filter MaterialiseEquipmentTags` → PASS.
**Step 4 (commit):**
```bash
git add src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/Phase7Applier.cs \
tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/<applier test file>
git commit -m "feat(alarms): materialise a Part 9 condition for an alarm equipment tag (Phase B WS-3)"
```
---
### Task 4: `NativeAlarmProjector` (transition → snapshot) — WS-4a
**Classification:** standard
**Estimated implement time:** ~5 min
**Parallelizable with:** Task 3, Task 5
**Files:**
- Create: `src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/NativeAlarmProjector.cs`
- Test: `tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/NativeAlarmProjectorTests.cs`
**Context:** `AlarmEventArgs` is a delta (raise/clear/ack). `AlarmConditionSnapshot` (`Commons/OpcUa/AlarmConditionSnapshot.cs`: `Active, Acknowledged, Confirmed, Enabled, Shelving, Severity(ushort), Message`) is the full state `WriteAlarmCondition` wants. The projector keeps per-condition-NodeId prior `(Active, Acked, Severity, Message)` and derives the next snapshot from `Kind`. It lives in Runtime (references both `Core.Abstractions` and `Commons`). It is owned by the single-threaded `DriverHostActor` → a plain `Dictionary` is safe (no locking).
**Severity map** (`AlarmSeverity` 4-bucket → ushort 1..1000): Low→200, Medium→500, High→700, Critical→900.
**Kind → snapshot:**
| Kind | Active | Acknowledged | Severity/Message |
|---|---|---|---|
| Raise / Retrigger | true | false | from event |
| Acknowledge | prior | true | from event (keep prior severity if event is a pure ack — use event severity, fine) |
| Clear | false | prior | from event |
| Unspecified | prior | prior | from event |
Constant fields: `Enabled=true`, `Confirmed=true`, `Shelving=Unshelved`.
**Step 1 (failing tests):**
```csharp
using Shouldly;
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using Xunit;
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.Drivers;
public class NativeAlarmProjectorTests
{
private static AlarmEventArgs Evt(AlarmTransitionKind kind, AlarmSeverity sev = AlarmSeverity.High, string msg = "m")
=> new(new H(), "Tank1.Hi", "c1", "LimitAlarm.Hi", msg, sev, DateTime.UnixEpoch, Kind: kind);
[Fact]
public void Raise_is_active_and_unacked()
{
var s = new NativeAlarmProjector().Project("n1", Evt(AlarmTransitionKind.Raise));
s.Active.ShouldBeTrue(); s.Acknowledged.ShouldBeFalse();
s.Severity.ShouldBe((ushort)700); s.Enabled.ShouldBeTrue();
s.Shelving.ShouldBe(AlarmShelvingKind.Unshelved);
}
[Fact]
public void Acknowledge_sets_acked_and_keeps_prior_active()
{
var p = new NativeAlarmProjector();
p.Project("n1", Evt(AlarmTransitionKind.Raise));
var s = p.Project("n1", Evt(AlarmTransitionKind.Acknowledge));
s.Active.ShouldBeTrue(); s.Acknowledged.ShouldBeTrue();
}
[Fact]
public void Clear_deactivates_and_keeps_prior_ack()
{
var p = new NativeAlarmProjector();
p.Project("n1", Evt(AlarmTransitionKind.Raise));
var s = p.Project("n1", Evt(AlarmTransitionKind.Clear));
s.Active.ShouldBeFalse(); s.Acknowledged.ShouldBeFalse();
}
[Fact]
public void State_is_isolated_per_nodeId()
{
var p = new NativeAlarmProjector();
p.Project("n1", Evt(AlarmTransitionKind.Raise));
var s2 = p.Project("n2", Evt(AlarmTransitionKind.Clear)); // cold n2: clear from default-inactive
s2.Active.ShouldBeFalse();
}
private sealed class H : IAlarmSubscriptionHandle { public string DiagnosticId => "t"; }
}
```
Run: `dotnet test tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests --filter NativeAlarmProjector` → FAIL.
**Step 2 (implement):**
```csharp
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
namespace ZB.MOM.WW.OtOpcUa.Runtime.Drivers;
/// <summary>
/// Derives a full Part 9 <see cref="AlarmConditionSnapshot"/> from each native
/// <see cref="AlarmEventArgs"/> delta, tracking per-condition-NodeId prior state. Owned by the
/// single-threaded <c>DriverHostActor</c> (no locking). Native alarms carry only a transition
/// <see cref="AlarmTransitionKind"/>, not a full state machine, so this is the translation the
/// scripted-alarm engine does internally.
/// </summary>
public sealed class NativeAlarmProjector
{
private readonly Dictionary<string, (bool Active, bool Acked, ushort Severity, string Message)> _prior =
new(StringComparer.Ordinal);
/// <summary>Project an alarm transition onto the full condition snapshot for <paramref name="nodeId"/>.</summary>
public AlarmConditionSnapshot Project(string nodeId, AlarmEventArgs e)
{
var prev = _prior.TryGetValue(nodeId, out var p) ? p : (Active: false, Acked: true, Severity: (ushort)0, Message: string.Empty);
var sev = MapSeverity(e.Severity);
var (active, acked) = e.Kind switch
{
AlarmTransitionKind.Raise or AlarmTransitionKind.Retrigger => (true, false),
AlarmTransitionKind.Acknowledge => (prev.Active, true),
AlarmTransitionKind.Clear => (false, prev.Acked),
_ => (prev.Active, prev.Acked),
};
_prior[nodeId] = (active, acked, sev, e.Message);
return new AlarmConditionSnapshot(
Active: active, Acknowledged: acked, Confirmed: true, Enabled: true,
Shelving: AlarmShelvingKind.Unshelved, Severity: sev, Message: e.Message);
}
/// <summary>Clears tracked state (call on address-space rebuild).</summary>
public void Clear() => _prior.Clear();
private static ushort MapSeverity(AlarmSeverity s) => s switch
{
AlarmSeverity.Low => 200, AlarmSeverity.Medium => 500,
AlarmSeverity.High => 700, AlarmSeverity.Critical => 900, _ => 500,
};
}
```
**Step 3:** Run the filter → PASS.
**Step 4 (commit):**
```bash
git add src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/NativeAlarmProjector.cs \
tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/NativeAlarmProjectorTests.cs
git commit -m "feat(alarms): NativeAlarmProjector maps transitions to condition snapshots (Phase B WS-4a)"
```
---
### Task 5: `DriverInstanceActor` subscribes `OnAlarmEvent` + publishes `AttributeAlarmPublished` — WS-4b
**Classification:** high-risk
**Estimated implement time:** ~5 min
**Parallelizable with:** Task 3, Task 4
**Files:**
- Modify: `src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverInstanceActor.cs` (msg defs `:63-66`; new fields; `AttachAlarmSource`/`DetachAlarmSource`; `Receive<NativeAlarmRaised>`; wire attach on Connected-entry, detach in `DetachSubscription` + `PostStop`)
- Test: `tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/` (new `DriverInstanceActorNativeAlarmTests.cs`)
**Context — mirror the `OnDataChange` pattern exactly** (`:408-409` attach, `:452-460` `DetachSubscription`): the driver fires `OnAlarmEvent` on its own thread → marshal to the actor thread via `self.Tell(...)`. Galaxy's alarm feed auto-starts in `InitializeAsync` and fires `OnAlarmEvent` independent of `SubscribeAlarmsAsync`, so the actor only subscribes the C# event (no `SubscribeAlarmsAsync` call — that's a deferred follow-up for drivers that gate on it). The server filters by `SourceNodeId` downstream (unknown refs drop), so forward every transition.
**Step 1 (failing test, Akka.TestKit — xUnit v2):**
```csharp
// Fake driver implements IDriver + ISubscribable + IAlarmSource; exposes RaiseAlarm(args).
// Spawn the actor, drive it to Connected, then fakeDriver.RaiseAlarm(...) and
// ExpectMsg<DriverInstanceActor.AttributeAlarmPublished> on a probe wired as the parent.
// Use CancellationToken.None (NOT TestContext.Current — this is xUnit v2 / Akka.TestKit.Xunit2).
```
Model it on the existing `DriverInstanceActor` subscribe tests (grep `AttributeValuePublished` in `Runtime.Tests/Drivers`). Assert `AttributeAlarmPublished.DriverInstanceId` + `.Args.SourceNodeId` match. Run → FAIL.
**Step 2 (implement messages):** After `AttributeValuePublished` (`:65`):
```csharp
/// <summary>Published to the parent whenever the subscribed driver (an <see cref="IAlarmSource"/>) fires
/// <see cref="IAlarmSource.OnAlarmEvent"/>. The parent (<see cref="DriverHostActor"/>) projects + routes it
/// to the materialised Part 9 condition. Parallels <see cref="AttributeValuePublished"/>.</summary>
public sealed record AttributeAlarmPublished(string DriverInstanceId, AlarmEventArgs Args);
private sealed record NativeAlarmRaised(AlarmEventArgs Args);
```
Add fields near `_dataChangeHandler`:
```csharp
private EventHandler<AlarmEventArgs>? _alarmEventHandler;
```
**Step 3 (implement attach/detach + receive):**
```csharp
/// <summary>Subscribe the driver's native alarm event (if it is an <see cref="IAlarmSource"/>),
/// marshaling each transition to the actor thread. Idempotent; mirrors the OnDataChange attach.</summary>
private void AttachAlarmSource()
{
if (_driver is not IAlarmSource src || _alarmEventHandler is not null) return;
var self = Self;
_alarmEventHandler = (_, e) => self.Tell(new NativeAlarmRaised(e));
src.OnAlarmEvent += _alarmEventHandler;
}
/// <summary>Symmetric teardown — called from <see cref="DetachSubscription"/> and PostStop so a stale
/// handler never pushes to a disconnected actor.</summary>
private void DetachAlarmSource()
{
if (_driver is IAlarmSource src && _alarmEventHandler is not null)
src.OnAlarmEvent -= _alarmEventHandler;
_alarmEventHandler = null;
}
```
Register in the `Connected()` behavior (next to `Receive<DataChangeForward>(OnDataChangeForward)` at `:275`):
```csharp
Receive<NativeAlarmRaised>(m => Context.Parent.Tell(new AttributeAlarmPublished(_driverInstanceId, m.Args)));
```
Call `AttachAlarmSource()` on every Connected entry — the cleanest single site is right where `ResubscribeDesired()` is called after `Become(Connected)` (both the first-connect `InitializeSucceeded` path **and** the `Reconnecting` `InitializeSucceeded` at `:295-302`). Add `AttachAlarmSource();` immediately after each `Become(Connected);`. Add `DetachAlarmSource();` inside `DetachSubscription()` (`:452`, so it fires on Connected→Reconnecting + Unsubscribe + PostStop, which all route through it — verify PostStop calls `DetachSubscription`; if not, add `DetachAlarmSource()` to `PostStop` too).
**Step 4:** Run the filter → PASS. Confirm no double-attach (the `_alarmEventHandler is not null` guard) and that a teardown→reconnect re-attaches cleanly (add an assertion that a second Connected entry still delivers exactly one `AttributeAlarmPublished` per raise).
**Step 5 (commit):**
```bash
git add src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverInstanceActor.cs \
tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/DriverInstanceActorNativeAlarmTests.cs
git commit -m "feat(alarms): DriverInstanceActor forwards native OnAlarmEvent to parent (Phase B WS-4b)"
```
---
### Task 6: `DriverHostActor` alarm map + `ForwardNativeAlarm` → live condition — WS-4c
**Classification:** high-risk
**Estimated implement time:** ~5 min
**Parallelizable with:** none
**Files:**
- Modify: `src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverHostActor.cs` (new `_alarmNodeIdByDriverRef` map + `_nativeAlarmProjector` field `:99`; build in `PushDesiredSubscriptions` `:748-763`, branching on `Alarm != null`; `Receive<AttributeAlarmPublished>` in the two behaviors that hold `Receive<AttributeValuePublished>`; new `ForwardNativeAlarm`)
- Test: `tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/` (new `DriverHostActorNativeAlarmTests.cs`)
**Context:** `ForwardToMux` (`:440-467`) is the value analogue. The value maps (`_nodeIdByDriverRef`, `_driverRefByNodeId`) + `refsByDriver` (value subscription) are built in `PushDesiredSubscriptions` (`:734-763`). Alarm tags must be **excluded** from the value maps + value subscription (they're conditions, not variables) and routed via a parallel alarm map. An alarm's `AlarmEventArgs.SourceNodeId` equals the tag's `FullName`, so the alarm map keys on the same `(DriverInstanceId, FullName)`.
**Step 1 (failing test, Akka.TestKit):** Spawn `DriverHostActor` with a wired `_opcUaPublishActor` probe; apply a composition (or call the SubscribeBulk path) containing one alarm-bearing `EquipmentTag`; send `AttributeAlarmPublished(driverId, raiseEvent)`; `ExpectMsg<OpcUaPublishActor.AlarmStateUpdate>` at the alarm tag's NodeId with `State.Active == true`. Second test: an `AttributeAlarmPublished` for an unknown ref produces **no** `AlarmStateUpdate`. Model on the existing `DriverHostActor` value-routing tests (grep `AttributeValueUpdate`/`_nodeIdByDriverRef` in `Runtime.Tests`). Run → FAIL.
**Step 2 (fields):** At `:99` add:
```csharp
/// <summary>(DriverInstanceId, FullName=alarm SourceNodeId) → folder-scoped condition NodeId(s). Built
/// from EquipmentTags whose plan carries Alarm, alongside the value maps; resolves native alarm
/// transitions to their materialised Part 9 condition node(s).</summary>
private readonly Dictionary<(string DriverInstanceId, string FullName), HashSet<string>> _alarmNodeIdByDriverRef = new();
private readonly NativeAlarmProjector _nativeAlarmProjector = new();
```
**Step 3 (build the map — `PushDesiredSubscriptions`):** In the `EquipmentTags` loop (`:755-763`), branch so alarm tags go ONLY into `_alarmNodeIdByDriverRef` and are kept OUT of the value maps; and exclude alarm refs from `refsByDriver` (the value-subscription set at `:734-741`). Concretely:
- Add `_alarmNodeIdByDriverRef.Clear();` next to the other `Clear()`s.
- In the `foreach (var t in composition.EquipmentTags)` loop:
```csharp
var key = (t.DriverInstanceId, t.FullName);
var nodeId = EquipmentNodeIds.Variable(t.EquipmentId, t.FolderPath, t.Name);
if (t.Alarm is not null)
{
if (!_alarmNodeIdByDriverRef.TryGetValue(key, out var aset))
_alarmNodeIdByDriverRef[key] = aset = new HashSet<string>(StringComparer.Ordinal);
aset.Add(nodeId);
continue; // alarm tags are conditions, not value variables
}
// …existing value-map population (unchanged)…
```
- For `refsByDriver` (`:734-741`), add `.Where(t => t.Alarm is null)` before the `GroupBy` so the driver doesn't value-subscribe alarm attributes.
- Reset projector state on rebuild: call `_nativeAlarmProjector.Clear();` alongside the map clears (the condition nodes are torn down + rebuilt each apply, so prior state must not leak).
**Step 4 (`ForwardNativeAlarm` + receives):** Add the handler (model on `ForwardToMux`):
```csharp
private void ForwardNativeAlarm(DriverInstanceActor.AttributeAlarmPublished msg)
{
if (_opcUaPublishActor is null) return;
if (!_alarmNodeIdByDriverRef.TryGetValue((msg.DriverInstanceId, msg.Args.SourceNodeId), out var nodeIds))
{
_log.Debug("DriverHost {Node}: no alarm condition for ({Driver},{Ref}) — transition dropped",
_localNode, msg.DriverInstanceId, msg.Args.SourceNodeId);
return;
}
foreach (var nodeId in nodeIds)
{
var snapshot = _nativeAlarmProjector.Project(nodeId, msg.Args);
_opcUaPublishActor.Tell(new ZB.MOM.WW.OtOpcUa.Runtime.OpcUa.OpcUaPublishActor.AlarmStateUpdate(
nodeId, snapshot, msg.Args.SourceTimestampUtc));
}
}
```
Register `Receive<DriverInstanceActor.AttributeAlarmPublished>(ForwardNativeAlarm);` immediately after **each** `Receive<DriverInstanceActor.AttributeValuePublished>(ForwardToMux);` (there are two — the steady + applying behaviors; grep `ForwardToMux` to find both registration sites).
**Step 5:** Run the filter → PASS. Full build clean.
**Step 6 (commit):**
```bash
git add src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverHostActor.cs \
tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/DriverHostActorNativeAlarmTests.cs
git commit -m "feat(alarms): DriverHostActor routes native alarm transitions to Part 9 conditions (Phase B WS-4c)"
```
---
### Task 7: Primary-gated `AlarmTransitionEvent` fan-out to `alerts` — WS-5
**Classification:** high-risk
**Estimated implement time:** ~5 min
**Parallelizable with:** none
**Files:**
- Modify: `src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverHostActor.cs` (alarm-meta map; mediator publish in `ForwardNativeAlarm`, Primary-gated via `_localRole`)
- Test: `tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/DriverHostActorNativeAlarmTests.cs` (extend)
**Context:** `ScriptedAlarmHostActor.OnEngineEmission` (`:289-315`) publishes `AlarmTransitionEvent` to the `alerts` topic (consumed by `HistorianAdapterActor` + AdminUI `/alerts`), **Primary-gated** (suppress on `Secondary`/`Detached`). DriverHostActor already holds `_localRole` (`:121`, same gate it uses for `RouteNodeWrite`) and a DistributedPubSub mediator (it subscribes `RedundancyStateTopic` at `:265`). Reuse both. The event needs `EquipmentPath`/`AlarmName`/`AlarmTypeName` per condition node → add a small meta map built in the same `PushDesiredSubscriptions` pass. Grep `AlertsTopic` + `AlarmTransitionEvent` (Commons `Messages/Alerts/`) and `ScriptedAlarmHostActor` for the exact topic constant, the mediator field name, and the `Publish` usage to copy.
**Step 1 (failing test):** Drive the host to `_localRole = Secondary` (send the `RedundancyStateChanged` it consumes; grep the existing redundancy-gate test for `RouteNodeWrite`/"not primary" to copy the setup) → an `AttributeAlarmPublished` still Tells `AlarmStateUpdate` (condition stays warm) but publishes **no** `AlarmTransitionEvent`. With `_localRole = Primary` (or unset) → it publishes one. Run → FAIL.
**Step 2 (implement meta map):** Add `private readonly Dictionary<string, (string EquipmentId, string Name, string AlarmType)> _alarmMetaByNodeId = new(StringComparer.Ordinal);`; populate it in the alarm branch of the `PushDesiredSubscriptions` loop (Task 6 step 3): `_alarmMetaByNodeId[nodeId] = (t.EquipmentId, t.Name, t.Alarm.AlarmType);` and `Clear()` it with the others.
**Step 3 (implement gated publish):** In `ForwardNativeAlarm`, after the `AlarmStateUpdate` Tell (inside the `foreach`), append the Primary-gated publish, mirroring `ScriptedAlarmHostActor`:
```csharp
if (_localRole is RedundancyRole.Secondary or RedundancyRole.Detached) continue; // warm-standby dedup
var meta = _alarmMetaByNodeId.TryGetValue(nodeId, out var m) ? m : (EquipmentId: nodeId, Name: nodeId, AlarmType: "AlarmCondition");
_mediator.Tell(new Publish(AlertsTopic, new AlarmTransitionEvent(
AlarmId: nodeId,
EquipmentPath: meta.EquipmentId,
AlarmName: meta.Name,
TransitionKind: msg.Args.Kind.ToString(),
Severity: snapshot.Severity,
Message: msg.Args.Message,
User: msg.Args.OperatorComment is null ? string.Empty : "device",
TimestampUtc: msg.Args.SourceTimestampUtc,
AlarmTypeName: meta.AlarmType,
Comment: msg.Args.OperatorComment,
HistorizeToAveva: true)));
```
Use the exact `AlarmTransitionEvent` constructor argument list discovered by grep (adjust names/order if they differ; the historian + `/alerts` consumers already handle this shape from scripted alarms). Resolve the mediator handle the same way the existing redundancy subscription does (the field used at `:265`).
**Step 4:** Run the filter → PASS. Full build + `dotnet test tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests` green.
**Step 5 (commit):**
```bash
git add src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverHostActor.cs \
tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/DriverHostActorNativeAlarmTests.cs
git commit -m "feat(alarms): Primary-gated AlarmTransitionEvent fan-out for native alarms (Phase B WS-5)"
```
---
### Task 8: Document the `TagConfig` alarm schema — Docs
**Classification:** small
**Estimated implement time:** ~3 min
**Parallelizable with:** Task 3, Task 4, Task 5
**Files:**
- Modify: `docs/ScriptedAlarms.md` (add a "Native driver alarms (equipment-tag path)" section) — or `docs/AlarmTracking.md` if that's the better home; pick whichever already covers condition materialization.
**Step 1:** Add a section documenting: a native driver alarm (Galaxy) is an authored equipment `Tag` whose `TagConfig` carries an `alarm` object — `{"FullName":"tag.attr","alarm":{"alarmType":"OffNormalAlarm","severity":700}}`; absent ⇒ plain variable; `alarmType` ∈ {AlarmCondition, OffNormalAlarm, DiscreteAlarm, LimitAlarm} (default AlarmCondition), `severity` 1..1000 (default 500). Note it materializes a Part 9 condition (not a variable) under the equipment folder, fed by the driver's live `IAlarmSource.OnAlarmEvent`; transitions fan out to `/alerts` + the historian (Primary-gated). State the two deferred follow-ups: inbound device-ack (client Acknowledge → AVEVA) and the AdminUI Galaxy-picker pre-fill.
**Step 2 (commit):**
```bash
git add docs/ScriptedAlarms.md
git commit -m "docs(alarms): native driver-alarm TagConfig schema (Phase B)"
```
---
### Task 9: Live docker-dev `/run` verification (user-driven)
**Classification:** verification
**Estimated implement time:** n/a (user drives; the agent does NOT sign in)
**Parallelizable with:** none
**Gate (the design's live-verify):** On the live-gateway-backed `MAIN-galaxy-eq` (dev rig is LOCAL on this Mac — OrbStack; central-1 @ `localhost:4840`, deploy/AdminUI @ `localhost:9200`, sql @ `localhost:14330`; the Galaxy gateway needs the ephemeral `GALAXY_MXGW_API_KEY` re-exported on container recreate — see `pending.md` Galaxy dev-rig note):
1. Rebuild central on the branch: `docker compose -f docker-dev/docker-compose.yml up -d --build migrator central-1 central-2` (re-export `GALAXY_MXGW_API_KEY=…` on the recreate).
2. Author a Galaxy alarm equipment tag on `EQ-55297329838d` whose `TagConfig` carries the `alarm` object pointing at a real galaxy alarm reference (a `TestMachine_002` attribute with an alarm extension, or the seeded `TestMachine_001.TestAlarm00x`). Deploy: `POST http://localhost:9200/api/deployments`, header `X-Api-Key: docker-dev-deploy-key`. **Order:** deploy FIRST, then recreate central if the driver is faulted (a faulted driver ignores `ApplyDelta`).
3. Trip the Galaxy alarm. Confirm via Client.CLI `alarms`/`read` against `opc.tcp://localhost:4840` that a Part 9 `AlarmConditionState` appears **active** under the equipment NodeId; confirm the AdminUI `/alerts` row appears. Clear → condition goes inactive.
4. (Device-ack round-trip is the deferred follow-up — NOT part of this gate.)
**On pass:** finish via `superpowers-extended-cc:finishing-a-development-branch` (intent: merge-to-master + push). Update `pending.md` (disk-only) marking Phase B done; refresh the memory.
---
## Execution order / dependency summary
```
T0 ─┬─ T1 (contract) ─┬─ T4 (projector) ─┐
│ └─ T5 (instance actor) ─┐
└─ T2 (plan field) ─┬─ T3 (applier) ├─ T6 (host live) ── T7 (host alerts) ── T9 (live)
└─ T8 (docs) ┘
```
- **Parallel batch A** (after T0): T1 ∥ T2.
- **Parallel batch B** (T1+T2 done): T3 ∥ T4 ∥ T5 ∥ T8 (all disjoint files).
- **Serial tail:** T6 (needs T2+T4+T5) → T7 (same file) → T9.
@@ -0,0 +1,16 @@
{
"planPath": "docs/plans/2026-06-14-galaxy-phase-b-native-alarms-plan.md",
"tasks": [
{"id": "367", "subject": "Task 0: Feature branch feat/galaxy-phase-b-native-alarms", "classification": "trivial", "status": "pending"},
{"id": "368", "subject": "Task 1 (WS-1): AlarmEventArgs.Kind contract + Galaxy populates it", "classification": "standard", "status": "pending", "blockedBy": ["367"], "parallelizableWith": ["369"]},
{"id": "369", "subject": "Task 2 (WS-2): EquipmentTagPlan.Alarm parsed byte-parity from TagConfig", "classification": "high-risk", "status": "pending", "blockedBy": ["367"], "parallelizableWith": ["368"]},
{"id": "370", "subject": "Task 3 (WS-3): Materialise a Part 9 condition for an alarm tag", "classification": "standard", "status": "pending", "blockedBy": ["369"], "parallelizableWith": ["371", "372", "375"]},
{"id": "371", "subject": "Task 4 (WS-4a): NativeAlarmProjector (transition -> snapshot)", "classification": "standard", "status": "pending", "blockedBy": ["368"], "parallelizableWith": ["370", "372", "375"]},
{"id": "372", "subject": "Task 5 (WS-4b): DriverInstanceActor forwards native OnAlarmEvent", "classification": "high-risk", "status": "pending", "blockedBy": ["368"], "parallelizableWith": ["370", "371", "375"]},
{"id": "373", "subject": "Task 6 (WS-4c): DriverHostActor routes native alarms to conditions", "classification": "high-risk", "status": "pending", "blockedBy": ["369", "371", "372"]},
{"id": "374", "subject": "Task 7 (WS-5): Primary-gated AlarmTransitionEvent fan-out", "classification": "high-risk", "status": "pending", "blockedBy": ["373"]},
{"id": "375", "subject": "Task 8 (Docs): Native driver-alarm TagConfig schema", "classification": "small", "status": "pending", "blockedBy": ["369"], "parallelizableWith": ["370", "371", "372"]},
{"id": "376", "subject": "Task 9: Live docker-dev /run verification (user-driven)", "classification": "verification", "status": "pending", "blockedBy": ["374", "375"]}
],
"lastUpdated": "2026-06-14"
}
@@ -71,6 +71,12 @@ public sealed record AlarmAcknowledgeRequest(
/// <c>Diagnostics</c>). Maps to OPC UA <c>ConditionClassName</c> downstream when
/// a class mapping is configured. Null when the upstream path doesn't carry it.
/// </param>
/// <param name="Kind">
/// The alarm transition kind (raise / acknowledge / clear / retrigger). Lets a
/// consumer derive OPC UA Part 9 active/ack state without inferring it from
/// other fields. <see cref="AlarmTransitionKind.Unspecified"/> when the upstream
/// path doesn't surface a distinct kind.
/// </param>
public sealed record AlarmEventArgs(
IAlarmSubscriptionHandle SubscriptionHandle,
string SourceNodeId,
@@ -81,7 +87,15 @@ public sealed record AlarmEventArgs(
DateTime SourceTimestampUtc,
string? OperatorComment = null,
DateTime? OriginalRaiseTimestampUtc = null,
string? AlarmCategory = null);
string? AlarmCategory = null,
AlarmTransitionKind Kind = AlarmTransitionKind.Unspecified);
/// <summary>Mirrors the <c>NodePermissions</c> alarm-severity enum in <c>docs/v2/acl-design.md</c>.</summary>
public enum AlarmSeverity { Low, Medium, High, Critical }
/// <summary>
/// Kind of alarm state change carried by <see cref="AlarmEventArgs.Kind"/>, letting a
/// consumer derive OPC UA Part 9 active/ack state. Mirrors the driver-side
/// transition-kind enums (e.g. Galaxy's <c>GalaxyAlarmTransitionKind</c>).
/// </summary>
public enum AlarmTransitionKind { Unspecified = 0, Raise, Acknowledge, Clear, Retrigger }
@@ -1153,7 +1153,17 @@ public sealed class GalaxyDriver
SourceTimestampUtc: transition.TransitionTimestampUtc,
OperatorComment: string.IsNullOrEmpty(transition.OperatorComment) ? null : transition.OperatorComment,
OriginalRaiseTimestampUtc: transition.OriginalRaiseTimestampUtc,
AlarmCategory: string.IsNullOrEmpty(transition.Category) ? null : transition.Category);
AlarmCategory: string.IsNullOrEmpty(transition.Category) ? null : transition.Category,
// Fully-qualify the Core.Abstractions enum: this file also imports
// MxGateway.Contracts.Proto, which defines a same-named AlarmTransitionKind.
Kind: transition.TransitionKind switch
{
GalaxyAlarmTransitionKind.Raise => Core.Abstractions.AlarmTransitionKind.Raise,
GalaxyAlarmTransitionKind.Acknowledge => Core.Abstractions.AlarmTransitionKind.Acknowledge,
GalaxyAlarmTransitionKind.Clear => Core.Abstractions.AlarmTransitionKind.Clear,
GalaxyAlarmTransitionKind.Retrigger => Core.Abstractions.AlarmTransitionKind.Retrigger,
_ => Core.Abstractions.AlarmTransitionKind.Unspecified,
});
try
{
OnAlarmEvent?.Invoke(this, args);
@@ -189,7 +189,16 @@ public sealed class Phase7Applier
? tag.EquipmentId
: EquipmentNodeIds.SubFolder(tag.EquipmentId, tag.FolderPath);
var nodeId = EquipmentNodeIds.Variable(tag.EquipmentId, tag.FolderPath, tag.Name);
SafeEnsureVariable(nodeId, parent, tag.Name, tag.DataType, tag.Writable);
if (tag.Alarm is not null)
{
// Native alarm tag → a real Part 9 condition node (reuses the scripted-alarm path),
// NOT a value variable. Parent is the sub-folder when set, else the equipment folder.
SafeMaterialiseAlarmCondition(nodeId, parent, tag.Name, tag.Alarm.AlarmType, tag.Alarm.Severity);
}
else
{
SafeEnsureVariable(nodeId, parent, tag.Name, tag.DataType, tag.Writable);
}
}
_logger.LogInformation(
@@ -75,7 +75,9 @@ public sealed record ScriptedAlarmPlan(string ScriptedAlarmId, string EquipmentI
/// mirrors the authored <c>Tag.AccessLevel == ReadWrite</c> so the materialised node is created
/// <c>CurrentReadWrite</c> (the prerequisite for the inbound-write pipeline); a <c>Read</c> tag
/// stays read-only. This flag is derived identically on the artifact-decode side
/// (<c>DeploymentArtifact.BuildEquipmentTagPlans</c>) for byte-parity.
/// (<c>DeploymentArtifact.BuildEquipmentTagPlans</c>) for byte-parity. <see cref="Alarm"/> carries
/// the optional native-alarm intent parsed from <c>Tag.TagConfig</c>'s <c>alarm</c> object (null ⇒
/// a plain value variable); it too is parsed identically on the artifact-decode side for byte-parity.
/// </summary>
public sealed record EquipmentTagPlan(
string TagId,
@@ -85,7 +87,13 @@ public sealed record EquipmentTagPlan(
string Name,
string DataType,
string FullName,
bool Writable);
bool Writable,
EquipmentTagAlarmInfo? Alarm);
/// <summary>Native-alarm intent parsed from an equipment tag's <c>TagConfig.alarm</c> object. Null ⇒
/// the tag is a plain value variable. <see cref="AlarmType"/> is an OPC UA Part 9 subtype string
/// (OffNormalAlarm/DiscreteAlarm/LimitAlarm/AlarmCondition); <see cref="Severity"/> is the 1..1000 scale.</summary>
public sealed record EquipmentTagAlarmInfo(string AlarmType, int Severity);
/// <summary>
/// One Equipment-namespace VirtualTag from a <see cref="VirtualTag"/> row (joined to its
@@ -328,7 +336,8 @@ public static class Phase7Composer
Name: t.Name,
DataType: t.DataType,
FullName: ExtractTagFullName(t.TagConfig),
Writable: t.AccessLevel == TagAccessLevel.ReadWrite))
Writable: t.AccessLevel == TagAccessLevel.ReadWrite,
Alarm: ExtractTagAlarm(t.TagConfig)))
.ToList();
// Per-equipment tag base = the shared substring-before-first-dot across each equipment's
@@ -445,4 +454,24 @@ public static class Phase7Composer
catch (JsonException) { /* fall through to raw blob */ }
return tagConfig;
}
/// <summary>Parses the optional <c>alarm</c> object from a tag's <c>TagConfig</c> JSON. Returns null
/// when absent, non-object, or non-JSON (the tag is then a plain variable). Never throws. The
/// artifact-decode side (<c>DeploymentArtifact.ExtractTagAlarm</c>) MUST parse identically (byte-parity).</summary>
internal static EquipmentTagAlarmInfo? ExtractTagAlarm(string? tagConfig)
{
if (string.IsNullOrWhiteSpace(tagConfig)) return null;
try
{
using var doc = JsonDocument.Parse(tagConfig);
if (doc.RootElement.ValueKind != JsonValueKind.Object) return null;
if (!doc.RootElement.TryGetProperty("alarm", out var a) || a.ValueKind != JsonValueKind.Object) return null;
var type = a.TryGetProperty("alarmType", out var tEl) && tEl.ValueKind == JsonValueKind.String
? (tEl.GetString() ?? "AlarmCondition") : "AlarmCondition";
var sev = a.TryGetProperty("severity", out var sEl) && sEl.ValueKind == JsonValueKind.Number
&& sEl.TryGetInt32(out var sv) ? sv : 500;
return new EquipmentTagAlarmInfo(type, sev);
}
catch (JsonException) { return null; }
}
}
@@ -445,7 +445,8 @@ public static class DeploymentArtifact
Name: name!,
DataType: dataType ?? "BaseDataType",
FullName: ExtractTagFullName(tagConfig),
Writable: writable));
Writable: writable,
Alarm: ExtractTagAlarm(tagConfig)));
}
result.Sort((a, b) =>
@@ -651,6 +652,26 @@ public static class DeploymentArtifact
return tagConfig;
}
/// <summary>Parses the optional <c>alarm</c> object from a tag's <c>TagConfig</c> JSON. Returns null
/// when absent, non-object, or non-JSON (the tag is then a plain variable). Never throws. The
/// live-edit side (<c>Phase7Composer.ExtractTagAlarm</c>) MUST parse identically (byte-parity).</summary>
private static EquipmentTagAlarmInfo? ExtractTagAlarm(string? tagConfig)
{
if (string.IsNullOrWhiteSpace(tagConfig)) return null;
try
{
using var doc = JsonDocument.Parse(tagConfig);
if (doc.RootElement.ValueKind != JsonValueKind.Object) return null;
if (!doc.RootElement.TryGetProperty("alarm", out var a) || a.ValueKind != JsonValueKind.Object) return null;
var type = a.TryGetProperty("alarmType", out var tEl) && tEl.ValueKind == JsonValueKind.String
? (tEl.GetString() ?? "AlarmCondition") : "AlarmCondition";
var sev = a.TryGetProperty("severity", out var sEl) && sEl.ValueKind == JsonValueKind.Number
&& sEl.TryGetInt32(out var sv) ? sv : 500;
return new EquipmentTagAlarmInfo(type, sev);
}
catch (JsonException) { return null; }
}
private static IReadOnlyList<T> ReadArray<T>(JsonElement root, string propertyName, Func<JsonElement, T?> reader)
where T : class
{
@@ -8,6 +8,7 @@ using Microsoft.Extensions.Logging.Abstractions;
using ZB.MOM.WW.OtOpcUa.Commons.Engines;
using ZB.MOM.WW.OtOpcUa.Commons.Interfaces;
using ZB.MOM.WW.OtOpcUa.Commons.Messages.Admin;
using ZB.MOM.WW.OtOpcUa.Commons.Messages.Alerts;
using ZB.MOM.WW.OtOpcUa.Commons.Messages.Deploy;
using ZB.MOM.WW.OtOpcUa.Commons.Messages.Fleet;
using ZB.MOM.WW.OtOpcUa.Commons.Messages.Redundancy;
@@ -110,6 +111,22 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers
private readonly Dictionary<string, (string DriverInstanceId, string FullName)> _driverRefByNodeId =
new(StringComparer.Ordinal);
/// <summary>(DriverInstanceId, FullName = alarm ConditionId / AlarmFullReference) → folder-scoped condition NodeId(s).
/// Built from EquipmentTags whose plan carries Alarm, alongside the value maps; resolves a native
/// alarm transition to the materialised Part 9 condition node(s). Alarm tags are conditions, not
/// value variables, so they are kept OUT of the value maps + value-subscription set.</summary>
private readonly Dictionary<(string DriverInstanceId, string FullName), HashSet<string>> _alarmNodeIdByDriverRef = new();
/// <summary>Condition NodeId → (EquipmentId, tag Name, OPC UA alarm type) for building the
/// AlarmTransitionEvent fan-out. Built in the same PushDesiredSubscriptions alarm branch.</summary>
private readonly Dictionary<string, (string EquipmentId, string Name, string AlarmType)> _alarmMetaByNodeId =
new(StringComparer.Ordinal);
/// <summary>Derives a full Part 9 condition snapshot from each native alarm transition delta,
/// tracking per-condition-NodeId prior state. <see cref="Clear"/>'d on every apply alongside the
/// value maps so stale condition state never leaks across redeploys.</summary>
private readonly NativeAlarmProjector _nativeAlarmProjector = new();
/// <summary>
/// Cached local <see cref="RedundancyRole"/> from the latest <see cref="RedundancyStateChanged"/>
/// snapshot (null = unknown until the first snapshot arrives, or no local node match). The inbound
@@ -120,6 +137,12 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers
/// </summary>
private RedundancyRole? _localRole;
/// <summary>Cached cluster DistributedPubSub mediator, resolved once in <see cref="PreStart"/> (on the
/// actor thread) and reused for the Primary-gated native-alarm <c>alerts</c> fan-out in
/// <see cref="ForwardNativeAlarm"/> instead of re-resolving it per-publish. Mirrors
/// <c>ScriptedAlarmHostActor._mediator</c>.</summary>
private IActorRef _mediator = null!;
/// <summary>
/// Routes an inbound operator write (resolved from the OPC UA node-manager side, Task 11) to the
/// owning driver child. <see cref="HandleRouteNodeWrite"/> gates on the local node being the
@@ -254,14 +277,17 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers
/// <inheritdoc />
protected override void PreStart()
{
// Resolve the cluster DPS mediator once, on the actor thread, and reuse it for every subscribe +
// the Primary-gated native-alarm alerts fan-out in ForwardNativeAlarm (mirrors ScriptedAlarmHostActor).
_mediator = DistributedPubSub.Get(Context.System).Mediator;
// Subscribe to deployments topic so the coordinator's broadcast lands here.
DistributedPubSub.Get(Context.System).Mediator.Tell(new Subscribe(DeploymentsTopic, Self));
_mediator.Tell(new Subscribe(DeploymentsTopic, Self));
// Subscribe to driver-control topic so AdminUI Reconnect/Restart commands land here.
DistributedPubSub.Get(Context.System).Mediator.Tell(new Subscribe(DriverControlTopic, Self));
_mediator.Tell(new Subscribe(DriverControlTopic, Self));
// Subscribe to the redundancy-state topic so cluster role changes cache this node's role — the
// inbound-write gate in HandleRouteNodeWrite reuses the SAME signal the scripted-alarm emit gate
// uses so only the Primary services operator writes (the secondary keeps state warm for failover).
DistributedPubSub.Get(Context.System).Mediator.Tell(
_mediator.Tell(
new Subscribe(ZB.MOM.WW.OtOpcUa.Runtime.OpcUa.OpcUaPublishActor.RedundancyStateTopic, Self));
// Spawn the VirtualTag host BEFORE Bootstrap so the bootstrap-restore path (which routes
// through PushDesiredSubscriptions and Tells ApplyVirtualTags) has a live host to target.
@@ -406,6 +432,7 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers
Receive<DispatchDeployment>(HandleDispatchFromSteady);
Receive<GetDiagnostics>(HandleGetDiagnostics);
Receive<DriverInstanceActor.AttributeValuePublished>(ForwardToMux);
Receive<DriverInstanceActor.AttributeAlarmPublished>(ForwardNativeAlarm);
Receive<RestartDriver>(HandleRestartDriver);
Receive<ReconnectDriver>(HandleReconnectDriver);
Receive<RouteNodeWrite>(HandleRouteNodeWrite);
@@ -429,6 +456,7 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers
});
Receive<GetDiagnostics>(HandleGetDiagnostics);
Receive<DriverInstanceActor.AttributeValuePublished>(ForwardToMux);
Receive<DriverInstanceActor.AttributeAlarmPublished>(ForwardNativeAlarm);
Receive<RestartDriver>(HandleRestartDriver);
Receive<ReconnectDriver>(HandleReconnectDriver);
Receive<RouteNodeWrite>(HandleRouteNodeWrite);
@@ -466,6 +494,88 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers
}
}
/// <summary>
/// Routes a native alarm transition (published by a driver child as
/// <see cref="DriverInstanceActor.AttributeAlarmPublished"/>) to its materialised Part 9 condition
/// node(s). The alarm path analogue of <see cref="ForwardToMux"/>: the transition's <c>ConditionId</c>
/// (the dotted alarm full-reference, which equals the authored equipment-tag FullName — NOT the bare
/// <c>SourceNodeId</c> owning object) is resolved by the <see cref="_alarmNodeIdByDriverRef"/> map —
/// built each apply from the alarm-bearing EquipmentTags — to the folder-scoped condition NodeId(s)
/// the materialiser placed the condition(s) at.
/// For each node the <see cref="_nativeAlarmProjector"/> projects the transition delta into a full
/// <c>AlarmConditionSnapshot</c>, then this Tells <see cref="ZB.MOM.WW.OtOpcUa.Runtime.OpcUa.OpcUaPublishActor.AlarmStateUpdate"/>
/// — the SAME message scripted alarms use, so it routes through <c>WriteAlarmCondition</c>. An
/// unknown ref is Debug-logged and dropped (mirrors the value drop).
///
/// <para>
/// Each transition is ALSO published as an <see cref="AlarmTransitionEvent"/> to the cluster
/// <c>alerts</c> topic — the single historization + live <c>/alerts</c> fan-out path, exactly as
/// scripted alarms do (<c>ScriptedAlarmHostActor.OnEngineEmission</c>). The OPC UA condition
/// write above stays UNGATED (a Secondary keeps its address space warm for failover), but the
/// cluster-wide alerts publish is Primary-gated on the same <see cref="_localRole"/> redundancy
/// signal the inbound-write gate uses — only the Primary publishes the single fleet-wide copy.
/// </para>
/// </summary>
private void ForwardNativeAlarm(DriverInstanceActor.AttributeAlarmPublished msg)
{
if (_opcUaPublishActor is null) return;
// Resolve on ConditionId, NOT SourceNodeId: for Galaxy the dotted alarm full-reference — which
// equals the authored equipment-tag FullName the map is keyed by — is carried in ConditionId
// (AlarmFullReference), while SourceNodeId is the bare owning object (SourceObjectReference).
if (!_alarmNodeIdByDriverRef.TryGetValue((msg.DriverInstanceId, msg.Args.ConditionId), out var nodeIds))
{
_log.Debug("DriverHost {Node}: no alarm condition for ({Driver},{Ref}) — transition dropped",
_localNode, msg.DriverInstanceId, msg.Args.ConditionId);
return;
}
foreach (var nodeId in nodeIds)
{
var snapshot = _nativeAlarmProjector.Project(nodeId, msg.Args);
_opcUaPublishActor.Tell(new ZB.MOM.WW.OtOpcUa.Runtime.OpcUa.OpcUaPublishActor.AlarmStateUpdate(
nodeId, snapshot, msg.Args.SourceTimestampUtc));
// Warm-standby dedup: the OPC UA condition write above is UNGATED (the secondary keeps its
// address space warm), but only the Primary publishes the cluster-wide alerts transition.
// Default-emit until told we are Secondary/Detached so single-node deploys + the boot window
// never drop transitions — the SAME signal HandleRouteNodeWrite gates writes on.
if (_localRole is RedundancyRole.Secondary or RedundancyRole.Detached) continue;
var meta = _alarmMetaByNodeId.TryGetValue(nodeId, out var m)
? m : (EquipmentId: nodeId, Name: nodeId, AlarmType: "AlarmCondition");
_mediator.Tell(new Publish(ScriptedAlarmHostActor.AlertsTopic, new AlarmTransitionEvent(
AlarmId: nodeId,
EquipmentPath: meta.EquipmentId,
AlarmName: meta.Name,
TransitionKind: ToEventKind(msg.Args.Kind),
// The projector mapped the four-bucket AlarmSeverity onto the OPC UA 1..1000 scale already;
// reuse its ushort so the condition node + the alerts row agree on severity.
Severity: snapshot.Severity,
Message: msg.Args.Message,
// Native transitions are device-driven; an operator comment only rides along on an
// acknowledge from the upstream alarm system. "device" marks a non-operator origin.
User: msg.Args.OperatorComment is null ? string.Empty : "device",
TimestampUtc: msg.Args.SourceTimestampUtc,
AlarmTypeName: meta.AlarmType,
Comment: msg.Args.OperatorComment,
// Native alarms always historize (no per-condition opt-out surface yet — that is a
// scripted-alarm plan flag); pass a concrete true so the historian's null-default isn't relied on.
HistorizeToAveva: true)));
}
}
/// <summary>Maps a native <see cref="AlarmTransitionKind"/> onto the canonical alarm event-kind
/// vocabulary scripted alarms emit (the <c>EmissionKind</c> names) so a native row renders with the
/// correct chip on the <c>/alerts</c> page and historizes into the same <c>EventKind</c> column as
/// scripted alarms. An unmapped/unknown transition surfaces as <c>Activated</c> (visible) rather than
/// a grey unknown label.</summary>
private static string ToEventKind(AlarmTransitionKind kind) => kind switch
{
AlarmTransitionKind.Raise or AlarmTransitionKind.Retrigger => "Activated",
AlarmTransitionKind.Clear => "Cleared",
AlarmTransitionKind.Acknowledge => "Acknowledged",
_ => "Activated",
};
/// <summary>
/// Routes an inbound operator write (Task 11 Asks this from the OPC UA node-manager side) to the
/// owning driver child. Order matters:
@@ -731,7 +841,11 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers
return;
}
// Value-subscription set: alarm-bearing tags are Part 9 conditions, not value variables, so they
// are excluded — the driver must not value-subscribe an alarm attribute (it is fed via the native
// alarm event stream, routed by ForwardNativeAlarm).
var refsByDriver = composition.EquipmentTags
.Where(t => t.Alarm is null)
.GroupBy(t => t.DriverInstanceId, StringComparer.Ordinal)
.ToDictionary(
g => g.Key,
@@ -752,10 +866,34 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers
// reflected. Each NodeId maps to exactly one driver ref (a variable is backed by a single driver
// attribute), so last-writer-wins on the rare duplicate is harmless.
_driverRefByNodeId.Clear();
// Alarm condition routing map: (DriverInstanceId, FullName = alarm ConditionId/AlarmFullReference) → folder-scoped
// condition NodeId(s). Built from the SAME EquipmentTags pass (alarm-bearing tags only) so
// ForwardNativeAlarm can land a native transition on the right condition node. Clear-and-rebuild
// every apply; the projector is Clear()'d too so stale per-condition state never leaks across
// redeploys (renames/removals/address-space rebuilds).
_alarmNodeIdByDriverRef.Clear();
// Per-condition metadata (EquipmentId / Name / OPC UA alarm type) for the alerts fan-out, built in
// the SAME alarm branch as the node map so a redeploy can't leave it out of sync. Cleared alongside it.
_alarmMetaByNodeId.Clear();
_nativeAlarmProjector.Clear();
foreach (var t in composition.EquipmentTags)
{
var key = (t.DriverInstanceId, t.FullName);
var nodeId = EquipmentNodeIds.Variable(t.EquipmentId, t.FolderPath, t.Name);
if (t.Alarm is not null)
{
// Alarm tags are conditions, not value variables: route them ONLY into the alarm map and
// keep them OUT of the value maps + value-subscription set (so they don't get both a value
// variable AND a condition).
if (!_alarmNodeIdByDriverRef.TryGetValue(key, out var aset))
_alarmNodeIdByDriverRef[key] = aset = new HashSet<string>(StringComparer.Ordinal);
aset.Add(nodeId);
// Capture the per-condition metadata the alerts fan-out (ForwardNativeAlarm) needs to build
// the AlarmTransitionEvent: the equipment path, the operator-visible alarm name, and the
// OPC UA Part 9 subtype. Keyed by the condition NodeId (the projection's own key).
_alarmMetaByNodeId[nodeId] = (t.EquipmentId, t.Name, t.Alarm.AlarmType);
continue;
}
if (!_nodeIdByDriverRef.TryGetValue(key, out var set))
_nodeIdByDriverRef[key] = set = new HashSet<string>(StringComparer.Ordinal);
set.Add(nodeId);
@@ -64,6 +64,11 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
/// <see cref="ISubscribable.OnDataChange"/>. The parent forwards to OpcUaPublishActor.</summary>
public sealed record AttributeValuePublished(string DriverInstanceId, string FullReference, object? Value, OpcUaQuality Quality, DateTime TimestampUtc);
private sealed record DataChangeForward(string FullReference, DataValueSnapshot Snapshot);
/// <summary>Published to the parent whenever the subscribed driver (an <see cref="IAlarmSource"/>) fires
/// <see cref="IAlarmSource.OnAlarmEvent"/>. The parent (<see cref="DriverHostActor"/>) projects + routes it
/// to the materialised Part 9 condition. Parallels <see cref="AttributeValuePublished"/>.</summary>
public sealed record AttributeAlarmPublished(string DriverInstanceId, AlarmEventArgs Args);
private sealed record NativeAlarmRaised(AlarmEventArgs Args);
public sealed class RetryConnect
{
public static readonly RetryConnect Instance = new();
@@ -94,6 +99,7 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
/// do not need to re-send subscription requests after a reconnect.</summary>
private ISubscriptionHandle? _subscriptionHandle;
private EventHandler<DataChangeEventArgs>? _dataChangeHandler;
private EventHandler<AlarmEventArgs>? _alarmEventHandler;
/// <summary>The references the host wants kept subscribed (set by <see cref="SetDesiredSubscriptions"/>).
/// Re-applied on every entry into <c>Connected</c> so values resume after a reconnect or redeploy.</summary>
@@ -222,6 +228,7 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
Become(Connected);
PublishHealthSnapshot();
ResubscribeDesired();
AttachAlarmSource();
});
Receive<InitializeFailed>(msg =>
{
@@ -241,6 +248,10 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
// to Self (HandleSubscribeAsync already logged the underlying cause). Swallow it so it doesn't dead-letter.
Receive<SubscriptionFailed>(msg =>
_log.Debug("DriverInstance {Id}: resubscribe reported failure: {Reason}", _driverInstanceId, msg.Reason));
// A native alarm transition can race in while still (re)connecting (the driver's feed runs on its
// own thread); drop it — the feed re-delivers active alarms once Connected. Trace only.
Receive<NativeAlarmRaised>(_ =>
_log.Debug("DriverInstance {Id}: native alarm arrived during connect — dropped (feed re-delivers)", _driverInstanceId));
Receive<HealthPollTick>(_ => PublishHealthSnapshot());
}
@@ -273,6 +284,9 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
else if (_subscriptionHandle is not null) Self.Tell(new Unsubscribe());
});
Receive<DataChangeForward>(OnDataChangeForward);
// Native alarm transition marshaled onto the actor thread from the driver's OnAlarmEvent;
// project it to the parent the same way DataChangeForward projects AttributeValuePublished.
Receive<NativeAlarmRaised>(m => Context.Parent.Tell(new AttributeAlarmPublished(_driverInstanceId, m.Args)));
// ResubscribeDesired self-Tells Subscribe; HandleSubscribeAsync replies SubscriptionEstablished to the
// sender, which on the self-resubscribe path is Self. Swallow it (trace only) so it doesn't dead-letter.
Receive<SubscriptionEstablished>(msg =>
@@ -299,6 +313,7 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
Become(Connected);
PublishHealthSnapshot();
ResubscribeDesired();
AttachAlarmSource();
});
Receive<InitializeFailed>(_ => { /* keep retrying via timer */ });
Receive<SetDesiredSubscriptions>(StoreDesiredSubscriptions);
@@ -312,6 +327,10 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
// to Self (HandleSubscribeAsync already logged the underlying cause). Swallow it so it doesn't dead-letter.
Receive<SubscriptionFailed>(msg =>
_log.Debug("DriverInstance {Id}: resubscribe reported failure: {Reason}", _driverInstanceId, msg.Reason));
// A native alarm transition can race in while still reconnecting (the driver's feed runs on its
// own thread); drop it — the feed re-delivers active alarms once Connected. Trace only.
Receive<NativeAlarmRaised>(_ =>
_log.Debug("DriverInstance {Id}: native alarm arrived during reconnect — dropped (feed re-delivers)", _driverInstanceId));
Receive<HealthPollTick>(_ => PublishHealthSnapshot());
Timers.StartPeriodicTimer("retry-connect", RetryConnect.Instance, _reconnectInterval);
}
@@ -446,9 +465,9 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
}
}
/// <summary>Tear down the event handler + null the handle. Called from Unsubscribe path, on
/// PostStop, and on Connected → Reconnecting transitions so a stale handler doesn't push
/// data-change events to an actor that has lost its driver connection.</summary>
/// <summary>Tear down the data-change + native-alarm event handlers + null the handle. Called from the
/// Unsubscribe path, on PostStop, and on Connected → Reconnecting transitions so a stale handler doesn't
/// push data-change / alarm events to an actor that has lost its driver connection.</summary>
private void DetachSubscription()
{
if (_driver is ISubscribable subscribable && _dataChangeHandler is not null)
@@ -457,6 +476,26 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
}
_dataChangeHandler = null;
_subscriptionHandle = null;
DetachAlarmSource();
}
/// <summary>Subscribe the driver's native alarm event (if it is an <see cref="IAlarmSource"/>),
/// marshaling each transition to the actor thread. Idempotent; mirrors the OnDataChange attach.</summary>
private void AttachAlarmSource()
{
if (_driver is not IAlarmSource src || _alarmEventHandler is not null) return;
var self = Self;
_alarmEventHandler = (_, e) => self.Tell(new NativeAlarmRaised(e));
src.OnAlarmEvent += _alarmEventHandler;
}
/// <summary>Symmetric teardown — called from <see cref="DetachSubscription"/> and PostStop so a stale
/// handler never pushes to a disconnected actor.</summary>
private void DetachAlarmSource()
{
if (_driver is IAlarmSource src && _alarmEventHandler is not null)
src.OnAlarmEvent -= _alarmEventHandler;
_alarmEventHandler = null;
}
/// <summary>Records the host's desired subscription set without touching the live subscription.
@@ -0,0 +1,49 @@
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
namespace ZB.MOM.WW.OtOpcUa.Runtime.Drivers;
/// <summary>
/// Derives a full Part 9 <see cref="AlarmConditionSnapshot"/> from each native
/// <see cref="AlarmEventArgs"/> delta, tracking per-condition-NodeId prior state. Owned by the
/// single-threaded <c>DriverHostActor</c> (no locking). Native alarms carry only a transition
/// <see cref="AlarmTransitionKind"/>, not a full state machine, so this is the translation the
/// scripted-alarm engine does internally.
/// </summary>
public sealed class NativeAlarmProjector
{
private readonly Dictionary<string, (bool Active, bool Acked)> _prior = new(StringComparer.Ordinal);
/// <summary>Project an alarm transition onto the full condition snapshot for <paramref name="nodeId"/>.</summary>
/// <param name="nodeId">The materialised condition node's id (the projection's state key).</param>
/// <param name="e">The native alarm transition.</param>
/// <returns>The full Part 9 condition snapshot to write to the node.</returns>
public AlarmConditionSnapshot Project(string nodeId, AlarmEventArgs e)
{
var prev = _prior.TryGetValue(nodeId, out var p) ? p : (Active: false, Acked: true);
var sev = MapSeverity(e.Severity);
var (active, acked) = e.Kind switch
{
AlarmTransitionKind.Raise or AlarmTransitionKind.Retrigger => (true, false),
AlarmTransitionKind.Acknowledge => (prev.Active, true),
AlarmTransitionKind.Clear => (false, prev.Acked),
_ => (prev.Active, prev.Acked),
};
_prior[nodeId] = (active, acked);
return new AlarmConditionSnapshot(
Active: active, Acknowledged: acked, Confirmed: true, Enabled: true,
Shelving: AlarmShelvingKind.Unshelved, Severity: sev, Message: e.Message);
}
/// <summary>Clears all tracked per-node state (call on address-space rebuild).</summary>
public void Clear() => _prior.Clear();
private static ushort MapSeverity(AlarmSeverity s) => s switch
{
AlarmSeverity.Low => 200,
AlarmSeverity.Medium => 500,
AlarmSeverity.High => 700,
AlarmSeverity.Critical => 900,
_ => 500,
};
}
@@ -0,0 +1,23 @@
using Shouldly;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using Xunit;
namespace ZB.MOM.WW.OtOpcUa.Core.Abstractions.Tests;
public class AlarmEventArgsTests
{
private static AlarmEventArgs Make(AlarmTransitionKind? kind = null) =>
kind is null
? new AlarmEventArgs(new FakeHandle(), "Tank1.Hi", "c1", "LimitAlarm.Hi", "msg", AlarmSeverity.High, DateTime.UnixEpoch)
: new AlarmEventArgs(new FakeHandle(), "Tank1.Hi", "c1", "LimitAlarm.Hi", "msg", AlarmSeverity.High, DateTime.UnixEpoch, Kind: kind.Value);
[Fact]
public void Kind_defaults_to_Unspecified_so_existing_callers_compile()
=> Make().Kind.ShouldBe(AlarmTransitionKind.Unspecified);
[Fact]
public void Kind_round_trips_when_supplied()
=> Make(AlarmTransitionKind.Raise).Kind.ShouldBe(AlarmTransitionKind.Raise);
private sealed class FakeHandle : IAlarmSubscriptionHandle { public string DiagnosticId => "t"; }
}
@@ -42,6 +42,39 @@ public sealed class GalaxyDriverAlarmSourceTests
observed[0].SubscriptionHandle.ShouldBe(handle);
}
/// <summary>
/// Verifies that the driver maps each Galaxy transition kind onto the matching
/// <see cref="AlarmTransitionKind"/> on the surfaced <see cref="AlarmEventArgs"/>,
/// so a Part 9 consumer can derive active/ack state. The Galaxy kind is passed by
/// name because <c>GalaxyAlarmTransitionKind</c> is internal to the driver and so
/// cannot appear in a public test method signature.
/// </summary>
/// <param name="galaxyKindName">The <c>GalaxyAlarmTransitionKind</c> member name fed into the alarm feed.</param>
/// <param name="expectedKind">The expected <see cref="AlarmTransitionKind"/> on the surfaced event.</param>
[Theory]
[InlineData(nameof(GalaxyAlarmTransitionKind.Raise), AlarmTransitionKind.Raise)]
[InlineData(nameof(GalaxyAlarmTransitionKind.Acknowledge), AlarmTransitionKind.Acknowledge)]
[InlineData(nameof(GalaxyAlarmTransitionKind.Clear), AlarmTransitionKind.Clear)]
[InlineData(nameof(GalaxyAlarmTransitionKind.Retrigger), AlarmTransitionKind.Retrigger)]
[InlineData(nameof(GalaxyAlarmTransitionKind.Unspecified), AlarmTransitionKind.Unspecified)]
public async Task Transition_kind_maps_onto_AlarmEventArgs_Kind(
string galaxyKindName, AlarmTransitionKind expectedKind)
{
var galaxyKind = Enum.Parse<GalaxyAlarmTransitionKind>(galaxyKindName);
var feed = new FakeAlarmFeed();
var ack = new RecordingAcknowledger();
using var driver = NewDriver(feed, ack);
var handle = await driver.SubscribeAlarmsAsync(["Tank01"], CancellationToken.None);
var observed = new List<AlarmEventArgs>();
driver.OnAlarmEvent += (_, args) => observed.Add(args);
feed.Emit(NewTransition("Tank01.Level.HiHi", "Tank01", galaxyKind, AlarmSeverity.High));
observed.ShouldHaveSingleItem();
observed[0].Kind.ShouldBe(expectedKind);
}
/// <summary>Verifies that OnAlarmEvent does not fire before any alarm subscription.</summary>
[Fact]
public void OnAlarmEvent_does_not_fire_before_any_alarm_subscription()
@@ -6,6 +6,11 @@ using Xunit;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Runtime;
// Core.Abstractions now also defines an AlarmTransitionKind (the AlarmEventArgs surface
// kind). This file drives the gateway proto, so pin the bare token to the proto enum to
// preserve the existing references unchanged.
using AlarmTransitionKind = ZB.MOM.WW.MxGateway.Contracts.Proto.AlarmTransitionKind;
namespace ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Tests.Runtime;
/// <summary>
@@ -0,0 +1,22 @@
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.OpcUaServer;
namespace ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests;
public class ExtractTagAlarmTests
{
[Theory]
[InlineData("{\"FullName\":\"X.Y\"}", false, null, 0)]
[InlineData("{\"FullName\":\"X.Y\",\"alarm\":{}}", true, "AlarmCondition", 500)]
[InlineData("{\"FullName\":\"X.Y\",\"alarm\":{\"alarmType\":\"OffNormalAlarm\",\"severity\":700}}", true, "OffNormalAlarm", 700)]
[InlineData("not json", false, null, 0)]
[InlineData("{\"FullName\":\"X.Y\",\"alarm\":\"oops\"}", false, null, 0)]
public void ExtractTagAlarm_parses_or_returns_null(string cfg, bool present, string? type, int sev)
{
var info = Phase7Composer.ExtractTagAlarm(cfg);
if (!present) { info.ShouldBeNull(); return; }
info!.AlarmType.ShouldBe(type);
info.Severity.ShouldBe(sev);
}
}
@@ -143,7 +143,7 @@ public sealed class Phase7ApplierHierarchyTests : IDisposable
{
EquipmentTags = new[]
{
new EquipmentTagPlan("tag-1", "eq-1", "drv", FolderPath: "", Name: "Speed", DataType: "Float", FullName: "40001", Writable: false),
new EquipmentTagPlan("tag-1", "eq-1", "drv", FolderPath: "", Name: "Speed", DataType: "Float", FullName: "40001", Writable: false, Alarm: null),
},
};
@@ -131,7 +131,7 @@ public sealed class Phase7ApplierTests
{
EquipmentTags = new[]
{
new EquipmentTagPlan("tag-1", "eq-1", "drv", FolderPath: "", Name: "Speed", DataType: "Float", FullName: "40001", Writable: true),
new EquipmentTagPlan("tag-1", "eq-1", "drv", FolderPath: "", Name: "Speed", DataType: "Float", FullName: "40001", Writable: true, Alarm: null),
},
};
@@ -158,7 +158,7 @@ public sealed class Phase7ApplierTests
{
EquipmentTags = new[]
{
new EquipmentTagPlan("tag-2", "eq-1", "drv", FolderPath: "Diagnostics", Name: "Temp", DataType: "Float", FullName: "40002", Writable: false),
new EquipmentTagPlan("tag-2", "eq-1", "drv", FolderPath: "Diagnostics", Name: "Temp", DataType: "Float", FullName: "40002", Writable: false, Alarm: null),
},
};
@@ -185,8 +185,8 @@ public sealed class Phase7ApplierTests
{
EquipmentTags = new[]
{
new EquipmentTagPlan("tag-a", "eq-1", "drv-1", FolderPath: "", Name: "Speed", DataType: "Float", FullName: "40001", Writable: false),
new EquipmentTagPlan("tag-b", "eq-2", "drv-2", FolderPath: "", Name: "Speed", DataType: "Float", FullName: "40001", Writable: false),
new EquipmentTagPlan("tag-a", "eq-1", "drv-1", FolderPath: "", Name: "Speed", DataType: "Float", FullName: "40001", Writable: false, Alarm: null),
new EquipmentTagPlan("tag-b", "eq-2", "drv-2", FolderPath: "", Name: "Speed", DataType: "Float", FullName: "40001", Writable: false, Alarm: null),
},
};
@@ -197,6 +197,71 @@ public sealed class Phase7ApplierTests
sink.VariableCalls.ShouldContain(("eq-2/Speed", "eq-2", "Speed", "Float", false));
}
/// <summary>Phase B WS-3 — an alarm-bearing equipment tag (<c>Alarm is not null</c>) materialises a
/// real OPC UA Part 9 condition node (via the same path scripted alarms use) instead of a value
/// variable; a plain tag (<c>Alarm == null</c>) stays a value variable. The alarm tag's condition
/// uses the tag's folder-scoped NodeId, the equipment folder as parent, and carries the tag's
/// AlarmType/Severity. Proves BOTH branches in one composition.</summary>
[Fact]
public void MaterialiseEquipmentTags_alarm_bearing_tag_becomes_condition_plain_tag_stays_variable()
{
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-plain", "eq-1", "drv", FolderPath: "", Name: "Speed", DataType: "Float", FullName: "40001", Writable: true, Alarm: null),
new EquipmentTagPlan("tag-alarm", "eq-1", "drv", FolderPath: "", Name: "OverTemp", DataType: "Boolean", FullName: "00001", Writable: false, Alarm: new EquipmentTagAlarmInfo("OffNormalAlarm", 700)),
},
};
applier.MaterialiseEquipmentTags(composition);
// The plain tag drove EnsureVariable at its folder-scoped NodeId, and NOT a condition.
var plainNodeId = EquipmentNodeIds.Variable("eq-1", "", "Speed");
sink.VariableCalls.ShouldHaveSingleItem().ShouldBe((plainNodeId, "eq-1", "Speed", "Float", true));
sink.AlarmConditionCalls.ShouldNotContain(c => c.AlarmNodeId == plainNodeId);
// The alarm tag drove MaterialiseAlarmCondition (folder-scoped NodeId, equipment parent,
// matching display/type/severity) and did NOT drive EnsureVariable.
var alarmNodeId = EquipmentNodeIds.Variable("eq-1", "", "OverTemp");
sink.AlarmConditionCalls.ShouldHaveSingleItem()
.ShouldBe((alarmNodeId, "eq-1", "OverTemp", "OffNormalAlarm", 700));
sink.VariableCalls.ShouldNotContain(v => v.NodeId == alarmNodeId);
}
/// <summary>Phase B WS-3 — an alarm-bearing equipment tag WITH a FolderPath still gets its
/// sub-folder created, and its condition is parented to that sub-folder (not the equipment folder),
/// using the folder-scoped NodeId.</summary>
[Fact]
public void MaterialiseEquipmentTags_alarm_bearing_tag_with_FolderPath_conditions_under_subfolder()
{
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-alarm", "eq-1", "drv", FolderPath: "Diagnostics", Name: "OverTemp", DataType: "Boolean", FullName: "00001", Writable: false, Alarm: new EquipmentTagAlarmInfo("OffNormalAlarm", 500)),
},
};
applier.MaterialiseEquipmentTags(composition);
// The sub-folder is still created for an alarm tag with a FolderPath.
sink.FolderCalls.ShouldHaveSingleItem().ShouldBe(("eq-1/Diagnostics", "eq-1", "Diagnostics"));
// Condition is parented to the sub-folder, with the folder-scoped NodeId. No value variable.
var alarmNodeId = EquipmentNodeIds.Variable("eq-1", "Diagnostics", "OverTemp");
sink.AlarmConditionCalls.ShouldHaveSingleItem()
.ShouldBe((alarmNodeId, "eq-1/Diagnostics", "OverTemp", "OffNormalAlarm", 500));
sink.VariableCalls.ShouldBeEmpty();
}
/// <summary>Verifies MaterialiseEquipmentVirtualTags creates one Variable per VirtualTag directly
/// under its existing equipment folder, with a folder-scoped NodeId (EquipmentId/Name — NOT the
/// VirtualTagId or Expression), parent == EquipmentId, displayName == Name, and does NOT re-create
@@ -243,8 +308,8 @@ public sealed class Phase7ApplierTests
{
EquipmentTags = new[]
{
new EquipmentTagPlan("tag-flat", "eq-1", "drv", FolderPath: "", Name: "Speed", DataType: "Float", FullName: "40001", Writable: false),
new EquipmentTagPlan("tag-nested", "eq-1", "drv", FolderPath: "Diagnostics", Name: "Temp", DataType: "Float", FullName: "40002", Writable: false),
new EquipmentTagPlan("tag-flat", "eq-1", "drv", FolderPath: "", Name: "Speed", DataType: "Float", FullName: "40001", Writable: false, Alarm: null),
new EquipmentTagPlan("tag-nested", "eq-1", "drv", FolderPath: "Diagnostics", Name: "Temp", DataType: "Float", FullName: "40002", Writable: false, Alarm: null),
},
EquipmentVirtualTags = new[]
{
@@ -338,7 +403,7 @@ public sealed class Phase7ApplierTests
{
AddedEquipmentTags = new[]
{
new EquipmentTagPlan("tag-1", "eq-1", "drv", FolderPath: "", Name: "Speed", DataType: "Float", FullName: "40001", Writable: false),
new EquipmentTagPlan("tag-1", "eq-1", "drv", FolderPath: "", Name: "Speed", DataType: "Float", FullName: "40001", Writable: false, Alarm: null),
},
};
@@ -43,7 +43,7 @@ public sealed class Phase7PlannerTests
{
EquipmentTags = new[]
{
new EquipmentTagPlan("tag-1", "eq-1", "drv", FolderPath: "", Name: "Speed", DataType: "Float", FullName: "40001", Writable: false),
new EquipmentTagPlan("tag-1", "eq-1", "drv", FolderPath: "", Name: "Speed", DataType: "Float", FullName: "40001", Writable: false, Alarm: null),
},
};
@@ -241,6 +241,8 @@ public sealed class DeploymentArtifactAliasParityTests
};
// The Galaxy equipment tag — FullName is the Galaxy ref "tag_name.AttributeName".
// It also carries a native-alarm intent in TagConfig.alarm, so this draft proves the
// optional Alarm field is parsed byte-identically on both producers (Phase B WS-2).
var galaxyTag = new Tag
{
TagId = "tag-galaxy",
@@ -250,7 +252,7 @@ public sealed class DeploymentArtifactAliasParityTests
Name = "DownloadPath",
DataType = "String",
AccessLevel = TagAccessLevel.Read,
TagConfig = "{\"FullName\":\"DelmiaReceiver_001.DownloadPath\"}",
TagConfig = "{\"FullName\":\"DelmiaReceiver_001.DownloadPath\",\"alarm\":{\"alarmType\":\"OffNormalAlarm\",\"severity\":700}}",
};
// A non-Galaxy (Modbus) equipment tag — proves the parity holds across drivers, not just Galaxy.
var modbusTag = new Tag
@@ -315,6 +317,7 @@ public sealed class DeploymentArtifactAliasParityTests
d.DataType.ShouldBe(x.DataType);
d.FullName.ShouldBe(x.FullName);
d.Writable.ShouldBe(x.Writable);
d.Alarm.ShouldBe(x.Alarm); // EquipmentTagAlarmInfo is a positional record ⇒ value equality
}
var galaxyPlan = decoded.EquipmentTags.Single(t => t.TagId == "tag-galaxy");
@@ -323,6 +326,15 @@ public sealed class DeploymentArtifactAliasParityTests
galaxyPlan.DriverInstanceId.ShouldBe("drv-galaxy");
galaxyPlan.FolderPath.ShouldBe(string.Empty); // null FolderPath coalesced identically on both sides
// The native-alarm intent in the Galaxy tag's TagConfig.alarm is parsed byte-identically on both
// producers (Phase B WS-2). The Modbus tag has no alarm object ⇒ null Alarm on both sides.
galaxyPlan.Alarm.ShouldNotBeNull();
galaxyPlan.Alarm!.AlarmType.ShouldBe("OffNormalAlarm");
galaxyPlan.Alarm.Severity.ShouldBe(700);
composed.EquipmentTags.Single(t => t.TagId == "tag-galaxy").Alarm.ShouldBe(galaxyPlan.Alarm);
decoded.EquipmentTags.Single(t => t.TagId == "tag-modbus").Alarm.ShouldBeNull();
composed.EquipmentTags.Single(t => t.TagId == "tag-modbus").Alarm.ShouldBeNull();
// Writability flows from Tag.AccessLevel: the Galaxy tag is Read (read-only node), the Modbus
// tag is ReadWrite (writable node). Both producers must derive the same Writable flag, and the
// SequenceEqual above already proves they agree element-wise.
@@ -0,0 +1,309 @@
using System.Text.Json;
using Akka.Actor;
using Akka.Cluster.Tools.PublishSubscribe;
using Akka.TestKit;
using Microsoft.EntityFrameworkCore;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Commons.Engines;
using ZB.MOM.WW.OtOpcUa.Commons.Messages.Alerts;
using ZB.MOM.WW.OtOpcUa.Commons.Messages.Deploy;
using ZB.MOM.WW.OtOpcUa.Commons.Messages.Fleet;
using ZB.MOM.WW.OtOpcUa.Commons.Messages.Redundancy;
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.Core.Abstractions;
using ZB.MOM.WW.OtOpcUa.Runtime.Drivers;
using ZB.MOM.WW.OtOpcUa.Runtime.OpcUa;
using ZB.MOM.WW.OtOpcUa.Runtime.ScriptedAlarms;
using ZB.MOM.WW.OtOpcUa.Runtime.Tests.Harness;
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.Drivers;
/// <summary>
/// Verifies the equipment-tag <b>native-alarm routing</b> wired into <see cref="DriverHostActor"/>
/// (Phase B WS-4c, the LIVE-CONDITION half): a driver child publishes a native alarm transition as
/// <see cref="DriverInstanceActor.AttributeAlarmPublished"/> keyed by the alarm source's
/// <c>SourceNodeId</c> (the equipment tag's wire-ref <c>FullName</c>), but the materialised condition
/// lives at a FOLDER-SCOPED NodeId (<c>{equipmentId}/{folderPath}/{name}</c>). After an apply, the
/// host's <c>_alarmNodeIdByDriverRef</c> map (built only from alarm-bearing EquipmentTags) resolves
/// <c>(DriverInstanceId, SourceNodeId)</c> to that NodeId, the <c>NativeAlarmProjector</c> projects
/// the transition into a full <c>AlarmConditionSnapshot</c>, and <c>ForwardNativeAlarm</c> Tells the
/// publish actor an <see cref="OpcUaPublishActor.AlarmStateUpdate"/> — the same message scripted
/// alarms use.
///
/// <para>
/// Mirrors the value-routing harness in <c>DriverHostActorLiveValueTests</c>: the seeded artifact
/// carries the <c>Namespaces</c> / <c>DriverInstances</c> / <c>Tags</c> arrays, with each alarm
/// tag's <c>TagConfig</c> carrying an <c>alarm</c> object so
/// <c>DeploymentArtifact.ExtractTagAlarm</c> projects a non-null
/// <c>EquipmentTagAlarmInfo</c>. The OPC UA sink + dependency mux are injected as TestProbes.
/// </para>
/// </summary>
public sealed class DriverHostActorNativeAlarmTests : RuntimeActorTestBase
{
private static readonly NodeId TestNode = NodeId.Parse("driver-alarm-test");
private static readonly RevisionHash RevA = RevisionHash.Parse(new string('a', 64));
private static readonly DateTime Ts = new(2026, 6, 14, 10, 0, 0, DateTimeKind.Utc);
/// <summary>A native alarm RAISE whose <c>ConditionId</c> equals the alarm tag's <c>FullName</c> lands on
/// the condition's folder-scoped NodeId (here <c>eq-1/temp_hi</c>) as an
/// <see cref="OpcUaPublishActor.AlarmStateUpdate"/> with <c>State.Active == true</c>. The event carries a
/// production-shaped <c>SourceNodeId</c> (the bare owning object, distinct from <c>ConditionId</c>) so the
/// lookup is proven to key on <c>ConditionId</c>, not <c>SourceNodeId</c>.</summary>
[Fact]
public void Native_alarm_raise_routes_to_folder_scoped_condition_NodeId_active()
{
var db = NewInMemoryDbFactory();
// One alarm-bearing equipment tag: eq-1, drv-1, FullName "Temp.HiHi", no folder, Name "temp_hi".
var deploymentId = SeedDeploymentWithAlarmTag(db, RevA,
Equip: "eq-1", Driver: "drv-1", FullName: "Temp.HiHi", Folder: null, Name: "temp_hi");
var (actor, publish) = SpawnHostAndApply(db, deploymentId);
actor.Tell(new DriverInstanceActor.AttributeAlarmPublished("drv-1", new AlarmEventArgs(
new StubAlarmHandle(),
SourceNodeId: "Temp", // bare owning object (SourceObjectReference) — NOT the lookup key
ConditionId: "Temp.HiHi", // dotted alarm full-reference = the authored FullName (the lookup key)
AlarmType: "OffNormalAlarm",
Message: "temperature high",
Severity: AlarmSeverity.High,
SourceTimestampUtc: Ts,
Kind: AlarmTransitionKind.Raise)));
var update = publish.ExpectMsg<OpcUaPublishActor.AlarmStateUpdate>(TimeSpan.FromSeconds(5));
update.AlarmNodeId.ShouldBe("eq-1/temp_hi");
update.State.Active.ShouldBeTrue();
update.State.Acknowledged.ShouldBeFalse();
update.TimestampUtc.ShouldBe(Ts);
}
/// <summary>An <see cref="DriverInstanceActor.AttributeAlarmPublished"/> whose <c>ConditionId</c> is not in
/// the alarm map produces NO <see cref="OpcUaPublishActor.AlarmStateUpdate"/> (unknown-ref drop).</summary>
[Fact]
public void Unknown_alarm_ref_produces_no_AlarmStateUpdate()
{
var db = NewInMemoryDbFactory();
var deploymentId = SeedDeploymentWithAlarmTag(db, RevA,
Equip: "eq-1", Driver: "drv-1", FullName: "Temp.HiHi", Folder: null, Name: "temp_hi");
var (actor, publish) = SpawnHostAndApply(db, deploymentId);
actor.Tell(new DriverInstanceActor.AttributeAlarmPublished("drv-1", new AlarmEventArgs(
new StubAlarmHandle(),
SourceNodeId: "Temp", // owning object exists, but the condition ref below is unmapped
ConditionId: "NoSuch.HiHi", // dotted ref not in the alarm map ⇒ drop
AlarmType: "OffNormalAlarm",
Message: "nope",
Severity: AlarmSeverity.Low,
SourceTimestampUtc: Ts,
Kind: AlarmTransitionKind.Raise)));
// No alarm-condition NodeId for ("drv-1","NoSuch.Alarm") → nothing reaches the sink.
publish.ExpectNoMsg(TimeSpan.FromMilliseconds(500));
}
/// <summary>Primary (default/unset role) fan-out (Phase B WS-5): a native alarm RAISE on a known ref
/// publishes exactly one <see cref="AlarmTransitionEvent"/> to the cluster <c>alerts</c> topic with
/// <c>AlarmId</c> = the folder-scoped condition NodeId, alongside the (ungated) OPC UA condition
/// update. No <see cref="RedundancyStateChanged"/> is sent, so the cached role is unknown ⇒ emit.</summary>
[Fact]
public void Native_alarm_publishes_AlarmTransitionEvent_to_alerts_when_primary()
{
var db = NewInMemoryDbFactory();
var deploymentId = SeedDeploymentWithAlarmTag(db, RevA,
Equip: "eq-1", Driver: "drv-1", FullName: "Temp.HiHi", Folder: null, Name: "temp_hi");
var alerts = CreateTestProbe();
SubscribeToAlerts(alerts);
var (actor, publish) = SpawnHostAndApply(db, deploymentId);
actor.Tell(new DriverInstanceActor.AttributeAlarmPublished("drv-1", new AlarmEventArgs(
new StubAlarmHandle(),
SourceNodeId: "Temp", // bare owning object (SourceObjectReference) — NOT the lookup key
ConditionId: "Temp.HiHi", // dotted alarm full-reference = the authored FullName (the lookup key)
AlarmType: "OffNormalAlarm",
Message: "temperature high",
Severity: AlarmSeverity.High,
SourceTimestampUtc: Ts,
Kind: AlarmTransitionKind.Raise)));
// The OPC UA condition update is UNGATED — it must arrive.
var update = publish.ExpectMsg<OpcUaPublishActor.AlarmStateUpdate>(TimeSpan.FromSeconds(5));
update.AlarmNodeId.ShouldBe("eq-1/temp_hi");
// Role unknown ⇒ default-emit: exactly one AlarmTransitionEvent on the alerts topic.
var evt = alerts.ExpectMsg<AlarmTransitionEvent>(TimeSpan.FromSeconds(5));
evt.AlarmId.ShouldBe("eq-1/temp_hi"); // the folder-scoped condition NodeId
evt.EquipmentPath.ShouldBe("eq-1"); // from the alarm-bearing tag's EquipmentId
evt.AlarmName.ShouldBe("temp_hi"); // from the tag's Name
evt.TransitionKind.ShouldBe("Activated"); // native Kind → canonical EmissionKind vocabulary (Raise → Activated)
evt.AlarmTypeName.ShouldBe("OffNormalAlarm"); // the tag's alarm AlarmType
evt.Severity.ShouldBe(700); // AlarmSeverity.High → projector 700
evt.Message.ShouldBe("temperature high");
evt.User.ShouldBe(string.Empty); // no operator comment ⇒ device-origin (empty user)
evt.HistorizeToAveva.ShouldBe(true);
alerts.ExpectNoMsg(TimeSpan.FromMilliseconds(300)); // exactly one
}
/// <summary>Secondary suppression (Phase B WS-5): when the cached local role is Secondary the host
/// MUST still write the local OPC UA condition node (ungated — keeps the standby's address space warm
/// for failover) but MUST NOT publish the cluster-wide <c>alerts</c> transition (the Primary publishes
/// the single fleet-wide copy).</summary>
[Fact]
public void Secondary_node_suppresses_alerts_publish_but_still_updates_condition()
{
var db = NewInMemoryDbFactory();
var deploymentId = SeedDeploymentWithAlarmTag(db, RevA,
Equip: "eq-1", Driver: "drv-1", FullName: "Temp.HiHi", Folder: null, Name: "temp_hi");
var alerts = CreateTestProbe();
SubscribeToAlerts(alerts);
var (actor, publish) = SpawnHostAndApply(db, deploymentId);
// Mark this node Secondary so the alerts publish is gated off.
TellRedundancyRole(actor, RedundancyRole.Secondary);
actor.Tell(new DriverInstanceActor.AttributeAlarmPublished("drv-1", new AlarmEventArgs(
new StubAlarmHandle(),
SourceNodeId: "Temp", // bare owning object (SourceObjectReference) — NOT the lookup key
ConditionId: "Temp.HiHi", // dotted alarm full-reference = the authored FullName (the lookup key)
AlarmType: "OffNormalAlarm",
Message: "temperature high",
Severity: AlarmSeverity.High,
SourceTimestampUtc: Ts,
Kind: AlarmTransitionKind.Raise)));
// The OPC UA condition update is UNGATED — it must still arrive on the secondary.
var update = publish.ExpectMsg<OpcUaPublishActor.AlarmStateUpdate>(TimeSpan.FromSeconds(5));
update.AlarmNodeId.ShouldBe("eq-1/temp_hi");
update.State.Active.ShouldBeTrue();
// The cluster-wide alerts publish is gated off on the secondary.
alerts.ExpectNoMsg(TimeSpan.FromMilliseconds(500));
}
/// <summary>Subscribe <paramref name="probe"/> to the <c>alerts</c> DPS topic and wait for the ack.
/// The Subscribe is sent FROM the probe so the SubscribeAck returns to it. Mirrors the
/// ScriptedAlarmHostActor test harness.</summary>
private void SubscribeToAlerts(TestProbe probe)
{
DistributedPubSub.Get(Sys).Mediator.Tell(
new Subscribe(ScriptedAlarmHostActor.AlertsTopic, probe.Ref), probe.Ref);
probe.ExpectMsg<SubscribeAck>(TimeSpan.FromSeconds(5));
}
/// <summary>Tell the host a <see cref="RedundancyStateChanged"/> snapshot marking the host's own
/// node (<see cref="TestNode"/>, which equals the host's <c>_localNode</c>) with <paramref name="role"/>
/// so the alerts-publish gate observes the local role.</summary>
private static void TellRedundancyRole(IActorRef host, RedundancyRole role)
{
host.Tell(new RedundancyStateChanged(
new[]
{
new NodeRedundancyState(
NodeId: TestNode,
Role: role,
IsClusterLeader: role == RedundancyRole.Primary,
IsRoleLeaderForDriver: role == RedundancyRole.Primary,
AsOfUtc: DateTime.UtcNow),
},
CorrelationId.NewId()));
}
/// <summary>Spawns the host with a publish probe, dispatches the deployment, and waits for the Applied
/// ACK so the apply (and thus the alarm-map build in PushDesiredSubscriptions) has completed before the
/// test publishes an alarm. A VirtualTag-host probe is injected so the real host isn't spawned.</summary>
private (IActorRef Actor, Akka.TestKit.TestProbe Publish) 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<AlarmStateUpdate> assertions see only alarm updates.
publish.ExpectMsg<OpcUaPublishActor.RebuildAddressSpace>(TimeSpan.FromSeconds(5));
return (actor, publish);
}
/// <summary>
/// Seeds a Sealed deployment whose artifact carries one alarm-bearing equipment tag: the tag's
/// <c>TagConfig</c> carries both a <c>FullName</c> and an <c>alarm</c> object
/// (<c>alarmType</c> + <c>severity</c>) so <c>DeploymentArtifact.ExtractTagAlarm</c> projects a
/// non-null <c>EquipmentTagAlarmInfo</c> (here <c>OffNormalAlarm</c> / 700) — making the tag a
/// condition rather than a value variable.
/// </summary>
private static DeploymentId SeedDeploymentWithAlarmTag(
IDbContextFactory<OtOpcUaConfigDbContext> db, RevisionHash rev,
string Equip, string Driver, string FullName, string? Folder, string Name)
{
var artifact = JsonSerializer.SerializeToUtf8Bytes(new
{
Namespaces = new[]
{
new { NamespaceId = "ns-eq", Kind = 0 }, // NamespaceKind.Equipment = 0
},
DriverInstances = new[]
{
new { DriverInstanceId = Driver, NamespaceId = "ns-eq" },
},
Tags = new[]
{
new
{
TagId = "tag-0",
EquipmentId = Equip,
DriverInstanceId = Driver,
Name,
FolderPath = Folder,
DataType = "Boolean",
TagConfig = JsonSerializer.Serialize(new
{
FullName,
alarm = new { alarmType = "OffNormalAlarm", severity = 700 },
}),
},
},
});
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;
}
/// <summary>Minimal <see cref="IAlarmSubscriptionHandle"/> for building <see cref="AlarmEventArgs"/>.</summary>
private sealed class StubAlarmHandle : IAlarmSubscriptionHandle
{
/// <summary>Gets the diagnostic ID of the alarm subscription.</summary>
public string DiagnosticId => "stub-alarm-sub";
}
}
@@ -0,0 +1,259 @@
using Akka.Actor;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
using ZB.MOM.WW.OtOpcUa.Commons.Types;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using ZB.MOM.WW.OtOpcUa.Runtime.Drivers;
using ZB.MOM.WW.OtOpcUa.Runtime.Tests.Harness;
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.Drivers;
/// <summary>
/// Covers WS-4b: <see cref="DriverInstanceActor"/> subscribes a driver's native
/// <see cref="IAlarmSource.OnAlarmEvent"/> (when the driver is an <see cref="IAlarmSource"/>)
/// and forwards every transition to its parent as
/// <see cref="DriverInstanceActor.AttributeAlarmPublished"/> — mirroring the OnDataChange →
/// <see cref="DriverInstanceActor.AttributeValuePublished"/> forward. The driver fires
/// <c>OnAlarmEvent</c> on its OWN thread; the actor marshals it onto the actor thread via Self.
/// </summary>
public sealed class DriverInstanceActorNativeAlarmTests : RuntimeActorTestBase
{
/// <summary>
/// Driving an <see cref="IAlarmSource"/> driver to Connected then raising a native alarm forwards
/// it to the parent as <see cref="DriverInstanceActor.AttributeAlarmPublished"/> carrying the
/// driver-instance id + the original <see cref="AlarmEventArgs"/> (SourceNodeId preserved).
/// </summary>
[Fact]
public async Task Native_alarm_is_forwarded_to_parent_as_AttributeAlarmPublished()
{
var driver = new AlarmSourceStubDriver();
var parent = CreateTestProbe();
var actor = parent.ChildActorOf(DriverInstanceActor.Props(driver));
actor.Tell(new DriverInstanceActor.InitializeRequested("{}"));
AwaitCondition(() => driver.InitializeCount > 0, TimeSpan.FromSeconds(2));
// The alarm handler is attached after Become(Connected); wait for it to be wired before raising.
AwaitCondition(() => driver.AlarmSubscriberCount == 1, TimeSpan.FromSeconds(2));
// Also establish a data-change subscription so the OnDataChange path is wired (the alarm attach is
// independent of Subscribe — this proves both event paths coexist on one driver).
await actor.Ask<DriverInstanceActor.SubscriptionEstablished>(
new DriverInstanceActor.Subscribe(new[] { "tag-z" }, TimeSpan.FromMilliseconds(100)),
TimeSpan.FromSeconds(3));
driver.RaiseAlarm(new AlarmEventArgs(
new StubAlarmHandle(),
SourceNodeId: "src-node-7",
ConditionId: "cond-1",
AlarmType: "AnalogLimitAlarm.HiHi",
Message: "level too high",
Severity: AlarmSeverity.High,
SourceTimestampUtc: DateTime.UtcNow,
Kind: AlarmTransitionKind.Raise));
var published = parent.ExpectMsg<DriverInstanceActor.AttributeAlarmPublished>(TimeSpan.FromSeconds(2));
published.DriverInstanceId.ShouldBe(driver.DriverInstanceId);
published.Args.SourceNodeId.ShouldBe("src-node-7");
published.Args.ConditionId.ShouldBe("cond-1");
published.Args.Kind.ShouldBe(AlarmTransitionKind.Raise);
// The same driver's OnDataChange still flows independently — alarm + value events coexist.
driver.FireDataChange("tag-z", value: 9.0, statusCode: 0u);
parent.ExpectMsg<DriverInstanceActor.AttributeValuePublished>(TimeSpan.FromSeconds(2))
.FullReference.ShouldBe("tag-z");
}
/// <summary>
/// A driver that is NOT an <see cref="IAlarmSource"/> (only <see cref="ISubscribable"/>) connects
/// and serves data changes normally — <c>AttachAlarmSource</c> is a safe no-op (no crash) and no
/// <see cref="DriverInstanceActor.AttributeAlarmPublished"/> is ever produced.
/// </summary>
[Fact]
public async Task Non_alarm_source_driver_serves_data_changes_and_never_publishes_alarms()
{
var driver = new SubscribableOnlyStubDriver();
var parent = CreateTestProbe();
var actor = parent.ChildActorOf(DriverInstanceActor.Props(driver));
actor.Tell(new DriverInstanceActor.InitializeRequested("{}"));
AwaitCondition(() => driver.InitializeCount > 0, TimeSpan.FromSeconds(2));
await actor.Ask<DriverInstanceActor.SubscriptionEstablished>(
new DriverInstanceActor.Subscribe(new[] { "tag-a" }, TimeSpan.FromMilliseconds(100)),
TimeSpan.FromSeconds(3));
driver.FireDataChange("tag-a", value: 1.5, statusCode: 0u);
// Data-change forwarding still works (no crash on AttachAlarmSource for a non-IAlarmSource driver).
var dc = parent.ExpectMsg<DriverInstanceActor.AttributeValuePublished>(TimeSpan.FromSeconds(2));
dc.FullReference.ShouldBe("tag-a");
// An AttributeAlarmPublished can never be produced for a non-IAlarmSource driver.
parent.ExpectNoMsg(TimeSpan.FromMilliseconds(300));
}
/// <summary>
/// After a full reconnect cycle (Connected → Reconnecting → Connected), a single raised alarm still
/// yields EXACTLY ONE <see cref="DriverInstanceActor.AttributeAlarmPublished"/> — the
/// <c>_alarmEventHandler is not null</c> guard in <c>AttachAlarmSource</c> plus the detach on the
/// Connected → Reconnecting transition prevent a double-attach (which would publish twice).
/// </summary>
[Fact]
public void Reconnect_does_not_double_attach_alarm_handler()
{
var driver = new AlarmSourceStubDriver();
var parent = CreateTestProbe();
var actor = parent.ChildActorOf(DriverInstanceActor.Props(driver, reconnectInterval: TimeSpan.FromMilliseconds(50)));
actor.Tell(new DriverInstanceActor.InitializeRequested("{}"));
AwaitCondition(() => driver.AlarmSubscriberCount == 1, TimeSpan.FromSeconds(2));
// Force Connected → Reconnecting (detaches) → Connected (re-attaches). InitializeCount climbs on
// the retry; the alarm handler count must settle back to exactly one (no leaked extra handler).
var initBefore = driver.InitializeCount;
actor.Tell(new DriverInstanceActor.DisconnectObserved("backend blip"));
AwaitCondition(() => driver.InitializeCount > initBefore, TimeSpan.FromSeconds(3));
AwaitCondition(() => driver.AlarmSubscriberCount == 1, TimeSpan.FromSeconds(3));
driver.RaiseAlarm(new AlarmEventArgs(
new StubAlarmHandle(),
SourceNodeId: "src-node-1",
ConditionId: "cond-x",
AlarmType: "T",
Message: "m",
Severity: AlarmSeverity.Low,
SourceTimestampUtc: DateTime.UtcNow,
Kind: AlarmTransitionKind.Raise));
// Exactly one forward — a double-attach would surface as a second AttributeAlarmPublished.
parent.ExpectMsg<DriverInstanceActor.AttributeAlarmPublished>(TimeSpan.FromSeconds(2))
.Args.SourceNodeId.ShouldBe("src-node-1");
parent.ExpectNoMsg(TimeSpan.FromMilliseconds(300));
}
// --- stub drivers ----------------------------------------------------------------------------
private class StubDriver : IDriver
{
/// <summary>Gets the number of times initialization was called.</summary>
public int InitializeCount;
/// <summary>Gets the driver instance ID.</summary>
public string DriverInstanceId => "alarm-stub-driver-1";
/// <summary>Gets the driver type.</summary>
public string DriverType => "Stub";
/// <summary>Initializes the driver.</summary>
public Task InitializeAsync(string driverConfigJson, CancellationToken cancellationToken)
{
Interlocked.Increment(ref InitializeCount);
return Task.CompletedTask;
}
/// <summary>Reinitializes the driver.</summary>
public Task ReinitializeAsync(string driverConfigJson, CancellationToken cancellationToken) =>
Task.CompletedTask;
/// <summary>Shuts down the driver.</summary>
public Task ShutdownAsync(CancellationToken cancellationToken) => Task.CompletedTask;
/// <summary>Gets the health status of the driver.</summary>
public DriverHealth GetHealth() => new(DriverState.Healthy, DateTime.UtcNow, null);
/// <summary>Gets the memory footprint of the driver.</summary>
public long GetMemoryFootprint() => 0;
/// <summary>Flushes optional caches in the driver.</summary>
public Task FlushOptionalCachesAsync(CancellationToken cancellationToken) => Task.CompletedTask;
}
/// <summary>A driver that implements <see cref="ISubscribable"/> + <see cref="IAlarmSource"/> and lets the
/// test raise <see cref="IAlarmSource.OnAlarmEvent"/> on demand (the driver fires it on its own thread in
/// production; here the test thread stands in for that).</summary>
private sealed class AlarmSourceStubDriver : StubDriver, ISubscribable, IAlarmSource
{
private readonly StubHandle _subHandle = new();
/// <summary>Occurs when data changes.</summary>
public event EventHandler<DataChangeEventArgs>? OnDataChange;
/// <summary>Server-pushed alarm transition.</summary>
public event EventHandler<AlarmEventArgs>? OnAlarmEvent;
/// <summary>Number of live subscribers on <see cref="OnAlarmEvent"/> — proves attach/detach.</summary>
public int AlarmSubscriberCount => OnAlarmEvent?.GetInvocationList().Length ?? 0;
/// <summary>Subscribes to the specified full references.</summary>
public Task<ISubscriptionHandle> SubscribeAsync(
IReadOnlyList<string> fullReferences, TimeSpan publishingInterval, CancellationToken cancellationToken) =>
Task.FromResult<ISubscriptionHandle>(_subHandle);
/// <summary>Unsubscribes from the specified subscription handle.</summary>
public Task UnsubscribeAsync(ISubscriptionHandle handle, CancellationToken cancellationToken) =>
Task.CompletedTask;
/// <summary>Subscribes to alarm events for the specified node set.</summary>
public Task<IAlarmSubscriptionHandle> SubscribeAlarmsAsync(
IReadOnlyList<string> sourceNodeIds, CancellationToken cancellationToken) =>
Task.FromResult<IAlarmSubscriptionHandle>(new StubAlarmHandle());
/// <summary>Cancels an alarm subscription.</summary>
public Task UnsubscribeAlarmsAsync(IAlarmSubscriptionHandle handle, CancellationToken cancellationToken) =>
Task.CompletedTask;
/// <summary>Acknowledges a batch of alarms.</summary>
public Task AcknowledgeAsync(
IReadOnlyList<AlarmAcknowledgeRequest> acknowledgements, CancellationToken cancellationToken) =>
Task.CompletedTask;
/// <summary>Fires <see cref="OnAlarmEvent"/> — stands in for the driver's native feed.</summary>
public void RaiseAlarm(AlarmEventArgs args) => OnAlarmEvent?.Invoke(this, args);
/// <summary>Fires a data change event (keeps OnDataChange exercised; the actor wires both events).</summary>
public void FireDataChange(string fullRef, object? value, uint statusCode)
{
var snapshot = new DataValueSnapshot(value, statusCode, DateTime.UtcNow, DateTime.UtcNow);
OnDataChange?.Invoke(this, new DataChangeEventArgs(_subHandle, fullRef, snapshot));
}
private sealed class StubHandle : ISubscriptionHandle
{
/// <summary>Gets the diagnostic ID of the subscription.</summary>
public string DiagnosticId => "stub-sub";
}
}
/// <summary>A driver that is <see cref="ISubscribable"/> but NOT <see cref="IAlarmSource"/> — proves
/// <c>AttachAlarmSource</c> is a no-op (no crash) and no alarm forward ever happens.</summary>
private sealed class SubscribableOnlyStubDriver : StubDriver, ISubscribable
{
private readonly StubHandle _subHandle = new();
/// <summary>Occurs when data changes.</summary>
public event EventHandler<DataChangeEventArgs>? OnDataChange;
/// <summary>Subscribes to the specified full references.</summary>
public Task<ISubscriptionHandle> SubscribeAsync(
IReadOnlyList<string> fullReferences, TimeSpan publishingInterval, CancellationToken cancellationToken) =>
Task.FromResult<ISubscriptionHandle>(_subHandle);
/// <summary>Unsubscribes from the specified subscription handle.</summary>
public Task UnsubscribeAsync(ISubscriptionHandle handle, CancellationToken cancellationToken) =>
Task.CompletedTask;
/// <summary>Fires a data change event with the specified parameters.</summary>
public void FireDataChange(string fullRef, object? value, uint statusCode)
{
var snapshot = new DataValueSnapshot(value, statusCode, DateTime.UtcNow, DateTime.UtcNow);
OnDataChange?.Invoke(this, new DataChangeEventArgs(_subHandle, fullRef, snapshot));
}
private sealed class StubHandle : ISubscriptionHandle
{
/// <summary>Gets the diagnostic ID of the subscription.</summary>
public string DiagnosticId => "stub-sub";
}
}
/// <summary>Minimal <see cref="IAlarmSubscriptionHandle"/> for building <see cref="AlarmEventArgs"/>.</summary>
private sealed class StubAlarmHandle : IAlarmSubscriptionHandle
{
/// <summary>Gets the diagnostic ID of the alarm subscription.</summary>
public string DiagnosticId => "stub-alarm-sub";
}
}
@@ -0,0 +1,166 @@
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using ZB.MOM.WW.OtOpcUa.Runtime.Drivers;
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.Drivers;
public class NativeAlarmProjectorTests
{
[Fact]
public void Raise_projects_active_unacked_with_constant_fields_and_mapped_severity()
{
var sut = new NativeAlarmProjector();
var snap = sut.Project("n1", Evt(AlarmTransitionKind.Raise, AlarmSeverity.High, "boom"));
snap.Active.ShouldBeTrue();
snap.Acknowledged.ShouldBeFalse();
snap.Confirmed.ShouldBeTrue();
snap.Enabled.ShouldBeTrue();
snap.Shelving.ShouldBe(AlarmShelvingKind.Unshelved);
snap.Severity.ShouldBe((ushort)700);
snap.Message.ShouldBe("boom");
}
[Fact]
public void Retrigger_projects_active_unacked()
{
var sut = new NativeAlarmProjector();
var snap = sut.Project("n1", Evt(AlarmTransitionKind.Retrigger));
snap.Active.ShouldBeTrue();
snap.Acknowledged.ShouldBeFalse();
}
[Fact]
public void Acknowledge_after_raise_acks_and_keeps_active()
{
var sut = new NativeAlarmProjector();
sut.Project("n1", Evt(AlarmTransitionKind.Raise));
var snap = sut.Project("n1", Evt(AlarmTransitionKind.Acknowledge));
snap.Active.ShouldBeTrue();
snap.Acknowledged.ShouldBeTrue();
}
[Fact]
public void Clear_after_raise_deactivates_and_keeps_prior_ack()
{
var sut = new NativeAlarmProjector();
sut.Project("n1", Evt(AlarmTransitionKind.Raise)); // active, unacked
var snap = sut.Project("n1", Evt(AlarmTransitionKind.Clear));
snap.Active.ShouldBeFalse();
snap.Acknowledged.ShouldBeFalse(); // preserved prior (unacked) ack state
}
[Fact]
public void Clear_after_acknowledge_deactivates_and_keeps_acked()
{
var sut = new NativeAlarmProjector();
sut.Project("n1", Evt(AlarmTransitionKind.Raise));
sut.Project("n1", Evt(AlarmTransitionKind.Acknowledge)); // active, acked
var snap = sut.Project("n1", Evt(AlarmTransitionKind.Clear));
snap.Active.ShouldBeFalse();
snap.Acknowledged.ShouldBeTrue(); // preserved prior (acked) ack state
}
[Fact]
public void Unspecified_carries_prior_active_and_ack_state()
{
var sut = new NativeAlarmProjector();
sut.Project("n1", Evt(AlarmTransitionKind.Raise)); // active, unacked
var snap = sut.Project("n1", Evt(AlarmTransitionKind.Unspecified));
snap.Active.ShouldBeTrue();
snap.Acknowledged.ShouldBeFalse();
}
[Fact]
public void Cold_state_defaults_to_inactive_acked()
{
var sut = new NativeAlarmProjector();
// Acknowledge on a never-seen node: prior Active defaults false, ack set true.
var snap = sut.Project("nNew", Evt(AlarmTransitionKind.Acknowledge));
snap.Active.ShouldBeFalse();
snap.Acknowledged.ShouldBeTrue();
}
[Fact]
public void Per_node_state_is_isolated()
{
var sut = new NativeAlarmProjector();
sut.Project("n1", Evt(AlarmTransitionKind.Raise)); // n1 active
// n2 is cold; a Clear on it must stay inactive and not borrow n1's active state.
var n2 = sut.Project("n2", Evt(AlarmTransitionKind.Clear));
n2.Active.ShouldBeFalse();
// n1 is unaffected by the n2 transition.
var n1 = sut.Project("n1", Evt(AlarmTransitionKind.Acknowledge));
n1.Active.ShouldBeTrue();
}
[Theory]
[InlineData(AlarmSeverity.Low, (ushort)200)]
[InlineData(AlarmSeverity.Medium, (ushort)500)]
[InlineData(AlarmSeverity.High, (ushort)700)]
[InlineData(AlarmSeverity.Critical, (ushort)900)]
public void Severity_buckets_map_to_opcua_scale(AlarmSeverity sev, ushort expected)
{
var sut = new NativeAlarmProjector();
var snap = sut.Project("n1", Evt(AlarmTransitionKind.Raise, sev));
snap.Severity.ShouldBe(expected);
}
[Fact]
public void Severity_and_message_always_come_from_the_event()
{
var sut = new NativeAlarmProjector();
sut.Project("n1", Evt(AlarmTransitionKind.Raise, AlarmSeverity.High, "first"));
// A later Clear carries its own severity + message; the snapshot reflects the event, not prior.
var snap = sut.Project("n1", Evt(AlarmTransitionKind.Clear, AlarmSeverity.Low, "second"));
snap.Severity.ShouldBe((ushort)200);
snap.Message.ShouldBe("second");
}
[Fact]
public void Clear_resets_tracked_state()
{
var sut = new NativeAlarmProjector();
sut.Project("n1", Evt(AlarmTransitionKind.Raise)); // n1 active, unacked
sut.Clear();
// After Clear() the node is cold again: an Acknowledge sees prior Active=false.
var snap = sut.Project("n1", Evt(AlarmTransitionKind.Acknowledge));
snap.Active.ShouldBeFalse();
snap.Acknowledged.ShouldBeTrue();
}
private static AlarmEventArgs Evt(
AlarmTransitionKind kind,
AlarmSeverity sev = AlarmSeverity.High,
string msg = "m")
=> new(new H(), "Tank1.Hi", "c1", "LimitAlarm.Hi", msg, sev, DateTime.UnixEpoch, Kind: kind);
private sealed class H : IAlarmSubscriptionHandle
{
public string DiagnosticId => "t";
}
}