Files
laatzen/Common/Hardware/Common.Hardware.SIRT/SIRTPort.cs
T

146 lines
3.8 KiB
C#

namespace Common.Hardware.SIRT
{
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO.Ports;
using System.Threading;
public sealed class SIRTPort
{
private static readonly ConcurrentDictionary<string, SerialPort> serialPorts
= new ConcurrentDictionary<string, SerialPort>();
private readonly int baudRate;
private readonly Parity parity;
private readonly int dataBits;
private readonly StopBits stopBits;
public SIRTPort(string portName, int baudRate, Parity parity, int dataBits, StopBits stopBits)
{
this.PortName = portName;
this.baudRate = baudRate;
this.parity = parity;
this.dataBits = dataBits;
this.stopBits = stopBits;
}
public event Action Connected;
public event Action Disconnected;
public event Action<string> Logging;
public string PortName { get; }
public void Close()
{
try
{
var awaiter = new ManualResetEventSlim();
var sp = this.GetOrAddSerialPort();
void disposed(object _, EventArgs _1)
=> awaiter.Set();
sp.Disposed += disposed;
sp.Close();
awaiter.Wait(5000);
sp.Disposed -= disposed;
this.Disconnected?.Invoke();
}
catch (Exception e)
{
this.Logging?.Invoke(e.ToString());
}
serialPorts.TryRemove(this.PortName, out var _);
}
public void Open()
{
var sp = this.GetOrAddSerialPort();
if (sp?.IsOpen == true)
{
this.Close();
}
try
{
sp.Open();
this.Connected?.Invoke();
}
catch (Exception e)
{
this.Logging?.Invoke(e.ToString());
}
}
public IEnumerable<byte[]> ReadBytes()
{
var awaiter = new ManualResetEventSlim();
void dataReceived(object _, SerialDataReceivedEventArgs args)
{
if (args.EventType == SerialData.Chars)
{
awaiter.Set();
}
}
var sp = this.GetOrAddSerialPort();
sp.DataReceived += dataReceived;
var size = sp.ReadBufferSize;
var buffer = new byte[size];
var length = 0;
while (sp?.IsOpen == true)
{
if (!awaiter.IsSet)
{
awaiter.Wait();
awaiter.Reset();
}
try
{
buffer = new byte[size];
length = sp.Read(buffer, 0, size);
Array.Resize(ref buffer, length);
}
catch (Exception e)
{
this.Logging?.Invoke(e.ToString());
}
awaiter.Reset();
yield return buffer;
}
sp.DataReceived -= dataReceived;
}
public void Write(byte[] bytes)
{
try
{
this.GetOrAddSerialPort().Write(bytes, 0, bytes.Length);
}
catch (Exception e)
{
this.Logging?.Invoke(e.ToString());
}
}
private SerialPort GetOrAddSerialPort()
=> serialPorts.GetOrAdd(this.PortName, new SerialPort(this.PortName, this.baudRate, this.parity, this.dataBits, this.stopBits));
public static string[] GetPortNames()
=> SerialPort.GetPortNames();
}
}