From 434e306430b9075e67d9648c61deca75db3f3177 Mon Sep 17 00:00:00 2001 From: TeTeHacko Date: Sat, 11 Jul 2026 19:21:11 +0200 Subject: [PATCH] feat: expose repeater text console over BLE + nRF52 SoftDevice fixes Co-Authored-By: Claude Opus 4.8 --- boards/nrf52840_s140_v7_extrafs.ld | 5 +- examples/simple_repeater/MyMesh.cpp | 6 + examples/simple_repeater/main.cpp | 191 +++++++++++++++++++++++++ src/helpers/ArduinoSerialInterface.cpp | 8 +- src/helpers/NRF52Board.cpp | 15 ++ 5 files changed, 222 insertions(+), 3 deletions(-) diff --git a/boards/nrf52840_s140_v7_extrafs.ld b/boards/nrf52840_s140_v7_extrafs.ld index 5956183a..75b746a8 100644 --- a/boards/nrf52840_s140_v7_extrafs.ld +++ b/boards/nrf52840_s140_v7_extrafs.ld @@ -14,7 +14,10 @@ MEMORY * - Concurrent connection peripheral + central + secure links * - Event Len, HVN queue, Write CMD queue */ - RAM (rwx) : ORIGIN = 0x20006000, LENGTH = 0x20040000 - 0x20006000 + /* CUSTOM (TeTeHacko): reserve 16 B at the end of RAM for a hardfault record + * (PC/LR survive soft reset, printed on next boot) — see HardFault_Handler + * in the framework and the boot-time printout in main.cpp. */ + RAM (rwx) : ORIGIN = 0x20006000, LENGTH = 0x2003FFF0 - 0x20006000 } SECTIONS diff --git a/examples/simple_repeater/MyMesh.cpp b/examples/simple_repeater/MyMesh.cpp index 09690749..f243e02d 100644 --- a/examples/simple_repeater/MyMesh.cpp +++ b/examples/simple_repeater/MyMesh.cpp @@ -1258,6 +1258,12 @@ void MyMesh::handleCommand(uint32_t sender_timestamp, char *command, char *reply strcpy(reply, "OK - Discover sent"); } } else{ +#if defined(BLE_PIN_CODE) && defined(NRF52_PLATFORM) + // CUSTOM (TeTeHacko): `ble on|off|ble` — implemented in main.cpp (BLE console). + // Available from serial, the BLE console and remotely via MC (admin remote CLI). + extern bool bleConsoleHandleCommand(const char* command, char* reply); + if (bleConsoleHandleCommand(command, reply)) return; +#endif _cli.handleCommand(sender_timestamp, command, reply); // common CLI commands } } diff --git a/examples/simple_repeater/main.cpp b/examples/simple_repeater/main.cpp index 2ce056f5..4c2e55aa 100644 --- a/examples/simple_repeater/main.cpp +++ b/examples/simple_repeater/main.cpp @@ -3,6 +3,97 @@ #include "MyMesh.h" +#if defined(BLE_PIN_CODE) && defined(NRF52_PLATFORM) + // CUSTOM (TeTeHacko): exposes the repeater text console over BLE Nordic-UART + // so the node can be queried wirelessly (advert, neighbor list with SNR) + // without USB. Enabled by the BLE_PIN_CODE build flag; otherwise no change. + #include + static BLEUart bleuart; + static BLEDfu bledfu; + #define _MC_STR2(x) #x + #define _MC_STR(x) _MC_STR2(x) + #ifndef BLE_DEVICE_NAME + #define BLE_DEVICE_NAME ADVERT_NAME + #endif + // CUSTOM (TeTeHacko): reliable send over BLE UART. + // When the SoftDevice notification queue is full, Bluefruit bleuart.write() + // returns fewer bytes and silently DROPS the rest (non-blocking), so long + // replies spanning multiple notifications (neighbors/stats-*) get truncated. + // Fix: send in <=20 B chunks (1 notification) + retry unwritten bytes with a + // short pause. The stall guard is bounded so this can NEVER block the main + // loop for long (watchdog would reset otherwise). + // WARNING: do NOT call bleuart.flushTXD() — without bufferTXD(true) _tx_fifo + // is NULL and flushTXD() dereferences it → memory corruption/HardFault (this + // was the observed lockup). In unbuffered mode write() notifies immediately, + // no flush needed. + static void bleWriteAll(const char* s) { + size_t n = strlen(s), i = 0; uint32_t stall = 0; + while (i < n && Bluefruit.connected() && stall < 300) { // max ~0.9 s stall → bail + size_t chunk = n - i; if (chunk > 20) chunk = 20; + size_t w = bleuart.write((const uint8_t*)(s + i), chunk); + if (w > 0) { i += w; stall = 0; } + else { stall++; delay(3); } // queue full -> wait a moment and retry + } + } + + // CUSTOM (TeTeHacko): runtime BLE on/off via `ble on|off|ble` command + // (works from serial, the BLE console AND REMOTELY from the MC app — admin + // remote CLI). State is persistent (marker file in InternalFS), so BLE stays + // off even across watchdog reboots on the mast; `ble on` sent over MC wakes + // it up for OTA. + #include + #define BLE_OFF_MARKER "/ble_off" + static bool ble_enabled = true; + static bool ble_toggle_target = true; + static unsigned long ble_toggle_at = 0; // deferred apply so the reply can go out first + + static void blePersist(bool on) { + if (on) { + InternalFS.remove(BLE_OFF_MARKER); + } else { + auto f = InternalFS.open(BLE_OFF_MARKER, Adafruit_LittleFS_Namespace::FILE_O_WRITE); + if (f) { f.write((uint8_t)'1'); f.close(); } + } + } + + static void bleApply(bool on) { + if (on) { + Bluefruit.Advertising.restartOnDisconnect(true); + if (!Bluefruit.Advertising.isRunning()) Bluefruit.Advertising.start(0); + } else { + Bluefruit.Advertising.restartOnDisconnect(false); + if (Bluefruit.Advertising.isRunning()) Bluefruit.Advertising.stop(); + for (uint16_t h = 0; h < BLE_MAX_CONNECTION; h++) { + BLEConnection* c = Bluefruit.Connection(h); + if (c && c->connected()) c->disconnect(); + } + } + } + + // called from MyMesh::handleCommand (serial, BLE console and mesh admin CLI) + bool bleConsoleHandleCommand(const char* command, char* reply) { + if (strcmp(command, "ble on") == 0) { + ble_enabled = true; blePersist(true); + ble_toggle_target = true; ble_toggle_at = millis() + 1500; + strcpy(reply, "OK - BLE on (persistent)"); + return true; + } + if (strcmp(command, "ble off") == 0) { + ble_enabled = false; blePersist(false); + ble_toggle_target = false; ble_toggle_at = millis() + 1500; + strcpy(reply, "OK - BLE off (persistent)"); + return true; + } + if (strcmp(command, "ble") == 0) { + sprintf(reply, "BLE: %s%s", ble_enabled ? "on" : "off", + Bluefruit.connected() ? " (connected)" + : (Bluefruit.Advertising.isRunning() ? " (advertising)" : "")); + return true; + } + return false; + } +#endif + #ifdef DISPLAY_CLASS #include "UITask.h" static UITask ui_task(display); @@ -39,6 +130,20 @@ void setup() { delay(5000); #endif +#if defined(NRF52_PLATFORM) + // CUSTOM (TeTeHacko diagnostics): print the hardfault record saved by the + // patched HardFault_Handler (framework debug.cpp) before the last reset. + // 16 B at the end of RAM, reserved in nrf52840_s140_v7_extrafs.ld. + { + volatile uint32_t* hf = (volatile uint32_t*)0x2003FFF0; + if (hf[0] == 0xFA010DEB) { + Serial.printf("!!! HARDFAULT before last reboot: PC=%08lX LR=%08lX PSR=%08lX\n", + (unsigned long)hf[1], (unsigned long)hf[2], (unsigned long)hf[3]); + hf[0] = 0; + } + } +#endif + #ifdef DISPLAY_CLASS if (display.begin()) { display.startFrame(); @@ -100,10 +205,82 @@ void setup() { the_mesh.sendSelfAdvertisement(16000, false); #endif +#if defined(BLE_PIN_CODE) && defined(NRF52_PLATFORM) + // BLE UART console (PIN pairing). Runs alongside normal repeater duty. + Bluefruit.begin(); + Bluefruit.setTxPower(8); // +8 dBm = nRF52840 max (range to the dongle across the balcony) + Bluefruit.setName(BLE_DEVICE_NAME); + Bluefruit.Security.setPIN(_MC_STR(BLE_PIN_CODE)); + // Without setPermission the characteristics stay SECMODE_OPEN and the PIN is + // never enforced -> the admin console would be open to anyone in range. Same + // pattern as SerialBLEInterface.cpp (companion). + bledfu.setPermission(SECMODE_ENC_WITH_MITM, SECMODE_ENC_WITH_MITM); + bledfu.begin(); + bleuart.setPermission(SECMODE_ENC_WITH_MITM, SECMODE_ENC_WITH_MITM); + bleuart.begin(); + Bluefruit.Advertising.addFlags(BLE_GAP_ADV_FLAGS_LE_ONLY_GENERAL_DISC_MODE); + Bluefruit.Advertising.addTxPower(); + Bluefruit.Advertising.addService(bleuart); + Bluefruit.ScanResponse.addName(); + Bluefruit.Advertising.setInterval(32, 244); + Bluefruit.Advertising.setFastTimeout(30); + // persistent BLE state: with the marker present keep BLE dark (see `ble on|off`) + ble_enabled = !InternalFS.exists(BLE_OFF_MARKER); + if (ble_enabled) { + Bluefruit.Advertising.restartOnDisconnect(true); + Bluefruit.Advertising.start(0); + Serial.println("BLE UART console started"); + } else { + Bluefruit.Advertising.restartOnDisconnect(false); + Serial.println("BLE UART console disabled (ble off)"); + } +#endif + board.onBootComplete(); + +#if defined(NRF52_PLATFORM) + // CUSTOM (TeTeHacko): hardware watchdog. If the main loop freezes COMPLETELY + // (observed with BLE/SoftDevice — even serial dies, only reset helps), the + // chip resets itself after ~20 s and the repeater comes back — no physical + // reset needed (it lives on a mast). + // SLEEP=Pause -> WDT only counts while the CPU runs -> no resets during + // power-saving sleep (no false positives). A freeze = CPU spinning/fault. + // HALT=Pause -> does not get in the debugger's way. The Adafruit bootloader + // feeds the WDT during DFU -> OTA stays safe. + NRF_WDT->CONFIG = (WDT_CONFIG_HALT_Pause << WDT_CONFIG_HALT_Pos) + | (WDT_CONFIG_SLEEP_Pause << WDT_CONFIG_SLEEP_Pos); + NRF_WDT->CRV = 20 * 32768 - 1; // ~20 s timeout (LFCLK 32.768 kHz) + NRF_WDT->RREN = (WDT_RREN_RR0_Enabled << WDT_RREN_RR0_Pos); // reload register 0 + NRF_WDT->TASKS_START = 1; +#endif } void loop() { +#if defined(NRF52_PLATFORM) + NRF_WDT->RR[0] = WDT_RR_RR_Reload; // feed the HW watchdog (setup); if the loop freezes the chip resets in ~20 s +#endif +#if defined(BLE_PIN_CODE) && defined(NRF52_PLATFORM) + // CUSTOM (TeTeHacko): deferred apply of `ble on|off` — the reply still goes + // out over the old path, only then advertising/connections get switched. + if (ble_toggle_at && (long)(millis() - ble_toggle_at) >= 0) { + ble_toggle_at = 0; + bleApply(ble_toggle_target); + } + // CUSTOM (TeTeHacko): BLE watchdog. Observed: the repeater stops advertising + // after a while (SoftDevice/LoRa coexistence) and only a reset helps. Every + // 5 s check: if not connected and not advertising, restart advertising — + // without needing a physical reset. Respects `ble off`. + { + static unsigned long _lastAdvChk = 0; + if ((unsigned long)(millis() - _lastAdvChk) >= 5000) { + _lastAdvChk = millis(); + if (ble_enabled && ble_toggle_at == 0 + && Bluefruit.connected() == 0 && !Bluefruit.Advertising.isRunning()) { + Bluefruit.Advertising.start(0); + } + } + } +#endif int len = strlen(command); while (Serial.available() && len < sizeof(command)-1) { char c = Serial.read(); @@ -114,6 +291,17 @@ void loop() { } if (c == '\r') break; } +#if defined(BLE_PIN_CODE) && defined(NRF52_PLATFORM) + // same console from BLE UART too (commands share the buffer) + while (bleuart.available() && len < (int)sizeof(command)-1) { + char c = (char) bleuart.read(); + if (c != '\n') { + command[len++] = c; + command[len] = 0; + } + if (c == '\r') break; + } +#endif if (len == sizeof(command)-1) { // command buffer full command[sizeof(command)-1] = '\r'; } @@ -125,6 +313,9 @@ void loop() { the_mesh.handleCommand(0, command, reply); // NOTE: there is no sender_timestamp via serial! if (reply[0]) { Serial.print(" -> "); Serial.println(reply); +#if defined(BLE_PIN_CODE) && defined(NRF52_PLATFORM) + bleWriteAll(" -> "); bleWriteAll(reply); bleWriteAll("\r\n"); +#endif } command[0] = 0; // reset command buffer diff --git a/src/helpers/ArduinoSerialInterface.cpp b/src/helpers/ArduinoSerialInterface.cpp index a01fa586..2412edc7 100644 --- a/src/helpers/ArduinoSerialInterface.cpp +++ b/src/helpers/ArduinoSerialInterface.cpp @@ -13,8 +13,12 @@ void ArduinoSerialInterface::disable() { _isEnabled = false; } -bool ArduinoSerialInterface::isConnected() const { - return true; // no way of knowing, so assume yes +bool ArduinoSerialInterface::isConnected() const { +#if defined(NRF52_PLATFORM) || defined(ESP32_PLATFORM) + return Serial; // operator bool() checks connection (USB CDC DTR, UART init) +#else + return true; // platforms without operator bool() on Serial have no way of knowing, so assume yes +#endif } bool ArduinoSerialInterface::isWriteBusy() const { diff --git a/src/helpers/NRF52Board.cpp b/src/helpers/NRF52Board.cpp index 17265f04..b9082a89 100644 --- a/src/helpers/NRF52Board.cpp +++ b/src/helpers/NRF52Board.cpp @@ -279,6 +279,21 @@ void NRF52Board::sleep(uint32_t secs) { // Temperature from NRF52 MCU float NRF52Board::getMCUTemperature() { + // With the SoftDevice enabled, TEMP is a SoftDevice-protected peripheral + // (the SD uses it for RC oscillator calibration). Direct register access + // raises an APP_MEMACC SoftDevice fault -> firmware reboot. This is why + // BLE-enabled repeater builds crashed on every telemetry request. Use the + // sd_temp_get() SVC in that case. + uint8_t sd_enabled = 0; + sd_softdevice_is_enabled(&sd_enabled); + if (sd_enabled) { + int32_t temp; + if (sd_temp_get(&temp) == NRF_SUCCESS) { + return temp * 0.25f; // Convert to *C + } + return NAN; + } + NRF_TEMP->TASKS_START = 1; // Start temperature measurement long startTime = millis();