Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //
- // Can ESP32 read data from Home Assistant? Reading "Inverter Active Power" from Home Assistant connected to Huawei SUN2000-5KTL-L1 inverter
- //
- // https://youtu.be/p7ZOHrjYuNU
- //
- #include <Adafruit_GFX.h>
- #include <Adafruit_ST7735.h>
- #include <SPI.h>
- #include <ArduinoJson.h>
- #include <WiFi.h>
- #include <HTTPClient.h>
- const char* ssid = "YOUR WIFI SSID";
- const char* password = "YOUR WIFI PASSWORD";
- const char* haApiUrl = "http://YOUR HOME ASSISTANT SERVER IP:8123/api/states/XXXXXXXXX_SENSOR_NAME_XXXXXXX";
- // EXAMPLE:
- // const char* haApiUrl = "http://192.168.0.103:8123/api/states/sensor.power_meter_active_power";
- const char* haApiToken = "YOUR HOME ASSISTANT TOKEN";
- #define TFT_CS 5
- #define TFT_RST 4
- #define TFT_DC 2
- Adafruit_ST7735 tft = Adafruit_ST7735(TFT_CS, TFT_DC, TFT_RST);
- void setup() {
- Serial.begin(115200);
- WiFi.begin(ssid, password);
- while (WiFi.status() != WL_CONNECTED) {
- delay(1000);
- Serial.println("Connecting to WiFi...");
- }
- Serial.println("Connected to WiFi");
- //tft.initR(INITR_GREENTAB);
- //tft.initR(INITR_REDTAB);
- tft.initR(INITR_BLACKTAB);
- tft.setRotation(1);
- tft.fillScreen(ST7735_BLACK);
- }
- void loop() {
- HTTPClient http;
- http.begin(haApiUrl);
- http.addHeader("Authorization", "Bearer " + String(haApiToken));
- int httpCode = http.GET();
- if (httpCode > 0) {
- String payload = http.getString();
- DynamicJsonDocument doc(1024);
- deserializeJson(doc, payload);
- float currentProduction = doc["state"].as<float>();
- int intProduction = int(currentProduction);
- Serial.print("Current Production: ");
- int lungimeText;
- int16_t x, y;
- uint16_t w, h;
- //tft.setTextColor(ST7735_WHITE);
- if (intProduction >= 0)
- {
- //tft.setTextColor(ST7735_GREEN);
- tft.setTextColor(0x07E0);
- } else {
- //tft.setTextColor(ST7735_RED);
- tft.setTextColor(0xF800);
- }
- tft.setTextSize(5);
- tft.getTextBounds(String(intProduction), 0, 0, &x, &y, &w, &h);
- lungimeText = w + (intProduction < 0 ? 6 : 0);
- int inaltimeText = h;
- tft.setCursor(tft.width() - lungimeText, tft.height() - inaltimeText);
- tft.fillScreen(ST7735_BLACK);
- tft.print(intProduction);
- Serial.println(intProduction);
- delay(5000);
- } else {
- Serial.println("Error in HTTP request");
- delay(1000);
- }
- http.end();
- }
- int numarDigits(int numar)
- {
- int cifre = 1;
- while (numar /= 10)
- {
- cifre++;
- }
- return cifre;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement