namespace Common.Hardware.SIRT { using Common.Hardware.Ports; using System; using System.Collections.Concurrent; using Parity = System.IO.Ports.Parity; using StopBits = System.IO.Ports.StopBits; public partial class SIRTBroadcaster { public SIRTBroadcaster(string comPort) { this.serialPort = new SerialPort(comPort, 115200, Parity.None, 8, StopBits.One); this.tasks = new ConcurrentDictionary>(); } public event Action Activated; public event Action Connected; public event Action Disconnected; public event Action Logging; public event Action MessageReceived; public string COMPort => this.serialPort.COMPort; public string HexId { get; protected set; } public int Frequency { get; protected set; } public void Close() { this.serialPort.Close(); this.HexId = null; this.Frequency = 0; this.serialPort.Connected -= this.SerialPort_Connected; this.serialPort.Disconnected -= this.SerialPort_Disconnected; this.serialPort.Logging -= this.SerialPort_Logging; this.Activated -= this.StartProcessingTasksAsync; this.MessageReceived -= this.SIRTConnection_MessageReceived; } public void Open() { if (!this.serialPort.IsOpen) { this.serialPort.Connected += this.SerialPort_Connected; this.serialPort.Disconnected += this.SerialPort_Disconnected; this.serialPort.Logging += this.SerialPort_Logging; this.Activated += this.StartProcessingTasksAsync; this.MessageReceived += this.SIRTConnection_MessageReceived; this.serialPort.Open(); } } public void DequeueTasks(uint address) { if (this.tasks.TryRemove(address, out var tasksQueue)) { while (tasksQueue.TryDequeue(out var task)) { this.TaskRemoveEventHandlers(task); } } } public void EnqueueTask(SIRTTask task) { if (this.Frequency == task.Frequency) { this.TaskAddEventHandlers(task); var requestTasks = this.tasks.GetOrAdd(task.RequestAddress, new ConcurrentQueue()); requestTasks.Enqueue(task); if (task.RequestAddress != task.ResponseAddress) { this.tasks.AddOrUpdate(task.ResponseAddress, requestTasks, (_, _requestTasks) => _requestTasks); } } } public void RemoveConnection() => this.serialPort.RemoveConnection(); } }