feat: preserve grpc write admission and uncertain outcomes
This commit is contained in:
@@ -5,6 +5,7 @@ using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using ZB.MOM.WW.OtOpcUa.Commons.Observability;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Driver.Modbus;
|
||||
|
||||
@@ -20,7 +21,7 @@ namespace ZB.MOM.WW.OtOpcUa.Driver.Modbus;
|
||||
/// <see cref="PollGroupEngine"/> since Modbus has no native push model.
|
||||
/// </remarks>
|
||||
public sealed class ModbusDriver
|
||||
: IDriver, ITagDiscovery, IReadable, IWritable, IBatchSubscribable, IHostConnectivityProbe, IPerCallHostResolver, ISkippedTagReporter, IDisposable, IAsyncDisposable
|
||||
: IDriver, ITagDiscovery, IReadable, IWritable, IWriteOutcomeCapability, IBatchSubscribable, IHostConnectivityProbe, IPerCallHostResolver, ISkippedTagReporter, IDisposable, IAsyncDisposable
|
||||
{
|
||||
/// <summary>Authored tags this driver could not build into its poll table.</summary>
|
||||
private readonly SkippedTagLedger _skippedTags = new();
|
||||
@@ -1477,6 +1478,112 @@ public sealed class ModbusDriver
|
||||
|
||||
// ---- IWritable ----
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<IReadOnlyList<DataWriteOutcome>> WriteWithOutcomesAsync(
|
||||
IReadOnlyList<WriteRequest> writes, CancellationToken cancellationToken)
|
||||
{
|
||||
var (generation, transport, table) = CaptureLifecycle();
|
||||
var results = new DataWriteOutcome[writes.Count];
|
||||
var batch = new BatchOutcome();
|
||||
for (var i = 0; i < writes.Count; i++)
|
||||
{
|
||||
var write = writes[i];
|
||||
if (!table.TryGetValue(write.FullReference, out var tag))
|
||||
{
|
||||
results[i] = new(DataWriteState.RejectedBeforeDispatch, StatusBadNodeIdUnknown, "Unknown tag.");
|
||||
continue;
|
||||
}
|
||||
if (!tag.Writable || tag.Region is ModbusRegion.DiscreteInputs or ModbusRegion.InputRegisters)
|
||||
{
|
||||
results[i] = new(DataWriteState.RejectedBeforeDispatch, StatusBadNotWritable, "Tag is not writable.");
|
||||
continue;
|
||||
}
|
||||
if (transport is not IModbusWriteOnceTransport once)
|
||||
{
|
||||
results[i] = new(DataWriteState.RejectedBeforeDispatch, StatusBadNotSupported, "Transport cannot guarantee a single send.");
|
||||
continue;
|
||||
}
|
||||
if (cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
results[i] = new(DataWriteState.RejectedBeforeDispatch, StatusBadTimeout, "Canceled before dispatch.");
|
||||
continue;
|
||||
}
|
||||
if (_options.WriteOnChangeOnly && IsRedundantWrite(write.FullReference, write.Value))
|
||||
{
|
||||
results[i] = new(DataWriteState.AcceptedUnconfirmed, 0, "Write suppressed without a new device acknowledgement.");
|
||||
continue;
|
||||
}
|
||||
var unit = ResolveUnitId(tag);
|
||||
if (batch.IsFailedFast(unit))
|
||||
{
|
||||
results[i] = new(DataWriteState.RejectedBeforeDispatch, StatusBadCommunicationError, "Batch stopped before dispatch.");
|
||||
continue;
|
||||
}
|
||||
var tracked = new SingleSendWriteTransport(once);
|
||||
try
|
||||
{
|
||||
await WriteOneAsync(tracked, tag, write.Value, cancellationToken).ConfigureAwait(false);
|
||||
results[i] = tracked.ValidWriteAcknowledged
|
||||
? new(DataWriteState.DriverConfirmedSuccess, 0, null)
|
||||
: new(DataWriteState.OutcomeUnknown, StatusBadCommunicationError, "No confirmed write response.");
|
||||
batch.Answered = true;
|
||||
if (_options.WriteOnChangeOnly && tracked.ValidWriteAcknowledged)
|
||||
lock (_lastWrittenLock) _lastWrittenByRef[write.FullReference] = write.Value;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
var status = MapWriteFailure(ex, unit, write.FullReference, batch, cancellationToken);
|
||||
var state = tracked.DefinitiveRefusal ? DataWriteState.DriverConfirmedFailure :
|
||||
!tracked.WriteAttempted && ex is (ModbusWriteRefusedException or OverflowException or FormatException or
|
||||
InvalidCastException or ArgumentException or NotSupportedException)
|
||||
? DataWriteState.RejectedBeforeDispatch : DataWriteState.OutcomeUnknown;
|
||||
results[i] = new(state, status, ex.Message);
|
||||
InvalidateWriteCache(write.FullReference);
|
||||
}
|
||||
}
|
||||
ReportOutcome(generation, batch, DateTime.UtcNow);
|
||||
return results;
|
||||
}
|
||||
|
||||
/// <summary>Tracks actual write PDUs and validates their protocol responses without altering the legacy path.</summary>
|
||||
private sealed class SingleSendWriteTransport(IModbusWriteOnceTransport transport) : IModbusTransport
|
||||
{
|
||||
public bool WriteAttempted { get; private set; }
|
||||
public bool ValidWriteAcknowledged { get; private set; }
|
||||
public bool DefinitiveRefusal { get; private set; }
|
||||
public Task ConnectAsync(CancellationToken ct) => throw new NotSupportedException();
|
||||
public ValueTask DisposeAsync() => ValueTask.CompletedTask;
|
||||
|
||||
public async Task<byte[]> SendAsync(byte unitId, byte[] pdu, CancellationToken ct)
|
||||
{
|
||||
var isWrite = pdu[0] is 0x05 or 0x06 or 0x0F or 0x10 or 0x17;
|
||||
if (isWrite)
|
||||
{
|
||||
WriteAttempted = true;
|
||||
ValidWriteAcknowledged = false;
|
||||
DefinitiveRefusal = false;
|
||||
}
|
||||
byte[] reply;
|
||||
try { reply = await transport.SendWithoutRetryAsync(unitId, pdu, ct).ConfigureAwait(false); }
|
||||
catch (ModbusException ex)
|
||||
{
|
||||
// A response for another function cannot establish that this write was refused.
|
||||
// In particular, don't let FC23's illegal-function fallback replay an ambiguous write.
|
||||
if (isWrite && ex.FunctionCode != pdu[0])
|
||||
throw new InvalidDataException("Modbus exception function did not match the write request.", ex);
|
||||
DefinitiveRefusal = isWrite && ex.FunctionCode == pdu[0] && ex.ExceptionCode is (1 or 2 or 3);
|
||||
throw;
|
||||
}
|
||||
if (!isWrite) return reply;
|
||||
var valid = pdu[0] == 0x17
|
||||
? reply.Length == 2 + 2 * ((pdu[3] << 8) | pdu[4]) && reply[0] == pdu[0] && reply[1] == reply.Length - 2
|
||||
: reply.Length == 5 && reply.AsSpan().SequenceEqual(pdu.AsSpan(0, 5));
|
||||
if (!valid) throw new InvalidDataException("Modbus write acknowledgement did not match the request.");
|
||||
ValidWriteAcknowledged = true;
|
||||
return reply;
|
||||
}
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<IReadOnlyList<WriteResult>> WriteAsync(
|
||||
IReadOnlyList<WriteRequest> writes, CancellationToken cancellationToken)
|
||||
|
||||
Reference in New Issue
Block a user