Arduino to Xively JSON Error 400 The Feed is Empty - json

I am trying to upload data from an Aurdino to Xively. I can connect to Xively and even get the PUT request showing up on the Xively Request Log.
But i get the error 400 Bad Request
{"title":"JSON Parser Error","errors":"The feed is empty"}
I think the problem may be here
data = data + "\n" + "{\"version\":\"1.0.0\",\"datastreams\" : [ {\"id\" : \"Reading\",\"current_value\" : \"" + String(reading) + "\"}]}";
Any tips would be much appreciated.
Cheers and thanks
///////////////////////
// Saving to Xively ///
///////////////////////
int savetoxively(String reading, char* feedID) {
//getting the IP address for the xively website.
ip = 0;
Serial.print(WEBSITE); Serial.print(F(" -> "));
while (ip == 0) {
if (! cc3000.getHostByName(WEBSITE, &ip)) {
Serial.println(F("Couldn't resolve!"));
}
delay(500);
}
cc3000.printIPdotsRev(ip);
// formatting the data for the xively website.
int length = 0;
String data = ""; //the problem might be here, the serial monitor says the length is 0. should have something ing it.
data = data + "\n" + "{\"version\":\"1.0.0\",\"datastreams\" : [ {\"id\" : \"Reading\",\"current_value\" : \"" + String(reading) + "\"}]}";
length = data.length();
Serial.print("Data length");
Serial.println(length);
Serial.println();
// Print request for debug purposes
Serial.print("PUT /v2/feeds/");
Serial.print(feedID); //serial monitor shows the correct feedID here
Serial.println(".json HTTP/1.1");
Serial.println("Host: api.xively.com");
Serial.print("X-ApiKey: ");
Serial.println(API_key); //serial monitor shows the correct API key
Serial.print("Content-Length: ");
Serial.println(length, DEC);
Serial.print("Connection: close");
Serial.println();
Serial.print("Reading: ");
Serial.println(reading); //serial monitor shows the correct reading
Serial.println();
// connecting with the xively server
Adafruit_CC3000_Client client = cc3000.connectTCP(ip, 80);
if (client.connected()) {
Serial.println("Connected!");
Serial.print("feedID: ");
Serial.println(feedID);
client.print("PUT /v2/feeds/");
client.print(feedID);
client.println(".json HTTP/1.1");
client.println("Host: api.xively.com");
client.print("X-ApiKey: ");
client.println(API_key);
client.print("User-Agent: ");
client.println(USERAGENT);
client.print("Content-Length: ");
client.println(length);
client.print("Connection: close");
client.println();
client.print(data);
client.println();
Serial.println("data sent");
}
while (client.connected()) { //printing connection status
while (client.available()) { //HTTP/1.1 400 Bad Request
char c = client.read(); //Date: Sat, 15 Mar 2014 19:33:38 GMT
Serial.print(c); //Content-Type: application/json; charset=utf-8
//Content-Length: 58
//Connection: close
//X-Request-Id: f48494a26daa2a5f0979dc4460264d233103f0f5
//{"title":"JSON Parser Error","errors":"The feed is empty"}
}
}
client.close(); // closes the connection with xively
cc3000.disconnect(); //disconnects the Wifi network
return 1;
}

Related

How to take an Input integer from HTM? - Arduino / NodeMCU ESP32

Hi im currently doing Servo NodeMCU controlling. my plan is to create an Input Box where i can type, then whatever number i type will be use as servo angle using Webserver or 194.168.4.1 or so on. (ex: i type 90, servo angle will be 90) the problem i si do not know how to get it. here is the code:
#include<Servo.h>
Servo ServoPin;
int angle = 0;
#include <WiFi.h>
#include <WiFiClient.h>
#include <WiFiAP.h>
#define ServoPin 34; // Set the GPIO pin where you connected your test LED or comment this line out if your dev board has a built-in LED
// Set these to your desired credentials.
const char *ssid = "XXXXXX";
const char *password = "XXXXXX";
WiFiServer server(80);
void setup() {
Serial.begin(115200);
Serial.println();
Serial.println("Configuring access point...");
pinMode(ServoPin,OUTPUT);
// You can remove the password parameter if you want the AP to be open.
WiFi.softAP(ssid, password);
IPAddress myIP = WiFi.softAPIP();
Serial.print("AP IP address: ");
Serial.println(myIP);
server.begin();
Serial.println("Server started");
}
void loop() {
WiFiClient client = server.available(); // listen for incoming clients
if (client) { // if you get a client,
Serial.println("New Client."); // print a message out the serial port
String currentLine = ""; // make a String to hold incoming data from the client
while (client.connected()) { // loop while the client's connected
if (client.available()) { // if there's bytes to read from the client,
char c = client.read(); // read a byte, then
Serial.write(c); // print it out the serial monitor
if (c == '\n') { // if the byte is a newline character
// if the current line is blank, you got two newline characters in a row.
// that's the end of the client HTTP request, so send a response:
if (currentLine.length() == 0) {
// HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK)
// and a content-type so the client knows what's coming, then a blank line:
client.println("HTTP/1.1 200 OK");
client.println("Content-type:text/html");
client.println();
// the content of the HTTP response follows the header:
client.print("<!DOCTYPE html>");
client.print("<html>");
client.print("<body>");
client.print("<p>Change the text of the text field, and then click the button below.</p>"); //
client.print("INPUT NUMBER: <input type='number' id='servo'>"); //in this area, I WILL TYPE number 0-255.
client.print("<button type='button' '>Go</button>");
ServoPin.attach(number); //the area where i will assign the servo to the angle i type.
// break out of the while loop:
break;
} else { // if you got a newline, then clear currentLine:
currentLine = "";
}
} else if (c != '\r') { // if you got anything else but a carriage return character,
currentLine += c; // add it to the end of the currentLine
}
}
}
// close the connection:
client.stop();
Serial.println("Client Disconnected.");
}
}
So as you can see in client.print"INPUT NUMBER.... so on line, that is the place where my code will design an input box. the problem is it is inside a " " or double quotation mark. i wonder what should i do to get the 'number' input then use it on ServoPin.attach(number);
im very beginner on HTML(zero actually) because i dont have knowledge here yet. this code is mostly taken from internet w3school website then i modify it a bit to Servo controlling. so im really hoping that someone can tell me how to do it....
Board: Node32
actual Board: NodeMCU ESP 32
Here is web server code that parses two variables from a GET response of a HTML form, I suppose it should be no problem to adopt it for your needs: http://playground.arduino.cc/Code/WebServerST
Hey so this is the how I do this, I've made a form in your html that would take the input and send a get request to the server and can be dealt with there. this is the process:
input put into form, sent to server in get request.
the get request is send stored char by char in header variable.
if statement checks if the parameter is in the header. The string is searched for the value and the value is saved into a string.
good luck this should work.
#include<Servo.h>
Servo ServoPin;
int angle = 0;
#include <WiFi.h>
#include <WiFiClient.h>
#include <WiFiAP.h>
#define ServoPin 34; // Set the GPIO pin where you connected your test LED or comment this line out if your dev board has a built-in LED
// Set these to your desired credentials.
const char *ssid = "XXXXXX";
const char *password = "";
WiFiServer server(80);
String header;
void setup() {
Serial.begin(115200);
Serial.println();
Serial.println("Configuring access point...");
pinMode(ServoPin,OUTPUT);
// You can remove the password parameter if you want the AP to be open.
WiFi.softAP(ssid, password);
IPAddress myIP = WiFi.softAPIP();
Serial.print("AP IP address: ");
Serial.println(myIP);
server.begin();
Serial.println("Server started");
}
void loop() {
WiFiClient client = server.available(); // listen for incoming clients
if (client) { // if you get a client,
Serial.println("New Client."); // print a message out the serial port
String currentLine = ""; // make a String to hold incoming data from the client
while (client.connected()) { // loop while the client's connected
if (client.available()) { // if there's bytes to read from the client,
char c = client.read();// read a byte, then
header += c; //write request to the header
Serial.write(c); // print it out the serial monitor
if (c == '\n') { // if the byte is a newline character
// if the current line is blank, you got two newline characters in a row.
// that's the end of the client HTTP request, so send a response:
if (currentLine.length() == 0) {
// HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK)
// and a content-type so the client knows what's coming, then a blank line:
client.println("HTTP/1.1 200 OK");
client.println("Content-type:text/html");
client.println();
if (header.indexOf("input1=") >= 0) { //if input1 is in the header then...
Serial.println(header);
String input_string = "";
int reqEnd = header.indexOf(" HTTP/1.1");
for (int n = 16; n < reqEnd; ++n) { //put the input value from the header to the variable
input_string += header[n];
}
Serial.println(input_string);
}
// the content of the HTTP response follows the header:
client.print("<!DOCTYPE html>");
client.print("<html>");
client.print("<body>");
client.print("<form action=\"/get\">"); //added a form to take a text input and send a get request.
client.print("input1: <input type=\"text\" name=\"input1\">");
client.print("<input type=\"submit\" value=\"Submit\">");
client.print("</form><br>");
ServoPin.attach(number); //the area where i will assign the servo to the angle i type.
// break out of the while loop:
break;
} else { // if you got a newline, then clear currentLine:
currentLine = "";
}
} else if (c != '\r') { // if you got anything else but a carriage return character,
currentLine += c; // add it to the end of the currentLine
}
}
}
// close the connection:
client.stop();
Serial.println("Client Disconnected.");
}
}
#include "WiFi.h"
#include "ESPAsyncWebServer.h"
const char* ssid = "yourNetworkName";
const char* password = "yourNetworkPass";
AsyncWebServer server(80);
void setup(){
Serial.begin(115200);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi..");
}
Serial.println(WiFi.localIP());
server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){
int paramsNr = request->params();
Serial.println(paramsNr);
for(int i=0;i<paramsNr;i++){
AsyncWebParameter* p = request->getParam(i);
Serial.print("Param name: ");
Serial.println(p->name());
Serial.print("Param value: ");
Serial.println(p->value());
Serial.println("------");
}
request->send(200, "text/plain", "message received");
});
server.begin();
}
void loop()
{}

arduino wifi client not posting data to mysql server

data says it has been sent and is seen on the apache log but the actual data is not posted. I can post data via browser using the php script i wrote so i know the php script "project0" works. in a separate script that i wrote the data is actually posted to the server during the void setup period but only once. i have also configured mysql to allow remote users access to phpmyadmin.
apache log info from esp32: 192.168.1.10 - - [21/Mar/2021:03:03:37 -0400] "GET /stringcode/project0.php?names=Jonathon Allen" 400 325 "-" "-"
apache log info from successful data post from browser: ::1 - - [20/Mar/2021:23:01:37 -0400] "GET /stringcode/project0.php?names=jonathon allen HTTP/1.1" 200 - "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36"
#include <SPI.h>
#include <MFRC522.h>
#include <WiFi.h>
#define RST_PIN 13
#define SS_PIN 23
#define WIFI_SSID "NETGEAR04"
#define WIFI_PASSWORD "huskylotus321"
MFRC522 mfrc522(SS_PIN,RST_PIN);
WiFiClient client;
String USERNAME = "";
void setup() {
Serial.begin(9600);
while(!Serial);
SPI.begin();
mfrc522.PCD_Init();
mfrc522.PCD_DumpVersionToSerial();
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
while(WiFi.status() != WL_CONNECTED){
Serial.println(" Trying to connect to wifi.. ");
delay(100);
}
Serial.println("connected to wifi...");
Serial.println(WiFi.localIP());
Serial.println("Ready to scan...");
}
void loop() {
if ( ! mfrc522.PICC_IsNewCardPresent()) {
return;
}
if ( ! mfrc522.PICC_ReadCardSerial()) {
return;
}
Serial.println("UID tag is : ");
String content = "";
byte letter;
for (byte i = 0; i < mfrc522.uid.size; i++) // to populate content with the
string characters read from MFRC522
{
Serial.print(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " ");
Serial.print(mfrc522.uid.uidByte[i], HEX); // print what contents value is on
content.concat(String(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " "));
content.concat(String(mfrc522.uid.uidByte[i], HEX));
}
Serial.println();
Serial.println("Message : ");
content.toUpperCase();
if(content.substring(1) == "37 07 04 D9" ){
Serial.println(" Jonathon Allen ");
USERNAME = "Jonathon Allen";
Sending_to_MYSQL();
}
if(content.substring(1) == "57 01 A2 C8" ){
Serial.println("Elijah Anies");
USERNAME = "Elijah Anies";
Sending_to_MYSQL();
}
delay(100);
}
void Sending_to_MYSQL(){
int HTTP_PORT = 80;
String HTTP_METHOD = "GET"; // or "POST"
char HOST_NAME[] = "192.168.1.11"; // hostname of web server:
String PATH_NAME = "/stringcode/project0.php?names=";
if(client.connect(HOST_NAME,HTTP_PORT)){
Serial.println("connected to server but may have not successfully sent data ");
client.println(HTTP_METHOD + " " + PATH_NAME + USERNAME + " HTTP/1.1");
client.println("Host: " + String(HOST_NAME));
client.println();
} else{
Serial.println("Did not connect to server ");
}
if(client.connected())
client.stop();
delay(500);
}

esp32 arduino ide Web Socket stream json no errors but no values

Thank you for considering this problem.
I'm streaming a small json from a Web socket and can see the stringified json arrive to the client because it prints to the serial monitor, but then it deserializes to a 1 or 0 instead of my key:value pairs. I just want it to parse the json so that the rest of my program can use the values. I get no errors. Tried both Dynamic and Static json docs. Tried triple the memory requirement.
Arduino:
#include <WiFi.h>
#define ARDUINOJSON_ENABLE_ARDUINO_STREAM 1
#include <ArduinoJson.h>
#include <StreamUtils.h>
const char* ssid = "ssid";
const char* password = "pw";
const char* host = "10.0.0.250";
void setup()
{
Serial.begin(115200);
delay(10);
// We start by connecting to a WiFi network
int loopCount = 0;
StaticJsonDocument<384> doc;
DeserializationError error;
void loop()
{
//delay(5000);
++loopCount;
if (loopCount > 1) return;
Serial.print("connecting to ");
Serial.println(host);
// Use WiFiClient class to create TCP connections
WiFiClient client;
const int httpPort = 1337;
if (!client.connect(host, httpPort)) {
Serial.println("connection failed");
return;
}
// This will send the request to the server
client.print(String("GET ") + "HTTP/1.1\r\n" +
"Host: " + host + "\r\n" +
"Connection: close\r\n\r\n");
unsigned long timeout = millis();
while (client.available() == 0) {
if (millis() - timeout > 5000) {
Serial.println(">>> Client Timeout !");
client.stop();
return;
}
}
// Read all the lines of the reply from server and print them to Serial
while (client.available() > 0) {
ReadLoggingStream loggingClient(client, Serial);
error = deserializeJson(doc, loggingClient);
}
Serial.println("");
if (error) {
Serial.print(F("deserializeJson() failed: "));
Serial.println(error.f_str());
return;
}
//this doesn't work
int id = doc["id"]; // Should be 5 but I get 0 for every value
Serial.print("id: "); Serial.println(id);
}
/*Serial monitor:
14:21:25.905 ->
07:16:36.574 -> WiFi connected
07:16:36.574 -> IP address:
07:16:36.574 -> 10.0.0.113
07:16:36.574 -> connecting to 10.0.0.250
07:16:36.849 -> "{\"id\":5,\"nom\":\"whynot\",\"delayStart\":200,\"rampePWM\":11,\"pulseWelding\":200,\"speedBalayage\":0.4,\"speedWelding\":0.5,\"speedWire\":1.1,\"balayage\":0.8,\"pulseWire\":5,\"retractWire\":7}"
07:16:36.849 -> id: 0
*/
The tcp-socket is in my node express setup. The file projet.json is only the json seen above ^^ no white space.
var net = require('net');
var serverN = net.createServer(function(socket) {
fs.readFile("./data/projet.json", 'utf-8', (err, data) => {
if (err) {
throw err;
}
socket.write(JSON.stringify(data));
socket.pipe(socket);
});
});
serverN.listen(1337, '10.0.0.250');
I can only show you how i use it to get the right values. i use a DynamicJsonDocument in my solution:
DynamicJsonDocument root(2048);
DeserializationError err = deserializeJson(root, http.getString());
String TravelTimes = root["travelTime"];
Otherwise you can also try to output the values directly via the jsonobject
JsonObject object = doc.to<JsonObject>();
const char* id = object["id"];
The code parses the JSON string but then calls JsonDocument::to<T>() to obtain a JsonObject. This method clears the document - from https://arduinojson.org/v6/api/jsondocument/to/
Clears the JsonDocument and converts it to the specified type.
JsonDocument::as<T>() should be used instead:
JsonObject object = doc.as<JsonObject>();
From https://arduinojson.org/v6/api/jsondocument/as/
Casts JsonDocument to the specified type.
Unlike JsonDocument::to(), this function doesn’t change the content of the JsonDocument.
You can also use serializeJsonPretty() to display the JsonObject on the serial output. Instead of:
JsonObject object = doc.to<JsonObject>();
Serial.println(object);
this can be done with:
serializeJsonPretty(doc, Serial);
Thanks to bblanchon of ArduinoJson - The node socket was stringifying the json twice. I changed the socket to socket.write(data) instead of socket.write(JSON.stringify(data)) and it works.
See full explanation here
https://github.com/bblanchon/ArduinoJson/issues/1507
Thanks again!

Couldn't send/recieve POST DATA REQUEST between ESP8266 (NodeMCU) and PHP live server

I want to connect my NODEMCU wifi module to live server and then comunicate with rest API. While I was calling simple GET method with plain-text content then everything works fine, problem arises while calling POST and JSON data. Though my server API seems to work fine on ARC(Rest API testing Application).
Working With
Windows 10
Arduino IDE 1.8.12
Linux Live Server (hosted on BIGROCK)
Secure Domain (https://)
API directory permission is 755
LIVE SERVER
<?php
if (strtoupper($_SERVER['REQUEST_METHOD']) != 'POST') {
throw new Exception('Only POST requests are allowed');
}
$content_type = isset($_SERVER['CONTENT_TYPE']) ? $_SERVER['CONTENT_TYPE'] : '';
if (stripos($content_type, 'application/json') === false) {
throw new Exception('Content-Type must be application/json');
}
$body = file_get_contents("php://input");
$object = json_decode($body, true);
if (!is_array($object)) {
throw new Exception('Failed to decode JSON object');
}
print_r($object);
?>
Arduino IDE
#include <ESP8266WiFi.h>
const char* ssid = "**********";
const char* password = "**********";
const char* host = "www.ameyakrishi.com";
void setup()
{
Serial.begin(115200);
delay(2000);
Serial.print("[Connecting to "); Serial.print(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED)
{
Serial.print(".");delay(500);
}
Serial.println(" Connected]");delay(1000);
}
void loop()
{
WiFiClient client;
Serial.print("[Connecting to "); Serial.print(host);delay(500);
if (client.connect(host, 80))
{
Serial.println(" Connected]");delay(1000);
String postData = "{\"key\":\"papa\",\"val\":999}";
client.print(String("POST /automation/app.php") + " HTTP/1.1\r\n" +
"Host: " + host + "\r\n" +
"Content-Type: application/json \r\n" +
"Content-Length: " + postData.length() + "\r\n" +
"Connection: close\r\n" +
"\r\n"
);
while (client.connected() || client.available())
{
if (client.available())
{
String line = client.readStringUntil('\n');
Serial.println(line);
}
}
client.stop();
Serial.println("\n[Disconnected]");delay(1000);
}
else
{
Serial.println("connection failed!]");delay(1000);
client.stop();
}
delay(30000);
}
Serial Monitor Output
All connections are succeed and then print the 500 Internal Server Error response in format.

Send data from Arduino to ESP8266 using JSON and display this data in a WebServer?

I'm sending Humidity data from a sensor (DHT11) connected to an Arduino Uno to a NodeMCU (ESP8266). I'm sending this data through ArduinoJSON library and this is working perfect. So the NodeMCU can Deserialize with no problem the JSON object and read it, and send it to the WebServer.
What I want to do is: Have an automatic refresh of the Web Server, so I can see these data continuosly without manually refresh the page everytime
I followed This youtube tutorial for the following code and
This below is the code of the NodeMCU in an Arduino IDE:
/*------------------------------------------------------------------------------
06/25/2019
Author: Makerbro
Platforms: ESP8266
Language: C++/Arduino
File: esp8266_firmware.ino
------------------------------------------------------------------------------
Description:
Code for YouTube video demonstrating how to communicate between an Arduino UNO
and an ESP8266.
https://youtu.be/6-RXqFS_UtU
Do you like my videos? You can support the channel:
https://patreon.com/acrobotic
https://paypal.me/acrobotic
------------------------------------------------------------------------------
Please consider buying products from ACROBOTIC to help fund future
Open-Source projects like this! We'll always put our best effort in every
project, and release all our design files and code for you to use.
https://acrobotic.com/
https://amazon.com/acrobotic
------------------------------------------------------------------------------
License:
Please see attached LICENSE.txt file for details.
------------------------------------------------------------------------------*/
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
#include <ArduinoJson.h>
#ifndef STASSID
#define STASSID "********"
#define STAPSK "********"
#endif
ESP8266WebServer server(80);
const char* ssid = STASSID;
const char* password = STAPSK;
void setup()
{
WiFi.begin(ssid, password);
Serial.begin(9600);
while (WiFi.status() != WL_CONNECTED)
{
Serial.print(".");
delay(500);
}
Serial.println("");
Serial.print("IP Address: ");
Serial.println(WiFi.localIP());
server.on("/", handleIndex);
server.begin();
}
void loop()
{
server.handleClient();
}
void handleIndex()
{
// Send a JSON-formatted request with key "type" and value "request"
// then parse the JSON-formatted response with keys "gas" and "distance"
DynamicJsonDocument doc(1024);
float Humidity = 0;
// Sending the request
doc["type"] = "request";
serializeJson(doc, Serial);
// Reading the response
boolean messageReady = false;
String message = "";
while (messageReady == false) { // blocking but that's ok
if (Serial.available()) {
message = Serial.readString();
messageReady = true;
}
}
// Attempt to deserialize the JSON-formatted message
DeserializationError error = deserializeJson(doc, message);
if (error) {
Serial.print(F("deserializeJson() failed: "));
Serial.println(error.c_str());
return;
}
Humidity = doc["Humidity"];
// Prepare the data for serving it over HTTP
String output = "Humidity: " + String(Humidity);
// Serve the data as plain text, for example
server.send(200, "text/plain", output);
}
I found a way to autorefresh the WebServer every x second in This Great Tutorial and this is working perfect, but only for simple programs (eg I can see the page refresh in automatic and display different integers).
But when I try to send the JSON data in the new code where I want also to refresh in automatic the page, let's say every 5 seconds, the JSON desirialization gives me back the error: Invalid Input multiple times.
So because of this error is given multiple times I think that the part of the autorefresh of the WebServer is working, but for some reason the JSON part has conflict with the autorefresh part of the WebServer.
This is the last code, the one that doesn't work:
//http://www.martyncurrey.com/esp8266-and-the-arduino-ide-part-8-auto-update-webpage/
/*
* Sketch: ESP8266_Part8_01_AutoUpdate_HTML
* Intended to be run on an ESP8266
*/
String header = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n";
String html_1 = R"=====(
<!DOCTYPE html>
<html>
<head>
<meta name='viewport' content='width=device-width, initial-scale=1.0'/>
<meta charset='utf-8'>
<meta http-equiv='refresh' content='5'>
<style>
body {font-size:100%;}
#main {display: table; margin: auto; padding: 0 10px 0 10px; }
h2 {text-align:center; }
p { text-align:center; }
</style>
<title>Auto Update Example Using HTML</title>
</head>
<body>
<div id='main'>
<h2>Auto Update Example Using HTML</h2>
<div id='count'>
<p>Count = %Humidity%</p>
</div>
</div>
</body>
</html>
)=====";
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
#include <ArduinoJson.h>
// change these values to match your network
char ssid[] = "*********"; // your network SSID (name)
char pass[] = "********"; // your network password
WiFiServer server(80);
String tmpString = "";
unsigned int count = 0;
void setup()
{
Serial.begin(9600);
Serial.println();
Serial.println("Serial started at 115200");
Serial.println();
// Connect to a WiFi network
Serial.print(F("Connecting to ")); Serial.println(ssid);
WiFi.begin(ssid, pass);
while (WiFi.status() != WL_CONNECTED)
{
Serial.print(".");
delay(500);
}
Serial.println("");
Serial.println(F("[CONNECTED]"));
Serial.print("[IP ");
Serial.print(WiFi.localIP());
Serial.println("]");
// start a server
server.begin();
Serial.println("Server started");
} // void setup()
void loop()
{
// Send a JSON-formatted request with key "type" and value "request"
// then parse the JSON-formatted response with keys "gas" and "distance"
DynamicJsonDocument doc(1024);
float Humidity = 0;
// Sending the request
doc["type"] = "request";
serializeJson(doc, Serial);
// Reading the response
boolean messageReady = false;
String message = "";
while (messageReady == false) { // blocking but that's ok
if (Serial.available()) {
message = Serial.readString();
messageReady = true;
}
}
// Attempt to deserialize the JSON-formatted message
DeserializationError error = deserializeJson(doc, message);
if (error) {
Serial.print(F("deserializeJson() failed: "));
Serial.println(error.c_str());
return;
}
Humidity = doc["Humidity"];
Serial.print("Humidity = ");
Serial.println(Humidity);
delay(2000);
Serial.println("Entering the Client part");
// Check if a client has connected
WiFiClient client = server.available();
if (!client) { return; }
// Prepare the data for serving it over HTTP
tmpString = html_1;
tmpString.replace("%Humidity%", String(Humidity) );
client.flush();
client.print( header );
client.print( tmpString );
delay(100);
// The client will actually be disconnected when the function returns and 'client' object is destroyed
} // void loop()
Can someone see this conflict in these two part of the code?
How can I fix this?
Any suggestion are welcomed.