Data hosted with ♥ by Pastebin.com - Download Raw - See Original
  1. //
  2. // Can ESP32 read data from Home Assistant? Reading "Inverter Active Power" from Home Assistant connected to Huawei SUN2000-5KTL-L1 inverter
  3. //
  4. //  https://youtu.be/p7ZOHrjYuNU
  5. //
  6.  
  7. #include <ArduinoJson.h>
  8. #include <WiFi.h>
  9. #include <HTTPClient.h>
  10.  
  11. const char* ssid = "YOUR WIFI SSID";
  12. const char* password = "YOUR WIFI PASSWORD";
  13.  
  14. const char* haApiUrl = "http://XXX.XXX.XXX.XXX:8123/api/states/XXXXXXXXX_SENSOR_NAME_XXXXXXX";
  15. // EXAMPLE
  16. // const char* haApiUrl = "http://192.168.0.103:8123/api/states/sensor.inverter_active_power";
  17.  
  18. const char* haApiToken = "XXXXX HOME ASSISTANT TOKEN XXXXXXXXXXXXXXXXXXXXX";
  19.  
  20. void setup() {
  21.   Serial.begin(115200);
  22.   WiFi.begin(ssid, password);
  23.  
  24.   while (WiFi.status() != WL_CONNECTED) {
  25.     delay(1000);
  26.     Serial.println("Conectare la reteaua WIFI...");
  27.   }
  28.  
  29.   Serial.println("Conectat la Wifi!");
  30. }
  31.  
  32. void loop() {
  33.   HTTPClient http;
  34.   http.begin(haApiUrl);
  35.   http.addHeader("Authorization", "Bearer " + String(haApiToken));
  36.  
  37.   int httpCode = http.GET();
  38.  
  39.   if (httpCode > 0) {
  40.     String payload = http.getString();
  41.  
  42.     DynamicJsonDocument doc(1024);
  43.     deserializeJson(doc, payload);
  44.  
  45.     float currentProduction = doc["state"].as<float>();
  46.  
  47.     Serial.print("Productia curenta: ");
  48.     Serial.println(currentProduction);
  49.   } else {
  50.     Serial.println("Eroare la solicitarea HTTP");
  51.   }
  52.  
  53.   http.end();
  54.  
  55.   delay(5000);
  56. }