#include <ArduinoJson.h>
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <ESP8266WebServer.h>
#define HTTP_REST_PORT 80
#define WIFI_RETRY_DELAY 500
#define MAX_WIFI_INIT_RETRY 50
const char* wifi_ssid = "ssid";
const char* wifi_passwd = "password";
byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};
ESP8266WebServer server(HTTP_REST_PORT);
void handleRoot() {
server.send(200, "text/plain", "hello from esp8266!\n\n go to /json or /get to request value.");
}
void handleJson(){
// Allocate a temporary JsonDocument
// Use arduinojson.org/v6/assistant to compute the capacity.
StaticJsonDocument<500> doc;
// Create the "analog" array
JsonArray analogValues = doc.createNestedArray("analog");
for (int pin = 0; pin < 6; pin++) {
// Read the analog input
int value = analogRead(pin);
// Add the value at the end of the array
analogValues.add(value);
}
// Create the "digital" array
JsonArray digitalValues = doc.createNestedArray("digital");
for (int pin = 0; pin < 14; pin++) {
// Read the digital input
int value = digitalRead(pin);
// Add the value at the end of the array
digitalValues.add(value);
}
Serial.print(F("Sending: "));
serializeJson(doc, Serial);
Serial.println();
WiFiClient client;
// Write response headers
client.println(F("HTTP/1.0 200 OK"));
client.println(F("Content-Type: application/json"));
client.println(F("Connection: close"));
client.print(F("Content-Length: "));
client.println(measureJsonPretty(doc));
client.println();
// server.send(200, "application/json", measureJsonPretty(doc));
// Write JSON document
serializeJsonPretty(doc, client);
Serial.println(measureJsonPretty(doc));
// Disconnect
client.stop();
}
void setup() {
// Initialize serial port
Serial.begin(9600);
while (!Serial) continue;
if (init_wifi() == WL_CONNECTED) {
Serial.print("Connetted to ");
Serial.print(wifi_ssid);
Serial.print("--- IP: ");
Serial.println(WiFi.localIP());
}
else {
Serial.print("Error connecting to: ");
Serial.println(wifi_ssid);
}
server.on("/", handleRoot);
server.on("/json", handleJson);
// Start to listen
server.begin();
Serial.println("HTTP server started");
}
void loop() {
//webserver
server.handleClient();
}
int init_wifi() {
int retries = 0;
Serial.println("Connecting to WiFi AP..........");
WiFi.mode(WIFI_STA);
WiFi.begin(wifi_ssid, wifi_passwd);
// check the status of WiFi connection to be WL_CONNECTED
while ((WiFi.status() != WL_CONNECTED) && (retries < MAX_WIFI_INIT_RETRY)) {
retries++;
delay(WIFI_RETRY_DELAY);
Serial.print("#");
}
return WiFi.status(); // return the WiFi connection status
}
I have written this code above trying make it work with ArduinoJson 6. but when I try to access http://ip_addess/json url I get nothing.
I suppose client should work fine with how I have implemented but this doesn't seems to be working.
:o