Compare commits

..
Author SHA1 Message Date
Thomas GöttgensandGitHub 82a66f2d70 Merge branch 'develop' into zps-module 2026-06-07 10:08:31 +02:00
Thomas Göttgens d98bc0b4ee fix(zps): build against bundled NimBLE host stack after pioarduino migration 2026-06-03 14:48:34 +02:00
Thomas Göttgens 5e6dc43a59 Merge branch 'zps-module' of https://github.com/meshtastic/firmware into zps-module 2026-06-03 12:34:11 +02:00
Thomas GöttgensandGitHub 110bb1b858 Merge branch 'develop' into zps-module 2026-06-03 12:32:39 +02:00
Thomas Göttgens cc1eeb7eb9 Merge branch 'zps-module' of https://github.com/meshtastic/firmware into zps-module 2026-04-12 18:01:43 +02:00
Thomas GöttgensandGitHub 8b9e06b05f Merge branch 'develop' into zps-module 2026-04-12 17:19:30 +02:00
Thomas Göttgens feed29eaf5 Merge branch 'zps-module' of https://github.com/meshtastic/firmware into zps-module 2026-02-04 14:04:41 +01:00
Thomas GöttgensandGitHub b0060b61fe Merge branch 'develop' into zps-module 2026-02-04 14:03:29 +01:00
Thomas Göttgens c0a1b2058b Merge branch 'zps-module' of https://github.com/meshtastic/firmware into zps-module 2026-02-04 14:02:14 +01:00
Thomas GöttgensandTom Fifield a7435b85a1 trunk fmt 2025-08-28 13:50:22 +10:00
Thomas GöttgensandTom Fifield 729d6c576f everyone's a critic, especially copilot. 2025-08-28 13:50:22 +10:00
Thomas GöttgensandTom Fifield 15b84fca01 Fix compile and check issues 2025-08-28 13:50:22 +10:00
Thomas GöttgensandTom Fifield 285b30dff0 the original ZPS module from https://github.com/a-f-G-U-C/Meshtastic-ZPS - work in progress, adapted to 2.x firmware convention, disabled by default 2025-08-28 13:50:22 +10:00
Thomas Göttgens 0258057adf trunk fmt 2025-08-19 17:44:25 +02:00
Thomas Göttgens aeb14a697d everyone's a critic, especially copilot. 2025-08-19 15:52:27 +02:00
Thomas Göttgens b546de1661 Fix compile and check issues 2025-08-19 14:47:14 +02:00
Thomas Göttgens f65a708148 Merge branch 'zps-module' of https://github.com/meshtastic/firmware into zps-module 2025-08-19 13:13:26 +02:00
Thomas Göttgens 5c874945fa the original ZPS module from https://github.com/a-f-G-U-C/Meshtastic-ZPS - work in progress, adapted to 2.x firmware convention, disabled by default 2025-08-19 13:12:31 +02:00
Thomas Göttgens 493742308a the original ZPS module from https://github.com/a-f-G-U-C/Meshtastic-ZPS - work in progress, adapted to 2.x firmware convention, disabled by default 2025-08-17 13:40:53 +02:00
48 changed files with 885 additions and 1110 deletions
-16
View File
@@ -1,16 +0,0 @@
{
"hooks": {
"PostToolUse": [
{
"matcher": "Write|Edit",
"hooks": [
{
"type": "command",
"command": "python3 -c \"import json,sys,subprocess,shutil,os; f=json.load(sys.stdin).get('tool_input',{}).get('file_path',''); t=shutil.which('trunk') or os.path.expanduser('~/.cache/trunk/launcher/trunk'); f and os.path.exists(t) and subprocess.run([t,'fmt','--force',f],stderr=subprocess.DEVNULL)\" 2>/dev/null || true",
"statusMessage": "Formatting..."
}
]
}
]
}
}
+4 -9
View File
@@ -16,18 +16,13 @@ jobs:
submodules: true
- name: Update submodule
if: ${{ github.ref_name == 'master' || github.ref_name == 'develop' }}
working-directory: protobufs
env:
# Use the branch that triggered the workflow as the protobuf branch.
GIT_BRANCH: ${{ github.ref_name }}
if: ${{ github.ref == 'refs/heads/master' || github.ref == 'refs/heads/develop' }}
run: |
git fetch --prune origin $GIT_BRANCH
git checkout origin/$GIT_BRANCH
git submodule update --remote protobufs
- name: Download nanopb
run: |
wget https://github.com/nanopb/nanopb/releases/download/nanopb-0.4.9.1/nanopb-0.4.9.1-linux-x86.tar.gz
wget https://jpa.kapsi.fi/nanopb/download/nanopb-0.4.9.1-linux-x86.tar.gz
tar xvzf nanopb-0.4.9.1-linux-x86.tar.gz
mv nanopb-0.4.9.1-linux-x86 nanopb-0.4.9
@@ -38,7 +33,7 @@ jobs:
- name: Create pull request
uses: peter-evans/create-pull-request@v8
with:
branch: create-pull-request/update-protobufs-${{ github.ref_name }}
branch: create-pull-request/update-protobufs
labels: submodules
title: Update protobufs and classes
commit-message: Update protobufs
-138
View File
@@ -1,138 +0,0 @@
#!/usr/bin/env python3
# trunk-ignore-all(ruff/F821)
# trunk-ignore-all(flake8/F821)
#
# Whole-image LTO for nrf52840 (~-60KB; ~-23KB beyond src-only LTO), EXCEPT the objects
# that own interrupt/exception handlers.
#
# Every ISR is referenced only from the assembly vector table (gcc_startup_nrf52840.S),
# which LTO cannot see -> whole-program LTO judges the handlers dead, removes them, and
# the weak `b .` Default_Handler stubs prevail -> the IRQ lands in an infinite loop and the
# chip hangs (or the peripheral silently stalls). Compiling the handler-bearing objects
# WITHOUT LTO lets ordinary linking keep the strong handlers; everything else stays LTO'd:
# - framework core (/FrameworkArduino/, /cores/nRF5/): every nrfx ISR + the FreeRTOS
# SVC/PendSV port.
# - TinyUSB nrf port (Adafruit_TinyUSB_nrf.cpp): USBD_IRQHandler (USB data path).
# - library .cpp files that own a vector ISR (would otherwise be silently dropped):
# bluefruit.cpp -> SD_EVT/SWI2_EGU2 (SoftDevice BLE-event delivery -- advertising
# hangs without it)
# Wire_nRF52.cpp -> SPIM0/TWIM0 + SPIM1/TWIM1 (interrupt-driven I2C/SPI)
# PDM.cpp -> PDM_IRQHandler (PDM microphone)
# RotaryEncoder.cpp -> QDEC_IRQHandler (hardware quadrature/rotary encoder)
#
# A post-link guard (bottom of this file) fails the build if a critical handler was dropped
# anyway -- so a future deps bump or a new ISR-owning library becomes a red build, not a field
# hang. To hunt a dropped ISR by hand: nm the .elf for `_IRQHandler$` symbols marked `W`, then
# grep the libs/framework for who defines them.
#
# HW-validated: RAK4631 (SX1262) + muzi-base (LR1121).
import glob
import os
Import("env")
env.Append(LINKFLAGS=["-flto", "-flto-partition=1to1"])
# The -fno-lto re-compiles below run with the global env, which lacks the framework's
# bundled-library include dirs -- and those libs cross-include each other (Wire pulls in
# Adafruit_TinyUSB.h, which pulls in SPI.h, ...). Add every bundled-lib dir (+ its src/) so
# the re-compiles resolve without chasing headers one at a time.
_fw = env.PioPlatform().get_package_dir("framework-arduinoadafruitnrf52") or ""
_extra_inc = []
for _d in sorted(glob.glob(os.path.join(_fw, "libraries", "*"))):
if os.path.isdir(_d):
_extra_inc.append(_d)
if os.path.isdir(os.path.join(_d, "src")):
_extra_inc.append(os.path.join(_d, "src"))
FRAMEWORK = ("/FrameworkArduino/", "/cores/nRF5/")
USB_ISR = "Adafruit_TinyUSB_nrf" # USBD_IRQHandler
# Library .cpp files that define vector-table ISRs (the rest of their lib stays LTO'd):
LIB_ISR = ("/bluefruit.cpp", "/Wire_nRF52.cpp", "/PDM.cpp", "/RotaryEncoder.cpp")
def _no_lto(node):
try:
path = node.get_abspath()
except Exception:
path = str(node)
path = path.replace(
"\\", "/"
) # normalize Windows backslashes so matches work cross-platform
if (
USB_ISR in path
or any(s in path for s in FRAMEWORK)
or any(s in path for s in LIB_ISR)
):
return env.Object(
node,
CCFLAGS=env["CCFLAGS"] + ["-fno-lto"],
CPPPATH=env["CPPPATH"] + _extra_inc,
)
return node
env.AddBuildMiddleware(_no_lto)
# --- post-link guard: catch a dropped ISR handler at build time (CI footgun protection) ----
# After every link, fail the build if one of these critical vector-table handlers resolved to
# the weak `b .` Default_Handler stub -- i.e. LTO (or a deps bump, or a new ISR-owning library
# that nobody added to LIB_ISR) silently dropped it. A dropped handler hangs the chip the
# instant that IRQ fires; this turns a field hang into a red build. CI builds every nrf52840
# target, so this runs on every PR automatically. All five are used by every nrf52840
# Meshtastic build; if a board deliberately stops using one, edit this tuple on purpose.
_REQUIRED_STRONG = (
"SWI2_EGU2_IRQHandler", # SoftDevice BLE event (SD_EVT) -- advertising & connections
"GPIOTE_IRQHandler", # GPIO interrupts: radio DIO + buttons
"RTC1_IRQHandler", # FreeRTOS scheduler tick
"USBD_IRQHandler", # USB CDC (serial console + 1200bps DFU trigger)
"POWER_CLOCK_IRQHandler", # HF/LF clock + power (HFCLK start for radio & SoftDevice)
)
_tc = env.PioPlatform().get_package_dir("toolchain-gccarmnoneeabi") or ""
_NM = os.path.join(_tc, "bin", "arm-none-eabi-nm")
if not os.path.isfile(_NM):
_NM = "arm-none-eabi-nm" # fall back to PATH
def _assert_isr_handlers_survived(source, target, env):
import subprocess
import sys
try:
# Resolve the ELF at build time; target[0] is the buildprog alias, not the file.
elf = env.subst("$BUILD_DIR/${PROGNAME}.elf")
out = subprocess.check_output([_NM, elf], universal_newlines=True)
except Exception as exc: # tooling hiccup: warn loudly, don't wedge the build
print("nrf52_lto: WARNING - ISR-handler guard skipped (nm failed: %s)" % exc)
return
# nm line: "<addr> <type> <symbol>". type 'T'/'t' = strong (good); 'W'/'w' = weak stub.
kind = {}
for line in out.split("\n"):
f = line.split()
if len(f) >= 3 and f[-1].endswith("_IRQHandler"):
kind[f[-1]] = f[-2]
dropped = [h for h in _REQUIRED_STRONG if kind.get(h, "W").upper() != "T"]
if dropped:
sys.stderr.write(
"\n*** nrf52 LTO guard: interrupt handler(s) DROPPED: %s ***\n"
"Each resolved to the weak Default_Handler stub, so the chip hangs when that IRQ\n"
"fires. Compile the .cpp that defines the handler with -fno-lto by adding it to\n"
"LIB_ISR in extra_scripts/nrf52_lto.py. Find the owner of FOO_IRQHandler with:\n"
" grep -rl FOO_IRQHandler <framework-arduinoadafruitnrf52>/{libraries,cores}\n\n"
% ", ".join(dropped)
)
from SCons.Script import Exit
Exit(1) # canonical SCons build-abort -> red build
print(
"nrf52_lto: ISR-handler guard OK -- %d critical handlers strong"
% len(_REQUIRED_STRONG)
)
# Attach to the phony "buildprog" alias, NOT the .elf file node: SCons can skip a post-action
# on a file target during an incremental relink (observed), but the buildprog alias runs every
# build -- so the guard fires on local incremental rebuilds and clean CI builds alike.
env.AddPostAction("buildprog", _assert_isr_handlers_survived)
+39
View File
@@ -0,0 +1,39 @@
#!/usr/bin/env python3
# trunk-ignore-all(ruff/F821)
# trunk-ignore-all(flake8/F821): For SConstruct imports
import re
Import("env")
# The ZPS module scans BLE through the NimBLE *host* API ble_gap_disc(), which the
# ESP-IDF only compiles when CONFIG_BT_NIMBLE_ROLE_OBSERVER=y. The base esp32 config
# disables the observer role to save flash (see variants/esp32/esp32-common.ini), so
# re-enable it ONLY when the ZPS module is actually built. This keeps a single flag
# (-DMESHTASTIC_EXCLUDE_ZPS) driving both the C++ module and the IDF sdkconfig.
#
# This runs as a pre: script, before the arduino framework builder reads
# custom_sdkconfig (PlatformIO core runs pre-scripts before $BUILD_SCRIPT). Appending
# to custom_sdkconfig changes its hash and triggers the framework's IDF rebuild path,
# but only for ZPS-enabled envs; for every normal build this is a no-op.
flags = env.GetProjectOption("build_flags", "")
if isinstance(flags, (list, tuple)):
flags = " ".join(flags)
# Mirror the C semantics of `#if !MESHTASTIC_EXCLUDE_ZPS`:
# flag absent -> module enabled
# -DMESHTASTIC_EXCLUDE_ZPS=0 -> module enabled
# -DMESHTASTIC_EXCLUDE_ZPS or =1 (or anything else) -> module excluded
match = re.search(r"\bMESHTASTIC_EXCLUDE_ZPS\b(?:=(\S+))?", flags)
zps_enabled = (match is None) or (match.group(1) == "0")
section = "env:" + env["PIOENV"]
config = env.GetProjectConfig()
if zps_enabled and config.has_option(section, "custom_sdkconfig"):
sdkconfig = env.GetProjectOption("custom_sdkconfig")
if "CONFIG_BT_NIMBLE_ROLE_OBSERVER" not in sdkconfig:
config.set(
section,
"custom_sdkconfig",
sdkconfig.rstrip("\n") + "\n CONFIG_BT_NIMBLE_ROLE_OBSERVER=y\n",
)
print("[ZPS] module enabled -> CONFIG_BT_NIMBLE_ROLE_OBSERVER=y (IDF rebuild)")
+1
View File
@@ -53,6 +53,7 @@ build_flags = -Wno-missing-field-initializers
-DRADIOLIB_EXCLUDE_ADSB=1
-DRADIOLIB_EXCLUDE_LORAWAN=1
-DMESHTASTIC_EXCLUDE_DROPZONE=1
-DMESHTASTIC_EXCLUDE_ZPS=1
-DMESHTASTIC_EXCLUDE_REPLYBOT=1
-DMESHTASTIC_EXCLUDE_REMOTEHARDWARE=1
-DMESHTASTIC_EXCLUDE_HEALTH_TELEMETRY=1
-5
View File
@@ -14,7 +14,6 @@
* For more information, see: https://meshtastic.org/
*/
#include "power.h"
#include "BluetoothCommon.h"
#include "MessageStore.h"
#include "NodeDB.h"
#include "PowerFSM.h"
@@ -963,10 +962,6 @@ void Power::readPowerStatus()
lastLogTime = millis();
}
newStatus.notifyObservers(&powerStatus2);
// Mirror battery level to the BLE Battery Service (0x2A19); the platform layer clamps and dedupes.
if (hasBattery == OptTrue)
updateBatteryLevel(powerStatus2.getBatteryChargePercent());
#ifdef DEBUG_HEAP
if (lastheap != memGet.getFreeHeap()) {
// Use stack-allocated buffer to avoid heap allocations in monitoring code
+12 -299
View File
@@ -17,10 +17,7 @@
#include "main.h" // pmu_found
#include "sleep.h"
#include "FSCommon.h"
#include "GPSUpdateScheduling.h"
#include "SPILock.h"
#include "SafeFile.h"
#include "cas.h"
#include "ubx.h"
@@ -74,67 +71,6 @@ static struct uBloxGnssModelInfo {
#define GPS_SOL_EXPIRY_MS 5000 // in millis. give 1 second time to combine different sentences. NMEA Frequency isn't higher anyway
#define NMEA_MSG_GXGSA "GNGSA" // GSA message (GPGSA, GNGSA etc)
namespace
{
// Versioned on-disk record for persisted GPS probe results.
constexpr uint32_t GPS_PROBE_CACHE_MAGIC = 0x47504348UL; // "GPCH"
constexpr uint16_t GPS_PROBE_CACHE_VERSION = 1;
constexpr const char *GPS_PROBE_CACHE_FILE = "/prefs/gps_probe_cache.dat";
struct GPSProbeCacheRecord {
uint32_t magic;
uint16_t version;
uint16_t reserved;
uint32_t baud;
uint8_t model;
};
bool isValidGnssModel(uint8_t model)
{
// Keep persisted values bounded to known enum range.
return model <= static_cast<uint8_t>(GNSS_MODEL_CM121);
}
bool isValidProbeBaud(uint32_t baud)
{
// Conservative sanity range for UART baud values.
return baud >= 1200 && baud <= 921600;
}
template <typename T> bool sawNmeaSentenceAtBaud(T *serialGps, uint32_t timeoutMs)
{
// Lightweight passive check: look for at least one complete
// "$...,<field>\n" style NMEA sentence.
const uint32_t deadline = millis() + timeoutMs;
bool sawDollar = false;
bool sawComma = false;
while ((int32_t)(millis() - deadline) < 0) {
while (serialGps->available()) {
char c = static_cast<char>(serialGps->read());
if (c == '$') {
sawDollar = true;
sawComma = false;
continue;
}
if (c == ',') {
sawComma = true;
}
if (c == '\n' || c == '\r') {
if (sawDollar && sawComma) {
return true;
}
sawDollar = false;
sawComma = false;
}
}
delay(10);
}
return false;
}
} // namespace
// For logging
static const char *getGPSPowerStateString(GPSPowerState state)
{
@@ -556,201 +492,6 @@ static const int rareSerialSpeeds[3] = {4800, 57600, GPS_BAUDRATE};
#define GPS_PROBETRIES 2
#endif
bool GPS::loadProbeCache()
{
#ifdef FSCom
// Load the last known-good GPS model/baud pair so we can avoid a full probe
// sweep on every boot.
triedProbeCache = true; // Latch this boot's load attempt, even if no cache.
GPSProbeCacheRecord record = {};
size_t bytesRead = 0;
spiLock->lock();
auto file = FSCom.open(GPS_PROBE_CACHE_FILE, FILE_O_READ);
if (!file) {
spiLock->unlock();
return false;
}
bytesRead = file.read(reinterpret_cast<uint8_t *>(&record), sizeof(record));
file.close();
spiLock->unlock();
const bool headerValid = (bytesRead == sizeof(record)) && (record.magic == GPS_PROBE_CACHE_MAGIC) &&
(record.version == GPS_PROBE_CACHE_VERSION) && (record.reserved == 0U);
if (!headerValid || !isValidGnssModel(record.model) || !isValidProbeBaud(record.baud)) {
clearProbeCache(); // Drop corrupt/invalid cache so next boot can
// recover.
return false;
}
cachedProbeBaud = static_cast<int32_t>(record.baud);
cachedProbeModel = static_cast<GnssModel_t>(record.model);
hasProbeCache = true;
triedProbeCache = false;
LOG_INFO("Loaded cached GPS probe: baud=%u", record.baud);
return true;
#else
return false;
#endif
}
void GPS::clearProbeCache()
{
// Invalidate in-memory and on-disk cache so next boot is forced to do a
// full probe.
hasProbeCache = false;
triedProbeCache = true;
cachedProbeBaud = 0;
cachedProbeModel = GNSS_MODEL_UNKNOWN;
#ifdef FSCom
spiLock->lock();
if (FSCom.exists(GPS_PROBE_CACHE_FILE)) {
FSCom.remove(GPS_PROBE_CACHE_FILE);
}
spiLock->unlock();
#endif
}
bool GPS::saveProbeCache() const
{
#ifdef FSCom
if (gnssModel == GNSS_MODEL_UNKNOWN || !isValidGnssModel(static_cast<uint8_t>(gnssModel)) ||
!isValidProbeBaud(detectedBaud)) {
return false;
}
spiLock->lock();
FSCom.mkdir("/prefs");
spiLock->unlock();
GPSProbeCacheRecord record = {
GPS_PROBE_CACHE_MAGIC, GPS_PROBE_CACHE_VERSION, 0, static_cast<uint32_t>(detectedBaud), static_cast<uint8_t>(gnssModel),
};
auto file = SafeFile(GPS_PROBE_CACHE_FILE, true);
spiLock->lock();
const size_t written = file.write(reinterpret_cast<const uint8_t *>(&record), sizeof(record));
spiLock->unlock();
return (written == sizeof(record)) && file.close();
#else
return false;
#endif
}
bool GPS::verifyCachedProbePresence()
{
if (!hasProbeCache || cachedProbeModel == GNSS_MODEL_UNKNOWN || !isValidProbeBaud(cachedProbeBaud)) {
return false;
}
#if defined(ARCH_NRF52) || defined(ARCH_PORTDUINO) || defined(ARCH_STM32WL)
_serial_gps->end();
_serial_gps->begin(cachedProbeBaud);
#elif defined(ARCH_RP2040)
_serial_gps->end();
_serial_gps->setFIFOSize(256);
_serial_gps->begin(cachedProbeBaud);
#else
if (_serial_gps->baudRate() != cachedProbeBaud) {
LOG_DEBUG("Set GPS Baud to %i (cached verify)", cachedProbeBaud);
_serial_gps->updateBaudRate(cachedProbeBaud);
}
#endif
// Before trusting cached model/baud, require either active model-specific
// response or passive NMEA flow.
clearBuffer();
bool present = false;
// Model-specific "active ping" checks to avoid false stale decisions on
// modules that start streaming late.
const char *cachedProbeModelName = "UNKNOWN";
switch (cachedProbeModel) {
case GNSS_MODEL_MTK:
cachedProbeModelName = "L76K/MTK";
_serial_gps->write("$PCAS06,0*1B\r\n");
present = (getACK("$GPTXT,01,01,02,SW=", 700) == GNSS_RESPONSE_OK);
break;
case GNSS_MODEL_MTK_L76B:
cachedProbeModelName = "L76B";
case GNSS_MODEL_MTK_PA1010D:
if (cachedProbeModel == GNSS_MODEL_MTK_PA1010D)
cachedProbeModelName = "PA1010D";
case GNSS_MODEL_MTK_PA1616S:
if (cachedProbeModel == GNSS_MODEL_MTK_PA1616S)
cachedProbeModelName = "PA1616S";
case GNSS_MODEL_LS20031:
if (cachedProbeModel == GNSS_MODEL_LS20031)
cachedProbeModelName = "LS20031";
_serial_gps->write("$PMTK605*31\r\n");
present = (getACK("$PMTK705", 900) == GNSS_RESPONSE_OK);
break;
case GNSS_MODEL_AG3335:
cachedProbeModelName = "AG3335";
case GNSS_MODEL_AG3352:
if (cachedProbeModel == GNSS_MODEL_AG3352)
cachedProbeModelName = "AG3352";
_serial_gps->write("$PAIR021*39\r\n");
present = (getACK("$PAIR021,", 900) == GNSS_RESPONSE_OK);
break;
case GNSS_MODEL_ATGM336H:
cachedProbeModelName = "ATGM336H";
_serial_gps->write("$PCAS06,1*1A\r\n");
present = (getACK("$GPTXT,01,01,02,HW=ATGM", 900) == GNSS_RESPONSE_OK);
break;
case GNSS_MODEL_UC6580:
cachedProbeModelName = "UC6580/UM600";
_serial_gps->write("$PDTINFO\r\n");
present = (getACK("UC6580", 900) == GNSS_RESPONSE_OK) || (getACK("UM600", 900) == GNSS_RESPONSE_OK);
break;
case GNSS_MODEL_CM121:
cachedProbeModelName = "CM121";
_serial_gps->write("$PDTINFO\r\n");
present = (getACK("CM121", 900) == GNSS_RESPONSE_OK);
break;
case GNSS_MODEL_UBLOX6:
case GNSS_MODEL_UBLOX7:
case GNSS_MODEL_UBLOX8:
case GNSS_MODEL_UBLOX9:
case GNSS_MODEL_UBLOX10: {
if (cachedProbeModel == GNSS_MODEL_UBLOX6)
cachedProbeModelName = "U-blox 6";
else if (cachedProbeModel == GNSS_MODEL_UBLOX7)
cachedProbeModelName = "U-blox 7";
else if (cachedProbeModel == GNSS_MODEL_UBLOX8)
cachedProbeModelName = "U-blox 8";
else if (cachedProbeModel == GNSS_MODEL_UBLOX9)
cachedProbeModelName = "U-blox 9";
else if (cachedProbeModel == GNSS_MODEL_UBLOX10)
cachedProbeModelName = "U-blox 10";
uint8_t cfg_rate[] = {0xB5, 0x62, 0x06, 0x08, 0x00, 0x00, 0x00, 0x00};
UBXChecksum(cfg_rate, sizeof(cfg_rate));
_serial_gps->write(cfg_rate, sizeof(cfg_rate));
present = (getACK(0x06, 0x08, 900) != GNSS_RESPONSE_NONE);
break;
}
default:
break;
}
if (!present) {
// Some modules may not respond to probes while still streaming NMEA, so
// allow a passive fallback check.
present = sawNmeaSentenceAtBaud(_serial_gps, 3000);
}
if (!present) {
LOG_WARN("Cached GPS probe is stale (%s @ %d), clearing cache", cachedProbeModelName, cachedProbeBaud);
clearProbeCache();
cachedProbeFailedThisBoot = true;
return false;
}
detectedBaud = cachedProbeBaud;
gnssModel = cachedProbeModel;
LOG_INFO("Using cached GPS probe: %s @ %d", cachedProbeModelName, detectedBaud);
return true;
}
/**
* @brief Setup the GPS based on the model detected.
* We detect the GPS by cycling through a set of baud rates, first common then rare.
@@ -762,46 +503,25 @@ bool GPS::setup()
{
if (!didSerialInit) {
int msglen = 0;
if (cachedProbeFailedThisBoot) {
// If cached verification failed, suppress further probing until
// reboot.
didSerialInit = true;
return true;
}
if (tx_gpio && gnssModel == GNSS_MODEL_UNKNOWN) {
if (!hasProbeCache && !triedProbeCache) {
(void)loadProbeCache();
}
if (hasProbeCache && !triedProbeCache) {
triedProbeCache = true;
if (!verifyCachedProbePresence()) {
// Cache was stale and got wiped; skip scanning this boot
// and let next boot do a full probe.
didSerialInit = true;
return true;
}
} else if (probeTries < GPS_PROBETRIES) {
// No usable cache: walk common baud rates first.
if (probeTries < GPS_PROBETRIES) {
gnssModel = probe(serialSpeeds[speedSelect]);
if (gnssModel != GNSS_MODEL_UNKNOWN) {
detectedBaud = serialSpeeds[speedSelect];
} else if (currentStep == 0 && ++speedSelect == array_count(serialSpeeds)) {
speedSelect = 0;
++probeTries;
if (gnssModel == GNSS_MODEL_UNKNOWN) {
if (currentStep == 0 && ++speedSelect == array_count(serialSpeeds)) {
speedSelect = 0;
++probeTries;
}
}
}
// Rare Serial Speeds
#ifndef CONFIG_IDF_TARGET_ESP32C6
else if (probeTries == GPS_PROBETRIES) {
// Then try less common baud rates before giving up.
if (probeTries == GPS_PROBETRIES) {
gnssModel = probe(rareSerialSpeeds[speedSelect]);
if (gnssModel != GNSS_MODEL_UNKNOWN) {
detectedBaud = rareSerialSpeeds[speedSelect];
} else if (currentStep == 0 && ++speedSelect == array_count(rareSerialSpeeds)) {
LOG_WARN("Give up on GPS probe and set to %d", GPS_BAUDRATE);
return true;
if (gnssModel == GNSS_MODEL_UNKNOWN) {
if (currentStep == 0 && ++speedSelect == array_count(rareSerialSpeeds)) {
LOG_WARN("Give up on GPS probe and set to %d", GPS_BAUDRATE);
return true;
}
}
}
#endif
@@ -809,7 +529,6 @@ bool GPS::setup()
if (gnssModel != GNSS_MODEL_UNKNOWN) {
setConnected();
(void)saveProbeCache();
} else {
return false;
}
@@ -1383,12 +1102,6 @@ int32_t GPS::runOnce()
if (!setup())
return currentDelay; // Setup failed, re-run in two seconds
if (cachedProbeFailedThisBoot || gnssModel == GNSS_MODEL_UNKNOWN) {
LOG_WARN("GPS not detected at cached settings; marked not present "
"for this boot");
return disable();
}
// We have now loaded our saved preferences from flash
if (config.position.gps_mode != meshtastic_Config_PositionConfig_GpsMode_ENABLED) {
return disable();
-17
View File
@@ -155,19 +155,8 @@ class GPS : private concurrency::OSThread
* @return true if we've acquired a new location
*/
virtual bool lookForLocation();
// Load persisted GPS model+baud from /prefs.
bool loadProbeCache();
// Clear persisted GPS model+baud cache.
void clearProbeCache();
// Persist the currently detected GPS model+baud.
bool saveProbeCache() const;
// Verify the cached model+baud still maps to a live GPS device.
bool verifyCachedProbePresence();
GnssModel_t gnssModel = GNSS_MODEL_UNKNOWN;
int32_t detectedBaud = GPS_BAUDRATE;
int32_t cachedProbeBaud = 0;
GnssModel_t cachedProbeModel = GNSS_MODEL_UNKNOWN;
TinyGPSPlus reader;
uint8_t fixQual = 0; // fix quality from GPGGA
@@ -189,12 +178,6 @@ class GPS : private concurrency::OSThread
uint8_t speedSelect = 0;
uint8_t probeTries = 0;
// Cache file is successfully loaded.
bool hasProbeCache = false;
// Ensures cached probe is attempted once per boot.
bool triedProbeCache = false;
// Latched when cached presence check fails
bool cachedProbeFailedThisBoot = false;
/**
* hasValidLocation - indicates that the position variables contain a complete
+109 -64
View File
@@ -102,8 +102,8 @@ namespace graphics
// if defined a pixel will blink to show redraws
// #define SHOW_REDRAWS
#define ASCII_BELL '\x07'
// Base frames plus active module/favorite frames; grows only when the actual frameset needs it.
static std::vector<FrameCallback> normalFrames;
// A text message frame + debug frame + all the node infos
FrameCallback *normalFrames;
static uint32_t targetFramerate = IDLE_FRAMERATE;
#if GRAPHICS_TFT_COLORING_ENABLED
static inline void prepareFrameColorRegions()
@@ -136,7 +136,6 @@ uint32_t dopThresholds[5] = {2000, 1000, 500, 200, 100};
// At some point, we're going to ask all of the modules if they would like to display a screen frame
// we'll need to hold onto pointers for the modules that can draw a frame.
std::vector<MeshModule *> moduleFrames;
static uint8_t moduleFrameStart = 0;
#if HAS_GPS
// GeoCoord object for the screen
@@ -334,14 +333,8 @@ static void drawModuleFrame(OLEDDisplay *display, OLEDDisplayUiState *state, int
// otherwise, just display the module frame that's aligned with the current frame
module_frame = state->currentFrame;
}
if (module_frame < moduleFrameStart)
return;
const uint8_t moduleIndex = module_frame - moduleFrameStart;
if (moduleIndex >= moduleFrames.size() || moduleFrames[moduleIndex] == nullptr)
return;
moduleFrames[moduleIndex]->drawFrame(display, state, x, y);
MeshModule &pi = *moduleFrames.at(module_frame);
pi.drawFrame(display, state, x, y);
}
/**
@@ -409,11 +402,9 @@ SPIClass SPI1(HSPI);
#endif
Screen::Screen(ScanI2C::DeviceAddress address, meshtastic_Config_DisplayConfig_OledType screenType, OLEDDISPLAY_GEOMETRY geometry)
: concurrency::OSThread("Screen"), address_found(address), model(screenType), geometry(geometry), cmdQueue(16)
: concurrency::OSThread("Screen"), address_found(address), model(screenType), geometry(geometry), cmdQueue(32)
{
normalFrames.reserve(24);
indicatorIcons.reserve(24);
moduleFrames.reserve(8);
graphics::normalFrames = new FrameCallback[MAX_NUM_NODES + NUM_EXTRA_FRAMES];
#if defined(USE_SH1106) || defined(USE_SH1107) || defined(USE_SH1107_128_64)
dispdev = new SH1106Wire(address.address, -1, -1, geometry,
@@ -497,6 +488,7 @@ Screen::Screen(ScanI2C::DeviceAddress address, meshtastic_Config_DisplayConfig_O
Screen::~Screen()
{
delete[] graphics::normalFrames;
}
/**
@@ -1150,130 +1142,183 @@ void Screen::setFrames(FrameFocus focus)
LOG_DEBUG("Show standard frames");
showingNormalScreen = true;
normalFrames.clear();
indicatorIcons.clear();
auto appendFrame = [this](FrameCallback frame, const uint8_t *icon) -> uint8_t {
normalFrames.emplace_back(frame);
indicatorIcons.push_back(icon);
return normalFrames.size() - 1;
};
size_t numframes = 0;
// If we have a critical fault, show it first
fsi.positions.fault = normalFrames.size();
fsi.positions.fault = numframes;
if (error_code) {
fsi.positions.fault = appendFrame(NotificationRenderer::drawCriticalFaultFrame, icon_error);
normalFrames[numframes++] = NotificationRenderer::drawCriticalFaultFrame;
indicatorIcons.push_back(icon_error);
focus = FOCUS_FAULT; // Change our "focus" parameter, to ensure we show the fault frame
}
#if defined(DISPLAY_CLOCK_FRAME)
if (!hiddenFrames.clock) {
fsi.positions.clock = numframes;
#if defined(OLED_TINY)
fsi.positions.clock = appendFrame(graphics::ClockRenderer::drawAnalogClockFrame, digital_icon_clock);
normalFrames[numframes++] = graphics::ClockRenderer::drawAnalogClockFrame;
#else
fsi.positions.clock = appendFrame(uiconfig.is_clockface_analog ? graphics::ClockRenderer::drawAnalogClockFrame
: graphics::ClockRenderer::drawDigitalClockFrame,
digital_icon_clock);
normalFrames[numframes++] = uiconfig.is_clockface_analog ? graphics::ClockRenderer::drawAnalogClockFrame
: graphics::ClockRenderer::drawDigitalClockFrame;
#endif
indicatorIcons.push_back(digital_icon_clock);
}
#endif
if (!hiddenFrames.home) {
fsi.positions.home = appendFrame(graphics::UIRenderer::drawDeviceFocused, icon_home);
fsi.positions.home = numframes;
normalFrames[numframes++] = graphics::UIRenderer::drawDeviceFocused;
indicatorIcons.push_back(icon_home);
}
fsi.positions.textMessage = appendFrame(graphics::MessageRenderer::drawTextMessageFrame, icon_mail);
fsi.positions.textMessage = numframes;
normalFrames[numframes++] = graphics::MessageRenderer::drawTextMessageFrame;
indicatorIcons.push_back(icon_mail);
#ifndef USE_EINK
if (!hiddenFrames.nodelist_nodes) {
fsi.positions.nodelist_nodes = appendFrame(graphics::NodeListRenderer::drawDynamicListScreen_Nodes, icon_nodes);
fsi.positions.nodelist_nodes = numframes;
normalFrames[numframes++] = graphics::NodeListRenderer::drawDynamicListScreen_Nodes;
indicatorIcons.push_back(icon_nodes);
}
if (!hiddenFrames.nodelist_location) {
fsi.positions.nodelist_location = appendFrame(graphics::NodeListRenderer::drawDynamicListScreen_Location, icon_list);
fsi.positions.nodelist_location = numframes;
normalFrames[numframes++] = graphics::NodeListRenderer::drawDynamicListScreen_Location;
indicatorIcons.push_back(icon_list);
}
#endif
// Show detailed node views only on E-Ink builds
#ifdef USE_EINK
if (!hiddenFrames.nodelist_lastheard) {
fsi.positions.nodelist_lastheard = appendFrame(graphics::NodeListRenderer::drawLastHeardScreen, icon_nodes);
fsi.positions.nodelist_lastheard = numframes;
normalFrames[numframes++] = graphics::NodeListRenderer::drawLastHeardScreen;
indicatorIcons.push_back(icon_nodes);
}
if (!hiddenFrames.nodelist_hopsignal) {
fsi.positions.nodelist_hopsignal = appendFrame(graphics::NodeListRenderer::drawHopSignalScreen, icon_signal);
fsi.positions.nodelist_hopsignal = numframes;
normalFrames[numframes++] = graphics::NodeListRenderer::drawHopSignalScreen;
indicatorIcons.push_back(icon_signal);
}
if (!hiddenFrames.nodelist_distance) {
fsi.positions.nodelist_distance = appendFrame(graphics::NodeListRenderer::drawDistanceScreen, icon_distance);
fsi.positions.nodelist_distance = numframes;
normalFrames[numframes++] = graphics::NodeListRenderer::drawDistanceScreen;
indicatorIcons.push_back(icon_distance);
}
#endif
#if HAS_GPS
#ifdef USE_EINK
if (!hiddenFrames.nodelist_bearings) {
fsi.positions.nodelist_bearings = appendFrame(graphics::NodeListRenderer::drawNodeListWithCompasses, icon_list);
fsi.positions.nodelist_bearings = numframes;
normalFrames[numframes++] = graphics::NodeListRenderer::drawNodeListWithCompasses;
indicatorIcons.push_back(icon_list);
}
#endif
if (!hiddenFrames.gps) {
fsi.positions.gps = appendFrame(graphics::UIRenderer::drawCompassAndLocationScreen, icon_compass);
fsi.positions.gps = numframes;
normalFrames[numframes++] = graphics::UIRenderer::drawCompassAndLocationScreen;
indicatorIcons.push_back(icon_compass);
}
#endif
if (RadioLibInterface::instance && !hiddenFrames.lora) {
fsi.positions.lora = appendFrame(graphics::DebugRenderer::drawLoRaFocused, icon_radio);
fsi.positions.lora = numframes;
normalFrames[numframes++] = graphics::DebugRenderer::drawLoRaFocused;
indicatorIcons.push_back(icon_radio);
}
if (!hiddenFrames.system) {
fsi.positions.system = appendFrame(graphics::DebugRenderer::drawSystemScreen, icon_system);
fsi.positions.system = numframes;
normalFrames[numframes++] = graphics::DebugRenderer::drawSystemScreen;
indicatorIcons.push_back(icon_system);
}
#if !defined(DISPLAY_CLOCK_FRAME)
if (!hiddenFrames.clock) {
fsi.positions.clock = appendFrame(uiconfig.is_clockface_analog ? graphics::ClockRenderer::drawAnalogClockFrame
: graphics::ClockRenderer::drawDigitalClockFrame,
digital_icon_clock);
fsi.positions.clock = numframes;
normalFrames[numframes++] = uiconfig.is_clockface_analog ? graphics::ClockRenderer::drawAnalogClockFrame
: graphics::ClockRenderer::drawDigitalClockFrame;
indicatorIcons.push_back(digital_icon_clock);
}
#endif
if (!hiddenFrames.chirpy) {
fsi.positions.chirpy = appendFrame(graphics::DebugRenderer::drawChirpy, chirpy_small);
fsi.positions.chirpy = numframes;
normalFrames[numframes++] = graphics::DebugRenderer::drawChirpy;
indicatorIcons.push_back(chirpy_small);
}
#if HAS_WIFI && !defined(ARCH_PORTDUINO)
if (!hiddenFrames.wifi && isWifiAvailable()) {
fsi.positions.wifi = appendFrame(graphics::DebugRenderer::drawDebugInfoWiFiTrampoline, icon_wifi);
fsi.positions.wifi = numframes;
normalFrames[numframes++] = graphics::DebugRenderer::drawDebugInfoWiFiTrampoline;
indicatorIcons.push_back(icon_wifi);
}
#endif
moduleFrameStart = normalFrames.size();
moduleFrames = MeshModule::GetMeshModulesWithUIFrames();
// Beware of what changes you make in this code!
// We pass numframes into GetMeshModulesWithUIFrames() which is highly important!
// Inside of that callback, goes over to MeshModule.cpp and we run
// modulesWithUIFrames.resize(startIndex, nullptr), to insert nullptr
// entries until we're ready to start building the matching entries.
// We are doing our best to keep the normalFrames vector
// and the moduleFrames vector in lock step.
moduleFrames = MeshModule::GetMeshModulesWithUIFrames(numframes);
LOG_DEBUG("Show %d module frames", moduleFrames.size());
for (MeshModule *m : moduleFrames) {
const uint8_t frameIndex = appendFrame(drawModuleFrame, icon_module);
if (m && m->isRequestingFocus())
fsi.positions.focusedModule = frameIndex;
if (m && m == waypointModule)
fsi.positions.waypoint = frameIndex;
for (auto i = moduleFrames.begin(); i != moduleFrames.end(); ++i) {
// Draw the module frame, using the hack described above
if (*i != nullptr) {
normalFrames[numframes] = drawModuleFrame;
// Check if the module being drawn has requested focus
// We will honor this request later, if setFrames was triggered by a UIFrameEvent
MeshModule *m = *i;
if (m && m->isRequestingFocus())
fsi.positions.focusedModule = numframes;
if (m && m == waypointModule)
fsi.positions.waypoint = numframes;
indicatorIcons.push_back(icon_module);
numframes++;
}
}
LOG_DEBUG("Added modules. numframes: %d", normalFrames.size());
LOG_DEBUG("Added modules. numframes: %d", numframes);
// We don't show the node info of our node (if we have it yet - we should)
size_t numMeshNodes = nodeDB->getNumMeshNodes();
if (numMeshNodes > 0)
numMeshNodes--;
if (!hiddenFrames.show_favorites) {
uint8_t firstFavorite = 255;
uint8_t lastFavorite = 255;
// Temporary array to hold favorite node frames
std::vector<FrameCallback> favoriteFrames;
for (size_t i = 0; i < nodeDB->getNumMeshNodes(); i++) {
const meshtastic_NodeInfoLite *n = nodeDB->getMeshNodeByIndex(i);
if (n && n->num != nodeDB->getNodeNum() && nodeInfoLiteIsFavorite(n)) {
const uint8_t frameIndex = appendFrame(graphics::UIRenderer::drawFavoriteNode, icon_node);
if (firstFavorite == 255)
firstFavorite = frameIndex;
lastFavorite = frameIndex;
favoriteFrames.push_back(graphics::UIRenderer::drawFavoriteNode);
}
}
fsi.positions.firstFavorite = firstFavorite;
fsi.positions.lastFavorite = lastFavorite;
// Insert favorite frames *after* collecting them all
if (!favoriteFrames.empty()) {
fsi.positions.firstFavorite = numframes;
for (const auto &f : favoriteFrames) {
normalFrames[numframes++] = f;
indicatorIcons.push_back(icon_node);
}
fsi.positions.lastFavorite = numframes - 1;
} else {
fsi.positions.firstFavorite = 255;
fsi.positions.lastFavorite = 255;
}
}
fsi.frameCount = normalFrames.size(); // Total framecount is used to apply FOCUS_PRESERVE
this->frameCount = normalFrames.size(); // Save frame count for use in custom overlay
LOG_DEBUG("Finished build frames. numframes: %d", normalFrames.size());
fsi.frameCount = numframes; // Total framecount is used to apply FOCUS_PRESERVE
this->frameCount = numframes; // Save frame count for use in custom overlay
LOG_DEBUG("Finished build frames. numframes: %d", numframes);
ui->setFrames(normalFrames.data(), fsi.frameCount);
ui->setFrames(normalFrames, numframes);
ui->disableAllIndicators();
// Add overlays: frame icons and alert banner)
+1 -1
View File
@@ -12,7 +12,7 @@
#define getStringCenteredX(s) ((SCREEN_WIDTH - display->getStringWidth(s)) / 2)
namespace graphics
{
enum notificationTypeEnum { none, text_banner, selection_picker, node_picker, number_picker, hex_picker, text_input };
enum notificationTypeEnum { none, text_banner, selection_picker, node_picker, number_picker, text_input };
struct BannerOverlayOptions {
const char *message;
-4
View File
@@ -578,11 +578,7 @@ void drawCommonFooter(OLEDDisplay *display, int16_t x, int16_t y)
#endif
display->setColor(BLACK);
#if GRAPHICS_TFT_COLORING_ENABLED
display->fillRect(0, footerY, SCREEN_WIDTH, footerH);
#else
display->fillRect(0, footerY, connection_icon_width + 1, footerH);
#endif
display->setColor(WHITE);
if (currentResolution == ScreenResolution::High) {
const int bytesPerRow = (connection_icon_width + 7) / 8;
+2 -6
View File
@@ -183,13 +183,9 @@ void drawDigitalClockFrame(OLEDDisplay *display, OLEDDisplayUiState *state, int1
static float segmentHeight = SEGMENT_HEIGHT * 0.75f;
if (!scaleInitialized) {
#ifdef DISPLAY_FORCE_SMALL_FONTS
float screenwidth_target_ratio = 0.70f; // Target 70% of display width (adjustable)
#else
float screenwidth_target_ratio = 0.80f; // Target 80% of display width (adjustable)
#endif
float max_scale = 3.5f; // Safety limit to avoid runaway scaling
float step = 0.05f; // Step increment per iteration
float max_scale = 3.5f; // Safety limit to avoid runaway scaling
float step = 0.05f; // Step increment per iteration
float target_width = display->getWidth() * screenwidth_target_ratio;
float target_height =
+20 -82
View File
@@ -126,7 +126,6 @@ void launchReplyForMessage(const StoredMessage &message, bool freetext)
menuHandler::screenMenus menuHandler::menuQueue = MenuNone;
uint32_t menuHandler::pickedNodeNum = 0;
meshtastic_Config_LoRaConfig_RegionCode menuHandler::pendingRegion = meshtastic_Config_LoRaConfig_RegionCode_UNSET;
bool test_enabled = false;
uint8_t test_count = 0;
@@ -175,36 +174,6 @@ void menuHandler::OnboardMessage()
screen->showOverlayBanner(bannerOptions);
}
static void applyLoraRegion(meshtastic_Config_LoRaConfig_RegionCode region, bool isHam)
{
config.lora.region = region;
config.lora.channel_num = 0; // Reset to default channel
if (isHam && adminModule) {
meshtastic_HamParameters hamParams = meshtastic_HamParameters_init_zero;
strncpy(hamParams.call_sign, "N0CALL", sizeof(hamParams.call_sign) - 1);
strncpy(hamParams.short_name, "N0CL", sizeof(hamParams.short_name));
hamParams.tx_power = config.lora.tx_power;
hamParams.frequency = config.lora.override_frequency;
adminModule->handleSetHamMode(hamParams);
}
auto changes = SEGMENT_CONFIG;
#if !(MESHTASTIC_EXCLUDE_PKI_KEYGEN || MESHTASTIC_EXCLUDE_PKI)
if (crypto) {
crypto->ensurePkiKeys(config.security, owner);
}
#endif
initRegion();
if (getEffectiveDutyCycle() < 100) {
config.lora.ignore_mqtt = true;
}
if (strncmp(moduleConfig.mqtt.root, default_mqtt_root, strlen(default_mqtt_root)) == 0) {
sprintf(moduleConfig.mqtt.root, "%s/%s", default_mqtt_root, myRegion->name);
changes |= SEGMENT_MODULECONFIG;
}
service->reloadConfig(changes);
}
void menuHandler::LoraRegionPicker(uint32_t duration)
{
static const LoraRegionOption regionOptions[] = {
@@ -273,20 +242,27 @@ void menuHandler::LoraRegionPicker(uint32_t duration)
return;
}
bool hamMode = getRegion(selectedRegion)->profile->licensedOnly;
if (hamMode) {
LOG_INFO("User chose an amateur radio mode region");
pendingRegion = selectedRegion;
menuQueue = HamModeConfirm;
screen->runNow();
} else if (owner.is_licensed) {
LOG_INFO("Licensed user chose a non-ham region; prompting to revert licensed mode");
pendingRegion = selectedRegion;
menuQueue = LicensedToNormalConfirm;
screen->runNow();
} else {
applyLoraRegion(selectedRegion, false);
config.lora.region = selectedRegion;
auto changes = SEGMENT_CONFIG;
#if !(MESHTASTIC_EXCLUDE_PKI_KEYGEN || MESHTASTIC_EXCLUDE_PKI)
if (crypto) {
crypto->ensurePkiKeys(config.security, owner);
}
#endif
config.lora.tx_enabled = true;
initRegion();
if (getEffectiveDutyCycle() < 100) {
config.lora.ignore_mqtt = true; // Ignore MQTT by default if region has a duty cycle limit
}
if (strncmp(moduleConfig.mqtt.root, default_mqtt_root, strlen(default_mqtt_root)) == 0) {
// Default broker is in use, so subscribe to the appropriate MQTT root topic for this region
sprintf(moduleConfig.mqtt.root, "%s/%s", default_mqtt_root, myRegion->name);
changes |= SEGMENT_MODULECONFIG;
}
service->reloadConfig(changes);
});
bannerOptions.durationMs = duration;
@@ -303,38 +279,6 @@ void menuHandler::LoraRegionPicker(uint32_t duration)
screen->showOverlayBanner(bannerOptions);
}
void menuHandler::hamModeConfirmMenu()
{
static const char *confirmOptions[] = {"No", "Yes"};
BannerOverlayOptions confirmBanner;
confirmBanner.message = "I confirm I am a\nlicensed amateur\nradio operator";
confirmBanner.optionsArrayPtr = confirmOptions;
confirmBanner.optionsCount = 2;
confirmBanner.bannerCallback = [](int selected) {
if (selected == 1)
applyLoraRegion(pendingRegion, true);
};
screen->showOverlayBanner(confirmBanner);
}
void menuHandler::licensedToNormalConfirmMenu()
{
static const char *confirmOptions[] = {"Keep licensed", "Revert to Normal"};
BannerOverlayOptions confirmBanner;
confirmBanner.message = "Revert licensed\nmode? This will\nre-enable encryption.";
confirmBanner.optionsArrayPtr = confirmOptions;
confirmBanner.optionsCount = 2;
confirmBanner.bannerCallback = [](int selected) {
if (selected == 1) {
owner.is_licensed = false;
config.lora.override_duty_cycle = false;
service->reloadOwner(false);
}
applyLoraRegion(pendingRegion, false);
};
screen->showOverlayBanner(confirmBanner);
}
void menuHandler::deviceRolePicker()
{
static const char *optionsArray[] = {"Back", "Client", "Client Mute", "Lost and Found", "Tracker"};
@@ -2878,12 +2822,6 @@ void menuHandler::handleMenuSwitch(OLEDDisplay *display)
case ThemeMenu:
themeMenu();
break;
case HamModeConfirm:
hamModeConfirmMenu();
break;
case LicensedToNormalConfirm:
licensedToNormalConfirmMenu();
break;
}
menuQueue = MenuNone;
}
+1 -6
View File
@@ -55,13 +55,10 @@ class menuHandler
FrameToggles,
DisplayUnits,
MessageBubblesMenu,
ThemeMenu,
HamModeConfirm,
LicensedToNormalConfirm
ThemeMenu
};
static screenMenus menuQueue;
static uint32_t pickedNodeNum; // node selected by NodePicker for ManageNodeMenu
static meshtastic_Config_LoRaConfig_RegionCode pendingRegion;
static void OnboardMessage();
static void LoraRegionPicker(uint32_t duration = 30000);
@@ -114,8 +111,6 @@ class menuHandler
static void messageBubblesMenu();
static void themeMenu();
static void textMessageMenu();
static void hamModeConfirmMenu();
static void licensedToNormalConfirmMenu();
private:
static void saveUIConfig();
+18 -69
View File
@@ -154,8 +154,8 @@ static std::vector<uint32_t> seenPeers;
// Public helper so menus / store can clear stale registries
void clearThreadRegistries()
{
std::vector<int>().swap(seenChannels);
std::vector<uint32_t>().swap(seenPeers);
seenChannels.clear();
seenPeers.clear();
}
// Setter so other code can switch threads
@@ -387,58 +387,6 @@ static void drawMessageScrollbar(OLEDDisplay *display, int visibleHeight, int to
}
}
static void appendWrappedLines(OLEDDisplay *display, const char *messageBuf, int textWidth, std::vector<std::string> &allLines,
size_t maxTotalLines, size_t maxWrappedLines)
{
std::string line;
std::string word;
size_t wrappedCount = 0;
auto appendLine = [&](std::string &&newLine) -> bool {
if (newLine.empty())
return true;
if (allLines.size() >= maxTotalLines || wrappedCount >= maxWrappedLines)
return false;
allLines.emplace_back(std::move(newLine));
++wrappedCount;
return true;
};
for (int i = 0; messageBuf[i]; ++i) {
char ch = messageBuf[i];
if ((unsigned char)messageBuf[i] == 0xE2 && (unsigned char)messageBuf[i + 1] == 0x80 &&
(unsigned char)messageBuf[i + 2] == 0x99) {
ch = '\''; // plain apostrophe
i += 2; // skip over the extra UTF-8 bytes
}
if (ch == '\n') {
if (!word.empty())
line += word;
if (!appendLine(std::move(line)))
return;
line.clear();
word.clear();
} else if (ch == ' ') {
line += word + ' ';
word.clear();
} else {
word += ch;
std::string test = line + word;
uint16_t strWidth = graphics::UIRenderer::measureStringWithEmotes(display, test.c_str());
if (strWidth > textWidth) {
if (!line.empty() && !appendLine(std::move(line)))
return;
line = word;
word.clear();
}
}
}
if (!word.empty())
line += word;
appendLine(std::move(line));
}
void drawTextMessageFrame(OLEDDisplay *display, OLEDDisplayUiState *state, int16_t x, int16_t y)
{
// Ensure any boot-relative timestamps are upgraded if RTC is valid
@@ -698,15 +646,19 @@ void drawTextMessageFrame(OLEDDisplay *display, OLEDDisplayUiState *state, int16
const char *msgText = MessageStore::getText(m);
int wrapWidth = mine ? rightTextWidth : leftTextWidth;
std::vector<std::string> wrapped = generateLines(display, "", msgText, wrapWidth);
// Per-message wrap-line limit: even if wrapping produces many lines, cap them to prevent
// a single long message from consuming most or all of the cache.
constexpr size_t MAX_WRAPPED_LINES_PER_MSG = 20U;
const size_t previousLineCount = allLines.size();
appendWrappedLines(display, msgText, wrapWidth, allLines, MAX_CACHED_LINES, MAX_WRAPPED_LINES_PER_MSG);
for (size_t i = previousLineCount; i < allLines.size(); ++i) {
size_t wrappedCount = 0;
for (auto &ln : wrapped) {
if (allLines.size() >= MAX_CACHED_LINES || wrappedCount >= MAX_WRAPPED_LINES_PER_MSG)
break; // Cache limit or per-message limit reached; stop adding lines from this message
allLines.emplace_back(std::move(ln));
isMine.push_back(mine);
isHeader.push_back(false);
ackForLine.push_back(AckStatus::NONE);
++wrappedCount;
}
}
@@ -1056,23 +1008,20 @@ std::vector<int> calculateLineHeights(const std::vector<std::string> &lines, con
std::vector<int> rowHeights;
rowHeights.reserve(lines.size());
auto currentMetrics = graphics::EmoteRenderer::LineMetrics{};
auto nextMetrics = lines.empty()
? graphics::EmoteRenderer::LineMetrics{}
: graphics::EmoteRenderer::analyzeLine(nullptr, lines[0], FONT_HEIGHT_SMALL, emotes, numEmotes);
std::vector<graphics::EmoteRenderer::LineMetrics> lineMetrics;
lineMetrics.reserve(lines.size());
for (const auto &line : lines) {
lineMetrics.push_back(graphics::EmoteRenderer::analyzeLine(nullptr, line, FONT_HEIGHT_SMALL, emotes, numEmotes));
}
for (size_t idx = 0; idx < lines.size(); ++idx) {
currentMetrics = nextMetrics;
nextMetrics = (idx + 1 < lines.size())
? graphics::EmoteRenderer::analyzeLine(nullptr, lines[idx + 1], FONT_HEIGHT_SMALL, emotes, numEmotes)
: graphics::EmoteRenderer::LineMetrics{};
const int baseHeight = FONT_HEIGHT_SMALL;
int lineHeight = baseHeight;
const int tallestEmote = currentMetrics.tallestHeight;
const bool hasEmote = currentMetrics.hasEmote;
const bool nextHasEmote = (idx + 1 < lines.size()) && nextMetrics.hasEmote;
const int tallestEmote = lineMetrics[idx].tallestHeight;
const bool hasEmote = lineMetrics[idx].hasEmote;
const bool nextHasEmote = (idx + 1 < lines.size()) && lineMetrics[idx + 1].hasEmote;
if (isHeaderVec[idx]) {
// Header line spacing
-111
View File
@@ -66,15 +66,6 @@ uint32_t pow_of_10(uint32_t n)
return ret;
}
uint64_t pow_of_16(uint32_t n)
{
uint64_t ret = 1;
for (uint32_t i = 0; i < n; i++) {
ret *= 16ULL;
}
return ret;
}
char graphics::NotificationRenderer::alertBannerLines[MAX_LINES + 1][64] = {};
uint8_t graphics::NotificationRenderer::alertBannerLineCount = 0;
graphics::NotificationRenderer::BannerFont graphics::NotificationRenderer::alertBannerLineFonts[MAX_LINES + 1] = {};
@@ -268,9 +259,6 @@ void NotificationRenderer::drawBannercallback(OLEDDisplay *display, OLEDDisplayU
case notificationTypeEnum::number_picker:
drawNumberPicker(display, state);
break;
case notificationTypeEnum::hex_picker:
drawHexPicker(display, state);
break;
}
}
@@ -357,105 +345,6 @@ void NotificationRenderer::drawNumberPicker(OLEDDisplay *display, OLEDDisplayUiS
drawNotificationBox(display, state, linePointers, totalLines, 0);
}
void NotificationRenderer::drawHexPicker(OLEDDisplay *display, OLEDDisplayUiState *state)
{
const char *lineStarts[MAX_LINES + 1] = {0};
uint16_t lineCount = 0;
// Parse lines
char *alertEnd = alertBannerMessage + strnlen(alertBannerMessage, sizeof(alertBannerMessage));
lineStarts[lineCount] = alertBannerMessage;
// Find lines
while ((lineCount < MAX_LINES) && (lineStarts[lineCount] < alertEnd)) {
lineStarts[lineCount + 1] = std::find((char *)lineStarts[lineCount], alertEnd, '\n');
if (lineStarts[lineCount + 1][0] == '\n')
lineStarts[lineCount + 1] += 1;
lineCount++;
}
// modulo to extract
uint8_t this_digit = (currentNumber % (pow_of_16(numDigits - curSelected))) / (pow_of_16(numDigits - curSelected - 1));
// Handle input
if (inEvent.inputEvent == INPUT_BROKER_UP || inEvent.inputEvent == INPUT_BROKER_ALT_PRESS ||
inEvent.inputEvent == INPUT_BROKER_UP_LONG) {
if (this_digit == 15) {
currentNumber -= 15 * (pow_of_16(numDigits - curSelected - 1));
} else {
currentNumber += (pow_of_16(numDigits - curSelected - 1));
}
} else if (inEvent.inputEvent == INPUT_BROKER_DOWN || inEvent.inputEvent == INPUT_BROKER_USER_PRESS ||
inEvent.inputEvent == INPUT_BROKER_DOWN_LONG) {
if (this_digit == 0) {
currentNumber += 15 * (pow_of_16(numDigits - curSelected - 1));
} else {
currentNumber -= (pow_of_16(numDigits - curSelected - 1));
}
} else if (inEvent.inputEvent == INPUT_BROKER_ANYKEY) {
if (inEvent.kbchar > 47 && inEvent.kbchar < 58) { // have a digit
currentNumber -= this_digit * (pow_of_16(numDigits - curSelected - 1));
currentNumber += (inEvent.kbchar - 48) * (pow_of_16(numDigits - curSelected - 1));
curSelected++;
}
} else if (inEvent.inputEvent == INPUT_BROKER_SELECT || inEvent.inputEvent == INPUT_BROKER_RIGHT) {
curSelected++;
} else if (inEvent.inputEvent == INPUT_BROKER_LEFT) {
curSelected--;
} else if ((inEvent.inputEvent == INPUT_BROKER_CANCEL || inEvent.inputEvent == INPUT_BROKER_ALT_LONG) &&
alertBannerUntil != 0) {
resetBanner();
return;
}
if (curSelected == static_cast<int8_t>(numDigits)) {
alertBannerCallback(currentNumber);
resetBanner();
return;
}
inEvent.inputEvent = INPUT_BROKER_NONE;
if (alertBannerMessage[0] == '\0')
return;
uint16_t totalLines = lineCount + 2;
const char *linePointers[totalLines + 1] = {0}; // this is sort of a dynamic allocation
// copy the linestarts to display to the linePointers holder
for (uint16_t i = 0; i < lineCount; i++) {
linePointers[i] = lineStarts[i];
}
std::string digits = " ";
std::string arrowPointer = " ";
for (uint16_t i = 0; i < numDigits; i++) {
// Modulo minus modulo to return just the current number
uint8_t digitValue = (currentNumber % (pow_of_16(numDigits - i))) / (pow_of_16(numDigits - i - 1));
if (digitValue < 10) {
digits += std::to_string(digitValue) + " ";
} else if (digitValue == 10) {
digits += "A ";
} else if (digitValue == 11) {
digits += "B ";
} else if (digitValue == 12) {
digits += "C ";
} else if (digitValue == 13) {
digits += "D ";
} else if (digitValue == 14) {
digits += "E ";
} else if (digitValue == 15) {
digits += "F ";
}
if (curSelected == i) {
arrowPointer += "^ ";
} else {
arrowPointer += "_ ";
}
}
linePointers[lineCount++] = digits.c_str();
linePointers[lineCount++] = arrowPointer.c_str();
drawNotificationBox(display, state, linePointers, totalLines, 0);
}
void NotificationRenderer::drawNodePicker(OLEDDisplay *display, OLEDDisplayUiState *state)
{
static uint32_t selectedNodenum = 0;
-1
View File
@@ -42,7 +42,6 @@ class NotificationRenderer
static void drawBannercallback(OLEDDisplay *display, OLEDDisplayUiState *state);
static void drawAlertBannerOverlay(OLEDDisplay *display, OLEDDisplayUiState *state);
static void drawNumberPicker(OLEDDisplay *display, OLEDDisplayUiState *state);
static void drawHexPicker(OLEDDisplay *display, OLEDDisplayUiState *state);
static void drawNodePicker(OLEDDisplay *display, OLEDDisplayUiState *state);
static void drawTextInput(OLEDDisplay *display, OLEDDisplayUiState *state);
static void drawNotificationBox(OLEDDisplay *display, OLEDDisplayUiState *state, const char *lines[MAX_LINES + 1],
+4 -11
View File
@@ -79,12 +79,10 @@ static inline void transformNeedlePoint(float localX, float localY, float sinHea
outY = static_cast<int16_t>(y);
}
#if GRAPHICS_TFT_COLORING_ENABLED
static float getCompassRingAngleOffset(float heading)
{
return (uiconfig.compass_mode != meshtastic_CompassMode_FIXED_RING) ? -heading : 0.0f;
}
#endif
static inline StandardCompassNeedlePoints computeStandardCompassNeedlePoints(int16_t compassX, int16_t compassY,
uint16_t compassDiam, float headingRadian,
@@ -1144,16 +1142,11 @@ void UIRenderer::drawDeviceFocused(OLEDDisplay *display, OLEDDisplayUiState *sta
bool origBold = config.display.heading_bold;
config.display.heading_bold = false;
if (!config.lora.tx_enabled) {
const char *txdisabled = "Transmit Disabled";
display->drawString(x, getTextPositions(display)[line], txdisabled);
// Display Region and Channel Utilization
if (currentResolution == ScreenResolution::UltraLow) {
drawNodes(display, x, getTextPositions(display)[line] + 2, nodeStatus, -1, false, "online");
} else {
// Display Region and Channel Utilization
if (currentResolution == ScreenResolution::UltraLow) {
drawNodes(display, x, getTextPositions(display)[line] + 2, nodeStatus, -1, false, "online");
} else {
drawNodes(display, x + 1, getTextPositions(display)[line] + 2, nodeStatus, -1, false, "online");
}
drawNodes(display, x + 1, getTextPositions(display)[line] + 2, nodeStatus, -1, false, "online");
}
char uptimeStr[32] = "";
if (currentResolution != ScreenResolution::UltraLow) {
+5 -2
View File
@@ -244,10 +244,13 @@ void setReplyTo(meshtastic_MeshPacket *p, const meshtastic_MeshPacket &to)
p->decoded.request_id = to.id;
}
std::vector<MeshModule *> MeshModule::GetMeshModulesWithUIFrames()
std::vector<MeshModule *> MeshModule::GetMeshModulesWithUIFrames(int startIndex)
{
std::vector<MeshModule *> modulesWithUIFrames;
// Fill with nullptr up to startIndex
modulesWithUIFrames.resize(startIndex, nullptr);
if (modules) {
for (auto i = modules->begin(); i != modules->end(); ++i) {
auto &pi = **i;
@@ -308,4 +311,4 @@ bool MeshModule::isRequestingFocus()
} else
return false;
}
#endif
#endif
+1 -1
View File
@@ -76,7 +76,7 @@ class MeshModule
*/
static void callModules(meshtastic_MeshPacket &mp, RxSource src = RX_SRC_RADIO);
static std::vector<MeshModule *> GetMeshModulesWithUIFrames();
static std::vector<MeshModule *> GetMeshModulesWithUIFrames(int startIndex);
static void observeUIEvents(Observer<const UIFrameEvent *> *observer);
static AdminMessageHandleResult handleAdminMessageForAllModules(const meshtastic_MeshPacket &mp,
meshtastic_AdminMessage *request,
-8
View File
@@ -1989,14 +1989,6 @@ bool NodeDB::saveDeviceStateToDisk()
bool NodeDB::saveNodeDatabaseToDisk()
{
// Don't persist the node DB until this device has a PKI keypair
// TODO: revisit when https://github.com/meshtastic/firmware/pull/10478 lands
#if !(MESHTASTIC_EXCLUDE_PKI_KEYGEN || MESHTASTIC_EXCLUDE_PKI)
if (owner.public_key.size != 32 && !owner.is_licensed) {
LOG_DEBUG("Skip NodeDB without key");
return true;
}
#endif
// do not try to save anything if power level is not safe. In many cases flash will be lock-protected
// and all writes will fail anyway. Device should be sleeping at this point anyway.
+3 -5
View File
@@ -621,9 +621,7 @@ typedef enum _meshtastic_MeshPacket_TransportMechanism {
/* Arrived via Multicast UDP */
meshtastic_MeshPacket_TransportMechanism_TRANSPORT_MULTICAST_UDP = 6,
/* Arrived via API connection */
meshtastic_MeshPacket_TransportMechanism_TRANSPORT_API = 7,
/* Arrived via Unicast UDP */
meshtastic_MeshPacket_TransportMechanism_TRANSPORT_UNICAST_UDP = 8
meshtastic_MeshPacket_TransportMechanism_TRANSPORT_API = 7
} meshtastic_MeshPacket_TransportMechanism;
/* Log levels, chosen to match python logging conventions. */
@@ -1534,8 +1532,8 @@ extern "C" {
#define _meshtastic_MeshPacket_Delayed_ARRAYSIZE ((meshtastic_MeshPacket_Delayed)(meshtastic_MeshPacket_Delayed_DELAYED_DIRECT+1))
#define _meshtastic_MeshPacket_TransportMechanism_MIN meshtastic_MeshPacket_TransportMechanism_TRANSPORT_INTERNAL
#define _meshtastic_MeshPacket_TransportMechanism_MAX meshtastic_MeshPacket_TransportMechanism_TRANSPORT_UNICAST_UDP
#define _meshtastic_MeshPacket_TransportMechanism_ARRAYSIZE ((meshtastic_MeshPacket_TransportMechanism)(meshtastic_MeshPacket_TransportMechanism_TRANSPORT_UNICAST_UDP+1))
#define _meshtastic_MeshPacket_TransportMechanism_MAX meshtastic_MeshPacket_TransportMechanism_TRANSPORT_API
#define _meshtastic_MeshPacket_TransportMechanism_ARRAYSIZE ((meshtastic_MeshPacket_TransportMechanism)(meshtastic_MeshPacket_TransportMechanism_TRANSPORT_API+1))
#define _meshtastic_LogRecord_Level_MIN meshtastic_LogRecord_Level_UNSET
#define _meshtastic_LogRecord_Level_MAX meshtastic_LogRecord_Level_CRITICAL
-4
View File
@@ -1463,10 +1463,6 @@ void AdminModule::handleSetHamMode(const meshtastic_HamParameters &p)
}
channels.onConfigChanged();
if (strcmp(p.call_sign, "N0CALL") == 0) {
config.lora.tx_enabled = false;
}
service->reloadOwner(false);
saveChanges(SEGMENT_CONFIG | SEGMENT_NODEDATABASE | SEGMENT_DEVICESTATE | SEGMENT_CHANNELS);
}
-4
View File
@@ -67,11 +67,7 @@ class AdminModule : public ProtobufModule<meshtastic_AdminMessage>, public Obser
private:
bool handleSetModuleConfig(const meshtastic_ModuleConfig &c);
void handleSetChannel();
public:
void handleSetHamMode(const meshtastic_HamParameters &req);
private:
void handleStoreDeviceUIConfig(const meshtastic_DeviceUIConfig &uicfg);
void handleSendInputEvent(const meshtastic_AdminMessage_InputEvent &inputEvent);
void reboot(int32_t seconds);
+91 -145
View File
@@ -44,8 +44,6 @@ extern MessageStore messageStore;
#include "graphics/ScreenFonts.h"
#include <Throttle.h>
#include <cctype>
#include <new>
// Remove Canned message screen if no action is taken for some milliseconds
#define INACTIVATE_AFTER_MS 20000
@@ -146,36 +144,6 @@ bool hasKeyForNode(const meshtastic_NodeInfoLite *node)
{
return nodeInfoLiteHasUser(node) && node->public_key.size > 0;
}
static bool containsIgnoreCase(const char *text, const char *query)
{
if (!query || !*query)
return true;
if (!text || !*text)
return false;
const size_t queryLen = strlen(query);
for (const char *p = text; *p; ++p) {
size_t i = 0;
while (i < queryLen && p[i] &&
std::tolower(static_cast<unsigned char>(p[i])) == std::tolower(static_cast<unsigned char>(query[i]))) {
++i;
}
if (i == queryLen)
return true;
}
return false;
}
static bool activeChannelNameSeen(const std::vector<uint8_t> &activeChannelIndices, const char *name)
{
for (uint8_t channelIndex : activeChannelIndices) {
const char *existingName = channels.getName(channelIndex);
if (existingName && strcmp(existingName, name) == 0)
return true;
}
return false;
}
/**
* @brief Items in array this->messages will be set to be pointing on the right
* starting points of the string this->messageStore
@@ -187,9 +155,10 @@ int CannedMessageModule::splitConfiguredMessages()
{
int i = 0;
String canned_messages = cannedMessageModuleConfig.messages;
// Copy all message parts into the buffer
strncpy(this->messageBuffer, cannedMessageModuleConfig.messages, sizeof(this->messageBuffer) - 1);
this->messageBuffer[sizeof(this->messageBuffer) - 1] = '\0';
strncpy(this->messageBuffer, canned_messages.c_str(), sizeof(this->messageBuffer));
// Temporary array to allow for insertion
const char *tempMessages[CANNED_MESSAGE_MODULE_MESSAGE_MAX_COUNT + 3] = {0};
@@ -253,7 +222,7 @@ void CannedMessageModule::resetSearch()
{
int previousDestIndex = destIndex;
searchQuery[0] = '\0';
searchQuery = "";
updateDestinationSelectionList();
// Adjust scrollIndex so previousDestIndex is still visible
@@ -269,21 +238,26 @@ void CannedMessageModule::resetSearch()
}
void CannedMessageModule::updateDestinationSelectionList()
{
static size_t lastNumMeshNodes = 0;
static String lastSearchQuery = "";
size_t numMeshNodes = nodeDB->getNumMeshNodes();
bool nodesChanged = (numMeshNodes != cachedDestinationNodeCount);
cachedDestinationNodeCount = numMeshNodes;
bool nodesChanged = (numMeshNodes != lastNumMeshNodes);
lastNumMeshNodes = numMeshNodes;
// Early exit if nothing changed
if (destinationSelectionCacheValid && strcmp(searchQuery, cachedDestinationSearchQuery) == 0 && !nodesChanged)
if (searchQuery == lastSearchQuery && !nodesChanged)
return;
strncpy(cachedDestinationSearchQuery, searchQuery, sizeof(cachedDestinationSearchQuery) - 1);
cachedDestinationSearchQuery[sizeof(cachedDestinationSearchQuery) - 1] = '\0';
lastSearchQuery = searchQuery;
needsUpdate = false;
this->filteredNodes.clear();
this->activeChannelIndices.clear();
NodeNum myNodeNum = nodeDB->getNodeNum();
String lowerSearchQuery = searchQuery;
lowerSearchQuery.toLowerCase();
// Preallocate space to reduce reallocation
this->filteredNodes.reserve(numMeshNodes);
@@ -292,27 +266,38 @@ void CannedMessageModule::updateDestinationSelectionList()
if (!node || node->num == myNodeNum || !nodeInfoLiteHasUser(node) || node->public_key.size != 32)
continue;
const char *nodeName = node->long_name;
const char *shortName = node->short_name;
const String &nodeName = node->long_name;
if (searchQuery[0] == '\0') {
this->filteredNodes.push_back({node, sinceLastSeen(node)});
} else if (containsIgnoreCase(nodeName, searchQuery) || containsIgnoreCase(shortName, searchQuery)) {
if (searchQuery.length() == 0) {
this->filteredNodes.push_back({node, sinceLastSeen(node)});
} else {
// Avoid unnecessary lowercase conversion if already matched
String lowerNodeName = nodeName;
lowerNodeName.toLowerCase();
if (lowerNodeName.indexOf(lowerSearchQuery) != -1) {
this->filteredNodes.push_back({node, sinceLastSeen(node)});
}
}
}
meshtastic_MeshPacket *p = allocDataPacket();
p->pki_encrypted = true;
p->channel = 0;
// Populate active channels
std::vector<String> seenChannels;
seenChannels.reserve(channels.getNumChannels());
for (uint8_t i = 0; i < channels.getNumChannels(); ++i) {
const char *name = channels.getName(i);
if (name && name[0] && !activeChannelNameSeen(activeChannelIndices, name)) {
String name = channels.getName(i);
if (name.length() > 0 && std::find(seenChannels.begin(), seenChannels.end(), name) == seenChannels.end()) {
this->activeChannelIndices.push_back(i);
seenChannels.push_back(name);
}
}
scrollIndex = 0; // Show first result at the top
destIndex = 0; // Highlight the first entry
destinationSelectionCacheValid = true;
if (nodesChanged && runState == CANNED_MESSAGE_RUN_STATE_DESTINATION_SELECTION) {
LOG_INFO("Nodes changed, forcing UI refresh.");
screen->forceDisplay();
@@ -495,11 +480,7 @@ int CannedMessageModule::handleInputEvent(const InputEvent *event)
void CannedMessageModule::updateState(cannedMessageModuleRunState newState, bool shouldRequestFocus)
{
cannedMessageModuleRunState oldState = runState;
runState = newState;
if (oldState == CANNED_MESSAGE_RUN_STATE_DESTINATION_SELECTION && newState != CANNED_MESSAGE_RUN_STATE_DESTINATION_SELECTION) {
releaseDestinationSelectionCache();
}
if (runState == CANNED_MESSAGE_RUN_STATE_FREETEXT) {
inputBroker->menuMode =
false; // Allow any key input to be sent to the message composer instead of being interpreted as menu navigation
@@ -511,26 +492,6 @@ void CannedMessageModule::updateState(cannedMessageModuleRunState newState, bool
}
}
void CannedMessageModule::releaseDestinationSelectionCache()
{
searchQuery[0] = '\0';
cachedDestinationSearchQuery[0] = '\0';
cachedDestinationNodeCount = 0;
destinationSelectionCacheValid = false;
destIndex = 0;
scrollIndex = 0;
std::vector<uint8_t>().swap(activeChannelIndices);
std::vector<NodeEntry>().swap(filteredNodes);
}
void CannedMessageModule::releaseFreetext()
{
freetext.~String();
new (&freetext) String();
cursor = 0;
}
bool CannedMessageModule::isUpEvent(const InputEvent *event)
{
return event->inputEvent == INPUT_BROKER_UP ||
@@ -586,15 +547,11 @@ int CannedMessageModule::handleDestinationSelectionInput(const InputEvent *event
if (event->kbchar >= 32 && event->kbchar <= 126 && !isUp && !isDown && event->inputEvent != INPUT_BROKER_LEFT &&
event->inputEvent != INPUT_BROKER_RIGHT && event->inputEvent != INPUT_BROKER_SELECT) {
size_t queryLen = strlen(searchQuery);
if (queryLen + 1 < sizeof(searchQuery)) {
searchQuery[queryLen] = static_cast<char>(event->kbchar);
searchQuery[queryLen + 1] = '\0';
needsUpdate = true;
if ((millis() - lastFilterUpdate) > filterDebounceMs) {
runOnce(); // update filter immediately
lastFilterUpdate = millis();
}
this->searchQuery += (char)event->kbchar;
needsUpdate = true;
if ((millis() - lastFilterUpdate) > filterDebounceMs) {
runOnce(); // update filter immediately
lastFilterUpdate = millis();
}
return 1;
}
@@ -608,13 +565,12 @@ int CannedMessageModule::handleDestinationSelectionInput(const InputEvent *event
// Handle backspace
if (event->inputEvent == INPUT_BROKER_BACK) {
size_t queryLen = strlen(searchQuery);
if (queryLen > 0) {
searchQuery[queryLen - 1] = '\0';
if (searchQuery.length() > 0) {
searchQuery.remove(searchQuery.length() - 1);
needsUpdate = true;
runOnce();
}
if (searchQuery[0] == '\0') {
if (searchQuery.length() == 0) {
resetSearch();
needsUpdate = false;
}
@@ -685,7 +641,7 @@ int CannedMessageModule::handleDestinationSelectionInput(const InputEvent *event
if (event->inputEvent == INPUT_BROKER_CANCEL || event->inputEvent == INPUT_BROKER_ALT_LONG) {
updateState(returnToCannedList ? CANNED_MESSAGE_RUN_STATE_ACTIVE : CANNED_MESSAGE_RUN_STATE_FREETEXT, true);
returnToCannedList = false;
searchQuery[0] = '\0';
searchQuery = "";
// UIFrameEvent e;
// e.action = UIFrameEvent::Action::REGENERATE_FRAMESET;
@@ -715,7 +671,8 @@ bool CannedMessageModule::handleMessageSelectorInput(const InputEvent *event, bo
if (runState != CANNED_MESSAGE_RUN_STATE_INACTIVE &&
(event->inputEvent == INPUT_BROKER_CANCEL || event->inputEvent == INPUT_BROKER_ALT_LONG)) {
updateState(CANNED_MESSAGE_RUN_STATE_INACTIVE);
releaseFreetext();
freetext = "";
cursor = 0;
payload = 0;
currentMessageIndex = -1;
@@ -805,7 +762,8 @@ bool CannedMessageModule::handleMessageSelectorInput(const InputEvent *event, bo
// Return to inactive state
this->updateState(CANNED_MESSAGE_RUN_STATE_INACTIVE);
this->currentMessageIndex = -1;
this->releaseFreetext();
this->freetext = "";
this->cursor = 0;
// Force display update to show normal screen
UIFrameEvent e;
@@ -864,7 +822,8 @@ bool CannedMessageModule::handleFreeTextInput(const InputEvent *event)
// Cancel (dismiss freetext screen)
if (event->inputEvent == INPUT_BROKER_LEFT) {
updateState(CANNED_MESSAGE_RUN_STATE_INACTIVE);
releaseFreetext();
freetext = "";
cursor = 0;
payload = 0;
currentMessageIndex = -1;
@@ -987,7 +946,8 @@ bool CannedMessageModule::handleFreeTextInput(const InputEvent *event)
if (event->inputEvent == INPUT_BROKER_CANCEL || event->inputEvent == INPUT_BROKER_ALT_LONG ||
(event->inputEvent == INPUT_BROKER_BACK && this->freetext.length() == 0)) {
updateState(CANNED_MESSAGE_RUN_STATE_INACTIVE);
releaseFreetext();
freetext = "";
cursor = 0;
payload = 0;
currentMessageIndex = -1;
@@ -1227,7 +1187,8 @@ int32_t CannedMessageModule::runOnce()
UIFrameEvent e;
e.action = UIFrameEvent::Action::REGENERATE_FRAMESET;
this->currentMessageIndex = -1;
this->releaseFreetext();
this->freetext = "";
this->cursor = 0;
this->notifyObservers(&e);
return 2000;
}
@@ -1240,21 +1201,24 @@ int32_t CannedMessageModule::runOnce()
this->updateState(CANNED_MESSAGE_RUN_STATE_INACTIVE);
e.action = UIFrameEvent::Action::REGENERATE_FRAMESET;
this->currentMessageIndex = -1;
this->releaseFreetext();
this->freetext = "";
this->cursor = 0;
this->notifyObservers(&e);
}
// Handle SENDING_ACTIVE state transition after virtual keyboard message
else if (this->runState == CANNED_MESSAGE_RUN_STATE_SENDING_ACTIVE && this->payload == 0) {
this->updateState(CANNED_MESSAGE_RUN_STATE_INACTIVE);
this->currentMessageIndex = -1;
this->releaseFreetext();
this->freetext = "";
this->cursor = 0;
return INT32_MAX;
} else if (((this->runState == CANNED_MESSAGE_RUN_STATE_ACTIVE) || (this->runState == CANNED_MESSAGE_RUN_STATE_FREETEXT)) &&
!Throttle::isWithinTimespanMs(this->lastTouchMillis, INACTIVATE_AFTER_MS)) {
// Reset module on inactivity
e.action = UIFrameEvent::Action::REGENERATE_FRAMESET;
this->currentMessageIndex = -1;
this->releaseFreetext();
this->freetext = "";
this->cursor = 0;
this->updateState(CANNED_MESSAGE_RUN_STATE_INACTIVE);
// Clean up virtual keyboard if it exists during timeout
@@ -1276,7 +1240,8 @@ int32_t CannedMessageModule::runOnce()
// Clean up state but *dont* deactivate yet
this->currentMessageIndex = -1;
this->releaseFreetext();
this->freetext = "";
this->cursor = 0;
// Tell Screen to jump straight to the TextMessage frame
e.action = UIFrameEvent::Action::SWITCH_TO_TEXTMESSAGE;
@@ -1302,7 +1267,8 @@ int32_t CannedMessageModule::runOnce()
// Clean up state
this->currentMessageIndex = -1;
this->releaseFreetext();
this->freetext = "";
this->cursor = 0;
// Tell Screen to jump straight to the TextMessage frame
e.action = UIFrameEvent::Action::SWITCH_TO_TEXTMESSAGE;
@@ -1319,7 +1285,8 @@ int32_t CannedMessageModule::runOnce()
}
// fallback clean-up if nothing above returned
this->currentMessageIndex = -1;
this->releaseFreetext();
this->freetext = "";
this->cursor = 0;
e.action = UIFrameEvent::Action::REGENERATE_FRAMESET;
this->notifyObservers(&e);
@@ -1345,13 +1312,15 @@ int32_t CannedMessageModule::runOnce()
} else if (this->runState == CANNED_MESSAGE_RUN_STATE_ACTION_UP) {
if (this->messagesCount > 0) {
this->currentMessageIndex = getPrevIndex();
this->releaseFreetext();
this->freetext = "";
this->cursor = 0;
this->updateState(CANNED_MESSAGE_RUN_STATE_ACTIVE);
}
} else if (this->runState == CANNED_MESSAGE_RUN_STATE_ACTION_DOWN) {
if (this->messagesCount > 0) {
this->currentMessageIndex = this->getNextIndex();
this->releaseFreetext();
this->freetext = "";
this->cursor = 0;
this->updateState(CANNED_MESSAGE_RUN_STATE_ACTIVE);
}
} else if (this->runState == CANNED_MESSAGE_RUN_STATE_FREETEXT || this->runState == CANNED_MESSAGE_RUN_STATE_ACTIVE) {
@@ -1525,10 +1494,8 @@ void CannedMessageModule::drawKeyboard(OLEDDisplay *display, OLEDDisplayUiState
display->setColor(OLEDDISPLAY_COLOR::WHITE);
char msgWithCursor[meshtastic_Constants_DATA_PAYLOAD_LEN + 2];
cannedMessageModule->drawWithCursor(msgWithCursor, sizeof(msgWithCursor), cannedMessageModule->freetext.c_str(),
cannedMessageModule->cursor);
display->drawStringMaxWidth(0, 0, display->getWidth(), msgWithCursor);
display->drawStringMaxWidth(0, 0, display->getWidth(),
cannedMessageModule->drawWithCursor(cannedMessageModule->freetext, cannedMessageModule->cursor));
display->setFont(FONT_MEDIUM);
@@ -1714,11 +1681,8 @@ void CannedMessageModule::drawDestinationSelectionScreen(OLEDDisplay *display, O
// Header
int titleY = 2;
char titleText[64];
if (searchQuery[0])
snprintf(titleText, sizeof(titleText), "Select Destination [%s]", searchQuery);
else
snprintf(titleText, sizeof(titleText), "Select Destination [ ]");
String titleText = "Select Destination";
titleText += searchQuery.length() > 0 ? " [" + searchQuery + "]" : " [ ]";
display->setTextAlignment(TEXT_ALIGN_CENTER);
display->drawString(display->getWidth() / 2, titleY, titleText);
display->setTextAlignment(TEXT_ALIGN_LEFT);
@@ -1745,27 +1709,26 @@ void CannedMessageModule::drawDestinationSelectionScreen(OLEDDisplay *display, O
int xOffset = 0;
int yOffset = row * (FONT_HEIGHT_SMALL - 4) + rowYOffset;
char entryText[96] = "";
std::string entryText;
// Draw Channels First
if (itemIndex < numActiveChannels) {
uint8_t channelIndex = this->activeChannelIndices[itemIndex];
const char *channelName = channels.getName(channelIndex);
snprintf(entryText, sizeof(entryText), "#%s", channelName ? channelName : "?");
entryText = std::string("#") + (channelName ? channelName : "?");
}
// Then Draw Nodes
else {
int nodeIndex = itemIndex - numActiveChannels;
if (nodeIndex >= 0 && nodeIndex < static_cast<int>(this->filteredNodes.size())) {
meshtastic_NodeInfoLite *node = this->filteredNodes[nodeIndex].node;
const char *nodeName = nullptr;
if (node) {
if (display->getWidth() <= 64) {
nodeName = node->short_name;
entryText = node->short_name;
} else if (node->long_name[0]) {
nodeName = node->long_name;
entryText = node->long_name;
} else {
nodeName = node->short_name;
entryText = node->short_name;
}
}
@@ -1775,21 +1738,22 @@ void CannedMessageModule::drawDestinationSelectionScreen(OLEDDisplay *display, O
if (availWidth < 0)
availWidth = 0;
char truncatedEntry[96];
graphics::UIRenderer::truncateStringWithEmotes(display, nodeName ? nodeName : "", truncatedEntry, sizeof(truncatedEntry),
graphics::UIRenderer::truncateStringWithEmotes(display, entryText.c_str(), truncatedEntry, sizeof(truncatedEntry),
availWidth);
snprintf(entryText, sizeof(entryText), "%s", truncatedEntry);
entryText = truncatedEntry;
// Prepend "* " if this is a favorite
if (nodeInfoLiteIsFavorite(node)) {
snprintf(entryText, sizeof(entryText), "* %s", truncatedEntry);
entryText = "* " + entryText;
}
graphics::UIRenderer::truncateStringWithEmotes(display, entryText, truncatedEntry, sizeof(truncatedEntry), availWidth);
snprintf(entryText, sizeof(entryText), "%s", truncatedEntry);
graphics::UIRenderer::truncateStringWithEmotes(display, entryText.c_str(), truncatedEntry, sizeof(truncatedEntry),
availWidth);
entryText = truncatedEntry;
}
}
if (entryText[0] == '\0' || strcmp(entryText, "Unknown") == 0)
snprintf(entryText, sizeof(entryText), "?");
if (entryText.empty() || entryText == "Unknown")
entryText = "?";
// Highlight background (if selected)
if (itemIndex == destIndex) {
@@ -1799,7 +1763,7 @@ void CannedMessageModule::drawDestinationSelectionScreen(OLEDDisplay *display, O
}
// Draw entry text
graphics::UIRenderer::drawStringWithEmotes(display, xOffset + 2, yOffset, entryText, FONT_HEIGHT_SMALL, 1, false);
graphics::UIRenderer::drawStringWithEmotes(display, xOffset + 2, yOffset, entryText.c_str(), FONT_HEIGHT_SMALL, 1, false);
display->setColor(WHITE);
// Draw key icon (after highlight)
@@ -2058,9 +2022,8 @@ void CannedMessageModule::drawFrame(OLEDDisplay *display, OLEDDisplayUiState *st
display->setColor(WHITE);
{
int inputY = 0 + y + FONT_HEIGHT_SMALL;
char msgWithCursor[meshtastic_Constants_DATA_PAYLOAD_LEN + 2];
this->drawWithCursor(msgWithCursor, sizeof(msgWithCursor), this->freetext.c_str(), this->cursor);
drawWrappedEmoteText(display, x, inputY, msgWithCursor, display->getWidth() - x, FONT_HEIGHT_SMALL);
String msgWithCursor = this->drawWithCursor(this->freetext, this->cursor);
drawWrappedEmoteText(display, x, inputY, msgWithCursor.c_str(), display->getWidth() - x, FONT_HEIGHT_SMALL);
}
#endif
return;
@@ -2405,27 +2368,10 @@ void CannedMessageModule::handleSetCannedMessageModuleMessages(const char *from_
}
}
void CannedMessageModule::drawWithCursor(char *buffer, size_t bufferSize, const char *text, size_t cursor)
String CannedMessageModule::drawWithCursor(String text, int cursor)
{
if (!buffer || bufferSize == 0)
return;
const char *source = text ? text : "";
const size_t sourceLen = strlen(source);
const size_t cursorIndex = std::min(cursor, sourceLen);
const size_t beforeLen = std::min(cursorIndex, bufferSize - 1);
memcpy(buffer, source, beforeLen);
size_t outLen = beforeLen;
if (outLen < bufferSize - 1)
buffer[outLen++] = '_';
const size_t remaining = bufferSize - 1 - outLen;
const size_t afterLen = std::min(sourceLen - cursorIndex, remaining);
memcpy(buffer + outLen, source + cursorIndex, afterLen);
outLen += afterLen;
buffer[outLen] = '\0';
String result = text.substring(0, cursor) + "_" + text.substring(cursor);
return result;
}
#endif
+2 -8
View File
@@ -75,7 +75,7 @@ class CannedMessageModule : public SinglePortModule, public Observable<const UIF
void updateDestinationSelectionList();
void drawDestinationSelectionScreen(OLEDDisplay *display, OLEDDisplayUiState *state, int16_t x, int16_t y);
bool isCharInputAllowed() const;
void drawWithCursor(char *buffer, size_t bufferSize, const char *text, size_t cursor);
String drawWithCursor(String text, int cursor);
// === Emote Picker ===
int handleEmotePickerInput(const InputEvent *event);
@@ -146,8 +146,7 @@ class CannedMessageModule : public SinglePortModule, public Observable<const UIF
int visibleRows = 0;
bool needsUpdate = true;
unsigned long lastUpdateMillis = 0;
static constexpr size_t searchQuerySize = 33;
char searchQuery[searchQuerySize] = {0};
String searchQuery;
String freetext;
// === Message Storage ===
@@ -176,9 +175,6 @@ class CannedMessageModule : public SinglePortModule, public Observable<const UIF
unsigned long lastTouchMillis = 0;
uint32_t lastFilterUpdate = 0;
static constexpr uint32_t filterDebounceMs = 30;
size_t cachedDestinationNodeCount = 0;
char cachedDestinationSearchQuery[searchQuerySize] = {0};
bool destinationSelectionCacheValid = false;
std::vector<uint8_t> activeChannelIndices;
std::vector<NodeEntry> filteredNodes;
@@ -188,8 +184,6 @@ class CannedMessageModule : public SinglePortModule, public Observable<const UIF
#endif
void updateState(cannedMessageModuleRunState, bool shouldRequestFocus = false);
void releaseDestinationSelectionCache();
void releaseFreetext();
bool isUpEvent(const InputEvent *event);
bool isDownEvent(const InputEvent *event);
+7
View File
@@ -107,6 +107,10 @@
#include "modules/StatusMessageModule.h"
#endif
#if !MESHTASTIC_EXCLUDE_ZPS
#include "modules/esp32/ZPSModule.h"
#endif
#if defined(HAS_HARDWARE_WATCHDOG)
#include "watchdog/watchdogThread.h"
#endif
@@ -181,6 +185,9 @@ void setupModules()
#if !MESHTASTIC_EXCLUDE_STATUS
statusMessageModule = new StatusMessageModule();
#endif
#if !MESHTASTIC_EXCLUDE_ZPS
zpsModule = new ZPSModule();
#endif
#if !MESHTASTIC_EXCLUDE_GENERIC_THREAD_MODULE
new GenericThreadModule();
#endif
+2 -2
View File
@@ -158,8 +158,8 @@ meshtastic_MeshPacket *NodeInfoModule::allocReply()
ignoreRequest = true;
return NULL;
} else {
ignoreRequest = false; // Don't ignore requests anymore
meshtastic_User u = owner; // deliberate copy: the licensed strip below must not clobber the global owner state
ignoreRequest = false; // Don't ignore requests anymore
meshtastic_User &u = owner;
// Strip the public key if the user is licensed
if (u.is_licensed && u.public_key.size > 0) {
+25 -27
View File
@@ -193,36 +193,24 @@ void OnScreenKeyboardModule::drawPopup(OLEDDisplay *display)
display->setTextAlignment(TEXT_ALIGN_LEFT);
const uint16_t maxWrapWidth = display->width() - 40;
char lineStorage[maxContentLines + 1][64] = {};
const char *linePtrs[maxContentLines + 2] = {};
uint8_t lineCount = 0;
auto appendLine = [&](const std::string &line) {
if (line.empty() || lineCount >= maxContentLines + (hasTitle ? 1 : 0))
return;
strncpy(lineStorage[lineCount], line.c_str(), sizeof(lineStorage[lineCount]) - 1);
lineStorage[lineCount][sizeof(lineStorage[lineCount]) - 1] = '\0';
linePtrs[lineCount] = lineStorage[lineCount];
++lineCount;
};
auto wrapText = [&](const char *text, uint16_t availableWidth) {
auto wrapText = [&](const char *text, uint16_t availableWidth) -> std::vector<std::string> {
std::vector<std::string> wrapped;
std::string current;
std::string word;
const char *p = text;
while (*p && lineCount < maxContentLines + (hasTitle ? 1 : 0)) {
while (*p && wrapped.size() < maxContentLines) {
while (*p && (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r')) {
if (*p == '\n') {
if (!current.empty()) {
appendLine(current);
wrapped.push_back(current);
current.clear();
if (lineCount >= maxContentLines + (hasTitle ? 1 : 0))
if (wrapped.size() >= maxContentLines)
break;
}
}
++p;
}
if (!*p || lineCount >= maxContentLines + (hasTitle ? 1 : 0))
if (!*p || wrapped.size() >= maxContentLines)
break;
word.clear();
while (*p && *p != ' ' && *p != '\t' && *p != '\n' && *p != '\r')
@@ -235,9 +223,9 @@ void OnScreenKeyboardModule::drawPopup(OLEDDisplay *display)
current = test;
else {
if (!current.empty()) {
appendLine(current);
wrapped.push_back(current);
current = word;
if (lineCount >= maxContentLines + (hasTitle ? 1 : 0))
if (wrapped.size() >= maxContentLines)
break;
} else {
current = word;
@@ -247,26 +235,36 @@ void OnScreenKeyboardModule::drawPopup(OLEDDisplay *display)
}
}
}
if (!current.empty() && lineCount < maxContentLines + (hasTitle ? 1 : 0))
appendLine(current);
if (!current.empty() && wrapped.size() < maxContentLines)
wrapped.push_back(current);
return wrapped;
};
std::vector<std::string> allLines;
if (hasTitle)
appendLine(popupTitle);
allLines.emplace_back(popupTitle);
char buf[sizeof(popupMessage)];
strncpy(buf, popupMessage, sizeof(buf) - 1);
buf[sizeof(buf) - 1] = '\0';
char *paragraph = strtok(buf, "\n");
while (paragraph && lineCount < maxContentLines + (hasTitle ? 1 : 0)) {
wrapText(paragraph, maxWrapWidth);
while (paragraph && allLines.size() < maxContentLines + (hasTitle ? 1 : 0)) {
auto wrapped = wrapText(paragraph, maxWrapWidth);
for (const auto &ln : wrapped) {
if (allLines.size() >= maxContentLines + (hasTitle ? 1 : 0))
break;
allLines.push_back(ln);
}
paragraph = strtok(nullptr, "\n");
}
linePtrs[lineCount] = nullptr;
std::vector<const char *> ptrs;
for (const auto &ln : allLines)
ptrs.push_back(ln.c_str());
ptrs.push_back(nullptr);
// Use the standard notification box drawing from NotificationRenderer
NotificationRenderer::drawNotificationBox(display, nullptr, linePtrs, lineCount, 0, 0);
NotificationRenderer::drawNotificationBox(display, nullptr, ptrs.data(), allLines.size(), 0, 0);
}
} // namespace graphics
+1 -1
View File
@@ -21,7 +21,7 @@ void TraceRouteModule::setResultText(const String &text)
void TraceRouteModule::clearResultLines()
{
std::vector<String>().swap(resultLines);
resultLines.clear();
resultLinesDirty = false;
}
#if HAS_SCREEN
+429
View File
@@ -0,0 +1,429 @@
/*
* ZPS - Zero-GPS Positioning System for standalone Meshtastic devices
* - experimental tools for estimating own position without a GPS -
*
* Copyright 2021 all rights reserved by https://github.com/a-f-G-U-C
* Released under GPL v3 (see LICENSE file for details)
*/
#if defined(ARCH_ESP32) && !MESHTASTIC_EXCLUDE_ZPS
#include "ZPSModule.h"
#include "Default.h"
#include "MeshService.h"
#include "NodeDB.h"
#include "NodeStatus.h"
#include "Router.h"
#include "configuration.h"
#include "gps/RTC.h"
#include <WiFi.h>
#if !defined(MESHTASTIC_EXCLUDE_BLUETOOTH)
// Use the bundled NimBLE host stack directly (matching src/nimble/NimbleBluetooth.cpp).
// The external h2zero NimBLE-Arduino library (NimBLEDevice.h) is in lib_ignore since the
// pioarduino / arduino-esp32 3.x migration, so we talk to the raw host APIs instead.
#include "host/ble_gap.h"
#include "host/ble_hs.h"
#include "host/ble_hs_adv.h"
#include "host/ble_hs_id.h"
#define BLE_MAX_REC 15
#define BLE_NO_RESULTS -1 // Indicates a BLE scan is in progress
uint8_t bleCounter = 0; // used internally by the ble scanner
uint64_t bleResult[BLE_MAX_REC + 1];
int bleResSize = BLE_NO_RESULTS;
uint64_t scanStart = 0;
ZPSModule *zpsModule;
// Mini BLE scanner, NIMBLE based and modelled loosely after the Wifi scanner
static int ble_scan(uint32_t duration, bool passive = true, bool dedup = true);
// ZPSModule::ZPSModule()
// : ProtobufModule("ZPS", ZPS_PORTNUM, Position_fields), concurrency::OSThread("ZPSModule")
ZPSModule::ZPSModule() : SinglePortModule("ZPS", ZPS_PORTNUM), concurrency::OSThread("ZPSModule")
{
setIntervalFromNow(ZPS_STARTUP_DELAY); // Delay startup by 10 seconds, no need to race :)
wantBSS = true;
wantBLE = true;
WiFi.mode(WIFI_STA);
WiFi.disconnect();
WiFi.scanNetworks(true, true); // nonblock, showhidden
scanState = SCAN_BSS_RUN;
}
ProcessMessage ZPSModule::handleReceived(const meshtastic_MeshPacket &mp)
{
meshtastic_Position pos = meshtastic_Position_init_default;
auto &pd = mp.decoded;
uint8_t nRecs = pd.payload.size >> 3;
LOG_DEBUG("handleReceived %s 0x%0x->0x%0x, id=0x%x, port=%d, len=%d, rec=%d\n", name, mp.from, mp.to, mp.id, pd.portnum,
pd.payload.size, nRecs);
if (nRecs > ZPS_DATAPKT_MAXITEMS)
nRecs = ZPS_DATAPKT_MAXITEMS;
memcpy(&netData, pd.payload.bytes, nRecs << 3);
// Currently we are unable to act as a position server, so we're
// not interested in broadcasts (this will change later)
if (mp.to != nodeDB->getNodeNum()) {
// Message is not for us, won't process
return ProcessMessage::CONTINUE;
}
#ifdef ZPS_EXTRAVERBOSE
for (int i = 0; i < nRecs; i++) {
LOG_DEBUG("ZPS[%d]: %08x"
"%08x\n",
i, (uint32_t)(netData[i] >> 32), (uint32_t)netData[i]);
}
#endif
if ((netData[0] & 0x800000000000) && (nRecs >= 2)) {
// message contains a position
pos.PDOP = (netData[0] >> 40) & 0x7f;
pos.timestamp = netData[0] & 0xffffffff;
// second int64 encodes lat and lon
pos.longitude_i = (int32_t)(netData[1] & 0xffffffff);
pos.latitude_i = (int32_t)((netData[1] >> 32) & 0xffffffff);
// FIXME should be conditional, to ensure we don't overwrite a good GPS fix!
LOG_DEBUG("ZPS lat/lon/dop/pts %d/%d/%d/%d\n", pos.latitude_i, pos.longitude_i, pos.PDOP, pos.timestamp);
// Some required fields
pos.time = getTime();
pos.location_source = meshtastic_Position_LocSource_LOC_EXTERNAL;
// don't update position if my gps fix is valid
if (nodeDB->hasValidPosition(nodeDB->getMeshNode(nodeDB->getNodeNum()))) {
LOG_DEBUG("ZPSModule::handleReceived: ignoring position update, GPS is valid\n");
return ProcessMessage::CONTINUE;
}
nodeDB->updatePosition(nodeDB->getNodeNum(), pos);
} else {
// nothing we can do - for now
return ProcessMessage::CONTINUE;
}
return ProcessMessage::CONTINUE; // Let others look at this message also if they want
}
meshtastic_MeshPacket *ZPSModule::allocReply()
{
meshtastic_MeshPacket *p = allocDataPacket();
p->decoded.payload.size = (netRecs + 2) << 3; // actually can be only +1 if no GPS data
LOG_DEBUG("Allocating dataPacket for %d items, %d bytes\n", netRecs, p->decoded.payload.size);
memcpy(p->decoded.payload.bytes, &netData, p->decoded.payload.size);
return (p);
}
void ZPSModule::sendDataPacket(NodeNum dest, bool wantReplies)
{
// cancel any not yet sent (now stale) position packets
if (prevPacketId)
service->cancelSending(prevPacketId);
meshtastic_MeshPacket *p = allocReply();
p->to = dest;
p->decoded.portnum = meshtastic_PortNum_ZPS_APP;
p->decoded.want_response = wantReplies;
p->priority = meshtastic_MeshPacket_Priority_BACKGROUND;
prevPacketId = p->id;
service->sendToMesh(p, RX_SRC_LOCAL);
}
int32_t ZPSModule::runOnce()
{
meshtastic_NodeInfoLite *node = nodeDB->getMeshNode(nodeDB->getNodeNum());
assert(node);
// LOG_DEBUG("ZPSModule::runOnce() START, scanState: %d\n", (int) scanState);
int numWifi = 0;
if (scanState == SCAN_BSS_RUN) {
// check completion status of any running Wifi scan
numWifi = WiFi.scanComplete();
if (numWifi >= 0) {
// scan is complete
LOG_DEBUG("%d BSS found\n", numWifi);
LOG_DEBUG("BSS scan done in %d millis\n", millis() - scanStart);
if (wantBSS && haveBSS) {
// old data exists, overwrite it
netRecs = 0;
haveBSS = haveBLE = false;
}
for (int i = 0; i < numWifi; i++) {
// pack each Wifi network record into a 64-bit int
uint64_t netBytes = encodeBSS(WiFi.BSSID(i), WiFi.channel(i), abs(WiFi.RSSI(i)));
if (wantBSS) {
// load into outbound array if needed
outBufAdd(netBytes);
haveBSS = true;
}
#ifdef ZPS_EXTRAVERBOSE
LOG_DEBUG("BSS[%02d]: %08x"
"%08x\n",
i, (uint32_t)(netBytes >> 32), (uint32_t)netBytes);
#endif
}
WiFi.scanDelete();
scanState = SCAN_BSS_DONE;
#ifdef ZPS_EXTRAVERBOSE
} else if (numWifi == -1) {
// LOG_DEBUG("BSS scan in-progress\n");
} else {
LOG_DEBUG("BSS scan state=%d\n", numWifi);
#endif
}
}
if ((scanState == SCAN_BLE_RUN) && (bleResSize >= 0)) {
// completion status checked above (bleResSize >= 0)
LOG_DEBUG("BLE scan done in %d millis\n", millis() - scanStart);
scanState = SCAN_BLE_DONE;
if (wantBLE && haveBLE) {
// old data exists, overwrite it
netRecs = 0;
haveBSS = haveBLE = false;
}
for (int i = 0; i < bleResSize; i++) {
// load data into output array if needed
if (wantBLE) {
outBufAdd(bleResult[i]);
haveBLE = true;
}
#ifdef ZPS_EXTRAVERBOSE
LOG_DEBUG("BLE[%d]: %08x"
"%08x\n",
i, (uint32_t)(bleResult[i] >> 32), (uint32_t)bleResult[i]);
#endif
}
// Reset the counter once we're done with the dataset
bleResSize = BLE_NO_RESULTS;
}
// Are we finished assembling that packet? Then send it out
if ((wantBSS == haveBSS) && (wantBLE == haveBLE) &&
airTime->isTxAllowedChannelUtil(config.device.role != meshtastic_Config_DeviceConfig_Role_SENSOR) &&
airTime->isTxAllowedAirUtil() &&
(lastSend == 0 || millis() - lastSend >= Default::getConfiguredOrDefaultMsScaled(config.position.position_broadcast_secs,
default_broadcast_interval_secs,
nodeStatus->getNumOnline()))) {
haveBSS = haveBLE = false;
sendDataPacket(NODENUM_BROADCAST, false); // no replies
lastSend = millis();
netRecs = 0; // reset packet
}
/*
* State machine transitions
*
* FIXME could be managed better, for example: check if we require
* each type of scan (wantBSS/wantBLE), and if not, don't start it!
*/
if (scanState == SCAN_BLE_DONE) {
// BLE done, transition to BSS scanning
scanStart = millis();
LOG_DEBUG("BSS scan start t=%d\n", scanStart);
if (WiFi.scanNetworks(true, true) == WIFI_SCAN_RUNNING) // nonblock, showhidden
scanState = SCAN_BSS_RUN;
} else if (scanState == SCAN_BSS_DONE) {
// BSS done, transition to BLE scanning
scanStart = millis();
LOG_DEBUG("BLE scan start t=%d\n", scanStart);
if (ble_scan(ZPS_BLE_SCANTIME) == 0)
scanState = SCAN_BLE_RUN;
}
// LOG_DEBUG("ZPSModule::runOnce() DONE, scanState=%d\n", scanState);
if ((scanState == SCAN_BSS_RUN) || (scanState == SCAN_BLE_RUN)) {
return 1000; // scan in progress, re-check soon
}
return 5000;
}
uint64_t encodeBSS(const uint8_t *bssid, uint8_t chan, uint8_t absRSSI)
{
uint64_t netBytes = absRSSI & 0xff;
netBytes <<= 8;
netBytes |= (chan & 0xff);
for (uint8_t b = 0; b < 6; b++) {
netBytes <<= 8;
netBytes |= bssid[b];
}
return netBytes;
}
uint64_t encodeBLE(const uint8_t *addr, uint8_t absRSSI)
{
uint64_t netBytes = absRSSI & 0xff;
netBytes <<= 8;
netBytes |= 0xff; // "channel" byte reserved in BLE records
for (uint8_t b = 0; b < 6; b++) {
netBytes <<= 8;
netBytes |= addr[5 - b] & 0xff;
}
return netBytes;
}
/**
* Event handler
*/
static int ble_gap_event(struct ble_gap_event *event, void *arg)
{
// Adverts matching certain patterns are useless for positioning purposes
// (ephemeral MAC etc), so try excluding them if possible
//
// TODO: Expand the list of reject patterns for BLE adverts.
// There are likely more than 10 patterns to test and reject, including most Apple devices and others.
//
// TODO: Implement full packet search for reject patterns (use memmem() or similar),
// not just at the beginning (currently uses memcmp()).
const uint8_t rejPat[] = {0x1e, 0xff, 0x06, 0x00, 0x01}; // one of many
struct ble_hs_adv_fields fields;
int rc;
int i = 0;
uint64_t netBytes = 0;
switch (event->type) {
case BLE_GAP_EVENT_DISC:
// called once for every BLE advert received
rc = ble_hs_adv_parse_fields(&fields, event->disc.data, event->disc.length_data);
if (rc != 0)
return 0;
if (bleResSize != BLE_NO_RESULTS)
// as far as we know, we're not in the middle of a BLE scan!
LOG_DEBUG("Unexpected BLE_GAP_EVENT_DISC!\n");
#ifdef ZPS_EXTRAVERBOSE
// Dump the advertisement packet
DEBUG_PORT.hexDump("DEBUG", (unsigned char *)event->disc.data, event->disc.length_data);
#endif
// Reject beacons known to be unreliable (ephemeral etc)
if (memcmp(event->disc.data, rejPat, sizeof(rejPat)) == 0) {
LOG_DEBUG("(BLE item filtered by pattern)\n");
return 0; // Processing-wise, it's still a success
}
//
// STORE THE RESULTS IN A SORTED LIST
//
// first, pack each BLE item reading into a 64-bit int
netBytes = encodeBLE(event->disc.addr.val, abs(event->disc.rssi));
// SOME DUPLICATES SURVIVE through filter_duplicates = 1, catch them here
// Duplicate filtering is now handled in the sorting loop below,
// but right now we write for clarity not optimization
for (i = 0; i < bleCounter; i++) {
if ((bleResult[i] & 0xffffffffffff) == (netBytes & 0xffffffffffff)) {
LOG_DEBUG("(BLE duplicate filtered)\n");
return 0;
}
}
#ifdef ZPS_EXTRAVERBOSE
// redundant extraverbosity, but I need it for duplicate hunting
LOG_DEBUG("BL_[%02d]: %08x"
"%08x\n",
bleCounter, (uint32_t)(netBytes >> 32), (uint32_t)netBytes);
#endif
// then insert item into a list (up to BLE_MAX_REC records), sorted by RSSI
for (i = 0; i < bleCounter; i++) {
// find first element greater than ours, that will be our insertion point
if (bleResult[i] > netBytes)
break;
}
// any other records move down one position to vacate res[i]
for (int j = bleCounter; j > i; j--)
bleResult[j] = bleResult[j - 1];
// write new element at insertion point
bleResult[i] = netBytes;
// advance tail of list, but not beyond limit
if (bleCounter < BLE_MAX_REC)
bleCounter++;
return 0; // SUCCESS
case BLE_GAP_EVENT_DISC_COMPLETE:
LOG_DEBUG("EVENT_DISC_COMPLETE in %d millis\n", (millis() - scanStart));
LOG_DEBUG("%d BLE found\n", bleCounter);
bleResSize = bleCounter;
bleCounter = 0; // reset counter
return 0; // SUCCESS
default:
return 0; // SUCCESS
}
}
/**
* Initiates the GAP general discovery procedure (non-blocking)
*/
static int ble_scan(uint32_t duration, bool passive, bool dedup)
{
uint8_t own_addr_type;
struct ble_gap_disc_params disc_params;
int rc;
// Figure out address type to use
rc = ble_hs_id_infer_auto(0, &own_addr_type);
if (rc != 0) {
LOG_DEBUG("error determining address type; rc=%d\n", rc);
return rc;
}
// Scanning parameters, these are mostly default
disc_params.itvl = 0;
disc_params.window = 0;
disc_params.filter_policy = 0;
disc_params.limited = 0;
// These two params are the more interesting ones
disc_params.filter_duplicates = dedup; // self-explanatory
disc_params.passive = passive; // passive uses less power
// Start scanning process (non-blocking) and return
rc = ble_gap_disc(own_addr_type, duration, &disc_params, ble_gap_event, NULL);
if (rc != 0) {
LOG_DEBUG("error initiating GAP discovery; rc=%d\n", rc);
}
return rc;
}
#endif // MESHTASTIC_EXCLUDE_BLUETOOTH
#endif // ARCH_ESP32 && !MESHTASTIC_EXCLUDE_ZPS
+86
View File
@@ -0,0 +1,86 @@
#pragma once
#include "SinglePortModule.h"
#include "concurrency/OSThread.h"
#include "gps/RTC.h"
#define ZPS_PORTNUM meshtastic_PortNum_ZPS_APP
#define ZPS_DATAPKT_MAXITEMS 20 // max number of records to pack in an outbound packet (~10)
#define ZPS_STARTUP_DELAY 10000 // Module startup delay in millis
// Duration of a BLE scan in millis.
// We want this number to be SLIGHTLY UNDER an integer number of seconds,
// to be able to catch the result as fresh as possible on a 1-second polling loop
#define ZPS_BLE_SCANTIME 2900 // millis
enum SCANSTATE { SCAN_NONE, SCAN_BSS_RUN, SCAN_BSS_DONE, SCAN_BLE_RUN, SCAN_BLE_DONE };
/*
* Data packing "compression" functions
* Ingest a WiFi BSSID, channel and RSSI (or BLE address and RSSI)
* and encode them into a packed uint64
*/
uint64_t encodeBSS(const uint8_t *bssid, uint8_t chan, uint8_t absRSSI);
uint64_t encodeBLE(const uint8_t *addr, uint8_t absRSSI);
class ZPSModule : public SinglePortModule, private concurrency::OSThread
{
/// The id of the last packet we sent, to allow us to cancel it if we make something fresher
PacketId prevPacketId = 0;
/// We limit our broadcasts to a max rate
uint32_t lastSend = 0;
bool wantBSS = true;
bool haveBSS = false;
bool wantBLE = true;
bool haveBLE = false;
public:
/** Constructor
* name is for debugging output
*/
ZPSModule();
/**
* Send our radio environment data into the mesh
*/
void sendDataPacket(NodeNum dest = NODENUM_BROADCAST, bool wantReplies = false);
protected:
/** Called to handle a particular incoming message
@return true if you've guaranteed you've handled this message and no other handlers should be considered for it
*/
virtual ProcessMessage handleReceived(const meshtastic_MeshPacket &mp);
/** Messages can be received that have the want_response bit set. If set, this callback will be invoked
* so that subclasses can (optionally) send a response back to the original sender. */
virtual meshtastic_MeshPacket *allocReply();
/** Does our periodic broadcast */
virtual int32_t runOnce();
private:
// outbound data packet staging buffer and record counter
uint64_t netData[ZPS_DATAPKT_MAXITEMS + 2] = {0};
uint8_t netRecs = 0;
// mini state machine to alternate between BSS(Wifi) and BLE scanning
SCANSTATE scanState = SCAN_NONE;
inline void outBufAdd(uint64_t netBytes)
{
// If this is the first record, initialize the header with the current time and reset the record count.
if (!netRecs) {
netData[0] = getTime();
netData[1] = 0;
}
// push to buffer and update counter
if (netRecs < ZPS_DATAPKT_MAXITEMS)
netData[2 + (netRecs++)] = netBytes;
}
};
extern ZPSModule *zpsModule;
+8 -2
View File
@@ -71,6 +71,9 @@ int32_t ICM42607PSensor::runOnce()
}
return MOTION_SENSOR_CHECK_INTERVAL_MS;
#else
int16_t x = 0;
int16_t y = 0;
int16_t z = 0;
inv_imu_sensor_event_t event = {};
if (sensor == nullptr || sensor->getDataFromRegisters(event) != 0) {
@@ -82,8 +85,11 @@ int32_t ICM42607PSensor::runOnce()
return MOTION_SENSOR_CHECK_INTERVAL_MS;
}
// LOG_DEBUG("ICM-42607-P accel read x=%.3fg y=%.3fg z=%.3fg", (float)event.accel[0] / ICM42607P_COUNTS_PER_G,
// (float)event.accel[1] / ICM42607P_COUNTS_PER_G, (float)event.accel[2] / ICM42607P_COUNTS_PER_G);
x = event.accel[0];
y = event.accel[1];
z = event.accel[2];
// LOG_DEBUG("ICM-42607-P accel read x=%.3fg y=%.3fg z=%.3fg", (float)x / ICM42607P_COUNTS_PER_G,
// (float)y / ICM42607P_COUNTS_PER_G, (float)z / ICM42607P_COUNTS_PER_G);
return MOTION_SENSOR_CHECK_INTERVAL_MS;
#endif
+1 -2
View File
@@ -5,8 +5,7 @@
// meshtastic_ServiceEnvelope that automatically releases dynamically allocated memory when it goes out of scope.
struct DecodedServiceEnvelope : public meshtastic_ServiceEnvelope {
DecodedServiceEnvelope(const uint8_t *payload, size_t length);
// const-qualified so std::variant instantiation works on Apple libc++ (copying stays ill-formed either way)
DecodedServiceEnvelope(const DecodedServiceEnvelope &) = delete;
DecodedServiceEnvelope(DecodedServiceEnvelope &) = delete;
DecodedServiceEnvelope(DecodedServiceEnvelope &&);
~DecodedServiceEnvelope();
// Clients must check that this is true before using.
+3 -21
View File
@@ -40,7 +40,6 @@ constexpr uint16_t kPreferredBleTxTimeUs = (kPreferredBleTxOctets + 14) * 8;
BLECharacteristic *fromNumCharacteristic;
BLECharacteristic *BatteryCharacteristic;
static int lastBatteryLevel = -1; // last value written to 0x2A19, to skip redundant writes/notifies
BLECharacteristic *logRadioCharacteristic;
BLEServer *bleServer;
@@ -719,8 +718,6 @@ void NimbleBluetooth::deinit()
#endif
BLEDevice::deinit(true);
BatteryCharacteristic = nullptr; // freed by deinit; clear so updateBatteryLevel() won't touch it
lastBatteryLevel = -1;
#endif
}
@@ -859,31 +856,16 @@ void NimbleBluetooth::setupService()
BatteryCharacteristic = batteryService->createCharacteristic( // 0x2A19 is the Battery Level characteristic)
(uint16_t)0x2a19, BLECharacteristic::PROPERTY_READ | BLECharacteristic::PROPERTY_NOTIFY);
BatteryCharacteristic->addDescriptor(batteryLevelDescriptor);
// Seed an initial 0-100 level so an early read of 0x2A19 returns a valid value.
uint8_t initialLevel = (powerStatus && powerStatus->getHasBattery()) ? powerStatus->getBatteryChargePercent() : 0;
if (initialLevel > 100)
initialLevel = 100;
BatteryCharacteristic->setValue(&initialLevel, 1);
lastBatteryLevel = initialLevel;
batteryService->start();
}
/// Given a level between 0-100, update the BLE attribute
void updateBatteryLevel(uint8_t level)
{
if (!config.bluetooth.enabled || !BatteryCharacteristic)
return;
if (level > 100) // 0x2A19 must stay within the BAS 0-100 range
level = 100;
if (level == lastBatteryLevel)
return;
lastBatteryLevel = level;
// Cache the value so a READ works without a subscriber; notify only when connected.
BatteryCharacteristic->setValue(&level, 1);
if (nimbleBluetooth && nimbleBluetooth->isConnected())
if ((config.bluetooth.enabled == true) && nimbleBluetooth && nimbleBluetooth->isConnected()) {
BatteryCharacteristic->setValue(&level, 1);
BatteryCharacteristic->notify();
}
}
void NimbleBluetooth::clearBonds()
+2 -12
View File
@@ -15,9 +15,8 @@ static BLECharacteristic fromRadio = BLECharacteristic(BLEUuid(FROMRADIO_UUID_16
static BLECharacteristic toRadio = BLECharacteristic(BLEUuid(TORADIO_UUID_16));
static BLECharacteristic logRadio = BLECharacteristic(BLEUuid(LOGRADIO_UUID_16));
static BLEDis bledis; // DIS (Device Information Service) helper class instance
static BLEBas blebas; // BAS (Battery Service) helper class instance
static int lastBatteryLevel = -1; // last value written to BAS, to skip redundant writes/notifies
static BLEDis bledis; // DIS (Device Information Service) helper class instance
static BLEBas blebas; // BAS (Battery Service) helper class instance
#ifndef BLE_DFU_SECURE
static BLEDfu bledfu; // DFU software update helper service
#else
@@ -337,7 +336,6 @@ void NRF52Bluetooth::setup()
LOG_INFO("Init the Battery Service");
blebas.begin();
blebas.write(0); // Unknown battery level for now
lastBatteryLevel = 0;
// Setup the Heart Rate Monitor service using
// BLEService and BLECharacteristic classes
LOG_INFO("Init the Mesh bluetooth service");
@@ -357,14 +355,6 @@ void NRF52Bluetooth::resumeAdvertising()
/// Given a level between 0-100, update the BLE attribute
void updateBatteryLevel(uint8_t level)
{
if (!nrf52Bluetooth) // skip until the Battery Service has been begun in setup()
return;
if (level > 100) // BAS battery level must stay within 0-100
level = 100;
if (level == lastBatteryLevel)
return;
lastBatteryLevel = level;
blebas.write(level);
}
void NRF52Bluetooth::clearBonds()
-2
View File
@@ -85,8 +85,6 @@
#define HW_VENDOR meshtastic_HardwareModel_T_ECHO
#elif defined(T_ECHO_LITE)
#define HW_VENDOR meshtastic_HardwareModel_T_ECHO_LITE
#elif defined(T_ECHO_CARD)
#define HW_VENDOR meshtastic_HardwareModel_T_ECHO_CARD
#elif defined(TTGO_T_ECHO_PLUS)
#define HW_VENDOR meshtastic_HardwareModel_T_ECHO_PLUS
#elif defined(ELECROW_ThinkNode_M1)
@@ -1,5 +1,4 @@
#include "TestUtil.h"
#include <cstdlib>
#include <unity.h>
static void test_placeholder()
@@ -1,5 +1,4 @@
#include "TestUtil.h"
#include <cstdlib>
#include <unity.h>
#if defined(ARCH_PORTDUINO)
+1
View File
@@ -14,6 +14,7 @@ platform_packages =
extra_scripts =
${env.extra_scripts}
pre:extra_scripts/esp32_pre.py
pre:extra_scripts/zps_observer.py
extra_scripts/esp32_extra.py
build_src_filter =
-10
View File
@@ -1,17 +1,7 @@
[env:tlora-c6]
custom_meshtastic_hw_model = 83
custom_meshtastic_hw_model_slug = TLORA_C6
custom_meshtastic_architecture = esp32-c6
custom_meshtastic_actively_supported = true
custom_meshtastic_support_level = 1
custom_meshtastic_display_name = LilyGo T3-C6
custom_meshtastic_images = tlora-c6.svg
custom_meshtastic_tags = LilyGo
extends = esp32c6_base
board = esp32-c6-devkitm-1
board_level = pr
build_flags =
${esp32c6_base.build_flags}
-D TLORA_C6
+1
View File
@@ -12,6 +12,7 @@
#define LORA_RESET 21
#define SX126X_CS LORA_CS
#define SX126X_DIO1 23
#define SX126X_DIO2 20
#define SX126X_BUSY 22
#define SX126X_RESET LORA_RESET
#define SX126X_RXEN 15
@@ -1,5 +0,0 @@
void initVariant()
{
pinMode(LED_PAIRING, OUTPUT);
digitalWrite(LED_PAIRING, !LED_STATE_ON); // Turn off the LED to start
}
@@ -6,12 +6,11 @@
#define UART_TX 43
#define UART_RX 44
#define LED_PAIRING 46
#define LED_LORA 46
#define WIFI_LED 3
#define WIFI_STATE_ON 0
#define LED_PIN 3
#define LED_PIN 46
#define LED_STATE_ON 0
#define LED_STATE_OFF 1
#define BUTTON_PIN 4
#define BUTTON_ACTIVE_LOW true
#define BUTTON_ACTIVE_PULLUP true
+1
View File
@@ -55,6 +55,7 @@ build_flags_common =
-lyaml-cpp
-ljsoncpp
!pkg-config --cflags jsoncpp --silence-errors || :
-li2c
-luv
-std=gnu17
-std=gnu++17
-3
View File
@@ -14,7 +14,6 @@ platform_packages =
extra_scripts =
${env.extra_scripts}
extra_scripts/nrf52_extra.py
pre:extra_scripts/nrf52_lto.py
build_type = release
build_flags =
@@ -27,8 +26,6 @@ build_flags =
-DMESHTASTIC_EXCLUDE_PAXCOUNTER=1
-Os
-std=gnu++17
-flto ; whole-image LTO (~-60KB) on every nrf52840 target; nrf52_lto.py (pre: extra_script) keeps the interrupt handlers out of LTO so they survive
-fmerge-all-constants ; fold identical constants image-wide (~0.7KB; same flag stm32 uses)
build_unflags =
-Ofast
-Og
@@ -6,6 +6,7 @@ debug_tool = jlink
build_flags = ${nrf52840_base.build_flags}
-I variants/nrf52840/t-echo-card
-D PRIVATE_HW
-D T_ECHO_CARD
build_src_filter = ${nrf52_base.build_src_filter} +<../variants/nrf52840/t-echo-card>