Storing photocell data in Django

This demo covers reading a photocell from a Raspberry Pi using django. We setup a 1 minute cron job to read the photocell and store the result in a django model. This allows us to track changes in light intensity throught the day.


Prerequisites

This tutorial uses a photocell and a capacitor, you will need both.

If you don't have RPi.GPIO installed, you can install it with this command:

$ sudo pip install RPi.GPIO

microfarm/sensors/models.py:

from django.db import models

class LightSensorReading(models.Model):
        reading                 = models.CharField(max_length=20)
        time                    = models.DateTimeField(auto_now_add=True)

        def __unicode__(self):
                return self.reading

class LightSensor(models.Model):
        name                    = models.CharField(max_length=200)
        slug                    = models.SlugField(unique=True)
        gpio_pin                = models.PositiveIntegerField(default=0)
        readings                = models.ManyToManyField(LightSensorReading, null=True, blank=True)

        def __unicode__(self):
                return self.name

/home/pi/lightsensor.py:

#!/usr/bin/python
import sys
import RPi.GPIO as GPIO, time

GPIO.setmode(GPIO.BOARD)

def RCtime(RCpin):
        reading = 0
        GPIO.setup(RCpin, GPIO.OUT)
        GPIO.output(RCpin, GPIO.LOW)
        time.sleep(0.1)
        GPIO.setup(RCpin, GPIO.IN)
        while(GPIO.input(RCpin) == GPIO.LOW):
                reading += 1
        return reading

print RCtime(int(sys.argv[1]))

microfarm/sensors/services.py:

import subprocess
from sensors.models import LightSensorReading, LightSensor

def ReadLightSensors():
        for sensor in LightSensor.objects.all():
                reading = subprocess.check_output(['sudo', '/home/pi/lightsensor.py', str(sensor.gpio_pin)])
                newreading = LightSensorReading(reading=reading)
                newreading.save()
                sensor.readings.add(newreading)
                sensor.save()
        return True

microfarm/cronhandler/views.py:

from django.http import HttpResponse
from sensors.services import ReadLightSensors

def OneMinuteCron(request):
        ReadLightSensors()
        return HttpResponse('')

add this to urls.py:

url(r'^oneminutecron/$', 'cronhandler.views.OneMinuteCron'),

microfarm/sensors/admin.py:

from django.contrib import admin
from sensors.models import LightSensor, LightSensorReading

admin.site.register(LightSensor)
admin.site.register(LightSensorReading)

add the cron job to /etc/crontab/

* * * * * pi curl -s http://127.0.0.1:8000/oneminutecron/