diff --git a/boards/heltec_meshpocket_v2.json b/boards/heltec_meshpocket_v2.json new file mode 100644 index 00000000..169d1ef7 --- /dev/null +++ b/boards/heltec_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": "heltec_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/src/helpers/ui/DisplayDriver.h b/src/helpers/ui/DisplayDriver.h index 2fd22977..7f544faf 100644 --- a/src/helpers/ui/DisplayDriver.h +++ b/src/helpers/ui/DisplayDriver.h @@ -15,6 +15,7 @@ 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 diff --git a/src/helpers/ui/NV3001BDisplay.cpp b/src/helpers/ui/NV3001BDisplay.cpp index 3b7072e5..da2865e3 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. + 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(); } @@ -462,6 +485,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(); @@ -550,7 +576,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 338d1954..12f8d091 100644 --- a/src/helpers/ui/NV3001BDisplay.h +++ b/src/helpers/ui/NV3001BDisplay.h @@ -34,6 +34,13 @@ class NV3001BDisplay : public DisplayDriver { 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); @@ -59,6 +66,7 @@ public: #endif bool begin(); + void setNativePixels(bool enabled); 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/heltec_meshpocket_v2/HeltecMeshPocketV2Board.cpp b/variants/heltec_meshpocket_v2/HeltecMeshPocketV2Board.cpp new file mode 100644 index 00000000..bba0c606 --- /dev/null +++ b/variants/heltec_meshpocket_v2/HeltecMeshPocketV2Board.cpp @@ -0,0 +1,39 @@ +#include "HeltecMeshPocketV2Board.h" +#include + +void HeltecMeshPocketV2Board::begin() { + NRF52Board::begin(); + powerBank.begin(); + pinMode(PIN_USER_BTN, INPUT_PULLUP); +} + +uint16_t HeltecMeshPocketV2Board::getBattMilliVolts() { + const auto& status = powerBank.snapshot(); + if (status.cw.ready) return status.cw.voltageMv; + return status.hltLive() ? status.hlt.batteryMv : 0; +} + +void HeltecMeshPocketV2Board::setUsbDataEnabled(bool enabled) { + digitalWrite(PIN_IO_CSA, enabled ? HIGH : LOW); +} + +bool HeltecMeshPocketV2Board::toggleUsbData() { + const bool enabled = !isUsbDataEnabled(); + setUsbDataEnabled(enabled); + return enabled; +} + +bool HeltecMeshPocketV2Board::isUsbDataEnabled() const { + return digitalRead(PIN_IO_CSA) == HIGH; +} + +void HeltecMeshPocketV2Board::shutdownPeripherals() { + NRF52Board::shutdownPeripherals(); + powerBank.end(); + setUsbDataEnabled(false); + 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/heltec_meshpocket_v2/HeltecMeshPocketV2Board.h b/variants/heltec_meshpocket_v2/HeltecMeshPocketV2Board.h new file mode 100644 index 00000000..34fb8c34 --- /dev/null +++ b/variants/heltec_meshpocket_v2/HeltecMeshPocketV2Board.h @@ -0,0 +1,21 @@ +#pragma once + +#include +#include "PowerBank.h" + +class HeltecMeshPocketV2Board : public NRF52Board { +public: + HeltecMeshPocketV2Board() : 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 toggleUsbData(); + bool isUsbDataEnabled() const; + const char* getManufacturerName() const override { return "Heltec MeshPocket V2"; } + void shutdownPeripherals() override; + +private: + void setUsbDataEnabled(bool enabled); +}; diff --git a/variants/heltec_meshpocket_v2/PowerBank.cpp b/variants/heltec_meshpocket_v2/PowerBank.cpp new file mode 100644 index 00000000..4cab3726 --- /dev/null +++ b/variants/heltec_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/heltec_meshpocket_v2/PowerBank.h b/variants/heltec_meshpocket_v2/PowerBank.h new file mode 100644 index 00000000..dbb7de8b --- /dev/null +++ b/variants/heltec_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/heltec_meshpocket_v2/PowerBankPage.cpp b/variants/heltec_meshpocket_v2/PowerBankPage.cpp new file mode 100644 index 00000000..ac57df6d --- /dev/null +++ b/variants/heltec_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/heltec_meshpocket_v2/PowerBankPage.h b/variants/heltec_meshpocket_v2/PowerBankPage.h new file mode 100644 index 00000000..2c5ea3be --- /dev/null +++ b/variants/heltec_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/heltec_meshpocket_v2/PowerBankUi.cpp b/variants/heltec_meshpocket_v2/PowerBankUi.cpp new file mode 100644 index 00000000..72565232 --- /dev/null +++ b/variants/heltec_meshpocket_v2/PowerBankUi.cpp @@ -0,0 +1,35 @@ +#include "PowerBankUi.h" +#include "HeltecMeshPocketV2Board.h" +#include + +PowerBankUi::PowerBankUi(HeltecMeshPocketV2Board& board) + : board(board), secondaryButton(PIN_BUTTON2, 1000, true, true, false) {} + +void PowerBankUi::begin() { + secondaryButton.begin(); +} + +uint8_t PowerBankUi::pollEvents() { + uint8_t events = 0; + const int buttonEvent = secondaryButton.check(); + if (buttonEvent == BUTTON_EVENT_CLICK) events |= EVENT_SHOW_PAGE; +#ifdef MESHPOCKET_V2_USB_SWITCHABLE + if (buttonEvent == BUTTON_EVENT_LONG_PRESS) events |= EVENT_PAGE_ACTION; +#endif + if (board.powerBank.takePageEvent()) events |= EVENT_REQUEST_FOCUS; + return events; +} + +void PowerBankUi::handlePageAction() { +#ifdef MESHPOCKET_V2_USB_SWITCHABLE + board.toggleUsbData(); +#endif +} + +uint32_t PowerBankUi::render(NV3001BDisplay& display, bool fullRefresh) { + if (fullRefresh) page.invalidate(); + display.setNativePixels(true); + page.draw(display, board.powerBank.snapshot(), board.isUsbDataEnabled()); + display.setNativePixels(false); + return 500; +} diff --git a/variants/heltec_meshpocket_v2/PowerBankUi.h b/variants/heltec_meshpocket_v2/PowerBankUi.h new file mode 100644 index 00000000..91ad98de --- /dev/null +++ b/variants/heltec_meshpocket_v2/PowerBankUi.h @@ -0,0 +1,26 @@ +#pragma once + +#include +#include "PowerBankPage.h" + +class HeltecMeshPocketV2Board; +class NV3001BDisplay; + +class PowerBankUi { + HeltecMeshPocketV2Board& board; + PowerBankPage page; + MomentaryButton secondaryButton; + +public: + enum Event : uint8_t { + EVENT_SHOW_PAGE = 1 << 0, + EVENT_PAGE_ACTION = 1 << 1, + EVENT_REQUEST_FOCUS = 1 << 2, + }; + + explicit PowerBankUi(HeltecMeshPocketV2Board& board); + void begin(); + uint8_t pollEvents(); + void handlePageAction(); + uint32_t render(NV3001BDisplay& display, bool fullRefresh); +}; diff --git a/variants/heltec_meshpocket_v2/platformio.ini b/variants/heltec_meshpocket_v2/platformio.ini new file mode 100644 index 00000000..551343c4 --- /dev/null +++ b/variants/heltec_meshpocket_v2/platformio.ini @@ -0,0 +1,87 @@ +[heltec_meshpocket_v2] +extends = nrf52_base +board = heltec_meshpocket_v2 +board_build.ldscript = boards/nrf52840_s140_v6_extrafs.ld +board_upload.maximum_size = 712704 +build_flags = ${nrf52_base.build_flags} + -I variants/heltec_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/heltec_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 + +[heltec_meshpocket_v2_companion] +extends = heltec_meshpocket_v2 +build_flags = ${heltec_meshpocket_v2.build_flags} + -I variants/heltec_meshpocket_v2/ui-companion + -D MAX_CONTACTS=350 + -D MAX_GROUP_CHANNELS=40 +build_src_filter = ${heltec_meshpocket_v2.build_src_filter} + +<../examples/companion_radio/*.cpp> + +<../variants/heltec_meshpocket_v2/ui-companion/*.cpp> +lib_deps = ${heltec_meshpocket_v2.lib_deps} + densaugeo/base64 @ ~1.4.0 + +[env:heltec_meshpocket_v2_companion_radio_ble] +extends = heltec_meshpocket_v2_companion +build_flags = ${heltec_meshpocket_v2_companion.build_flags} + -D BLE_PIN_CODE=123456 + -D OFFLINE_QUEUE_SIZE=256 +build_src_filter = ${heltec_meshpocket_v2_companion.build_src_filter} + + + +[env:heltec_meshpocket_v2_companion_radio_usb] +extends = heltec_meshpocket_v2_companion +build_flags = ${heltec_meshpocket_v2_companion.build_flags} + -D ENABLE_USB_INTERFACE + -D MESHPOCKET_V2_USB_SWITCHABLE + +[heltec_meshpocket_v2_server] +extends = heltec_meshpocket_v2 +build_flags = ${heltec_meshpocket_v2.build_flags} + -I variants/heltec_meshpocket_v2/ui-server + -D MESHPOCKET_V2_USB_SWITCHABLE +build_src_filter = ${heltec_meshpocket_v2.build_src_filter} + + + +<../variants/heltec_meshpocket_v2/ui-server/*.cpp> + +[env:heltec_meshpocket_v2_repeater] +extends = heltec_meshpocket_v2_server +build_flags = ${heltec_meshpocket_v2_server.build_flags} + -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 = ${heltec_meshpocket_v2_server.build_src_filter} + +<../examples/simple_repeater> + +[env:heltec_meshpocket_v2_room_server] +extends = heltec_meshpocket_v2_server +build_flags = ${heltec_meshpocket_v2_server.build_flags} + -D MESHPOCKET_V2_ROOM_SERVER + -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 = ${heltec_meshpocket_v2_server.build_src_filter} + +<../examples/simple_room_server> diff --git a/variants/heltec_meshpocket_v2/target.cpp b/variants/heltec_meshpocket_v2/target.cpp new file mode 100644 index 00000000..d2852bbb --- /dev/null +++ b/variants/heltec_meshpocket_v2/target.cpp @@ -0,0 +1,21 @@ +#include "target.h" +#include + +HeltecMeshPocketV2Board 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; +NmeaGpsDriver gps_driver(Serial1); +MicroNMEALocationProvider gps(gps_driver, &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/heltec_meshpocket_v2/target.h b/variants/heltec_meshpocket_v2/target.h new file mode 100644 index 00000000..484c8e01 --- /dev/null +++ b/variants/heltec_meshpocket_v2/target.h @@ -0,0 +1,20 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include "HeltecMeshPocketV2Board.h" + +extern HeltecMeshPocketV2Board board; +extern WRAPPER_CLASS radio_driver; +extern VolatileRTCClock rtc_clock; +extern EnvironmentSensorManager sensors; +extern DISPLAY_CLASS display; +extern MomentaryButton user_btn; +extern UITask ui_task; + +bool radio_init(); +mesh::LocalIdentity radio_new_identity(); diff --git a/variants/heltec_meshpocket_v2/ui-companion/UITask.cpp b/variants/heltec_meshpocket_v2/ui-companion/UITask.cpp new file mode 100644 index 00000000..7683b886 --- /dev/null +++ b/variants/heltec_meshpocket_v2/ui-companion/UITask.cpp @@ -0,0 +1,1355 @@ +// Based on src/helpers/ui/companion-new/UITask.cpp at 88bbae29. +#include "UITask.h" +#include +#include "target.h" +#include +#include +#ifdef ENABLE_WIFI_INTERFACE + #include +#endif + +#ifndef AUTO_OFF_MILLIS + #define AUTO_OFF_MILLIS 15000 // 15 seconds +#endif +#define BOOT_SCREEN_MILLIS 3000 // 3 seconds + +#ifdef PIN_STATUS_LED +#define LED_ON_MILLIS 20 +#define LED_ON_MSG_MILLIS 200 +#define LED_CYCLE_MILLIS 4000 +#endif + +#define LONG_PRESS_MILLIS 1200 + +// Used both for recent adverts and discovered nodes +#ifndef UI_RECENT_LIST_SIZE + #define UI_RECENT_LIST_SIZE 4 +#endif + +#if UI_HAS_JOYSTICK || UI_HAS_ROTARY_INPUT + #define PRESS_LABEL "press Enter" +#else + #define PRESS_LABEL "long press" +#endif + +// Copied from simple_repeater +#define CTL_TYPE_NODE_DISCOVER_REQ 0x80 +#define CTL_TYPE_NODE_DISCOVER_RESP 0x90 + +#include + +class SplashScreen : public UIScreen { + UITask* _task; + unsigned long dismiss_after; + char _version_info[12]; + const char* _build_date; + +public: + SplashScreen(UITask* task, const char* ver, const char* build_date) : _task(task) { + // strip off dash and commit hash by changing dash to null terminator + // e.g: v1.2.3-abcdef -> v1.2.3 + const char *dash = strchr(ver, '-'); + + int len = dash ? dash - ver : strlen(ver); + if (len >= sizeof(_version_info)) len = sizeof(_version_info) - 1; + memcpy(_version_info, ver, len); + _version_info[len] = 0; + + _build_date = build_date; + + dismiss_after = millis() + BOOT_SCREEN_MILLIS; + } + + int render(DisplayDriver& display) override { + // meshcore logo + display.setColor(UIColor::corp_blue); + int logoWidth = 128; + display.drawXbm((display.width() - logoWidth) / 2, 3, meshcore_logo, logoWidth, 13); + + // meshcore website + const char* website = "https://meshcore.io"; + display.setColor(UIColor::primary_txt); + display.setTextSize(1); + uint16_t websiteWidth = display.getTextWidth(website); + display.setCursor((display.width() - websiteWidth) / 2, 22); + display.print(website); + + // version info + display.setColor(UIColor::primary_txt); + display.setTextSize(1); + display.drawTextCentered(display.width()/2, 35, _version_info); + + display.setColor(UIColor::secondary_txt); + display.setTextSize(1); + display.drawTextCentered(display.width()/2, 48, _build_date); + + return 1000; + } + + void poll() override { + if (millis() >= dismiss_after) { + _task->gotoHomeScreen(); + } + } +}; + +#if ENV_INCLUDE_GPS == 1 +// exact period with the largest unit that divides it: "30s", "5m", "2h" +static void formatGpsPeriod(char* buf, size_t size, uint32_t seconds) { + if (seconds % 3600 == 0) { + snprintf(buf, size, "%luh", (unsigned long)(seconds / 3600)); + } else if (seconds % 60 == 0) { + snprintf(buf, size, "%lum", (unsigned long)(seconds / 60)); + } else { + snprintf(buf, size, "%lus", (unsigned long)seconds); + } +} + +// age of the last fix, rounded down to a single unit: "45s", "12m", "3h" +static void formatFixAge(char* buf, size_t size, uint32_t seconds) { + if (seconds < 60) { + snprintf(buf, size, "%lus", (unsigned long)seconds); + } else if (seconds < 3600) { + snprintf(buf, size, "%lum", (unsigned long)(seconds / 60)); + } else { + snprintf(buf, size, "%luh", (unsigned long)(seconds / 3600)); + } +} +#endif + +struct AdvertPath { + char name[32]; + uint32_t recv_timestamp; +}; + +class HomeScreen : public UIScreen { + enum HomePage { + FIRST, + RECENT, + RADIO, +#ifdef BLE_PIN_CODE + BLUETOOTH, +#endif + ADVERT, +#if ENV_INCLUDE_GPS == 1 + GPS, +#endif +#if UI_SENSORS_PAGE == 1 + SENSORS, +#endif +#if UI_DISCOVER_SCREEN + DISCOVERY, +#endif +#ifndef UI_NO_HIBERNATE + SHUTDOWN, +#endif + POWER_BANK, + Count // keep as last + }; + + UITask* _task; + PowerBankUi& powerUi; + mesh::RTCClock* _rtc; + SensorManager* _sensors; + NodePrefs* _node_prefs; + uint8_t _page; + bool _shutdown_init; + bool powerPageFullRefresh; + int recent_next_idx; + AdvertPath recent[UI_RECENT_LIST_SIZE]; +#if UI_DISCOVER_SCREEN + DiscoveredNode discovered[DISCOVERED_NODES_TABLE_SIZE]; // not circular, latest discovered nodes are not kept + uint32_t disc_node_req_tag = 0; + uint32_t disc_nodes_count = 0; + uint32_t discovery_req_time = 0; +#endif + + void renderBatteryIndicator(DisplayDriver& display, uint16_t batteryMilliVolts) { + // Convert millivolts to percentage +#ifndef BATT_MIN_MILLIVOLTS + #define BATT_MIN_MILLIVOLTS 3000 +#endif +#ifndef BATT_MAX_MILLIVOLTS + #define BATT_MAX_MILLIVOLTS 4200 +#endif + const int minMilliVolts = BATT_MIN_MILLIVOLTS; + const int maxMilliVolts = BATT_MAX_MILLIVOLTS; + int batteryPercentage = ((batteryMilliVolts - minMilliVolts) * 100) / (maxMilliVolts - minMilliVolts); + if (batteryPercentage < 0) batteryPercentage = 0; // Clamp to 0% + if (batteryPercentage > 100) batteryPercentage = 100; // Clamp to 100% + + // battery icon + int iconWidth = 24; + int iconHeight = 10; + int iconX = display.width() - iconWidth - 5; // Position the icon near the top-right corner + int iconY = 0; + display.setColor(UIColor::title_txt); + + // battery outline + display.drawRect(iconX, iconY, iconWidth, iconHeight); + + // battery "cap" + display.fillRect(iconX + iconWidth, iconY + (iconHeight / 4), 3, iconHeight / 2); + + // fill the battery based on the percentage + int fillWidth = (batteryPercentage * (iconWidth - 4)) / 100; + display.fillRect(iconX + 2, iconY + 2, fillWidth, iconHeight - 4); + + // while charging, show a bolt (or a plug once full) just left of the battery, + // keeping the fill bar itself clean and uninterrupted + const bool charging = board.isChargerActive(); + 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). + const int BATT_FULL_PCT = 95; + const uint8_t* symbol = (batteryPercentage >= BATT_FULL_PCT) ? plug_icon : charging_icon; + display.setColor(UIColor::title_txt); + display.drawXbm(iconX - 9, iconY + 1, symbol, 8, 8); + } + + // show muted icon if buzzer is muted (shifted further left when the charging + // icon already occupies the slot immediately left of the battery) +#ifdef PIN_BUZZER + if (_task->isBuzzerQuiet()) { + display.setColor(UIColor::warning_txt); + display.drawXbm(iconX - (charging ? 18 : 9), iconY + 1, muted_icon, 8, 8); + } +#endif + } + + CayenneLPP sensors_lpp; + int sensors_nb = 0; + bool sensors_scroll = false; + int sensors_scroll_offset = 0; + int next_sensors_refresh = 0; + + void refresh_sensors() { + if (millis() > next_sensors_refresh) { + sensors_lpp.reset(); + sensors_nb = 0; + sensors_lpp.addVoltage(TELEM_CHANNEL_SELF, (float)board.getBattMilliVolts() / 1000.0f); + sensors.querySensors(0xFF, sensors_lpp); + LPPReader reader (sensors_lpp.getBuffer(), sensors_lpp.getSize()); + uint8_t channel, type; + while(reader.readHeader(channel, type)) { + reader.skipData(type); + sensors_nb ++; + } + sensors_scroll = sensors_nb > UI_RECENT_LIST_SIZE; + if (display.isEink()) // preserve eink displays + next_sensors_refresh = millis() + 60000; // refresh sensor values every 1 min + else + next_sensors_refresh = millis() + 5000; // refresh sensor values every 5 sec + } + } + +public: + HomeScreen(UITask* task, PowerBankUi& powerUi, mesh::RTCClock* rtc, SensorManager* sensors, NodePrefs* node_prefs) + : _task(task), powerUi(powerUi), _rtc(rtc), _sensors(sensors), _node_prefs(node_prefs), _page(0), + _shutdown_init(false), powerPageFullRefresh(true), sensors_lpp(200) + { + memset(recent, 0, sizeof(recent)); + recent_next_idx = 0; + } + + void addToRecents(ContactInfo &contact) { + auto p = &recent[recent_next_idx]; + recent_next_idx = (recent_next_idx + 1) % UI_RECENT_LIST_SIZE; + + strcpy(p->name, contact.name); + p->recv_timestamp = _rtc->getCurrentTime(); + } + +#if UI_DISCOVER_SCREEN + bool sendDiscoverRequest() { + uint8_t cmd_bytes[6]; + cmd_bytes[0] = CTL_TYPE_NODE_DISCOVER_REQ | 1; // DISCOVER_REQ | prefix only + cmd_bytes[1] = 0xFF; // Repeaters + _task->getMesh()->getRNG()->random((uint8_t *) &disc_node_req_tag, 4); // generate random tag + memcpy(&cmd_bytes[2], &disc_node_req_tag, 4); + disc_nodes_count = 0; + mesh::Packet* req = _task->getMesh()->createControlData(cmd_bytes, sizeof(cmd_bytes)); + if (req) { + _task->getMesh()->sendZeroHop(req); + discovery_req_time = millis(); + return true; + } + return false; + } + + void handleDiscoverResponse(const mesh::Packet* packet) { + if (disc_nodes_count < DISCOVERED_NODES_TABLE_SIZE && memcmp(&packet->payload[2], &disc_node_req_tag, 4) == 0) { + auto d = &discovered[disc_nodes_count++]; + memcpy(d->pubkey_prefix, &packet->payload[6], 8); + d->type = packet->payload[0] & 0xF; + d->snr_out = ((int8_t)packet->payload[1]) / 4.0; + d->snr_in = radio_driver.getLastSNR(); + ContactInfo* c = _task->getMesh()->lookupContactByPubKey(&packet->payload[6], 8); + if (c != NULL) { + strncpy(d->name, c->name, 32); + } else { + d->name[0] = 0; + } + } + } +#endif + + void poll() override { + if (_shutdown_init && !_task->isButtonPressed()) { // must wait for USR button to be released + _task->shutdown(); + } + } + + bool isPowerPage() const { return _page == POWER_BANK; } + void invalidatePowerPage() { powerPageFullRefresh = true; } + + bool showPowerPage() { + if (_shutdown_init) return false; +#ifndef UI_NO_HIBERNATE + if (_page == SHUTDOWN) return false; +#endif + if (_page != POWER_BANK) { + _page = POWER_BANK; + powerPageFullRefresh = true; + } + return true; + } + + int render(DisplayDriver& display) override { + if (isPowerPage()) { + const int interval = powerUi.render(::display, powerPageFullRefresh); + powerPageFullRefresh = false; + return interval; + } + display.setColor(UIColor::title_bkg); + display.fillRect(0, 0, display.width(), 12); + char tmp[80]; + // node name + display.setTextSize(1); + display.setColor(UIColor::title_txt); + char filtered_name[sizeof(_node_prefs->node_name)]; + display.translateUTF8ToBlocks(filtered_name, _node_prefs->node_name, sizeof(filtered_name)); + display.setCursor(0, 2); + display.print(filtered_name); + + // battery voltage + renderBatteryIndicator(display, _task->getBattMilliVolts()); + + // curr page indicator + if (UIColor::title_bkg == UIColor::window_bkg) { + display.setColor(UIColor::title_txt); + } else { + 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) { + if (i == _page) { + display.fillRect(x-1, y-1, 4, 4); + } else { + display.fillRect(x, y, 2, 2); + } + } + + if (_page == HomePage::FIRST) { + display.setColor(UIColor::primary_txt); + #ifdef ENABLE_WIFI_INTERFACE + // smaller unread message ui for wifi variants + display.setTextSize(1); + sprintf(tmp, "Unread Msg: %d", _task->getMsgCount()); + display.drawTextCentered(display.width() / 2, 22, tmp); + #else + // larger unread message ui for non wifi variants + display.setTextSize(2); + sprintf(tmp, "MSG: %d", _task->getMsgCount()); + display.drawTextCentered(display.width() / 2, 22, tmp); + #endif + if (_node_prefs->ui_show_clock) { + display.setTextSize(3); + uint32_t now = _rtc->getCurrentTime(); + now += (int32_t)(_node_prefs->tz_offset * 3600); + DateTime dt (now); + sprintf(tmp, "%02d:%02d", dt.hour(), dt.minute()); + display.drawTextCentered(display.width() / 2, 60, tmp); + display.setTextSize(1); + sprintf(tmp, "%02d/%02d/%d", dt.day(), dt.month(), dt.year()); + display.drawTextCentered(display.width() / 2, 80, tmp); + } + #ifdef ENABLE_WIFI_INTERFACE + IPAddress ip = WiFi.localIP(); + snprintf(tmp, sizeof(tmp), "IP: %d.%d.%d.%d", ip[0], ip[1], ip[2], ip[3]); + display.setTextSize(1); + display.drawTextCentered(display.width() / 2, 32, tmp); + #endif + if (_task->hasConnection()) { + display.setColor(UIColor::warning_txt); + display.setTextSize(1); + if (_node_prefs->ui_show_clock) + display.drawTextCentered(display.width() / 2, 110, "< Connected >"); + else + display.drawTextCentered(display.width() / 2, 43, "< Connected >"); + } else if (_task->getBLEPin() != 0) { // BT pin + display.setColor(UIColor::warning_txt); + sprintf(tmp, "Pin:%d", _task->getBLEPin()); + if (_node_prefs->ui_show_clock) { + display.setTextSize(1); + display.drawTextCentered(display.width() / 2, 110, tmp); + } else { + display.setTextSize(2); + display.drawTextCentered(display.width() / 2, 43, tmp); + } + } + } else if (_page == HomePage::RECENT) { + display.setColor(UIColor::primary_txt); + int y = 20; + for (int i = 0, k = recent_next_idx; i < UI_RECENT_LIST_SIZE; i++, y += 11, k = (k + 1) % UI_RECENT_LIST_SIZE) { + auto a = &recent[k]; + if (a->name[0] == 0) continue; // empty slot + int secs = _rtc->getCurrentTime() - a->recv_timestamp; + if (secs < 60) { + sprintf(tmp, "%ds", secs); + } else if (secs < 60*60) { + sprintf(tmp, "%dm", secs / 60); + } else { + sprintf(tmp, "%dh", secs / (60*60)); + } + + int timestamp_width = display.getTextWidth(tmp); + int max_name_width = display.width() - timestamp_width - 1; + + char filtered_recent_name[sizeof(a->name)]; + display.translateUTF8ToBlocks(filtered_recent_name, a->name, sizeof(filtered_recent_name)); + display.drawTextEllipsized(0, y, max_name_width, filtered_recent_name); + display.setCursor(display.width() - timestamp_width - 1, y); + display.print(tmp); + } + } else if (_page == HomePage::RADIO) { + display.setColor(UIColor::primary_txt); + display.setTextSize(1); + // freq / sf + display.setCursor(0, 20); + sprintf(tmp, "FQ: %06.3f SF: %d", _node_prefs->freq, _node_prefs->sf); + display.print(tmp); + + display.setCursor(0, 31); + sprintf(tmp, "BW: %03.2f CR: %d", _node_prefs->bw, _node_prefs->cr); + display.print(tmp); + + // tx power, noise floor + display.setCursor(0, 42); + sprintf(tmp, "TX: %ddBm", _node_prefs->tx_power_dbm); + display.print(tmp); + display.setCursor(0, 53); + sprintf(tmp, "Noise floor: %d", radio_driver.getNoiseFloor()); + display.print(tmp); +#ifdef BLE_PIN_CODE + } else if (_page == HomePage::BLUETOOTH) { + display.setColor(UIColor::corp_blue); + display.drawXbm((display.width() - 32) / 2, 18, + _task->isBluetoothEnabled() ? bluetooth_on : bluetooth_off, + 32, 32); + display.setColor(UIColor::secondary_txt); + display.setTextSize(1); + display.drawTextCentered(display.width() / 2, 64 - 11, "toggle: " PRESS_LABEL); +#endif + } else if (_page == HomePage::ADVERT) { + display.setColor(UIColor::corp_blue); + display.drawXbm((display.width() - 32) / 2, 18, advert_icon, 32, 32); + display.setColor(UIColor::secondary_txt); + display.drawTextCentered(display.width() / 2, 64 - 11, "advert: " PRESS_LABEL); +#if ENV_INCLUDE_GPS == 1 + } else if (_page == HomePage::GPS) { + LocationProvider* nmea = sensors.getLocationProvider(); + char buf[50]; + int y = 18; + bool gps_state = _task->getGPSState(); + bool hw_gps_state = nmea != NULL && nmea->isHardwareEnabled(); + uint32_t period = nmea != NULL ? nmea->getGpsPeriod() : 0; + char fix_buf[12] = ""; + if (nmea != NULL) { + uint32_t fix_age = nmea->getLastFixAge(); + if (fix_age == UINT32_MAX) { + strcpy(fix_buf, "no fix"); + } else { + formatFixAge(fix_buf, sizeof(fix_buf), fix_age); + } + } + if (nmea != NULL && nmea->hasHardwareEnableState() && gps_state != hw_gps_state) { + strcpy(buf, gps_state ? "gps off(hw)" : "gps off(sw)"); + } else if (!gps_state) { + strcpy(buf, "gps off"); + } else if (period == 0) { + strcpy(buf, "gps on"); + } else { + char per[12]; + formatGpsPeriod(per, sizeof(per), period); + snprintf(buf, sizeof(buf), "%s (%s)", nmea != NULL && nmea->isActive() ? "active" : "sleep", per); + } + display.setColor(UIColor::primary_txt); + display.drawTextLeftAlign(0, y, buf); + if (nmea == NULL) { + y = y + 12; + display.setColor(UIColor::secondary_txt); + display.drawTextLeftAlign(0, y, "Can't access GPS"); + } else { + display.setColor(UIColor::primary_txt); + display.drawTextRightAlign(display.width()-1, y, fix_buf); + y = y + 12; + display.setColor(UIColor::secondary_txt); + display.drawTextLeftAlign(0, y, "sat"); + display.setColor(UIColor::primary_txt); + sprintf(buf, "%d", nmea->satellitesCount()); + display.drawTextRightAlign(display.width()-1, y, buf); + y = y + 12; + display.setColor(UIColor::secondary_txt); + display.drawTextLeftAlign(0, y, "pos"); + display.setColor(UIColor::primary_txt); + sprintf(buf, "%.4f %.4f", + nmea->getLatitude()/1000000., nmea->getLongitude()/1000000.); + display.drawTextRightAlign(display.width()-1, y, buf); + y = y + 12; + display.setColor(UIColor::secondary_txt); + display.drawTextLeftAlign(0, y, "alt"); + display.setColor(UIColor::primary_txt); + sprintf(buf, "%.2f", nmea->getAltitude()/1000.); + display.drawTextRightAlign(display.width()-1, y, buf); + y = y + 12; + } +#endif +#if UI_SENSORS_PAGE == 1 + } else if (_page == HomePage::SENSORS) { + int y = 18; + refresh_sensors(); + char buf[30]; + char name[30]; + LPPReader r(sensors_lpp.getBuffer(), sensors_lpp.getSize()); + + for (int i = 0; i < sensors_scroll_offset; i++) { + uint8_t channel, type; + r.readHeader(channel, type); + r.skipData(type); + } + + for (int i = 0; i < (sensors_scroll?UI_RECENT_LIST_SIZE:sensors_nb); i++) { + uint8_t channel, type; + if (!r.readHeader(channel, type)) { // reached end, reset + r.reset(); + r.readHeader(channel, type); + } + + display.setCursor(0, y); + float v; + switch (type) { + case LPP_GPS: // GPS + float lat, lon, alt; + r.readGPS(lat, lon, alt); + strcpy(name, "gps"); sprintf(buf, "%.4f %.4f", lat, lon); + break; + case LPP_VOLTAGE: + r.readVoltage(v); + strcpy(name, "voltage"); sprintf(buf, "%6.2f", v); + break; + case LPP_CURRENT: + r.readCurrent(v); + strcpy(name, "current"); sprintf(buf, "%.3f", v); + break; + case LPP_TEMPERATURE: + r.readTemperature(v); + strcpy(name, "temperature"); sprintf(buf, "%.2f", v); + break; + case LPP_RELATIVE_HUMIDITY: + r.readRelativeHumidity(v); + strcpy(name, "humidity"); sprintf(buf, "%.2f", v); + break; + case LPP_BAROMETRIC_PRESSURE: + r.readPressure(v); + strcpy(name, "pressure"); sprintf(buf, "%.2f", v); + break; + case LPP_ALTITUDE: + r.readAltitude(v); + strcpy(name, "altitude"); sprintf(buf, "%.0f", v); + break; + case LPP_POWER: + r.readPower(v); + strcpy(name, "power"); sprintf(buf, "%6.2f", v); + break; + default: + r.skipData(type); + strcpy(name, "unk"); sprintf(buf, ""); + } + display.setCursor(0, y); + display.setColor(UIColor::secondary_txt); + display.print(name); + display.setColor(UIColor::primary_txt); + display.setCursor( + display.width()-display.getTextWidth(buf)-1, y + ); + display.print(buf); + y = y + 12; + } + if (sensors_scroll) sensors_scroll_offset = (sensors_scroll_offset+1)%sensors_nb; + else sensors_scroll_offset = 0; +#endif +#if UI_DISCOVER_SCREEN + } else if (_page == HomePage::DISCOVERY) { + int count = disc_nodes_count; + display.setColor(UIColor::primary_txt); + int y = 20; + for (int i = 0; i < count; i++, y += 11) { + char name[32]; + auto a = &discovered[i]; + if ((a->name[0] == 0) || !_node_prefs->ui_nd_name) { + mesh::Utils::toHex(name, a->pubkey_prefix, 4); + } else { + strncpy(name, a->name, 32); + } + char filtered_name[sizeof(name)]; + char snr_s[12]; + if (strlen(name) <= 8) { // display snr_o + sprintf(snr_s, "%02.1f>%02.1f", a->snr_out, a->snr_in); + } else { + sprintf(snr_s, "%02.1f", a->snr_in); + } + int snr_width = display.getTextWidth(snr_s); + int max_name_width = display.width() - snr_width - 1; + display.translateUTF8ToBlocks(filtered_name, name, sizeof(filtered_name)); + display.drawTextEllipsized(0, y, max_name_width, filtered_name); + display.setCursor(display.width() - snr_width - 1, y); + display.print(snr_s); + } + if (millis() < discovery_req_time + 5000) { + return 1000; // more frequent updates just after req + } else if (count < DISCOVERED_NODES_TABLE_SIZE -1) { // show only 5 sec after last disc + y = 10 + 11 * DISCOVERED_NODES_TABLE_SIZE; + display.drawTextCentered(display.width() / 2, y, "discover: " PRESS_LABEL); + } +#endif +#ifndef UI_NO_HIBERNATE + } else if (_page == HomePage::SHUTDOWN) { + display.setColor(UIColor::corp_blue); + display.setTextSize(1); + if (_shutdown_init) { + display.setColor(UIColor::warning_txt); + display.drawTextCentered(display.width() / 2, 34, "hibernating..."); + } else { + display.setColor(UIColor::secondary_txt); + display.drawXbm((display.width() - 32) / 2, 18, power_icon, 32, 32); + display.drawTextCentered(display.width() / 2, 64 - 11, "hibernate:" PRESS_LABEL); + } +#endif + } + return 5000; // next render after 5000 ms + } + + bool handleInput(char c) override { + if (c == KEY_LEFT || c == KEY_PREV) { + _page = (_page + HomePage::Count - 1) % HomePage::Count; + invalidatePowerPage(); + return true; + } + if (c == KEY_NEXT || c == KEY_RIGHT) { + _page = (_page + 1) % HomePage::Count; + invalidatePowerPage(); + if (_page == HomePage::RECENT) { + _task->showAlert("Recent adverts", 800); + } +#if UI_DISCOVER_SCREEN + if (_page == HomePage::DISCOVERY) { + _task->showAlert("Repeater disc", 800); + } +#endif + return true; + } +#ifdef BLE_PIN_CODE + if (c == KEY_ENTER && _page == HomePage::BLUETOOTH) { + if (_task->isBluetoothEnabled()) { // toggle Bluetooth on/off + _task->disableBluetooth(); + } else { + _task->enableBluetooth(); + } + return true; + } +#endif + if (c == KEY_ENTER && _page == HomePage::ADVERT) { + _task->notify(UIEventType::ack); + + mesh::Packet* pkt; + if (_node_prefs->advert_loc_policy == ADVERT_LOC_NONE) { + pkt = _task->getMesh()->createSelfAdvert(_node_prefs->node_name); + } else { + pkt = _task->getMesh()->createSelfAdvert(_node_prefs->node_name, sensors.node_lat, sensors.node_lon); + } + if (pkt) { + _task->getMesh()->sendZeroHop(pkt); + _task->showAlert("Advert sent!", 1000); + } else { + _task->showAlert("Advert failed..", 1000); + } + return true; + } +#if ENV_INCLUDE_GPS == 1 + if (c == KEY_ENTER && _page == HomePage::GPS) { + if (_node_prefs->ui_gps_action == 1) _task->triggerGPS(); else _task->toggleGPS(); + return true; + } +#endif +#if UI_SENSORS_PAGE == 1 + if (c == KEY_ENTER && _page == HomePage::SENSORS) { + _task->toggleGPS(); + next_sensors_refresh=0; + return true; + } +#endif +#if UI_DISCOVER_SCREEN + if (c == KEY_ENTER && _page == HomePage::DISCOVERY) { + if (millis() > discovery_req_time + 5000) { // rate limiter + sendDiscoverRequest(); + } + return true; + } + if (c == KEY_SELECT && _page == HomePage::DISCOVERY) { + _node_prefs->ui_nd_name = !_node_prefs->ui_nd_name; + return true; + } +#endif +#ifndef UI_NO_HIBERNATE + if (c == KEY_ENTER && _page == HomePage::SHUTDOWN) { + _shutdown_init = true; // need to wait for button to be released + return true; + } +#endif + return false; + } +}; + +#ifndef UI_MSG_PREVIEW_SIZE + #define UI_MSG_PREVIEW_SIZE 78 +#endif + +class MsgPreviewScreen : public UIScreen { + UITask* _task; + mesh::RTCClock* _rtc; + + struct MsgEntry { + uint32_t timestamp; + char origin[62]; + char msg[UI_MSG_PREVIEW_SIZE]; + }; + #define MAX_UNREAD_MSGS 32 + int num_unread; + int head = MAX_UNREAD_MSGS - 1; // index of latest unread message + MsgEntry unread[MAX_UNREAD_MSGS]; + +public: + MsgPreviewScreen(UITask* task, mesh::RTCClock* rtc) : _task(task), _rtc(rtc) { num_unread = 0; } + + void addPreview(uint8_t path_len, const char* from_name, const char* msg) { + head = (head + 1) % MAX_UNREAD_MSGS; + if (num_unread < MAX_UNREAD_MSGS) num_unread++; + + auto p = &unread[head]; + p->timestamp = _rtc->getCurrentTime(); + if (path_len == 0xFF) { + sprintf(p->origin, "(D) %s:", from_name); + } else { + sprintf(p->origin, "(%d) %s:", (uint32_t) path_len, from_name); + } + StrHelper::strncpy(p->msg, msg, sizeof(p->msg)); + } + + int render(DisplayDriver& display) override { + char tmp[16]; + display.setCursor(0, 0); + display.setTextSize(1); + display.setColor(UIColor::corp_blue); + sprintf(tmp, "Unread: %d", num_unread); + display.print(tmp); + + auto p = &unread[head]; + + int secs = _rtc->getCurrentTime() - p->timestamp; + if (secs < 60) { + sprintf(tmp, "%ds", secs); + } else if (secs < 60*60) { + sprintf(tmp, "%dm", secs / 60); + } else { + sprintf(tmp, "%dh", secs / (60*60)); + } + display.setCursor(display.width() - display.getTextWidth(tmp) - 2, 0); + display.print(tmp); + + display.drawRect(0, 11, display.width(), 1); // horiz line + + display.setCursor(0, 14); + display.setColor(UIColor::secondary_txt); + char filtered_origin[sizeof(p->origin)]; + display.translateUTF8ToBlocks(filtered_origin, p->origin, sizeof(filtered_origin)); + display.print(filtered_origin); + + display.setCursor(0, 25); + display.setColor(UIColor::primary_txt); + char filtered_msg[sizeof(p->msg)]; + display.translateUTF8ToBlocks(filtered_msg, p->msg, sizeof(filtered_msg)); + display.printWordWrap(filtered_msg, display.width()); + + return display.isEink() ? 10000 : 1000; // 10 s for eink + } + + bool handleInput(char c) override { + if (c == KEY_NEXT || c == KEY_RIGHT) { + head = (head + MAX_UNREAD_MSGS - 1) % MAX_UNREAD_MSGS; + num_unread--; + if (num_unread == 0) { + _task->gotoHomeScreen(); + } + return true; + } + if (c == KEY_ENTER) { + num_unread = 0; // clear unread queue + _task->gotoHomeScreen(); + return true; + } + return false; + } +}; + +void UITask::begin(DisplayDriver* display, SensorManager* sensors, NodePrefs* node_prefs, MultiSerialInterface* serial, + BaseChatMesh* mesh, uint32_t ble_pin, const char* ver, const char* build_date) +{ + _display = display; + _sensors = sensors; + _interfaceManager = serial; + the_mesh = mesh; + _ble_pin = ble_pin; + + powerUi.begin(); +#if defined(PIN_USER_BTN) + user_btn.begin(); +#endif +#if defined(PIN_USER_BTN_ANA) + analog_btn.begin(); +#endif +#if defined(BACKLIGHT_BTN) + backlight_btn.begin(); +#endif + + _node_prefs = node_prefs; + _auto_off = millis() + _node_prefs->ui_auto_off_delay * 1000; + _backlight_off = millis() + _node_prefs->ui_backlight_delay * 1000; + + if (_display != NULL) { + _display->turnOn(_node_prefs->ui_max_partial); + } + +#ifdef PIN_BUZZER + buzzer.begin(); + buzzer.quiet(_node_prefs->buzzer_quiet); + buzzer.startup(); +#endif + +#ifdef PIN_VIBRATION + vibration.begin(); +#endif + + ui_started_at = millis(); + _alert_expiry = 0; + + splash = new SplashScreen(this, ver, build_date); + home = new HomeScreen(this, powerUi, &rtc_clock, sensors, node_prefs); + msg_preview = new MsgPreviewScreen(this, &rtc_clock); + setCurrScreen(splash); +} + +void UITask::showAlert(const char* text, int duration_millis) { + strcpy(_alert, text); + _alert_expiry = millis() + duration_millis; +} + +void UITask::notify(UIEventType t) { +#if defined(PIN_BUZZER) +switch(t){ + case UIEventType::contactMessage: + // gemini's pick + buzzer.play("MsgRcv3:d=4,o=6,b=200:32e,32g,32b,16c7"); + break; + case UIEventType::channelMessage: + buzzer.play("kerplop:d=16,o=6,b=120:32g#,32c#"); + break; + case UIEventType::ack: + buzzer.play("ack:d=32,o=8,b=120:c"); + break; + case UIEventType::roomMessage: + case UIEventType::newContactMessage: + case UIEventType::none: + default: + break; +} +#endif + +#ifdef PIN_VIBRATION + // Trigger vibration for all UI events except none + if (t != UIEventType::none) { + vibration.trigger(); + } +#endif +} + +void UITask::onMessageRecv(mesh::Packet *pkt, const ContactInfo &from, uint8_t txt_type, uint32_t sender_timestamp, const char* text) { + // we only want to show text messages on display, not cli data + if (!(txt_type == TXT_TYPE_PLAIN || txt_type == TXT_TYPE_SIGNED_PLAIN)) return; + + uint8_t path_len = pkt->isRouteFlood() ? pkt->path_len : 0xFF; + ((MsgPreviewScreen *) msg_preview)->addPreview(path_len, from.name, text); + setCurrScreen(msg_preview); + + if (_display != NULL) { + if (!_display->isOn() && !hasConnection()) { + _display->turnOn(_node_prefs->ui_max_partial); + } + if (_display->isOn()) { + _auto_off = millis() + _node_prefs->ui_auto_off_delay * 1000; // extend the auto-off timer + _next_refresh = 100; // trigger refresh + if (_node_prefs->ui_backlight_on_msgs) { + _backlight_off = millis() + _node_prefs->ui_backlight_delay * 1000; + } + } + } + + if (!hasConnection()) { + notify(UIEventType::contactMessage); + } +} + +void UITask::onChannelMessageRecv(mesh::Packet *pkt, ChannelDetails& channel_details, const char* text) { + uint8_t path_len = pkt->isRouteFlood() ? pkt->path_len : 0xFF; + ((MsgPreviewScreen *) msg_preview)->addPreview(path_len, channel_details.name, text); + setCurrScreen(msg_preview); + + if (_display != NULL) { + if (!_display->isOn() && !hasConnection()) { + _display->turnOn(_node_prefs->ui_max_partial); + } + if (_display->isOn()) { + _auto_off = millis() + _node_prefs->ui_auto_off_delay * 1000; // extend the auto-off timer + _next_refresh = 100; // trigger refresh + } + } + + if (!hasConnection()) { + notify(UIEventType::channelMessage); + } +} + +void UITask::onQueueSizeChanged(int msgcount) { + _msgcount = msgcount; + if (msgcount == 0) { + gotoHomeScreen(); + } +} + +void UITask::onDiscoveredContact(ContactInfo &contact, bool is_new, uint8_t path_len, const uint8_t* path) { + if (!hasConnection()) { + notify(UIEventType::newContactMessage); + } + + ((HomeScreen *) home)->addToRecents(contact); +} + +void UITask::onControlDataRecv(const mesh::Packet* packet) { +#if UI_DISCOVER_SCREEN + if (packet->payload_len >= 14 && (packet->payload[0] & 0xF0) == CTL_TYPE_NODE_DISCOVER_RESP) { + ((HomeScreen *) home)->handleDiscoverResponse(packet); + } +#endif +} + +void UITask::userLedHandler() { +#ifdef PIN_STATUS_LED + int cur_time = millis(); + if (cur_time > next_led_change) { + if (led_state == 0) { + led_state = 1; + if (_msgcount > 0) { + last_led_increment = LED_ON_MSG_MILLIS; + } else { + last_led_increment = LED_ON_MILLIS; + } + next_led_change = cur_time + last_led_increment; + } else { + led_state = 0; + next_led_change = cur_time + LED_CYCLE_MILLIS - last_led_increment; + } + digitalWrite(PIN_STATUS_LED, led_state == LED_STATE_ON); + } +#endif +} + +void UITask::setCurrScreen(UIScreen* c) { + if (curr && curr == home && c != home) static_cast(home)->invalidatePowerPage(); + curr = c; + _next_refresh = 100; +} + +/* + hardware-agnostic pre-shutdown activity should be done here +*/ +void UITask::shutdown(bool restart){ + + #ifdef PIN_BUZZER + /* note: we have a choice here - + we can do a blocking buzzer.loop() with non-deterministic consequences + or we can set a flag and delay the shutdown for a couple of seconds + while a non-blocking buzzer.loop() plays out in UITask::loop() + */ + buzzer.shutdown(); + uint32_t buzzer_timer = millis(); // fail-safe shutdown + while (buzzer.isPlaying() && (millis() - 2500) < buzzer_timer) + buzzer.loop(); + + #endif // PIN_BUZZER + + if (restart) { + _board->reboot(); + } else { + if (_display->isEink()) { + _display->turnOff(true); + } + // Power off board including radio, display, GPS and components + _board->powerOff(); + } +} + +bool UITask::isButtonPressed() const { +#ifdef PIN_USER_BTN + return user_btn.isPressed(); +#else + return false; +#endif +} + +void UITask::handlePowerPageFocus(uint8_t events, bool handlingInput) { + // Consume even when busy: an old event must not steal focus later. + if (!(events & PowerBankUi::EVENT_REQUEST_FOCUS) || handlingInput || + !_display || curr != home || millis() < _alert_expiry) return; + if (static_cast(home)->showPowerPage()) checkDisplayOn(0); +} + +void UITask::loop() { + char c = 0; + bool powerInputHandled = false; +#if UI_HAS_JOYSTICK + int ev = user_btn.check(); + if (ev == BUTTON_EVENT_CLICK) { + c = checkDisplayOn(KEY_ENTER); + } else if (ev == BUTTON_EVENT_LONG_PRESS) { + c = handleLongPress(KEY_ENTER); // REVISIT: could be mapped to different key code + } + ev = joystick_left.check(); + if (ev == BUTTON_EVENT_CLICK) { + c = checkDisplayOn(KEY_LEFT); + } else if (ev == BUTTON_EVENT_LONG_PRESS) { + c = handleLongPress(KEY_LEFT); + } + ev = joystick_right.check(); + if (ev == BUTTON_EVENT_CLICK) { + c = checkDisplayOn(KEY_RIGHT); + } else if (ev == BUTTON_EVENT_LONG_PRESS) { + c = handleLongPress(KEY_RIGHT); + } + ev = back_btn.check(); + if (ev == BUTTON_EVENT_TRIPLE_CLICK) { + c = handleTripleClick(KEY_SELECT); + } +#elif defined(PIN_USER_BTN) + int ev = user_btn.check(); + #ifdef UI_HAS_NAV_INPUT + if (ev == BUTTON_EVENT_CLICK) { + c = checkDisplayOn(KEY_ENTER); + } else if (ev == BUTTON_EVENT_LONG_PRESS) { + display.turnOff(true); + } else if (ev == BUTTON_EVENT_DOUBLE_CLICK) { + c = handleDoubleClick(KEY_SELECT); + } else if (ev == BUTTON_EVENT_TRIPLE_CLICK) { + c = handleTripleClick(KEY_SELECT); + } + #else + if (ev == BUTTON_EVENT_CLICK) { + c = checkDisplayOn(KEY_NEXT); + } else if (ev == BUTTON_EVENT_LONG_PRESS) { + c = handleLongPress(KEY_ENTER); + } else if (ev == BUTTON_EVENT_DOUBLE_CLICK) { + c = handleDoubleClick(KEY_PREV); + } else if (ev == BUTTON_EVENT_TRIPLE_CLICK) { + c = handleTripleClick(KEY_SELECT); + } + #endif +#endif +#if defined(UI_HAS_ROTARY_INPUT) + RotaryInputEvent rotaryEv = rotary_input.poll(); + if (c == 0 && _display != NULL) { + if (rotaryEv == RotaryInputEvent::Next) { + c = checkDisplayOn(KEY_NEXT); + } else if (rotaryEv == RotaryInputEvent::Prev) { + c = checkDisplayOn(KEY_PREV); + } + } +#endif + const uint8_t powerEvents = powerUi.pollEvents(); + HomeScreen* homeScreen = static_cast(home); + if ((powerEvents & PowerBankUi::EVENT_SHOW_PAGE) && c == 0 && + curr == home && homeScreen->showPowerPage()) { + checkDisplayOn(0); + powerInputHandled = true; + } + else if ((powerEvents & PowerBankUi::EVENT_PAGE_ACTION) && c == 0 && + _display && _display->isOn() && curr == home && homeScreen->isPowerPage() && + millis() >= _alert_expiry) { + powerUi.handlePageAction(); + _auto_off = millis() + _node_prefs->ui_auto_off_delay * 1000; + _next_refresh = 0; + powerInputHandled = true; + } +#if defined(PIN_USER_BTN_ANA) + if (abs(millis() - _analogue_pin_read_millis) > 10) { + int ev = analog_btn.check(); + if (ev == BUTTON_EVENT_CLICK) { + c = checkDisplayOn(KEY_NEXT); + } else if (ev == BUTTON_EVENT_LONG_PRESS) { + c = handleLongPress(KEY_ENTER); + } else if (ev == BUTTON_EVENT_DOUBLE_CLICK) { + c = handleDoubleClick(KEY_PREV); + } else if (ev == BUTTON_EVENT_TRIPLE_CLICK) { + c = handleTripleClick(KEY_SELECT); + } + _analogue_pin_read_millis = millis(); + } +#endif +#if defined(DISP_BACKLIGHT) || defined(EXP_PIN_BACKLIGHT) +#if defined(BACKLIGHT_BTN) + if (millis() > next_backlight_btn_check) { + if (backlight_btn.isPressed()) { + if (!_display->isOn()) { + _display->turnOn(_node_prefs->ui_max_partial); + _next_refresh = 0; + } + _auto_off = millis() + _node_prefs->ui_auto_off_delay * 1000; // extend auto-off timer + _backlight_off = millis() + _node_prefs->ui_backlight_delay * 1000; // extend auto_off for backlight + } + next_backlight_btn_check = millis() + 100; + } + int bev = backlight_btn.check(); + if (bev == BUTTON_EVENT_DOUBLE_CLICK) { + _display->forceFullRefresh(); + } else if (bev == BUTTON_EVENT_TRIPLE_CLICK) { + _display->turnOff(true); + _backlight_off = 0; + } +#endif + + bool backlight_state; + if (_node_prefs->ui_backlight_delay == -1) { + backlight_state = true; + } else if (_node_prefs->ui_backlight_delay < -1) { + backlight_state = false; + } else if (_node_prefs->ui_backlight_delay == 0) { + backlight_state = false; + #ifdef BACKLIGHT_BTN + backlight_state = backlight_btn.isPressed(); + #endif + } else { + backlight_state = (millis() < _backlight_off); + } + +#if defined(DISP_BACKLIGHT) + digitalWrite(DISP_BACKLIGHT, backlight_state); +#elif defined(EXP_PIN_BACKLIGHT) + expander.digitalWrite(EXP_PIN_BACKLIGHT, backlight_state); +#endif +#endif + + handlePowerPageFocus(powerEvents, c != 0 || powerInputHandled); + if (c != 0 && curr) { + curr->handleInput(c); + _auto_off = millis() + _node_prefs->ui_auto_off_delay * 1000; // extend auto-off timer + _next_refresh = 100; // trigger refresh + } + + userLedHandler(); + +#ifdef PIN_BUZZER + if (buzzer.isQuiet() != (bool)_node_prefs->buzzer_quiet) buzzer.quiet(_node_prefs->buzzer_quiet); + if (buzzer.isPlaying()) buzzer.loop(); +#endif + + if (curr) curr->poll(); + + if (_display != NULL && _display->isOn()) { + if (millis() >= _next_refresh && curr) { + const bool powerFrame = curr == home && homeScreen->isPowerPage(); + const bool alertVisible = millis() < _alert_expiry; + // The power page keeps its pixels between field updates. + if (!powerFrame || (powerPageHadAlert && !alertVisible)) homeScreen->invalidatePowerPage(); + if (!powerFrame) _display->startFrame(); + powerPageHadAlert = powerFrame && alertVisible; + int delay_millis = curr->render(*_display); + if (alertVisible) { // render alert popup + _display->setTextSize(1); + int y = _display->height() / 3; + int p = _display->height() / 32; + _display->setColor(UIColor::popup_bkg); + _display->fillRect(p, y, _display->width() - p*2, y); + _display->setColor(UIColor::popup_txt); // draw box border + _display->drawRect(p, y, _display->width() - p*2, y); + _display->drawTextCentered(_display->width() / 2, y + p*3, _alert); + _next_refresh = _alert_expiry; // will need refresh when alert is dismissed + } else { + _next_refresh = millis() + delay_millis; + } + _display->endFrame(); + } + if (_node_prefs->ui_auto_off_delay > 0) { +#ifdef KEEP_DISPLAY_ON_USB + // Opt-in: refresh the auto-off deadline while externally powered, so the + // timer counts from the moment external power is removed. Off by default + // because OLED panels burn in quickly; only enable for LCD targets or + // where the display is replaceable. + if (board.isExternalPowered()) { + _auto_off = millis() + _node_prefs->ui_auto_off_delay * 1000; + } +#endif + if (millis() > _auto_off) { + homeScreen->invalidatePowerPage(); + if (_node_prefs->ui_auto_off_blank && + !(_node_prefs->ui_auto_off_keep_msgs + && curr == msg_preview)) { + // don't blank if messages are waiting + _display->turnOff(true); + } else { + _display->turnOff(); + } + } + } + } + +#ifdef PIN_VIBRATION + vibration.loop(); +#endif + +#ifdef AUTO_SHUTDOWN_MILLIVOLTS + if (millis() > next_batt_chck) { + uint16_t milliVolts = getBattMilliVolts(); + if (milliVolts > 0 && milliVolts < AUTO_SHUTDOWN_MILLIVOLTS) { + if(!board.isExternalPowered()) { + if (_display != NULL) { + _display->startFrame(); + _display->setTextSize(2); + _display->setColor(UIColor::warning_txt); + _display->drawTextCentered(_display->width() / 2, 20, "Low Battery."); + _display->drawTextCentered(_display->width() / 2, 40, "Shutting Down!"); + _display->endFrame(); + if (_display->isEink() == false) { delay(3000); } + } + shutdown(); + } + } + next_batt_chck = millis() + 8000; + } +#endif +} + +char UITask::checkDisplayOn(char c) { + if (_display != NULL) { + if (!_display->isOn()) { + static_cast(home)->invalidatePowerPage(); + _display->turnOn(_node_prefs->ui_max_partial); // turn display on and consume event + c = 0; + } + _auto_off = millis() + _node_prefs->ui_auto_off_delay * 1000; // extend auto-off timer + if (_node_prefs->ui_backlight_on_keys) { + _backlight_off = millis() + _node_prefs->ui_backlight_delay * 1000; + } + _next_refresh = 0; // trigger refresh + } + return c; +} + +char UITask::handleLongPress(char c) { + if (millis() - ui_started_at < 8000) { // long press in first 8 seconds since startup -> CLI/rescue + the_mesh->enterCLIRescue(); + c = 0; // consume event + } + return c; +} + +char UITask::handleDoubleClick(char c) { + MESH_DEBUG_PRINTLN("UITask: double-click triggered"); + checkDisplayOn(c); + return c; +} + +char UITask::handleTripleClick(char c) { + MESH_DEBUG_PRINTLN("UITask: triple click triggered"); + checkDisplayOn(c); + toggleBuzzer(); + c = 0; + return c; +} + +bool UITask::getGPSState() { + if (_sensors != NULL) { + int num = _sensors->getNumSettings(); + for (int i = 0; i < num; i++) { + if (strcmp(_sensors->getSettingName(i), "gps") == 0) { + return !strcmp(_sensors->getSettingValue(i), "1"); + } + } + } + return false; +} + +void UITask::toggleGPS() { + if (_sensors != NULL) { + // toggle GPS on/off + int num = _sensors->getNumSettings(); + for (int i = 0; i < num; i++) { + if (strcmp(_sensors->getSettingName(i), "gps") == 0) { + if (strcmp(_sensors->getSettingValue(i), "1") == 0) { + _node_prefs->getGpsPrefs()->setGpsEnabled(*_sensors, false); + notify(UIEventType::ack); + } else { + _node_prefs->getGpsPrefs()->setGpsEnabled(*_sensors, true); + notify(UIEventType::ack); + } + the_mesh->savePrefs(); + showAlert(_node_prefs->getGpsPrefs()->isGpsEnabled() ? "GPS: Enabled" : "GPS: Disabled", 800); + _next_refresh = 0; + break; + } + } + } +} + +void UITask::triggerGPS() { + LocationProvider* location = _sensors != NULL ? _sensors->getLocationProvider() : NULL; + if (location != NULL && !(location->hasHardwareEnableState() && !location->isHardwareEnabled()) + && location->startOnce()) { + notify(UIEventType::ack); + } + _next_refresh = 0; +} + +void UITask::toggleBuzzer() { + // Toggle buzzer quiet mode + #ifdef PIN_BUZZER + if (buzzer.isQuiet()) { + buzzer.quiet(false); + notify(UIEventType::ack); + } else { + buzzer.quiet(true); + } + _node_prefs->buzzer_quiet = buzzer.isQuiet(); + the_mesh->savePrefs(); + showAlert(buzzer.isQuiet() ? "Buzzer: OFF" : "Buzzer: ON", 800); + _next_refresh = 0; // trigger refresh + #endif +} diff --git a/variants/heltec_meshpocket_v2/ui-companion/UITask.h b/variants/heltec_meshpocket_v2/ui-companion/UITask.h new file mode 100644 index 00000000..7f7f21fa --- /dev/null +++ b/variants/heltec_meshpocket_v2/ui-companion/UITask.h @@ -0,0 +1,145 @@ +// Based on src/helpers/ui/companion-new/UITask.h at 88bbae29. +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include + +#ifndef LED_STATE_ON + #define LED_STATE_ON 1 +#endif + +#ifdef PIN_BUZZER + #include +#endif +#ifdef PIN_VIBRATION + #include +#endif + +#include +#include +#include "HeltecMeshPocketV2Board.h" +#include "PowerBankUi.h" + +#ifdef UI_NO_DISCOVER_SCREEN + #error "UI_NO_DISCOVER_SCREEN is obsolete - use -D UI_DISCOVER_SCREEN=0 instead" +#endif + +#ifndef UI_DISCOVER_SCREEN + #define UI_DISCOVER_SCREEN 1 +#endif + +#if UI_DISCOVER_SCREEN + #ifdef UI_RECENT_LIST_SIZE + #define DISCOVERED_NODES_TABLE_SIZE UI_RECENT_LIST_SIZE + #else + #define DISCOVERED_NODES_TABLE_SIZE 4 + #endif + +struct DiscoveredNode { + float snr_in; + float snr_out; + uint8_t pubkey_prefix[9]; + uint8_t type; + char name[32]; +}; +#endif + +class UITask : public AbstractUITask { + PowerBankUi powerUi; + DisplayDriver* _display; + SensorManager* _sensors; + BaseChatMesh* the_mesh; + uint32_t _ble_pin; +#ifdef PIN_BUZZER + genericBuzzer buzzer; +#endif +#ifdef PIN_VIBRATION + GenericVibration vibration; +#endif + unsigned long _next_refresh, _auto_off; + NodePrefs* _node_prefs; + char _alert[80]; + unsigned long _alert_expiry; + int _msgcount; + unsigned long ui_started_at, next_batt_chck; + unsigned long next_backlight_btn_check = 0; + unsigned long _backlight_off = 0; +#ifdef PIN_STATUS_LED + int led_state = 0; + int next_led_change = 0; + int last_led_increment = 0; +#endif + +#ifdef PIN_USER_BTN_ANA + unsigned long _analogue_pin_read_millis = millis(); +#endif + + UIScreen* splash; + UIScreen* home; + UIScreen* msg_preview; + UIScreen* curr; + bool powerPageHadAlert = false; + + void userLedHandler(); + + // Button action handlers + char checkDisplayOn(char c); + char handleLongPress(char c); + char handleDoubleClick(char c); + char handleTripleClick(char c); + + void setCurrScreen(UIScreen* c); + void handlePowerPageFocus(uint8_t events, bool handlingInput); + +public: + + UITask(HeltecMeshPocketV2Board& board, DisplayDriver* display = NULL) : + AbstractUITask(&board), powerUi(board), _display(display), _sensors(NULL) { + next_batt_chck = _next_refresh = 0; + ui_started_at = 0; + curr = NULL; + } + void begin(DisplayDriver* display, SensorManager* sensors, NodePrefs* node_prefs, MultiSerialInterface* serial, + BaseChatMesh* mesh, uint32_t ble_pin, const char* ver, const char* build_date); + + void gotoHomeScreen() { setCurrScreen(home); } + void showAlert(const char* text, int duration_millis); + int getMsgCount() const { return _msgcount; } + bool hasDisplay() const { return _display != NULL; } + bool isButtonPressed() const; + + BaseChatMesh* getMesh() const { return the_mesh; } + uint32_t getBLEPin() const { return _ble_pin; } + + bool isBuzzerQuiet() { +#ifdef PIN_BUZZER + return buzzer.isQuiet(); +#else + return true; +#endif + } + + void toggleBuzzer(); + bool getGPSState(); + void toggleGPS(); + void triggerGPS(); + + // MeshEventListener + void onMessageRecv(mesh::Packet *pkt, const ContactInfo &from, uint8_t txt_type, uint32_t sender_timestamp, const char* text) override; + void onChannelMessageRecv(mesh::Packet *pkt, ChannelDetails& channel_details, const char* text) override; + void onQueueSizeChanged(int offline_queue_size) override; + void onDiscoveredContact(ContactInfo &contact, bool is_new, uint8_t path_len, const uint8_t* path) override; + void onControlDataRecv(const mesh::Packet* pkt) override; + + // from AbstractUITask + void notify(UIEventType t = UIEventType::none) override; + void loop() override; + + void shutdown(bool restart = false); +}; diff --git a/variants/heltec_meshpocket_v2/ui-companion/target.cpp b/variants/heltec_meshpocket_v2/ui-companion/target.cpp new file mode 100644 index 00000000..a08f1dca --- /dev/null +++ b/variants/heltec_meshpocket_v2/ui-companion/target.cpp @@ -0,0 +1,3 @@ +#include "target.h" + +UITask ui_task(board); diff --git a/variants/heltec_meshpocket_v2/ui-server/UITask.cpp b/variants/heltec_meshpocket_v2/ui-server/UITask.cpp new file mode 100644 index 00000000..b384e152 --- /dev/null +++ b/variants/heltec_meshpocket_v2/ui-server/UITask.cpp @@ -0,0 +1,206 @@ +// Based on src/helpers/ui/server/UITask.cpp at upstream 88bbae29. +#include "UITask.h" +#include "target.h" +#include +#include + +#ifndef USER_BTN_PRESSED +#define USER_BTN_PRESSED LOW +#endif + +#define AUTO_OFF_MILLIS 20000 // 20 seconds +#define BOOT_SCREEN_MILLIS 4000 // 4 seconds + +#define POWEROFF_DELAY 3000 + +// 'meshcore', 128x13px +static const uint8_t meshcore_logo [] PROGMEM = { + 0x3c, 0x01, 0xe3, 0xff, 0xc7, 0xff, 0x8f, 0x03, 0x87, 0xfe, 0x1f, 0xfe, 0x1f, 0xfe, 0x1f, 0xfe, + 0x3c, 0x03, 0xe3, 0xff, 0xc7, 0xff, 0x8e, 0x03, 0x8f, 0xfe, 0x3f, 0xfe, 0x1f, 0xff, 0x1f, 0xfe, + 0x3e, 0x03, 0xc3, 0xff, 0x8f, 0xff, 0x0e, 0x07, 0x8f, 0xfe, 0x7f, 0xfe, 0x1f, 0xff, 0x1f, 0xfc, + 0x3e, 0x07, 0xc7, 0x80, 0x0e, 0x00, 0x0e, 0x07, 0x9e, 0x00, 0x78, 0x0e, 0x3c, 0x0f, 0x1c, 0x00, + 0x3e, 0x0f, 0xc7, 0x80, 0x1e, 0x00, 0x0e, 0x07, 0x1e, 0x00, 0x70, 0x0e, 0x38, 0x0f, 0x3c, 0x00, + 0x7f, 0x0f, 0xc7, 0xfe, 0x1f, 0xfc, 0x1f, 0xff, 0x1c, 0x00, 0x70, 0x0e, 0x38, 0x0e, 0x3f, 0xf8, + 0x7f, 0x1f, 0xc7, 0xfe, 0x0f, 0xff, 0x1f, 0xff, 0x1c, 0x00, 0xf0, 0x0e, 0x38, 0x0e, 0x3f, 0xf8, + 0x7f, 0x3f, 0xc7, 0xfe, 0x0f, 0xff, 0x1f, 0xff, 0x1c, 0x00, 0xf0, 0x1e, 0x3f, 0xfe, 0x3f, 0xf0, + 0x77, 0x3b, 0x87, 0x00, 0x00, 0x07, 0x1c, 0x0f, 0x3c, 0x00, 0xe0, 0x1c, 0x7f, 0xfc, 0x38, 0x00, + 0x77, 0xfb, 0x8f, 0x00, 0x00, 0x07, 0x1c, 0x0f, 0x3c, 0x00, 0xe0, 0x1c, 0x7f, 0xf8, 0x38, 0x00, + 0x73, 0xf3, 0x8f, 0xff, 0x0f, 0xff, 0x1c, 0x0e, 0x3f, 0xf8, 0xff, 0xfc, 0x70, 0x78, 0x7f, 0xf8, + 0xe3, 0xe3, 0x8f, 0xff, 0x1f, 0xfe, 0x3c, 0x0e, 0x3f, 0xf8, 0xff, 0xfc, 0x70, 0x3c, 0x7f, 0xf8, + 0xe3, 0xe3, 0x8f, 0xff, 0x1f, 0xfc, 0x3c, 0x0e, 0x1f, 0xf8, 0xff, 0xf8, 0x70, 0x3c, 0x7f, 0xf8, +}; + +void UITask::begin(NodePrefs* node_prefs, const char* build_date, const char* firmware_version, const char* role_lbl) { + powerUi.begin(); +#ifdef MESHPOCKET_V2_ROOM_SERVER + _prevBtnState = HIGH; + _started_at = 0; // The Room Server's splash starts at power-on. +#else + _started_at = millis(); +#endif + _auto_off = millis() + AUTO_OFF_MILLIS; + _node_prefs = node_prefs; + _display->turnOn(); + +#ifndef MESHPOCKET_V2_ROOM_SERVER + user_btn.begin(); +#endif + + // strip off dash and commit hash by changing dash to null terminator + // e.g: v1.2.3-abcdef -> v1.2.3 + char *version = strdup(firmware_version); + char *dash = strchr(version, '-'); + if (dash){ + *dash = 0; + } + + // v1.2.3 (1 Jan 2025) + snprintf(_version_info, sizeof(_version_info), "%s (%s)", version, build_date); + free(version); + + _role_label = role_lbl; +} + +long UITask::renderCurrScreen() { + if (!_powering_off_at && _power_page_selected) { + const long interval = powerUi.render(::display, _power_page_full_refresh); + _power_page_full_refresh = false; + return interval; + } + _display->startFrame(); + char tmp[80]; + if (millis() < _started_at + BOOT_SCREEN_MILLIS) { // boot screen + // meshcore logo + _display->setColor(UIColor::corp_blue); + int logoWidth = 128; + _display->drawXbm((_display->width() - logoWidth) / 2, 3, meshcore_logo, logoWidth, 13); + + // meshcore website + const char* website = "https://meshcore.io"; + _display->setColor(UIColor::primary_txt); + _display->setTextSize(1); + _display->drawTextCentered(_display->width() / 2, 22, website); + + // version info + _display->setTextSize(1); + _display->drawTextCentered(_display->width() / 2, 35, _version_info); + + // node type + _display->drawTextCentered(_display->width() / 2, 48, _role_label); + } else if (_powering_off_at > 0) { + // meshcore logo + _display->setColor(UIColor::corp_blue); + int logoWidth = 128; + _display->drawXbm((_display->width() - logoWidth) / 2, 3, meshcore_logo, logoWidth, 13); + + // meshcore website + const char* website = "https://meshcore.io"; + _display->setColor(UIColor::primary_txt); + _display->setTextSize(1); + _display->drawTextCentered(_display->width()/ 2, 22, website); + + // Powering off + const char* poweroff_string = "Turning OFF"; + uint16_t poffWidth = _display->getTextWidth(poweroff_string); + _display->setCursor((_display->width() - poffWidth) / 2, 48); + _display->drawTextCentered(_display->width()/2, 48, poweroff_string); + } else { + _display->setCursor(0, 0); + _display->setTextSize(1); + _display->setColor(UIColor::primary_txt); + _display->print(_node_prefs->node_name); + + // freq / sf + _display->setCursor(0, 20); + sprintf(tmp, "FREQ: %06.3f SF%d", _node_prefs->freq, _node_prefs->sf); + _display->print(tmp); + + // bw / cr + _display->setCursor(0, 30); + sprintf(tmp, "BW: %03.2f CR: %d", _node_prefs->bw, _node_prefs->cr); + _display->print(tmp); + } + return 1000; // 1 sec interval +} + +int UITask::readPrimaryButton() { +#ifdef MESHPOCKET_V2_ROOM_SERVER + if (millis() < _next_read) return BUTTON_EVENT_NONE; + const int state = digitalRead(PIN_USER_BTN); + const bool pressed = state == USER_BTN_PRESSED && state != _prevBtnState; + _prevBtnState = state; + _next_read = millis() + 200; + return pressed ? BUTTON_EVENT_CLICK : BUTTON_EVENT_NONE; +#else + return user_btn.check(); +#endif +} + +void UITask::showPowerPage() { + if (!_display->isOn()) _display->turnOn(); + if (!_power_page_selected) _power_page_full_refresh = true; + _power_page_selected = true; + _next_refresh = 0; + _auto_off = millis() + AUTO_OFF_MILLIS; +} + +void UITask::loop() { + if (!_display->isOn()) _power_page_full_refresh = true; + const uint8_t events = powerUi.pollEvents(); + const bool canChangePage = !_powering_off_at && millis() - _started_at >= BOOT_SCREEN_MILLIS; + bool handlingInput = false; + if (canChangePage && (events & PowerBankUi::EVENT_SHOW_PAGE)) { + showPowerPage(); + handlingInput = true; + } else if (canChangePage && (events & PowerBankUi::EVENT_PAGE_ACTION) && + _display->isOn() && _power_page_selected) { + powerUi.handlePageAction(); + _next_refresh = 0; + _auto_off = millis() + AUTO_OFF_MILLIS; + handlingInput = true; + } + + const int ev = readPrimaryButton(); + handlingInput = handlingInput || ev != BUTTON_EVENT_NONE; + if (ev == BUTTON_EVENT_CLICK) { + if (!_display->isOn()) { + _display->turnOn(); + } else if (canChangePage) { + _power_page_selected = !_power_page_selected; + _power_page_full_refresh = true; + _next_refresh = 0; + } + _auto_off = millis() + AUTO_OFF_MILLIS; + } else if (ev == BUTTON_EVENT_LONG_PRESS) { + _display->turnOn(); + Serial.println("Powering Off"); + _powering_off_at = millis() + POWEROFF_DELAY; + _next_refresh = 0; + _auto_off = millis() + AUTO_OFF_MILLIS; + } + + const bool canTakePowerEvent = !_powering_off_at && millis() - _started_at >= BOOT_SCREEN_MILLIS; + if (!handlingInput && canTakePowerEvent && (events & PowerBankUi::EVENT_REQUEST_FOCUS)) { + showPowerPage(); + } + + if (_display->isOn()) { + if (millis() >= _next_refresh) { + const long interval = renderCurrScreen(); + _display->endFrame(); + _next_refresh = millis() + interval; + } + if (millis() > _auto_off) _display->turnOff(); + } + + if (_powering_off_at > 0) { // power off timer armed +#if defined(LED_PIN) && defined(LED_STATE_ON) + digitalWrite(LED_PIN, LED_STATE_ON); // switch on the led until poweroff + delay(1000); + digitalWrite(LED_PIN, !LED_STATE_ON); // off LED +#endif + if (millis() > _powering_off_at) { + _board->powerOff(); // should not return + } + } +} diff --git a/variants/heltec_meshpocket_v2/ui-server/UITask.h b/variants/heltec_meshpocket_v2/ui-server/UITask.h new file mode 100644 index 00000000..bb1b1100 --- /dev/null +++ b/variants/heltec_meshpocket_v2/ui-server/UITask.h @@ -0,0 +1,34 @@ +// Based on src/helpers/ui/server/UITask.h at upstream 88bbae29. +#pragma once + +#include +#include +#include "HeltecMeshPocketV2Board.h" +#include "PowerBankUi.h" + +class UITask : public BaseUITask { + PowerBankUi powerUi; + bool _power_page_selected = false; + bool _power_page_full_refresh = true; +#ifdef MESHPOCKET_V2_ROOM_SERVER + unsigned long _next_read = 0; + int _prevBtnState; +#endif + NodePrefs* _node_prefs; + char _version_info[32]; + const char* _role_label; + unsigned long _powering_off_at = 0; + unsigned long _started_at = 0; + + int readPrimaryButton(); + void showPowerPage(); + +protected: + long renderCurrScreen() override; + +public: + UITask(HeltecMeshPocketV2Board& board, DisplayDriver* display) : BaseUITask(&board, display), powerUi(board) {} + void begin(NodePrefs* node_prefs, const char* build_date, const char* firmware_version, const char* role_lbl); + + void loop() override; +}; diff --git a/variants/heltec_meshpocket_v2/ui-server/target.cpp b/variants/heltec_meshpocket_v2/ui-server/target.cpp new file mode 100644 index 00000000..0c312736 --- /dev/null +++ b/variants/heltec_meshpocket_v2/ui-server/target.cpp @@ -0,0 +1,3 @@ +#include "target.h" + +UITask ui_task(board, &display); diff --git a/variants/heltec_meshpocket_v2/variant.cpp b/variants/heltec_meshpocket_v2/variant.cpp new file mode 100644 index 00000000..397ad3ca --- /dev/null +++ b/variants/heltec_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/heltec_meshpocket_v2/variant.h b/variants/heltec_meshpocket_v2/variant.h new file mode 100644 index 00000000..6e9ba58f --- /dev/null +++ b/variants/heltec_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 8000000 +#define DISPLAY_ROTATION 3 // NV3001B MADCTL MX | MV