using System.Buffers; using System.IO.Pipelines; using System.Threading.Channels; using Serilog; using Shiki.Common.Result; using UniScan.Device.Connection.Command.Protocol; using UniScan.Device.Connection.Protocol.Payload; using UniScan.Device.Connection.Protocol.Payload.IO; using UniScan.Device.Connection.Transport; namespace UniScan.Device.Connection.Command; public abstract class CommandBasedDeviceConnection : DeviceConnection, IDevicePayload>, ICommandBasedDeviceConnection where TOpCode : notnull where TProtocol : CommandBasedDeviceProtocol { public TProtocol Protocol { get; } CommandBasedDeviceProtocol ICommandBasedDeviceConnection.Protocol => Protocol; public ITransport> Transport { get; } public ILogger Logger { get; set; } = Log.ForContext>(); public Dictionary>> PayloadReceived { get; } = []; private readonly Dictionary>> _commandQueues = new(); private readonly SemaphoreSlim _writeSemaphore = new(1, 1); //my name is slim semaphore private readonly Channel> _packetDispatcherQueue; private Pipe? _bufferPipe; protected CommandBasedDeviceConnection(TProtocol protocol, ITransport> transport) : base(transport) { Protocol = protocol; Transport = transport; _packetDispatcherQueue = Channel.CreateUnbounded>(new UnboundedChannelOptions { SingleReader = true, AllowSynchronousContinuations = false }); Transport.DataReceived += OnTransportDataReceived; Protocol.CommandPacketReceived += OnPacketReceived; } public virtual async Task SendAsync(IPayloadResponseEncoder encoder) { await this.Transport.SendAsync(encoder.EncodeResponse()); } public async Task SendAsync(TArgs args, CancellationToken ct = default) where TRequestEncoder : IPayloadRequestEncoder => await Transport.SendAsync(TRequestEncoder.EncodeRequest(args), ct); /// /// Called to perform a handshake before the scanner connection is considered ready for use /// protected abstract Task Handshake(CancellationToken ct = default); public override async Task RunAsync(CancellationToken ct = default) { if (!Transport.IsOpen.Value) { throw new InvalidOperationException("Transport is not open"); } _bufferPipe = new Pipe(); await this.Handshake(ct); CancellationTokenSource dispatchCts = CancellationTokenSource.CreateLinkedTokenSource(ct); //run dispatcher thread //so we dont spend valuable time handling events on the connection thread Task dispatchTask = DispatchAsync(dispatchCts.Token); //now we read PipeReader reader = _bufferPipe.Reader; try { while (!ct.IsCancellationRequested) { ReadResult res = await reader.ReadAsync(ct); ReadOnlySequence buffer = res.Buffer; // wait until we read everything while (Protocol.HandlePayload(ref buffer)) { } reader.AdvanceTo(buffer.Start, buffer.End); if (res.IsCompleted) break; } } catch (OperationCanceledException) { //exit } catch (Exception ex) { Logger.Error(ex, "Exception thrown in connection runner"); } finally { dispatchCts.Cancel(); await dispatchTask; await reader.CompleteAsync(); if (Transport.IsOpen.Value) await Transport.CloseAsync(); } } public virtual async Task> SendRequestAsync( TArgs args, CancellationToken ct = default) where TRequestEncoder : IPayloadRequestEncoder where TResponse : IDevicePayload { TOpCode opCode = TRequestEncoder.CommandDefinition.OpCode; TaskCompletionSource source = new(TaskCreationOptions.RunContinuationsAsynchronously); await _writeSemaphore.WaitAsync(ct); try { lock (_commandQueues) { if (!_commandQueues.TryGetValue(opCode, out var queue)) { queue = new Queue>(); _commandQueues[opCode] = queue; } queue.Enqueue(source); } await SendAsync(args, ct); } finally { _writeSemaphore.Release(); } try { return await Result.FromWrappedAsync(async () => (TResponse) await source.Task .WaitAsync(TimeSpan.FromSeconds(5), ct) ); } catch (TimeoutException ex) { return new Result(ex); } finally { lock (_commandQueues) { if (_commandQueues.TryGetValue(opCode, out var queue) && queue.Count > 0 && queue.Peek() == source) { queue.Dequeue(); } } } } public async Task StartAsync() => await this.Transport.OpenAsync(); public async Task StopAsync() => await this.Transport.CloseAsync(); private async Task DispatchAsync(CancellationToken ct) { try { await foreach (CommandPacketReceivedEventArgs packet in _packetDispatcherQueue.Reader.ReadAllAsync(ct)) { if (PayloadReceived.TryGetValue(packet.OpCode, out var ev)) { ev.Invoke(this, packet); } } } catch (OperationCanceledException) { } } private void OnTransportDataReceived(object? sender, ReadOnlyMemory buffer) { _bufferPipe.Writer.Write(buffer.Span); _ = _bufferPipe.Writer.FlushAsync().AsTask(); } private void OnPacketReceived(object? sender, CommandPacketReceivedEventArgs args) { if (!args.Payload.IsBroadcast) { lock (_commandQueues) { if (_commandQueues.TryGetValue(args.OpCode, out var queue) && queue.Count > 0) { queue.Dequeue().SetResult(args.Payload); return; } } } _packetDispatcherQueue.Writer.TryWrite(args); } }