laatzen/Common/Hardware/Common.Hardware.SIRT/SIRTPort.cs
2025-04-30 16:20:42 +02:00

117 lines
3.0 KiB
C#

namespace Common.Hardware.SIRT
{
using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Threading;
public class SIRTPort
{
private readonly SerialPort serialPort;
public SIRTPort(string portName)
=> this.serialPort = new SerialPort(portName, 112500, Parity.None, 8, StopBits.One);
public bool IsOpen => this.serialPort.IsOpen;
public string PortName => this.serialPort.PortName;
public void Close()
{
SIRTLogger.LogState($"Closing: {this}");
var waitEvent = new ManualResetEventSlim();
void SerialPortDisposed(object sender, EventArgs args)
{
waitEvent.Set();
}
this.serialPort.Disposed += SerialPortDisposed;
try
{
this.serialPort.Close();
waitEvent.Wait(5000);
}
catch (Exception e)
{
SIRTLogger.LogMessage(e);
}
this.serialPort.Disposed -= SerialPortDisposed;
if (!this.IsOpen)
{
SIRTLogger.LogState($"Closed: {this}");
}
}
public void Open()
{
SIRTLogger.LogState($"Opening: {this}");
try
{
this.serialPort.Open();
}
catch (Exception e)
{
SIRTLogger.LogMessage(e);
}
if (this.IsOpen)
{
SIRTLogger.LogState($"Opened: {this}");
}
}
public IEnumerable<byte[]> Read()
{
var buffer = Array.Empty<byte>();
var length = default(int);
while (this.serialPort.IsOpen)
{
try
{
buffer = new byte[this.serialPort.ReadBufferSize];
length = this.serialPort.Read(buffer, 0, buffer.Length);
}
catch (Exception e)
{
SIRTLogger.LogMessage(e);
continue;
}
Array.Resize(ref buffer, length);
yield return buffer;
SIRTLogger.LogRawData($"{this.PortName}|RX: {BitConverter.ToString(buffer)}");
}
}
public override string ToString()
=> $"{this.serialPort.PortName}, "
+ $"{this.serialPort.BaudRate}, "
+ $"{this.serialPort.Parity}, "
+ $"{this.serialPort.DataBits}, "
+ $"{this.serialPort.StopBits}";
public void Write(byte[] bytes)
{
try
{
this.serialPort.Write(bytes, 0, bytes.Length);
SIRTLogger.LogRawData($"{this.PortName}|TX: {BitConverter.ToString(bytes)}");
}
catch (Exception e)
{
SIRTLogger.LogMessage(e);
}
}
}
}