#include #include #include #include "wifi-connect.h" #include "esp_lvgl_port.h" #include "lvgl_st7789_use.h" #include "ui.h" #include "vars.h" #include "relay_ctrl.h" #include "esp_err.h" #include "esp_log.h" #include "freertos/FreeRTOS.h" #include "freertos/task.h" #include "freertos/semphr.h" #include "sntp_time.h" #include "esp_mac.h" #include "esp_system.h" #include "esp_efuse.h" #include "esp_efuse_table.h" #include "bh1750_use.h" #include "aht30.h" #define TAG "MAIN" typedef struct { char time_str[32]; float lux; float temp; float humidity; } env_data_t; static env_data_t s_env_data; static SemaphoreHandle_t s_env_data_lock = NULL; static bool wait_for_wifi_connected(TickType_t timeout_ticks) { const TickType_t start_ticks = xTaskGetTickCount(); while ((xTaskGetTickCount() - start_ticks) < timeout_ticks) { if (wifi_connect_get_status() == WIFI_CONNECT_STATUS_CONNECTED) return true; vTaskDelay(pdMS_TO_TICKS(200)); } return false; } static void env_data_update_system_info(void) { if (s_env_data_lock == NULL) return; time_t now; struct tm timeinfo; time(&now); localtime_r(&now, &timeinfo); char time_buf[32]; strftime(time_buf, sizeof(time_buf), "%Y-%m-%d %H:%M:%S", &timeinfo); xSemaphoreTake(s_env_data_lock, portMAX_DELAY); strncpy(s_env_data.time_str, time_buf, sizeof(s_env_data.time_str)); xSemaphoreGive(s_env_data_lock); set_var_local_time(s_env_data.time_str); } static void ui_task(void *arg) { for (;;) { env_data_update_system_info(); lvgl_port_lock(0); ui_tick(); lvgl_port_unlock(); vTaskDelay(pdMS_TO_TICKS(30)); } } extern "C" void app_main(void) { vTaskDelay(pdMS_TO_TICKS(100)); ESP_LOGI(TAG, "--- APP STARTING ---"); s_env_data_lock = xSemaphoreCreateMutex(); // 1. 初始化 Wi-Fi ESP_ERROR_CHECK(wifi_connect_init()); // 2. 初始化显示屏和 LVGL start_lvgl_demo(); // 3. 初始化 UI lvgl_port_lock(100 / portTICK_PERIOD_MS); ui_init(); lvgl_port_unlock(); // 7. 创建 UI 任务 xTaskCreate(ui_task, "ui_task", 8192, NULL, 5, NULL); if (wait_for_wifi_connected(pdMS_TO_TICKS(15000))) { set_var_system_ip(wifi_connect_get_ip()); } // 5. 初始化 I2C 总线并注册传感器 (共享总线) ESP_ERROR_CHECK(bh1750_user_init()); i2c_master_bus_handle_t i2c_bus = bh1750_get_i2c_bus_handle(); // AHT30 挂载到同一条 I2C 总线上 aht30_handle_t aht30_dev = NULL; ESP_ERROR_CHECK(aht30_create(i2c_bus, AHT30_I2C_ADDRESS, &aht30_dev)); // 6. 创建传感器读取任务 xTaskCreate([](void *arg) { aht30_handle_t aht30 = (aht30_handle_t)arg; for (;;) { float lux = 0.0f, temp = 0.0f, hum = 0.0f; // 读取 BH1750 if (bh1750_user_read(&lux) == ESP_OK) { set_var_light_val(lux); } // 读取 AHT30 if (aht30_get_temperature_humidity_value(aht30, &temp, &hum) == ESP_OK) { set_var_temp(temp); set_var_humity_val(hum); } // 数据存入共享结构体 if (s_env_data_lock) { xSemaphoreTake(s_env_data_lock, portMAX_DELAY); s_env_data.lux = lux; s_env_data.temp = temp; s_env_data.humidity = hum; xSemaphoreGive(s_env_data_lock); } vTaskDelay(pdMS_TO_TICKS(1000)); } }, "sensor_task", 4096 * 2, (void *)aht30_dev, 6, NULL); }