#include // needed for PlatformIO #include #include "MyMesh.h" #include // =========================================================================== // CUSTOM (TeTeHacko): `blink [n]` -- make THIS board flash its LED on demand, // so a bench full of identical boards can be told apart and labelled. // // The problem it solves: nothing else identifies a board in situ. The USB // serial number is only readable over a data cable (and boards sharing power // rails have none), the BLE MAC is not printed anywhere, and ADVERT_NAME is // only as trustworthy as the last flash -- which is exactly what you are trying // to confirm. Two boards here were both advertising "bench-board". // // It deliberately does NOT use the status LED. On XIAO that is LED_BLUE // (PIN_STATUS_LED), which Bluefruit drives as its connection indicator, so // every BLE node blinks blue identically and a blink there would be lost in the // noise. LED_GREEN is untouched by the library, so a green burst is unambiguous. // // Ticked from loop() rather than looping inline: a blocking blink would stall // the mesh for the whole burst (up to ~7 s at the 30-blink cap) and disturb the // LoRa RX/TX timing the test fleet exists to measure. // =========================================================================== // Pick an LED nothing else drives, in that order of preference: // LED_GREEN -- XIAO (13). Free; LED_BLUE there is Bluefruit's connection LED. // LED_WHITE -- SenseCap Solar (11). Only ever set LOW at boot and at // powerOff(), so a burst on it is unambiguous. // LED_BUILTIN -- last resort. On SenseCap this is pin 12 = LED_BLUE = the LoRa // TX indicator, so a blink there competes with live traffic; // workable, but that is why it is last. // A variant may DEFINE a colour it does not physically have by pointing it at // PINS_COUNT (SenseCap does exactly that with LED_RED), so #ifdef alone is not // enough -- the range check below is what actually proves the pin exists. #ifndef RPT_IDENT_LED_PIN #if defined(LED_GREEN) && (LED_GREEN < PINS_COUNT) #define RPT_IDENT_LED_PIN LED_GREEN #elif defined(LED_WHITE) && (LED_WHITE < PINS_COUNT) #define RPT_IDENT_LED_PIN LED_WHITE #elif defined(LED_BUILTIN) && (LED_BUILTIN < PINS_COUNT) #define RPT_IDENT_LED_PIN LED_BUILTIN #endif #endif #ifndef RPT_IDENT_LED_MS #define RPT_IDENT_LED_MS 120 // half-period; 120 ms reads as a clear flash #endif // `blink on` keeps going until `blink off`, because a fixed burst is a race // against how long it takes to walk to the bench -- the first version capped at // 30 blinks (~7 s) and that was not enough to find the board. Held blinking // still expires on its own: a node left blinking would quietly eat a battery, // and on a mounted node nobody would notice. #ifndef RPT_IDENT_HOLD_MS #define RPT_IDENT_HOLD_MS (10UL * 60UL * 1000UL) // 10 min #endif #ifdef RPT_IDENT_LED_PIN static uint16_t ident_edges_left = 0; // remaining on/off transitions static bool ident_led_on = false; static unsigned long ident_next_ms = 0; static bool ident_pin_ready = false; static bool ident_hold = false; // blink until told to stop static unsigned long ident_hold_until = 0; // LED_STATE_ON is 0 on XIAO (active low) and 1 elsewhere; go through it rather // than hard-coding HIGH/LOW, or the "blink" is an unlit board on half the fleet. static inline void identLedWrite(bool on) { digitalWrite(RPT_IDENT_LED_PIN, on ? LED_STATE_ON : !LED_STATE_ON); } static void identBegin() { if (!ident_pin_ready) { pinMode(RPT_IDENT_LED_PIN, OUTPUT); ident_pin_ready = true; } ident_led_on = true; identLedWrite(true); ident_next_ms = millis() + RPT_IDENT_LED_MS; } static void identStart(int blinks) { if (blinks < 1) blinks = 1; if (blinks > 999) blinks = 999; ident_hold = false; ident_edges_left = (uint16_t)(blinks * 2); // one on + one off per blink identBegin(); } static void identHold(bool on) { ident_hold = on; ident_edges_left = 0; if (on) { ident_hold_until = millis() + RPT_IDENT_HOLD_MS; identBegin(); } else if (ident_pin_ready) { identLedWrite(false); } } static void identStop() { identHold(false); } static void identTick() { if (ident_hold) { if ((long)(millis() - ident_hold_until) >= 0) { identStop(); return; } } else if (ident_edges_left == 0) { return; } if ((long)(millis() - ident_next_ms) < 0) return; if (!ident_hold) { ident_edges_left--; if (ident_edges_left == 0) { identLedWrite(false); // always finish dark, never leave it lit return; } } ident_led_on = !ident_led_on; identLedWrite(ident_led_on); ident_next_ms = millis() + RPT_IDENT_LED_MS; } #endif // RPT_IDENT_LED_PIN // Reachable from serial, the BLE console AND the mesh admin CLI, so a node that // is already mounted can still be asked to identify itself. bool identHandleCommand(const char* command, char* reply) { if (memcmp(command, "blink", 5) != 0 || (command[5] != 0 && command[5] != ' ')) return false; #ifdef RPT_IDENT_LED_PIN const char* arg = (command[5] == ' ') ? &command[6] : ""; while (*arg == ' ') arg++; if (strcmp(arg, "on") == 0) { identHold(true); sprintf(reply, "OK - blinking until `blink off` (or %lu min)", (unsigned long)(RPT_IDENT_HOLD_MS / 60000UL)); } else if (strcmp(arg, "off") == 0) { identStop(); strcpy(reply, "OK - blinking off"); } else { int n = arg[0] ? atoi(arg) : 6; if (n < 1) n = 6; if (n > 999) n = 999; identStart(n); sprintf(reply, "OK - blinking %d times", n); } #else strcpy(reply, "ERR: no spare LED on this board"); #endif return true; } #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, without ever blocking the // main loop. Bluefruit bleuart.write() is non-blocking: when the SoftDevice // notification queue is full it returns 0 and silently DROPS the rest, so // long replies (nodes/rxlog/stats-*) got truncated; the earlier retry loop // fixed truncation but stalled loop() up to ~0.9 s per call — enough to // disturb LoRa RX/TX timing while a client streams the console. Now // bleWriteAll() only copies into a ring buffer and bleTxPump() (called every // loop() pass) hands the SoftDevice as much as it will take right now, never // waiting. On overflow the NEWEST bytes are cut (a torn page keeps its 'E,' // trailer framing wrong -> the bridge just re-requests the same cursor). // 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. #define BLE_TXRING_SIZE 4096 // power of 2; >= " -> " + reply[1032] + CRLF with slack static uint8_t ble_txring[BLE_TXRING_SIZE]; static size_t ble_tx_head = 0, ble_tx_tail = 0; // enqueue + pump both run in loop(): no locking static void bleWriteAll(const char* s) { if (!Bluefruit.connected()) return; size_t used = (ble_tx_head - ble_tx_tail) & (BLE_TXRING_SIZE - 1); size_t space = BLE_TXRING_SIZE - 1 - used; size_t n = strlen(s); if (n > space) n = space; // overflow -> truncate newest (see comment above) for (size_t i = 0; i < n; i++) { ble_txring[ble_tx_head] = (uint8_t)s[i]; ble_tx_head = (ble_tx_head + 1) & (BLE_TXRING_SIZE - 1); } } // True while the console still has bytes to hand to the SoftDevice. The // powersaving sleep must consult this: WFE only wakes on an interrupt, and a // half-drained page would then sit in the ring until the next connection // event instead of going out on this pass. On the observer node the bridge // drains paged output (rxlog/pktlog) in a 2-minute duty cycle, so a slower // drain directly costs collected frames. static bool bleTxPending() { return ble_tx_tail != ble_tx_head; } static void bleTxPump() { if (ble_tx_tail == ble_tx_head) return; if (!Bluefruit.connected()) { ble_tx_tail = ble_tx_head; return; } // client gone -> drop // chunk = ATT payload (MTU-3); bridge negotiates MTU 247 -> 244 B chunks. // Fallback 20 B when MTU stayed at the 23 B default (unpaired phone etc.). size_t maxchunk = 20; BLEConnection* conn = Bluefruit.Connection(Bluefruit.connHandle()); if (conn && conn->getMtu() > 23) maxchunk = conn->getMtu() - 3; while (ble_tx_tail != ble_tx_head) { size_t avail = (ble_tx_head - ble_tx_tail) & (BLE_TXRING_SIZE - 1); size_t chunk = avail; if (chunk > maxchunk) chunk = maxchunk; size_t run = BLE_TXRING_SIZE - ble_tx_tail; // stop at ring wrap; rest goes next write if (chunk > run) chunk = run; size_t w = bleuart.write(&ble_txring[ble_tx_tail], chunk); if (w == 0) break; // SoftDevice queue full -> retry next loop() pass ble_tx_tail = (ble_tx_tail + w) & (BLE_TXRING_SIZE - 1); } } // CUSTOM (TeTeHacko): BLE connection tuning to stop the reconnect churn. The // Bluefruit default supervision timeout is only 2 s, and THIS node also relays // heavy LoRa flood traffic: measured behaviour is a periodic (~60 s) multi- // second stall (advert TX airtime / SoftDevice-LoRa coexistence). 2 s dropped // every 15-30 s, 6 s every ~60 s -> the stall occasionally exceeds 6 s. Widen // the supervision timeout to 16 s so those stalls are tolerated; a genuine // freeze is still caught by the 20 s hardware watchdog (16 s < 20 s). Like the // companion, request the params explicitly on 'secured' (some centrals ignore // the advertised PPCP). // Interval 60-80 ms (was 15-30 ms): a controlled A/B test (21 Jul 2026) showed // ~40 % of DIRECT-route LoRa forwards silently lost with an IDLE BLE // connection at 15-30 ms — the SoftDevice's per-event preemption disturbs the // SX126x TX path (startTransmit fail / send-complete timeout). Fewer // connection events = proportionally fewer collisions; the Dispatcher TX // retry (MESH_TX_RETRIES) covers the rest. Console throughput drops ~3x, // which the duty-cycled bridge tolerates fine. // Overridable so the pre-fix 15-30 ms interval (12/24 in 1.25 ms units) can be // rebuilt as a POSITIVE CONTROL: a measurement that reads zero in both the // treatment and the control has not shown it can detect anything. Reproducing // the known-bad interval proves the harness is sensitive before "no loss on the // fixed build" is allowed to mean anything. #ifndef RPT_BLE_MIN_CONN_INTERVAL #define RPT_BLE_MIN_CONN_INTERVAL 48 // 60 ms (1.25 ms units) #endif #ifndef RPT_BLE_MAX_CONN_INTERVAL #define RPT_BLE_MAX_CONN_INTERVAL 64 // 80 ms #endif // latency 0 (not the companion's 4): the mast link is marginal (RSSI -75..-90) // and the disconnects are HCI reason 0x3E (lost sync), not supervision timeout. // With latency>0 the node may skip connection events -> the central loses sync // sooner -> 0x3E. Responding every event maximises sync on a weak/busy link. #define RPT_BLE_SLAVE_LATENCY 0 #define RPT_BLE_CONN_SUP_TIMEOUT 1600 // 16000 ms (10 ms units); < 20 s HW watchdog // CUSTOM (TeTeHacko): two power knobs for a headless node that advertises // around the clock. Measured on this hardware, GPS aside, everything left in // the budget is single-digit mA -- so a blinking LED and a 6.5 Hz advertising // rate are not rounding errors, they are the budget. // // Bluefruit blinks LED_BLUE while advertising and holds it on while connected // (bluefruit.cpp::_setConnLed). On SenseCap Solar LED_BLUE is pin 12 -- the // SAME pin as P_LORA_TX_LED -- so a mast node burns solar charge blinking an // LED sealed inside an enclosure, and the LoRa TX indicator lies as a bonus. #ifndef RPT_BLE_CONN_LED #define RPT_BLE_CONN_LED 0 // 1 = keep the library's blinking LED #endif // Advertising intervals (0.625 ms units). Fast is used for the first // RPT_BLE_ADV_FAST_SECS after boot or a disconnect, then it falls back to // slow forever. Upstream leaves slow at 244 = 152.5 ms, i.e. a headless node // transmits on three channels ~6.5 times a second for years. 1 s still gets // discovered by a phone scan well within one sweep. #ifndef RPT_BLE_ADV_FAST #define RPT_BLE_ADV_FAST 32 // 20 ms #endif #ifndef RPT_BLE_ADV_SLOW #define RPT_BLE_ADV_SLOW 1600 // 1000 ms #endif #ifndef RPT_BLE_ADV_FAST_SECS #define RPT_BLE_ADV_FAST_SECS 30 #endif // CUSTOM (TeTeHacko): TX power of the CONNECTION, which is a separate knob // from the Bluefruit.setTxPower(8) in setup(). That one only stores a value // that BLEAdvertising::start() feeds to sd_ble_gap_tx_power_set() with // BLE_GAP_TX_POWER_ROLE_ADV -- the CONN role is never set anywhere in the // library, so once the central connects the link drops to the SoftDevice // default of 0 dBm. The +8 buys discovery range across the balcony and // nothing else. Set it per connection, on every 'secured' (the handle is new // each time), and keep the default at 0 so behaviour is unchanged. // // Runtime-settable via `blepwr` because it is the reproduction lever for the // BLE/LoRa TX-loss bug: the effect needs the marginal link the mast has // (RSSI -75..-90, see the latency note above) and the bench link is -57 dBm. // // Weakening OUR side is the direction that costs us radio time, and the // central's would not. A connection event ends as soon as either side misses // a packet, so: if the CENTRAL misses our PDU, we still have to re-send it at // the next anchor -- an extra slave TX. If WE miss the central's PDU, we never // transmit in that event at all, so the SoftDevice actually uses LESS radio. // More slave TX = more high-priority SoftDevice work in the way of the app's // DIO1 handling, which is the suspected mechanism. Far enough down the ladder // the link drops outright and Bluefruit re-advertises (at +8 dBm, 3 channels) // -- also radio time, and the same reconnect churn the mast shows as 0x3E. // // Runtime as well as a build flag: reflashing the XIAO costs a physical // double-tap + UF2 drop (BLE DFU cannot reach its bootloader, same MAC), and // a dose-response sweep needs many points. #ifndef RPT_BLE_CONN_TX_POWER #define RPT_BLE_CONN_TX_POWER 0 // dBm; = SoftDevice default #endif // Measured on the bench: at -20 dBm the node's replies stop arriving and at // -40 dBm a connection cannot be established at all. A too-low value set by // mistake is fixed over the mesh admin CLI (`blepwr` works there too). static int8_t ble_conn_tx_power = RPT_BLE_CONN_TX_POWER; // CUSTOM (TeTeHacko): last connection parameters actually in force, latched // from loop() so they can be read over USB after the central has gone -- // reading them over the BLE console while it is connected would collide on // the shared command[160] buffer. // // This is the control for everything above: bleOnSecured() only REQUESTS // 15-30/60-80 ms, and the central is free to refuse. Without reading back // what was negotiated, "the pre-fix interval showed no loss either" cannot // be distinguished from "the pre-fix interval was never actually in force". static uint16_t ble_seen_interval = 0; // 1.25 ms units static uint16_t ble_seen_latency = 0; static uint16_t ble_seen_timeout = 0; // 10 ms units // returns how many live connections accepted the new power (nRF52840 only // takes -40,-20,-16,-12,-8,-4,0,2..8; setTxPower() rejects the rest) static int bleApplyConnTxPower(int8_t p, int* live_out) { int ok = 0, live = 0; for (uint16_t h = 0; h < BLE_MAX_CONNECTION; h++) { BLEConnection* c = Bluefruit.Connection(h); if (c && c->connected()) { live++; if (c->setTxPower(p)) ok++; } } if (live_out) *live_out = live; return ok; } static void bleOnSecured(uint16_t conn_handle) { ble_gap_conn_params_t cp; cp.min_conn_interval = RPT_BLE_MIN_CONN_INTERVAL; cp.max_conn_interval = RPT_BLE_MAX_CONN_INTERVAL; cp.slave_latency = RPT_BLE_SLAVE_LATENCY; cp.conn_sup_timeout = RPT_BLE_CONN_SUP_TIMEOUT; sd_ble_gap_conn_param_update(conn_handle, &cp); BLEConnection* c = Bluefruit.Connection(conn_handle); if (c) c->setTxPower(ble_conn_tx_power); } // 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. // // RPT_BLE_DEFAULT_OFF (public builds): the console starts OFF and `ble on` // is what gets saved (marker /ble_on). Those builds carry the placeholder PIN // 123456, and the console has no login of its own -- the PIN is all that // guards it. So there `ble on` is refused until `ble pin` has set another. #include #define BLE_OFF_MARKER "/ble_off" #define BLE_ON_MARKER "/ble_on" #ifdef RPT_BLE_DEFAULT_OFF static bool ble_enabled = false; #else static bool ble_enabled = true; #endif static bool ble_toggle_target = true; static unsigned long ble_toggle_at = 0; // deferred apply so the reply can go out first static void bleMarker(const char* path, bool present) { if (!present) { InternalFS.remove(path); return; } auto f = InternalFS.open(path, Adafruit_LittleFS_Namespace::FILE_O_WRITE); if (f) { f.write((uint8_t)'1'); f.close(); } } static void blePersist(bool on) { #ifdef RPT_BLE_DEFAULT_OFF bleMarker(BLE_ON_MARKER, on); #else bleMarker(BLE_OFF_MARKER, !on); #endif } static bool bleSavedOn() { #ifdef RPT_BLE_DEFAULT_OFF return InternalFS.exists(BLE_ON_MARKER); #else return !InternalFS.exists(BLE_OFF_MARKER); #endif } // CUSTOM (TeTeHacko): `blepwr` survives a reboot (marker file like `ble off`). // mast-three's bridge reaches it through a closed window and the link only holds // at +8 dBm, which every reboot used to drop back to the 0 dBm default. #define BLE_PWR_FILE "/ble_pwr" static constexpr bool bleConnTxPowerValid(int p) { return p == -40 || p == -20 || p == -16 || p == -12 || p == -8 || p == -4 || p == 0 || (p >= 2 && p <= 8); } static_assert(bleConnTxPowerValid(RPT_BLE_CONN_TX_POWER), "RPT_BLE_CONN_TX_POWER: -40,-20,-16,-12,-8,-4,0,2..8"); // Pins an EXPLICIT value, even one equal to the build default: a file that // only held deviations from the default would silently follow a reflash // with a different RPT_BLE_CONN_TX_POWER (`blepwr 8` on mast-three, then an // image without its -D, would come up at 0 dBm). `blepwr default` unpins. // true when the value will come back after a reboot static bool bleConnTxPowerPersist(int8_t p) { // FILE_O_WRITE appends; a stale file would shadow the new byte if (!InternalFS.remove(BLE_PWR_FILE) && InternalFS.exists(BLE_PWR_FILE)) return false; auto f = InternalFS.open(BLE_PWR_FILE, Adafruit_LittleFS_Namespace::FILE_O_WRITE); if (!f) return false; bool ok = f.write((uint8_t)p) == 1; f.close(); return ok; } static int8_t bleConnTxPowerLoad() { int8_t p = RPT_BLE_CONN_TX_POWER; auto f = InternalFS.open(BLE_PWR_FILE, Adafruit_LittleFS_Namespace::FILE_O_READ); if (f) { uint8_t b; if (f.read(&b, 1) == 1 && bleConnTxPowerValid((int8_t)b)) p = (int8_t)b; f.close(); } return p; } // CUSTOM (TeTeHacko): `ble pin <6 digits>` -- the BLE PIN, saved in // InternalFS so it survives a reboot and a reflash (erase drops it). Without // it the PIN is the build's BLE_PIN_CODE, which in a public build everybody // knows. A new PIN clears the bonds: a central that paired with the old one // would otherwise keep its access without ever knowing the new PIN. #define BLE_PIN_FILE "/ble_pin" static char ble_pin[7] = _MC_STR(BLE_PIN_CODE); // the SoftDevice keeps the pointer static bool ble_pin_custom = false; static unsigned long ble_pin_reset_at = 0; // deferred so the reply can go out first static_assert(sizeof(_MC_STR(BLE_PIN_CODE)) == 7, "BLE_PIN_CODE must be 6 digits"); static bool blePinValid(const char* p) { if (strlen(p) != 6) return false; for (int i = 0; i < 6; i++) if (p[i] < '0' || p[i] > '9') return false; return true; } static void blePinLoad() { auto f = InternalFS.open(BLE_PIN_FILE, Adafruit_LittleFS_Namespace::FILE_O_READ); if (!f) return; char b[7] = {0}; if (f.read((uint8_t*)b, 6) == 6 && blePinValid(b)) { memcpy(ble_pin, b, 7); ble_pin_custom = strcmp(ble_pin, _MC_STR(BLE_PIN_CODE)) != 0; } f.close(); } static bool blePinSave(const char* p) { // FILE_O_WRITE appends; a stale file would shadow the new digits if (!InternalFS.remove(BLE_PIN_FILE) && InternalFS.exists(BLE_PIN_FILE)) return false; auto f = InternalFS.open(BLE_PIN_FILE, Adafruit_LittleFS_Namespace::FILE_O_WRITE); if (!f) return false; bool ok = f.write((const uint8_t*)p, 6) == 6; f.close(); return ok; } 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) { #ifdef RPT_BLE_DEFAULT_OFF if (!ble_pin_custom) { strcpy(reply, "ERR - set your own PIN first: ble pin <6 digits>"); return true; } #endif 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, PIN %s", ble_enabled ? "on" : "off", Bluefruit.connected() ? " (connected)" : (Bluefruit.Advertising.isRunning() ? " (advertising)" : ""), ble_pin_custom ? "own" : "build default"); return true; } // the PIN itself is never printed: the reply may travel over the mesh if (strcmp(command, "ble pin") == 0) { sprintf(reply, "BLE PIN: %s", ble_pin_custom ? "own (saved)" : "build default"); return true; } if (memcmp(command, "ble pin ", 8) == 0) { const char* p = &command[8]; if (!blePinValid(p)) { strcpy(reply, "ERR - ble pin <6 digits>"); return true; } if (!blePinSave(p)) { strcpy(reply, "ERR - BLE PIN not saved"); return true; } memcpy(ble_pin, p, 7); ble_pin_custom = strcmp(ble_pin, _MC_STR(BLE_PIN_CODE)) != 0; Bluefruit.Security.setPIN(ble_pin); ble_pin_reset_at = millis() + 1500; strcpy(reply, "OK - BLE PIN saved, bonds cleared: pair again"); return true; } // CUSTOM (TeTeHacko): `blepwr [dBm]` -- report or set the CONNECTION tx // power (see RPT_BLE_CONN_TX_POWER). Applied to every live connection, // remembered for the next 'secured' and saved, so a reconnect AND a reboot // keep the setting. // The nRF52840 only accepts -40,-20,-16,-12,-8,-4,0,2..8; setTxPower() // rejects anything else, hence the applied/failed count in the reply. if (memcmp(command, "blepwr", 6) == 0 && (command[6] == 0 || command[6] == ' ')) { if (strcmp(&command[6], " default") == 0) { // back to the build default: drop the saved value, apply it now InternalFS.remove(BLE_PWR_FILE); ble_conn_tx_power = RPT_BLE_CONN_TX_POWER; int live = 0; int ok = bleApplyConnTxPower(ble_conn_tx_power, &live); sprintf(reply, "OK - BLE conn tx %d dBm = build default (%d/%d conn), not saved", (int) ble_conn_tx_power, ok, live); return true; } if (command[6] == ' ') { // strict parse: now that the value is saved, a typo must not become // permanent (atoi turned "216" into -40 and "abc" into 0) char* end; long v = strtol(&command[7], &end, 10); if (end == &command[7] || *end != 0 || !bleConnTxPowerValid((int) v)) { strcpy(reply, "ERR - blepwr : -40,-20,-16,-12,-8,-4,0,2..8"); return true; } int8_t p = (int8_t) v; int live = 0; int ok = bleApplyConnTxPower(p, &live); // only latch a value the radio actually accepted, otherwise the next // reconnect would silently re-apply a bogus one bool applied = (live == 0 || ok > 0); bool saved = false; if (applied) { ble_conn_tx_power = p; saved = bleConnTxPowerPersist(p); } sprintf(reply, "%s - BLE conn tx %d dBm (%d/%d conn)%s", applied ? "OK" : "ERR", (int) p, ok, live, applied ? (saved ? ", saved" : ", NOT saved") : ""); } else { sprintf(reply, "BLE conn tx: %d dBm, adv tx: %d dBm", (int) ble_conn_tx_power, (int) Bluefruit.getTxPower()); } return true; } // CUSTOM (TeTeHacko): what the central actually agreed to, not what we asked // for. Values are from the last sample taken while connected. if (strcmp(command, "bleconn") == 0) { if (ble_seen_interval == 0) { strcpy(reply, "BLE conn: nothing seen yet"); } else { sprintf(reply, "BLE conn: interval %d.%02d ms (req %d-%d), latency %d, " "sup timeout %d ms%s", (ble_seen_interval * 125) / 100, (ble_seen_interval * 125) % 100, (RPT_BLE_MIN_CONN_INTERVAL * 125) / 100, (RPT_BLE_MAX_CONN_INTERVAL * 125) / 100, (int) ble_seen_latency, (int) ble_seen_timeout * 10, Bluefruit.connected() ? " [live]" : " [last]"); } return true; } return false; } #endif #ifdef ETHERNET_ENABLED #define ETHERNET_CLI_BANNER "MeshCore Repeater CLI" #include #endif StdRNG fast_rng; SimpleMeshTables tables; MyMesh the_mesh(board, radio_driver, *new ArduinoMillis(), fast_rng, rtc_clock, tables); // CUSTOM (TeTeHacko): `txpwr [dBm]` -- set LoRa output power and report what // RadioLib actually did with the request. // // `set tx` cannot answer that. It clamps to -9..30, saves the pref and replies // "OK", but SX1262 accepts only -9..+22 and rejects anything outside that range // WITHOUT touching the PA -- so `get tx` can report a power the radio never took. // A power sweep built on that is measuring nothing, and an earlier sweep here was // in exactly that position: +2 dBm and -9 dBm both produced RSSI -44.1/-44.0 at a // witness, with no way to tell "the radio ignored me" from "the link does not // care". This is the missing instrument for that measurement. // // Deliberately does NOT write the pref, so a sweep cannot leave a node booting // at some experimental power; use `set tx` when the value should persist. // Status 0 = RADIOLIB_ERR_NONE, -13 = RADIOLIB_ERR_INVALID_OUTPUT_POWER. bool txPwrHandleCommand(const char* command, char* reply) { if (memcmp(command, "txpwr", 5) != 0 || (command[5] != 0 && command[5] != ' ')) return false; if (command[5] == ' ') { int dbm = atoi(&command[6]); radio_driver.setTxPower((int8_t) dbm); int16_t st = radio_driver.getLastTxPowerStatus(); sprintf(reply, "%s - txpwr %d dBm, RadioLib status %d%s", st == RADIOLIB_ERR_NONE ? "OK" : "ERR", dbm, (int) st, st == RADIOLIB_ERR_INVALID_OUTPUT_POWER ? " (out of range, PA UNCHANGED)" : ""); } else { sprintf(reply, "txpwr: last request %d dBm, status %d (SX1262 accepts -9..22)", (int) radio_driver.getLastTxPowerRequested(), (int) radio_driver.getLastTxPowerStatus()); } return true; } // CUSTOM (TeTeHacko): `dfu`, the radio silence watchdog (#6) and `get boot` -- // board upkeep shared with the sensor, see helpers/NodeMaintenance.h. static NodeMaintenance maint(board, radio_driver); bool maintHandleCommand(uint32_t sender_timestamp, const char* command, char* reply) { return maint.handleCommand(sender_timestamp, command, reply); } // CUSTOM (TeTeHacko): binary firmware chunks (REQ_TYPE_FW_OTA), see helpers/FwUpdate.h. int maintHandleRequest(bool admin, const uint8_t* req, int len, uint8_t* reply, int reply_max) { return maint.handleRequest(admin, req, len, reply, reply_max); } #ifdef RADIO_DIAG // CUSTOM (TeTeHacko): `radiostat` / `radiokick` -- see RadioLibWrappers.cpp. // On the masts since 2. 11. 2026: mast-three came up deaf after a BLE OTA (recv 0, // tx_timeout 4, 17 min, a reboot fixed it), the same picture as x4 on 31. 10. // The next time it happens on a mast, the state is there to read. bool radioDiagHandleCommand(const char* command, char* reply) { return radio_driver.diagHandleCommand(command, reply); } #endif #ifdef PIN_DIAG // CUSTOM (TeTeHacko): `dio1` -- salvage diagnostic for a node whose radio // transmits (a witness hears the frames) but never reports completion, i.e. the // classic dead-DIO1 signature: `sent 0`, tx_timeout climbing, `recv 0`. // // The board itself becomes the instrument. probeDio1() has the SX1262 generate a // TX_DONE and then compares two things that a working line keeps in step: the // chip's IRQ status register (over SPI, so it is true regardless of the pin) and // the level on the pin. Where they disagree is where the break is. bool pinDiagHandleCommand(const char* command, char* reply) { if (memcmp(command, "dio1", 4) != 0 || command[4] != 0) return false; uint32_t irq = 0; int lvl = -1, probe = -1; int st = radio_driver.probeDio1(&irq, &lvl, &probe); if (st == -1) { strcpy(reply, "ERR - busy transmitting, try again"); return true; } if (st == -3) { strcpy(reply, "ERR - this radio exposes no IRQ mask"); return true; } if (st == -2) { sprintf(reply, "dio1: NO TX_DONE within 2s (irq=0x%04lx) - the fault is NOT the DIO1 line " "(SPI/BUSY/PA); the chip never finished the transmit", (unsigned long) irq); return true; } if (st != 0) { sprintf(reply, "ERR - startTransmit %d", st); return true; } const char* verdict; if (lvl == 1) verdict = "line OK - DIO1 rose with the IRQ, look elsewhere"; else if (probe == 1) verdict = "MCU input pad DEAD (probe wire sees the signal) -> rewiring FIXES it"; else if (probe == 0) verdict = "net dead at the SX1262 end -> rewiring will NOT help"; else verdict = "DIO1 stayed LOW - fit a probe wire (PIN_DIAG_PROBE) to tell the ends apart"; sprintf(reply, "dio1: irq=0x%04lx TX_DONE set, pin=%d probe=%d - %s", (unsigned long) irq, lvl, probe, verdict); return true; } #endif void halt() { while (1) ; } static char command[160]; #ifdef ETHERNET_ENABLED static char ethernet_command[160]; #endif // For power saving unsigned long POWERSAVING_FIRSTSLEEP_SECS = 120; // The first sleep (if enabled) from boot #if defined(PIN_USER_BTN) && defined(_SEEED_SENSECAP_SOLAR_H_) static unsigned long userBtnDownAt = 0; #define USER_BTN_HOLD_OFF_MILLIS 1500 #endif void setup() { Serial.begin(115200); delay(1000); board.begin(); #ifdef HAS_EXTERNAL_WATCHDOG external_watchdog.begin(); #endif #if defined(MESH_DEBUG) && defined(NRF52_PLATFORM) // give some extra time for serial to settle so // boot debug messages can be seen on terminal delay(5000); #elif defined(BOOT_DIAG_DELAY_MS) && defined(NRF52_PLATFORM) // CUSTOM (TeTeHacko): the same settle window, but WITHOUT MESH_DEBUG. The // hardfault record below is printed once and then cleared, so with only the // delay(1000) above it is unobservable: USB CDC has not finished enumerating, // the printf goes to a closed port and is dropped, and hf[0]=0 destroys the // evidence. MESH_DEBUG would open that window but also logs inside the mesh // path -- unusable on a node whose RX timing is the thing being measured. delay(BOOT_DIAG_DELAY_MS); #endif // CUSTOM (TeTeHacko): reset reason, build epoch and the hardfault record of the // last crash (NodeMaintenance.cpp). Needs MESH_DEBUG or BOOT_DIAG_DELAY_MS to be // seen at boot (above); `get boot` keeps it readable afterwards. maint.printBootDiag(); #if defined(PIN_DIAG) && defined(XIAO_NRF52) // CUSTOM (TeTeHacko): header GPIO integrity sweep, for salvaging a board whose // pins were abused (bench-board took GND on D1 and 5 V on D0 in a breadboard). // // Deliberately placed BEFORE radio_init(), because that halt()s when the radio // does not answer -- so this is the only diagnostic that still runs with the // XIAO UNPLUGGED from the Wio-SX1262 module. Unplugged is also the only state // in which the D1 result means anything: attached, the SX1262 drives DIO1 low // and a perfectly healthy board reads 0 too. // // The internal pull resistor IS the ohmmeter (~13 kOhm): a floating pin follows // it, a pin shorted to a rail does not. Run the same build on a known-good // board as the paired control. // // What the pull test CANNOT see: a lifted pad or broken bond. The resistor sits // on the die, so an open pad still reads 1/0 exactly like a healthy one while // the outside world is disconnected. Only the loopback below catches that. { static const uint8_t diag_pins[] = { D0, D1, D2, D3, D4, D5, D6, D7, D8, D9, D10 }; static const char* diag_use[] = { "-", "DIO1", "RESET", "BUSY", "NSS", "RXEN", "SCL", "SDA", "SCK", "MISO", "MOSI" }; Serial.println("PIN_DIAG: unplug the Wio module first, otherwise the radio drives these pins"); Serial.println("PIN_DIAG: pin use pu pd verdict"); for (uint8_t i = 0; i < sizeof(diag_pins); i++) { uint8_t p = diag_pins[i]; pinMode(p, INPUT_PULLUP); delay(2); int pu = digitalRead(p); pinMode(p, INPUT_PULLDOWN); delay(2); int pd = digitalRead(p); pinMode(p, INPUT); const char* v = (pu == 1 && pd == 0) ? "follows pulls (pad healthy OR open)" : (pu == 0 && pd == 0) ? "STUCK LOW <- shorted to GND?" : (pu == 1 && pd == 1) ? "STUCK HIGH <- shorted to VDD?" : "inverted?!"; Serial.printf("PIN_DIAG: D%-2d %-5s %d %d %s\n", (int) i, diag_use[i], pu, pd, v); } #if defined(PIN_DIAG_LOOP_A) && defined(PIN_DIAG_LOOP_B) // Loopback over ONE jumper wire between two pins -- the only test that can // see a lifted pad, because it drives from outside the die. Each read pulls // AGAINST the driver, so a pass proves the driver actually wins the pin. // // DANGER: this DRIVES pins. Never enable it with the Wio module attached. // Driving DIO1 against the SX1262's own output is the very fight that is // suspected of having killed this board. { const uint8_t pair[2] = { PIN_DIAG_LOOP_A, PIN_DIAG_LOOP_B }; int ok = 0; for (int dir = 0; dir < 2; dir++) { uint8_t drv = pair[dir], rd = pair[1 - dir]; pinMode(drv, OUTPUT); for (int lvl = 0; lvl < 2; lvl++) { digitalWrite(drv, lvl); pinMode(rd, lvl ? INPUT_PULLDOWN : INPUT_PULLUP); // pull against it delay(2); int got = digitalRead(rd); if (got == lvl) ok++; Serial.printf("PIN_DIAG: loop pin%d=%d -> pin%d reads %d %s\n", (int) drv, lvl, (int) rd, got, got == lvl ? "ok" : "FAIL"); } pinMode(drv, INPUT); } Serial.printf("PIN_DIAG: loopback %d/4 - 4 means both pads drive AND sense through the wire\n", ok); } #endif // The sweep took the I2C pins away from the TWI peripheral that board.begin() // configured. Nothing here depends on I2C (no RTC, no sensors) and the clock // falls back to VolatileRTCClock, but say so rather than leave it silent. Serial.println("PIN_DIAG: done (I2C pin config was clobbered by the sweep)"); } #endif #ifdef DISPLAY_CLASS if (display.begin()) { display.startFrame(); display.setCursor(0, 0); display.print("Please wait..."); display.endFrame(); } #endif if (!radio_init()) { MESH_DEBUG_PRINTLN("Radio init failed!"); halt(); } #ifdef RETAINED_CLOCK_NOINIT // Deliberately AFTER radio_init(), which calls rtc_clock.begin(Wire) and so // decides whether a hardware RTC answers. VolatileRTCClock restores a clock // retained across a warm reset on its first read (ArduinoHelpers.h); NOT silent, // because "nothing restored" looks exactly like "working" otherwise. { uint32_t now = rtc_clock.getCurrentTime(); static const char* const why[] = { "nepouzito (HW RTC?)", "prazdne", "ignorovany (power-on, stara hodnota by lhala)", "nenovejsi nez hodiny", "obnoveny" }; Serial.printf("boot: retained hodiny (.noinit %08lX) %s, epoch %lu\n", (unsigned long) (uintptr_t) g_retained_clock, why[g_retained_clock_status < 5 ? g_retained_clock_status : 0], (unsigned long) now); } #endif fast_rng.begin(radio_driver.getRngSeed()); FILESYSTEM* fs; #if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM) InternalFS.begin(); fs = &InternalFS; IdentityStore store(InternalFS, ""); #elif defined(ESP32) SPIFFS.begin(true); fs = &SPIFFS; IdentityStore store(SPIFFS, "/identity"); #elif defined(RP2040_PLATFORM) LittleFS.begin(); fs = &LittleFS; IdentityStore store(LittleFS, "/identity"); store.begin(); #else #error "need to define filesystem" #endif if (!store.load("_main", the_mesh.self_id)) { MESH_DEBUG_PRINTLN("Generating new keypair"); the_mesh.self_id = radio_new_identity(); // create new random identity int count = 0; while (count < 10 && (the_mesh.self_id.pub_key[0] == 0x00 || the_mesh.self_id.pub_key[0] == 0xFF)) { // reserved id hashes the_mesh.self_id = radio_new_identity(); count++; } store.save("_main", the_mesh.self_id); } Serial.print("Repeater ID: "); mesh::Utils::printHex(Serial, the_mesh.self_id.pub_key, PUB_KEY_SIZE); Serial.println(); command[0] = 0; #ifdef ETHERNET_ENABLED ethernet_command[0] = 0; #endif sensors.begin(); the_mesh.begin(fs); maint.begin(fs, the_mesh.getNodePrefs(), &the_mesh); // CUSTOM (TeTeHacko): needs the prefs loaded by begin() #ifdef DISPLAY_CLASS ui_task.begin(the_mesh.getNodePrefs(), FIRMWARE_BUILD_DATE, FIRMWARE_VERSION, "< Repeater >"); #endif #ifdef ETHERNET_ENABLED ethernet_start_task(); #endif // send out initial zero hop Advertisement to the mesh #if ENABLE_ADVERT_ON_BOOT == 1 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(); // Must come after begin(): autoConnLed(false) also stops the blink timer, // which only exists once begin() has created it. Bluefruit.autoConnLed(RPT_BLE_CONN_LED); // +8 dBm = nRF52840 max (range to the dongle across the balcony). NOTE: this // is ADVERTISING power only -- Bluefruit stores it and BLEAdvertising::start() // hands it to sd_ble_gap_tx_power_set(BLE_GAP_TX_POWER_ROLE_ADV). Nothing in // the library ever sets the CONN role, so an established link runs at the // SoftDevice default 0 dBm. See RPT_BLE_CONN_TX_POWER / `blepwr` for that half. Bluefruit.setTxPower(8); // CUSTOM (TeTeHacko): advertise the node's ACTUAL name, not the build-time // constant. BLE_DEVICE_NAME defaults to ADVERT_NAME, which only ever seeds a // fresh install -- so once several boards share one image, they all advertise // the same string no matter what `set name` says, and a BLE scan cannot tell // them apart. Four boards here advertised "bench-board" at once, including the // one with a dead radio. The prefs name is the one that was deliberately set, // so that is the one to broadcast; the build constant stays the fallback for a // node that has never been named. { const char* nm = the_mesh.getNodePrefs()->node_name; Bluefruit.setName((nm && nm[0]) ? nm : BLE_DEVICE_NAME); } blePinLoad(); // `ble pin` saved value, else the build's BLE_PIN_CODE Bluefruit.Security.setPIN(ble_pin); // widen the BLE connection params so the busy LoRa loop can't trip the // (default 2 s) supervision timeout -> no more reconnect churn. PPCP is // advertised AND requested explicitly on 'secured' (bleOnSecured). Bluefruit.Periph.setConnInterval(RPT_BLE_MIN_CONN_INTERVAL, RPT_BLE_MAX_CONN_INTERVAL); Bluefruit.Periph.setConnSlaveLatency(RPT_BLE_SLAVE_LATENCY); Bluefruit.Periph.setConnSupervisionTimeout(RPT_BLE_CONN_SUP_TIMEOUT); Bluefruit.Security.setSecuredCallback(bleOnSecured); // 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(RPT_BLE_ADV_FAST, RPT_BLE_ADV_SLOW); Bluefruit.Advertising.setFastTimeout(RPT_BLE_ADV_FAST_SECS); // persistent BLE state (see `ble on|off` and RPT_BLE_DEFAULT_OFF) ble_enabled = bleSavedOn(); ble_conn_tx_power = bleConnTxPowerLoad(); // `blepwr` saved value, if any 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 #ifdef RPT_IDENT_LED_PIN identTick(); // CUSTOM (TeTeHacko): drive `blink` without blocking the mesh #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): new BLE PIN -- drop every link and every bond made // under the old one (see `ble pin`) if (ble_pin_reset_at && (long)(millis() - ble_pin_reset_at) >= 0) { ble_pin_reset_at = 0; for (uint16_t h = 0; h < BLE_MAX_CONNECTION; h++) { BLEConnection* c = Bluefruit.Connection(h); if (c && c->connected()) c->disconnect(); } Bluefruit.Periph.clearBonds(); } // CUSTOM (TeTeHacko): latch the live connection parameters once a second, so // `bleconn` can report them after the central is gone (see ble_seen_*). { static unsigned long _lastParamChk = 0; if ((unsigned long)(millis() - _lastParamChk) >= 1000) { _lastParamChk = millis(); for (uint16_t h = 0; h < BLE_MAX_CONNECTION; h++) { BLEConnection* c = Bluefruit.Connection(h); if (c && c->connected()) { ble_seen_interval = c->getConnectionInterval(); ble_seen_latency = c->getSlaveLatency(); ble_seen_timeout = c->getSupervisionTimeout(); break; } } } } // 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); } } } bleTxPump(); // drain queued console output, never blocks (see bleWriteAll) #endif // Handle Serial CLI int len = strlen(command); // `command` must stay NUL-terminated within its bounds. If it ever isn't, // strlen() above can return >= sizeof(command) and the loop below would then // index past the buffer, so clamp defensively. if (len >= (int)sizeof(command)) { command[0] = 0; len = 0; } while (Serial.available() && len < sizeof(command)-1) { char c = Serial.read(); if (c != '\n') { command[len++] = c; command[len] = 0; Serial.print(c); } 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) { // buffer full: treat as a completed line command[sizeof(command)-2] = '\r'; // place end-of-line marker inside the buffer command[sizeof(command)-1] = 0; // keep the buffer NUL-terminated } if (len > 0 && command[len - 1] == '\r') { // received complete line Serial.print('\n'); command[len - 1] = 0; // replace newline with C string null terminator static char reply[1032]; // big pages for paged analyzer replies (nodes/rxlog); BSS, ne stack reply[0] = 0; // static buffer: clear it, or an unanswered command reprints the previous reply #ifdef ETHERNET_ENABLED if (!ethernet_handle_command(command, reply)) { the_mesh.handleCommand(0, command, reply, (int)sizeof(reply) - 32); } #else the_mesh.handleCommand(0, command, reply, (int)sizeof(reply) - 32); // NOTE: there is no sender_timestamp via serial! #endif 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 } board.loop(); // let the board feed its watchdog, run periodic housekeeping #ifdef ETHERNET_ENABLED ethernet_loop_maintain(); if (ethernet_read_line(ethernet_command, sizeof(ethernet_command))) { char reply[160]; reply[0] = 0; if (!ethernet_handle_command(ethernet_command, reply)) { the_mesh.handleCommand(0, ethernet_command, reply); } ethernet_send_reply(reply); ethernet_command[0] = 0; } #endif #if defined(PIN_USER_BTN) && defined(_SEEED_SENSECAP_SOLAR_H_) && !defined(DISPLAY_CLASS) // Hold the user button to power off the SenseCAP Solar repeater. int btnState = digitalRead(PIN_USER_BTN); if (btnState == LOW) { if (userBtnDownAt == 0) { userBtnDownAt = millis(); } else if ((unsigned long)(millis() - userBtnDownAt) >= USER_BTN_HOLD_OFF_MILLIS) { Serial.println("Powering off..."); board.powerOff(); // does not return } } else { userBtnDownAt = 0; } #endif the_mesh.loop(); maint.loop(the_mesh.txQueued(), the_mesh.txDue()); // CUSTOM (TeTeHacko): deferred `dfu`, deaf-receiver and TX stall watchdogs sensors.loop(); #ifdef DISPLAY_CLASS ui_task.loop(); #endif rtc_clock.tick(); #ifdef HAS_EXTERNAL_WATCHDOG external_watchdog.loop(); #endif bool ble_tx_busy = false; #if defined(BLE_PIN_CODE) && defined(NRF52_PLATFORM) ble_tx_busy = bleTxPending(); // console output still queued -> keep pumping #endif if (the_mesh.getNodePrefs()->powersaving_enabled && !the_mesh.hasPendingWork() && !ble_tx_busy) { #if defined(NRF52_PLATFORM) board.sleep(0); // nrf ignores seconds param, sleeps whenever possible #else if (the_mesh.millisHasNowPassed(POWERSAVING_FIRSTSLEEP_SECS * 1000)) { // To check if it is time to sleep board.sleep(30); // Sleep. Wake up after a while or when receiving a LoRa packet } #endif } }