From ae8cc34e10ed593667d91433b10759970b0bffeb Mon Sep 17 00:00:00 2001 From: Quency-D Date: Tue, 10 Nov 2026 18:34:03 +0800 Subject: [PATCH] feat: add MeshPocket V2 support --- boards/meshpocket_v2.json | 53 ++++ examples/companion_radio/ui-new/UITask.cpp | 85 +++++- examples/companion_radio/ui-new/UITask.h | 7 +- examples/simple_repeater/UITask.cpp | 37 ++- examples/simple_repeater/UITask.h | 6 +- examples/simple_room_server/UITask.cpp | 30 +- examples/simple_room_server/UITask.h | 9 +- examples/simple_room_server/main.cpp | 2 +- src/MeshCore.h | 6 + src/helpers/ui/BoardUiExtension.h | 27 ++ src/helpers/ui/BoardUiScreen.h | 74 +++++ src/helpers/ui/DisplayDriver.h | 4 + src/helpers/ui/NV3001BDisplay.cpp | 47 ++- src/helpers/ui/NV3001BDisplay.h | 17 ++ variants/meshpocket_v2/MeshPocketV2.cpp | 94 ++++++ variants/meshpocket_v2/MeshPocketV2.h | 25 ++ variants/meshpocket_v2/PowerBank.cpp | 115 +++++++ variants/meshpocket_v2/PowerBank.h | 43 +++ variants/meshpocket_v2/PowerBankPage.cpp | 334 +++++++++++++++++++++ variants/meshpocket_v2/PowerBankPage.h | 34 +++ variants/meshpocket_v2/platformio.ini | 79 +++++ variants/meshpocket_v2/target.cpp | 20 ++ variants/meshpocket_v2/target.h | 18 ++ variants/meshpocket_v2/variant.cpp | 13 + variants/meshpocket_v2/variant.h | 68 +++++ 25 files changed, 1210 insertions(+), 37 deletions(-) create mode 100644 boards/meshpocket_v2.json create mode 100644 src/helpers/ui/BoardUiExtension.h create mode 100644 src/helpers/ui/BoardUiScreen.h create mode 100644 variants/meshpocket_v2/MeshPocketV2.cpp create mode 100644 variants/meshpocket_v2/MeshPocketV2.h create mode 100644 variants/meshpocket_v2/PowerBank.cpp create mode 100644 variants/meshpocket_v2/PowerBank.h create mode 100644 variants/meshpocket_v2/PowerBankPage.cpp create mode 100644 variants/meshpocket_v2/PowerBankPage.h create mode 100644 variants/meshpocket_v2/platformio.ini create mode 100644 variants/meshpocket_v2/target.cpp create mode 100644 variants/meshpocket_v2/target.h create mode 100644 variants/meshpocket_v2/variant.cpp create mode 100644 variants/meshpocket_v2/variant.h diff --git a/boards/meshpocket_v2.json b/boards/meshpocket_v2.json new file mode 100644 index 00000000..cdc03033 --- /dev/null +++ b/boards/meshpocket_v2.json @@ -0,0 +1,53 @@ +{ + "build": { + "arduino": { + "ldscript": "nrf52840_s140_v6.ld" + }, + "core": "nRF5", + "cpu": "cortex-m4", + "extra_flags": "-DNRF52840_XXAA", + "f_cpu": "64000000L", + "hwids": [ + ["0x239A", "0x4405"], + ["0x239A", "0x0029"], + ["0x239A", "0x002A"], + ["0x1915", "0x1667"] + ], + "usb_product": "pocket-v2", + "mcu": "nrf52840", + "variant": "meshpocket_v2", + "bsp": { + "name": "adafruit" + }, + "softdevice": { + "sd_flags": "-DS140", + "sd_name": "s140", + "sd_version": "6.1.1", + "sd_fwid": "0x00B6" + }, + "bootloader": { + "settings_addr": "0xFF000" + } + }, + "connectivity": ["bluetooth"], + "debug": { + "jlink_device": "nRF52840_xxAA", + "onboard_tools": ["jlink"], + "svd_path": "nrf52840.svd", + "openocd_target": "nrf52840-mdk-rs" + }, + "frameworks": ["arduino"], + "name": "Heltec Mesh Pocket V2 (Adafruit BSP)", + "upload": { + "maximum_ram_size": 237568, + "maximum_size": 815104, + "speed": 115200, + "protocol": "nrfutil", + "protocols": ["jlink", "nrfjprog", "nrfutil", "stlink"], + "use_1200bps_touch": true, + "require_upload_port": true, + "wait_for_upload_port": true + }, + "url": "https://heltec.org", + "vendor": "Heltec" +} diff --git a/examples/companion_radio/ui-new/UITask.cpp b/examples/companion_radio/ui-new/UITask.cpp index 55cae1fe..cc06f981 100644 --- a/examples/companion_radio/ui-new/UITask.cpp +++ b/examples/companion_radio/ui-new/UITask.cpp @@ -107,6 +107,7 @@ class HomeScreen : public UIScreen { #ifndef UI_NO_HIBERNATE SHUTDOWN, #endif + BOARD_PAGE, Count // keep as last }; @@ -114,8 +115,10 @@ class HomeScreen : public UIScreen { mesh::RTCClock* _rtc; SensorManager* _sensors; NodePrefs* _node_prefs; + mesh::BoardUiExtension* _board_ui; uint8_t _page; bool _shutdown_init; + bool boardPageFullRefresh; AdvertPath recent[UI_RECENT_LIST_SIZE]; #if UI_DISCOVER_SCREEN DiscoveredNode discovered[DISCOVERED_NODES_TABLE_SIZE]; // not circular, latest discovered nodes are not kept @@ -157,7 +160,7 @@ class HomeScreen : public UIScreen { // while charging, show a bolt (or a plug once full) just left of the battery, // keeping the fill bar itself clean and uninterrupted - bool charging = board.isExternalPowered(); + bool charging = board.hasChargerStatus() ? board.isChargerActive() : board.isExternalPowered(); if (charging) { // There's no charge-complete signal on most boards, so "full" is a high // voltage band rather than an exact 100% (a real pack rarely reads 4.2V). @@ -204,9 +207,10 @@ class HomeScreen : public UIScreen { } public: - HomeScreen(UITask* task, mesh::RTCClock* rtc, SensorManager* sensors, NodePrefs* node_prefs) - : _task(task), _rtc(rtc), _sensors(sensors), _node_prefs(node_prefs), _page(0), - _shutdown_init(false), sensors_lpp(200) { } + HomeScreen(UITask* task, mesh::RTCClock* rtc, SensorManager* sensors, NodePrefs* node_prefs, + mesh::BoardUiExtension* board_ui) + : _task(task), _rtc(rtc), _sensors(sensors), _node_prefs(node_prefs), _board_ui(board_ui), _page(0), + _shutdown_init(false), boardPageFullRefresh(true), sensors_lpp(200) { } #if UI_DISCOVER_SCREEN bool sendDiscoverRequest() { @@ -248,7 +252,28 @@ public: } } + uint8_t pageCount() const { return _board_ui ? HomePage::Count : HomePage::BOARD_PAGE; } + bool isBoardPage() const { return _board_ui && _page == BOARD_PAGE; } + void invalidateBoardPage() { if (_board_ui) boardPageFullRefresh = true; } + + bool showBoardPage() { + if (!_board_ui || _shutdown_init) return false; +#ifndef UI_NO_HIBERNATE + if (_page == SHUTDOWN) return false; +#endif + if (_page != BOARD_PAGE) { + _page = BOARD_PAGE; + boardPageFullRefresh = true; + } + return true; + } + int render(DisplayDriver& display) override { + if (isBoardPage()) { + const int interval = _board_ui->render(display, boardPageFullRefresh); + boardPageFullRefresh = false; + return interval; + } display.setColor(UIColor::title_bkg); display.fillRect(0, 0, display.width(), 12); char tmp[80]; @@ -270,8 +295,9 @@ public: display.setColor(UIColor::title_bkg); } int y = 14; - int x = display.width() / 2 - 5 * (HomePage::Count-1); - for (uint8_t i = 0; i < HomePage::Count; i++, x += 10) { + const uint8_t count = pageCount(); + int x = display.width() / 2 - 5 * (count-1); + for (uint8_t i = 0; i < count; i++, x += 10) { if (i == _page) { display.fillRect(x-1, y-1, 4, 4); } else { @@ -561,11 +587,14 @@ public: bool handleInput(char c) override { if (c == KEY_LEFT || c == KEY_PREV) { - _page = (_page + HomePage::Count - 1) % HomePage::Count; + const uint8_t count = pageCount(); + _page = (_page + count - 1) % count; + invalidateBoardPage(); return true; } if (c == KEY_NEXT || c == KEY_RIGHT) { - _page = (_page + 1) % HomePage::Count; + _page = (_page + 1) % pageCount(); + invalidateBoardPage(); if (_page == HomePage::RECENT) { _task->showAlert("Recent adverts", 800); } @@ -724,6 +753,7 @@ public: void UITask::begin(DisplayDriver* display, SensorManager* sensors, NodePrefs* node_prefs) { _display = display; _sensors = sensors; + _board_ui = _board->getUiExtension(); #if defined(PIN_USER_BTN) user_btn.begin(); @@ -757,7 +787,7 @@ void UITask::begin(DisplayDriver* display, SensorManager* sensors, NodePrefs* no _alert_expiry = 0; splash = new SplashScreen(this); - home = new HomeScreen(this, &rtc_clock, sensors, node_prefs); + home = new HomeScreen(this, &rtc_clock, sensors, node_prefs, _board_ui); msg_preview = new MsgPreviewScreen(this, &rtc_clock); setCurrScreen(splash); } @@ -885,6 +915,7 @@ void UITask::userLedHandler() { } void UITask::setCurrScreen(UIScreen* c) { + if (curr && curr == home && c != home) static_cast(home)->invalidateBoardPage(); curr = c; _next_refresh = 100; } @@ -926,8 +957,16 @@ bool UITask::isButtonPressed() const { #endif } +void UITask::handleBoardUiFocus(uint8_t events, bool handlingInput) { + // Consume even when busy: an old event must not steal focus later. + if (!(events & mesh::BoardUiExtension::EVENT_REQUEST_FOCUS) || handlingInput || + !_display || curr != home || millis() < _alert_expiry) return; + if (static_cast(home)->showBoardPage()) checkDisplayOn(0); +} + void UITask::loop() { char c = 0; + bool boardInputHandled = false; #if UI_HAS_JOYSTICK int ev = user_btn.check(); if (ev == BUTTON_EVENT_CLICK) { @@ -985,6 +1024,21 @@ void UITask::loop() { } } #endif + const uint8_t boardEvents = _board_ui ? _board_ui->pollEvents() : mesh::BoardUiExtension::EVENT_NONE; + HomeScreen* homeScreen = static_cast(home); + if ((boardEvents & mesh::BoardUiExtension::EVENT_SHOW_PAGE) && c == 0 && + curr == home && homeScreen->showBoardPage()) { + checkDisplayOn(0); + boardInputHandled = true; + } + else if ((boardEvents & mesh::BoardUiExtension::EVENT_PAGE_ACTION) && c == 0 && + _display && _display->isOn() && curr == home && homeScreen->isBoardPage() && + millis() >= _alert_expiry) { + _board_ui->handlePageAction(); + _auto_off = millis() + _node_prefs->ui_auto_off_delay * 1000; + _next_refresh = 0; + boardInputHandled = true; + } #if defined(PIN_USER_BTN_ANA) if (abs(millis() - _analogue_pin_read_millis) > 10) { int ev = analog_btn.check(); @@ -1043,6 +1097,7 @@ void UITask::loop() { #endif #endif + handleBoardUiFocus(boardEvents, c != 0 || boardInputHandled); if (c != 0 && curr) { curr->handleInput(c); _auto_off = millis() + _node_prefs->ui_auto_off_delay * 1000; // extend auto-off timer @@ -1060,9 +1115,15 @@ void UITask::loop() { if (_display != NULL && _display->isOn()) { if (millis() >= _next_refresh && curr) { - _display->startFrame(); + HomeScreen* homeScreen = static_cast(home); + const bool boardFrame = curr == home && homeScreen->isBoardPage(); + const bool alertVisible = millis() < _alert_expiry; + // A board page may keep its pixels for field-level updates. + if (!boardFrame || (boardPageHadAlert && !alertVisible)) homeScreen->invalidateBoardPage(); + if (!boardFrame) _display->startFrame(); + boardPageHadAlert = boardFrame && alertVisible; int delay_millis = curr->render(*_display); - if (millis() < _alert_expiry) { // render alert popup + if (alertVisible) { // render alert popup _display->setTextSize(1); int y = _display->height() / 3; int p = _display->height() / 32; @@ -1088,6 +1149,7 @@ void UITask::loop() { } #endif if (millis() > _auto_off) { + static_cast(home)->invalidateBoardPage(); if (_node_prefs->ui_auto_off_blank && !(_node_prefs->ui_auto_off_keep_msgs && curr == msg_preview)) { @@ -1129,6 +1191,7 @@ void UITask::loop() { char UITask::checkDisplayOn(char c) { if (_display != NULL) { if (!_display->isOn()) { + static_cast(home)->invalidateBoardPage(); _display->turnOn(_node_prefs->ui_max_partial); // turn display on and consume event c = 0; } diff --git a/examples/companion_radio/ui-new/UITask.h b/examples/companion_radio/ui-new/UITask.h index 61831488..a53bb0a4 100644 --- a/examples/companion_radio/ui-new/UITask.h +++ b/examples/companion_radio/ui-new/UITask.h @@ -1,6 +1,7 @@ #pragma once #include +#include #include #include #include @@ -77,6 +78,8 @@ class UITask : public AbstractUITask { UIScreen* home; UIScreen* msg_preview; UIScreen* curr; + mesh::BoardUiExtension* _board_ui; + bool boardPageHadAlert = false; void userLedHandler(); @@ -87,10 +90,12 @@ class UITask : public AbstractUITask { char handleTripleClick(char c); void setCurrScreen(UIScreen* c); + void handleBoardUiFocus(uint8_t events, bool handlingInput); public: - UITask(mesh::MainBoard* board, MultiSerialInterface* serial) : AbstractUITask(board, serial), _display(NULL), _sensors(NULL) { + UITask(mesh::MainBoard* board, MultiSerialInterface* serial) : + AbstractUITask(board, serial), _display(NULL), _sensors(NULL), _board_ui(nullptr) { next_batt_chck = _next_refresh = 0; ui_started_at = 0; curr = NULL; diff --git a/examples/simple_repeater/UITask.cpp b/examples/simple_repeater/UITask.cpp index e0b6a41d..8f3695e0 100644 --- a/examples/simple_repeater/UITask.cpp +++ b/examples/simple_repeater/UITask.cpp @@ -35,6 +35,7 @@ void UITask::begin(NodePrefs* node_prefs, const char* build_date, const char* fi _started_at = millis(); _node_prefs = node_prefs; _display->turnOn(); + boardScreen.begin(*_board, *_display); #if defined(PIN_USER_BTN) && defined(DISPLAY_CLASS) user_btn.begin(); @@ -53,7 +54,10 @@ void UITask::begin(NodePrefs* node_prefs, const char* build_date, const char* fi free(version); } -void UITask::renderCurrScreen() { +unsigned long UITask::renderCurrScreen() { + uint32_t interval; + if (!_powering_off_at && boardScreen.renderIfSelected(interval)) return interval; + _display->startFrame(); char tmp[80]; if (millis() < _started_at + BOOT_SCREEN_MILLIS) { // boot screen // meshcore logo @@ -107,14 +111,26 @@ void UITask::renderCurrScreen() { sprintf(tmp, "BW: %03.2f CR: %d", _node_prefs->bw, _node_prefs->cr); _display->print(tmp); } + return 1000; } void UITask::loop() { + const uint8_t boardEvents = boardScreen.pollEvents(); + bool handlingInput = false; + const bool canChangePage = !_powering_off_at && millis() - _started_at >= BOOT_SCREEN_MILLIS; + if (boardScreen.handleInput(boardEvents, canChangePage)) { + handlingInput = true; + _auto_off = millis() + AUTO_OFF_MILLIS; + _next_refresh = 0; + } #if defined(PIN_USER_BTN) && defined(DISPLAY_CLASS) int ev = user_btn.check(); + handlingInput = handlingInput || ev != BUTTON_EVENT_NONE; if (ev == BUTTON_EVENT_CLICK) { if (_display->isOn()) { - // TODO: any action ? + if (canChangePage && boardScreen.togglePage()) { + _next_refresh = 0; + } } else { _display->turnOn(); } @@ -122,17 +138,26 @@ void UITask::loop() { } else if (ev == BUTTON_EVENT_LONG_PRESS) { _display->turnOn(); Serial.println("Powering Off"); - _powering_off_at = millis() + POWEROFF_DELAY; + _powering_off_at = millis() + POWEROFF_DELAY; + if (boardScreen.available()) { + _next_refresh = 0; + _auto_off = millis() + AUTO_OFF_MILLIS; + } } #endif + const bool canTakePowerEvent = !_powering_off_at && millis() - _started_at >= BOOT_SCREEN_MILLIS; + if (boardScreen.handleFocusRequest(boardEvents, canTakePowerEvent, handlingInput)) { + _auto_off = millis() + AUTO_OFF_MILLIS; + _next_refresh = 0; + } + if (_display->isOn()) { if (millis() >= _next_refresh) { - _display->startFrame(); - renderCurrScreen(); + unsigned long interval = renderCurrScreen(); _display->endFrame(); - _next_refresh = millis() + 1000; // refresh every second + _next_refresh = millis() + interval; } if (millis() > _auto_off) { _display->turnOff(); diff --git a/examples/simple_repeater/UITask.h b/examples/simple_repeater/UITask.h index d8e3ce1d..6c4a900d 100644 --- a/examples/simple_repeater/UITask.h +++ b/examples/simple_repeater/UITask.h @@ -1,9 +1,11 @@ #pragma once #include +#include #include class UITask { + BoardUiScreen boardScreen; mesh::MainBoard* _board; DisplayDriver* _display; unsigned long _next_read, _next_refresh, _auto_off; @@ -13,10 +15,10 @@ class UITask { unsigned long _powering_off_at = 0; unsigned long _started_at = 0; - void renderCurrScreen(); + unsigned long renderCurrScreen(); public: UITask(mesh::MainBoard& board, DisplayDriver& display) : _board(&board), _display(&display) { _next_read = _next_refresh = 0; } void begin(NodePrefs* node_prefs, const char* build_date, const char* firmware_version); void loop(); -}; \ No newline at end of file +}; diff --git a/examples/simple_room_server/UITask.cpp b/examples/simple_room_server/UITask.cpp index 8e4c2fcf..08136935 100644 --- a/examples/simple_room_server/UITask.cpp +++ b/examples/simple_room_server/UITask.cpp @@ -31,6 +31,7 @@ void UITask::begin(NodePrefs* node_prefs, const char* build_date, const char* fi _auto_off = millis() + AUTO_OFF_MILLIS; _node_prefs = node_prefs; _display->turnOn(); + boardScreen.begin(*_board, *_display); // strip off dash and commit hash by changing dash to null terminator // e.g: v1.2.3-abcdef -> v1.2.3 @@ -45,7 +46,10 @@ void UITask::begin(NodePrefs* node_prefs, const char* build_date, const char* fi free(version); } -void UITask::renderCurrScreen() { +unsigned long UITask::renderCurrScreen() { + uint32_t interval; + if (boardScreen.renderIfSelected(interval)) return interval; + _display->startFrame(); char tmp[80]; if (millis() < BOOT_SCREEN_MILLIS) { // boot screen // meshcore logo @@ -89,16 +93,28 @@ void UITask::renderCurrScreen() { sprintf(tmp, "BW: %03.2f CR: %d", _node_prefs->bw, _node_prefs->cr); _display->print(tmp); } + return 1000; } void UITask::loop() { + const uint8_t boardEvents = boardScreen.pollEvents(); + bool handlingInput = false; + const bool canChangePage = millis() >= BOOT_SCREEN_MILLIS; + if (boardScreen.handleInput(boardEvents, canChangePage)) { + handlingInput = true; + _auto_off = millis() + AUTO_OFF_MILLIS; + _next_refresh = 0; + } #ifdef PIN_USER_BTN if (millis() >= _next_read) { int btnState = digitalRead(PIN_USER_BTN); if (btnState != _prevBtnState) { if (btnState == USER_BTN_PRESSED) { // pressed? + handlingInput = true; if (_display->isOn()) { - // TODO: any action ? + if (canChangePage && boardScreen.togglePage()) { + _next_refresh = 0; + } } else { _display->turnOn(); } @@ -110,13 +126,17 @@ void UITask::loop() { } #endif + if (boardScreen.handleFocusRequest(boardEvents, canChangePage, handlingInput)) { + _auto_off = millis() + AUTO_OFF_MILLIS; + _next_refresh = 0; + } + if (_display->isOn()) { if (millis() >= _next_refresh) { - _display->startFrame(); - renderCurrScreen(); + unsigned long interval = renderCurrScreen(); _display->endFrame(); - _next_refresh = millis() + 1000; // refresh every second + _next_refresh = millis() + interval; } if (millis() > _auto_off) { _display->turnOff(); diff --git a/examples/simple_room_server/UITask.h b/examples/simple_room_server/UITask.h index a27259f1..723f8d16 100644 --- a/examples/simple_room_server/UITask.h +++ b/examples/simple_room_server/UITask.h @@ -1,19 +1,22 @@ #pragma once #include +#include #include class UITask { + BoardUiScreen boardScreen; + mesh::MainBoard* _board; DisplayDriver* _display; unsigned long _next_read, _next_refresh, _auto_off; int _prevBtnState; NodePrefs* _node_prefs; char _version_info[32]; - void renderCurrScreen(); + unsigned long renderCurrScreen(); public: - UITask(DisplayDriver& display) : _display(&display) { _next_read = _next_refresh = 0; } + UITask(mesh::MainBoard& board, DisplayDriver& display) : _board(&board), _display(&display) { _next_read = _next_refresh = 0; } void begin(NodePrefs* node_prefs, const char* build_date, const char* firmware_version); void loop(); -}; \ No newline at end of file +}; diff --git a/examples/simple_room_server/main.cpp b/examples/simple_room_server/main.cpp index 65fc55ef..ac31e39c 100644 --- a/examples/simple_room_server/main.cpp +++ b/examples/simple_room_server/main.cpp @@ -10,7 +10,7 @@ #ifdef DISPLAY_CLASS #include "UITask.h" - static UITask ui_task(display); + static UITask ui_task(board, display); #endif StdRNG fast_rng; diff --git a/src/MeshCore.h b/src/MeshCore.h index b9cfb418..906c5b03 100644 --- a/src/MeshCore.h +++ b/src/MeshCore.h @@ -42,6 +42,8 @@ namespace mesh { #define BD_STARTUP_NORMAL 0 // getStartupReason() codes #define BD_STARTUP_RX_PACKET 1 +class BoardUiExtension; + class MainBoard { public: virtual uint16_t getBattMilliVolts() = 0; @@ -70,6 +72,7 @@ public: virtual bool isExternalPowered() { return false; } // True while a board can identify an active battery-charging source. virtual bool isChargerActive() { return false; } + virtual bool hasChargerStatus() const { return false; } // Optional, source-specific power detection. Boards that can distinguish a USB // supply from a solar charger override these; defaults keep every other board @@ -85,6 +88,9 @@ public: virtual uint8_t getShutdownReason() const { return 0; } virtual const char* getShutdownReasonString(uint8_t reason) { return "Not available"; } + // Optional full-screen board UI. The returned object remains owned by the board. + virtual BoardUiExtension* getUiExtension() { return nullptr; } + virtual bool handleCommand(const char* command, uint32_t sender_timestamp, char* reply) { return false; } // Called from the example main loops. Lets a board feed its watchdog and diff --git a/src/helpers/ui/BoardUiExtension.h b/src/helpers/ui/BoardUiExtension.h new file mode 100644 index 00000000..c35154a8 --- /dev/null +++ b/src/helpers/ui/BoardUiExtension.h @@ -0,0 +1,27 @@ +#pragma once + +#include + +class DisplayDriver; + +namespace mesh { + +class BoardUiExtension { +public: + enum Event : uint8_t { + EVENT_NONE = 0, + EVENT_SHOW_PAGE = 1 << 0, + EVENT_PAGE_ACTION = 1 << 1, + EVENT_REQUEST_FOCUS = 1 << 2, + }; + + // Consume and return all board-owned input and focus events for this loop. + virtual uint8_t pollEvents() = 0; + virtual void handlePageAction() {} + + // The extension owns startFrame() and any coordinate-mode changes. The UI + // host calls endFrame() after render() returns. + virtual uint32_t render(DisplayDriver& display, bool fullRefresh) = 0; +}; + +} diff --git a/src/helpers/ui/BoardUiScreen.h b/src/helpers/ui/BoardUiScreen.h new file mode 100644 index 00000000..ac1baec5 --- /dev/null +++ b/src/helpers/ui/BoardUiScreen.h @@ -0,0 +1,74 @@ +#pragma once + +#include +#include "BoardUiExtension.h" +#include "DisplayDriver.h" + +class BoardUiScreen { + mesh::BoardUiExtension* extension = nullptr; + DisplayDriver* display = nullptr; + bool selected = false; + bool fullRefresh = true; + + void selectPage() { + if (!selected) { + selected = true; + fullRefresh = true; + } + } + +public: + void begin(mesh::MainBoard& board, DisplayDriver& screen) { + extension = board.getUiExtension(); + display = &screen; + } + + bool available() const { return extension != nullptr; } + + uint8_t pollEvents() { + if (!extension) return mesh::BoardUiExtension::EVENT_NONE; + if (!display->isOn()) fullRefresh = true; + return extension->pollEvents(); + } + + bool handleInput(uint8_t events, bool canOperate) { + if (!extension || !canOperate) return false; + + const bool awake = display->isOn(); + if (events & mesh::BoardUiExtension::EVENT_SHOW_PAGE) { + if (!awake) display->turnOn(); + selectPage(); + return true; + } + if ((events & mesh::BoardUiExtension::EVENT_PAGE_ACTION) && awake && selected) { + extension->handlePageAction(); + return true; + } + return false; + } + + bool handleFocusRequest(uint8_t events, bool canTakeFocus, bool handlingInput) { + if (!extension || !(events & mesh::BoardUiExtension::EVENT_REQUEST_FOCUS) || + !canTakeFocus || handlingInput) return false; + + const bool awake = display->isOn(); + if (!awake) display->turnOn(); + selectPage(); + if (!awake) fullRefresh = true; + return true; + } + + bool togglePage() { + if (!extension) return false; + selected = !selected; + fullRefresh = true; + return true; + } + + bool renderIfSelected(uint32_t& interval) { + if (!extension || !selected) return false; + interval = extension->render(*display, fullRefresh); + fullRefresh = false; + return true; + } +}; diff --git a/src/helpers/ui/DisplayDriver.h b/src/helpers/ui/DisplayDriver.h index 0e41dab5..99e982ad 100644 --- a/src/helpers/ui/DisplayDriver.h +++ b/src/helpers/ui/DisplayDriver.h @@ -15,12 +15,16 @@ class DisplayDriver { int _w, _h; protected: DisplayDriver(int w, int h) { _w = w; _h = h; } + void setLogicalSize(int w, int h) { _w = w; _h = h; } public: //enum Color { DARK=0, LIGHT, RED, GREEN, BLUE, YELLOW, ORANGE }; // on b/w screen, colors will be !=0 synonym of light int width() const { return _w; } int height() const { return _h; } + // Optional physical-pixel coordinate mode. Unsupported displays keep their + // existing logical coordinate system. + virtual void setNativePixels(bool) {} virtual bool isOn() = 0; virtual bool isEink() { return false; } // default to non-eink, override in eink drivers virtual void forceFullRefresh() {} // next refresh will be full for eink diff --git a/src/helpers/ui/NV3001BDisplay.cpp b/src/helpers/ui/NV3001BDisplay.cpp index 1ff7765c..3bbecd2e 100644 --- a/src/helpers/ui/NV3001BDisplay.cpp +++ b/src/helpers/ui/NV3001BDisplay.cpp @@ -107,21 +107,27 @@ ColorVal UIColor::popup_bkg = 0x07FF; // CYAN ColorVal UIColor::popup_txt = 0x0000; ColorVal UIColor::corp_blue = 0x001A; -static int scaleX(int x) { - return (int)(x * DISPLAY_SCALE_X); +void NV3001BDisplay::setNativePixels(bool enabled) { + nativePixels = enabled; + setLogicalSize(enabled ? NV3001B_SCREEN_WIDTH : NV3001B_LOGICAL_WIDTH, + enabled ? NV3001B_SCREEN_HEIGHT : NV3001B_LOGICAL_HEIGHT); } -static int scaleY(int y) { - return (int)(y * DISPLAY_SCALE_Y); +int NV3001BDisplay::scaleX(int x) const { + return nativePixels ? x : (int)(x * DISPLAY_SCALE_X); } -static int scaleWidth(int x, int w) { +int NV3001BDisplay::scaleY(int y) const { + return nativePixels ? y : (int)(y * DISPLAY_SCALE_Y); +} + +int NV3001BDisplay::scaleWidth(int x, int w) const { if (w <= 0) return 0; int scaled = scaleX(x + w) - scaleX(x); return scaled > 0 ? scaled : 1; } -static int scaleHeight(int y, int h) { +int NV3001BDisplay::scaleHeight(int y, int h) const { if (h <= 0) return 0; int scaled = scaleY(y + h) - scaleY(y); return scaled > 0 ? scaled : 1; @@ -183,7 +189,8 @@ static int textPixelScaleX(uint8_t size) { return size <= 1 ? NV3001B_TEXT_SIZE1_SCALE_X : NV3001B_TEXT_SIZE2_SCALE_X; } -static int textPixelScaleY(uint8_t size) { +int NV3001BDisplay::textPixelScaleY(uint8_t size) const { + if (nativePixels) return textPixelScaleX(size); // Square glyph pixels on the native canvas. return size <= 1 ? NV3001B_TEXT_SIZE1_SCALE_Y : NV3001B_TEXT_SIZE2_SCALE_Y; } @@ -254,10 +261,26 @@ void NV3001BDisplay::writeColor(uint16_t rgb, uint32_t count) { spi.beginTransaction(SPISettings(SPI_FREQUENCY, MSBFIRST, SPI_MODE0)); digitalWrite(PIN_TFT_DC, HIGH); digitalWrite(PIN_TFT_CS, LOW); +#ifdef NRF52_PLATFORM + // EasyDMA needs a RAM buffer. Send repeated pixels in bursts at 4 MHz. + uint8_t pixels[64]; + size_t bytes = sizeof(pixels); + if (count < bytes / 2) bytes = count * 2; + for (size_t i = 0; i < bytes; i += 2) { + pixels[i] = hi; + pixels[i + 1] = lo; + } + while (count) { + if (count < bytes / 2) bytes = count * 2; + spi.transfer(pixels, nullptr, bytes); + count -= bytes / 2; + } +#else while (count--) { spi.transfer(hi); spi.transfer(lo); } +#endif digitalWrite(PIN_TFT_CS, HIGH); spi.endTransaction(); } @@ -425,7 +448,11 @@ bool NV3001BDisplay::begin() { digitalWrite(PIN_TFT_DC, HIGH); delay(20); +#ifdef NRF52_PLATFORM + spi.begin(); // Pins are set by the nRF52 variant. +#else spi.begin(PIN_TFT_SCL, PIN_TFT_MISO, PIN_TFT_SDA, PIN_TFT_CS); +#endif if (PIN_TFT_RST >= 0) { pinMode(PIN_TFT_RST, OUTPUT); digitalWrite(PIN_TFT_RST, HIGH); @@ -456,6 +483,9 @@ void NV3001BDisplay::turnOff() { if (!is_on) return; writeOptionalPin(PIN_TFT_BL, !PIN_TFT_BL_ACTIVE); +#ifdef NRF52_PLATFORM + spi.end(); +#endif writeOptionalPin(PIN_TFT_EN, !PIN_TFT_EN_ACTIVE); is_on = false; if (periph_power) periph_power->release(); @@ -544,7 +574,8 @@ uint16_t NV3001BDisplay::getTextWidth(const char* str) { uint16_t len = 0; while (str[len] && str[len] != '\n' && str[len] != '\r') len++; - return (uint16_t)((len * 6 * textPixelScaleX(text_size)) / DISPLAY_SCALE_X); + const int pixels = len * 6 * textPixelScaleX(text_size); + return nativePixels ? pixels : (uint16_t)(pixels / DISPLAY_SCALE_X); } void NV3001BDisplay::endFrame() { diff --git a/src/helpers/ui/NV3001BDisplay.h b/src/helpers/ui/NV3001BDisplay.h index 76505b5d..5886f102 100644 --- a/src/helpers/ui/NV3001BDisplay.h +++ b/src/helpers/ui/NV3001BDisplay.h @@ -25,13 +25,24 @@ #endif class NV3001BDisplay : public DisplayDriver { +#ifdef NRF52_PLATFORM + SPIClass& spi; +#else SPIClass spi; +#endif RefCountedDigitalPin* periph_power; bool is_on = false; uint16_t color = 0xffff; uint8_t text_size = 1; int cursor_x = 0; int cursor_y = 0; + bool nativePixels = false; + + int scaleX(int x) const; + int scaleY(int y) const; + int scaleWidth(int x, int w) const; + int scaleHeight(int y, int h) const; + int textPixelScaleY(uint8_t size) const; void writeCommand(uint8_t cmd); void writeBytes(const uint8_t* data, size_t len); @@ -43,10 +54,16 @@ class NV3001BDisplay : public DisplayDriver { void drawChar(int x, int y, char ch); public: +#ifdef NRF52_PLATFORM + explicit NV3001BDisplay(SPIClass& bus) : + DisplayDriver(NV3001B_LOGICAL_WIDTH, NV3001B_LOGICAL_HEIGHT), spi(bus), periph_power(nullptr) { } +#else NV3001BDisplay(RefCountedDigitalPin* power = nullptr) : DisplayDriver(NV3001B_LOGICAL_WIDTH, NV3001B_LOGICAL_HEIGHT), spi(NV3001B_SPI_HOST), periph_power(power) { } +#endif bool begin(); + void setNativePixels(bool enabled) override; static const char* driverName() { return "NV3001B"; } static uint16_t physicalWidth() { return NV3001B_PANEL_WIDTH; } static uint16_t physicalHeight() { return NV3001B_PANEL_HEIGHT; } diff --git a/variants/meshpocket_v2/MeshPocketV2.cpp b/variants/meshpocket_v2/MeshPocketV2.cpp new file mode 100644 index 00000000..f72fab65 --- /dev/null +++ b/variants/meshpocket_v2/MeshPocketV2.cpp @@ -0,0 +1,94 @@ +#include "MeshPocketV2.h" +#include "PowerBankPage.h" +#include +#include +#include + +class MeshPocketV2::UiExtension : public mesh::BoardUiExtension { + MeshPocketV2& board; + PowerBankPage page; + MomentaryButton secondaryButton; + +public: + explicit UiExtension(MeshPocketV2& board) : + board(board), secondaryButton(PIN_BUTTON2, 1000, true, true, false) {} + + void begin() { + secondaryButton.begin(); + } + + uint8_t pollEvents() override { + uint8_t events = EVENT_NONE; + const int buttonEvent = secondaryButton.check(); + if (buttonEvent == BUTTON_EVENT_CLICK) { + events |= EVENT_SHOW_PAGE; + } +#ifdef MESHPOCKET_V2_USB_SWITCHABLE + else if (buttonEvent == BUTTON_EVENT_LONG_PRESS) { + events |= EVENT_PAGE_ACTION; + } +#endif + if (board.powerBank.takePageEvent()) events |= EVENT_REQUEST_FOCUS; + return events; + } + +#ifdef MESHPOCKET_V2_USB_SWITCHABLE + void handlePageAction() override { + board.toggleUsbData(); + } +#endif + + uint32_t render(DisplayDriver& display, bool fullRefresh) override { + if (fullRefresh) page.invalidate(); + display.setNativePixels(true); + page.draw(display, board.powerBank.snapshot(), board.isUsbDataEnabled()); + display.setNativePixels(false); + return 500; + } +}; + +void MeshPocketV2::begin() { + NRF52Board::begin(); + powerBank.begin(); + pinMode(PIN_USER_BTN, INPUT_PULLUP); + uiExtension().begin(); +} + +MeshPocketV2::UiExtension& MeshPocketV2::uiExtension() { + static UiExtension extension(*this); + return extension; +} + +mesh::BoardUiExtension* MeshPocketV2::getUiExtension() { + return &uiExtension(); +} + +uint16_t MeshPocketV2::getBattMilliVolts() { + const auto& status = powerBank.snapshot(); + if (status.cw.ready) return status.cw.voltageMv; + return status.hltLive() ? status.hlt.batteryMv : 0; +} + +void MeshPocketV2::setUsbDataEnabled(bool enabled) { + digitalWrite(PIN_IO_CSA, enabled ? HIGH : LOW); +} + +bool MeshPocketV2::toggleUsbData() { + const bool enabled = !isUsbDataEnabled(); + setUsbDataEnabled(enabled); + return enabled; +} + +bool MeshPocketV2::isUsbDataEnabled() const { + return digitalRead(PIN_IO_CSA) == HIGH; +} + +void MeshPocketV2::shutdownPeripherals() { + NRF52Board::shutdownPeripherals(); + powerBank.end(); + nrf_gpio_cfg_sense_input(PIN_USER_BTN, NRF_GPIO_PIN_PULLUP, NRF_GPIO_PIN_SENSE_LOW); + pinMode(PIN_9006_IO1, INPUT_PULLDOWN); + // A held-high IO1 must not immediately wake the board from SYSTEM OFF. + const auto sense = digitalRead(PIN_9006_IO1) ? NRF_GPIO_PIN_SENSE_LOW : NRF_GPIO_PIN_SENSE_HIGH; + nrf_gpio_cfg_sense_input(PIN_9006_IO1, NRF_GPIO_PIN_PULLDOWN, sense); +} diff --git a/variants/meshpocket_v2/MeshPocketV2.h b/variants/meshpocket_v2/MeshPocketV2.h new file mode 100644 index 00000000..0902b729 --- /dev/null +++ b/variants/meshpocket_v2/MeshPocketV2.h @@ -0,0 +1,25 @@ +#pragma once + +#include +#include "PowerBank.h" + +class MeshPocketV2 : public NRF52Board { +public: + MeshPocketV2() : NRF52Board("MeshPocket_V2_OTA") {} + PowerBank powerBank; + void begin() override; + void loop() override { powerBank.poll(); } + uint16_t getBattMilliVolts() override; + bool isChargerActive() override { return powerBank.snapshot().hasChargingInput(); } + bool hasChargerStatus() const override { return true; } + mesh::BoardUiExtension* getUiExtension() override; + bool toggleUsbData(); + bool isUsbDataEnabled() const; + const char* getManufacturerName() const override { return "Heltec MeshPocket V2"; } + void shutdownPeripherals() override; + +private: + class UiExtension; + UiExtension& uiExtension(); + void setUsbDataEnabled(bool enabled); +}; diff --git a/variants/meshpocket_v2/PowerBank.cpp b/variants/meshpocket_v2/PowerBank.cpp new file mode 100644 index 00000000..4cab3726 --- /dev/null +++ b/variants/meshpocket_v2/PowerBank.cpp @@ -0,0 +1,115 @@ +#include "PowerBank.h" + +namespace { +constexpr uint32_t hltPollMs = 100; +constexpr uint32_t hltStatusMs = 500; +constexpr uint32_t hltStaleMs = 3000; +constexpr uint32_t io1WindowMs = 120; +constexpr uint32_t gaugeNormalMs = 3000; +constexpr uint32_t gaugeFastMs = 500; + +// Only the ISR writes this counter. The main loop consumes a single aligned read. +volatile uint32_t io1Pulses = 0; +void onIo1Rise() { + ++io1Pulses; +} + +bool stateChanged(const HLT331Serial::Status& before, const HLT331Serial::Status& after) { + return !before.valid || before.systemWorking != after.systemWorking || + (after.systemWorking && + (before.charging != after.charging || before.c1State != after.c1State || + before.c2State != after.c2State || before.wirelessWork != after.wirelessWork || + before.wirelessFull != after.wirelessFull)); +} +} + +bool PowerBankSnapshot::hltLive() const { + return hlt.valid && hlt.systemWorking && uint32_t(millis() - hlt.lastFrameMs) <= hltStaleMs; +} + +bool PowerBankSnapshot::hasChargingInput() const { + return hltLive() && (hlt.charging || hlt.c1State == HLT331Serial::PORT_CHARGING || + hlt.c2State == HLT331Serial::PORT_CHARGING); +} + +void PowerBank::begin() { + gaugeStarted = gauge.begin(Wire); + if (gaugeStarted) readGauge(); + hltStarted = hlt.begin(Serial2, PIN_SERIAL2_RX, PIN_SERIAL2_TX); + if (hltStarted) { + hlt.configurePins(PIN_CW_INT, PIN_9006_IO1, PIN_9006_IO2, -1); + attachInterrupt(digitalPinToInterrupt(PIN_9006_IO1), onIo1Rise, RISING); + readHlt(); + } + // Capture the boot sample as a baseline before the UI starts. + pageEvent = false; +} + +void PowerBank::updateFault(bool& sourceFault, bool active) { + const bool wasFault = cwFault || hltFault; + sourceFault = active; + if (wasFault != (cwFault || hltFault)) { + pageEvent = true; + fastGaugeReads = 3; + } +} + +void PowerBank::readGauge() { + status.cw.ready = gauge.readStatus(status.cw); + lastGauge = millis(); + if (fastGaugeReads) --fastGaugeReads; + if (status.cw.ready) updateFault(cwFault, !status.cw.profile.matches); +} + +void PowerBank::readHlt() { + const bool valid = hlt.readStatus(status.hlt); + lastHlt = millis(); + if (!valid || status.hlt.ageMs > hltStaleMs) return; + + const auto& sample = status.hlt; + if (sample.systemWorking) updateFault(hltFault, sample.ntcOverTemp || sample.wirelessFod); + if (stateChanged(previous, sample)) { + pageEvent = true; + fastGaugeReads = 3; + } + previous = sample; +} + +void PowerBank::poll() { + const uint32_t now = millis(); + if (hltStarted && now - lastPoll >= hltPollMs) { + lastPoll = now; + hlt.poll(); + } + const uint32_t pulses = io1Pulses; + if (pulses != seenPulses) { + seenPulses = pulses; + drainStarted = now; + draining = true; + fastGaugeReads = 3; + } + if (draining && now - drainStarted >= io1WindowMs) { + // Collect any bytes received since the regular UART poll. + hlt.poll(); + readHlt(); + pageEvent = true; + draining = false; + } else if (hltStarted && !draining && now - lastHlt >= hltStatusMs) { + readHlt(); + } + const uint32_t interval = fastGaugeReads ? gaugeFastMs : gaugeNormalMs; + if (gaugeStarted && now - lastGauge >= interval) readGauge(); +} + +bool PowerBank::takePageEvent() { + const bool pending = pageEvent; + pageEvent = false; + return pending; +} + +void PowerBank::end() { + if (hltStarted) { + detachInterrupt(digitalPinToInterrupt(PIN_9006_IO1)); + Serial2.end(); + } +} diff --git a/variants/meshpocket_v2/PowerBank.h b/variants/meshpocket_v2/PowerBank.h new file mode 100644 index 00000000..dbb7de8b --- /dev/null +++ b/variants/meshpocket_v2/PowerBank.h @@ -0,0 +1,43 @@ +#pragma once + +#include +#include + +struct PowerBankSnapshot { + CW221X::Status cw{}; + HLT331Serial::Status hlt{}; + + bool hltLive() const; + bool hasChargingInput() const; +}; + +class PowerBank { +public: + void begin(); + void poll(); + void end(); + const PowerBankSnapshot& snapshot() const { return status; } + bool takePageEvent(); + +private: + void readGauge(); + void readHlt(); + void updateFault(bool& sourceFault, bool active); + + CW221X gauge; + HLT331Serial hlt; + PowerBankSnapshot status; + HLT331Serial::Status previous{}; + bool gaugeStarted = false; + bool hltStarted = false; + bool cwFault = false; + bool hltFault = false; + bool pageEvent = false; + bool draining = false; + uint8_t fastGaugeReads = 0; + uint32_t seenPulses = 0; + uint32_t drainStarted = 0; + uint32_t lastPoll = 0; + uint32_t lastHlt = 0; + uint32_t lastGauge = 0; +}; diff --git a/variants/meshpocket_v2/PowerBankPage.cpp b/variants/meshpocket_v2/PowerBankPage.cpp new file mode 100644 index 00000000..ac57df6d --- /dev/null +++ b/variants/meshpocket_v2/PowerBankPage.cpp @@ -0,0 +1,334 @@ +#include "PowerBankPage.h" +#include "PowerBank.h" + +namespace { +constexpr ColorVal background = 0x0063; +constexpr ColorVal blue = 0x653d; +constexpr ColorVal purple = 0x611f; +constexpr ColorVal card = 0xdefc; +constexpr ColorVal dark = 0x31c8; +constexpr ColorVal white = 0xffff; +constexpr ColorVal green = 0x06ae; +constexpr ColorVal gold = 0xff0e; +constexpr ColorVal red = 0xfa69; +constexpr ColorVal off = 0x3a6b; +constexpr ColorVal well = 0x1127, shine = 0x47d5, track = 0x94b8; +constexpr ColorVal badgeFace = 0xffbf, tempFace = 0xf776, tempInk = 0xa465; +constexpr ColorVal divider = 0x9515, lightDivider = 0xd71e, boltInk = 0x93ba; +constexpr int temperatureCenterX = 134; + +void label(DisplayDriver& d, int x, int y, const char* value, ColorVal ink, int size = 1) { + d.setColor(ink); + d.setTextSize(size); + d.setCursor(x, y); + d.print(value); +} + +void panel(DisplayDriver& d, int x, int y, int w, int h, ColorVal color, int r = 6) { + d.setColor(color); + if (h > 2 * r) d.fillRect(x, y + r, w, h - 2 * r); + int span = 0; + for (int row = 0; row < r; ++row) { + int dy = r - row; + while ((span + 1) * (span + 1) + dy * dy <= r * (r + 1)) ++span; + int inset = r - span; + d.fillRect(x + inset, y + row, w - 2 * inset, 1); + d.fillRect(x + inset, y + h - 1 - row, w - 2 * inset, 1); + } +} + +void drawPortCard(DisplayDriver& d, int x, const char* name) { + panel(d, x, 72, 70, 54, card); + label(d, x + 5, 78, name, dark, 2); + d.setColor(divider); + d.fillRect(x + 5, 97, 60, 1); +} + +void drawUsbConnector(DisplayDriver& d, int x, ColorVal ink) { + panel(d, x + 33, 82, 25, 10, ink, 4); + panel(d, x + 34, 83, 23, 8, card, 3); + d.setColor(ink); + d.fillRect(x + 38, 87, 15, 1); +} + +void drawUsbCard(DisplayDriver& d, int x, const char* name) { + drawPortCard(d, x, name); + drawUsbConnector(d, x, dark); +} + +void drawLayout(DisplayDriver& d) { + d.startFrame(background); + panel(d, 2, 2, 164, 66, blue); + label(d, 8, 10, "Battery", white); + panel(d, 89, 23, 4, 9, white, 1); + panel(d, 49, 16, 40, 23, white, 4); + panel(d, 50, 17, 38, 21, well, 3); + d.setColor(white); + d.fillRect(8, 50, 85, 8); + d.setColor(track); + d.fillRect(9, 51, 83, 6); + d.setColor(white); + for (int i = 1; i < 10; ++i) d.fillRect(9 + i * 83 / 10, 51, 1, 6); + d.setColor(lightDivider); + d.fillRect(8, 44, 85, 1); + d.fillRect(101, 9, 1, 51); + panel(d, temperatureCenterX - 11, 13, 23, 23, badgeFace, 11); + panel(d, temperatureCenterX - 8, 16, 17, 17, tempFace, 8); + label(d, temperatureCenterX - 2, 21, "T", tempInk); + panel(d, 169, 2, 49, 66, purple); + panel(d, 182, 13, 23, 23, badgeFace, 11); + drawUsbCard(d, 2, "C1"); + drawUsbCard(d, 75, "C2"); + drawPortCard(d, 148, "Qi2"); + label(d, 154, 103, "FOD:", dark); +} + +bool connected(uint8_t port) { + return port == HLT331Serial::PORT_CHARGING || port == HLT331Serial::PORT_DISCHARGING; +} + +// Write only the changed span inside each segment, skipping the white dividers. +void updateBar(DisplayDriver& d, int x, int y, int w, int h, int before, int after, + ColorVal filled, ColorVal empty, int segments = 1) { + int oldWidth = before > 0 ? (w * before + 50) / 100 : 0; + int newWidth = after > 0 ? (w * after + 50) / 100 : 0; + if (oldWidth == newWidth) return; + d.setColor(newWidth > oldWidth ? filled : empty); + for (int i = 0; i < segments; ++i) { + int left = max(min(oldWidth, newWidth), i * w / segments + (i != 0)); + int right = min(max(oldWidth, newWidth), (i + 1) * w / segments); + if (left < right) d.fillRect(x + left, y, right - left, h); + } +} + +void clearField(DisplayDriver& d, int x, int y, int w, int h, ColorVal color) { + d.setColor(color); + d.fillRect(x, y, w, h); +} + +void drawTemperature(DisplayDriver& d, const char* value) { + const bool hasPoint = strchr(value, '.') != nullptr; + const int glyphs = strlen(value) - hasPoint; + const int size = glyphs <= 3 ? 2 : 1; // Leave room for the unit on longer readings. + const int advance = 5 * size + 1; + const int width = glyphs * advance + (hasPoint ? 3 : 0); + int x = temperatureCenterX - (width - 1) / 2; + + clearField(d, 102, 43, 64, 14, blue); + d.setColor(white); + d.setTextSize(size); + for (const char* p = value; *p; ++p) { + if (*p == '.') { + d.fillRect(x, 55, 2, 2); + x += 3; + } else { + char glyph[] = {*p, '\0'}; + d.setCursor(x, 57 - 7 * size); + d.print(glyph); + x += advance; + } + } + d.drawRect(x + 1, 49, 3, 3); + label(d, x + 5, 50, "C", white); +} + +void drawPowerRays(DisplayDriver& d, ColorVal ink) { + d.setColor(ink); + d.fillRect(193, 7, 1, 4); + d.fillRect(193, 38, 1, 4); + d.fillRect(176, 24, 4, 1); + d.fillRect(207, 24, 4, 1); + for (int offset = 10; offset <= 12; ++offset) { + d.fillRect(193 - offset, 24 - offset, 1, 1); + d.fillRect(193 + offset, 24 - offset, 1, 1); + d.fillRect(193 - offset, 24 + offset, 1, 1); + d.fillRect(193 + offset, 24 + offset, 1, 1); + } +} + +void drawWatts(DisplayDriver& d, int32_t wattsX10) { + char value[16] = "--"; + if (wattsX10 >= 0) { + snprintf(value, sizeof(value), "%ld.%ld", long(wattsX10 / 10), long(wattsX10 % 10)); + } + clearField(d, 170, 43, 47, 14, purple); + if (wattsX10 >= 1000) { // Three integer digits only fit in the small font. + d.setTextSize(1); + int digits = d.getTextWidth(value); + int x = 193 - (digits + 7) / 2; + label(d, x, 50, value, white); + label(d, x + digits + 1, 50, "W", white); + return; + } + // Budget 11 pixels per digit, 3 for the decimal point and 7 for the unit. + int width = 7; + for (const char* p = value; *p; ++p) width += (*p == '.') ? 3 : 11; + int x = 193 - width / 2; + d.setColor(white); + d.setTextSize(2); + for (const char* p = value; *p; ++p) { + if (*p == '.') { + d.fillRect(x, 55, 2, 2); + x += 3; + } else { + char digit[] = {*p, '\0'}; + d.setCursor(x, 43); + d.print(digit); + x += 11; + } + } + label(d, x + 1, 50, "W", white); +} +} + +void PowerBankPage::drawUsb(DisplayDriver& d, int x, UsbPort& last, uint8_t state, uint8_t mode, bool shared, bool force) { + if (!painted || force || state != last.state) { + const char* name = "--"; + ColorVal badge = off; + switch (state) { + case HLT331Serial::PORT_NOT_CONNECTED: name = "OFF"; break; + case HLT331Serial::PORT_CHARGING: name = "CHG"; badge = green; break; + case HLT331Serial::PORT_DISCHARGING: name = "DCHG"; badge = gold; break; + } + clearField(d, x + 5, 102, 60, 10, card); + panel(d, x + 6, 102, 28, 10, badge, 5); + d.setTextSize(1); + label(d, x + 21 - d.getTextWidth(name) / 2, 104, name, badge == off ? white : dark); + last.state = state; + } + char protocol[sizeof(last.protocol)] = ""; + if (connected(state) && mode != HLT331Serial::FAST_CHARGE_NONE) { + snprintf(protocol, sizeof(protocol), "%s%s", HLT331Serial::fastChargeName(mode), shared ? "*" : ""); + } + if (!painted || force || strcmp(last.protocol, protocol) != 0) { + clearField(d, x + 6, 116, 63, 7, card); + label(d, x + 6, 116, protocol, dark); + strcpy(last.protocol, protocol); + } +} + +void PowerBankPage::drawUsbDataMode(DisplayDriver& d, int x) { + drawUsbConnector(d, x, blue); + + clearField(d, x + 5, 102, 60, 10, card); + panel(d, x + 21, 102, 28, 10, blue, 5); + d.setTextSize(1); + const char* badge = "USB"; + label(d, x + 35 - d.getTextWidth(badge) / 2, 104, badge, white); + + clearField(d, x + 6, 116, 63, 7, card); + const char* blocked = "CHG/DCHG"; + const int width = d.getTextWidth(blocked); + const int textX = x + 35 - width / 2; + label(d, textX, 116, blocked, dark); + d.setColor(red); + const int dischargeX = textX + d.getTextWidth("CHG/"); + d.fillRect(dischargeX, 119, d.getTextWidth("DCHG"), 1); +} + +void PowerBankPage::drawBattery(DisplayDriver& d, const PowerBankSnapshot& status) { + const auto& cw = status.cw; + const int nextPercent = cw.ready ? min(100, int(cw.socPercent)) : -1; + char value[16]; + if (!painted || percent != nextPercent) { + if (nextPercent < 0) strcpy(value, "--"); + else snprintf(value, sizeof(value), "%d", nextPercent); + clearField(d, 8, 25, 41, 14, blue); + label(d, 8, 25, value, white, 2); + label(d, min(43, 10 + d.getTextWidth(value)), 31, "%", white); + int before = painted ? percent : 0; + updateBar(d, 52, 19, 34, 7, before, nextPercent, shine, well); + updateBar(d, 52, 26, 34, 10, before, nextPercent, green, well); + updateBar(d, 9, 51, 83, 6, before, nextPercent, green, track, 10); + percent = nextPercent; + } + const int32_t nextTemp = cw.ready ? cw.temperatureX10C : INT32_MIN; + if (!painted || nextTemp != temperature) { + if (!cw.ready) strcpy(value, "--"); + else { + const int temp = cw.temperatureX10C; + snprintf(value, sizeof(value), "%s%d.%d", temp < 0 ? "-" : "", abs(temp) / 10, abs(temp) % 10); + } + drawTemperature(d, value); + temperature = nextTemp; + } +} + +void PowerBankPage::drawPower(DisplayDriver& d, const PowerBankSnapshot& status, bool live) { + const auto& hlt = status.hlt; + const bool active = live && (hlt.charging || connected(hlt.c1State) || connected(hlt.c2State) || hlt.wirelessWork); + if (!painted || active != boltActive) { + static const uint8_t bolt[] = {0x0c, 0x18, 0x30, 0x7e, 0x0c, 0x18, 0x30}; + drawPowerRays(d, active ? badgeFace : purple); + d.setColor(active ? dark : boltInk); + d.drawXbm(190, 21, bolt, 8, 7); + boltActive = active; + } + const int32_t nextWatts = live ? int32_t(uint32_t(hlt.busMv) * hlt.busMa / 100000) : -1; + if (!painted || nextWatts != wattsX10) { + drawWatts(d, nextWatts); + wattsX10 = nextWatts; + } +} + +void PowerBankPage::drawWireless(DisplayDriver& d, const PowerBankSnapshot& status, bool live) { + const auto& hlt = status.hlt; + const char* state = "--"; + if (live) { + if (hlt.wirelessFod) state = "FOD!"; + else state = hlt.wirelessWork ? "ON" : "OFF"; + } + if (!painted || strcmp(state, qiState) != 0) { + const bool fault = live && hlt.wirelessFod; + const bool on = live && hlt.wirelessWork; + ColorVal fill = fault ? red : off; + if (on && !fault) fill = green; + panel(d, 188, 82, 28, 11, fill, 5); + if (fault) { + label(d, 190, 84, state, dark); + } else { + panel(d, on ? 207 : 190, 84, 7, 7, white, 3); + label(d, on ? 191 : 197, 84, state, on ? dark : white); + } + qiState = state; + } + const int nextFod = live ? int(hlt.wirelessFod) : -1; + if (!painted || nextFod != fod) { + ColorVal fill = off; + if (live) fill = hlt.wirelessFod ? red : gold; + panel(d, 182, 102, 13, 10, fill, 4); + const char* value = "--"; + if (live) value = hlt.wirelessFod ? "1" : "0"; + label(d, live ? 186 : 183, 104, value, live ? dark : white); + fod = nextFod; + } + const char* protocol = ""; + if (live && hlt.wirelessWork && hlt.wirelessProtocol != HLT331Serial::WIRELESS_NULL) { + protocol = HLT331Serial::wirelessProtocolName(hlt.wirelessProtocol); + } + if (!painted || strcmp(protocol, qiProtocol) != 0) { + clearField(d, 154, 116, 63, 7, card); + label(d, 154, 116, protocol, dark); + snprintf(qiProtocol, sizeof(qiProtocol), "%s", protocol); + } +} + +void PowerBankPage::draw(DisplayDriver& d, const PowerBankSnapshot& status, bool usbDataEnabled) { + if (!painted) drawLayout(d); + const auto& hlt = status.hlt; + const bool live = status.hltLive(); + const bool shared = !usbDataEnabled && connected(hlt.c1State) && connected(hlt.c2State); + const bool usbModeChanged = !painted || usbDataMode != usbDataEnabled; + drawBattery(d, status); + drawPower(d, status, live); + drawUsb(d, 2, c1, live ? hlt.c1State : HLT331Serial::PORT_RESERVED, hlt.fastCharge, shared); + if (usbDataEnabled) { + if (usbModeChanged) drawUsbDataMode(d, 75); + } else { + if (usbModeChanged) drawUsbConnector(d, 75, dark); + drawUsb(d, 75, c2, live ? hlt.c2State : HLT331Serial::PORT_RESERVED, hlt.fastCharge, shared, usbModeChanged); + } + drawWireless(d, status, live); + usbDataMode = usbDataEnabled; + painted = true; +} diff --git a/variants/meshpocket_v2/PowerBankPage.h b/variants/meshpocket_v2/PowerBankPage.h new file mode 100644 index 00000000..2c5ea3be --- /dev/null +++ b/variants/meshpocket_v2/PowerBankPage.h @@ -0,0 +1,34 @@ +#pragma once + +#include + +struct PowerBankSnapshot; + +class PowerBankPage { +public: + void invalidate() { painted = false; } + void draw(DisplayDriver& display, const PowerBankSnapshot& status, bool usbDataEnabled); + +private: + struct UsbPort { + uint8_t state = 0; + char protocol[16]{}; + }; + + void drawBattery(DisplayDriver& d, const PowerBankSnapshot& status); + void drawPower(DisplayDriver& d, const PowerBankSnapshot& status, bool live); + void drawUsb(DisplayDriver& d, int x, UsbPort& last, uint8_t state, uint8_t mode, bool shared, bool force = false); + void drawUsbDataMode(DisplayDriver& d, int x); + void drawWireless(DisplayDriver& d, const PowerBankSnapshot& status, bool live); + + bool painted = false; + int percent = -1; + int32_t temperature = 0; + int32_t wattsX10 = -1; + bool boltActive = false; + bool usbDataMode = false; + UsbPort c1, c2; + const char* qiState = ""; + int fod = -1; + char qiProtocol[16]{}; +}; diff --git a/variants/meshpocket_v2/platformio.ini b/variants/meshpocket_v2/platformio.ini new file mode 100644 index 00000000..54fcb9b3 --- /dev/null +++ b/variants/meshpocket_v2/platformio.ini @@ -0,0 +1,79 @@ +[meshpocket_v2] +extends = nrf52_base +board = meshpocket_v2 +board_build.ldscript = boards/nrf52840_s140_v6_extrafs.ld +board_upload.maximum_size = 712704 +build_flags = ${nrf52_base.build_flags} + -I variants/meshpocket_v2 + -I src/helpers/nrf52 + -I lib/nrf52/s140_nrf52_6.1.1_API/include + -I lib/nrf52/s140_nrf52_6.1.1_API/include/nrf52 + -D HELTEC_MESH_POCKET_V2 + -D RADIO_CLASS=CustomSX1262 + -D WRAPPER_CLASS=CustomSX1262Wrapper + -D LORA_TX_POWER=22 + -D SX126X_CURRENT_LIMIT=140 + -D SX126X_RX_BOOSTED_GAIN=1 + -D DISPLAY_CLASS=NV3001BDisplay + -D ENV_INCLUDE_GPS=1 + -D DISABLE_DIAGNOSTIC_OUTPUT +build_src_filter = ${nrf52_base.build_src_filter} + +<../variants/meshpocket_v2/*.cpp> + + + + +lib_deps = ${nrf52_base.lib_deps} + https://github.com/Quency-D/heltec-meshpocket-v2-power/releases/download/v0.2.0/HeltecMeshPocketV2Power-0.2.0.zip + stevemarple/MicroNMEA @ ^2.0.6 + bakercp/CRC32 @ ^2.0.0 +debug_tool = jlink +upload_protocol = nrfutil + +[meshpocket_v2_companion] +extends = meshpocket_v2 +build_flags = ${meshpocket_v2.build_flags} + -I examples/companion_radio/ui-new + -D MAX_CONTACTS=350 + -D MAX_GROUP_CHANNELS=40 +build_src_filter = ${meshpocket_v2.build_src_filter} + +<../examples/companion_radio/*.cpp> + +<../examples/companion_radio/ui-new/*.cpp> +lib_deps = ${meshpocket_v2.lib_deps} + densaugeo/base64 @ ~1.4.0 + +[env:meshpocket_v2_companion_radio_ble] +extends = meshpocket_v2_companion +build_flags = ${meshpocket_v2_companion.build_flags} + -D BLE_PIN_CODE=123456 + -D OFFLINE_QUEUE_SIZE=256 +build_src_filter = ${meshpocket_v2_companion.build_src_filter} + + + +[env:meshpocket_v2_companion_radio_usb] +extends = meshpocket_v2_companion +build_flags = ${meshpocket_v2_companion.build_flags} + -D ENABLE_USB_INTERFACE + -D MESHPOCKET_V2_USB_SWITCHABLE + +[env:meshpocket_v2_repeater] +extends = meshpocket_v2 +build_flags = ${meshpocket_v2.build_flags} + -D MESHPOCKET_V2_USB_SWITCHABLE + -D ADVERT_NAME='"MeshPocket V2 Repeater"' + -D ADVERT_LAT=0.0 + -D ADVERT_LON=0.0 + -D ADMIN_PASSWORD='"password"' + -D MAX_NEIGHBOURS=50 +build_src_filter = ${meshpocket_v2.build_src_filter} + +<../examples/simple_repeater> + +[env:meshpocket_v2_room_server] +extends = meshpocket_v2 +build_flags = ${meshpocket_v2.build_flags} + -D MESHPOCKET_V2_USB_SWITCHABLE + -D ADVERT_NAME='"MeshPocket V2 Room"' + -D ADVERT_LAT=0.0 + -D ADVERT_LON=0.0 + -D ADMIN_PASSWORD='"password"' + -D ROOM_PASSWORD='"hello"' +build_src_filter = ${meshpocket_v2.build_src_filter} + +<../examples/simple_room_server> diff --git a/variants/meshpocket_v2/target.cpp b/variants/meshpocket_v2/target.cpp new file mode 100644 index 00000000..3ffb2c1f --- /dev/null +++ b/variants/meshpocket_v2/target.cpp @@ -0,0 +1,20 @@ +#include "target.h" +#include + +MeshPocketV2 board; +RADIO_CLASS radio = new Module(P_LORA_NSS, P_LORA_DIO_1, P_LORA_RESET, P_LORA_BUSY, SPI); +WRAPPER_CLASS radio_driver(radio, board); +VolatileRTCClock rtc_clock; +MicroNMEALocationProvider gps(Serial1, &rtc_clock); +EnvironmentSensorManager sensors(gps); +DISPLAY_CLASS display(SPI1); +MomentaryButton user_btn(PIN_USER_BTN, 1000, true, true); + +bool radio_init() { + return radio.std_init(&SPI); +} + +mesh::LocalIdentity radio_new_identity() { + RadioNoiseListener rng(radio); + return mesh::LocalIdentity(&rng); +} diff --git a/variants/meshpocket_v2/target.h b/variants/meshpocket_v2/target.h new file mode 100644 index 00000000..9cab738c --- /dev/null +++ b/variants/meshpocket_v2/target.h @@ -0,0 +1,18 @@ +#pragma once + +#include +#include +#include +#include +#include +#include "MeshPocketV2.h" + +extern MeshPocketV2 board; +extern WRAPPER_CLASS radio_driver; +extern VolatileRTCClock rtc_clock; +extern EnvironmentSensorManager sensors; +extern DISPLAY_CLASS display; +extern MomentaryButton user_btn; + +bool radio_init(); +mesh::LocalIdentity radio_new_identity(); diff --git a/variants/meshpocket_v2/variant.cpp b/variants/meshpocket_v2/variant.cpp new file mode 100644 index 00000000..397ad3ca --- /dev/null +++ b/variants/meshpocket_v2/variant.cpp @@ -0,0 +1,13 @@ +#include + +const uint32_t g_ADigitalPinMap[] = { + 0xff, 0xff, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, + 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47 +}; + +void initVariant() { + // Preload the output latch before driving the USB data switch. + digitalWrite(PIN_IO_CSA, LOW); + pinMode(PIN_IO_CSA, OUTPUT); +} diff --git a/variants/meshpocket_v2/variant.h b/variants/meshpocket_v2/variant.h new file mode 100644 index 00000000..7ff1fd28 --- /dev/null +++ b/variants/meshpocket_v2/variant.h @@ -0,0 +1,68 @@ +#pragma once + +#include "WVariant.h" + +#define USE_LFXO +#define VARIANT_MCK 64000000ul +#define PINS_COUNT 48 +#define NUM_DIGITAL_PINS 48 +#define NUM_ANALOG_INPUTS 0 +#define NUM_ANALOG_OUTPUTS 0 +#define PIN_LED1 (-1) +#define LED_BUILTIN PIN_LED1 +#define LED_BLUE (-1) +#define LED_GREEN (-1) +#define LED_STATE_ON 1 +#define PIN_USER_BTN 43 +#define PIN_BUTTON2 42 + +#define WIRE_INTERFACES_COUNT 1 +#define PIN_WIRE_SDA 13 +#define PIN_WIRE_SCL 5 +#define PIN_CW_INT 12 +#define PIN_IO_CSA 20 +#define PIN_9006_IO1 4 +#define PIN_9006_IO2 41 +#define PIN_SERIAL2_RX 26 +#define PIN_SERIAL2_TX 15 + +// EnvironmentSensorManager names the UART pins from the GPS module's side. +#define PIN_GPS_TX 34 +#define PIN_GPS_RX 36 +#define PIN_SERIAL1_RX PIN_GPS_TX +#define PIN_SERIAL1_TX PIN_GPS_RX +#define PIN_GPS_EN 22 +#define PIN_GPS_EN_ACTIVE LOW +#define PIN_GPS_RESET 38 +#define PIN_GPS_RESET_ACTIVE LOW +#define PIN_GPS_PPS 10 +#define GPS_BAUD_RATE 115200 + +#define SPI_INTERFACES_COUNT 2 +#define PIN_SPI_MISO 2 +#define PIN_SPI_MOSI 47 +#define PIN_SPI_SCK 45 +#define P_LORA_MISO PIN_SPI_MISO +#define P_LORA_MOSI PIN_SPI_MOSI +#define P_LORA_SCLK PIN_SPI_SCK +#define P_LORA_NSS 14 +#define P_LORA_DIO_1 31 +#define P_LORA_BUSY 29 +#define P_LORA_RESET 11 +#define SX126X_DIO2_AS_RF_SWITCH true +#define SX126X_DIO3_TCXO_VOLTAGE 1.8f + +#define PIN_SPI1_MISO 3 +#define PIN_SPI1_MOSI 39 +#define PIN_SPI1_SCK 33 +#define PIN_TFT_SDA PIN_SPI1_MOSI +#define PIN_TFT_SCL PIN_SPI1_SCK +#define PIN_TFT_CS 16 +#define PIN_TFT_DC 32 +#define PIN_TFT_RST 24 +#define PIN_TFT_EN 9 +#define PIN_TFT_EN_ACTIVE LOW +#define PIN_TFT_BL 25 +#define PIN_TFT_BL_ACTIVE HIGH +#define SPI_FREQUENCY 4000000 +#define DISPLAY_ROTATION 3 // NV3001B MADCTL MX | MV