Skip to content

Display Reboot when try to use Wi-Fi #193

Open
@razarahil

Description

@razarahil

I've created the UI using Squareline and added the UI to the code with the help of lvgl port.
When I run just UI, it works fine and as soon as I add Wi-Fi code, the display start rebooting.

lvgl v8.4.4
esp display panel: v1.0.0
esp32 aduino core: v3.1.3
Display: Waveshare ESP32S3-LCD-Touch-5B

`#include <Arduino.h>
#include <esp_display_panel.hpp>
#include <lvgl.h>
#include "lvgl_v8_port.h"
#include <ui.h>
#include <WiFi.h>
#include <HTTPClient.h>
#include <ArduinoJson.h>

using namespace esp_panel::drivers;
using namespace esp_panel::board;

// WiFi configuration
const char* ssid = "YOUR_WIFI_SSID"; // Replace with your WiFi SSID
const char* password = "YOUR_WIFI_PASSWORD"; // Replace with your WiFi password

// Home Assistant configuration
const char* ha_url = "https://homeassistant.local";
const char* ha_token = "YOUR_LONG_LIVED_TOKEN"; // Replace with your Home Assistant long-lived token

// Sensor IDs
const char* outdoor_humidity_id = "sensor.outdoor_outside_humidity";
const char* outdoor_temp_id = "sensor.outdoor_outside_temperature";
const char* indoor_temp_id = "sensor.sonoff_temperature_temperature";
const char* indoor_humidity_id = "sensor.sonoff_temperature_humidity";
const char* energy_consumption_id = "sensor.tapo_this_month_s_consumption";

// Update interval (10 minutes = 600000 milliseconds)
const unsigned long updateInterval = 600000;
unsigned long lastUpdateTime = 0;

// Function declarations
void connectWiFi();
void fetchHAData();
String getSensorValue(const char* sensorId);

void setup() {
String title = "LVGL porting example";

Serial.begin(115200);
Serial.println("Initializing board");

// Initialize board
Board *board = new Board();
board->init();

#if LVGL_PORT_AVOID_TEARING_MODE
auto lcd = board->getLCD();
// When avoid tearing function is enabled, the frame buffer number should be set in the board driver
lcd->configFrameBufferNumber(LVGL_PORT_DISP_BUFFER_NUM);

#if ESP_PANEL_DRIVERS_BUS_ENABLE_RGB && CONFIG_IDF_TARGET_ESP32S3
auto lcd_bus = lcd->getBus();
/**

  • As the anti-tearing feature typically consumes more PSRAM bandwidth, for the ESP32-S3, we need to utilize the
  • "bounce buffer" functionality to enhance the RGB data bandwidth.
  • This feature will consume bounce_buffer_size * bytes_per_pixel * 2 of SRAM memory.
    */
    if (lcd_bus->getBasicAttributes().type == ESP_PANEL_BUS_TYPE_RGB) {
    static_cast<BusRGB *>(lcd_bus)->configRGB_BounceBufferSize(lcd->getFrameWidth() * 10);
    }
    #endif
    #endif

assert(board->begin());

Serial.println("Initializing LVGL");
lvgl_port_init(board->getLCD(), board->getTouch());

Serial.println("Creating UI");
/* Lock the mutex due to the LVGL APIs are not thread-safe /
lvgl_port_lock(-1);
ui_init();
/
Release the mutex */
lvgl_port_unlock();

// PRIORITY 2: Connect to WiFi
connectWiFi();

// PRIORITY 3: First data fetch
if (WiFi.status() == WL_CONNECTED) {
fetchHAData();
}
}

void loop() {
// Handle display updates
lvgl_port_task_handler();

// Check WiFi connection
if (WiFi.status() != WL_CONNECTED) {
Serial.println("WiFi connection lost, reconnecting...");
connectWiFi();
}

// Check if it's time to update data from Home Assistant (every 10 minutes)
unsigned long currentTime = millis();
if (currentTime - lastUpdateTime >= updateInterval || lastUpdateTime == 0) {
if (WiFi.status() == WL_CONNECTED) {
fetchHAData();
lastUpdateTime = currentTime;
}
}

delay(10); // Small delay to prevent watchdog issues
}

// Connect to WiFi
void connectWiFi() {
Serial.println("Connecting to WiFi...");
WiFi.begin(ssid, password);

// Wait for connection with timeout
int timeout = 20; // 10 seconds timeout
while (WiFi.status() != WL_CONNECTED && timeout > 0) {
delay(500);
Serial.print(".");
timeout--;
}

if (WiFi.status() == WL_CONNECTED) {
Serial.println("");
Serial.println("WiFi connected");
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
} else {
Serial.println("");
Serial.println("WiFi connection failed");
}
}

// Fetch data from Home Assistant
void fetchHAData() {
Serial.println("Fetching data from Home Assistant...");

// Update UI with values from Home Assistant
lvgl_port_lock(-1);

// Get and set outdoor temperature
String outdoorTemp = getSensorValue(outdoor_temp_id);
if (outdoorTemp != "") {
lv_label_set_text(ui_outdoorTemp, outdoorTemp.c_str());
}

// Get and set outdoor humidity
String outdoorHumi = getSensorValue(outdoor_humidity_id);
if (outdoorHumi != "") {
lv_label_set_text(ui_outdoorHumi, outdoorHumi.c_str());
}

// Get and set indoor temperature
String indoorTemp = getSensorValue(indoor_temp_id);
if (indoorTemp != "") {
lv_label_set_text(ui_indoorTemp, indoorTemp.c_str());
}

// Get and set indoor humidity
String indoorHumi = getSensorValue(indoor_humidity_id);
if (indoorHumi != "") {
lv_label_set_text(ui_indoorHumi, indoorHumi.c_str());
}

// Get and set energy consumption
String energy = getSensorValue(energy_consumption_id);
if (energy != "") {
lv_label_set_text(ui_energyConsum, energy.c_str());
}

lvgl_port_unlock();

Serial.println("Home Assistant data updated");
}

// Helper function to get sensor value from Home Assistant
String getSensorValue(const char* sensorId) {
String value = "";
HTTPClient http;

// Construct the API URL
String url = String(ha_url) + "/api/states/" + String(sensorId);

// Begin HTTP request
http.begin(url);

// Add authorization header
http.addHeader("Authorization", "Bearer " + String(ha_token));
http.addHeader("Content-Type", "application/json");

// Send GET request
int httpCode = http.GET();

if (httpCode == HTTP_CODE_OK) {
String payload = http.getString();

// Parse JSON response
DynamicJsonDocument doc(1024);
DeserializationError error = deserializeJson(doc, payload);

if (!error) {
  value = doc["state"].as<String>();
  
  // Include unit of measurement if available
  if (doc.containsKey("attributes") && doc["attributes"].containsKey("unit_of_measurement")) {
    value += " " + doc["attributes"]["unit_of_measurement"].as<String>();
  }
} else {
  Serial.print("JSON parsing failed: ");
  Serial.println(error.c_str());
}

} else {
Serial.print("HTTP GET failed, error: ");
Serial.println(httpCode);
}

http.end();
return value;
}`

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions