From d7c1aef77ad83eb7f8d14a9baac498deff17cb1b Mon Sep 17 00:00:00 2001 From: NologoTech <47595794+NologoTech@users.noreply.github.com> Date: Mon, 1 Dec 2025 19:38:14 +0800 Subject: [PATCH] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E6=97=A0=E5=90=8D=E7=A7=91?= =?UTF-8?q?=E6=8A=80=E6=98=9F=E6=99=BA=E9=93=9D=E5=90=88=E9=87=91=20wifi?= =?UTF-8?q?=E7=89=88=E6=9C=AC=20=E7=9A=84board=E6=94=AF=E6=8C=81=20(#1352)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * 增加无名科技星智铝合金 wifi版本 的board支持 * 删除多余头文件 * 星智铝合金:触摸单击时间改为200ms --------- Co-authored-by: Limh2017 --- main/CMakeLists.txt | 5 + main/Kconfig.projbuild | 3 + main/boards/xingzhi-metal-1.54-wifi/README.md | 61 ++++ main/boards/xingzhi-metal-1.54-wifi/config.h | 53 +++ .../xingzhi-metal-1.54-wifi/config.json | 10 + .../boards/xingzhi-metal-1.54-wifi/cst816x.cc | 214 ++++++++++++ main/boards/xingzhi-metal-1.54-wifi/cst816x.h | 90 +++++ .../xingzhi-metal-1.54-wifi/power_manager.h | 314 ++++++++++++++++++ .../xingzhi-metal-1.54-wifi.cc | 202 +++++++++++ 9 files changed, 952 insertions(+) create mode 100644 main/boards/xingzhi-metal-1.54-wifi/README.md create mode 100644 main/boards/xingzhi-metal-1.54-wifi/config.h create mode 100644 main/boards/xingzhi-metal-1.54-wifi/config.json create mode 100644 main/boards/xingzhi-metal-1.54-wifi/cst816x.cc create mode 100644 main/boards/xingzhi-metal-1.54-wifi/cst816x.h create mode 100644 main/boards/xingzhi-metal-1.54-wifi/power_manager.h create mode 100644 main/boards/xingzhi-metal-1.54-wifi/xingzhi-metal-1.54-wifi.cc diff --git a/main/CMakeLists.txt b/main/CMakeLists.txt index 9000174d..825dd877 100644 --- a/main/CMakeLists.txt +++ b/main/CMakeLists.txt @@ -445,6 +445,11 @@ elseif(CONFIG_BOARD_TYPE_XINGZHI_CUBE_1_54TFT_ML307) set(BUILTIN_TEXT_FONT font_puhui_basic_20_4) set(BUILTIN_ICON_FONT font_awesome_20_4) set(DEFAULT_EMOJI_COLLECTION twemoji_64) +elseif(CONFIG_BOARD_TYPE_XINGZHI_METAL_1_54_WIFI) + set(BOARD_TYPE "xingzhi-metal-1.54-wifi") + set(BUILTIN_TEXT_FONT font_puhui_basic_20_4) + set(BUILTIN_ICON_FONT font_awesome_20_4) + set(DEFAULT_EMOJI_COLLECTION twemoji_64) elseif(CONFIG_BOARD_TYPE_SEEED_STUDIO_SENSECAP_WATCHER) set(BOARD_TYPE "sensecap-watcher") set(BUILTIN_TEXT_FONT font_puhui_basic_30_4) diff --git a/main/Kconfig.projbuild b/main/Kconfig.projbuild index bc4f5bca..8c18ba57 100644 --- a/main/Kconfig.projbuild +++ b/main/Kconfig.projbuild @@ -378,6 +378,9 @@ choice BOARD_TYPE config BOARD_TYPE_XINGZHI_CUBE_1_54TFT_ML307 bool "无名科技星智1.54(ML307)" depends on IDF_TARGET_ESP32S3 + config BOARD_TYPE_XINGZHI_METAL_1_54_WIFI + bool "无名科技星智1.54 METAL(wifi)" + depends on IDF_TARGET_ESP32S3 config BOARD_TYPE_SEEED_STUDIO_SENSECAP_WATCHER bool "Seeed Studio SenseCAP Watcher" depends on IDF_TARGET_ESP32S3 diff --git a/main/boards/xingzhi-metal-1.54-wifi/README.md b/main/boards/xingzhi-metal-1.54-wifi/README.md new file mode 100644 index 00000000..2ad3efd8 --- /dev/null +++ b/main/boards/xingzhi-metal-1.54-wifi/README.md @@ -0,0 +1,61 @@ +# 无名科技星智 1.54 METAL (wifi) + +## 简介 +无名科技星智 1.54 METAL (wifi) 是星智 1.54 开模版的升级款,配备 1.54 寸 LCD 屏幕与 CST816 触摸芯片。它用触摸交互替代物理按键,并将外壳升级为铝合金材质,同步优化了交互体验与产品质感、手感。 + +>### 按键操作 +>- **开机**: 关机状态,长按电源键3秒后自动开机(旧版硬件长按电源键1s后自动开机) +>- **关机**: 开机状态,长按电源键5秒后自动关机(旧版硬件插入usb时不会自动关机) +>- **唤醒/打断**: 正常通话环境下,单击中间触摸按键 +>- **重新配网**: 开机后,1秒钟内单击中间触摸按键,会自动重启并进入配网界面 +>- **增加音量**: 开机状态下,单击右侧触摸按键,音量增加。长按右侧触摸按键2s,音量递增。 +>- **减小音量**: 开机状态下,单击左侧触摸按键,音量减小。长按左侧触摸按键2s,音量递减。 + +>### 休眠操作 +>- **浅睡眠**: 开机后,维持待命状态60s后,进入浅睡眠(屏幕亮度调整到1%) +>- **深睡眠**: 开机后,维持待命状态300s后,进入深睡眠(自动关机) +>- **唤醒**: 浅睡眠状态下,单击中间触摸按键,唤醒设备(屏幕亮度回调) + +# 编译配置命令 + +**克隆工程** + +```bash +git clone https://github.com/78/xiaozhi-esp32.git +``` + +**进入工程** + +```bash +cd xiaozhi-esp32 +``` + +**配置编译目标为 ESP32S3** + +```bash +idf.py set-target esp32s3 +``` + +**打开 menuconfig** + +```bash +idf.py menuconfig +``` + +**选择板子** + +```bash +- `Xiaozhi Assistant` → `Board Type` → 选择 `无名科技星智1.54 METAL(wifi)` +``` + +**编译** + +```ba +idf.py build +``` + +**下载并打开串口终端** + +```bash +idf.py build flash monitor +``` \ No newline at end of file diff --git a/main/boards/xingzhi-metal-1.54-wifi/config.h b/main/boards/xingzhi-metal-1.54-wifi/config.h new file mode 100644 index 00000000..11dab54e --- /dev/null +++ b/main/boards/xingzhi-metal-1.54-wifi/config.h @@ -0,0 +1,53 @@ + +#ifndef _BOARD_CONFIG_H_ +#define _BOARD_CONFIG_H_ + +#include + +// 音频 +#define AUDIO_INPUT_SAMPLE_RATE 24000 +#define AUDIO_OUTPUT_SAMPLE_RATE 24000 + +#define AUDIO_INPUT_REFERENCE true +#define AUDIO_I2S_GPIO_WS GPIO_NUM_4 +#define AUDIO_I2S_GPIO_MCLK GPIO_NUM_5 +#define AUDIO_I2S_GPIO_BCLK GPIO_NUM_6 +#define AUDIO_I2S_GPIO_DIN GPIO_NUM_17 +#define AUDIO_I2S_GPIO_DOUT GPIO_NUM_15 + +#define AUDIO_CODEC_USE_PCA9557 +#define AUDIO_CODEC_I2C_PA_EN GPIO_NUM_21 +#define AUDIO_CODEC_I2C_SDA_PIN GPIO_NUM_41 +#define AUDIO_CODEC_I2C_SCL_PIN GPIO_NUM_42 +#define AUDIO_CODEC_ES8311_ADDR ES8311_CODEC_DEFAULT_ADDR + +// 按键 +#define BOOT_BUTTON_GPIO GPIO_NUM_0 + +// 屏幕 +#define DISPLAY_SPI_HOST SPI3_HOST +#define DISPLAY_SDA GPIO_NUM_10 +#define DISPLAY_SCL GPIO_NUM_9 +#define DISPLAY_DC GPIO_NUM_8 +#define DISPLAY_CS GPIO_NUM_14 +#define DISPLAY_RES GPIO_NUM_18 +#define DISPLAY_WIDTH 240 +#define DISPLAY_HEIGHT 240 +#define DISPLAY_SWAP_XY false +#define DISPLAY_MIRROR_X false +#define DISPLAY_MIRROR_Y false +#define BACKLIGHT_INVERT false +#define DISPLAY_OFFSET_X 0 +#define DISPLAY_OFFSET_Y 0 +#define DISPLAY_BACKLIGHT_PIN GPIO_NUM_13 +#define DISPLAY_BACKLIGHT_OUTPUT_INVERT false + +// 电源管理 +#define POWER_USB_IN GPIO_NUM_1 +#define Power_Control GPIO_NUM_48 // 电源控制引脚 +#define Power_Dec GPIO_NUM_47 // 电源键检测引脚 +#define POWER_CBS_ADC_UNIT ADC_UNIT_1 // adc检测公共unit GPIO1 +#define POWER_USBIN_ADC_CHANNEL ADC_CHANNEL_0 // 检测usb是否插入 GPIO1 +#define POWER_BATTERY_ADC_CHANNEL ADC_CHANNEL_6 // 电池电量检测 GPIO7 + +#endif // _BOARD_CONFIG_H_ diff --git a/main/boards/xingzhi-metal-1.54-wifi/config.json b/main/boards/xingzhi-metal-1.54-wifi/config.json new file mode 100644 index 00000000..53bebb5f --- /dev/null +++ b/main/boards/xingzhi-metal-1.54-wifi/config.json @@ -0,0 +1,10 @@ +{ + "target": "esp32s3", + "builds": [ + { + "name": "xingzhi-metal-1.54-wifi", + "sdkconfig_append": [ + ] + } + ] +} \ No newline at end of file diff --git a/main/boards/xingzhi-metal-1.54-wifi/cst816x.cc b/main/boards/xingzhi-metal-1.54-wifi/cst816x.cc new file mode 100644 index 00000000..4879c13a --- /dev/null +++ b/main/boards/xingzhi-metal-1.54-wifi/cst816x.cc @@ -0,0 +1,214 @@ +#include "cst816x.h" +#include "board.h" +#include "application.h" +#include "display.h" +#include "assets/lang_config.h" +// #include "audio_codec.h" +#include "wifi_board.h" +#include +#include "power_save_timer.h" +#include "codecs/es8311_audio_codec.h" +#include // 用于std::max/std::min + +#define TAG "Cst816x" + +const Cst816x::TouchThresholdConfig& Cst816x::getThresholdConfig(int x, int y) { + for (const auto& config : TOUCH_THRESHOLD_TABLE) { + if (config.x == x && config.y == y) { + return config; + } + } + return DEFAULT_THRESHOLD; +} + +Cst816x::Cst816x(i2c_master_bus_handle_t i2c_bus, uint8_t addr) : I2cDevice(i2c_bus, addr) { + uint8_t chip_id = ReadReg(0xA7); + ESP_LOGI(TAG, "Get CST816x chip ID: 0x%02X", chip_id); + read_buffer_ = new uint8_t[6]; +} + +Cst816x::~Cst816x() { + if (read_buffer_ != nullptr) { + delete[] read_buffer_; + read_buffer_ = nullptr; + } +} + +int64_t Cst816x::getCurrentTimeUs() { + struct timeval tv; + gettimeofday(&tv, nullptr); + return (int64_t)tv.tv_sec * 1000000L + tv.tv_usec; +} + +void Cst816x::UpdateTouchPoint() { + ReadRegs(0x02, read_buffer_, 6); + tp_.num = read_buffer_[0] & 0x0F; + tp_.x = ((read_buffer_[1] & 0x0F) << 8) | read_buffer_[2]; + tp_.y = ((read_buffer_[3] & 0x0F) << 8) | read_buffer_[4]; + memset(read_buffer_, 0, 6); +} + +void Cst816x::resetTouchCounters() { + is_touching_ = false; + touch_start_time_ = 0; + last_release_time_ = 0; + click_count_ = 0; + long_press_started_ = false; + + is_volume_long_pressing_ = false; + volume_long_press_dir_ = 0; + last_volume_adjust_time_ = 0; +} + +void Cst816x::touchpad_daemon(void* arg) { + Cst816x* cst816x = static_cast(arg); + auto& board = Board::GetInstance(); + auto codec = board.GetAudioCodec(); + auto display = board.GetDisplay(); + + while (1) { + cst816x->UpdateTouchPoint(); + auto& tp = cst816x->GetTouchPoint(); + int64_t current_time = cst816x->getCurrentTimeUs(); + + const auto& config = cst816x->getThresholdConfig(tp.x, tp.y); + if (tp.num > 0) { + ESP_LOGD(TAG, "Touch at (%d,%d) → SingleThresh:%lldms, DoubleWindow:%lldms, LongThresh:%lldms", + tp.x, tp.y, + config.single_click_thresh_us / 1000, + config.double_click_window_us / 1000, + config.long_press_thresh_us / 1000); + } + + TouchEvent current_event; + bool event_detected = false; + + if (tp.num > 0 && !cst816x->is_touching_) { + cst816x->is_touching_ = true; + cst816x->touch_start_time_ = current_time; + cst816x->long_press_started_ = false; + } + else if (tp.num > 0 && cst816x->is_touching_) { + if (!cst816x->long_press_started_ && + (current_time - cst816x->touch_start_time_ >= config.long_press_thresh_us)) { + current_event = {TouchEventType::LONG_PRESS_START, tp.x, tp.y}; + event_detected = true; + cst816x->long_press_started_ = true; + } + } + else if (tp.num == 0 && cst816x->is_touching_) { + cst816x->is_touching_ = false; + int64_t touch_duration = current_time - cst816x->touch_start_time_; + cst816x->last_release_time_ = current_time; + if (cst816x->long_press_started_) { + current_event = {TouchEventType::LONG_PRESS_END, tp.x, tp.y}; + event_detected = true; + } + else if (touch_duration <= config.single_click_thresh_us) { + cst816x->click_count_++; + } + } + else if (tp.num == 0 && !cst816x->is_touching_) { + if (cst816x->click_count_ > 0 && + (current_time - cst816x->last_release_time_ >= config.double_click_window_us)) { + if (cst816x->click_count_ == 2) { + current_event = {TouchEventType::DOUBLE_CLICK, tp.x, tp.y}; + event_detected = true; + } + else if (cst816x->click_count_ == 1) { + current_event = {TouchEventType::SINGLE_CLICK, tp.x, tp.y}; + event_detected = true; + } + cst816x->click_count_ = 0; + } + } + + if (event_detected) { + if (current_event.y == 600 && (current_event.x == 20 || current_event.x == 40 || current_event.x == 60)) { + switch (current_event.type) { + case TouchEventType::SINGLE_CLICK: + if (current_event.x == 40) { + board.SetPowerSaveMode(false); + auto& app = Application::GetInstance(); + if (app.GetDeviceState() == kDeviceStateStarting && !WifiStation::GetInstance().IsConnected()) { + auto& wifi_board = static_cast(Board::GetInstance()); + wifi_board.ResetWifiConfiguration(); + } + app.ToggleChatState(); + } else if (current_event.x == 20) { // 20,600 单击:音量+ + int current_vol = codec->output_volume(); + int new_vol = current_vol + 10; + new_vol = (new_vol >= ES8311_VOL_MAX) ? ES8311_VOL_MAX : new_vol; + ESP_LOGI(TAG, "current_vol, new_vol(%d, %d)", current_vol, new_vol); + codec->EnableOutput(true); + codec->SetOutputVolume(new_vol); + display->ShowNotification(Lang::Strings::VOLUME + std::to_string(new_vol)); + } else if (current_event.x == 60) { // 60,600 单击:音量- + int current_vol = codec->output_volume(); + int new_vol = current_vol - 10; + new_vol = (new_vol <= ES8311_VOL_MIN) ? ES8311_VOL_MIN : new_vol; + ESP_LOGI(TAG, "current_vol, new_vol(%d, %d)", current_vol, new_vol); + codec->EnableOutput(true); + codec->SetOutputVolume(new_vol); + display->ShowNotification(Lang::Strings::VOLUME + std::to_string(new_vol)); + } + break; + + case TouchEventType::DOUBLE_CLICK: + ESP_LOGI(TAG, "Double click detected at (%d, %d)", current_event.x, current_event.y); + break; + + case TouchEventType::LONG_PRESS_START: + ESP_LOGI(TAG, "Long press started at (%d, %d) → Start volume adjust", current_event.x, current_event.y); + if (current_event.x == 20) { + cst816x->is_volume_long_pressing_ = true; + cst816x->volume_long_press_dir_ = 1; + cst816x->last_volume_adjust_time_ = current_time; + } else if (current_event.x == 60) { + cst816x->is_volume_long_pressing_ = true; + cst816x->volume_long_press_dir_ = -1; + cst816x->last_volume_adjust_time_ = current_time; + } + break; + + case TouchEventType::LONG_PRESS_END: + ESP_LOGI(TAG, "Long press ended at (%d, %d) → Stop volume adjust", current_event.x, current_event.y); + if (current_event.x == 20 || current_event.x == 60) { + cst816x->is_volume_long_pressing_ = false; + cst816x->volume_long_press_dir_ = 0; + cst816x->last_volume_adjust_time_ = 0; + } + break; + } + } + } + + if (cst816x->is_volume_long_pressing_) { + int64_t now = cst816x->getCurrentTimeUs(); + if (now - cst816x->last_volume_adjust_time_ >= cst816x->VOL_ADJ_INTERVAL_US) { + int current_vol = codec->output_volume(); + int new_vol = current_vol + (cst816x->volume_long_press_dir_ * cst816x->VOL_ADJ_STEP); + + new_vol = std::max(ES8311_VOL_MIN, std::min(ES8311_VOL_MAX, new_vol)); + + if (new_vol != current_vol) { + codec->EnableOutput(true); + codec->SetOutputVolume(new_vol); + display->ShowNotification(Lang::Strings::VOLUME + std::to_string(new_vol)); + cst816x->last_volume_adjust_time_ = now; + } else { + cst816x->is_volume_long_pressing_ = false; + cst816x->volume_long_press_dir_ = 0; + ESP_LOGI(TAG, "Volume reached limit (%d), stop adjusting", new_vol); + } + } + } + + vTaskDelay(pdMS_TO_TICKS(40)); + } +} + +void Cst816x::InitCst816d() { + ESP_LOGI(TAG, "Init CST816x touch driver"); + xTaskCreate(touchpad_daemon, "touch_daemon", 2048, this, 1, NULL); +} \ No newline at end of file diff --git a/main/boards/xingzhi-metal-1.54-wifi/cst816x.h b/main/boards/xingzhi-metal-1.54-wifi/cst816x.h new file mode 100644 index 00000000..7a8a3d34 --- /dev/null +++ b/main/boards/xingzhi-metal-1.54-wifi/cst816x.h @@ -0,0 +1,90 @@ +#ifndef _CST816X_H_ +#define _CST816X_H_ + +#include "esp_log.h" +#include "esp_err.h" +#include "driver/i2c.h" +#include "i2c_device.h" +#include +#include +#include + +#define ES8311_VOL_MIN 0 +#define ES8311_VOL_MAX 100 + +enum class TouchEventType { + SINGLE_CLICK, // 单击事件 + DOUBLE_CLICK, // 双击事件 + LONG_PRESS_START,// 长按开始事件 + LONG_PRESS_END // 长按结束事件 +}; + +struct TouchEvent { + TouchEventType type; + int x; + int y; +}; + +class Cst816x : public I2cDevice { +private: + struct TouchPoint_t { + int num = 0; + int x = -1; + int y = -1; + }; + + struct TouchThresholdConfig { + int x; // 目标X坐标 + int y; // 目标Y坐标 + int64_t single_click_thresh_us; // 单击最大时长(us) + int64_t double_click_window_us; // 双击窗口(us) + int64_t long_press_thresh_us; // 长按阈值(us) + }; + + const TouchThresholdConfig DEFAULT_THRESHOLD = { + .x = -1, .y = -1, + .single_click_thresh_us = 120000, // 150ms + .double_click_window_us = 240000, // 150ms + .long_press_thresh_us = 4000000 // 4000ms + }; + + const std::array TOUCH_THRESHOLD_TABLE = { + { + {20, 600, 200000, 240000, 2000000}, // 音量+ + {40, 600, 200000, 240000, 4000000}, // boot按键 + {60, 600, 200000, 240000, 2000000} // 音量- + } + }; + + const TouchThresholdConfig& getThresholdConfig(int x, int y); + + uint8_t* read_buffer_ = nullptr; + TouchPoint_t tp_; + + bool is_touching_ = false; + int64_t touch_start_time_ = 0; // 触摸开始时间(us) + int64_t last_release_time_ = 0; // 上次释放时间(us) + int click_count_ = 0; // 单击计数(双击检测用) + bool long_press_started_ = false; // 长按是否已触发 + + bool is_volume_long_pressing_ = false; // 是否处于音量长按调整中 + int volume_long_press_dir_ = 0; // 调整方向:1=递增,-1=递减 + int64_t last_volume_adjust_time_ = 0; // 上次调整音量的时间(us) + const int64_t VOL_ADJ_INTERVAL_US = 200000; // 音量调整间隔(100ms) + const int VOL_ADJ_STEP = 5; // 每次调整步长 + + int64_t getCurrentTimeUs(); + +public: + Cst816x(i2c_master_bus_handle_t i2c_bus, uint8_t addr); + ~Cst816x(); + + void InitCst816d(); + void UpdateTouchPoint(); + void resetTouchCounters(); + static void touchpad_daemon(void* param); + + const TouchPoint_t& GetTouchPoint() { return tp_; } +}; + +#endif \ No newline at end of file diff --git a/main/boards/xingzhi-metal-1.54-wifi/power_manager.h b/main/boards/xingzhi-metal-1.54-wifi/power_manager.h new file mode 100644 index 00000000..5be6ee8c --- /dev/null +++ b/main/boards/xingzhi-metal-1.54-wifi/power_manager.h @@ -0,0 +1,314 @@ +#pragma once +#include +#include + +#include +#include +#include +#include "sdkconfig.h" +#include "button.h" +#include "board.h" +#include "config.h" +#include "assets/lang_config.h" +#include + +class PowerManager { +private: + esp_timer_handle_t timer_handle_; + esp_timer_handle_t power_timer_handle_; + std::function on_charging_status_changed_; + std::function on_low_battery_status_changed_; + + gpio_num_t charging_pin_ = GPIO_NUM_NC; + std::vector adc_values_; + uint32_t battery_level_ = 30; + bool is_charging_ = false; + bool is_low_battery_ = false; + int ticks_ = 0; + adc_oneshot_unit_handle_t adc_handle_; + const int kBatteryAdcInterval = 60; + const int kBatteryAdcDataCount = 3; + const int kLowBatteryLevel = 20; + + // power + bool pressed = false; // 是否按下电源键 + int PowerControl_ticks_ = 0; // 开机时长 + int press_ticks_ = 0; // 按下时的tick + bool is_first_boot = true; // + uint8_t PowerDec_level_ = 0; // 电源键电平 + const int power_off_ticks_ = 20; // 按键按下20/5秒准备关机; + bool new_charging_status = false; // 插入usb时无法软件关机 + bool is_shutting_down_ = false; // 标记是否进入关机流程 + int shutdown_delay_ticks_ = 0; // 关机延迟计数 + uint8_t shutdown_ticks = 5; // 5/5s后关机 预留的关机操作 + bool shutdown_first_ = true; + + // 旧版硬件软件关机逻辑 + void PowrSwitch() { + PowerDec_level_ = gpio_get_level(Power_Dec); + + // 确保开机后电源键松开再检测关机 + if (PowerDec_level_ == 1) { + is_first_boot = false; + } + + if (is_shutting_down_) { + shutdown_delay_ticks_++; + if (shutdown_delay_ticks_ >= shutdown_ticks) { + shutdown(); + is_shutting_down_ = false; + shutdown_delay_ticks_ = 0; + } + return; + } + + if (!is_first_boot) { + PowerControl_ticks_++; + if (PowerDec_level_ == 0 && pressed == false) { + press_ticks_ = PowerControl_ticks_; + pressed = true; + } + if ((press_ticks_ != 0) &&( PowerControl_ticks_ - press_ticks_ == power_off_ticks_ )&& (!new_charging_status)) { + if (timer_handle_) { + esp_timer_stop(timer_handle_); + esp_timer_delete(timer_handle_); + } + is_shutting_down_ = true; + shutdown_delay_ticks_ = 0; + } + if (PowerDec_level_ == 1 && press_ticks_!= 0) { + PowerDec_level_ = gpio_get_level(Power_Dec); + if (PowerDec_level_ == 1) { + pressed = false; + press_ticks_ = 0; + } + } + } + } + + void CheckBatteryStatus() { + int usb_usb_adc_value0; + ESP_ERROR_CHECK(adc_oneshot_read(adc_handle_, POWER_USBIN_ADC_CHANNEL, &usb_usb_adc_value0)); + new_charging_status = (1500 < usb_usb_adc_value0 && usb_usb_adc_value0 < 4000); + // ESP_LOGE("powercontrol", "USB ADC VALUE 1: %d", usb_usb_adc_value0); + + if (new_charging_status != is_charging_) { + ReadBatteryAdcData(); + is_charging_ = new_charging_status; + if (on_charging_status_changed_) { + on_charging_status_changed_(is_charging_); + } + return; + } + + // 如果电池电量数据不足,则读取电池电量数据 + if (adc_values_.size() < kBatteryAdcDataCount) { + ReadBatteryAdcData(); + return; + } + + // 如果电池电量数据充足,则每 kBatteryAdcInterval 个 tick 读取一次电池电量数据 + ticks_++; + if (ticks_ % kBatteryAdcInterval == 0) { + ReadBatteryAdcData(); + } + } + + void ReadBatteryAdcData() { + int adc_value; + ESP_ERROR_CHECK(adc_oneshot_read(adc_handle_, POWER_BATTERY_ADC_CHANNEL, &adc_value)); + + // 将 ADC 值添加到队列中 + adc_values_.push_back(adc_value); + if (adc_values_.size() > kBatteryAdcDataCount) { + adc_values_.erase(adc_values_.begin()); + } + uint32_t average_adc = 0; + for (auto value : adc_values_) { + average_adc += value; + } + average_adc /= adc_values_.size(); + + // 定义电池电量区间 + const struct { + uint16_t adc; + uint8_t level; + } levels[] = { + {1970, 0}, + {2062, 20}, + {2154, 40}, + {2246, 60}, + {2338, 80}, + {2430, 100} + }; + + // 低于最低值时 + if (average_adc < levels[0].adc) { + battery_level_ = 0; + } + // 高于最高值时 + else if (average_adc >= levels[5].adc) { + battery_level_ = 100; + } else { + // 线性插值计算中间值 + for (int i = 0; i < 5; i++) { + if (average_adc >= levels[i].adc && average_adc < levels[i+1].adc) { + float ratio = static_cast(average_adc - levels[i].adc) / (levels[i+1].adc - levels[i].adc); + battery_level_ = levels[i].level + ratio * (levels[i+1].level - levels[i].level); + break; + } + } + } + + // Check low battery status + if (adc_values_.size() >= kBatteryAdcDataCount) { + bool new_low_battery_status = battery_level_ <= kLowBatteryLevel; + if (new_low_battery_status != is_low_battery_) { + is_low_battery_ = new_low_battery_status; + if (on_low_battery_status_changed_) { + on_low_battery_status_changed_(is_low_battery_); + } + } + } + + ESP_LOGI("PowerManager", "ADC value: %d average: %ld level: %ld", adc_value, average_adc, battery_level_); + } + +public: + PowerManager(gpio_num_t pin) : charging_pin_(pin) { + // 初始化电源键检测引脚 + gpio_config_t powerdecgpio_conf = {}; + powerdecgpio_conf.intr_type = GPIO_INTR_DISABLE; + powerdecgpio_conf.mode = GPIO_MODE_INPUT; + powerdecgpio_conf.pin_bit_mask = (1ULL << Power_Dec); + powerdecgpio_conf.pull_down_en = GPIO_PULLDOWN_DISABLE; + powerdecgpio_conf.pull_up_en = GPIO_PULLUP_DISABLE; + gpio_config(&powerdecgpio_conf); + + // 初始化电源控制引脚 + gpio_config_t powercontgpio_conf = {}; + powercontgpio_conf.intr_type = GPIO_INTR_DISABLE; + powercontgpio_conf.mode = GPIO_MODE_OUTPUT; + powercontgpio_conf.pin_bit_mask = (1ULL << Power_Control); + powercontgpio_conf.pull_down_en = GPIO_PULLDOWN_ENABLE; + powercontgpio_conf.pull_up_en = GPIO_PULLUP_DISABLE; + gpio_config(&powercontgpio_conf); + gpio_set_level(Power_Control, 1); + ESP_LOGI("powercontrol", "turnded on ..."); + + // 创建电源控制检查定时器 + esp_timer_create_args_t power_timer_args = { + .callback = [](void* arg) { + PowerManager* self = static_cast(arg); + self->PowrSwitch(); + }, + .arg = this, + .dispatch_method = ESP_TIMER_TASK, + .name = "power_cotrol_timer", + .skip_unhandled_events = true, + }; + ESP_ERROR_CHECK(esp_timer_create(&power_timer_args, &power_timer_handle_)); + ESP_ERROR_CHECK(esp_timer_start_periodic(power_timer_handle_, 200000)); + // 初始化充电引脚 + gpio_config_t io_conf = {}; + io_conf.intr_type = GPIO_INTR_DISABLE; + io_conf.mode = GPIO_MODE_INPUT; + io_conf.pin_bit_mask = (1ULL << charging_pin_); + io_conf.pull_down_en = GPIO_PULLDOWN_DISABLE; + io_conf.pull_up_en = GPIO_PULLUP_DISABLE; + gpio_config(&io_conf); + + // 创建电池电量检查定时器 + esp_timer_create_args_t timer_args = { + .callback = [](void* arg) { + PowerManager* self = static_cast(arg); + self->CheckBatteryStatus(); + }, + .arg = this, + .dispatch_method = ESP_TIMER_TASK, + .name = "battery_check_timer", + .skip_unhandled_events = true, + }; + ESP_ERROR_CHECK(esp_timer_create(&timer_args, &timer_handle_)); + ESP_ERROR_CHECK(esp_timer_start_periodic(timer_handle_, 1000000)); + + adc_oneshot_unit_init_cfg_t init_config = { + .unit_id = POWER_CBS_ADC_UNIT, + .ulp_mode = ADC_ULP_MODE_DISABLE, + }; + ESP_ERROR_CHECK(adc_oneshot_new_unit(&init_config, &adc_handle_)); + + adc_oneshot_chan_cfg_t chan_config = { + .atten = ADC_ATTEN_DB_12, + .bitwidth = ADC_BITWIDTH_12, + }; + ESP_ERROR_CHECK(adc_oneshot_config_channel(adc_handle_, POWER_BATTERY_ADC_CHANNEL, &chan_config)); // 电池电量 + ESP_ERROR_CHECK(adc_oneshot_config_channel(adc_handle_, POWER_USBIN_ADC_CHANNEL, &chan_config)); // usb + } + + ~PowerManager() { + if (timer_handle_) { + esp_timer_stop(timer_handle_); + esp_timer_delete(timer_handle_); + } + if (power_timer_handle_) { + esp_timer_stop(power_timer_handle_); + esp_timer_delete(power_timer_handle_); + } + if (adc_handle_ != nullptr) { + adc_oneshot_del_unit(adc_handle_); + } + } + + bool IsCharging() { + // 如果电量已经满了,则不再显示充电中 + if (battery_level_ == 100) { + return false; + } + return is_charging_; + } + + bool IsDischarging() { + // 没有区分充电和放电,所以直接返回相反状态 + return !is_charging_; + } + + uint8_t GetBatteryLevel() { + return battery_level_; + } + + void OnLowBatteryStatusChanged(std::function callback) { + on_low_battery_status_changed_ = callback; + } + + void OnChargingStatusChanged(std::function callback) { + on_charging_status_changed_ = callback; + } + + void shutdown() { + if (!new_charging_status && shutdown_first_) + { + shutdown_first_ = false; // 进入后置 false ,防止再次进入关机状态 + gpio_config_t shutdown_gpio_conf = {}; + shutdown_gpio_conf.intr_type = GPIO_INTR_DISABLE; + shutdown_gpio_conf.mode = GPIO_MODE_OUTPUT; + shutdown_gpio_conf.pin_bit_mask = (1ULL << Power_Dec); + shutdown_gpio_conf.pull_down_en = GPIO_PULLDOWN_DISABLE; + shutdown_gpio_conf.pull_up_en = GPIO_PULLUP_DISABLE; + gpio_config(&shutdown_gpio_conf); + gpio_set_level(DISPLAY_BACKLIGHT_PIN, 0); + gpio_set_level(Power_Control, 0); + for (int i=1;i<15;i++) { + gpio_set_level(Power_Dec, 1); + vTaskDelay(pdMS_TO_TICKS(100)); + gpio_set_level(Power_Dec, 0); + vTaskDelay(pdMS_TO_TICKS(100)); + ESP_LOGI("PowerManager","触发开关机控制"); + } + ESP_LOGI("PowerManager","关机失败,进入深睡眠"); + esp_deep_sleep_start(); + } else { + ESP_LOGI("PowerManager","检测到插入usb,无法关机"); + } + } +}; diff --git a/main/boards/xingzhi-metal-1.54-wifi/xingzhi-metal-1.54-wifi.cc b/main/boards/xingzhi-metal-1.54-wifi/xingzhi-metal-1.54-wifi.cc new file mode 100644 index 00000000..1ca4aa61 --- /dev/null +++ b/main/boards/xingzhi-metal-1.54-wifi/xingzhi-metal-1.54-wifi.cc @@ -0,0 +1,202 @@ +#include "wifi_board.h" +#include "codecs/es8311_audio_codec.h" +#include "display/lcd_display.h" +#include "system_reset.h" +#include "application.h" +#include "button.h" +#include "config.h" +#include "i2c_device.h" +#include +#include +#include +#include +#include "power_manager.h" +#include "power_save_timer.h" +#include "led/single_led.h" +#include "assets/lang_config.h" +#include +#include +#include +#include "cst816x.h" + +#define TAG "XINGZHI_METAL_1_54_WIFI" + +class XINGZHI_METAL_1_54_WIFI : public WifiBoard { +private: + i2c_master_bus_handle_t i2c_bus_; + Button boot_button_; + SpiLcdDisplay* display_; + PowerSaveTimer* power_save_timer_; + PowerManager* power_manager_; + esp_lcd_panel_io_handle_t panel_io_ = nullptr; + esp_lcd_panel_handle_t panel_ = nullptr; + esp_err_t err; + bool is_device_found = false; + Cst816x *cst816d_; + + void InitializePowerManager() { + power_manager_ = new PowerManager(POWER_USB_IN);//USB是否插入 + power_manager_->OnChargingStatusChanged([this](bool is_charging) { + if (is_charging) { + power_save_timer_->SetEnabled(false); + } else { + power_save_timer_->SetEnabled(true); + } + }); + } + + void InitializePowerSaveTimer() { + power_save_timer_ = new PowerSaveTimer(-1, 60, 300); + power_save_timer_->OnEnterSleepMode([this]() { + ESP_LOGI(TAG, "Enabling sleep mode"); + display_->SetChatMessage("system", ""); + display_->SetEmotion("sleepy"); + GetBacklight()->SetBrightness(1); + }); + power_save_timer_->OnExitSleepMode([this]() { + display_->SetChatMessage("system", ""); + display_->SetEmotion("neutral"); + GetBacklight()->RestoreBrightness(); + }); + power_save_timer_->OnShutdownRequest([this]() { + ESP_LOGI(TAG, "Shutting down"); + power_manager_->shutdown(); + }); + power_save_timer_->SetEnabled(true); + } + + void InitializeI2c() { + // Initialize I2C peripheral + i2c_master_bus_config_t i2c_bus_cfg = { + .i2c_port = I2C_NUM_0, + .sda_io_num = AUDIO_CODEC_I2C_SDA_PIN, + .scl_io_num = AUDIO_CODEC_I2C_SCL_PIN, + .clk_source = I2C_CLK_SRC_DEFAULT, + .glitch_ignore_cnt = 7, + .intr_priority = 0, + .trans_queue_depth = 0, + .flags = { + .enable_internal_pullup = 1, + }, + }; + ESP_ERROR_CHECK(i2c_new_master_bus(&i2c_bus_cfg, &i2c_bus_)); + for (uint8_t addr = 1; addr < 127; addr++) { + err = i2c_master_probe(i2c_bus_, addr, 100); + if (err == ESP_OK) { + ESP_LOGI(TAG, "Device found at address 0x%02X", addr); + if (addr == 0x15) { + is_device_found = true; + } + } + } + } + + void InitializeSpi() { + spi_bus_config_t buscfg = {}; + buscfg.mosi_io_num = DISPLAY_SDA; + buscfg.miso_io_num = GPIO_NUM_NC; + buscfg.sclk_io_num = DISPLAY_SCL; + buscfg.quadwp_io_num = GPIO_NUM_NC; + buscfg.quadhd_io_num = GPIO_NUM_NC; + buscfg.max_transfer_sz = DISPLAY_WIDTH * DISPLAY_HEIGHT * sizeof(uint16_t); + ESP_ERROR_CHECK(spi_bus_initialize(DISPLAY_SPI_HOST, &buscfg, SPI_DMA_CH_AUTO)); + } + + void InitializeSt7789Display() { + ESP_LOGD(TAG, "Install panel IO"); + esp_lcd_panel_io_spi_config_t io_config = {}; + io_config.cs_gpio_num = DISPLAY_CS; + io_config.dc_gpio_num = DISPLAY_DC; + io_config.spi_mode = 3; + io_config.pclk_hz = 80 * 1000 * 1000; + io_config.trans_queue_depth = 10; + io_config.lcd_cmd_bits = 8; + io_config.lcd_param_bits = 8; + ESP_ERROR_CHECK(esp_lcd_new_panel_io_spi(DISPLAY_SPI_HOST, &io_config, &panel_io_)); + + ESP_LOGD(TAG, "Install LCD driver"); + esp_lcd_panel_dev_config_t panel_config = {}; + panel_config.reset_gpio_num = DISPLAY_RES; + panel_config.rgb_ele_order = LCD_RGB_ELEMENT_ORDER_RGB; + panel_config.bits_per_pixel = 16; + ESP_ERROR_CHECK(esp_lcd_new_panel_st7789(panel_io_, &panel_config, &panel_)); + ESP_ERROR_CHECK(esp_lcd_panel_reset(panel_)); + ESP_ERROR_CHECK(esp_lcd_panel_init(panel_)); + ESP_ERROR_CHECK(esp_lcd_panel_swap_xy(panel_, DISPLAY_SWAP_XY)); + ESP_ERROR_CHECK(esp_lcd_panel_mirror(panel_, DISPLAY_MIRROR_X, DISPLAY_MIRROR_Y)); + ESP_ERROR_CHECK(esp_lcd_panel_invert_color(panel_, true)); + + display_ = new SpiLcdDisplay(panel_io_, panel_, DISPLAY_WIDTH, DISPLAY_HEIGHT, DISPLAY_OFFSET_X, DISPLAY_OFFSET_Y, + DISPLAY_MIRROR_X, DISPLAY_MIRROR_Y, DISPLAY_SWAP_XY); + } + + void Initialtouchtask() { + if (is_device_found) { + cst816d_ = new Cst816x(i2c_bus_, 0x15); + cst816d_->InitCst816d(); + } + } + +public: + XINGZHI_METAL_1_54_WIFI() : + boot_button_(BOOT_BUTTON_GPIO) { + InitializePowerManager(); + InitializePowerSaveTimer(); + InitializeI2c(); + InitializeSpi(); + InitializeSt7789Display(); + Initialtouchtask(); + GetBacklight()->RestoreBrightness(); + } + + virtual AudioCodec* GetAudioCodec() override { + static Es8311AudioCodec audio_codec( + i2c_bus_, + I2C_NUM_0, + AUDIO_INPUT_SAMPLE_RATE, + AUDIO_OUTPUT_SAMPLE_RATE, + AUDIO_I2S_GPIO_MCLK, + AUDIO_I2S_GPIO_BCLK, + AUDIO_I2S_GPIO_WS, + AUDIO_I2S_GPIO_DOUT, + AUDIO_I2S_GPIO_DIN, + AUDIO_CODEC_I2C_PA_EN, + AUDIO_CODEC_ES8311_ADDR, + AUDIO_INPUT_REFERENCE); + return &audio_codec; + } + + virtual Display* GetDisplay() override { + return display_; + } + + virtual Backlight* GetBacklight() override { + static PwmBacklight backlight(DISPLAY_BACKLIGHT_PIN, DISPLAY_BACKLIGHT_OUTPUT_INVERT); + return &backlight; + } + + Cst816x *GetTouchpad() { + return cst816d_; + } + + virtual bool GetBatteryLevel(int& level, bool& charging, bool& discharging) override { + static bool last_discharging = false; + charging = power_manager_->IsCharging(); + discharging = power_manager_->IsDischarging(); + if (discharging != last_discharging) { + power_save_timer_->SetEnabled(discharging); + last_discharging = discharging; + } + level = power_manager_->GetBatteryLevel(); + return true; + } + + virtual void SetPowerSaveMode(bool enabled) override { + if (!enabled) { + power_save_timer_->WakeUp(); + } + WifiBoard::SetPowerSaveMode(enabled); + } +}; + +DECLARE_BOARD(XINGZHI_METAL_1_54_WIFI);