serialport communication timeout added

This commit is contained in:
atef 2025-08-04 10:41:17 +02:00
parent 661201617c
commit e1a5aa3b2f
1 changed files with 23 additions and 8 deletions

View File

@ -27,7 +27,11 @@ public class SerialPortChannel : ConnectionChannel<SerialPort>
_Open = () =>
{
var serialPort = new SerialPort(portName, baudRate, parity, dataBits, sb);
var serialPort = new SerialPort(portName, baudRate, parity, dataBits, sb)
{
ReadTimeout = 1000, // milliseconds
WriteTimeout = 1000 // milliseconds
};
serialPort.Open();
return serialPort;
};
@ -40,11 +44,16 @@ public class SerialPortChannel : ConnectionChannel<SerialPort>
protected override IReadOnlyList<Byte> Read(SerialPort serialPort, Int32 nBytes)
{
var buffer = new Byte[nBytes];
var bytesReceived = 0;
try
{
do
{
//Console.WriteLine($"🔧 Waiting for {nBytes} bytes...");
var received = serialPort.Read(buffer, bytesReceived, nBytes - bytesReceived);
//Console.WriteLine($"✅ Received {bytesReceived} bytes so far");
if (received < 0)
throw new NotConnectedException("Serial Connection has been closed");
@ -52,6 +61,12 @@ public class SerialPortChannel : ConnectionChannel<SerialPort>
}
while (bytesReceived < nBytes);
}
catch (TimeoutException)
{
throw new IOException("Serial read timed out");
}
return buffer;
}