Question

I would like to be able to use a USB device from several applications (for instance I run a Flask web application), making sure only one uses it at a time.

In my case I am using a relay to open / close a door. The door takes about 20 seconds to open. During that time the relay should not be activated, because this would lock the door in the middle.

Thanks in advance!

Was it helpful?

Solution 2

You have a number of possible solutions.

The posix_ipc or sysv_ipc Python modules provide a named semaphore class. You can initialize a semaphore to 1 and have all your web processes acquire the semaphore while they send a command to the USB device.

A somewhat similar mechanism can be achieved using a file lock, maybe using fcntl.lockf.

Another completely different approach could be to put a new process between your web server processes and the USB API. This process exposes an API that receives requests from the web server workers and implicitly serializes those into the USB device by means of being a single threaded process.

OTHER TIPS

Not exactly an answer to your question, but maybe another idea about how to tackle this with out using globals.

Why don't you write a small program for controlling your USB device. This script runs once (one instance) on your server and takes care of communicating with the device in the manner you need. It also takes care of concurrency.

Now communicate from your web application via pipes, sockets, whatever with this script, send commands to it and receive results from it.

You could add a variabale to your config (make sure its uppercase)

app.config['YOUR_GLOBAL'] = 'your global'

http://flask.pocoo.org/docs/config/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top