用 ESP8266 发送 json 文档

Send json document with ESP8266

我创建了一个函数,通过 http post 请求将带有名称的传感器值发送到 node.js 服务器。

我使用 ArduinoJson V6 库和 ESP8266HTTPClient.h

所以我写了这个:

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);
}

而且我不知道为什么,在我的服务器上,我只收到 sensor1,有时会收到一个错误(SyntaxError),但它是随机的:

{ 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)

你能帮帮我吗? 谢谢。

你在评论中显示的消息使我得出以下分析:

阅读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.

即因为您重用 postmessage,这可能是全局声明的 Stringstd::string,您不断向其添加新数据,导致无效的 JSON 字符串。

解决方法是在本地声明对象,例如

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