+
+
+
+
+
+ https://github.com/meshtastic/firmware/releases/tag/v2.6.4.b89355f
+
+
+
\ No newline at end of file
diff --git a/bin/org.meshtastic.meshtasticd.svg b/bin/org.meshtastic.meshtasticd.svg
new file mode 100644
index 000000000..e6863f6a6
--- /dev/null
+++ b/bin/org.meshtastic.meshtasticd.svg
@@ -0,0 +1,16 @@
+
+
+
\ No newline at end of file
diff --git a/bin/rpkg.macros b/bin/rpkg.macros
index 2bbb203de..aa036fc33 100644
--- a/bin/rpkg.macros
+++ b/bin/rpkg.macros
@@ -2,6 +2,10 @@ function meshtastic_version {
meshtastic_version=$(python3 bin/buildinfo.py short)
echo -n "$meshtastic_version"
}
+function web_version {
+ web_version=$(cat bin/web.version)
+ echo -n "$web_version"
+}
function git_commits_num {
total_commits=$(git rev-list --all --count)
echo -n "$total_commits"
diff --git a/bin/web.version b/bin/web.version
new file mode 100644
index 000000000..914ec9671
--- /dev/null
+++ b/bin/web.version
@@ -0,0 +1 @@
+2.6.0
\ No newline at end of file
diff --git a/boards/heltec_vision_master_e213.json b/boards/heltec_vision_master_e213.json
index bf5fe15ad..152515cf3 100644
--- a/boards/heltec_vision_master_e213.json
+++ b/boards/heltec_vision_master_e213.json
@@ -2,7 +2,8 @@
"build": {
"arduino": {
"ldscript": "esp32s3_out.ld",
- "partitions": "default_8MB.csv"
+ "partitions": "default_8MB.csv",
+ "memory_type": "qio_opi"
},
"core": "esp32",
"extra_flags": [
@@ -15,6 +16,7 @@
"f_cpu": "240000000L",
"f_flash": "80000000L",
"flash_mode": "qio",
+ "psram_type": "opi",
"hwids": [
["0x303A", "0x1001"],
["0x303A", "0x0002"]
diff --git a/boards/heltec_vision_master_e290.json b/boards/heltec_vision_master_e290.json
index 70f7d5f02..b7cbac878 100644
--- a/boards/heltec_vision_master_e290.json
+++ b/boards/heltec_vision_master_e290.json
@@ -2,7 +2,8 @@
"build": {
"arduino": {
"ldscript": "esp32s3_out.ld",
- "partitions": "default_8MB.csv"
+ "partitions": "default_8MB.csv",
+ "memory_type": "qio_opi"
},
"core": "esp32",
"extra_flags": [
@@ -15,6 +16,7 @@
"f_cpu": "240000000L",
"f_flash": "80000000L",
"flash_mode": "qio",
+ "psram_type": "opi",
"hwids": [
["0x303A", "0x1001"],
["0x303A", "0x0002"]
diff --git a/boards/heltec_vision_master_t190.json b/boards/heltec_vision_master_t190.json
index 341e70218..440f76ad0 100644
--- a/boards/heltec_vision_master_t190.json
+++ b/boards/heltec_vision_master_t190.json
@@ -2,7 +2,8 @@
"build": {
"arduino": {
"ldscript": "esp32s3_out.ld",
- "partitions": "default_8MB.csv"
+ "partitions": "default_8MB.csv",
+ "memory_type": "qio_opi"
},
"core": "esp32",
"extra_flags": [
@@ -15,6 +16,7 @@
"f_cpu": "240000000L",
"f_flash": "80000000L",
"flash_mode": "qio",
+ "psram_type": "opi",
"hwids": [
["0x303A", "0x1001"],
["0x303A", "0x0002"]
diff --git a/boards/seeed-sensecap-indicator.json b/boards/seeed-sensecap-indicator.json
index 0a02fc882..03bff35b5 100644
--- a/boards/seeed-sensecap-indicator.json
+++ b/boards/seeed-sensecap-indicator.json
@@ -18,6 +18,7 @@
"f_boot": "120000000L",
"boot": "qio",
"flash_mode": "qio",
+ "psram_type": "opi",
"hwids": [["0x1A86", "0x7523"]],
"mcu": "esp32s3",
"variant": "esp32s3"
diff --git a/boards/seeed-xiao-s3.json b/boards/seeed-xiao-s3.json
index 0b7b432a0..6981085dd 100644
--- a/boards/seeed-xiao-s3.json
+++ b/boards/seeed-xiao-s3.json
@@ -15,6 +15,7 @@
"f_cpu": "240000000L",
"f_flash": "80000000L",
"flash_mode": "qio",
+ "psram_type": "opi",
"hwids": [["0x2886", "0x0059"]],
"mcu": "esp32s3",
"variant": "seeed-xiao-s3"
diff --git a/boards/t-watch-s3.json b/boards/t-watch-s3.json
index e6e363305..bae4f47b0 100644
--- a/boards/t-watch-s3.json
+++ b/boards/t-watch-s3.json
@@ -16,6 +16,7 @@
"f_cpu": "240000000L",
"f_flash": "80000000L",
"flash_mode": "qio",
+ "psram_type": "opi",
"hwids": [
["0x303A", "0x1001"],
["0x303A", "0x0002"]
@@ -23,16 +24,16 @@
"mcu": "esp32s3",
"variant": "t-watch-s3"
},
- "connectivity": ["wifi"],
+ "connectivity": ["wifi", "bluetooth", "lora"],
"debug": {
"openocd_target": "esp32s3.cfg"
},
"frameworks": ["arduino"],
"name": "LilyGo T-Watch 2020 V3",
"upload": {
- "flash_size": "8MB",
+ "flash_size": "16MB",
"maximum_ram_size": 327680,
- "maximum_size": 8388608,
+ "maximum_size": 16777216,
"require_upload_port": true,
"use_1200bps_touch": true,
"wait_for_upload_port": true,
diff --git a/debian/ci_pack_sdeb.sh b/debian/ci_pack_sdeb.sh
index a8b2252ae..c0cea0010 100755
--- a/debian/ci_pack_sdeb.sh
+++ b/debian/ci_pack_sdeb.sh
@@ -10,8 +10,9 @@ platformio pkg install -e native -t platformio/tool-scons@4.40502.0
# Compress `pio` directory to prevent dh_clean from sanitizing it
tar -cf pio.tar pio/
rm -rf pio
-# Download the latest meshtastic/web release build.tar to `web.tar`
-curl -L https://github.com/meshtastic/web/releases/latest/download/build.tar -o web.tar
+# Download the meshtastic/web release build.tar to `web.tar`
+web_ver=$(cat bin/web.version)
+curl -L "https://github.com/meshtastic/web/releases/download/v$web_ver/build.tar" -o web.tar
package=$(dpkg-parsechangelog --show-field Source)
diff --git a/meshtasticd.spec.rpkg b/meshtasticd.spec.rpkg
index a09261056..4d6c9d6f5 100644
--- a/meshtasticd.spec.rpkg
+++ b/meshtasticd.spec.rpkg
@@ -21,7 +21,7 @@ Summary: Meshtastic daemon for communicating with Meshtastic devices
License: GPL-3.0
URL: https://github.com/meshtastic/firmware
Source0: {{{ git_dir_pack }}}
-Source1: https://github.com/meshtastic/web/releases/latest/download/build.tar
+Source1: https://github.com/meshtastic/web/releases/download/v{{{ web_version }}}/build.tar
BuildRequires: systemd-rpm-macros
BuildRequires: python3-devel
diff --git a/platformio.ini b/platformio.ini
index 3db4af88d..e1eabf952 100644
--- a/platformio.ini
+++ b/platformio.ini
@@ -50,18 +50,26 @@ build_flags = -Wno-missing-field-initializers
-DMESHTASTIC_EXCLUDE_REMOTEHARDWARE=1
-DMESHTASTIC_EXCLUDE_HEALTH_TELEMETRY=1
-DMESHTASTIC_EXCLUDE_POWERSTRESS=1 ; exclude power stress test module from main firmware
+ -DMESHTASTIC_EXCLUDE_GENERIC_THREAD_MODULE=1
#-DBUILD_EPOCH=$UNIX_TIME
#-D OLED_PL=1
monitor_speed = 115200
monitor_filters = direct
lib_deps =
- https://github.com/meshtastic/esp8266-oled-ssd1306/archive/e16cee124fe26490cb14880c679321ad8ac89c95.zip
+ # renovate: datasource=git-refs depName=meshtastic-esp8266-oled-ssd1306 packageName=https://github.com/meshtastic/esp8266-oled-ssd1306 gitBranch=master
+ https://github.com/meshtastic/esp8266-oled-ssd1306/archive/0119501e9983bd894830b02f545c377ee08d66fe.zip
+ # renovate: datasource=custom.pio depName=OneButton packageName=mathertel/library/OneButton
mathertel/OneButton@2.6.1
+ # renovate: datasource=git-refs depName=meshtastic-arduino-fsm packageName=https://github.com/meshtastic/arduino-fsm gitBranch=master
https://github.com/meshtastic/arduino-fsm/archive/7db3702bf0cfe97b783d6c72595e3f38e0b19159.zip
+ # renovate: datasource=git-refs depName=meshtastic-TinyGPSPlus packageName=https://github.com/meshtastic/TinyGPSPlus gitBranch=master
https://github.com/meshtastic/TinyGPSPlus/archive/71a82db35f3b973440044c476d4bcdc673b104f4.zip
+ # renovate: datasource=git-refs depName=meshtastic-ArduinoThread packageName=https://github.com/meshtastic/ArduinoThread gitBranch=master
https://github.com/meshtastic/ArduinoThread/archive/7c3ee9e1951551b949763b1f5280f8db1fa4068d.zip
+ # renovate: datasource=custom.pio depName=Nanopb packageName=nanopb/library/Nanopb
nanopb/Nanopb@0.4.91
+ # renovate: datasource=custom.pio depName=ErriezCRC32 packageName=erriez/library/ErriezCRC32
erriez/ErriezCRC32@1.0.1
; Used for the code analysis in PIO Home / Inspect
@@ -77,6 +85,7 @@ check_flags =
framework = arduino
lib_deps =
${env.lib_deps}
+ # renovate: datasource=custom.pio depName=NonBlockingRTTTL packageName=end2endzone/library/NonBlockingRTTTL
end2endzone/NonBlockingRTTTL@1.3.0
build_flags = ${env.build_flags} -Os
build_src_filter = ${env.build_src_filter} - -
@@ -84,57 +93,98 @@ build_src_filter = ${env.build_src_filter} - -.+)$"],
+ "datasourceTemplate": "github-releases",
+ "depNameTemplate": "meshtastic/web",
+ "versioningTemplate": "semver-coerced"
+ },
+ {
+ "customType": "regex",
+ "description": "Match normal PIO dependencies",
+ "fileMatch": [".*\\.ini$"],
+ "matchStrings": [
+ "# renovate: datasource=(?.*?)(?: depName=(?.+?))? packageName=(?.+?)(?: versioning=(?[a-z-]+?))?\\s+?.+?@(?.+?)\\s"
+ ],
+ "versioningTemplate": "{{#if versioning}}{{{versioning}}}{{else}}semver-coerced{{/if}}"
+ },
+ {
+ "customType": "regex",
+ "description": "Match PIO zipped dependencies with github tag ref",
+ "fileMatch": [".*\\.ini$"],
+ "matchStrings": [
+ "# renovate: datasource=github-tags(?: depName=(?.+?))? packageName=(?.+?)(?: versioning=(?[a-z-]+?))?\\s+?https:\/\/.+?archive\/(?.+?).zip\\s"
+ ],
+ "datasourceTemplate": "github-tags",
+ "versioningTemplate": "{{#if versioning}}{{{versioning}}}{{else}}semver-coerced{{/if}}"
+ },
+ {
+ "customType": "regex",
+ "description": "Match PIO zipped dependencies with git commit ref",
+ "fileMatch": [".*\\.ini$"],
+ "matchStrings": [
+ "# renovate: datasource=git-refs(?: depName=(?.+?))? packageName=(?.+?)(?: versioning=(?[a-z-]+?))?\\sgitBranch=(?.+?)\\s+?https:\/\/.+?archive\/(?.+?).zip\\s"
+ ],
+ "datasourceTemplate": "git-refs",
+ "currentValueTemplate": "{{{gitBranch}}}",
+ "versioningTemplate": "{{#if versioning}}{{{versioning}}}{{else}}git{{/if}}"
+ }
+ ],
+ "packageRules": []
+}
diff --git a/src/AmbientLightingThread.h b/src/AmbientLightingThread.h
index c487f9d53..bff8846d6 100644
--- a/src/AmbientLightingThread.h
+++ b/src/AmbientLightingThread.h
@@ -6,6 +6,11 @@
NCP5623 rgb;
#endif
+#ifdef HAS_LP5562
+#include
+LP5562 rgbw;
+#endif
+
#ifdef HAS_NEOPIXEL
#include
Adafruit_NeoPixel pixels(NEOPIXEL_COUNT, NEOPIXEL_DATA, NEOPIXEL_TYPE);
@@ -26,7 +31,7 @@ class AmbientLightingThread : public concurrency::OSThread
notifyDeepSleepObserver.observe(¬ifyDeepSleep); // Let us know when shutdown() is issued.
// Enables Ambient Lighting by default if conditions are meet.
-#if defined(HAS_NCP5623) || defined(RGBLED_RED) || defined(HAS_NEOPIXEL) || defined(UNPHONE)
+#ifdef HAS_RGB_LED
#ifdef ENABLE_AMBIENTLIGHTING
moduleConfig.ambient_lighting.led_state = true;
#endif
@@ -39,7 +44,7 @@ class AmbientLightingThread : public concurrency::OSThread
// moduleConfig.ambient_lighting.green = (myNodeInfo.my_node_num & 0x00FF00) >> 8;
// moduleConfig.ambient_lighting.blue = myNodeInfo.my_node_num & 0x0000FF;
-#ifdef HAS_NCP5623
+#if defined(HAS_NCP5623) || defined(HAS_LP5562)
_type = type;
if (_type == ScanI2C::DeviceType::NONE) {
LOG_DEBUG("AmbientLighting Disable due to no RGB leds found on I2C bus");
@@ -47,17 +52,21 @@ class AmbientLightingThread : public concurrency::OSThread
return;
}
#endif
-#if defined(HAS_NCP5623) || defined(RGBLED_RED) || defined(HAS_NEOPIXEL) || defined(UNPHONE)
+#ifdef HAS_RGB_LED
if (!moduleConfig.ambient_lighting.led_state) {
LOG_DEBUG("AmbientLighting Disable due to moduleConfig.ambient_lighting.led_state OFF");
disable();
return;
}
LOG_DEBUG("AmbientLighting init");
-#ifdef HAS_NCP5623
+#if defined(HAS_NCP5623) || defined(HAS_LP5562)
if (_type == ScanI2C::NCP5623) {
rgb.begin();
#endif
+#ifdef HAS_LP5562
+ } else if (_type == ScanI2C::LP5562) {
+ rgbw.begin();
+#endif
#ifdef RGBLED_RED
pinMode(RGBLED_RED, OUTPUT);
pinMode(RGBLED_GREEN, OUTPUT);
@@ -70,7 +79,7 @@ class AmbientLightingThread : public concurrency::OSThread
#endif
setLighting();
#endif
-#ifdef HAS_NCP5623
+#if defined(HAS_NCP5623) || defined(HAS_LP5562)
}
#endif
}
@@ -78,13 +87,13 @@ class AmbientLightingThread : public concurrency::OSThread
protected:
int32_t runOnce() override
{
-#if defined(HAS_NCP5623) || defined(RGBLED_RED) || defined(HAS_NEOPIXEL) || defined(UNPHONE)
-#ifdef HAS_NCP5623
- if (_type == ScanI2C::NCP5623 && moduleConfig.ambient_lighting.led_state) {
+#ifdef HAS_RGB_LED
+#if defined(HAS_NCP5623) || defined(HAS_LP5562)
+ if ((_type == ScanI2C::NCP5623 || _type == ScanI2C::LP5562) && moduleConfig.ambient_lighting.led_state) {
#endif
setLighting();
return 30000; // 30 seconds to reset from any animations that may have been running from Ext. Notification
-#ifdef HAS_NCP5623
+#if defined(HAS_NCP5623) || defined(HAS_LP5562)
}
#endif
#endif
@@ -108,6 +117,14 @@ class AmbientLightingThread : public concurrency::OSThread
rgb.setBlue(0);
LOG_INFO("OFF: NCP5623 Ambient lighting");
#endif
+#ifdef HAS_LP5562
+ rgbw.setCurrent(0);
+ rgbw.setRed(0);
+ rgbw.setGreen(0);
+ rgbw.setBlue(0);
+ rgbw.setWhite(0);
+ LOG_INFO("OFF: LP5562 Ambient lighting");
+#endif
#ifdef HAS_NEOPIXEL
pixels.clear();
pixels.show();
@@ -141,6 +158,14 @@ class AmbientLightingThread : public concurrency::OSThread
LOG_DEBUG("Init NCP5623 Ambient light w/ current=%d, red=%d, green=%d, blue=%d", moduleConfig.ambient_lighting.current,
moduleConfig.ambient_lighting.red, moduleConfig.ambient_lighting.green, moduleConfig.ambient_lighting.blue);
#endif
+#ifdef HAS_LP5562
+ rgbw.setCurrent(moduleConfig.ambient_lighting.current);
+ rgbw.setRed(moduleConfig.ambient_lighting.red);
+ rgbw.setGreen(moduleConfig.ambient_lighting.green);
+ rgbw.setBlue(moduleConfig.ambient_lighting.blue);
+ LOG_DEBUG("Init LP5562 Ambient light w/ current=%d, red=%d, green=%d, blue=%d", moduleConfig.ambient_lighting.current,
+ moduleConfig.ambient_lighting.red, moduleConfig.ambient_lighting.green, moduleConfig.ambient_lighting.blue);
+#endif
#ifdef HAS_NEOPIXEL
pixels.fill(pixels.Color(moduleConfig.ambient_lighting.red, moduleConfig.ambient_lighting.green,
moduleConfig.ambient_lighting.blue),
diff --git a/src/ButtonThread.cpp b/src/ButtonThread.cpp
index 2363f804c..04200a7df 100644
--- a/src/ButtonThread.cpp
+++ b/src/ButtonThread.cpp
@@ -116,46 +116,55 @@ ButtonThread::ButtonThread() : OSThread("Button")
#endif
}
+void ButtonThread::switchPage()
+{
+#ifdef BUTTON_PIN
+#if !defined(USERPREFS_BUTTON_PIN)
+ if (((config.device.button_gpio ? config.device.button_gpio : BUTTON_PIN) !=
+ moduleConfig.canned_message.inputbroker_pin_press) ||
+ !(moduleConfig.canned_message.updown1_enabled || moduleConfig.canned_message.rotary1_enabled) ||
+ !moduleConfig.canned_message.enabled) {
+ powerFSM.trigger(EVENT_PRESS);
+ }
+#endif
+#if defined(USERPREFS_BUTTON_PIN)
+ if (((config.device.button_gpio ? config.device.button_gpio : USERPREFS_BUTTON_PIN) !=
+ moduleConfig.canned_message.inputbroker_pin_press) ||
+ !(moduleConfig.canned_message.updown1_enabled || moduleConfig.canned_message.rotary1_enabled) ||
+ !moduleConfig.canned_message.enabled) {
+ powerFSM.trigger(EVENT_PRESS);
+ }
+#endif
+
+#endif
+#if defined(ARCH_PORTDUINO)
+ if ((settingsMap.count(user) != 0 && settingsMap[user] != RADIOLIB_NC) &&
+ (settingsMap[user] != moduleConfig.canned_message.inputbroker_pin_press) ||
+ !moduleConfig.canned_message.enabled) {
+ powerFSM.trigger(EVENT_PRESS);
+ }
+#endif
+}
+
+void ButtonThread::sendAdHocPosition()
+{
+ service->refreshLocalMeshNode();
+ auto sentPosition = service->trySendPosition(NODENUM_BROADCAST, true);
+ if (screen) {
+ if (sentPosition)
+ screen->print("Sent ad-hoc position\n");
+ else
+ screen->print("Sent ad-hoc nodeinfo\n");
+ screen->forceDisplay(true); // Force a new UI frame, then force an EInk update
+ }
+}
+
int32_t ButtonThread::runOnce()
{
// If the button is pressed we suppress CPU sleep until release
canSleep = true; // Assume we should not keep the board awake
#if defined(BUTTON_PIN) || defined(USERPREFS_BUTTON_PIN)
- // #if defined(ELECROW_ThinkNode_M1) || defined(ELECROW_ThinkNode_M2)
- // buzzer_updata();
- // if (buttonPressed) {
- // buttonPressed = false; // 清除标志
- // LOG_INFO("PIN_BUTTON2 pressed!"); // 串口打印信息
- // // off_currentTime = millis();
- // while (digitalRead(PIN_BUTTON2) == HIGH) {
- // if (cont < 40) {
- // // unsigned long currentTime = millis(); // 获取当前时间
- // // if (currentTime - off_currentTime >= 1000) {
- // cont++;
- // // off_currentTime = currentTime;
- // // }
- // delay(100);
- // } else {
-
- // currentState = OFF;
- // isBuzzing = false;
- // cont = 0;
- // BEEP_STATE = false;
- // analogWrite(M2_buzzer, 0);
- // pinMode(M2_buzzer, INPUT);
- // screen->setOn(false);
- // cont = 0;
- // LOG_INFO("GGGGGGGGGGGGGGGGGGGGGGGGG");
- // pinMode(1, OUTPUT);
- // digitalWrite(1, LOW);
- // pinMode(6, OUTPUT);
- // digitalWrite(6, LOW);
- // }
- // }
- // }
-
- // #endif
userButton.tick();
canSleep &= userButton.isIdle();
#elif defined(ARCH_PORTDUINO)
@@ -180,32 +189,27 @@ int32_t ButtonThread::runOnce()
// If a nag notification is running, stop it and prevent other actions
if (moduleConfig.external_notification.enabled && (externalNotificationModule->nagCycleCutoff != UINT32_MAX)) {
externalNotificationModule->stopNow();
- return 50;
- }
-#ifdef BUTTON_PIN
-#if !defined(USERPREFS_BUTTON_PIN)
- if (((config.device.button_gpio ? config.device.button_gpio : BUTTON_PIN) !=
-#endif
-#if defined(USERPREFS_BUTTON_PIN)
- if (((config.device.button_gpio ? config.device.button_gpio : USERPREFS_BUTTON_PIN) !=
-#endif
- moduleConfig.canned_message.inputbroker_pin_press) ||
- !(moduleConfig.canned_message.updown1_enabled || moduleConfig.canned_message.rotary1_enabled) ||
- !moduleConfig.canned_message.enabled) {
- powerFSM.trigger(EVENT_PRESS);
- }
-#endif
-#if defined(ARCH_PORTDUINO)
- if ((settingsMap.count(user) != 0 && settingsMap[user] != RADIOLIB_NC) &&
- (settingsMap[user] != moduleConfig.canned_message.inputbroker_pin_press) ||
- !moduleConfig.canned_message.enabled) {
- powerFSM.trigger(EVENT_PRESS);
+ break;
}
+#ifdef ELECROW_ThinkNode_M1
+ sendAdHocPosition();
+ break;
#endif
+ switchPage();
break;
}
case BUTTON_EVENT_PRESSED_SCREEN: {
+ LOG_BUTTON("AltPress!");
+#ifdef ELECROW_ThinkNode_M1
+ // If a nag notification is running, stop it and prevent other actions
+ if (moduleConfig.external_notification.enabled && (externalNotificationModule->nagCycleCutoff != UINT32_MAX)) {
+ externalNotificationModule->stopNow();
+ break;
+ }
+ switchPage();
+ break;
+#endif
// turn screen on or off
screen_flag = !screen_flag;
if (screen)
@@ -215,22 +219,18 @@ int32_t ButtonThread::runOnce()
case BUTTON_EVENT_DOUBLE_PRESSED: {
LOG_BUTTON("Double press!");
- service->refreshLocalMeshNode();
- auto sentPosition = service->trySendPosition(NODENUM_BROADCAST, true);
- if (screen) {
- if (sentPosition)
- screen->print("Sent ad-hoc position\n");
- else
- screen->print("Sent ad-hoc nodeinfo\n");
- screen->forceDisplay(true); // Force a new UI frame, then force an EInk update
- }
+#ifdef ELECROW_ThinkNode_M1
+ digitalWrite(PIN_EINK_EN, digitalRead(PIN_EINK_EN) == LOW);
+ break;
+#endif
+ sendAdHocPosition();
break;
}
case BUTTON_EVENT_MULTI_PRESSED: {
LOG_BUTTON("Mulitipress! %hux", multipressClickCount);
switch (multipressClickCount) {
-#if HAS_GPS
+#if HAS_GPS && !defined(ELECROW_ThinkNode_M1)
// 3 clicks: toggle GPS
case 3:
if (!config.device.disable_triple_click && (gps != nullptr)) {
@@ -239,17 +239,17 @@ int32_t ButtonThread::runOnce()
screen->forceDisplay(true); // Force a new UI frame, then force an EInk update
}
break;
-#elif defined(ELECROW_ThinkNode_M2)
+#elif defined(ELECROW_ThinkNode_M1) || defined(ELECROW_ThinkNode_M2)
case 3:
LOG_INFO("3 clicks: toggle buzzer");
buzzer_flag = !buzzer_flag;
- if (buzzer_flag) {
- playBeep();
- }
+ if (!buzzer_flag)
+ noTone(PIN_BUZZER);
break;
+
#endif
-#if defined(USE_EINK) && defined(PIN_EINK_EN) // i.e. T-Echo
+#if defined(USE_EINK) && defined(PIN_EINK_EN) && !defined(ELECROW_ThinkNode_M1) // i.e. T-Echo
// 4 clicks: toggle backlight
case 4:
digitalWrite(PIN_EINK_EN, digitalRead(PIN_EINK_EN) == LOW);
@@ -349,8 +349,12 @@ void ButtonThread::attachButtonInterrupts()
#endif
#ifdef BUTTON_PIN_ALT
+#ifdef ELECROW_ThinkNode_M2
+ wakeOnIrq(BUTTON_PIN_ALT, RISING);
+#else
wakeOnIrq(BUTTON_PIN_ALT, FALLING);
#endif
+#endif
#ifdef BUTTON_PIN_TOUCH
wakeOnIrq(BUTTON_PIN_TOUCH, FALLING);
diff --git a/src/ButtonThread.h b/src/ButtonThread.h
index a8f1f77c3..3af700dd0 100644
--- a/src/ButtonThread.h
+++ b/src/ButtonThread.h
@@ -37,6 +37,9 @@ class ButtonThread : public concurrency::OSThread
void attachButtonInterrupts();
void detachButtonInterrupts();
void storeClickCount();
+ bool isBuzzing() { return buzzer_flag; }
+ void setScreenFlag(bool flag) { screen_flag = flag; }
+ bool getScreenFlag() { return screen_flag; }
// Disconnect and reconnect interrupts for light sleep
#ifdef ARCH_ESP32
@@ -72,14 +75,12 @@ class ButtonThread : public concurrency::OSThread
static void wakeOnIrq(int irq, int mode);
+ static void sendAdHocPosition();
+ static void switchPage();
+
// IRQ callbacks
static void userButtonPressed() { btnEvent = BUTTON_EVENT_PRESSED; }
- static void userButtonPressedScreen()
- {
- if (millis() > c_holdOffTime) {
- btnEvent = BUTTON_EVENT_PRESSED_SCREEN;
- }
- }
+ static void userButtonPressedScreen() { btnEvent = BUTTON_EVENT_PRESSED_SCREEN; }
static void userButtonDoublePressed() { btnEvent = BUTTON_EVENT_DOUBLE_PRESSED; }
static void userButtonMultiPressed(void *callerThread); // Retrieve click count from non-static Onebutton while still valid
static void userButtonPressedLongStart();
diff --git a/src/DisplayFormatters.cpp b/src/DisplayFormatters.cpp
index 0718ffcbd..44bc0897b 100644
--- a/src/DisplayFormatters.cpp
+++ b/src/DisplayFormatters.cpp
@@ -27,9 +27,6 @@ const char *DisplayFormatters::getModemPresetDisplayName(meshtastic_Config_LoRaC
case meshtastic_Config_LoRaConfig_ModemPreset_LONG_MODERATE:
return useShortName ? "LongM" : "LongMod";
break;
- case meshtastic_Config_LoRaConfig_ModemPreset_VERY_LONG_SLOW:
- return useShortName ? "VeryL" : "VLongSlow";
- break;
default:
return useShortName ? "Custom" : "Invalid";
break;
diff --git a/src/Power.cpp b/src/Power.cpp
index 0dec0fc21..f11f8eac3 100644
--- a/src/Power.cpp
+++ b/src/Power.cpp
@@ -380,6 +380,20 @@ class AnalogBatteryLevel : public HasBatteryLevel
// if we have a integrated device with a battery, we can assume that the battery is always connected
#ifdef BATTERY_IMMUTABLE
virtual bool isBatteryConnect() override { return true; }
+#elif defined(ADC_V)
+ virtual bool isBatteryConnect() override
+ {
+ int lastReading = digitalRead(ADC_V);
+ // 判断值是否变化
+ for (int i = 2; i < 500; i++) {
+ int reading = digitalRead(ADC_V);
+ if (reading != lastReading) {
+ return false; // 有变化,USB供电, 没接电池
+ }
+ }
+
+ return true;
+ }
#else
virtual bool isBatteryConnect() override { return getBatteryPercent() != -1; }
#endif
@@ -533,9 +547,6 @@ Power::Power() : OSThread("Power")
{
statusHandler = {};
low_voltage_counter = 0;
-#if defined(ELECROW_ThinkNode_M1) || defined(POWER_CFG)
- low_voltage_counter_led3 = 0;
-#endif
#ifdef DEBUG_HEAP
lastheap = memGet.getFreeHeap();
#endif
@@ -716,9 +727,6 @@ void Power::readPowerStatus()
const PowerStatus powerStatus2 = PowerStatus(hasBattery, usbPowered, isChargingNow, batteryVoltageMv, batteryChargePercent);
LOG_DEBUG("Battery: usbPower=%d, isCharging=%d, batMv=%d, batPct=%d", powerStatus2.getHasUSB(), powerStatus2.getIsCharging(),
powerStatus2.getBatteryVoltageMv(), powerStatus2.getBatteryChargePercent());
-#if defined(ELECROW_ThinkNode_M1) || defined(POWER_CFG)
- power_num = powerStatus2.getBatteryVoltageMv();
-#endif
newStatus.notifyObservers(&powerStatus2);
#ifdef DEBUG_HEAP
if (lastheap != memGet.getFreeHeap()) {
@@ -766,9 +774,6 @@ void Power::readPowerStatus()
if (batteryLevel && powerStatus2.getHasBattery() && !powerStatus2.getHasUSB()) {
if (batteryLevel->getBattVoltage() < OCV[NUM_OCV_POINTS - 1]) {
low_voltage_counter++;
-#if defined(ELECROW_ThinkNode_M1)
- low_voltage_counter_led3 = low_voltage_counter;
-#endif
LOG_DEBUG("Low voltage counter: %d/10", low_voltage_counter);
if (low_voltage_counter > 10) {
#ifdef ARCH_NRF52
@@ -781,13 +786,7 @@ void Power::readPowerStatus()
}
} else {
low_voltage_counter = 0;
-#if defined(ELECROW_ThinkNode_M1)
- low_voltage_counter_led3 = low_voltage_counter;
-#endif
}
-#ifdef POWER_CFG
- low_voltage_counter_led3 = low_voltage_counter;
-#endif
}
}
diff --git a/src/configuration.h b/src/configuration.h
index fd4a5b196..d319ddb0a 100644
--- a/src/configuration.h
+++ b/src/configuration.h
@@ -152,6 +152,7 @@ along with this program. If not, see .
#define MLX90614_ADDR_DEF 0x5A
#define CGRADSENS_ADDR 0x66
#define LTR390UV_ADDR 0x53
+#define XPOWERS_AXP192_AXP2101_ADDRESS 0x34 // same adress as TCA8418
// -----------------------------------------------------------------------------
// ACCELEROMETER
@@ -170,6 +171,7 @@ along with this program. If not, see .
// LED
// -----------------------------------------------------------------------------
#define NCP5623_ADDR 0x38
+#define LP5562_ADDR 0x30
// -----------------------------------------------------------------------------
// Security
@@ -295,6 +297,11 @@ along with this program. If not, see .
#error HW_VENDOR must be defined
#endif
+// Support multiple RGB LED configuration
+#if defined(HAS_NCP5623) || defined(HAS_LP5562) || defined(RGBLED_RED) || defined(HAS_NEOPIXEL) || defined(UNPHONE)
+#define HAS_RGB_LED
+#endif
+
// -----------------------------------------------------------------------------
// Global switches to turn off features for a minimized build
// -----------------------------------------------------------------------------
diff --git a/src/detect/ScanI2C.cpp b/src/detect/ScanI2C.cpp
index 4caa0f730..5bd5c0d12 100644
--- a/src/detect/ScanI2C.cpp
+++ b/src/detect/ScanI2C.cpp
@@ -31,8 +31,8 @@ ScanI2C::FoundDevice ScanI2C::firstRTC() const
ScanI2C::FoundDevice ScanI2C::firstKeyboard() const
{
- ScanI2C::DeviceType types[] = {CARDKB, TDECKKB, BBQ10KB, RAK14004, MPR121KB};
- return firstOfOrNONE(5, types);
+ ScanI2C::DeviceType types[] = {CARDKB, TDECKKB, BBQ10KB, RAK14004, MPR121KB, TCA8418KB};
+ return firstOfOrNONE(6, types);
}
ScanI2C::FoundDevice ScanI2C::firstAccelerometer() const
@@ -41,6 +41,12 @@ ScanI2C::FoundDevice ScanI2C::firstAccelerometer() const
return firstOfOrNONE(8, types);
}
+ScanI2C::FoundDevice ScanI2C::firstRGBLED() const
+{
+ ScanI2C::DeviceType types[] = {NCP5623, LP5562};
+ return firstOfOrNONE(2, types);
+}
+
ScanI2C::FoundDevice ScanI2C::find(ScanI2C::DeviceType) const
{
return DEVICE_NONE;
diff --git a/src/detect/ScanI2C.h b/src/detect/ScanI2C.h
index 5b6bbe629..c363db1b5 100644
--- a/src/detect/ScanI2C.h
+++ b/src/detect/ScanI2C.h
@@ -18,7 +18,7 @@ class ScanI2C
TDECKKB,
BBQ10KB,
RAK14004,
- PMU_AXP192_AXP2101,
+ PMU_AXP192_AXP2101, // has the same adress as the TCA8418KB
BME_680,
BME_280,
BMP_280,
@@ -49,6 +49,7 @@ class ScanI2C
VEML7700,
RCWL9620,
NCP5623,
+ LP5562,
TSL2591,
OPT3001,
MLX90632,
@@ -69,6 +70,7 @@ class ScanI2C
DFROBOT_RAIN,
DPS310,
LTR390UV,
+ TCA8418KB,
} DeviceType;
// typedef uint8_t DeviceAddress;
@@ -121,6 +123,8 @@ class ScanI2C
FoundDevice firstAccelerometer() const;
+ FoundDevice firstRGBLED() const;
+
virtual FoundDevice find(DeviceType) const;
virtual bool exists(DeviceType) const;
diff --git a/src/detect/ScanI2CTwoWire.cpp b/src/detect/ScanI2CTwoWire.cpp
index 8b779277d..9781cbf56 100644
--- a/src/detect/ScanI2CTwoWire.cpp
+++ b/src/detect/ScanI2CTwoWire.cpp
@@ -10,11 +10,6 @@
#include "meshUtils.h" // vformat
#endif
-// AXP192 and AXP2101 have the same device address, we just need to identify it in Power.cpp
-#ifndef XPOWERS_AXP192_AXP2101_ADDRESS
-#define XPOWERS_AXP192_AXP2101_ADDRESS 0x34
-#endif
-
bool in_array(uint8_t *array, int size, uint8_t lookfor)
{
int i;
@@ -218,9 +213,20 @@ void ScanI2CTwoWire::scanPort(I2CPort port, uint8_t *address, uint8_t asize)
#ifdef HAS_NCP5623
SCAN_SIMPLE_CASE(NCP5623_ADDR, NCP5623, "NCP5623", (uint8_t)addr.address);
#endif
-#ifdef HAS_PMU
- SCAN_SIMPLE_CASE(XPOWERS_AXP192_AXP2101_ADDRESS, PMU_AXP192_AXP2101, "AXP192/AXP2101", (uint8_t)addr.address)
+#ifdef HAS_LP5562
+ SCAN_SIMPLE_CASE(LP5562_ADDR, LP5562, "LP5562", (uint8_t)addr.address);
#endif
+ case XPOWERS_AXP192_AXP2101_ADDRESS:
+ // Do we have the axp2101/192 or the TCA8418
+ registerValue = getRegisterValue(ScanI2CTwoWire::RegisterLocation(addr, 0x90), 1);
+ if (registerValue == 0x0) {
+ logFoundDevice("TCA8418", (uint8_t)addr.address);
+ type = TCA8418KB;
+ } else {
+ logFoundDevice("AXP192/AXP2101", (uint8_t)addr.address);
+ type = PMU_AXP192_AXP2101;
+ }
+ break;
case BME_ADDR:
case BME_ADDR_ALTERNATE:
registerValue = getRegisterValue(ScanI2CTwoWire::RegisterLocation(addr, 0xD0), 1); // GET_ID
diff --git a/src/gps/GPS.cpp b/src/gps/GPS.cpp
index 41a2ff980..55f62d8ad 100644
--- a/src/gps/GPS.cpp
+++ b/src/gps/GPS.cpp
@@ -12,6 +12,7 @@
#include "RTC.h"
#include "Throttle.h"
#include "buzz.h"
+#include "concurrency/Periodic.h"
#include "meshUtils.h"
#include "main.h" // pmu_found
@@ -89,6 +90,45 @@ static const char *getGPSPowerStateString(GPSPowerState state)
}
}
+#ifdef PIN_GPS_SWITCH
+// If we have a hardware switch, define a periodic watcher outside of the GPS runOnce thread, since this can be sleeping
+// idefinitely
+
+int lastState = LOW;
+bool firstrun = true;
+
+static int32_t gpsSwitch()
+{
+ if (gps) {
+ int currentState = digitalRead(PIN_GPS_SWITCH);
+
+ // if the switch is set to zero, disable the GPS Thread
+ if (firstrun)
+ if (currentState == LOW)
+ lastState = HIGH;
+
+ if (currentState != lastState) {
+ if (currentState == LOW) {
+ config.position.gps_mode = meshtastic_Config_PositionConfig_GpsMode_DISABLED;
+ if (!firstrun)
+ playGPSDisableBeep();
+ gps->disable();
+ } else {
+ config.position.gps_mode = meshtastic_Config_PositionConfig_GpsMode_ENABLED;
+ if (!firstrun)
+ playGPSEnableBeep();
+ gps->enable();
+ }
+ lastState = currentState;
+ }
+ firstrun = false;
+ }
+ return 1000;
+}
+
+static concurrency::Periodic *gpsPeriodic;
+#endif
+
static void UBXChecksum(uint8_t *message, size_t length)
{
uint8_t CK_A = 0, CK_B = 0;
@@ -770,13 +810,6 @@ void GPS::setPowerState(GPSPowerState newState, uint32_t sleepTime)
powerState = newState;
LOG_INFO("GPS power state move from %s to %s", getGPSPowerStateString(oldState), getGPSPowerStateString(newState));
-#ifdef HELTEC_MESH_NODE_T114
- if ((oldState == GPS_OFF || oldState == GPS_HARDSLEEP) && (newState != GPS_OFF && newState != GPS_HARDSLEEP)) {
- _serial_gps->begin(serialSpeeds[speedSelect]);
- } else if ((newState == GPS_OFF || newState == GPS_HARDSLEEP) && (oldState != GPS_OFF && oldState != GPS_HARDSLEEP)) {
- _serial_gps->end();
- }
-#endif
switch (newState) {
case GPS_ACTIVE:
case GPS_IDLE:
@@ -1206,7 +1239,8 @@ GnssModel_t GPS::probe(int serialSpeed)
delay(20);
std::vector mtk = {{"L76B", "Quectel-L76B", GNSS_MODEL_MTK_L76B},
{"PA1616S", "1616S", GNSS_MODEL_MTK_PA1616S},
- {"LS20031", "MC-1513", GNSS_MODEL_MTK_L76B}};
+ {"LS20031", "MC-1513", GNSS_MODEL_MTK_L76B},
+ {"L96", "Quectel-L96", GNSS_MODEL_MTK_L76B}};
PROBE_FAMILY("MTK Family", "$PMTK605*31", mtk, 500);
uint8_t cfg_rate[] = {0xB5, 0x62, 0x06, 0x08, 0x00, 0x00, 0x00, 0x00};
@@ -1389,6 +1423,12 @@ GPS *GPS::createGps()
pinMode(PIN_GPS_PPS, INPUT);
#endif
+#ifdef PIN_GPS_SWITCH
+ // toggle GPS via external GPIO switch
+ pinMode(PIN_GPS_SWITCH, INPUT);
+ gpsPeriodic = new concurrency::Periodic("GPSSwitch", gpsSwitch);
+#endif
+
// Currently disabled per issue #525 (TinyGPS++ crash bug)
// when fixed upstream, can be un-disabled to enable 3D FixType and PDOP
#ifndef TINYGPS_OPTION_NO_CUSTOM_FIELDS
diff --git a/src/gps/ubx.h b/src/gps/ubx.h
index d674bed51..0fe2f01fb 100644
--- a/src/gps/ubx.h
+++ b/src/gps/ubx.h
@@ -224,7 +224,7 @@ static const uint8_t _message_GSA[] = {
0x00, // Rate for DDC
0x00, // Rate for UART1
0x00, // Rate for UART2
- 0x00, // Rate for USB usefull for native linux
+ 0x00, // Rate for USB useful for native linux
0x00, // Rate for SPI
0x00 // Reserved
};
@@ -258,7 +258,7 @@ static const uint8_t _message_RMC[] = {
0x00, // Rate for DDC
0x01, // Rate for UART1
0x00, // Rate for UART2
- 0x01, // Rate for USB usefull for native linux
+ 0x01, // Rate for USB useful for native linux
0x00, // Rate for SPI
0x00 // Reserved
};
@@ -269,7 +269,7 @@ static const uint8_t _message_GGA[] = {
0x00, // Rate for DDC
0x01, // Rate for UART1
0x00, // Rate for UART2
- 0x01, // Rate for USB, usefull for native linux
+ 0x01, // Rate for USB, useful for native linux
0x00, // Rate for SPI
0x00 // Reserved
};
diff --git a/src/graphics/EInkDisplay2.cpp b/src/graphics/EInkDisplay2.cpp
index 96c6b44c1..d2d373d24 100644
--- a/src/graphics/EInkDisplay2.cpp
+++ b/src/graphics/EInkDisplay2.cpp
@@ -129,9 +129,10 @@ bool EInkDisplay::connect()
// backlight power, HIGH is backlight on, LOW is off
pinMode(PIN_EINK_EN, OUTPUT);
#ifdef ELECROW_ThinkNode_M1
- digitalWrite(PIN_EINK_EN, LOW);
-#else
+ // ThinkNode M1 has a hardware dimmable backlight. Start enabled
digitalWrite(PIN_EINK_EN, HIGH);
+#else
+ digitalWrite(PIN_EINK_EN, LOW);
#endif
#endif
diff --git a/src/graphics/NomadStarLED.h b/src/graphics/NomadStarLED.h
new file mode 100644
index 000000000..0633a577e
--- /dev/null
+++ b/src/graphics/NomadStarLED.h
@@ -0,0 +1,5 @@
+#ifdef HAS_LP5562
+#include
+extern LP5562 rgbw;
+
+#endif
\ No newline at end of file
diff --git a/src/graphics/Screen.cpp b/src/graphics/Screen.cpp
index e27495f54..8075dd468 100644
--- a/src/graphics/Screen.cpp
+++ b/src/graphics/Screen.cpp
@@ -30,6 +30,7 @@ along with this program. If not, see .
#if !MESHTASTIC_EXCLUDE_GPS
#include "GPS.h"
#endif
+#include "ButtonThread.h"
#include "MeshService.h"
#include "NodeDB.h"
#include "error.h"
@@ -1606,6 +1607,7 @@ void Screen::handleSetOn(bool on, FrameCallback einkScreensaver)
if (on != screenOn) {
if (on) {
LOG_INFO("Turn on screen");
+ buttonThread->setScreenFlag(true);
powerMon->setState(meshtastic_PowerMon_State_Screen_On);
#ifdef T_WATCH_S3
PMU->enablePowerOutput(XPOWERS_ALDO2);
@@ -1641,6 +1643,7 @@ void Screen::handleSetOn(bool on, FrameCallback einkScreensaver)
setScreensaverFrames(einkScreensaver);
#endif
LOG_INFO("Turn off screen");
+ buttonThread->setScreenFlag(false);
#ifdef ELECROW_ThinkNode_M1
if (digitalRead(PIN_EINK_EN) == HIGH) {
digitalWrite(PIN_EINK_EN, LOW);
diff --git a/src/graphics/ScreenFonts.h b/src/graphics/ScreenFonts.h
index 910d1b0b9..079a3e282 100644
--- a/src/graphics/ScreenFonts.h
+++ b/src/graphics/ScreenFonts.h
@@ -16,6 +16,10 @@
#include "graphics/fonts/OLEDDisplayFontsCS.h"
#endif
+#ifdef CROWPANEL_ESP32S3_5_EPAPER
+#include "graphics/fonts/EinkDisplayFonts.h"
+#endif
+
#ifdef OLED_PL
#define FONT_SMALL_LOCAL ArialMT_Plain_10_PL
#else
@@ -74,13 +78,12 @@
#endif
#if defined(CROWPANEL_ESP32S3_5_EPAPER)
-#include "graphics/fonts/EinkDisplayFonts.h"
#undef FONT_SMALL
#undef FONT_MEDIUM
#undef FONT_LARGE
-#define FONT_SMALL FONT_LARGE_LOCAL // Height: 30
-#define FONT_MEDIUM FONT_LARGE_LOCAL // Height: 30
-#define FONT_LARGE FONT_LARGE_LOCAL // Height: 30
+#define FONT_SMALL Monospaced_plain_30
+#define FONT_MEDIUM Monospaced_plain_30
+#define FONT_LARGE Monospaced_plain_30
#endif
#define _fontHeight(font) ((font)[1] + 1) // height is position 1
diff --git a/src/graphics/niche/Drivers/EInk/DEPG0154BNS800.cpp b/src/graphics/niche/Drivers/EInk/DEPG0154BNS800.cpp
deleted file mode 100644
index b8715ed1d..000000000
--- a/src/graphics/niche/Drivers/EInk/DEPG0154BNS800.cpp
+++ /dev/null
@@ -1 +0,0 @@
-#include "./DEPG0154BNS800.h"
\ No newline at end of file
diff --git a/src/graphics/niche/Drivers/EInk/DEPG0154BNS800.h b/src/graphics/niche/Drivers/EInk/DEPG0154BNS800.h
deleted file mode 100644
index 62d42ef57..000000000
--- a/src/graphics/niche/Drivers/EInk/DEPG0154BNS800.h
+++ /dev/null
@@ -1,34 +0,0 @@
-/*
-
-E-Ink display driver
- - DEPG0154BNS800
- - Manufacturer: DKE
- - Size: 1.54 inch
- - Resolution: 152px x 152px
- - Flex connector marking: FPC7525
-
-*/
-
-#pragma once
-
-#ifdef MESHTASTIC_INCLUDE_NICHE_GRAPHICS
-#include "configuration.h"
-
-#include "./SSD16XX.h"
-
-namespace NicheGraphics::Drivers
-{
-class DEPG0154BNS800 : public SSD16XX
-{
- // Display properties
- private:
- static constexpr uint32_t width = 152;
- static constexpr uint32_t height = 152;
- static constexpr UpdateTypes supported = (UpdateTypes)(FULL);
-
- public:
- DEPG0154BNS800() : SSD16XX(width, height, supported, 1) {} // Note: left edge of this display is offset by 1 byte
-};
-
-} // namespace NicheGraphics::Drivers
-#endif // MESHTASTIC_INCLUDE_NICHE_GRAPHICS
\ No newline at end of file
diff --git a/src/graphics/niche/Drivers/EInk/DEPG0213BNS800.cpp b/src/graphics/niche/Drivers/EInk/DEPG0213BNS800.cpp
new file mode 100644
index 000000000..2c8df96ed
--- /dev/null
+++ b/src/graphics/niche/Drivers/EInk/DEPG0213BNS800.cpp
@@ -0,0 +1,132 @@
+#include "./DEPG0213BNS800.h"
+
+#ifdef MESHTASTIC_INCLUDE_NICHE_GRAPHICS
+
+using namespace NicheGraphics::Drivers;
+
+// Describes the operation performed when a "fast refresh" is performed
+// Source: Modified from GxEPD2 (GxEPD2_213_BN)
+static const uint8_t LUT_FAST[] = {
+ // 1 2 3
+ 0x00, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // B2B (Existing black pixels)
+ 0x80, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // B2W (New white pixels)
+ 0x40, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // W2B (New black pixels)
+ 0x00, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // W2W (Existing white pixels)
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // VCOM
+
+ 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, // 1. Any pixels changing W2B or B2W. Two medium taps.
+ 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // 2. All pixels. One short tap.
+ 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // 3. Cooldown
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, //
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, //
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, //
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, //
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, //
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, //
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, //
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, //
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, //
+ 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x00, 0x00, 0x00, //
+};
+
+// How strongly the pixels are pulled and pushed
+void DEPG0213BNS800::configVoltages()
+{
+ switch (updateType) {
+ case FAST:
+ // Reference: display datasheet, GxEPD1
+ sendCommand(0x03); // Gate voltage
+ sendData(0x17); // VGH: 20V
+
+ // Reference: display datasheet, GxEPD1
+ sendCommand(0x04); // Source voltage
+ sendData(0x41); // VSH1: 15V
+ sendData(0x00); // VSH2: NA
+ sendData(0x32); // VSL: -15V
+
+ // GxEPD1 sets this at -1.2V, but that seems to be drive the pixels very hard
+ sendCommand(0x2C); // VCOM voltage
+ sendData(0x08); // VCOM: -0.2V
+ break;
+
+ case FULL:
+ default:
+ // From OTP memory
+ break;
+ }
+}
+
+// Load settings about how the pixels are moved from old state to new state during a refresh
+// - manually specified,
+// - or with stored values from displays OTP memory
+void DEPG0213BNS800::configWaveform()
+{
+ switch (updateType) {
+ case FAST:
+ sendCommand(0x3C); // Border waveform:
+ sendData(0x80); // VSS
+
+ sendCommand(0x32); // Write LUT register from MCU:
+ sendData(LUT_FAST, sizeof(LUT_FAST)); // (describes operation for a FAST refresh)
+ break;
+
+ case FULL:
+ default:
+ // From OTP memory
+ break;
+ }
+}
+
+// Describes the sequence of events performed by the displays controller IC during a refresh
+// Includes "power up", "load settings from memory", "update the pixels", etc
+void DEPG0213BNS800::configUpdateSequence()
+{
+ switch (updateType) {
+ case FAST:
+ sendCommand(0x22); // Set "update sequence"
+ sendData(0xCF); // Differential, use manually loaded waveform
+ break;
+
+ case FULL:
+ default:
+ sendCommand(0x22); // Set "update sequence"
+ sendData(0xF7); // Non-differential, load waveform from OTP
+ break;
+ }
+}
+
+// Once the refresh operation has been started,
+// begin periodically polling the display to check for completion, using the normal Meshtastic threading code
+// Only used when refresh is "async"
+void DEPG0213BNS800::detachFromUpdate()
+{
+ switch (updateType) {
+ case FAST:
+ return beginPolling(50, 500); // At least 500ms, then poll every 50ms
+ case FULL:
+ default:
+ return beginPolling(100, 3500); // At least 3500ms, then poll every 100ms
+ }
+}
+
+// For this display, we do not need to re-write the new image.
+// We're overriding SSD16XX::finalizeUpdate to make this small optimization.
+// The display does also work just fine with the generic SSD16XX method, though.
+void DEPG0213BNS800::finalizeUpdate()
+{
+ // Put a copy of the image into the "old memory".
+ // Used with differential refreshes (e.g. FAST update), to determine which px need to move, and which can remain in place
+ // We need to keep the "old memory" up to date, because don't know whether next refresh will be FULL or FAST etc.
+ if (updateType != FULL) {
+ // writeNewImage(); // Not required for this display
+ writeOldImage();
+ sendCommand(0x7F); // Terminate image write without update
+ wait();
+ }
+
+ // Enter deep-sleep to save a few µA
+ // Waking from this requires that display's reset pin is broken out
+ if (pin_rst != 0xFF)
+ deepSleep();
+}
+#endif // MESHTASTIC_INCLUDE_NICHE_GRAPHICS
\ No newline at end of file
diff --git a/src/graphics/niche/Drivers/EInk/DEPG0213BNS800.h b/src/graphics/niche/Drivers/EInk/DEPG0213BNS800.h
new file mode 100644
index 000000000..e1bb96450
--- /dev/null
+++ b/src/graphics/niche/Drivers/EInk/DEPG0213BNS800.h
@@ -0,0 +1,44 @@
+/*
+
+E-Ink display driver
+ - DEPG0213BNS800
+ - Manufacturer: DKE
+ - Size: 2.13 inch
+ - Resolution: 122px x 250px
+ - Flex connector marking: FPC-7528B
+
+ Note: this is from an older generation of DKE panels, which still used Solomon Systech controller ICs.
+ DKE's website suggests that the latest DEPG0213BN displays may use Fitipower controllers instead.
+*/
+
+#pragma once
+
+#ifdef MESHTASTIC_INCLUDE_NICHE_GRAPHICS
+
+#include "configuration.h"
+
+#include "./SSD16XX.h"
+
+namespace NicheGraphics::Drivers
+{
+class DEPG0213BNS800 : public SSD16XX
+{
+ // Display properties
+ private:
+ static constexpr uint32_t width = 122;
+ static constexpr uint32_t height = 250;
+ static constexpr UpdateTypes supported = (UpdateTypes)(FULL | FAST);
+
+ public:
+ DEPG0213BNS800() : SSD16XX(width, height, supported, 1) {} // Note: left edge of this display is offset by 1 byte
+
+ protected:
+ void configVoltages() override;
+ void configWaveform() override;
+ void configUpdateSequence() override;
+ void detachFromUpdate() override;
+ void finalizeUpdate() override; // Only overriden for a slight optimization
+};
+
+} // namespace NicheGraphics::Drivers
+#endif // MESHTASTIC_INCLUDE_NICHE_GRAPHICS
\ No newline at end of file
diff --git a/src/graphics/niche/Drivers/EInk/DEPG0290BNS800.cpp b/src/graphics/niche/Drivers/EInk/DEPG0290BNS800.cpp
index 5f3a05670..15134d5ad 100644
--- a/src/graphics/niche/Drivers/EInk/DEPG0290BNS800.cpp
+++ b/src/graphics/niche/Drivers/EInk/DEPG0290BNS800.cpp
@@ -116,5 +116,10 @@ void DEPG0290BNS800::finalizeUpdate()
sendCommand(0x7F); // Terminate image write without update
wait();
}
+
+ // Enter deep-sleep to save a few µA
+ // Waking from this requires that display's reset pin is broken out
+ if (pin_rst != 0xFF)
+ deepSleep();
}
#endif // MESHTASTIC_INCLUDE_NICHE_GRAPHICS
\ No newline at end of file
diff --git a/src/graphics/niche/Drivers/EInk/EInk.cpp b/src/graphics/niche/Drivers/EInk/EInk.cpp
index 043788b13..cd2e9dc98 100644
--- a/src/graphics/niche/Drivers/EInk/EInk.cpp
+++ b/src/graphics/niche/Drivers/EInk/EInk.cpp
@@ -6,7 +6,7 @@ using namespace NicheGraphics::Drivers;
// Separate from EInk::begin method, as derived class constructors can probably supply these parameters as constants
EInk::EInk(uint16_t width, uint16_t height, UpdateTypes supported)
- : concurrency::OSThread("E-Ink Driver"), width(width), height(height), supportedUpdateTypes(supported)
+ : concurrency::OSThread("EInkDriver"), width(width), height(height), supportedUpdateTypes(supported)
{
OSThread::disable();
}
@@ -31,8 +31,8 @@ bool EInk::supports(UpdateTypes type)
void EInk::beginPolling(uint32_t interval, uint32_t expectedDuration)
{
updateRunning = true;
- updateBegunAt = millis();
pollingInterval = interval;
+ pollingBegunAt = millis();
// To minimize load, we can choose to delay polling for a few seconds, if we know roughly how long the update will take
// By default, expectedDuration is 0, and we'll start polling immediately
@@ -45,10 +45,26 @@ void EInk::beginPolling(uint32_t interval, uint32_t expectedDuration)
// This is what allows us to update the display asynchronously
int32_t EInk::runOnce()
{
+ // Check for polling timeout
+ // Manually set at 10 seconds, in case some big task holds up the firmware's cooperative multitasking
+ if (millis() - pollingBegunAt > 10000)
+ failed = true;
+
+ // Handle failure
+ // - polling timeout
+ // - other error (derived classes)
+ if (failed) {
+ LOG_WARN("Display update failed. Check wiring & power supply.");
+ updateRunning = false;
+ failed = false;
+ return disable();
+ }
+
+ // If update not yet done
if (!isUpdateDone())
return pollingInterval; // Poll again in a few ms
- // If update done:
+ // If update done
finalizeUpdate(); // Any post-update code: power down panel hardware, hibernate, etc
updateRunning = false; // Change what we report via EInk::busy()
return disable(); // Stop polling
diff --git a/src/graphics/niche/Drivers/EInk/EInk.h b/src/graphics/niche/Drivers/EInk/EInk.h
index facb8ce72..3c51d4f1d 100644
--- a/src/graphics/niche/Drivers/EInk/EInk.h
+++ b/src/graphics/niche/Drivers/EInk/EInk.h
@@ -24,7 +24,7 @@ class EInk : private concurrency::OSThread
enum UpdateTypes : uint8_t {
UNSPECIFIED = 0,
FULL = 1 << 0,
- FAST = 1 << 1,
+ FAST = 1 << 1, // "Partial Refresh"
};
EInk(uint16_t width, uint16_t height, UpdateTypes supported);
@@ -41,14 +41,15 @@ class EInk : private concurrency::OSThread
void beginPolling(uint32_t interval, uint32_t expectedDuration); // Begin checking repeatedly if update finished
virtual bool isUpdateDone() = 0; // Check once if update finished
virtual void finalizeUpdate() {} // Run any post-update code
+ bool failed = false; // If an error occurred during update
private:
int32_t runOnce() override; // Repeated checking if update finished
const UpdateTypes supportedUpdateTypes; // Capabilities of a derived display class
bool updateRunning = false; // see EInk::busy()
- uint32_t updateBegunAt = 0; // For initial pause before polling for update completion
uint32_t pollingInterval = 0; // How often to check if update complete (ms)
+ uint32_t pollingBegunAt = 0; // To timeout during polling
};
} // namespace NicheGraphics::Drivers
diff --git a/src/graphics/niche/Drivers/EInk/HINK_E042A87.cpp b/src/graphics/niche/Drivers/EInk/HINK_E042A87.cpp
new file mode 100644
index 000000000..1b72bc4a9
--- /dev/null
+++ b/src/graphics/niche/Drivers/EInk/HINK_E042A87.cpp
@@ -0,0 +1,58 @@
+#include "./HINK_E042A87.h"
+
+#ifdef MESHTASTIC_INCLUDE_NICHE_GRAPHICS
+
+using namespace NicheGraphics::Drivers;
+
+// Load settings about how the pixels are moved from old state to new state during a refresh
+// - manually specified,
+// - or with stored values from displays OTP memory
+void HINK_E042A87::configWaveform()
+{
+ sendCommand(0x3C); // Border waveform:
+ sendData(0x01); // Follow LUT for VSH1
+
+ sendCommand(0x18); // Temperature sensor:
+ sendData(0x80); // Use internal temperature sensor to select an appropriate refresh waveform
+}
+
+// Describes the sequence of events performed by the displays controller IC during a refresh
+// Includes "power up", "load settings from memory", "update the pixels", etc
+void HINK_E042A87::configUpdateSequence()
+{
+ switch (updateType) {
+ case FAST:
+ sendCommand(0x21); // Use both "old" and "new" image memory (differential)
+ sendData(0x00);
+ sendData(0x00);
+
+ sendCommand(0x22); // Set "update sequence"
+ sendData(0xFF); // Differential, load waveform from OTP
+ break;
+
+ case FULL:
+ default:
+ sendCommand(0x21); // Bypass "old" image memory (non-differential)
+ sendData(0x40);
+ sendData(0x00);
+
+ sendCommand(0x22); // Set "update sequence":
+ sendData(0xF7); // Non-differential, load waveform from OTP
+ break;
+ }
+}
+
+// Once the refresh operation has been started,
+// begin periodically polling the display to check for completion, using the normal Meshtastic threading code
+// Only used when refresh is "async"
+void HINK_E042A87::detachFromUpdate()
+{
+ switch (updateType) {
+ case FAST:
+ return beginPolling(50, 1000); // At least 1 second, then check every 50ms
+ case FULL:
+ default:
+ return beginPolling(100, 3500); // At least 3.5 seconds, then check every 100ms
+ }
+}
+#endif // MESHTASTIC_INCLUDE_NICHE_GRAPHICS
\ No newline at end of file
diff --git a/src/graphics/niche/Drivers/EInk/HINK_E042A87.h b/src/graphics/niche/Drivers/EInk/HINK_E042A87.h
new file mode 100644
index 000000000..ac03b65ef
--- /dev/null
+++ b/src/graphics/niche/Drivers/EInk/HINK_E042A87.h
@@ -0,0 +1,43 @@
+/*
+
+E-Ink display driver
+ - HINK-E042A87
+ - Manufacturer: Holitech
+ - Size: 4.2 inch
+ - Resolution: 400px x 300px
+ - Flex connector marking: HINK-E042A07-FPC-A1
+ - Silver sticker with QR code, marked: HE042A87
+
+ Note: as of Feb. 2025, these panels are used for "WeActStudio 4.2in B&W" display modules
+
+*/
+
+#pragma once
+
+#ifdef MESHTASTIC_INCLUDE_NICHE_GRAPHICS
+
+#include "configuration.h"
+
+#include "./SSD16XX.h"
+
+namespace NicheGraphics::Drivers
+{
+class HINK_E042A87 : public SSD16XX
+{
+ // Display properties
+ private:
+ static constexpr uint32_t width = 400;
+ static constexpr uint32_t height = 300;
+ static constexpr UpdateTypes supported = (UpdateTypes)(FULL | FAST);
+
+ public:
+ HINK_E042A87() : SSD16XX(width, height, supported) {}
+
+ protected:
+ void configWaveform() override;
+ void configUpdateSequence() override;
+ void detachFromUpdate() override;
+};
+
+} // namespace NicheGraphics::Drivers
+#endif // MESHTASTIC_INCLUDE_NICHE_GRAPHICS
\ No newline at end of file
diff --git a/src/graphics/niche/Drivers/EInk/README.md b/src/graphics/niche/Drivers/EInk/README.md
index 04a23a31f..eca91c6a8 100644
--- a/src/graphics/niche/Drivers/EInk/README.md
+++ b/src/graphics/niche/Drivers/EInk/README.md
@@ -28,6 +28,17 @@ void setupNicheGraphics()
}
```
+- [Methods](#methods)
+ - [`update(uint8_t *imageData, UpdateTypes type)`](#updateuint8_t-imagedata-updatetypes-type)
+ - [`await()`](#await)
+ - [`supports(UpdateTypes type)`](#supportsupdatetypes-type)
+ - [`busy()`](#busy)
+ - [`width()`](#width)
+ - [`height()`](#height)
+- [Supporting New Displays](#supporting-new-displays)
+ - [Controller IC](#controller-ic)
+ - [Finding Information](#finding-information)
+
## Methods
### `update(uint8_t *imageData, UpdateTypes type)`
@@ -37,7 +48,7 @@ Update the image on the display
- _`imageData`_ to draw to the display.
- _`type`_ which type of update to perform.
- `FULL`
- - `FAST`
+ - `FAST` (partial refresh)
- (Other custom types may be possible)
The imageData is a 1-bit image. X-Pixels are 8-per byte, with the MSB being the leftmost pixel. This was not an InkHUD design decision; it is the raw format accepted by the E-Ink display controllers ICs.
@@ -83,3 +94,39 @@ Width of the display, in pixels. Note: most displays are portrait. Your UI will
### `height()`
Height of the display, in pixels. Note: most displays are portrait. Your UI will need to implement rotation in software.
+
+## Supporting New Displays
+
+_This topic is not covered in depth, but these notes may be helpful._
+
+The `InkHUD::Drivers::EInk` class contains only the mechanism for implementing an E-Ink driver on-top of Meshtastic's `OSThread`. A driver for a specific display needs to extend this class.
+
+### Controller IC
+
+If your display uses a controller IC from Solomon Systech, you can probably extend the existing `Drivers::SSD16XX` class, making only minor modifications.
+
+At this stage, displays using controller ICS from other manufacturers (UltraChip, Fitipower, etc) need to manually implemented. See `Drivers::LCMEN2R13EFC1` for an example.
+
+Generic base classes for manufacturers other than Solomon Systech might be added here in future.
+
+### Finding Information
+
+#### Flex-Connector Labels
+
+The orange flex-connector attached to E-Ink displays is often printed with an identifying label. This is not a _totally_ unique identifier, but does give a very strong clue as to the true model of the display, which can be used to search out further information.
+
+#### Datasheets
+
+The manufacturer of a DIY display module may publish a datasheet. These are often incomplete, but might reveal the true model of the display, or the controller IC.
+
+If you can determine the true model name of the display, you can likely find a more complete datasheet on the display manufacturer's website. This will often provide a "typical operating sequence"; a general overview of the code used to drive the display
+
+#### Example Code
+
+The manufacturer of a DIY module may publish example code. You may have more luck finding example code published by the display manufacturer themselves, if you can determine the true model of the panel. These examples are a very valuable reference.
+
+#### Other E-Ink drivers
+
+Libraries like ZinggJM's GxEPD2 can be valuable sources of information, although your panel may not be _specifically_ supported, and only _compatible_ with a driver there, so some caution is advised.
+
+The display selection file in GxEPD2's Hello World example is also a useful resource for matching "flex connector labels" with display models, but the flex connector label is _not_ a unique identifier, so this is only another clue.
diff --git a/src/graphics/niche/Drivers/EInk/SSD16XX.cpp b/src/graphics/niche/Drivers/EInk/SSD16XX.cpp
index 07d02a2ae..a2357a80b 100644
--- a/src/graphics/niche/Drivers/EInk/SSD16XX.cpp
+++ b/src/graphics/niche/Drivers/EInk/SSD16XX.cpp
@@ -37,11 +37,26 @@ void SSD16XX::begin(SPIClass *spi, uint8_t pin_dc, uint8_t pin_cs, uint8_t pin_b
reset();
}
-void SSD16XX::wait()
+// Poll the displays busy pin until an operation is complete
+// Timeout and set fail flag if something went wrong and the display got stuck
+void SSD16XX::wait(uint32_t timeout)
{
+ // Don't bother waiting if part of the update sequence failed
+ // In that situation, we're now just failing-through the process, until we can try again with next update.
+ if (failed)
+ return;
+
+ uint32_t startMs = millis();
+
// Busy when HIGH
- while (digitalRead(pin_busy) == HIGH)
+ while (digitalRead(pin_busy) == HIGH) {
+ // Check for timeout
+ if (millis() - startMs > timeout) {
+ failed = true;
+ break;
+ }
yield();
+ }
}
void SSD16XX::reset()
@@ -50,8 +65,9 @@ void SSD16XX::reset()
if (pin_rst != 0xFF) {
pinMode(pin_rst, OUTPUT);
digitalWrite(pin_rst, LOW);
- delay(50);
- pinMode(pin_rst, INPUT_PULLUP);
+ delay(10);
+ digitalWrite(pin_rst, HIGH);
+ delay(10);
wait();
}
@@ -61,6 +77,11 @@ void SSD16XX::reset()
void SSD16XX::sendCommand(const uint8_t command)
{
+ // Abort if part of the update sequence failed
+ // This will unlock again once we have failed-through the entire process
+ if (failed)
+ return;
+
spi->beginTransaction(spiSettings);
digitalWrite(pin_dc, LOW); // DC pin low indicates command
digitalWrite(pin_cs, LOW);
@@ -77,6 +98,11 @@ void SSD16XX::sendData(uint8_t data)
void SSD16XX::sendData(const uint8_t *data, uint32_t size)
{
+ // Abort if part of the update sequence failed
+ // This will unlock again once we have failed-through the entire process
+ if (failed)
+ return;
+
spi->beginTransaction(spiSettings);
digitalWrite(pin_dc, HIGH); // DC pin HIGH indicates data, instead of command
digitalWrite(pin_cs, LOW);
@@ -216,5 +242,18 @@ void SSD16XX::finalizeUpdate()
sendCommand(0x7F); // Terminate image write without update
wait();
}
+
+ // Enter deep-sleep to save a few µA
+ // Waking from this requires that display's reset pin is broken out
+ if (pin_rst != 0xFF)
+ deepSleep();
+}
+
+// Enter a lower-power state
+// May only save a few µA..
+void SSD16XX::deepSleep()
+{
+ sendCommand(0x10); // Enter deep sleep
+ sendData(0x01); // Mode 1: preserve image RAM
}
#endif // MESHTASTIC_INCLUDE_NICHE_GRAPHICS
\ No newline at end of file
diff --git a/src/graphics/niche/Drivers/EInk/SSD16XX.h b/src/graphics/niche/Drivers/EInk/SSD16XX.h
index 88fe4dc25..3f92818ce 100644
--- a/src/graphics/niche/Drivers/EInk/SSD16XX.h
+++ b/src/graphics/niche/Drivers/EInk/SSD16XX.h
@@ -27,7 +27,7 @@ class SSD16XX : public EInk
virtual void update(uint8_t *imageData, UpdateTypes type) override;
protected:
- virtual void wait();
+ virtual void wait(uint32_t timeout = 1000);
virtual void reset();
virtual void sendCommand(const uint8_t command);
virtual void sendData(const uint8_t data);
@@ -44,6 +44,7 @@ class SSD16XX : public EInk
virtual void detachFromUpdate();
virtual bool isUpdateDone() override;
virtual void finalizeUpdate() override;
+ virtual void deepSleep();
protected:
uint8_t bufferOffsetX = 0; // In bytes. Panel x=0 does not always align with controller x=0. Quirky internal wiring?
diff --git a/src/graphics/niche/InkHUD/Applet.cpp b/src/graphics/niche/InkHUD/Applet.cpp
index 9fda9a87e..6c6245ec3 100644
--- a/src/graphics/niche/InkHUD/Applet.cpp
+++ b/src/graphics/niche/InkHUD/Applet.cpp
@@ -582,9 +582,12 @@ std::string InkHUD::Applet::getTimeString(uint32_t epochSeconds)
uint32_t hour = hms / SEC_PER_HOUR;
uint32_t min = (hms % SEC_PER_HOUR) / SEC_PER_MIN;
- // Format the clock string
+ // Format the clock string, either 12 hour or 24 hour
char clockStr[11];
- sprintf(clockStr, "%u:%02u %s", (hour % 12 == 0 ? 12 : hour % 12), min, hour > 11 ? "PM" : "AM");
+ if (config.display.use_12h_clock)
+ sprintf(clockStr, "%u:%02u %s", (hour % 12 == 0 ? 12 : hour % 12), min, hour > 11 ? "PM" : "AM");
+ else
+ sprintf(clockStr, "%02u:%02u", hour, min);
return clockStr;
}
@@ -799,7 +802,7 @@ uint16_t InkHUD::Applet::getLogoHeight(uint16_t limitWidth, uint16_t limitHeight
// // \\
*/
-void InkHUD::Applet::drawLogo(int16_t centerX, int16_t centerY, uint16_t width, uint16_t height)
+void InkHUD::Applet::drawLogo(int16_t centerX, int16_t centerY, uint16_t width, uint16_t height, Color color)
{
struct Point {
int x;
@@ -905,24 +908,24 @@ void InkHUD::Applet::drawLogo(int16_t centerX, int16_t centerY, uint16_t width,
Point aq2{a2.x - fromPath.x, a2.y - fromPath.y};
Point aq3{a2.x + fromPath.x, a2.y + fromPath.y};
Point aq4{a1.x + fromPath.x, a1.y + fromPath.y};
- fillTriangle(aq1.x, aq1.y, aq2.x, aq2.y, aq3.x, aq3.y, BLACK);
- fillTriangle(aq1.x, aq1.y, aq3.x, aq3.y, aq4.x, aq4.y, BLACK);
+ fillTriangle(aq1.x, aq1.y, aq2.x, aq2.y, aq3.x, aq3.y, color);
+ fillTriangle(aq1.x, aq1.y, aq3.x, aq3.y, aq4.x, aq4.y, color);
// Make the path thick: path b becomes quad b
Point bq1{b1.x - fromPath.x, b1.y - fromPath.y};
Point bq2{b2.x - fromPath.x, b2.y - fromPath.y};
Point bq3{b2.x + fromPath.x, b2.y + fromPath.y};
Point bq4{b1.x + fromPath.x, b1.y + fromPath.y};
- fillTriangle(bq1.x, bq1.y, bq2.x, bq2.y, bq3.x, bq3.y, BLACK);
- fillTriangle(bq1.x, bq1.y, bq3.x, bq3.y, bq4.x, bq4.y, BLACK);
+ fillTriangle(bq1.x, bq1.y, bq2.x, bq2.y, bq3.x, bq3.y, color);
+ fillTriangle(bq1.x, bq1.y, bq3.x, bq3.y, bq4.x, bq4.y, color);
// Make the path thick: path c becomes quad c
Point cq1{c1.x - fromPath.x, c1.y + fromPath.y};
Point cq2{c2.x - fromPath.x, c2.y + fromPath.y};
Point cq3{c2.x + fromPath.x, c2.y - fromPath.y};
Point cq4{c1.x + fromPath.x, c1.y - fromPath.y};
- fillTriangle(cq1.x, cq1.y, cq2.x, cq2.y, cq3.x, cq3.y, BLACK);
- fillTriangle(cq1.x, cq1.y, cq3.x, cq3.y, cq4.x, cq4.y, BLACK);
+ fillTriangle(cq1.x, cq1.y, cq2.x, cq2.y, cq3.x, cq3.y, color);
+ fillTriangle(cq1.x, cq1.y, cq3.x, cq3.y, cq4.x, cq4.y, color);
// Radius the intersection of quad b and quad c
/*
@@ -941,7 +944,7 @@ void InkHUD::Applet::drawLogo(int16_t centerX, int16_t centerY, uint16_t width,
// The radius for the cap *should* be the same as logoTh, but it's not, due to accumulated rounding
// We get better results just re-deriving it
int16_t capRad = sqrt(pow(fromPath.x, 2) + pow(fromPath.y, 2));
- fillCircle(b2.x, b2.y, capRad, BLACK);
+ fillCircle(b2.x, b2.y, capRad, color);
}
}
diff --git a/src/graphics/niche/InkHUD/Applet.h b/src/graphics/niche/InkHUD/Applet.h
index 028b24f9c..8f4466647 100644
--- a/src/graphics/niche/InkHUD/Applet.h
+++ b/src/graphics/niche/InkHUD/Applet.h
@@ -130,7 +130,8 @@ class Applet : public GFX
static constexpr float LOGO_ASPECT_RATIO = 1.9; // Width:Height for drawing the Meshtastic logo
uint16_t getLogoWidth(uint16_t limitWidth, uint16_t limitHeight); // Size Meshtastic logo to fit within region
uint16_t getLogoHeight(uint16_t limitWidth, uint16_t limitHeight); // Size Meshtastic logo to fit within region
- void drawLogo(int16_t centerX, int16_t centerY, uint16_t width, uint16_t height); // Draw the meshtastic logo
+ void drawLogo(int16_t centerX, int16_t centerY, uint16_t width, uint16_t height,
+ Color color = BLACK); // Draw the Meshtastic logo
std::string hexifyNodeNum(NodeNum num); // Style as !0123abdc
SignalStrength getSignalStrength(float snr, float rssi); // Interpret SNR and RSSI, as an easy to understand value
diff --git a/src/graphics/niche/InkHUD/Applets/Examples/BasicExample/BasicExampleApplet.cpp b/src/graphics/niche/InkHUD/Applets/Examples/BasicExample/BasicExampleApplet.cpp
index 17458ab96..b12ea4809 100644
--- a/src/graphics/niche/InkHUD/Applets/Examples/BasicExample/BasicExampleApplet.cpp
+++ b/src/graphics/niche/InkHUD/Applets/Examples/BasicExample/BasicExampleApplet.cpp
@@ -8,7 +8,7 @@ using namespace NicheGraphics;
// Our basic example doesn't do anything useful. It just passively prints some text.
void InkHUD::BasicExampleApplet::onRender()
{
- print("Hello, World!");
+ printAt(0, 0, "Hello, World!");
}
#endif
\ No newline at end of file
diff --git a/src/graphics/niche/InkHUD/Applets/Examples/NewMsgExample/NewMsgExampleApplet.cpp b/src/graphics/niche/InkHUD/Applets/Examples/NewMsgExample/NewMsgExampleApplet.cpp
index e31f534ac..6b02f4c92 100644
--- a/src/graphics/niche/InkHUD/Applets/Examples/NewMsgExample/NewMsgExampleApplet.cpp
+++ b/src/graphics/niche/InkHUD/Applets/Examples/NewMsgExample/NewMsgExampleApplet.cpp
@@ -4,11 +4,12 @@
using namespace NicheGraphics;
-// We configured MeshModule API to call this method when we receive a new text message
+// We configured the Module API to call this method when we receive a new text message
ProcessMessage InkHUD::NewMsgExampleApplet::handleReceived(const meshtastic_MeshPacket &mp)
{
// Abort if applet fully deactivated
+ // Don't waste time: we wouldn't be rendered anyway
if (!isActive())
return ProcessMessage::CONTINUE;
@@ -25,7 +26,7 @@ ProcessMessage InkHUD::NewMsgExampleApplet::handleReceived(const meshtastic_Mesh
requestUpdate();
}
- // Tell MeshModule API to continue informing other firmware components about this message
+ // Tell Module API to continue informing other firmware components about this message
// We're not the only component which is interested in new text messages
return ProcessMessage::CONTINUE;
}
diff --git a/src/graphics/niche/InkHUD/Applets/System/Logo/LogoApplet.cpp b/src/graphics/niche/InkHUD/Applets/System/Logo/LogoApplet.cpp
index 24c2d88a4..520b3ef65 100644
--- a/src/graphics/niche/InkHUD/Applets/System/Logo/LogoApplet.cpp
+++ b/src/graphics/niche/InkHUD/Applets/System/Logo/LogoApplet.cpp
@@ -34,7 +34,15 @@ void InkHUD::LogoApplet::onRender()
int16_t logoCX = X(0.5);
int16_t logoCY = Y(0.5 - 0.05);
- drawLogo(logoCX, logoCY, logoW, logoH);
+ // Invert colors if black-on-white
+ // Used during shutdown, to resport display health
+ // Todo: handle this in InkHUD::Renderer instead
+ if (inverted) {
+ fillScreen(BLACK);
+ setTextColor(WHITE);
+ }
+
+ drawLogo(logoCX, logoCY, logoW, logoH, inverted ? WHITE : BLACK);
if (!textLeft.empty()) {
setFont(fontSmall);
@@ -74,13 +82,45 @@ void InkHUD::LogoApplet::onBackground()
// Begin displaying the screen which is shown at shutdown
void InkHUD::LogoApplet::onShutdown()
{
+ bringToForeground();
+
+ textLeft = "";
+ textRight = "";
+ textTitle = "Shutting Down...";
+ fontTitle = fontSmall;
+
+ // Draw a shutting down screen, twice.
+ // Once white on black, once black on white.
+ // Intention is to restore display health.
+
+ inverted = true;
+ inkhud->forceUpdate(Drivers::EInk::FULL, false);
+ delay(1000); // Cooldown. Back to back updates aren't great for health.
+ inverted = false;
+ inkhud->forceUpdate(Drivers::EInk::FULL, false);
+ delay(1000); // Cooldown
+
+ // Prepare for the powered-off screen now
+ // We can change these values because the initial "shutting down" screen has already rendered at this point
textLeft = "";
textRight = "";
textTitle = owner.short_name;
fontTitle = fontLarge;
+ // This is then drawn by InkHUD::Events::onShutdown, with a blocking FULL update, after InkHUD's flash write is complete
+}
+
+void InkHUD::LogoApplet::onReboot()
+{
bringToForeground();
- // This is then drawn by InkHUD::Events::onShutdown, with a blocking FULL update
+
+ textLeft = "";
+ textRight = "";
+ textTitle = "Rebooting...";
+ fontTitle = fontSmall;
+
+ inkhud->forceUpdate(Drivers::EInk::FULL, false);
+ // Perform the update right now, waiting here until complete
}
int32_t InkHUD::LogoApplet::runOnce()
diff --git a/src/graphics/niche/InkHUD/Applets/System/Logo/LogoApplet.h b/src/graphics/niche/InkHUD/Applets/System/Logo/LogoApplet.h
index b55d4a2d9..3f604baed 100644
--- a/src/graphics/niche/InkHUD/Applets/System/Logo/LogoApplet.h
+++ b/src/graphics/niche/InkHUD/Applets/System/Logo/LogoApplet.h
@@ -25,6 +25,7 @@ class LogoApplet : public SystemApplet, public concurrency::OSThread
void onForeground() override;
void onBackground() override;
void onShutdown() override;
+ void onReboot() override;
protected:
int32_t runOnce() override;
@@ -33,6 +34,7 @@ class LogoApplet : public SystemApplet, public concurrency::OSThread
std::string textRight;
std::string textTitle;
AppletFont fontTitle;
+ bool inverted = false; // Invert colors. Used during shutdown, to restore display health.
};
} // namespace NicheGraphics::InkHUD
diff --git a/src/graphics/niche/InkHUD/Applets/System/Menu/MenuAction.h b/src/graphics/niche/InkHUD/Applets/System/Menu/MenuAction.h
index 6950bb110..f162aa385 100644
--- a/src/graphics/niche/InkHUD/Applets/System/Menu/MenuAction.h
+++ b/src/graphics/niche/InkHUD/Applets/System/Menu/MenuAction.h
@@ -18,19 +18,20 @@ namespace NicheGraphics::InkHUD
enum MenuAction {
NO_ACTION,
- SEND_NODEINFO,
- SEND_POSITION,
+ SEND_PING,
SHUTDOWN,
NEXT_TILE,
+ TOGGLE_BACKLIGHT,
+ TOGGLE_GPS,
+ ENABLE_BLUETOOTH,
TOGGLE_APPLET,
- ACTIVATE_APPLETS, // Todo: remove? Possible redundant, handled by TOGGLE_APPLET?
TOGGLE_AUTOSHOW_APPLET,
SET_RECENTS,
ROTATE,
LAYOUT,
TOGGLE_BATTERY_ICON,
TOGGLE_NOTIFICATIONS,
- TOGGLE_BACKLIGHT,
+ TOGGLE_12H_CLOCK,
};
} // namespace NicheGraphics::InkHUD
diff --git a/src/graphics/niche/InkHUD/Applets/System/Menu/MenuApplet.cpp b/src/graphics/niche/InkHUD/Applets/System/Menu/MenuApplet.cpp
index 7397f7e9f..5ca9692c8 100644
--- a/src/graphics/niche/InkHUD/Applets/System/Menu/MenuApplet.cpp
+++ b/src/graphics/niche/InkHUD/Applets/System/Menu/MenuApplet.cpp
@@ -4,9 +4,15 @@
#include "RTC.h"
+#include "MeshService.h"
#include "airtime.h"
+#include "main.h"
#include "power.h"
+#if !MESHTASTIC_EXCLUDE_GPS
+#include "GPS.h"
+#endif
+
using namespace NicheGraphics;
static constexpr uint8_t MENU_TIMEOUT_SEC = 60; // How many seconds before menu auto-closes
@@ -27,8 +33,6 @@ InkHUD::MenuApplet::MenuApplet() : concurrency::OSThread("MenuApplet")
}
}
-void InkHUD::MenuApplet::onActivate() {}
-
void InkHUD::MenuApplet::onForeground()
{
// We do need this before we render, but we can optimize by just calculating it once now
@@ -141,6 +145,14 @@ void InkHUD::MenuApplet::execute(MenuItem item)
inkhud->nextTile();
break;
+ case SEND_PING:
+ service->refreshLocalMeshNode();
+ service->trySendPosition(NODENUM_BROADCAST, true);
+
+ // Force the next refresh to use FULL, to protect the display, as some users will probably spam this button
+ inkhud->forceUpdate(Drivers::EInk::UpdateTypes::FULL);
+ break;
+
case ROTATE:
inkhud->rotate();
break;
@@ -161,12 +173,6 @@ void InkHUD::MenuApplet::execute(MenuItem item)
case TOGGLE_APPLET:
settings->userApplets.active[cursor] = !settings->userApplets.active[cursor];
inkhud->updateAppletSelection();
- // requestUpdate(Drivers::EInk::UpdateTypes::FULL); // Select FULL, seeing how this action doesn't auto exit
- break;
-
- case ACTIVATE_APPLETS:
- // Todo: remove this action? Already handled by TOGGLE_APPLET?
- inkhud->updateAppletSelection();
break;
case TOGGLE_AUTOSHOW_APPLET:
@@ -205,6 +211,25 @@ void InkHUD::MenuApplet::execute(MenuItem item)
backlight->latch();
break;
+ case TOGGLE_12H_CLOCK:
+ config.display.use_12h_clock = !config.display.use_12h_clock;
+ nodeDB->saveToDisk(SEGMENT_CONFIG);
+ break;
+
+ case TOGGLE_GPS:
+ gps->toggleGpsMode();
+ nodeDB->saveToDisk(SEGMENT_CONFIG);
+ break;
+
+ case ENABLE_BLUETOOTH:
+ // This helps users recover from a bad wifi config
+ LOG_INFO("Enabling Bluetooth");
+ config.network.wifi_enabled = false;
+ config.bluetooth.enabled = true;
+ nodeDB->saveToDisk();
+ rebootAtMsec = millis() + 2000;
+ break;
+
default:
LOG_WARN("Action not implemented");
}
@@ -226,7 +251,7 @@ void InkHUD::MenuApplet::showPage(MenuPage page)
if (settings->optionalMenuItems.nextTile && settings->userTiles.count > 1)
items.push_back(MenuItem("Next Tile", MenuAction::NEXT_TILE, MenuPage::ROOT)); // Only if multiple applets shown
- // items.push_back(MenuItem("Send", MenuPage::SEND)); // TODO
+ items.push_back(MenuItem("Send", MenuPage::SEND));
items.push_back(MenuItem("Options", MenuPage::OPTIONS));
// items.push_back(MenuItem("Display Off", MenuPage::EXIT)); // TODO
items.push_back(MenuItem("Save & Shut Down", MenuAction::SHUTDOWN));
@@ -234,21 +259,28 @@ void InkHUD::MenuApplet::showPage(MenuPage page)
break;
case SEND:
- items.push_back(MenuItem("Send Message", MenuPage::EXIT));
- items.push_back(MenuItem("Send NodeInfo", MenuAction::SEND_NODEINFO));
- items.push_back(MenuItem("Send Position", MenuAction::SEND_POSITION));
+ items.push_back(MenuItem("Ping", MenuAction::SEND_PING, MenuPage::EXIT));
+ // Todo: canned messages
items.push_back(MenuItem("Exit", MenuPage::EXIT));
break;
case OPTIONS:
// Optional: backlight
- if (settings->optionalMenuItems.backlight) {
- assert(backlight);
+ if (settings->optionalMenuItems.backlight)
items.push_back(MenuItem(backlight->isLatched() ? "Backlight Off" : "Keep Backlight On", // Label
MenuAction::TOGGLE_BACKLIGHT, // Action
MenuPage::EXIT // Exit once complete
));
- }
+
+ // Optional: GPS
+ if (config.position.gps_mode == meshtastic_Config_PositionConfig_GpsMode_DISABLED)
+ items.push_back(MenuItem("Enable GPS", MenuAction::TOGGLE_GPS, MenuPage::EXIT));
+ if (config.position.gps_mode == meshtastic_Config_PositionConfig_GpsMode_ENABLED)
+ items.push_back(MenuItem("Disable GPS", MenuAction::TOGGLE_GPS, MenuPage::EXIT));
+
+ // Optional: Enable Bluetooth, in case of lost wifi connection
+ if (!config.bluetooth.enabled || config.network.wifi_enabled)
+ items.push_back(MenuItem("Enable Bluetooth", MenuAction::ENABLE_BLUETOOTH, MenuPage::EXIT));
items.push_back(MenuItem("Applets", MenuPage::APPLETS));
items.push_back(MenuItem("Auto-show", MenuPage::AUTOSHOW));
@@ -260,26 +292,14 @@ void InkHUD::MenuApplet::showPage(MenuPage page)
&settings->optionalFeatures.notifications));
items.push_back(MenuItem("Battery Icon", MenuAction::TOGGLE_BATTERY_ICON, MenuPage::OPTIONS,
&settings->optionalFeatures.batteryIcon));
-
- // TODO - GPS and Wifi switches
- /*
- // Optional: has GPS
- if (config.position.gps_mode == meshtastic_Config_PositionConfig_GpsMode_DISABLED)
- items.push_back(MenuItem("Enable GPS", MenuPage::EXIT)); // TODO
- if (config.position.gps_mode == meshtastic_Config_PositionConfig_GpsMode_ENABLED)
- items.push_back(MenuItem("Disable GPS", MenuPage::EXIT)); // TODO
-
- // Optional: using wifi
- if (!config.bluetooth.enabled)
- items.push_back(MenuItem("Enable Bluetooth", MenuPage::EXIT)); // TODO: escape hatch if wifi configured wrong
- */
-
+ items.push_back(
+ MenuItem("12-Hour Clock", MenuAction::TOGGLE_12H_CLOCK, MenuPage::OPTIONS, &config.display.use_12h_clock));
items.push_back(MenuItem("Exit", MenuPage::EXIT));
break;
case APPLETS:
populateAppletPage();
- items.push_back(MenuItem("Exit", MenuAction::ACTIVATE_APPLETS));
+ items.push_back(MenuItem("Exit", MenuPage::EXIT));
break;
case AUTOSHOW:
@@ -293,7 +313,6 @@ void InkHUD::MenuApplet::showPage(MenuPage page)
case EXIT:
sendToBackground(); // Menu applet dismissed, allow normal behavior to resume
- // requestUpdate(Drivers::EInk::UpdateTypes::FULL);
break;
default:
@@ -378,11 +397,14 @@ void InkHUD::MenuApplet::onRender()
// Center-line for the text
int16_t center = itemT + (itemH / 2);
+ // Box, if currently selected
if (cursorShown && i == cursor)
drawRect(itemL, itemT, itemW, itemH, BLACK);
+
+ // Item's text
printAt(itemL + X(padding), center, item.label, LEFT, MIDDLE);
- // Testing only: circle instead of check box
+ // Checkbox, if relevant
if (item.checkState) {
const uint16_t cbWH = fontSmall.lineHeight(); // Checkbox: width / height
const int16_t cbL = itemR - X(padding) - cbWH; // Checkbox: left
diff --git a/src/graphics/niche/InkHUD/Applets/System/Menu/MenuApplet.h b/src/graphics/niche/InkHUD/Applets/System/Menu/MenuApplet.h
index fe72d826b..d9297c8ed 100644
--- a/src/graphics/niche/InkHUD/Applets/System/Menu/MenuApplet.h
+++ b/src/graphics/niche/InkHUD/Applets/System/Menu/MenuApplet.h
@@ -21,7 +21,6 @@ class MenuApplet : public SystemApplet, public concurrency::OSThread
{
public:
MenuApplet();
- void onActivate() override;
void onForeground() override;
void onBackground() override;
void onButtonShortPress() override;
diff --git a/src/graphics/niche/InkHUD/Applets/System/Tips/TipsApplet.cpp b/src/graphics/niche/InkHUD/Applets/System/Tips/TipsApplet.cpp
index 1abf3ccfa..82a196cb1 100644
--- a/src/graphics/niche/InkHUD/Applets/System/Tips/TipsApplet.cpp
+++ b/src/graphics/niche/InkHUD/Applets/System/Tips/TipsApplet.cpp
@@ -207,8 +207,6 @@ void InkHUD::TipsApplet::onBackground()
inkhud->forceUpdate(EInk::UpdateTypes::FULL);
}
-void InkHUD::TipsApplet::onActivate() {}
-
// While our SystemApplet::handleInput flag is true
void InkHUD::TipsApplet::onButtonShortPress()
{
diff --git a/src/graphics/niche/InkHUD/Applets/System/Tips/TipsApplet.h b/src/graphics/niche/InkHUD/Applets/System/Tips/TipsApplet.h
index e7bb7bedc..db88585e9 100644
--- a/src/graphics/niche/InkHUD/Applets/System/Tips/TipsApplet.h
+++ b/src/graphics/niche/InkHUD/Applets/System/Tips/TipsApplet.h
@@ -33,7 +33,6 @@ class TipsApplet : public SystemApplet
TipsApplet();
void onRender() override;
- void onActivate() override;
void onForeground() override;
void onBackground() override;
void onButtonShortPress() override;
diff --git a/src/graphics/niche/InkHUD/Events.cpp b/src/graphics/niche/InkHUD/Events.cpp
index 10072b302..ddd01b7e1 100644
--- a/src/graphics/niche/InkHUD/Events.cpp
+++ b/src/graphics/niche/InkHUD/Events.cpp
@@ -70,6 +70,9 @@ void InkHUD::Events::onButtonLong()
// Returns 0 to signal that we agree to sleep now
int InkHUD::Events::beforeDeepSleep(void *unused)
{
+ // If a previous display update is in progress, wait for it to complete.
+ inkhud->awaitUpdate();
+
// Notify all applets that we're shutting down
for (Applet *ua : inkhud->userApplets) {
ua->onDeactivate();
@@ -87,9 +90,12 @@ int InkHUD::Events::beforeDeepSleep(void *unused)
inkhud->persistence->saveSettings();
inkhud->persistence->saveLatestMessage();
- // LogoApplet::onShutdown will have requested an update, to draw the shutdown screen
- // Draw that now, and wait here until the update is complete
+ // LogoApplet::onShutdown attempted to heal the display by drawing a "shutting down" screen twice,
+ // then prepared a final powered-off screen for us, which shows device shortname.
+ // We're updating to show that one now.
+
inkhud->forceUpdate(Drivers::EInk::UpdateTypes::FULL, false);
+ delay(1000); // Cooldown, before potentially yanking display power
return 0; // We agree: deep sleep now
}
@@ -106,16 +112,16 @@ int InkHUD::Events::beforeReboot(void *unused)
a->onDeactivate();
a->onShutdown();
}
- for (Applet *sa : inkhud->systemApplets) {
+ for (SystemApplet *sa : inkhud->systemApplets) {
// Note: no onDeactivate. System applets are always active.
- sa->onShutdown();
+ sa->onReboot();
}
inkhud->persistence->saveSettings();
inkhud->persistence->saveLatestMessage();
// Note: no forceUpdate call here
- // Because OSThread will not be given another chance to run before reboot, this means that no display update will occur
+ // We don't have any final screen to draw, although LogoApplet::onReboot did already display a "rebooting" screen
return 0; // No special status to report. Ignored anyway by this Observable
}
diff --git a/src/graphics/niche/InkHUD/Persistence.h b/src/graphics/niche/InkHUD/Persistence.h
index 28841d4d9..40f1dd521 100644
--- a/src/graphics/niche/InkHUD/Persistence.h
+++ b/src/graphics/niche/InkHUD/Persistence.h
@@ -99,7 +99,7 @@ class Persistence
// Rotation of the display
// Multiples of 90 degrees clockwise
// Most commonly: rotation is 0 when flex connector is oriented below display
- uint8_t rotation = 1;
+ uint8_t rotation = 0;
// How long do we consider another node to be "active"?
// Used when applets want to filter for "active nodes" only
diff --git a/src/graphics/niche/InkHUD/README.md b/src/graphics/niche/InkHUD/README.md
deleted file mode 100644
index 8d788ffa8..000000000
--- a/src/graphics/niche/InkHUD/README.md
+++ /dev/null
@@ -1,12 +0,0 @@
-# InkHUD
-
-A heads-up-display for E-Ink devices, intended to supplement a connected phone / client. Implemented as a "NicheGraphics" UI.
-
-Supported devices (as of 1st Feb. 2025):
-
-- Heltec Vision Master E213
-- Heltec Vision Master E290
-- Heltec Wireless Paper V1.1
-- LILYGO T-Echo
-
-More to follow
diff --git a/src/graphics/niche/InkHUD/SystemApplet.h b/src/graphics/niche/InkHUD/SystemApplet.h
index 0f8ceedc7..7ee47eeb9 100644
--- a/src/graphics/niche/InkHUD/SystemApplet.h
+++ b/src/graphics/niche/InkHUD/SystemApplet.h
@@ -26,6 +26,8 @@ class SystemApplet : public Applet
bool lockRendering = false; // - prevent other applets from being rendered during an update
bool lockRequests = false; // - prevent other applets from triggering display updates
+ virtual void onReboot() { onShutdown(); } // - handle reboot specially
+
// Other system applets may take precedence over our own system applet though
// The order an applet is passed to WindowManager::addSystemApplet determines this hierarchy (added earlier = higher rank)
diff --git a/src/graphics/niche/InkHUD/docs/README.md b/src/graphics/niche/InkHUD/docs/README.md
new file mode 100644
index 000000000..07fe6c942
--- /dev/null
+++ b/src/graphics/niche/InkHUD/docs/README.md
@@ -0,0 +1,640 @@
+# InkHUD
+
+This document is intended as a reference for maintainers. A haphazard collection of notes which _might_ be helpful.
+
+
+
+---
+
+- [Purpose](#purpose)
+- [Design Principles](#design-principles)
+ - [Self-Contained](#self-contained)
+ - [Static](#static)
+ - [Non-interactive](#non-interactive)
+ - [Customizable](#customizable)
+ - [Event-Driven Rendering](#event-driven-rendering)
+ - [No `#ifdef` spaghetti](#no-ifdef-spaghetti)
+- [The Implementation](#the-implementation)
+- [The Rendering Process](#the-rendering-process)
+- [Concepts](#concepts)
+ - [NicheGraphics Framework](#nichegraphics-framework)
+ - [NicheGraphics E-Ink Drivers](#nichegraphics-e-ink-drivers)
+ - [InkHUD Applets](#inkhud-applets)
+- [Adding a Variant](#adding-a-variant)
+ - [platformio.ini](#platformioini)
+ - [nicheGraphics.h](#nichegraphicsh)
+- [Class Notes](#class-notes)
+ - [`InkHUD::InkHUD`](#inkhudinkhud)
+ - [`InkHUD::Persistence`](#inkhudpersistence)
+ - [`InkHUD::Persistence::Settings`](#inkhudpersistencesettings)
+ - [`InkHUD::Persistence::LatestMessage`](#inkhudpersistencelatestmessage)
+ - [`InkHUD::WindowManager`](#inkhudwindowmanager)
+ - [`InkHUD::Renderer`](#inkhudrenderer)
+ - [`InkHUD::Renderer::DisplayHealth`](#inkhudrendererdisplayhealth)
+ - [`InkHUD::Events`](#inkhudevents)
+ - [`InkHUD::Applet`](#inkhudapplet)
+ - [`InkHUD::SystemApplet`](#inkhudsystemapplet)
+ - [`InkHUD::Tile`](#inkhudtile)
+ - [`InkHUD::AppletFont`](#inkhudappletfont)
+
+## Purpose
+
+InkHUD is a minimal UI for E-Ink devices. It displays the user's choice of info, as statically as possible, to minimize the amount of display refreshing.
+
+It is intended to supplement a connected client app.
+
+## Design Principles
+
+### Self-Contained
+
+- Keep InkHUD code within `/src/graphics/niche/InkHUD`.
+- Place reusable components within `/src/graphics/niche`, for other UIs to take advantage of.
+- Interact with the firmware code using the **Module API**, **Observables**, and other similarly non-intrusive hooks.
+
+### Static
+
+Information should be displayed as statically as possible. Unnecessary updates should be avoided.
+
+As as example, fixed timestamps are used instead of `X seconds ago` labels, as these need to be constantly updated to remain current.
+
+### Non-interactive
+
+InkHUD aims to be a "heads up display". The intention is for the user to glance at the display. The intention is _not_ for the user to frequently interact with the display.
+
+Some interactivity is tolerated as a means to an end: the display _should_ be customizable, but this should be minimized as much as possible.
+
+_Edit: there's significant demand for keyboard support, so some sort of free-text feature will need to be added eventually, although it does go against the original design principles._
+
+### Customizable
+
+The user should be given the choice to decide which information they would like to receive, and how they would like to receive it.
+
+### Event-Driven Rendering
+
+The display image does not update "automatically". Individual applets are responsible for deciding when they have new information to show, and then requesting a display update.
+
+### No `#ifdef` spaghetti
+
+**Don't** use preprocessor macros for device-specific configuration. This should be achieved with config methods, in [`nicheGraphics.h`](#nichegraphicsh).
+
+**Do** use preprocessor macros to guard all files
+
+- `#ifdef MESHTASTIC_INCLUDE_INKHUD` for InkHUD files
+- `#ifdef MESHTASTIC_INCLUDE_NICHE_GRAPHICS` for reusable components (drivers, etc)
+
+## The Implementation
+
+- Variant's platformio.ini file extends `inkhud` (defined in InkHUD/PlatformioConfig.ini)
+ - original screen class suppressed: `MESHTASTIC_EXCLUDE_SCREEN`
+ - ButtonThread suppressed: `HAS_BUTTON=0`
+ - NicheGraphics components included: `MESHTASTIC_INCLUDE_NICHE_GRAPHICS`
+ - InkHUD components included: `MESHTASTIC_INCLUDE_INKHUD`
+- `main.cpp`
+ - includes `nicheGraphics.h` (from variant folder)
+ - calls `setupNicheGraphics`, (from nicheGraphics.h)
+- `nicheGraphics.h`
+ - includes InkHUD components
+ - includes shared NicheGraphics components
+ - `setupNicheGraphics`
+ - configures and connects components
+ - `inkhud->begin`
+
+## The Rendering Process
+
+(animated diagram)
+
+
+
+An overview:
+
+- A component calls `requestUpdate` (applets only) or `InkHUD::forceUpdate`
+- `Renderer` schedules a render cycle for the next loop(), using `Renderer::runOnce`
+- `Renderer` determines whether the update request is valid
+- `Renderer` asks relevant applets to render
+- Applet dimensions are updated (by Applet's `Tile`)
+- Applets generate pixel output, and pass this to their `Tile`
+- Tiles shift these "relative" pixels to their true region, for multiplexing
+- Tiles pass the pixels to `Renderer`
+- `Renderer` applies any global display rotation to the pixels
+- `Renderer` combines the pixels into the finished image
+- The finished image is passed to the display driver, starting the physical update process
+
+## Concepts
+
+### NicheGraphics Framework
+
+InkHUD is implemented as a _NicheGraphics_ UI.
+
+Intended as a pattern / philosophy for implementing self-contained UIs, to suit various niche devices, which are best served by their own custom user interface.
+
+Hypothetical examples: E-Ink, 1602 LCDs, tiny OLEDs, smart watches, etc
+
+A NicheGraphics UI:
+
+- Is self-contained
+- Makes use of the loose collection of resources (drivers, input methods, etc) gathered in the `/src/graphics/niche` folder.
+- Implements a `setupNicheGraphics()` method.
+
+### NicheGraphics E-Ink Drivers
+
+InkHUD uses a set of custom E-Ink drivers. These are not based on GxEPD2, or any other code base. They are written directly on-top of the Meshtastic firmware, to make use of the OSThread class for asynchronous display updates.
+
+Interacting with the drivers is straightforward. InkHUD generates a frame of 1-bit image data. This image data is passed to the driver, along with the type of refresh to use (FULL or FAST).
+
+`driver->update(uint8_t* buffer, EInk::UpdateTypes::FULL)`
+
+For more information, see the documentation in `src/graphics/niche/Drivers/EInk`
+
+### InkHUD Applets
+
+An InkHUD applet is a class which generates a screen of info for the display.
+
+Consider: `DMApplet.h` (displays most recent direct message) and `RecentsList.h` (displays a list of recently heard nodes)
+
+- Applets are modular: they are easy to write, and easy to implement. Users select which applets they want, using the menu.
+- Applets use responsive design. They should scale for different screens / layouts / fonts.
+- Applets decide when to update. They use the Module API, Observers, etc, to retrieve information, and request a display update when they have something interesting to show.
+
+See `src/graphics/niche/InkHUD/Applets/Examples` for example code.
+
+#### Writing an Applet
+
+Your new applet class will inherit `InkHUD::Applet`.
+
+```cpp
+class BasicExampleApplet : public Applet
+{
+ public:
+ // You must have an onRender() method
+ // All drawing happens here
+
+ void onRender() override;
+};
+```
+
+The `onRender` method is called when the display image is redrawn. This can happen at any time, so be ready!
+
+```cpp
+// All drawing happens here
+// Our basic example doesn't do anything useful. It just passively prints some text.
+void InkHUD::BasicExampleApplet::onRender()
+{
+ printAt(0, 0, "Hello, world!");
+}
+```
+
+Your applet will need to scale automatically, to suit a variety of screens / layouts / fonts. Make sure you draw relative to applet's size.
+
+| edge | coordinate | shorthand |
+| ------ | ---------- | --------- |
+| left | 0 | `X(0.0)` |
+| top | 0 | `Y(0.0)` |
+| right | `width()` | `X(1.0)` |
+| bottom | `height()` | `Y(1.0)` |
+
+The same principles apply for drawing text. Methods like `AppletFont::lineHeight` and `getTextWidth` are useful here.
+
+```cpp
+std::string line1 = "Line 1";
+printAt(0, Y(0.5), line1);
+drawRect(0, Y(0.5), getTextWidth(line1), fontSmall.lineHeight(), BLACK);
+```
+
+Your applet will only be redrawn when _something_ requests a display update. Your applet is welcome to request a display update, when it determines that it has new info to display, by calling `requestUpdate`.
+
+Exactly how you determine this, depends on what your applet actually does. Here's a code snippet from one of the example applets. The applet is requesting an update when a new message is received.
+
+```cpp
+// We configured the Module API to call this method when we receive a new text message
+ProcessMessage InkHUD::NewMsgExampleApplet::handleReceived(const meshtastic_MeshPacket &mp)
+{
+
+ // Abort if applet fully deactivated
+ // Don't waste time: we wouldn't be rendered anyway
+ if (!isActive())
+ return ProcessMessage::CONTINUE;
+
+ // Check that this is an incoming message
+ // Outgoing messages (sent by us) will also call handleReceived
+
+ if (!isFromUs(&mp)) {
+ // Store the sender's nodenum
+ // We need to keep this information, so we can re-use it anytime render() is called
+ haveMessage = true;
+ fromWho = mp.from;
+
+ // Tell InkHUD that we have something new to show on the screen
+ requestUpdate();
+ }
+
+ // Tell Module API to continue informing other firmware components about this message
+ // We're not the only component which is interested in new text messages
+ return ProcessMessage::CONTINUE;
+}
+```
+
+#### Implementing an Applet
+
+Incorporating your new applet into InkHUD is easy.
+
+In a variant's `nicheGraphics.h`:
+
+- `#include` your applet
+- `inkhud->addApplet("My Applet", new InkHUD::MyApplet);`
+
+You will need to add these lines to any variants which will use your applet.
+
+#### Applet Bases
+
+If you need to create several similar applets, it might make sense to create a reusable base class. Several of these already exist in `src/graphics/niche/InkHUD/Applets/Bases`, but use these with caution, as they may be modified in future.
+
+#### System Applets
+
+So far, we have been talking about "user applets". We also recognize a separate category of "system applets". These handle things like the menu, and the boot screen. These often need special handling, and need to be implemented manually.
+
+## Adding a Variant
+
+In `/variants//`:
+
+### platformio.ini
+
+Extend `inkhud`, then combine with any other platformio config your hardware variant requires.
+
+_(Example shows only config required by InkHUD. This is not a complete `env` definition.)_
+
+```ini
+[env:YOUR_VARIANT-inkhud]
+extends = esp32s3_base, inkhud ; or nrf52840_base, etc
+
+build_src_filter =
+${esp32_base.build_src_filter}
+${inkhud.build_src_filter}
+
+build_flags =
+${esp32s3_base.build_flags}
+${inkhud.build_flags}
+
+lib_deps =
+${inkhud.lib_deps} ; InkHUD libs first, so we get GFXRoot instead of AdafruitGFX
+${esp32s3_base.lib_deps}
+```
+
+### nicheGraphics.h
+
+⚠ Wrap this file in `#ifdef MESHTASTIC_INCLUDE_NICHE_GRAPHICS`
+
+`nicheGraphics.h` should be placed in the same folder as your variant's `platformio.ini`. If this is not possible, modify `build_src_filter`.
+
+`nicheGraphics.h` should contain a `setupNicheGraphics` method, which creates and configures the various components for InkHUD.
+
+- Display
+ - Start SPI
+ - Create display driver
+- InkHUD
+ - Create InkHUD instance
+ - Set E-Ink fast refresh limit (`setDisplayResilience`)
+ - Set fonts
+ - Set default user-settings
+ - Select applets to build (`addApplet`)
+ - Start InkHUD
+- Buttons
+ - Setup `TwoButton` driver (user button, optional "auxiliary" button)
+ - Connect to InkHUD handlers (use lambdas)
+
+For well commented examples, see:
+
+- `variants/heltec_vision_master_e290/nicheGraphics.h` (ESP32)
+- `variants/t-echo/nicheGraphics.h` (NRF52)
+
+## Class Notes
+
+### `InkHUD::InkHUD`
+
+_`src/graphics/niche/InkHUD/InkHUD.h`_
+
+- singleton
+- mediator between other InkHUD components
+
+#### `getInstance()`
+
+Gets access to the class.
+First `getInstance` call instantiates the class, and the subclasses:
+
+- `InkHUD::Persistence`
+- `InkHUD::WindowManager`
+- `InkHUD::Renderer`
+- `InkHUD::Events`
+
+For convenience, many InkHUD components call this on `begin`, and store it as `InkHUD* inkhud`.
+
+---
+
+### `InkHUD::Persistence`
+
+_`src/graphics/niche/InkHUD/Persistence.h`_
+
+Stores InkHUD data in flash
+
+- settings
+- most recent text message received (both for broadcast and DM)
+
+In rare cases, applets may store their own specific data separately (e.g. `ThreadedMessageApplet`)
+
+Data saved only on shutdown / reboot. Not saved if power is removed unexpectedly.
+
+---
+
+### `InkHUD::Persistence::Settings`
+
+_`src/graphics/niche/InkHUD/Persistence.h`_
+
+Settings which relate to InkHUD. Mostly user's customization, but some values record the UI's state (e.g. `tips.safeShutdownSeen`)
+
+- stored using `FlashData.h` (a shared Niche Graphics tool)
+- not encoded as protobufs
+- serialized directly as bytes of struct
+
+#### Defaults
+
+Global default values are set when the struct is defined (Persistence.h).
+Per-variant defaults are set by modifying the values of the settings instance during `setupNicheGraphics()`, before `inkhud->begin` is called.
+
+```cpp
+inkhud->persistence->settings.userTiles.count = 2;
+inkhud->persistence->settings.userTiles.maxCount = 4;
+inkhud->persistence->settings.rotation = 3;
+```
+
+By modifying the values at this point, they will be used if we fail to load previous settings from flash (not yet saved, old version, etc)
+
+---
+
+### `InkHUD::Persistence::LatestMessage`
+
+_`src/graphics/niche/InkHUD/Persistence.h`_
+
+Most recently received text message
+
+- most recent DM
+- most recent broadcast
+
+Collected here, so various user applets don't all have to store their own copy of this info.
+
+We are unable to use `devicestate.rx_text_message` for this purpose, because:
+
+- it is cleared by an outgoing text message
+- we want to store both a recent broadcast and a recent DM
+
+#### Saving / Loading
+
+_A bit of a hack.._
+Stored to flash using `InkHUD::MessageStore`, which is really intended for storing a thread of messages (see `ThreadedMessageApplet`). Used because it stores strings more efficiently than `FlashData.h`.
+
+The hack is:
+
+- If most recent message was a DM, we only store the DM.
+- If most recent message was a broadcast, we store both a DM and a broadcast. The DM may be 0-length string.
+
+---
+
+### `InkHUD::WindowManager`
+
+_`src/graphics/niche/InkHUD/WindowManager.h`_
+
+Manages which applets are shown, and their size / position (by manipulating the "tiles")
+
+- owns the `Tile` instances
+- creates and destroys tiles; sets size and position:
+ - at startup
+ - at runtime, when config changes (layout, rotation, etc)
+- activates (or deactivates) applets
+- cycling through applets (e.g. on button press)
+
+The window manager doesn't process pixels; that is handled by the `InkHUD::Tile` objects.
+
+Note: Some of the methods (incl. `changeLayout`, `changeActivatedApplets`) don't trigger changes themselves. They should be called _after_ the relevant values in `inkhud->persistence->settings` have been modified.
+
+---
+
+### `InkHUD::Renderer`
+
+_`src/graphics/niche/InkHUD/Renderer.h`_
+
+Get pixel output from applets (via a tile), combine, and pass to the driver.
+
+- triggered by `requestUpdate` or `forceUpdate`
+- not run immediately: allows multiple applets to share one render cycle
+- calls `Applet::onRender` for relevant applets
+- applies global rotation
+- passes finalized image to driver
+
+`requestUpdate` is for applets (user or system). Renderer will honor the request if the applet is visible. `forceUpdate` can be used anywhere, but not from user applets, please.
+
+#### Asynchronous updates
+
+`requestUpdate` and `forceUpdate` do not block code execution. They schedule rendering for "ASAP", using `Renderer::runOnce`. Renderer then gets pixel output from relevant applets, and hands the assembled image to the driver. Driver's update process is also asynchronous. If the driver is busy when `requestUpdate` or `forceUpdate` is called, another rendering will run as soon as possible. This is handled by `Renderer::runOnce`
+
+#### Blocking updates
+
+If needed, call `forceUpdate` with the optional argument `async=false` to wait while an update runs (> 1 second). Additionally, the `awaitUpdate` method can be used to block until any previous update has completed. An example usage of this is waiting to draw the shutdown screen.
+
+#### Global rotation
+
+The exact size / position / rotation of InkHUD applets is configurable by the user. To achieve this, applets draw pixels between 0,0 and `Applet::width()`, `Applet::height()`
+
+- **Scaling**: Applet's `width()` and `height()` are set by `Tile` before rendering starts
+- **Translation**: `Tile` shifts applet pixels up/down/left/right
+- **Rotation**: `Renderer` rotates all pixels it receives, before placing them into the final image buffer
+
+---
+
+### `InkHUD::Renderer::DisplayHealth`
+
+_`src/graphics/niche/InkHUD/DisplayHealth.h`_
+
+Responsible for maintaining display health, by optimizing the ratio of FAST vs FULL refreshes
+
+- count number of FAST vs FULL refreshes (debt)
+- suggest either FAST or FULL type
+- periodically FULL refresh the display unprovoked, if needed
+
+#### Background Info
+
+When the image on an E-Ink display is updated, different procedures can be used to move the pixels to their new states. We have defined two procedures: `FAST` and `FULL`.
+
+A `FAST` update moves pixels directly from their old position, to their new position. This is aesthetically pleasing, and quick, _but_ it is challenging for the display hardware. If used excessively, pixels can build up residual charge, which negatively impacts the display's lifespan and image quality.
+
+A `FULL` update first moves all pixels between black and white, before letting them eventually settle at their final position. This causes an unpleasant flashing of the display image, but is best for the display health and image quality.
+
+Most displays readily tolerate `FAST` updates, so long as a `FULL` update is occasionally performed. How often this `FULL` update is required depends on the display model.
+
+#### Debt
+
+`InkHUD::DisplayHealth` records how many `FAST` refreshes have occurred since the previous `FULL` refresh.
+
+This is referred to as the "full refresh debt".
+
+If an update of a specific type (`FULL` / `FAST`) is requested / forced, this will be granted.
+
+If an update is requested / forced _without_ a specified type (`UpdateTypes::UNSPECIFIED`), `DisplayHealth` will select either `FAST` or `FULL`, in an attempt to maintain a target ratio of fast to full updates.
+
+This target is set by `InkHUD::setDisplayResilience`, when setting up in `nichegraphics.h`
+
+If an _excessive_ amount of `FAST` refreshes are performed back-to-back, `DisplayHealth` will begin artificially inflating the full refresh debt. This will cause the next few `UNSPECIFIED` updates to _all_ be performed as `FULL`, while the debt is paid down.
+
+This system of "full refresh debt" allows us to increase perceived responsiveness by tolerating additional strain on the display during periods of user interaction, and attempting to "repair the damage" later, once user interaction ceases.
+
+#### Maintenance
+
+The system of "full refresh debt" assumes that the display will perform many updates of `UNSPECIFIED` type between periods of user interaction. Depending on the amount of mesh traffic / applet selection, this may not be the case.
+
+If debt is particularly high, and no updates are taking place organically, `DisplayHealth` will begin infrequently performing `FULL` updates, purely to pay down the full refresh debt.
+
+---
+
+### `InkHUD::Events`
+
+Handles events which impact the InkHUD system generally (e.g. shutdown, button press).
+
+Applets themselves do also listen separately for various events, but for the purpose of gathering information which they would like to display.
+
+#### Buttons
+
+Button input is sometimes handled by a system applet. `InkHUD::Events` determines whether the button should be handled by a specific system applet, or should instead trigger a default behavior
+
+---
+
+### `InkHUD::Applet`
+
+A base class for applets. An applet is one "program", which may show info on the display.
+
+To oversimplify, all of the InkHUD code "under the hood" only exists to support applets. Applets are what actually shows useful information to the user. This base class exposes the functionality needed to write an applet.
+
+#### Drawing Methods
+
+`Applet` implements most AdafruitGFX drawing methods. Exception is the text handling. `printAt`, `printWrapped`, and `printThick` should be used instead. These are intended to be more convenient, but they also implement the character substitution system which powers the foreign alphabet support.
+
+`Applet` also adds methods for drawing several design elements which are re-used commonly though-out InkHUD.
+
+#### InkHUD Events
+
+Applets undergo a number of state changes: activated / deactivated by user, brought to foreground / hidden to background by user button press, etc. The `Applet` class provides a set of virtual methods, which an applet can override to appropriately handle these events.
+
+The `onRender` virtual method is one example. This is called when an applet is rendered, and should execute all drawing code. An applet _must_ implement this method.
+
+#### Responsive Design
+
+An applet's size will vary depending on the screen size, and the user's layout (multiplexing). Immediately before `onRender` is called, an applet's dimensions are updated, so that `width()` and `height()` will give the required size. The applet should draw its graphical elements relative to these values. The methods `X(float)` and `Y(float)` are also provided for convenience.
+
+| edge | coordinate | shorthand |
+| ------ | ---------- | --------- |
+| left | 0 | `X(0.0)` |
+| top | 0 | `Y(0.0)` |
+| right | `width()` | `X(1.0)` |
+| bottom | `height()` | `Y(1.0)` |
+
+The same principles apply for drawing text. Methods like `AppletFont::lineHeight` and `getTextWidth` are useful here.
+
+Applets should always draw relative to their top left corner, at _x=0, y=0._ The applet's pixels are automatically moved to the correct position on-screen by an InkHUD::Tile.
+
+#### User Applets
+
+User applets are the "normal" applets, each one displaying a specific set of information to the user. They can be activated / deactivated at run-time using the on-screen menu. Examples include `DMApplet.h` and `PositionsApplet.h`. User applets are not expected to interact with lower layers of the InkHUD code.
+
+Users applets are instantiated in a variant's `setupNicheGraphics` method, and passed to `InkHUD::addApplet`. Their class should not be mentioned elsewhere, so that its code can be stripped away during compilation if a variant does not implement the specific applet. Internal processing of user applets treats them all as the generic `Applet` type only.
+
+#### Activated / Deactivated
+
+User applets can be activated or deactivated. This changes at run-time: the user selects which applets should be active using the on-screen menu. An applet should not process data while it is deactivated. It can unobserve any observables, ignore `handleReceived` calls, etc.
+
+An applet can implement the virtual `onActivate` and `onDeactivate` methods to handle this change in state. It can check this state internally by calling `isActive`.
+
+System applets cannot be deactivated.
+
+#### Foreground / Background
+
+An activated applet can either be _foreground_ or _background_. A foreground applet is one which will be rendered to a tile when the screen updates. A background applet will not be drawn. The applet cycling which takes place when the user button is pressed is implemented using foreground / background.
+
+Regardless of whether it is foreground or background, an activated applet should continue to collect / process data, and request update when it has new info to display. This is because of the _autoshow_ mechanic, which might bring a background applet to foreground in order to display its data. If an applet remains background, its update requests will be safely ignored.
+
+#### Autoshow
+
+Autoshow is a feature which allows the user to select which applets (if any) they would like to be shown automatically. If autoshow is enabled for an applet, it will be brought to foreground when it has new information to display. The user grants this privilege on a per-applet basis, using the on-screen menu. If an event causes an applet to be autoshown, NotificationApplet should not be shown for the same event.
+
+An applet needs to decide when it has information worthy of autoshowing. It signals this by calling `requestAutoshow`, in addition to the usual `requestUpdate` call.
+
+---
+
+### `InkHUD::SystemApplet`
+
+_System applets_ are applets with special roles, which require special handling. Examples include `BatteryIconApplet.h` and `LogoApplet.h`. These are manually implemented, one-by-one, in `WindowManager.h`.
+
+This class is a slight extension of `Applet`. It adds extra flags for some special features which are restricted to system applets: exclusive use of the display, and the handling of user input. Having a separate system applet class also allows us to make it clear within the code when system applets are being handled, rather than user applets
+
+We store reference to these as a `vector`. This parallels how we treat user applets, and makes rendering convenient.
+Because system applets do have unique roles, there are times when we will need to interact with a specific applet. Rather than keeping an extra set of references, we access them from the `vector`. Use `InkHUD::getSystemApplet` to access the applet by its `Applet::name` value, and then typecast.
+
+---
+
+### `InkHUD::Tile`
+
+A tile represents a region of the display. A tile controls the size and position of an applet.
+
+For an applet to render, it must be assigned to a tile. When an applet is assigned to a tile, the two become linked. The applet is aware of the tile; the tile is aware of the applet. Applets cannot share a tile; assigning a different applet will remove any existing link.
+
+Before an applet renders, its width and height are set to the dimensions of the tile. During `onRender`, an applet's drawing methods generate pixels between _x=0, y=0_ and _x=Applet::width(), y=Applet::height()_. These pixels are passed to its tile's `Tile::handleAppletPixel` method. The tile then applies x and y offset, "translating" these pixels to the tile's region of the display. These translated pixels are then passed on to the `InkHUD::Renderer`.
+
+
+
+#### User Tiles
+
+_User applets_ are the "normal" applets. They can be activated / deactivated at run-time using the on-screen menu. User applets are rendered to one of the **user tiles**.
+
+The user can customize the "layout", using the on-screen menu. Depending on their selected layout, a certain number of _user tiles_ are created. These tiles are automatically positioned and sized so that they fill the entire screen.
+
+Often, a user will have enabled more applets than they have tiles. Pressing the user-button will cycle through these applets. The old applet is sent to _background_, the new applet is brought to _foreground_. When a user applet is brought to foreground, it becomes assigned to a user tile (the focused tile). When it renders, its size will be set by this tile, and its pixels will be translated to this tile's region. The user applet which was sent to background loses its assignment; it no longer has an assigned tile.
+
+#### Focused Tile
+
+The focused tile is one of the user tiles. This is tile whose applet will change when the user button is pressed. This also the tile where the menu will appear on longpress. The focused tile is identified by its index in `vector userTiles`.
+
+#### Highlighting
+
+In addition to the user button, some devices have a second "auxiliary button". The function of this button can vary from device to device, but it is sometimes used to focus a different tile. When this happens, the newly focused tile is temporarily "highlighted", by drawing it with a border. This border is automatically removed after several seconds. As drawing code may only be executed by applets, this highlighting is a collaborative effort between a `Tile` and an `Applet`: performed in `Applet::render`, after the virtual `onRender` method has already run.
+
+Highlighting is only used when `nextTile` is fired by an aux button. It does not occur if performed via the on-screen menu.
+
+#### System Tiles
+
+_System applets_ are applets with special roles, which require special handling. Examples include `BatteryIconApplet.h` and `LogoApplet.h`. _Mostly_, these applets do not render to user tiles. Instead, they are given their own unique tile, which is positioned / dimensioned manually. The only reference we keep to these special tiles is stored within the linked system applet. They can be accessed with `Applet::getTile`.
+
+---
+
+### `InkHUD::AppletFont`
+
+Wrapper which extends the functionality of an AdafruitGFX font.
+
+#### Dimension Info
+
+The AppletFont class pre-calculates some info about a font's dimensions, which is useful for design (`AppletFont::lineHeight`), and is used to power InkHUD's custom text handling.
+
+The default AdafruitGFX text handling places characters "upon a line", as if hand-written on a sheet of ruled paper. `InkHUD::AppletFont` measures the character set of the font, so that we instead draw fixed-height lines of text, positioned by the bounding box, with optional horizontal and vertical alignment.
+
+
+
+The height of this box is `AppletFont::lineHeight`, which is the height of the tallest character in the font. This gives us a fixed-height for text, which is much tighter than with AdafruitGFX's default line spacing.
+
+#### UTF-8 Substitutions
+
+To enable non-English text, the `AppletFont` class includes a mechanism to detect specific UTF-8 characters, and replace them with alternative glyphs from the AdafruitGFX font. This can be used to remap characters for a custom font, or to offer a suitable ASCII replacement.
+
+```cpp
+// With a custom font
+// ї is ASCII 0xBF, in Windows-1251 encoding
+addSubstitution("ї", "\xBF");
+
+// Substitution (with a default font)
+addSubstitution("ö", "oe");
+```
+
+These substitutions should be performed in a variant's `setupNicheGraphics` method. For convenience, some common ASCII encodings have ready-to-go sets of substitutions you can apply, for example `AppletFont::addSubstitutionsWin1251`
diff --git a/src/graphics/niche/InkHUD/docs/appletfont.png b/src/graphics/niche/InkHUD/docs/appletfont.png
new file mode 100644
index 000000000..f0b11d323
Binary files /dev/null and b/src/graphics/niche/InkHUD/docs/appletfont.png differ
diff --git a/src/graphics/niche/InkHUD/docs/disclaimer.jpg b/src/graphics/niche/InkHUD/docs/disclaimer.jpg
new file mode 100644
index 000000000..d4c2c890e
Binary files /dev/null and b/src/graphics/niche/InkHUD/docs/disclaimer.jpg differ
diff --git a/src/graphics/niche/InkHUD/docs/rendering.gif b/src/graphics/niche/InkHUD/docs/rendering.gif
new file mode 100644
index 000000000..cb712381b
Binary files /dev/null and b/src/graphics/niche/InkHUD/docs/rendering.gif differ
diff --git a/src/graphics/niche/InkHUD/docs/tile_translation.png b/src/graphics/niche/InkHUD/docs/tile_translation.png
new file mode 100644
index 000000000..7bbf63643
Binary files /dev/null and b/src/graphics/niche/InkHUD/docs/tile_translation.png differ
diff --git a/src/graphics/niche/Inputs/TwoButton.cpp b/src/graphics/niche/Inputs/TwoButton.cpp
index 10d89ef41..1e91d9080 100644
--- a/src/graphics/niche/Inputs/TwoButton.cpp
+++ b/src/graphics/niche/Inputs/TwoButton.cpp
@@ -2,6 +2,7 @@
#include "./TwoButton.h"
+#include "NodeDB.h" // For the helper function TwoButton::getUserButtonPin
#include "PowerFSM.h"
#include "sleep.h"
@@ -57,16 +58,48 @@ void TwoButton::stop()
detachInterrupt(buttons[1].pin);
}
+// Attempt to resolve a GPIO pin for the user button, honoring userPrefs.jsonc and device settings
+// This helper method isn't used by the TweButton class itself, it could be moved elsewhere.
+// Intention is to pass this value to TwoButton::setWiring in the setupNicheGraphics method.
+uint8_t TwoButton::getUserButtonPin()
+{
+ uint8_t pin = 0xFF; // Unset
+
+ // Use default pin for variant, if no better source
+#ifdef BUTTON_PIN
+ pin = BUTTON_PIN;
+#endif
+
+ // From userPrefs.jsonc, if set
+#ifdef USERPREFS_BUTTON_PIN
+ pin = USERPREFS_BUTTON_PIN;
+#endif
+
+ // From user's override in device settings, if set
+ if (config.device.button_gpio)
+ pin = config.device.button_gpio;
+
+ return pin;
+}
+
// Configures the wiring and logic of either button
// Called when outlining your NicheGraphics implementation, in variant/nicheGraphics.cpp
void TwoButton::setWiring(uint8_t whichButton, uint8_t pin, bool internalPullup)
{
+ // Prevent the same GPIO being assigned to multiple buttons
+ // Allows an edge case when the user remaps hardware buttons using device settings, due to a broken user button
+ for (uint8_t i = 0; i < whichButton; i++) {
+ if (buttons[i].pin == pin) {
+ LOG_WARN("Attempted reuse of GPIO %d. Ignoring assignment whichButton=%d", pin, whichButton);
+ return;
+ }
+ }
+
assert(whichButton < 2);
buttons[whichButton].pin = pin;
- buttons[whichButton].activeLogic = LOW;
- buttons[whichButton].mode = internalPullup ? INPUT_PULLUP : INPUT; // fix me
+ buttons[whichButton].activeLogic = LOW; // Unimplemented
- pinMode(buttons[whichButton].pin, buttons[whichButton].mode);
+ pinMode(buttons[whichButton].pin, internalPullup ? INPUT_PULLUP : INPUT);
}
void TwoButton::setTiming(uint8_t whichButton, uint32_t debounceMs, uint32_t longpressMs)
@@ -265,7 +298,9 @@ int TwoButton::afterLightSleep(esp_sleep_wakeup_cause_t cause)
// Manually trigger the button-down ISR
// - during light sleep, our ISR is disabled
// - if light sleep ends by button press, pretend our own ISR caught it
- if (cause == ESP_SLEEP_WAKEUP_GPIO)
+ // - need to manually confirm by reading pin ourselves, to avoid occasional false positives
+ // (false positive only when using internal pullup resistors?)
+ if (cause == ESP_SLEEP_WAKEUP_GPIO && digitalRead(buttons[0].pin) == buttons[0].activeLogic)
isrPrimary();
return 0; // Indicates success
diff --git a/src/graphics/niche/Inputs/TwoButton.h b/src/graphics/niche/Inputs/TwoButton.h
index 1e1576256..ae66adf96 100644
--- a/src/graphics/niche/Inputs/TwoButton.h
+++ b/src/graphics/niche/Inputs/TwoButton.h
@@ -30,10 +30,12 @@ class TwoButton : protected concurrency::OSThread
public:
typedef std::function Callback;
+ static uint8_t getUserButtonPin(); // Resolve the GPIO, considering the various possible source of definition
+
static TwoButton *getInstance(); // Create or get the singleton instance
void start(); // Start handling button input
void stop(); // Stop handling button input (disconnect ISRs for sleep)
- void setWiring(uint8_t whichButton, uint8_t pin, bool internalPulldown = false);
+ void setWiring(uint8_t whichButton, uint8_t pin, bool internalPullup = false);
void setTiming(uint8_t whichButton, uint32_t debounceMs, uint32_t longpressMs);
void setHandlerDown(uint8_t whichButton, Callback onDown);
void setHandlerUp(uint8_t whichButton, Callback onUp);
@@ -62,8 +64,7 @@ class TwoButton : protected concurrency::OSThread
public:
// Per-button config
uint8_t pin = 0xFF; // 0xFF: unset
- bool activeLogic = LOW; // Active LOW by default. Todo: remove, unused
- uint8_t mode = INPUT; // Whether to use internal pull up / pull down resistors
+ bool activeLogic = LOW; // Active LOW by default. Currently unimplemented.
uint32_t debounceLength = 50; // Minimum length for shortpress, in ms
uint32_t longpressLength = 500; // How long after button down to fire longpress, in ms
volatile State state = State::REST; // Internal state
diff --git a/src/input/TCA8418Keyboard.cpp b/src/input/TCA8418Keyboard.cpp
new file mode 100644
index 000000000..21cd7b2d5
--- /dev/null
+++ b/src/input/TCA8418Keyboard.cpp
@@ -0,0 +1,561 @@
+// Based on the MPR121 Keyboard and Adafruit TCA8418 library
+
+#include "TCA8418Keyboard.h"
+#include "configuration.h"
+
+#include
+
+// REGISTERS
+// #define _TCA8418_REG_RESERVED 0x00
+#define _TCA8418_REG_CFG 0x01 // Configuration register
+#define _TCA8418_REG_INT_STAT 0x02 // Interrupt status
+#define _TCA8418_REG_KEY_LCK_EC 0x03 // Key lock and event counter
+#define _TCA8418_REG_KEY_EVENT_A 0x04 // Key event register A
+#define _TCA8418_REG_KEY_EVENT_B 0x05 // Key event register B
+#define _TCA8418_REG_KEY_EVENT_C 0x06 // Key event register C
+#define _TCA8418_REG_KEY_EVENT_D 0x07 // Key event register D
+#define _TCA8418_REG_KEY_EVENT_E 0x08 // Key event register E
+#define _TCA8418_REG_KEY_EVENT_F 0x09 // Key event register F
+#define _TCA8418_REG_KEY_EVENT_G 0x0A // Key event register G
+#define _TCA8418_REG_KEY_EVENT_H 0x0B // Key event register H
+#define _TCA8418_REG_KEY_EVENT_I 0x0C // Key event register I
+#define _TCA8418_REG_KEY_EVENT_J 0x0D // Key event register J
+#define _TCA8418_REG_KP_LCK_TIMER 0x0E // Keypad lock1 to lock2 timer
+#define _TCA8418_REG_UNLOCK_1 0x0F // Unlock register 1
+#define _TCA8418_REG_UNLOCK_2 0x10 // Unlock register 2
+#define _TCA8418_REG_GPIO_INT_STAT_1 0x11 // GPIO interrupt status 1
+#define _TCA8418_REG_GPIO_INT_STAT_2 0x12 // GPIO interrupt status 2
+#define _TCA8418_REG_GPIO_INT_STAT_3 0x13 // GPIO interrupt status 3
+#define _TCA8418_REG_GPIO_DAT_STAT_1 0x14 // GPIO data status 1
+#define _TCA8418_REG_GPIO_DAT_STAT_2 0x15 // GPIO data status 2
+#define _TCA8418_REG_GPIO_DAT_STAT_3 0x16 // GPIO data status 3
+#define _TCA8418_REG_GPIO_DAT_OUT_1 0x17 // GPIO data out 1
+#define _TCA8418_REG_GPIO_DAT_OUT_2 0x18 // GPIO data out 2
+#define _TCA8418_REG_GPIO_DAT_OUT_3 0x19 // GPIO data out 3
+#define _TCA8418_REG_GPIO_INT_EN_1 0x1A // GPIO interrupt enable 1
+#define _TCA8418_REG_GPIO_INT_EN_2 0x1B // GPIO interrupt enable 2
+#define _TCA8418_REG_GPIO_INT_EN_3 0x1C // GPIO interrupt enable 3
+#define _TCA8418_REG_KP_GPIO_1 0x1D // Keypad/GPIO select 1
+#define _TCA8418_REG_KP_GPIO_2 0x1E // Keypad/GPIO select 2
+#define _TCA8418_REG_KP_GPIO_3 0x1F // Keypad/GPIO select 3
+#define _TCA8418_REG_GPI_EM_1 0x20 // GPI event mode 1
+#define _TCA8418_REG_GPI_EM_2 0x21 // GPI event mode 2
+#define _TCA8418_REG_GPI_EM_3 0x22 // GPI event mode 3
+#define _TCA8418_REG_GPIO_DIR_1 0x23 // GPIO data direction 1
+#define _TCA8418_REG_GPIO_DIR_2 0x24 // GPIO data direction 2
+#define _TCA8418_REG_GPIO_DIR_3 0x25 // GPIO data direction 3
+#define _TCA8418_REG_GPIO_INT_LVL_1 0x26 // GPIO edge/level detect 1
+#define _TCA8418_REG_GPIO_INT_LVL_2 0x27 // GPIO edge/level detect 2
+#define _TCA8418_REG_GPIO_INT_LVL_3 0x28 // GPIO edge/level detect 3
+#define _TCA8418_REG_DEBOUNCE_DIS_1 0x29 // Debounce disable 1
+#define _TCA8418_REG_DEBOUNCE_DIS_2 0x2A // Debounce disable 2
+#define _TCA8418_REG_DEBOUNCE_DIS_3 0x2B // Debounce disable 3
+#define _TCA8418_REG_GPIO_PULL_1 0x2C // GPIO pull-up disable 1
+#define _TCA8418_REG_GPIO_PULL_2 0x2D // GPIO pull-up disable 2
+#define _TCA8418_REG_GPIO_PULL_3 0x2E // GPIO pull-up disable 3
+// #define _TCA8418_REG_RESERVED 0x2F
+
+// FIELDS CONFIG REGISTER 1
+#define _TCA8418_REG_CFG_AI 0x80 // Auto-increment for read/write
+#define _TCA8418_REG_CFG_GPI_E_CGF 0x40 // Event mode config
+#define _TCA8418_REG_CFG_OVR_FLOW_M 0x20 // Overflow mode enable
+#define _TCA8418_REG_CFG_INT_CFG 0x10 // Interrupt config
+#define _TCA8418_REG_CFG_OVR_FLOW_IEN 0x08 // Overflow interrupt enable
+#define _TCA8418_REG_CFG_K_LCK_IEN 0x04 // Keypad lock interrupt enable
+#define _TCA8418_REG_CFG_GPI_IEN 0x02 // GPI interrupt enable
+#define _TCA8418_REG_CFG_KE_IEN 0x01 // Key events interrupt enable
+
+// FIELDS INT_STAT REGISTER 2
+#define _TCA8418_REG_STAT_CAD_INT 0x10 // Ctrl-alt-del seq status
+#define _TCA8418_REG_STAT_OVR_FLOW_INT 0x08 // Overflow interrupt status
+#define _TCA8418_REG_STAT_K_LCK_INT 0x04 // Key lock interrupt status
+#define _TCA8418_REG_STAT_GPI_INT 0x02 // GPI interrupt status
+#define _TCA8418_REG_STAT_K_INT 0x01 // Key events interrupt status
+
+// FIELDS KEY_LCK_EC REGISTER 3
+#define _TCA8418_REG_LCK_EC_K_LCK_EN 0x40 // Key lock enable
+#define _TCA8418_REG_LCK_EC_LCK_2 0x20 // Keypad lock status 2
+#define _TCA8418_REG_LCK_EC_LCK_1 0x10 // Keypad lock status 1
+#define _TCA8418_REG_LCK_EC_KLEC_3 0x08 // Key event count bit 3
+#define _TCA8418_REG_LCK_EC_KLEC_2 0x04 // Key event count bit 2
+#define _TCA8418_REG_LCK_EC_KLEC_1 0x02 // Key event count bit 1
+#define _TCA8418_REG_LCK_EC_KLEC_0 0x01 // Key event count bit 0
+
+// Pin IDs for matrix rows/columns
+enum {
+ _TCA8418_ROW0, // Pin ID for row 0
+ _TCA8418_ROW1, // Pin ID for row 1
+ _TCA8418_ROW2, // Pin ID for row 2
+ _TCA8418_ROW3, // Pin ID for row 3
+ _TCA8418_ROW4, // Pin ID for row 4
+ _TCA8418_ROW5, // Pin ID for row 5
+ _TCA8418_ROW6, // Pin ID for row 6
+ _TCA8418_ROW7, // Pin ID for row 7
+ _TCA8418_COL0, // Pin ID for column 0
+ _TCA8418_COL1, // Pin ID for column 1
+ _TCA8418_COL2, // Pin ID for column 2
+ _TCA8418_COL3, // Pin ID for column 3
+ _TCA8418_COL4, // Pin ID for column 4
+ _TCA8418_COL5, // Pin ID for column 5
+ _TCA8418_COL6, // Pin ID for column 6
+ _TCA8418_COL7, // Pin ID for column 7
+ _TCA8418_COL8, // Pin ID for column 8
+ _TCA8418_COL9 // Pin ID for column 9
+};
+
+#define _TCA8418_COLS 3
+#define _TCA8418_ROWS 4
+#define _TCA8418_NUM_KEYS 12
+
+uint8_t TCA8418TapMod[_TCA8418_NUM_KEYS] = {13, 7, 7, 7, 7, 7,
+ 9, 7, 9, 2, 2, 2}; // Num chars per key, Modulus for rotating through characters
+
+unsigned char TCA8418TapMap[_TCA8418_NUM_KEYS][13] = {
+ {'1', '.', ',', '?', '!', ':', ';', '-', '_', '\\', '/', '(', ')'}, // 1
+ {'2', 'a', 'b', 'c', 'A', 'B', 'C'}, // 2
+ {'3', 'd', 'e', 'f', 'D', 'E', 'F'}, // 3
+ {'4', 'g', 'h', 'i', 'G', 'H', 'I'}, // 4
+ {'5', 'j', 'k', 'l', 'J', 'K', 'L'}, // 5
+ {'6', 'm', 'n', 'o', 'M', 'N', 'O'}, // 6
+ {'7', 'p', 'q', 'r', 's', 'P', 'Q', 'R', 'S'}, // 7
+ {'8', 't', 'u', 'v', 'T', 'U', 'V'}, // 8
+ {'9', 'w', 'x', 'y', 'z', 'W', 'X', 'Y', 'Z'}, // 9
+ {'*', '+'}, // *
+ {'0', ' '}, // 0
+ {'#', '@'}, // #
+};
+
+unsigned char TCA8418LongPressMap[_TCA8418_NUM_KEYS] = {
+ _TCA8418_ESC, // 1
+ _TCA8418_UP, // 2
+ _TCA8418_NONE, // 3
+ _TCA8418_LEFT, // 4
+ _TCA8418_NONE, // 5
+ _TCA8418_RIGHT, // 6
+ _TCA8418_NONE, // 7
+ _TCA8418_DOWN, // 8
+ _TCA8418_NONE, // 9
+ _TCA8418_BSP, // *
+ _TCA8418_NONE, // 0
+ _TCA8418_NONE, // #
+};
+
+#define _TCA8418_LONG_PRESS_THRESHOLD 2000
+#define _TCA8418_MULTI_TAP_THRESHOLD 750
+
+TCA8418Keyboard::TCA8418Keyboard() : m_wire(nullptr), m_addr(0), readCallback(nullptr), writeCallback(nullptr)
+{
+ state = Init;
+ last_key = -1;
+ next_key = -1;
+ should_backspace = false;
+ last_tap = 0L;
+ char_idx = 0;
+ tap_interval = 0;
+ backlight_on = true;
+ queue = "";
+}
+
+void TCA8418Keyboard::begin(uint8_t addr, TwoWire *wire)
+{
+ m_addr = addr;
+ m_wire = wire;
+
+ m_wire->begin();
+
+ reset();
+}
+
+void TCA8418Keyboard::begin(i2c_com_fptr_t r, i2c_com_fptr_t w, uint8_t addr)
+{
+ m_addr = addr;
+ m_wire = nullptr;
+ writeCallback = w;
+ readCallback = r;
+ reset();
+}
+
+void TCA8418Keyboard::reset()
+{
+ LOG_DEBUG("TCA8418 Reset");
+ // GPIO
+ // set default all GIO pins to INPUT
+ writeRegister(_TCA8418_REG_GPIO_DIR_1, 0x00);
+ writeRegister(_TCA8418_REG_GPIO_DIR_2, 0x00);
+ // Set COL9 as GPIO output
+ writeRegister(_TCA8418_REG_GPIO_DIR_3, 0x02);
+ // Switch off keyboard backlight (COL9 = LOW)
+ writeRegister(_TCA8418_REG_GPIO_DAT_OUT_3, 0x00);
+
+ // add all pins to key events
+ writeRegister(_TCA8418_REG_GPI_EM_1, 0xFF);
+ writeRegister(_TCA8418_REG_GPI_EM_2, 0xFF);
+ writeRegister(_TCA8418_REG_GPI_EM_3, 0xFF);
+
+ // set all pins to FALLING interrupts
+ writeRegister(_TCA8418_REG_GPIO_INT_LVL_1, 0x00);
+ writeRegister(_TCA8418_REG_GPIO_INT_LVL_2, 0x00);
+ writeRegister(_TCA8418_REG_GPIO_INT_LVL_3, 0x00);
+
+ // add all pins to interrupts
+ writeRegister(_TCA8418_REG_GPIO_INT_EN_1, 0xFF);
+ writeRegister(_TCA8418_REG_GPIO_INT_EN_2, 0xFF);
+ writeRegister(_TCA8418_REG_GPIO_INT_EN_3, 0xFF);
+
+ // Set keyboard matrix size
+ matrix(_TCA8418_ROWS, _TCA8418_COLS);
+ enableDebounce();
+ flush();
+ state = Idle;
+}
+
+bool TCA8418Keyboard::matrix(uint8_t rows, uint8_t columns)
+{
+ if ((rows > 8) || (columns > 10))
+ return false;
+
+ // Skip zero size matrix
+ if ((rows != 0) && (columns != 0)) {
+ // Setup the keypad matrix.
+ uint8_t mask = 0x00;
+ for (int r = 0; r < rows; r++) {
+ mask <<= 1;
+ mask |= 1;
+ }
+ writeRegister(_TCA8418_REG_KP_GPIO_1, mask);
+
+ mask = 0x00;
+ for (int c = 0; c < columns && c < 8; c++) {
+ mask <<= 1;
+ mask |= 1;
+ }
+ writeRegister(_TCA8418_REG_KP_GPIO_2, mask);
+
+ if (columns > 8) {
+ if (columns == 9)
+ mask = 0x01;
+ else
+ mask = 0x03;
+ writeRegister(_TCA8418_REG_KP_GPIO_3, mask);
+ }
+ }
+
+ return true;
+}
+
+uint8_t TCA8418Keyboard::keyCount() const
+{
+ uint8_t eventCount = readRegister(_TCA8418_REG_KEY_LCK_EC);
+ eventCount &= 0x0F; // lower 4 bits only
+ return eventCount;
+}
+
+bool TCA8418Keyboard::hasEvent()
+{
+ return queue.length() > 0;
+}
+
+void TCA8418Keyboard::queueEvent(char next)
+{
+ if (next == _TCA8418_NONE) {
+ return;
+ }
+ queue.concat(next);
+}
+
+char TCA8418Keyboard::dequeueEvent()
+{
+ if (queue.length() < 1) {
+ return _TCA8418_NONE;
+ }
+ char next = queue.charAt(0);
+ queue.remove(0, 1);
+ return next;
+}
+
+void TCA8418Keyboard::trigger()
+{
+ if (keyCount() == 0) {
+ return;
+ }
+ if (state != Init) {
+ // Read the key register
+ uint8_t k = readRegister(_TCA8418_REG_KEY_EVENT_A);
+ uint8_t key = k & 0x7F;
+ if (k & 0x80) {
+ if (state == Idle)
+ pressed(key);
+ return;
+ } else {
+ if (state == Held) {
+ released();
+ }
+ state = Idle;
+ return;
+ }
+ } else {
+ reset();
+ }
+}
+
+void TCA8418Keyboard::pressed(uint8_t key)
+{
+ if (state == Init || state == Busy) {
+ return;
+ }
+ uint8_t next_key = 0;
+ int row = (key - 1) / 10;
+ int col = (key - 1) % 10;
+
+ if (row >= _TCA8418_ROWS || col >= _TCA8418_COLS) {
+ return; // Invalid key
+ }
+
+ // Compute key index based on dynamic row/column
+ next_key = row * _TCA8418_COLS + col;
+
+ // LOG_DEBUG("TCA8418: Key %u -> Next Key %u", key, next_key);
+
+ state = Held;
+ uint32_t now = millis();
+ tap_interval = now - last_tap;
+ if (tap_interval < 0) {
+ // Long running, millis has overflowed.
+ last_tap = 0;
+ state = Busy;
+ return;
+ }
+
+ // Check if the key is the same as the last one or if the time interval has passed
+ if (next_key != last_key || tap_interval > _TCA8418_MULTI_TAP_THRESHOLD) {
+ char_idx = 0; // Reset char index if new key or long press
+ should_backspace = false; // dont backspace on new key
+ } else {
+ char_idx += 1; // Cycle through characters if same key pressed
+ should_backspace = true; // allow backspace on same key
+ }
+
+ // Store the current key as the last key
+ last_key = next_key;
+ last_tap = now;
+}
+
+void TCA8418Keyboard::released()
+{
+ if (state != Held) {
+ return;
+ }
+
+ if (last_key < 0 || last_key > _TCA8418_NUM_KEYS) { // reset to idle if last_key out of bounds
+ last_key = -1;
+ state = Idle;
+ return;
+ }
+ uint32_t now = millis();
+ int32_t held_interval = now - last_tap;
+ last_tap = now;
+ if (tap_interval < _TCA8418_MULTI_TAP_THRESHOLD && should_backspace) {
+ queueEvent(_TCA8418_BSP);
+ }
+ if (held_interval > _TCA8418_LONG_PRESS_THRESHOLD) {
+ queueEvent(TCA8418LongPressMap[last_key]);
+ // LOG_DEBUG("Long Press Key: %i Map: %i", last_key, TCA8418LongPressMap[last_key]);
+ } else {
+ queueEvent(TCA8418TapMap[last_key][(char_idx % TCA8418TapMod[last_key])]);
+ // LOG_DEBUG("Key Press: %i Index:%i if %i Map: %c", last_key, char_idx, TCA8418TapMod[last_key],
+ // TCA8418TapMap[last_key][(char_idx % TCA8418TapMod[last_key])]);
+ }
+}
+
+uint8_t TCA8418Keyboard::flush()
+{
+ // Flush key events
+ uint8_t count = 0;
+ while (readRegister(_TCA8418_REG_KEY_EVENT_A) != 0)
+ count++;
+ // Flush gpio events
+ readRegister(_TCA8418_REG_GPIO_INT_STAT_1);
+ readRegister(_TCA8418_REG_GPIO_INT_STAT_2);
+ readRegister(_TCA8418_REG_GPIO_INT_STAT_3);
+ // Clear INT_STAT register
+ writeRegister(_TCA8418_REG_INT_STAT, 3);
+ return count;
+}
+
+uint8_t TCA8418Keyboard::digitalRead(uint8_t pinnum) const
+{
+ if (pinnum > _TCA8418_COL9)
+ return 0xFF;
+
+ uint8_t reg = _TCA8418_REG_GPIO_DAT_STAT_1 + pinnum / 8;
+ uint8_t mask = (1 << (pinnum % 8));
+
+ // Level 0 = low other = high
+ uint8_t value = readRegister(reg);
+ if (value & mask)
+ return HIGH;
+ return LOW;
+}
+
+bool TCA8418Keyboard::digitalWrite(uint8_t pinnum, uint8_t level)
+{
+ if (pinnum > _TCA8418_COL9)
+ return false;
+
+ uint8_t reg = _TCA8418_REG_GPIO_DAT_OUT_1 + pinnum / 8;
+ uint8_t mask = (1 << (pinnum % 8));
+
+ // Level 0 = low other = high
+ uint8_t value = readRegister(reg);
+ if (level == LOW)
+ value &= ~mask;
+ else
+ value |= mask;
+ writeRegister(reg, value);
+ return true;
+}
+
+bool TCA8418Keyboard::pinMode(uint8_t pinnum, uint8_t mode)
+{
+ if (pinnum > _TCA8418_COL9)
+ return false;
+
+ uint8_t idx = pinnum / 8;
+ uint8_t reg = _TCA8418_REG_GPIO_DIR_1 + idx;
+ uint8_t mask = (1 << (pinnum % 8));
+
+ // Mode 0 = input 1 = output
+ uint8_t value = readRegister(reg);
+ if (mode == OUTPUT)
+ value |= mask;
+ else
+ value &= ~mask;
+ writeRegister(reg, value);
+
+ // Pullup 0 = enabled 1 = disabled
+ reg = _TCA8418_REG_GPIO_PULL_1 + idx;
+ value = readRegister(reg);
+ if (mode == INPUT_PULLUP)
+ value &= ~mask;
+ else
+ value |= mask;
+ writeRegister(reg, value);
+
+ return true;
+}
+
+bool TCA8418Keyboard::pinIRQMode(uint8_t pinnum, uint8_t mode)
+{
+ if (pinnum > _TCA8418_COL9)
+ return false;
+ if ((mode != RISING) && (mode != FALLING))
+ return false;
+
+ // Mode 0 = falling 1 = rising
+ uint8_t idx = pinnum / 8;
+ uint8_t reg = _TCA8418_REG_GPIO_INT_LVL_1 + idx;
+ uint8_t mask = (1 << (pinnum % 8));
+
+ uint8_t value = readRegister(reg);
+ if (mode == RISING)
+ value |= mask;
+ else
+ value &= ~mask;
+ writeRegister(reg, value);
+
+ // Enable interrupt
+ reg = _TCA8418_REG_GPIO_INT_EN_1 + idx;
+ value = readRegister(reg);
+ value |= mask;
+ writeRegister(reg, value);
+
+ return true;
+}
+
+void TCA8418Keyboard::enableInterrupts()
+{
+ uint8_t value = readRegister(_TCA8418_REG_CFG);
+ value |= (_TCA8418_REG_CFG_GPI_IEN | _TCA8418_REG_CFG_KE_IEN);
+ writeRegister(_TCA8418_REG_CFG, value);
+};
+
+void TCA8418Keyboard::disableInterrupts()
+{
+ uint8_t value = readRegister(_TCA8418_REG_CFG);
+ value &= ~(_TCA8418_REG_CFG_GPI_IEN | _TCA8418_REG_CFG_KE_IEN);
+ writeRegister(_TCA8418_REG_CFG, value);
+};
+
+void TCA8418Keyboard::enableMatrixOverflow()
+{
+ uint8_t value = readRegister(_TCA8418_REG_CFG);
+ value |= _TCA8418_REG_CFG_OVR_FLOW_M;
+ writeRegister(_TCA8418_REG_CFG, value);
+};
+
+void TCA8418Keyboard::disableMatrixOverflow()
+{
+ uint8_t value = readRegister(_TCA8418_REG_CFG);
+ value &= ~_TCA8418_REG_CFG_OVR_FLOW_M;
+ writeRegister(_TCA8418_REG_CFG, value);
+};
+
+void TCA8418Keyboard::enableDebounce()
+{
+ writeRegister(_TCA8418_REG_DEBOUNCE_DIS_1, 0x00);
+ writeRegister(_TCA8418_REG_DEBOUNCE_DIS_2, 0x00);
+ writeRegister(_TCA8418_REG_DEBOUNCE_DIS_3, 0x00);
+}
+
+void TCA8418Keyboard::disableDebounce()
+{
+ writeRegister(_TCA8418_REG_DEBOUNCE_DIS_1, 0xFF);
+ writeRegister(_TCA8418_REG_DEBOUNCE_DIS_2, 0xFF);
+ writeRegister(_TCA8418_REG_DEBOUNCE_DIS_3, 0xFF);
+}
+
+void TCA8418Keyboard::setBacklight(bool on)
+{
+ if (on) {
+ digitalWrite(_TCA8418_COL9, HIGH);
+ } else {
+ digitalWrite(_TCA8418_COL9, LOW);
+ }
+}
+
+uint8_t TCA8418Keyboard::readRegister(uint8_t reg) const
+{
+ if (m_wire) {
+ m_wire->beginTransmission(m_addr);
+ m_wire->write(reg);
+ m_wire->endTransmission();
+
+ m_wire->requestFrom(m_addr, (uint8_t)1);
+ if (m_wire->available() < 1)
+ return 0;
+
+ return m_wire->read();
+ }
+ if (readCallback) {
+ uint8_t data;
+ readCallback(m_addr, reg, &data, 1);
+ return data;
+ }
+ return 0;
+}
+
+void TCA8418Keyboard::writeRegister(uint8_t reg, uint8_t value)
+{
+ uint8_t data[2];
+ data[0] = reg;
+ data[1] = value;
+
+ if (m_wire) {
+ m_wire->beginTransmission(m_addr);
+ m_wire->write(data, sizeof(uint8_t) * 2);
+ m_wire->endTransmission();
+ }
+ if (writeCallback) {
+ writeCallback(m_addr, data[0], &(data[1]), 1);
+ }
+}
\ No newline at end of file
diff --git a/src/input/TCA8418Keyboard.h b/src/input/TCA8418Keyboard.h
new file mode 100644
index 000000000..c7f3c1f28
--- /dev/null
+++ b/src/input/TCA8418Keyboard.h
@@ -0,0 +1,83 @@
+// Based on the MPR121 Keyboard and Adafruit TCA8418 library
+#include "configuration.h"
+#include
+
+#define _TCA8418_NONE 0x00
+#define _TCA8418_REBOOT 0x90
+#define _TCA8418_LEFT 0xb4
+#define _TCA8418_UP 0xb5
+#define _TCA8418_DOWN 0xb6
+#define _TCA8418_RIGHT 0xb7
+#define _TCA8418_ESC 0x1b
+#define _TCA8418_BSP 0x08
+#define _TCA8418_SELECT 0x0d
+
+class TCA8418Keyboard
+{
+ public:
+ typedef uint8_t (*i2c_com_fptr_t)(uint8_t dev_addr, uint8_t reg_addr, uint8_t *data, uint8_t len);
+
+ enum KeyState { Init = 0, Idle, Held, Busy };
+
+ KeyState state;
+ int8_t last_key;
+ int8_t next_key;
+ bool should_backspace;
+ uint32_t last_tap;
+ uint8_t char_idx;
+ int32_t tap_interval;
+ bool backlight_on;
+
+ String queue;
+
+ TCA8418Keyboard();
+
+ void begin(uint8_t addr = XPOWERS_AXP192_AXP2101_ADDRESS, TwoWire *wire = &Wire);
+ void begin(i2c_com_fptr_t r, i2c_com_fptr_t w, uint8_t addr = XPOWERS_AXP192_AXP2101_ADDRESS);
+
+ void reset(void);
+ // Configure the size of the keypad.
+ // All other rows and columns are set as inputs.
+ bool matrix(uint8_t rows, uint8_t columns);
+
+ // Flush all events in the FIFO buffer + GPIO events.
+ uint8_t flush(void);
+
+ // Key events available in the internal FIFO buffer.
+ uint8_t keyCount(void) const;
+
+ void trigger(void);
+ void pressed(uint8_t key);
+ void released(void);
+ bool hasEvent(void);
+ char dequeueEvent(void);
+ void queueEvent(char);
+
+ uint8_t digitalRead(uint8_t pinnum) const;
+ bool digitalWrite(uint8_t pinnum, uint8_t level);
+ bool pinMode(uint8_t pinnum, uint8_t mode);
+ bool pinIRQMode(uint8_t pinnum, uint8_t mode); // MODE FALLING or RISING
+
+ // enable / disable interrupts for matrix and GPI pins
+ void enableInterrupts();
+ void disableInterrupts();
+
+ // ignore key events when FIFO buffer is full or not.
+ void enableMatrixOverflow();
+ void disableMatrixOverflow();
+
+ // debounce keys.
+ void enableDebounce();
+ void disableDebounce();
+
+ void setBacklight(bool on);
+
+ uint8_t readRegister(uint8_t reg) const;
+ void writeRegister(uint8_t reg, uint8_t value);
+
+ private:
+ TwoWire *m_wire;
+ uint8_t m_addr;
+ i2c_com_fptr_t readCallback;
+ i2c_com_fptr_t writeCallback;
+};
diff --git a/src/input/cardKbI2cImpl.cpp b/src/input/cardKbI2cImpl.cpp
index eb9b07d6e..21ecf381a 100644
--- a/src/input/cardKbI2cImpl.cpp
+++ b/src/input/cardKbI2cImpl.cpp
@@ -12,8 +12,8 @@ void CardKbI2cImpl::init()
#if !MESHTASTIC_EXCLUDE_I2C && !defined(ARCH_PORTDUINO) && !defined(I2C_NO_RESCAN)
if (cardkb_found.address == 0x00) {
LOG_DEBUG("Rescan for I2C keyboard");
- uint8_t i2caddr_scan[] = {CARDKB_ADDR, TDECK_KB_ADDR, BBQ10_KB_ADDR, MPR121_KB_ADDR};
- uint8_t i2caddr_asize = 4;
+ uint8_t i2caddr_scan[] = {CARDKB_ADDR, TDECK_KB_ADDR, BBQ10_KB_ADDR, MPR121_KB_ADDR, XPOWERS_AXP192_AXP2101_ADDRESS};
+ uint8_t i2caddr_asize = 5;
auto i2cScanner = std::unique_ptr(new ScanI2CTwoWire());
#if WIRE_INTERFACES_COUNT == 2
@@ -43,6 +43,10 @@ void CardKbI2cImpl::init()
// assign an arbitrary value to distinguish from other models
kb_model = 0x37;
break;
+ case ScanI2C::DeviceType::TCA8418KB:
+ // assign an arbitrary value to distinguish from other models
+ kb_model = 0x84;
+ break;
default:
// use this as default since it's also just zero
LOG_WARN("kb_info.type is unknown(0x%02x), setting kb_model=0x00", kb_info.type);
diff --git a/src/input/kbI2cBase.cpp b/src/input/kbI2cBase.cpp
index 9b1a27745..70e9e4365 100644
--- a/src/input/kbI2cBase.cpp
+++ b/src/input/kbI2cBase.cpp
@@ -43,6 +43,9 @@ int32_t KbI2cBase::runOnce()
if (cardkb_found.address == MPR121_KB_ADDR) {
MPRkeyboard.begin(MPR121_KB_ADDR, &Wire1);
}
+ if (cardkb_found.address == XPOWERS_AXP192_AXP2101_ADDRESS) {
+ TCAKeyboard.begin(XPOWERS_AXP192_AXP2101_ADDRESS, &Wire1);
+ }
break;
#endif
case ScanI2C::WIRE:
@@ -55,6 +58,9 @@ int32_t KbI2cBase::runOnce()
if (cardkb_found.address == MPR121_KB_ADDR) {
MPRkeyboard.begin(MPR121_KB_ADDR, &Wire);
}
+ if (cardkb_found.address == XPOWERS_AXP192_AXP2101_ADDRESS) {
+ TCAKeyboard.begin(XPOWERS_AXP192_AXP2101_ADDRESS, &Wire);
+ }
break;
case ScanI2C::NO_I2C:
default:
@@ -226,6 +232,68 @@ int32_t KbI2cBase::runOnce()
}
break;
}
+ case 0x84: { // Adafruit TCA8418
+ TCAKeyboard.trigger();
+ InputEvent e;
+ while (TCAKeyboard.hasEvent()) {
+ char nextEvent = TCAKeyboard.dequeueEvent();
+ e.inputEvent = ANYKEY;
+ e.kbchar = 0x00;
+ e.source = this->_originName;
+ switch (nextEvent) {
+ case _TCA8418_NONE:
+ e.inputEvent = meshtastic_ModuleConfig_CannedMessageConfig_InputEventChar_NONE;
+ e.kbchar = 0x00;
+ break;
+ case _TCA8418_REBOOT:
+ e.inputEvent = ANYKEY;
+ e.kbchar = INPUT_BROKER_MSG_REBOOT;
+ break;
+ case _TCA8418_LEFT:
+ e.inputEvent = meshtastic_ModuleConfig_CannedMessageConfig_InputEventChar_LEFT;
+ e.kbchar = 0x00;
+ break;
+ case _TCA8418_UP:
+ e.inputEvent = meshtastic_ModuleConfig_CannedMessageConfig_InputEventChar_UP;
+ e.kbchar = 0x00;
+ break;
+ case _TCA8418_DOWN:
+ e.inputEvent = meshtastic_ModuleConfig_CannedMessageConfig_InputEventChar_DOWN;
+ e.kbchar = 0x00;
+ break;
+ case _TCA8418_RIGHT:
+ e.inputEvent = meshtastic_ModuleConfig_CannedMessageConfig_InputEventChar_RIGHT;
+ e.kbchar = 0x00;
+ break;
+ case _TCA8418_BSP:
+ e.inputEvent = meshtastic_ModuleConfig_CannedMessageConfig_InputEventChar_BACK;
+ e.kbchar = 0x08;
+ break;
+ case _TCA8418_SELECT:
+ e.inputEvent = meshtastic_ModuleConfig_CannedMessageConfig_InputEventChar_SELECT;
+ e.kbchar = 0x0d;
+ break;
+ case _TCA8418_ESC:
+ e.inputEvent = meshtastic_ModuleConfig_CannedMessageConfig_InputEventChar_CANCEL;
+ e.kbchar = 0x1b;
+ break;
+ default:
+ if (nextEvent > 127) {
+ e.inputEvent = meshtastic_ModuleConfig_CannedMessageConfig_InputEventChar_NONE;
+ e.kbchar = 0x00;
+ break;
+ }
+ e.inputEvent = ANYKEY;
+ e.kbchar = nextEvent;
+ break;
+ }
+ if (e.inputEvent != meshtastic_ModuleConfig_CannedMessageConfig_InputEventChar_NONE) {
+ LOG_DEBUG("TCA8418 Notifying: %i Char: %c", e.inputEvent, e.kbchar);
+ this->notifyObservers(&e);
+ }
+ }
+ break;
+ }
case 0x02: {
// RAK14004
uint8_t rDataBuf[8] = {0};
diff --git a/src/input/kbI2cBase.h b/src/input/kbI2cBase.h
index dc2414fc0..8193433fe 100644
--- a/src/input/kbI2cBase.h
+++ b/src/input/kbI2cBase.h
@@ -3,6 +3,7 @@
#include "BBQ10Keyboard.h"
#include "InputBroker.h"
#include "MPR121Keyboard.h"
+#include "TCA8418Keyboard.h"
#include "Wire.h"
#include "concurrency/OSThread.h"
@@ -21,5 +22,6 @@ class KbI2cBase : public Observable, public concurrency::OST
BBQ10Keyboard Q10keyboard;
MPR121Keyboard MPRkeyboard;
+ TCA8418Keyboard TCAKeyboard;
bool is_sym = false;
};
\ No newline at end of file
diff --git a/src/main.cpp b/src/main.cpp
index 59cd6d8e9..bfbd73a43 100644
--- a/src/main.cpp
+++ b/src/main.cpp
@@ -212,6 +212,64 @@ const char *getDeviceName()
return name;
}
+#if defined(ELECROW_ThinkNode_M1) || defined(ELECROW_ThinkNode_M2)
+static int32_t ledBlinkCount = 0;
+
+static int32_t elecrowLedBlinker()
+{
+ // are we in alert buzzer mode?
+#if HAS_BUTTON
+ if (buttonThread->isBuzzing()) {
+ // blink LED three times for 3 seconds, then 3 times for a second, with one second pause
+ if (ledBlinkCount % 2) { // odd means LED OFF
+ ledBlink.set(false);
+ ledBlinkCount++;
+ if (ledBlinkCount >= 12)
+ ledBlinkCount = 0;
+ noTone(PIN_BUZZER);
+ return 1000;
+ } else {
+ if (ledBlinkCount < 6) {
+ ledBlink.set(true);
+ tone(PIN_BUZZER, 4000, 3000);
+ ledBlinkCount++;
+ return 3000;
+ } else {
+ ledBlink.set(true);
+ tone(PIN_BUZZER, 4000, 1000);
+ ledBlinkCount++;
+ return 1000;
+ }
+ }
+ } else {
+#endif
+ ledBlinkCount = 0;
+ if (config.device.led_heartbeat_disabled)
+ return 1000;
+
+ static bool ledOn;
+ // remain on when fully charged or discharging above 10%
+ if ((powerStatus->getIsCharging() && powerStatus->getBatteryChargePercent() >= 100) ||
+ (!powerStatus->getIsCharging() && powerStatus->getBatteryChargePercent() >= 10)) {
+ ledOn = true;
+ } else {
+ ledOn ^= 1;
+ }
+ ledBlink.set(ledOn);
+ // when charging, blink 0.5Hz square wave rate to indicate that
+ if (powerStatus->getIsCharging()) {
+ return 500;
+ }
+ // Blink rapidly when almost empty or if battery is not connected
+ if ((!powerStatus->getIsCharging() && powerStatus->getBatteryChargePercent() < 10) || !powerStatus->getHasBattery()) {
+ return 250;
+ }
+#if HAS_BUTTON
+ }
+#endif
+ return 1000;
+}
+#else
static int32_t ledBlinker()
{
// Still set up the blinking (heartbeat) interval but skip code path below, so LED will blink if
@@ -227,6 +285,7 @@ static int32_t ledBlinker()
// have a very sparse duty cycle of LED being on, unless charging, then blink 0.5Hz square wave rate to indicate that
return powerStatus->getIsCharging() ? 1000 : (ledOn ? 1 : 1000);
}
+#endif
uint32_t timeLastPowered = 0;
@@ -263,11 +322,6 @@ void printInfo()
void setup()
{
-#ifdef POWER_CHRG
- pinMode(POWER_CHRG, OUTPUT);
- digitalWrite(POWER_CHRG, HIGH);
-#endif
-
#if defined(PIN_POWER_EN)
pinMode(PIN_POWER_EN, OUTPUT);
digitalWrite(PIN_POWER_EN, HIGH);
@@ -278,11 +332,6 @@ void setup()
digitalWrite(LED_POWER, HIGH);
#endif
-#ifdef POWER_LED
- pinMode(POWER_LED, OUTPUT);
- digitalWrite(POWER_LED, HIGH);
-#endif
-
#ifdef USER_LED
pinMode(USER_LED, OUTPUT);
digitalWrite(USER_LED, LOW);
@@ -414,7 +463,12 @@ void setup()
OSThread::setup();
+#if defined(ELECROW_ThinkNode_M1) || defined(ELECROW_ThinkNode_M2)
+ // The ThinkNodes have their own blink logic
+ ledPeriodic = new Periodic("Blink", elecrowLedBlinker);
+#else
ledPeriodic = new Periodic("Blink", ledBlinker);
+#endif
fsInit();
@@ -587,6 +641,10 @@ void setup()
// assign an arbitrary value to distinguish from other models
kb_model = 0x37;
break;
+ case ScanI2C::DeviceType::TCA8418KB:
+ // assign an arbitrary value to distinguish from other models
+ kb_model = 0x84;
+ break;
default:
// use this as default since it's also just zero
LOG_WARN("kb_info.type is unknown(0x%02x), setting kb_model=0x00", kb_info.type);
@@ -602,9 +660,9 @@ void setup()
* "found".
*/
-// Only one supported RGB LED currently
-#ifdef HAS_NCP5623
- rgb_found = i2cScanner->find(ScanI2C::DeviceType::NCP5623);
+// Two supported RGB LED currently
+#ifdef HAS_RGB_LED
+ rgb_found = i2cScanner->firstRGBLED();
#endif
#ifdef HAS_TPS65233
@@ -1270,10 +1328,23 @@ extern meshtastic_DeviceMetadata getDeviceMetadata()
#ifndef ARCH_ESP32
deviceMetadata.excluded_modules |= meshtastic_ExcludedModules_PAXCOUNTER_CONFIG;
#endif
-#if !defined(HAS_NCP5623) && !defined(RGBLED_RED) && !defined(HAS_NEOPIXEL) && !defined(UNPHONE) && !RAK_4631
+#if !defined(HAS_RGB_LED) && !RAK_4631
deviceMetadata.excluded_modules |= meshtastic_ExcludedModules_AMBIENTLIGHTING_CONFIG;
#endif
+// No bluetooth on these targets (yet):
+// Pico W / 2W may get it at some point
+// Portduino and ESP32-C6 are excluded because we don't have a working bluetooth stacks integrated yet.
+#if defined(ARCH_RP2040) || defined(ARCH_PORTDUINO) || defined(ARCH_STM32WL) || defined(CONFIG_IDF_TARGET_ESP32C6)
+ deviceMetadata.excluded_modules |= meshtastic_ExcludedModules_BLUETOOTH_CONFIG;
+#endif
+
+#if defined(ARCH_NRF52) && !HAS_ETHERNET // nrf52 doesn't have network unless it's a RAK ethernet gateway currently
+ deviceMetadata.excluded_modules |= meshtastic_ExcludedModules_NETWORK_CONFIG; // No network on nRF52
+#elif defined(ARCH_RP2040) && !HAS_WIFI && !HAS_ETHERNET
+ deviceMetadata.excluded_modules |= meshtastic_ExcludedModules_NETWORK_CONFIG; // No network on RP2040
+#endif
+
#if !(MESHTASTIC_EXCLUDE_PKI)
deviceMetadata.hasPKC = true;
#endif
diff --git a/src/mesh/NodeDB.cpp b/src/mesh/NodeDB.cpp
index 3f79d18e6..c89abbe74 100644
--- a/src/mesh/NodeDB.cpp
+++ b/src/mesh/NodeDB.cpp
@@ -689,7 +689,7 @@ void NodeDB::initConfigIntervals()
config.display.screen_on_secs = default_screen_on_secs;
-#if defined(T_WATCH_S3) || defined(T_DECK) || defined(MESH_TAB) || defined(RAK14014)
+#if defined(T_WATCH_S3) || defined(T_DECK) || defined(UNPHONE) || defined(MESH_TAB) || defined(RAK14014)
config.power.is_power_saving = true;
config.display.screen_on_secs = 30;
config.power.wait_bluetooth_secs = 30;
@@ -743,6 +743,15 @@ void NodeDB::installDefaultModuleConfig()
moduleConfig.external_notification.output_ms = 100;
moduleConfig.external_notification.active = true;
#endif
+#ifdef ELECROW_ThinkNode_M1
+ // Default to Elecrow USER_LED (blue)
+ moduleConfig.external_notification.enabled = true;
+ moduleConfig.external_notification.output = USER_LED;
+ moduleConfig.external_notification.active = true;
+ moduleConfig.external_notification.alert_message = true;
+ moduleConfig.external_notification.output_ms = 1000;
+ moduleConfig.external_notification.nag_timeout = 60;
+#endif
#ifdef BUTTON_SECONDARY_CANNEDMESSAGES
// Use a board's second built-in button as input source for canned messages
moduleConfig.canned_message.enabled = true;
diff --git a/src/mesh/RadioInterface.cpp b/src/mesh/RadioInterface.cpp
index 2e50c0168..86903153b 100644
--- a/src/mesh/RadioInterface.cpp
+++ b/src/mesh/RadioInterface.cpp
@@ -488,11 +488,6 @@ void RadioInterface::applyModemConfig()
cr = 8;
sf = 12;
break;
- case meshtastic_Config_LoRaConfig_ModemPreset_VERY_LONG_SLOW:
- bw = (myRegion->wideLora) ? 203.125 : 62.5;
- cr = 8;
- sf = 12;
- break;
}
} else {
sf = loraConfig.spread_factor;
diff --git a/src/mesh/Router.cpp b/src/mesh/Router.cpp
index b8b7ee610..2cc3007a2 100644
--- a/src/mesh/Router.cpp
+++ b/src/mesh/Router.cpp
@@ -283,11 +283,6 @@ ErrorCode Router::send(meshtastic_MeshPacket *p)
abortSendAndNak(encodeResult, p);
return encodeResult; // FIXME - this isn't a valid ErrorCode
}
-#if HAS_UDP_MULTICAST
- if (udpThread && config.network.enabled_protocols & meshtastic_Config_NetworkConfig_ProtocolFlags_UDP_BROADCAST) {
- udpThread->onSend(const_cast(p));
- }
-#endif
#if !MESHTASTIC_EXCLUDE_MQTT
// Only publish to MQTT if we're the original transmitter of the packet
if (moduleConfig.mqtt.enabled && isFromUs(p) && mqtt) {
@@ -297,6 +292,12 @@ ErrorCode Router::send(meshtastic_MeshPacket *p)
packetPool.release(p_decoded);
}
+#if HAS_UDP_MULTICAST
+ if (udpThread && config.network.enabled_protocols & meshtastic_Config_NetworkConfig_ProtocolFlags_UDP_BROADCAST) {
+ udpThread->onSend(const_cast(p));
+ }
+#endif
+
assert(iface); // This should have been detected already in sendLocal (or we just received a packet from outside)
return iface->send(p);
}
diff --git a/src/mesh/generated/meshtastic/config.pb.h b/src/mesh/generated/meshtastic/config.pb.h
index 848f8df86..edcd7b41c 100644
--- a/src/mesh/generated/meshtastic/config.pb.h
+++ b/src/mesh/generated/meshtastic/config.pb.h
@@ -180,14 +180,16 @@ typedef enum _meshtastic_Config_DisplayConfig_DisplayUnits {
/* Override OLED outo detect with this if it fails. */
typedef enum _meshtastic_Config_DisplayConfig_OledType {
- /* Default / Auto */
+ /* Default / Autodetect */
meshtastic_Config_DisplayConfig_OledType_OLED_AUTO = 0,
- /* Default / Auto */
+ /* Default / Autodetect */
meshtastic_Config_DisplayConfig_OledType_OLED_SSD1306 = 1,
- /* Default / Auto */
+ /* Default / Autodetect */
meshtastic_Config_DisplayConfig_OledType_OLED_SH1106 = 2,
/* Can not be auto detected but set by proto. Used for 128x128 screens */
- meshtastic_Config_DisplayConfig_OledType_OLED_SH1107 = 3
+ meshtastic_Config_DisplayConfig_OledType_OLED_SH1107 = 3,
+ /* Can not be auto detected but set by proto. Used for 128x64 screens */
+ meshtastic_Config_DisplayConfig_OledType_OLED_SH1107_128_64 = 4
} meshtastic_Config_DisplayConfig_OledType;
typedef enum _meshtastic_Config_DisplayConfig_DisplayMode {
@@ -639,8 +641,8 @@ extern "C" {
#define _meshtastic_Config_DisplayConfig_DisplayUnits_ARRAYSIZE ((meshtastic_Config_DisplayConfig_DisplayUnits)(meshtastic_Config_DisplayConfig_DisplayUnits_IMPERIAL+1))
#define _meshtastic_Config_DisplayConfig_OledType_MIN meshtastic_Config_DisplayConfig_OledType_OLED_AUTO
-#define _meshtastic_Config_DisplayConfig_OledType_MAX meshtastic_Config_DisplayConfig_OledType_OLED_SH1107
-#define _meshtastic_Config_DisplayConfig_OledType_ARRAYSIZE ((meshtastic_Config_DisplayConfig_OledType)(meshtastic_Config_DisplayConfig_OledType_OLED_SH1107+1))
+#define _meshtastic_Config_DisplayConfig_OledType_MAX meshtastic_Config_DisplayConfig_OledType_OLED_SH1107_128_64
+#define _meshtastic_Config_DisplayConfig_OledType_ARRAYSIZE ((meshtastic_Config_DisplayConfig_OledType)(meshtastic_Config_DisplayConfig_OledType_OLED_SH1107_128_64+1))
#define _meshtastic_Config_DisplayConfig_DisplayMode_MIN meshtastic_Config_DisplayConfig_DisplayMode_DEFAULT
#define _meshtastic_Config_DisplayConfig_DisplayMode_MAX meshtastic_Config_DisplayConfig_DisplayMode_COLOR
diff --git a/src/mesh/generated/meshtastic/mesh.pb.h b/src/mesh/generated/meshtastic/mesh.pb.h
index daee04f90..191f9e121 100644
--- a/src/mesh/generated/meshtastic/mesh.pb.h
+++ b/src/mesh/generated/meshtastic/mesh.pb.h
@@ -237,6 +237,8 @@ typedef enum _meshtastic_HardwareModel {
meshtastic_HardwareModel_T_ETH_ELITE = 91,
/* Heltec HRI-3621 industrial probe */
meshtastic_HardwareModel_HELTEC_SENSOR_HUB = 92,
+ /* Reserved Fried Chicken ID for future use */
+ meshtastic_HardwareModel_RESERVED_FRIED_CHICKEN = 93,
/* ------------------------------------------------------------------------------------------------------------------------------------------
Reserved ID For developing private Ports. These will show up in live traffic sparsely, so we can use a high number. Keep it within 8 bits.
------------------------------------------------------------------------------------------------------------------------------------------ */
@@ -326,7 +328,11 @@ typedef enum _meshtastic_ExcludedModules {
/* Detection Sensor module */
meshtastic_ExcludedModules_DETECTIONSENSOR_CONFIG = 2048,
/* Paxcounter module */
- meshtastic_ExcludedModules_PAXCOUNTER_CONFIG = 4096
+ meshtastic_ExcludedModules_PAXCOUNTER_CONFIG = 4096,
+ /* Bluetooth config (not technically a module, but used to indicate bluetooth capabilities) */
+ meshtastic_ExcludedModules_BLUETOOTH_CONFIG = 8192,
+ /* Network config (not technically a module, but used to indicate network capabilities) */
+ meshtastic_ExcludedModules_NETWORK_CONFIG = 16384
} meshtastic_ExcludedModules;
/* How the location was acquired: manual, onboard GPS, external (EUD) GPS */
@@ -1122,8 +1128,8 @@ extern "C" {
#define _meshtastic_CriticalErrorCode_ARRAYSIZE ((meshtastic_CriticalErrorCode)(meshtastic_CriticalErrorCode_FLASH_CORRUPTION_UNRECOVERABLE+1))
#define _meshtastic_ExcludedModules_MIN meshtastic_ExcludedModules_EXCLUDED_NONE
-#define _meshtastic_ExcludedModules_MAX meshtastic_ExcludedModules_PAXCOUNTER_CONFIG
-#define _meshtastic_ExcludedModules_ARRAYSIZE ((meshtastic_ExcludedModules)(meshtastic_ExcludedModules_PAXCOUNTER_CONFIG+1))
+#define _meshtastic_ExcludedModules_MAX meshtastic_ExcludedModules_NETWORK_CONFIG
+#define _meshtastic_ExcludedModules_ARRAYSIZE ((meshtastic_ExcludedModules)(meshtastic_ExcludedModules_NETWORK_CONFIG+1))
#define _meshtastic_Position_LocSource_MIN meshtastic_Position_LocSource_LOC_UNSET
#define _meshtastic_Position_LocSource_MAX meshtastic_Position_LocSource_LOC_EXTERNAL
diff --git a/src/mesh/generated/meshtastic/telemetry.pb.h b/src/mesh/generated/meshtastic/telemetry.pb.h
index 69cdd33fe..dcc511ea6 100644
--- a/src/mesh/generated/meshtastic/telemetry.pb.h
+++ b/src/mesh/generated/meshtastic/telemetry.pb.h
@@ -242,7 +242,7 @@ typedef struct _meshtastic_AirQualityMetrics {
/* 10.0um Particle Count */
bool has_particles_100um;
uint32_t particles_100um;
- /* 10.0um Particle Count */
+ /* CO2 concentration in ppm */
bool has_co2;
uint32_t co2;
} meshtastic_AirQualityMetrics;
diff --git a/src/mesh/mesh-pb-constants.h b/src/mesh/mesh-pb-constants.h
index 1c86653dc..f748d295e 100644
--- a/src/mesh/mesh-pb-constants.h
+++ b/src/mesh/mesh-pb-constants.h
@@ -18,6 +18,10 @@
#define MAX_RX_TOPHONE 32
#endif
+/// Verify baseline assumption of node size. If it increases, we need to reevaluate
+/// the impact of its memory footprint, notably on MAX_NUM_NODES.
+static_assert(sizeof(meshtastic_NodeInfoLite) <= 192, "NodeInfoLite size increased. Reconsider impact on MAX_NUM_NODES.");
+
/// max number of nodes allowed in the nodeDB
#ifndef MAX_NUM_NODES
#if defined(ARCH_STM32WL)
diff --git a/src/mesh/wifi/WiFiAPClient.cpp b/src/mesh/wifi/WiFiAPClient.cpp
index e050c2057..4d0b74f7c 100644
--- a/src/mesh/wifi/WiFiAPClient.cpp
+++ b/src/mesh/wifi/WiFiAPClient.cpp
@@ -163,7 +163,7 @@ static int32_t reconnectWiFi()
delay(5000);
if (!WiFi.isConnected()) {
-#ifdef ARCH_ESP32
+#ifdef CONFIG_IDF_TARGET_ESP32C3
WiFi.mode(WIFI_MODE_NULL);
WiFi.useStaticBuffers(true);
WiFi.mode(WIFI_STA);
diff --git a/src/modules/AdminModule.cpp b/src/modules/AdminModule.cpp
index c04c26a5a..88109bc78 100644
--- a/src/modules/AdminModule.cpp
+++ b/src/modules/AdminModule.cpp
@@ -265,7 +265,7 @@ bool AdminModule::handleReceivedProtobuf(const meshtastic_MeshPacket &mp, meshta
disableBluetooth();
LOG_INFO("Commit transaction for edited settings");
hasOpenEditTransaction = false;
- saveChanges(SEGMENT_CONFIG | SEGMENT_MODULECONFIG | SEGMENT_DEVICESTATE | SEGMENT_CHANNELS);
+ saveChanges(SEGMENT_CONFIG | SEGMENT_MODULECONFIG | SEGMENT_DEVICESTATE | SEGMENT_CHANNELS | SEGMENT_NODEDATABASE);
break;
}
case meshtastic_AdminMessage_get_device_connection_status_request_tag: {
@@ -334,7 +334,7 @@ bool AdminModule::handleReceivedProtobuf(const meshtastic_MeshPacket &mp, meshta
node->position = TypeConversions::ConvertToPositionLite(r->set_fixed_position);
nodeDB->setLocalPosition(r->set_fixed_position);
config.position.fixed_position = true;
- saveChanges(SEGMENT_DEVICESTATE | SEGMENT_NODEDATABASE | SEGMENT_CONFIG, false);
+ saveChanges(SEGMENT_NODEDATABASE | SEGMENT_CONFIG, false);
#if !MESHTASTIC_EXCLUDE_GPS
if (gps != nullptr)
gps->enable();
@@ -347,7 +347,7 @@ bool AdminModule::handleReceivedProtobuf(const meshtastic_MeshPacket &mp, meshta
LOG_INFO("Client received remove_fixed_position command");
nodeDB->clearLocalPosition();
config.position.fixed_position = false;
- saveChanges(SEGMENT_DEVICESTATE | SEGMENT_NODEDATABASE | SEGMENT_CONFIG, false);
+ saveChanges(SEGMENT_NODEDATABASE | SEGMENT_CONFIG, false);
break;
}
case meshtastic_AdminMessage_set_time_only_tag: {
@@ -574,7 +574,6 @@ void AdminModule::handleSetConfig(const meshtastic_Config &c)
config.has_position = true;
config.position = c.payload_variant.position;
// Save nodedb as well in case we got a fixed position packet
- saveChanges(SEGMENT_DEVICESTATE, false);
break;
case meshtastic_Config_power_tag:
LOG_INFO("Set config: Power");
diff --git a/src/modules/CannedMessageModule.cpp b/src/modules/CannedMessageModule.cpp
index 2a5ec00ab..c16c0e4b3 100644
--- a/src/modules/CannedMessageModule.cpp
+++ b/src/modules/CannedMessageModule.cpp
@@ -483,7 +483,7 @@ int32_t CannedMessageModule::runOnce()
#if defined(USE_VIRTUAL_KEYBOARD)
sendText(this->dest, indexChannels[this->channel], this->messages[this->currentMessageIndex], true);
#else
- sendText(NODENUM_BROADCAST, channels.getPrimaryIndex(), this->messages[this->currentMessageIndex], true);
+ sendText(this->dest, indexChannels[this->channel], this->messages[this->currentMessageIndex], true);
#endif
}
this->runState = CANNED_MESSAGE_RUN_STATE_SENDING_ACTIVE;
@@ -1114,20 +1114,19 @@ void CannedMessageModule::drawFrame(OLEDDisplay *display, OLEDDisplayUiState *st
display->drawStringf(0 + x, 0 + y, buffer, "To: %s", cannedMessageModule->getNodeName(this->dest));
int lines = (display->getHeight() / FONT_HEIGHT_SMALL) - 1;
if (lines == 3) {
- // static (old) behavior for small displays
- display->drawString(0 + x, 0 + y + FONT_HEIGHT_SMALL, cannedMessageModule->getPrevMessage());
display->fillRect(0 + x, 0 + y + FONT_HEIGHT_SMALL * 2, x + display->getWidth(), y + FONT_HEIGHT_SMALL);
display->setColor(BLACK);
display->drawString(0 + x, 0 + y + FONT_HEIGHT_SMALL * 2, cannedMessageModule->getCurrentMessage());
display->setColor(WHITE);
- display->drawString(0 + x, 0 + y + FONT_HEIGHT_SMALL * 3, cannedMessageModule->getNextMessage());
+ if (this->messagesCount > 1) {
+ display->drawString(0 + x, 0 + y + FONT_HEIGHT_SMALL, cannedMessageModule->getPrevMessage());
+ display->drawString(0 + x, 0 + y + FONT_HEIGHT_SMALL * 3, cannedMessageModule->getNextMessage());
+ }
} else {
- // use entire display height for larger displays
int topMsg = (messagesCount > lines && currentMessageIndex >= lines - 1) ? currentMessageIndex - lines + 2 : 0;
for (int i = 0; i < std::min(messagesCount, lines); i++) {
if (i == currentMessageIndex - topMsg) {
#ifdef USE_EINK
- // Avoid drawing solid black with fillRect: harder to clear for E-Ink
display->drawString(0 + x, 0 + y + FONT_HEIGHT_SMALL * (i + 1), ">");
display->drawString(12 + x, 0 + y + FONT_HEIGHT_SMALL * (i + 1),
cannedMessageModule->getCurrentMessage());
@@ -1138,7 +1137,7 @@ void CannedMessageModule::drawFrame(OLEDDisplay *display, OLEDDisplayUiState *st
display->drawString(0 + x, 0 + y + FONT_HEIGHT_SMALL * (i + 1), cannedMessageModule->getCurrentMessage());
display->setColor(WHITE);
#endif
- } else {
+ } else if (messagesCount > 1) { // Only draw others if there are multiple messages
display->drawString(0 + x, 0 + y + FONT_HEIGHT_SMALL * (i + 1),
cannedMessageModule->getMessageByIndex(topMsg + i));
}
diff --git a/src/modules/ExternalNotificationModule.cpp b/src/modules/ExternalNotificationModule.cpp
index bbb3f90e0..dc17460f6 100644
--- a/src/modules/ExternalNotificationModule.cpp
+++ b/src/modules/ExternalNotificationModule.cpp
@@ -28,6 +28,10 @@
#include
#endif
+#ifdef HAS_LP5562
+#include
+#endif
+
#ifdef HAS_NEOPIXEL
#include
#endif
@@ -37,10 +41,11 @@
extern unPhone unphone;
#endif
-#if defined(HAS_NCP5623) || defined(RGBLED_RED) || defined(HAS_NEOPIXEL) || defined(UNPHONE)
+#if defined(HAS_RGB_LED)
uint8_t red = 0;
uint8_t green = 0;
uint8_t blue = 0;
+uint8_t white = 0;
uint8_t colorState = 1;
uint8_t brightnessIndex = 0;
uint8_t brightnessValues[] = {0, 10, 20, 30, 50, 90, 160, 170}; // blue gets multiplied by 1.5
@@ -128,15 +133,21 @@ int32_t ExternalNotificationModule::runOnce()
millis());
setExternalState(2, !getExternal(2));
}
-#if defined(HAS_NCP5623) || defined(RGBLED_RED) || defined(HAS_NEOPIXEL) || defined(UNPHONE)
+#if defined(HAS_RGB_LED)
red = (colorState & 4) ? brightnessValues[brightnessIndex] : 0; // Red enabled on colorState = 4,5,6,7
green = (colorState & 2) ? brightnessValues[brightnessIndex] : 0; // Green enabled on colorState = 2,3,6,7
blue = (colorState & 1) ? (brightnessValues[brightnessIndex] * 1.5) : 0; // Blue enabled on colorState = 1,3,5,7
+ white = (colorState & 12) ? brightnessValues[brightnessIndex] : 0;
#ifdef HAS_NCP5623
if (rgb_found.type == ScanI2C::NCP5623) {
rgb.setColor(red, green, blue);
}
#endif
+#ifdef HAS_LP5562
+ if (rgb_found.type == ScanI2C::LP5562) {
+ rgbw.setColor(red, green, blue, white);
+ }
+#endif
#ifdef RGBLED_CA
analogWrite(RGBLED_RED, 255 - red); // CA type needs reverse logic
analogWrite(RGBLED_GREEN, 255 - green);
@@ -233,11 +244,12 @@ void ExternalNotificationModule::setExternalState(uint8_t index, bool on)
break;
}
-#if defined(HAS_NCP5623) || defined(RGBLED_RED) || defined(HAS_NEOPIXEL) || defined(UNPHONE)
+#if defined(HAS_RGB_LED)
if (!on) {
red = 0;
green = 0;
blue = 0;
+ white = 0;
}
#endif
@@ -246,6 +258,11 @@ void ExternalNotificationModule::setExternalState(uint8_t index, bool on)
rgb.setColor(red, green, blue);
}
#endif
+#ifdef HAS_LP5562
+ if (rgb_found.type == ScanI2C::LP5562) {
+ rgbw.setColor(red, green, blue, white);
+ }
+#endif
#ifdef RGBLED_CA
analogWrite(RGBLED_RED, 255 - red); // CA type needs reverse logic
analogWrite(RGBLED_GREEN, 255 - green);
@@ -365,6 +382,12 @@ ExternalNotificationModule::ExternalNotificationModule()
rgb.setCurrent(10);
}
#endif
+#ifdef HAS_LP5562
+ if (rgb_found.type == ScanI2C::LP5562) {
+ rgbw.begin();
+ rgbw.setCurrent(20);
+ }
+#endif
#ifdef RGBLED_RED
pinMode(RGBLED_RED, OUTPUT); // set up the RGB led pins
pinMode(RGBLED_GREEN, OUTPUT);
diff --git a/src/modules/GenericThreadModule.cpp b/src/modules/GenericThreadModule.cpp
new file mode 100644
index 000000000..eb92566bd
--- /dev/null
+++ b/src/modules/GenericThreadModule.cpp
@@ -0,0 +1,28 @@
+#include "GenericThreadModule.h"
+#include "MeshService.h"
+#include "configuration.h"
+#include
+
+/*
+Generic Thread Module allows for the execution of custom code at a set interval.
+*/
+GenericThreadModule *genericThreadModule;
+
+GenericThreadModule::GenericThreadModule() : concurrency::OSThread("GenericThreadModule") {}
+
+int32_t GenericThreadModule::runOnce()
+{
+
+ bool enabled = true;
+ if (!enabled)
+ return disable();
+
+ if (firstTime) {
+ // do something the first time we run
+ firstTime = 0;
+ LOG_INFO("first time GenericThread running");
+ }
+
+ LOG_INFO("GenericThread executing");
+ return (my_interval);
+}
diff --git a/src/modules/GenericThreadModule.h b/src/modules/GenericThreadModule.h
new file mode 100644
index 000000000..05f7946bb
--- /dev/null
+++ b/src/modules/GenericThreadModule.h
@@ -0,0 +1,21 @@
+#pragma once
+
+#include "MeshModule.h"
+#include "concurrency/OSThread.h"
+#include "configuration.h"
+#include
+#include
+
+class GenericThreadModule : private concurrency::OSThread
+{
+ bool firstTime = 1;
+
+ public:
+ GenericThreadModule();
+
+ protected:
+ unsigned int my_interval = 10000; // interval in millisconds
+ virtual int32_t runOnce() override;
+};
+
+extern GenericThreadModule *genericThreadModule;
diff --git a/src/modules/Modules.cpp b/src/modules/Modules.cpp
index e2a4a970c..1f2b50057 100644
--- a/src/modules/Modules.cpp
+++ b/src/modules/Modules.cpp
@@ -65,6 +65,10 @@
#if HAS_TELEMETRY && !MESHTASTIC_EXCLUDE_POWER_TELEMETRY
#include "modules/Telemetry/PowerTelemetry.h"
#endif
+#if !MESHTASTIC_EXCLUDE_GENERIC_THREAD_MODULE
+#include "modules/GenericThreadModule.h"
+#endif
+
#ifdef ARCH_ESP32
#if defined(USE_SX1280) && !MESHTASTIC_EXCLUDE_AUDIO
#include "modules/esp32/AudioModule.h"
@@ -131,6 +135,9 @@ void setupModules()
#if !MESHTASTIC_EXCLUDE_DROPZONE
dropzoneModule = new DropzoneModule();
+#endif
+#if !MESHTASTIC_EXCLUDE_GENERIC_THREAD_MODULE
+ new GenericThreadModule();
#endif
// Note: if the rest of meshtastic doesn't need to explicitly use your module, you do not need to assign the instance
// to a global variable.
@@ -249,4 +256,4 @@ void setupModules()
// NOTE! This module must be added LAST because it likes to check for replies from other modules and avoid sending extra
// acks
routingModule = new RoutingModule();
-}
\ No newline at end of file
+}
diff --git a/src/modules/SerialModule.cpp b/src/modules/SerialModule.cpp
index f3f23b080..e088b4612 100644
--- a/src/modules/SerialModule.cpp
+++ b/src/modules/SerialModule.cpp
@@ -408,6 +408,49 @@ uint32_t SerialModule::getBaudRate()
return BAUD;
}
+// Add this structure to help with parsing WindGust = 24.4 serial lines.
+struct ParsedLine {
+ String name;
+ String value;
+};
+
+/**
+ * Parse a line of format "Name = Value" into name/value pair
+ * @param line Input line to parse
+ * @return ParsedLine containing name and value, or empty strings if parse failed
+ */
+ParsedLine parseLine(const char *line)
+{
+ ParsedLine result = {"", ""};
+
+ // Find equals sign
+ const char *equals = strchr(line, '=');
+ if (!equals) {
+ return result;
+ }
+
+ // Extract name by copying substring
+ char nameBuf[64]; // Temporary buffer
+ size_t nameLen = equals - line;
+ if (nameLen >= sizeof(nameBuf)) {
+ nameLen = sizeof(nameBuf) - 1;
+ }
+ strncpy(nameBuf, line, nameLen);
+ nameBuf[nameLen] = '\0';
+
+ // Create trimmed name string
+ String name = String(nameBuf);
+ name.trim();
+
+ // Extract value after equals sign
+ String value = String(equals + 1);
+ value.trim();
+
+ result.name = name;
+ result.value = value;
+ return result;
+}
+
/**
* Process the received weather station serial data, extract wind, voltage, and temperature information,
* calculate averages and send telemetry data over the mesh network.
@@ -453,6 +496,7 @@ void SerialModule::processWXSerial()
// WindSpeed = 0.5
// WindGust = 0.6
// GXTS04Temp = 24.4
+ // Temperature = 23.4 // WS80
// RainIntSum = 0
// Rain = 0.0
@@ -471,75 +515,48 @@ void SerialModule::processWXSerial()
memset(line, '\0', sizeof(line));
if (lineEnd - lineStart < sizeof(line) - 1) {
memcpy(line, &serialBytes[lineStart], lineEnd - lineStart);
- if (strstr(line, "Wind") != NULL) // we have a wind line
- {
- gotwind = true;
- // Find the positions of "=" signs in the line
- char *windDirPos = strstr(line, "WindDir = ");
- char *windSpeedPos = strstr(line, "WindSpeed = ");
- char *windGustPos = strstr(line, "WindGust = ");
- if (windDirPos != NULL) {
- // Extract data after "=" for WindDir
- strlcpy(windDir, windDirPos + 15, sizeof(windDir)); // Add 15 to skip "WindDir = "
+ ParsedLine parsed = parseLine(line);
+ if (parsed.name.length() > 0) {
+ if (parsed.name == "WindDir") {
+ strlcpy(windDir, parsed.value.c_str(), sizeof(windDir));
double radians = GeoCoord::toRadians(strtof(windDir, nullptr));
dir_sum_sin += sin(radians);
dir_sum_cos += cos(radians);
dirCount++;
- } else if (windSpeedPos != NULL) {
- // Extract data after "=" for WindSpeed
- strlcpy(windVel, windSpeedPos + 15, sizeof(windVel)); // Add 15 to skip "WindSpeed = "
+ gotwind = true;
+ } else if (parsed.name == "WindSpeed") {
+ strlcpy(windVel, parsed.value.c_str(), sizeof(windVel));
float newv = strtof(windVel, nullptr);
velSum += newv;
velCount++;
- if (newv < lull || lull == -1)
+ if (newv < lull || lull == -1) {
lull = newv;
-
- } else if (windGustPos != NULL) {
- strlcpy(windGust, windGustPos + 15, sizeof(windGust)); // Add 15 to skip "WindSpeed = "
+ }
+ gotwind = true;
+ } else if (parsed.name == "WindGust") {
+ strlcpy(windGust, parsed.value.c_str(), sizeof(windGust));
float newg = strtof(windGust, nullptr);
- if (newg > gust)
+ if (newg > gust) {
gust = newg;
- }
-
- // these are also voltage data we care about possibly
- } else if (strstr(line, "BatVoltage") != NULL) { // we have a battVoltage line
- char *batVoltagePos = strstr(line, "BatVoltage = ");
- if (batVoltagePos != NULL) {
- strlcpy(batVoltage, batVoltagePos + 17, sizeof(batVoltage)); // 18 for ws 80, 17 for ws85
+ }
+ gotwind = true;
+ } else if (parsed.name == "BatVoltage") {
+ strlcpy(batVoltage, parsed.value.c_str(), sizeof(batVoltage));
batVoltageF = strtof(batVoltage, nullptr);
break; // last possible data we want so break
- }
- } else if (strstr(line, "CapVoltage") != NULL) { // we have a cappVoltage line
- char *capVoltagePos = strstr(line, "CapVoltage = ");
- if (capVoltagePos != NULL) {
- strlcpy(capVoltage, capVoltagePos + 17, sizeof(capVoltage)); // 18 for ws 80, 17 for ws85
+ } else if (parsed.name == "CapVoltage") {
+ strlcpy(capVoltage, parsed.value.c_str(), sizeof(capVoltage));
capVoltageF = strtof(capVoltage, nullptr);
- }
- // GXTS04Temp = 24.4
- } else if (strstr(line, "GXTS04Temp") != NULL) { // we have a temperature line
- char *tempPos = strstr(line, "GXTS04Temp = ");
- if (tempPos != NULL) {
- strlcpy(temperature, tempPos + 15, sizeof(temperature)); // 15 spaces for ws85
+ } else if (parsed.name == "GXTS04Temp" || parsed.name == "Temperature") {
+ strlcpy(temperature, parsed.value.c_str(), sizeof(temperature));
temperatureF = strtof(temperature, nullptr);
- }
-
- } else if (strstr(line, "RainIntSum") != NULL) { // we have a rainsum line
- // LOG_INFO(line);
- char *pos = strstr(line, "RainIntSum = ");
- if (pos != NULL) {
- strlcpy(rainStr, pos + 17, sizeof(rainStr)); // 17 spaces for ws85
+ } else if (parsed.name == "RainIntSum") {
+ strlcpy(rainStr, parsed.value.c_str(), sizeof(rainStr));
rainSum = int(strtof(rainStr, nullptr));
- }
-
- } else if (strstr(line, "Rain") != NULL) { // we have a rain line
- if (strstr(line, "WaveRain") == NULL) { // skip WaveRain lines though.
- // LOG_INFO(line);
- char *pos = strstr(line, "Rain = ");
- if (pos != NULL) {
- strlcpy(rainStr, pos + 17, sizeof(rainStr)); // 17 spaces for ws85
- rain = strtof(rainStr, nullptr);
- }
+ } else if (parsed.name == "Rain") {
+ strlcpy(rainStr, parsed.value.c_str(), sizeof(rainStr));
+ rain = strtof(rainStr, nullptr);
}
}
@@ -557,7 +574,7 @@ void SerialModule::processWXSerial()
}
if (gotwind) {
- LOG_INFO("WS85 : %i %.1fg%.1f %.1fv %.1fv %.1fC rain: %.1f, %i sum", atoi(windDir), strtof(windVel, nullptr),
+ LOG_INFO("WS8X : %i %.1fg%.1f %.1fv %.1fv %.1fC rain: %.1f, %i sum", atoi(windDir), strtof(windVel, nullptr),
strtof(windGust, nullptr), batVoltageF, capVoltageF, temperatureF, rain, rainSum);
}
if (gotwind && !Throttle::isWithinTimespanMs(lastAveraged, averageIntervalMillis)) {
@@ -607,7 +624,7 @@ void SerialModule::processWXSerial()
m.variant.environment_metrics.wind_lull = lull;
m.variant.environment_metrics.has_wind_lull = true;
- LOG_INFO("WS85 Transmit speed=%fm/s, direction=%d , lull=%f, gust=%f, voltage=%f temperature=%f",
+ LOG_INFO("WS8X Transmit speed=%fm/s, direction=%d , lull=%f, gust=%f, voltage=%f temperature=%f",
m.variant.environment_metrics.wind_speed, m.variant.environment_metrics.wind_direction,
m.variant.environment_metrics.wind_lull, m.variant.environment_metrics.wind_gust,
m.variant.environment_metrics.voltage, m.variant.environment_metrics.temperature);
diff --git a/src/platform/esp32/main-esp32.cpp b/src/platform/esp32/main-esp32.cpp
index ab1e5c922..3c4faac3e 100644
--- a/src/platform/esp32/main-esp32.cpp
+++ b/src/platform/esp32/main-esp32.cpp
@@ -109,9 +109,8 @@ void esp32Setup()
randomSeed(seed);
*/
-#ifdef POWER_FULL
- pinMode(POWER_FULL, INPUT);
- pinMode(7, INPUT);
+#ifdef ADC_V
+ pinMode(ADC_V, INPUT);
#endif
LOG_DEBUG("Total heap: %d", ESP.getHeapSize());
diff --git a/src/platform/nrf52/main-nrf52.cpp b/src/platform/nrf52/main-nrf52.cpp
index 53971e95a..9accd2a02 100644
--- a/src/platform/nrf52/main-nrf52.cpp
+++ b/src/platform/nrf52/main-nrf52.cpp
@@ -235,10 +235,6 @@ void nrf52InitSemiHosting()
void nrf52Setup()
{
-#ifdef USB_CHECK
- pinMode(USB_CHECK, INPUT);
-#endif
-
#ifdef ADC_V
pinMode(ADC_V, INPUT);
#endif
@@ -288,7 +284,7 @@ void cpuDeepSleep(uint32_t msecToWake)
#endif
// This may cause crashes as debug messages continue to flow.
Serial.end();
-#ifdef PIN_SERIAL_RX1
+#ifdef PIN_SERIAL1_RX
Serial1.end();
#endif
setBluetoothEnable(false);
diff --git a/src/platform/portduino/PortduinoGlue.cpp b/src/platform/portduino/PortduinoGlue.cpp
index 7b13971b4..6d0972dc3 100644
--- a/src/platform/portduino/PortduinoGlue.cpp
+++ b/src/platform/portduino/PortduinoGlue.cpp
@@ -33,6 +33,7 @@ std::ofstream traceFile;
Ch341Hal *ch341Hal = nullptr;
char *configPath = nullptr;
char *optionMac = nullptr;
+bool forceSimulated = false;
// FIXME - move setBluetoothEnable into a HALPlatform class
void setBluetoothEnable(bool enable)
@@ -61,6 +62,9 @@ static error_t parse_opt(int key, char *arg, struct argp_state *state)
case 'c':
configPath = arg;
break;
+ case 's':
+ forceSimulated = true;
+ break;
case 'h':
optionMac = arg;
break;
@@ -78,6 +82,7 @@ void portduinoCustomInit()
static struct argp_option options[] = {{"port", 'p', "PORT", 0, "The TCP port to use."},
{"config", 'c', "CONFIG_PATH", 0, "Full path of the .yaml config file to use."},
{"hwid", 'h', "HWID", 0, "The mac address to assign to this virtual machine"},
+ {"sim", 's', 0, 0, "Run in Simulated radio mode"},
{0}};
static void *childArguments;
static char doc[] = "Meshtastic native build.";
@@ -157,7 +162,9 @@ void portduinoSetup()
YAML::Node yamlConfig;
- if (configPath != nullptr) {
+ if (forceSimulated == true) {
+ settingsMap[use_simradio] = true;
+ } else if (configPath != nullptr) {
if (loadConfig(configPath)) {
std::cout << "Using " << configPath << " as config file" << std::endl;
} else {
@@ -179,7 +186,12 @@ void portduinoSetup()
exit(EXIT_FAILURE);
}
} else {
- std::cout << "No 'config.yaml' found, running simulated." << std::endl;
+ std::cout << "No 'config.yaml' found..." << std::endl;
+ settingsMap[use_simradio] = true;
+ }
+
+ if (settingsMap[use_simradio] == true) {
+ std::cout << "Running in simulated mode." << std::endl;
settingsMap[maxnodes] = 200; // Default to 200 nodes
settingsMap[logoutputlevel] = level_debug; // Default to debug
// Set the random seed equal to TCPPort to have a different seed per instance
@@ -197,6 +209,56 @@ void portduinoSetup()
}
}
}
+
+ // If LoRa `Module: auto` (default in config.yaml),
+ // attempt to auto config based on Product Strings
+ if (settingsMap[use_autoconf] == true) {
+ char autoconf_product[96] = {0};
+ // Try CH341
+ try {
+ std::cout << "autoconf: Looking for CH341 device..." << std::endl;
+ ch341Hal =
+ new Ch341Hal(0, settingsStrings[lora_usb_serial_num], settingsMap[lora_usb_vid], settingsMap[lora_usb_pid]);
+ ch341Hal->getProductString(autoconf_product, 95);
+ delete ch341Hal;
+ std::cout << "autoconf: Found CH341 device " << autoconf_product << std::endl;
+ } catch (...) {
+ std::cout << "autoconf: Could not locate CH341 device" << std::endl;
+ }
+ // Try Pi HAT+
+ std::cout << "autoconf: Looking for Pi HAT+..." << std::endl;
+ if (access("/proc/device-tree/hat/product", R_OK) == 0) {
+ std::ifstream hatProductFile("/proc/device-tree/hat/product");
+ if (hatProductFile.is_open()) {
+ hatProductFile.read(autoconf_product, 95);
+ hatProductFile.close();
+ }
+ std::cout << "autoconf: Found Pi HAT+ " << autoconf_product << " at /proc/device-tree/hat/product" << std::endl;
+ } else {
+ std::cout << "autoconf: Could not locate Pi HAT+ at /proc/device-tree/hat/product" << std::endl;
+ }
+ // Load the config file based on the product string
+ if (strlen(autoconf_product) > 0) {
+ // From configProducts map in PortduinoGlue.h
+ std::string product_config = "";
+ try {
+ product_config = configProducts.at(autoconf_product);
+ } catch (std::out_of_range &e) {
+ std::cerr << "autoconf: Unable to find config for " << autoconf_product << std::endl;
+ exit(EXIT_FAILURE);
+ }
+ if (loadConfig((settingsStrings[available_directory] + product_config).c_str())) {
+ std::cout << "autoconf: Using " << product_config << " as config file for " << autoconf_product << std::endl;
+ } else {
+ std::cerr << "autoconf: Unable to use " << product_config << " as config file for " << autoconf_product
+ << std::endl;
+ exit(EXIT_FAILURE);
+ }
+ } else {
+ std::cerr << "autoconf: Could not locate any devices" << std::endl;
+ }
+ }
+
// if we're using a usermode driver, we need to initialize it here, to get a serial number back for mac address
uint8_t dmac[6] = {0};
if (settingsStrings[spidev] == "ch341") {
@@ -358,8 +420,9 @@ bool loadConfig(const char *configPath)
const struct {
configNames cfgName;
std::string strName;
- } loraModules[] = {{use_rf95, "RF95"}, {use_sx1262, "sx1262"}, {use_sx1268, "sx1268"}, {use_sx1280, "sx1280"},
- {use_lr1110, "lr1110"}, {use_lr1120, "lr1120"}, {use_lr1121, "lr1121"}, {use_llcc68, "LLCC68"}};
+ } loraModules[] = {{use_simradio, "sim"}, {use_autoconf, "auto"}, {use_rf95, "RF95"}, {use_sx1262, "sx1262"},
+ {use_sx1268, "sx1268"}, {use_sx1280, "sx1280"}, {use_lr1110, "lr1110"}, {use_lr1120, "lr1120"},
+ {use_lr1121, "lr1121"}, {use_llcc68, "LLCC68"}};
for (auto &loraModule : loraModules) {
settingsMap[loraModule.cfgName] = false;
}
@@ -539,6 +602,8 @@ bool loadConfig(const char *configPath)
settingsMap[maxnodes] = (yamlConfig["General"]["MaxNodes"]).as(200);
settingsMap[maxtophone] = (yamlConfig["General"]["MaxMessageQueue"]).as(100);
settingsStrings[config_directory] = (yamlConfig["General"]["ConfigDirectory"]).as("");
+ settingsStrings[available_directory] =
+ (yamlConfig["General"]["AvailableDirectory"]).as("/etc/meshtasticd/available.d/");
if ((yamlConfig["General"]["MACAddress"]).as("") != "" &&
(yamlConfig["General"]["MACAddressSource"]).as("") != "") {
std::cout << "Cannot set both MACAddress and MACAddressSource!" << std::endl;
diff --git a/src/platform/portduino/PortduinoGlue.h b/src/platform/portduino/PortduinoGlue.h
index a52ca88f8..f7239cb73 100644
--- a/src/platform/portduino/PortduinoGlue.h
+++ b/src/platform/portduino/PortduinoGlue.h
@@ -1,9 +1,19 @@
#pragma once
#include
#include