Search code examples
c++jsonarduinoesp8266

Send json document with ESP8266


I created a function to send a sensor value with a name to a node.js server with a http post request.

I use ArduinoJson V6 library and ESP8266HTTPClient.h

so i wrote this :

void stk(String name, float value)
{
  if (WiFi.status() == WL_CONNECTED) //Check WiFi connection status
  {
    digitalWrite(2, HIGH);
    DynamicJsonDocument doc(300);
    doc["name"] = name;
    doc["value"] = value;
    serializeJson(doc, postmessage);
    HTTPClient http;                                    //Declare object of class HTTPClient
    http.begin(host);                                   //Specify request destination
    http.addHeader("Content-Type", "application/json"); //Specify content-type header
    int httpCode = http.POST(postmessage);              //Send the request
    String payload = http.getString();                  //Get the response payload
    doc.~BasicJsonDocument();                           //clear the DynamicJsonDocument
    if (httpCode > 199 && httpCode < 300)
    {
      Serial.println(httpCode); //Print HTTP return code
      Serial.println(payload);  //Print request response payload
    }
    else
    {
      Serial.println("server isn't active at the specified IP or encounter an error");
    }
    http.end(); //Close connection
  }
  else
  {
    Serial.println("Error in WiFi connection");
  }
  digitalWrite(2, LOW);
}

void loop()
{
  stk("sensor1", 12);
  delay(100);
  stk("sensor2", 11.1);
}

and i don't know why, on my server, i only receive sensor1, and sometime an error (the SyntaxError) but it's random:

{ name: 'sensor1', value: 12 }
{ name: 'sensor1', value: 12 }
{ name: 'sensor1', value: 12 }
SyntaxError: Unexpected token { in JSON at position 29
    at JSON.parse (<anonymous>)
    at parse (G:\Calamar Industries\kraken\kraken_node\node_modules\body-parser\lib\types\json.js:89:19)
    at G:\Calamar Industries\kraken\kraken_node\node_modules\body-parser\lib\read.js:121:18
    at invokeCallback (G:\Calamar Industries\kraken\kraken_node\node_modules\raw-body\index.js:224:16)
    at done (G:\Calamar Industries\kraken\kraken_node\node_modules\raw-body\index.js:213:7)
    at IncomingMessage.onEnd (G:\Calamar Industries\kraken\kraken_node\node_modules\raw-body\index.js:273:7)
    at IncomingMessage.emit (events.js:333:22)
    at endReadableNT (_stream_readable.js:1201:12)
    at processTicksAndRejections (internal/process/task_queues.js:84:21)

Could you help me ? thank you.


Solution

  • You showing the message in the comments leads me to the following analysis:

    Read the ArduinoJson V6 documentation on the serializeJson() function

    This function treats String and std::string as streams: it doesn’t replace the content, it appends to the end.

    I.e. because you reuse postmessage, which is probably a globally declared String or std::string, you keep appending new data to it, leading to an invalid JSON string.

    The solution is to declare the object locally, e.g.

    [...]
        doc["value"] = value;
        String postmessage;
        serializeJson(doc, postmessage);
    [...]