Tuesday, January 15, 2013

Raspberry Pi GPIO web interface using webpy

Finally made a web-interface for the GPIO on my Raspberry Pi that controlls the lights in my living room.
The script uses webpy, and starts hosting a webpage on port 8080 that listens for visitors and parameters:
If i open the page:
http://192.168.1.6:8080/?turn=on
Lights will be switched on.
And this next one switches them off again:
http://192.168.1.6:8080/?turn=off

I put the source together after reading this guide to webpy:
http://cloud101.eu/blog/2012/04/24/python-for-the-web-with-webpy/#more-

webpy is installed easy from apt-get:
       sudo apt-get install python-webpy

Here is the script:

#!/usr/bin/env python
# first line points to path for python

# we import the webpy library
import web

import RPi.GPIO as GPIO

#dont bug me with warnings
GPIO.setwarnings(False)

# to use Raspberry Pi board pin numbers
GPIO.setmode(GPIO.BOARD)

# set up GPIO output channels
GPIO.setup(18, GPIO.OUT)
GPIO.setup(16, GPIO.OUT)

urls = ('/','root')
app = web.application(urls,globals())
 
class root:
 
    def __init__(self):
        self.hello = "snakes on a pie!"
 
    def GET(self):
        getInput = web.input(turn="")
        kommando = str(getInput.turn)
        if kommando == "on":
            #    set RPi board pins high
            GPIO.output(18, GPIO.HIGH)
            GPIO.output(16, GPIO.HIGH)
            return "Lights on"
        if kommando == "off":
            #    set RPi board pins low
            GPIO.output(18, GPIO.LOW)
            GPIO.output(16, GPIO.LOW)
            return "Lights off"
 
if __name__ == "__main__":
        app.run()

2 comments: