namespace ZB.MOM.WW.OtOpcUa.Driver.MTConnect;
/// The four MTConnect CONDITION levels the alarm path distinguishes.
internal enum MTConnectConditionLevel
{
/// <Normal/> — nothing is active.
Normal = 0,
/// <Warning/> — active, Part 9 severity 500.
Warning = 1,
/// <Fault/> — active, Part 9 severity 800.
Fault = 2,
/// <Unavailable/> — the Agent has no state for the item (inactive, Bad quality).
Unavailable = 3,
}
///
/// The derived state of ONE CONDITION DataItem as the alarm path sees it: the most severe active
/// condition when any is active, else Normal or Unavailable.
///
/// The derived level.
///
/// The detail of the observation the level comes from — the winning active condition, or the latest
/// Normal/Unavailable observation. Never null.
///
/// That observation's Agent timestamp.
/// How many distinct conditions (by nativeCode) are active at once.
internal sealed record MTConnectConditionState(
MTConnectConditionLevel Level,
MTConnectConditionDetail Detail,
DateTime TimestampUtc,
int ActiveCount)
{
/// Whether the derived condition is active (Warning or Fault).
public bool IsActive => Level is MTConnectConditionLevel.Warning or MTConnectConditionLevel.Fault;
///
/// Whether two states are the SAME alarm statement — the dedup key the alarm path diffs on. Two active
/// states match when level, nativeCode, nativeSeverity and qualifier agree (a new
/// code or an escalation is a new statement); two inactive states match on the level alone, so a
/// re-reported Normal never re-clears. NOT part of it: the timestamp and the active count (a replayed
/// /current after a reconnect carries the same condition under a new sequence, and re-raising it
/// would un-acknowledge an operator's ack) and the message TEXT (an adapter that embeds a live value in
/// the text, e.g. "Spindle temp 82C", would otherwise re-raise and un-ack on every tick — the message
/// shown stays the statement's first text).
///
/// The state to compare against.
/// True when the alarm path must emit nothing to move from one to the other.
public bool SameAlarmAs(MTConnectConditionState other)
{
if (Level != other.Level) return false;
if (!IsActive) return true;
return string.Equals(Detail.NativeCode, other.Detail.NativeCode, StringComparison.Ordinal)
&& string.Equals(Detail.NativeSeverity, other.Detail.NativeSeverity, StringComparison.Ordinal)
&& string.Equals(Detail.Qualifier, other.Detail.Qualifier, StringComparison.Ordinal);
}
}
///
/// Folds MTConnect CONDITION observations into per-DataItem alarm state with the protocol's own
/// multi-condition semantics — the alarm path's analogue of .
///
///
///
/// Why the index is not enough. The index reconciles several states reported for one DataItem
/// only within one document and otherwise treats each document as the new statement of the
/// value. That is right for a /current snapshot but wrong for a /sample delta: an Agent
/// streams each nativeCode's activation and clearing separately, so a chunk carrying
/// <Normal nativeCode="A"/> clears code A only — code B, raised in an earlier chunk,
/// is still active. The alarm path must not report "return to normal" there.
///
///
/// Rules, per DataItem, applied in document order. Warning/Fault activates (or
/// replaces) the entry keyed by its nativeCode (blank = one unnamed entry). Normal with a
/// nativeCode clears that code; Normal without one clears every code. Unavailable
/// clears every code and marks the item unavailable until any other level arrives (the alarm path does
/// NOT treat that as a clear — see ). A baseline
/// (/current, which lists every currently-active condition) first resets each DataItem it
/// mentions, so an entry cleared while the driver was not listening cannot survive a re-baseline. An
/// unrecognised (vendor) state word is treated as an active Warning — surfacing an unknown
/// condition beats hiding it.
///
///
/// Thread safety. One internal lock; every member is atomic. The pump is the only writer.
///
///
internal sealed class MTConnectConditionTracker
{
/// The parser's normalised spelling of <Unavailable/>.
private const string UnavailableSentinel = "UNAVAILABLE";
private readonly Lock _lock = new();
private readonly Dictionary _items = new(StringComparer.Ordinal);
///
/// Folds every CONDITION observation of into the tracked state.
///
/// A /current snapshot or one /sample chunk.
///
/// True for a /current answer — each DataItem it mentions is reset before its observations are
/// applied; false for a /sample delta.
///
/// The DataItem ids whose condition state the document touched (empty when none).
public IReadOnlySet Apply(MTConnectStreamsResult document, bool baseline)
{
ArgumentNullException.ThrowIfNull(document);
var touched = new HashSet(StringComparer.Ordinal);
if (document.Observations is not { Count: > 0 }) return touched;
lock (_lock)
{
foreach (var observation in document.Observations)
{
if (observation?.Condition is null || string.IsNullOrWhiteSpace(observation.DataItemId)) continue;
if (!_items.TryGetValue(observation.DataItemId, out var item))
{
_items[observation.DataItemId] = item = new ItemState();
}
if (touched.Add(observation.DataItemId) && baseline)
{
item.Active.Clear();
item.Unavailable = false;
}
ApplyOne(item, observation);
}
}
return touched;
}
/// The derived state of one DataItem, or null when it has never been observed as a condition.
/// The DataItem id.
/// The derived state, or null when the item was never observed.
public MTConnectConditionState? Get(string dataItemId)
{
lock (_lock)
{
if (string.IsNullOrEmpty(dataItemId) || !_items.TryGetValue(dataItemId, out var item)) return null;
if (item.Active.Count > 0)
{
// Most severe wins; among equals, a DETERMINISTIC tie-break (ordinal nativeCode, then type) —
// never document order, which an Agent may present differently on a re-baseline and which would
// then re-raise (and un-ack) an unchanged condition on every reconnect.
var winner = item.Active.Values
.OrderByDescending(e => e.Level)
.ThenBy(e => e.Detail.NativeCode ?? string.Empty, StringComparer.Ordinal)
.ThenBy(e => e.Detail.ConditionType ?? string.Empty, StringComparer.Ordinal)
.First();
return new MTConnectConditionState(winner.Level, winner.Detail, winner.TimestampUtc, item.Active.Count);
}
var last = item.LastInactive;
return last is null
? null
: new MTConnectConditionState(
item.Unavailable ? MTConnectConditionLevel.Unavailable : MTConnectConditionLevel.Normal,
last.Detail,
last.TimestampUtc,
0);
}
}
/// Drops every tracked state — the Agent-restart re-baseline, mirroring .
public void Clear()
{
lock (_lock) _items.Clear();
}
/// Maps a parsed condition state word onto a level (unknown vendor words ⇒ Warning).
/// The observation's state word.
/// The mapped condition level.
internal static MTConnectConditionLevel LevelOf(string? value) => value switch
{
UnavailableSentinel => MTConnectConditionLevel.Unavailable,
_ when string.Equals(value, "Normal", StringComparison.OrdinalIgnoreCase) => MTConnectConditionLevel.Normal,
_ when string.Equals(value, "Fault", StringComparison.OrdinalIgnoreCase) => MTConnectConditionLevel.Fault,
_ when string.Equals(value, "Unavailable", StringComparison.OrdinalIgnoreCase) => MTConnectConditionLevel.Unavailable,
_ => MTConnectConditionLevel.Warning,
};
private void ApplyOne(ItemState item, MTConnectObservation observation)
{
var detail = observation.Condition!;
var entry = new Entry(LevelOf(observation.Value), detail, observation.TimestampUtc);
switch (entry.Level)
{
case MTConnectConditionLevel.Normal:
if (detail.NativeCode is null) item.Active.Clear();
else item.Active.Remove(detail.NativeCode);
item.Unavailable = false;
item.LastInactive = entry;
break;
case MTConnectConditionLevel.Unavailable:
item.Active.Clear();
item.Unavailable = true;
item.LastInactive = entry;
break;
default:
item.Active[detail.NativeCode ?? string.Empty] = entry;
item.Unavailable = false;
break;
}
}
private sealed record Entry(MTConnectConditionLevel Level, MTConnectConditionDetail Detail, DateTime TimestampUtc);
private sealed class ItemState
{
/// Active conditions keyed by nativeCode ("" for an unnamed one).
public Dictionary Active { get; } = new(StringComparer.Ordinal);
/// Whether the latest inactive statement was Unavailable.
public bool Unavailable { get; set; }
/// The latest Normal/Unavailable observation (its text and type feed the clear message).
public Entry? LastInactive { get; set; }
}
}