feat: 添加 Wi-Fi 连接等待功能,确保在连接成功后再初始化控制台

This commit is contained in:
Wang Beihong
2026-03-06 13:30:26 +08:00
parent 8bb5cc8836
commit 61a250048d

View File

@@ -43,6 +43,33 @@
static const char *TAG = "main"; static const char *TAG = "main";
static void wait_for_wifi_connected(void)
{
const uint32_t timeout_s = 120;
uint32_t elapsed_half_s = 0;
ESP_LOGI(TAG, "等待 Wi-Fi 连接成功后再初始化 console...");
while (wifi_connect_get_status() != WIFI_CONNECT_STATUS_CONNECTED)
{
if (elapsed_half_s >= (timeout_s * 2))
{
ESP_LOGW(TAG, "等待 Wi-Fi 超时(%" PRIu32 "s继续初始化 console", timeout_s);
return;
}
vTaskDelay(pdMS_TO_TICKS(500));
elapsed_half_s++;
// 每 5 秒打印一次等待状态,避免日志刷屏。
if ((elapsed_half_s % 10) == 0)
{
ESP_LOGI(TAG, "仍在等待 Wi-Fi 连接(%" PRIu32 "s", elapsed_half_s / 2);
}
}
ESP_LOGI(TAG, "Wi-Fi 已连接,开始初始化 console");
}
void app_main(void) void app_main(void)
{ {
// 初始化 Wi-Fi 配网组件,支持长按按键进入配网 // 初始化 Wi-Fi 配网组件,支持长按按键进入配网
@@ -86,6 +113,9 @@ void app_main(void)
i2c_ready = true; i2c_ready = true;
} }
// 按需求:仅在 Wi-Fi 确认连通后再初始化 console。
wait_for_wifi_connected();
ESP_ERROR_CHECK(console_cmd_init()); ESP_ERROR_CHECK(console_cmd_init());
ESP_ERROR_CHECK(console_user_cmds_register()); ESP_ERROR_CHECK(console_user_cmds_register());
ESP_ERROR_CHECK(console_cmd_all_register()); // 可选:自动注册插件命令 ESP_ERROR_CHECK(console_cmd_all_register()); // 可选:自动注册插件命令