serialport communication timeout added
This commit is contained in:
parent
661201617c
commit
e1a5aa3b2f
|
|
@ -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;
|
||||
}
|
||||
|
||||
|
|
|
|||
Loading…
Reference in New Issue