Moving the Where Clock from a web browser

Posted in Posted on 2012-12-27 15:39

Moving the Where Clock from a web browser

Now I’ve got a web server and I’ve got code to control the stepper motor, let’s put them together and control the stepper motor from a web browser! Here’s the new code: clockServer.py.

#!/usr/bin/env python

# This code is written by Stephen C Phillips.
# It is in the public domain, so you can do what you like with it
# but a link to http://scphillips.com would be nice.

import socket
import re
import RPi.GPIO as GPIO
from move import Motor

# Set up stepper-motor:
GPIO.setmode(GPIO.BOARD)
motor = Motor([18,22,24,26])
motor.rpm = 5

# Standard socket stuff:
host = '' # do we need socket.gethostname() ?
port = 8080
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind((host, port))
sock.listen(1) # don't queue up any requests

# Loop forever, listening for requests:
while True:
    print "Waiting..."
    csock, caddr = sock.accept()
    print "Connection from: " + `caddr`
    req = csock.recv(1024) # get the request, 1kB max
    req = req.split("\n")[0]
    print "Request: " + req
    # Look in the first line of the request for a move command
    # A move command should be e.g. 'http://server/move?a=90'
    match = re.match('GET /move\?a=(\d+)\sHTTP/1', req)
    if match:
        angle = int(match.group(1))
        print "Angle: " + `angle`
        csock.sendall("HTTP/1.0 200 OK\r\n")
        print "Moving motor..."
        motor.move_to(angle)
    else:
        # If there was no recognised command then return a 404 (page not found)
        print "Returning 404"
        csock.sendall("HTTP/1.0 404 Not Found\r\n")
    csock.close()
    print "--------"

This is pretty much the same as the little web server from the last post, but this time instead of returning a web page when we’re asked to move the motor we just return a 200 code and actually move the motor (lines 36-40). This is very nearly all in place now - I just need to get the phone to call the web server at appropriate moments.

Till then, here’s a little video:

Comments

Comments powered by Disqus