Something went wrong. Try again.
Modular scanner/radio client and multi-broadcast server. uniscan.dexrn.me
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208using 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<TOpCode, TProtocol> : DeviceConnection<ReadOnlyMemory<byte>, IDevicePayload>, ICommandBasedDeviceConnection<TOpCode> where TOpCode : notnull where TProtocol : CommandBasedDeviceProtocol<TOpCode>{ public TProtocol Protocol { get; } CommandBasedDeviceProtocol<TOpCode> ICommandBasedDeviceConnection<TOpCode>.Protocol => Protocol; public ITransport<ReadOnlyMemory<byte>> Transport { get; } public ILogger Logger { get; set; } = Log.ForContext<CommandBasedDeviceConnection<TOpCode, TProtocol>>(); public Dictionary<TOpCode, EventHandler<CommandPacketReceivedEventArgs<TOpCode>>> PayloadReceived { get; } = [];
private readonly Dictionary<TOpCode, Queue<TaskCompletionSource<IDevicePayload>>> _commandQueues = new(); private readonly SemaphoreSlim _writeSemaphore = new(1, 1); //my name is slim semaphore private readonly Channel<CommandPacketReceivedEventArgs<TOpCode>> _packetDispatcherQueue; private Pipe? _bufferPipe;
protected CommandBasedDeviceConnection(TProtocol protocol, ITransport<ReadOnlyMemory<byte>> transport) : base(transport) { Protocol = protocol; Transport = transport;
_packetDispatcherQueue = Channel.CreateUnbounded<CommandPacketReceivedEventArgs<TOpCode>>(new UnboundedChannelOptions { SingleReader = true, AllowSynchronousContinuations = false }); Transport.DataReceived += OnTransportDataReceived; Protocol.CommandPacketReceived += OnPacketReceived; }
public virtual async Task SendAsync(IPayloadResponseEncoder<TOpCode> encoder) { await this.Transport.SendAsync(encoder.EncodeResponse()); }
public async Task SendAsync<TRequestEncoder, TArgs>(TArgs args, CancellationToken ct = default) where TRequestEncoder : IPayloadRequestEncoder<TOpCode, TArgs> => await Transport.SendAsync(TRequestEncoder.EncodeRequest(args), ct);
/// <summary> /// Called to perform a handshake before the scanner connection is considered ready for use /// </summary> 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<byte> 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<Result<TResponse, Exception>> SendRequestAsync<TRequestEncoder, TArgs, TResponse>( TArgs args, CancellationToken ct = default) where TRequestEncoder : IPayloadRequestEncoder<TOpCode, TArgs> where TResponse : IDevicePayload { TOpCode opCode = TRequestEncoder.CommandDefinition.OpCode; TaskCompletionSource<IDevicePayload> source = new(TaskCreationOptions.RunContinuationsAsynchronously);
await _writeSemaphore.WaitAsync(ct); try { lock (_commandQueues) { if (!_commandQueues.TryGetValue(opCode, out var queue)) { queue = new Queue<TaskCompletionSource<IDevicePayload>>();
_commandQueues[opCode] = queue; }
queue.Enqueue(source); }
await SendAsync<TRequestEncoder, TArgs>(args, ct); } finally { _writeSemaphore.Release(); }
try { return await Result<TResponse, Exception>.FromWrappedAsync(async () => (TResponse) await source.Task .WaitAsync(TimeSpan.FromSeconds(5), ct) ); } catch (TimeoutException ex) { return new Result<TResponse, Exception>(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<TOpCode> 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<byte> buffer) { _bufferPipe.Writer.Write(buffer.Span); _ = _bufferPipe.Writer.FlushAsync().AsTask(); }
private void OnPacketReceived(object? sender, CommandPacketReceivedEventArgs<TOpCode> 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); }}