#include <SPI.h>
#include <Ethernet.h>
byte mac[] = {
// first byte DE, remaining bytes decided by d20 roll
0xDE, 0xB2, 0x77, 0xA5, 0x21, 0x48
};
IPAddress ip(10, 1, 1, 21);
EthernetServer server(80);
void setup() {
Ethernet.begin(mac, ip);
server.begin();
}
const int MAXLN = 256;
char ln[MAXLN + 1];
int contentLength;
boolean readLine(EthernetClient &client) {
int i = 0;
boolean cr = false;
for (;;) {
if (!client.connected()) return false;
if (!client.available()) continue;
char c = client.read();
switch (c) {
case '\r':
if (cr) {
// should never happen
if (i < MAXLN) ln[i++] = '\r';
}
cr = true;
break;
case '\n':
if (cr) {
// there's always room for the trailing NUL
ln[i++] = '\0';
return true;
}
// else fall through, treat \n like a regular character
// should never happen
default:
if (cr) {
// should never happen
if (i < MAXLN) ln[i++] = '\r';
cr = false;
}
if (i < MAXLN) ln[i++] = c;
break;
}
}
}
boolean readRequestHeader(EthernetClient &client) {
if(!readLine(client)) return false; // read the http request line
contentLength = -1; // initialize
// we are assuming http 1.1. Read lines until we get a blank line
do {
if(!readLine(client)) return false; // read a header
// pull out Content-Length, for example
if(strncmp(ln, "Content-Length: ", 16) == 0) {
contentLength = atoi(ln+16);
}
}
while (strlen(ln) > 0);
return true;
}
void loop() {
// is someone making a request?
EthernetClient client = server.available();
if (!client) return;
if(!readRequestHeader(client)) {
client.stop();
return;
}
client.println("HTTP/1.1 200 OK");
client.println("Content-Type: application/json");
client.println("Connection: close");
// this is the CORS header. Yery important. Google CORS.
client.println("Access-Control-Allow-Origin: *");
client.println();
client.print("{\"analogInput\":[");
for (int analogChannel = 0; analogChannel < 6; analogChannel++) {
if(analogChannel>0) client.print(',');
int sensorReading = analogRead(analogChannel);
client.print(sensorReading);
}
client.println("]}");
// give the web browser time to receive the data
delay(1);
// close the connection:
client.stop();
}