12 Commits

Author SHA1 Message Date
GW_MC
41516374f0 fix: invalid const and declaration ordering and added smart pointer for get 2026-01-19 21:09:11 +08:00
GW_MC
4cda7d2de3 feat: integrate NetworkHandler and WifiHandler for network initialization 2026-01-19 20:44:52 +08:00
GW_MC
a801caaae6 feat: implement HttpHandler and WifiHandler classes for network management 2026-01-19 20:44:28 +08:00
GW_MC
89e8014798 feat: implement HttpHandler and WifiHandler classes for HTTP client management 2026-01-19 20:44:08 +08:00
GW_MC
1d12dc5160 feat: add esp_wifi to required components in CMakeLists.txt 2026-01-19 20:42:07 +08:00
GW_MC
0b26e0c7c9 feat: semaphore guard helper 2026-01-19 20:38:51 +08:00
GW_MC
89daff2267 Merge branch 'setup' into network-control 2026-01-19 12:55:38 +08:00
GW_MC
18ac21e257 Enhance NVSStorageHandler with filtering capabilities and update constructor to accept namespace 2026-01-19 12:55:12 +08:00
GW_MC
821fb0d9d7 added network dependencies 2026-01-19 11:19:59 +08:00
GW_MC
01c36669cf Fix event group reference in app_main for shutdown handling 2026-01-18 14:46:31 +08:00
GW_MC
d339a1f4c3 Add NVS storage handler and integrate with main application logic 2026-01-18 14:46:25 +08:00
GW_MC
e458256193 Add main application logic and touch handling functionality
- Implemented main application entry point in main.cpp, initializing queues and event groups.
- Created TouchHandler and EInkTouchHandler classes for handling touch events.
- Added a minimal event loop for touch processing in touch.cpp.
- Introduced unit tests for the hello world application in pytest_hello_world.py.
- Added configuration files for CI and Wokwi support.
- Created empty header files for network and UI modules.
2026-01-17 20:09:33 +08:00
62 changed files with 2013 additions and 9585 deletions

6
.gitignore vendored
View File

@@ -82,9 +82,3 @@ Desktop.ini
# vscode settings # vscode settings
.vscode/ .vscode/
# sample code
sample-code/
.env
*.env

View File

@@ -3,40 +3,6 @@
cmake_minimum_required(VERSION 3.16) cmake_minimum_required(VERSION 3.16)
# target_compile_options(${COMPONENT_LIB} PRIVATE -std=c++23) # target_compile_options(${COMPONENT_LIB} PRIVATE -std=c++23)
# Define the path to your .env file
set(ENV_FILE "${CMAKE_SOURCE_DIR}/.env")
# Check if the .env file exists
if(EXISTS ${ENV_FILE})
# Read the .env file line by line
file(STRINGS ${ENV_FILE} ENV_VARS)
foreach(VAR ${ENV_VARS})
# Use regex to extract the key and value
if (VAR MATCHES "([^=]+)=(.*)")
set(ENV{${CMAKE_MATCH_1}} ${CMAKE_MATCH_2})
message(STATUS "Loaded environment variable from .env: ${CMAKE_MATCH_1}")
endif()
endforeach()
else()
message(STATUS ".env file not found at ${ENV_FILE}")
endif()
# If build-time WiFi environment variables were loaded above, expose them
# as compile-time definitions so C++ can use them.
if(DEFINED ENV{WIFI_SSID})
add_compile_definitions(BUILD_WIFI_SSID="$ENV{WIFI_SSID}")
message(STATUS "Added BUILD_WIFI_SSID compile definition")
else()
message(STATUS "WIFI_SSID not defined; skipping BUILD_WIFI_SSID compile definition")
endif()
if(DEFINED ENV{WIFI_PASSWORD})
add_compile_definitions(BUILD_WIFI_PASSWORD="$ENV{WIFI_PASSWORD}")
message(STATUS "Added BUILD_WIFI_PASSWORD compile definition")
else()
message(STATUS "WIFI_PASSWORD not defined; skipping BUILD_WIFI_PASSWORD compile definition")
endif()
include($ENV{IDF_PATH}/tools/cmake/project.cmake) include($ENV{IDF_PATH}/tools/cmake/project.cmake)
# "Trim" the build. Include the minimal set of components, main, and anything it depends on. # "Trim" the build. Include the minimal set of components, main, and anything it depends on.
idf_build_set_property(MINIMAL_BUILD ON) idf_build_set_property(MINIMAL_BUILD ON)

View File

@@ -1,556 +0,0 @@
{
"AEL": {
"name": "機場快綫",
"code": "AEL",
"line_color": "#00888A",
"stations": [
{
"code": "HOK",
"name": "香港"
},
{
"code": "KOW",
"name": "九龍"
},
{
"code": "TSY",
"name": "青衣"
},
{
"code": "AIR",
"name": "機場"
},
{
"code": "AWE",
"name": "博覽館"
}
]
},
"TCL": {
"name": "東涌綫",
"code": "TCL",
"line_color": "#F38B00",
"stations": [
{
"code": "HOK",
"name": "香港"
},
{
"code": "KOW",
"name": "九龍"
},
{
"code": "OLY",
"name": "奧運"
},
{
"code": "NAC",
"name": "南昌"
},
{
"code": "LAK",
"name": "荔景"
},
{
"code": "TSY",
"name": "青衣"
},
{
"code": "SUN",
"name": "欣澳"
},
{
"code": "TUC",
"name": "東涌"
}
]
},
"TML": {
"name": "屯馬綫",
"code": "TML",
"line_color": "#9A3820",
"stations": [
{
"code": "WKS",
"name": "烏溪沙"
},
{
"code": "MOS",
"name": "馬鞍山"
},
{
"code": "HEO",
"name": "恆安"
},
{
"code": "TSH",
"name": "大水坑"
},
{
"code": "SHM",
"name": "石門"
},
{
"code": "CIO",
"name": "第一城"
},
{
"code": "STW",
"name": "沙田圍"
},
{
"code": "CKT",
"name": "車公廟"
},
{
"code": "TAW",
"name": "大圍"
},
{
"code": "HIK",
"name": "顯徑"
},
{
"code": "DIH",
"name": "鑽石山"
},
{
"code": "KAT",
"name": "啟德"
},
{
"code": "SUW",
"name": "宋皇臺"
},
{
"code": "TKW",
"name": "土瓜灣"
},
{
"code": "HOM",
"name": "何文田"
},
{
"code": "HUH",
"name": "紅磡"
},
{
"code": "ETS",
"name": "尖東"
},
{
"code": "AUS",
"name": "柯士甸"
},
{
"code": "NAC",
"name": "南昌"
},
{
"code": "MEF",
"name": "美孚"
},
{
"code": "TWW",
"name": "荃灣西"
},
{
"code": "KSR",
"name": "錦上路"
},
{
"code": "YUL",
"name": "元朗"
},
{
"code": "LOP",
"name": "朗屏"
},
{
"code": "TIS",
"name": "天水圍"
},
{
"code": "SIH",
"name": "兆康"
},
{
"code": "TUM",
"name": "屯門"
}
]
},
"TKL": {
"name": "將軍澳綫",
"code": "TKL",
"line_color": "#A35EB5",
"stations": [
{
"code": "NOP",
"name": "北角"
},
{
"code": "QUB",
"name": "鰂魚涌"
},
{
"code": "YAT",
"name": "油塘"
},
{
"code": "TIK",
"name": "調景嶺"
},
{
"code": "TKO",
"name": "將軍澳"
},
{
"code": "LHP",
"name": "康城"
},
{
"code": "HAH",
"name": "坑口"
},
{
"code": "POA",
"name": "寶琳"
}
]
},
"EAL": {
"name": "東鐵綫",
"code": "EAL",
"line_color": "#53B7E8",
"stations": [
{
"code": "ADM",
"name": "金鐘"
},
{
"code": "EXC",
"name": "會展"
},
{
"code": "HUH",
"name": "紅磡"
},
{
"code": "MKK",
"name": "旺角東"
},
{
"code": "KOT",
"name": "九龍塘"
},
{
"code": "TAW",
"name": "大圍"
},
{
"code": "SHT",
"name": "沙田"
},
{
"code": "FOT",
"name": "火炭"
},
{
"code": "RAC",
"name": "馬場"
},
{
"code": "UNI",
"name": "大學"
},
{
"code": "TAP",
"name": "大埔墟"
},
{
"code": "TWO",
"name": "太和"
},
{
"code": "FAN",
"name": "粉嶺"
},
{
"code": "SHS",
"name": "上水"
},
{
"code": "LOW",
"name": "羅湖"
},
{
"code": "LMC",
"name": "落馬洲"
}
]
},
"SIL": {
"name": "南港島綫",
"code": "SIL",
"line_color": "#B6BD00",
"stations": [
{
"code": "ADM",
"name": "金鐘"
},
{
"code": "OCP",
"name": "海洋公園"
},
{
"code": "WCH",
"name": "黃竹坑"
},
{
"code": "LET",
"name": "利東"
},
{
"code": "SOH",
"name": "海怡半島"
}
]
},
"TWL": {
"name": "荃灣綫",
"code": "TWL",
"line_color": "#E2231A",
"stations": [
{
"code": "CEN",
"name": "中環"
},
{
"code": "ADM",
"name": "金鐘"
},
{
"code": "TST",
"name": "尖沙咀"
},
{
"code": "JOR",
"name": "佐敦"
},
{
"code": "YMT",
"name": "油麻地"
},
{
"code": "MOK",
"name": "旺角"
},
{
"code": "PRE",
"name": "太子"
},
{
"code": "SSP",
"name": "深水埗"
},
{
"code": "CSW",
"name": "長沙灣"
},
{
"code": "LCK",
"name": "荔枝角"
},
{
"code": "MEF",
"name": "美孚"
},
{
"code": "LAK",
"name": "荔景"
},
{
"code": "KWF",
"name": "葵芳"
},
{
"code": "KWH",
"name": "葵興"
},
{
"code": "TWH",
"name": "大窩口"
},
{
"code": "TSW",
"name": "荃灣"
}
]
},
"ISL": {
"name": "港島綫",
"code": "ISL",
"line_color": "#007DC5",
"stations": [
{
"code": "KET",
"name": "堅尼地城"
},
{
"code": "HKU",
"name": "香港大學"
},
{
"code": "SYP",
"name": "西營盤"
},
{
"code": "SHW",
"name": "上環"
},
{
"code": "CEN",
"name": "中環"
},
{
"code": "ADM",
"name": "金鐘"
},
{
"code": "WAC",
"name": "灣仔"
},
{
"code": "CAB",
"name": "銅鑼灣"
},
{
"code": "TIH",
"name": "天后"
},
{
"code": "FOH",
"name": "炮台山"
},
{
"code": "NOP",
"name": "北角"
},
{
"code": "QUB",
"name": "鰂魚涌"
},
{
"code": "TAK",
"name": "太古"
},
{
"code": "SWH",
"name": "西灣河"
},
{
"code": "SKW",
"name": "筲箕灣"
},
{
"code": "HFC",
"name": "杏花邨"
},
{
"code": "CHW",
"name": "柴灣"
}
]
},
"KTL": {
"name": "觀塘綫",
"code": "KTL",
"line_color": "#00AB4E",
"stations": [
{
"code": "WHA",
"name": "黃埔"
},
{
"code": "HOM",
"name": "何文田"
},
{
"code": "YMT",
"name": "油麻地"
},
{
"code": "MOK",
"name": "旺角"
},
{
"code": "PRE",
"name": "太子"
},
{
"code": "SKM",
"name": "石硤尾"
},
{
"code": "KOT",
"name": "九龍塘"
},
{
"code": "LOF",
"name": "樂富"
},
{
"code": "WTS",
"name": "黃大仙"
},
{
"code": "DIH",
"name": "鑽石山"
},
{
"code": "CHH",
"name": "彩虹"
},
{
"code": "KOB",
"name": "九龍灣"
},
{
"code": "NTK",
"name": "牛頭角"
},
{
"code": "KWT",
"name": "觀塘"
},
{
"code": "LAT",
"name": "藍田"
},
{
"code": "YAT",
"name": "油塘"
},
{
"code": "TIK",
"name": "調景嶺"
}
]
},
"DRL": {
"name": "迪士尼綫",
"code": "DRL",
"line_color": "#F550A6",
"stations": [
{
"code": "SUN",
"name": "欣澳"
},
{
"code": "DIS",
"name": "迪士尼"
}
]
}
}

View File

@@ -1,14 +1,4 @@
dependencies: dependencies:
espressif/cjson:
component_hash: 9372811fb197926f522c467627cf4a8e72b681e0366e17879631da801103aef3
dependencies:
- name: idf
require: private
version: '>=5.0'
source:
registry_url: https://components.espressif.com/
type: service
version: 1.7.19
espressif/esp_lcd_touch: espressif/esp_lcd_touch:
component_hash: 3f85a7d95af876f1a6ecca8eb90a81614890d0f03a038390804e5a77e2caf862 component_hash: 3f85a7d95af876f1a6ecca8eb90a81614890d0f03a038390804e5a77e2caf862
dependencies: dependencies:
@@ -59,11 +49,10 @@ dependencies:
type: service type: service
version: 9.4.0 version: 9.4.0
direct_dependencies: direct_dependencies:
- espressif/cjson
- espressif/esp_lcd_touch_gt911 - espressif/esp_lcd_touch_gt911
- espressif/esp_lvgl_port - espressif/esp_lvgl_port
- idf - idf
- lvgl/lvgl - lvgl/lvgl
manifest_hash: 2010806782b4d2486b02b853afa44a545717d3d0593eb60f9aa6e5c696270f8f manifest_hash: fef450d0c399587685f90aba8ae661965ef507d04a5fcf17633db86d5d0fbcff
target: esp32s3 target: esp32
version: 2.0.0 version: 2.0.0

View File

@@ -4,7 +4,7 @@
"editor": "wokwi", "editor": "wokwi",
"parts": [ "parts": [
{ {
"type": "board-esp32-s3-devkitc-1", "type": "board-esp32-devkit-c-v4",
"id": "esp", "id": "esp",
"top": 0, "top": 0,
"left": 0, "left": 0,

View File

@@ -1,41 +1,6 @@
set(requires esp-tls spi_flash nvs_flash esp_event esp_netif esp_http_client esp_wifi esp_psram esp_lvgl_port) set(requires esp-tls spi_flash nvs_flash esp_event esp_netif esp_http_client esp_wifi)
file(GLOB SRCS "main.cpp" "*.cpp" "*.c" "**/*.cpp" "**/*.cpp" "ui/**/*.cpp" "ui/**/*.c" "external/**/*.cpp" "external/**/*.c") file(GLOB SRCS "main.cpp" "*.cpp" "*.c" "**/*.cpp" "**/*.c")
# Path to the source JSON in this component
set(ASSETS_SRC_DIR ${CMAKE_CURRENT_LIST_DIR}/../assets)
set(ASSETS_BINARY_OUTPUT_DIR ${CMAKE_CURRENT_BINARY_DIR}/assets)
set(MTR_JSON_SRC ${ASSETS_SRC_DIR}/MTR_LINE_STATION.json)
set(MTR_JSON_HEADER ${ASSETS_BINARY_OUTPUT_DIR}/MTR_LINE_STATION.h)
set(CUSTOM_CMAKE_MODULES_DIR ${CMAKE_CURRENT_LIST_DIR}/cmake)
## Generate a minified header at configure time using Python
find_package(Python3 COMPONENTS Interpreter)
file(MAKE_DIRECTORY ${ASSETS_BINARY_OUTPUT_DIR})
if (Python3_Interpreter_FOUND)
execute_process(
COMMAND ${Python3_EXECUTABLE} -c "import json,sys,io; sys.stdout.write(json.dumps(json.load(open(sys.argv[1], 'r', encoding='utf-8')),separators=(',',':')))"
"${MTR_JSON_SRC}"
RESULT_VARIABLE _mtr_json_minify_result
OUTPUT_VARIABLE MTR_JSON_MINIFIED
ERROR_VARIABLE _mtr_json_minify_error
OUTPUT_STRIP_TRAILING_WHITESPACE
)
if (_mtr_json_minify_result)
message(WARNING "Python minify failed (code=${_mtr_json_minify_result}): ${_mtr_json_minify_error}\nEmbedding original ${MTR_JSON_SRC} instead.")
file(READ ${MTR_JSON_SRC} MTR_JSON_MINIFIED)
elseif (NOT MTR_JSON_MINIFIED)
message(WARNING "Python minified output empty; embedding original ${MTR_JSON_SRC} instead.")
file(READ ${MTR_JSON_SRC} MTR_JSON_MINIFIED)
endif()
else()
message(WARNING "Python3 not found; embedding original JSON without minification.")
file(READ ${MTR_JSON_SRC} MTR_JSON_MINIFIED)
endif()
file(WRITE ${MTR_JSON_HEADER} "#pragma once\nstatic const char MTR_LINE_STATION_JSON[] = R\"json(${MTR_JSON_MINIFIED})json\";\n")
idf_component_register(SRCS ${SRCS} idf_component_register(SRCS ${SRCS}
PRIV_REQUIRES ${requires} PRIV_REQUIRES ${requires}
INCLUDE_DIRS "." "${CMAKE_CURRENT_BINARY_DIR}" "display" "network" "ui" "ui/apps" "io" "common" "external") INCLUDE_DIRS "." "display" "touch" "network" "ui" "io" "common")

View File

@@ -1,20 +0,0 @@
if(NOT DEFINED INPUT)
message(FATAL_ERROR "write_json_header.cmake: INPUT not defined")
endif()
if(NOT DEFINED OUTPUT)
message(FATAL_ERROR "write_json_header.cmake: OUTPUT not defined")
endif()
find_package(Python3 COMPONENTS Interpreter REQUIRED)
execute_process(
COMMAND ${Python3_EXECUTABLE} -c "import json,sys;print(json.dumps(json.load(open(sys.argv[1])),separators=(', ',':')) )" ${INPUT}
OUTPUT_VARIABLE MINIFIED_JSON
OUTPUT_STRIP_TRAILING_WHITESPACE
)
if(NOT MINIFIED_JSON)
message(FATAL_ERROR "write_json_header.cmake: failed to minify ${INPUT}")
endif()
file(WRITE ${OUTPUT} "#pragma once\nstatic const char MTR_LINE_STATION_JSON[] = R\"json(${MINIFIED_JSON})json\";\n")

View File

@@ -1,18 +1,14 @@
#pragma once #pragma once
#include "freertos/semphr.h" #include "freertos/semphr.h"
#include "freertos/portmacro.h" #include "freertos/portmacro.h"
#include "esp_log.h"
struct SemaphoreGuard { struct SemaphoreGuard {
public: public:
const SemaphoreHandle_t semaphore;
SemaphoreGuard(SemaphoreHandle_t semaphore) : semaphore(semaphore) { } SemaphoreGuard(SemaphoreHandle_t semaphore) : semaphore(semaphore) { }
portBASE_TYPE take(TickType_t ticks_to_wait = portMAX_DELAY) { portBASE_TYPE take(TickType_t ticks_to_wait = portMAX_DELAY) {
if (this->semaphore == nullptr) {
ESP_LOGE("SemaphoreGuard", "Attempted to take a null semaphore");
return pdFALSE;
}
portBASE_TYPE result = xSemaphoreTake(this->semaphore, ticks_to_wait); portBASE_TYPE result = xSemaphoreTake(this->semaphore, ticks_to_wait);
taken = (result == pdTRUE); taken = (result == pdTRUE);
return result; return result;
@@ -24,26 +20,9 @@ public:
} }
} }
// allow move semantics
SemaphoreGuard(SemaphoreGuard&& other) noexcept
: semaphore(other.semaphore), taken(other.taken) {
other.taken = false;
}
SemaphoreGuard& operator=(SemaphoreGuard&& other) noexcept {
if (this != &other) {
// move from other
taken = other.taken;
other.taken = false;
semaphore = other.semaphore;
other.semaphore = nullptr;
}
return *this;
}
private: private:
// prevent copying // prevent copying
SemaphoreGuard(const SemaphoreGuard&) = delete; SemaphoreGuard(const SemaphoreGuard&) = delete;
SemaphoreGuard& operator=(const SemaphoreGuard&) = delete; SemaphoreGuard& operator=(const SemaphoreGuard&) = delete;
SemaphoreHandle_t semaphore = nullptr;
bool taken = false; bool taken = false;
}; };

View File

@@ -1,14 +0,0 @@
#pragma once
#include "driver/spi_master.h"
#include "driver/gpio.h"
#define PIN_TOUCH_IRQ GPIO_NUM_4
#define PIN_TOUCH_SDA GPIO_NUM_5
#define PIN_TOUCH_SCL GPIO_NUM_6
#define PIN_BUSY GPIO_NUM_7
#define PIN_RST GPIO_NUM_8
#define PIN_DC GPIO_NUM_9
#define PIN_CS GPIO_NUM_10
#define PIN_MOSI GPIO_NUM_11
#define PIN_SCK GPIO_NUM_12
#define PIN_TOUCH_RST GPIO_NUM_13

62
main/display/display.cpp Normal file
View File

@@ -0,0 +1,62 @@
#include "display.h"
#include "common/constants.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/event_groups.h"
// TODO: implement actual display functionality
DisplayHandler::DisplayHandler(QueueHandle_t touch_queue, SemaphoreHandle_t lvgl_mutex) {
(void)touch_queue;
(void)lvgl_mutex;
}
DisplayHandler::~DisplayHandler() { }
EInkDisplayHandler::EInkDisplayHandler(QueueHandle_t touch_queue, SemaphoreHandle_t lvgl_mutex)
: DisplayHandler(touch_queue, lvgl_mutex) { }
EInkDisplayHandler::~EInkDisplayHandler() { }
void EInkDisplayHandler::init(EventGroupHandle_t system_event_group) {
if (system_event_group != NULL) {
xEventGroupSetBits(system_event_group, DISPLAY_READY_BIT);
}
}
void EInkDisplayHandler::start_event_loop() {
// Minimal background task to represent display processing
xTaskCreate(
// use the static adapter and pass `this` as the task parameter
EInkDisplayHandler::task_adapter,
"display_task",
2048,
this,
tskIDLE_PRIORITY + 1,
nullptr
);
}
// static
void EInkDisplayHandler::task_adapter(void* arg) {
EInkDisplayHandler* self = static_cast<EInkDisplayHandler*>(arg);
if (self) {
self->run_event_loop();
} else {
printf("EInkDisplayHandler::task_adapter received null pointer\n");
}
// If run_event_loop ever returns, delete the task.
vTaskDelete(NULL);
}
void EInkDisplayHandler::run_event_loop() {
for (;;) {
vTaskDelay(pdMS_TO_TICKS(1000));
}
}
shutdown_display_handlerFunc EInkDisplayHandler::get_shutdown_display_handler() {
return nullptr;
}
restart_display_handlerFunc EInkDisplayHandler::get_restart_display_handler() {
return nullptr;
}

View File

@@ -1,199 +0,0 @@
#include "display/display.h"
#include "common/constants.h"
#include "esp_log.h"
#include "esp_lcd_touch_gt911.h"
#define BUSY_ACTIVE_LEVEL 0 // BUSY pin is active low
#define BUSY_INACTIVE_LEVEL 1
DisplayHandler::~DisplayHandler() {
if (_spi_mutex != nullptr) {
vSemaphoreDelete(_spi_mutex);
}
if (_spi != nullptr) {
spi_bus_remove_device(_spi);
}
if (_tp_handle != nullptr) {
esp_lcd_touch_del(_tp_handle);
}
if (_tp_io_handle != nullptr) {
esp_lcd_panel_io_del(_tp_io_handle);
}
}
void DisplayHandler::init_devices(bool set_display_ready /*= true*/) {
ESP_LOGI("DisplayHandler", "Initializing display and touch...");
_epd_init();
_touch_init();
ESP_LOGI("DisplayHandler", "Display and touch initialized.");
if (set_display_ready) {
ESP_LOGI("DisplayHandler", "Setting display ready bit.");
xEventGroupSetBits(_system_event_group, DISPLAY_READY_BIT | TOUCH_CALIBRATED_BIT);
}
}
void DisplayHandler::epd_write_cmd(uint8_t cmd) {
ESP_LOGI("DisplayHandler", "epd_write_cmd: waiting to send 0x%02X", cmd);
if (xSemaphoreTake(_spi_mutex, pdMS_TO_TICKS(5000)) != pdTRUE) {
ESP_LOGE("DisplayHandler", "SPI mutex timeout for cmd 0x%02X", cmd);
return;
}
_dangerous_epd_write_cmd_without_lock(cmd);
xSemaphoreGive(_spi_mutex);
ESP_LOGI("DisplayHandler", "epd_write_cmd: 0x%02X done", cmd);
}
void DisplayHandler::epd_write_data(uint8_t data) {
ESP_LOGI("DisplayHandler", "epd_write_data: waiting to send 0x%02X", data);
if (xSemaphoreTake(_spi_mutex, pdMS_TO_TICKS(5000)) != pdTRUE) {
ESP_LOGE("DisplayHandler", "SPI mutex timeout for data 0x%02X", data);
return;
}
_dangerous_epd_write_data_without_lock(data);
xSemaphoreGive(_spi_mutex);
ESP_LOGI("DisplayHandler", "epd_write_data: 0x%02X done", data);
}
void DisplayHandler::epd_write_cmd_with_data(uint8_t cmd, const uint8_t* data, size_t data_len) {
ESP_LOGI("DisplayHandler", "epd_write_cmd_with_data: waiting to send cmd 0x%02X with %u bytes of data", cmd, (unsigned)data_len);
if (xSemaphoreTake(_spi_mutex, pdMS_TO_TICKS(5000)) != pdTRUE) {
ESP_LOGE("DisplayHandler", "SPI mutex timeout for cmd with data 0x%02X", cmd);
return;
}
_dangerous_epd_write_cmd_without_lock(cmd);
for (size_t i = 0; i < data_len; ++i) {
_dangerous_epd_write_data_without_lock(data[i]);
}
xSemaphoreGive(_spi_mutex);
ESP_LOGI("DisplayHandler", "epd_write_cmd_with_data: cmd 0x%02X with %u bytes of data done", cmd, (unsigned)data_len);
}
//
// Private methods
//
void DisplayHandler::_dangerous_epd_write_cmd_without_lock(uint8_t cmd) {
ESP_LOGI("DisplayHandler", "_dangerous_epd_write_cmd_without_lock: sending 0x%02X", cmd);
gpio_set_level(PIN_DC, 0); // Command mode
spi_transaction_t t {};
t.length = 8;t.tx_buffer = &cmd;
esp_err_t err = spi_device_polling_transmit(_spi, &t);
if (err != ESP_OK) {
ESP_LOGE("DisplayHandler", "Failed to send data 0x%02X", cmd);
} else {
ESP_LOGI("DisplayHandler", "_dangerous_epd_write_cmd_without_lock: 0x%02X sent", cmd);
}
}
void DisplayHandler::_dangerous_epd_write_data_without_lock(uint8_t data) {
ESP_LOGI("DisplayHandler", "_dangerous_epd_write_data_without_lock: sending 0x%02X", data);
gpio_set_level(PIN_DC, 1); // Data mode
spi_transaction_t t = { };
t.length = 8; t.tx_buffer = &data;
esp_err_t err = spi_device_polling_transmit(_spi, &t);
if (err != ESP_OK) {
ESP_LOGE("DisplayHandler", "Failed to send data 0x%02X", data);
} else {
ESP_LOGI("DisplayHandler", "_dangerous_epd_write_data_without_lock: 0x%02X sent", data);
}
}
// required to be called by inheriting class after SPI device is created
void DisplayHandler::_epd_init(void) {
ESP_LOGI("DisplayHandler", "Initializing EPD...");
// 1. Hardware Reset
gpio_set_level(PIN_RST, 0);
vTaskDelay(pdMS_TO_TICKS(10));
gpio_set_level(PIN_RST, 1);
vTaskDelay(pdMS_TO_TICKS(10));
// 2. Initialization Sequence
const uint8_t panel_setting_data[] = { 0x1F };
epd_write_cmd_with_data(0x00, panel_setting_data, 1); // Panel Setting
vTaskDelay(pdMS_TO_TICKS(10));
const uint8_t vcom_data[] = { 0x10, 0x07 };
epd_write_cmd_with_data(0x50, vcom_data, 2); // VCOM
vTaskDelay(pdMS_TO_TICKS(10));
epd_write_cmd(0x04); // Power ON
vTaskDelay(pdMS_TO_TICKS(100)); // Wait for power on
// Check BUSY pin with detailed logging
ESP_LOGI("DisplayHandler", "Waiting for EPD to be ready after power on...");
ESP_LOGI("DisplayHandler", "BUSY pin level after power on: %d (0=BUSY, 1=FREE)", gpio_get_level(PIN_BUSY));
int busy_timeout = 0;
while (gpio_get_level(PIN_BUSY) == BUSY_ACTIVE_LEVEL) { // BUSY is active LOW
vTaskDelay(pdMS_TO_TICKS(10));
busy_timeout++;
if (busy_timeout > 500) { // 5 second timeout
ESP_LOGE("DisplayHandler", "EPD power on timeout! BUSY pin stuck at 0");
break;
}
if (busy_timeout % 50 == 0) { // Log every 500ms
ESP_LOGW("DisplayHandler", "Still waiting for EPD power on, timeout: %d/500", busy_timeout);
}
}
ESP_LOGI("DisplayHandler", "EPD power on complete after %d * 10ms, BUSY pin: %d", busy_timeout, gpio_get_level(PIN_BUSY));
const uint8_t booster_data[] = { 0x27, 0x27, 0x18, 0x17 };
epd_write_cmd_with_data(0x06, booster_data, 4); // Booster Soft Start
vTaskDelay(pdMS_TO_TICKS(10));
// Enhanced display drive commands
const uint8_t e0_data[] = { 0x02 };
epd_write_cmd_with_data(0xE0, e0_data, 1);
const uint8_t e5_data[] = { 0x5A };
epd_write_cmd_with_data(0xE5, e5_data, 1);
}
void DisplayHandler::_touch_init(void) {
ESP_LOGI("DisplayHandler", "Initializing touch...");
// 1. Initialize I2C Bus
i2c_config_t conf = {};
conf.mode = I2C_MODE_MASTER;
conf.sda_io_num = PIN_TOUCH_SDA;
conf.scl_io_num = PIN_TOUCH_SCL;
conf.sda_pullup_en = GPIO_PULLUP_ENABLE;
conf.scl_pullup_en = GPIO_PULLUP_ENABLE;
conf.master.clk_speed = 400000;
i2c_param_config(I2C_NUM_0, &conf);
i2c_driver_install(I2C_NUM_0, I2C_MODE_MASTER, 0, 0, 0);
ESP_LOGI("DisplayHandler", "I2C driver installed");
// 2. Initialize GT911
ESP_LOGI("DisplayHandler", "Initializing GT911 touch controller...");
esp_lcd_panel_io_i2c_config_t tp_io_config = {};
// temporarily disable -Wmissing-field-initializers, as ESP_LCD_TOUCH_IO_I2C_GT911_CONFIG macro does not set all fields
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wmissing-field-initializers"
esp_lcd_panel_io_i2c_config_t default_tp_io_config = ESP_LCD_TOUCH_IO_I2C_GT911_CONFIG();
#pragma GCC diagnostic pop
tp_io_config.dev_addr = default_tp_io_config.dev_addr;
tp_io_config.control_phase_bytes = default_tp_io_config.control_phase_bytes;
tp_io_config.dc_bit_offset = default_tp_io_config.dc_bit_offset;
tp_io_config.lcd_cmd_bits = default_tp_io_config.lcd_cmd_bits;
tp_io_config.flags = default_tp_io_config.flags;
esp_lcd_new_panel_io_i2c(I2C_NUM_0, &tp_io_config, &_tp_io_handle);
// GT911-specific config with I2C address (0x5D = INT low during reset)
static esp_lcd_touch_io_gt911_config_t gt911_config = {
.dev_addr = ESP_LCD_TOUCH_IO_I2C_GT911_ADDRESS // 0x5D
};
esp_lcd_touch_config_t tp_cfg = {};
tp_cfg.x_max = 800;
tp_cfg.y_max = 480;
tp_cfg.rst_gpio_num = PIN_TOUCH_RST;
tp_cfg.int_gpio_num = PIN_TOUCH_IRQ;
tp_cfg.driver_data = &gt911_config; // Pass GT911-specific config for automatic reset
esp_err_t touch_ret = esp_lcd_touch_new_i2c_gt911(_tp_io_handle, &tp_cfg, &_tp_handle);
if (touch_ret == ESP_OK && _tp_handle != nullptr) {
ESP_LOGI("DisplayHandler", "GT911 touch controller initialized successfully");
} else {
ESP_LOGE("DisplayHandler", "GT911 touch controller initialization failed: %s", esp_err_to_name(touch_ret));
_tp_handle = nullptr;
}
}

42
main/display/display.h Normal file
View File

@@ -0,0 +1,42 @@
#include "info/info.h"
typedef void (*shutdown_display_handlerFunc)(void);
typedef void (*restart_display_handlerFunc)(void);
class DisplayHandler {
public:
DisplayHandler(QueueHandle_t touch_queue, SemaphoreHandle_t lvgl_mutex);
// the system_event_group is used to set display-ready bit
virtual void init(EventGroupHandle_t system_event_group) = 0;
virtual void start_event_loop() = 0;
// get a handler to perform display shutdown cleanup, this is called after event loop ends and DisplayHandler is deleted
virtual shutdown_display_handlerFunc get_shutdown_display_handler() = 0;
virtual restart_display_handlerFunc get_restart_display_handler() = 0;
virtual ~DisplayHandler() = 0;
private:
DisplayHandler(const DisplayHandler&) = delete;
DisplayHandler& operator=(const DisplayHandler&) = delete;
};
class EInkDisplayHandler : public DisplayHandler {
public:
EInkDisplayHandler(QueueHandle_t touch_queue, SemaphoreHandle_t lvgl_mutex);
void init(EventGroupHandle_t system_event_group) override;
void start_event_loop() override;
shutdown_display_handlerFunc get_shutdown_display_handler() override;
restart_display_handlerFunc get_restart_display_handler() override;
~EInkDisplayHandler() override;
private:
// Task adapter used for FreeRTOS task creation. It forwards to the
// instance `run_event_loop()` method using the `this` pointer passed
// as the task parameter.
static void task_adapter(void* arg);
// Instance method that implements the display task loop.
void run_event_loop();
// prevent copying
EInkDisplayHandler(const EInkDisplayHandler&) = delete;
EInkDisplayHandler& operator=(const EInkDisplayHandler&) = delete;
};

View File

@@ -1,42 +0,0 @@
#pragma once
#include "driver/spi_master.h"
#include "driver/gpio.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "esp_lcd_touch_gt911.h"
#include "display/constants.h"
#include <driver/i2c.h>
class DisplayHandler {
public:
DisplayHandler(
EventGroupHandle_t system_event_group
) : _system_event_group(system_event_group) { }
virtual ~DisplayHandler();
// required to be called by inheriting class after SPI device is created
// set set_display_ready to false if further initialization is needed before marking display ready
virtual void init_devices(bool set_display_ready = true);
protected:
// Allow derived classes to access touch handle
esp_lcd_touch_handle_t get_touch_handle() const { return _tp_handle; }
void epd_write_cmd(uint8_t cmd);
void epd_write_data(uint8_t data);
void epd_write_cmd_with_data(uint8_t cmd, const uint8_t* data, size_t data_len);
protected:
SemaphoreHandle_t _spi_mutex = xSemaphoreCreateMutex();
spi_device_handle_t _spi = nullptr;
EventGroupHandle_t _system_event_group = nullptr;
esp_lcd_panel_io_handle_t _tp_io_handle = nullptr;
esp_lcd_touch_handle_t _tp_handle = nullptr;
void _dangerous_epd_write_cmd_without_lock(uint8_t cmd);
void _dangerous_epd_write_data_without_lock(uint8_t data);
void _epd_init(void);
void _touch_init(void);
};

View File

@@ -1,773 +0,0 @@
#include "display/eink_display_handler.h"
#include "display/constants.h"
#include "common/constants.h"
#include "esp_lcd_touch_gt911.h"
#include "esp_log.h"
#include <driver/i2c.h>
#include <vector>
#include "common/semaphore_guard.h"
#define TAG "EInkDisplayHandler"
#define DISPLAY_BUFFER_SIZE (EINK_HEIGHT* EINK_WIDTH) / 8 // 1 bit per pixels
#define MINIMUM_PIN_SETUP_DELAY_MS 10
#define MINIMUM_POWER_ON_DELAY_MS 100
static uint8_t* DRAW_BUFFER; // 1 bit per pixel
static uint8_t* OLD_DRAW_BUFFER; // 1 bit per pixel
static uint8_t* black_data;
static uint8_t* white_data;
EInkDisplayHandler::EInkDisplayHandler() {
black_data = static_cast<uint8_t*>(heap_caps_malloc(DISPLAY_BUFFER_SIZE, MALLOC_CAP_SPIRAM));
white_data = static_cast<uint8_t*>(heap_caps_malloc(DISPLAY_BUFFER_SIZE, MALLOC_CAP_SPIRAM));
DRAW_BUFFER = static_cast<uint8_t*>(heap_caps_malloc(DISPLAY_BUFFER_SIZE, MALLOC_CAP_SPIRAM));
OLD_DRAW_BUFFER = static_cast<uint8_t*>(heap_caps_malloc(DISPLAY_BUFFER_SIZE, MALLOC_CAP_SPIRAM));
memset(black_data, 0xFF, DISPLAY_BUFFER_SIZE); // eink uses 1 for black
memset(white_data, 0x00, DISPLAY_BUFFER_SIZE);
memset(DRAW_BUFFER, 0x00, DISPLAY_BUFFER_SIZE); // start with all white (0 = white in e-ink)
memset(OLD_DRAW_BUFFER, 0x00, DISPLAY_BUFFER_SIZE); // start with all white (0 = white in e-ink)
draw_buffer_ = DRAW_BUFFER;
old_buffer_ = OLD_DRAW_BUFFER;
refresh_mutex_ = xSemaphoreCreateMutex();
if (refresh_mutex_ == nullptr) {
ESP_LOGE(TAG, "Failed to create refresh mutex");
}
}
EInkDisplayHandler::~EInkDisplayHandler() {
if (refresh_mutex_ != nullptr) {
vSemaphoreDelete(refresh_mutex_);
}
if (tp_handle_ != nullptr) {
esp_lcd_touch_del(tp_handle_);
}
if (tp_io_handle_ != nullptr) {
esp_lcd_panel_io_del(tp_io_handle_);
}
if (black_data != nullptr) {
heap_caps_free(black_data);
}
if (white_data != nullptr) {
heap_caps_free(white_data);
}
if (DRAW_BUFFER != nullptr) {
heap_caps_free(DRAW_BUFFER);
}
if (OLD_DRAW_BUFFER != nullptr) {
heap_caps_free(OLD_DRAW_BUFFER);
}
}
esp_err_t EInkDisplayHandler::deep_sleep_display(void) {
ESP_LOGI(TAG, "Putting display into deep sleep mode...");
if (is_deep_sleep_) {
ESP_LOGI(TAG, "Display is already in deep sleep mode");
return ESP_OK;
}
{
esp_err_t err = ESP_OK;
TransactionGuard transaction_guard(this->epd_handler_);
err = transaction_guard.begin(pdMS_TO_TICKS(5000));
if (err != ESP_OK) {
ESP_LOGE(TAG, "Failed to begin transaction for deep sleep: %s", esp_err_to_name(err));
return err;
}
epd_handler_.wait_for_idle();
err = epd_handler_.epd_write_cmd(0x02, transaction_guard.transaction_id()); // power off
if (err != ESP_OK) {
ESP_LOGE(TAG, "Failed to send power off command: %s", esp_err_to_name(err));
return err;
}
epd_handler_.wait_for_idle();
err = epd_handler_.epd_write_cmd(0x07, transaction_guard.transaction_id()); //deep sleep
if (err != ESP_OK) {
ESP_LOGE(TAG, "Failed to send deep sleep command: %s", esp_err_to_name(err));
return err;
}
err = epd_handler_.epd_write_data(0xA5, transaction_guard.transaction_id());
if (err != ESP_OK) {
ESP_LOGE(TAG, "Failed to send deep sleep data: %s", esp_err_to_name(err));
return err;
}
is_deep_sleep_ = true;
return err;
}
}
esp_err_t EInkDisplayHandler::refresh_display() {
esp_err_t err = ESP_OK;
{
ESP_LOGI(TAG, "Waiting for display to be idle...");
TransactionGuard transaction_guard(this->epd_handler_);
err = transaction_guard.begin(pdMS_TO_TICKS(10000));
if (err != ESP_OK) {
ESP_LOGE(TAG, "Failed to begin transaction for display refresh: %s", esp_err_to_name(err));
return err;
}
if (is_deep_sleep_) {
epd_init_internal_(transaction_guard.transaction_id());
}
epd_handler_.wait_for_idle();
ESP_LOGI(TAG, "Starting display refresh...");
err = epd_handler_.epd_write_cmd(0x92, transaction_guard.transaction_id()); // enter normal mode
if (err != ESP_OK) {
ESP_LOGE(TAG, "Failed to enter normal mode: %s", esp_err_to_name(err));
return err;
}
err = epd_handler_.epd_write_cmd(0x12, transaction_guard.transaction_id()); // display refresh
if (err != ESP_OK) {
ESP_LOGE(TAG, "Failed to send display refresh command: %s", esp_err_to_name(err));
return err;
}
vTaskDelay(pdMS_TO_TICKS(MINIMUM_PIN_SETUP_DELAY_MS)); // at least 200us delay
epd_handler_.wait_for_idle();
}
{
SemaphoreGuard guard(refresh_mutex_);
if (guard.take(pdMS_TO_TICKS(5000)) != pdTRUE) {
ESP_LOGE(TAG, "Refresh mutex timeout in refresh_display");
return ESP_ERR_TIMEOUT;
}
partial_refresh_count_ = 0;
force_full_refresh_ = false;
}
ESP_LOGI(TAG, "Refresh complete");
return ESP_OK;
}
esp_err_t EInkDisplayHandler::full_write(const uint8_t* framebuffer, const bool white_basemap) {
ESP_LOGI(TAG, "Starting full refresh (3 seconds)...");
esp_err_t err = ESP_OK;
{
TransactionGuard transaction_guard(this->epd_handler_);
err = transaction_guard.begin(pdMS_TO_TICKS(10000));
if (err != ESP_OK) {
ESP_LOGE(TAG, "Failed to begin transaction for full refresh: %s", esp_err_to_name(err));
return err;
}
if (is_deep_sleep_) {
epd_init_internal_(transaction_guard.transaction_id());
}
write_to_buffer_(framebuffer, RefreshArea { 0, 0, DISPLAY_WIDTH - 1, DISPLAY_HEIGHT - 1 });
epd_handler_.wait_for_idle();
// Step 0: Enter normal mode
err = epd_handler_.epd_write_cmd(0x92, transaction_guard.transaction_id()); // enter normal mode
if (err != ESP_OK) {
ESP_LOGE(TAG, "Failed to enter normal mode: %s", esp_err_to_name(err));
return err;
}
// Step 1: Write old data (0x10) - Arduino uses 0xFF (all white) for base map
{
err = epd_handler_.epd_write_cmd(0x10, transaction_guard.transaction_id());
if (err != ESP_OK) {
ESP_LOGE(TAG, "Failed to send old data command: %s", esp_err_to_name(err));
return err;
}
err = epd_handler_.transfer_spi_data(white_basemap ? black_data : white_data, DISPLAY_BUFFER_SIZE, transaction_guard.transaction_id()); // Send all white data (0xFF)
if (err != ESP_OK) {
ESP_LOGE(TAG, "Failed to send all white data for old data: %s", esp_err_to_name(err));
return err;
}
}
// Step 2: Write new data (0x13)
{
err = epd_handler_.epd_write_cmd(0x13, transaction_guard.transaction_id());
if (err != ESP_OK) {
ESP_LOGE(TAG, "Failed to send new data command: %s", esp_err_to_name(err));
return err;
}
err = epd_handler_.transfer_spi_data(draw_buffer_, DISPLAY_BUFFER_SIZE, transaction_guard.transaction_id()); // Send new framebuffer data
if (err != ESP_OK) {
ESP_LOGE(TAG, "Failed to send framebuffer data for new data: %s", esp_err_to_name(err));
return err;
}
}
// Step 3: Trigger display refresh (DRF)
err = epd_handler_.epd_write_cmd(0x12, transaction_guard.transaction_id());
if (err != ESP_OK) {
ESP_LOGE(TAG, "Failed to send display refresh command: %s", esp_err_to_name(err));
return err;
}
vTaskDelay(pdMS_TO_TICKS(MINIMUM_PIN_SETUP_DELAY_MS)); // at least 200us delay
ESP_LOGI(TAG, "Display refresh triggered, BUSY pin: %d", gpio_get_level(PIN_BUSY));
// Wait for refresh to complete
epd_handler_.wait_for_idle();
}
err = deep_sleep_display();
if (err != ESP_OK) {
ESP_LOGE(TAG, "Failed to enter deep sleep after full refresh: %s", esp_err_to_name(err));
return err;
}
refresh_area_.reset();
memcpy(old_buffer_, draw_buffer_, DISPLAY_BUFFER_SIZE);
ESP_LOGI(TAG, "Full refresh complete");
return ESP_OK;
}
// TODO: Partial refresh is inverted in color
esp_err_t EInkDisplayHandler::partial_refresh(const uint8_t* incoming_partial_framebuffer, const RefreshArea& incoming_area, const bool is_last_partial_update) {
ESP_LOGI(TAG, "Starting partial refresh (0.3 seconds)...");
esp_err_t err = ESP_OK;
write_to_buffer_(incoming_partial_framebuffer, incoming_area);
// Always expand refresh_area_ to include incoming_area
refresh_area_.expand_to_include(incoming_area);
if (!is_last_partial_update) {
ESP_LOGI(TAG, "Partial refresh skipped (not last partial update)");
return ESP_OK;
}
{
TransactionGuard transaction_guard(this->epd_handler_);
err = transaction_guard.begin(pdMS_TO_TICKS(5000));
if (err != ESP_OK) {
ESP_LOGE(TAG, "Failed to begin transaction for partial refresh: %s", esp_err_to_name(err));
return err;
}
// Wake display from deep sleep INSIDE the transaction to prevent race conditions
if (is_deep_sleep_) {
err = epd_init_internal_(transaction_guard.transaction_id());
if (err != ESP_OK) {
ESP_LOGE(TAG, "Failed to initialize EPD for partial refresh: %s", esp_err_to_name(err));
return err;
}
err = refresh_old_buffer_(transaction_guard.transaction_id());
if (err != ESP_OK) {
ESP_LOGE(TAG, "Failed to refresh old buffer during partial refresh init: %s", esp_err_to_name(err));
return err;
}
}
RefreshArea area = refresh_area_;
if (area.x1 % 8 != 0 || area.x2 % 8 != 7) {
ESP_LOGE(TAG, "Partial refresh area x1 and x2 must be byte-aligned (x1 %% 8 == 0 and x2 %% 8 == 7)");
ESP_LOGI(TAG, "Given area: x1=%d, x2=%d", area.x1, area.x2);
return ESP_ERR_INVALID_ARG;
}
// Calculate partial buffer size based on the refresh area
const uint32_t area_width_bytes = (area.x2 - area.x1 + 1) / 8;
const uint32_t area_height = area.y2 - area.y1 + 1;
const size_t partial_buffer_size = area_width_bytes * area_height;
// uint8_t* partial_buffer = new uint8_t[partial_buffer_size];
uint8_t* partial_buffer = static_cast<uint8_t*>(heap_caps_malloc(partial_buffer_size, MALLOC_CAP_DMA | MALLOC_CAP_INTERNAL));
if (partial_buffer == nullptr) {
ESP_LOGE(TAG, "Failed to allocate partial buffer for partial refresh");
return ESP_ERR_NO_MEM;
}
// Copy the relevant area from draw_buffer_ to partial_buffer
for (int32_t row = 0; row < area_height; ++row) {
uint32_t fb_y = area.y1 + row;
uint32_t fb_x_byte_start = area.x1 / 8;
uint8_t* fb_ptr = &draw_buffer_[fb_y * (DISPLAY_WIDTH / 8) + fb_x_byte_start];
uint8_t* dest_ptr = &partial_buffer[row * area_width_bytes];
memcpy(dest_ptr, fb_ptr, area_width_bytes);
}
epd_handler_.wait_for_idle();
// Step 1 VCOM setting
std::vector<uint8_t> vcom_data = { 0xA9, 0x07 };
err = epd_handler_.epd_write_cmd_with_data(0x50, vcom_data, transaction_guard.transaction_id()); // VCOM for partial refresh
if (err != ESP_OK) {
ESP_LOGE(TAG, "Failed to set VCOM for partial refresh: %s", esp_err_to_name(err));
return err;
}
// Step 2: Enter partial refresh mode
err = epd_handler_.epd_write_cmd(0x91, transaction_guard.transaction_id()); // Enter partial mode
if (err != ESP_OK) {
ESP_LOGE(TAG, "Failed to enter partial refresh mode: %s", esp_err_to_name(err));
return err;
}
// Step 3: Set partial window
{
// ------DD
// DDDDD000
// ------DD
// DDDDD111
// ------DD
// DDDDDDDD
// ------DD
// DDDDDDDD
// -------D
// area should be multiple of 8 in x direction
const int32_t x_bank_start = area.x1 >> 3;
const int32_t x_bank_end = area.x2 >> 3;
std::vector<uint8_t> window_data = {
// x start, [9:8] bit -> 6 and 7 bits of x_bank_start
static_cast<uint8_t>((x_bank_start >> 5) & 0x03),
// x start, [7:3] bit + 3 bits of 0 -> 5 bits of x_bank_start and pad 3 LSBs as 0
static_cast<uint8_t>((x_bank_start & 0x1F) << 3),
// x end, [9:8] bit
static_cast<uint8_t>((x_bank_end >> 5) & 0x03),
// x end, [7:3] bit + 3 bits of 1
static_cast<uint8_t>(((x_bank_end & 0x1F) << 3) | 0x07),
// y start, [9:8] bit
static_cast<uint8_t>((area.y1 >> 8) & 0x03),
// y start, [7:0] bit
static_cast<uint8_t>(area.y1 & 0xFF),
// y end, [9:8] bit
static_cast<uint8_t>((area.y2 >> 8) & 0x03),
// y end, [7:0] bit
static_cast<uint8_t>(area.y2 & 0xFF),
0x01 // Gates scan both inside and outside of the partial window
};
ESP_LOGI(TAG, "Setting partial window: x1=%d, y1=%d, x2=%d, y2=%d",
area.x1, area.y1, area.x2, area.y2);
ESP_LOGI(TAG, "Partial window data: %02X %02X %02X %02X %02X %02X %02X %02X",
window_data[0], window_data[1], window_data[2], window_data[3], window_data[4],
window_data[5], window_data[6], window_data[7]);
err = epd_handler_.epd_write_cmd_with_data(0x90, window_data, transaction_guard.transaction_id()); // Set partial window
if (err != ESP_OK) {
ESP_LOGE(TAG, "Failed to send set partial window command: %s", esp_err_to_name(err));
return err;
}
}
// Step 5: Write new data (0x13)
{
err = epd_handler_.epd_write_cmd(0x13, transaction_guard.transaction_id());
if (err != ESP_OK) {
ESP_LOGE(TAG, "Failed to send new data command for partial refresh: %s", esp_err_to_name(err));
heap_caps_free(partial_buffer);
return err;
}
// Send only the partial area data, not the full display buffer
ESP_LOGI(TAG, "Sending new partial buffer: %zu bytes (area: %dx%d)",
partial_buffer_size, area_width_bytes * 8, area_height);
err = epd_handler_.transfer_spi_data(partial_buffer, partial_buffer_size, transaction_guard.transaction_id());
if (err != ESP_OK) {
ESP_LOGE(TAG, "Failed to send partial_buffer data for partial refresh: %s", esp_err_to_name(err));
heap_caps_free(partial_buffer);
return err;
}
memcpy(old_buffer_, draw_buffer_, DISPLAY_BUFFER_SIZE);
}
// Clean up partial buffer
heap_caps_free(partial_buffer);
// Step 6: Trigger partial display refresh (DRF)
// Use 0x12 (Display Update) command - same as full refresh, per sample code
err = epd_handler_.epd_write_cmd(0x12, transaction_guard.transaction_id());
if (err != ESP_OK) {
ESP_LOGE(TAG, "Failed to send display refresh command for partial refresh: %s", esp_err_to_name(err));
return err;
}
vTaskDelay(pdMS_TO_TICKS(MINIMUM_PIN_SETUP_DELAY_MS)); // at least 200us delay
epd_handler_.wait_for_idle();
// Step 7: Exit partial mode
err = epd_handler_.epd_write_cmd(0x92, transaction_guard.transaction_id());
if (err != ESP_OK) {
ESP_LOGE(TAG, "Failed to exit partial refresh mode: %s", esp_err_to_name(err));
return err;
}
}
ESP_LOGI(TAG, "Partial refresh complete");
if (force_full_refresh_) {
ESP_LOGI(TAG, "Full refresh already requested, skipping partial refresh count increment");
err = refresh_display();
if (err != ESP_OK) {
ESP_LOGE(TAG, "Failed to perform forced full refresh: %s", esp_err_to_name(err));
return err;
}
return ESP_OK;
}
{
SemaphoreGuard guard(refresh_mutex_);
if (guard.take(pdMS_TO_TICKS(5000)) != pdTRUE) {
ESP_LOGE(TAG, "Refresh mutex timeout in partial_refresh");
return ESP_ERR_TIMEOUT;
}
if (partial_refresh_count_ < UINT32_MAX) {
partial_refresh_count_++;
}
if (partial_refresh_count_ >= PARTIAL_REFRESH_THRESHOLD) {
ESP_LOGI(TAG, "Partial refresh count %u reached threshold %u, next refresh will be full",
partial_refresh_count_, PARTIAL_REFRESH_THRESHOLD);
force_full_refresh_ = true;
partial_refresh_count_ = 0;
}
}
err = deep_sleep_display();
if (err != ESP_OK) {
ESP_LOGE(TAG, "Failed to enter deep sleep after partial refresh: %s", esp_err_to_name(err));
return err;
}
refresh_area_.reset();
return ESP_OK;
}
esp_err_t EInkDisplayHandler::clear_display(void) {
ESP_LOGI(TAG, "Clearing display to all white...");
esp_err_t err = full_write(white_data, false);
if (err != ESP_OK) {
ESP_LOGE(TAG, "Failed to clear display: %s", esp_err_to_name(err));
return err;
}
ESP_LOGI(TAG, "Display cleared to all white");
return ESP_OK;
}
void EInkDisplayHandler::write_to_buffer_(const uint8_t* src_buffer, const RefreshArea& area) {
// Copy the relevant area from src_buffer to draw_buffer_
const uint32_t area_width_bytes = (area.x2 - area.x1 + 1) / 8;
const uint32_t area_height = area.y2 - area.y1 + 1;
for (int32_t row = 0; row < area_height; ++row) {
uint32_t fb_y = area.y1 + row;
uint32_t fb_x_byte_start = area.x1 / 8;
const uint8_t* src_ptr = &src_buffer[row * area_width_bytes];
uint8_t* dest_ptr = &draw_buffer_[fb_y * (DISPLAY_WIDTH / 8) + fb_x_byte_start];
memcpy(dest_ptr, src_ptr, area_width_bytes);
}
}
// Request a full refresh on next flush
void EInkDisplayHandler::request_full_refresh(void) {
SemaphoreGuard guard(refresh_mutex_);
if (guard.take(pdMS_TO_TICKS(100))) {
force_full_refresh_ = true;
partial_refresh_count_ = 0;
ESP_LOGI(TAG, "Full refresh requested");
} else {
ESP_LOGE(TAG, "Failed to take refresh mutex to request full refresh");
}
}
esp_err_t EInkDisplayHandler::init_devices(EventGroupHandle_t system_event_group) {
esp_err_t err;
err = init_display_pins_();
if (err != ESP_OK) {
ESP_LOGE(TAG, "Failed to initialize display pins: %s", esp_err_to_name(err));
return err;
}
err = this->epd_handler_.init();
if (err != ESP_OK) {
ESP_LOGE(TAG, "Failed to initialize EPD handler: %s", esp_err_to_name(err));
return err;
}
err = init_touch_();
if (err != ESP_OK) {
ESP_LOGE(TAG, "Failed to initialize touch: %s", esp_err_to_name(err));
return err;
}
// if system_event_group is provided, set display ready bits
if (system_event_group != nullptr) {
// Indicate that display is ready
xEventGroupSetBits(system_event_group, DISPLAY_READY_BIT | TOUCH_CALIBRATED_BIT);
ESP_LOGI(TAG, "Display marked as ready");
}
return ESP_OK;
}
esp_err_t EInkDisplayHandler::init_display_pins_(void) {
ESP_LOGI(TAG, "Initializing E-Ink display handler...");
esp_err_t ret;
// Initialize GPIO pins
gpio_config_t io_conf = {};
io_conf.pin_bit_mask = (1ULL << PIN_DC) | (1ULL << PIN_RST);
io_conf.mode = GPIO_MODE_OUTPUT;
io_conf.pull_up_en = GPIO_PULLUP_DISABLE;
io_conf.pull_down_en = GPIO_PULLDOWN_DISABLE;
io_conf.intr_type = GPIO_INTR_DISABLE;
ret = gpio_config(&io_conf);
if (ret != ESP_OK) {
ESP_LOGE(TAG, "Failed to configure GPIO pins: %s", esp_err_to_name(ret));
return ret;
}
// Configure BUSY pin as input (no pull-up like sample code)
io_conf.pin_bit_mask = (1ULL << PIN_BUSY);
io_conf.mode = GPIO_MODE_INPUT;
io_conf.pull_up_en = GPIO_PULLUP_DISABLE;
io_conf.pull_down_en = GPIO_PULLDOWN_DISABLE;
ret = gpio_config(&io_conf);
if (ret != ESP_OK) {
ESP_LOGE(TAG, "Failed to configure BUSY pin: %s", esp_err_to_name(ret));
return ret;
}
return ESP_OK;
}
esp_err_t EInkDisplayHandler::epd_init_internal_(uint32_t transaction_id) {
ESP_LOGI(TAG, "Initializing EPD...");
esp_err_t err;
// 1. Hardware Reset
err = gpio_set_level(PIN_RST, 0);
if (err != ESP_OK) {
ESP_LOGE(TAG, "Failed to set PIN_RST low: %s", esp_err_to_name(err));
return err;
}
vTaskDelay(pdMS_TO_TICKS(MINIMUM_PIN_SETUP_DELAY_MS));
err = gpio_set_level(PIN_RST, 1);
if (err != ESP_OK) {
ESP_LOGE(TAG, "Failed to set PIN_RST high: %s", esp_err_to_name(err));
return err;
}
vTaskDelay(pdMS_TO_TICKS(MINIMUM_PIN_SETUP_DELAY_MS));
// 2. Initialization Sequence
std::vector<uint8_t> panel_setting_data = { 0x1F };
err = epd_handler_.epd_write_cmd_with_data(0x00, panel_setting_data, transaction_id); // Panel Setting
if (err != ESP_OK) {
ESP_LOGE(TAG, "Failed to send Panel Setting command: %s", esp_err_to_name(err));
return err;
}
vTaskDelay(pdMS_TO_TICKS(MINIMUM_PIN_SETUP_DELAY_MS));
std::vector<uint8_t> vcom_data = { 0x10, 0x07 };
err = epd_handler_.epd_write_cmd_with_data(0x50, vcom_data, transaction_id); // VCOM
if (err != ESP_OK) {
ESP_LOGE(TAG, "Failed to send VCOM command: %s", esp_err_to_name(err));
return err;
}
vTaskDelay(pdMS_TO_TICKS(MINIMUM_PIN_SETUP_DELAY_MS));
err = epd_handler_.epd_write_cmd(0x04, transaction_id); // Power ON
if (err != ESP_OK) {
ESP_LOGE(TAG, "Failed to send Power ON command: %s", esp_err_to_name(err));
return err;
}
vTaskDelay(pdMS_TO_TICKS(MINIMUM_POWER_ON_DELAY_MS)); // Wait for power on
// Check BUSY pin with detailed logging
ESP_LOGI(TAG, "Waiting for EPD to be ready after power on...");
ESP_LOGI(TAG, "BUSY pin level after power on: %d (0=BUSY, 1=FREE)", gpio_get_level(PIN_BUSY));
epd_handler_.wait_for_idle();
std::vector<uint8_t> booster_data = { 0x27, 0x27, 0x18, 0x17 };
err = epd_handler_.epd_write_cmd_with_data(0x06, booster_data, transaction_id); // Booster Soft Start
if (err != ESP_OK) {
ESP_LOGE(TAG, "Failed to send Booster Soft Start command: %s", esp_err_to_name(err));
return err;
}
vTaskDelay(pdMS_TO_TICKS(MINIMUM_PIN_SETUP_DELAY_MS));
// Enhanced display drive commands
std::vector<uint8_t> e0_data = { 0x02 };
err = epd_handler_.epd_write_cmd_with_data(0xE0, e0_data, transaction_id);
if (err != ESP_OK) {
ESP_LOGE(TAG, "Failed to send Enhanced Display Drive command: %s", esp_err_to_name(err));
return err;
}
std::vector<uint8_t> e5_data = { 0x5A };
err = epd_handler_.epd_write_cmd_with_data(0xE5, e5_data, transaction_id);
if (err != ESP_OK) {
ESP_LOGE(TAG, "Failed to send Enhanced Display Drive command: %s", esp_err_to_name(err));
return err;
}
is_deep_sleep_ = false;
return err;
}
// Internal version that uses an existing transaction (no separate TransactionGuard)
esp_err_t EInkDisplayHandler::epd_init_partial_internal_(uint32_t transaction_id) {
ESP_LOGI(TAG, "Initializing EPD for partial refresh (internal)...");
esp_err_t err = ESP_OK;
// 1. Hardware Reset
err = gpio_set_level(PIN_RST, 0);
if (err != ESP_OK) {
ESP_LOGE(TAG, "Failed to set PIN_RST low: %s", esp_err_to_name(err));
return err;
}
vTaskDelay(pdMS_TO_TICKS(MINIMUM_PIN_SETUP_DELAY_MS));
err = gpio_set_level(PIN_RST, 1);
if (err != ESP_OK) {
ESP_LOGE(TAG, "Failed to set PIN_RST high: %s", esp_err_to_name(err));
return err;
}
vTaskDelay(pdMS_TO_TICKS(MINIMUM_PIN_SETUP_DELAY_MS));
// 2. Panel Setting
std::vector<uint8_t> panel_setting_data = { 0x1F };
err = epd_handler_.epd_write_cmd_with_data(0x00, panel_setting_data, transaction_id);
if (err != ESP_OK) {
ESP_LOGE(TAG, "Failed to send Panel Setting command: %s", esp_err_to_name(err));
return err;
}
vTaskDelay(pdMS_TO_TICKS(MINIMUM_PIN_SETUP_DELAY_MS));
// 3. Power ON
err = epd_handler_.epd_write_cmd(0x04, transaction_id);
if (err != ESP_OK) {
ESP_LOGE(TAG, "Failed to send Power ON command: %s", esp_err_to_name(err));
return err;
}
vTaskDelay(pdMS_TO_TICKS(MINIMUM_POWER_ON_DELAY_MS));
epd_handler_.wait_for_idle();
// 4. Partial initialization sequence - Enhanced Display Drive
std::vector<uint8_t> e0_data = { 0x02 };
err = epd_handler_.epd_write_cmd_with_data(0xE0, e0_data, transaction_id);
if (err != ESP_OK) {
ESP_LOGE(TAG, "Failed to send Enhanced Display Drive command (E0): %s", esp_err_to_name(err));
return err;
}
std::vector<uint8_t> e5_data = { 0x6E };
err = epd_handler_.epd_write_cmd_with_data(0xE5, e5_data, transaction_id);
if (err != ESP_OK) {
ESP_LOGE(TAG, "Failed to send Enhanced Display Drive command (E5): %s", esp_err_to_name(err));
return err;
}
is_deep_sleep_ = false;
err = refresh_old_buffer_(transaction_id);
if (err != ESP_OK) {
ESP_LOGE(TAG, "Failed to refresh old buffer during partial init: %s", esp_err_to_name(err));
return err;
}
ESP_LOGI(TAG, "EPD partial init (internal) complete");
return ESP_OK;
}
esp_err_t EInkDisplayHandler::init_touch_() {
ESP_LOGI(TAG, "Initializing touch...");
esp_err_t err;
// 1. Initialize I2C Bus
i2c_config_t conf = {};
conf.mode = I2C_MODE_MASTER;
conf.sda_io_num = PIN_TOUCH_SDA;
conf.scl_io_num = PIN_TOUCH_SCL;
conf.sda_pullup_en = GPIO_PULLUP_ENABLE;
conf.scl_pullup_en = GPIO_PULLUP_ENABLE;
conf.master.clk_speed = 400000;
err = i2c_param_config(I2C_NUM_0, &conf);
if (err != ESP_OK) {
ESP_LOGE(TAG, "Failed to configure I2C parameters: %s", esp_err_to_name(err));
return err;
}
err = i2c_driver_install(I2C_NUM_0, I2C_MODE_MASTER, 0, 0, 0);
if (err != ESP_OK) {
ESP_LOGE(TAG, "Failed to install I2C driver: %s", esp_err_to_name(err));
return err;
}
ESP_LOGI("DisplayHandler", "I2C driver installed");
// 2. Initialize GT911
ESP_LOGI("DisplayHandler", "Initializing GT911 touch controller...");
esp_lcd_panel_io_i2c_config_t tp_io_config = {};
// temporarily disable -Wmissing-field-initializers, as ESP_LCD_TOUCH_IO_I2C_GT911_CONFIG macro does not set all fields
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wmissing-field-initializers"
esp_lcd_panel_io_i2c_config_t default_tp_io_config = ESP_LCD_TOUCH_IO_I2C_GT911_CONFIG();
#pragma GCC diagnostic pop
tp_io_config.dev_addr = default_tp_io_config.dev_addr;
tp_io_config.control_phase_bytes = default_tp_io_config.control_phase_bytes;
tp_io_config.dc_bit_offset = default_tp_io_config.dc_bit_offset;
tp_io_config.lcd_cmd_bits = default_tp_io_config.lcd_cmd_bits;
tp_io_config.flags = default_tp_io_config.flags;
esp_lcd_new_panel_io_i2c(I2C_NUM_0, &tp_io_config, &tp_io_handle_);
// GT911-specific config with I2C address (0x5D = INT low during reset)
static esp_lcd_touch_io_gt911_config_t gt911_config = {
.dev_addr = ESP_LCD_TOUCH_IO_I2C_GT911_ADDRESS // 0x5D
};
esp_lcd_touch_config_t tp_cfg = {};
tp_cfg.x_max = DISPLAY_WIDTH;
tp_cfg.y_max = DISPLAY_HEIGHT;
tp_cfg.rst_gpio_num = PIN_TOUCH_RST;
tp_cfg.int_gpio_num = PIN_TOUCH_IRQ;
tp_cfg.driver_data = &gt911_config; // Pass GT911-specific config for automatic reset
err = esp_lcd_touch_new_i2c_gt911(tp_io_handle_, &tp_cfg, &tp_handle_);
if (err == ESP_OK && tp_handle_ != nullptr) {
ESP_LOGI("DisplayHandler", "GT911 touch controller initialized successfully");
} else {
ESP_LOGE("DisplayHandler", "GT911 touch controller initialization failed: %s", esp_err_to_name(err));
tp_handle_ = nullptr;
}
return err;
}
esp_err_t EInkDisplayHandler::refresh_old_buffer_(uint32_t transaction_id) {
ESP_LOGI(TAG, "Refreshing display SRAM to restore state after wake...");
esp_err_t err;
err = epd_handler_.epd_write_cmd(0x92, transaction_id); // enter normal mode
if (err != ESP_OK) {
ESP_LOGE(TAG, "Failed to enter normal mode: %s", esp_err_to_name(err));
return err;
}
// Write OLD data (0x10) as all 0x00 (white in e-ink terms)
// This tells the controller: "assume display was all white"
// Matches sample's EPD_WhiteScreen_ALL() which uses 0x00 for old SRAM
// The differential refresh: old=0 + new=0 → stay white, old=0 + new=1 → drive to black
err = epd_handler_.epd_write_cmd(0x10, transaction_id);
if (err != ESP_OK) {
ESP_LOGE(TAG, "Failed to send old data command: %s", esp_err_to_name(err));
return err;
}
// Send the old buffer as old data
err = epd_handler_.transfer_spi_data(old_buffer_, DISPLAY_BUFFER_SIZE, transaction_id);
if (err != ESP_OK) {
ESP_LOGE(TAG, "Failed to send white baseline to old SRAM: %s", esp_err_to_name(err));
return err;
}
// Write NEW data (0x13) with the actual display content
// This restores the display to show old_buffer_ content
err = epd_handler_.epd_write_cmd(0x13, transaction_id);
if (err != ESP_OK) {
ESP_LOGE(TAG, "Failed to send new data command: %s", esp_err_to_name(err));
return err;
}
// Send the last displayed content to new SRAM
err = epd_handler_.transfer_spi_data(old_buffer_, DISPLAY_BUFFER_SIZE, transaction_id);
if (err != ESP_OK) {
ESP_LOGE(TAG, "Failed to send display content to new SRAM: %s", esp_err_to_name(err));
return err;
}
ESP_LOGI(TAG, "Display SRAM restored successfully");
return ESP_OK;
}

View File

@@ -1,661 +0,0 @@
#include "display/eink_display_handler.h"
#include "display/constants.h"
#include "common/constants.h"
#include "esp_log.h"
#include "esp_heap_caps.h"
#include "esp_task_wdt.h"
#include <cstring>
#define TAG "EInkDisplayHandler"
#define BUSY_ACTIVE_LEVEL 0 // BUSY pin is active low
#define BUSY_INACTIVE_LEVEL 1
EInkDisplayHandler::EInkDisplayHandler(EventGroupHandle_t system_event_group)
: DisplayHandler(system_event_group) {
_refresh_mutex = xSemaphoreCreateMutex();
if (_refresh_mutex == nullptr) {
ESP_LOGE(TAG, "Failed to create refresh mutex");
}
}
EInkDisplayHandler::~EInkDisplayHandler() {
if (_refresh_task_handle != nullptr) {
vTaskDelete(_refresh_task_handle);
}
if (_touch_task_handle != nullptr) {
vTaskDelete(_touch_task_handle);
}
if (_refresh_queue != nullptr) {
vQueueDelete(_refresh_queue);
}
if (_lvgl_display != nullptr) {
lv_display_delete(_lvgl_display);
_lvgl_display = nullptr;
if (_lvgl_draw_buf != nullptr) {
lv_draw_buf_destroy(_lvgl_draw_buf);
_lvgl_draw_buf = nullptr;
}
}
if (_lvgl_touch_indev != nullptr) {
lvgl_port_remove_touch(_lvgl_touch_indev);
}
if (_framebuffer != nullptr) {
heap_caps_free(_framebuffer);
}
if (_refresh_mutex != nullptr) {
vSemaphoreDelete(_refresh_mutex);
}
}
void EInkDisplayHandler::init() {
ESP_LOGI(TAG, "Initializing E-Ink display handler...");
// Initialize GPIO pins
gpio_config_t io_conf = {};
io_conf.pin_bit_mask = (1ULL << PIN_DC) | (1ULL << PIN_RST);
io_conf.mode = GPIO_MODE_OUTPUT;
io_conf.pull_up_en = GPIO_PULLUP_DISABLE;
io_conf.pull_down_en = GPIO_PULLDOWN_DISABLE;
io_conf.intr_type = GPIO_INTR_DISABLE;
gpio_config(&io_conf);
// Configure BUSY pin as input (no pull-up like sample code)
io_conf.pin_bit_mask = (1ULL << PIN_BUSY);
io_conf.mode = GPIO_MODE_INPUT;
io_conf.pull_up_en = GPIO_PULLUP_DISABLE;
gpio_config(&io_conf);
// Initialize SPI bus
spi_bus_config_t buscfg = {};
buscfg.mosi_io_num = 11; // MOSI pin
buscfg.miso_io_num = -1; // No MISO for e-paper
buscfg.sclk_io_num = 12; // SCK pin
buscfg.quadwp_io_num = -1;
buscfg.quadhd_io_num = -1;
buscfg.max_transfer_sz = DISPLAY_BUFFER_SIZE;
esp_err_t ret = spi_bus_initialize(SPI2_HOST, &buscfg, SPI_DMA_CH_AUTO);
if (ret != ESP_OK) {
ESP_LOGE(TAG, "Failed to initialize SPI bus: %s", esp_err_to_name(ret));
return;
}
// Add SPI device
spi_device_interface_config_t devcfg = {};
devcfg.clock_speed_hz = 6 * 1000 * 1000; // 6 MHz (reduced for reliability)
devcfg.mode = 0; // SPI mode 0
devcfg.spics_io_num = PIN_CS;
devcfg.queue_size = 7; // Queue size for non-blocking transactions
devcfg.pre_cb = nullptr;
ret = spi_bus_add_device(SPI2_HOST, &devcfg, &_spi);
if (ret != ESP_OK) {
ESP_LOGE(TAG, "Failed to add SPI device: %s", esp_err_to_name(ret));
return;
}
// Initialize base display and touch devices
init_devices(false); // Don't set ready bit yet
// Create refresh queue (queue 5 refresh requests)
_refresh_queue = xQueueCreate(5, sizeof(bool));
if (_refresh_queue == nullptr) {
ESP_LOGE(TAG, "Failed to create refresh queue");
return;
}
// Create refresh task
BaseType_t ret_task = xTaskCreatePinnedToCore(
_refresh_task,
"eink_refresh",
8192,
this,
5, // Priority - lower than LVGL task
&_refresh_task_handle,
1 // Pin to core 1
);
if (ret_task != pdPASS) {
ESP_LOGE(TAG, "Failed to create refresh task");
return;
}
// Allocate framebuffer - try PSRAM first, fallback to internal RAM
// Note: Internal framebuffer excludes the 8-byte palette (raw pixel data only)
const size_t fb_size = DISPLAY_BUFFER_SIZE - 8; // Exclude palette from internal storage
_framebuffer = (uint8_t*)heap_caps_malloc(fb_size, MALLOC_CAP_SPIRAM);
if (_framebuffer != nullptr) {
_framebuffer_in_psram = true;
ESP_LOGI(TAG, "Framebuffer allocated in PSRAM (%zu bytes, LVGL buffer: %d bytes)",
fb_size, DISPLAY_BUFFER_SIZE);
} else {
ESP_LOGW(TAG, "PSRAM not available, allocating framebuffer in internal RAM");
_framebuffer = (uint8_t*)heap_caps_malloc(fb_size, MALLOC_CAP_INTERNAL);
_framebuffer_in_psram = false;
if (_framebuffer == nullptr) {
ESP_LOGE(TAG, "Failed to allocate framebuffer");
return;
}
ESP_LOGI(TAG, "Framebuffer allocated in internal RAM (%zu bytes, LVGL buffer: %d bytes)",
fb_size, DISPLAY_BUFFER_SIZE);
}
memset(_framebuffer, 0xFF, fb_size); // Initialize to white
// Perform initial full refresh to clear display BEFORE creating LVGL display
// This prevents LVGL from trying to render during the initial clear
ESP_LOGI(TAG, "Performing initial display clear...");
_perform_full_refresh(_framebuffer);
ESP_LOGI(TAG, "Initial display clear complete");
// Create LVGL display manually (no esp_lcd panel for e-paper)
lv_display_t* disp = lv_display_create(DISPLAY_WIDTH, DISPLAY_HEIGHT);
if (disp == nullptr) {
ESP_LOGE(TAG, "Failed to create LVGL display");
return;
}
/* 1-bit e-paper display */
lv_display_set_color_format(disp, LV_COLOR_FORMAT_I1);
/* Disable antialiasing for monochrome display to ensure crisp 1px lines */
lv_display_set_antialiasing(disp, false);
/* Create a draw buffer covering ~40 lines */
_lvgl_draw_buf = lv_draw_buf_create(DISPLAY_WIDTH, DISPLAY_HEIGHT, LV_COLOR_FORMAT_I1, LV_STRIDE_AUTO);
if (_lvgl_draw_buf == nullptr) {
ESP_LOGE(TAG, "Failed to create LVGL draw buffer");
lv_display_delete(disp);
return;
}
lv_display_set_draw_buffers(disp, _lvgl_draw_buf, NULL);
lv_display_set_render_mode(disp, LV_DISPLAY_RENDER_MODE_DIRECT);
// Set custom flush callback and user data
lv_display_set_flush_cb(disp, _lvgl_flush_cb);
lv_display_set_user_data(disp, this);
_lvgl_display = disp;
ESP_LOGI(TAG, "LVGL display registered");
// Register GT911 touch input with LVGL, only if touch handle is valid
esp_lcd_touch_handle_t tp_handle = get_touch_handle();
if (tp_handle == nullptr) {
ESP_LOGE(TAG, "Touch handle is NULL — touch initialization failed; skipping LVGL touch registration");
} else {
const lvgl_port_touch_cfg_t touch_cfg = {
.disp = _lvgl_display,
.handle = tp_handle,
.scale = {}, // Default scaling
};
_lvgl_touch_indev = lvgl_port_add_touch(&touch_cfg);
if (_lvgl_touch_indev == nullptr) {
ESP_LOGE(TAG, "Failed to register LVGL touch input");
return;
}
// Override touch read callback to check BUSY pin
lv_indev_set_read_cb(_lvgl_touch_indev, _lvgl_touch_read_cb);
lv_indev_set_user_data(_lvgl_touch_indev, this);
ESP_LOGI(TAG, "LVGL touch input registered");
}
// Set display ready bits
xEventGroupSetBits(_system_event_group, DISPLAY_READY_BIT | TOUCH_CALIBRATED_BIT);
ESP_LOGI(TAG, "E-Ink display handler initialized successfully");
}
void EInkDisplayHandler::start_touch_task() {
// Note: With lvgl_port_add_touch, the ESP-IDF LVGL port handles touch reading internally
// We don't need a separate touch task unless we want custom processing
ESP_LOGI(TAG, "Touch input handled by LVGL port");
}
void EInkDisplayHandler::request_full_refresh() {
if (xSemaphoreTake(_refresh_mutex, pdMS_TO_TICKS(100)) == pdTRUE) {
_force_full_refresh = true;
_partial_refresh_count = 0;
xSemaphoreGive(_refresh_mutex);
ESP_LOGI(TAG, "Full refresh requested");
}
}
bool EInkDisplayHandler::is_busy() const {
return gpio_get_level(PIN_BUSY) == BUSY_ACTIVE_LEVEL; // BUSY is active LOW
}
void EInkDisplayHandler::_lvgl_flush_cb(lv_display_t* disp, const lv_area_t* area, uint8_t* px_map) {
EInkDisplayHandler* handler = static_cast<EInkDisplayHandler*>(lv_display_get_user_data(disp));
if (handler == nullptr) {
ESP_LOGE(TAG, "Invalid handler in flush callback");
lv_display_flush_ready(disp);
return;
}
// Check if display is busy with detailed logging
int busy_level = gpio_get_level(PIN_BUSY);
ESP_LOGI(TAG, "Flush callback: BUSY pin = %d, is_busy() = %d", busy_level, handler->is_busy());
if (handler->is_busy()) {
ESP_LOGW(TAG, "Display busy (BUSY pin = 0), skipping flush");
lv_display_flush_ready(disp);
return;
}
// Wait for any ongoing refresh to complete
handler->_wait_for_busy();
bool perform_full_refresh = false;
if (xSemaphoreTake(handler->_refresh_mutex, pdMS_TO_TICKS(100)) == pdTRUE) {
// Check if full refresh is needed
if (handler->_force_full_refresh) {
perform_full_refresh = true;
handler->_force_full_refresh = false;
handler->_partial_refresh_count = 0;
} else {
handler->_partial_refresh_count++;
if (handler->_partial_refresh_count >= PARTIAL_REFRESH_THRESHOLD) {
perform_full_refresh = true;
handler->_partial_refresh_count = 0;
}
}
xSemaphoreGive(handler->_refresh_mutex);
}
// Copy LVGL buffer to framebuffer
// For 1-bit mode, LVGL provides data in packed format (8 pixels per byte)
// CRITICAL: Skip first 8 bytes (LVGL I1 palette) as per LVGL documentation
uint8_t* pixel_data = px_map + 8; // Skip 8-byte palette
int32_t w = lv_area_get_width(area);
int32_t h = lv_area_get_height(area);
ESP_LOGI(TAG, "Flushing area: x=%d, y=%d, w=%d, h=%d, full_refresh=%d",
area->x1, area->y1, w, h, perform_full_refresh);
ESP_LOGI(TAG, "Buffer: px_map=%p, pixel_data=%p, palette skipped: %d bytes",
(void*)px_map, (void*)pixel_data, 8);
// Check if this is a full screen update - if so, simple copy
if (area->x1 == 0 && area->y1 == 0 && w == DISPLAY_WIDTH && h == DISPLAY_HEIGHT) {
ESP_LOGI(TAG, "Full screen update, direct copy (skipping palette)");
memcpy(handler->_framebuffer, pixel_data, DISPLAY_BUFFER_SIZE - 8);
} else {
ESP_LOGI(TAG, "Partial area update");
// In DIRECT render mode, px_map points to the full screen buffer
// The stride is always the full display width
const uint32_t stride = DISPLAY_WIDTH / 8; // 800 / 8 = 100 bytes per row
// Check if we can do row-by-row copy (byte-aligned on both x1 and width)
bool byte_aligned = (area->x1 % 8 == 0) && (w % 8 == 0);
if (byte_aligned) {
// Optimized: byte-aligned row copy
ESP_LOGI(TAG, "Byte-aligned copy: x=%ld, y=%ld, w=%ld, h=%ld",
(long)area->x1, (long)area->y1, (long)w, (long)h);
uint32_t x_byte = area->x1 / 8;
uint32_t width_bytes = w / 8;
for (int32_t y = 0; y < h; y++) {
int32_t fb_y = area->y1 + y;
if (fb_y >= DISPLAY_HEIGHT) break;
uint8_t* src = pixel_data + (fb_y * stride + x_byte);
uint8_t* dst = handler->_framebuffer + (fb_y * stride + x_byte);
memcpy(dst, src, width_bytes);
}
} else {
// Bit-level copy for non-aligned regions
ESP_LOGI(TAG, "Bit-level copy: x=%ld, y=%ld, w=%ld, h=%ld",
(long)area->x1, (long)area->y1, (long)w, (long)h);
for (int32_t y = 0; y < h; y++) {
int32_t fb_y = area->y1 + y;
if (fb_y >= DISPLAY_HEIGHT) break;
for (int32_t x = 0; x < w; x++) {
int32_t fb_x = area->x1 + x;
if (fb_x >= DISPLAY_WIDTH) break;
// Get pixel from source buffer (using full screen coordinates)
size_t src_byte_idx = fb_y * stride + (fb_x / 8);
size_t src_bit_idx = fb_x % 8;
uint8_t src_bit = (pixel_data[src_byte_idx] >> (7 - src_bit_idx)) & 0x01;
// Set pixel in destination buffer
size_t dst_byte_idx = fb_y * stride + (fb_x / 8);
size_t dst_bit_idx = fb_x % 8;
if (dst_byte_idx < (DISPLAY_BUFFER_SIZE - 8)) {
if (src_bit) {
handler->_framebuffer[dst_byte_idx] |= (1 << (7 - dst_bit_idx));
} else {
handler->_framebuffer[dst_byte_idx] &= ~(1 << (7 - dst_bit_idx));
}
}
}
}
}
}
// Queue refresh request (non-blocking)
if (handler->_refresh_queue != nullptr) {
if (xQueueSend(handler->_refresh_queue, &perform_full_refresh, 0) != pdPASS) {
ESP_LOGW(TAG, "Refresh queue full, skipping refresh");
} else {
ESP_LOGI(TAG, "Queued %s refresh", perform_full_refresh ? "full" : "partial");
}
}
lv_display_flush_ready(disp);
}
void EInkDisplayHandler::_lvgl_touch_read_cb(lv_indev_t* indev, lv_indev_data_t* data) {
EInkDisplayHandler* handler = static_cast<EInkDisplayHandler*>(lv_indev_get_user_data(indev));
// Disable touch input during display refresh (BUSY)
if (handler->is_busy()) {
data->state = LV_INDEV_STATE_RELEASED;
data->continue_reading = false;
return;
}
esp_lcd_touch_handle_t tp_handle = handler->get_touch_handle();
if (tp_handle == nullptr) {
data->state = LV_INDEV_STATE_RELEASED;
return;
}
// Read touch data from GT911
esp_err_t ret = esp_lcd_touch_read_data(tp_handle);
if (ret == ESP_OK) {
uint8_t touch_cnt = 0;
// Get touch data using new API
esp_lcd_touch_point_data_t point_data[1];
esp_lcd_touch_get_data(tp_handle, point_data, &touch_cnt, 1);
if (touch_cnt > 0) {
ESP_LOGI(TAG, "Touch data read successfully: x=%d, y=%d", point_data[0].x, point_data[0].y);
data->point.x = point_data[0].x;
data->point.y = point_data[0].y;
data->state = LV_INDEV_STATE_PRESSED;
} else {
data->state = LV_INDEV_STATE_RELEASED;
}
} else {
data->state = LV_INDEV_STATE_RELEASED;
}
data->continue_reading = false;
}
void EInkDisplayHandler::_perform_full_refresh(const uint8_t* framebuffer) {
ESP_LOGI(TAG, "Starting full refresh (3 seconds)...");
_wait_for_busy();
// Step 1: Write old data (0x10) - Arduino uses 0xFF (all white) for base map
epd_write_cmd(0x10);
if (xSemaphoreTake(_spi_mutex, pdMS_TO_TICKS(5000)) != pdTRUE) {
ESP_LOGE(TAG, "SPI mutex timeout in full refresh step 1");
return;
}
gpio_set_level(PIN_DC, 1); // Data mode
ESP_LOGI(TAG, "Starting SPI data transmission for old data (0x10)...");
// Send 0xFF (white) for all old data, matching Arduino EPD_SetRAMValue_BaseMap
// Use DMA transfers in chunks for better performance
static uint8_t white_buffer[4096]; // 4KB chunk buffer
memset(white_buffer, 0xFF, sizeof(white_buffer));
const size_t CHUNK_SIZE = sizeof(white_buffer);
size_t remaining = DISPLAY_BUFFER_SIZE - 8; // Exclude palette from transmission
size_t offset = 0;
while (remaining > 0) {
size_t transfer_size = (remaining < CHUNK_SIZE) ? remaining : CHUNK_SIZE;
spi_transaction_t t = {};
t.length = transfer_size * 8; // Length in bits
t.tx_buffer = white_buffer;
esp_err_t ret = spi_device_polling_transmit(_spi, &t);
if (ret != ESP_OK) {
ESP_LOGE(TAG, "Failed to send SPI chunk at offset %zu: %s", offset, esp_err_to_name(ret));
break;
}
remaining -= transfer_size;
offset += transfer_size;
// Yield every 16KB to prevent watchdog timeout
if (offset % (16 * 1024) == 0) {
ESP_LOGI(TAG, "Old data progress: %zu/%zu bytes (%.1f%%)", offset, remaining,
(float)offset * 100.0f / (float)remaining);
vTaskDelay(pdMS_TO_TICKS(1));
}
}
ESP_LOGI(TAG, "Completed SPI data transmission for old data");
xSemaphoreGive(_spi_mutex);
// Step 2: Write new data (0x13)
epd_write_cmd(0x13);
if (xSemaphoreTake(_spi_mutex, pdMS_TO_TICKS(5000)) != pdTRUE) {
ESP_LOGE(TAG, "SPI mutex timeout in full refresh step 2");
return;
}
gpio_set_level(PIN_DC, 1); // Data mode
ESP_LOGI(TAG, "Starting SPI data transmission for new data (0x13)...");
// Send actual framebuffer data in chunks using DMA for better performance
offset = 0;
remaining = DISPLAY_BUFFER_SIZE - 8; // Reset remaining for step 2
while (remaining > 0) {
size_t transfer_size = (remaining < CHUNK_SIZE) ? remaining : CHUNK_SIZE;
spi_transaction_t t = {};
t.length = transfer_size * 8; // Length in bits
t.tx_buffer = framebuffer + offset;
esp_err_t ret = spi_device_polling_transmit(_spi, &t);
if (ret != ESP_OK) {
ESP_LOGE(TAG, "Failed to send SPI chunk at offset %zu: %s", offset, esp_err_to_name(ret));
break;
}
remaining -= transfer_size;
offset += transfer_size;
// Yield every 16KB to prevent watchdog timeout
if (offset % (16 * 1024) == 0) {
ESP_LOGI(TAG, "New data progress: %zu/%zu bytes (%.1f%%)", offset, remaining,
(float)offset * 100.0f / (float)remaining);
vTaskDelay(pdMS_TO_TICKS(1));
}
}
ESP_LOGI(TAG, "Completed SPI data transmission for new data");
xSemaphoreGive(_spi_mutex);
// Step 3: Trigger display refresh (DRF)
epd_write_cmd(0x12);
// Critical delay - sample code says "!!!The delay here is necessary, 200uS at least!!!"
vTaskDelay(pdMS_TO_TICKS(10));
ESP_LOGI(TAG, "Display refresh triggered, BUSY pin: %d", gpio_get_level(PIN_BUSY));
// Wait for refresh to complete
_wait_for_busy();
ESP_LOGI(TAG, "Full refresh complete");
}
void EInkDisplayHandler::_perform_partial_refresh(const uint8_t* framebuffer) {
ESP_LOGI(TAG, "Starting partial refresh (0.3 seconds)...");
_wait_for_busy();
// Step 1: Configure VCOM for partial refresh
const uint8_t vcom_data[] = { 0xA9, 0x07 };
epd_write_cmd_with_data(0x50, vcom_data, 2);
// Step 2: Enter partial refresh mode
epd_write_cmd(0x91);
// Step 3: Define partial window (full screen for now)
// Format: 0x90 + 9 bytes (x_start_H, x_start_L, x_end_H, x_end_L, y_start_H, y_start_L, y_end_H, y_end_L, 0x01)
// For full screen: x=0 to 799 (0x031F), y=0 to 479 (0x01DF)
const uint8_t window_data[] = {
0x00, 0x00, // x_start = 0
0x03, 0x1F, // x_end = 799 (0x31F)
0x00, 0x00, // y_start = 0
0x01, 0xDF, // y_end = 479 (0x1DF)
0x01 // PT_SCAN
};
epd_write_cmd_with_data(0x90, window_data, 9);
// Step 4: Write new data (0x13 command)
epd_write_cmd(0x13);
if (xSemaphoreTake(_spi_mutex, pdMS_TO_TICKS(5000)) != pdTRUE) {
ESP_LOGE(TAG, "SPI mutex timeout in partial refresh");
return;
}
gpio_set_level(PIN_DC, 1); // Data mode
ESP_LOGI(TAG, "Starting SPI data transmission for partial refresh...");
// Send framebuffer data in chunks using DMA for better performance
const size_t CHUNK_SIZE = 4096; // 4KB chunks
size_t remaining = DISPLAY_BUFFER_SIZE - 8; // Exclude palette from transmission
size_t offset = 0;
while (remaining > 0) {
size_t transfer_size = (remaining < CHUNK_SIZE) ? remaining : CHUNK_SIZE;
spi_transaction_t t = {};
t.length = transfer_size * 8; // Length in bits
t.tx_buffer = framebuffer + offset;
esp_err_t ret = spi_device_polling_transmit(_spi, &t);
if (ret != ESP_OK) {
ESP_LOGE(TAG, "Failed to send SPI chunk at offset %zu: %s", offset, esp_err_to_name(ret));
break;
}
remaining -= transfer_size;
offset += transfer_size;
// Yield every 16KB to prevent watchdog timeout
if (offset % (16 * 1024) == 0) {
ESP_LOGI(TAG, "Partial refresh progress: %zu/%zu bytes (%.1f%%)", offset, remaining,
(float)offset * 100.0f / (float)remaining);
vTaskDelay(pdMS_TO_TICKS(1));
}
}
ESP_LOGI(TAG, "Completed SPI data transmission for partial refresh");
xSemaphoreGive(_spi_mutex);
// Step 5: Trigger partial display refresh (DRF)
epd_write_cmd(0x12);
// Critical delay - sample code says "!!!The delay here is necessary, 200uS at least!!!"
vTaskDelay(pdMS_TO_TICKS(10));
ESP_LOGI(TAG, "Partial refresh triggered, BUSY pin: %d", gpio_get_level(PIN_BUSY));
// Wait for refresh to complete
_wait_for_busy();
// Step 6: Exit partial refresh mode
epd_write_cmd(0x92);
ESP_LOGI(TAG, "Partial refresh complete");
}
void EInkDisplayHandler::_refresh_task(void* param) {
EInkDisplayHandler* handler = static_cast<EInkDisplayHandler*>(param);
bool perform_full_refresh = false;
ESP_LOGI(TAG, "Refresh task started");
while (true) {
// Wait for refresh request
if (xQueueReceive(handler->_refresh_queue, &perform_full_refresh, portMAX_DELAY) == pdTRUE) {
// Perform the requested refresh type
if (perform_full_refresh) {
ESP_LOGI(TAG, "Refresh task: Performing full refresh...");
handler->_perform_full_refresh(handler->_framebuffer);
} else {
ESP_LOGI(TAG, "Refresh task: Performing partial refresh...");
handler->_perform_partial_refresh(handler->_framebuffer);
}
}
}
}
void EInkDisplayHandler::_wait_for_busy() {
ESP_LOGI(TAG, "Waiting for display ready (BUSY pin)...");
int initial_level = gpio_get_level(PIN_BUSY);
ESP_LOGI(TAG, "Initial BUSY pin level: %d (0=BUSY, 1=FREE)", initial_level);
// If already free, no need to wait
if (initial_level == BUSY_INACTIVE_LEVEL) {
ESP_LOGI(TAG, "Display already ready (BUSY pin = 1)");
return;
}
int timeout = 0;
while (gpio_get_level(PIN_BUSY) == BUSY_ACTIVE_LEVEL) { // 0=BUSY, 1=FREE
vTaskDelay(pdMS_TO_TICKS(100));
timeout++;
if (timeout > 100) { // 10 second timeout
ESP_LOGE(TAG, "Display BUSY timeout! Pin level: %d", gpio_get_level(PIN_BUSY));
ESP_LOGW(TAG, "Attempting hardware reset...");
// Hardware reset sequence
gpio_set_level(PIN_RST, 0);
vTaskDelay(pdMS_TO_TICKS(10));
gpio_set_level(PIN_RST, 1);
vTaskDelay(pdMS_TO_TICKS(100));
// Re-initialize display
ESP_LOGI(TAG, "Re-initializing display after reset...");
_epd_init();
// Check if reset worked
int reset_timeout = 0;
while (gpio_get_level(PIN_BUSY) == BUSY_ACTIVE_LEVEL) {
vTaskDelay(pdMS_TO_TICKS(100));
reset_timeout++;
if (reset_timeout > 50) { // 5 second timeout after reset
ESP_LOGE(TAG, "Display reset failed! Still busy after reset.");
break;
}
}
if (gpio_get_level(PIN_BUSY) != BUSY_ACTIVE_LEVEL) {
ESP_LOGI(TAG, "Display reset successful after %d tenths of a second", reset_timeout);
}
break;
}
// Log every 2 seconds to track progress
if (timeout % 20 == 0) {
ESP_LOGW(TAG, "Still waiting for BUSY pin, timeout: %d/100, level: %d",
timeout, gpio_get_level(PIN_BUSY));
}
}
ESP_LOGI(TAG, "Display ready after %d tenths of a second", timeout);
}
void EInkDisplayHandler::_convert_buffer_to_epaper(const uint8_t* lvgl_buf, uint8_t* epd_buf, size_t size) {
// LVGL 1-bit format is already compatible with e-paper
// Just copy directly
memcpy(epd_buf, lvgl_buf, size);
}

View File

@@ -1,99 +0,0 @@
#pragma once
#include "freertos/FreeRTOS.h"
#include "freertos/semphr.h"
#include "esp_lcd_touch_gt911.h"
#include "common/semaphore_guard.h"
#include <vector>
#include <atomic>
#include "epd_handler.h"
// Refresh mode configuration
#define PARTIAL_REFRESH_THRESHOLD 10 // Full refresh every N partial refreshes
#define DISPLAY_WIDTH 800
#define DISPLAY_HEIGHT 480
// forward declarations
class EInkDisplayHandler;
struct RefreshArea {
public:
RefreshArea(int32_t x_start, int32_t y_start, int32_t x_end, int32_t y_end)
: x1(x_start), y1(y_start), x2(x_end), y2(y_end) { }
int32_t x1;
int32_t y1;
int32_t x2;
int32_t y2;
// reset to empty area
void reset() {
x1 = y1 = x2 = y2 = 0;
}
// expand area to include another area
void expand_to_include(const RefreshArea& other) {
expand_to_include(other.x1, other.y1, other.x2, other.y2);
}
void expand_to_include(int32_t x1, int32_t y1, int32_t x2, int32_t y2) {
const bool force_update = is_empty();
if (x1 < this->x1 || force_update) this->x1 = x1;
if (y1 < this->y1 || force_update) this->y1 = y1;
if (x2 > this->x2 || force_update) this->x2 = x2;
if (y2 > this->y2 || force_update) this->y2 = y2;
}
bool is_empty() const {
return (x1 == 0 && y1 == 0 && x2 == 0 && y2 == 0);
}
uint32_t area() const {
if (is_empty()) return 0;
return (x2 - x1 + 1) * (y2 - y1 + 1);
}
};
class EInkDisplayHandler {
public:
EInkDisplayHandler();
virtual ~EInkDisplayHandler();
esp_err_t init_devices(EventGroupHandle_t system_event_group = nullptr);
esp_err_t refresh_display(void);
esp_err_t full_write(const uint8_t* framebuffer, const bool white_basemap = true);
esp_err_t partial_refresh(const uint8_t* framebuffer, const RefreshArea& area, const bool is_last_partial_update = true);
esp_err_t clear_display(void);
esp_err_t deep_sleep_display(void);
// Request a full refresh on next flush
void request_full_refresh(void);
bool is_busy() {
return epd_handler_.is_busy();
}
esp_lcd_touch_handle_t get_touch_handle() const { return tp_handle_; }
private:
esp_err_t init_display_pins_(void);
esp_err_t epd_init_internal_(uint32_t transaction_id); // full fast refresh init
esp_err_t epd_init_partial_internal_(uint32_t transaction_id); // partial refresh init (within existing transaction)
esp_err_t init_touch_(void);
// write to the internal draw buffer
void write_to_buffer_(const uint8_t* src, const RefreshArea& area);
// write the internal draw buffer to the display's old sram
esp_err_t refresh_old_buffer_(uint32_t transaction_id);
EPDHandler epd_handler_;
uint32_t partial_refresh_count_ = 0;
bool force_full_refresh_ = false;
std::atomic<bool> is_deep_sleep_ { false };
SemaphoreHandle_t refresh_mutex_ = nullptr;
esp_lcd_panel_io_handle_t tp_io_handle_ = nullptr;
esp_lcd_touch_handle_t tp_handle_ = nullptr;
// this buffer reflects the current display state (1=black, 0=white)
uint8_t* draw_buffer_ = nullptr;
uint8_t* old_buffer_ = nullptr;
RefreshArea refresh_area_ = { 0, 0, 0, 0 };
};

View File

@@ -1,66 +0,0 @@
#pragma once
#include "display/display.h"
#include "lvgl.h"
#include "esp_lvgl_port.h"
#include "freertos/semphr.h"
// Refresh mode configuration
#define PARTIAL_REFRESH_THRESHOLD 10 // Full refresh every N partial refreshes
#define DISPLAY_WIDTH 800
#define DISPLAY_HEIGHT 480
#define DISPLAY_BUFFER_SIZE (((DISPLAY_WIDTH * DISPLAY_HEIGHT) / 8) + 8) // 1-bit per pixel + 8-byte palette
class EInkDisplayHandler : public DisplayHandler {
public:
EInkDisplayHandler(EventGroupHandle_t system_event_group);
virtual ~EInkDisplayHandler();
void init();
void start_touch_task();
// Request a full refresh on next flush
void request_full_refresh();
// Check if display is busy (refreshing)
bool is_busy() const;
private:
// LVGL display and input device handles
lv_display_t* _lvgl_display = nullptr;
lv_indev_t* _lvgl_touch_indev = nullptr;
lv_draw_buf_t* _lvgl_draw_buf = nullptr;
// Framebuffer
uint8_t* _framebuffer = nullptr;
bool _framebuffer_in_psram = false;
// Refresh tracking
uint32_t _partial_refresh_count = 0;
bool _force_full_refresh = false;
SemaphoreHandle_t _refresh_mutex = nullptr;
// Touch task
TaskHandle_t _touch_task_handle = nullptr;
// Refresh task and queue
TaskHandle_t _refresh_task_handle = nullptr;
QueueHandle_t _refresh_queue = nullptr;
// LVGL callbacks
static void _lvgl_flush_cb(lv_display_t* disp, const lv_area_t* area, uint8_t* px_map);
static void _lvgl_touch_read_cb(lv_indev_t* indev, lv_indev_data_t* data);
// Display operations
void _perform_full_refresh(const uint8_t* framebuffer);
void _perform_partial_refresh(const uint8_t* framebuffer);
void _wait_for_busy();
// Touch task
static void _touch_task(void* param);
// Refresh task
static void _refresh_task(void* param);
// Helper to convert LVGL 1-bit buffer to e-paper format
void _convert_buffer_to_epaper(const uint8_t* lvgl_buf, uint8_t* epd_buf, size_t size);
};

View File

@@ -1,292 +0,0 @@
#include "display/epd_handler.h"
#include "esp_log.h"
#include "display/constants.h"
#include "common/constants.h"
#include "esp_lcd_touch_gt911.h"
#include <driver/i2c.h>
#define TAG "EPDHandler"
#define BUSY_ACTIVE_LEVEL 0 // BUSY pin is active low
#define BUSY_INACTIVE_LEVEL 1
#define DMA_TRANSFER_CHUNK_SIZE 4096 // 4KB chunk size for DMA transfers
EPDHandler::EPDHandler() {
spi_mutex_ = xSemaphoreCreateMutex();
if (spi_mutex_ == nullptr) {
ESP_LOGE(TAG, "Failed to create SPI mutex");
}
spi_transaction_mutex_ = xSemaphoreCreateMutex();
if (spi_transaction_mutex_ == nullptr) {
ESP_LOGE(TAG, "Failed to create SPI transaction mutex");
}
}
EPDHandler::~EPDHandler() {
if (spi_mutex_ != nullptr) {
vSemaphoreDelete(spi_mutex_);
}
if (spi_transaction_mutex_ != nullptr) {
vSemaphoreDelete(spi_transaction_mutex_);
}
if (spi_ != nullptr) {
spi_bus_remove_device(spi_);
}
}
esp_err_t EPDHandler::init() {
esp_err_t err;
// Initialize SPI bus
spi_bus_config_t buscfg = {};
buscfg.mosi_io_num = 11; // MOSI pin
buscfg.miso_io_num = -1; // No MISO for e-paper
buscfg.sclk_io_num = 12; // SCK pin
buscfg.quadwp_io_num = -1;
buscfg.quadhd_io_num = -1;
buscfg.max_transfer_sz = DMA_TRANSFER_CHUNK_SIZE;
err = spi_bus_initialize(SPI2_HOST, &buscfg, SPI_DMA_CH_AUTO);
if (err != ESP_OK) {
ESP_LOGE(TAG, "Failed to initialize SPI bus: %s", esp_err_to_name(err));
return err;
}
// Add SPI device
spi_device_interface_config_t devcfg = {};
devcfg.clock_speed_hz = 10 * 1000 * 1000; // 10 MHz
devcfg.mode = 0; // SPI mode 0
devcfg.spics_io_num = PIN_CS;
devcfg.queue_size = 7; // Queue size for non-blocking transactions
devcfg.pre_cb = nullptr;
err = spi_bus_add_device(SPI2_HOST, &devcfg, &spi_);
if (err != ESP_OK) {
ESP_LOGE(TAG, "Failed to add SPI device: %s", esp_err_to_name(err));
return err;
}
return ESP_OK;
}
// Check if display is busy (refreshing)
bool EPDHandler::is_busy(void) const {
return gpio_get_level(PIN_BUSY) != BUSY_ACTIVE_LEVEL; // BUSY is active LOW
}
void EPDHandler::wait_for_idle(void) const {
ESP_LOGI(TAG, "Waiting for display ready (BUSY pin)...");
int initial_level = gpio_get_level(PIN_BUSY);
ESP_LOGI(TAG, "Initial BUSY pin level: %d (0=BUSY, 1=FREE)", initial_level);
// If already free, no need to wait
if (initial_level == BUSY_INACTIVE_LEVEL) {
ESP_LOGI(TAG, "Display already ready (BUSY pin = 1)");
return;
}
while (gpio_get_level(PIN_BUSY) != BUSY_INACTIVE_LEVEL) {
vTaskDelay(pdMS_TO_TICKS(10));
}
ESP_LOGI(TAG, "Display is now ready (BUSY pin = 1)");
}
esp_err_t EPDHandler::epd_write_cmd(const uint8_t cmd, uint32_t transaction_id) {
ESP_LOGI(TAG, "epd_write_cmd: waiting to send 0x%02X", cmd);
SemaphoreGuard transaction_guard(spi_transaction_mutex_);
esp_err_t err =
wait_for_transaction_end_(pdMS_TO_TICKS(5000), transaction_id, transaction_guard);
if (err != ESP_OK) {
ESP_LOGE(TAG, "Failed to wait for previous transaction end before sending cmd 0x%02X: %s",
cmd, esp_err_to_name(err));
return err;
}
SemaphoreGuard guard(spi_mutex_);
if (!guard.take(pdMS_TO_TICKS(5000))) {
ESP_LOGE(TAG, "SPI mutex timeout for cmd 0x%02X", cmd);
return ESP_ERR_TIMEOUT;
}
err = dangerous_epd_write_cmd_without_lock_(cmd);
ESP_LOGI(TAG, "epd_write_cmd: 0x%02X done", cmd);
return err;
}
esp_err_t EPDHandler::epd_write_data(const uint8_t data, uint32_t transaction_id) {
ESP_LOGI(TAG, "epd_write_data: waiting to send 0x%02X", data);
SemaphoreGuard transaction_guard(spi_transaction_mutex_);
esp_err_t err =
wait_for_transaction_end_(pdMS_TO_TICKS(5000), transaction_id, transaction_guard);
if (err != ESP_OK) {
ESP_LOGE(TAG, "Failed to wait for previous transaction end before sending data 0x%02X: %s",
data, esp_err_to_name(err));
return err;
}
SemaphoreGuard guard(spi_mutex_);
if (!guard.take(pdMS_TO_TICKS(5000))) {
ESP_LOGE(TAG, "SPI mutex timeout for data 0x%02X", data);
return ESP_ERR_TIMEOUT;
}
err = dangerous_epd_write_data_without_lock_(data);
ESP_LOGI(TAG, "epd_write_data: 0x%02X done", data);
return err;
}
esp_err_t EPDHandler::epd_write_cmd_with_data(const uint8_t cmd, std::vector<uint8_t>& data, uint32_t transaction_id) {
const size_t data_len = data.size();
ESP_LOGI(TAG, "epd_write_cmd_with_data: waiting to send cmd 0x%02X with %u bytes of data", cmd, data_len);
SemaphoreGuard transaction_guard(spi_transaction_mutex_);
esp_err_t err =
wait_for_transaction_end_(pdMS_TO_TICKS(5000), transaction_id, transaction_guard);
if (err != ESP_OK) {
ESP_LOGE(TAG, "Failed to wait for previous transaction end before sending cmd 0x%02X: %s, with data",
cmd, esp_err_to_name(err));
return err;
}
SemaphoreGuard guard(spi_mutex_);
if (!guard.take(pdMS_TO_TICKS(5000))) {
ESP_LOGE(TAG, "SPI mutex timeout for cmd with data 0x%02X", cmd);
return ESP_ERR_TIMEOUT;
}
err = dangerous_epd_write_cmd_without_lock_(cmd);
if (err != ESP_OK) {
return err;
};
for (size_t i = 0; i < data_len; ++i) {
err = dangerous_epd_write_data_without_lock_(data[i]);
if (err != ESP_OK) {
return err;
}
}
ESP_LOGI(TAG, "epd_write_cmd_with_data: cmd 0x%02X with %u bytes of data done", cmd, data_len);
return ESP_OK;
}
esp_err_t EPDHandler::dangerous_epd_write_cmd_without_lock_(const uint8_t cmd) {
ESP_LOGI(TAG, "dangerous_epd_write_cmd_without_lock_: sending 0x%02X", cmd);
gpio_set_level(PIN_DC, 0); // Command mode
spi_transaction_t t {};
t.length = 8;t.tx_buffer = &cmd;
esp_err_t err = spi_device_polling_transmit(spi_, &t);
if (err != ESP_OK) {
ESP_LOGE(TAG, "Failed to send data 0x%02X", cmd);
} else {
ESP_LOGI(TAG, "dangerous_epd_write_cmd_without_lock_: 0x%02X sent", cmd);
}
return err;
}
esp_err_t EPDHandler::dangerous_epd_write_data_without_lock_(const uint8_t data) {
ESP_LOGI(TAG, "dangerous_epd_write_data_without_lock_: sending 0x%02X", data);
gpio_set_level(PIN_DC, 1); // Data mode
spi_transaction_t t = { };
t.length = 8; t.tx_buffer = &data;
esp_err_t err = spi_device_polling_transmit(spi_, &t);
if (err != ESP_OK) {
ESP_LOGE(TAG, "Failed to send data 0x%02X", data);
} else {
ESP_LOGI(TAG, "dangerous_epd_write_data_without_lock_: 0x%02X sent", data);
}
return err;
}
esp_err_t EPDHandler::transfer_spi_data(const uint8_t* data, const size_t& length, uint32_t transaction_id) {
ESP_LOGI(TAG, "transfer_spi_data: waiting to send %zu bytes of data", length);
SemaphoreGuard transaction_guard(spi_transaction_mutex_);
esp_err_t err =
wait_for_transaction_end_(pdMS_TO_TICKS(5000), transaction_id, transaction_guard);
if (err != ESP_OK) {
ESP_LOGE(TAG, "Failed to wait for previous transaction end before sending data of %zu bytes: %s",
length, esp_err_to_name(err));
return err;
}
SemaphoreGuard guard(spi_mutex_);
if (!guard.take(pdMS_TO_TICKS(5000))) {
ESP_LOGE(TAG, "SPI mutex timeout for data transfer of %zu bytes", length);
return ESP_ERR_TIMEOUT;
}
ESP_LOGI(TAG, "transfer_spi_data: starting to send %zu bytes of data", length);
size_t offset = 0;
size_t remaining = length;
gpio_set_level(PIN_DC, 1); // Data mode
while (remaining > 0) {
size_t transfer_size = (remaining < DMA_TRANSFER_CHUNK_SIZE) ? remaining : DMA_TRANSFER_CHUNK_SIZE;
spi_transaction_t t = {};
t.length = transfer_size * 8; // Length in bits
t.tx_buffer = data + offset;
esp_err_t ret = spi_device_polling_transmit(spi_, &t);
if (ret != ESP_OK) {
ESP_LOGE(TAG, "Failed to send SPI chunk at offset %zu: %s", offset, esp_err_to_name(ret));
if (ret == ESP_ERR_NO_MEM) {
ESP_LOGE(TAG, "Current free heap size: %u bytes", esp_get_free_heap_size());
ESP_LOGE(TAG, "Current free DMA-capable memory size: %u bytes",
heap_caps_get_free_size(MALLOC_CAP_DMA));
}
return ret;
}
remaining -= transfer_size;
offset += transfer_size;
// Yield every 16KB to prevent watchdog timeout
if (offset % (16 * 1024) == 0) {
ESP_LOGI(TAG, "New data progress: %zu/%zu bytes sent, yielding...", offset, length);
vTaskDelay(pdMS_TO_TICKS(1));
}
}
ESP_LOGI(TAG, "transfer_spi_data: completed sending %zu bytes of data", length);
return ESP_OK;
}
esp_err_t EPDHandler::begin_transaction_(TickType_t timeout, uint32_t& out_id) {
ESP_LOGI(TAG, "begin_transaction_: waiting to obtain transaction mutex");
if (xSemaphoreTake(spi_transaction_mutex_, timeout) != pdTRUE) {
ESP_LOGE(TAG, "begin_transaction_: transaction mutex timeout");
return ESP_ERR_TIMEOUT;
}
out_id = ++spi_transaction_id;
ESP_LOGI(TAG, "begin_transaction_: transaction mutex obtained");
return ESP_OK;
}
esp_err_t EPDHandler::end_transaction_(void) {
ESP_LOGI(TAG, "end_transaction_: releasing transaction mutex");
if (xSemaphoreGive(spi_transaction_mutex_) != pdTRUE) {
ESP_LOGE(TAG, "end_transaction_: failed to release transaction mutex");
return ESP_FAIL;
}
ESP_LOGI(TAG, "end_transaction_: transaction mutex released");
return ESP_OK;
}
esp_err_t EPDHandler::wait_for_transaction_end_(TickType_t timeout, uint32_t awaiting_transaction_id, SemaphoreGuard& out_transaction_guard) {
// Validate transaction ID if provided
if (awaiting_transaction_id != 0 && awaiting_transaction_id != spi_transaction_id) {
// Invalid transaction ID
ESP_LOGE(TAG, "Invalid transaction ID 0x%08X while waiting, current transaction ID: 0x%08X",
awaiting_transaction_id, spi_transaction_id);
return ESP_ERR_INVALID_ARG;
}
SemaphoreGuard transaction_guard(spi_transaction_mutex_);
if (awaiting_transaction_id == 0) {
// wait for current transaction to complete
ESP_LOGV(TAG, "Waiting for current transaction 0x%08X to complete",
spi_transaction_id);
// take the mutex to ensure no transaction is active
if (!transaction_guard.take(timeout)) {
ESP_LOGE(TAG, "SPI transaction mutex timeout while waiting for transaction end");
return ESP_ERR_TIMEOUT;
}
}
// awaited_transaction_id is valid and matches current transaction ID or 0
out_transaction_guard = std::move(transaction_guard);
return ESP_OK;
}

View File

@@ -1,41 +0,0 @@
#pragma once
#include "freertos/FreeRTOS.h"
#include "freertos/semphr.h"
#include "driver/spi_master.h"
#include "common/semaphore_guard.h"
#include <vector>
#include "display/transaction_guard.h"
class EPDHandler : public WithTransaction {
public:
EPDHandler();
~EPDHandler();
esp_err_t init();
esp_err_t epd_write_cmd(const uint8_t cmd, uint32_t transaction_id);
esp_err_t epd_write_data(const uint8_t data, uint32_t transaction_id);
esp_err_t epd_write_cmd_with_data(const uint8_t cmd, std::vector<uint8_t>& data, uint32_t transaction_id);
esp_err_t transfer_spi_data(const uint8_t* data, const size_t& length, uint32_t transaction_id);
bool is_busy(void) const;
void wait_for_idle(void) const;
private:
esp_err_t dangerous_epd_write_cmd_without_lock_(const uint8_t cmd);
esp_err_t dangerous_epd_write_data_without_lock_(const uint8_t data);
esp_err_t begin_transaction_(TickType_t timeout, uint32_t& out_id) override;
esp_err_t end_transaction_(void) override;
// given a transaction ID, wait for current transaction to complete. The transaction ID will determine if the wait is needed.
esp_err_t wait_for_transaction_end_(TickType_t timeout, uint32_t awaiting_transaction_id, SemaphoreGuard& out_transaction_guard);
spi_device_handle_t spi_ = nullptr;
SemaphoreHandle_t spi_mutex_ = nullptr;
SemaphoreHandle_t spi_transaction_mutex_ = nullptr;
uint32_t spi_transaction_id = 0; // For tracking SPI transactions
friend class TransactionGuard;
};

View File

@@ -1,318 +0,0 @@
#include "display/lvgl_handler.h"
#include "esp_log.h"
#include "common/semaphore_guard.h"
#include "common/constants.h"
#include <portmacro.h>
#define DISPLAY_BUFFER_SIZE (DISPLAY_WIDTH * DISPLAY_HEIGHT) / 8 // 1 bit per pixels
#define LVGL_BUFFER_SIZE (DISPLAY_BUFFER_SIZE + 8) // 1 bit per pixels + 8 bytes for palette
#define LV_DISPLAY_RENDER_MODE LV_DISPLAY_RENDER_MODE_PARTIAL
#define TAG "LVGLHandler"
LVGLHandler::LVGLHandler(
std::unique_ptr<EInkDisplayHandler> display_handler_in
) : display_handler_(std::move(display_handler_in)) { }
LVGLHandler::~LVGLHandler() {
if (lvgl_display_ != nullptr) {
lv_display_delete(lvgl_display_);
lvgl_display_ = nullptr;
}
if (lvgl_touch_indev_ != nullptr) {
lvgl_port_remove_touch(lvgl_touch_indev_);
lvgl_touch_indev_ = nullptr;
}
if (lvgl_draw_buf_ != nullptr) {
lv_draw_buf_destroy(lvgl_draw_buf_);
lvgl_draw_buf_ = nullptr;
}
}
esp_err_t LVGLHandler::initLVGL(EventGroupHandle_t system_event_group) {
esp_err_t err = initLVGLPort_();
if (err != ESP_OK) {
return err;
}
err = initLVGLDisplay_();
if (err != ESP_OK) {
return err;
}
err = registerLVGLTouch_();
if (err != ESP_OK) {
return err;
}
auto lvgl_tick_timer_callback = [](TimerHandle_t xTimer) {
lv_tick_inc(5);
};
TickType_t lvgl_tick_period = pdMS_TO_TICKS(5);
if (lvgl_tick_period == 0) {
lvgl_tick_period = 1; // ensure at least 1 tick to avoid FreeRTOS assert
}
ESP_LOGV(TAG, "Creating LVGL tick timer with period %u ticks...\n", (unsigned)lvgl_tick_period);
TimerHandle_t lvgl_tick_timer = xTimerCreate(
"lvgl_tick_timer",
lvgl_tick_period,
pdTRUE,
NULL,
lvgl_tick_timer_callback
);
if (lvgl_tick_timer == NULL) {
ESP_LOGE("Main", "Failed to create LVGL tick timer");
vTaskDelay(5000 / portTICK_PERIOD_MS);
return ESP_ERR_NO_MEM;
}
ESP_LOGV(TAG, "Starting LVGL tick timer...\n");
xTimerStart(lvgl_tick_timer, 0);
if (system_event_group != nullptr) {
xEventGroupSetBits(system_event_group, DISPLAY_READY_BIT | TOUCH_CALIBRATED_BIT);
}
return ESP_OK;
}
//
// Private methods
//
void LVGLHandler::rounder_cb_(lv_display_t* disp, lv_area_t* area) {
// align x to byte boundary
area->x1 = (area->x1 & ~0x7);
area->x2 = (area->x2 | 0x7);
}
void LVGLHandler::flush_cb_(lv_display_t* disp, const lv_area_t* area, uint8_t* px_map) {
if (disp == nullptr || area == nullptr || px_map == nullptr) {
ESP_LOGE(TAG, "Null parameters in flush callback");
if (disp != nullptr) lv_display_flush_ready(disp);
return;
}
LVGLHandler* handler = static_cast<LVGLHandler*>(lv_display_get_user_data(disp));
if (handler == nullptr || handler->display_handler_ == nullptr) {
ESP_LOGE(TAG, "Invalid handler in flush callback");
lv_display_flush_ready(disp);
return;
}
uint8_t* pixel_data = px_map + 8; // Skip palette
//
ESP_LOGI(TAG, "Flush callback: x1=%d, y1=%d, x2=%d, y2=%d", area->x1, area->y1, area->x2, area->y2);
// copy data to framebuffer
int32_t area_w = lv_area_get_width(area);
int32_t area_h = lv_area_get_height(area);
if (area->x1 == 0 && area->y1 == 0 && area_w == DISPLAY_WIDTH && area_h == DISPLAY_HEIGHT) {
// revert the pixel data for e-ink (LVGL: 1=white, 0=black; E-Ink: 1=black, 0=white)
for (size_t i = 0; i < DISPLAY_BUFFER_SIZE; ++i) {
pixel_data[i] = ~pixel_data[i];
}
esp_err_t err = handler->display_handler_->full_write(
pixel_data,
true // white basemap
);
if (err != ESP_OK) {
ESP_LOGE(TAG, "Full refresh request failed: %s", esp_err_to_name(err));
}
} else {
// partial update
ESP_LOGI(TAG, "Partial update: x1=%d, y1=%d, w=%d, h=%d", area->x1, area->y1, area_w, area_h);
// Prepare partial buffer
const uint32_t area_width_bytes = (area->x2 - area->x1 + 1) / 8;
const uint32_t area_height = area->y2 - area->y1 + 1;
const size_t partial_buffer_size = area_width_bytes * area_height;
uint8_t* partial_buffer = new uint8_t[partial_buffer_size];
if (partial_buffer == nullptr) {
ESP_LOGE(TAG, "Failed to allocate partial buffer for flush callback");
lv_display_flush_ready(disp);
return;
}
// Copy pixel data to partial buffer and invert for e-ink
for (int32_t row = 0; row < area_height; ++row) {
for (int32_t col = 0; col < area_width_bytes; ++col) {
size_t src_index = row * area_width_bytes + col;
partial_buffer[src_index] = ~pixel_data[src_index];
}
}
esp_err_t err = handler->display_handler_->partial_refresh(partial_buffer,
RefreshArea {
area->x1,
area->y1,
area->x2,
area->y2
}, lv_display_flush_is_last(disp));
delete[] partial_buffer;
if (err != ESP_OK) {
ESP_LOGE(TAG, "Partial refresh request failed: %s", esp_err_to_name(err));
}
}
//
lv_display_flush_ready(disp);
}
void LVGLHandler::touch_read_cb_(lv_indev_t* indev, lv_indev_data_t* data) {
LVGLHandler* handler = static_cast<LVGLHandler*>(lv_indev_get_user_data(indev));
if (handler == nullptr || handler->display_handler_ == nullptr) {
data->state = LV_INDEV_STATE_RELEASED;
ESP_LOGE(TAG, "Invalid handler in touch read callback");
return;
}
// Disable touch input during display refresh (BUSY)
if (handler->display_handler_->is_busy()) {
data->state = LV_INDEV_STATE_RELEASED;
data->continue_reading = false;
return;
}
esp_lcd_touch_handle_t tp_handle = handler->display_handler_->get_touch_handle();
if (tp_handle == nullptr) {
data->state = LV_INDEV_STATE_RELEASED;
return;
}
// Read touch data from GT911
esp_err_t ret = esp_lcd_touch_read_data(tp_handle);
if (ret == ESP_OK) {
uint8_t touch_cnt = 0;
// Get touch data using new API
esp_lcd_touch_point_data_t point_data[1];
esp_lcd_touch_get_data(tp_handle, point_data, &touch_cnt, 1);
if (touch_cnt > 0) {
// ESP_LOGI(TAG, "Touch data read successfully: x=%d, y=%d", point_data[0].x, point_data[0].y);
data->point.x = point_data[0].x;
data->point.y = point_data[0].y;
data->state = LV_INDEV_STATE_PRESSED;
} else {
data->state = LV_INDEV_STATE_RELEASED;
}
} else {
data->state = LV_INDEV_STATE_RELEASED;
}
data->continue_reading = false;
}
esp_err_t LVGLHandler::initLVGLDisplay_() {
if (display_handler_ == nullptr) {
return ESP_ERR_INVALID_STATE;
}
esp_err_t err = ESP_OK;
// Lock LVGL to prevent the timer task from accessing partially initialized display
if (!lvgl_port_lock(pdMS_TO_TICKS(5000))) {
ESP_LOGE(TAG, "Failed to lock LVGL port for display initialization");
return ESP_ERR_TIMEOUT;
}
// Create LVGL display
lvgl_display_ = lv_display_create(DISPLAY_WIDTH, DISPLAY_HEIGHT);
if (lvgl_display_ == nullptr) {
ESP_LOGE(TAG, "Failed to create LVGL display");
lvgl_port_unlock();
return ESP_FAIL;
}
// Create a draw buffer covering the entire display
lvgl_draw_buf_ = lv_draw_buf_create(DISPLAY_WIDTH, DISPLAY_HEIGHT, LV_COLOR_FORMAT_I1, LV_STRIDE_AUTO);
if (lvgl_draw_buf_ == nullptr) {
ESP_LOGE(TAG, "Failed to create LVGL draw buffer");
lv_display_delete(lvgl_display_);
lvgl_display_ = nullptr;
lvgl_port_unlock();
return ESP_FAIL;
}
lv_display_set_draw_buffers(lvgl_display_, lvgl_draw_buf_, nullptr);
lv_display_set_render_mode(lvgl_display_, LV_DISPLAY_RENDER_MODE);
//
// Configure LVGL display
lv_display_set_color_format(lvgl_display_, LV_COLOR_FORMAT_I1);
lv_display_set_user_data(lvgl_display_, this);
lv_display_add_event_cb(lvgl_display_, [](lv_event_t* e) {
LVGLHandler* handler = static_cast<LVGLHandler*>(lv_display_get_user_data(static_cast<lv_display_t*>(lv_event_get_target(e))));
if (handler != nullptr) {
handler->rounder_cb_(static_cast<lv_display_t*>(lv_event_get_target(e)),
static_cast<lv_area_t*>(lv_event_get_param(e)));
} else {
ESP_LOGE(TAG, "Invalid handler in rounder callback");
}
}, LV_EVENT_INVALIDATE_AREA, lvgl_display_);
lv_display_set_flush_cb(lvgl_display_, [](lv_display_t* disp, const lv_area_t* area, uint8_t* px_map) {
LVGLHandler* handler = static_cast<LVGLHandler*>(lv_display_get_user_data(disp));
if (handler != nullptr) {
handler->flush_cb_(disp, area, px_map);
} else {
lv_display_flush_ready(disp);
}
});
// Unlock LVGL now that display is fully initialized
ESP_LOGI(TAG, "Performing initial display write...");
// err = display_handler_->full_write(framebuffer_, false);
err = display_handler_->clear_display();
if (err != ESP_OK) {
ESP_LOGE(TAG, "Initial display write failed: %d", err);
} else {
ESP_LOGI(TAG, "Initial display write complete");
}
lvgl_port_unlock();
ESP_LOGI(TAG, "LVGL display registered");
return err;
}
esp_err_t LVGLHandler::registerLVGLTouch_() {
if (display_handler_ == nullptr) {
return ESP_ERR_INVALID_STATE;
}
esp_lcd_touch_handle_t tp_handle = display_handler_->get_touch_handle();
if (tp_handle == nullptr) {
ESP_LOGE(TAG, "Touch handle is NULL — touch initialization failed; skipping LVGL touch registration");
return ESP_FAIL;
}
const lvgl_port_touch_cfg_t touch_cfg = {
.disp = lvgl_display_,
.handle = tp_handle,
.scale = {}, // Default scaling
};
lvgl_touch_indev_ = lvgl_port_add_touch(&touch_cfg);
if (lvgl_touch_indev_ == nullptr) {
ESP_LOGE(TAG, "Failed to register LVGL touch input");
return ESP_FAIL;
}
lv_indev_set_user_data(lvgl_touch_indev_, this);
lv_indev_set_read_cb(lvgl_touch_indev_, [](lv_indev_t* indev, lv_indev_data_t* data) {
LVGLHandler* handler = static_cast<LVGLHandler*>(lv_indev_get_user_data(indev));
if (handler != nullptr) {
handler->touch_read_cb_(indev, data);
} else {
data->state = LV_INDEV_STATE_RELEASED;
}
});
ESP_LOGI(TAG, "LVGL touch input registered");
return ESP_OK;
}
esp_err_t LVGLHandler::initLVGLPort_() {
const lvgl_port_cfg_t lvgl_cfg = ESP_LVGL_PORT_INIT_CONFIG();
esp_err_t err = lvgl_port_init(&lvgl_cfg);
if (err != ESP_OK) {
ESP_LOGE(TAG, "LVGL port initialization failed: %s", esp_err_to_name(err));
vTaskDelay(5000 / portTICK_PERIOD_MS);
return ESP_ERR_INVALID_STATE;
}
ESP_LOGI(TAG, "LVGL port initialized successfully.\n");
return ESP_OK;
}

View File

@@ -1,34 +0,0 @@
#pragma once
#include "lvgl.h"
#include "esp_lvgl_port.h"
#include "display/eink_display_handler.h"
#include "freertos/semphr.h"
#include "freertos/event_groups.h"
#include "esp_err.h"
#include <memory>
class LVGLHandler {
public:
LVGLHandler(
// an owning pointer to the display handler
// The display handler must outlive the LVGLHandler
// The display handler must be fully initialized before calling initLVGLDisplay
std::unique_ptr<EInkDisplayHandler> display_handler_in
);
~LVGLHandler();
esp_err_t initLVGL(EventGroupHandle_t system_event_group = nullptr);
private:
void rounder_cb_(lv_display_t* disp, lv_area_t* area);
void flush_cb_(lv_display_t* disp, const lv_area_t* area, uint8_t* px_map);
void touch_read_cb_(lv_indev_t* indev, lv_indev_data_t* data);
esp_err_t initLVGLDisplay_();
esp_err_t registerLVGLTouch_();
esp_err_t initLVGLPort_();
std::unique_ptr<EInkDisplayHandler> display_handler_ = nullptr;
lv_display_t* lvgl_display_ = nullptr;
lv_indev_t* lvgl_touch_indev_ = nullptr;
lv_draw_buf_t* lvgl_draw_buf_ = nullptr;
};

View File

@@ -1,33 +0,0 @@
#pragma once
#include "freertos/FreeRTOS.h"
#include "freertos/semphr.h"
#include <esp_err.h>
#include <type_traits>
class WithTransaction {
protected:
virtual esp_err_t end_transaction_() = 0;
virtual esp_err_t begin_transaction_(TickType_t timeout, uint32_t& out_id) = 0;
friend class TransactionGuard;
};
class TransactionGuard {
public:
TransactionGuard(WithTransaction& handler, TickType_t timeout = portMAX_DELAY)
: handler_(handler) { }
~TransactionGuard() { if (transaction_id_) handler_.end_transaction_(); }
esp_err_t begin(TickType_t timeout = portMAX_DELAY) {
esp_err_t err = handler_.begin_transaction_(timeout, transaction_id_);
return err;
}
uint32_t transaction_id() const { return transaction_id_; }
bool is_active() const { return transaction_id_ != 0; }
private:
// delete copy constructor and assignment operator
TransactionGuard(const TransactionGuard&) = delete;
TransactionGuard& operator=(const TransactionGuard&) = delete;
WithTransaction& handler_;
uint32_t transaction_id_ = 0;
};

View File

@@ -1,98 +0,0 @@
#include "external/mtr/arrival.h"
#include "cJSON.h"
#include "esp_log.h"
#include <string>
static const char* TAG = "StationArrivalInfo";
StationArrivalInfo::StationArrivalInfo(
cJSON* mtr_line_station_json,
cJSON* arrival_json,
const std::string& train_line_code,
const std::string& train_station_code
) : _status(UNKNOWN_STATUS)
, _train_line(train_line_code)
, _train_station(train_station_code) {
if (!arrival_json) {
ESP_LOGE(TAG, "arrival_json is null");
_status = FAILED_WITH_MESSAGE;
_message = "No arrival data received";
return;
}
// Parse status
cJSON* status_json = cJSON_GetObjectItem(arrival_json, "status");
if (status_json && cJSON_IsNumber(status_json)) {
int status_value = status_json->valueint;
if (status_value >= 0 && status_value <= 3) {
_status = static_cast<StatusEnum>(status_value);
}
}
// TODO: verify the arrival json parsing
// Parse message (if present)
cJSON* message_json = cJSON_GetObjectItem(arrival_json, "message");
if (message_json && cJSON_IsString(message_json)) {
_message = message_json->valuestring;
}
// Parse UP direction arrivals
cJSON* up_json = cJSON_GetObjectItem(arrival_json, "UP");
if (up_json && cJSON_IsArray(up_json)) {
int up_count = cJSON_GetArraySize(up_json);
for (int i = 0; i < up_count; i++) {
cJSON* arrival_item = cJSON_GetArrayItem(up_json, i);
if (arrival_item) {
std::string time_str = "";
std::string dest_str = "";
cJSON* time_json = cJSON_GetObjectItem(arrival_item, "time");
if (time_json && cJSON_IsString(time_json)) {
time_str = time_json->valuestring;
}
cJSON* dest_json = cJSON_GetObjectItem(arrival_item, "dest");
if (dest_json && cJSON_IsString(dest_json)) {
dest_str = dest_json->valuestring;
}
if (!time_str.empty()) {
_up_arrivals.emplace_back(time_str, dest_str);
}
}
}
}
// Parse DOWN direction arrivals
cJSON* down_json = cJSON_GetObjectItem(arrival_json, "DOWN");
if (down_json && cJSON_IsArray(down_json)) {
int down_count = cJSON_GetArraySize(down_json);
for (int i = 0; i < down_count; i++) {
cJSON* arrival_item = cJSON_GetArrayItem(down_json, i);
if (arrival_item) {
std::string time_str = "";
std::string dest_str = "";
cJSON* time_json = cJSON_GetObjectItem(arrival_item, "time");
if (time_json && cJSON_IsString(time_json)) {
time_str = time_json->valuestring;
}
cJSON* dest_json = cJSON_GetObjectItem(arrival_item, "dest");
if (dest_json && cJSON_IsString(dest_json)) {
dest_str = dest_json->valuestring;
}
if (!time_str.empty()) {
_down_arrivals.emplace_back(time_str, dest_str);
}
}
}
}
ESP_LOGI(TAG, "Parsed arrival info for %s/%s: %zu UP, %zu DOWN trains",
train_line_code.c_str(), train_station_code.c_str(),
_up_arrivals.size(), _down_arrivals.size());
}

View File

@@ -1,67 +0,0 @@
#pragma once
#include "external/mtr/arrival.h"
#include "cJSON.h"
#include "external/mtr/mtr.h"
#include <string>
#include <vector>
// Forward declaration
class MTRNextTrainHandler;
struct ArrivalInfo {
public:
// Caller transfers ownership of arrival_time to ArrivalInfo
ArrivalInfo(
const std::string& arrival_time,
const std::string& destination_name
) : _arrival_time(arrival_time)
, _destination_name(destination_name) { }
const char* arrival_time() const {
return _arrival_time.c_str();
}
const char* destination() const {
return _destination_name.c_str();
}
private:
const std::string _arrival_time;
const std::string _destination_name; // not the code of the station
};
enum StatusEnum {
SUCCESSFUL_WITHOUT_DELAY = 0,
SUCCESSFUL_WITH_DELAY = 1,
FAILED_WITH_MESSAGE = 2,
UNKNOWN_STATUS = 3
};
struct StationArrivalInfo {
public:
friend class MTRNextTrainHandler;
// Public accessors
StatusEnum status() const { return _status; }
const char* message() const { return _message.c_str(); }
const char* train_line() const { return _train_line.c_str(); }
const char* train_station() const { return _train_station.c_str(); }
const std::vector<ArrivalInfo>* up_arrivals() const { return &_up_arrivals; }
const std::vector<ArrivalInfo>* down_arrivals() const { return &_down_arrivals; }
private:
StationArrivalInfo(
cJSON* mtr_line_station_json,
cJSON* arrival_json,
const std::string& train_line_code,
const std::string& train_station_code
);
StatusEnum _status;
std::string _message; // only valid if status == FAILED_WITH_MESSAGE
std::string _train_line;
std::string _train_station;
std::vector<ArrivalInfo> _up_arrivals;
std::vector<ArrivalInfo> _down_arrivals;
};

View File

@@ -1,45 +0,0 @@
#include "external/mtr/line_info.h"
#include "external/mtr/station_info.h"
#include "cJSON.h"
#include "esp_log.h"
LineInfo::LineInfo(cJSON* line_json) {
if (!line_json) {
ESP_LOGE(LINE_INFO_TAG, "line_json is null");
return;
}
// Parse line code
cJSON* code_json = cJSON_GetObjectItem(line_json, "code");
if (code_json && cJSON_IsString(code_json)) {
_code = code_json->valuestring;
} else {
ESP_LOGW(LINE_INFO_TAG, "Missing or invalid 'code' field");
}
// Parse line color (note: field is 'line_color' in JSON, not 'color')
cJSON* color_json = cJSON_GetObjectItem(line_json, "line_color");
if (color_json && cJSON_IsString(color_json)) {
_color = color_json->valuestring;
} else {
ESP_LOGW(LINE_INFO_TAG, "Missing or invalid 'line_color' field");
}
// Parse stations array
cJSON* stations_json = cJSON_GetObjectItem(line_json, "stations");
if (stations_json && cJSON_IsArray(stations_json)) {
int station_count = cJSON_GetArraySize(stations_json);
_stations.reserve(station_count);
for (int i = 0; i < station_count; i++) {
cJSON* station_json = cJSON_GetArrayItem(stations_json, i);
if (station_json) {
_stations.emplace_back(station_json);
}
}
ESP_LOGI(LINE_INFO_TAG, "Created LineInfo: %s with %d stations", _code.c_str(), station_count);
} else {
ESP_LOGW(LINE_INFO_TAG, "Missing or invalid 'stations' array");
}
}

View File

@@ -1,46 +0,0 @@
#pragma once
#include "cJSON.h"
#include "esp_log.h"
#include "external/mtr/station_info.h"
#include "external/mtr/mtr.h"
#include <string>
#include <vector>
#define LINE_INFO_TAG "LineInfo"
// Forward declaration
class MTRNextTrainHandler;
struct StationInfo;
struct LineInfo {
public:
// caller does not own the returned char pointers
const char* code() const {
return _code.c_str();
}
// caller does not own the returned char pointers
const char* color() const {
return _color.c_str();
}
size_t station_count() const {
return _stations.size();
}
// caller does not own the returned array or StationInfo pointers
const std::vector<StationInfo>* stations() const {
return &_stations;
}
friend class MTRNextTrainHandler;
private:
// Caller transfers ownership of stations array and its contents to LineInfo
LineInfo(
cJSON* line_json
);
std::string _code;
std::string _color;
std::vector<StationInfo> _stations;
};

View File

@@ -1,167 +0,0 @@
#include "external/mtr/mtr.h"
#include "external/mtr/line_info.h"
#include "external/mtr/station_info.h"
#include "external/mtr/arrival.h"
#include "assets/MTR_LINE_STATION.h"
#include "network/network.h"
#include "network/http_handler.h"
#include "cJSON.h"
#include "esp_log.h"
#include <string>
#include <sstream>
static const char* TAG = "MTRNextTrainHandler";
// MTR Next Train API endpoint
// Note: This is a placeholder - replace with actual MTR API endpoint
static const char* MTR_API_BASE = "https://rt.data.gov.hk/v1/transport/mtr/getSchedule.php";
MTRNextTrainHandler::MTRNextTrainHandler() {
ESP_LOGI(TAG, "Initializing MTR Next Train Handler");
mtr_data = cJSON_Parse(MTR_LINE_STATION_JSON);
if (!mtr_data) {
ESP_LOGE(TAG, "Failed to parse MTR line station JSON");
} else {
ESP_LOGI(TAG, "Successfully parsed MTR line station JSON");
}
}
MTRNextTrainHandler::~MTRNextTrainHandler() {
if (mtr_data) {
cJSON_Delete(mtr_data);
mtr_data = nullptr;
}
ESP_LOGI(TAG, "MTR Next Train Handler destroyed");
}
std::vector<LineInfo> MTRNextTrainHandler::get_lines() {
std::vector<LineInfo> lines;
if (!mtr_data) {
ESP_LOGE(TAG, "MTR data not initialized");
return lines;
}
// Iterate through all line objects in the JSON
cJSON* line_json = mtr_data->child;
while (line_json) {
if (cJSON_IsObject(line_json)) {
lines.push_back(LineInfo(line_json));
}
line_json = line_json->next;
}
ESP_LOGI(TAG, "Retrieved %zu MTR lines", lines.size());
return lines;
}
MtrArrivalErrorCode MTRNextTrainHandler::get_next_arrival_info(
NetworkHandler* network_handler,
std::string& line_code,
std::string& station_code,
StationArrivalInfo*& out_info,
Language lang
) {
if (!network_handler) {
ESP_LOGE(TAG, "NetworkHandler is null");
return MtrArrivalErrorCode::UNKNOWN;
}
if (!mtr_data) {
ESP_LOGE(TAG, "MTR data not initialized");
return MtrArrivalErrorCode::UNKNOWN;
}
// Verify line exists
cJSON* line_json = cJSON_GetObjectItem(mtr_data, line_code.c_str());
if (!line_json) {
ESP_LOGW(TAG, "Line not found: %s", line_code.c_str());
return MtrArrivalErrorCode::LINE_NOT_FOUND;
}
// Verify station exists in line
bool station_found = false;
cJSON* stations_json = cJSON_GetObjectItem(line_json, "stations");
if (stations_json && cJSON_IsArray(stations_json)) {
int station_count = cJSON_GetArraySize(stations_json);
for (int i = 0; i < station_count; i++) {
cJSON* station = cJSON_GetArrayItem(stations_json, i);
cJSON* code_json = cJSON_GetObjectItem(station, "code");
if (code_json && cJSON_IsString(code_json)) {
if (station_code == code_json->valuestring) {
station_found = true;
break;
}
}
}
}
if (!station_found) {
ESP_LOGW(TAG, "Station not found: %s in line %s", station_code.c_str(), line_code.c_str());
return MtrArrivalErrorCode::STATION_NOT_FOUND;
}
// Build API URL
std::ostringstream url;
url << MTR_API_BASE << "?line=" << line_code << "&sta=" << station_code;
if (lang == Language::EN) {
url << "&lang=en";
}
std::string url_str = url.str();
ESP_LOGI(TAG, "Fetching arrival info from: %s", url_str.c_str());
// Create HTTP client configuration
esp_http_client_config_t http_config = {};
http_config.url = url_str.c_str();
http_config.timeout_ms = 10000;
http_config.transport_type = HTTP_TRANSPORT_OVER_SSL;
http_config.use_global_ca_store = true;
http_config.skip_cert_common_name_check = false;
// Get HTTP handler and perform request
auto http_handler = network_handler->get_http_handler(std::move(http_config));
if (!http_handler) {
ESP_LOGE(TAG, "Failed to create HTTP handler");
return MtrArrivalErrorCode::UNKNOWN;
}
esp_err_t err = http_handler->perform_request();
if (err != ESP_OK) {
ESP_LOGE(TAG, "HTTP request failed: %s", esp_err_to_name(err));
return MtrArrivalErrorCode::NO_ARRIVAL_INFO;
}
// Get response body
char* buffer = nullptr;
int total_len = 0;
http_handler->get_body(buffer, total_len);
if (!buffer || total_len <= 0) {
ESP_LOGE(TAG, "Empty response from MTR API");
if (buffer) {
free(buffer);
}
return MtrArrivalErrorCode::NO_ARRIVAL_INFO;
}
ESP_LOGI(TAG, "Received %d bytes from MTR API", total_len);
ESP_LOGD(TAG, "Response: %s", buffer);
// Parse JSON response
cJSON* arrival_json = cJSON_Parse(buffer);
free(buffer);
if (!arrival_json) {
ESP_LOGE(TAG, "Failed to parse MTR API response");
return MtrArrivalErrorCode::NO_ARRIVAL_INFO;
}
// Create StationArrivalInfo object
out_info = new StationArrivalInfo(mtr_data, arrival_json, line_code, station_code);
cJSON_Delete(arrival_json);
ESP_LOGI(TAG, "Successfully retrieved arrival info for %s/%s", line_code.c_str(), station_code.c_str());
return MtrArrivalErrorCode::NONE;
}

View File

@@ -1,58 +0,0 @@
#pragma once
#include "assets/MTR_LINE_STATION.h"
#include "cJSON.h"
#include <string>
#include "esp_log.h"
#include "external/mtr/line_info.h"
#include <vector>
#include "network/network.h"
// Forward declaration
struct StationArrivalInfo;
struct LineInfo;
enum class MtrArrivalErrorCode {
NONE = 0,
LINE_NOT_FOUND = 1,
STATION_NOT_FOUND = 2,
NO_ARRIVAL_INFO = 3,
UNKNOWN = 99,
};
enum class Language {
EN,
TC,
};
class MTRNextTrainHandler {
public:
/**
* @brief Construct a new MTR Next Train Handler object
* @param json Pointer to cJSON object containing MTR Next Train data
*
* > Caller transfers ownership of the cJSON object to MTRNextTrainHandler
*
* cJSON structure for MTR Next Train data
* This structure is used to parse and store the MTR Next Train JSON data.
* Record<code name string, {name: string, code: string, color: hex string, station: {code: string, name: string}[]}>
*/
MTRNextTrainHandler();
~MTRNextTrainHandler();
std::vector<LineInfo> get_lines();
MtrArrivalErrorCode get_next_arrival_info(
NetworkHandler* network_handler,
std::string& line_code,
std::string& station_code,
StationArrivalInfo*& out_info,
Language lang = Language::TC
);
private:
cJSON* mtr_data;
};

View File

@@ -1,28 +0,0 @@
#include "external/mtr/station_info.h"
#include "cJSON.h"
#include "esp_log.h"
StationInfo::StationInfo(cJSON* station_json) {
if (!station_json) {
ESP_LOGE(STATION_INFO_TAG, "station_json is null");
return;
}
// Parse station code
cJSON* code_json = cJSON_GetObjectItem(station_json, "code");
if (code_json && cJSON_IsString(code_json)) {
_code = code_json->valuestring;
} else {
ESP_LOGW(STATION_INFO_TAG, "Missing or invalid 'code' field");
}
// Parse station name
cJSON* name_json = cJSON_GetObjectItem(station_json, "name");
if (name_json && cJSON_IsString(name_json)) {
_name = name_json->valuestring;
} else {
ESP_LOGW(STATION_INFO_TAG, "Missing or invalid 'name' field");
}
ESP_LOGD(STATION_INFO_TAG, "Created StationInfo: %s (%s)", _name.c_str(), _code.c_str());
}

View File

@@ -1,27 +0,0 @@
#pragma once
#include "esp_log.h"
#include "external/mtr/line_info.h"
#include <string>
#define STATION_INFO_TAG "StationInfo"
// Forward declaration
struct LineInfo;
struct StationInfo {
public:
StationInfo(cJSON* station_json);
const char* name() const { return _name.c_str(); }
const char* code() const { return _code.c_str(); }
friend class LineInfo;
private:
// Caller transfers ownership of station_name and station_code to StationInfo
StationInfo(std::string& station_name, std::string& station_code)
: _name(station_name), _code(station_code) { }
std::string _name;
std::string _code;
};

View File

@@ -17,4 +17,3 @@ dependencies:
lvgl/lvgl: ^9.4.0 lvgl/lvgl: ^9.4.0
espressif/esp_lcd_touch_gt911: ^1.2.0~1 espressif/esp_lcd_touch_gt911: ^1.2.0~1
espressif/esp_lvgl_port: ^2.7.0 espressif/esp_lvgl_port: ^2.7.0
espressif/cjson: ^1.7.19

View File

@@ -1,12 +1,3 @@
#include <stdio.h>
#include <inttypes.h>
#include "sdkconfig.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "esp_chip_info.h"
#include "esp_flash.h"
#include "esp_system.h"
#include "esp_psram.h"
#include "info.h" #include "info.h"
void display_chip_info() { void display_chip_info() {
@@ -15,16 +6,13 @@ void display_chip_info() {
esp_chip_info_t chip_info; esp_chip_info_t chip_info;
uint32_t flash_size; uint32_t flash_size;
esp_chip_info(&chip_info); esp_chip_info(&chip_info);
printf("This is %s chip with %d CPU core(s), %s%s%s%s%s, ", printf("This is %s chip with %d CPU core(s), %s%s%s%s, ",
CONFIG_IDF_TARGET, CONFIG_IDF_TARGET,
chip_info.cores, chip_info.cores,
(chip_info.features & CHIP_FEATURE_WIFI_BGN) ? "WiFi/" : "", (chip_info.features & CHIP_FEATURE_WIFI_BGN) ? "WiFi/" : "",
(chip_info.features & CHIP_FEATURE_BT) ? "BT" : "", (chip_info.features & CHIP_FEATURE_BT) ? "BT" : "",
(chip_info.features & CHIP_FEATURE_BLE) ? "BLE" : "", (chip_info.features & CHIP_FEATURE_BLE) ? "BLE" : "",
(chip_info.features & CHIP_FEATURE_IEEE802154) ? ", 802.15.4 (Zigbee/Thread), " : "", (chip_info.features & CHIP_FEATURE_IEEE802154) ? ", 802.15.4 (Zigbee/Thread)" : "");
// psram
(chip_info.features & CHIP_FEATURE_EMB_PSRAM) ? "with embedded PSRAM, " : ""
);
unsigned major_rev = chip_info.revision / 100; unsigned major_rev = chip_info.revision / 100;
unsigned minor_rev = chip_info.revision % 100; unsigned minor_rev = chip_info.revision % 100;
@@ -38,10 +26,5 @@ void display_chip_info() {
(chip_info.features & CHIP_FEATURE_EMB_FLASH) ? "embedded" : "external"); (chip_info.features & CHIP_FEATURE_EMB_FLASH) ? "embedded" : "external");
printf("Minimum free heap size: %" PRIu32 " bytes\n", esp_get_minimum_free_heap_size()); printf("Minimum free heap size: %" PRIu32 " bytes\n", esp_get_minimum_free_heap_size());
// psram
printf("PSRAM size: %u bytes\n", esp_psram_get_size());
// dma size
printf("DMA-capable memory size: %u bytes\n", heap_caps_get_free_size(MALLOC_CAP_DMA));
printf("DMA-capable internal memory size: %u bytes\n", heap_caps_get_free_size(MALLOC_CAP_DMA | MALLOC_CAP_INTERNAL));
} }

View File

@@ -1 +1,10 @@
#include <stdio.h>
#include <inttypes.h>
#include "sdkconfig.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "esp_chip_info.h"
#include "esp_flash.h"
#include "esp_system.h"
void display_chip_info(); void display_chip_info();

View File

@@ -3,8 +3,8 @@
#include "freertos/event_groups.h" #include "freertos/event_groups.h"
#include <memory> #include <memory>
typedef bool(*FilterFunc)(const std::string& key); typedef bool(*FilterFunc)(const char* const& key);
typedef void (*KeyValueProcessor)(void* arg, const std::string& key, const std::string& value); typedef void (*KeyValueProcessor)(void* arg, const char* const& key, const char* const& value);
class KVStorageHandler { class KVStorageHandler {
public: public:
@@ -13,14 +13,15 @@ public:
virtual void init(const EventGroupHandle_t& system_event_group) = 0; virtual void init(const EventGroupHandle_t& system_event_group) = 0;
// Store a key-value pair // Store a key-value pair
virtual void put(const std::string& key, const std::string& value) = 0; virtual void put(const char* const& key, const char* const& value) = 0;
// Retrieve a value by key, returns empty string if key not found // Retrieve a value by key, returns nullptr if key not found
virtual std::string get(const std::string& key) const = 0; // The caller is responsible for freeing the returned memory
virtual std::unique_ptr<char[]> get(const char* const& key) const = 0;
virtual esp_err_t process_all(KeyValueProcessor processor, void* arg) const = 0; virtual esp_err_t process_all(KeyValueProcessor processor, void* arg) const = 0;
virtual esp_err_t process_filtered(const std::string& key_prefix, KeyValueProcessor processor, void* arg) const = 0; virtual esp_err_t process_filtered(const char* const& key_prefix, KeyValueProcessor processor, void* arg) const = 0;
virtual esp_err_t process_filtered(FilterFunc filter_func, KeyValueProcessor processor, void* arg) const = 0; virtual esp_err_t process_filtered(FilterFunc filter_func, KeyValueProcessor processor, void* arg) const = 0;
// Delete a key-value pair // Delete a key-value pair
virtual void remove(const std::string& key) = 0; virtual void remove(const char* const& key) = 0;
}; };

View File

@@ -2,9 +2,6 @@
#include "io/nvs_handler.h" #include "io/nvs_handler.h"
#include "nvs_flash.h" #include "nvs_flash.h"
#include "string.h" #include "string.h"
#include "esp_log.h"
#define TAG "NVSStorageHandler"
NVSStorageHandler::NVSStorageHandler( NVSStorageHandler::NVSStorageHandler(
const char* name_space const char* name_space
@@ -27,52 +24,49 @@ void NVSStorageHandler::init(const EventGroupHandle_t& system_event_group) {
err = nvs_open(this->name_space, NVS_READWRITE, &this->nvsHandle); err = nvs_open(this->name_space, NVS_READWRITE, &this->nvsHandle);
if (err != ESP_OK) { if (err != ESP_OK) {
ESP_LOGE(TAG, "Error (%s) opening NVS handle!", esp_err_to_name(err)); printf("Error (%s) opening NVS handle!\n", esp_err_to_name(err));
} else { } else {
if (system_event_group != nullptr) {
xEventGroupSetBits(system_event_group, STORAGE_READY_BIT); xEventGroupSetBits(system_event_group, STORAGE_READY_BIT);
} printf("NVS Storage initialized.\n");
ESP_LOGI(TAG, "NVS Storage initialized.");
} }
} }
void NVSStorageHandler::put(const std::string& key, const std::string& value) { void NVSStorageHandler::put(const char* const& key, const char* const& value) {
if (this->nvsHandle == 0) { if (this->nvsHandle == 0) {
ESP_LOGE(TAG, "NVS handle is not initialized."); printf("NVS handle is not initialized.\n");
return; return;
} }
esp_err_t err = nvs_set_str(this->nvsHandle, key.c_str(), value.c_str()); esp_err_t err = nvs_set_str(this->nvsHandle, key, value);
if (err != ESP_OK) { if (err != ESP_OK) {
ESP_LOGE(TAG, "Error (%s) setting key-value pair in NVS!", esp_err_to_name(err)); printf("Error (%s) setting key-value pair in NVS!\n", esp_err_to_name(err));
} else { } else {
nvs_commit(this->nvsHandle); nvs_commit(this->nvsHandle);
// ESP_LOGI(TAG, "Key-value pair (%s, %s) stored in NVS.", key.c_str(), value.c_str()); printf("Key-value pair (%s, %s) stored in NVS.\n", key, value);
} }
} }
std::string NVSStorageHandler::get(const std::string& key) const { std::unique_ptr<char[]> NVSStorageHandler::get(const char* const& key) const {
if (this->nvsHandle == 0) { if (this->nvsHandle == 0) {
ESP_LOGE(TAG, "NVS handle is not initialized."); printf("NVS handle is not initialized.\n");
return ""; return nullptr;
} }
size_t required_size = 0; size_t required_size = 0;
esp_err_t err = nvs_get_str(this->nvsHandle, key.c_str(), nullptr, &required_size); esp_err_t err = nvs_get_str(this->nvsHandle, key, nullptr, &required_size);
if (err == ESP_ERR_NVS_NOT_FOUND) { if (err == ESP_ERR_NVS_NOT_FOUND) {
ESP_LOGW(TAG, "Key %s not found in NVS.", key.c_str()); printf("Key %s not found in NVS.\n", key);
return ""; return nullptr;
} else if (err != ESP_OK) { } else if (err != ESP_OK) {
ESP_LOGE(TAG, "Error (%s) getting size for key %s from NVS!", esp_err_to_name(err), key.c_str()); printf("Error (%s) getting size for key %s from NVS!\n", esp_err_to_name(err), key);
return ""; return nullptr;
} }
// Allocate string buffer with correct size (includes null terminator) std::unique_ptr<char[]> value(new char[required_size]);
std::string value(required_size - 1, '\0'); err = nvs_get_str(this->nvsHandle, key, value.get(), &required_size);
err = nvs_get_str(this->nvsHandle, key.c_str(), &value[0], &required_size);
if (err != ESP_OK) { if (err != ESP_OK) {
ESP_LOGE(TAG, "Error (%s) getting value for key %s from NVS!", esp_err_to_name(err), key.c_str()); printf("Error (%s) getting value for key %s from NVS!\n", esp_err_to_name(err), key);
return ""; return nullptr;
} }
return value; return value;
@@ -82,7 +76,7 @@ NVSIteratorGuard NVSStorageHandler::create_iterator() const {
nvs_iterator_t it = nullptr; nvs_iterator_t it = nullptr;
esp_err_t err = nvs_entry_find(NVS_DEFAULT_PART_NAME, this->name_space, NVS_TYPE_ANY, &it); esp_err_t err = nvs_entry_find(NVS_DEFAULT_PART_NAME, this->name_space, NVS_TYPE_ANY, &it);
if (err != ESP_OK) { if (err != ESP_OK) {
ESP_LOGE(TAG, "Error (%s) creating NVS iterator!", esp_err_to_name(err)); printf("Error (%s) creating NVS iterator!\n", esp_err_to_name(err));
return NVSIteratorGuard(nullptr, err); return NVSIteratorGuard(nullptr, err);
} }
@@ -100,23 +94,22 @@ esp_err_t NVSStorageHandler::process_all(KeyValueProcessor processor, void* arg)
nvs_entry_info_t info; nvs_entry_info_t info;
esp_err_t err = nvs_entry_info(it, &info); esp_err_t err = nvs_entry_info(it, &info);
if (err != ESP_OK) { if (err != ESP_OK) {
ESP_LOGE(TAG, "Error (%s) getting NVS entry info!", esp_err_to_name(err)); printf("Error (%s) getting NVS entry info!\n", esp_err_to_name(err));
return err; return err;
} }
nvs_handle_t temp_handle; nvs_handle_t temp_handle;
err = nvs_open(this->name_space, NVS_READONLY, &temp_handle); err = nvs_open(this->name_space, NVS_READONLY, &temp_handle);
if (err != ESP_OK) { if (err != ESP_OK) {
ESP_LOGE(TAG, "Error (%s) opening NVS handle for reading!", esp_err_to_name(err)); printf("Error (%s) opening NVS handle for reading!\n", esp_err_to_name(err));
return err; return err;
} }
// call the processor with the key and value // call the processor with the key and value
std::string key_str = info.key; processor(arg, info.key, this->get(info.key).get());
processor(arg, key_str, this->get(key_str));
} }
return ESP_OK; return ESP_OK;
} }
esp_err_t NVSStorageHandler::process_filtered(const std::string& key_prefix, KeyValueProcessor processor, void* arg) const { esp_err_t NVSStorageHandler::process_filtered(const char* const& key_prefix, KeyValueProcessor processor, void* arg) const {
NVSIteratorGuard iterator_guard = this->create_iterator(); NVSIteratorGuard iterator_guard = this->create_iterator();
if (!iterator_guard.is_valid()) { if (!iterator_guard.is_valid()) {
return iterator_guard.get_error(); return iterator_guard.get_error();
@@ -127,19 +120,19 @@ esp_err_t NVSStorageHandler::process_filtered(const std::string& key_prefix, Key
nvs_entry_info_t info; nvs_entry_info_t info;
esp_err_t err = nvs_entry_info(it, &info); esp_err_t err = nvs_entry_info(it, &info);
if (err != ESP_OK) { if (err != ESP_OK) {
ESP_LOGE(TAG, "Error (%s) getting NVS entry info!", esp_err_to_name(err)); printf("Error (%s) getting NVS entry info!\n", esp_err_to_name(err));
return err; return err;
} }
// check if the key matches the prefix // check if the key matches the prefix
if (strncmp(info.key, key_prefix.c_str(), key_prefix.length()) == 0) { if (strncmp(info.key, key_prefix, strlen(key_prefix)) == 0) {
nvs_handle_t temp_handle; nvs_handle_t temp_handle;
err = nvs_open(this->name_space, NVS_READONLY, &temp_handle); err = nvs_open(this->name_space, NVS_READONLY, &temp_handle);
if (err != ESP_OK) { if (err != ESP_OK) {
ESP_LOGE(TAG, "Error (%s) opening NVS handle for reading!", esp_err_to_name(err)); printf("Error (%s) opening NVS handle for reading!\n", esp_err_to_name(err));
return err; return err;
} }
// call the processor with the key and value // call the processor with the key and value
processor(arg, std::string(info.key), this->get(std::string(info.key))); processor(arg, info.key, this->get(info.key).get());
} }
} }
return ESP_OK; return ESP_OK;
@@ -156,36 +149,35 @@ esp_err_t NVSStorageHandler::process_filtered(FilterFunc filter_func, KeyValuePr
nvs_entry_info_t info; nvs_entry_info_t info;
esp_err_t err = nvs_entry_info(it, &info); esp_err_t err = nvs_entry_info(it, &info);
if (err != ESP_OK) { if (err != ESP_OK) {
ESP_LOGE(TAG, "Error (%s) getting NVS entry info!", esp_err_to_name(err)); printf("Error (%s) getting NVS entry info!\n", esp_err_to_name(err));
return err; return err;
} }
// check if the key matches the filter function // check if the key matches the filter function
std::string key_str(info.key); if (filter_func(info.key)) {
if (filter_func(key_str)) {
nvs_handle_t temp_handle; nvs_handle_t temp_handle;
err = nvs_open(this->name_space, NVS_READONLY, &temp_handle); err = nvs_open(this->name_space, NVS_READONLY, &temp_handle);
if (err != ESP_OK) { if (err != ESP_OK) {
ESP_LOGE(TAG, "Error (%s) opening NVS handle for reading!", esp_err_to_name(err)); printf("Error (%s) opening NVS handle for reading!\n", esp_err_to_name(err));
return err; return err;
} }
// call the processor with the key and value // call the processor with the key and value
processor(arg, key_str, this->get(key_str)); processor(arg, info.key, this->get(info.key).get());
} }
} }
return ESP_OK; return ESP_OK;
} }
void NVSStorageHandler::remove(const std::string& key) { void NVSStorageHandler::remove(const char* const& key) {
if (this->nvsHandle == 0) { if (this->nvsHandle == 0) {
ESP_LOGE(TAG, "NVS handle is not initialized."); printf("NVS handle is not initialized.\n");
return; return;
} }
esp_err_t err = nvs_erase_key(this->nvsHandle, key.c_str()); esp_err_t err = nvs_erase_key(this->nvsHandle, key);
if (err != ESP_OK) { if (err != ESP_OK) {
ESP_LOGE(TAG, "Error (%s) deleting key %s from NVS!", esp_err_to_name(err), key.c_str()); printf("Error (%s) deleting key %s from NVS!\n", esp_err_to_name(err), key);
} else { } else {
nvs_commit(this->nvsHandle); nvs_commit(this->nvsHandle);
ESP_LOGI(TAG, "Key %s deleted from NVS.", key.c_str()); printf("Key %s deleted from NVS.\n", key);
} }
} }

View File

@@ -53,14 +53,14 @@ public:
void init(const EventGroupHandle_t& system_event_group) override; void init(const EventGroupHandle_t& system_event_group) override;
void put(const std::string& key, const std::string& value) override; void put(const char* const& key, const char* const& value) override;
std::string get(const std::string& key) const override; std::unique_ptr<char[]> get(const char* const& key) const override;
esp_err_t process_all(KeyValueProcessor processor, void* arg) const override; esp_err_t process_all(KeyValueProcessor processor, void* arg) const override;
esp_err_t process_filtered(const std::string& key_prefix, KeyValueProcessor processor, void* arg) const override; esp_err_t process_filtered(const char* const& key_prefix, KeyValueProcessor processor, void* arg) const override;
esp_err_t process_filtered(FilterFunc filter_func, KeyValueProcessor processor, void* arg) const override; esp_err_t process_filtered(FilterFunc filter_func, KeyValueProcessor processor, void* arg) const override;
void remove(const std::string& key) override; void remove(const char* const& key) override;
private: private:
NVSIteratorGuard create_iterator() const; NVSIteratorGuard create_iterator() const;

File diff suppressed because it is too large Load Diff

View File

@@ -1,3 +1,10 @@
/*
* SPDX-FileCopyrightText: 2010-2022 Espressif Systems (Shanghai) CO LTD
*
* SPDX-License-Identifier: CC0-1.0
*/
#include <stdio.h> #include <stdio.h>
#include <inttypes.h> #include <inttypes.h>
#include <stdexcept> #include <stdexcept>
@@ -7,32 +14,19 @@
#include "esp_chip_info.h" #include "esp_chip_info.h"
#include "esp_flash.h" #include "esp_flash.h"
#include "esp_system.h" #include "esp_system.h"
#include "esp_log.h"
// //
#include "common/constants.h" #include "common/constants.h"
#include "common/queue_defs.h" #include "common/queue_defs.h"
#include "io/nvs_handler.h" #include "io/nvs_handler.h"
#include "info/info.h" #include "info/info.h"
#include "display/eink_display_handler.h" #include "display/display.h"
#include "display/lvgl_handler.h" #include "touch/touch.h"
#include "ui/ui_handler.h"
#include "ui/app_registry.h"
#include "ui/apps/shutdown_app.h"
#include "ui/apps/discord_app.h"
#include "ui/apps/mtr_app.h"
#include <tick/lv_tick.h> #include <tick/lv_tick.h>
#include "esp_lvgl_port.h"
#include "lvgl.h"
#include "network.h" #include "network.h"
#include <esp_task_wdt.h>
#include "lvgl.h"
// nvs storage namespaces, 15 characters max
#define DEFAULT_STORAGE_NAMESPACE "storage" #define DEFAULT_STORAGE_NAMESPACE "storage"
#define WIFI_CREDENTIALS_STORAGE_NAMESPACE "wifi_cred" #define WIFI_CREDENTIALS_STORAGE_NAMESPACE "wifi_credentials"
#define TAG "Main"
extern "C" void app_main(void); extern "C" void app_main(void);
@@ -43,123 +37,69 @@ void init_queues(
); );
void app_main(void) { void app_main(void) {
display_chip_info(); display_chip_info();
try {
QueueHandle_t touch_event_queue = NULL; QueueHandle_t touch_event_queue = NULL;
EventGroupHandle_t system_event_group = NULL, system_lifecycle_event_group = NULL; EventGroupHandle_t system_event_group = NULL, system_lifecycle_event_group = NULL;
init_queues(touch_event_queue, system_event_group, system_lifecycle_event_group); init_queues(touch_event_queue, system_event_group, system_lifecycle_event_group);
if (touch_event_queue == NULL || system_event_group == NULL || system_lifecycle_event_group == NULL) { if (touch_event_queue == NULL || system_event_group == NULL || system_lifecycle_event_group == NULL) {
ESP_LOGE("Main", "Failed to create one or more queues/event groups"); throw std::runtime_error("Failed to create one or more queues/event groups");
vTaskDelay(5000 / portTICK_PERIOD_MS);
return esp_restart();
} }
ESP_LOGI(TAG, "Queues initialized.\n"); printf("Queues initialized.\n");
SemaphoreHandle_t lvgl_mutex = xSemaphoreCreateMutex();
// if (lvgl_mutex == NULL) {
// KVStorageHandler* kv_storage_handler = new NVSStorageHandler( throw std::runtime_error("Failed to create LVGL mutex");
// DEFAULT_STORAGE_NAMESPACE
// );
// auto wifi_handler = std::make_unique<WifiHandler>(
// std::unique_ptr<KVStorageHandler>(new NVSStorageHandler(WIFI_CREDENTIALS_STORAGE_NAMESPACE))
// );
// NetworkHandler* network_handler = new NetworkHandler(std::move(wifi_handler));
EInkDisplayHandler* display_handler = new EInkDisplayHandler();
// Initialize display and touch
// display_handler->init_devices(system_event_group);
display_handler->init_devices();
ESP_LOGI(TAG, "E-Ink display handler initialized.\n");
// LVGL Handler
std::unique_ptr<EInkDisplayHandler> display_uptr(display_handler);
LVGLHandler lvgl_handler(std::move(display_uptr));
esp_err_t err = lvgl_handler.initLVGL(system_event_group);
if (err != ESP_OK) {
ESP_LOGE(TAG, "Failed to initialize LVGL handler: %s", esp_err_to_name(err));
vTaskDelay(5000 / portTICK_PERIOD_MS);
return esp_restart();
} }
//
WifiHandler wifi_handler(
new NVSStorageHandler(WIFI_CREDENTIALS_STORAGE_NAMESPACE)
);
NetworkHandler* network_handler = new NetworkHandler(std::move(wifi_handler));
KVStorageHandler* kv_storage_handler = new NVSStorageHandler(
DEFAULT_STORAGE_NAMESPACE
);
DisplayHandler* display_handler = new EInkDisplayHandler(touch_event_queue, lvgl_mutex);
TouchHandler* touch_handler = new EInkTouchHandler(touch_event_queue);
//
network_handler->init(system_event_group);
kv_storage_handler->init(system_event_group);
display_handler->init(system_event_group);
touch_handler->init(system_event_group);
//
// LVGL tick timer
auto lvgl_tick_timer_callback = [](TimerHandle_t xTimer) {
lv_tick_inc(5);
};
TimerHandle_t lvgl_tick_timer = xTimerCreate(
"lvgl_tick_timer",
pdMS_TO_TICKS(5),
pdTRUE,
NULL,
lvgl_tick_timer_callback
);
if (lvgl_tick_timer == NULL) {
throw std::runtime_error("Failed to create LVGL tick timer");
}
xTimerStart(lvgl_tick_timer, 0);
// //
// kv_storage_handler->init(system_event_group); printf("Waiting for system to be ready...\n");
// network_handler->init(system_event_group);
//
ESP_LOGI(TAG, "Waiting for system to be ready...\n");
xEventGroupWaitBits( xEventGroupWaitBits(
system_event_group, system_event_group,
// DISPLAY_READY_BIT | STORAGE_READY_BIT | NETWORK_READY_BIT, DISPLAY_READY_BIT | TOUCH_CALIBRATED_BIT | STORAGE_READY_BIT | NETWORK_READY_BIT,
DISPLAY_READY_BIT,
// do not clear on exit, require explicit reset // do not clear on exit, require explicit reset
pdFALSE, pdFALSE,
pdTRUE, pdTRUE,
portMAX_DELAY portMAX_DELAY
); );
ESP_LOGI(TAG, "System is ready. Starting main application...\n"); printf("System is ready. Starting main application...\n");
// starting event loops
// Allow LVGL system to stabilize before creating objects display_handler->start_event_loop();
vTaskDelay(pdMS_TO_TICKS(100)); touch_handler->start_event_loop();
// Create main screen and button for random rectangle demo
lv_obj_t* scr = lv_scr_act();
// Create a button
lv_obj_t* btn = lv_btn_create(scr);
lv_obj_set_size(btn, 200, 60);
lv_obj_align(btn, LV_ALIGN_TOP_MID, 0, 20);
lv_obj_set_style_border_width(btn, 2, 0);
lv_obj_set_style_border_color(btn, lv_color_make(0, 0, 0), 0);
// Add label to button
lv_obj_t* label = lv_label_create(btn);
lv_label_set_text(label, "Create Random Rect");
lv_obj_center(label);
lv_obj_set_style_text_color(label, lv_color_make(0, 0, 0), 0);
// Event handler for button - creates random rectangles
auto btn_event_cb = [](lv_event_t* e) {
lv_obj_t* scr = lv_scr_act();
// Create a random rectangle
lv_obj_t* rect = lv_obj_create(scr);
// Random size (30-100 pixels)
lv_coord_t width = 30 + (esp_random() % 70);
lv_coord_t height = 30 + (esp_random() % 70);
lv_obj_set_size(rect, width, height);
// Random position (avoid top 100px where button is)
lv_coord_t x = esp_random() % (LV_HOR_RES - width);
lv_coord_t y = 100 + (esp_random() % (LV_VER_RES - 100 - height));
lv_obj_set_pos(rect, x, y);
lv_obj_set_style_bg_color(rect, lv_color_make(0, 0, 0), 0);
lv_obj_set_style_bg_opa(rect, LV_OPA_COVER, 0);
// Make rectangle clickable
lv_obj_add_flag(rect, LV_OBJ_FLAG_CLICKABLE);
// Event handler to delete rectangle when clicked
auto rect_event_cb = [](lv_event_t* e) {
lv_obj_t* rect = static_cast<lv_obj_t*>(lv_event_get_target(e));
lv_obj_del(rect);
ESP_LOGI(TAG, "Rectangle deleted");
};
lv_obj_add_event_cb(rect, rect_event_cb, LV_EVENT_CLICKED, NULL);
ESP_LOGI(TAG, "Created rectangle at (%d, %d) with size %dx%d", x, y, width, height);
};
lv_obj_add_event_cb(btn, btn_event_cb, LV_EVENT_CLICKED, NULL);
ESP_LOGI(TAG, "Random rectangle demo initialized. Tap button to create rectangles.\n");
// wait for shutdown signal // wait for shutdown signal
ESP_LOGI(TAG, "Waiting for shutdown signal...\n");
EventBits_t bits = xEventGroupWaitBits( EventBits_t bits = xEventGroupWaitBits(
system_lifecycle_event_group, system_lifecycle_event_group,
SYSTEM_SHUTDOWN_BIT | SYSTEM_RESTART_BIT, SYSTEM_SHUTDOWN_BIT | SYSTEM_RESTART_BIT,
@@ -168,34 +108,27 @@ void app_main(void) {
pdFALSE, pdFALSE,
portMAX_DELAY portMAX_DELAY
); );
ESP_LOGI(TAG, "Shutdown signal received. Cleaning up...\n"); printf("Shutdown signal received. Cleaning up...\n");
// Show shutdown screen using the shutdown descriptor's app instance
// ShutdownApp* shutdown_app = dynamic_cast<ShutdownApp*>(shutdown_descriptor->get_app_instance());
// if (shutdown_app) {
// ui_handler.switch_app(shutdown_app);
// }
vTaskDelay(1000 / portTICK_PERIOD_MS); // Display shutdown message briefly
// Cleanup
// ui_handler.deinit();
// delete demo_descriptor;
// delete shutdown_descriptor;
// delete mtr_descriptor;
// cleanup
shutdown_display_handlerFunc shutdown_display_handler = display_handler->get_shutdown_display_handler();
restart_display_handlerFunc restart_display_handler = display_handler->get_restart_display_handler();
delete display_handler;
delete touch_handler;
vSemaphoreDelete(lvgl_mutex);
vEventGroupDelete(system_event_group); vEventGroupDelete(system_event_group);
vQueueDelete(touch_event_queue); vQueueDelete(touch_event_queue);
ESP_LOGI(TAG, "Cleanup complete.\n"); printf("Cleanup complete.\n");
// handle shutdown or restart // handle shutdown or restart
if (bits & SYSTEM_SHUTDOWN_BIT) { if (bits & SYSTEM_SHUTDOWN_BIT) {
// if (shutdown_display_handler != nullptr) { if (shutdown_display_handler != nullptr) {
// ESP_LOGI(TAG, "Calling display shutdown handler...\n"); printf("Calling display shutdown handler...\n");
// shutdown_display_handler(); shutdown_display_handler();
// } else { } else {
// ESP_LOGI(TAG, "No display shutdown handler to call.\n"); printf("No display shutdown handler to call.\n");
// } }
ESP_LOGI(TAG, "System is shutting down.\n"); printf("System is shutting down.\n");
fflush(stdout); fflush(stdout);
// wait for start bit to be set again if future restart is desired, else expect manual power cycle // wait for start bit to be set again if future restart is desired, else expect manual power cycle
EventBits_t bits = xEventGroupWaitBits( EventBits_t bits = xEventGroupWaitBits(
@@ -206,27 +139,49 @@ void app_main(void) {
portMAX_DELAY portMAX_DELAY
); );
if (bits & SYSTEM_START_BIT) { if (bits & SYSTEM_START_BIT) {
ESP_LOGI(TAG, "SYSTEM_START_BIT received, restarting system.\n"); printf("SYSTEM_START_BIT received, restarting system.\n");
} else { } else {
ESP_LOGW(TAG, "No restart signal received, waiting for manual power cycle.\n"); printf("No restart signal received, waiting for manual power cycle.\n");
while (true) { while (true) {
vTaskDelay(portMAX_DELAY); vTaskDelay(portMAX_DELAY);
} }
} }
} else if (bits & SYSTEM_RESTART_BIT) { } else if (bits & SYSTEM_RESTART_BIT) {
// if (restart_display_handler != nullptr) { if (restart_display_handler != nullptr) {
// ESP_LOGI(TAG, "Calling display restart handler...\n"); printf("Calling display restart handler...\n");
// restart_display_handler(); restart_display_handler();
// } else { } else {
// ESP_LOGI(TAG, "No display restart handler to call.\n"); printf("No display restart handler to call.\n");
// } }
ESP_LOGI(TAG, "System is restarting.\n"); printf("System is restarting.\n");
fflush(stdout); fflush(stdout);
} else { } else {
ESP_LOGW(TAG, "Unknown shutdown signal received. Restarting by default.\n"); printf("Unknown shutdown signal received. Restarting by default.\n");
fflush(stdout); fflush(stdout);
} }
return esp_restart();
}
catch (const std::exception& e) {
printf("Exception occurred during initialization: %s\n", e.what());
printf("System will restart due to the error.\n");
for (int i = 5; i >= 0; --i) {
printf("Restarting in %d seconds...\n", i);
vTaskDelay(1000 / portTICK_PERIOD_MS);
}
printf("Restarting now.\n");
fflush(stdout);
return esp_restart();
}
printf("Reached end of app_main unexpectedly.\n");
printf("System will restart in 10 seconds...\n");
for (int i = 10; i >= 0; --i) {
printf("Restarting in %d seconds...\n", i);
vTaskDelay(1000 / portTICK_PERIOD_MS);
}
printf("Restarting now.\n");
fflush(stdout);
return esp_restart(); return esp_restart();
} }

View File

@@ -4,7 +4,7 @@
#include "common/constants.h" #include "common/constants.h"
NetworkHandler::NetworkHandler( NetworkHandler::NetworkHandler(
std::unique_ptr<WifiHandler> wifiHandler WifiHandler&& wifiHandler
) : wifiHandler(std::move(wifiHandler)) { } ) : wifiHandler(std::move(wifiHandler)) { }
NetworkHandler::~NetworkHandler() { } NetworkHandler::~NetworkHandler() { }
@@ -14,7 +14,7 @@ void NetworkHandler::init(EventGroupHandle_t system_event_group) {
ESP_LOGW("NetworkHandler", "Already initialized, skipping"); ESP_LOGW("NetworkHandler", "Already initialized, skipping");
return; return;
} }
this->wifiHandler->init(); this->wifiHandler.init();
this->initialized = true; this->initialized = true;
xEventGroupSetBits( xEventGroupSetBits(
system_event_group, system_event_group,
@@ -23,10 +23,10 @@ void NetworkHandler::init(EventGroupHandle_t system_event_group) {
} }
WifiHandler& NetworkHandler::get_wifi_handler() { WifiHandler& NetworkHandler::get_wifi_handler() {
return *this->wifiHandler; return this->wifiHandler;
} }
std::unique_ptr<HttpHandler> NetworkHandler::get_http_handler(const esp_http_client_config_t&& config) { std::unique_ptr<HttpHandler> NetworkHandler::get_http_handler(const esp_http_client_config_t&& config) {
return std::unique_ptr<HttpHandler>(new HttpHandler(std::move(config), this->wifiHandler.get())); return std::unique_ptr<HttpHandler>(new HttpHandler(std::move(config), &this->wifiHandler));
} }

View File

@@ -11,7 +11,7 @@ class HttpHandler;
class NetworkHandler { class NetworkHandler {
public: public:
NetworkHandler( NetworkHandler(
std::unique_ptr<WifiHandler> wifiHandler WifiHandler&& wifiHandler
); );
~NetworkHandler(); ~NetworkHandler();
@@ -22,6 +22,6 @@ public:
private: private:
std::unique_ptr<WifiHandler> wifiHandler; WifiHandler wifiHandler;
bool initialized = false; bool initialized = false;
}; };

View File

@@ -1,172 +0,0 @@
#include "udp_client.h"
#include <cstring>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include "esp_log.h"
static const char* TAG = "UDPClient";
UDPClient::UDPClient()
: sock_fd_(-1)
, remote_port_(0)
, configured_(false)
, initialized_(false) {
memset(&remote_addr_, 0, sizeof(remote_addr_));
}
UDPClient::~UDPClient() {
close();
}
esp_err_t UDPClient::init() {
if (initialized_) {
ESP_LOGW(TAG, "Already initialized");
return ESP_OK;
}
sock_fd_ = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (sock_fd_ < 0) {
ESP_LOGE(TAG, "Failed to create socket: errno %d", errno);
return ESP_FAIL;
}
// Set socket to non-blocking mode
esp_err_t err = set_nonblocking();
if (err != ESP_OK) {
::close(sock_fd_);
sock_fd_ = -1;
return err;
}
initialized_ = true;
ESP_LOGI(TAG, "UDP client initialized (fd=%d)", sock_fd_);
return ESP_OK;
}
esp_err_t UDPClient::set_nonblocking() {
int flags = fcntl(sock_fd_, F_GETFL, 0);
if (flags < 0) {
ESP_LOGE(TAG, "Failed to get socket flags: errno %d", errno);
return ESP_FAIL;
}
if (fcntl(sock_fd_, F_SETFL, flags | O_NONBLOCK) < 0) {
ESP_LOGE(TAG, "Failed to set non-blocking mode: errno %d", errno);
return ESP_FAIL;
}
return ESP_OK;
}
esp_err_t UDPClient::configure(const std::string& ip, uint16_t port) {
if (ip.empty() || port == 0) {
ESP_LOGE(TAG, "Invalid IP or port");
return ESP_ERR_INVALID_ARG;
}
struct in_addr addr;
if (inet_pton(AF_INET, ip.c_str(), &addr) != 1) {
ESP_LOGE(TAG, "Invalid IP address format: %s", ip.c_str());
return ESP_ERR_INVALID_ARG;
}
remote_addr_.sin_family = AF_INET;
remote_addr_.sin_port = htons(port);
remote_addr_.sin_addr = addr;
remote_ip_ = ip;
remote_port_ = port;
configured_ = true;
ESP_LOGI(TAG, "Configured endpoint: %s:%u", ip.c_str(), port);
return ESP_OK;
}
esp_err_t UDPClient::send_command(const std::string& command) {
if (!initialized_) {
ESP_LOGE(TAG, "Not initialized");
return ESP_FAIL;
}
if (!configured_) {
ESP_LOGE(TAG, "Endpoint not configured");
return ESP_FAIL;
}
ssize_t sent = sendto(sock_fd_, command.c_str(), command.length(), 0,
(struct sockaddr*)&remote_addr_, sizeof(remote_addr_));
if (sent < 0) {
ESP_LOGE(TAG, "Failed to send command '%s': errno %d", command.c_str(), errno);
return ESP_FAIL;
}
ESP_LOGD(TAG, "Sent command: %s (%d bytes)", command.c_str(), (int)sent);
return ESP_OK;
}
esp_err_t UDPClient::receive_response(std::string& response, int timeout_ms) {
if (!initialized_) {
ESP_LOGE(TAG, "Not initialized");
return ESP_FAIL;
}
// Setup select() for timeout
fd_set read_fds;
FD_ZERO(&read_fds);
FD_SET(sock_fd_, &read_fds);
struct timeval timeout;
struct timeval* timeout_ptr = nullptr;
if (timeout_ms >= 0) {
timeout.tv_sec = timeout_ms / 1000;
timeout.tv_usec = (timeout_ms % 1000) * 1000;
timeout_ptr = &timeout;
}
int ret = select(sock_fd_ + 1, &read_fds, nullptr, nullptr, timeout_ptr);
if (ret < 0) {
ESP_LOGE(TAG, "select() failed: errno %d", errno);
return ESP_FAIL;
}
if (ret == 0) {
ESP_LOGD(TAG, "Receive timeout (%d ms)", timeout_ms);
return ESP_ERR_TIMEOUT;
}
// Data is available
char buffer[512];
struct sockaddr_in from_addr;
socklen_t from_len = sizeof(from_addr);
ssize_t received = recvfrom(sock_fd_, buffer, sizeof(buffer) - 1, 0,
(struct sockaddr*)&from_addr, &from_len);
if (received < 0) {
ESP_LOGE(TAG, "recvfrom() failed: errno %d", errno);
return ESP_FAIL;
}
buffer[received] = '\0';
response = std::string(buffer, received);
ESP_LOGD(TAG, "Received response: %s (%d bytes)", response.c_str(), (int)received);
return ESP_OK;
}
void UDPClient::close() {
if (sock_fd_ >= 0) {
::close(sock_fd_);
ESP_LOGI(TAG, "Socket closed");
sock_fd_ = -1;
}
initialized_ = false;
configured_ = false;
remote_ip_.clear();
remote_port_ = 0;
}

View File

@@ -1,83 +0,0 @@
#pragma once
#include <string>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "esp_err.h"
/**
* @brief UDP client for sending commands and receiving responses
*
* Implements non-blocking UDP communication with configurable timeouts.
* Socket remains open for the lifetime of the instance.
*/
class UDPClient {
public:
UDPClient();
~UDPClient();
/**
* @brief Initialize UDP socket
* @return ESP_OK on success, error code otherwise
*/
esp_err_t init();
/**
* @brief Configure remote endpoint
* @param ip Remote IP address (e.g., "192.168.50.201")
* @param port Remote port number (e.g., 4211)
* @return ESP_OK on success, ESP_ERR_INVALID_ARG if IP is invalid
*/
esp_err_t configure(const std::string& ip, uint16_t port);
/**
* @brief Send command to remote endpoint
* @param command Command string to send (e.g., "TOGGLE", "STATUS", "MUTE", "UNMUTE")
* @return ESP_OK on success, ESP_FAIL if not configured or send failed
*/
esp_err_t send_command(const std::string& command);
/**
* @brief Receive response from remote endpoint (non-blocking)
* @param response Output string for received data
* @param timeout_ms Timeout in milliseconds (0 = no wait, -1 = wait forever)
* @return ESP_OK on success, ESP_ERR_TIMEOUT on timeout, ESP_FAIL on error
*/
esp_err_t receive_response(std::string& response, int timeout_ms = 1000);
/**
* @brief Check if client is configured with valid endpoint
* @return true if IP and port are configured
*/
bool is_configured() const { return configured_; }
/**
* @brief Get current remote IP
*/
std::string get_ip() const { return remote_ip_; }
/**
* @brief Get current remote port
*/
uint16_t get_port() const { return remote_port_; }
/**
* @brief Close socket and reset configuration
*/
void close();
private:
int sock_fd_; // Socket file descriptor
struct sockaddr_in remote_addr_; // Remote endpoint address
std::string remote_ip_; // Remote IP address
uint16_t remote_port_; // Remote port number
bool configured_; // Whether endpoint is configured
bool initialized_; // Whether socket is initialized
/**
* @brief Set socket to non-blocking mode
* @return ESP_OK on success
*/
esp_err_t set_nonblocking();
};

View File

@@ -1,44 +1,42 @@
#include "wifi_handler.h" #include "wifi_handler.h"
#include "esp_wifi.h" #include "esp_wifi.h"
#include "esp_event.h" #include "esp_event.h"
#include "esp_netif.h"
#include "freertos/event_groups.h" #include "freertos/event_groups.h"
#include "esp_log.h" #include "esp_log.h"
#include "freertos/semphr.h" #include "freertos/semphr.h"
#include "common/semaphore_guard.h" #include "common/semaphore_guard.h"
#include "cJSON.h"
static const char* TAG = "WifiHandler"; static const char* TAG = "WifiHandler";
static const char* WIFI_SSID_KEY = "ssid"; static const char* WIFI_SSID_KEY = "wifi_ssid";
static const char* WIFI_PASSWORD_STORE_KEY = "psw"; static const char* WIFI_PASSWORD_KEY = "wifi_password";
WifiHandler::WifiHandler( WifiHandler::WifiHandler(
// this handler is used to store/retrieve WiFi credentials // this handler is used to store/retrieve WiFi credentials
// should have a unique namespace for WiFi credentials // should have a unique namespace for WiFi credentials
// it will be owned by WifiHandler and deleted in its destructor // it will be owned by WifiHandler and deleted in its destructor
std::unique_ptr<KVStorageHandler> kvs KVStorageHandler* kvs
) : kvs(std::move(kvs)) { ) : kvs(kvs) {
this->s_wifi_event_group = xEventGroupCreate(); this->s_wifi_event_group = xEventGroupCreate();
if (!this->s_wifi_event_group) {
ESP_LOGE(TAG, "Failed to create WiFi event group");
}
this->scan_mutex = xSemaphoreCreateMutex(); this->scan_mutex = xSemaphoreCreateMutex();
if (!this->scan_mutex) {
ESP_LOGE(TAG, "Failed to create scan mutex");
}
this->connection_mutex = xSemaphoreCreateMutex(); this->connection_mutex = xSemaphoreCreateMutex();
if (!this->connection_mutex) { }
ESP_LOGE(TAG, "Failed to create connection mutex");
} // Move constructor: transfer ownership of resources
this->credential_mutex = xSemaphoreCreateMutex(); WifiHandler::WifiHandler(WifiHandler&& other) noexcept
if (!this->credential_mutex) { : initialized(other.initialized),
ESP_LOGE(TAG, "Failed to create credential mutex"); kvs(other.kvs),
} s_wifi_event_group(other.s_wifi_event_group),
if (this->kvs == nullptr) { scan_mutex(other.scan_mutex),
ESP_LOGW(TAG, "KVStorageHandler is null, WiFi credentials will not be stored"); connection_mutex(other.connection_mutex),
} else { current_ssid(other.current_ssid),
this->kvs->init(nullptr); expect_disconnected(other.expect_disconnected) {
} other.kvs = nullptr;
other.initialized = false;
other.s_wifi_event_group = 0;
other.scan_mutex = nullptr;
other.connection_mutex = nullptr;
other.current_ssid = nullptr;
other.expect_disconnected = false;
} }
WifiHandler::~WifiHandler() { WifiHandler::~WifiHandler() {
@@ -47,95 +45,29 @@ WifiHandler::~WifiHandler() {
// Check if it should be called // Check if it should be called
esp_wifi_deinit(); esp_wifi_deinit();
vEventGroupDelete(this->s_wifi_event_group); vEventGroupDelete(this->s_wifi_event_group);
if (!this->current_ssid.empty()) { if (this->current_ssid) {
this->current_ssid.clear(); delete[] this->current_ssid;
} }
vSemaphoreDelete(this->scan_mutex); vSemaphoreDelete(this->scan_mutex);
vSemaphoreDelete(this->connection_mutex); vSemaphoreDelete(this->connection_mutex);
esp_event_handler_unregister(WIFI_EVENT, ESP_EVENT_ANY_ID, &WifiHandler::wifi_event_handler);
esp_event_handler_unregister(IP_EVENT, IP_EVENT_STA_GOT_IP, &WifiHandler::wifi_event_handler);
this->initialized = false;
// unique_ptr will automatically delete the object
this->kvs = nullptr;
} }
} }
esp_err_t WifiHandler::init() { void WifiHandler::init() {
if (this->initialized) { if (this->initialized) {
ESP_LOGW(TAG, "Already initialized, skipping"); ESP_LOGW(TAG, "Already initialized, skipping");
return ESP_OK; return;
}
esp_err_t err;
// initialize TCP/IP stack and default event loop
err = esp_netif_init();
if (err != ESP_OK) {
ESP_LOGE(TAG, "esp_netif_init failed: %s", esp_err_to_name(err));
return err;
} }
err = esp_event_loop_create_default();
if (err != ESP_OK && err != ESP_ERR_INVALID_STATE) {
ESP_LOGE(TAG, "esp_event_loop_create_default failed: %s", esp_err_to_name(err));
return err;
}
// create default WiFi station
esp_netif_create_default_wifi_sta();
// init WiFi driver
wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
err = esp_wifi_init(&cfg);
if (err != ESP_OK) {
ESP_LOGE(TAG, "esp_wifi_init failed: %s", esp_err_to_name(err));
return err;
}
// register event handlers for WiFi and IP events
err = esp_event_handler_register(WIFI_EVENT, ESP_EVENT_ANY_ID, &WifiHandler::wifi_event_handler, this);
if (err != ESP_OK) {
ESP_LOGE(TAG, "esp_event_handler_register failed: %s", esp_err_to_name(err));
return err;
}
err = esp_event_handler_register(IP_EVENT, IP_EVENT_STA_GOT_IP, &WifiHandler::wifi_event_handler, this);
if (err != ESP_OK) {
ESP_LOGE(TAG, "esp_event_handler_register failed: %s", esp_err_to_name(err));
return err;
}
err = esp_wifi_set_mode(WIFI_MODE_STA);
if (err != ESP_OK) {
ESP_LOGE(TAG, "esp_wifi_set_mode failed: %s", esp_err_to_name(err));
return err;
}
err = esp_wifi_start();
if (err != ESP_OK) {
ESP_LOGE(TAG, "esp_wifi_start failed: %s", esp_err_to_name(err));
return err;
}
// get WiFi credentials from KV storage if available // get WiFi credentials from KV storage if available
std::string ssid; char* ssid = nullptr;
std::string password; char* password = nullptr;
this->get_wifi_credentials(ssid, password); this->get_wifi_credentials(ssid, password);
// If KV storage didn't provide credentials, allow build-time injected values if (ssid && password) {
// via compile-time defines BUILD_WIFI_SSID and BUILD_WIFI_PASSWORD. ESP_LOGI(TAG, "Found stored WiFi credentials, connecting to SSID: %s", ssid);
#if defined(BUILD_WIFI_SSID) and defined(BUILD_WIFI_PASSWORD) esp_err_t err = this->connect(ssid, password);
if (ssid.empty()) {
ssid = std::string(BUILD_WIFI_SSID);
ESP_LOGI(TAG, "Using build-time injected WiFi SSID");
}
if (password.empty()) {
password = std::string(BUILD_WIFI_PASSWORD);
ESP_LOGI(TAG, "Using build-time injected WiFi password");
}
#endif
if (!ssid.empty() && !password.empty()) {
ESP_LOGI(TAG, "Found stored WiFi credentials, connecting to SSID: %s", ssid.c_str());
err = this->connect(ssid, password);
if (err != ESP_OK) { if (err != ESP_OK) {
ESP_LOGE(TAG, "Failed to connect to stored WiFi credentials: %s", esp_err_to_name(err)); ESP_LOGE(TAG, "Failed to connect to stored WiFi credentials: %s", esp_err_to_name(err));
} }
@@ -143,11 +75,15 @@ esp_err_t WifiHandler::init() {
ESP_LOGI(TAG, "No stored WiFi credentials found, not connecting"); ESP_LOGI(TAG, "No stored WiFi credentials found, not connecting");
} }
delete[] ssid;
delete[] password;
// TODO: setup WiFi event handlers
// TODO: add auto-reconnect logic
//
initialized = true; initialized = true;
return ESP_OK;
} }
esp_err_t WifiHandler::connect(const std::string& ssid, const std::string& password) { esp_err_t WifiHandler::connect(const char* ssid, const char* password) {
SemaphoreGuard guard(this->connection_mutex); SemaphoreGuard guard(this->connection_mutex);
// wait up to 5 seconds to take the mutex // wait up to 5 seconds to take the mutex
if (!guard.take(5000 / portTICK_PERIOD_MS)) { if (!guard.take(5000 / portTICK_PERIOD_MS)) {
@@ -156,21 +92,24 @@ esp_err_t WifiHandler::connect(const std::string& ssid, const std::string& passw
} }
expect_disconnected = false; expect_disconnected = false;
if (!this->current_ssid.empty()) { if (this->current_ssid) {
this->current_ssid.clear(); delete[] this->current_ssid;
} }
this->current_ssid = ssid; size_t ssid_len = strlen(ssid);
this->current_ssid = new char[ssid_len + 1];
strncpy(this->current_ssid, ssid, ssid_len + 1);
this->current_ssid[ssid_len] = '\0';
// //
wifi_config_t wifi_config = {}; wifi_config_t wifi_config = {};
strncpy((char*)wifi_config.sta.ssid, this->current_ssid.c_str(), sizeof(wifi_config.sta.ssid)); strncpy((char*)wifi_config.sta.ssid, this->current_ssid, sizeof(wifi_config.sta.ssid));
wifi_config.sta.ssid[sizeof(wifi_config.sta.ssid) - 1] = '\0'; wifi_config.sta.ssid[sizeof(wifi_config.sta.ssid) - 1] = '\0';
strncpy((char*)wifi_config.sta.password, password.c_str(), sizeof(wifi_config.sta.password)); strncpy((char*)wifi_config.sta.password, password, sizeof(wifi_config.sta.password));
wifi_config.sta.password[sizeof(wifi_config.sta.password) - 1] = '\0'; wifi_config.sta.password[sizeof(wifi_config.sta.password) - 1] = '\0';
// set auth mode to WPA2_PSK minimum // set auth mode to WPA2_PSK minimum
wifi_config.sta.threshold.authmode = WIFI_AUTH_WPA2_PSK; wifi_config.sta.threshold.authmode = WIFI_AUTH_WPA2_PSK;
ESP_LOGI(TAG, "Connecting to SSID: %s", this->current_ssid.c_str()); ESP_LOGI(TAG, "Connecting to SSID: %s", this->current_ssid);
esp_err_t err = esp_wifi_set_config(wifi_interface_t::WIFI_IF_STA, &wifi_config); esp_err_t err = esp_wifi_set_config(wifi_interface_t::WIFI_IF_STA, &wifi_config);
if (err != ESP_OK) { if (err != ESP_OK) {
ESP_LOGE(TAG, "Failed to set WiFi config: %s", esp_err_to_name(err)); ESP_LOGE(TAG, "Failed to set WiFi config: %s", esp_err_to_name(err));
@@ -182,26 +121,40 @@ esp_err_t WifiHandler::connect(const std::string& ssid, const std::string& passw
return err; return err;
} }
// store credentials after successful connection attempt // store credentials
this->store_wifi_credentials(this->current_ssid, password); this->kvs->put(WIFI_SSID_KEY, this->current_ssid);
// store password under key derived from SSID
char* password_key = this->build_password_key(this->current_ssid);
this->kvs->put(password_key, password);
delete[] password_key;
// set connected bit on successful connection
xEventGroupSetBits(
this->s_wifi_event_group,
WIFI_CONNECTED_BIT
);
return ESP_OK; return ESP_OK;
} }
esp_err_t WifiHandler::connect(const std::string& ssid) { esp_err_t WifiHandler::connect(const char* ssid) {
std::string stored_ssid; char* stored_ssid = nullptr;
std::string stored_password; char* stored_password = nullptr;
this->get_wifi_credentials(stored_ssid, stored_password); this->get_wifi_credentials(stored_ssid, stored_password);
if (stored_ssid.empty() || stored_ssid != ssid) { if (!stored_ssid || strcmp(stored_ssid, ssid) != 0) {
ESP_LOGE(TAG, "No stored credentials for SSID: %s", ssid.c_str()); ESP_LOGE(TAG, "No stored credentials for SSID: %s", ssid);
delete[] stored_ssid;
delete[] stored_password;
return ESP_FAIL; return ESP_FAIL;
} }
esp_err_t err = this->connect(stored_ssid, stored_password); esp_err_t err = this->connect(stored_ssid, stored_password ? stored_password : "");
delete[] stored_ssid;
delete[] stored_password;
return err; return err;
} }
esp_err_t WifiHandler::reconnect() { esp_err_t WifiHandler::reconnect() {
if (this->current_ssid.empty()) { if (!this->current_ssid) {
ESP_LOGE(TAG, "No current SSID set, cannot reconnect"); ESP_LOGE(TAG, "No current SSID set, cannot reconnect");
return ESP_FAIL; return ESP_FAIL;
} }
@@ -276,15 +229,10 @@ void WifiHandler::wifi_event_handler(void* arg, esp_event_base_t event_base, int
case WIFI_EVENT_STA_START: case WIFI_EVENT_STA_START:
// When the station starts, attempt to connect // When the station starts, attempt to connect
ESP_LOGI(TAG, "WIFI_EVENT_STA_START"); ESP_LOGI(TAG, "WIFI_EVENT_STA_START");
if (!self->expect_disconnected && !self->current_ssid.empty()) { if (!self->expect_disconnected && self->current_ssid) {
ESP_LOGI(TAG, "Station started, attempting to connect to SSID: %s", self->current_ssid.c_str()); ESP_LOGI(TAG, "Station started, attempting to connect to SSID: %s", self->current_ssid);
self->reconnect(); self->reconnect();
} }
// set the event bit to indicate started
xEventGroupSetBits(
self->s_wifi_event_group,
WIFI_STARTED_BIT
);
break; break;
case WIFI_EVENT_STA_DISCONNECTED: case WIFI_EVENT_STA_DISCONNECTED:
ESP_LOGI(TAG, "WIFI_EVENT_STA_DISCONNECTED"); ESP_LOGI(TAG, "WIFI_EVENT_STA_DISCONNECTED");
@@ -317,106 +265,29 @@ void WifiHandler::wifi_event_handler(void* arg, esp_event_base_t event_base, int
// private methods // private methods
// //
void WifiHandler::store_wifi_credentials(const std::string& ssid, const std::string& password) { char* WifiHandler::build_password_key(const char* ssid) {
if (!kvs) { // `{WIFI_PASSWORD_KEY}_{ssid}`
ESP_LOGW(TAG, "KVStorageHandler not set, cannot store WiFi credentials"); size_t password_key_len = strlen(WIFI_PASSWORD_KEY) + 1 + strlen(ssid) + 1;
return; char* password_key_buff = new char[password_key_len];
} snprintf(password_key_buff, password_key_len, "%s_%s", WIFI_PASSWORD_KEY, ssid);
SemaphoreGuard guard(this->credential_mutex); return password_key_buff;
// wait up to 5 seconds to take the mutex
if (!guard.take(5000 / portTICK_PERIOD_MS)) {
ESP_LOGE(TAG, "Failed to take credential mutex");
return;
}
// store the password according to the JSON structure
std::string password_key_store = kvs->get(WIFI_PASSWORD_STORE_KEY);
cJSON* json = nullptr;
if (password_key_store.empty()) {
// create new JSON object
json = cJSON_CreateObject();
} else {
// parse existing JSON
json = cJSON_Parse(password_key_store.c_str());
if (json == nullptr) {
ESP_LOGE(TAG, "Failed to parse existing WiFi password JSON, creating new");
json = cJSON_CreateObject();
}
}
cJSON* credentials = cJSON_GetObjectItem(json, "credentials");
if (credentials == nullptr || !cJSON_IsObject(credentials)) {
// create credentials object if it doesn't exist
credentials = cJSON_CreateObject();
cJSON_AddItemToObject(json, "credentials", credentials);
}
// create SSID object
cJSON* ssid_item = cJSON_CreateObject();
// add password field
cJSON_AddStringToObject(ssid_item, "password", password.c_str());
// add SSID object to credentials
cJSON_AddItemToObject(credentials, ssid.c_str(), ssid_item);
// store updated JSON string
char* updated_json_str = cJSON_PrintUnformatted(json);
if (updated_json_str) {
kvs->put(WIFI_PASSWORD_STORE_KEY, std::string(updated_json_str));
cJSON_free(updated_json_str);
}
cJSON_Delete(json);
} }
void WifiHandler::get_wifi_credentials(std::string& out_ssid, std::string& out_password) { void WifiHandler::get_wifi_credentials(char*& ssid, char*& password) {
if (!kvs) { if (!kvs) {
ESP_LOGW(TAG, "KVStorageHandler not set, cannot get WiFi credentials"); ESP_LOGW(TAG, "KVStorageHandler not set, cannot get WiFi credentials");
return; return;
} }
SemaphoreGuard guard(this->credential_mutex); ssid = kvs->get(WIFI_SSID_KEY).get();
// wait up to 5 seconds to take the mutex if (!ssid) {
if (!guard.take(5000 / portTICK_PERIOD_MS)) { ssid = nullptr;
ESP_LOGE(TAG, "Failed to take credential mutex"); password = nullptr;
return;
}
out_ssid = kvs->get(WIFI_SSID_KEY);
if (out_ssid.empty()) {
out_ssid = "";
out_password = "";
return; return;
} }
// password is from KV storage, may be nullptr // password is from KV storage, may be nullptr
std::string password_key_store = kvs->get(WIFI_PASSWORD_STORE_KEY); char* password_key = this->build_password_key(ssid);
if (password_key_store.empty()) { password = kvs->get(password_key).get();
out_password = ""; delete[] password_key;
return;
}
// parse from json
cJSON* json = cJSON_Parse(password_key_store.c_str());
if (json == nullptr) {
ESP_LOGE(TAG, "Failed to parse WiFi password JSON");
out_password = "";
return;
}
cJSON* credentials = cJSON_GetObjectItem(json, "credentials");
if (credentials == nullptr || !cJSON_IsObject(credentials)) {
ESP_LOGE(TAG, "WiFi password JSON does not contain valid 'credentials' object");
out_password = "";
cJSON_Delete(json);
return;
}
// get the ssid value
cJSON* ssid_item = cJSON_GetObjectItem(credentials, out_ssid.c_str());
if (ssid_item == nullptr || !cJSON_IsObject(ssid_item)) {
ESP_LOGE(TAG, "WiFi password JSON does not contain valid SSID field for SSID: %s", out_ssid.c_str());
out_password = "";
cJSON_Delete(json);
return;
}
cJSON* password = cJSON_GetObjectItem(ssid_item, "password");
if (password == nullptr || !cJSON_IsString(password)) {
ESP_LOGE(TAG, "WiFi password JSON does not contain valid 'password' field for SSID: %s", out_ssid.c_str());
out_password = "";
cJSON_Delete(json);
return;
}
out_password = password->valuestring;
cJSON_Delete(json);
} }
EventBits_t WifiHandler::wait_for_connection(TickType_t ticks_to_wait) { EventBits_t WifiHandler::wait_for_connection(TickType_t ticks_to_wait) {

View File

@@ -3,9 +3,7 @@
#include "esp_wifi.h" #include "esp_wifi.h"
#include "freertos/event_groups.h" #include "freertos/event_groups.h"
#define WIFI_STARTED_BIT (1 << 0) #define WIFI_CONNECTED_BIT (1 << 0)
#define WIFI_CONNECTED_BIT (1 << 1)
class WifiHandler { class WifiHandler {
public: public:
@@ -13,13 +11,16 @@ public:
// this handler is used to store/retrieve WiFi credentials // this handler is used to store/retrieve WiFi credentials
// should have a unique namespace for WiFi credentials // should have a unique namespace for WiFi credentials
// it will be owned by WifiHandler and deleted in its destructor // it will be owned by WifiHandler and deleted in its destructor
std::unique_ptr<KVStorageHandler> kvs KVStorageHandler* kvs
); );
~WifiHandler(); ~WifiHandler();
esp_err_t init(); // move semantics
esp_err_t connect(const std::string& ssid, const std::string& password); WifiHandler(WifiHandler&& other) noexcept;
esp_err_t connect(const std::string& ssid); // connect using stored password
void init();
esp_err_t connect(const char* ssid, const char* password);
esp_err_t connect(const char* ssid); // connect using stored password
esp_err_t reconnect(); // reconnect to current SSID esp_err_t reconnect(); // reconnect to current SSID
void disconnect(); void disconnect();
EventBits_t wait_for_connection(TickType_t ticks_to_wait); EventBits_t wait_for_connection(TickType_t ticks_to_wait);
@@ -36,21 +37,17 @@ private:
// prevent copying // prevent copying
WifiHandler(const WifiHandler&) = delete; WifiHandler(const WifiHandler&) = delete;
WifiHandler& operator=(const WifiHandler&) = delete; WifiHandler& operator=(const WifiHandler&) = delete;
// prevent moving
WifiHandler(WifiHandler&& other) = delete;
WifiHandler& operator=(WifiHandler&& other) = delete;
void store_wifi_credentials(const std::string& ssid, const std::string& password); char* build_password_key(const char* ssid);
void get_wifi_credentials(std::string& out_ssid, std::string& out_password); void get_wifi_credentials(char*& ssid, char*& password);
bool initialized = false; bool initialized = false;
std::unique_ptr<KVStorageHandler> kvs = nullptr; KVStorageHandler* kvs = nullptr;
EventGroupHandle_t s_wifi_event_group = 0; EventGroupHandle_t s_wifi_event_group = 0;
SemaphoreHandle_t scan_mutex = nullptr; SemaphoreHandle_t scan_mutex = nullptr;
SemaphoreHandle_t connection_mutex = nullptr; SemaphoreHandle_t connection_mutex = nullptr;
SemaphoreHandle_t credential_mutex = nullptr;
// current connected / preferred SSID // current connected / preferred SSID
std::string current_ssid; char* current_ssid = nullptr;
// prevent auto-reconnect on expected disconnection, e.g. when user calls disconnect() // prevent auto-reconnect on expected disconnection, e.g. when user calls disconnect()
// should be reset to false after connect() // should be reset to false after connect()
bool expect_disconnected = false; bool expect_disconnected = false;

53
main/touch/touch.cpp Normal file
View File

@@ -0,0 +1,53 @@
#include "touch.h"
#include "common/constants.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/event_groups.h"
// TODO: implement actual touch functionality
TouchHandler::TouchHandler(QueueHandle_t touch_queue) {
(void)touch_queue;
}
TouchHandler::~TouchHandler() { }
EInkTouchHandler::EInkTouchHandler(QueueHandle_t touch_queue)
: TouchHandler(touch_queue) { }
EInkTouchHandler::~EInkTouchHandler() { }
void EInkTouchHandler::init(EventGroupHandle_t system_event_group) {
if (system_event_group != NULL) {
xEventGroupSetBits(system_event_group, TOUCH_CALIBRATED_BIT);
}
}
void EInkTouchHandler::start_event_loop() {
// Minimal background task to represent touch processing
xTaskCreate(
// use static adapter and pass `this` as task parameter
EInkTouchHandler::task_adapter,
"touch_task",
2048,
this,
tskIDLE_PRIORITY + 1,
nullptr
);
}
// static
void EInkTouchHandler::task_adapter(void* arg) {
EInkTouchHandler* self = static_cast<EInkTouchHandler*>(arg);
if (self) {
self->run_event_loop();
} else {
printf("EInkTouchHandler::task_adapter received null pointer\n");
}
vTaskDelete(NULL);
}
void EInkTouchHandler::run_event_loop() {
for (;;) {
vTaskDelay(pdMS_TO_TICKS(1000));
}
}

32
main/touch/touch.h Normal file
View File

@@ -0,0 +1,32 @@
#include "info/info.h"
class TouchHandler {
public:
TouchHandler(QueueHandle_t touch_queue);
// the system_event_group is used to set touch-calibrated bit
virtual void init(EventGroupHandle_t system_event_group) = 0;
virtual void start_event_loop() = 0;
virtual ~TouchHandler() = 0;
private:
TouchHandler(const TouchHandler&) = delete;
TouchHandler& operator=(const TouchHandler&) = delete;
};
class EInkTouchHandler : public TouchHandler {
public:
EInkTouchHandler(QueueHandle_t touch_queue);
void init(EventGroupHandle_t system_event_group) override;
void start_event_loop() override;
~EInkTouchHandler() override;
private:
// Task adapter used for FreeRTOS task creation. Forwards to
// `run_event_loop()` using the `this` pointer passed as the task param.
static void task_adapter(void* arg);
// Instance method implementing the touch event loop.
void run_event_loop();
// prevent copying
EInkTouchHandler(const EInkTouchHandler&) = delete;
EInkTouchHandler& operator=(const EInkTouchHandler&) = delete;
};

View File

@@ -1,39 +0,0 @@
#pragma once
#include "ui/ui_app.h"
#include <vector>
/**
* @brief Registry for all available apps
*
* This singleton class maintains a list of all registered
* AppDescriptor instances, allowing the UIHandler or other
* components to query available apps.
*/
class AppRegistry {
public:
static AppRegistry& instance() {
static AppRegistry registry;
return registry;
}
AppRegistry(const AppRegistry&) = delete;
void operator=(const AppRegistry&) = delete;
AppRegistry(AppRegistry&&) = delete;
void operator=(AppRegistry&&) = delete;
// Register a new app descriptor
// The registry takes ownership of the descriptor pointer.
void register_app(AppDescriptor* app_descriptor) {
_app_descriptors.push_back(app_descriptor);
}
const std::vector<AppDescriptor*>& get_app_descriptors() const {
return _app_descriptors;
}
private:
AppRegistry() = default;
~AppRegistry() = default;
std::vector<AppDescriptor*> _app_descriptors = {};
};

View File

@@ -1,652 +0,0 @@
#include "discord_app.h"
#include "esp_log.h"
#include "network/network.h"
#include <sstream>
static const char* TAG = "DiscordApp";
// ============================================================================
// DiscordApp Implementation
// ============================================================================
DiscordApp::DiscordApp()
: page_stack_(nullptr)
, status_icon_label_(nullptr)
, status_text_label_(nullptr)
, mute_button_(nullptr)
, error_notification_(nullptr)
, ip_textarea_(nullptr)
, port_textarea_(nullptr)
, test_result_label_(nullptr)
, remote_port_(0)
, settings_configured_(false)
, current_state_(VoiceState::UNKNOWN)
, state_mutex_(nullptr)
, poll_task_handle_(nullptr)
, stop_polling_(false)
, consecutive_failures_(0)
, storage_(nullptr) {
// Create mutex for thread-safe state access
state_mutex_ = xSemaphoreCreateMutex();
// Initialize storage
storage_ = new NVSStorageHandler(NVS_NAMESPACE);
}
DiscordApp::~DiscordApp() {
stop_polling_task();
if (state_mutex_) {
vSemaphoreDelete(state_mutex_);
}
if (storage_) {
delete storage_;
}
}
esp_err_t DiscordApp::init(lv_obj_t* container) {
ESP_LOGI(TAG, "Initializing Discord app");
_container = container;
// Initialize storage
storage_->init(nullptr);
// Load saved settings
load_settings();
// Initialize UDP client
udp_client_.init();
// Configure UDP if settings are available
if (settings_configured_) {
udp_client_.configure(remote_ip_, remote_port_);
}
// Create page stack
page_stack_ = new PageStack(container);
// Build main page
page_stack_->push([this](lv_obj_t* page) {
build_main_page(page);
});
// Start polling task
start_polling_task();
return ESP_OK;
}
esp_err_t DiscordApp::deinit() {
ESP_LOGI(TAG, "Deinitializing Discord app");
// Stop polling
stop_polling_task();
// Clean up page stack
if (page_stack_) {
delete page_stack_;
page_stack_ = nullptr;
}
// Close UDP client
udp_client_.close();
// Reset widget pointers
status_icon_label_ = nullptr;
status_text_label_ = nullptr;
mute_button_ = nullptr;
error_notification_ = nullptr;
ip_textarea_ = nullptr;
port_textarea_ = nullptr;
test_result_label_ = nullptr;
return ESP_OK;
}
void DiscordApp::handle_event(uint32_t event_type, void* event_data) {
// Handle system events if needed
}
bool DiscordApp::on_back_button_pressed() {
// If on settings page, go back to main page
if (page_stack_ && page_stack_->depth() > 1) {
page_stack_->pop();
return true;
}
// Let system handle back (return to app icons)
return false;
}
// ============================================================================
// Main Page UI
// ============================================================================
void DiscordApp::build_main_page(lv_obj_t* page) {
// Set up main page with flex column layout
lv_obj_set_flex_flow(page, LV_FLEX_FLOW_COLUMN);
lv_obj_set_flex_align(page, LV_FLEX_ALIGN_SPACE_BETWEEN, LV_FLEX_ALIGN_CENTER, LV_FLEX_ALIGN_CENTER);
lv_obj_set_style_pad_all(page, 10, 0);
// === Top Section: Error Notification ===
error_notification_ = lv_obj_create(page);
lv_obj_set_width(error_notification_, LV_PCT(90));
lv_obj_set_height(error_notification_, LV_SIZE_CONTENT);
lv_obj_set_style_bg_color(error_notification_, lv_color_hex(0xFF0000), 0);
lv_obj_set_style_bg_opa(error_notification_, LV_OPA_70, 0);
lv_obj_set_style_pad_all(error_notification_, 10, 0);
lv_obj_set_style_radius(error_notification_, 8, 0);
lv_obj_add_flag(error_notification_, LV_OBJ_FLAG_HIDDEN);
lv_obj_set_flex_flow(error_notification_, LV_FLEX_FLOW_ROW);
lv_obj_set_flex_align(error_notification_, LV_FLEX_ALIGN_CENTER, LV_FLEX_ALIGN_CENTER, LV_FLEX_ALIGN_CENTER);
lv_obj_t* error_label = lv_label_create(error_notification_);
lv_label_set_text(error_label, LV_SYMBOL_WARNING " Connection Lost");
lv_obj_set_style_text_color(error_label, lv_color_white(), 0);
// === Center Section: Main Content ===
lv_obj_t* center_container = lv_obj_create(page);
lv_obj_set_size(center_container, LV_PCT(100), LV_SIZE_CONTENT);
lv_obj_set_style_bg_opa(center_container, LV_OPA_TRANSP, 0);
lv_obj_set_style_border_width(center_container, 0, 0);
lv_obj_set_style_pad_all(center_container, 0, 0);
lv_obj_set_flex_flow(center_container, LV_FLEX_FLOW_COLUMN);
lv_obj_set_flex_align(center_container, LV_FLEX_ALIGN_CENTER, LV_FLEX_ALIGN_CENTER, LV_FLEX_ALIGN_CENTER);
lv_obj_set_style_pad_row(center_container, 15, 0);
lv_obj_set_flex_grow(center_container, 1);
// Status icon (large, centered)
status_icon_label_ = lv_label_create(center_container);
lv_label_set_text(status_icon_label_, LV_SYMBOL_MUTE);
// Status text
status_text_label_ = lv_label_create(center_container);
lv_label_set_text(status_text_label_, "Unknown Status");
// Mute button
mute_button_ = lv_btn_create(center_container);
lv_obj_set_size(mute_button_, 200, 60);
lv_obj_add_event_cb(mute_button_, on_mute_button_clicked, LV_EVENT_CLICKED, this);
lv_obj_t* mute_label = lv_label_create(mute_button_);
lv_label_set_text(mute_label, "MUTE");
lv_obj_center(mute_label);
// === Bottom Section: Settings and Config Prompt ===
lv_obj_t* bottom_container = lv_obj_create(page);
lv_obj_set_size(bottom_container, LV_PCT(100), LV_SIZE_CONTENT);
lv_obj_set_style_bg_opa(bottom_container, LV_OPA_TRANSP, 0);
lv_obj_set_style_border_width(bottom_container, 0, 0);
lv_obj_set_style_pad_all(bottom_container, 0, 0);
lv_obj_set_flex_flow(bottom_container, LV_FLEX_FLOW_ROW);
lv_obj_set_flex_align(bottom_container, LV_FLEX_ALIGN_SPACE_BETWEEN, LV_FLEX_ALIGN_CENTER, LV_FLEX_ALIGN_CENTER);
// Config prompt (left side)
if (!settings_configured_) {
lv_obj_t* config_prompt = lv_label_create(bottom_container);
lv_label_set_text(config_prompt, "Tap " LV_SYMBOL_SETTINGS " to configure");
lv_obj_set_style_text_color(config_prompt, lv_color_hex(0x888888), 0);
} else {
// Empty spacer if configured
lv_obj_t* spacer = lv_obj_create(bottom_container);
lv_obj_set_size(spacer, 0, 0);
lv_obj_set_style_bg_opa(spacer, LV_OPA_TRANSP, 0);
lv_obj_set_style_border_width(spacer, 0, 0);
}
// Settings button (right side)
lv_obj_t* settings_btn = lv_btn_create(bottom_container);
lv_obj_set_size(settings_btn, 60, 60);
lv_obj_add_event_cb(settings_btn, on_settings_button_clicked, LV_EVENT_CLICKED, this);
lv_obj_t* settings_icon = lv_label_create(settings_btn);
lv_label_set_text(settings_icon, LV_SYMBOL_SETTINGS);
lv_obj_center(settings_icon);
// Update display with current state
update_status_display();
}
// ============================================================================
// Settings Page UI
// ============================================================================
void DiscordApp::build_settings_page(lv_obj_t* page) {
// Title
lv_obj_t* title = lv_label_create(page);
lv_label_set_text(title, "Discord Bridge Settings");
// Using default font
lv_obj_align(title, LV_ALIGN_TOP_MID, 0, 20);
// IP address label
lv_obj_t* ip_label = lv_label_create(page);
lv_label_set_text(ip_label, "Bridge IP Address:");
lv_obj_align(ip_label, LV_ALIGN_TOP_LEFT, 20, 70);
// IP address textarea
ip_textarea_ = lv_textarea_create(page);
lv_obj_set_size(ip_textarea_, 300, 50);
lv_obj_align(ip_textarea_, LV_ALIGN_TOP_LEFT, 20, 100);
lv_textarea_set_one_line(ip_textarea_, true);
lv_textarea_set_placeholder_text(ip_textarea_, "e.g., 192.168.1.100");
if (!remote_ip_.empty()) {
lv_textarea_set_text(ip_textarea_, remote_ip_.c_str());
}
// Port label
lv_obj_t* port_label = lv_label_create(page);
lv_label_set_text(port_label, "Bridge Port:");
lv_obj_align(port_label, LV_ALIGN_TOP_LEFT, 20, 170);
// Port textarea
port_textarea_ = lv_textarea_create(page);
lv_obj_set_size(port_textarea_, 150, 50);
lv_obj_align(port_textarea_, LV_ALIGN_TOP_LEFT, 20, 200);
lv_textarea_set_one_line(port_textarea_, true);
lv_textarea_set_placeholder_text(port_textarea_, "e.g., 4211");
lv_textarea_set_accepted_chars(port_textarea_, "0123456789");
lv_textarea_set_max_length(port_textarea_, 5);
if (remote_port_ > 0) {
char port_str[8];
snprintf(port_str, sizeof(port_str), "%u", remote_port_);
lv_textarea_set_text(port_textarea_, port_str);
}
// Test connection button
lv_obj_t* test_btn = lv_btn_create(page);
lv_obj_set_size(test_btn, 200, 50);
lv_obj_align(test_btn, LV_ALIGN_TOP_MID, 0, 270);
lv_obj_add_event_cb(test_btn, on_test_connection_clicked, LV_EVENT_CLICKED, this);
lv_obj_t* test_label = lv_label_create(test_btn);
lv_label_set_text(test_label, "Test Connection");
lv_obj_center(test_label);
// Test result label
test_result_label_ = lv_label_create(page);
lv_label_set_text(test_result_label_, "");
lv_obj_align(test_result_label_, LV_ALIGN_TOP_MID, 0, 330);
// Save button
lv_obj_t* save_btn = lv_btn_create(page);
lv_obj_set_size(save_btn, 150, 50);
lv_obj_align(save_btn, LV_ALIGN_BOTTOM_MID, 0, -20);
lv_obj_add_event_cb(save_btn, on_save_settings_clicked, LV_EVENT_CLICKED, this);
lv_obj_set_style_bg_color(save_btn, lv_color_hex(0x00AA00), 0);
lv_obj_t* save_label = lv_label_create(save_btn);
lv_label_set_text(save_label, LV_SYMBOL_SAVE " Save");
lv_obj_set_style_text_color(save_label, lv_color_white(), 0);
lv_obj_center(save_label);
}
void DiscordApp::show_settings_page() {
page_stack_->push([this](lv_obj_t* page) {
build_settings_page(page);
});
}
// ============================================================================
// Event Callbacks
// ============================================================================
void DiscordApp::on_mute_button_clicked(lv_event_t* e) {
DiscordApp* app = static_cast<DiscordApp*>(lv_event_get_user_data(e));
if (app) {
app->send_mute_command();
}
}
void DiscordApp::on_settings_button_clicked(lv_event_t* e) {
DiscordApp* app = static_cast<DiscordApp*>(lv_event_get_user_data(e));
if (app) {
app->show_settings_page();
}
}
void DiscordApp::on_save_settings_clicked(lv_event_t* e) {
DiscordApp* app = static_cast<DiscordApp*>(lv_event_get_user_data(e));
if (app) {
app->save_settings();
// Go back to main page
if (app->page_stack_->depth() > 1) {
app->page_stack_->pop();
}
}
}
void DiscordApp::on_test_connection_clicked(lv_event_t* e) {
DiscordApp* app = static_cast<DiscordApp*>(lv_event_get_user_data(e));
if (!app || !app->test_result_label_) return;
// Get values from textareas
const char* ip = lv_textarea_get_text(app->ip_textarea_);
const char* port_str = lv_textarea_get_text(app->port_textarea_);
if (strlen(ip) == 0 || strlen(port_str) == 0) {
lv_label_set_text(app->test_result_label_, LV_SYMBOL_CLOSE " Please fill all fields");
lv_obj_set_style_text_color(app->test_result_label_, lv_color_hex(0xFF0000), 0);
return;
}
uint16_t port = atoi(port_str);
if (port == 0) {
lv_label_set_text(app->test_result_label_, LV_SYMBOL_CLOSE " Invalid port");
lv_obj_set_style_text_color(app->test_result_label_, lv_color_hex(0xFF0000), 0);
return;
}
// Configure UDP temporarily
UDPClient test_client;
test_client.init();
esp_err_t err = test_client.configure(ip, port);
if (err != ESP_OK) {
lv_label_set_text(app->test_result_label_, LV_SYMBOL_CLOSE " Invalid IP address");
lv_obj_set_style_text_color(app->test_result_label_, lv_color_hex(0xFF0000), 0);
return;
}
lv_label_set_text(app->test_result_label_, "Testing...");
lv_obj_set_style_text_color(app->test_result_label_, lv_color_hex(0x0000FF), 0);
// Send STATUS command
err = test_client.send_command("STATUS");
if (err != ESP_OK) {
lv_label_set_text(app->test_result_label_, LV_SYMBOL_CLOSE " Failed to send");
lv_obj_set_style_text_color(app->test_result_label_, lv_color_hex(0xFF0000), 0);
return;
}
// Wait for response
std::string response;
err = test_client.receive_response(response, 3000);
if (err == ESP_OK && (response == "MUTED" || response == "UNMUTED")) {
lv_label_set_text(app->test_result_label_, LV_SYMBOL_OK " Connection successful!");
lv_obj_set_style_text_color(app->test_result_label_, lv_color_hex(0x00AA00), 0);
} else {
lv_label_set_text(app->test_result_label_, LV_SYMBOL_CLOSE " No response from bridge");
lv_obj_set_style_text_color(app->test_result_label_, lv_color_hex(0xFF0000), 0);
}
}
// ============================================================================
// UDP Communication
// ============================================================================
void DiscordApp::send_mute_command() {
if (!settings_configured_) {
ESP_LOGW(TAG, "Cannot send command: not configured");
return;
}
esp_err_t err = udp_client_.send_command("MUTE");
if (err != ESP_OK) {
ESP_LOGE(TAG, "Failed to send MUTE command");
}
}
bool DiscordApp::test_connection() {
if (!settings_configured_) {
return false;
}
esp_err_t err = udp_client_.send_command("STATUS");
if (err != ESP_OK) {
return false;
}
std::string response;
err = udp_client_.receive_response(response, RESPONSE_TIMEOUT_MS);
return (err == ESP_OK && (response == "MUTED" || response == "UNMUTED"));
}
void DiscordApp::update_status_display() {
if (!status_icon_label_ || !status_text_label_) {
return;
}
// Thread-safe state access
VoiceState state;
if (xSemaphoreTake(state_mutex_, pdMS_TO_TICKS(100)) == pdTRUE) {
state = current_state_;
xSemaphoreGive(state_mutex_);
} else {
return;
}
switch (state) {
case VoiceState::MUTED:
lv_label_set_text(status_icon_label_, LV_SYMBOL_MUTE);
lv_label_set_text(status_text_label_, "Muted");
lv_obj_set_style_text_color(status_icon_label_, lv_color_hex(0xFF0000), 0);
break;
case VoiceState::UNMUTED:
lv_label_set_text(status_icon_label_, LV_SYMBOL_VOLUME_MAX);
lv_label_set_text(status_text_label_, "Unmuted");
lv_obj_set_style_text_color(status_icon_label_, lv_color_hex(0x00AA00), 0);
break;
case VoiceState::ERROR:
lv_label_set_text(status_icon_label_, LV_SYMBOL_WARNING);
lv_label_set_text(status_text_label_, "Connection Error");
lv_obj_set_style_text_color(status_icon_label_, lv_color_hex(0xFF8800), 0);
break;
case VoiceState::UNKNOWN:
default:
lv_label_set_text(status_icon_label_, LV_SYMBOL_BLUETOOTH);
lv_label_set_text(status_text_label_, "Unknown Status");
lv_obj_set_style_text_color(status_icon_label_, lv_color_hex(0x888888), 0);
break;
}
}
void DiscordApp::show_error_notification(bool show) {
if (error_notification_) {
if (show) {
lv_obj_clear_flag(error_notification_, LV_OBJ_FLAG_HIDDEN);
} else {
lv_obj_add_flag(error_notification_, LV_OBJ_FLAG_HIDDEN);
}
}
}
// ============================================================================
// Settings Management
// ============================================================================
void DiscordApp::load_settings() {
remote_ip_ = storage_->get(NVS_KEY_IP);
std::string port_str = storage_->get(NVS_KEY_PORT);
if (!remote_ip_.empty() && !port_str.empty()) {
remote_port_ = atoi(port_str.c_str());
settings_configured_ = (remote_port_ > 0);
ESP_LOGI(TAG, "Loaded settings: %s:%u", remote_ip_.c_str(), remote_port_);
} else {
settings_configured_ = false;
ESP_LOGI(TAG, "No settings found, user setup required");
}
}
void DiscordApp::save_settings() {
if (!ip_textarea_ || !port_textarea_) {
return;
}
const char* ip = lv_textarea_get_text(ip_textarea_);
const char* port_str = lv_textarea_get_text(port_textarea_);
if (strlen(ip) == 0 || strlen(port_str) == 0) {
ESP_LOGW(TAG, "Cannot save: empty fields");
return;
}
uint16_t port = atoi(port_str);
if (port == 0) {
ESP_LOGW(TAG, "Cannot save: invalid port");
return;
}
// Save to NVS
storage_->put(NVS_KEY_IP, ip);
storage_->put(NVS_KEY_PORT, port_str);
// Update local config
remote_ip_ = ip;
remote_port_ = port;
settings_configured_ = true;
// Reconfigure UDP client
udp_client_.configure(remote_ip_, remote_port_);
// Reset failure counter
consecutive_failures_ = 0;
ESP_LOGI(TAG, "Settings saved: %s:%u", remote_ip_.c_str(), remote_port_);
}
// ============================================================================
// Polling Task
// ============================================================================
void DiscordApp::poll_task(void* param) {
DiscordApp* app = static_cast<DiscordApp*>(param);
ESP_LOGI(TAG, "Polling task started");
while (!app->stop_polling_) {
app->poll_status();
// Use longer interval if in error state
int interval = (app->consecutive_failures_ >= MAX_FAILURES_BEFORE_ERROR)
? ERROR_POLL_INTERVAL_MS
: POLL_INTERVAL_MS;
vTaskDelay(pdMS_TO_TICKS(interval));
}
ESP_LOGI(TAG, "Polling task stopped");
app->poll_task_handle_ = nullptr;
vTaskDelete(nullptr);
}
void DiscordApp::start_polling_task() {
if (poll_task_handle_) {
ESP_LOGW(TAG, "Polling task already running");
return;
}
stop_polling_ = false;
xTaskCreate(poll_task, "discord_poll", 4096, this, 5, &poll_task_handle_);
}
void DiscordApp::stop_polling_task() {
if (!poll_task_handle_) {
return;
}
ESP_LOGI(TAG, "Stopping polling task");
stop_polling_ = true;
// Wait for task to finish (max 2 seconds)
int wait_count = 0;
while (poll_task_handle_ && wait_count < 20) {
vTaskDelay(pdMS_TO_TICKS(100));
wait_count++;
}
if (poll_task_handle_) {
ESP_LOGW(TAG, "Force deleting polling task");
vTaskDelete(poll_task_handle_);
poll_task_handle_ = nullptr;
}
}
void DiscordApp::poll_status() {
if (!settings_configured_) {
// Don't poll if not configured
return;
}
// Send STATUS command
esp_err_t err = udp_client_.send_command("STATUS");
if (err != ESP_OK) {
ESP_LOGW(TAG, "Failed to send STATUS command");
consecutive_failures_++;
if (consecutive_failures_ >= MAX_FAILURES_BEFORE_ERROR) {
if (xSemaphoreTake(state_mutex_, pdMS_TO_TICKS(100)) == pdTRUE) {
current_state_ = VoiceState::ERROR;
xSemaphoreGive(state_mutex_);
}
show_error_notification(true);
}
return;
}
// Wait for response
std::string response;
err = udp_client_.receive_response(response, RESPONSE_TIMEOUT_MS);
if (err == ESP_OK) {
// Success - reset failure counter
consecutive_failures_ = 0;
show_error_notification(false);
// Update state
VoiceState new_state = VoiceState::UNKNOWN;
if (response == "MUTED") {
new_state = VoiceState::MUTED;
} else if (response == "UNMUTED") {
new_state = VoiceState::UNMUTED;
}
if (xSemaphoreTake(state_mutex_, pdMS_TO_TICKS(100)) == pdTRUE) {
current_state_ = new_state;
xSemaphoreGive(state_mutex_);
}
update_status_display();
} else {
// Timeout or error
consecutive_failures_++;
ESP_LOGW(TAG, "No response (failures: %d)", consecutive_failures_);
if (consecutive_failures_ >= MAX_FAILURES_BEFORE_ERROR) {
if (xSemaphoreTake(state_mutex_, pdMS_TO_TICKS(100)) == pdTRUE) {
current_state_ = VoiceState::ERROR;
xSemaphoreGive(state_mutex_);
}
update_status_display();
show_error_notification(true);
}
}
}
// ============================================================================
// DiscordAppDescriptor Implementation
// ============================================================================
DiscordAppDescriptor::DiscordAppDescriptor()
: AppDescriptor("Discord", new DiscordApp()) {
// Auto-register on construction
AppRegistry::instance().register_app(this);
}
void DiscordAppDescriptor::draw_icon(lv_obj_t* parent) {
lv_obj_t* icon = lv_label_create(parent);
lv_label_set_text(icon, LV_SYMBOL_CALL);
lv_obj_center(icon);
}

View File

@@ -1,123 +0,0 @@
#pragma once
#include "ui/ui_app.h"
#include "ui/page_stack.h"
#include "ui/app_registry.h"
#include "network/udp_client.h"
#include "io/nvs_handler.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/semphr.h"
#include <string>
/**
* @brief Discord voice control app
*
* Allows control of Discord voice settings (mute/unmute) via UDP communication
* with the IotDis Node.js bridge. Features:
* - Main page: Status icon + mute button
* - Settings page: IP/port configuration with connection test
* - Periodic status polling with automatic retry
* - Error notification when remote is unreachable
*/
class DiscordApp : public UIApp {
public:
DiscordApp();
~DiscordApp() override;
// UIApp interface
esp_err_t init(lv_obj_t* container) override;
esp_err_t deinit() override;
std::string get_name() const override { return "Discord"; }
void handle_event(uint32_t event_type, void* event_data = nullptr) override;
bool on_back_button_pressed() override;
private:
// Voice state enum
enum class VoiceState {
UNKNOWN,
MUTED,
UNMUTED,
ERROR
};
// Page management
PageStack* page_stack_;
void build_main_page(lv_obj_t* page);
void build_settings_page(lv_obj_t* page);
void show_settings_page();
// Main page widgets
lv_obj_t* status_icon_label_;
lv_obj_t* status_text_label_;
lv_obj_t* mute_button_;
lv_obj_t* error_notification_;
// Settings page widgets
lv_obj_t* ip_textarea_;
lv_obj_t* port_textarea_;
lv_obj_t* test_result_label_;
// UDP client and configuration
UDPClient udp_client_;
std::string remote_ip_;
uint16_t remote_port_;
bool settings_configured_;
// Voice state
VoiceState current_state_;
SemaphoreHandle_t state_mutex_;
// Polling task
TaskHandle_t poll_task_handle_;
bool stop_polling_;
int consecutive_failures_;
static constexpr int MAX_FAILURES_BEFORE_ERROR = 3;
static constexpr int POLL_INTERVAL_MS = 5000;
static constexpr int ERROR_POLL_INTERVAL_MS = 15000;
static constexpr int RESPONSE_TIMEOUT_MS = 2000;
// NVS storage
NVSStorageHandler* storage_;
static constexpr const char* NVS_NAMESPACE = "discord";
static constexpr const char* NVS_KEY_IP = "remote_ip";
static constexpr const char* NVS_KEY_PORT = "remote_port";
// Event callbacks
static void on_mute_button_clicked(lv_event_t* e);
static void on_settings_button_clicked(lv_event_t* e);
static void on_save_settings_clicked(lv_event_t* e);
static void on_test_connection_clicked(lv_event_t* e);
// UDP communication
void send_mute_command();
bool test_connection();
void update_status_display();
void show_error_notification(bool show);
// Settings management
void load_settings();
void save_settings();
// Polling task
static void poll_task(void* param);
void start_polling_task();
void stop_polling_task();
void poll_status();
};
/**
* @brief Discord app descriptor for registration
*/
class DiscordAppDescriptor : public AppDescriptor {
public:
static DiscordAppDescriptor& instance() {
static DiscordAppDescriptor instance;
return instance;
}
void draw_icon(lv_obj_t* parent) override;
private:
DiscordAppDescriptor();
};

View File

@@ -1,399 +0,0 @@
#include "apps/mtr_app.h"
#include "external/mtr/arrival.h"
#include "esp_log.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#define TAG "MtrApp"
// Event type for network ready
#define EVENT_NETWORK_READY 1
MtrApp::MtrApp() {
_mtr_handler = std::make_unique<MTRNextTrainHandler>();
}
esp_err_t MtrApp::init(lv_obj_t* container) {
if (!container) {
ESP_LOGE(TAG, "Container is null");
return ESP_ERR_INVALID_ARG;
}
_container = container;
ESP_LOGI(TAG, "Initializing MTR app...");
// Create page stack
_page_stack = std::make_unique<PageStack>(container);
// Load all lines
_all_lines = _mtr_handler->get_lines();
ESP_LOGI(TAG, "Loaded %zu MTR lines", _all_lines.size());
// Build initial line selection page
_page_stack->push([this](lv_obj_t* page) {
this->build_line_selection_page(page);
});
ESP_LOGI(TAG, "MTR app initialized successfully");
return ESP_OK;
}
esp_err_t MtrApp::deinit(void) {
ESP_LOGI(TAG, "Deinitializing MTR app");
// Clear page stack
if (_page_stack) {
_page_stack->clear();
_page_stack.reset();
}
// Clear state
_selected_line_code.clear();
_selected_station_code.clear();
_selected_line_info = nullptr;
_all_lines.clear();
return ESP_OK;
}
std::string MtrApp::get_name(void) const {
return "MTR";
}
bool MtrApp::on_back_button_pressed(void) {
if (_page_stack && _page_stack->depth() > 1) {
_page_stack->pop();
return true; // Handled
}
return false; // Not handled, go back to main menu
}
void MtrApp::handle_event(uint32_t event_type, void* event_data) {
if (event_type == EVENT_NETWORK_READY) {
ESP_LOGI(TAG, "Network ready event received");
}
}
void MtrApp::build_line_selection_page(lv_obj_t* page_container) {
ESP_LOGI(TAG, "Building line selection page");
// Title
lv_obj_t* title = lv_label_create(page_container);
lv_label_set_text(title, "選擇路綫 Select Line");
lv_obj_set_style_text_color(title, lv_color_black(), 0);
lv_obj_align(title, LV_ALIGN_TOP_MID, 0, 10);
// Scrollable container for line buttons
lv_obj_t* scroll_container = lv_obj_create(page_container);
lv_obj_set_size(scroll_container, lv_pct(95), lv_pct(85));
lv_obj_align(scroll_container, LV_ALIGN_TOP_MID, 0, 40);
lv_obj_set_flex_flow(scroll_container, LV_FLEX_FLOW_COLUMN);
lv_obj_set_flex_align(scroll_container, LV_FLEX_ALIGN_START, LV_FLEX_ALIGN_CENTER, LV_FLEX_ALIGN_CENTER);
lv_obj_set_style_pad_all(scroll_container, 5, 0);
lv_obj_set_style_pad_row(scroll_container, 8, 0);
// Create button for each line
for (size_t i = 0; i < _all_lines.size(); i++) {
LineInfo* line = &_all_lines[i];
lv_obj_t* btn = lv_btn_create(scroll_container);
lv_obj_set_size(btn, lv_pct(95), 60);
// Set button color based on line color
uint32_t color = parse_color_hex(line->color());
lv_obj_set_style_bg_color(btn, lv_color_hex(color), 0);
// Button label
lv_obj_t* label = lv_label_create(btn);
lv_label_set_text_fmt(label, "%s", line->code());
lv_obj_set_style_text_color(label, lv_color_white(), 0);
lv_obj_center(label);
// Store line pointer in user data
lv_obj_add_event_cb(btn, line_button_event_cb, LV_EVENT_CLICKED, this);
lv_obj_set_user_data(btn, (void*)line);
}
ESP_LOGI(TAG, "Created %zu line buttons", _all_lines.size());
}
void MtrApp::build_station_selection_page(lv_obj_t* page_container) {
ESP_LOGI(TAG, "Building station selection page for line: %s", _selected_line_code.c_str());
if (!_selected_line_info) {
ESP_LOGE(TAG, "No line info selected");
return;
}
// Title with line code
lv_obj_t* title = lv_label_create(page_container);
lv_label_set_text_fmt(title, "%s 路綫車站", _selected_line_code.c_str());
lv_obj_set_style_text_color(title, lv_color_black(), 0);
lv_obj_align(title, LV_ALIGN_TOP_MID, 0, 10);
// Scrollable container for station buttons
lv_obj_t* scroll_container = lv_obj_create(page_container);
lv_obj_set_size(scroll_container, lv_pct(95), lv_pct(85));
lv_obj_align(scroll_container, LV_ALIGN_TOP_MID, 0, 40);
lv_obj_set_flex_flow(scroll_container, LV_FLEX_FLOW_COLUMN);
lv_obj_set_flex_align(scroll_container, LV_FLEX_ALIGN_START, LV_FLEX_ALIGN_CENTER, LV_FLEX_ALIGN_CENTER);
lv_obj_set_style_pad_all(scroll_container, 5, 0);
lv_obj_set_style_pad_row(scroll_container, 6, 0);
// Create button for each station
const std::vector<StationInfo>* stations = _selected_line_info->stations();
for (size_t i = 0; i < stations->size(); i++) {
const StationInfo* station = &(*stations)[i];
lv_obj_t* btn = lv_btn_create(scroll_container);
lv_obj_set_size(btn, lv_pct(95), 50);
lv_obj_set_style_bg_color(btn, lv_color_hex(0x4CAF50), 0);
// Button label with station name and code
lv_obj_t* label = lv_label_create(btn);
lv_label_set_text_fmt(label, "%s (%s)", station->name(), station->code());
lv_obj_set_style_text_color(label, lv_color_white(), 0);
lv_obj_center(label);
// Store station pointer in user data
lv_obj_add_event_cb(btn, station_button_event_cb, LV_EVENT_CLICKED, this);
lv_obj_set_user_data(btn, (void*)station);
}
ESP_LOGI(TAG, "Created %zu station buttons", stations->size());
}
void MtrApp::build_arrival_page(lv_obj_t* page_container) {
ESP_LOGI(TAG, "Building arrival page");
// Title
lv_obj_t* title = lv_label_create(page_container);
lv_label_set_text_fmt(title, "%s - %s", _selected_line_code.c_str(), _selected_station_code.c_str());
lv_obj_set_style_text_color(title, lv_color_black(), 0);
lv_obj_align(title, LV_ALIGN_TOP_MID, 0, 10);
// Loading message
lv_obj_t* loading_label = lv_label_create(page_container);
lv_label_set_text(loading_label, "載入中... Loading...");
lv_obj_set_style_text_color(loading_label, lv_color_black(), 0);
lv_obj_center(loading_label);
// Refresh button
lv_obj_t* refresh_btn = lv_btn_create(page_container);
lv_obj_set_size(refresh_btn, 120, 50);
lv_obj_align(refresh_btn, LV_ALIGN_BOTTOM_MID, 0, -10);
lv_obj_add_event_cb(refresh_btn, refresh_button_event_cb, LV_EVENT_CLICKED, this);
lv_obj_t* refresh_label = lv_label_create(refresh_btn);
lv_label_set_text(refresh_label, LV_SYMBOL_REFRESH " 重新整理");
lv_obj_set_style_text_color(refresh_label, lv_color_white(), 0);
lv_obj_center(refresh_label);
// Load arrival data asynchronously
load_arrival_data(page_container);
}
void MtrApp::load_arrival_data(lv_obj_t* page_container) {
if (!_network_handler) {
ESP_LOGW(TAG, "Network handler not set, cannot fetch arrival data");
// Update UI to show error
lv_obj_t* error_label = lv_label_create(page_container);
lv_label_set_text(error_label, "網絡未就緒\nNetwork not ready");
lv_obj_set_style_text_color(error_label, lv_color_black(), 0);
lv_obj_align(error_label, LV_ALIGN_CENTER, 0, -30);
return;
}
ESP_LOGI(TAG, "Fetching arrival data for %s/%s", _selected_line_code.c_str(), _selected_station_code.c_str());
StationArrivalInfo* arrival_info = nullptr;
MtrArrivalErrorCode error_code = _mtr_handler->get_next_arrival_info(
_network_handler,
_selected_line_code,
_selected_station_code,
arrival_info,
Language::TC
);
// Clear loading message
lv_obj_clean(page_container);
// Recreate title
lv_obj_t* title = lv_label_create(page_container);
lv_label_set_text_fmt(title, "%s - %s", _selected_line_code.c_str(), _selected_station_code.c_str());
lv_obj_set_style_text_color(title, lv_color_black(), 0);
lv_obj_align(title, LV_ALIGN_TOP_MID, 0, 10);
if (error_code != MtrArrivalErrorCode::NONE || !arrival_info) {
ESP_LOGE(TAG, "Failed to fetch arrival info, error code: %d", (int)error_code);
lv_obj_t* error_label = lv_label_create(page_container);
lv_label_set_text(error_label, "無法取得班次資料\nFailed to fetch arrival data");
lv_obj_set_style_text_color(error_label, lv_color_black(), 0);
lv_obj_center(error_label);
return;
}
// Create scrollable container for arrivals
lv_obj_t* scroll_container = lv_obj_create(page_container);
lv_obj_set_size(scroll_container, lv_pct(95), lv_pct(75));
lv_obj_align(scroll_container, LV_ALIGN_TOP_MID, 0, 45);
lv_obj_set_style_pad_all(scroll_container, 10, 0);
int y_offset = 0;
// Display UP direction trains
lv_obj_t* up_header = lv_label_create(scroll_container);
lv_label_set_text(up_header, "上行 UP:");
lv_obj_set_style_text_color(up_header, lv_color_black(), 0);
lv_obj_set_pos(up_header, 0, y_offset);
y_offset += 30;
const std::vector<ArrivalInfo>* up_arrivals = arrival_info->up_arrivals();
if (up_arrivals->empty()) {
lv_obj_t* no_train = lv_label_create(scroll_container);
lv_label_set_text(no_train, " 暫無班次 No trains");
lv_obj_set_style_text_color(no_train, lv_color_hex(0x666666), 0);
lv_obj_set_pos(no_train, 10, y_offset);
y_offset += 25;
} else {
for (const auto& arrival : *up_arrivals) {
lv_obj_t* arrival_label = lv_label_create(scroll_container);
lv_label_set_text_fmt(arrival_label, " %s → %s", arrival.arrival_time(), arrival.destination());
lv_obj_set_style_text_color(arrival_label, lv_color_black(), 0);
lv_obj_set_pos(arrival_label, 10, y_offset);
y_offset += 25;
}
}
y_offset += 10;
// Display DOWN direction trains
lv_obj_t* down_header = lv_label_create(scroll_container);
lv_label_set_text(down_header, "下行 DOWN:");
lv_obj_set_style_text_color(down_header, lv_color_black(), 0);
lv_obj_set_pos(down_header, 0, y_offset);
y_offset += 30;
const std::vector<ArrivalInfo>* down_arrivals = arrival_info->down_arrivals();
if (down_arrivals->empty()) {
lv_obj_t* no_train = lv_label_create(scroll_container);
lv_label_set_text(no_train, " 暫無班次 No trains");
lv_obj_set_style_text_color(no_train, lv_color_hex(0x666666), 0);
lv_obj_set_pos(no_train, 10, y_offset);
y_offset += 25;
} else {
for (const auto& arrival : *down_arrivals) {
lv_obj_t* arrival_label = lv_label_create(scroll_container);
lv_label_set_text_fmt(arrival_label, " %s → %s", arrival.arrival_time(), arrival.destination());
lv_obj_set_style_text_color(arrival_label, lv_color_black(), 0);
lv_obj_set_pos(arrival_label, 10, y_offset);
y_offset += 25;
}
}
// Clean up
if (arrival_info != nullptr) {
delete arrival_info;
}
// Refresh button
lv_obj_t* refresh_btn = lv_btn_create(page_container);
lv_obj_set_size(refresh_btn, 120, 50);
lv_obj_align(refresh_btn, LV_ALIGN_BOTTOM_MID, 0, -10);
lv_obj_add_event_cb(refresh_btn, refresh_button_event_cb, LV_EVENT_CLICKED, this);
lv_obj_t* refresh_label = lv_label_create(refresh_btn);
lv_label_set_text(refresh_label, LV_SYMBOL_REFRESH " 重新整理");
lv_obj_set_style_text_color(refresh_label, lv_color_white(), 0);
lv_obj_center(refresh_label);
ESP_LOGI(TAG, "Arrival data displayed successfully");
}
uint32_t MtrApp::parse_color_hex(const char* hex_str) {
if (!hex_str || hex_str[0] != '#') {
return 0x808080; // Default gray
}
// Skip the '#' character
hex_str++;
uint32_t color = 0;
sscanf(hex_str, "%" SCNx32, &color);
return color;
}
void MtrApp::line_button_event_cb(lv_event_t* e) {
lv_event_code_t code = lv_event_get_code(e);
if (code == LV_EVENT_CLICKED) {
MtrApp* app = (MtrApp*)lv_event_get_user_data(e);
lv_obj_t* btn = (lv_obj_t*)lv_event_get_target(e);
LineInfo* line = (LineInfo*)lv_obj_get_user_data(btn);
if (app && line) {
ESP_LOGI(TAG, "Line selected: %s", line->code());
app->_selected_line_code = line->code();
app->_selected_line_info = line;
// Push station selection page
app->_page_stack->push([app](lv_obj_t* page) {
app->build_station_selection_page(page);
});
}
}
}
void MtrApp::station_button_event_cb(lv_event_t* e) {
lv_event_code_t code = lv_event_get_code(e);
if (code == LV_EVENT_CLICKED) {
MtrApp* app = (MtrApp*)lv_event_get_user_data(e);
lv_obj_t* btn = (lv_obj_t*)lv_event_get_target(e);
const StationInfo* station = (const StationInfo*)lv_obj_get_user_data(btn);
if (app && station) {
ESP_LOGI(TAG, "Station selected: %s (%s)", station->name(), station->code());
app->_selected_station_code = station->code();
// Push arrival page
app->_page_stack->push([app](lv_obj_t* page) {
app->build_arrival_page(page);
});
}
}
}
void MtrApp::refresh_button_event_cb(lv_event_t* e) {
lv_event_code_t code = lv_event_get_code(e);
if (code == LV_EVENT_CLICKED) {
MtrApp* app = (MtrApp*)lv_event_get_user_data(e);
if (app && app->_page_stack && app->_page_stack->current_page()) {
ESP_LOGI(TAG, "Refresh button clicked");
app->load_arrival_data(app->_page_stack->current_page());
}
}
}
// MtrAppDescriptor implementation
MtrApp* MtrAppDescriptor::_app_instance = nullptr;
MtrAppDescriptor::MtrAppDescriptor()
: AppDescriptor("MTR", []() -> UIApp* {
if (!MtrAppDescriptor::_app_instance) {
MtrAppDescriptor::_app_instance = new MtrApp();
}
return MtrAppDescriptor::_app_instance;
}()) {
// Register with AppRegistry
AppRegistry::instance().register_app(this);
ESP_LOGI(TAG, "MtrApp registered with AppRegistry");
}
void MtrAppDescriptor::draw_icon(lv_obj_t* parent) {
// Create MTR icon with train symbol
lv_obj_t* icon_label = lv_label_create(parent);
lv_label_set_text(icon_label, LV_SYMBOL_GPS "\nMTR");
lv_obj_set_style_text_color(icon_label, lv_color_white(), 0);
lv_obj_set_style_text_align(icon_label, LV_TEXT_ALIGN_CENTER, 0);
lv_obj_center(icon_label);
}

View File

@@ -1,71 +0,0 @@
#pragma once
#include "ui/ui_app.h"
#include "ui/app_registry.h"
#include "ui/page_stack.h"
#include "external/mtr/mtr.h"
#include "external/mtr/line_info.h"
#include "external/mtr/station_info.h"
#include "network/network.h"
#include <memory>
#include <string>
/**
* @brief MTR Next Train application
*
* Provides multi-page navigation for:
* 1. Line selection - choose MTR line
* 2. Station selection - choose station within selected line
* 3. Arrival display - show real-time train arrival information
*/
class MtrApp : public UIApp {
public:
MtrApp();
virtual ~MtrApp() = default;
esp_err_t init(lv_obj_t* container) override;
esp_err_t deinit(void) override;
std::string get_name(void) const override;
bool on_back_button_pressed(void) override;
void handle_event(uint32_t event_type, void* event_data) override;
// Set network handler (must be called before using app)
void set_network_handler(NetworkHandler* handler) { _network_handler = handler; }
private:
std::unique_ptr<MTRNextTrainHandler> _mtr_handler;
std::unique_ptr<PageStack> _page_stack;
NetworkHandler* _network_handler = nullptr;
// Current selection state
std::string _selected_line_code;
std::string _selected_station_code;
LineInfo* _selected_line_info = nullptr;
std::vector<LineInfo> _all_lines;
// Page builders
void build_line_selection_page(lv_obj_t* page_container);
void build_station_selection_page(lv_obj_t* page_container);
void build_arrival_page(lv_obj_t* page_container);
// Event handlers
static void line_button_event_cb(lv_event_t* e);
static void station_button_event_cb(lv_event_t* e);
static void refresh_button_event_cb(lv_event_t* e);
// Helper functions
void load_arrival_data(lv_obj_t* page_container);
uint32_t parse_color_hex(const char* hex_str);
};
/**
* @brief AppDescriptor for MtrApp
*/
class MtrAppDescriptor : public AppDescriptor {
public:
MtrAppDescriptor();
void draw_icon(lv_obj_t* parent) override;
private:
static MtrApp* _app_instance;
};

View File

@@ -1,64 +0,0 @@
#include "apps/shutdown_app.h"
#include "esp_log.h"
#define TAG "ShutdownApp"
ShutdownApp::ShutdownApp(std::string message)
: _message(message.empty() ? "System Shutting Down..." : message) { }
esp_err_t ShutdownApp::init(lv_obj_t* container) {
if (!container) {
ESP_LOGE(TAG, "Container is null");
return ESP_ERR_INVALID_ARG;
}
_container = container;
ESP_LOGI(TAG, "Initializing shutdown app with message: %s", _message.c_str());
// Main message label
_label_message = lv_label_create(_container);
lv_label_set_text(_label_message, _message.c_str());
lv_obj_set_style_text_color(_label_message, lv_color_white(), 0);
lv_obj_align(_label_message, LV_ALIGN_CENTER, 0, 0);
// Optional: Add spinner animation
lv_obj_t* spinner = lv_spinner_create(_container);
lv_obj_set_size(spinner, 80, 80);
lv_obj_align(spinner, LV_ALIGN_CENTER, 0, 80);
lv_obj_set_style_arc_color(spinner, lv_color_white(), LV_PART_INDICATOR);
ESP_LOGI(TAG, "Shutdown app initialized successfully");
return ESP_OK;
}
esp_err_t ShutdownApp::deinit(void) {
ESP_LOGI(TAG, "Deinitializing shutdown app");
_label_message = nullptr;
return ESP_OK;
}
std::string ShutdownApp::get_name(void) const {
return "Shutdown";
}
// ShutdownAppDescriptor implementation
ShutdownApp* ShutdownAppDescriptor::_app_instance = nullptr;
ShutdownAppDescriptor::ShutdownAppDescriptor()
: AppDescriptor("Shutdown", nullptr) {
// Create singleton app instance with default message
if (!_app_instance) {
_app_instance = new ShutdownApp();
}
// it's only used during system shutdown, not as a user-launchable app
}
void ShutdownAppDescriptor::draw_icon(lv_obj_t* parent) {
// Create a simple icon (not normally shown in nav bar)
lv_obj_t* icon_label = lv_label_create(parent);
lv_label_set_text(icon_label, LV_SYMBOL_POWER "\nShutdown");
lv_obj_set_style_text_color(icon_label, lv_color_white(), 0);
lv_obj_set_style_text_align(icon_label, LV_TEXT_ALIGN_CENTER, 0);
lv_obj_center(icon_label);
}

View File

@@ -1,39 +0,0 @@
#pragma once
#include "ui/ui_app.h"
#include "ui/app_registry.h"
/**
* @brief Shutdown application - displays shutdown message
*
* Shown when the system is about to enter deep sleep or power off.
* Displays a message and optionally a spinner animation.
*/
class ShutdownApp : public UIApp {
public:
ShutdownApp(std::string message = "");
virtual ~ShutdownApp() = default;
esp_err_t init(lv_obj_t* container) override;
esp_err_t deinit(void) override;
std::string get_name(void) const override;
private:
std::string _message;
lv_obj_t* _label_message = nullptr;
};
/**
* @brief AppDescriptor for ShutdownApp
*
* Note: Shutdown app is typically not shown in the navigation bar
* as it's only used during system shutdown.
*/
class ShutdownAppDescriptor : public AppDescriptor {
public:
ShutdownAppDescriptor();
void draw_icon(lv_obj_t* parent) override;
private:
static ShutdownApp* _app_instance;
};

View File

@@ -1,115 +0,0 @@
#include "page_stack.h"
#include "esp_log.h"
static const char* TAG = "PageStack";
PageStack::PageStack(lv_obj_t* parent_container)
: parent_container_(parent_container) {
if (!parent_container_) {
ESP_LOGE(TAG, "Parent container is null");
}
}
PageStack::~PageStack() {
clear();
}
lv_obj_t* PageStack::create_page_container() {
lv_obj_t* page = lv_obj_create(parent_container_);
// Fill parent container
lv_obj_set_size(page, LV_PCT(100), LV_PCT(100));
lv_obj_set_pos(page, 0, 0);
// Remove padding and scrollbars
lv_obj_set_style_pad_all(page, 0, 0);
lv_obj_set_scrollbar_mode(page, LV_SCROLLBAR_MODE_OFF);
// White background
lv_obj_set_style_bg_color(page, lv_color_white(), 0);
lv_obj_set_style_bg_opa(page, LV_OPA_COVER, 0);
// Remove border
lv_obj_set_style_border_width(page, 0, 0);
return page;
}
lv_obj_t* PageStack::push(PageBuilder builder, PageCleanup cleanup) {
if (!parent_container_) {
ESP_LOGE(TAG, "Cannot push page: parent container is null");
return nullptr;
}
if (!builder) {
ESP_LOGE(TAG, "Cannot push page: builder is null");
return nullptr;
}
// Hide current page if any
if (!pages_.empty()) {
lv_obj_add_flag(pages_.back().container, LV_OBJ_FLAG_HIDDEN);
}
// Create new page container
lv_obj_t* page = create_page_container();
// Build page content
builder(page);
// Add to stack
pages_.push_back({page, cleanup});
ESP_LOGD(TAG, "Pushed page (depth: %d)", pages_.size());
return page;
}
bool PageStack::pop() {
if (pages_.empty()) {
ESP_LOGW(TAG, "Cannot pop: stack is empty");
return false;
}
// Get and remove current page
Page current = pages_.back();
pages_.pop_back();
// Call cleanup callback if provided
if (current.cleanup) {
current.cleanup(current.container);
}
// Delete page container
lv_obj_del(current.container);
// Show previous page if any
if (!pages_.empty()) {
lv_obj_clear_flag(pages_.back().container, LV_OBJ_FLAG_HIDDEN);
}
ESP_LOGD(TAG, "Popped page (depth: %d)", pages_.size());
return true;
}
void PageStack::clear() {
ESP_LOGD(TAG, "Clearing all pages (depth: %d)", pages_.size());
// Pop all pages (calls cleanup callbacks)
while (!pages_.empty()) {
Page current = pages_.back();
pages_.pop_back();
if (current.cleanup) {
current.cleanup(current.container);
}
lv_obj_del(current.container);
}
}
lv_obj_t* PageStack::current_page() const {
if (pages_.empty()) {
return nullptr;
}
return pages_.back().container;
}

View File

@@ -1,86 +0,0 @@
#pragma once
#include "lvgl.h"
#include <vector>
#include <functional>
/**
* @brief Reusable page stack for multi-page navigation within LVGL apps
*
* Manages a stack of LVGL containers, allowing apps to push/pop pages
* and implement hierarchical navigation. Thread-safe for use with LVGL.
*/
class PageStack {
public:
/**
* @brief Page builder callback
* @param page_container The LVGL container to build the page in
*/
using PageBuilder = std::function<void(lv_obj_t* page_container)>;
/**
* @brief Page cleanup callback
* @param page_container The LVGL container being destroyed
*/
using PageCleanup = std::function<void(lv_obj_t* page_container)>;
/**
* @brief Construct page stack with parent container
* @param parent_container Parent LVGL container for pages
*/
explicit PageStack(lv_obj_t* parent_container);
/**
* @brief Destructor - clears all pages
*/
~PageStack();
/**
* @brief Push a new page onto the stack
* @param builder Function to build page content
* @param cleanup Optional cleanup function called when page is popped
* @return The created page container
*/
lv_obj_t* push(PageBuilder builder, PageCleanup cleanup = nullptr);
/**
* @brief Pop the current page and return to previous
* @return true if page was popped, false if stack is empty
*/
bool pop();
/**
* @brief Clear all pages from the stack
*/
void clear();
/**
* @brief Get the current (top) page container
* @return Current page or nullptr if stack is empty
*/
lv_obj_t* current_page() const;
/**
* @brief Get the number of pages in the stack
*/
size_t depth() const { return pages_.size(); }
/**
* @brief Check if stack is empty
*/
bool empty() const { return pages_.empty(); }
private:
struct Page {
lv_obj_t* container;
PageCleanup cleanup;
};
lv_obj_t* parent_container_;
std::vector<Page> pages_;
/**
* @brief Create a page container
*/
lv_obj_t* create_page_container();
};

View File

@@ -1,264 +0,0 @@
#include "ui/root_layout.h"
#include "ui/ui_handler.h"
#include "ui/app_registry.h"
#include "esp_log.h"
#define TAG "RootLayout"
// Display dimensions
#define DISPLAY_WIDTH 800
#define DISPLAY_HEIGHT 480
// Layout dimensions
#define HEADER_HEIGHT 40
#define NAV_BAR_HEIGHT 50
#define APP_CONTAINER_HEIGHT (DISPLAY_HEIGHT - HEADER_HEIGHT - NAV_BAR_HEIGHT)
// forward-declare local event callback
static void on_home_button_clicked(lv_event_t* event);
RootLayout::RootLayout(UIHandler* ui_handler)
: _ui_handler(ui_handler) { }
esp_err_t RootLayout::init(lv_obj_t* parent) {
if (!parent) {
ESP_LOGE(TAG, "Parent object is null");
return ESP_ERR_INVALID_ARG;
}
ESP_LOGI(TAG, "Initializing RootLayout");
if (create_layout(parent) != ESP_OK) {
ESP_LOGE(TAG, "Failed to create layout");
return ESP_FAIL;
}
ESP_LOGI(TAG, "RootLayout initialized successfully");
return ESP_OK;
}
esp_err_t RootLayout::deinit(void) {
ESP_LOGI(TAG, "Deinitializing RootLayout");
// LVGL will handle cleanup when parent is destroyed
_header = nullptr;
_header_label = nullptr;
_app_container = nullptr;
_nav_bar = nullptr;
_back_button = nullptr;
return ESP_OK;
}
esp_err_t RootLayout::create_layout(lv_obj_t* parent) {
// Configure parent as flexbox column layout
lv_obj_set_flex_flow(parent, LV_FLEX_FLOW_COLUMN);
lv_obj_set_flex_align(parent, LV_FLEX_ALIGN_START, LV_FLEX_ALIGN_START, LV_FLEX_ALIGN_START);
lv_obj_set_style_pad_all(parent, 0, 0);
lv_obj_set_style_pad_gap(parent, 0, 0);
// Create header (top, fixed height)
_header = lv_obj_create(parent);
lv_obj_set_width(_header, lv_pct(100));
lv_obj_set_height(_header, HEADER_HEIGHT);
lv_obj_set_style_bg_color(_header, lv_color_hex(0xFFFFFF), 0);
lv_obj_set_style_border_width(_header, 0, 0);
lv_obj_set_style_border_color(_header, lv_color_hex(0x000000), 0);
lv_obj_set_style_border_width(_header, 1, LV_BORDER_SIDE_BOTTOM);
lv_obj_set_style_pad_all(_header, 0, 0);
lv_obj_set_style_radius(_header, 0, 0);
_header_label = lv_label_create(_header);
lv_label_set_text(_header_label, "App");
lv_obj_set_style_text_color(_header_label, lv_color_black(), 0);
lv_obj_align(_header_label, LV_ALIGN_LEFT_MID, 10, 0);
// Create app container (middle, flexible - grows to fill available space)
_app_container = lv_obj_create(parent);
lv_obj_set_width(_app_container, lv_pct(100));
lv_obj_set_flex_grow(_app_container, 1);
lv_obj_set_style_bg_color(_app_container, lv_color_white(), 0);
lv_obj_set_style_border_width(_app_container, 0, 0);
lv_obj_set_style_pad_all(_app_container, 0, 0);
lv_obj_set_style_radius(_app_container, 0, 0);
// Create navigation bar (bottom, fixed height)
_nav_bar = lv_obj_create(parent);
lv_obj_set_width(_nav_bar, lv_pct(100));
lv_obj_set_height(_nav_bar, NAV_BAR_HEIGHT);
lv_obj_set_style_bg_color(_nav_bar, lv_color_hex(0xFFFFFF), 0);
lv_obj_set_style_border_color(_nav_bar, lv_color_hex(0x000000), 0);
lv_obj_set_style_border_width(_nav_bar, 1, LV_BORDER_SIDE_TOP);
lv_obj_set_style_pad_all(_nav_bar, 5, 0);
lv_obj_set_style_radius(_nav_bar, 0, 0);
// Configure nav bar as flexbox row layout with space-between
lv_obj_set_flex_flow(_nav_bar, LV_FLEX_FLOW_ROW);
lv_obj_set_flex_align(_nav_bar, LV_FLEX_ALIGN_SPACE_BETWEEN, LV_FLEX_ALIGN_CENTER, LV_FLEX_ALIGN_CENTER);
// Create back button (aligned to start by flex layout)
_back_button = lv_btn_create(_nav_bar);
lv_obj_set_size(_back_button, 60, NAV_BAR_HEIGHT - 10);
lv_obj_set_style_bg_color(_back_button, lv_color_hex(0x555555), 0);
lv_obj_add_event_cb(_back_button, on_back_button_clicked, LV_EVENT_CLICKED, _ui_handler);
lv_obj_add_flag(_back_button, LV_OBJ_FLAG_HIDDEN);
// Add back arrow label
lv_obj_t* back_label = lv_label_create(_back_button);
lv_label_set_text(back_label, LV_SYMBOL_LEFT);
lv_obj_set_style_text_color(back_label, lv_color_black(), 0);
lv_obj_align(back_label, LV_ALIGN_CENTER, 0, 0);
// Create home button (aligned to end by flex layout)
lv_obj_t* home_button = lv_btn_create(_nav_bar);
lv_obj_set_size(home_button, 60, NAV_BAR_HEIGHT - 10);
lv_obj_set_style_bg_color(home_button, lv_color_hex(0x555555), 0);
lv_obj_t* home_label = lv_label_create(home_button);
lv_label_set_text(home_label, LV_SYMBOL_HOME);
lv_obj_set_style_text_color(home_label, lv_color_white(), 0);
lv_obj_align(home_label, LV_ALIGN_CENTER, 0, 0);
lv_obj_add_event_cb(home_button, on_home_button_clicked, LV_EVENT_CLICKED, _ui_handler);
ESP_LOGI(TAG, "Layout created with flexible design: Header=%d, NavBar=%d",
HEADER_HEIGHT, NAV_BAR_HEIGHT);
return ESP_OK;
}
void RootLayout::update_header(std::string app_name) {
if (!_header_label) {
return;
}
if (app_name.empty() == false) {
lv_label_set_text(_header_label, app_name.c_str());
} else {
lv_label_set_text(_header_label, "App");
}
}
esp_err_t RootLayout::render_app_icons(void) {
if (!_nav_bar) {
ESP_LOGE(TAG, "Navigation bar not initialized");
return ESP_FAIL;
}
// Clear existing app container content (icons are rendered in the app area)
if (!_app_container) {
ESP_LOGE(TAG, "App container not initialized");
return ESP_FAIL;
}
lv_obj_clean(_app_container);
// Get all registered apps from registry
const auto& app_descriptors = AppRegistry::instance().get_app_descriptors();
if (app_descriptors.empty()) {
ESP_LOGW(TAG, "No apps registered in AppRegistry");
lv_obj_t* nav_label = lv_label_create(_nav_bar);
lv_label_set_text(nav_label, "No apps available");
lv_obj_set_style_text_color(nav_label, lv_color_white(), 0);
lv_obj_align(nav_label, LV_ALIGN_CENTER, 0, 0);
return ESP_OK;
}
ESP_LOGI(TAG, "Rendering %d app icons", (int)app_descriptors.size());
// Calculate icon spacing inside the app container
int icon_count = app_descriptors.size();
int icon_width = 96;
int icon_height = 96;
int icon_spacing = DISPLAY_WIDTH / (icon_count + 1);
int x_offset = icon_spacing;
int y_offset = (APP_CONTAINER_HEIGHT - icon_height) / 2;
// Render each app icon into the app container
for (size_t i = 0; i < app_descriptors.size(); i++) {
AppDescriptor* descriptor = app_descriptors[i];
lv_obj_t* icon_container = lv_obj_create(_app_container);
lv_obj_set_size(icon_container, icon_width, icon_height);
lv_obj_set_pos(icon_container, x_offset - icon_width / 2, y_offset);
lv_obj_set_style_bg_opa(icon_container, LV_OPA_TRANSP, 0);
lv_obj_set_style_pad_all(icon_container, 0, 0);
// add a border for debugging
lv_obj_set_style_border_color(icon_container, lv_color_hex(0x000000), 0);
lv_obj_set_style_border_width(icon_container, 1, 0);
lv_obj_set_user_data(icon_container, descriptor);
descriptor->draw_icon(icon_container);
lv_obj_add_flag(icon_container, LV_OBJ_FLAG_CLICKABLE);
lv_obj_add_event_cb(icon_container, on_app_icon_clicked, LV_EVENT_CLICKED, _ui_handler);
x_offset += icon_spacing;
}
return ESP_OK;
}
void RootLayout::show_back_button(void) {
if (_back_button) {
lv_obj_clear_flag(_back_button, LV_OBJ_FLAG_HIDDEN);
}
}
void RootLayout::hide_back_button(void) {
if (_back_button) {
lv_obj_add_flag(_back_button, LV_OBJ_FLAG_HIDDEN);
}
}
void RootLayout::on_app_icon_clicked(lv_event_t* event) {
// Use the current target (the object the callback was attached to)
// instead of the event target, which may be a child (like a label).
lv_obj_t* icon_container = static_cast<lv_obj_t*>(lv_event_get_current_target(event));
UIHandler* handler = static_cast<UIHandler*>(lv_event_get_user_data(event));
AppDescriptor* descriptor = static_cast<AppDescriptor*>(lv_obj_get_user_data(icon_container));
if (!handler || !descriptor) {
ESP_LOGE(TAG, "Invalid event data in app icon click");
return;
}
ESP_LOGI(TAG, "App icon clicked: %s", descriptor->get_name().c_str());
handler->switch_app(descriptor);
}
void RootLayout::on_back_button_clicked(lv_event_t* event) {
UIHandler* handler = static_cast<UIHandler*>(lv_event_get_user_data(event));
if (!handler) {
ESP_LOGE(TAG, "Invalid handler in back button click");
return;
}
// Get the active app
UIApp* active_app = handler->get_active_app();
if (!active_app) {
ESP_LOGW(TAG, "Back button pressed but no active app");
return;
}
// Let the app handle the back button press
bool handled = active_app->on_back_button_pressed();
if (handled) {
ESP_LOGI(TAG, "Back button handled by app: %s", active_app->get_name());
} else {
ESP_LOGI(TAG, "Back button not handled by app, returning to main screen");
handler->return_to_main_screen();
}
}
static void on_home_button_clicked(lv_event_t* event) {
UIHandler* handler = static_cast<UIHandler*>(lv_event_get_user_data(event));
if (!handler) {
ESP_LOGE(TAG, "Invalid handler in home button click");
return;
}
handler->return_to_main_screen();
}

View File

@@ -1,138 +0,0 @@
#pragma once
#include "lvgl.h"
#include "esp_err.h"
#include <string>
// Forward declaration
class UIHandler;
/**
* @brief Root Layout Manager - manages the main screen layout
*
* The RootLayout class is responsible for:
* - Creating and managing the main screen structure (header, app container, nav bar)
* - Rendering app icons from the AppRegistry
* - Managing the back button
* - Updating header content
*/
class RootLayout {
public:
/**
* @brief Construct a new RootLayout object
*
* @param ui_handler Pointer to the UIHandler (for callbacks)
*/
RootLayout(UIHandler* ui_handler);
/**
* @brief Initialize the layout
*
* Creates the main screen with header, app container, and navigation bar.
*
* @param parent Parent LVGL object to attach layout to
* @return ESP_OK on success, error code otherwise
*/
esp_err_t init(lv_obj_t* parent);
/**
* @brief Deinitialize the layout
*
* Cleans up all layout widgets.
*
* @return ESP_OK on success, error code otherwise
*/
esp_err_t deinit(void);
/**
* @brief Render app icons in the navigation bar
*
* Queries the AppRegistry for all registered apps and
* renders their icons in the navigation bar. Also creates
* the back button.
*
* @return ESP_OK on success, error code otherwise
*/
esp_err_t render_app_icons(void);
/**
* @brief Update header with app name
*
* @param app_name Name to display in header (nullptr for default)
*/
void update_header(std::string app_name);
/**
* @brief Show the back button
*/
void show_back_button(void);
/**
* @brief Hide the back button
*/
void hide_back_button(void);
/**
* @brief Get the header object
*
* @return lv_obj_t* pointer to the header container
*/
lv_obj_t* get_header(void) const {
return _header;
}
/**
* @brief Get the app container (where apps render)
*
* @return lv_obj_t* pointer to the app container
*/
lv_obj_t* get_app_container(void) const {
return _app_container;
}
/**
* @brief Get the navigation bar object
*
* @return lv_obj_t* pointer to the navigation bar container
*/
lv_obj_t* get_nav_bar(void) const {
return _nav_bar;
}
private:
UIHandler* _ui_handler = nullptr; ///< Reference to UIHandler for callbacks
lv_obj_t* _header = nullptr; ///< Header area (top)
lv_obj_t* _header_label = nullptr; ///< Header text label
lv_obj_t* _app_container = nullptr; ///< Container for app widgets (middle)
lv_obj_t* _nav_bar = nullptr; ///< Navigation bar (bottom)
lv_obj_t* _back_button = nullptr; ///< Back button in navigation bar
/**
* @brief Create the layout structure
*
* Sets up header, app container, and navigation bar with
* appropriate dimensions and positioning.
*
* @param parent Parent object to attach layout to
* @return ESP_OK on success, error code otherwise
*/
esp_err_t create_layout(lv_obj_t* parent);
/**
* @brief Handle app icon click event
*
* Static callback for LVGL event handling.
*
* @param event LVGL event object
*/
static void on_app_icon_clicked(lv_event_t* event);
/**
* @brief Handle back button click event
*
* Static callback for LVGL event handling.
*
* @param event LVGL event object
*/
static void on_back_button_clicked(lv_event_t* event);
};

0
main/ui/ui.h Normal file
View File

View File

@@ -1,98 +0,0 @@
#pragma once
#include "lvgl.h"
#include "esp_err.h"
#include <string>
/**
* @brief Base class for all UI applications
*
* All UI applications (apps) must inherit from this class.
* Each app is responsible for managing its own widgets within
* the provided LVGL container. The UIHandler will manage the
* lifecycle of apps and event routing.
*/
class UIApp {
public:
virtual ~UIApp() = default;
/**
* @brief Initialize the app with the given container
*
* The app should create all its widgets as children of the
* provided container. The container is already positioned
* between the header and navigation bar.
*
* @param container LVGL container object for this app
* @return ESP_OK on success, error code otherwise
*/
virtual esp_err_t init(lv_obj_t* container) = 0;
/**
* @brief Deinitialize and clean up app resources
*
* The app should delete all widgets and release any resources.
* The container itself will be handled by UIHandler.
*
* @return ESP_OK on success, error code otherwise
*/
virtual esp_err_t deinit(void) = 0;
/**
* @brief Get the display name of this app
*
* Used for logging and potentially showing in navigation.
*
* @return std::string app name
*/
virtual std::string get_name(void) const = 0;
/**
* @brief Handle system events passed from UIHandler
*
* System events include network status changes, storage ready,
* display refresh, and other system-level events.
*
* @param event_type Type/ID of the event
* @param event_data Optional event data payload
*/
virtual void handle_event(uint32_t event_type, void* event_data = nullptr) { }
virtual bool on_back_button_pressed(void) {
return false; // default: not handled
}
/**
* @brief Get the app's root container
*
* @return lv_obj_t* pointer to the app's container
*/
lv_obj_t* get_container(void) const {
return _container;
}
protected:
lv_obj_t* _container = nullptr; ///< LVGL container provided by UIHandler
};
class AppDescriptor {
public:
virtual ~AppDescriptor() = default;
virtual void draw_icon(lv_obj_t* parent) = 0;
std::string get_name() const {
return _name;
}
UIApp* get_app_instance() const {
return _app_instance;
}
protected:
AppDescriptor(std::string name, UIApp* app_instance)
: _name(name), _app_instance(app_instance) { }
std::string _name;
UIApp* _app_instance;
};

View File

@@ -1,208 +0,0 @@
#include "ui/ui_handler.h"
#include "ui/root_layout.h"
#include "ui/app_registry.h"
#include "esp_log.h"
#include "lvgl.h"
#define TAG "UIHandler"
// Display dimensions from constants.h
#define DISPLAY_WIDTH 800
#define DISPLAY_HEIGHT 480
// Layout dimensions
#define HEADER_HEIGHT 40
#define NAV_BAR_HEIGHT 50
#define _APP_CONTAINERHEIGHT (DISPLAY_HEIGHT - HEADER_HEIGHT - NAV_BAR_HEIGHT)
esp_err_t UIHandler::init(void) {
ESP_LOGI(TAG, "Initializing UIHandler");
// Create main screen
_main_screen = lv_obj_create(NULL);
if (!_main_screen) {
ESP_LOGE(TAG, "Failed to create main screen");
return ESP_FAIL;
}
lv_obj_set_style_bg_color(_main_screen, lv_color_black(), 0);
lv_obj_set_size(_main_screen, DISPLAY_WIDTH, DISPLAY_HEIGHT);
// Create root layout
_root_layout = new RootLayout(this);
if (!_root_layout) {
ESP_LOGE(TAG, "Failed to allocate RootLayout");
return ESP_FAIL;
}
if (_root_layout->init(_main_screen) != ESP_OK) {
ESP_LOGE(TAG, "Failed to initialize root layout");
delete _root_layout;
_root_layout = nullptr;
return ESP_FAIL;
}
// Render app icons from registry
if (_root_layout->render_app_icons() != ESP_OK) {
ESP_LOGW(TAG, "Failed to render app icons");
}
// Defer screen loading to prevent blocking during initialization
// Use LVGL timer to load screen after allowing watchdog reset
lv_timer_create([](lv_timer_t* timer) {
lv_obj_t* screen = static_cast<lv_obj_t*>(lv_timer_get_user_data(timer));
ESP_LOGI("UIHandler", "Loading main screen via timer");
lv_screen_load(screen);
lv_timer_del(timer);
}, 100, _main_screen); // 100ms delay to allow watchdog reset
ESP_LOGI(TAG, "UIHandler initialized successfully");
return ESP_OK;
}
esp_err_t UIHandler::deinit(void) {
ESP_LOGI(TAG, "Deinitializing UIHandler");
// Deinit current app
if (_active_app) {
if (_active_app->deinit() != ESP_OK) {
ESP_LOGW(TAG, "Error deinitializing active app: %s", _active_app->get_name());
}
_active_app = nullptr;
}
// Delete shutdown app if cached
if (_shutdown_app) {
delete _shutdown_app;
_shutdown_app = nullptr;
}
// Clean up root layout
if (_root_layout) {
_root_layout->deinit();
delete _root_layout;
_root_layout = nullptr;
}
// Main screen will be cleaned up by LVGL
_main_screen = nullptr;
return ESP_OK;
}
esp_err_t UIHandler::switch_app(UIApp* app) {
if (!app) {
ESP_LOGE(TAG, "Cannot switch to null app");
return ESP_ERR_INVALID_ARG;
}
lv_obj_t* app_container = get_app_container();
if (!app_container) {
ESP_LOGE(TAG, "App container not initialized");
return ESP_FAIL;
}
ESP_LOGI(TAG, "Switching to app: %s", app->get_name());
// Deinit current app
if (_active_app) {
if (_active_app->deinit() != ESP_OK) {
ESP_LOGW(TAG, "Error deinitializing app: %s", _active_app->get_name());
}
}
// Clear the app container
lv_obj_clean(app_container);
// Initialize new app
if (app->init(app_container) != ESP_OK) {
ESP_LOGE(TAG, "Failed to initialize app: %s", app->get_name());
_active_app = nullptr;
return ESP_FAIL;
}
_active_app = app;
// Update header through RootLayout
if (_root_layout) {
_root_layout->update_header(_active_app->get_name());
_root_layout->show_back_button();
}
return ESP_OK;
}
esp_err_t UIHandler::switch_app(AppDescriptor* app_descriptor) {
if (!app_descriptor) {
ESP_LOGE(TAG, "Cannot switch to null app descriptor");
return ESP_ERR_INVALID_ARG;
}
UIApp* app = app_descriptor->get_app_instance();
if (!app) {
ESP_LOGE(TAG, "App descriptor has null app instance");
return ESP_ERR_INVALID_ARG;
}
return switch_app(app);
}
void UIHandler::route_event(uint32_t event_type, void* event_data) {
if (_active_app) {
_active_app->handle_event(event_type, event_data);
}
}
esp_err_t UIHandler::show_shutdown_screen(std::string message) {
ESP_LOGI(TAG, "Showing shutdown screen");
lv_obj_t* app_container = get_app_container();
if (!app_container) {
ESP_LOGE(TAG, "App container not initialized");
return ESP_FAIL;
}
// Clear current app reference
_active_app = nullptr;
// Clear the app container
lv_obj_clean(app_container);
// Create shutdown message
lv_obj_t* shutdown_label = lv_label_create(app_container);
lv_label_set_text(shutdown_label, message.empty() ? "Shutting down..." : message.c_str());
lv_obj_set_style_text_color(shutdown_label, lv_color_white(), 0);
lv_obj_align(shutdown_label, LV_ALIGN_CENTER, 0, 0);
// Update header through RootLayout
if (_root_layout) {
_root_layout->update_header("System Shutdown");
}
return ESP_OK;
}
esp_err_t UIHandler::return_to_main_screen(void) {
ESP_LOGI(TAG, "Returning to main screen");
// Deinit current app
if (_active_app) {
if (_active_app->deinit() != ESP_OK) {
ESP_LOGW(TAG, "Error deinitializing app: %s", _active_app->get_name());
}
_active_app = nullptr;
}
// Clear the app container
lv_obj_t* app_container = get_app_container();
if (app_container) {
lv_obj_clean(app_container);
}
// Update header and hide back button through RootLayout
if (_root_layout) {
_root_layout->update_header("");
_root_layout->hide_back_button();
}
return ESP_OK;
}

View File

@@ -1,147 +0,0 @@
#pragma once
#include "ui_app.h"
#include "app_registry.h"
#include "root_layout.h"
#include "esp_err.h"
// Forward declaration
class RootLayout;
/**
* @brief UI Handler - manages app lifecycle and rendering
*
* The UIHandler manages:
* - Creation and destruction of UI apps
* - Switching between apps
* - Main screen layout (header, app container, navigation bar)
* - System event routing to active app
* - Displaying special screens (shutdown, etc.)
*/
class UIHandler {
public:
/**
* @brief Initialize the UI system with default layout
*
* Creates the main screen with:
* - Header area (top)
* - App container (middle)
* - Navigation bar (bottom)
*
* @return ESP_OK on success, error code otherwise
*/
esp_err_t init(void);
/**
* @brief Deinitialize the UI system
*
* Cleans up the current app and destroys the main screen.
*
* @return ESP_OK on success, error code otherwise
*/
esp_err_t deinit(void);
/**
* @brief Switch to a new app
*
* Deinitializes the current app (if any), initializes the new app,
* and updates the display.
*
* @param app Pointer to the new app to switch to
* @return ESP_OK on success, error code otherwise
*/
esp_err_t switch_app(UIApp* app);
/**
* @brief Switch to an app by its descriptor
*
* Convenience method that extracts the UIApp from the descriptor
* and calls switch_app().
*
* @param app_descriptor Pointer to the app descriptor
* @return ESP_OK on success, error code otherwise
*/
esp_err_t switch_app(AppDescriptor* app_descriptor);
/**
* @brief Get the currently active app
*
* @return Pointer to the active UIApp, or nullptr if none
*/
UIApp* get_active_app(void) const {
return _active_app;
}
/**
* @brief Route a system event to the active app
*
* If an app is active, this forwards the event to it.
*
* @param event_type Type/ID of the event
* @param event_data Optional event data payload
*/
void route_event(uint32_t event_type, void* event_data = nullptr);
/**
* @brief Display shutdown screen
*
* Shows a shutdown screen with a message. Typically called
* before the system enters deep sleep or powers off.
*
* @param message Optional message to display (e.g., "Shutting down...")
* @return ESP_OK on success, error code otherwise
*/
esp_err_t show_shutdown_screen(std::string message = "");
/**
* @brief Get the main screen object
*
* @return lv_obj_t* pointer to the main screen
*/
lv_obj_t* get_main_screen(void) const {
return _main_screen;
}
/**
* @brief Get the app container (where apps render)
*
* @return lv_obj_t* pointer to the app container
*/
lv_obj_t* get_app_container(void) const {
return _root_layout ? _root_layout->get_app_container() : nullptr;
}
/**
* @brief Get the header object
*
* @return lv_obj_t* pointer to the header container
*/
lv_obj_t* get_header(void) const {
return _root_layout ? _root_layout->get_header() : nullptr;
}
/**
* @brief Get the navigation bar object
*
* @return lv_obj_t* pointer to the navigation bar container
*/
lv_obj_t* get_nav_bar(void) const {
return _root_layout ? _root_layout->get_nav_bar() : nullptr;
}
/**
* @brief Return to main screen (deinit app and show app icons)
*
* Deinitializes the active app and displays the app icons
* in the navigation bar, returning to the home screen.
*
* @return ESP_OK on success, error code otherwise
*/
esp_err_t return_to_main_screen(void);
private:
lv_obj_t* _main_screen = nullptr; ///< Root screen
RootLayout* _root_layout = nullptr; ///< Root layout manager
UIApp* _active_app = nullptr; ///< Currently active app
UIApp* _shutdown_app = nullptr; ///< Cached shutdown app
};

File diff suppressed because it is too large Load Diff