e68d856fcb
- P-6: the wire adapter throws refused fixed-tree calls as FocasWireException carrying the rc (was InvalidOperationException, so a refusing control looked silent, degraded and was reconnect-looped by the #527 watchdog); a refused axis is per-node BadNoData and the tick continues. - P-7: bootstrap capability probes latch only an ANSWER (rc, or session still up); a transport failure/timeout or a session dropped mid-pass retries the bootstrap. - P-21: CoalesceRejected latches only range-shaped codes (not EW_BUSY/EW_SOCKET/EW_UNEXP/EW_HANDLE/unknown). Macro/param multi-block batching deferred (unproven on hardware). - P-10: any fault once a request is on the wire closes the session (bad magic/version, unexpected PDU, malformed blocks); replies must echo the request's command ids in order (verified against every 31i-B capture). A refusal never closes the session. - P-8: close handshake bounded to 1 s and run under the request gate (sync + async dispose). - P-11: data-path callers check the backoff before ConnectGate and fail fast behind an in-flight reconnect to a device whose last connect failed. - P-9: axes/spindles carry their wire slot (FocasAxisName/FocasSpindleName.Slot); cnc_rddynamic2 and the spindle-meter lookup use it. - P-20: a truncated (>= 32) alarm list never clears/retriggers a told-active condition unless it shows a new key; unseen told keys are kept. - P-25: a refused connect-time sysinfo is not cached; a short PARAM payload reads BadTypeMismatch. Tests: loopback MockFocasWireServer drives the real wire client; every fix mutation-checked (reverting it fails its test). FOCAS.Tests 619/619, FOCAS.IntegrationTests 19/19 vs the sim on 10.100.0.35, Runtime.Tests FOCAS 7/7, FOCAS.Cli.Tests 57/57.
230 lines
9.6 KiB
C#
230 lines
9.6 KiB
C#
using System.Buffers.Binary;
|
|
using System.Net;
|
|
using System.Net.Sockets;
|
|
|
|
namespace ZB.MOM.WW.OtOpcUa.Driver.FOCAS.Tests;
|
|
|
|
/// <summary>One request block as the mock CNC received it.</summary>
|
|
/// <param name="Command">The FOCAS command id.</param>
|
|
/// <param name="Arg1">32-bit argument 1.</param>
|
|
/// <param name="Arg2">32-bit argument 2.</param>
|
|
internal sealed record MockFocasRequest(ushort Command, int Arg1, int Arg2);
|
|
|
|
/// <summary>
|
|
/// A loopback FOCAS/2 Ethernet peer speaking the real binary framing (the shape the 31i-B captures under
|
|
/// <c>Fixtures/v3</c> and the focas-mock fixture use: initiate on both sockets, then <c>0x21</c> data PDUs whose
|
|
/// reply blocks echo the request's command ids in order). Each test scripts what it answers — a stray PDU, a
|
|
/// mismatched block, silence on the close PDU — to drive the real <see cref="Wire.FocasWireClient"/> through
|
|
/// the protocol faults #985 is about. Default behaviour answers everything with rc 0.
|
|
/// </summary>
|
|
internal sealed class MockFocasWireServer : IAsyncDisposable
|
|
{
|
|
private readonly TcpListener _listener = new(IPAddress.Loopback, 0);
|
|
private readonly CancellationTokenSource _cts = new();
|
|
private readonly List<TcpClient> _connections = [];
|
|
private readonly Task _acceptLoop;
|
|
private int _initiates;
|
|
private int _closes;
|
|
private int _dataRequests;
|
|
|
|
public MockFocasWireServer()
|
|
{
|
|
_listener.Start();
|
|
Port = ((IPEndPoint)_listener.LocalEndpoint).Port;
|
|
_acceptLoop = AcceptLoopAsync();
|
|
}
|
|
|
|
/// <summary>The listening port.</summary>
|
|
public int Port { get; }
|
|
|
|
/// <summary>The driver host address of this peer.</summary>
|
|
public string HostAddress => $"focas://127.0.0.1:{Port}";
|
|
|
|
/// <summary>Answer the close PDU (default) or stay silent on it with the socket left open.</summary>
|
|
public volatile bool AnswerClose = true;
|
|
|
|
/// <summary>
|
|
/// Builds the bytes written for one data PDU (any number of whole PDUs, or <see langword="null"/> to stay
|
|
/// silent). Default: <see cref="Reply"/> of every block through <see cref="Responder"/>.
|
|
/// </summary>
|
|
public Func<IReadOnlyList<MockFocasRequest>, byte[]?>? OnData { get; set; }
|
|
|
|
/// <summary>The (rc, payload) the default <see cref="OnData"/> answers one block with.</summary>
|
|
public Func<MockFocasRequest, (short Rc, byte[] Payload)> Responder { get; set; } = DefaultResponder;
|
|
|
|
/// <summary>Initiate PDUs received (two per session).</summary>
|
|
public int Initiates => Volatile.Read(ref _initiates);
|
|
|
|
/// <summary>Close PDUs received.</summary>
|
|
public int Closes => Volatile.Read(ref _closes);
|
|
|
|
/// <summary>Data PDUs received.</summary>
|
|
public int DataRequests => Volatile.Read(ref _dataRequests);
|
|
|
|
/// <summary>Every data request block received, in order (lock it to read while the server runs).</summary>
|
|
public List<MockFocasRequest> Requests { get; } = [];
|
|
|
|
/// <summary>How many request blocks of <paramref name="command"/> have been received.</summary>
|
|
public int CountOf(ushort command)
|
|
{
|
|
lock (Requests) return Requests.Count(r => r.Command == command);
|
|
}
|
|
|
|
/// <summary>The default answer: a sysinfo record for 0x0018, a macro whose mantissa is its number, else 4 zero bytes.</summary>
|
|
public static (short Rc, byte[] Payload) DefaultResponder(MockFocasRequest r) => r.Command switch
|
|
{
|
|
0x0018 => (0, SysInfoPayload()),
|
|
0x000e when r.Arg1 == 0x26f0 => (1, []), // the setup request — a real 31i-B answers EW_FUNC
|
|
0x0015 => (0, MacroPayload(r.Arg1, 0)),
|
|
_ => (0, new byte[4]),
|
|
};
|
|
|
|
/// <summary>An 18-byte <c>cnc_sysinfo</c> payload (2 axes, "31", "MM", "G431", "22.0", "07").</summary>
|
|
public static byte[] SysInfoPayload() =>
|
|
[0x02, 0x02, 0x00, 0x20, 0x33, 0x31, 0x4d, 0x4d, 0x47, 0x34, 0x33, 0x31, 0x32, 0x32, 0x2e, 0x30, 0x30, 0x37];
|
|
|
|
/// <summary>An 8-byte <c>cnc_rdmacro</c> payload: mantissa, the constant 10, decimal places.</summary>
|
|
public static byte[] MacroPayload(int mantissa, short decimals)
|
|
{
|
|
var p = new byte[8];
|
|
BinaryPrimitives.WriteInt32BigEndian(p.AsSpan(0, 4), mantissa);
|
|
BinaryPrimitives.WriteInt16BigEndian(p.AsSpan(4, 2), 10);
|
|
BinaryPrimitives.WriteInt16BigEndian(p.AsSpan(6, 2), decimals);
|
|
return p;
|
|
}
|
|
|
|
/// <summary>A data-reply PDU answering <paramref name="requests"/> block-for-block through <see cref="Responder"/>.</summary>
|
|
public byte[] Reply(IReadOnlyList<MockFocasRequest> requests) =>
|
|
DataPdu([.. requests.Select(r => { var (rc, p) = Responder(r); return (r.Command, rc, p); })]);
|
|
|
|
/// <summary>A data-reply PDU carrying exactly the given blocks.</summary>
|
|
public static byte[] DataPdu(params (ushort Command, short Rc, byte[] Payload)[] blocks)
|
|
{
|
|
var encoded = blocks.Select(b =>
|
|
{
|
|
var block = new byte[0x10 + b.Payload.Length];
|
|
BinaryPrimitives.WriteUInt16BigEndian(block.AsSpan(0, 2), (ushort)block.Length);
|
|
BinaryPrimitives.WriteUInt16BigEndian(block.AsSpan(2, 2), 1);
|
|
BinaryPrimitives.WriteUInt16BigEndian(block.AsSpan(4, 2), 1);
|
|
BinaryPrimitives.WriteUInt16BigEndian(block.AsSpan(6, 2), b.Command);
|
|
BinaryPrimitives.WriteInt16BigEndian(block.AsSpan(8, 2), b.Rc);
|
|
BinaryPrimitives.WriteUInt16BigEndian(block.AsSpan(14, 2), (ushort)b.Payload.Length);
|
|
b.Payload.CopyTo(block.AsSpan(0x10));
|
|
return block;
|
|
}).ToArray();
|
|
var body = new byte[2 + encoded.Sum(b => b.Length)];
|
|
BinaryPrimitives.WriteUInt16BigEndian(body.AsSpan(0, 2), (ushort)encoded.Length);
|
|
var offset = 2;
|
|
foreach (var b in encoded) { b.CopyTo(body.AsSpan(offset)); offset += b.Length; }
|
|
return Pdu(0x21, body);
|
|
}
|
|
|
|
/// <summary>A whole response PDU (version 3, direction response) of <paramref name="type"/>.</summary>
|
|
public static byte[] Pdu(byte type, byte[] body, byte[]? magic = null)
|
|
{
|
|
var pdu = new byte[10 + body.Length];
|
|
(magic ?? [0xa0, 0xa0, 0xa0, 0xa0]).CopyTo(pdu, 0);
|
|
BinaryPrimitives.WriteUInt16BigEndian(pdu.AsSpan(4, 2), 3);
|
|
pdu[6] = type;
|
|
pdu[7] = 0x02;
|
|
BinaryPrimitives.WriteUInt16BigEndian(pdu.AsSpan(8, 2), (ushort)body.Length);
|
|
body.CopyTo(pdu, 10);
|
|
return pdu;
|
|
}
|
|
|
|
/// <summary>Drops every open connection (the CNC goes away) and stops accepting new ones.</summary>
|
|
public void Stop()
|
|
{
|
|
_listener.Stop();
|
|
lock (_connections)
|
|
{
|
|
foreach (var c in _connections) c.Dispose();
|
|
_connections.Clear();
|
|
}
|
|
}
|
|
|
|
private async Task AcceptLoopAsync()
|
|
{
|
|
while (!_cts.IsCancellationRequested)
|
|
{
|
|
TcpClient client;
|
|
try { client = await _listener.AcceptTcpClientAsync(_cts.Token); }
|
|
catch { return; }
|
|
lock (_connections) _connections.Add(client);
|
|
_ = ServeAsync(client);
|
|
}
|
|
}
|
|
|
|
private async Task ServeAsync(TcpClient client)
|
|
{
|
|
try
|
|
{
|
|
var stream = client.GetStream();
|
|
var header = new byte[10];
|
|
while (!_cts.IsCancellationRequested)
|
|
{
|
|
await stream.ReadExactlyAsync(header, _cts.Token);
|
|
var length = BinaryPrimitives.ReadUInt16BigEndian(header.AsSpan(8, 2));
|
|
var body = new byte[length];
|
|
if (length > 0) await stream.ReadExactlyAsync(body, _cts.Token);
|
|
byte[]? answer;
|
|
switch (header[6])
|
|
{
|
|
case 0x01:
|
|
Interlocked.Increment(ref _initiates);
|
|
answer = Pdu(0x01, new byte[24]);
|
|
break;
|
|
case 0x02:
|
|
Interlocked.Increment(ref _closes);
|
|
answer = AnswerClose ? Pdu(0x02, []) : null;
|
|
break;
|
|
case 0x21:
|
|
Interlocked.Increment(ref _dataRequests);
|
|
var requests = ParseRequests(body);
|
|
lock (Requests) Requests.AddRange(requests);
|
|
answer = (OnData ?? Reply)(requests);
|
|
break;
|
|
default:
|
|
answer = null;
|
|
break;
|
|
}
|
|
if (answer is not null)
|
|
{
|
|
await stream.WriteAsync(answer, _cts.Token);
|
|
await stream.FlushAsync(_cts.Token);
|
|
}
|
|
}
|
|
}
|
|
catch
|
|
{
|
|
// Peer closed / test over.
|
|
}
|
|
}
|
|
|
|
private static List<MockFocasRequest> ParseRequests(byte[] body)
|
|
{
|
|
var list = new List<MockFocasRequest>();
|
|
if (body.Length < 2) return list;
|
|
var count = BinaryPrimitives.ReadUInt16BigEndian(body.AsSpan(0, 2));
|
|
var offset = 2;
|
|
for (var i = 0; i < count && offset + 0x1c <= body.Length; i++)
|
|
{
|
|
var blockLength = BinaryPrimitives.ReadUInt16BigEndian(body.AsSpan(offset, 2));
|
|
list.Add(new MockFocasRequest(
|
|
BinaryPrimitives.ReadUInt16BigEndian(body.AsSpan(offset + 6, 2)),
|
|
BinaryPrimitives.ReadInt32BigEndian(body.AsSpan(offset + 8, 4)),
|
|
BinaryPrimitives.ReadInt32BigEndian(body.AsSpan(offset + 12, 4))));
|
|
offset += blockLength;
|
|
}
|
|
return list;
|
|
}
|
|
|
|
public async ValueTask DisposeAsync()
|
|
{
|
|
_cts.Cancel();
|
|
Stop();
|
|
try { await _acceptLoop; } catch { /* stopped */ }
|
|
_cts.Dispose();
|
|
}
|
|
}
|