JanezStupar
JanezStupar

Reputation: 358

How to find out if serial port is closed?

I am working on a multi threaded server application for processing serial/USB ports.

The issue is that if a cable gets unplugged, pyserial keeps reporting that the port is open and available. When reading I only receive Empty exceptions (due to read timeout).

How do I find out that a port has been disconnected so that I can handle this case?

Edit: OS is Ubuntu 12.04

Edit 2: Clarification - I am connecting to serial port devices via Serial to USB connector, thus the device being disconnected is an USB device.

Upvotes: 1

Views: 2782

Answers (1)

DThought
DThought

Reputation: 1314

A Serial port has no real concept of "cable connected" or not connected.

Depending on the equipment you are using you could try to poll the DSR or CTS lines, and decide there is no device connected when those stay low over a certain time.

From wikipedia:

DTR and DSR are usually on all the time and, per the RS-232 standard and its successors, are used to signal from each end that the other equipment is actually present and powered-up

So if you've got a conforming device, the DSR line could be the thing you need.

Edit: As you seem to use an USB2Serial converter, you can try to check whether the device node still exists - you don't need to try to open it.

so os.path.exists(devNode) could suffice.

Upvotes: 3

Related Questions