Files
lmxopcua/src/Core/ZB.MOM.WW.OtOpcUa.Commons/DataConnections/DataConditionProtoMapper.cs
T

165 lines
9.1 KiB
C#

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;
/// <summary>
/// A2 condition codecs (plan §4.2, §5.5): <c>CapabilitiesResponse.conditions</c>, <c>SubscriptionItem.condition_scope</c>
/// and the <c>condition_states</c> frame arm (9). Only ever exercised on a call that negotiated <c>conditions</c>: the
/// host strips every one of these shapes from a header-less call, so a v1 client never sees them.
/// </summary>
public static class DataConditionProtoMapper
{
/// <summary>The most condition records one decoded frame may carry.</summary>
public const int MaxRecordsPerFrame = 5000;
/// <summary>Encodes the capabilities field.</summary>
public static W.ConditionCapabilities EncodeCapabilities(DataConditionCapabilities x) =>
new() { RootScopeItems = x.RootScopeItems, Methods = x.Methods, MaxConditions = x.MaxConditions };
/// <summary>Decodes the capabilities field (null when absent).</summary>
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;
}
/// <summary>Encodes one condition record.</summary>
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;
}
/// <summary>Decodes one condition record (a malformed key or negative version is an <see cref="ArgumentException"/>).</summary>
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);
}
/// <summary>Encodes a condition frame (arm 9). The host calls this only on a call that negotiated <c>conditions</c>.</summary>
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,
};
}
/// <summary>Decodes a condition frame; the handle must belong to the frame's stream.</summary>
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) ----
/// <summary>Encodes a condition method request.</summary>
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;
}
/// <summary>
/// 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 <see cref="ArgumentException"/> ⇒ INVALID_ARGUMENT. <c>on_behalf_of</c> is NOT
/// refused for its content: it is untrusted audit text the origin caps and sanitises (§6).
/// </summary>
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;
}
/// <summary>Encodes a condition method response.</summary>
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;
}
/// <summary>Decodes a condition method response (an unknown state is an <see cref="ArgumentException"/>).</summary>
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));
}
}