public
Created

Arduino Web Service and Python Client for a Digital Thermometer with LED display

  • Download Gist
client_controller.py
Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
"""
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())
service.cpp
C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419
// 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();
}
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.