[Answer]-Maintain a persistent Serial connection that dajaxice calls can use?

1πŸ‘

βœ…

A middleware might be an option if your runtime environment is simple.

// middleware/__init__.py
class ArduinoMiddleware:

    def __init__(self):
        self.serial = serial.Serial('/dev/ttyUSB0', 9600)
        time.sleep(1.5)

    def process_request(self, request):
        request.serialWrite = self.serialWrite

    def serialWrite(self, msg):
        try:
            self.serial.write(msg)
            return "Running Animation"
        except:
            return "Failed to communicate with cube"

// ajax.py
@dajaxice_register
def animate(request, data):
    msg = request.serialWrite(str(data))
    return simplejson.dumps({'message':msg})

// settings.py
...
MIDDLEWARE_CLASSES = (
  'middleware.ArduinoMiddleware',
  ...
)

Untested, and might require locking if you’re running in a multithreaded environment (like manage.py runserver).

πŸ‘€robertklep

Leave a comment