Skip to content

Instantly share code, notes, and snippets.

@mhauri
Created January 23, 2012 20:55
Show Gist options
  • Save mhauri/1665496 to your computer and use it in GitHub Desktop.
Save mhauri/1665496 to your computer and use it in GitHub Desktop.
ardREST
/*
A REST-style interface for the Arduino Ethernet Board.
Based on RESTduino: https://github.com/jjg/RESTduino
Adapted for the Arduino Ethernet Board
by Marcel Hauri | http://m83.ch | twitter.com/mhauri
*/
#include <SPI.h>
#include <Ethernet.h>
byte mac[] = {0x90, 0xA2, 0xDA, 0x00, 0xEE, 0xAB};
byte ip[] = {192,168,250,4};
EthernetServer server(80);
void setup()
{
Ethernet.begin(mac, ip);
server.begin();
}
#define BUFSIZE 255
void loop()
{
char clientline[BUFSIZE];
int index = 0;
EthernetClient client = server.available();
if (client) {
index = 0;
while (client.connected()) {
if (client.available()) {
char c = client.read();
if(c != '\n' && c != '\r'){
clientline[index] = c;
index++;
if(index >= BUFSIZE)
index = BUFSIZE -1;
continue;
}
String urlString = String(clientline);
String op = urlString.substring(0,urlString.indexOf(' '));
urlString = urlString.substring(urlString.indexOf('/'), urlString.indexOf(' ', urlString.indexOf('/')));
urlString.toCharArray(clientline, BUFSIZE);
char *pin = strtok(clientline,"/");
char *value = strtok(NULL,"/");
char outValue[10] = "MU";
String jsonOut = String();
if(pin != NULL){
if(value != NULL){
int selectedPin = atoi (pin);
pinMode(selectedPin, OUTPUT);
if(strncmp(value, "HIGH", 4) == 0 || strncmp(value, "LOW", 3) == 0){
if(strncmp(value, "HIGH", 4) == 0){
digitalWrite(selectedPin, HIGH);
}
if(strncmp(value, "LOW", 3) == 0){
digitalWrite(selectedPin, LOW);
}
} else {
int selectedValue = atoi(value);
analogWrite(selectedPin, selectedValue);
}
jsonOut += "{\"";
jsonOut += pin;
jsonOut += "\":\"";
jsonOut += value;
jsonOut += "\"}";
client.println("HTTP/1.1 200 OK");
client.println("Content-Type: text/html");
client.println("Access-Control-Allow-Origin: *");
client.println();
client.println(jsonOut);
}
else {
if(pin[0] == 'a' || pin[0] == 'A'){
int selectedPin = pin[1] - '0';
sprintf(outValue,"%d",analogRead(selectedPin));
}
else if(pin[0] != NULL) {
int selectedPin = pin[0] - '0';
pinMode(selectedPin, INPUT);
int inValue = digitalRead(selectedPin);
if(inValue == 0){
sprintf(outValue,"%s","LOW");
}
if(inValue == 1){
sprintf(outValue,"%s","HIGH");
}
}
jsonOut += "{\"";
jsonOut += pin;
jsonOut += "\":\"";
jsonOut += outValue;
jsonOut += "\"}";
client.println("HTTP/1.1 200 OK");
client.println("Content-Type: text/html");
client.println("Access-Control-Allow-Origin: *");
client.println();
client.println(jsonOut);
}
}
else {
// error
client.println("HTTP/1.1 404 Not Found");
client.println("Content-Type: text/html");
client.println();
}
break;
}
}
delay(1);
client.stop();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment