Serial connections and threads in a GUI

user at domain.invalid user at domain.invalid
Tue Sep 29 23:08:35 EDT 2009


Aaron Hoover wrote:
> I have a wx-based GUI application that I'd like to have read "streaming"
> data from a serial port and plot that data using matplotlib and a figure
> canvas. It's a robotic application where the workflow goes something
> like this:
> 
> 1) Connect to robot
> 2) Configure robot settings
> 3) Command robot to do something for time, t
>     - While robot does something, read sensor data and plot
> 4) End of t seconds, resume at (2)
> 
> I have the application reading from the serial port in a separate
> thread, but my problem is this - I'd like the user to be able to write
> to the serial port by interacting with the GUI between runs. However,
> the infinite loop running inside the thread responsible for receiving
> data has exclusive access to the serial connection object.
> 
> Because of how the application works, I know that I won't need to write
> to the serial port when I'm in the middle of receiving data, so that
> simplifies things somewhat. But, how can I allow the thread access to
> the connection for reading, but then have it give up control over the
> connection when it's done so the main GUI thread can access the
> connection again for writing?
> 
> Currently, I have the thread's run() method exit when it's done
> receiving data. But, that means that I can only receive data again using
> the same thread by calling run(), blocking the main GUI thread from
> updating the plot until it completes.
> 
> This is my first go at using threads in Python, so I'm sure there's a
> straightforward way to do this that I'm just missing. At any rate,
> thanks in advance for your patience and assistance.
> 
> 
> Thanks,
> Aaron
Use a few queue objects (see the queue module). Your serial port thread
can have an rx and a tx queue. Your gui program just checks the rx queue
whenever it wants and puts data into the tx queue whenever it wants, and
the queue objects do all the worrying about synchronizing and thread
safety and such. Works like magic!

Paul Probert



More information about the Python-list mailing list