Now I can control the stepper-motor from Python I need to be able to tell the Raspberry Pi to move the motor from my phone so that, for instance, when I get to work it can tell the motor to move the indicator hand to point to “Work”.
To do this, the easiest way seem to me to be using a web server on the Pi. I want to make it so that if you GET the URL http://<raspberry.server>:8080/move?a=90 then it will move the hand to 90 degrees. This normally requires a web server and a CGI script but it seemed overkill to install Apache or even something lighter-weight such as lighttpd or nginx for such a simple task so I’ve written my own: much more interesting!
This is about as simple as a web server gets. It sets up a server socket to listen on using port 8080 and doesn’t queue up any requests (it’s not going to get many…). When a connection is made from the client (e.g. a web browser) the sock.accept() line (19) creates a client socket to communicate with the client on. We then just read at most 1kB of data from the client, which is the HTTP headers saying what the client wants and using a regular expression (line 25) we see if it is a “move” request and pull out the angle. If it was a move request then we print the angle to the console and return a simple web page by using csock.sendall on line 29. Otherwise we return a 404 error (line 45). Finally we close the client socket and loop round to the top again to wait for another connection.
If I run this script (e.g. python server.py) and go to the URL http://<server>:8080/move?a=20 then I see this on the console of the Pi:
So we first get a connection from IP address 192.168.1.129 (my address on my home network) asking for “/move?a=20” using HTTP version 1.1. It then says that it wants that “page” from “Host: raspberry1.scphillips.com:8080”. This is in case my web browser is talking to a proxy - the proxy needs to know where to get the page from (however, in this case there is no proxy). There are then a load of other headers that describe what the client is and how it would like information sent to it (language, character set, etc).
The web server ignores all but the first line of the headers, spots that it’s a move request and prints out the angle to the console. Immediately we then get a second request from the web browser asking for the “favicon.ico” - this just happens automatically. The favicon is the little icon you see in the address bar of most websites. Web browsers request them a lot. Our little web server just ignores this request and sends a 404 (page not found) so the web browser is happy.
On the web browser we get a page that says “Boo!”.
Next, this needs linking up with the Motor class from the last post.
Comments
Comments powered by Disqus