Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python web app - synchronized serial access

I'm a java intermediate developer, python newbie and web-services uber newbie. As a learning experience, I'm trying to realize a RESTful web service in python to remotely control a simple on/off light via an RS232-over-USB relay board. I already figured out the basics of web.py & pyserial libraries. The board I am using takes an ascii byte as input to turn relays on/off and provides an ascii byte as a feedback for every input sent. Single requests are answered in the correct way but, when multiple requests are issued by web.py delegated class, feedbacks sometimes get mixed up. I'm guessing this is a thread synchronization problem. What's the best way to synchronize write/read access to the serial port with pyserial in order to correctly send feedbacks to the appropriate web.py-born thread? Could a solution such as the following one be considered as correct?

from threading import RLock
import serial   # pyserial library

lock = RLock()
ser = serial.Serial("/dev/ttyACM0", 9600, 1)

def serialOut(self, string):
    lock.acquire()
    data = ''
    try:
        ser.open()
        ser.write(string)
        data = ser.readall()
        ser.flushOutput()
    finally:
        lock.release()
        return data
like image 890
Jacoscaz Avatar asked Jul 18 '26 22:07

Jacoscaz


1 Answers

Your solution seems OK if your web app is run under the same python instance (running integrated in web.py dev webserver).

But if you want to run it under multiple Python processes, then you have to put the lock on the file itself using fcntl module.

like image 199
Andrey Kuzmin Avatar answered Jul 21 '26 11:07

Andrey Kuzmin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!