From e2016cf65b62a69688d6bb976f63db37f686d501 Mon Sep 17 00:00:00 2001 From: Benoit Blanchon Date: Sat, 10 Jan 2015 15:25:27 +0100 Subject: [PATCH] Added an example with EthernetServer --- examples/JsonServer/JsonServer.ino | 74 ++++++++++++++++++++++++++++++ 1 file changed, 74 insertions(+) create mode 100644 examples/JsonServer/JsonServer.ino diff --git a/examples/JsonServer/JsonServer.ino b/examples/JsonServer/JsonServer.ino new file mode 100644 index 00000000..d3fec3ec --- /dev/null +++ b/examples/JsonServer/JsonServer.ino @@ -0,0 +1,74 @@ +// Sample Arduino Json Web Server +// Created by Benoit Blanchon. +// Heavily inspired by "Web Server" from David A. Mellis and Tom Igoe + +#include +#include +#include + +byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED}; +IPAddress ip(192, 168, 0, 177); +EthernetServer server(80); + +bool readRequest(EthernetClient& client) { + bool currentLineIsBlank = true; + while (client.connected()) { + if (client.available()) { + char c = client.read(); + if (c == '\n' && currentLineIsBlank) { + return true; + } else if (c == '\n') { + currentLineIsBlank = true; + } else if (c != '\r') { + currentLineIsBlank = false; + } + } + } + return false; +} + +JsonObject& prepareResponse(JsonBuffer& jsonBuffer) { + JsonObject& root = jsonBuffer.createObject(); + + JsonArray& analogValues = root.createNestedArray("analog"); + for (int pin = 0; pin < 6; pin++) { + int value = analogRead(pin); + analogValues.add(value); + } + + JsonArray& digitalValues = root.createNestedArray("digital"); + for (int pin = 0; pin < 14; pin++) { + int value = digitalRead(pin); + digitalValues.add(value); + } + + return root; +} + +void writeResponse(EthernetClient& client, JsonObject& json) { + client.println("HTTP/1.1 200 OK"); + client.println("Content-Type: application/json"); + client.println("Connection: close"); + client.println(); + + json.prettyPrintTo(client); +} + +void setup() { + Ethernet.begin(mac, ip); + server.begin(); +} + +void loop() { + EthernetClient client = server.available(); + if (client) { + bool success = readRequest(client); + if (success) { + StaticJsonBuffer<500> jsonBuffer; + JsonObject& json = prepareResponse(jsonBuffer); + writeResponse(client, json); + } + delay(1); + client.stop(); + } +}