Skip to content

Instantly share code, notes, and snippets.

@rob-smallshire
Created November 17, 2012 20:01
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rob-smallshire/4099513 to your computer and use it in GitHub Desktop.
Save rob-smallshire/4099513 to your computer and use it in GitHub Desktop.
Arduino Web Service and Python Client for a Digital Thermometer with LED display
"""
A Python web service client which GETs temperatures over a web service API
from an Arduino based server and PUTs the status of LEDs back to the Arduino
to provide a visual temperature indication.
The intent of this system is to demonstrate how control logic can be moved
to remote systems which communicate with the Arduino over the network.
Pass the base url of the server e.g. "http://192.168.1.101" as the
only command line argument.
"""
from __future__ import print_function
import sys
import time
# Requests: HTTP for Humans
# http://docs.python-requests.org/en/latest/
import requests
def get_temperature(server_url):
url = server_url + '/thermometer1/celsius'
r = requests.get(url)
if not r.ok:
raise RuntimeError(r.text)
return float(r.text)
def set_color(server_url, color):
url = server_url + '/color'
r = requests.put(url, color)
if not r.ok:
raise RuntimeError(r.text)
def control(server_url):
while True:
t_celsius = get_temperature(server_url)
print(t_celsius)
if t_celsius < 20.0:
set_color(server_url, "green")
elif 20.0 <= t_celsius < 25.0:
set_color(server_url, "yellow")
elif 25.0 <= t_celsius:
set_color(server_url, "red")
else:
pass
time.sleep(1)
def main(argv=None):
if argv is None:
argv = sys.argv
server_url = argv[1]
control(server_url)
if __name__ == '__main__':
sys.exit(main())
// An Arduino program for continually reading the temperature from
// a Dallas DS18B20 digital thermometer and presenting the results
// over a simple web service API. Further web serices allow the
// control turning on or off red, yellow or green LEDs to
// indicate the temperature range.
//
// The intent of this program is to show that complex (or in this
// case simple) control logic can be moved off the Arduino onto
// into more capable or more easily debugguable environments.
// Built-in Arduino Libraries
#include <SPI.h>
#include <Ethernet.h>
// OneWire 2 library (an improved version of the original OneWire)
// http://www.pjrc.com/teensy/td_libs_OneWire.html
#include <OneWire.h>
// Dallas Temperature Control library from
// http://milesburton.com/Dallas_Temperature_Control_Library
#include <DallasTemperature.h>
// Configure Ethernet server on port 80
byte mac[] = { 0x90, 0xA2, 0xDA, 0x0D, 0x35, 0x4C };
IPAddress ip(192,168,1, 101);
EthernetServer server(80);
// Configure DS18B20 thermometer on pin 7
const int ONE_WIRE_BUS = 7;
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);
DeviceAddress THERMOMETER_1 = { 0x28, 0xEA, 0x10, 0x72, 0x03, 0x00, 0x00, 0xCF };
const int TEMPERATURE_PRECISION = 9; // bits
const float FAULTY_SENSOR = 85.0;
// Configure LED outputs
enum { RED = 4, YELLOW = 5, GREEN = 6 };
void setup() {
// Bring up serial
Serial.begin(9600);
while (!Serial) {
// wait
}
// Bring up Ethernet web server
Ethernet.begin(mac, ip);
server.begin();
Serial.print("server is at ");
Serial.println(Ethernet.localIP());
// Start up the one wire bus
sensors.begin();
Serial.print("Locating devices...");
Serial.print("Found ");
Serial.print(sensors.getDeviceCount(), DEC);
Serial.println(" devices.");
sensors.setResolution(THERMOMETER_1, TEMPERATURE_PRECISION);
// LEDs
pinMode(RED, OUTPUT);
pinMode(YELLOW, OUTPUT);
pinMode(GREEN, OUTPUT);
}
const int HTTP_BUFFER_SIZE = 255;
/**
* Read a line from the EthernetClient.
*/
String readHttpLine(EthernetClient & client) {
char buffer[HTTP_BUFFER_SIZE + 1];
int index = 0;
while (client.connected()) {
if (client.available()) {
int b = client.read();
if (b == -1) { // no data
break;
}
char c = static_cast<char>(b);
if (c == '\r') { // carriage-return
client.read(); // line-feed
break;
}
if (index >= HTTP_BUFFER_SIZE) {
break;
}
buffer[index] = c;
++index;
}
}
buffer[index] = '\0';
return String(buffer);
}
enum HttpMethod {
HTTP_UNKNOWN,
HTTP_GET,
HTTP_PUT,
HTTP_POST,
};
HttpMethod parseHttpMethod(const String & method_token) {
if (method_token == "GET") return HTTP_GET;
if (method_token == "PUT") return HTTP_PUT;
if (method_token == "POST") return HTTP_POST;
return HTTP_UNKNOWN;
}
void readHttpHeaders(EthernetClient & client, int & content_length, String & content_type) {
while (true) {
String header_line = readHttpLine(client);
Serial.print("HEADER: ");
Serial.println(header_line);
if (header_line.startsWith("Content-Length:")) {
content_length = header_line.substring(15).toInt();
Serial.print("Content length = ");
Serial.println(content_length);
}
else if (header_line.startsWith("Content-Type:")) {
content_type = header_line.substring(13);
Serial.print("Content type = ");
Serial.println(content_type);
}
if (header_line.length() == 0) {
break;
}
}
}
void readHttpContent(EthernetClient& client, int content_length, String& content) {
for (int i = 0; i < content_length; ++i) {
int b = client.read();
if (b == -1) {
break;
}
char c = static_cast<char>(b);
content += c;
}
Serial.print("CONTENT: ");
Serial.println(content);
}
/**
* Simple HTTP parser for GET and PUT requests.
*
* Args:
* client: An EthernetClient
* url: A String out parameter which will contain the URL
* content: A String out parameter which will contain the content
*
* Returns:
* GET or PUT
*/
HttpMethod readHttpRequest(EthernetClient & client, String & url, String & content_type, String & content) {
String request = readHttpLine(client);
int end_method = request.indexOf(' ');
String method_token = request.substring(0, end_method);
Serial.println(method_token);
HttpMethod method = parseHttpMethod(method_token);
int end_url = request.indexOf(' ', end_method + 1);
url = request.substring(end_method + 1, end_url);
Serial.println(url);
int content_length = -1;;
readHttpHeaders(client, content_length, content_type);
readHttpContent(client, content_length, content);
// TODO: Add a check for the Host header - important for compliance with HTTP/1.1
client.flush();
return method;
}
void httpBadRequest(EthernetClient& client, const String & content) {
client.println("HTTP/1.1 400 Bad Request");
client.println("Content-Type: text/plain");
client.print("Content-Length: ");
client.println(content.length());
client.println();
client.print(content);
}
void httpMethodNotAllowed(EthernetClient& client, const String & content) {
client.println("HTTP/1.1 405 Method Not Allowed");
client.println("Content-Type: text/plain");
client.print("Content-Length: ");
client.println(content.length());
client.println();
client.print(content);
}
void httpNotFound(EthernetClient& client, const String & content) {
client.println("HTTP/1.1 404 Not Found");
client.println("Content-Type: text/plain");
client.print("Content-Length: ");
client.println(content.length());
client.println();
client.print(content);
}
void httpGone(EthernetClient& client) {
client.println("HTTP/1.1 410 Gone");
client.print("Content-Length: 0");
client.println();
}
void httpServiceUnavailable(EthernetClient& client, const String & content) {
client.println("HTTP/1.1 503 Service Unavailable");
client.println("Content-Type: text/plain");
client.print("Content-Length: ");
client.println(content.length());
client.println();
client.print(content);
}
template <typename T>
String makeString(T value) {
return String(value);
}
const int DECIMAL_PLACES = 2;
template <>
String makeString(float value) {
char buffer[33];
char* s = dtostrf(value, DECIMAL_PLACES + 2, DECIMAL_PLACES, buffer);
return String(s);
}
template <typename T>
void httpOkScalar(EthernetClient& client, T scalar) {
String response_content = makeString(scalar);
client.println("HTTP/1.1 200 OK");
client.println("Content-Type: text/plain");
client.print("Content-Length: ");
client.println(response_content.length());
client.println();
client.println(response_content);
}
void httpOk(EthernetClient& client) {
client.println("HTTP/1.1 200 OK");
client.println();
}
void handleRootRequest(EthernetClient & client, HttpMethod method, String & content) {
switch (method) {
case HTTP_GET:
httpOkScalar(client, "Arduino temperature service");
break;
default:
httpMethodNotAllowed(client, "This HTTP verb is not allowed");
break;
}
}
void handleColor(EthernetClient & client, HttpMethod method, String & content) {
content.toLowerCase();
switch (method) {
case HTTP_PUT: {
if (content.startsWith("red")) {
digitalWrite(RED, HIGH);
digitalWrite(YELLOW, LOW);
digitalWrite(GREEN, LOW);
}
else if (content.startsWith("yellow")) {
digitalWrite(RED, LOW);
digitalWrite(YELLOW, HIGH);
digitalWrite(GREEN, LOW);
}
else if (content.startsWith("green")) {
digitalWrite(RED, LOW);
digitalWrite(YELLOW, LOW);
digitalWrite(GREEN, HIGH);
}
else {
httpBadRequest(client, "No such color");
return;
}
httpOk(client);
} break;
default:
httpMethodNotAllowed(client, "This HTTP verb is not allowed");
break;
}
}
void handleThermometer1Celsius(EthernetClient & client, HttpMethod method, String & content) {
switch (method) {
case HTTP_GET: {
sensors.requestTemperatures();
float celsius_temperature = sensors.getTempC(THERMOMETER_1);
Serial.print("celsius_temperature = ");
Serial.println(celsius_temperature);
if (celsius_temperature == DEVICE_DISCONNECTED) {
httpServiceUnavailable(client, "Temperature sensor disconnected?");
return;
}
if (celsius_temperature == FAULTY_SENSOR) {
httpServiceUnavailable(client, "Temperature sensor faulty?");
return;
}
httpOkScalar(client, celsius_temperature);
} break;
default: {
httpMethodNotAllowed(client, "This HTTP verb is not allowed");
} break;
}
}
void handleThermometer1Fahrenheit(EthernetClient & client, HttpMethod method, String & content) {
switch (method) {
case HTTP_GET: {
sensors.requestTemperatures();
float celsius_temperature = sensors.getTempC(THERMOMETER_1);
Serial.print("celsius_temperature = ");
Serial.println(celsius_temperature);
if (celsius_temperature == DEVICE_DISCONNECTED) {
httpServiceUnavailable(client, "Temperature sensor disconnected?");
return;
}
if (celsius_temperature == FAULTY_SENSOR) {
httpServiceUnavailable(client, "Temperature sensor faulty?");
return;
}
float fahrenheit_temperature = DallasTemperature::toFahrenheit(celsius_temperature);
httpOkScalar(client, fahrenheit_temperature);
} break;
default: {
httpMethodNotAllowed(client, "This HTTP verb is not allowed");
} break;
}
}
void handleThermometer1Resolution(EthernetClient & client, HttpMethod method, String & content) {
switch (method) {
case HTTP_GET: {
int resolution = sensors.getResolution(THERMOMETER_1);
httpOkScalar(client, resolution);
} break;
case HTTP_PUT: {
int resolution = content.toInt();
if (resolution < 9 || resolution > 12) {
httpBadRequest(client, "Resolution out of range");
return;
}
sensors.setResolution(THERMOMETER_1, resolution);
httpOk(client);
} break;
default: {
httpMethodNotAllowed(client, "This HTTP verb is not allowed");
} break;
}
}
void handleRequest(EthernetClient & client, HttpMethod method, String & url, String & content) {
if (url == "/") { handleRootRequest(client, method, content); }
else if (url == "/thermometer1/celsius") { handleThermometer1Celsius(client, method, content); }
else if (url == "/thermometer1/fahrenheit") { handleThermometer1Fahrenheit(client, method, content); }
else if (url == "/thermometer1/resolution") { handleThermometer1Resolution(client, method, content); }
else if (url == "/color") { handleColor(client, method, content); }
else if (url == "/favicon.ico") { httpGone(client); }
else { httpNotFound(client, "No resource at this URL"); }
}
void loop()
{
// listen for incoming clients
EthernetClient client = server.available();
if (client) {
String url;
String content_type;
String content;
HttpMethod method = readHttpRequest(client, /*out*/ url, /*out*/ content_type, /*out*/ content);
handleRequest(client, method, url, content);
}
delay(1); // give the client time to receive the data
client.stop();
}
int main(void) {
init();
setup();
while(true) {
loop();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment