Harden nRF52 storage and hardware recovery

This commit is contained in:
mikecarper committed 2026-07-21 00:01:01 -07:00
1 parent d5a00da2a0
commit bda0722ad8
40 files changed
+2069 -275

No files matched your search

+61 -28
View File
@@ -16,6 +16,13 @@ namespace mesh {
#define NOISE_FLOOR_CALIB_INTERVAL 2000 // refresh every 2 seconds
#endif
#ifndef RADIO_LIVENESS_SOFT_MS
#define RADIO_LIVENESS_SOFT_MS (30UL * 60UL * 1000UL)
#endif
#ifndef RADIO_LIVENESS_HARD_MS
#define RADIO_LIVENESS_HARD_MS (12UL * 60UL * 60UL * 1000UL)
#endif
void Dispatcher::begin() {
n_sent_flood = n_sent_direct = 0;
n_recv_flood = n_recv_direct = 0;
@@ -29,12 +36,11 @@ void Dispatcher::begin() {
_radio->begin();
prev_isrecv_mode = _radio->isInRecvMode();
#ifdef WITH_MQTT_BRIDGE
// Use begin() as the watchdog baseline even if the radio never reports an
// RX/IRQ timestamp. This lets a radio that is dead from startup recover.
last_radio_active_ms = _ms->getMillis();
last_watchdog_recovery = last_radio_active_ms;
#endif
last_observed_radio_irq = _radio->getLastRadioInterruptMillis();
radio_liveness.begin(last_radio_active_ms);
nonrx_soft_recovery_attempted = false;
}
float Dispatcher::getAirtimeBudgetFactor() const {
@@ -130,43 +136,67 @@ void Dispatcher::loop() {
}
_radio->loop();
const unsigned long now = _ms->getMillis();
const unsigned long latest_irq = _radio->getLastRadioInterruptMillis();
if (latest_irq != 0 && latest_irq != last_observed_radio_irq) {
last_observed_radio_irq = latest_irq;
last_radio_active_ms = now;
radio_liveness.noteActivity(now);
}
// check for radio 'stuck' in mode other than Rx
bool is_recv = _radio->isInRecvMode();
if (is_recv != prev_isrecv_mode) {
prev_isrecv_mode = is_recv;
if (!is_recv) {
radio_nonrx_start = _ms->getMillis();
radio_nonrx_start = now;
} else {
nonrx_soft_recovery_attempted = false;
}
}
if (!is_recv && _ms->getMillis() - radio_nonrx_start > 8000) { // radio has not been in Rx mode for 8 seconds!
bool recovered_this_loop = false;
if (!is_recv && outbound == NULL && now - radio_nonrx_start > 8000) {
_err_flags |= ERR_EVENT_STARTRX_TIMEOUT;
const bool hard = nonrx_soft_recovery_attempted;
MESH_DEBUG_PRINTLN("Radio watchdog: radio outside RX for %lu ms; %s recovery",
now - radio_nonrx_start, hard ? "hard" : "soft");
if (_radio->recoverRadio(hard)) {
last_watchdog_recovery = now;
recovered_this_loop = true;
}
nonrx_soft_recovery_attempted = true;
radio_nonrx_start = now; // bounded retry cadence if recovery is unsupported
}
// Radio watchdog: detect radio stuck in RX mode but not receiving any packets.
// Observer-only feature (gated behind WITH_MQTT_BRIDGE); configured via the
// MQTTPrefs radio_watchdog_minutes setting.
// Continuous-RX can fail while the MCU and main loop remain healthy, so a
// CPU watchdog cannot detect it. Use packet/IRQ/TX activity as proof of
// radio life and stage recovery from a harmless re-arm to a radio-only
// hardware reset when the driver supports one. Observer configuration may
// request a faster soft check.
uint32_t soft_liveness_ms = RADIO_LIVENESS_SOFT_MS;
#ifdef WITH_MQTT_BRIDGE
{
const uint32_t watchdog_ms = getRadioWatchdogMillis();
if (watchdog_ms > 0) {
const unsigned long now = _ms->getMillis();
unsigned long silent_ms = now - last_radio_active_ms;
const unsigned long last_recv = _radio->getLastRecvMillis();
const unsigned long last_irq = _radio->getLastRadioInterruptMillis();
if (last_recv != 0 && now - last_recv < silent_ms) silent_ms = now - last_recv;
if (last_irq != 0 && now - last_irq < silent_ms) silent_ms = now - last_irq;
const unsigned long since_recovery = now - last_watchdog_recovery;
if (is_recv && silent_ms >= watchdog_ms && since_recovery >= watchdog_ms) {
_err_flags |= ERR_EVENT_RADIO_WATCHDOG;
MESH_DEBUG_PRINTLN("Radio watchdog: silent %lu ms, state=%d, recovering", silent_ms, _radio->getRadioState());
_radio->idle();
_radio->startRecv();
last_watchdog_recovery = now;
last_radio_active_ms = now;
}
const uint32_t configured_watchdog_ms = getRadioWatchdogMillis();
if (configured_watchdog_ms > 0) soft_liveness_ms = configured_watchdog_ms;
#endif
uint32_t hard_liveness_ms = RADIO_LIVENESS_HARD_MS;
if (soft_liveness_ms > hard_liveness_ms / 2) {
hard_liveness_ms = soft_liveness_ms <= 0x7FFFFFFFUL
? soft_liveness_ms * 2 : 0xFFFFFFFFUL;
}
if (is_recv && outbound == NULL && !recovered_this_loop) {
const RadioRecoveryAction action = radio_liveness.poll(
now, soft_liveness_ms, hard_liveness_ms);
if (action != RadioRecoveryAction::NONE) {
const bool hard = action == RadioRecoveryAction::HARD;
_err_flags |= ERR_EVENT_RADIO_WATCHDOG;
MESH_DEBUG_PRINTLN("Radio watchdog: no hardware activity for %lu ms, state=%d, %s recovery",
now - last_radio_active_ms, _radio->getRadioState(),
hard ? "hard" : "soft");
const bool recovered = _radio->recoverRadio(hard);
if (recovered) last_watchdog_recovery = now;
if (hard) radio_liveness.noteHardRecoveryResult(now, recovered);
}
}
#endif // WITH_MQTT_BRIDGE (radio watchdog)
if (outbound) { // waiting for outbound send to be completed
if (_radio->isSendComplete()) {
@@ -192,6 +222,7 @@ void Dispatcher::loop() {
_radio->onSendFinished();
last_radio_active_ms = _ms->getMillis(); // TX success → radio is alive
radio_liveness.noteActivity(last_radio_active_ms);
restoreOutboundTxOverrides();
logTx(outbound, 2 + outbound->getPathByteLen() + outbound->payload_len);
onSendComplete(outbound);
@@ -317,6 +348,8 @@ void Dispatcher::checkRecv() {
uint8_t raw[MAX_TRANS_UNIT+1];
int len = _radio->recvRaw(raw, MAX_TRANS_UNIT);
if (len > 0) {
last_radio_active_ms = _ms->getMillis();
radio_liveness.noteActivity(last_radio_active_ms);
logRxRaw(_radio->getLastSNR(), _radio->getLastRSSI(), raw, len);
pkt = _mgr->allocNew();
+17
View File
@@ -4,6 +4,7 @@
#include <Identity.h>
#include <Packet.h>
#include <Utils.h>
#include <helpers/RadioLivenessTracker.h>
#include <string.h>
namespace mesh {
@@ -78,6 +79,17 @@ public:
virtual void idle() { }
virtual void startRecv() { }
// Recover a radio whose MCU driver is still running but whose RF state has
// stopped making progress. hard=false is a safe receive/AGC re-arm;
// hard=true may reset only the radio peripheral. The default remains useful
// for simple radios that do not expose a dedicated reset.
virtual bool recoverRadio(bool hard) {
(void)hard;
idle();
startRecv();
return true;
}
virtual int getNoiseFloor() const { return 0; }
virtual void triggerNoiseFloorCalibrate(int threshold) { }
@@ -210,6 +222,8 @@ class Dispatcher {
unsigned long outbound_expiry, outbound_start, total_air_time, rx_air_time;
unsigned long last_watchdog_recovery;
unsigned long last_radio_active_ms; // updated on any TX or RX event; used by watchdog
unsigned long last_observed_radio_irq;
RadioLivenessTracker radio_liveness;
uint16_t outbound_restore_preamble_len;
uint8_t outbound_restore_cr;
unsigned long next_tx_time;
@@ -217,6 +231,7 @@ class Dispatcher {
unsigned long radio_nonrx_start;
unsigned long next_floor_calib_time, next_agc_reset_time;
bool prev_isrecv_mode;
bool nonrx_soft_recovery_attempted;
uint32_t n_sent_flood, n_sent_direct;
uint32_t n_recv_flood, n_recv_direct;
unsigned long tx_budget_ms;
@@ -252,6 +267,8 @@ protected:
duty_cycle_window_ms = 3600000;
last_watchdog_recovery = 0;
last_radio_active_ms = 0;
last_observed_radio_irq = 0;
nonrx_soft_recovery_attempted = false;
}
virtual DispatcherAction onRecvPacket(Packet* pkt) = 0;
+1 -1
View File
@@ -111,7 +111,7 @@ void LocalIdentity::printTo(Stream& s) const {
s.print("prv_key: "); Utils::printHex(s, prv_key, PRV_KEY_SIZE); s.println();
}
size_t LocalIdentity::writeTo(uint8_t* dest, size_t max_len) {
size_t LocalIdentity::writeTo(uint8_t* dest, size_t max_len) const {
if (max_len < PRV_KEY_SIZE) return 0; // not big enough
if (max_len < PRV_KEY_SIZE + PUB_KEY_SIZE) { // only room for prv_key
+1 -2
View File
@@ -90,9 +90,8 @@ public:
bool readFrom(Stream& s);
bool writeTo(Stream& s) const;
void printTo(Stream& s) const;
size_t writeTo(uint8_t* dest, size_t max_len);
size_t writeTo(uint8_t* dest, size_t max_len) const;
void readFrom(const uint8_t* src, size_t len);
};
}
+2
View File
@@ -110,6 +110,8 @@ public:
virtual const char* getResetReasonString(uint32_t reason) { return "Not available"; }
virtual uint8_t getShutdownReason() const { return 0; }
virtual const char* getShutdownReasonString(uint8_t reason) { return "Not available"; }
virtual bool isPowerManagementInitialized() const { return false; }
virtual bool supportsVoltageWake() const { return false; }
inline static uint32_t n_cad_busy = 0;
};
+7
View File
@@ -105,6 +105,9 @@ ContactInfo* BaseChatMesh::allocateContactSlot(bool transient_only) {
void BaseChatMesh::populateContactFromAdvert(ContactInfo& ci, const mesh::Identity& id, const AdvertDataParser& parser, uint32_t timestamp) {
memset(&ci, 0, sizeof(ci));
#if defined(NRF52_PLATFORM)
ci.storage_slot = mesh::storage::CONTACT_SLOT_NONE;
#endif
ci.id = id;
ci.out_path_len = OUT_PATH_UNKNOWN;
StrHelper::strncpy(ci.name, parser.getName(), sizeof(ci.name));
@@ -148,6 +151,9 @@ void BaseChatMesh::onAdvertRecv(mesh::Packet* packet, const mesh::Identity& id,
if (from && from->type == ADV_TYPE_NONE) { // already in contacts, but from a temporary ANON_REQ ?
memset(from, 0, sizeof(*from)); // clear the anon/temp slot
#if defined(NRF52_PLATFORM)
from->storage_slot = mesh::storage::CONTACT_SLOT_NONE;
#endif
from = NULL; // do normal 'add' flow
}
@@ -182,6 +188,7 @@ void BaseChatMesh::onAdvertRecv(mesh::Packet* packet, const mesh::Identity& id,
populateContactFromAdvert(*from, id, parser, timestamp);
from->sync_since = 0;
from->shared_secret_valid = false;
is_new = true;
}
// update
+8
View File
@@ -96,6 +96,11 @@ protected:
void resetContacts() {
memset(contacts, 0, sizeof(contacts[0])*MAX_ANON_CONTACTS); // set all to have type = ADV_TYPE_NONE(0)
#if defined(NRF52_PLATFORM)
for (int i = 0; i < MAX_ANON_CONTACTS; i++) {
contacts[i].storage_slot = mesh::storage::CONTACT_SLOT_NONE;
}
#endif
num_contacts = MAX_ANON_CONTACTS; // seed the first contacts for anon requests
}
void populateContactFromAdvert(ContactInfo& ci, const mesh::Identity& id, const AdvertDataParser& parser, uint32_t timestamp);
@@ -177,6 +182,9 @@ public:
int getTotalContactSlots() const { return num_contacts; }
int getNumContacts() const { return num_contacts - MAX_ANON_CONTACTS; } // don't include the reserved slots at start
bool getContactByIdx(uint32_t idx, ContactInfo& contact);
ContactInfo* getContactPtrByIdx(uint32_t idx) {
return idx < (uint32_t)num_contacts ? &contacts[idx] : NULL;
}
ContactsIterator startContactsIterator();
ChannelDetails* addChannel(const char* name, const char* psk_base64);
bool getChannel(int idx, ChannelDetails& dest);
+10
View File
@@ -2,6 +2,9 @@
#include <Arduino.h>
#include <Mesh.h>
#if defined(NRF52_PLATFORM)
#include "PersistentStoreFormat.h"
#endif
#define OUT_PATH_UNKNOWN 0xFF
@@ -18,6 +21,13 @@ struct ContactInfo {
int32_t gps_lat, gps_lon; // 6 dec places
uint32_t sync_since;
// Runtime-only position in the paged companion contact store. It is not
// part of the on-disk record; the record's page/slot supplies it on load.
// Mutable keeps persistence bookkeeping out of contact protocol semantics.
#if defined(NRF52_PLATFORM)
mutable uint16_t storage_slot = mesh::storage::CONTACT_SLOT_NONE;
#endif
const uint8_t* getSharedSecret(const mesh::LocalIdentity& self_id) const {
if (!shared_secret_valid) {
self_id.calcSharedSecret(shared_secret, id.pub_key);
+42 -6
View File
@@ -1,5 +1,9 @@
#include "IdentityStore.h"
#if defined(NRF52_PLATFORM)
#include "AtomicFileWriter.h"
#endif
bool IdentityStore::load(const char *name, mesh::LocalIdentity& id) {
bool loaded = false;
char filename[40];
@@ -46,7 +50,20 @@ bool IdentityStore::save(const char *name, const mesh::LocalIdentity& id) {
char filename[40];
sprintf(filename, "%s/%s.id", _dir, name);
#if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM)
#if defined(NRF52_PLATFORM)
uint8_t key_data[PRV_KEY_SIZE + PUB_KEY_SIZE];
if (id.writeTo(key_data, sizeof(key_data)) != sizeof(key_data)) return false;
// LocalIdentity's byte-buffer export is private-key then public-key, while
// the historical file format is public-key then private-key.
mesh::AtomicFileWriter writer(_fs, filename);
const bool wrote = writer
&& writer.write(&key_data[PRV_KEY_SIZE], PUB_KEY_SIZE) == PUB_KEY_SIZE
&& writer.write(key_data, PRV_KEY_SIZE) == PRV_KEY_SIZE;
const bool success = writer.commit(wrote);
MESH_DEBUG_PRINTLN("IdentityStore::save() atomic write - %s", success ? "OK" : "Err");
return success;
#elif defined(STM32_PLATFORM)
_fs->remove(filename);
File file = _fs->open(filename, FILE_O_WRITE);
#elif defined(RP2040_PLATFORM)
@@ -54,12 +71,14 @@ bool IdentityStore::save(const char *name, const mesh::LocalIdentity& id) {
#else
File file = _fs->open(filename, "w", true);
#endif
#if !defined(NRF52_PLATFORM)
if (file) {
bool success = id.writeTo(file);
file.close();
MESH_DEBUG_PRINTLN("IdentityStore::save() write - %s", success ? "OK" : "Err");
return true;
return success;
}
#endif
MESH_DEBUG_PRINTLN("IdentityStore::save() failed");
return false;
}
@@ -68,7 +87,22 @@ bool IdentityStore::save(const char *name, const mesh::LocalIdentity& id, const
char filename[40];
sprintf(filename, "%s/%s.id", _dir, name);
#if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM)
#if defined(NRF52_PLATFORM)
uint8_t key_data[PRV_KEY_SIZE + PUB_KEY_SIZE];
if (id.writeTo(key_data, sizeof(key_data)) != sizeof(key_data)) return false;
uint8_t display_data[32];
memset(display_data, 0, sizeof(display_data));
size_t display_len = strlen(display_name);
if (display_len > sizeof(display_data) - 1) display_len = sizeof(display_data) - 1;
memcpy(display_data, display_name, display_len);
mesh::AtomicFileWriter writer(_fs, filename);
const bool wrote = writer
&& writer.write(&key_data[PRV_KEY_SIZE], PUB_KEY_SIZE) == PUB_KEY_SIZE
&& writer.write(key_data, PRV_KEY_SIZE) == PRV_KEY_SIZE
&& writer.write(display_data, sizeof(display_data)) == sizeof(display_data);
return writer.commit(wrote);
#elif defined(STM32_PLATFORM)
_fs->remove(filename);
File file = _fs->open(filename, FILE_O_WRITE);
#elif defined(RP2040_PLATFORM)
@@ -76,18 +110,20 @@ bool IdentityStore::save(const char *name, const mesh::LocalIdentity& id, const
#else
File file = _fs->open(filename, "w", true);
#endif
#if !defined(NRF52_PLATFORM)
if (file) {
id.writeTo(file);
bool success = id.writeTo(file);
uint8_t tmp[32];
memset(tmp, 0, sizeof(tmp));
int n = strlen(display_name);
if (n > sizeof(tmp)-1) n = sizeof(tmp)-1;
memcpy(tmp, display_name, n);
file.write(tmp, sizeof(tmp));
success = success && file.write(tmp, sizeof(tmp)) == sizeof(tmp);
file.close();
return true;
return success;
}
#endif
return false;
}
+35 -7
View File
@@ -1,5 +1,6 @@
#if defined(NRF52_PLATFORM)
#include "NRF52Board.h"
#include "PowerManagementUtils.h"
#include <target.h>
#include <bluefruit.h>
@@ -104,6 +105,8 @@ static void __attribute__((constructor(101))) nrf52_early_reset_capture() {
}
void NRF52Board::initPowerMgr() {
if (power_mgr_initialized) return;
// Copy early-captured register values
reset_reason = g_nrf52_reset_reason;
shutdown_reason = g_nrf52_shutdown_reason;
@@ -130,6 +133,7 @@ void NRF52Board::initPowerMgr() {
MESH_DEBUG_PRINTLN("PWRMGT: Reset = %s (0x%lX)",
getResetReasonString(reset_reason), (unsigned long)reset_reason);
}
power_mgr_initialized = true;
}
const char* NRF52Board::getResetReasonString(uint32_t reason) {
@@ -154,6 +158,7 @@ const char* NRF52Board::getResetReasonString(uint32_t reason) {
const char* NRF52Board::getShutdownReasonString(uint8_t reason) {
switch (reason) {
case SHUTDOWN_REASON_NONE: return "None";
case SHUTDOWN_REASON_LOW_VOLTAGE: return "Low Voltage";
case SHUTDOWN_REASON_USER: return "User Request";
case SHUTDOWN_REASON_BOOT_PROTECT: return "Boot Protection";
@@ -164,15 +169,22 @@ const char* NRF52Board::getShutdownReasonString(uint8_t reason) {
bool NRF52Board::checkBootVoltage(const PowerMgtConfig* config) {
initPowerMgr();
// Read boot voltage
boot_voltage_mv = getBattMilliVolts();
if (config == nullptr) return true;
// Use the median of three readings. A single unsettled ADC sample during a
// brownout must not put the device into a persistent SYSTEMOFF boot lock.
uint16_t samples[3];
for (uint8_t i = 0; i < 3; i++) {
samples[i] = getBattMilliVolts();
if (i != 2) delay(5);
}
boot_voltage_mv = mesh::power::medianVoltage(samples[0], samples[1], samples[2]);
if (config->voltage_bootlock == 0) return true; // Protection disabled
// Skip check if externally powered
if (isExternalPowered()) {
MESH_DEBUG_PRINTLN("PWRMGT: Boot check skipped (external power)");
boot_voltage_mv = getBattMilliVolts();
return true;
}
@@ -181,7 +193,7 @@ bool NRF52Board::checkBootVoltage(const PowerMgtConfig* config) {
// Only trigger shutdown if reading is valid (>1000mV) AND below threshold
// This prevents spurious shutdowns on ADC glitches or uninitialized reads
if (boot_voltage_mv > 1000 && boot_voltage_mv < config->voltage_bootlock) {
if (mesh::power::shouldBootLock(boot_voltage_mv, config->voltage_bootlock, false)) {
MESH_DEBUG_PRINTLN("PWRMGT: Boot voltage too low - entering protective shutdown");
initiateShutdown(SHUTDOWN_REASON_BOOT_PROTECT);
@@ -230,6 +242,18 @@ void NRF52Board::enterSystemOff(uint8_t reason) {
}
void NRF52Board::configureVoltageWake(uint8_t ain_channel, uint8_t refsel) {
// USB power should always be able to recover a device from SYSTEMOFF, even
// if voltage comparator setup is unavailable or invalid.
armVbusWake();
if (!power_mgr_initialized || !supportsVoltageWake()) {
MESH_DEBUG_PRINTLN("PWRMGT: LPCOMP wake skipped (power manager not ready/unsupported)");
return;
}
if (ain_channel > 7 || refsel > 15) {
MESH_DEBUG_PRINTLN("PWRMGT: LPCOMP wake skipped (invalid AIN/ref)");
return;
}
// LPCOMP is not managed by SoftDevice - direct register access required
// Halt and disable before reconfiguration
NRF_LPCOMP->TASKS_STOP = 1;
@@ -244,8 +268,9 @@ void NRF52Board::configureVoltageWake(uint8_t ain_channel, uint8_t refsel) {
// Detect UP events (voltage rises above threshold for battery recovery)
NRF_LPCOMP->ANADETECT = LPCOMP_ANADETECT_ANADETECT_Up;
// Enable 50mV hysteresis for noise immunity
NRF_LPCOMP->HYST = LPCOMP_HYST_HYST_Hyst50mV;
// Do not add comparator hysteresis here. On divided battery inputs it can
// shift the effective wake point enough to strand a valid low-voltage cell.
NRF_LPCOMP->HYST = LPCOMP_HYST_HYST_NoHyst;
// Clear stale events/interrupts before enabling wake
NRF_LPCOMP->EVENTS_READY = 0;
@@ -276,7 +301,10 @@ void NRF52Board::configureVoltageWake(uint8_t ain_channel, uint8_t refsel) {
ain_channel, ref_num);
}
// Configure VBUS (USB power) wake alongside LPCOMP
}
void NRF52Board::armVbusWake() {
// Configure VBUS (USB power) wake alongside (or instead of) LPCOMP.
uint8_t sd_enabled = 0;
sd_softdevice_is_enabled(&sd_enabled);
if (sd_enabled) {
+9 -1
View File
@@ -27,6 +27,8 @@ struct PowerMgtConfig {
class NRF52Board : public mesh::MainBoard {
#ifdef NRF52_POWER_MANAGEMENT
void initPowerMgr();
void armVbusWake();
bool power_mgr_initialized;
#endif
protected:
@@ -45,7 +47,11 @@ protected:
#endif
public:
NRF52Board(char *otaname) : ota_name(otaname) {}
NRF52Board(char *otaname) : ota_name(otaname)
#ifdef NRF52_POWER_MANAGEMENT
, power_mgr_initialized(false)
#endif
{}
virtual void begin();
// Feed the hardware main-loop watchdog. The first call starts it, so normal
// setup (including filesystem mount and radio initialization) is not timed.
@@ -71,6 +77,8 @@ public:
uint8_t getShutdownReason() const override { return shutdown_reason; }
const char* getResetReasonString(uint32_t reason) override;
const char* getShutdownReasonString(uint8_t reason) override;
bool isPowerManagementInitialized() const override { return power_mgr_initialized; }
bool supportsVoltageWake() const override { return true; }
#endif
};
+221
View File
@@ -0,0 +1,221 @@
#pragma once
#include <stddef.h>
#include <stdint.h>
#include <string.h>
namespace mesh {
namespace storage {
// Contact pages are deliberately smaller than a 4 KiB LittleFS block. A
// single contact update therefore never rewrites the complete contact list.
static const uint8_t CONTACTS_PER_PAGE = 25;
static const uint8_t CONTACT_PAGE_COUNT = 14;
static const uint16_t CONTACT_RECORD_SIZE = 152;
static const uint16_t CONTACT_PAGE_HEADER_SIZE = 20;
static const uint16_t CONTACT_PAGE_PAYLOAD_SIZE =
CONTACTS_PER_PAGE * CONTACT_RECORD_SIZE;
static const uint16_t CONTACT_PAGE_FILE_SIZE =
CONTACT_PAGE_HEADER_SIZE + CONTACT_PAGE_PAYLOAD_SIZE;
static const uint16_t CONTACT_SLOT_NONE = 0xFFFF;
static const uint8_t CONTACT_PAGE_VERSION = 1;
static const uint8_t CONTACT_PAGE_MAGIC[4] = {'M', 'C', 'P', '4'};
struct ContactPageHeader {
uint8_t page_index;
uint32_t occupied;
uint32_t generation;
uint32_t payload_crc;
};
enum class ContactStoreSource : uint8_t {
EMPTY,
LEGACY,
PAGED,
};
// A retained legacy file means migration is still in progress. Its complete
// record count is the authoritative prefix boundary; page records at or above
// that boundary have already committed.
inline ContactStoreSource chooseContactStoreSource(bool legacy_exists,
bool page_exists) {
if (legacy_exists) return ContactStoreSource::LEGACY;
if (page_exists) return ContactStoreSource::PAGED;
return ContactStoreSource::EMPTY;
}
// When a legacy file returns after a downgrade, old page files may describe a
// different contact list. Only a marker created after stale pages were removed
// makes those pages valid participants in an in-progress migration.
inline bool trustMigratedContactPages(bool legacy_exists,
bool migration_marker_exists) {
return !legacy_exists || migration_marker_exists;
}
inline uint16_t legacyContactCountForSize(size_t file_size) {
const size_t count = file_size / CONTACT_RECORD_SIZE;
const size_t capacity = CONTACT_PAGE_COUNT * CONTACTS_PER_PAGE;
return (uint16_t)(count < capacity ? count : capacity);
}
inline uint8_t legacyMigrationPage(uint16_t legacy_contact_count) {
return legacy_contact_count == 0 ? CONTACT_PAGE_COUNT
: (uint8_t)((legacy_contact_count - 1) / CONTACTS_PER_PAGE);
}
inline uint16_t legacyCountAfterMigratingPage(uint8_t page) {
return page < CONTACT_PAGE_COUNT
? (uint16_t)page * CONTACTS_PER_PAGE : 0;
}
// During tail-first migration, the still-present prefix in /contacts3 wins.
// Page slots at or beyond its complete-record count are already committed and
// can be loaded. This also makes a reset between page commit and truncation
// harmless: the duplicate page records remain hidden until truncation commits.
inline bool loadSlotFromMigratedPage(uint16_t slot,
uint16_t legacy_contact_count) {
return slot >= legacy_contact_count;
}
inline uint16_t readLE16(const uint8_t* src) {
return (uint16_t)src[0] | ((uint16_t)src[1] << 8);
}
inline uint32_t readLE32(const uint8_t* src) {
return (uint32_t)src[0] | ((uint32_t)src[1] << 8)
| ((uint32_t)src[2] << 16) | ((uint32_t)src[3] << 24);
}
inline void writeLE16(uint8_t* dest, uint16_t value) {
dest[0] = (uint8_t)value;
dest[1] = (uint8_t)(value >> 8);
}
inline void writeLE32(uint8_t* dest, uint32_t value) {
dest[0] = (uint8_t)value;
dest[1] = (uint8_t)(value >> 8);
dest[2] = (uint8_t)(value >> 16);
dest[3] = (uint8_t)(value >> 24);
}
// Same CRC convention as AtomicFileWriter: reflected CRC-32, initial value
// 0xFFFFFFFF, with no final xor. Keeping this incremental makes it usable on
// small targets without buffering an entire file.
inline uint32_t updateCRC32(uint32_t crc, const uint8_t* data, size_t len) {
while (len-- > 0) {
crc ^= *data++;
for (uint8_t bit = 0; bit < 8; bit++) {
crc = (crc >> 1) ^ ((crc & 1) ? 0xEDB88320UL : 0);
}
}
return crc;
}
inline void encodeContactPageHeader(uint8_t dest[CONTACT_PAGE_HEADER_SIZE],
const ContactPageHeader& header) {
memcpy(dest, CONTACT_PAGE_MAGIC, sizeof(CONTACT_PAGE_MAGIC));
dest[4] = CONTACT_PAGE_VERSION;
dest[5] = header.page_index;
writeLE16(&dest[6], CONTACT_RECORD_SIZE);
writeLE32(&dest[8], header.occupied);
writeLE32(&dest[12], header.generation);
writeLE32(&dest[16], header.payload_crc);
}
inline bool decodeContactPageHeader(const uint8_t src[CONTACT_PAGE_HEADER_SIZE],
uint8_t expected_page,
ContactPageHeader& header) {
const uint32_t valid_slots = (1UL << CONTACTS_PER_PAGE) - 1UL;
if (memcmp(src, CONTACT_PAGE_MAGIC, sizeof(CONTACT_PAGE_MAGIC)) != 0
|| src[4] != CONTACT_PAGE_VERSION || src[5] != expected_page
|| readLE16(&src[6]) != CONTACT_RECORD_SIZE) {
return false;
}
header.page_index = src[5];
header.occupied = readLE32(&src[8]);
header.generation = readLE32(&src[12]);
header.payload_crc = readLE32(&src[16]);
return (header.occupied & ~valid_slots) == 0;
}
class DirtyPageSet {
uint32_t _bits;
public:
DirtyPageSet() : _bits(0) {}
void clearAll() { _bits = 0; }
bool empty() const { return _bits == 0; }
uint32_t bits() const { return _bits; }
bool mark(uint8_t page) {
if (page >= CONTACT_PAGE_COUNT) return false;
_bits |= (1UL << page);
return true;
}
int first() const {
for (uint8_t page = 0; page < CONTACT_PAGE_COUNT; page++) {
if ((_bits & (1UL << page)) != 0) return page;
}
return -1;
}
void clear(uint8_t page) {
if (page < CONTACT_PAGE_COUNT) _bits &= ~(1UL << page);
}
};
class ContactSlotMap {
uint32_t _used[CONTACT_PAGE_COUNT];
public:
ContactSlotMap() { clear(); }
void clear() { memset(_used, 0, sizeof(_used)); }
uint32_t pageMask(uint8_t page) const {
return page < CONTACT_PAGE_COUNT ? _used[page] : 0;
}
bool isUsed(uint16_t slot) const {
if (slot >= CONTACT_PAGE_COUNT * CONTACTS_PER_PAGE) return false;
return (_used[slot / CONTACTS_PER_PAGE]
& (1UL << (slot % CONTACTS_PER_PAGE))) != 0;
}
bool reserve(uint16_t slot) {
if (slot >= CONTACT_PAGE_COUNT * CONTACTS_PER_PAGE) return false;
const uint8_t page = slot / CONTACTS_PER_PAGE;
const uint32_t bit = 1UL << (slot % CONTACTS_PER_PAGE);
if ((_used[page] & bit) != 0) return false;
_used[page] |= bit;
return true;
}
uint16_t allocate() {
const uint32_t valid_slots = (1UL << CONTACTS_PER_PAGE) - 1UL;
for (uint8_t page = 0; page < CONTACT_PAGE_COUNT; page++) {
if ((_used[page] & valid_slots) == valid_slots) continue;
for (uint8_t index = 0; index < CONTACTS_PER_PAGE; index++) {
const uint32_t bit = 1UL << index;
if ((_used[page] & bit) == 0) {
_used[page] |= bit;
return (uint16_t)page * CONTACTS_PER_PAGE + index;
}
}
}
return CONTACT_SLOT_NONE;
}
bool release(uint16_t slot) {
if (!isUsed(slot)) return false;
_used[slot / CONTACTS_PER_PAGE] &= ~(1UL << (slot % CONTACTS_PER_PAGE));
return true;
}
};
} // namespace storage
} // namespace mesh
+22
View File
@@ -0,0 +1,22 @@
#pragma once
#include <stdint.h>
namespace mesh {
namespace power {
inline uint16_t medianVoltage(uint16_t a, uint16_t b, uint16_t c) {
if (a > b) { uint16_t t = a; a = b; b = t; }
if (b > c) { uint16_t t = b; b = c; c = t; }
if (a > b) { uint16_t t = a; a = b; b = t; }
return b;
}
inline bool shouldBootLock(uint16_t voltage_mv, uint16_t threshold_mv,
bool externally_powered) {
return !externally_powered && threshold_mv != 0
&& voltage_mv > 1000 && voltage_mv < threshold_mv;
}
} // namespace power
} // namespace mesh
+67
View File
@@ -0,0 +1,67 @@
#pragma once
#include <stdint.h>
namespace mesh {
enum class RadioRecoveryAction : uint8_t {
NONE,
SOFT,
HARD,
};
// Tracks proof that the radio hardware is alive independently of the MCU main
// loop. A successful packet, IRQ, or TX resets the schedule. Silence first
// requests a non-destructive RX/AGC re-arm, then a radio-only hardware reset.
class RadioLivenessTracker {
static const uint32_t HARD_RETRY_MS = 30000UL;
uint32_t _last_activity;
uint32_t _last_hard_attempt;
uint8_t _stage;
public:
RadioLivenessTracker() : _last_activity(0), _last_hard_attempt(0), _stage(0) {}
void begin(uint32_t now) {
_last_activity = now;
_last_hard_attempt = 0;
_stage = 0;
}
void noteActivity(uint32_t now) {
_last_activity = now;
_last_hard_attempt = 0;
_stage = 0;
}
// A completed hard recovery is a safe point from which to restart the
// liveness window. Failed recoveries remain escalated and retry at a bounded
// cadence, instead of being silently deferred for another full interval.
void noteHardRecoveryResult(uint32_t now, bool success) {
if (success) noteActivity(now);
}
RadioRecoveryAction poll(uint32_t now, uint32_t soft_after_ms,
uint32_t hard_after_ms) {
const uint32_t silent_for = now - _last_activity;
if (hard_after_ms > 0 && silent_for >= hard_after_ms) {
if (_stage < 2 || now - _last_hard_attempt >= HARD_RETRY_MS) {
_stage = 2;
_last_hard_attempt = now;
return RadioRecoveryAction::HARD;
}
return RadioRecoveryAction::NONE;
}
if (_stage == 0 && soft_after_ms > 0 && silent_for >= soft_after_ms) {
_stage = 1;
return RadioRecoveryAction::SOFT;
}
return RadioRecoveryAction::NONE;
}
uint32_t lastActivity() const { return _last_activity; }
uint8_t stage() const { return _stage; }
};
} // namespace mesh
+6 -1
View File
@@ -1,4 +1,5 @@
#include "RS232Bridge.h"
#include "RS232UartUtils.h"
#include <HardwareSerial.h>
@@ -17,7 +18,11 @@ void RS232Bridge::begin() {
((HardwareSerial *)_serial)->setPins(WITH_RS232_BRIDGE_RX, WITH_RS232_BRIDGE_TX);
#elif defined(NRF52_PLATFORM)
// Tested with RAK_4631 and T114
((Uart *)_serial)->setPins(WITH_RS232_BRIDGE_RX, WITH_RS232_BRIDGE_TX);
// The Adafruit Uart object may already be active on its variant defaults.
// Stop it before changing pins or the EasyDMA instance can retain the old
// pin selection and silently receive nothing.
mesh::bridge::prepareNrfUart(*((Uart *)_serial),
WITH_RS232_BRIDGE_RX, WITH_RS232_BRIDGE_TX);
#elif defined(RP2040_PLATFORM)
((SerialUART *)_serial)->setRX(WITH_RS232_BRIDGE_RX);
((SerialUART *)_serial)->setTX(WITH_RS232_BRIDGE_TX);
+13
View File
@@ -0,0 +1,13 @@
#pragma once
namespace mesh {
namespace bridge {
template <typename UartType, typename PinType>
inline void prepareNrfUart(UartType& uart, PinType rx, PinType tx) {
uart.end();
uart.setPins(rx, tx);
}
} // namespace bridge
} // namespace mesh
+28
View File
@@ -0,0 +1,28 @@
#pragma once
#include <stdint.h>
// Keep the link available for the same two-minute window used by the pairing
// PIN screen. An expired session is disconnected, but its bond is not erased.
static const uint32_t BLE_SECURITY_SESSION_TIMEOUT_MS = 120000UL;
class SecuritySessionTimer {
bool _pending;
uint32_t _started_at;
public:
SecuritySessionTimer() : _pending(false), _started_at(0) {}
void start(uint32_t now) {
_pending = true;
_started_at = now;
}
void cancel() { _pending = false; }
bool pending() const { return _pending; }
bool expired(uint32_t now,
uint32_t timeout_ms = BLE_SECURITY_SESSION_TIMEOUT_MS) const {
return _pending && (uint32_t)(now - _started_at) >= timeout_ms;
}
};
+18
View File
@@ -36,6 +36,7 @@ void SerialBLEInterface::onConnect(uint16_t connection_handle) {
if (instance) {
instance->_conn_handle = connection_handle;
instance->_isDeviceConnected = false;
instance->_security_timer.start(millis());
instance->clearBuffers();
}
}
@@ -46,6 +47,7 @@ void SerialBLEInterface::onDisconnect(uint16_t connection_handle, uint8_t reason
if (instance->_conn_handle == connection_handle) {
instance->_conn_handle = BLE_CONN_HANDLE_INVALID;
instance->_isDeviceConnected = false;
instance->_security_timer.cancel();
instance->clearBuffers();
}
}
@@ -59,6 +61,7 @@ void SerialBLEInterface::onSecured(uint16_t connection_handle) {
if (conn == nullptr || !conn->secured()) {
BLE_DEBUG_PRINTLN("SerialBLEInterface: security update did not secure the link");
instance->_isDeviceConnected = false;
instance->_security_timer.cancel();
if (conn != nullptr && conn->bonded()) {
instance->removeStoredBondForPeer("unsecured link");
}
@@ -67,6 +70,7 @@ void SerialBLEInterface::onSecured(uint16_t connection_handle) {
}
instance->_isDeviceConnected = true;
instance->_security_timer.cancel();
// Connection interval units: 1.25ms, supervision timeout units: 10ms
// Apple: "The product will not read or use the parameters in the Peripheral Preferred Connection Parameters characteristic."
@@ -113,6 +117,7 @@ void SerialBLEInterface::onPairingComplete(uint16_t connection_handle, uint8_t a
instance->removeStoredBondForPeer("pairing failure");
}
instance->_isDeviceConnected = false;
instance->_security_timer.cancel();
instance->disconnect();
}
} else {
@@ -140,6 +145,7 @@ void SerialBLEInterface::onBLEEvent(ble_evt_t* evt) {
instance->removeStoredBondForPeer("failed bond encryption");
}
instance->_isDeviceConnected = false;
instance->_security_timer.cancel();
sd_ble_gap_disconnect(conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
}
} else if (evt->header.evt_id == BLE_GAP_EVT_DISCONNECTED) {
@@ -335,6 +341,7 @@ void SerialBLEInterface::disable() {
Bluefruit.Advertising.restartOnDisconnect(false);
Bluefruit.Advertising.stop();
disconnect();
_security_timer.cancel();
_last_health_check = 0;
}
@@ -408,6 +415,17 @@ size_t SerialBLEInterface::checkRecvFrame(uint8_t dest[]) {
// Advertising watchdog: periodically check if advertising is running, restart if not
// Only run when truly disconnected (no connection handle), not during connection establishment
unsigned long now = millis();
if (_isEnabled && _conn_handle != BLE_CONN_HANDLE_INVALID
&& _security_timer.expired(now)) {
// A client may open a link and never finish PIN/bond negotiation. That
// otherwise suppresses advertising forever because a connection handle
// remains live. Disconnect only: inactivity is not evidence of a stale
// bond, so do not erase anything here.
BLE_DEBUG_PRINTLN("SerialBLEInterface: security setup timed out after %lu ms",
(unsigned long)BLE_SECURITY_SESSION_TIMEOUT_MS);
_security_timer.cancel();
disconnect();
}
if (_isEnabled && !isConnected() && _conn_handle == BLE_CONN_HANDLE_INVALID) {
if (now - _last_health_check >= BLE_HEALTH_CHECK_INTERVAL) {
_last_health_check = now;
+2
View File
@@ -1,6 +1,7 @@
#pragma once
#include "../BaseSerialInterface.h"
#include "SecuritySessionTimer.h"
#include <bluefruit.h>
#ifndef BLE_TX_POWER
@@ -18,6 +19,7 @@ class SerialBLEInterface : public BaseSerialInterface {
ble_gap_addr_t _peer_address = {};
bool _peer_address_valid;
bool _bond_removed_for_connection;
SecuritySessionTimer _security_timer;
struct Frame {
uint8_t len;
@@ -39,6 +39,12 @@ public:
void doResetAGC() override { sx126xResetAGC((SX126x *)_radio); }
protected:
bool radioDeepInit() override {
return ((CustomLLCC68 *)_radio)->std_init();
}
bool supportsRadioDeepInit() const override { return true; }
protected:
bool applyRxBoostedGainMode(bool en) override {
return ((CustomLLCC68 *)_radio)->setRxBoostedGainMode(en) == RADIOLIB_ERR_NONE;
@@ -91,6 +91,7 @@ protected:
// via NRST - the only way out of a hard-locked chip (BUSY stuck high).
return ((CustomSX1262 *)_radio)->std_init();
}
bool supportsRadioDeepInit() const override { return true; }
void doResetAGC() override { sx126xResetAGC((SX126x *)_radio); }
@@ -43,6 +43,12 @@ public:
void doResetAGC() override { sx126xResetAGC((SX126x *)_radio); }
protected:
bool radioDeepInit() override {
return ((CustomSX1268 *)_radio)->std_init();
}
bool supportsRadioDeepInit() const override { return true; }
protected:
bool applyRxBoostedGainMode(bool en) override {
return ((CustomSX1268 *)_radio)->setRxBoostedGainMode(en) == RADIOLIB_ERR_NONE;
@@ -39,4 +39,10 @@ public:
return packetScoreInt(snr, sf, packet_len);
}
uint8_t getSpreadingFactor() const override { return ((CustomSX1276 *)_radio)->spreadingFactor; }
protected:
bool radioDeepInit() override {
return ((CustomSX1276 *)_radio)->std_init();
}
bool supportsRadioDeepInit() const override { return true; }
};
+58 -21
View File
@@ -92,6 +92,31 @@ void RadioLibWrapper::endReconfigure(bool resume_rx) {
if (resume_rx) startRecv();
}
bool RadioLibWrapper::restoreAfterDeepInit() {
if (!radioDeepInit()) return false;
_rx_ps_armed = false;
state = STATE_IDLE;
_radio->setPacketReceivedAction(setFlag);
bool restored;
if (_params_valid) {
restored = applyParams(_cur_freq, _cur_bw, _cur_sf, _cur_cr);
} else {
_preamble_sf = getSpreadingFactor();
restored = _radio->setPreambleLength(preambleLengthForSF(_preamble_sf))
== RADIOLIB_ERR_NONE;
}
if (_dbm_valid) {
restored = _radio->setOutputPower(_cur_dbm) == RADIOLIB_ERR_NONE && restored;
}
if (_rx_boosted_gain_valid) {
restored = applyRxBoostedGainMode(_cur_rx_boosted_gain) && restored;
}
recalibrateNoiseFloor();
return restored;
}
mesh::RadioParamApplyResult RadioLibWrapper::trySetParams(float freq, float bw, uint8_t sf, uint8_t cr,
const uint32_t* rx_ps_timings) {
if (rx_ps_timings != NULL && !supportsRxPowerSaving()) {
@@ -119,19 +144,7 @@ mesh::RadioParamApplyResult RadioLibWrapper::trySetParams(float freq, float bw,
bool restored = had_previous_params
&& applyParams(previous_freq, previous_bw, previous_sf, previous_cr);
if (!restored && radioDeepInit()) {
_rx_ps_armed = false;
state = STATE_IDLE;
_radio->setPacketReceivedAction(setFlag);
if (had_previous_params) {
restored = applyParams(previous_freq, previous_bw, previous_sf, previous_cr);
} else {
_preamble_sf = getSpreadingFactor();
restored = _radio->setPreambleLength(preambleLengthForSF(_preamble_sf)) == RADIOLIB_ERR_NONE;
}
if (_dbm_valid) _radio->setOutputPower(_cur_dbm);
if (_rx_boosted_gain_valid) applyRxBoostedGainMode(_cur_rx_boosted_gain);
}
if (!restored) restored = restoreAfterDeepInit();
if (!restored) {
MESH_DEBUG_PRINTLN("RadioLibWrapper: failed to restore radio parameters after apply failure");
@@ -234,6 +247,37 @@ void RadioLibWrapper::resetAGC() {
_nf_calib_deadline = 0; // starts after reset recovery reaches RX
}
bool RadioLibWrapper::recoverRadio(bool hard) {
const uint8_t base_state = state & ~STATE_INT_READY;
if ((state & STATE_INT_READY) != 0 || base_state == STATE_TX_WAIT) return false;
const bool busy = isChipBusy();
if (!busy && isReceivingPacket()) return false;
if (hard) {
n_wd_hard++;
if (supportsRadioDeepInit()) {
MESH_DEBUG_PRINTLN("RadioLibWrapper: liveness watchdog: hard radio reset");
return restoreAfterDeepInit();
}
// LR11xx and integrated radios do not all expose a safe board-level reset
// here. Fall back to their proven AGC/RX re-arm instead of reporting a
// successful no-op. A stuck BUSY pin still reports failure and is retried.
if (busy) return false;
MESH_DEBUG_PRINTLN("RadioLibWrapper: hard reset unavailable; using RX re-arm");
resetAGC();
return true;
}
// Never issue a warm-sleep/standby command while BUSY is stuck high. The
// hard stage can still escape that condition through the hardware reset pin.
if (busy) return false;
n_wd_soft++;
MESH_DEBUG_PRINTLN("RadioLibWrapper: liveness watchdog: soft AGC/RX re-arm");
resetAGC();
return true;
}
void RadioLibWrapper::rxPsWatchdogCheck() {
// don't interfere mid-transmit or with a completed-but-unread packet
// (a pending DIO1 event is itself proof the radio is alive; recvRaw() will
@@ -296,14 +340,7 @@ void RadioLibWrapper::rxPsWatchdogCheck() {
_wd_stage = 2;
n_wd_hard++;
MESH_DEBUG_PRINTLN("RadioLibWrapper: watchdog: still stuck, hard radio reset");
if (radioDeepInit()) {
_rx_ps_armed = false; // chip is factory-fresh after NRST
state = STATE_IDLE;
_radio->setPacketReceivedAction(setFlag);
if (_params_valid) setParams(_cur_freq, _cur_bw, _cur_sf, _cur_cr);
if (_dbm_valid) _radio->setOutputPower(_cur_dbm);
if (_rx_boosted_gain_valid) applyRxBoostedGainMode(_cur_rx_boosted_gain);
}
restoreAfterDeepInit();
state = STATE_IDLE; // re-arm (rx powersaving settings are kept in members)
}
}
+3
View File
@@ -80,11 +80,13 @@ protected:
// full radio recovery: hardware reset (NRST) + re-init to boot defaults;
// returns false if unsupported. Caller reapplies cached runtime params.
virtual bool radioDeepInit() { return false; }
virtual bool supportsRadioDeepInit() const { return false; }
virtual bool applyParams(float freq, float bw, uint8_t sf, uint8_t cr) = 0;
virtual bool applyRxBoostedGainMode(bool) { return false; }
// 0 = reconfigure from idle, 1 = resume RX afterwards, 2 = currently busy.
uint8_t beginReconfigure();
void endReconfigure(bool resume_rx);
bool restoreAfterDeepInit();
float packetScoreInt(float snr, int sf, int packet_len);
virtual bool isReceivingPacket() =0;
virtual void doResetAGC();
@@ -152,6 +154,7 @@ public:
void resetAGC() override;
void loop() override;
bool recoverRadio(bool hard) override;
uint32_t getPacketsRecv() const { return n_recv; }
uint32_t getPacketsRecvErrors() const override { return n_recv_errors; }