Question: How to detect disconnect
Closed this issue · 2 comments
I have a question:
How would I detect a disconnection of the opened serial port?
Is it only during read write access?
Is there maybe some API I can call to detect a disconnection?
Best regards
Hey! Serial ports do not really have a uniform concept of being "connected". Some devices or modems can use the status lines to indicate connectivity. If your device is one of them, and you have a serial converter that supports these status lines, you could poll these periodically to detect a disconnect.
There are a few status lines that you can poll:
Carrier Detect: SerialPort::read_cd()
Clear To Send: SerialPort::read_cts()
Data Terminal Ready: SerialPort::read_dtr()
Ring Indicator: SerialPort::read_ri()
Sadly there is no simple way to wait for these signals to change. So periodic polling is the best you can do.
The exact use of these signals is also not really standardized, so different devices may use them for different purposes. But I believe Carrier Detect is the most likely one for your use case.
Be aware that the CTS and DTR signals are also used for hardware flow control. So one of these signals going low could indicate a temporary situation where the device is unwilling to accept more data or doesn't have any more data to transmit. This doesn't have to mean that the device is disconnected.
If your device or serial converter does not support a status line for indicating connectivity, the only thing you can do is detect a time-out on a read or write operation.
Thanks for the extensive answer :-)