using System.Buffers.Binary; using System.Collections.Concurrent; using System.Net; using System.Net.Sockets; using System.Text; namespace ZB.MOM.WW.OtOpcUa.Driver.Heidenhain.Tests.Simulator; /// One request frame as the simulated control received it. public sealed record Lsv2Request(string Command, byte[] Payload) { /// The payload decoded as Latin-1 (for login/path assertions). public string Text => Encoding.Latin1.GetString(Payload); /// The R_RI selector. public int Selector => BinaryPrimitives.ReadUInt16BigEndian(Payload); } /// A scripted connection to the simulator. public sealed class SimConnection(TcpClient client) { private readonly NetworkStream _stream = client.GetStream(); /// Reads one complete request frame, or null on EOF. public async Task ReadRequestAsync(CancellationToken ct) { var header = new byte[8]; var read = 0; while (read < 8) { var n = await _stream.ReadAsync(header.AsMemory(read), ct).ConfigureAwait(false); if (n == 0) return read == 0 ? null : throw new EndOfStreamException(); read += n; } var length = (int)BinaryPrimitives.ReadUInt32BigEndian(header); var payload = new byte[length]; await _stream.ReadExactlyAsync(payload, ct).ConfigureAwait(false); return new Lsv2Request(Encoding.ASCII.GetString(header, 4, 4), payload); } /// Writes one well-formed reply frame. public Task ReplyAsync(string command, byte[] payload, CancellationToken ct = default) => WriteRawAsync(Frame(command, payload), byteByByte: false, ct); /// Writes raw bytes, optionally one byte per write (TCP fragmentation). public async Task WriteRawAsync(byte[] bytes, bool byteByByte, CancellationToken ct = default) { if (!byteByByte) { await _stream.WriteAsync(bytes, ct).ConfigureAwait(false); await _stream.FlushAsync(ct).ConfigureAwait(false); return; } foreach (var b in bytes) { await _stream.WriteAsync(new[] { b }, ct).ConfigureAwait(false); await _stream.FlushAsync(ct).ConfigureAwait(false); await Task.Delay(1, ct).ConfigureAwait(false); } } /// Reads one raw byte (blocks until the peer sends or closes). public async Task ReadByteAsync(CancellationToken ct) { var b = new byte[1]; return await _stream.ReadAsync(b, ct).ConfigureAwait(false) == 0 ? -1 : b[0]; } /// Closes the connection. public void Close() => client.Dispose(); /// Builds a frame independently of the driver's encoder. public static byte[] Frame(string command, byte[] payload) { var f = new byte[8 + payload.Length]; BinaryPrimitives.WriteUInt32BigEndian(f, (uint)payload.Length); Encoding.ASCII.GetBytes(command, f.AsSpan(4, 4)); payload.CopyTo(f, 8); return f; } } /// /// In-process LSV2 peer on a loopback port. Either runs a per-connection (framing tests) /// or serves a model. Records every request it receives on any connection, /// so a test can prove that only allowlisted telegrams ever left the driver. /// public sealed class Lsv2Simulator : IAsyncDisposable { private readonly TcpListener _listener = new(IPAddress.Loopback, 0); private readonly CancellationTokenSource _cts = new(); private readonly Func _script; private readonly ConcurrentQueue _requests = new(); private readonly ConcurrentBag _clients = new(); private readonly Task _accept; private readonly ConcurrentQueue _faults = new(); private volatile bool _offline; private int _connections; private Lsv2Simulator(Func script) { _script = script; _listener.Start(); _accept = Task.Run(AcceptLoopAsync); } /// A simulator running a raw per-connection script. public static Lsv2Simulator WithScript(Func script) => new(script); /// A simulator serving a control model (one model shared by all connections). public static Lsv2Simulator WithControl(SimulatedControl control) { Lsv2Simulator? sim = null; sim = new Lsv2Simulator(async (c, ct) => { while (true) { var req = await c.ReadRequestAsync(ct).ConfigureAwait(false); if (req is null) return; sim!._requests.Enqueue(req); var reply = control.Handle(req); switch (reply.Kind) { case SimReplyKind.Frame: await c.ReplyAsync(reply.Command!, reply.Payload!, ct).ConfigureAwait(false); break; case SimReplyKind.Drop: c.Close(); return; case SimReplyKind.Stall: await Task.Delay(Timeout.Infinite, ct).ConfigureAwait(false); return; } } }); return sim; } /// The loopback port. public int Port => ((IPEndPoint)_listener.LocalEndpoint).Port; /// Every request received (model mode), in arrival order. public IReadOnlyList Requests => _requests.ToArray(); /// Accepted connection count. public int Connections => Volatile.Read(ref _connections); /// Exceptions a script threw (tests assert this is empty). public IReadOnlyList Faults => _faults.ToArray(); /// Simulates a network outage: drops every live connection and refuses (closes) new ones. public void GoOffline() { _offline = true; foreach (var c in _clients) c.Dispose(); } /// Ends the outage. public void GoOnline() => _offline = false; private async Task AcceptLoopAsync() { while (!_cts.IsCancellationRequested) { TcpClient client; try { client = await _listener.AcceptTcpClientAsync(_cts.Token).ConfigureAwait(false); } catch { return; } if (_offline) { client.Dispose(); continue; } Interlocked.Increment(ref _connections); _clients.Add(client); _ = Task.Run(async () => { try { await _script(new SimConnection(client), _cts.Token).ConfigureAwait(false); } catch (Exception ex) when (ex is IOException or ObjectDisposedException or OperationCanceledException or SocketException or EndOfStreamException) { } catch (Exception ex) { _faults.Enqueue(ex); } finally { client.Dispose(); } }); } } /// public async ValueTask DisposeAsync() { await _cts.CancelAsync().ConfigureAwait(false); _listener.Stop(); foreach (var c in _clients) c.Dispose(); try { await _accept.ConfigureAwait(false); } catch { /* stopped */ } _cts.Dispose(); } }