feat(heidenhain): Part 9 condition class from alarm class/group, ALARM: selectors in the browse picker, unclaimed alarms counted + logged (#839)

- Core: optional AlarmEventArgs.ConditionClass (AlarmConditionClass Base/Process/Maintenance/System/Safety)
  carried by NativeAlarmProjector on AlarmConditionSnapshot and written to ConditionClassId/Name by
  OtOpcUaNodeManager (kept across class-less events, carried across a #641 rebuild).
- Heidenhain: HeidenhainAlarmClasses — HEIDENHAIN DNC-interface class/group names (corroborated by the
  captured iTNC 530 record); class 5 => Safety, group 1/2 => Process, 4/5 => System, else Base.
- DiscoverAsync offers AlarmConditions/ selector leaves (IsAlarm Boolean); browse-commit seeds the alarm object.
- Alarms no selector claims: otopcua.driver.alarms.unmatched counter, /hosts diagnostics, rate-limited Warning.

Refs #839
This commit is contained in:
Joseph Doherty
2026-11-11 03:41:14 -05:00
parent 481985e20b
commit ddc1f29e3a
17 changed files with 593 additions and 39 deletions
+6 -1
View File
@@ -337,7 +337,12 @@ host logger factory (wired in `DriverFactoryBootstrap`; the FOCAS and TwinCAT fa
arrays unchanged. Walked on `Polling.AlarmMs` (2 s) by the control's single loop with the SAME `R_RI 27/28` — the
allowlist is unchanged. FOCAS transition rules; identity = class+group+number+TEXT (numbers repeat, `-1`). A failed walk
(refusal/overflow/comms) is quality-only, never a clear. ⚠️ Ack is LOCAL-ONLY (`AcknowledgeAsync` no-op success) —
never add an LSV2 ack/write to the allowlist for it. Class/group codes have no invented names or severities.
never add an LSV2 ack/write to the allowlist for it. Class/group codes have no invented SEVERITIES; since #839 they
carry HEIDENHAIN DNC-interface names (labels + browse leaves only — corroborated by one iTNC 530 record, else
hardware-unproven) and set the Part 9 `ConditionClass` (class 5 ⇒ Safety; group 1/2 ⇒ Process; 4/5 ⇒ System; else Base)
via the new optional `AlarmEventArgs.ConditionClass` (projector keeps it across class-less events; node manager writes
it; rebuild carries it). The browse picker offers `AlarmConditions/` selector leaves; alarms no selector claims are
counted (`otopcua.driver.alarms.unmatched`, `/hosts` `<host>.alarms.unmatched[Total]`) + rate-limited Warning.
- **Credential references are namespaced per driver (#815):** ONE table (`Core.Abstractions.DriverCredentialPolicy`) +
ONE parser/resolver (`CredentialReferences`) for Galaxy (`secret:galaxy/`·`secret:otopcua/galaxy/`·`env:OTOPCUA_GALAXY_`·
`env:GALAXY_MXGW_`), OpcUaClient (`secret:opcuaclient/`·`env:OTOPCUA_OPCUACLIENT_`) and Heidenhain. Enforced at save
+14 -7
View File
@@ -163,8 +163,8 @@ are set explicitly. Leaving them unset shipped them as **null** on every event
| `SourceNode` | the condition's **own NodeId** — equal to `ConditionId` | The condition **is** the source: an alarm-bearing raw tag materializes only the condition, with no sibling value variable, so there is no other node to point at |
| `SourceName` | the same identifying id string: **RawPath** (native) / **ScriptedAlarmId** (scripted) | Deliberately the *unique* id, **not** the leaf name |
| `ConditionName` | the leaf / display name (e.g. `HR200`) | Where the short human-readable name lives |
| `ConditionClassId` | always **`BaseConditionClassType`** | Part 9's "no condition class modelled" value. Unset shipped `NodeId.Null` (#475) |
| `ConditionClassName` | always **`"BaseConditionClass"`** | Matches `ConditionClassId`. Unset shipped empty text (#475) |
| `ConditionClassId` | **`BaseConditionClassType`** at materialize; a classifying native driver may set `Process`/`Maintenance`/`System`/`SafetyConditionClassType` at runtime (#839 — today only Heidenhain) | Part 9's "no condition class modelled" value. Unset shipped `NodeId.Null` (#475) |
| `ConditionClassName` | **`"BaseConditionClass"`**, or the matching `"<X>ConditionClass"` | Matches `ConditionClassId`. Unset shipped empty text (#475) |
| `Quality` | the condition's **source-data quality** — native tracks the source's connectivity (`Good` / `Bad`); scripted takes the worst of its input tags' qualities (#478) | A pure annotation; never alters Active/Acked/Retain. Unset shipped the accidentally-Good default (#477) — see below |
**Why `BaseConditionClassType` and not `ProcessConditionClassType`.** We hold no per-alarm
@@ -173,11 +173,18 @@ classification at the materialize seam, and `ConditionClassId` is a wire contrac
condition classes"* — it fixes the real defect (a null that breaks conformant clients) without
asserting a classification we cannot back. `ProcessConditionClassType` — the SDK sample's pick —
was rejected deliberately: it would be *actively wrong* for a Galaxy alarm whose upstream category is
Safety or Diagnostics, trading a detectable null for an undetectable lie. Real per-alarm
classification is a separate future feature: it needs the driver's alarm category, which today lives
only on the runtime `AlarmEventArgs` transition, carried to the deploy-time authored composition that
`MaterialiseAlarmCondition` sees. Until then the `IAlarmSource` doc comment claiming the category
"maps to `ConditionClassName` downstream" describes an intent, not the implementation.
Safety or Diagnostics, trading a detectable null for an undetectable lie.
**Per-alarm classification arrives at runtime (#839).** A native driver whose upstream codes say where
an alarm comes from sets the optional `AlarmEventArgs.ConditionClass` (`AlarmConditionClass` —
Base/Process/Maintenance/System/Safety) on its Raise/Retrigger; `NativeAlarmProjector` carries it on the
`AlarmConditionSnapshot` (kept across events that state none — quality-only annotations, Clears) and
`WriteAlarmCondition` writes `ConditionClassId`/`ConditionClassName` over the materialize default. It is
not in the event delta-gate (a class rides along with the transition that set it) and the #641 rebuild
carry-over keeps it, normal conditions included. Only Heidenhain classifies today
(`docs/drivers/Heidenhain.md` §Alarm conditions); every other source leaves `BaseConditionClassType`.
Galaxy's free-text `AlarmCategory` is still not mapped — the `IAlarmSource` doc comment's
"maps to `ConditionClassName` downstream" remains an intent for that field.
**Why `SourceName` is the id, not the leaf name.** The leaf is ambiguous across devices (`HR200` on
two PLCs collides) and is already carried by `ConditionName`, so the leaf-name option would add no
+41 -6
View File
@@ -177,10 +177,34 @@ MTConnect #626.
| `ALARM:CLASS=<r>[/GROUP=<r>][/NUMBER=<r>]` (any subset, any order, each key once) | an alarm matches every named field |
`<r>` is `n` or `lo..hi` (inclusive; `..` because numbers can be negative — a real iTNC 530 reports `-1`). CLASS/GROUP
are 0–65535 (wire uint16), NUMBER is int32. **No semantic class/group names**: their meaning is undocumented in the
reference (pyLSV2 / the Java port keep them raw), so nothing is guessed — observe `Alarms/Classes` / `Alarms/Groups` or
a condition message, then filter. One parser (`HeidenhainAlarmSelector`) backs the editor, the deploy inspector and the
driver.
are 0–65535 (wire uint16), NUMBER is int32. Selectors always filter on the **raw codes**; observe `Alarms/Classes` /
`Alarms/Groups` or a condition message, then filter. One parser (`HeidenhainAlarmSelector`) backs the editor, the deploy
inspector and the driver.
**Class / group names and the Part 9 condition class (Gitea #839).** LSV2 documents neither field (pyLSV2 and the Java
port keep them raw). `HeidenhainAlarmClasses` carries HEIDENHAIN's own names from the **DNC interface** (RemoTools SDK
`DNC_ERROR_CLASS` / `DNC_ERROR_GROUP`), which describe the same control error list. That the LSV2 codes share that
numbering is corroborated by the one real record we hold — the captured iTNC 530 "Run test of cutout channels" is class 7
`INFO`, group 4 `GENERAL`, a power-up self-test notice — and is otherwise **hardware-unproven** (the commissioning gate
should confirm it on a live control).
| Class | 1 Warning · 2 FeedHold · 3 ProgramHold · 4 ProgramAbort · **5 EmergencyStop** · 6 Reset · 7 Info · 8 Error · 9 Note |
|---|---|
| **Group** | **1 Operating** · **2 Programming** · 3 Plc · **4 General** · **5 Remote** · 6 Python |
The names are labels only — they drive no selection and no severity. They set the condition's Part 9
`ConditionClassId`/`ConditionClassName`, and only where a code says *where the alarm comes from*:
| Controller alarm | Part 9 class |
|---|---|
| class 5 (EmergencyStop), any group | `SafetyConditionClassType` |
| group 1 Operating / 2 Programming (machining and NC-program errors) | `ProcessConditionClassType` |
| group 4 General / 5 Remote (the control's own system and remote-interface messages) | `SystemConditionClassType` |
| group 3 Plc (machine-builder text: process, maintenance or safety alike), 6 Python, 0 / unknown | `BaseConditionClassType` ("not modelled") |
Nothing maps to `MaintenanceConditionClassType` — no code is evidence of it. A condition's class is that of its
**displayed** alarm, set on every Raise/Retrigger; a Clear or a quality-only event states none, so the node keeps the
class of the alarm it last showed (and a rebuild carries it). The condition message is unchanged.
- **Opt-in is the tag — nothing is on by default.** An existing config gains no condition and loses nothing; the
`Alarms/*` arrays keep publishing. This follows FOCAS #647 (`AlarmProjection.Enabled` became a no-op: the authored
@@ -198,7 +222,14 @@ driver.
alarm leaves while others remain → `Retrigger` (un-acknowledges — a statement the operator has not seen); a
non-displayed member leaves → nothing; nothing matches → `Clear`.
- **Severity**: an authored integer `alarm.severity` is the exact Part 9 severity; otherwise High (700). No
class→severity table is invented.
class→severity table is invented (the class names above set the condition CLASS, never its severity).
- **Unclaimed alarms are reported, not dropped silently (Gitea #839).** On a control with no `*`/`OTHER` selector, an
alarm no `CLASS/GROUP/NUMBER` filter matches is shown by no condition. Each such alarm *entering* that set counts once
(a standing alarm is not re-counted per walk) on the OTel counter `otopcua.driver.alarms.unmatched`
(`driver_type=Heidenhain`, `driver_instance`), and `/hosts` diagnostics carry `<host>.alarms.unmatched` (unclaimed on
the last good walk) and `<host>.alarms.unmatchedTotal` (since the driver started). One Warning per control at most
per minute names up to three of them and how many more were suppressed since the previous line. A failed walk changes
nothing. Add a selector, or an `ALARM:OTHER` catch-all, to surface them.
- **Diffed against what the server was TOLD**, recorded only while a handler is attached; the record lives on the
driver instance (survives a reconnect / same-set re-subscribe / in-place re-init). A deploy respawns the driver and its
first walk re-states still-active alarms with `Raise`, which the host treats as a re-statement (ack kept,
@@ -217,7 +248,11 @@ driver.
every `Polling.AlarmMs`, and only for a control that carries an `ALARM:` tag. No new command type exists
(`HeidenhainAlarmTests` asserts the wire log is a subset of the read set and `Lsv2ReadOnlyPolicy` is unchanged).
- **Authoring:** the `/raw` tag modal (`Native alarm` section + the typed editor), manual entry (the editor seeds the
alarm object) and CSV (`Alarm.AlarmType` / `Alarm.Severity` columns). The browse picker offers only catalog leaves.
alarm object), CSV (`Alarm.AlarmType` / `Alarm.Severity` columns) and — since #839 — the **browse picker**, whose
`AlarmConditions/` folder offers `AnyAlarm` (`ALARM:*`), `OtherAlarms` (`ALARM:OTHER`), `ByClass/Class<n>_<Name>`
(`ALARM:CLASS=n`, classes 1–9) and `ByGroup/Group<n>_<Name>` (`ALARM:GROUP=n`, groups 1–6) as `IsAlarm` Boolean leaves;
a commit seeds the paired `alarm` object (severity 700), so the committed tag passes the factory unchanged. Ranges,
`NUMBER` and combined filters are still typed by hand. Discovery still contacts no control.
- E2E: `Runtime.Tests/Drivers/HeidenhainNativeAlarmEndToEndTests` (real driver → simulator → real `DriverHostActor`).
## Quality
@@ -86,6 +86,17 @@ public static class OtOpcUaTelemetry
Meter.CreateCounter<long>("otopcua.driver.opcuaclient.events", unit: "{event}",
description: "OPC UA Client driver session/publish events (event=publish_response|notification|data_change|bad_status_value|publish_error|keepalive_miss|keepalive_recovered|stale_notification_dropped).");
/// <summary>
/// Controller alarms a native-alarm driver saw that NO configured alarm selector on that device claims, so no
/// Part 9 condition shows them (lmxopcua#839 — Heidenhain <c>ALARM:</c> selectors without <c>*</c>/<c>OTHER</c>).
/// Counted once per alarm occurrence (an alarm entering the unclaimed set), not once per poll. Tagged
/// <see cref="PollOverrunDriverTypeTag"/> + <see cref="PollOverrunDriverInstanceTag"/>. A non-zero rate means
/// operators are not seeing some controller alarms — add a selector (or an <c>OTHER</c> catch-all).
/// </summary>
public static readonly Counter<long> DriverAlarmsUnmatched =
Meter.CreateCounter<long>("otopcua.driver.alarms.unmatched", unit: "{alarm}",
description: "Controller alarm occurrences no configured native-alarm selector claims (shown by no condition).");
// ---------------- VirtualTag / ScriptedAlarm engines ----------------
public static readonly Counter<long> VirtualTagEval =
@@ -1,3 +1,5 @@
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
namespace ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
/// <summary>
@@ -30,6 +32,11 @@ namespace ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
/// time instead of the SDK's ~24.8-day ceiling. A timed snapshot without it (a caller that
/// predates the field) falls back to that ceiling — the engine still owns the expiry either way.
/// </param>
/// <param name="ConditionClass">
/// The Part 9 <c>ConditionClass</c> a native source assigned (lmxopcua#839), or <c>null</c> to leave the node's class
/// as it is (scripted alarms and every native source that does not classify). Not part of the event delta-gate: a
/// class rides along with the transition that set it.
/// </param>
public sealed record AlarmConditionSnapshot(
bool Active,
bool Acknowledged,
@@ -39,7 +46,8 @@ public sealed record AlarmConditionSnapshot(
ushort Severity,
string Message,
uint StatusCode = OpcUaStatus.Good,
DateTime? UnshelveAtUtc = null);
DateTime? UnshelveAtUtc = null,
AlarmConditionClass? ConditionClass = null);
/// <summary>
/// Commons-local mirror of the Core <c>ShelvingKind</c> enum so this assembly carries no
@@ -122,6 +122,13 @@ public sealed record AlarmAcknowledgeRequest(
/// that writes nothing and a host retaining it Active gets a real "Cleared". <c>false</c> (the default, every source that does not
/// opt in) keeps every transition's row.
/// </param>
/// <param name="ConditionClass">
/// Optional Part 9 <c>ConditionClass</c> of the condition (lmxopcua#839), for a source whose upstream classifies its
/// alarms in a way that maps onto the Part 9 classes with evidence (Heidenhain's error class / group). When set, the
/// host writes it to the condition's <c>ConditionClassId</c> / <c>ConditionClassName</c>; <c>null</c> (every other
/// source) leaves the node's class untouched — <c>BaseConditionClass</c> ("not modelled") unless an earlier event of
/// the same condition set one. A pure annotation: it never moves Active/Acked state and never fires an event on its own.
/// </param>
public sealed record AlarmEventArgs(
IAlarmSubscriptionHandle SubscriptionHandle,
string SourceNodeId,
@@ -136,7 +143,8 @@ public sealed record AlarmEventArgs(
AlarmTransitionKind Kind = AlarmTransitionKind.Unspecified,
int? OpcUaSeverity = null,
uint? QualityStatusCode = null,
bool IsRestatement = false)
bool IsRestatement = false,
AlarmConditionClass? ConditionClass = null)
{
/// <summary>
/// True when this event only re-annotates the condition's source-data quality — a
@@ -163,3 +171,26 @@ public enum AlarmSeverity { Low, Medium, High, Critical }
/// Members are append-only: their numeric values must not move.
/// </summary>
public enum AlarmTransitionKind { Unspecified = 0, Raise, Acknowledge, Clear, Retrigger, ActiveAcknowledged, InactiveUnacknowledged }
/// <summary>
/// The OPC UA Part 9 condition classes (<c>BaseConditionClassType</c> subtypes, Part 9 §5.9) a driver can assign to a
/// native condition via <see cref="AlarmEventArgs.ConditionClass"/> (lmxopcua#839). Only the classes a driver has
/// evidence for are listed; <see cref="Base"/> is Part 9's "no class modelled". Members are append-only.
/// </summary>
public enum AlarmConditionClass
{
/// <summary><c>BaseConditionClassType</c> — the class is not modelled / not known.</summary>
Base = 0,
/// <summary><c>ProcessConditionClassType</c> — the condition relates to the process the system controls.</summary>
Process,
/// <summary><c>MaintenanceConditionClassType</c> — the condition relates to maintenance.</summary>
Maintenance,
/// <summary><c>SystemConditionClassType</c> — the condition relates to the system itself (hardware, software, comms).</summary>
System,
/// <summary><c>SafetyConditionClassType</c> — the condition relates to safety.</summary>
Safety,
}
@@ -0,0 +1,98 @@
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
namespace ZB.MOM.WW.OtOpcUa.Driver.Heidenhain;
/// <summary>
/// Names for the class / group codes of a Heidenhain control's active-alarm list, and the Part 9
/// <c>ConditionClass</c> each maps to (lmxopcua#839).
/// </summary>
/// <remarks>
/// <para><b>Provenance.</b> LSV2 itself documents neither field (pyLSV2 and the ignitionoee Java port keep them
/// raw). The names are HEIDENHAIN's own error enums from the DNC interface (RemoTools SDK / HeidenhainDNC
/// <c>DNC_ERROR_CLASS</c>, <c>DNC_ERROR_GROUP</c>), which describe the same control error list. That the LSV2
/// <c>R_RI 27/28</c> codes use the same numbering is corroborated by the one real record we hold — the captured
/// iTNC 530 alarm "Run test of cutout channels" is class 7 (<c>INFO</c>), group 4 (<c>GENERAL</c>), a power-up
/// self-test notice — but is not otherwise proven on hardware. Treat the names as labels, never as behaviour:
/// they drive no selection and no severity (an authored <c>alarm.severity</c>, else High, still decides that).</para>
/// <para><b>Part 9 mapping — only where the code says where the alarm comes from.</b>
/// <c>EMERGENCY_STOP</c> (class 5) is a safety reaction ⇒ <see cref="AlarmConditionClass.Safety"/>, whatever its
/// group. Otherwise the GROUP decides: <c>OPERATING</c> / <c>PROGRAMMING</c> (machining and NC-program errors) ⇒
/// <see cref="AlarmConditionClass.Process"/>; <c>GENERAL</c> / <c>REMOTE</c> (the control's own system and
/// remote-interface messages) ⇒ <see cref="AlarmConditionClass.System"/>. <c>PLC</c> messages are written by the
/// machine builder and can be process, maintenance or safety alike, and <c>PYTHON</c> / unknown codes say nothing
/// ⇒ <see cref="AlarmConditionClass.Base"/> ("not modelled"). Nothing maps to Maintenance: no code is evidence of
/// it.</para>
/// </remarks>
public static class HeidenhainAlarmClasses
{
/// <summary>The emergency-stop error class.</summary>
public const int EmergencyStopClass = 5;
/// <summary>Class code → HEIDENHAIN DNC name (<c>DNC_ERROR_CLASS</c>).</summary>
public static IReadOnlyDictionary<int, string> ClassNames { get; } = new Dictionary<int, string>
{
[0] = "None",
[1] = "Warning",
[2] = "FeedHold",
[3] = "ProgramHold",
[4] = "ProgramAbort",
[5] = "EmergencyStop",
[6] = "Reset",
[7] = "Info",
[8] = "Error",
[9] = "Note",
};
/// <summary>Group code → HEIDENHAIN DNC name (<c>DNC_ERROR_GROUP</c>).</summary>
public static IReadOnlyDictionary<int, string> GroupNames { get; } = new Dictionary<int, string>
{
[0] = "None",
[1] = "Operating",
[2] = "Programming",
[3] = "Plc",
[4] = "General",
[5] = "Remote",
[6] = "Python",
};
/// <summary>The browse-picker folder holding the <c>ALARM:</c> selectors (lmxopcua#839).</summary>
public const string BrowseFolder = "AlarmConditions";
/// <summary>
/// The <c>ALARM:</c> selectors the <c>/raw</c> browse picker offers (lmxopcua#839), as (sub-folder or null, leaf
/// name, address): <c>*</c> and <c>OTHER</c> at the folder root, then one <c>CLASS=n</c> per named class
/// (<c>ByClass/</c>) and one <c>GROUP=n</c> per named group (<c>ByGroup/</c>), code 0 ("None") excluded. The leaf
/// name carries the code AND the DNC name (<c>Class5_EmergencyStop</c>) so a committed tag still says which
/// number it filters on. Any other selector (ranges, NUMBER, combinations) is typed by hand as before.
/// </summary>
public static IReadOnlyList<(string? SubFolder, string Name, string Address)> BrowseSelectors { get; } = BuildBrowseSelectors();
private static List<(string?, string, string)> BuildBrowseSelectors()
{
var list = new List<(string?, string, string)>
{
(null, "AnyAlarm", HeidenhainAlarmSelector.Prefix + HeidenhainAlarmSelector.AnyToken),
(null, "OtherAlarms", HeidenhainAlarmSelector.Prefix + HeidenhainAlarmSelector.OtherToken),
};
foreach (var (code, name) in ClassNames.Where(kv => kv.Key != 0).OrderBy(kv => kv.Key))
list.Add(("ByClass", $"Class{code}_{name}", $"{HeidenhainAlarmSelector.Prefix}CLASS={code}"));
foreach (var (code, name) in GroupNames.Where(kv => kv.Key != 0).OrderBy(kv => kv.Key))
list.Add(("ByGroup", $"Group{code}_{name}", $"{HeidenhainAlarmSelector.Prefix}GROUP={code}"));
return list;
}
/// <summary>The Part 9 condition class of one controller alarm (see the remarks for the evidence).</summary>
/// <param name="errorClass">The alarm's class code.</param>
/// <param name="group">The alarm's group code.</param>
/// <returns>The class; <see cref="AlarmConditionClass.Base"/> when the codes say nothing.</returns>
public static AlarmConditionClass ConditionClassOf(int errorClass, int group)
{
if (errorClass == EmergencyStopClass) return AlarmConditionClass.Safety;
return group switch
{
1 or 2 => AlarmConditionClass.Process,
4 or 5 => AlarmConditionClass.System,
_ => AlarmConditionClass.Base,
};
}
}
@@ -51,9 +51,10 @@ public readonly record struct HeidenhainAlarmRange(long Low, long High)
/// <para>A range <c>&lt;r&gt;</c> is <c>n</c> or <c>lo..hi</c> (inclusive; <c>..</c> rather than <c>-</c> because
/// alarm numbers can be negative — a real iTNC 530 reports <c>-1</c>). CLASS and GROUP are the wire's uint16
/// fields (0–65535); NUMBER is int32.</para>
/// <para><b>No semantic names.</b> The meaning of the class/group codes is not documented in the reference
/// (pyLSV2 / the Java port keep them raw), so — like FOCAS's unconfirmed 30i type table — nothing is guessed:
/// observe the raw values on <c>Alarms/Classes</c> / <c>Alarms/Groups</c> or in a condition message, then filter.</para>
/// <para><b>Numeric codes only.</b> The grammar takes raw codes, never names: LSV2 itself does not document them.
/// <see cref="HeidenhainAlarmClasses"/> carries HEIDENHAIN's DNC-interface names for labels (the browse picker) and
/// the Part 9 condition class (lmxopcua#839), but a selector always filters on the number the wire carries —
/// observe it on <c>Alarms/Classes</c> / <c>Alarms/Groups</c> or in a condition message.</para>
/// <para><b>One authority.</b> Backs the AdminUI editor, the deploy inspector and the driver's table build.</para>
/// </remarks>
/// <param name="Kind">The selector kind.</param>
@@ -1,5 +1,6 @@
using System.Text;
using Microsoft.Extensions.Logging;
using ZB.MOM.WW.OtOpcUa.Commons.Observability;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using ZB.MOM.WW.OtOpcUa.Driver.Heidenhain.Lsv2;
@@ -45,8 +46,10 @@ internal sealed record HeidenhainToldCondition(
/// displayed alarm leaves while others remain = <c>Retrigger</c> (un-acknowledges: a statement the operator
/// has not seen); a non-displayed member leaves = nothing; nothing matches = <c>Clear</c>.</item>
/// <item><b>Severity</b>: an authored integer <c>alarm.severity</c> is sent exactly (<c>OpcUaSeverity</c>);
/// otherwise the bucket is High and no exact value is sent. Class semantics are undocumented, so no
/// class→severity table is invented.</item>
/// otherwise the bucket is High and no exact value is sent. No class→severity table is invented.</item>
/// <item><b>Condition class</b> (lmxopcua#839): a Raise / Retrigger carries the DISPLAYED alarm's Part 9 class
/// (<see cref="HeidenhainAlarmClasses.ConditionClassOf"/>); a Clear or a quality-only event carries none, so the
/// node keeps the class of the alarm it last showed.</item>
/// </list>
/// </remarks>
internal static class HeidenhainAlarmRules
@@ -90,10 +93,11 @@ internal static class HeidenhainAlarmRules
var (bucket, exact) = tag.AuthoredSeverity is { } s ? (BucketOf(s), (int?)s) : (AlarmSeverity.High, null);
var message = MessageOf(matched);
var raised = new HeidenhainToldCondition(true, keys, winner, message, bucket, exact);
var conditionClass = HeidenhainAlarmClasses.ConditionClassOf(winner.Class, winner.Group);
if (told is not { Active: true })
return (Build(tag, handle, nowUtc, AlarmTransitionKind.Raise, message, bucket, exact), raised);
return (Build(tag, handle, nowUtc, AlarmTransitionKind.Raise, message, bucket, exact, conditionClass: conditionClass), raised);
if (keys.Any(k => !told.Keys.Contains(k)) || told.Winner != winner)
return (Build(tag, handle, nowUtc, AlarmTransitionKind.Retrigger, message, bucket, exact), raised);
return (Build(tag, handle, nowUtc, AlarmTransitionKind.Retrigger, message, bucket, exact, conditionClass: conditionClass), raised);
return (null, told with { Keys = keys });
}
@@ -119,7 +123,8 @@ internal static class HeidenhainAlarmRules
}
public static AlarmEventArgs Build(HeidenhainAlarmTag tag, IAlarmSubscriptionHandle handle, DateTime nowUtc,
AlarmTransitionKind kind, string message, AlarmSeverity bucket, int? exact, uint? quality = null) =>
AlarmTransitionKind kind, string message, AlarmSeverity bucket, int? exact, uint? quality = null,
AlarmConditionClass? conditionClass = null) =>
new(handle,
SourceNodeId: tag.HostName,
ConditionId: tag.RawPath,
@@ -129,7 +134,8 @@ internal static class HeidenhainAlarmRules
SourceTimestampUtc: nowUtc,
Kind: kind,
OpcUaSeverity: exact,
QualityStatusCode: quality);
QualityStatusCode: quality,
ConditionClass: conditionClass);
}
/// <summary>
@@ -154,8 +160,14 @@ internal static class HeidenhainAlarmRules
/// that follows still sees the difference. Delivery runs under <see cref="_lock"/>; the only production handler
/// is <c>DriverInstanceActor</c>'s non-blocking <c>Tell</c>.</para>
/// </remarks>
internal sealed class HeidenhainAlarmProjection(object sender, Func<EventHandler<AlarmEventArgs>?> handlers, ILogger logger)
internal sealed class HeidenhainAlarmProjection(
object sender, Func<EventHandler<AlarmEventArgs>?> handlers, ILogger logger, string driverInstanceId = "")
{
/// <summary>The shortest gap between two "unclaimed alarms" log lines for one control (lmxopcua#839).</summary>
internal static readonly TimeSpan DefaultUnmatchedLogInterval = TimeSpan.FromMinutes(1);
private readonly Dictionary<string, UnmatchedState> _unmatched = new(StringComparer.Ordinal);
private readonly Lock _lock = new();
private readonly Dictionary<string, HeidenhainToldCondition> _told = new(StringComparer.Ordinal);
private readonly Dictionary<string, uint> _qualityTold = new(StringComparer.Ordinal);
@@ -226,6 +238,8 @@ internal sealed class HeidenhainAlarmProjection(object sender, Func<EventHandler
logger.LogInformation("Heidenhain {Host}: alarm list readable again", hostName);
}
if (status == HeidenhainStatus.Good && alarms is not null) TrackUnmatched(hostName, deviceTags, alarms, now);
var h = handlers();
if (h is null) return; // nobody listening: record nothing, the re-subscribe diffs again
@@ -255,6 +269,77 @@ internal sealed class HeidenhainAlarmProjection(object sender, Func<EventHandler
}
}
/// <summary>The gap between two "unclaimed alarms" log lines per control (test seam).</summary>
internal TimeSpan UnmatchedLogInterval { get; set; } = DefaultUnmatchedLogInterval;
/// <summary>
/// Per control: how many alarms on its last good walk no configured selector claims, and how many unclaimed
/// occurrences were seen since the driver started (lmxopcua#839). Published on <c>/hosts</c> via
/// <see cref="HeidenhainDriver.GetDiagnostics"/>.
/// </summary>
/// <returns>Host → (current, total).</returns>
public IReadOnlyDictionary<string, (int Current, long Total)> UnmatchedSnapshot()
{
lock (_lock)
return _unmatched.ToDictionary(kv => kv.Key, kv => (kv.Value.Keys.Count, kv.Value.Total), StringComparer.Ordinal);
}
/// <summary>
/// Controller alarms that no configured <c>ALARM:</c> selector on the control claims are shown by NO condition
/// (lmxopcua#839 — they used to vanish silently). A control with a <c>*</c> or <c>OTHER</c> selector claims every
/// alarm. Each alarm ENTERING the unclaimed set counts once (metric + total), so a standing alarm is not
/// re-counted every walk; the log is rate-limited per control to one line per <see cref="UnmatchedLogInterval"/>,
/// naming up to three alarms and how many more were suppressed since the previous line. Must run under
/// <see cref="_lock"/>.
/// </summary>
private void TrackUnmatched(string hostName, List<HeidenhainAlarmTag> deviceTags, IReadOnlyList<Lsv2Alarm> alarms, DateTime now)
{
if (!_unmatched.TryGetValue(hostName, out var state)) _unmatched[hostName] = state = new UnmatchedState();
var claimsAll = deviceTags.Any(t => t.Selector.Kind != HeidenhainAlarmSelectorKind.Filter);
var current = claimsAll
? new HashSet<HeidenhainAlarmKey>()
: alarms.Where(a => !deviceTags.Any(t => t.Selector.Matches(a.ErrorClass, a.Group, a.Number)))
.Select(HeidenhainAlarmKey.Of).ToHashSet();
var entered = current.Where(k => !state.Keys.Contains(k))
.OrderBy(k => k.Class).ThenBy(k => k.Group).ThenBy(k => k.Number).ThenBy(k => k.Message, StringComparer.Ordinal)
.ToList();
state.Keys = current;
if (entered.Count == 0) return;
state.Total += entered.Count;
OtOpcUaTelemetry.DriverAlarmsUnmatched.Add(entered.Count,
new KeyValuePair<string, object?>(OtOpcUaTelemetry.PollOverrunDriverTypeTag, DriverTypeNames.Heidenhain),
new KeyValuePair<string, object?>(OtOpcUaTelemetry.PollOverrunDriverInstanceTag, driverInstanceId));
state.PendingLog += entered.Count;
if (state.LastLogUtc is { } last && now - last < UnmatchedLogInterval)
{
state.PendingSample ??= entered;
return;
}
var sample = state.PendingSample is { } earlier ? earlier.Concat(entered).Distinct().ToList() : entered;
var suppressed = state.PendingLog - entered.Count;
logger.LogWarning(
"Heidenhain {Host}: {Count} controller alarm(s) match no ALARM: selector on this control and are shown by no condition " +
"(e.g. {Examples}){Suppressed}; add a selector or an ALARM:OTHER catch-all to surface them",
hostName, entered.Count, string.Join("; ", sample.Take(3).Select(Describe)),
suppressed > 0 ? $"; {suppressed} more since the previous report" : "");
state.LastLogUtc = now;
state.PendingLog = 0;
state.PendingSample = null;
static string Describe(HeidenhainAlarmKey k) => HeidenhainAlarmRules.MessageOf([k]);
}
private sealed class UnmatchedState
{
public HashSet<HeidenhainAlarmKey> Keys { get; set; } = [];
public long Total { get; set; }
public DateTime? LastLogUtc { get; set; }
public long PendingLog { get; set; }
public List<HeidenhainAlarmKey>? PendingSample { get; set; }
}
private AlarmEventArgs QualityOnly(HeidenhainAlarmTag tag, IAlarmSubscriptionHandle handle, uint quality, DateTime now)
{
_told.TryGetValue(tag.RawPath, out var told);
@@ -87,7 +87,7 @@ public sealed class HeidenhainDriver : IDriver, IReadable, ISubscribable, ITagDi
_credentials = credentials;
_clientFactory = clientFactory ?? ((h, p, t) => new Lsv2Client(h, p, t));
_time = time ?? TimeProvider.System;
_alarms = new HeidenhainAlarmProjection(this, () => OnAlarmEvent, _logger);
_alarms = new HeidenhainAlarmProjection(this, () => OnAlarmEvent, _logger, driverInstanceId);
}
/// <inheritdoc />
@@ -419,6 +419,13 @@ public sealed class HeidenhainDriver : IDriver, IReadable, ISubscribable, ITagDi
if (d.ControllerModel is { } m) bag[$"{d.HostName}.model"] = m;
}
// lmxopcua#839: controller alarms no ALARM: selector claims (shown by no condition) — current + since start.
foreach (var (host, (current, total)) in _alarms.UnmatchedSnapshot())
{
bag[$"{host}.alarms.unmatched"] = current.ToString(System.Globalization.CultureInfo.InvariantCulture);
bag[$"{host}.alarms.unmatchedTotal"] = total.ToString(System.Globalization.CultureInfo.InvariantCulture);
}
return DriverDiagnostics.Bound(bag);
}
@@ -428,7 +435,8 @@ public sealed class HeidenhainDriver : IDriver, IReadable, ISubscribable, ITagDi
/// <inheritdoc />
/// <remarks>
/// The namespace is a fixed catalog (no control-dependent path churn), so the browse picker can offer it
/// without contacting the control. PLC/DATA bindings are authored by hand: LSV2 has no proven universal
/// without contacting the control — plus the <c>AlarmConditions/</c> folder of <c>ALARM:</c> selectors
/// (lmxopcua#839). PLC/DATA bindings are authored by hand: LSV2 has no proven universal
/// symbol model and this driver performs no memory scanning.
/// </remarks>
public bool SupportsOnlineDiscovery => true;
@@ -449,6 +457,20 @@ public sealed class HeidenhainDriver : IDriver, IReadable, ISubscribable, ITagDi
e.Address, e.DataType, e.IsArray, null, SecurityClassification.ViewOnly, IsHistorized: false));
}
// lmxopcua#839: the ALARM: selectors, so a condition can be browse-committed rather than only typed. Each is an
// IsAlarm Boolean leaf; the commit's typed model seeds the paired `alarm` object the factory requires.
var alarmRoot = builder.Folder(HeidenhainAlarmClasses.BrowseFolder, HeidenhainAlarmClasses.BrowseFolder);
var alarmFolders = new Dictionary<string, IAddressSpaceBuilder>(StringComparer.Ordinal);
foreach (var (sub, name, address) in HeidenhainAlarmClasses.BrowseSelectors)
{
var parent = alarmRoot;
if (sub is not null && !alarmFolders.TryGetValue(sub, out parent))
alarmFolders[sub] = parent = alarmRoot.Folder(sub, sub);
parent.Variable(name, name, new DriverAttributeInfo(
address, HeidenhainTagDefinitionFactory.AlarmConditionDataType, false, null, SecurityClassification.ViewOnly,
IsHistorized: false, IsAlarm: true));
}
return Task.CompletedTask;
}
@@ -1209,6 +1209,10 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3
}
condition.SetSeverity(SystemContext, ToPart9Severity(state.Severity));
condition.Message!.Value = new LocalizedText(state.Message);
// #839: a classifying native source's Part 9 ConditionClass. Null leaves the node's class as it is
// (BaseConditionClass from materialise, or what an earlier event set). Not in the delta-gate: a class
// rides along with the transition that set it and never fires an event on its own.
if (state.ConditionClass is { } conditionClass) ApplyConditionClass(condition, conditionClass);
// Project the source-data quality. A Good→Bad bucket change is a genuine condition
// change (it's in the delta-gate above), so it fires a Part 9 event carrying the new Quality;
@@ -1244,6 +1248,27 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3
}
}
/// <summary>
/// The Part 9 class type id + browse name of an <see cref="AlarmConditionClass"/> (lmxopcua#839).
/// </summary>
/// <param name="conditionClass">The driver-assigned class.</param>
/// <returns>The <c>ConditionClassId</c> / <c>ConditionClassName</c> pair to write.</returns>
internal static (NodeId Id, string Name) ConditionClassOf(AlarmConditionClass conditionClass) => conditionClass switch
{
AlarmConditionClass.Process => (ObjectTypeIds.ProcessConditionClassType, "ProcessConditionClass"),
AlarmConditionClass.Maintenance => (ObjectTypeIds.MaintenanceConditionClassType, "MaintenanceConditionClass"),
AlarmConditionClass.System => (ObjectTypeIds.SystemConditionClassType, "SystemConditionClass"),
AlarmConditionClass.Safety => (ObjectTypeIds.SafetyConditionClassType, "SafetyConditionClass"),
_ => (ObjectTypeIds.BaseConditionClassType, "BaseConditionClass"),
};
private static void ApplyConditionClass(AlarmConditionState condition, AlarmConditionClass conditionClass)
{
var (id, name) = ConditionClassOf(conditionClass);
if (condition.ConditionClassId is not null) condition.ConditionClassId.Value = id;
if (condition.ConditionClassName is not null) condition.ConditionClassName.Value = new LocalizedText(name);
}
/// <summary>
/// The <c>shelvingTime</c> (ms) to hand <c>SetShelvingState</c> for a timed shelve expiring at
/// <paramref name="unshelveAtUtc"/>. <c>0</c> when the expiry is unknown (the SDK then uses
@@ -1623,9 +1648,9 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3
// BaseConditionClassType is Part 9's "no class modelled" value and is the honest report: we hold no
// classification at this seam. Deliberately NOT ProcessConditionClassType (the SDK sample's pick) — it
// would assert a classification we cannot back, and would be actively wrong for a Galaxy alarm whose
// upstream category is Safety/Diagnostics. Real per-alarm classification needs the driver's
// AlarmCategory, which today exists only on the runtime AlarmEventArgs transition and not on the
// authored composition this deploy-time seam sees — a separate feature, not a default picked here.
// upstream category is Safety/Diagnostics. Per-alarm classification arrives at RUNTIME instead: a
// classifying native driver states AlarmEventArgs.ConditionClass on its transitions (#839, Heidenhain),
// which WriteAlarmCondition applies over this default — the deploy-time seam still holds none.
if (alarm.ConditionClassId is not null) alarm.ConditionClassId.Value = ObjectTypeIds.BaseConditionClassType;
if (alarm.ConditionClassName is not null) alarm.ConditionClassName.Value = new LocalizedText("BaseConditionClass");
@@ -1783,7 +1808,8 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3
/// <param name="ClientUserId">Who left that comment, if recorded.</param>
private sealed record NativeConditionCarryOver(
AlarmConditionDelta State, DateTime Time, DateTime? ActiveTransitionTime, DateTime? QualityTimestamp,
LocalizedText? Comment = null, string? ClientUserId = null);
LocalizedText? Comment = null, string? ClientUserId = null, NodeId? ConditionClassId = null,
LocalizedText? ConditionClassName = null);
/// <summary>
/// Read what a native condition node holds right now, so the rebuild can put it back.
@@ -1810,7 +1836,9 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3
condition.ActiveState?.TransitionTime?.Value.ToDateTime(),
condition.Quality?.SourceTimestamp?.Value.ToDateTime(),
condition.Comment?.Value,
condition.ClientUserId?.Value);
condition.ClientUserId?.Value,
condition.ConditionClassId?.Value,
condition.ConditionClassName?.Value);
/// <summary>
/// Put a carried state back onto the freshly materialised native condition. MUST be called
@@ -1839,6 +1867,12 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3
private void RestoreCarryOver(AlarmConditionState alarm, RealmKey conditionKey, NativeConditionCarryOver carried)
{
var state = carried.State;
// #839: a driver-assigned ConditionClass is a property of the condition, not of its state — restored whether
// or not the condition is off-normal (the materialise default is BaseConditionClass).
if (alarm.ConditionClassId is { } classIdNode && carried.ConditionClassId is { } classId && !classId.IsNull)
classIdNode.Value = classId;
if (alarm.ConditionClassName is not null && carried.ConditionClassName is { } className)
alarm.ConditionClassName.Value = className;
if (alarm.Quality is not null)
{
alarm.Quality.Value = state.Quality;
@@ -12,7 +12,7 @@ namespace ZB.MOM.WW.OtOpcUa.Runtime.Drivers;
/// </summary>
public sealed class NativeAlarmProjector
{
private readonly Dictionary<string, (bool Active, bool Acked, string? Message, ushort Severity, uint StatusCode)> _prior =
private readonly Dictionary<string, (bool Active, bool Acked, string? Message, ushort Severity, uint StatusCode, AlarmConditionClass? Class)> _prior =
new(StringComparer.Ordinal);
/// <summary>
@@ -82,7 +82,7 @@ public sealed class NativeAlarmProjector
// driver's word, so a late ack failure must not rewrite it.
_pendingLocalAck.Remove(nodeId);
var prev = _prior.TryGetValue(nodeId, out var p)
? p : (Active: false, Acked: true, Message: (string?)null, Severity: (ushort)0, StatusCode: OpcUaStatus.Good);
? p : (Active: false, Acked: true, Message: (string?)null, Severity: (ushort)0, StatusCode: OpcUaStatus.Good, Class: (AlarmConditionClass?)null);
// A source with a finer scale than the four buckets supplies the exact Part 9 severity.
var sev = e.OpcUaSeverity is { } exact ? (ushort)Math.Clamp(exact, 1, 1000) : MapSeverity(e.Severity);
// Only a statement saying the SAME thing the condition already shows is a re-statement.
@@ -154,14 +154,18 @@ public sealed class NativeAlarmProjector
}
var statusCode = e.QualityStatusCode ?? OpcUaStatus.Good;
_prior[nodeId] = (active, acked, e.Message, sev, statusCode);
// A source that classifies its conditions (#839) states the class on its transitions; one that does not (or a
// quality-only annotation) keeps whatever the condition last carried.
var conditionClass = e.ConditionClass ?? prev.Class;
_prior[nodeId] = (active, acked, e.Message, sev, statusCode, conditionClass);
return new AlarmConditionSnapshot(
Active: active, Acknowledged: acked, Confirmed: true, Enabled: true,
Shelving: AlarmShelvingKind.Unshelved, Severity: sev, Message: e.Message,
// A per-condition source quality (MTConnect Unavailable) when the driver reports one. Absent
// (every earlier source) ⇒ Good, as before — driver-wide comms loss stays the host's
// out-of-band WriteAlarmQuality annotation, not something the projector infers.
StatusCode: statusCode);
StatusCode: statusCode,
ConditionClass: conditionClass);
}
/// <summary>
@@ -195,7 +199,7 @@ public sealed class NativeAlarmProjector
snapshot = new AlarmConditionSnapshot(
Active: p.Active, Acknowledged: false, Confirmed: true, Enabled: true,
Shelving: AlarmShelvingKind.Unshelved, Severity: p.Severity, Message: p.Message ?? string.Empty,
StatusCode: p.StatusCode);
StatusCode: p.StatusCode, ConditionClass: p.Class);
return true;
}
@@ -150,6 +150,131 @@ public sealed class HeidenhainAlarmTests
e.OpcUaSeverity.ShouldBeNull();
}
// ---- Part 9 condition class (lmxopcua#839) ----
[Theory]
[InlineData(5, 3, AlarmConditionClass.Safety)] // EMERGENCY STOP, whatever the group
[InlineData(5, 0, AlarmConditionClass.Safety)]
[InlineData(8, 1, AlarmConditionClass.Process)] // OPERATING
[InlineData(1, 2, AlarmConditionClass.Process)] // PROGRAMMING
[InlineData(7, 4, AlarmConditionClass.System)] // GENERAL — the captured iTNC 530 "Run test of cutout channels"
[InlineData(8, 5, AlarmConditionClass.System)] // REMOTE
[InlineData(8, 3, AlarmConditionClass.Base)] // PLC: machine-builder text, no evidence either way
[InlineData(8, 6, AlarmConditionClass.Base)] // PYTHON
[InlineData(8, 0, AlarmConditionClass.Base)]
[InlineData(99, 99, AlarmConditionClass.Base)] // unknown codes never guess
public void Condition_class_maps_only_where_the_codes_say_where_the_alarm_comes_from(int cls, int group, AlarmConditionClass expected) =>
HeidenhainAlarmClasses.ConditionClassOf(cls, group).ShouldBe(expected);
[Fact]
public void Raise_and_retrigger_carry_the_displayed_alarms_class_and_clear_carries_none()
{
var tag = Tag("*");
var all = new[] { tag.Selector };
var now = DateTime.UtcNow;
var info = new Lsv2Alarm(7, 4, -1, "Run test of cutout channels");
var estop = new Lsv2Alarm(5, 3, 10, "Emergency stop");
var (e1, t1) = HeidenhainAlarmRules.Transition(null, HeidenhainAlarmRules.Evaluate(tag.Selector, [info], all), tag, H, now);
e1!.ConditionClass.ShouldBe(AlarmConditionClass.System);
var (e2, t2) = HeidenhainAlarmRules.Transition(t1, HeidenhainAlarmRules.Evaluate(tag.Selector, [info, estop], all), tag, H, now);
e2!.Kind.ShouldBe(AlarmTransitionKind.Retrigger);
e2.ConditionClass.ShouldBe(AlarmConditionClass.Safety); // the class-5 alarm is now the displayed one
var (e3, _) = HeidenhainAlarmRules.Transition(t2, [], tag, H, now);
e3!.Kind.ShouldBe(AlarmTransitionKind.Clear);
e3.ConditionClass.ShouldBeNull(); // the node keeps the class of the alarm it last showed
e1.Message.ShouldBe("-1 Run test of cutout channels (class 7, group 4)"); // the message is unchanged by #839
}
// ---- unclaimed alarms are counted and logged (lmxopcua#839) ----
private sealed class ListLogger : Microsoft.Extensions.Logging.ILogger
{
public ConcurrentQueue<(Microsoft.Extensions.Logging.LogLevel Level, string Text)> Entries { get; } = new();
public IDisposable? BeginScope<TState>(TState state) where TState : notnull => null;
public bool IsEnabled(Microsoft.Extensions.Logging.LogLevel logLevel) => true;
public void Log<TState>(Microsoft.Extensions.Logging.LogLevel logLevel, Microsoft.Extensions.Logging.EventId eventId,
TState state, Exception? exception, Func<TState, Exception?, string> formatter) =>
Entries.Enqueue((logLevel, formatter(state, exception)));
}
private static HeidenhainAlarmProjection Projection(ListLogger log, params HeidenhainAlarmTag[] tags)
{
var p = new HeidenhainAlarmProjection(new object(), () => null, log, "hh-1")
{
Tags = tags.ToDictionary(t => t.RawPath, StringComparer.Ordinal),
};
p.Subscribe(tags.Select(t => t.RawPath).ToList());
return p;
}
private static HeidenhainAlarmTag TagOn(string host, string selector, string name) =>
new($"Plant/H/dev1/{name}", host, Parse(selector), null);
[Fact]
public void Alarms_no_selector_claims_are_counted_once_per_occurrence_and_logged_rate_limited()
{
var log = new ListLogger();
var p = Projection(log, TagOn("h:1", "CLASS=7", "Info"));
var claimed = new Lsv2Alarm(7, 4, -1, "Run test of cutout channels");
var lost = new Lsv2Alarm(3, 1, 100, "Coolant low");
var lost2 = new Lsv2Alarm(8, 2, 200, "Program error");
static int Warnings(ListLogger l) => l.Entries.Count(e => e.Level == Microsoft.Extensions.Logging.LogLevel.Warning);
p.OnWalk("h:1", HeidenhainStatus.Good, [claimed, lost]);
p.UnmatchedSnapshot()["h:1"].ShouldBe((1, 1L));
Warnings(log).ShouldBe(1);
log.Entries.Last().Text.ShouldContain("100 Coolant low (class 3, group 1)");
// A standing alarm is not re-counted, and the log is rate-limited.
p.OnWalk("h:1", HeidenhainStatus.Good, [claimed, lost]);
p.OnWalk("h:1", HeidenhainStatus.Good, [lost, lost2]);
p.UnmatchedSnapshot()["h:1"].ShouldBe((2, 2L));
Warnings(log).ShouldBe(1);
// It leaves and comes back — a new occurrence. The next permitted line reports what was suppressed.
p.OnWalk("h:1", HeidenhainStatus.Good, [lost2]);
p.UnmatchedLogInterval = TimeSpan.Zero;
p.OnWalk("h:1", HeidenhainStatus.Good, [lost, lost2]);
p.UnmatchedSnapshot()["h:1"].ShouldBe((2, 3L));
Warnings(log).ShouldBe(2);
log.Entries.Last().Text.ShouldContain("1 more since the previous report");
// A failed walk is not "no alarms": it changes nothing.
p.OnWalk("h:1", HeidenhainStatus.BadNoCommunication, null);
p.UnmatchedSnapshot()["h:1"].ShouldBe((2, 3L));
}
[Theory]
[InlineData("*")]
[InlineData("OTHER")]
public void A_catch_all_selector_claims_every_alarm(string catchAll)
{
var log = new ListLogger();
var p = Projection(log, TagOn("h:1", "CLASS=7", "Info"), TagOn("h:1", catchAll, "All"));
p.OnWalk("h:1", HeidenhainStatus.Good, [new Lsv2Alarm(3, 1, 100, "Coolant low")]);
p.UnmatchedSnapshot()["h:1"].ShouldBe((0, 0L));
log.Entries.ShouldNotContain(e => e.Level == Microsoft.Extensions.Logging.LogLevel.Warning);
}
[Fact]
public async Task Unclaimed_alarms_reach_the_hosts_diagnostics()
{
var control = new SimulatedControl();
var list = new AlarmList();
list.Install(control);
list.Set(Golden(), Record(3, 1, 100, "Coolant low"));
await using var sim = Lsv2Simulator.WithControl(control);
var cls7 = AlarmTag("CLASS=7", "Class7");
await using var d = Create(Options(sim.Port, cls7));
await d.InitializeAsync("{}", Ct);
await d.SubscribeAlarmsAsync([cls7.RawPath], Ct);
var host = $"127.0.0.1:{sim.Port}";
await WaitUntil(() => d.GetDiagnostics().TryGetValue($"{host}.alarms.unmatched", out var v) && v == "1");
d.GetDiagnostics()[$"{host}.alarms.unmatchedTotal"].ShouldBe("1");
}
// ---- end to end against the simulator ----
/// <summary>A control whose active-alarm list can be changed between walks (27 = first, 28 = next, 57 = end).</summary>
@@ -80,7 +80,21 @@ public sealed class HeidenhainDriverTests
await d.DiscoverAsync(builder, Ct);
await Task.Delay(200, Ct);
sim.Connections.ShouldBe(0);
builder.Variables.Count.ShouldBe(HeidenhainCatalog.Entries.Count);
// The fixed catalog plus the ALARM: selectors (lmxopcua#839) — every one an IsAlarm Boolean leaf whose address
// the driver's own parser takes as a condition selector.
builder.Variables.Count.ShouldBe(HeidenhainCatalog.Entries.Count + HeidenhainAlarmClasses.BrowseSelectors.Count);
var alarmLeaves = builder.Variables.Where(v => v.IsAlarm).ToList();
alarmLeaves.Select(v => v.FullName).ShouldBe(HeidenhainAlarmClasses.BrowseSelectors.Select(x => x.Address));
alarmLeaves.ShouldAllBe(v => v.DriverDataType == DriverDataType.Boolean && !v.IsArray);
foreach (var leaf in alarmLeaves)
{
HeidenhainAddress.TryParse(leaf.FullName, out var a, out var error).ShouldBeTrue(error);
a!.Kind.ShouldBe(HeidenhainAddressKind.Alarm);
}
alarmLeaves.Select(v => v.FullName).ShouldContain("ALARM:*");
alarmLeaves.Select(v => v.FullName).ShouldContain("ALARM:OTHER");
alarmLeaves.Select(v => v.FullName).ShouldContain("ALARM:CLASS=5");
builder.Variables.ShouldContain(v => v.FullName == "Axes/Positions" && v.IsArray && v.DriverDataType == DriverDataType.Float64);
builder.Variables.ShouldAllBe(v => v.SecurityClass == SecurityClassification.ViewOnly);
d.GetHealth().State.ShouldBe(DriverState.Healthy);
@@ -122,4 +122,27 @@ public sealed class HeidenhainAuthoringTests
TagConfigValidator.Validate(DriverTypeNames.Heidenhain, json).ShouldBeNull();
HeidenhainTagConfigModel.FromJson(json).Address.ShouldBe(address);
}
/// <summary>
/// lmxopcua#839: every <c>ALARM:</c> selector the browse picker offers commits as a complete condition tag — the
/// paired <c>alarm</c> object seeded, Boolean, accepted by the driver's own factory and the editor's validator —
/// so a browse-commit never lands a tag the deploy gate would refuse.
/// </summary>
[Fact]
public void Browse_committed_alarm_selectors_are_complete_conditions_the_driver_accepts()
{
HeidenhainAlarmClasses.BrowseSelectors.Count.ShouldBeGreaterThan(2);
foreach (var (_, name, address) in HeidenhainAlarmClasses.BrowseSelectors)
{
var row = RawBrowseCommitMapper.MapLeaf(
DriverTypeNames.Heidenhain, address, name, nameof(DriverDataType.Boolean), "String",
groupPrefix: null, folderPath: null, createGroups: false);
row.Tag.DataType.ShouldBe("Boolean");
var json = row.Tag.TagConfig!;
JsonNode.Parse(json)!["alarm"].ShouldNotBeNull(address);
HeidenhainTagDefinitionFactory.TryFromTagConfig("p", "d", json, out var def, out var error).ShouldBeTrue(error);
def!.IsAlarmCondition.ShouldBeTrue();
TagConfigValidator.Validate(DriverTypeNames.Heidenhain, json).ShouldBeNull();
}
}
}
@@ -123,6 +123,37 @@ public sealed class NodeManagerNativeAlarmRebuildCarryOverTests : IDisposable
await host.DisposeAsync();
}
/// <summary>
/// lmxopcua#839 — a classifying native source's Part 9 ConditionClass lands on the node, a later snapshot
/// without one (a quality-only annotation, a non-classifying path) keeps it, and a rebuild carries it.
/// </summary>
[Trait("Category", "Unit")]
[Fact]
public async Task A_driver_assigned_condition_class_is_applied_kept_and_carried_across_a_rebuild()
{
var (host, nm) = await BootAsync();
Materialise(nm, native: true);
Condition(nm).ConditionClassId!.Value.ShouldBe(ObjectTypeIds.BaseConditionClassType);
nm.WriteAlarmCondition(Alarm, Fault(acked: false) with { ConditionClass = ZB.MOM.WW.OtOpcUa.Core.Abstractions.AlarmConditionClass.Safety },
DateTime.UtcNow, AddressSpaceRealm.Raw);
Condition(nm).ConditionClassId!.Value.ShouldBe(ObjectTypeIds.SafetyConditionClassType);
Condition(nm).ConditionClassName!.Value.Text.ShouldBe("SafetyConditionClass");
nm.WriteAlarmCondition(Alarm, Fault(acked: false) with { StatusCode = OpcUaStatus.Bad }, DateTime.UtcNow, AddressSpaceRealm.Raw);
Condition(nm).ConditionClassId!.Value.ShouldBe(ObjectTypeIds.SafetyConditionClassType);
// Even a NORMAL condition keeps its class across a rebuild — the class is not state.
nm.WriteAlarmCondition(Alarm, Fault(acked: true) with { Active = false }, DateTime.UtcNow, AddressSpaceRealm.Raw);
nm.RebuildAddressSpace();
Materialise(nm, native: true);
nm.CompleteAddressSpaceApply();
Condition(nm).ConditionClassId!.Value.ShouldBe(ObjectTypeIds.SafetyConditionClassType);
Condition(nm).ConditionClassName!.Value.Text.ShouldBe("SafetyConditionClass");
await host.DisposeAsync();
}
/// <summary>Falsification control: a condition in the no-event position comes back exactly as a fresh
/// materialise builds it, and reports nothing.</summary>
[Trait("Category", "Unit")]
@@ -24,6 +24,26 @@ public class NativeAlarmProjectorTests
snap.Message.ShouldBe("boom");
}
/// <summary>lmxopcua#839 — a classifying source's ConditionClass rides the snapshot; an event without one (a
/// quality-only annotation, a Clear) keeps the class the condition last carried, and the default is null
/// (= leave the node's class alone).</summary>
[Fact]
public void Condition_class_is_carried_and_kept_until_restated()
{
var sut = new NativeAlarmProjector();
sut.Project("n1", Evt(AlarmTransitionKind.Raise)).ConditionClass.ShouldBeNull();
sut.Project("n1", Evt(AlarmTransitionKind.Retrigger) with { ConditionClass = AlarmConditionClass.System })
.ConditionClass.ShouldBe(AlarmConditionClass.System);
sut.Project("n1", Evt(AlarmTransitionKind.Unspecified) with { QualityStatusCode = 0x80310000u })
.ConditionClass.ShouldBe(AlarmConditionClass.System);
sut.Project("n1", Evt(AlarmTransitionKind.Clear)).ConditionClass.ShouldBe(AlarmConditionClass.System);
sut.MarkAcknowledged("n1");
sut.Project("n1", Evt(AlarmTransitionKind.Raise) with { ConditionClass = AlarmConditionClass.Safety });
sut.MarkAcknowledged("n1");
sut.TryRevertAcknowledge("n1", out var reverted).ShouldBeTrue();
reverted!.ConditionClass.ShouldBe(AlarmConditionClass.Safety);
}
/// <summary>Gitea #641 — <c>RetainOnly</c> keeps a still-deployed condition's prior state and forgets a removed
/// one's (which then starts from the default inactive + acked).</summary>
[Fact]