Question

I have a basic django setup running and am currently implementing dajaxice calls to write some data to the serial connection (a RainbowDuino is on the other end).

The following code works however when you establish a serial connection to the Arduino you must wait before writing data to it as the Arduino resets.

from django.utils import simplejson
from dajaxice.decorators import dajaxice_register
import time, serial

def serialWrite(msg):
    try:
        ser = serial.Serial('/dev/ttyUSB0', 9600)
        time.sleep(1.5) #wait for arduino to reset
        ser.write(msg)
        return "Running Animation"
    except:
        return "Failed to communicate with cube"

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

I'm new to all things python and django so I'm unsure how to maintain a persistent object that could use the serial connection in this environment. From my own reading and testing I can see that the dajaxice registered method is only called on receipt of the corresponding button click.

Is this a case where I could potentially use my app's view to instantiate a serial connection, if so how could I share the connection with a dajaxice call?

Was it helpful?

Solution

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).

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