using Google.Protobuf.WellKnownTypes; using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; using W = ZB.MOM.WW.OtOpcUa.Commons.Protos.DataConnection.V1; namespace ZB.MOM.WW.OtOpcUa.Commons.DataConnections; /// /// A2 condition codecs (plan §4.2, §5.5): CapabilitiesResponse.conditions, SubscriptionItem.condition_scope /// and the condition_states frame arm (9). Only ever exercised on a call that negotiated conditions: the /// host strips every one of these shapes from a header-less call, so a v1 client never sees them. /// public static class DataConditionProtoMapper { /// The most condition records one decoded frame may carry. public const int MaxRecordsPerFrame = 5000; /// Encodes the capabilities field. public static W.ConditionCapabilities EncodeCapabilities(DataConditionCapabilities x) => new() { RootScopeItems = x.RootScopeItems, Methods = x.Methods, MaxConditions = x.MaxConditions }; /// Decodes the capabilities field (null when absent). public static DataConditionCapabilities? DecodeCapabilities(W.ConditionCapabilities? x) { if (x is null) return null; var decoded = new DataConditionCapabilities(x.RootScopeItems, x.Methods, x.MaxConditions); decoded.Validate(); return decoded; } /// Encodes one condition record. public static W.ConditionState EncodeState(DataConditionState x) { var v = new W.ConditionState { ConditionKey = x.ConditionKey, Version = x.Version, Removed = x.Removed, StateKnown = x.StateKnown, Active = x.Active, Acknowledged = x.Acknowledged, Confirmed = x.Confirmed, Enabled = x.Enabled, Shelving = x.Shelving, Severity = x.Severity, Message = x.Message ?? "", Quality = x.Quality, ConditionClass = x.ConditionClass, Retain = x.Retain, }; if (x.Info is { } info) { v.Info = new W.ConditionInfo { ConditionType = info.ConditionType, ConditionName = info.ConditionName, SourceKind = (int)info.SourceKind, SupportedMethods = info.SupportedMethods, }; v.Info.Placements.AddRange(info.Placements.Select(DataProtoMapper.EncodeView)); } if (x.UnshelveAtUtc is { } unshelve) v.UnshelveAt = Timestamp.FromDateTimeOffset(unshelve); if (x.TimeUtc is { } time) v.Time = Timestamp.FromDateTimeOffset(time); if (x.Activation is { } a) v.Activation = new W.ActivationMarker { Incarnation = a.Incarnation, Sequence = a.Sequence }; if (x.Comment is not null) v.Comment = x.Comment; if (x.ClientUserId is not null) v.ClientUserId = x.ClientUserId; return v; } /// Decodes one condition record (a malformed key or negative version is an ). public static DataConditionState DecodeState(W.ConditionState x) { if (!ImportedConditionIds.IsWellFormedConditionKey(x.ConditionKey) || x.Version < 0) throw new ArgumentException("Invalid condition record."); DataConditionInfo? info = null; if (x.Info is { } i) { var kind = (DataConditionSourceKind)i.SourceKind; if (!System.Enum.IsDefined(kind)) kind = DataConditionSourceKind.Unspecified; info = new DataConditionInfo(i.ConditionType, i.ConditionName, kind, i.Placements.Select(DataProtoMapper.DecodeView).ToArray(), i.SupportedMethods); } return new DataConditionState(x.ConditionKey, x.Version, x.Removed, x.StateKnown, info, x.Active, x.Acknowledged, x.Confirmed, x.Enabled, x.Shelving, x.Severity, x.Message, x.Quality, x.UnshelveAt?.ToDateTimeOffset(), x.ConditionClass, x.Time?.ToDateTimeOffset(), x.Retain, x.Activation is { } m ? new DataActivationMarker(m.Incarnation, m.Sequence) : null, x.HasComment ? x.Comment : null, x.HasClientUserId ? x.ClientUserId : null); } /// Encodes a condition frame (arm 9). The host calls this only on a call that negotiated conditions. public static W.SubscriptionFrame EncodeFrame(DataSubscriptionConditions frame) { ArgumentNullException.ThrowIfNull(frame); var states = new W.ConditionStates { Handle = DataProtoMapper.EncodeHandle(frame.Handle), IsSnapshot = frame.IsSnapshot, SnapshotComplete = frame.SnapshotComplete, }; if (frame.Total is { } total) states.Total = total; states.Items.AddRange(frame.Items.Select(EncodeState)); return new W.SubscriptionFrame { SubscriptionId = frame.SubscriptionId, StreamEpoch = frame.StreamEpoch, Sequence = frame.Sequence, ConditionStates = states, }; } /// Decodes a condition frame; the handle must belong to the frame's stream. public static DataSubscriptionConditions DecodeFrame(W.SubscriptionFrame frame) { ArgumentNullException.ThrowIfNull(frame); var c = frame.ConditionStates ?? throw new ArgumentException("Expected condition states."); ArgumentException.ThrowIfNullOrWhiteSpace(frame.SubscriptionId); if (frame.StreamEpoch <= 0 || frame.Sequence <= 0 || c.Handle is null || c.Items.Count > MaxRecordsPerFrame || c.HasTotal && c.Total < 0) throw new ArgumentException("Invalid condition frame."); var handle = DataProtoMapper.DecodeHandle(c.Handle); if (handle.SubscriptionId != frame.SubscriptionId || handle.StreamEpoch != frame.StreamEpoch) throw new ArgumentException("Condition handle belongs to another stream."); return new DataSubscriptionConditions(frame.SubscriptionId, frame.StreamEpoch, frame.Sequence, handle, c.IsSnapshot, c.HasTotal ? c.Total : null, c.Items.Select(DecodeState).ToArray(), c.SnapshotComplete); } // ---- A2b CallConditionMethod (§4.2) ---- /// Encodes a condition method request. public static W.ConditionMethodRequest EncodeMethodRequest(DataConditionMethodRequest x) { ArgumentNullException.ThrowIfNull(x); x.Validate(); var v = new W.ConditionMethodRequest { OperationId = x.OperationId, Placement = DataProtoMapper.EncodeView(x.Placement), Method = (int)x.Method, ExpectedActivation = new W.ActivationMarker { Incarnation = x.ExpectedActivation.Incarnation, Sequence = x.ExpectedActivation.Sequence }, ExpectedServingIncarnation = x.ExpectedServingIncarnation, RemainingBudgetTicks = x.RemainingBudget.Ticks, }; if (x.Comment is not null) v.Comment = x.Comment; if (x.OnBehalfOf is not null) v.OnBehalfOf = x.OnBehalfOf; return v; } /// /// Decodes a condition method request. A malformed request (no placement, an unknown or multi-bit method, no marker, /// an oversized comment or id) is an ⇒ INVALID_ARGUMENT. on_behalf_of is NOT /// refused for its content: it is untrusted audit text the origin caps and sanitises (§6). /// public static DataConditionMethodRequest DecodeMethodRequest(W.ConditionMethodRequest x) { ArgumentNullException.ThrowIfNull(x); if (x.Placement is null || x.ExpectedActivation is null) throw new ArgumentException("Missing placement or activation marker."); if (x.Method <= 0) throw new ArgumentException("Unknown condition method."); var decoded = new DataConditionMethodRequest(x.OperationId, DataProtoMapper.DecodeView(x.Placement), (DataConditionMethods)(uint)x.Method, new DataActivationMarker(x.ExpectedActivation.Incarnation, x.ExpectedActivation.Sequence), x.HasComment ? x.Comment : null, x.ExpectedServingIncarnation, TimeSpan.FromTicks(x.RemainingBudgetTicks), x.HasOnBehalfOf ? x.OnBehalfOf : null); decoded.Validate(); return decoded; } /// Encodes a condition method response. public static W.ConditionMethodResponse EncodeMethodResponse(DataConditionMethodResult x) { ArgumentNullException.ThrowIfNull(x); x.Validate(); var v = new W.ConditionMethodResponse { State = (int)x.State, StatusCode = x.StatusCode }; if (x.Diagnostic is not null) v.Diagnostic = x.Diagnostic; if (x.Serving is { } serving) v.Serving = DataProtoMapper.EncodeServing(serving); return v; } /// Decodes a condition method response (an unknown state is an ). public static DataConditionMethodResult DecodeMethodResponse(W.ConditionMethodResponse x) { ArgumentNullException.ThrowIfNull(x); var state = (DataWriteState)x.State; if (state == DataWriteState.Unspecified || !System.Enum.IsDefined(state)) throw new ArgumentException("Unknown method outcome state."); return new DataConditionMethodResult(state, x.StatusCode, x.HasDiagnostic ? x.Diagnostic : null, x.Serving is null ? null : DataProtoMapper.DecodeServing(x.Serving)); } }