Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pySerial - Is there a way to select on multiple ports at once?

Tags:

python

windows

I am developing app that need to communicate with many serial ports. I havnt found a way to do this without using thread per port. Is there a way to do this with single thread?something like select or poll on multiple ports at once? I am using pyserial 2.6

like image 961
GabiMe Avatar asked Apr 27 '13 19:04

GabiMe


People also ask

Is pySerial full duplex?

Yes serial port hardware is full duplex. Yes, you can use threads to do Rx and Tx at the same time. Alternatively, you can use a single thread loop that does reads with a short timeout and alternates between reading and writing.

Is serial the same as pySerial?

pySerial includes a small console based terminal program called serial. tools.

What is Miniterm?

miniterm. This is a console application that provides a small terminal application. Miniterm itself does not implement any terminal features such as VT102 compatibility. However it may inherit these features from the terminal it is run.

How many ports are in a serial?

A serial port on a PC is a male 9-pin connector (DE-9 D-sub). Early PCs had two 9-pin connectors or one 9-pin and one 25-pin (DB-25). On a PC, serial ports are called "COM ports," identified as COM1, COM2, etc.


1 Answers

I'm assuming you are using PySerial on a unix like platform...

Since PySerial objects implement fileno() to get the underlying file descriptor you can pass them straight into select which will allow you to do deal with multiple PySerial objects at once.

Another alternative would be to set nonblocking() and deal with the fact that your reads and writes may return errno.EWOULDBLOCK errors. This is probably the simplest method.

A third alternative would be to use twisted serial ports if you don't ming getting your head round the way twisted does things.

Update

For Windows, pretty much your only alternative other than using threads is to use the inWaiting() method. Poll all your serial ports regularly reading inWaiting() from them. If there is stuff waiting then you can read that and only that many bytes without blocking.

Unfortunately pyserial doesn't have a "how much free space is there in the output buffer" method which means that when you write to serial ports you are at risk of blocking. If you are implementing a typical serial port protocol the default buffer sizes of a few kilobytes will ensure that this isn't normally a problem.

like image 131
Nick Craig-Wood Avatar answered Oct 15 '22 23:10

Nick Craig-Wood