Parsing http request json ESPHome

4 days of my life were not in vain. I found a solution to the problem, automation between nodes. I have put together a lot of instructions on how to parse json http reequest.
Unfortunately, I did not find any sensible instructions on the site https://esphome.io/, so I had to study and use the arduino libraries. As I understand it, the current version of esphome uses the ArduinoJson v5 library, so I got the following code

sensor:
  - platform: template
    name: Template sensor
    id: temp_sensor

# some trigger here
    on...
      then:
        - lambda: |-
            WiFiClient client;
            HTTPClient http;
            // http.useHTTP10(true);  // Remember to call useHTTP10(true) when you use getStream()
            http.begin(client, "http://ip_of_node/sensor/name_of_sensor");  // http://192.168.31.21/sensor/bw-shp8_ds18b20 details https://esphome.io/web-api/index.html#rest-api
            int httpCode = http.GET();
            if (httpCode > 0) {
              if (httpCode == HTTP_CODE_OK || httpCode == HTTP_CODE_MOVED_PERMANENTLY) {
              // String payload = http.getString();  // some debug info
              // Serial.println(payload);
              DynamicJsonBuffer doc(200);
              JsonObject& root = doc.parseObject(http.getString());
              float bt = root["value"];
              Serial.println(bt); // some debug info
              id(temp_sensor).publish_state(bt);
              //
              }
            }
            http.end();

4 Likes

Thank you for this great post! It saved me a lot of time and effort.

I was trying to do this with the http_request.get action, but I didn’t succeed. The documentation is very limited. Is there a way to do it with that action so your code could be simplified?


你好,我按照你的示例,执行报错,请问你知道是什么原因吗?