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
-
can help pySerial: opening multiple ports at once,http://stackoverflow.com/questions/6603475/pyserial-opening-multiple-ports-at-once – kiriloff Apr 27 '13 at 19:12
-
the problem is not opening them, but waiting on read events on them in parallel – GabiMe Apr 27 '13 at 19:30
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 open the Serial
object in non-blocking (read) mode (by passing timeout=0
) 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 mind 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 in_waiting
property. Poll all your serial ports regularly reading in_waiting
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.

- 132,704
- 33
- 254
- 328

- 52,955
- 12
- 126
- 132
-
Unfortunatly I need it under windows, so niether fileno() nor nonblocking() is available – GabiMe Apr 28 '13 at 00:38
-
1Have added a section about Windows for you. Suggest you write OS in the question next time as it is kind of important for something so platform dependent as serial ports! – Nick Craig-Wood Apr 28 '13 at 11:35