#include "device_mode.h" #include "nvs_flash.h" #include "esp_log.h" #include "esp_system.h" #include "freertos/FreeRTOS.h" #include "freertos/task.h" #include "esp_timer.h" #define TAG "DeviceMode" #define NVS_NAMESPACE "device" #define NVS_KEY "mode" #define NVS_KEY_SWITCHED "switched" // 模式切换标志(首次调用时从NVS读取并清除) static bool switch_flag_checked = false; static bool mode_was_switched = false; device_mode_t device_mode_get(void) { nvs_handle_t h; int32_t mode = DEVICE_MODE_AI; if (nvs_open(NVS_NAMESPACE, NVS_READONLY, &h) == ESP_OK) { nvs_get_i32(h, NVS_KEY, &mode); nvs_close(h); } return (device_mode_t)mode; } void device_mode_set(device_mode_t mode) { nvs_handle_t h; if (nvs_open(NVS_NAMESPACE, NVS_READWRITE, &h) == ESP_OK) { nvs_set_i32(h, NVS_KEY, (int32_t)mode); // 设置切换标志,重启后用于按键抑制 nvs_set_u8(h, NVS_KEY_SWITCHED, 1); nvs_commit(h); nvs_close(h); } ESP_LOGI(TAG, "模式切换为 %s,即将重启...", mode == DEVICE_MODE_BADGE ? "吧唧" : "AI"); vTaskDelay(pdMS_TO_TICKS(500)); esp_restart(); } bool device_mode_is_badge(void) { return device_mode_get() == DEVICE_MODE_BADGE; } bool device_mode_in_switch_suppress(void) { // 首次调用时从NVS读取切换标志并清除 if (!switch_flag_checked) { switch_flag_checked = true; nvs_handle_t h; uint8_t val = 0; if (nvs_open(NVS_NAMESPACE, NVS_READWRITE, &h) == ESP_OK) { nvs_get_u8(h, NVS_KEY_SWITCHED, &val); if (val) { nvs_set_u8(h, NVS_KEY_SWITCHED, 0); nvs_commit(h); ESP_LOGI(TAG, "检测到模式切换重启,启用2秒按键抑制"); } nvs_close(h); } mode_was_switched = (val == 1); } if (!mode_was_switched) return false; // 重启后2秒内抑制按键(组合键释放产生的幽灵事件) return esp_timer_get_time() < 2000000; }