1

This is a little of a newb question but I am trying to write a program in Django which controls an arduino from a django site though a serial connection. As an ardunio has a 'feature' which resets it when a new serial connection is made it means that it can't constantly just send the single command every time the page is loaded. So I am wondering:

I have already written the python program which controls the arduino over the serial port with no problems.

Is it possible to run a python script in the background (i.e. it stays active and keeps the serial connection active) of a django app/site and if so how to communicate with that running process via django so I can have pages with buttons which then pass a value to that background process?

Seen Green
  • 21
  • 1
  • 3

1 Answers1

2

Django-celery is great for background task processing. It sounds like you could just make your arduino code a celery task. That makes things really easy - the task has full access to your django models, and the django process can kick off a task anytime.

Plus celery is a great Swiss Army knife tool that you can use anytime you need something that takes longer than a request and response cycle.

This looked like a good ref to me:

http://www.hiddentao.com/archives/2012/01/27/processing-long-running-django-tasks-using-celery-rabbitmq-supervisord-monit/

I'd probably suggest using redis as a broker these days, b/c you can use redis as your cache too.

Nils
  • 5,612
  • 4
  • 34
  • 37
  • Thanks, this was the route I thought about going down but don't have any experience with celery. As the arduino connection needs to stay as a live process can celery keep a process open and just pass commands to it from the queue? – Seen Green Nov 07 '13 at 03:10
  • Celery runs as a separate process (you run ./manage.py celery or the equivalent). Through django, you add a "task" to the queue (redis, rabbitmq, etc) by calling the task.delay() function. Then one of the celery workers picks up the task when it can, and executes it. For sending serial commands to the arduino, I'd probably call each command a "task". You'll have to experiment a bit with it but IMO it's worth learning celery b/c it's very widely used in django projects. – Nils Nov 07 '13 at 16:00
  • I just re-read your comment. The answer is yes, the celery process could keep the connection open. But actually you could do that part in Django as well. It's not like the django process dies between requests... Maybe you wanted something like http://stackoverflow.com/questions/18013333/django-persistent-api-connections-between-requests ? – Nils Nov 07 '13 at 16:08