Harden marathon-tested OTA and hardware paths

Add durable TempRadio, ACL, clock, bridge, GPS/I2C, USB logging, and Indicator recovery safeguards together with expanded automation, build/profile contracts, release metadata, and the hardware validation ledger.
This commit is contained in:
mikecarper committed 2026-08-30 19:26:15 -07:00
1 parent e26d48e4ca
commit 9fd580c89e
109 files changed
+18697 -1094

No files matched your search

+79 -6
View File
@@ -23,25 +23,98 @@
#define MAX_PATH_SIZE 64
#define MAX_TRANS_UNIT 255
#if defined(ARDUINO) && defined(NRF52_PLATFORM) && \
((defined(MESH_DEBUG) && MESH_DEBUG) || \
(defined(BRIDGE_DEBUG) && BRIDGE_DEBUG) || \
(defined(POWERSAVING_DEBUG) && POWERSAVING_DEBUG))
#include <Arduino.h>
#include <atomic>
#include <stdarg.h>
#include <stdio.h>
#include <string.h>
#include "helpers/NonBlockingWriteStream.h"
namespace mesh {
// Adafruit_USBD_CDC::write() waits until the complete buffer has entered the
// TinyUSB FIFO. That is normally convenient, but it can wait forever when a
// host has opened the dedicated logging CDC without draining it. Keep debug
// output best-effort on nRF52: format into one bounded record, preserve a
// visible truncation marker, and submit it only when the whole record fits in
// the FIFO snapshot. The atomic flag also prevents two debug callers from both
// relying on the same availableForWrite() result.
inline size_t nrf52DebugPrintf(const char* format, ...) {
if (format == nullptr || !isUsbLoggingEnabled()) return 0;
static std::atomic_flag writer_busy = ATOMIC_FLAG_INIT;
if (writer_busy.test_and_set(std::memory_order_acquire)) return 0;
char output[256];
va_list args;
va_start(args, format);
const int required = vsnprintf(output, sizeof(output), format, args);
va_end(args);
size_t length = 0;
if (required > 0) {
length = static_cast<size_t>(required);
if (length >= sizeof(output)) {
length = sizeof(output) - 1;
const size_t format_length = strlen(format);
const bool preserve_newline = format_length > 0
&& format[format_length - 1] == '\n';
const size_t marker_length = preserve_newline ? 4 : 3;
memcpy(output + length - marker_length, "...", 3);
if (preserve_newline) output[length - 1] = '\n';
}
}
size_t written = 0;
if (length > 0) {
Stream& port = usbLoggingPort();
written = port.write(reinterpret_cast<const uint8_t*>(output), length);
}
writer_busy.clear(std::memory_order_release);
return written;
}
} // namespace mesh
#endif
#if MESH_DEBUG && ARDUINO
#include <Arduino.h>
#define MESH_DEBUG_PRINT(F, ...) do { if (mesh::isUsbLoggingEnabled() && mesh::usbLoggingPort().availableForWrite() > 0) { mesh::usbLoggingPort().printf("DEBUG: " F, ##__VA_ARGS__); } } while(0)
#define MESH_DEBUG_PRINTLN(F, ...) do { if (mesh::isUsbLoggingEnabled() && mesh::usbLoggingPort().availableForWrite() > 0) { mesh::usbLoggingPort().printf("DEBUG: " F "\n", ##__VA_ARGS__); } } while(0)
#if defined(NRF52_PLATFORM)
#define MESH_DEBUG_PRINT(F, ...) do { mesh::nrf52DebugPrintf("DEBUG: " F, ##__VA_ARGS__); } while(0)
#define MESH_DEBUG_PRINTLN(F, ...) do { mesh::nrf52DebugPrintf("DEBUG: " F "\n", ##__VA_ARGS__); } while(0)
#else
#define MESH_DEBUG_PRINT(F, ...) do { if (mesh::isUsbLoggingEnabled() && mesh::usbLoggingPort().availableForWrite() > 0) { mesh::usbLoggingPort().printf("DEBUG: " F, ##__VA_ARGS__); } } while(0)
#define MESH_DEBUG_PRINTLN(F, ...) do { if (mesh::isUsbLoggingEnabled() && mesh::usbLoggingPort().availableForWrite() > 0) { mesh::usbLoggingPort().printf("DEBUG: " F "\n", ##__VA_ARGS__); } } while(0)
#endif
#else
#define MESH_DEBUG_PRINT(...) {}
#define MESH_DEBUG_PRINTLN(...) {}
#endif
#if BRIDGE_DEBUG && ARDUINO
#define BRIDGE_DEBUG_PRINTLN(F, ...) do { if (mesh::isUsbLoggingEnabled() && mesh::usbLoggingPort().availableForWrite() > 0) { mesh::usbLoggingPort().printf("%s BRIDGE: " F, getLogDateTime(), ##__VA_ARGS__); } } while(0)
#if defined(NRF52_PLATFORM)
#define BRIDGE_DEBUG_PRINTLN(F, ...) do { mesh::nrf52DebugPrintf("%s BRIDGE: " F, getLogDateTime(), ##__VA_ARGS__); } while(0)
#else
#define BRIDGE_DEBUG_PRINTLN(F, ...) do { if (mesh::isUsbLoggingEnabled() && mesh::usbLoggingPort().availableForWrite() > 0) { mesh::usbLoggingPort().printf("%s BRIDGE: " F, getLogDateTime(), ##__VA_ARGS__); } } while(0)
#endif
#else
#define BRIDGE_DEBUG_PRINTLN(...) {}
#define BRIDGE_DEBUG_PRINTLN(...) {}
#endif
#if POWERSAVING_DEBUG && ARDUINO
#include <Arduino.h>
#define POWERSAVING_DEBUG_PRINT(F, ...) do { if (mesh::isUsbLoggingEnabled()) { mesh::usbLoggingPort().printf("POWERSAVING: " F, ##__VA_ARGS__); } } while(0)
#define POWERSAVING_DEBUG_PRINTLN(F, ...) do { if (mesh::isUsbLoggingEnabled()) { mesh::usbLoggingPort().printf("POWERSAVING: " F "\n", ##__VA_ARGS__); } } while(0)
#if defined(NRF52_PLATFORM)
#define POWERSAVING_DEBUG_PRINT(F, ...) do { mesh::nrf52DebugPrintf("POWERSAVING: " F, ##__VA_ARGS__); } while(0)
#define POWERSAVING_DEBUG_PRINTLN(F, ...) do { mesh::nrf52DebugPrintf("POWERSAVING: " F "\n", ##__VA_ARGS__); } while(0)
#else
#define POWERSAVING_DEBUG_PRINT(F, ...) do { if (mesh::isUsbLoggingEnabled()) { mesh::usbLoggingPort().printf("POWERSAVING: " F, ##__VA_ARGS__); } } while(0)
#define POWERSAVING_DEBUG_PRINTLN(F, ...) do { if (mesh::isUsbLoggingEnabled()) { mesh::usbLoggingPort().printf("POWERSAVING: " F "\n", ##__VA_ARGS__); } } while(0)
#endif
#else
#define POWERSAVING_DEBUG_PRINT(...) {}
#define POWERSAVING_DEBUG_PRINTLN(...) {}
+583 -38
View File
@@ -1,11 +1,110 @@
#include "ClientACL.h"
#include "ClientACLFileTransaction.h"
#include "ClientACLFileIntegrity.h"
#include "ClientLoginPersistence.h"
#include "ClientPathPersistence.h"
#if defined(NRF52_PLATFORM)
#include "AtomicFileWriter.h"
#endif
static const uint8_t CONTACT_RECORD_VERSION_ALT_PATH = 1;
static const uint8_t EMPTY_OUT_PATH[MAX_PATH_SIZE] = {};
static File openRead(FILESYSTEM* fs, const char* filename) {
#if defined(RP2040_PLATFORM)
return fs->open(filename, "r");
#else
return fs->open(filename);
#endif
}
#if !defined(NRF52_PLATFORM)
static const size_t CONTACT_RECORD_SIZE =
32 + 1 + 4 + 2 + 1 + 64 + PUB_KEY_SIZE + 1 + 64;
static const size_t LEGACY_CONTACT_RECORD_SIZE =
32 + 1 + 4 + 2 + 1 + 64 + PUB_KEY_SIZE;
#endif
static bool readPersistedClientPath(FILESYSTEM* fs,
const uint8_t pubkey[PUB_KEY_SIZE],
uint8_t* path_len,
uint8_t path[MAX_PATH_SIZE]) {
if (!fs->exists(mesh::CLIENT_ACL_PRIMARY_PATH)) return false;
File file = openRead(fs, mesh::CLIENT_ACL_PRIMARY_PATH);
if (!file) return false;
bool found = false;
while (!found) {
uint8_t record_pubkey[PUB_KEY_SIZE];
uint8_t permissions;
uint32_t sync_since;
uint8_t version[2];
uint8_t record_path_len;
uint8_t record_path[MAX_PATH_SIZE];
uint8_t shared_secret[PUB_KEY_SIZE];
bool success = file.read(record_pubkey, sizeof(record_pubkey))
== (int)sizeof(record_pubkey);
success = success && file.read(&permissions, sizeof(permissions))
== (int)sizeof(permissions);
success = success
&& file.read((uint8_t*)&sync_since, sizeof(sync_since))
== (int)sizeof(sync_since);
success = success && file.read(version, sizeof(version))
== (int)sizeof(version);
success = success && file.read(&record_path_len, sizeof(record_path_len))
== (int)sizeof(record_path_len);
success = success && file.read(record_path, sizeof(record_path))
== (int)sizeof(record_path);
success = success && file.read(shared_secret, sizeof(shared_secret))
== (int)sizeof(shared_secret);
if (!success) break;
if (version[0] >= CONTACT_RECORD_VERSION_ALT_PATH) {
uint8_t alt_path_len;
uint8_t alt_path[MAX_PATH_SIZE];
success = file.read(&alt_path_len, sizeof(alt_path_len))
== (int)sizeof(alt_path_len);
success = success && file.read(alt_path, sizeof(alt_path))
== (int)sizeof(alt_path);
if (!success) break;
}
if (memcmp(record_pubkey, pubkey, PUB_KEY_SIZE) == 0
&& (record_path_len == OUT_PATH_UNKNOWN
|| record_path_len == OUT_PATH_FORCE_FLOOD
|| mesh::isValidEncodedClientPathLength(
record_path_len, MAX_PATH_SIZE))) {
*path_len = record_path_len;
memcpy(path, record_path, MAX_PATH_SIZE);
found = true;
}
}
file.close();
return found;
}
static mesh::StoredClientPathView storedClientPathForSave(
FILESYSTEM* fs,
const ClientInfo* client,
uint8_t prior_path[MAX_PATH_SIZE],
uint8_t* prior_path_len) {
const bool prior_exists = !client->out_path_is_persistable
&& readPersistedClientPath(
fs, client->id.pub_key, prior_path_len, prior_path);
return mesh::selectStoredClientPath(
client->out_path_is_persistable,
client->out_path_len,
client->out_path,
prior_exists,
*prior_path_len,
prior_path,
OUT_PATH_UNKNOWN,
EMPTY_OUT_PATH);
}
#if !defined(NRF52_PLATFORM)
static File openWrite(FILESYSTEM* _fs, const char* filename) {
#if defined(STM32_PLATFORM)
_fs->remove(filename);
@@ -16,11 +115,337 @@ static File openWrite(FILESYSTEM* _fs, const char* filename) {
return _fs->open(filename, "w", true);
#endif
}
static bool readMatches(File& file, const uint8_t* expected, size_t length) {
uint8_t buffer[32];
while (length > 0) {
const size_t chunk = length < sizeof(buffer) ? length : sizeof(buffer);
if (file.read(buffer, chunk) != (int)chunk
|| memcmp(buffer, expected, chunk) != 0) {
return false;
}
expected += chunk;
length -= chunk;
}
return true;
}
static bool validateContactsFileIntegrity(FILESYSTEM* fs,
const char* filename) {
File file = openRead(fs, filename);
if (!file) return false;
const size_t size = file.size();
const bool has_crc = size >= 8 && (size - 8) % CONTACT_RECORD_SIZE == 0;
// A backup means publication was interrupted or is being finalized. In that
// state a primary without its CRC trailer is a torn new image, not a legacy
// image, even when truncation lands exactly on a record-size multiple.
const bool crc_required = strcmp(filename, mesh::CLIENT_ACL_PRIMARY_PATH) == 0
&& fs->exists(mesh::CLIENT_ACL_BACKUP_PATH);
if (!has_crc && size % CONTACT_RECORD_SIZE != 0
&& size % LEGACY_CONTACT_RECORD_SIZE != 0) {
file.close();
return false;
}
if (!has_crc) {
file.close();
return !crc_required; // standalone legacy fixed-record image
}
uint32_t crc = 0xFFFFFFFFUL;
size_t remaining = size - 8;
uint8_t buffer[32];
while (remaining != 0) {
const size_t chunk = remaining < sizeof(buffer) ? remaining : sizeof(buffer);
if (file.read(buffer, chunk) != (int)chunk) {
file.close();
return false;
}
crc = mesh::updateClientACLCRC(crc, buffer, chunk);
remaining -= chunk;
}
uint8_t magic[4];
uint32_t stored_crc;
const bool valid = file.read(magic, sizeof(magic)) == (int)sizeof(magic)
&& file.read((uint8_t*)&stored_crc, sizeof(stored_crc))
== (int)sizeof(stored_crc)
&& memcmp(magic, mesh::CLIENT_ACL_CRC_MAGIC, sizeof(magic)) == 0
&& stored_crc == (crc ^ 0xFFFFFFFFUL);
file.close();
return valid;
}
static bool verifyContactsFile(
FILESYSTEM* fs,
const char* filename,
ClientInfo* clients,
int num_clients,
bool (*filter)(ClientInfo*),
size_t expected_size) {
File file = openRead(fs, filename);
if (!file || file.size() != expected_size + 8) {
if (file) file.close();
return false;
}
const uint8_t unused[2] = {CONTACT_RECORD_VERSION_ALT_PATH, 0};
bool matches = true;
for (int i = 0; matches && i < num_clients; i++) {
ClientInfo* c = &clients[i];
if (!mesh::clientRoleIsPersisted(
c->permissions, PERM_ACL_ROLE_MASK, PERM_ACL_GUEST)
|| (filter && !filter(c))) continue;
uint8_t prior_path_len = OUT_PATH_UNKNOWN;
uint8_t prior_path[MAX_PATH_SIZE] = {};
const mesh::StoredClientPathView persisted_path =
storedClientPathForSave(
fs, c, prior_path, &prior_path_len);
matches = readMatches(file, c->id.pub_key, 32)
&& readMatches(file, &c->permissions, 1)
&& readMatches(file, (uint8_t*)&c->extra.room.sync_since, 4)
&& readMatches(file, unused, sizeof(unused))
&& readMatches(file, &persisted_path.encoded_path_len, 1)
&& readMatches(file, persisted_path.path, 64)
&& readMatches(file, c->shared_secret, PUB_KEY_SIZE)
&& readMatches(file, &c->alt_path_len, 1)
&& readMatches(file, c->alt_path, 64);
}
uint8_t magic[4];
uint32_t stored_crc;
matches = matches
&& file.read(magic, sizeof(magic)) == (int)sizeof(magic)
&& file.read((uint8_t*)&stored_crc, sizeof(stored_crc))
== (int)sizeof(stored_crc)
&& memcmp(magic, mesh::CLIENT_ACL_CRC_MAGIC, sizeof(magic)) == 0;
file.close();
return matches && validateContactsFileIntegrity(fs, filename);
}
#endif
static bool validateLoginReplayFileIntegrity(FILESYSTEM* fs,
const char* filename) {
File file = openRead(fs, filename);
if (!file) return false;
const size_t size = file.size();
if (size < mesh::CLIENT_LOGIN_REPLAY_TRAILER_SIZE) {
file.close();
return false;
}
const size_t payload_size =
size - mesh::CLIENT_LOGIN_REPLAY_TRAILER_SIZE;
const size_t record_count =
payload_size / mesh::CLIENT_LOGIN_REPLAY_RECORD_SIZE;
if (payload_size % mesh::CLIENT_LOGIN_REPLAY_RECORD_SIZE != 0
|| record_count > mesh::MAX_CLIENT_LOGIN_REPLAY_IDENTITIES) {
file.close();
return false;
}
uint32_t crc = 0xFFFFFFFFUL;
bool valid = true;
for (size_t i = 0; valid && i < record_count; i++) {
uint8_t pubkey[PUB_KEY_SIZE];
uint32_t ceiling;
valid = file.read(pubkey, sizeof(pubkey)) == (int)sizeof(pubkey)
&& file.read((uint8_t*)&ceiling, sizeof(ceiling))
== (int)sizeof(ceiling)
&& ceiling != 0;
if (valid) {
crc = mesh::updateClientLoginReplayCRC(
crc, pubkey, sizeof(pubkey));
crc = mesh::updateClientLoginReplayCRC(
crc, (const uint8_t*)&ceiling, sizeof(ceiling));
}
}
uint8_t magic[sizeof(mesh::CLIENT_LOGIN_REPLAY_MAGIC)];
uint32_t stored_crc;
valid = valid
&& file.read(magic, sizeof(magic)) == (int)sizeof(magic)
&& file.read((uint8_t*)&stored_crc, sizeof(stored_crc))
== (int)sizeof(stored_crc)
&& memcmp(magic, mesh::CLIENT_LOGIN_REPLAY_MAGIC,
sizeof(magic)) == 0
&& stored_crc == (crc ^ 0xFFFFFFFFUL);
file.close();
return valid;
}
// The image is validated before this scan. Choose the maximum if a legacy or
// manually recovered image somehow contains a duplicate identity; taking the
// strongest boundary remains fail-safe.
static bool readClientLoginReplayCeiling(
FILESYSTEM* fs,
const uint8_t pubkey[PUB_KEY_SIZE],
uint32_t* ceiling,
bool* found) {
*ceiling = 0;
*found = false;
if (!fs->exists(mesh::CLIENT_LOGIN_REPLAY_PRIMARY_PATH)) return true;
if (!validateLoginReplayFileIntegrity(
fs, mesh::CLIENT_LOGIN_REPLAY_PRIMARY_PATH)) {
return false;
}
File file = openRead(fs, mesh::CLIENT_LOGIN_REPLAY_PRIMARY_PATH);
if (!file) return false;
const size_t record_count =
(file.size() - mesh::CLIENT_LOGIN_REPLAY_TRAILER_SIZE)
/ mesh::CLIENT_LOGIN_REPLAY_RECORD_SIZE;
bool success = true;
for (size_t i = 0; success && i < record_count; i++) {
uint8_t record_pubkey[PUB_KEY_SIZE];
uint32_t record_ceiling;
success = file.read(record_pubkey, sizeof(record_pubkey))
== (int)sizeof(record_pubkey);
success = success
&& file.read((uint8_t*)&record_ceiling, sizeof(record_ceiling))
== (int)sizeof(record_ceiling);
if (success && memcmp(record_pubkey, pubkey, PUB_KEY_SIZE) == 0
&& (!*found || record_ceiling > *ceiling)) {
*ceiling = record_ceiling;
*found = true;
}
}
file.close();
return success;
}
template <typename Writer>
static bool writeClientLoginReplayRecord(
Writer& writer,
const uint8_t pubkey[PUB_KEY_SIZE],
uint32_t ceiling,
uint32_t* crc) {
const bool success = writer.write(pubkey, PUB_KEY_SIZE) == PUB_KEY_SIZE
&& writer.write((const uint8_t*)&ceiling, sizeof(ceiling))
== sizeof(ceiling);
if (success) {
*crc = mesh::updateClientLoginReplayCRC(
*crc, pubkey, PUB_KEY_SIZE);
*crc = mesh::updateClientLoginReplayCRC(
*crc, (const uint8_t*)&ceiling, sizeof(ceiling));
}
return success;
}
static bool writeClientLoginReplayCeiling(
FILESYSTEM* fs,
const uint8_t pubkey[PUB_KEY_SIZE],
uint32_t new_ceiling,
mesh::ClientLoginReplayReservationAction action) {
if (action == mesh::ClientLoginReplayReservationAction::None) return true;
#if defined(NRF52_PLATFORM)
if (fs->exists(mesh::CLIENT_LOGIN_REPLAY_PRIMARY_PATH)
&& !validateLoginReplayFileIntegrity(
fs, mesh::CLIENT_LOGIN_REPLAY_PRIMARY_PATH)) {
return false;
}
#else
if (!mesh::recoverClientLoginReplayFiles(
fs, validateLoginReplayFileIntegrity)) {
return false;
}
#endif
File source = openRead(fs, mesh::CLIENT_LOGIN_REPLAY_PRIMARY_PATH);
const size_t record_count = source
? (source.size() - mesh::CLIENT_LOGIN_REPLAY_TRAILER_SIZE)
/ mesh::CLIENT_LOGIN_REPLAY_RECORD_SIZE
: 0;
#if defined(NRF52_PLATFORM)
mesh::AtomicFileWriter destination(
fs, mesh::CLIENT_LOGIN_REPLAY_PRIMARY_PATH);
#else
File destination = openWrite(
fs, mesh::CLIENT_LOGIN_REPLAY_TEMP_PATH);
#endif
if (!destination) {
if (source) source.close();
return false;
}
uint32_t crc = 0xFFFFFFFFUL;
bool found = false;
bool success = true;
for (size_t i = 0; success && i < record_count; i++) {
uint8_t record_pubkey[PUB_KEY_SIZE];
uint32_t record_ceiling;
success = source.read(record_pubkey, sizeof(record_pubkey))
== (int)sizeof(record_pubkey);
success = success
&& source.read((uint8_t*)&record_ceiling, sizeof(record_ceiling))
== (int)sizeof(record_ceiling);
if (!success) break;
if (memcmp(record_pubkey, pubkey, PUB_KEY_SIZE) == 0) {
found = true;
if (record_ceiling < new_ceiling) record_ceiling = new_ceiling;
}
success = writeClientLoginReplayRecord(
destination, record_pubkey, record_ceiling, &crc);
}
if (source) source.close();
if (success
&& action == mesh::ClientLoginReplayReservationAction::UpdateExisting
&& !found) {
// Do not turn a low-trust update into insertion if the image changed
// between its admission read and this transaction.
success = false;
}
if (success && !found
&& action == mesh::ClientLoginReplayReservationAction::CreateNew) {
success = mesh::clientLoginReplayCanInsert(record_count);
}
if (success && !found) {
success = writeClientLoginReplayRecord(
destination, pubkey, new_ceiling, &crc);
}
if (success) {
const uint32_t final_crc = crc ^ 0xFFFFFFFFUL;
success = destination.write(
mesh::CLIENT_LOGIN_REPLAY_MAGIC,
sizeof(mesh::CLIENT_LOGIN_REPLAY_MAGIC))
== sizeof(mesh::CLIENT_LOGIN_REPLAY_MAGIC)
&& destination.write(
(const uint8_t*)&final_crc, sizeof(final_crc))
== sizeof(final_crc);
}
#if defined(NRF52_PLATFORM)
return destination.commit(success);
#else
destination.close();
const bool verified = success && validateLoginReplayFileIntegrity(
fs, mesh::CLIENT_LOGIN_REPLAY_TEMP_PATH);
return mesh::publishClientLoginReplayTemp(
fs, verified, validateLoginReplayFileIntegrity);
#endif
}
void ClientACL::load(FILESYSTEM* fs, const mesh::LocalIdentity& self_id) {
_fs = fs;
num_clients = 0;
#if defined(NRF52_PLATFORM)
// AtomicFileWriter may leave only a harmless temp image when reset before
// rename. The live image remains authoritative.
mesh::removeClientLoginReplayArtifact(
_fs, mesh::CLIENT_LOGIN_REPLAY_TEMP_PATH);
login_replay_store_available =
!_fs->exists(mesh::CLIENT_LOGIN_REPLAY_PRIMARY_PATH)
|| validateLoginReplayFileIntegrity(
_fs, mesh::CLIENT_LOGIN_REPLAY_PRIMARY_PATH);
#else
login_replay_store_available = mesh::recoverClientLoginReplayFiles(
_fs, validateLoginReplayFileIntegrity);
#endif
if (!login_replay_store_available) {
MESH_DEBUG_PRINTLN(
"ERROR: ClientACL::load could not recover login replay state");
}
#if !defined(NRF52_PLATFORM)
if (!mesh::recoverClientACLFilesVerified(
_fs, validateContactsFileIntegrity)) {
MESH_DEBUG_PRINTLN("ERROR: ClientACL::load could not recover contacts files");
return;
}
#endif
if (_fs->exists("/s_contacts")) {
#if defined(RP2040_PLATFORM)
File file = _fs->open("/s_contacts", "r");
@@ -52,6 +477,22 @@ void ClientACL::load(FILESYSTEM* fs, const mesh::LocalIdentity& self_id) {
if (!success) break; // EOF
c.id = mesh::Identity(pub_key);
c.out_path_is_persistable = true;
if (login_replay_store_available) {
uint32_t replay_ceiling;
bool replay_entry_found;
if (!readClientLoginReplayCeiling(
_fs, pub_key, &replay_ceiling, &replay_entry_found)) {
login_replay_store_available = false;
c.last_timestamp = UINT32_MAX;
} else if (replay_entry_found) {
// On boot, skip the unused reservation tail. During this boot a
// successful login replaces this with its exact accepted value.
c.last_timestamp = replay_ceiling;
}
} else {
c.last_timestamp = UINT32_MAX;
}
self_id.calcSharedSecret(c.shared_secret, pub_key); // recalculate shared secrets in case our private key changed
if (num_clients < MAX_CLIENTS) {
clients[num_clients++] = c;
@@ -64,43 +505,146 @@ void ClientACL::load(FILESYSTEM* fs, const mesh::LocalIdentity& self_id) {
}
}
void ClientACL::save(FILESYSTEM* fs, bool (*filter)(ClientInfo*)) {
bool ClientACL::authorizeLoginTimestamp(
const uint8_t* pubkey,
uint32_t sender_timestamp,
uint32_t runtime_last_timestamp,
uint8_t login_permissions) {
if (_fs == NULL || pubkey == NULL || !login_replay_store_available) {
return false;
}
uint32_t persisted_ceiling;
bool replay_entry_found;
if (!readClientLoginReplayCeiling(
_fs, pubkey, &persisted_ceiling, &replay_entry_found)) {
login_replay_store_available = false;
return false;
}
if (!replay_entry_found) persisted_ceiling = 0;
const bool role_needs_durable_replay =
mesh::clientLoginRoleNeedsDurableReplay(
login_permissions, PERM_ACL_ROLE_MASK,
PERM_ACL_GUEST, PERM_ACL_READ_ONLY);
const mesh::ClientLoginReplayPlan plan = mesh::planClientLoginReplay(
runtime_last_timestamp, persisted_ceiling, sender_timestamp);
if (!plan.fresh) return false;
const mesh::ClientLoginReplayReservationAction action =
mesh::selectClientLoginReplayReservation(
plan.reservation_needed, replay_entry_found,
role_needs_durable_replay);
if (action != mesh::ClientLoginReplayReservationAction::None
&& !writeClientLoginReplayCeiling(
_fs, pubkey, plan.reservation_ceiling, action)) {
// The old valid image remains usable after an ordinary write failure, but
// this login is not safe to accept until its new boundary is durable.
return false;
}
return true;
}
bool ClientACL::save(FILESYSTEM* fs, bool (*filter)(ClientInfo*)) {
_fs = fs;
#if defined(NRF52_PLATFORM)
mesh::AtomicFileWriter file(_fs, "/s_contacts");
#else
File file = openWrite(_fs, "/s_contacts");
#endif
if (file) {
uint8_t unused[2];
unused[0] = CONTACT_RECORD_VERSION_ALT_PATH;
unused[1] = 0;
bool success = true;
for (int i = 0; success && i < num_clients; i++) {
auto c = &clients[i];
if (c->permissions == 0 || (filter && !filter(c))) continue; // skip deleted entries, or by filter function
success = (file.write(c->id.pub_key, 32) == 32);
success = success && (file.write((uint8_t *) &c->permissions, 1) == 1);
success = success && (file.write((uint8_t *) &c->extra.room.sync_since, 4) == 4);
success = success && (file.write(unused, 2) == 2);
success = success && (file.write((uint8_t *)&c->out_path_len, 1) == 1);
success = success && (file.write(c->out_path, 64) == 64);
success = success && (file.write(c->shared_secret, PUB_KEY_SIZE) == PUB_KEY_SIZE);
success = success && (file.write((uint8_t *)&c->alt_path_len, 1) == 1);
success = success && (file.write(c->alt_path, 64) == 64);
if (!success) break; // write failed
}
#if defined(NRF52_PLATFORM)
if (!file.commit(success)) {
MESH_DEBUG_PRINTLN("ERROR: ClientACL::save atomic commit failed");
}
#else
file.close();
#endif
if (!mesh::recoverClientACLFilesVerified(
_fs, validateContactsFileIntegrity)) {
MESH_DEBUG_PRINTLN("ERROR: ClientACL::save recovery is incomplete");
return false;
}
File file = openWrite(_fs, mesh::CLIENT_ACL_TEMP_PATH);
#endif
if (!file) {
MESH_DEBUG_PRINTLN("ERROR: ClientACL::save could not open contacts file");
return false;
}
uint8_t unused[2];
unused[0] = CONTACT_RECORD_VERSION_ALT_PATH;
unused[1] = 0;
bool success = true;
#if !defined(NRF52_PLATFORM)
size_t expected_size = 0;
uint32_t contacts_crc = 0xFFFFFFFFUL;
#endif
for (int i = 0; success && i < num_clients; i++) {
auto c = &clients[i];
if (!mesh::clientRoleIsPersisted(
c->permissions, PERM_ACL_ROLE_MASK, PERM_ACL_GUEST)
|| (filter && !filter(c))) continue; // skip guests/deleted entries or filtered clients
success = (file.write(c->id.pub_key, 32) == 32);
success = success && (file.write((uint8_t *) &c->permissions, 1) == 1);
success = success && (file.write((uint8_t *) &c->extra.room.sync_since, 4) == 4);
success = success && (file.write(unused, 2) == 2);
uint8_t prior_path_len = OUT_PATH_UNKNOWN;
uint8_t prior_path[MAX_PATH_SIZE] = {};
const mesh::StoredClientPathView persisted_path =
storedClientPathForSave(
_fs, c, prior_path, &prior_path_len);
success = success
&& (file.write(&persisted_path.encoded_path_len, 1) == 1);
success = success
&& (file.write(persisted_path.path, MAX_PATH_SIZE) == MAX_PATH_SIZE);
success = success && (file.write(c->shared_secret, PUB_KEY_SIZE) == PUB_KEY_SIZE);
success = success && (file.write((uint8_t *)&c->alt_path_len, 1) == 1);
success = success && (file.write(c->alt_path, 64) == 64);
#if !defined(NRF52_PLATFORM)
if (success) {
expected_size += 32 + 1 + 4 + 2 + 1 + 64 + PUB_KEY_SIZE + 1 + 64;
contacts_crc = mesh::updateClientACLCRC(contacts_crc, c->id.pub_key, 32);
contacts_crc = mesh::updateClientACLCRC(contacts_crc, &c->permissions, 1);
contacts_crc = mesh::updateClientACLCRC(
contacts_crc, (uint8_t*)&c->extra.room.sync_since, 4);
contacts_crc = mesh::updateClientACLCRC(contacts_crc, unused, sizeof(unused));
contacts_crc = mesh::updateClientACLCRC(
contacts_crc, &persisted_path.encoded_path_len, 1);
contacts_crc = mesh::updateClientACLCRC(
contacts_crc, persisted_path.path, MAX_PATH_SIZE);
contacts_crc = mesh::updateClientACLCRC(contacts_crc, c->shared_secret, PUB_KEY_SIZE);
contacts_crc = mesh::updateClientACLCRC(contacts_crc, &c->alt_path_len, 1);
contacts_crc = mesh::updateClientACLCRC(contacts_crc, c->alt_path, 64);
}
#endif
}
#if !defined(NRF52_PLATFORM)
if (success) {
const uint32_t final_crc = contacts_crc ^ 0xFFFFFFFFUL;
success = file.write(mesh::CLIENT_ACL_CRC_MAGIC,
sizeof(mesh::CLIENT_ACL_CRC_MAGIC))
== sizeof(mesh::CLIENT_ACL_CRC_MAGIC)
&& file.write((const uint8_t*)&final_crc, sizeof(final_crc))
== sizeof(final_crc);
}
#endif
#if defined(NRF52_PLATFORM)
success = file.commit(success);
if (!success) {
MESH_DEBUG_PRINTLN("ERROR: ClientACL::save atomic commit failed");
}
#else
file.close();
if (success) {
success = verifyContactsFile(
_fs, mesh::CLIENT_ACL_TEMP_PATH, clients, num_clients,
filter, expected_size);
}
if (!success) {
mesh::publishVerifiedClientACLTemp(_fs, false);
MESH_DEBUG_PRINTLN("ERROR: ClientACL::save close/readback failed");
return false;
}
success = mesh::publishVerifiedClientACLTemp(
_fs, true, validateContactsFileIntegrity);
if (!success) {
MESH_DEBUG_PRINTLN("ERROR: ClientACL::save atomic publish failed");
}
#endif
return success;
}
bool ClientACL::clear() {
@@ -108,14 +652,14 @@ bool ClientACL::clear() {
if (_fs->exists("/s_contacts")) {
_fs->remove("/s_contacts");
}
#if defined(NRF52_PLATFORM)
if (_fs->exists("/s_contacts.tmp")) {
_fs->remove("/s_contacts.tmp");
}
#endif
if (_fs->exists("/s_contacts.tmp")) _fs->remove("/s_contacts.tmp");
if (_fs->exists("/s_contacts.bak")) _fs->remove("/s_contacts.bak");
const bool files_cleared = !_fs->exists("/s_contacts")
&& !_fs->exists("/s_contacts.tmp")
&& !_fs->exists("/s_contacts.bak");
memset(clients, 0, sizeof(clients));
num_clients = 0;
return true;
return files_cleared;
}
ClientInfo* ClientACL::getClient(const uint8_t* pubkey, int key_len) {
@@ -148,6 +692,7 @@ ClientInfo* ClientACL::putClient(const mesh::Identity& id, uint8_t init_perms) {
c->permissions = init_perms;
c->id = id;
c->out_path_len = OUT_PATH_UNKNOWN;
c->out_path_is_persistable = true;
c->alt_path_len = OUT_PATH_UNKNOWN;
return c;
}
+20 -3
View File
@@ -20,10 +20,11 @@ struct ClientInfo {
uint8_t permissions;
uint8_t out_path_len;
uint8_t out_path[MAX_PATH_SIZE];
bool out_path_is_persistable; // live route may replace, but not erase, durable route
uint8_t alt_path_len;
uint8_t alt_path[MAX_PATH_SIZE];
uint8_t shared_secret[PUB_KEY_SIZE];
uint32_t last_timestamp; // by THEIR clock (transient)
uint32_t last_timestamp; // by THEIR clock (exact live floor; reserved ceiling after load)
uint32_t last_activity; // by OUR clock (transient)
union {
struct {
@@ -50,16 +51,32 @@ class ClientACL {
FILESYSTEM* _fs;
ClientInfo clients[MAX_CLIENTS];
int num_clients;
bool login_replay_store_available;
public:
ClientACL() {
ClientACL() {
_fs = NULL;
memset(clients, 0, sizeof(clients));
num_clients = 0;
login_replay_store_available = false;
}
void load(FILESYSTEM* _fs, const mesh::LocalIdentity& self_id);
void save(FILESYSTEM* _fs, bool (*filter)(ClientInfo*)=NULL);
bool save(FILESYSTEM* _fs, bool (*filter)(ClientInfo*)=NULL);
bool clear();
// Authenticate the sender/password first, then call this before allocating
// or mutating a client. A true result means any required replay high-water
// reservation was durably published. runtime_last_timestamp is zero when
// this boot has no live state for the identity (including after eviction or
// revocation), in which case the durable tombstone is authoritative.
// login_permissions selects whether a missing identity may allocate durable
// state. Guest/read-only sessions still enforce and advance an existing
// tombstone, but otherwise use only their exact in-boot floor.
bool authorizeLoginTimestamp(const uint8_t* pubkey,
uint32_t sender_timestamp,
uint32_t runtime_last_timestamp,
uint8_t login_permissions);
ClientInfo* getClient(const uint8_t* pubkey, int key_len);
ClientInfo* putClient(const mesh::Identity& id, uint8_t init_perms);
bool applyPermissions(const mesh::LocalIdentity& self_id, const uint8_t* pubkey, int key_len, uint8_t perms);
+49
View File
@@ -0,0 +1,49 @@
#pragma once
#include <stddef.h>
#include <stdint.h>
#include <string.h>
namespace mesh {
static const uint8_t CLIENT_ACL_CRC_MAGIC[4] = {'M', 'C', 'A', '1'};
inline uint32_t updateClientACLCRC(uint32_t crc, const uint8_t* data,
size_t length) {
while (length-- != 0) {
crc ^= *data++;
for (uint8_t bit = 0; bit < 8; bit++) {
crc = (crc >> 1) ^ (0xEDB88320UL & (uint32_t)-(int32_t)(crc & 1U));
}
}
return crc;
}
enum ClientACLImageKind {
CLIENT_ACL_IMAGE_INVALID,
CLIENT_ACL_IMAGE_LEGACY,
CLIENT_ACL_IMAGE_CRC,
};
inline ClientACLImageKind classifyClientACLImage(
const uint8_t* image, size_t size,
size_t current_record_size, size_t legacy_record_size) {
if (size >= 8 && (size - 8) % current_record_size == 0) {
const size_t payload_size = size - 8;
uint32_t stored_crc;
memcpy(&stored_crc, image + payload_size + 4, sizeof(stored_crc));
uint32_t crc = updateClientACLCRC(0xFFFFFFFFUL, image, payload_size)
^ 0xFFFFFFFFUL;
if (memcmp(image + payload_size, CLIENT_ACL_CRC_MAGIC, 4) == 0
&& stored_crc == crc) {
return CLIENT_ACL_IMAGE_CRC;
}
}
if (size % current_record_size == 0
|| size % legacy_record_size == 0) {
return CLIENT_ACL_IMAGE_LEGACY;
}
return CLIENT_ACL_IMAGE_INVALID;
}
} // namespace mesh
+119
View File
@@ -0,0 +1,119 @@
#pragma once
namespace mesh {
static const char CLIENT_ACL_PRIMARY_PATH[] = "/s_contacts";
static const char CLIENT_ACL_TEMP_PATH[] = "/s_contacts.tmp";
static const char CLIENT_ACL_BACKUP_PATH[] = "/s_contacts.bak";
template <typename Filesystem>
bool removeClientACLArtifact(Filesystem* fs, const char* path) {
if (!fs->exists(path)) return true;
fs->remove(path);
return !fs->exists(path);
}
// Recover the last published image after any power-loss boundary in the
// temp -> backup -> primary transaction. A present primary is authoritative;
// if publication had not completed, the backup is restored instead.
template <typename Filesystem>
bool recoverClientACLFiles(Filesystem* fs) {
if (fs->exists(CLIENT_ACL_PRIMARY_PATH)) {
// The primary is already authoritative. Cleanup is best-effort: a
// filesystem which cannot remove a stale artifact must not make the
// committed image appear unavailable.
removeClientACLArtifact(fs, CLIENT_ACL_TEMP_PATH);
removeClientACLArtifact(fs, CLIENT_ACL_BACKUP_PATH);
return true;
}
if (fs->exists(CLIENT_ACL_BACKUP_PATH)) {
if (!fs->rename(CLIENT_ACL_BACKUP_PATH, CLIENT_ACL_PRIMARY_PATH)) {
return false;
}
removeClientACLArtifact(fs, CLIENT_ACL_TEMP_PATH);
return true;
}
return removeClientACLArtifact(fs, CLIENT_ACL_TEMP_PATH);
}
template <typename Filesystem, typename Validator>
bool recoverClientACLFilesVerified(Filesystem* fs, Validator is_valid) {
if (fs->exists(CLIENT_ACL_PRIMARY_PATH)
&& is_valid(fs, CLIENT_ACL_PRIMARY_PATH)) {
// A validated primary remains authoritative even when stale-artifact
// cleanup is temporarily unavailable.
removeClientACLArtifact(fs, CLIENT_ACL_TEMP_PATH);
removeClientACLArtifact(fs, CLIENT_ACL_BACKUP_PATH);
return true;
}
if (fs->exists(CLIENT_ACL_BACKUP_PATH)
&& is_valid(fs, CLIENT_ACL_BACKUP_PATH)) {
if (!removeClientACLArtifact(fs, CLIENT_ACL_PRIMARY_PATH)
|| !fs->rename(CLIENT_ACL_BACKUP_PATH, CLIENT_ACL_PRIMARY_PATH)) {
return false;
}
removeClientACLArtifact(fs, CLIENT_ACL_TEMP_PATH);
return true;
}
return !fs->exists(CLIENT_ACL_PRIMARY_PATH)
&& !fs->exists(CLIENT_ACL_BACKUP_PATH)
&& removeClientACLArtifact(fs, CLIENT_ACL_TEMP_PATH);
}
template <typename Filesystem>
bool publishVerifiedClientACLTemp(Filesystem* fs, bool temp_verified) {
if (!temp_verified) {
removeClientACLArtifact(fs, CLIENT_ACL_TEMP_PATH);
return false;
}
if (fs->exists(CLIENT_ACL_BACKUP_PATH)) return false;
const bool had_primary = fs->exists(CLIENT_ACL_PRIMARY_PATH);
if (had_primary
&& !fs->rename(CLIENT_ACL_PRIMARY_PATH, CLIENT_ACL_BACKUP_PATH)) {
return false;
}
if (!fs->rename(CLIENT_ACL_TEMP_PATH, CLIENT_ACL_PRIMARY_PATH)) {
// Restore the last committed image immediately when possible. If this
// rename also fails, leave both artifacts for recoverClientACLFiles().
if (had_primary && !fs->exists(CLIENT_ACL_PRIMARY_PATH)) {
fs->rename(CLIENT_ACL_BACKUP_PATH, CLIENT_ACL_PRIMARY_PATH);
}
return false;
}
// A stale backup does not make the newly published primary unsuccessful;
// recovery removes it before the next load/save.
removeClientACLArtifact(fs, CLIENT_ACL_BACKUP_PATH);
return true;
}
template <typename Filesystem, typename Validator>
bool publishVerifiedClientACLTemp(Filesystem* fs, bool temp_verified,
Validator is_valid) {
if (!temp_verified) {
removeClientACLArtifact(fs, CLIENT_ACL_TEMP_PATH);
return false;
}
if (fs->exists(CLIENT_ACL_BACKUP_PATH)) return false;
const bool had_primary = fs->exists(CLIENT_ACL_PRIMARY_PATH);
if (had_primary
&& !fs->rename(CLIENT_ACL_PRIMARY_PATH, CLIENT_ACL_BACKUP_PATH)) {
return false;
}
if (!fs->rename(CLIENT_ACL_TEMP_PATH, CLIENT_ACL_PRIMARY_PATH)
|| !is_valid(fs, CLIENT_ACL_PRIMARY_PATH)) {
removeClientACLArtifact(fs, CLIENT_ACL_PRIMARY_PATH);
if (had_primary) {
fs->rename(CLIENT_ACL_BACKUP_PATH, CLIENT_ACL_PRIMARY_PATH);
}
return false;
}
// Publication committed at the successful temp -> primary rename and
// validation. A stale backup is recoverable housekeeping, not a failed
// save (which could otherwise make RAM roll back while disk holds new data).
removeClientACLArtifact(fs, CLIENT_ACL_BACKUP_PATH);
return true;
}
} // namespace mesh
+298
View File
@@ -0,0 +1,298 @@
#pragma once
#include <stddef.h>
#include <stdint.h>
#include <string.h>
namespace mesh {
// Login timestamps are security state, not ordinary contact activity. Keep
// their durable high-water marks outside /s_contacts so an ACL eviction or an
// explicit role revocation cannot erase the replay boundary with the contact.
static const char CLIENT_LOGIN_REPLAY_PRIMARY_PATH[] = "/s_login_replay";
static const char CLIENT_LOGIN_REPLAY_TEMP_PATH[] = "/s_login_replay.tmp";
static const char CLIENT_LOGIN_REPLAY_BACKUP_PATH[] = "/s_login_replay.bak";
static const uint8_t CLIENT_LOGIN_REPLAY_MAGIC[4] = {'M', 'C', 'R', '1'};
static const size_t CLIENT_LOGIN_REPLAY_RECORD_SIZE = 32 + sizeof(uint32_t);
static const size_t CLIENT_LOGIN_REPLAY_TRAILER_SIZE =
sizeof(CLIENT_LOGIN_REPLAY_MAGIC) + sizeof(uint32_t);
// A successful login reserves this many sender-clock seconds in one durable
// write. Further monotonically increasing logins inside the reservation need
// no flash write. After a reset, the unused tail is deliberately skipped;
// this is the availability cost that prevents an already accepted timestamp
// from becoming fresh again. One minute bounds that cost while coalescing
// rapid reconnects and Bluetooth/Wi-Fi transport changes.
static const uint32_t CLIENT_LOGIN_REPLAY_RESERVATION_SECONDS = 60;
// This is deliberately larger than the live ACL. Historical entries are
// privileged tombstones and may not be evicted safely while their password
// remains usable. A full store fails closed for a new privileged identity
// rather than silently discarding an older replay boundary; low-trust roles do
// not allocate records.
static const size_t MAX_CLIENT_LOGIN_REPLAY_IDENTITIES = 128;
struct ClientLoginReplayPlan {
bool fresh;
bool reservation_needed;
uint32_t reservation_ceiling;
};
enum class ClientLoginReplayReservationAction : uint8_t {
None,
UpdateExisting,
CreateNew,
};
// Guest and read-only sessions can consume public or deliberately low-trust
// credentials. They still obey the exact in-boot floor and any historical
// privileged tombstone, but must not allocate a new permanent identity in the
// bounded replay store. Read/write and manager roles retain the durable
// pre-allocation reservation which protects a later revocation or ACL
// eviction.
inline bool clientLoginRoleNeedsDurableReplay(
uint8_t permissions,
uint8_t role_mask,
uint8_t guest_role,
uint8_t read_only_role) {
const uint8_t role = permissions & role_mask;
return role != (guest_role & role_mask)
&& role != (read_only_role & role_mask);
}
// Select durable work only after freshness is established. An existing
// privileged tombstone remains authoritative even if the identity currently
// logs in with a guest/read-only role, so advance that record rather than
// silently weakening revoked-role protection. Only a missing low-trust
// identity stays RAM-only.
inline ClientLoginReplayReservationAction selectClientLoginReplayReservation(
bool reservation_needed,
bool identity_already_stored,
bool role_needs_durable_replay) {
if (!reservation_needed) {
return ClientLoginReplayReservationAction::None;
}
if (identity_already_stored) {
return ClientLoginReplayReservationAction::UpdateExisting;
}
return role_needs_durable_replay
? ClientLoginReplayReservationAction::CreateNew
: ClientLoginReplayReservationAction::None;
}
inline bool clientLoginReplayCanInsert(size_t stored_identity_count) {
return stored_identity_count < MAX_CLIENT_LOGIN_REPLAY_IDENTITIES;
}
inline uint32_t reserveClientLoginTimestamp(uint32_t sender_timestamp,
uint32_t reservation_seconds) {
const uint32_t room = UINT32_MAX - sender_timestamp;
return room < reservation_seconds
? UINT32_MAX
: sender_timestamp + reservation_seconds;
}
// Plan the admission before mutating the ACL. runtime_last_timestamp is
// non-zero only when this boot has live state for the identity. Otherwise the
// persisted ceiling is the freshness floor (boot, eviction, and revocation all
// take this branch). The caller must durably publish reservation_ceiling
// before treating a plan with reservation_needed as accepted.
inline ClientLoginReplayPlan planClientLoginReplay(
uint32_t runtime_last_timestamp,
uint32_t persisted_ceiling,
uint32_t sender_timestamp,
uint32_t reservation_seconds =
CLIENT_LOGIN_REPLAY_RESERVATION_SECONDS) {
const uint32_t freshness_floor = runtime_last_timestamp != 0
? runtime_last_timestamp
: persisted_ceiling;
if (sender_timestamp == 0 || sender_timestamp <= freshness_floor) {
return {false, false, persisted_ceiling};
}
if (sender_timestamp <= persisted_ceiling) {
return {true, false, persisted_ceiling};
}
return {
true,
true,
reserveClientLoginTimestamp(sender_timestamp, reservation_seconds),
};
}
inline uint32_t updateClientLoginReplayCRC(uint32_t crc,
const uint8_t* data,
size_t length) {
while (length-- != 0) {
crc ^= *data++;
for (uint8_t bit = 0; bit < 8; bit++) {
crc = (crc >> 1) ^ (0xEDB88320UL &
(uint32_t)-(int32_t)(crc & 1U));
}
}
return crc;
}
inline bool validateClientLoginReplayImage(const uint8_t* image,
size_t size) {
if (image == NULL || size < CLIENT_LOGIN_REPLAY_TRAILER_SIZE) return false;
const size_t payload_size = size - CLIENT_LOGIN_REPLAY_TRAILER_SIZE;
if (payload_size % CLIENT_LOGIN_REPLAY_RECORD_SIZE != 0
|| payload_size / CLIENT_LOGIN_REPLAY_RECORD_SIZE
> MAX_CLIENT_LOGIN_REPLAY_IDENTITIES) {
return false;
}
if (memcmp(image + payload_size, CLIENT_LOGIN_REPLAY_MAGIC,
sizeof(CLIENT_LOGIN_REPLAY_MAGIC)) != 0) {
return false;
}
for (size_t offset = 0; offset < payload_size;
offset += CLIENT_LOGIN_REPLAY_RECORD_SIZE) {
uint32_t ceiling;
memcpy(&ceiling, image + offset + 32, sizeof(ceiling));
if (ceiling == 0) return false;
}
uint32_t stored_crc;
memcpy(&stored_crc,
image + payload_size + sizeof(CLIENT_LOGIN_REPLAY_MAGIC),
sizeof(stored_crc));
const uint32_t crc = updateClientLoginReplayCRC(
0xFFFFFFFFUL, image, payload_size) ^ 0xFFFFFFFFUL;
return stored_crc == crc;
}
template <typename Filesystem>
bool removeClientLoginReplayArtifact(Filesystem* fs, const char* path) {
if (!fs->exists(path)) return true;
fs->remove(path);
return !fs->exists(path);
}
template <typename Filesystem, typename Validator>
bool recoverClientLoginReplayFiles(Filesystem* fs, Validator is_valid) {
if (fs->exists(CLIENT_LOGIN_REPLAY_PRIMARY_PATH)
&& is_valid(fs, CLIENT_LOGIN_REPLAY_PRIMARY_PATH)) {
// The validated primary is already authoritative. Cleanup failure must
// not disable replay protection or make committed state appear absent.
removeClientLoginReplayArtifact(fs, CLIENT_LOGIN_REPLAY_TEMP_PATH);
removeClientLoginReplayArtifact(fs, CLIENT_LOGIN_REPLAY_BACKUP_PATH);
return true;
}
if (fs->exists(CLIENT_LOGIN_REPLAY_BACKUP_PATH)
&& is_valid(fs, CLIENT_LOGIN_REPLAY_BACKUP_PATH)) {
if (!removeClientLoginReplayArtifact(fs,
CLIENT_LOGIN_REPLAY_PRIMARY_PATH)
|| !fs->rename(CLIENT_LOGIN_REPLAY_BACKUP_PATH,
CLIENT_LOGIN_REPLAY_PRIMARY_PATH)) {
return false;
}
removeClientLoginReplayArtifact(fs, CLIENT_LOGIN_REPLAY_TEMP_PATH);
return true;
}
// A never-created store is the upgrade/first-boot case. An invalid live or
// backup image is different: retain it for diagnosis and fail closed.
return !fs->exists(CLIENT_LOGIN_REPLAY_PRIMARY_PATH)
&& !fs->exists(CLIENT_LOGIN_REPLAY_BACKUP_PATH)
&& removeClientLoginReplayArtifact(fs,
CLIENT_LOGIN_REPLAY_TEMP_PATH);
}
template <typename Filesystem, typename Validator>
bool publishClientLoginReplayTemp(Filesystem* fs,
bool temp_verified,
Validator is_valid) {
if (!temp_verified) {
removeClientLoginReplayArtifact(fs, CLIENT_LOGIN_REPLAY_TEMP_PATH);
return false;
}
if (fs->exists(CLIENT_LOGIN_REPLAY_BACKUP_PATH)) return false;
const bool had_primary = fs->exists(CLIENT_LOGIN_REPLAY_PRIMARY_PATH);
if (had_primary
&& !fs->rename(CLIENT_LOGIN_REPLAY_PRIMARY_PATH,
CLIENT_LOGIN_REPLAY_BACKUP_PATH)) {
return false;
}
if (!fs->rename(CLIENT_LOGIN_REPLAY_TEMP_PATH,
CLIENT_LOGIN_REPLAY_PRIMARY_PATH)
|| !is_valid(fs, CLIENT_LOGIN_REPLAY_PRIMARY_PATH)) {
removeClientLoginReplayArtifact(fs, CLIENT_LOGIN_REPLAY_PRIMARY_PATH);
if (had_primary) {
fs->rename(CLIENT_LOGIN_REPLAY_BACKUP_PATH,
CLIENT_LOGIN_REPLAY_PRIMARY_PATH);
}
return false;
}
// The new replay ceiling committed at the successful rename and
// validation. Treat stale-backup cleanup as best-effort so callers never
// reject a login whose durable reservation is already on disk.
removeClientLoginReplayArtifact(fs, CLIENT_LOGIN_REPLAY_BACKUP_PATH);
return true;
}
inline bool clientRoleIsPersisted(uint8_t permissions,
uint8_t role_mask,
uint8_t guest_role) {
return (permissions & role_mask) != (guest_role & role_mask);
}
inline bool isFreshClientLoginTimestamp(bool client_existed,
uint32_t sender_timestamp,
uint32_t last_timestamp) {
return sender_timestamp != 0
&& (!client_existed || sender_timestamp > last_timestamp);
}
inline bool successfulClientLoginNeedsPersistence(bool client_existed,
uint8_t previous_permissions,
uint8_t next_permissions,
uint8_t role_mask,
uint8_t guest_role,
bool persisted_changed) {
if (!persisted_changed) return false;
const uint8_t guest = guest_role & role_mask;
const bool previously_persisted = client_existed
&& clientRoleIsPersisted(previous_permissions, role_mask, guest);
const bool now_persisted =
clientRoleIsPersisted(next_permissions, role_mask, guest);
// A downgrade to guest must rewrite the ACL even though the guest itself is
// omitted from the file; otherwise the prior persisted role survives reboot.
return previously_persisted || now_persisted;
}
// Apply the successful-login state transition and report whether any field
// written by ClientACL::save() changed. Timestamps are deliberately excluded
// from that result: the exact live value is RAM state, while its reserved
// high-water boundary is synchronously owned by the separate replay store.
template <typename Client>
bool applySuccessfulClientLogin(
Client& client,
bool client_existed,
uint8_t role_permissions,
uint8_t role_mask,
const uint8_t* shared_secret,
uint32_t sender_timestamp,
uint32_t activity_timestamp,
bool reset_out_path,
uint8_t unknown_path) {
const uint8_t next_permissions =
(uint8_t)((client.permissions & (uint8_t)~role_mask)
| (role_permissions & role_mask));
bool persisted_changed = !client_existed
|| client.permissions != next_permissions
|| memcmp(client.shared_secret, shared_secret,
sizeof(client.shared_secret)) != 0
|| (reset_out_path && client.out_path_len != unknown_path);
client.last_timestamp = sender_timestamp;
client.last_activity = activity_timestamp;
client.permissions = next_permissions;
memcpy(client.shared_secret, shared_secret, sizeof(client.shared_secret));
if (reset_out_path) {
client.out_path_len = unknown_path;
client.out_path_is_persistable = true;
}
return persisted_changed;
}
} // namespace mesh
+108
View File
@@ -0,0 +1,108 @@
#pragma once
#include <stddef.h>
#include <stdint.h>
#include <string.h>
namespace mesh {
struct ClientPathUpdateResult {
bool changed;
bool persistence_needed;
};
struct StoredClientPathView {
uint8_t encoded_path_len;
const uint8_t* path;
};
inline bool clientPathPersistenceAllowed(bool client_is_persistable,
bool replay_freshness_proven) {
return client_is_persistable && replay_freshness_proven;
}
inline uint8_t storedClientPathLength(bool path_is_persistable,
uint8_t current_path_len,
uint8_t unknown_path) {
return path_is_persistable ? current_path_len : unknown_path;
}
// A replay-unproven PATH may replace the route used for the remainder of this
// boot, but it must not erase an earlier operator-selected route when an
// unrelated ACL mutation rewrites /s_contacts. Select the live route only
// when it owns durable state; otherwise retain the already-published route (or
// serialize unknown for a contact that has never had one).
inline StoredClientPathView selectStoredClientPath(
bool runtime_path_is_persistable,
uint8_t runtime_path_len,
const uint8_t* runtime_path,
bool prior_path_exists,
uint8_t prior_path_len,
const uint8_t* prior_path,
uint8_t unknown_path,
const uint8_t* empty_path) {
if (runtime_path_is_persistable) {
return {runtime_path_len, runtime_path};
}
if (prior_path_exists) {
return {prior_path_len, prior_path};
}
return {unknown_path, empty_path};
}
// Packet paths encode the hash width in the upper two bits and the hop count
// in the lower six bits. This intentionally matches Packet::writePath()'s byte
// count without pulling the firmware-only Packet dependencies into host tests.
inline size_t encodedClientPathByteLength(uint8_t encoded_path_len) {
const size_t hash_count = encoded_path_len & 63U;
const size_t hash_size = (encoded_path_len >> 6) + 1U;
return hash_count * hash_size;
}
inline bool isValidEncodedClientPathLength(uint8_t encoded_path_len,
size_t capacity) {
const size_t hash_size = (encoded_path_len >> 6) + 1U;
return hash_size != 4U
&& encodedClientPathByteLength(encoded_path_len) <= capacity;
}
// Update the RAM route and report whether the caller owns a persistent change.
// FORCE_FLOOD is an explicit operator setting and is never replaced by a
// learned route. Bytes beyond the encoded route length are deliberately
// ignored: they are stale capacity, not part of the logical path.
template <typename Client>
ClientPathUpdateResult applyReceivedClientPath(
Client& client,
const uint8_t* path,
uint8_t encoded_path_len,
bool client_is_persistable,
uint8_t force_flood_path) {
if (client.out_path_len == force_flood_path) return {false, false};
const size_t path_bytes = encodedClientPathByteLength(encoded_path_len);
if (!isValidEncodedClientPathLength(
encoded_path_len, sizeof(client.out_path))
|| (path_bytes != 0 && path == NULL)) {
return {false, false};
}
const bool changed = client.out_path_len != encoded_path_len
|| (path_bytes != 0
&& memcmp(client.out_path, path, path_bytes) != 0);
if (!changed) {
// A later request may carry the replay/freshness proof that the first copy
// lacked. Promote the identical RAM route without requiring it to change
// bytes a second time.
const bool persistence_upgrade = client_is_persistable
&& !client.out_path_is_persistable;
if (persistence_upgrade) client.out_path_is_persistable = true;
return {persistence_upgrade, persistence_upgrade};
}
if (path_bytes != 0) memcpy(client.out_path, path, path_bytes);
client.out_path_len = encoded_path_len;
client.out_path_is_persistable = client_is_persistable;
return {true, client_is_persistable};
}
} // namespace mesh
+149 -56
View File
@@ -316,6 +316,18 @@ static bool parseUint8Strict(const char* value, uint8_t min_value, uint8_t max_v
return true;
}
static bool parseOnOffStrict(const char* value, bool& enabled) {
if (strcmp(value, "on") == 0) {
enabled = true;
return true;
}
if (strcmp(value, "off") == 0) {
enabled = false;
return true;
}
return false;
}
static bool bwMatches(float bw, float allowed) {
float diff = bw - allowed;
if (diff < 0.0f) diff = -diff;
@@ -915,7 +927,8 @@ void CommonCLI::loadPrefsInt(FILESYSTEM* fs, const char* filename) {
File file = fs->open(filename);
#endif
if (file) {
#if defined(WITH_RS232_BRIDGE) && defined(RS232_BRIDGE_MERGED)
#if defined(WITH_RS232_BRIDGE) && defined(RS232_BRIDGE_MERGED) \
&& !defined(RS232_BRIDGE_DEFAULT_ON)
bool has_runtime_bridge_uart = false;
#endif
// Every supported layout contains the fixed 290-byte common core. Reject
@@ -1280,7 +1293,8 @@ void CommonCLI::loadPrefsInt(FILESYSTEM* fs, const char* filename) {
if (file.available() >= (int)sizeof(_prefs->bridge_uart)) {
file.read((uint8_t *)&_prefs->bridge_uart,
sizeof(_prefs->bridge_uart));
#if defined(WITH_RS232_BRIDGE) && defined(RS232_BRIDGE_MERGED)
#if defined(WITH_RS232_BRIDGE) && defined(RS232_BRIDGE_MERGED) \
&& !defined(RS232_BRIDGE_DEFAULT_ON)
has_runtime_bridge_uart = true;
#endif
if (file.available() >= (int)sizeof(_prefs->bridge_format)) {
@@ -1345,7 +1359,8 @@ void CommonCLI::loadPrefsInt(FILESYSTEM* fs, const char* filename) {
_prefs->loop_detect = constrain(_prefs->loop_detect, 0, 3); // LOOP_DETECT_OFF..LOOP_DETECT_STRICT
// sanitise bad bridge pref values
#if defined(WITH_RS232_BRIDGE) && defined(RS232_BRIDGE_MERGED)
#if defined(WITH_RS232_BRIDGE) && defined(RS232_BRIDGE_MERGED) \
&& !defined(RS232_BRIDGE_DEFAULT_ON)
if (!has_runtime_bridge_uart) {
// Pre-merge normal repeaters persisted bridge_enabled=1 even though no
// bridge was compiled. Fail safe on the first merged boot instead of
@@ -2722,13 +2737,6 @@ void CommonCLI::handleCommand(uint32_t sender_timestamp, char* command, char* re
} else if (!valid_gps_toggle) {
strcpy(reply, "gps must be 0 or 1");
}
#if defined(WITH_RS232_BRIDGE_GPS_CONFLICT_UART)
else if (is_gps_toggle && strcmp(value, "1") == 0
&& _prefs->bridge_enabled
&& _prefs->bridge_uart == WITH_RS232_BRIDGE_GPS_CONFLICT_UART) {
strcpy(reply, "turn the RS232 bridge off or select another UART first");
}
#endif
else if (_sensors->setSettingValue(key, value)) {
if (is_gps_interval) {
_prefs->gps_interval = gps_interval;
@@ -2737,7 +2745,16 @@ void CommonCLI::handleCommand(uint32_t sender_timestamp, char* command, char* re
_prefs->gps_enabled = strcmp(value, "1") == 0 ? 1 : 0;
savePrefs();
}
strcpy(reply, "ok");
#ifdef WITH_RS232_BRIDGE
if (is_gps_toggle && strcmp(value, "1") == 0
&& _callbacks->isBridgeRunning()
&& _sensors->gpsUsesSerialUart(_prefs->bridge_uart)) {
strcpy(reply, "saved; UART GPS paused while bridge is enabled");
} else
#endif
{
strcpy(reply, "ok");
}
} else {
strcpy(reply, "can't find custom var");
}
@@ -2770,17 +2787,19 @@ void CommonCLI::handleCommand(uint32_t sender_timestamp, char* command, char* re
handleRegionCmd(command, reply);
#if ENV_INCLUDE_GPS == 1
} else if (memcmp(command, "gps on", 6) == 0) {
#if defined(WITH_RS232_BRIDGE_GPS_CONFLICT_UART)
if (_prefs->bridge_enabled
&& _prefs->bridge_uart == WITH_RS232_BRIDGE_GPS_CONFLICT_UART) {
strcpy(reply, "turn the RS232 bridge off or select another UART first");
} else
#endif
if (_sensors->setSettingValue("gps", "1")) {
_prefs->gps_enabled = 1;
savePrefs();
if (_prefs->powersaving_enabled) { // Power Saving
if (_callbacks->isBridgeRunning()
#ifdef WITH_RS232_BRIDGE
&& _sensors->gpsUsesSerialUart(_prefs->bridge_uart)
#else
&& false
#endif
) {
strcpy(reply, "saved; UART GPS paused while bridge is enabled");
} else if (_prefs->powersaving_enabled) { // Power Saving
strcpy(reply, "on (powersaving)");
} else { // Normal mode
strcpy(reply, "ok");
@@ -2800,6 +2819,11 @@ void CommonCLI::handleCommand(uint32_t sender_timestamp, char* command, char* re
LocationProvider * l = _sensors->getLocationProvider();
if (!_prefs->gps_enabled) {
strcpy(reply, "gps is off");
#ifdef WITH_RS232_BRIDGE
} else if (_callbacks->isBridgeRunning()
&& _sensors->gpsUsesSerialUart(_prefs->bridge_uart)) {
strcpy(reply, "gps paused by RS232 bridge");
#endif
} else if (l != NULL) {
l->syncTime();
strcpy(reply, "scheduled");
@@ -4231,35 +4255,73 @@ void CommonCLI::handleSetCmd(uint32_t sender_timestamp, char* command, char* rep
}
#ifdef WITH_BRIDGE
} else if (memcmp(config, "bridge.enabled ", 15) == 0) {
const bool enable = memcmp(&config[15], "on", 2) == 0;
#if defined(WITH_RS232_BRIDGE_GPS_CONFLICT_UART)
if (enable && _prefs->gps_enabled
&& _prefs->bridge_uart == WITH_RS232_BRIDGE_GPS_CONFLICT_UART) {
strcpy(reply, "Error: turn GPS off or select another UART first");
} else
#endif
{
_prefs->bridge_enabled = enable;
const bool applied = _callbacks->setBridgeState(_prefs->bridge_enabled);
savePrefs();
if (applied) {
strcpy(reply, "OK");
} else {
strcpy(reply, enable ? "Error: bridge failed to start; setting saved"
: "Error: bridge failed to stop; setting saved");
bool enable = false;
if (!parseOnOffStrict(&config[15], enable)) {
strcpy(reply, "Error: usage set bridge.enabled on|off");
} else {
#ifdef WITH_RS232_BRIDGE
if (enable
&& _sensors->gpsSerialTransportMayConflict(_prefs->bridge_uart)
&& (!_sensors->gpsUsesSerialUart(_prefs->bridge_uart)
|| !_sensors->gpsSerialTransportCanYield(_prefs->bridge_uart))) {
strcpy(reply, "Error: UART may be driven by GPS; use UART 2 or a no-GPS build");
return;
}
const uint8_t previous_enabled = _prefs->bridge_enabled;
const bool previous_running = _callbacks->isBridgeRunning();
_prefs->bridge_enabled = enable;
const bool applied = _callbacks->setBridgeState(enable);
if (applied) {
savePrefs();
#ifdef WITH_RS232_BRIDGE
if (enable && _sensors->gpsUsesSerialUart(_prefs->bridge_uart)) {
strcpy(reply, "OK - UART GPS paused");
} else
#endif
{
strcpy(reply, "OK");
}
} else {
_prefs->bridge_enabled = previous_enabled;
bool restored = true;
if (_callbacks->isBridgeRunning() != previous_running
|| !previous_running) {
// The false/false case still calls disable to delete a failed,
// non-running heap-backed bridge instance.
restored = _callbacks->setBridgeState(previous_running);
}
strcpy(reply, restored
? "Error: bridge state change failed; setting unchanged"
: "Error: bridge state change failed; previous runtime state could not be restored");
}
#else
// MQTT and ESP-NOW preserve configured intent across missing WiFi
// credentials or transient initialization failure. Their runtime can be
// retried later, so do not apply the stricter RS-232 rollback policy.
_prefs->bridge_enabled = enable;
const bool applied = _callbacks->setBridgeState(enable);
savePrefs();
strcpy(reply, applied ? "OK"
: "Error: bridge runtime change failed; setting saved");
#endif
}
} else if (memcmp(config, "bridge.delay ", 13) == 0) {
int delay = _atoi(&config[13]);
if (delay >= 0 && delay <= 10000) {
_prefs->bridge_delay = (uint16_t)delay;
int32_t bridge_delay = 0;
if (mesh::cli::parseIntegerStrict(&config[13], bridge_delay)
&& bridge_delay >= 0 && bridge_delay <= 10000) {
_prefs->bridge_delay = (uint16_t)bridge_delay;
savePrefs();
strcpy(reply, "OK");
} else {
strcpy(reply, "Error: delay must be between 0-10000 ms");
}
} else if (memcmp(config, "bridge.source ", 14) == 0) {
_prefs->bridge_pkt_src = memcmp(&config[14], "rx", 2) == 0;
const char* source = &config[14];
if (strcmp(source, "rx") != 0 && strcmp(source, "tx") != 0) {
strcpy(reply, "Error: usage set bridge.source rx|tx");
return;
}
_prefs->bridge_pkt_src = strcmp(source, "rx") == 0;
#ifdef WITH_MQTT_BRIDGE
if (_prefs->bridge_pkt_src == 1) {
_mqtt_prefs.mqtt_rx_enabled = 1;
@@ -4276,24 +4338,37 @@ void CommonCLI::handleSetCmd(uint32_t sender_timestamp, char* command, char* rep
#endif
#ifdef WITH_RS232_BRIDGE
} else if (memcmp(config, "bridge.baud ", 12) == 0) {
uint32_t baud = atoi(&config[12]);
if (baud >= 9600 && baud <= BRIDGE_MAX_BAUD) {
_prefs->bridge_baud = (uint32_t)baud;
uint32_t baud = 0;
if (mesh::cli::parseUnsignedIntegerStrict(&config[12], baud)
&& baud >= 9600 && baud <= BRIDGE_MAX_BAUD) {
const uint32_t previous_baud = _prefs->bridge_baud;
const bool previous_running = _callbacks->isBridgeRunning();
_prefs->bridge_baud = baud;
const bool applied = !_prefs->bridge_enabled || _callbacks->restartBridge();
savePrefs();
strcpy(reply, applied ? "OK"
: "Error: setting saved; bridge failed to restart");
if (applied) {
savePrefs();
strcpy(reply, "OK");
} else {
_prefs->bridge_baud = previous_baud;
const bool restored = previous_running
? _callbacks->restartBridge()
: _callbacks->setBridgeState(false);
strcpy(reply, restored
? "Error: bridge failed to restart; baud unchanged"
: "Error: bridge failed to restart; previous baud could not be restored");
}
} else {
sprintf(reply, "Error: baud rate must be between 9600-%d",BRIDGE_MAX_BAUD);
}
} else if (memcmp(config, "bridge.uart ", 12) == 0) {
const int uart = atoi(&config[12]);
int32_t uart = 0;
const bool parsed = mesh::cli::parseIntegerStrict(&config[12], uart);
const bool supported = uart == WITH_RS232_BRIDGE_UART
#ifdef WITH_RS232_BRIDGE_ALT
|| uart == WITH_RS232_BRIDGE_ALT_UART
#endif
;
if (!supported) {
if (!parsed || !supported) {
#ifdef WITH_RS232_BRIDGE_ALT
sprintf(reply, "Error: UART must be %d or %d",
WITH_RS232_BRIDGE_UART, WITH_RS232_BRIDGE_ALT_UART);
@@ -4301,18 +4376,34 @@ void CommonCLI::handleSetCmd(uint32_t sender_timestamp, char* command, char* rep
sprintf(reply, "Error: UART is fixed at %d", WITH_RS232_BRIDGE_UART);
#endif
}
#if defined(WITH_RS232_BRIDGE_GPS_CONFLICT_UART)
else if (uart == WITH_RS232_BRIDGE_GPS_CONFLICT_UART
&& _prefs->gps_enabled && _prefs->bridge_enabled) {
strcpy(reply, "Error: turn GPS or the bridge off first");
}
#endif
else {
if (_prefs->bridge_enabled
&& _sensors->gpsSerialTransportMayConflict((uint8_t)uart)
&& (!_sensors->gpsUsesSerialUart((uint8_t)uart)
|| !_sensors->gpsSerialTransportCanYield((uint8_t)uart))) {
strcpy(reply, "Error: UART may be driven by GPS; keep UART 2 or use a no-GPS build");
return;
}
const uint8_t previous_uart = _prefs->bridge_uart;
const bool previous_running = _callbacks->isBridgeRunning();
_prefs->bridge_uart = (uint8_t)uart;
const bool applied = !_prefs->bridge_enabled || _callbacks->restartBridge();
savePrefs();
strcpy(reply, applied ? "OK"
: "Error: setting saved; bridge failed to restart");
if (!applied) {
_prefs->bridge_uart = previous_uart;
const bool restored = previous_running
? _callbacks->restartBridge()
: _callbacks->setBridgeState(false);
strcpy(reply, restored
? "Error: bridge failed to restart; UART unchanged"
: "Error: bridge failed to restart; previous UART could not be restored");
} else if (_prefs->bridge_enabled
&& _sensors->gpsUsesSerialUart(_prefs->bridge_uart)) {
savePrefs();
strcpy(reply, "OK - UART GPS paused");
} else {
savePrefs();
strcpy(reply, "OK");
}
}
#endif
#ifdef WITH_ESPNOW_BRIDGE
@@ -4740,10 +4831,12 @@ void CommonCLI::handleGetCmd(uint32_t sender_timestamp, char* command, char* rep
#ifdef WITH_BRIDGE
} else if (configKeyEquals(config, "bridge.enabled")) {
sprintf(reply, "> %s", _prefs->bridge_enabled ? "on" : "off");
} else if (configKeyEquals(config, "bridge.running")) {
sprintf(reply, "> %s", _callbacks->isBridgeRunning() ? "on" : "off");
} else if (configKeyEquals(config, "bridge.delay")) {
sprintf(reply, "> %d", (uint32_t)_prefs->bridge_delay);
} else if (configKeyEquals(config, "bridge.source")) {
sprintf(reply, "> %s", _prefs->bridge_pkt_src ? "logRx" : "logTx");
sprintf(reply, "> %s", _prefs->bridge_pkt_src ? "rx" : "tx");
#endif
#ifdef WITH_RS232_BRIDGE
} else if (configKeyEquals(config, "bridge.baud")) {
+2
View File
@@ -556,6 +556,8 @@ public:
return false;
};
virtual bool isBridgeRunning() const { return false; }
virtual void restartBridgeSlot(int slot) {
// Default: fall back to full restart
restartBridge();
+19 -7
View File
@@ -22,7 +22,9 @@
#include <WiFi.h>
#include <WiFiClientSecure.h>
#include <esp_wifi.h>
#include <time.h>
#include "WiFiPowerSave.h"
#include "esp32/TlsClockValidity.h"
#include "esp32/WiFiRadioPolicy.h"
#endif
#if defined(ESP32_PLATFORM) && defined(ENABLE_OTA) && \
@@ -1166,12 +1168,21 @@ bool CommonCLI::handleObserverCommand(uint32_t sender_timestamp, char* command,
client.setCACertBundle(rootca_crt_bundle_start);
#endif
client.setTimeout(8000);
bool ok = client.connect(host, port);
if (ok) {
client.stop();
snprintf(reply, 160, "OK: TLS bundle verified %s:%u", host, (unsigned)port);
// This diagnostic must distinguish a bad CA bundle from a clock that
// cannot validate any certificate yet. It does not mutate the global
// SNTP client while the MQTT task is live; normal bridge NTP supplies
// the signed wall clock checked here.
const time_t tls_now = time(nullptr);
if (!mesh::tls_clock::timeIsValid(tls_now)) {
strcpy(reply, "ERR: TLS clock is not synchronized");
} else {
snprintf(reply, 160, "ERR: TLS bundle failed %s:%u", host, (unsigned)port);
bool ok = client.connect(host, port);
if (ok) {
client.stop();
snprintf(reply, 160, "OK: TLS bundle verified %s:%u", host, (unsigned)port);
} else {
snprintf(reply, 160, "ERR: TLS bundle failed %s:%u", host, (unsigned)port);
}
}
}
}
@@ -1193,8 +1204,9 @@ bool CommonCLI::handleObserverCommand(uint32_t sender_timestamp, char* command,
} else if (memcmp(command, "ota check", 9) == 0) {
// Check is synchronous so its result lands in this reply, and runs with the
// MQTT bridge UP: the slim per-variant manifest is tiny, so the fetch only
// costs a single TLS handshake (no large JSON doc) - which fits alongside
// the live MQTT sessions even on no-PSRAM boards. No bridge bounce needed.
// costs one plain-HTTP request (no cert-bundle allocation or large JSON
// document). The later update path refetches it over verified HTTPS after
// the bridge is down. No bridge bounce is needed for this advisory check.
_board->otaFromManifest(_callbacks->getFirmwareVer(), true, reply);
} else {
// `ota update`: cheap pre-check first (plain HTTP, bridge stays up). Only
+11 -5
View File
@@ -10,6 +10,7 @@
#include <freertos/task.h>
#include <helpers/MQTTDefaults.h>
#include <helpers/MQTTPresets.h>
#include <helpers/UsbLogging.h>
#include <strings.h>
namespace {
@@ -553,8 +554,9 @@ bool CompanionMqttSetupPortal::begin(MQTTPrefs* prefs) {
impl->task = nullptr;
return false;
}
Serial.printf("MQTT setup: reconnect to the joined WiFi and open http://%s/\n",
WiFi.localIP().toString().c_str());
mesh::usbLoggingPort().printf(
"MQTT setup: reconnect to the joined WiFi and open http://%s/\n",
WiFi.localIP().toString().c_str());
return true;
}
@@ -580,9 +582,13 @@ bool CompanionMqttSetupPortal::loop() {
bool CompanionMqttSetupPortal::loadStoredConfig(MQTTPrefs& prefs) {
Preferences nvs;
if (!nvs.begin(NVS_NAMESPACE, true)) return false;
const uint16_t version = nvs.getUShort(NVS_VERSION_KEY, 0);
const size_t length = nvs.getBytesLength(NVS_PREFS_KEY);
// The namespace and blob legitimately do not exist on a fresh install.
// Avoid Arduino Preferences turning that state into UART error output.
if (!nvs.begin(NVS_NAMESPACE, false)) return false;
const uint16_t version = nvs.isKey(NVS_VERSION_KEY)
? nvs.getUShort(NVS_VERSION_KEY, 0) : 0;
const size_t length = nvs.isKey(NVS_PREFS_KEY)
? nvs.getBytesLength(NVS_PREFS_KEY) : 0;
// Companion stores this struct directly rather than using the observer's
// versioned file header. Accept the previously shipped pre-display size and
// default its append-only display tail so adding observer UI preferences
+115 -10
View File
@@ -2,6 +2,7 @@
#include "ESP32Board.h"
#include <target.h>
#include "UsbLogging.h"
#include "UserGpioPinPolicy.h"
namespace {
@@ -414,16 +415,113 @@ bool ESP32Board::stopOTAUpdate(char reply[]) {
#include <WiFiClientSecure.h>
#include <Update.h>
#include <ArduinoJson.h>
#include <atomic>
#include <helpers/esp32/SntpOperationCoordinator.h>
#include <helpers/esp32/TlsClockValidity.h>
#include <freertos/FreeRTOS.h>
#include <freertos/task.h>
#include <esp_partition.h>
#include <esp_sntp.h>
#include <strings.h>
#include <time.h>
// Embedded CA bundle (produced by board_build.embed_files). Weak so non-bundle
// builds still link; we check for presence at runtime.
extern const uint8_t rootca_crt_bundle_start[] asm("_binary_src_certs_x509_crt_bundle_bin_start") __attribute__((weak));
extern const uint8_t rootca_crt_bundle_end[] asm("_binary_src_certs_x509_crt_bundle_bin_end") __attribute__((weak));
static constexpr uint32_t OTA_NTP_SYNC_WAIT_MS = 15000UL;
static constexpr uint32_t OTA_TLS_PROOF_MAX_AGE_MS = 300000UL;
static std::atomic<bool> ota_tls_fresh_ntp_received{false};
static std::atomic<uint32_t> ota_tls_proof_millis{0};
static std::atomic<uint32_t> ota_tls_proof_generation{0};
static std::atomic<uint32_t> ota_tls_expected_generation{0};
static std::atomic<uint32_t> ota_sntp_operation_generation{0};
static void ota_clearNtpCallback() {
// OperationLease invokes this before publishing the global coordinator as
// free, so a stale OTA teardown cannot erase another service's callback.
ota_sntp_operation_generation.store(0, std::memory_order_release);
sntp_set_time_sync_notification_cb(nullptr);
}
static void ota_noteNtpTime(struct timeval* value) {
const uint32_t generation =
ota_sntp_operation_generation.load(std::memory_order_acquire);
if (!mesh::sntp_coord::processWideCoordinator().owns(generation)) return;
if (value != nullptr && mesh::tls_clock::timeIsValid(value->tv_sec)) {
ota_tls_proof_millis.store(millis(), std::memory_order_release);
ota_tls_proof_generation.store(generation, std::memory_order_release);
ota_tls_fresh_ntp_received.store(true, std::memory_order_release);
}
}
static bool ota_tlsClockProofValid() {
const bool fresh = ota_tls_fresh_ntp_received.load(std::memory_order_acquire);
const uint32_t proven_at =
ota_tls_proof_millis.load(std::memory_order_acquire);
const uint32_t proof_generation =
ota_tls_proof_generation.load(std::memory_order_acquire);
const uint32_t expected_generation =
ota_tls_expected_generation.load(std::memory_order_acquire);
return mesh::tls_clock::proofGenerationIsValid(
fresh, proof_generation, expected_generation)
&& mesh::tls_clock::proofIsValid(
fresh, WiFi.status() == WL_CONNECTED, time(nullptr))
&& mesh::tls_clock::proofAgeIsValid(
fresh, millis(), proven_at, OTA_TLS_PROOF_MAX_AGE_MS);
}
static bool ota_prepareTlsClock(char reply[]) {
if (WiFi.status() != WL_CONNECTED) {
strcpy(reply, "ERR: WiFi disconnected before NTP");
return false;
}
mesh::sntp_coord::OperationLease sntp_operation(
mesh::sntp_coord::processWideCoordinator(), ota_clearNtpCallback);
if (!sntp_operation.tryAcquire()) {
strcpy(reply, "ERR: NTP busy in another firmware service");
return false;
}
// The MQTT bridge has stopped for an actual update, but other firmware
// services can still need SNTP. The process-wide lease makes this callback
// and configTime() sequence exclusive. A plausible retained RTC is
// intentionally not enough: observe a response during this operation.
ota_tls_fresh_ntp_received.store(false, std::memory_order_release);
ota_tls_proof_millis.store(0, std::memory_order_release);
ota_tls_proof_generation.store(0, std::memory_order_release);
ota_tls_expected_generation.store(
sntp_operation.generation(), std::memory_order_release);
ota_sntp_operation_generation.store(
sntp_operation.generation(), std::memory_order_release);
sntp_set_time_sync_notification_cb(ota_noteNtpTime);
sntp_set_sync_status(SNTP_SYNC_STATUS_RESET);
mesh::usbLoggingPort().println(
"OTA: requesting fresh NTP time before HTTPS");
configTime(0, 0, "time.cloudflare.com", "time.google.com", "pool.ntp.org");
const uint32_t started = millis();
while (millis() - started < OTA_NTP_SYNC_WAIT_MS) {
if (WiFi.status() != WL_CONNECTED) {
strcpy(reply, "ERR: WiFi disconnected during NTP");
return false;
}
const time_t now = time(nullptr);
if (ota_tlsClockProofValid()) {
mesh::usbLoggingPort().printf(
"OTA: fresh NTP time %lld received in %lu ms\n",
(long long)now, (unsigned long)(millis() - started));
return true;
}
delay(100);
}
strcpy(reply, "ERR: fresh NTP time unavailable");
return false;
}
struct OtaHttpResponse {
int status;
size_t content_length;
@@ -513,6 +611,10 @@ static bool ota_openHttp(Client& client, const char* url, bool require_tls,
}
client.setTimeout(20000);
if (require_tls && !ota_tlsClockProofValid()) {
strcpy(reply, "ERR: TLS clock proof invalid");
return false;
}
if (!client.connect(host, port)) {
strcpy(reply, "ERR: HTTP connect failed");
return false;
@@ -647,7 +749,7 @@ static bool ota_streamFirmware(Client& client, size_t content_length, char reply
int decile = (int)((received_total * 10U) / content_length);
if (decile != progress_decile) {
progress_decile = decile;
Serial.printf("OTA: %d%%\n", decile * 10);
mesh::usbLoggingPort().printf("OTA: %d%%\n", decile * 10);
}
}
@@ -788,6 +890,9 @@ bool ESP32Board::otaFromManifestImpl(const char* current_ver, bool dry_run, char
strcpy(reply, "ERR: no embedded cert bundle");
return false;
}
if (!dry_run && !ota_prepareTlsClock(reply)) {
return false;
}
// --- Fetch this variant's slim manifest ----------------------------------
// <OTA_MANIFEST_BASE>/<OTA_VARIANT>.json - a ~180 byte per-variant file, not the
@@ -822,13 +927,12 @@ bool ESP32Board::otaFromManifestImpl(const char* current_ver, bool dry_run, char
mclient.setCACertBundle(rootca_crt_bundle_start);
#endif
snprintf(murl, sizeof(murl), "%s/%s.json", OTA_MANIFEST_BASE, OTA_VARIANT);
mesh::usbLoggingPort().printf("OTA: downloading manifest %s\n", murl);
if (!ota_fetchManifest(mclient, murl, true, doc, reply)) {
return false;
}
}
if (!dry_run) { Serial.print("OTA: checking manifest "); Serial.println(murl); }
// Copy fields out before the document is reused/cleared.
char file_url[200] = {0}, avail_version[40] = {0}, avail_base[40] = {0}, avail_hash[24] = {0};
strncpy(file_url, doc["file"] | "", sizeof(file_url) - 1);
@@ -931,8 +1035,9 @@ bool ESP32Board::otaFromManifestImpl(const char* current_ver, bool dry_run, char
}
// --- Stream the .bin (the manifest's full URL) into the inactive OTA slot -
Serial.printf("OTA: update %s -> %s\n", own_disp, avail_disp);
Serial.print("OTA: downloading "); Serial.println(file_url);
mesh::usbLoggingPort().printf(
"OTA: update %s -> %s\n", own_disp, avail_disp);
mesh::usbLoggingPort().printf("OTA: downloading %s\n", file_url);
inhibit_sleep = true; // keep awake through the flash
WiFiClientSecure uclient;
@@ -945,32 +1050,32 @@ bool ESP32Board::otaFromManifestImpl(const char* current_ver, bool dry_run, char
OtaHttpResponse response;
if (!ota_openHttp(uclient, file_url, true, response, reply)) {
inhibit_sleep = false;
Serial.print("OTA: FAILED - "); Serial.println(reply);
mesh::usbLoggingPort().printf("OTA: FAILED - %s\n", reply);
return false;
}
if (response.status != 200) {
inhibit_sleep = false;
snprintf(reply, 160, "ERR: firmware HTTP %d", response.status);
uclient.stop();
Serial.print("OTA: FAILED - "); Serial.println(reply);
mesh::usbLoggingPort().printf("OTA: FAILED - %s\n", reply);
return false;
}
if (!response.has_content_length) {
inhibit_sleep = false;
strcpy(reply, "ERR: firmware size missing");
uclient.stop();
Serial.print("OTA: FAILED - "); Serial.println(reply);
mesh::usbLoggingPort().printf("OTA: FAILED - %s\n", reply);
return false;
}
if (!ota_streamFirmware(uclient, response.content_length, reply)) {
inhibit_sleep = false;
uclient.stop();
Serial.print("OTA: FAILED - "); Serial.println(reply);
mesh::usbLoggingPort().printf("OTA: FAILED - %s\n", reply);
return false;
}
uclient.stop();
Serial.println("OTA: write complete, rebooting...");
mesh::usbLoggingPort().println("OTA: write complete, rebooting...");
delay(250);
esp_restart();
return true; // unreachable
@@ -0,0 +1,78 @@
#pragma once
#include <stddef.h>
#include <stdint.h>
#include <string.h>
namespace mesh {
namespace indicator_font {
// STAGEV2 is deliberately a separate command word from the legacy STAGE
// grammar. Old RP2040 services therefore reject it before consuming binary
// data, which makes the explicit ERROR COMMAND response safe to fall back on.
static constexpr size_t kStageV2ChunkBytes = 512;
static constexpr char kStageV2ReadyReply[] = "READY 2 512";
static constexpr char kStageV2LegacyUnsupportedReply[] = "ERROR COMMAND";
enum class StageV2BeginAction : uint8_t {
UseAcknowledged,
UseLegacy,
Fail,
};
inline StageV2BeginAction classifyStageV2BeginReply(bool replied,
const char* reply) {
if (!replied || reply == nullptr) return StageV2BeginAction::Fail;
if (strcmp(reply, kStageV2ReadyReply) == 0) {
return StageV2BeginAction::UseAcknowledged;
}
if (strcmp(reply, kStageV2LegacyUnsupportedReply) == 0) {
return StageV2BeginAction::UseLegacy;
}
return StageV2BeginAction::Fail;
}
inline size_t stageV2ChunkSize(size_t total, size_t acknowledged) {
if (acknowledged >= total) return 0;
const size_t remaining = total - acknowledged;
return remaining < kStageV2ChunkBytes ? remaining : kStageV2ChunkBytes;
}
// Advance only after the receiver has accepted the complete negotiated block.
// This keeps cumulative ACK offsets unambiguous and rejects premature/partial
// progress observations.
inline bool advanceStageV2Offset(size_t total, size_t acknowledged,
size_t stored, size_t& next) {
const size_t expected = stageV2ChunkSize(total, acknowledged);
if (expected == 0 || stored != expected) return false;
next = acknowledged + expected; // bounded by total, so this cannot overflow
return true;
}
inline bool parseStageV2Ack(const char* reply, size_t expectedOffset) {
static constexpr char prefix[] = "ACK ";
if (reply == nullptr || expectedOffset == 0
|| strncmp(reply, prefix, sizeof(prefix) - 1) != 0) {
return false;
}
const char* cursor = reply + sizeof(prefix) - 1;
if (*cursor < '0' || *cursor > '9') return false;
// The RP2040 emits canonical decimal offsets. Reject alternate spellings so
// stale or damaged lines cannot be interpreted leniently.
if (*cursor == '0' && cursor[1] != 0) return false;
size_t parsed = 0;
const size_t maximum = (size_t)-1;
do {
const size_t digit = (size_t)(*cursor - '0');
if (parsed > (maximum - digit) / 10) return false;
parsed = parsed * 10 + digit;
++cursor;
} while (*cursor >= '0' && *cursor <= '9');
return *cursor == 0 && parsed == expectedOffset;
}
} // namespace indicator_font
} // namespace mesh
+6 -1
View File
@@ -10,6 +10,7 @@
#include <string.h>
#include "ed_25519.h"
#include "mbedtls/base64.h"
#include "UsbLogging.h"
// Base64 URL encoding table (without padding)
static const char base64url_chars[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
@@ -87,7 +88,11 @@ bool JWTHelper::createAuthToken(
#if !defined(PORTABLE_MQTT_OBSERVER)
int verify_result = ed25519_verify(signature, (const unsigned char*)signingInput, signingInputLen, public_key);
if (verify_result != 1) {
if (Serial.availableForWrite() > 0) Serial.println("JWTHelper: Signature verification failed!");
if (mesh::isUsbLoggingEnabled()
&& mesh::usbLoggingPort().availableForWrite() > 0) {
mesh::usbLoggingPort().println(
"JWTHelper: Signature verification failed!");
}
return false;
}
#endif
+68
View File
@@ -0,0 +1,68 @@
#pragma once
#include <stdint.h>
namespace mesh {
static const uint32_t LAZY_PERSISTENCE_MAX_RETRY_DELAY_MILLIS = 300000UL;
inline unsigned long nonzeroLazyPersistenceDeadline(unsigned long deadline) {
// Zero is the callers' "not pending" sentinel. Preserve a pending write at
// the single millis() value where deadline arithmetic wraps exactly to zero.
return deadline == 0 ? 1UL : deadline;
}
inline bool armFirstLazyPersistence(unsigned long& pending_deadline,
unsigned long new_deadline,
bool persistence_needed) {
if (!persistence_needed || pending_deadline != 0) return false;
pending_deadline = nonzeroLazyPersistenceDeadline(new_deadline);
return true;
}
inline bool scheduleLazyPersistenceMutation(
unsigned long& pending_deadline,
uint8_t& consecutive_failures,
unsigned long new_deadline) {
// Once persistence has failed, ordinary mutations must not turn a permanent
// filesystem fault back into a five-second wake/write loop. Only a
// successful save resets the failure count and its bounded retry deadline.
if (consecutive_failures != 0) {
if (pending_deadline != 0) return false;
pending_deadline = nonzeroLazyPersistenceDeadline(new_deadline);
return true;
}
if (pending_deadline != 0) return false;
pending_deadline = nonzeroLazyPersistenceDeadline(new_deadline);
return true;
}
inline uint32_t recordLazyPersistenceSaveFailure(
uint8_t& consecutive_failures,
uint32_t base_delay,
uint32_t maximum_delay) {
uint32_t delay = base_delay > maximum_delay ? maximum_delay : base_delay;
uint8_t remaining_doublings = consecutive_failures;
while (remaining_doublings-- != 0 && delay < maximum_delay) {
delay = delay > maximum_delay / 2U ? maximum_delay : delay * 2U;
}
if (consecutive_failures != UINT8_MAX) consecutive_failures++;
return delay;
}
inline void resetLazyPersistenceAfterSuccess(
unsigned long& pending_deadline,
uint8_t& consecutive_failures) {
pending_deadline = 0;
consecutive_failures = 0;
}
inline void completeLazyPersistenceSave(unsigned long& pending_deadline,
bool save_succeeded,
unsigned long retry_deadline) {
pending_deadline = save_succeeded
? 0UL
: nonzeroLazyPersistenceDeadline(retry_deadline);
}
} // namespace mesh
+69
View File
@@ -1,5 +1,6 @@
#pragma once
#include <atomic>
#include <stdint.h>
// Pure timing and state-transition policy used by MQTTBridge's connection
@@ -13,6 +14,8 @@ static const uint32_t kStableResetMs = 120000UL;
static const uint32_t kCircuitBreakerProbeMs = 1800000UL;
static const uint32_t kRenewalThrottleMs = 60000UL;
static const uint32_t kSlotStaggerMs = 3000UL;
static const uint32_t kNtpRefreshIntervalMs = 86400000UL; // 24 hours
static const uint32_t kNtpRetryMs = 5000UL;
static const uint8_t kMaxFailuresAtMaxBackoff = 3;
static const uint32_t kDefaultJwtLifetimeSecs = 86400UL;
static const uint32_t kMaxJwtStaggerSecs = 300UL;
@@ -30,6 +33,53 @@ static inline uint32_t elapsedMs(uint32_t now, uint32_t then) {
return now - then;
}
// A pending short retry takes precedence over the normal daily schedule. The
// signed deadline comparison is safe because the retry is only five seconds
// away; the daily path uses unsigned elapsed time and therefore survives one
// millis() rollover as well.
static inline bool ntpRefreshDue(uint32_t now, uint32_t last_sync,
uint32_t retry_at) {
if (retry_at != 0) {
return static_cast<int32_t>(now - retry_at) >= 0;
}
return elapsedMs(now, last_sync) >= kNtpRefreshIntervalMs;
}
static inline uint32_t ntpRetryAt(uint32_t now) {
const uint32_t retry_at = now + kNtpRetryMs;
// Zero is the "no retry scheduled" sentinel, so move that one rollover
// collision forward by one millisecond.
return retry_at == 0 ? 1 : retry_at;
}
static inline uint32_t ntpReconnectRefreshAt(uint32_t now) {
// Reconnection invalidates any old short deadline. Schedule the refresh for
// the current task loop while preserving zero as the unscheduled sentinel.
return now == 0 ? 1 : now;
}
// WiFi events can run on a different task from MQTT maintenance. Keep the
// callback to a single atomic edge latch: the MQTT task consumes the edge only
// after WiFi is connected and makes every clock/scheduler decision itself.
// Coalescing multiple GOT_IP events is intentional; one fresh sample after the
// latest reconnect is sufficient.
class NtpReconnectLatch {
public:
NtpReconnectLatch() : _pending(false) {}
void noteGotIp() {
_pending.store(true, std::memory_order_release);
}
bool consumeIfConnected(bool wifi_connected) {
if (!wifi_connected) return false;
return _pending.exchange(false, std::memory_order_acq_rel);
}
private:
std::atomic<bool> _pending;
};
static inline bool reconnectGuardActive(uint32_t now, uint32_t last_reconnect) {
return elapsedMs(now, last_reconnect) < kReconnectGuardMs;
}
@@ -238,6 +288,25 @@ enum class ClockSource : uint8_t {
Rtc,
};
// RTCClock carries Unix seconds in a uint32_t. Validate the signed system
// time before converting it: time(nullptr) uses -1 for failure, which would
// otherwise become UINT32_MAX and look newer than every minimum-epoch check.
// Reject values beyond the RTC wire/storage range as well instead of wrapping
// them into an apparently plausible earlier date.
static inline bool checkedRtcEpoch(int64_t candidate,
uint32_t min_valid_epoch,
uint32_t& accepted) {
accepted = 0;
if (candidate < 0
|| static_cast<uint64_t>(candidate) > UINT32_MAX) {
return false;
}
const uint32_t converted = static_cast<uint32_t>(candidate);
if (converted < min_valid_epoch) return false;
accepted = converted;
return true;
}
// Prefer a plausible system clock, then an RTC. Server validation may not use
// a local clock as evidence that the requested NTP host answered.
static inline ClockSource chooseFallbackClock(bool validating_server,
+54
View File
@@ -0,0 +1,54 @@
#pragma once
#include <Arduino.h>
#include <atomic>
#include <stddef.h>
#include <stdint.h>
namespace mesh {
// A Stream facade for a transport whose underlying write() may wait for FIFO
// space. It never retries or forwards a write larger than one nRF52 TinyUSB TX
// FIFO. Print::printf() can report a length larger than its 256-byte scratch
// buffer; rejecting such a call here also prevents that stale length from
// making the delegate read beyond the scratch buffer.
template <size_t MAX_WRITE_SIZE = 256>
class WholeRecordNonBlockingStream : public Stream {
public:
explicit WholeRecordNonBlockingStream(Stream& delegate)
: _delegate(delegate) {}
int available() override { return _delegate.available(); }
int read() override { return _delegate.read(); }
int peek() override { return _delegate.peek(); }
void flush() override { _delegate.flush(); }
int availableForWrite() override { return _delegate.availableForWrite(); }
size_t write(uint8_t value) override {
return write(&value, 1);
}
size_t write(const uint8_t* data, size_t size) override {
if (data == nullptr || size == 0 || size > MAX_WRITE_SIZE) return 0;
// Never wait for another application writer. All diagnostic access to the
// delegate is routed through this facade; the USB task can only drain the
// TX FIFO, so free capacity cannot shrink while this gate is held.
if (_writer_busy.test_and_set(std::memory_order_acquire)) return 0;
size_t written = 0;
const int available = _delegate.availableForWrite();
if (available >= 0 && static_cast<size_t>(available) >= size) {
written = _delegate.write(data, size);
}
_writer_busy.clear(std::memory_order_release);
return written;
}
private:
Stream& _delegate;
std::atomic_flag _writer_busy = ATOMIC_FLAG_INIT;
};
} // namespace mesh
+63 -4
View File
@@ -49,14 +49,15 @@ void SensorManager::updateGpsTelemetryCache(float lat, float lon, float altitude
}
void SensorManager::maybeStopGpsForTelemetry(unsigned long now) {
if (telemetryGpsActive() && !gps_user_enabled && !gps_acquiring && !gpsTelemetryHoldActive(now)) {
if (gps_transport_available && telemetryGpsActive() && !gps_user_enabled
&& !gps_acquiring && !gpsTelemetryHoldActive(now)) {
telemetryGpsStop();
gps_next_cache_update_at = now + GPS_TELEMETRY_CACHE_INTERVAL_SEC * 1000UL;
}
}
void SensorManager::beginGpsTelemetryAcquisition(unsigned long now) {
if (!telemetryGpsDetected() || gps_acquiring) return;
if (!gps_transport_available || !telemetryGpsDetected() || gps_acquiring) return;
gps_acquiring = true;
gps_acquire_has_fix = false;
@@ -83,9 +84,19 @@ void SensorManager::finishGpsTelemetryAcquisition(unsigned long now, bool use_we
}
bool SensorManager::queryGpsTelemetry(uint8_t requester_permissions, CayenneLPP& telemetry) {
if (!(requester_permissions & TELEM_PERM_LOCATION) || !telemetryGpsDetected()) return false;
if (!(requester_permissions & TELEM_PERM_LOCATION)
|| !telemetryGpsDetected()) return false;
unsigned long now = millis();
if (!gps_transport_available) {
// A bridge may temporarily own the GPS UART. Authorized callers can still
// receive the last good fix while it is inside the normal freshness bound,
// but the query must not create a hold or try to reclaim the UART.
if (!gpsTelemetryCacheFresh(now)) return false;
telemetry.addGPS(TELEM_CHANNEL_SELF, gps_cache_lat, gps_cache_lon,
gps_cache_altitude);
return true;
}
gps_hold_until = now + GPS_TELEMETRY_HOLD_SEC * 1000UL;
if (!telemetryGpsActive()) telemetryGpsStart();
if (!gpsTelemetryCacheFresh(now) && !gps_acquiring) beginGpsTelemetryAcquisition(now);
@@ -96,6 +107,7 @@ bool SensorManager::queryGpsTelemetry(uint8_t requester_permissions, CayenneLPP&
}
void SensorManager::processGpsTelemetryFix(float lat, float lon, float altitude, unsigned long now) {
if (!gps_transport_available) return;
if (!gps_acquiring) {
if (gps_user_enabled || gpsTelemetryHoldActive(now)) {
updateGpsTelemetryCache(lat, lon, altitude, now);
@@ -129,6 +141,7 @@ void SensorManager::processGpsTelemetryFix(float lat, float lon, float altitude,
}
void SensorManager::loopGpsTelemetry(unsigned long now) {
if (!gps_transport_available) return;
if (!gps_user_enabled && !gpsTelemetryHoldActive(now) && !gps_acquiring) {
maybeStopGpsForTelemetry(now);
}
@@ -146,11 +159,57 @@ void SensorManager::setGpsTelemetryUserEnabled(bool enabled) {
gps_user_enabled = enabled;
unsigned long now = millis();
if (enabled) {
if (telemetryGpsDetected() && !telemetryGpsActive()) telemetryGpsStart();
if (gps_transport_available && telemetryGpsDetected()
&& !telemetryGpsActive()) telemetryGpsStart();
} else {
maybeStopGpsForTelemetry(now);
}
}
void SensorManager::setGpsTelemetryTransportAvailable(bool available) {
if (gps_transport_available == available) return;
gps_transport_available = available;
if (!available) {
// The UART is no longer ours. Cancel both the short acquisition and the
// two-hour remote-query hold so neither can silently reclaim it from a
// bridge. Preserve the user's preference and last good cache.
gps_acquiring = false;
gps_acquire_has_fix = false;
gps_hold_until = 0;
gps_acquire_started_at = 0;
gps_stable_started_at = 0;
gps_weighted_lat = 0;
gps_weighted_lon = 0;
gps_weighted_altitude = 0;
gps_weight_sum = 0;
gps_weight_count = 0;
return;
}
gps_next_cache_update_at = 0;
if (gps_user_enabled && telemetryGpsDetected() && !telemetryGpsActive()) {
telemetryGpsStart();
}
}
void SensorManager::resetGpsTelemetryTransportState() {
// Hardware discovery may be rerun after a bridge-owned UART was blocked.
// Reset transient ownership without invoking a provider callback before the
// new probe has established which provider, if any, is present.
gps_transport_available = true;
gps_acquiring = false;
gps_acquire_has_fix = false;
gps_hold_until = 0;
gps_acquire_started_at = 0;
gps_stable_started_at = 0;
gps_weighted_lat = 0;
gps_weighted_lon = 0;
gps_weighted_altitude = 0;
gps_weight_sum = 0;
gps_weight_count = 0;
gps_next_cache_update_at = 0;
}
#endif
void SensorManager::setTelemetryLocationAccessAvailable(bool available) {
+31
View File
@@ -16,6 +16,7 @@ class SensorManager {
#if ENV_INCLUDE_GPS
bool gps_cache_valid = false;
bool gps_location_access_available = false;
bool gps_transport_available = true;
bool gps_user_enabled = false;
bool gps_acquiring = false;
bool gps_acquire_has_fix = false;
@@ -52,7 +53,12 @@ protected:
void processGpsTelemetryFix(float lat, float lon, float altitude, unsigned long now);
void loopGpsTelemetry(unsigned long now);
void setGpsTelemetryUserEnabled(bool enabled);
void setGpsTelemetryTransportAvailable(bool available);
void resetGpsTelemetryTransportState();
bool isGpsTelemetryUserEnabled() const { return gps_user_enabled; }
bool isGpsTelemetryTransportAvailable() const {
return gps_transport_available;
}
bool gpsTelemetryReceiverRequired(unsigned long now) const {
return gps_acquiring || gpsTelemetryHoldActive(now);
}
@@ -109,6 +115,31 @@ public:
}
virtual LocationProvider* getLocationProvider() { return NULL; }
virtual void setPowerSavingEnabled(bool enabled) { powersaving_enabled = enabled; }
// Runtime bridges may temporarily own the UART used by a GPS receiver. A
// sensor manager that actually detected a GPS on that UART overrides these
// hooks; I2C GPS providers and boards without GPS remain unaffected.
virtual bool gpsUsesSerialUart(uint8_t uart) const {
(void)uart;
return false;
}
// A universal image may need to reserve a UART even when a receiver did not
// speak during its bounded boot probe. The default has no such uncertainty;
// hardware-specific managers can fail closed for a known shared connector.
virtual bool gpsSerialTransportMayConflict(uint8_t uart) const {
return gpsUsesSerialUart(uart);
}
// True only when the detected receiver can be made electrically silent on
// the selected UART. Stopping the MCU UART alone is not sufficient when a
// still-powered GPS continues driving its TX pin.
virtual bool gpsSerialTransportCanYield(uint8_t uart) const {
(void)uart;
return false;
}
virtual bool setGpsSerialTransportBlocked(uint8_t uart, bool blocked) {
(void)uart;
(void)blocked;
return false;
}
// Helper functions to manage setting by keys (useful in many places ...)
const char* getSettingByKey(const char* key) {
+38
View File
@@ -0,0 +1,38 @@
#pragma once
#include <stdint.h>
namespace mesh {
// Scheduled TempRadio uses wall-clock epochs so independently managed nodes
// can enter one common window. The wall clock may legitimately be corrected
// backward by mesh/GPS/NTP consensus, however, and that must never extend a
// temporary modulation lease. Anchor the accepted end to 64-bit uptime too;
// wall time decides when to start, while either clock is allowed to end it.
class TempRadioLeaseDeadline {
public:
static uint64_t fromEpochEnd(uint64_t now_uptime_millis,
uint32_t now_epoch,
uint32_t end_epoch) {
if (end_epoch <= now_epoch) return now_uptime_millis;
return now_uptime_millis
+ (uint64_t)(end_epoch - now_epoch) * 1000ULL;
}
static bool expired(uint64_t now_uptime_millis,
uint64_t hard_end_uptime_millis) {
return hard_end_uptime_millis != 0
&& now_uptime_millis >= hard_end_uptime_millis;
}
static uint32_t secondsUntil(uint64_t now_uptime_millis,
uint64_t hard_end_uptime_millis) {
if (hard_end_uptime_millis == 0) return UINT32_MAX;
if (now_uptime_millis >= hard_end_uptime_millis) return 0;
uint64_t remaining_millis = hard_end_uptime_millis - now_uptime_millis;
uint64_t seconds = (remaining_millis + 999ULL) / 1000ULL;
return seconds > UINT32_MAX ? UINT32_MAX : (uint32_t)seconds;
}
};
} // namespace mesh
+30
View File
@@ -0,0 +1,30 @@
#pragma once
namespace mesh {
// A parameterized TempRadio command changes the modulation used to carry its
// own remote-CLI reply. A wall-clock delay cannot prove that the reply has
// left a busy outbound queue, so keep the scheduled handoff blocked by the
// exact packet object until Dispatcher reports TX completion. This class is
// deliberately pointer-only: packet ownership stays with Dispatcher.
class TempRadioReplyBarrier {
const void* _packet;
public:
TempRadioReplyBarrier() : _packet(nullptr) {}
void arm(const void* packet) { _packet = packet; }
void clear() { _packet = nullptr; }
bool waiting() const { return _packet != nullptr; }
bool complete(const void* packet) {
if (_packet == nullptr || packet != _packet) return false;
_packet = nullptr;
return true;
}
bool fail(const void* packet) { return complete(packet); }
};
} // namespace mesh
+35 -2
View File
@@ -4,6 +4,10 @@
#include <Arduino.h>
#include <atomic>
#if defined(NRF52_PLATFORM)
#include "NonBlockingWriteStream.h"
#endif
#if defined(MESH_DUAL_CDC_LOGGING)
#if !defined(COMPANION_FEATURE_DEDICATED_USB_LOGGING) || \
!COMPANION_FEATURE_DEDICATED_USB_LOGGING
@@ -42,11 +46,30 @@ class NullUsbLoggingStream : public Stream {
static NullUsbLoggingStream null_usb_logging_stream;
static void setPlatformDebugOutputEnabled(bool enabled) {
#if defined(ESP32_PLATFORM) && defined(ENABLE_USB_INTERFACE)
// Arduino-ESP32 log_e()/ESP-IDF diagnostics otherwise write straight to
// the same UART/CDC stream used by Binary Companion. Keep that low-level
// route under the same runtime gate as MeshCore's own diagnostics.
Serial.setDebugOutput(enabled);
#else
(void)enabled;
#endif
}
#if defined(MESH_DUAL_CDC_LOGGING)
static bool dedicated_usb_logging_port_configured = false;
static bool dedicated_usb_logging_port_started = false;
static bool dedicated_usb_logging_port_connected = false;
static Adafruit_USBD_CDC dedicated_usb_logging_port;
static WholeRecordNonBlockingStream<>
nonblocking_dedicated_usb_logging_port(dedicated_usb_logging_port);
#elif defined(NRF52_PLATFORM)
// Single-CDC nRF52 roles need the same protection. In particular, BLE debug
// callbacks and packet logging write through usbLoggingPort() without going
// through MeshCore's formatted-debug helper.
static WholeRecordNonBlockingStream<>
nonblocking_primary_usb_logging_port(Serial);
#endif
bool isUsbLoggingEnabled() {
@@ -56,6 +79,7 @@ bool isUsbLoggingEnabled() {
void setUsbLoggingEnabled(bool enabled) {
usb_logging_enabled.store(enabled, std::memory_order_relaxed);
usb_logging_preference_known.store(true, std::memory_order_relaxed);
setPlatformDebugOutputEnabled(enabled);
}
bool saveUsbLoggingBootPreference(bool enabled) {
@@ -64,6 +88,11 @@ bool saveUsbLoggingBootPreference(bool enabled) {
}
void beginUsbLoggingPort() {
// setup() calls this once before role preferences are loaded and again
// afterwards. The first call silences framework diagnostics on a protected
// ESP32 Companion stream; setUsbLoggingEnabled() restores them only when the
// saved setting explicitly enables logging.
setPlatformDebugOutputEnabled(isUsbLoggingEnabled());
#if defined(MESH_DUAL_CDC_LOGGING)
if (dedicated_usb_logging_port_started
|| !usb_logging_preference_known.load(std::memory_order_relaxed)
@@ -109,12 +138,16 @@ void serviceUsbLoggingPort() {
Stream& usbLoggingPort() {
#if defined(MESH_DUAL_CDC_LOGGING)
if (isUsbLoggingEnabled() && dedicated_usb_logging_port_started) {
return dedicated_usb_logging_port;
return nonblocking_dedicated_usb_logging_port;
}
return null_usb_logging_stream;
#else
if (!isUsbLoggingEnabled()) return null_usb_logging_stream;
return Serial;
#if defined(NRF52_PLATFORM)
return nonblocking_primary_usb_logging_port;
#else
return Serial;
#endif
#endif
}
+27 -12
View File
@@ -10,6 +10,7 @@
#include <freertos/task.h>
#include <strings.h>
#include <helpers/CLICommandUtils.h>
#include <helpers/UsbLogging.h>
#include <helpers/esp32/WiFiRadioPolicy.h>
#include <helpers/esp32/WiFiStationPolicy.h>
@@ -173,7 +174,8 @@ static void handleSave(PortalImpl* impl, WiFiClient& client, const char* body) {
// A submitted configuration takes priority over a background retry of the
// previously saved network.
impl->recovery_connecting = false;
Serial.printf("WiFi setup: connecting to '%s'...\n", ssid);
mesh::usbLoggingPort().printf(
"WiFi setup: connecting to '%s'...\n", ssid);
mesh::wifi::beginStation(ssid, password);
uint32_t deadline = millis() + CONNECT_TIMEOUT_MS;
while (impl->active && *impl->active && WiFi.status() != WL_CONNECTED
@@ -187,7 +189,8 @@ static void handleSave(PortalImpl* impl, WiFiClient& client, const char* body) {
sendResponse(client, 200, "OK", "text/html",
"<!doctype html><meta name=viewport content='width=device-width'><h2>Connection failed</h2>"
"<p>Check the SSID and password, then <a href='/'>try again</a>.</p>");
Serial.println("WiFi setup: connection failed; setup AP remains active");
mesh::usbLoggingPort().println(
"WiFi setup: connection failed; setup AP remains active");
return;
}
@@ -195,7 +198,8 @@ static void handleSave(PortalImpl* impl, WiFiClient& client, const char* body) {
WiFi.disconnect();
sendResponse(client, 500, "Internal Server Error", "text/plain",
"Connected, but the credentials could not be saved.");
Serial.println("WiFi setup: connected, but credential persistence failed");
mesh::usbLoggingPort().println(
"WiFi setup: connected, but credential persistence failed");
return;
}
@@ -218,7 +222,8 @@ static void handleSave(PortalImpl* impl, WiFiClient& client, const char* body) {
ip.c_str());
#endif
sendResponse(client, 200, "OK", "text/html", response);
Serial.printf("WiFi setup: connected; IP %s\n", ip.c_str());
mesh::usbLoggingPort().printf(
"WiFi setup: connected; IP %s\n", ip.c_str());
impl->close_ap_at = millis() + AP_CLOSE_DELAY_MS;
}
@@ -272,18 +277,22 @@ static void portalTask(void* arg) {
if (impl->recovery_connecting) {
if (WiFi.status() == WL_CONNECTED) {
String ip = WiFi.localIP().toString();
Serial.printf("WiFi setup: saved network recovered; IP %s\n", ip.c_str());
mesh::usbLoggingPort().printf(
"WiFi setup: saved network recovered; IP %s\n", ip.c_str());
impl->recovery_connecting = false;
break;
}
if (static_cast<int32_t>(now - impl->recovery_deadline) >= 0) {
WiFi.disconnect();
impl->recovery_connecting = false;
Serial.println("WiFi setup: saved network still unavailable; setup AP remains active");
mesh::usbLoggingPort().println(
"WiFi setup: saved network still unavailable; setup AP remains active");
}
} else if (impl->recovery_ssid[0] && impl->recovery_interval_ms
&& static_cast<int32_t>(now - impl->next_recovery_at) >= 0) {
Serial.printf("WiFi setup: retrying saved network '%s'...\n", impl->recovery_ssid);
mesh::usbLoggingPort().printf(
"WiFi setup: retrying saved network '%s'...\n",
impl->recovery_ssid);
mesh::wifi::beginStation(
impl->recovery_ssid, impl->recovery_password);
impl->recovery_connecting = true;
@@ -358,8 +367,9 @@ bool WiFiSetupPortal::begin(const char* ap_name, SaveCallback save_callback, voi
impl->task = nullptr;
return false;
}
Serial.printf("WiFi setup: join open AP '%s' and open http://%s/\n",
impl->ap_name, SETUP_IP.toString().c_str());
mesh::usbLoggingPort().printf(
"WiFi setup: join open AP '%s' and open http://%s/\n",
impl->ap_name, SETUP_IP.toString().c_str());
return true;
}
@@ -394,9 +404,14 @@ bool WiFiSetupPortal::loadStoredCredentials(char* ssid, size_t ssid_size,
char* password, size_t password_size) {
if (!ssid || ssid_size == 0 || !password || password_size == 0) return false;
Preferences prefs;
if (!prefs.begin("mesh-wifi", true)) return false;
String stored_ssid = prefs.getString("ssid", "");
String stored_password = prefs.getString("password", "");
// Opening read-only reports ESP_ERR_NVS_NOT_FOUND on a normal fresh install.
// Read-write creates the namespace once; guard absent String keys because
// Preferences::getString() also logs NOT_FOUND instead of returning quietly.
if (!prefs.begin("mesh-wifi", false)) return false;
String stored_ssid = prefs.isKey("ssid")
? prefs.getString("ssid", "") : String();
String stored_password = prefs.isKey("password")
? prefs.getString("password", "") : String();
prefs.end();
if (stored_ssid.length() == 0 || stored_ssid.length() >= ssid_size
|| stored_password.length() >= password_size
+221 -37
View File
@@ -7,6 +7,7 @@
#include "../MQTTRuntimeBufferLifecycle.h"
#include "../MQTTTopicRouter.h"
#include "../TxtDataHelpers.h"
#include "../UsbLogging.h"
#include "../WiFiPowerSave.h"
#include <NTPClient.h>
#include <WiFiUdp.h>
@@ -25,6 +26,7 @@
#include <esp_wifi.h>
#include <esp_sntp.h>
#include <esp_heap_caps.h>
#include <helpers/esp32/SntpOperationCoordinator.h>
#include <helpers/esp32/WiFiStationPolicy.h>
#include <freertos/FreeRTOS.h>
#include <freertos/task.h>
@@ -58,6 +60,21 @@ static constexpr size_t kNtpBuiltinFallbackCount =
static_assert(MQTTBridge::kMaxNtpServers >= 1 + (int)kNtpBuiltinFallbackCount,
"kMaxNtpServers must hold the custom primary plus all built-in fallbacks");
static constexpr uint32_t MQTT_NTP_REFRESH_TIMEOUT_MS = 15000UL;
#ifndef ESP_PLATFORM
static constexpr uint32_t MQTT_NTP_NON_ESP_SETTLE_MS = 5000UL;
#endif
static constexpr unsigned long MQTT_NTP_MIN_VALID_EPOCH = 1767225600UL;
static bool mqttNtpRefreshDue(uint32_t now, uint32_t last_sync,
uint32_t retry_at) {
return MQTTConnectionPolicy::ntpRefreshDue(now, last_sync, retry_at);
}
static uint32_t mqttNtpRetryAt(uint32_t now) {
return MQTTConnectionPolicy::ntpRetryAt(now);
}
static void formatRadioInfo(float freq, float bw, int sf, int cr,
char* dest, size_t dest_size) {
char freq_text[20];
@@ -664,7 +681,7 @@ MQTTBridge::MQTTBridge(const MQTTNodeInfo& node_info, MQTTPrefs *obs,
_manage_wifi(manage_wifi),
_queue_count(0),
_last_status_publish(0), _last_status_retry(0), _status_interval(300000),
_ntp_client(_ntp_udp, effectiveNtpPrimary(obs), 0, 60000), _last_ntp_sync(0), _ntp_synced(false), _ntp_sync_pending(false), _slots_setup_done(false), _max_active_slots(RUNTIME_MQTT_SLOTS),
_ntp_client(_ntp_udp, effectiveNtpPrimary(obs), 0, 60000), _last_ntp_sync(0), _ntp_refresh_retry_at(0), _ntp_refresh_started_at(0), _ntp_refresh_pending(false), _ntp_synced(false), _ntp_sync_pending(false), _ntp_reconnect_latch(), _slots_setup_done(false), _max_active_slots(RUNTIME_MQTT_SLOTS),
_ntp_force_requested(false), _ntp_force_done(false), _ntp_force_result(false),
_ntp_diag_requested(false), _ntp_diag_done(false), _ntp_diag_count(0),
_ntp_estimate_requested(false), _ntp_estimate_done(false),
@@ -847,6 +864,13 @@ void MQTTBridge::begin() {
return;
}
_ntp_refresh_retry_at = 0;
_ntp_refresh_started_at = 0;
_ntp_refresh_pending = false;
// Do not clear _ntp_reconnect_latch here. The WiFi event handler remains
// registered while MQTT is stopped, so a GOT_IP edge received between end()
// and begin() must survive until the restarted task can consume it.
// A restarted bridge may be using a different preset or custom endpoint.
// Clear the old slot description before rebuilding it from _obs below.
for (int i = 0; i < RUNTIME_MQTT_SLOTS; i++) {
@@ -1316,10 +1340,9 @@ void MQTTBridge::initializeWiFiInTask() {
MQTT_DEBUG_PRINTLN("WiFi connected: %s", IPAddress(info.got_ip.ip_info.ip.addr).toString().c_str());
setWifiOutage(AlertFaultPolicy::applyWifiGotIp(wifiOutage()));
_wifi_reconnect_backoff_attempt = 0;
// Set flag to trigger NTP sync from loop() instead of doing it here
if (!_ntp_synced && !_ntp_sync_pending) {
_ntp_sync_pending = true;
}
// The 10-second status sampler can miss a short link flap. The event
// callback only records the edge; all NTP state remains task-owned.
_ntp_reconnect_latch.noteGotIp();
break;
case ARDUINO_EVENT_WIFI_STA_DISCONNECTED: {
const uint8_t reason = info.wifi_sta_disconnected.reason;
@@ -1348,7 +1371,8 @@ void MQTTBridge::initializeWiFiInTask() {
if (_manage_wifi) {
mesh::wifi::beginStation(_obs->wifi_ssid, _obs->wifi_password);
}
} else if (!_ntp_synced && !_ntp_sync_pending) {
} else if (!_ntp_synced.load(std::memory_order_acquire)
&& !_ntp_sync_pending) {
_ntp_sync_pending = true; // already connected but never synced - kick NTP now
}
@@ -1430,6 +1454,23 @@ void MQTTBridge::mqttTaskLoop() {
_slots[i].last_reconnect_attempt = 0;
}
}
_ntp_reconnect_latch.noteGotIp();
}
const bool wifi_connected = WiFi.status() == WL_CONNECTED;
if (_ntp_reconnect_latch.consumeIfConnected(wifi_connected)) {
if (!_ntp_synced.load(std::memory_order_acquire)) {
_ntp_sync_pending = true;
} else {
// A successful reconnect gets one fresh clock sample regardless of how
// long the link was down. This also discards a short retry deadline that
// may be ambiguous after a very long offline interval. The normal
// continuously-connected cadence remains once per day.
_ntp_refresh_pending = false;
_ntp_refresh_started_at = 0;
_ntp_refresh_retry_at =
MQTTConnectionPolicy::ntpReconnectRefreshAt(now);
}
}
// Check for pending NTP sync (triggered from WiFi event handler)
@@ -1439,7 +1480,8 @@ void MQTTBridge::mqttTaskLoop() {
}
// Retry NTP every 30s if initial sync failed (slots can't start without valid time)
if (!_ntp_synced && WiFi.status() == WL_CONNECTED) {
if (!_ntp_synced.load(std::memory_order_acquire)
&& WiFi.status() == WL_CONNECTED) {
static unsigned long last_ntp_retry = 0;
if (now - last_ntp_retry >= 30000) {
last_ntp_retry = now;
@@ -1481,7 +1523,7 @@ void MQTTBridge::mqttTaskLoop() {
// Deferred slot setup: wait until NTP is synced so JWT tokens get valid timestamps.
// This avoids wasted TLS handshakes that get rejected due to bad token times.
if (_ntp_synced && !_slots_setup_done) {
if (_ntp_synced.load(std::memory_order_acquire) && !_slots_setup_done) {
_slots_setup_done = true;
// Redirect mbedTLS allocations to PSRAM to save ~40KB internal heap per TLS connection.
@@ -1586,10 +1628,14 @@ void MQTTBridge::mqttTaskLoop() {
// Periodic configuration check (throttled to avoid spam)
checkConfigurationMismatch();
// Periodic NTP refresh (every hour) - lightweight, non-blocking.
// Periodic NTP refresh (once per day) - lightweight, non-blocking.
// Uses async SNTP instead of the heavy syncTimeWithNTP() which blocks Core 0
// for up to 20+ seconds with DNS lookups, UDP sockets, and retry loops.
if (WiFi.status() == WL_CONNECTED && now - _last_ntp_sync > 3600000) {
pollNtpRefresh(now);
if (WiFi.status() == WL_CONNECTED
&& !_ntp_refresh_pending
&& mqttNtpRefreshDue(now, _last_ntp_sync,
_ntp_refresh_retry_at)) {
refreshNTP();
}
@@ -2132,7 +2178,8 @@ void MQTTBridge::maintainSlotConnections() {
// JWT tokens require valid timestamps
unsigned long clock_sec = current_time;
bool can_do_jwt = MQTTConnectionPolicy::jwtClockAvailable(
_ntp_synced, static_cast<uint32_t>(clock_sec));
_ntp_synced.load(std::memory_order_acquire),
static_cast<uint32_t>(clock_sec));
// Count connected slots to inform reconnect decisions
int connected_count = 0;
@@ -3008,8 +3055,16 @@ void MQTTBridge::loop() {
return;
#else
unsigned long now = millis();
if (handleWiFiConnection(now) && !_ntp_synced) {
syncTimeWithNTP();
const bool wifi_just_connected = handleWiFiConnection(now);
if (wifi_just_connected) {
if (!_ntp_synced.load(std::memory_order_acquire)) {
syncTimeWithNTP();
} else {
_ntp_refresh_pending = false;
_ntp_refresh_started_at = 0;
_ntp_refresh_retry_at =
MQTTConnectionPolicy::ntpReconnectRefreshAt((uint32_t)now);
}
}
if (_ntp_sync_pending && WiFi.status() == WL_CONNECTED) {
_ntp_sync_pending = false;
@@ -3022,7 +3077,7 @@ void MQTTBridge::loop() {
}
// Deferred slot setup after NTP sync (non-ESP32 path)
if (_ntp_synced && !_slots_setup_done) {
if (_ntp_synced.load(std::memory_order_acquire) && !_slots_setup_done) {
_slots_setup_done = true;
for (int i = 0; i < RUNTIME_MQTT_SLOTS; i++) {
if (_slots[i].enabled) {
@@ -3055,8 +3110,13 @@ void MQTTBridge::loop() {
// Periodic configuration check (throttled to avoid spam)
checkConfigurationMismatch();
// Periodic NTP refresh (every hour) - lightweight, non-blocking.
if (WiFi.status() == WL_CONNECTED && millis() - _last_ntp_sync > 3600000) {
// Periodic NTP refresh (once per day) - lightweight, non-blocking.
const uint32_t ntp_now = millis();
pollNtpRefresh(ntp_now);
if (WiFi.status() == WL_CONNECTED
&& !_ntp_refresh_pending
&& mqttNtpRefreshDue(ntp_now, _last_ntp_sync,
_ntp_refresh_retry_at)) {
refreshNTP();
}
@@ -4037,12 +4097,96 @@ void MQTTBridge::storeRawRadioData(const uint8_t* raw_data, int len, float snr,
// ---------------------------------------------------------------------------
void MQTTBridge::refreshNTP() {
// Lightweight periodic refresh: just restart SNTP which runs async in the background.
// No blocking DNS, no UDP sockets, no retry loops on the MQTT task loop.
// The heavy syncTimeWithNTP() is only used for initial sync and WiFi reconnect recovery.
const uint32_t now = millis();
if (_ntp_refresh_pending) return;
// Both task-loop variants call this through mqttNtpRefreshDue(), but keep the
// deadline check here as well so a future direct caller cannot spin on the
// process-wide SNTP lease.
if (_ntp_refresh_retry_at != 0
&& !mqttNtpRefreshDue(now, _last_ntp_sync,
_ntp_refresh_retry_at)) {
return;
}
#ifdef ESP_PLATFORM
mesh::sntp_coord::OperationLease sntp_operation(
mesh::sntp_coord::processWideCoordinator());
if (!sntp_operation.tryAcquire()) {
_ntp_refresh_retry_at = mqttNtpRetryAt(now);
MQTT_DEBUG_PRINTLN(
"NTP refresh deferred; another firmware service owns SNTP");
return;
}
#endif
// Restart SNTP and let it run asynchronously. Resetting the status makes the
// later COMPLETED state proof of this request rather than an earlier boot
// sync. Do not advance _last_ntp_sync yet: an attempted configTime() is not a
// successful refresh, and MeshCore consumers read _rtc rather than time().
#ifdef ESP_PLATFORM
sntp_set_sync_status(SNTP_SYNC_STATUS_RESET);
#endif
configTime(0, 0, effectiveNtpPrimary(_obs));
_last_ntp_sync = millis();
MQTT_DEBUG_PRINTLN("NTP refresh triggered (async SNTP)");
_ntp_refresh_retry_at = 0;
_ntp_refresh_started_at = millis();
_ntp_refresh_pending = true;
MQTT_DEBUG_PRINTLN("NTP refresh requested (async SNTP)");
}
void MQTTBridge::pollNtpRefresh(uint32_t now) {
if (!_ntp_refresh_pending) return;
const uint32_t elapsed = now - _ntp_refresh_started_at;
if (WiFi.status() != WL_CONNECTED) {
_ntp_refresh_pending = false;
_ntp_refresh_retry_at = mqttNtpRetryAt(now);
MQTT_DEBUG_PRINTLN("NTP refresh aborted; WiFi disconnected");
return;
}
#ifdef ESP_PLATFORM
const bool completed =
sntp_get_sync_status() == SNTP_SYNC_STATUS_COMPLETED;
#else
// Other Arduino WiFi stacks do not expose ESP-IDF's completion status. Keep
// their historical asynchronous configTime() behavior, but wait before
// pulling the system clock into the MeshCore RTC.
const bool completed = elapsed >= MQTT_NTP_NON_ESP_SETTLE_MS;
#endif
if (completed) {
const time_t raw_system_time = time(nullptr);
uint32_t system_time = 0;
if (MQTTConnectionPolicy::checkedRtcEpoch(
static_cast<int64_t>(raw_system_time),
MQTT_NTP_MIN_VALID_EPOCH, system_time)) {
if (_rtc) _rtc->setCurrentTime(system_time);
_ntp_synced.store(true, std::memory_order_release);
_last_ntp_sync = now;
_ntp_refresh_retry_at = 0;
_ntp_refresh_pending = false;
MQTT_DEBUG_PRINTLN(
"NTP refresh completed; MeshCore RTC updated: %lu", system_time);
return;
}
// A completion carrying an implausible time cannot become authoritative.
// The ESP status is edge-like and may reset after it is read, so retry the
// whole operation instead of waiting on a completion that was consumed.
_ntp_refresh_pending = false;
_ntp_refresh_retry_at = mqttNtpRetryAt(now);
MQTT_DEBUG_PRINTLN(
"NTP refresh returned implausible time %lld; retry scheduled",
(long long)raw_system_time);
return;
}
if (elapsed >= MQTT_NTP_REFRESH_TIMEOUT_MS) {
_ntp_refresh_pending = false;
_ntp_refresh_retry_at = mqttNtpRetryAt(now);
MQTT_DEBUG_PRINTLN("NTP refresh timed out; retry scheduled");
}
}
bool MQTTBridge::syncTimeWithNTP(bool force, bool primary_only) {
@@ -4052,7 +4196,8 @@ bool MQTTBridge::syncTimeWithNTP(bool force, bool primary_only) {
}
unsigned long now = millis();
if (!force && _ntp_synced && (now - _last_ntp_sync) < 5000) {
if (!force && _ntp_synced.load(std::memory_order_acquire)
&& (now - _last_ntp_sync) < 5000) {
return false;
}
@@ -4077,8 +4222,9 @@ bool MQTTBridge::syncTimeWithNTP(bool force, bool primary_only) {
bool ntp_ok = false;
unsigned long epochTime = 0;
const unsigned long kMinValidEpoch = 1767225600; // 2026-01-01 00:00:00 UTC
const unsigned long kMinValidEpoch = MQTT_NTP_MIN_VALID_EPOCH;
const char* ntp_server_used = nullptr;
bool sntp_fallback_configured = false;
_ntp_client.begin();
const int kMaxNtpRetriesPerServer = 2;
@@ -4121,6 +4267,13 @@ bool MQTTBridge::syncTimeWithNTP(bool force, bool primary_only) {
for (int s = 0; s < server_count && !ntp_ok; s++) {
const char* server = servers[s];
MQTT_DEBUG_PRINTLN("SNTP fallback trying %s...", server);
mesh::sntp_coord::OperationLease sntp_operation(
mesh::sntp_coord::processWideCoordinator());
if (!sntp_operation.tryAcquire()) {
MQTT_DEBUG_PRINTLN(
"SNTP fallback deferred; another firmware service owns SNTP");
break;
}
// configTime() already stops and reconfigures an active SNTP client on
// both Arduino-ESP32 2.x and 3.x. Avoid the legacy unprefixed stop APIs,
// which are no longer exported by esp_sntp.h in Arduino 3.x.
@@ -4129,15 +4282,20 @@ bool MQTTBridge::syncTimeWithNTP(bool force, bool primary_only) {
for (int i = 0; i < 20; i++) {
delay(500);
if (sntp_get_sync_status() != SNTP_SYNC_STATUS_COMPLETED) continue;
epochTime = (unsigned long)time(nullptr);
if (epochTime >= kMinValidEpoch) {
const time_t raw_system_time = time(nullptr);
uint32_t checked_system_time = 0;
if (MQTTConnectionPolicy::checkedRtcEpoch(
static_cast<int64_t>(raw_system_time), kMinValidEpoch,
checked_system_time)) {
epochTime = checked_system_time;
ntp_ok = true;
ntp_server_used = server;
sntp_fallback_configured = true;
MQTT_DEBUG_PRINTLN("SNTP fallback succeeded on %s: %lu", server, epochTime);
} else {
MQTT_DEBUG_PRINTLN(
"SNTP fallback: %s synced an implausible epoch %lu", server,
epochTime);
"SNTP fallback: %s synced an implausible epoch %lld", server,
(long long)raw_system_time);
}
break;
}
@@ -4146,7 +4304,9 @@ bool MQTTBridge::syncTimeWithNTP(bool force, bool primary_only) {
#endif
if (!ntp_ok) {
const unsigned long system_time = (unsigned long)time(nullptr);
uint32_t system_time = 0;
MQTTConnectionPolicy::checkedRtcEpoch(
static_cast<int64_t>(time(nullptr)), kMinValidEpoch, system_time);
const unsigned long rtc_time =
_rtc ? (unsigned long)_rtc->getCurrentTime() : 0;
const MQTTConnectionPolicy::ClockSource source =
@@ -4171,14 +4331,36 @@ bool MQTTBridge::syncTimeWithNTP(bool force, bool primary_only) {
accepted.tv_usec = 0;
settimeofday(&accepted, nullptr);
if (ntp_server_used) configTime(0, 0, ntp_server_used);
if (ntp_server_used && !sntp_fallback_configured) {
// A direct NTPClient response has already made the clock authoritative.
// Re-arm background SNTP without letting this asynchronous convenience
// race a callback-owning firmware service. Failure here does not discard
// the fresh direct response; the task loop retries the re-arm shortly.
mesh::sntp_coord::OperationLease sntp_operation(
mesh::sntp_coord::processWideCoordinator());
if (sntp_operation.tryAcquire()) {
configTime(0, 0, ntp_server_used);
_ntp_refresh_retry_at = 0;
} else {
_ntp_refresh_retry_at = mqttNtpRetryAt(millis());
MQTT_DEBUG_PRINTLN(
"Background SNTP re-arm deferred; another firmware service owns SNTP");
}
} else if (sntp_fallback_configured) {
// The successful fallback's configTime() remains the active async client.
_ntp_refresh_retry_at = 0;
}
if (_rtc) {
_rtc->setCurrentTime(epochTime);
}
bool was_ntp_synced = _ntp_synced;
_ntp_synced = true;
bool was_ntp_synced = _ntp_synced.load(std::memory_order_acquire);
_ntp_synced.store(true, std::memory_order_release);
// A blocking/direct sync already copied its accepted epoch into _rtc, so
// it supersedes any older asynchronous periodic request.
_ntp_refresh_pending = false;
_ntp_refresh_started_at = 0;
_last_ntp_sync = millis();
sync_in_progress = false;
@@ -4361,20 +4543,22 @@ bool MQTTBridge::ntpDiag(char* reply, size_t reply_size, bool verbose) {
if (_ntp_diag_results[i].ok) ok_count++;
}
if (verbose) {
if (verbose && mesh::isUsbLoggingEnabled()) {
// Detailed table to the serial console; reply carries a short summary (the operator
// sees the table above the "-> <reply>" line). Mirrors the dumpLogFile() convention.
Serial.printf("NTP diag - %d server(s):\r\n", _ntp_diag_count);
Stream& output = mesh::usbLoggingPort();
output.printf("NTP diag - %d server(s):\r\n", _ntp_diag_count);
for (int i = 0; i < _ntp_diag_count; i++) {
const NtpDiagResult& r = _ntp_diag_results[i];
if (r.ok) {
time_t t = (time_t)r.epoch;
struct tm* tmv = gmtime(&t);
Serial.printf(" %-20s OK %04d-%02d-%02d %02d:%02d:%02d UTC\r\n",
r.server, tmv->tm_year + 1900, tmv->tm_mon + 1, tmv->tm_mday,
tmv->tm_hour, tmv->tm_min, tmv->tm_sec);
output.printf(
" %-20s OK %04d-%02d-%02d %02d:%02d:%02d UTC\r\n",
r.server, tmv->tm_year + 1900, tmv->tm_mon + 1,
tmv->tm_mday, tmv->tm_hour, tmv->tm_min, tmv->tm_sec);
} else {
Serial.printf(" %-20s FAIL\r\n", r.server);
output.printf(" %-20s FAIL\r\n", r.server);
}
}
snprintf(reply, reply_size, "> NTP diag: %d/%d OK (see console)", ok_count, _ntp_diag_count);
+20 -9
View File
@@ -10,6 +10,7 @@
#include <WiFiUdp.h>
#include <Timezone.h>
#include "helpers/JWTHelper.h"
#include "helpers/MQTTConnectionPolicy.h"
#include "helpers/MQTTPacketFilter.h"
#include "helpers/MQTTPresets.h"
#include "helpers/MQTTLifecycle.h"
@@ -221,8 +222,12 @@ private:
WiFiUDP _ntp_udp;
NTPClient _ntp_client;
unsigned long _last_ntp_sync;
volatile bool _ntp_synced;
bool _ntp_sync_pending; // Flag to trigger NTP sync from loop() instead of event handler
unsigned long _ntp_refresh_retry_at;
unsigned long _ntp_refresh_started_at;
bool _ntp_refresh_pending;
std::atomic<bool> _ntp_synced;
bool _ntp_sync_pending; // Owned by the MQTT task; the WiFi callback only records a GOT_IP edge
MQTTConnectionPolicy::NtpReconnectLatch _ntp_reconnect_latch;
bool _slots_setup_done; // Deferred: slots set up after NTP sync
// WiFi.onEvent() handler registered once and never removed by end(); the bridge
// object is reused across restarts, so re-registering would leak handlers and
@@ -507,7 +512,8 @@ private:
void queuePacket(mesh::Packet* packet, bool is_tx);
void dequeuePacket();
bool isAnySlotConnected();
void refreshNTP(); // Lightweight periodic NTP refresh (non-blocking)
void refreshNTP(); // Start a lightweight daily/reconnect NTP refresh (non-blocking)
void pollNtpRefresh(uint32_t now); // Copy a completed async refresh into MeshCore's RTC
void runNtpDiagProbe(); // Probe every server for connectivity; never sets the clock. Core 0 only.
void runNtpEstimateProbe(); // Query the first usable server without changing any clock. Core 0 only.
// Populates dst_out/std_out with TimeChangeRules for the given IANA or
@@ -700,10 +706,12 @@ public:
* Performs blocking NTP I/O and must only be called from the MQTT task (Core 0).
* Other tasks (e.g. the CLI on Core 1) must use requestForcedNtpSync() instead. */
bool syncTimeWithNTP(bool force = false, bool primary_only = false);
/** Request a forced NTP sync from another task (e.g. CLI on Core 1). Marshals the
* work onto the MQTT task so all NTP I/O stays on Core 0, then blocks up to
* timeout_ms for the result. Returns true if the sync succeeded, false on failure,
* timeout, or if the bridge is not running. */
/** Request a forced clock refresh from another task (e.g. CLI on Core 1).
* Marshals NTP I/O onto the MQTT task, then blocks up to timeout_ms for the
* result. This validation request tests only the configured primary server
* and never accepts a retained RTC/system clock as success, so a true result
* from a nonzero-timeout call proves a fresh NTP response. A zero timeout is
* fire-and-forget and proves only that the request was queued. */
bool requestForcedNtpSync(uint32_t timeout_ms = 30000);
/** Probe every configured NTP server (custom primary + built-in fallbacks) for
* connectivity and report each server's reported time WITHOUT touching the system
@@ -716,8 +724,11 @@ public:
bool requestNtpTimeEstimate();
/** Poll/consume the queued estimate. finished=false means it is still pending. */
bool takeNtpTimeEstimate(uint32_t& epoch, bool& finished);
/** True after this bridge has successfully set the RTC from NTP this boot. */
bool hasNtpTime() const { return _ntp_synced; }
/** True after the bridge established a usable clock this boot. This may be a
* plausible retained RTC/system clock accepted after NTP was unavailable. */
bool hasNtpTime() const {
return _ntp_synced.load(std::memory_order_acquire);
}
static void formatMqttStatusReply(char* buf, size_t bufsize, const MQTTPrefs* obs);
/** On-demand publish-health + heap snapshot for `get mqtt.stats` (per-slot ok/err,
* outbox size, free/max heap, queue depth). */
@@ -0,0 +1,102 @@
#pragma once
#include <atomic>
#include <stdint.h>
namespace mesh {
namespace sntp_coord {
using CleanupHook = void (*)();
// ESP-IDF exposes one process-wide SNTP client and one notification callback.
// Keep callback installation/configTime() sequences mutually exclusive across
// otherwise independent firmware features. Acquisition is deliberately
// non-blocking: a caller can retry through its own bounded policy instead of
// deadlocking behind a failed network operation.
class OperationCoordinator {
public:
OperationCoordinator() : owner_(0), next_generation_(1) {}
bool owns(uint32_t generation) const {
return generation != 0
&& owner_.load(std::memory_order_acquire) == generation;
}
private:
friend class OperationLease;
bool tryAcquire(uint32_t& generation) {
if (generation != 0) return false;
uint32_t candidate = 0;
do {
candidate = next_generation_.fetch_add(1, std::memory_order_relaxed);
} while (candidate == 0);
uint32_t expected = 0;
if (!owner_.compare_exchange_strong(
expected, candidate, std::memory_order_acq_rel,
std::memory_order_acquire)) {
return false;
}
generation = candidate;
return true;
}
bool release(uint32_t generation, CleanupHook cleanup) {
// Run the callback cleanup before publishing the coordinator as free. This
// prevents a new owner from installing its callback and then having a stale
// owner's teardown clear it. Only OperationLease can release a generation.
if (!owns(generation)) return false;
if (cleanup != nullptr) cleanup();
uint32_t expected = generation;
return owner_.compare_exchange_strong(
expected, 0, std::memory_order_acq_rel, std::memory_order_acquire);
}
std::atomic<uint32_t> owner_;
std::atomic<uint32_t> next_generation_;
};
class OperationLease {
public:
explicit OperationLease(OperationCoordinator& coordinator,
CleanupHook cleanup = nullptr)
: coordinator_(coordinator), cleanup_(cleanup), generation_(0) {}
~OperationLease() { release(); }
bool tryAcquire() { return coordinator_.tryAcquire(generation_); }
bool owns() const { return coordinator_.owns(generation_); }
uint32_t generation() const { return generation_; }
bool release() {
if (generation_ == 0) return false;
const uint32_t releasing = generation_;
// Make repeated release attempts inert even if cleanup code indirectly
// observes this lease.
generation_ = 0;
return coordinator_.release(releasing, cleanup_);
}
OperationLease(const OperationLease&) = delete;
OperationLease& operator=(const OperationLease&) = delete;
private:
OperationCoordinator& coordinator_;
CleanupHook cleanup_;
uint32_t generation_;
};
// A function-local static in an external-linkage inline function denotes one
// object program-wide under the C++ ODR, including the Arduino-ESP32 2.x C++11
// toolchain. Both the font repair and pull-OTA paths use this exact instance.
inline OperationCoordinator& processWideCoordinator() {
static OperationCoordinator coordinator;
return coordinator;
}
} // namespace sntp_coord
} // namespace mesh
+46
View File
@@ -0,0 +1,46 @@
#pragma once
#include <stdint.h>
#include <time.h>
namespace mesh {
namespace tls_clock {
// A certificate-validating TLS handshake must not treat an uninitialised or
// wrapped wall clock as usable. The fresh-proof bit is deliberately supplied by
// caller: a plausible retained RTC alone is not evidence that NTP answered in
// the operation which is about to download trusted content.
static constexpr time_t kMinimumValidEpoch = (time_t)1767225600; // 2026-01-01 UTC
constexpr bool timeIsValid(time_t now) {
return now >= kMinimumValidEpoch;
}
constexpr bool proofIsValid(bool fresh_proof, bool wifi_connected,
time_t now) {
return fresh_proof && wifi_connected && timeIsValid(now);
}
// `now - proven_at` is the standard modulo-uint32_t elapsed-time calculation,
// so a proof remains valid across the one millis() rollover that a bounded
// operation can cross. Callers must reset the fresh-proof/generation state
// before every operation and must not retain a proof for a complete 2^32-ms
// cycle, where a 32-bit elapsed clock necessarily becomes ambiguous.
constexpr bool proofAgeIsValid(bool fresh_proof, uint32_t now,
uint32_t proven_at,
uint32_t maximum_age_millis) {
return fresh_proof && now - proven_at <= maximum_age_millis;
}
// A callback can already be in flight when its owner unregisters it. Binding
// the proof to the lease generation makes such a late callback fail closed if
// a later operation of the same feature has already started.
constexpr bool proofGenerationIsValid(bool fresh_proof,
uint32_t proof_generation,
uint32_t expected_generation) {
return fresh_proof && expected_generation != 0
&& proof_generation == expected_generation;
}
} // namespace tls_clock
} // namespace mesh
+93 -49
View File
@@ -26,6 +26,7 @@
#include "WebConfigHtml.h"
#include "helpers/CLICommandUtils.h"
#include "helpers/UsbLogging.h"
#include "helpers/WebConfigKeys.h"
#include "helpers/WiFiPowerSave.h"
#include "helpers/esp32/WiFiRadioPolicy.h"
@@ -389,8 +390,11 @@ WebConfigServer::~WebConfigServer() {
bool WebConfigServer::loadEnabled(bool default_value) {
Preferences nvs;
if (!nvs.begin("mesh-webui", true)) return default_value;
bool enabled = nvs.getBool("enabled", default_value);
// A missing namespace is the normal erased-device state. Read-write creates
// it once instead of making Arduino Preferences log NOT_FOUND to Serial.
if (!nvs.begin("mesh-webui", false)) return default_value;
bool enabled = nvs.isKey("enabled")
? nvs.getBool("enabled", default_value) : default_value;
nvs.end();
return enabled;
}
@@ -405,8 +409,9 @@ bool WebConfigServer::saveEnabled(bool enabled) {
bool WebConfigServer::loadCliEnabled(bool default_value) {
Preferences nvs;
if (!nvs.begin("mesh-webui", true)) return default_value;
bool enabled = nvs.getBool("cli", default_value);
if (!nvs.begin("mesh-webui", false)) return default_value;
bool enabled = nvs.isKey("cli")
? nvs.getBool("cli", default_value) : default_value;
nvs.end();
return enabled;
}
@@ -426,11 +431,16 @@ bool WebConfigServer::loadStandaloneWiFi(char* ssid, size_t ssid_len,
ssid[0] = 0;
password[0] = 0;
Preferences nvs;
if (!nvs.begin("mesh-wifi", true)) return false;
String stored_ssid = nvs.getString("ssid", "");
String stored_password = nvs.getString("password", "");
uint8_t stored_ps = nvs.getUChar(
"powersave", mesh::wifi::kDefaultPowerSave);
if (!nvs.begin("mesh-wifi", false)) return false;
// Preferences::getString() logs an error for a missing key even when the
// caller supplied a default. Missing credentials are expected on first boot.
String stored_ssid = nvs.isKey("ssid")
? nvs.getString("ssid", "") : String();
String stored_password = nvs.isKey("password")
? nvs.getString("password", "") : String();
uint8_t stored_ps = nvs.isKey("powersave")
? nvs.getUChar("powersave", mesh::wifi::kDefaultPowerSave)
: mesh::wifi::kDefaultPowerSave;
nvs.end();
if (stored_ssid.length() >= ssid_len
|| stored_password.length() >= password_len
@@ -779,12 +789,13 @@ bool WebConfigServer::startSetupMode(char reply[]) {
const esp_err_t sta_protocol_result = esp_wifi_set_protocol(
WIFI_IF_STA, mesh::wifi::kProtocolMask);
if (ap_protocol_result == ESP_OK && sta_protocol_result == ESP_OK) break;
Serial.printf("WebConfig protocol reset failed: AP=%d STA=%d\n",
(int)ap_protocol_result, (int)sta_protocol_result);
mesh::usbLoggingPort().printf(
"WebConfig protocol reset failed: AP=%d STA=%d\n",
(int)ap_protocol_result, (int)sta_protocol_result);
ap_ok = false;
}
Serial.printf(
mesh::usbLoggingPort().printf(
"WebConfig AP attempt %u failed: mode_ok=%d disconnect_ok=%d mode=%d heap=%u largest=%u\n",
(unsigned)attempt, mode_ok, disconnect_ok, (int)WiFi.getMode(),
(unsigned)ESP.getFreeHeap(),
@@ -969,8 +980,9 @@ void WebConfigServer::tick(uint32_t now) {
break;
case WebConfigBatch::StopAction::Warn:
_stop_warned = true;
Serial.printf("WC: stop waiting for %lu handler(s); retaining session safely\n",
(unsigned long)refs);
mesh::usbLoggingPort().printf(
"WC: stop waiting for %lu handler(s); retaining session safely\n",
(unsigned long)refs);
break;
case WebConfigBatch::StopAction::Wait:
break;
@@ -993,9 +1005,12 @@ void WebConfigServer::tick(uint32_t now) {
createServer();
_connect_deadline = 0;
_last_activity = now;
Serial.printf("WebConfig ready: http://%s/\n", WiFi.localIP().toString().c_str());
mesh::usbLoggingPort().printf(
"WebConfig ready: http://%s/\n",
WiFi.localIP().toString().c_str());
} else if (_connect_deadline && (int32_t)(now - _connect_deadline) >= 0) {
Serial.printf("WebConfig: WiFi '%s' unavailable; opening setup AP\n", _wifi_ssid);
mesh::usbLoggingPort().printf(
"WebConfig: WiFi '%s' unavailable; opening setup AP\n", _wifi_ssid);
const bool retry_saved_wifi = _wifi_ssid[0] != 0;
// Keep the WiFi driver running while changing from STA to AP+STA.
// Powering it off here and starting an AP immediately can race the
@@ -1008,7 +1023,7 @@ void WebConfigServer::tick(uint32_t now) {
if (startSetupMode(ignored)) {
_retry_saved_wifi_in_setup = retry_saved_wifi;
}
Serial.println(ignored);
mesh::usbLoggingPort().println(ignored);
}
return;
}
@@ -1024,8 +1039,9 @@ void WebConfigServer::tick(uint32_t now) {
_wifi_reconnect_tracker.noteDisconnected(now);
if (_wifi_reconnect_tracker.retryDue(now)) {
_wifi_reconnect_tracker.noteAttempt(now);
Serial.printf("WebConfig: WiFi still unavailable; retrying '%s'\n",
_wifi_ssid);
mesh::usbLoggingPort().printf(
"WebConfig: WiFi still unavailable; retrying '%s'\n",
_wifi_ssid);
WiFi.mode(WIFI_STA);
mesh::wifi::setStationAutoReconnect(true);
WiFi.disconnect(false, false);
@@ -1061,20 +1077,23 @@ void WebConfigServer::tick(uint32_t now) {
_wifi_reconnect_tracker.noteConnected();
_mode = MODE_LAN;
_last_activity = now;
Serial.printf("WebConfig: saved WiFi recovered; ready at http://%s/\n",
WiFi.localIP().toString().c_str());
mesh::usbLoggingPort().printf(
"WebConfig: saved WiFi recovered; ready at http://%s/\n",
WiFi.localIP().toString().c_str());
} else if (_owns_wifi && _setup_reconnect_in_progress
&& (int32_t)(now - _setup_reconnect_deadline) >= 0) {
WiFi.disconnect(false, false);
_setup_reconnect_in_progress = false;
_setup_reconnect_deadline = 0;
Serial.println("WebConfig: saved WiFi still unavailable; setup AP remains active");
mesh::usbLoggingPort().println(
"WebConfig: saved WiFi still unavailable; setup AP remains active");
} else if (_owns_wifi && !_setup_reconnect_in_progress
&& _wifi_reconnect_tracker.retryDue(now)) {
_wifi_reconnect_tracker.noteAttempt(now);
_setup_reconnect_in_progress = true;
_setup_reconnect_deadline = now + 20000UL;
Serial.printf("WebConfig: retrying saved WiFi '%s'\n", _wifi_ssid);
mesh::usbLoggingPort().printf(
"WebConfig: retrying saved WiFi '%s'\n", _wifi_ssid);
mesh::wifi::beginStation(_wifi_ssid, _wifi_password);
}
}
@@ -1087,15 +1106,18 @@ void WebConfigServer::tick(uint32_t now) {
}
if (WebConfigBatch::rebootDue(_reboot_at, now)) {
Serial.printf("WC: rebooting now (%s)\n", _batch_reboot_armed ? "confirmed" : "fallback");
mesh::usbLoggingPort().printf(
"WC: rebooting now (%s)\n",
_batch_reboot_armed ? "confirmed" : "fallback");
_cb->rebootNow(); // does not return
}
if ((int32_t)(_diag_until - now) > 0 && (now - _diag_last) >= 1000) {
_diag_last = now;
Serial.printf("WC: diag sta=%d heap=%u batch=%d/%d state=%d\n",
(int)WiFi.softAPgetStationNum(), (unsigned)ESP.getFreeHeap(),
(int)_batch_next, (int)_batch_count, (int)_batch_state);
mesh::usbLoggingPort().printf(
"WC: diag sta=%d heap=%u batch=%d/%d state=%d\n",
(int)WiFi.softAPgetStationNum(), (unsigned)ESP.getFreeHeap(),
(int)_batch_next, (int)_batch_count, (int)_batch_state);
}
// Refresh the stats snapshot only while a client is actually polling.
@@ -1113,7 +1135,7 @@ void WebConfigServer::tick(uint32_t now) {
_mode == MODE_SETUP, _wifi_ssid[0] != 0, now,
_setup_started_at,
(uint32_t)WEBCONFIG_UNCONFIGURED_SETUP_TIMEOUT_MS)) {
Serial.printf(
mesh::usbLoggingPort().printf(
"WebConfig: WiFi still unconfigured after %lu minutes; powering off until reboot or explicit restart\n",
(unsigned long)((uint32_t)WEBCONFIG_UNCONFIGURED_SETUP_TIMEOUT_MS / 60000UL));
requestStop();
@@ -1144,7 +1166,8 @@ void WebConfigServer::tick(uint32_t now) {
_setup_reconnect_deadline = 0;
_mode = MODE_LAN;
_last_activity = now;
Serial.println("WebConfig: setup AP idle; saved WiFi recovery continues");
mesh::usbLoggingPort().println(
"WebConfig: setup AP idle; saved WiFi recovery continues");
} else {
requestStop();
}
@@ -1179,8 +1202,9 @@ void WebConfigServer::serviceSetupWiFiHandoff(uint32_t now) {
_setup_wifi_handoff_pending = false;
_setup_wifi_handoff_deadline = 0;
}
Serial.printf("WebConfig: joined '%s' at %s; waiting for browser handoff\n",
_wifi_ssid, ip);
mesh::usbLoggingPort().printf(
"WebConfig: joined '%s' at %s; waiting for browser handoff\n",
_wifi_ssid, ip);
finishBatch(now);
return;
}
@@ -1207,8 +1231,9 @@ void WebConfigServer::serviceSetupWiFiHandoff(uint32_t now) {
_setup_wifi_handoff_deadline = 0;
_setup_wifi_handoff_ip[0] = 0;
}
Serial.printf("WebConfig: could not join '%s'; setup AP remains active\n",
_wifi_ssid);
mesh::usbLoggingPort().printf(
"WebConfig: could not join '%s'; setup AP remains active\n",
_wifi_ssid);
finishBatch(now);
}
@@ -1314,11 +1339,14 @@ void WebConfigServer::drainBatch(uint32_t now) {
// `set wifi.pwd` or `password` from the terminal must not reach the serial
// log, which is a different audience from the browser session.
if (_batch_kind == BATCH_CLI) {
Serial.printf("WC: cli %d/%d took %lums\n", (int)_batch_next, (int)_batch_count,
(unsigned long)(_batch_last_cmd - t0));
mesh::usbLoggingPort().printf(
"WC: cli %d/%d took %lums\n", (int)_batch_next,
(int)_batch_count, (unsigned long)(_batch_last_cmd - t0));
} else {
Serial.printf("WC: cmd %d/%d '%s' took %lums\n", (int)_batch_next, (int)_batch_count,
e.key, (unsigned long)(_batch_last_cmd - t0));
mesh::usbLoggingPort().printf(
"WC: cmd %d/%d '%s' took %lums\n", (int)_batch_next,
(int)_batch_count, e.key,
(unsigned long)(_batch_last_cmd - t0));
}
if (!WebConfigBatch::drainFinished(_batch_next, _batch_count)) {
return; // more commands next tick
@@ -1368,8 +1396,8 @@ void WebConfigServer::drainBatch(uint32_t now) {
// that will be shown to the operator before the setup AP is shut down.
WiFi.mode(WIFI_AP_STA);
WiFi.setAutoReconnect(false);
Serial.printf("WebConfig: testing saved WiFi '%s' before reboot\n",
_wifi_ssid);
mesh::usbLoggingPort().printf(
"WebConfig: testing saved WiFi '%s' before reboot\n", _wifi_ssid);
mesh::wifi::beginStation(_wifi_ssid, _wifi_password);
return;
}
@@ -1384,7 +1412,8 @@ void WebConfigServer::drainBatch(uint32_t now) {
// Distinguishes "client stopped sending" from "server stopped accepting" when
// a save's confirmation polls go missing on hardware.
static void wcLogReq(AsyncWebServerRequest* r) {
Serial.printf("WC: http %s %s\n", r->methodToString(), r->url().c_str());
mesh::usbLoggingPort().printf(
"WC: http %s %s\n", r->methodToString(), r->url().c_str());
}
void WebConfigServer::attachRoutes() {
@@ -1943,7 +1972,9 @@ void WebConfigServer::handleConfigPost(AsyncWebServerRequest* req) {
uint32_t du = millis() + 60000;
if (du == 0) du = 1;
_diag_until = du;
Serial.printf("WC: config POST accepted, %d cmds, reboot=%d\n", count, (int)reboot_after);
mesh::usbLoggingPort().printf(
"WC: config POST accepted, %d cmds, reboot=%d\n",
count, (int)reboot_after);
StaticJsonDocument<96> ack;
ack["state"] = "pending";
@@ -1955,8 +1986,16 @@ void WebConfigServer::handleConfigPost(AsyncWebServerRequest* req) {
}
void WebConfigServer::handleConfigResult(AsyncWebServerRequest* req) {
if (_mode == MODE_OFF) { Serial.println("WC: result read -> 503 (mode off)"); req->send(503); return; }
if (!checkAuth(req)) { Serial.println("WC: result read -> 401"); req->send(401, "application/json", "{\"error\":\"auth\"}"); return; }
if (_mode == MODE_OFF) {
mesh::usbLoggingPort().println("WC: result read -> 503 (mode off)");
req->send(503);
return;
}
if (!checkAuth(req)) {
mesh::usbLoggingPort().println("WC: result read -> 401");
req->send(401, "application/json", "{\"error\":\"auth\"}");
return;
}
if (!req->hasParam("reqid")) {
req->send(400, "application/json", "{\"error\":\"bad reqid\"}");
return;
@@ -1969,7 +2008,9 @@ void WebConfigServer::handleConfigResult(AsyncWebServerRequest* req) {
// Entry print BEFORE the lock (racy state read is fine for diag): if this
// fires but no branch print follows, the handler is blocked on _mux.
Serial.printf("WC: result entry mode=%d state=%d\n", (int)_mode, (int)_batch_state);
mesh::usbLoggingPort().printf(
"WC: result entry mode=%d state=%d\n",
(int)_mode, (int)_batch_state);
WCLock lock(_mux);
// A CLI sequence occupying the shared slot is not a config save, whatever the
// reqid says: its entries have no `key` and its results belong to the
@@ -1979,7 +2020,7 @@ void WebConfigServer::handleConfigResult(AsyncWebServerRequest* req) {
const WebConfigBatch::ResultOutcome outcome =
WebConfigBatch::classifyResult(toSpecState(_batch_state), mine);
if (outcome == WebConfigBatch::ResultOutcome::Idle) {
Serial.println("WC: result read -> idle");
mesh::usbLoggingPort().println("WC: result read -> idle");
StaticJsonDocument<64> idle;
idle["state"] = "idle";
idle["reqid"] = requested_reqid;
@@ -2001,9 +2042,10 @@ void WebConfigServer::handleConfigResult(AsyncWebServerRequest* req) {
req->send(200, "application/json", out);
return;
}
Serial.printf("WC: result read -> done (reboot=%d armed=%d all_ok=%d)\n",
(int)_batch_reboot, (int)_batch_reboot_armed,
(int)_batch_all_ok);
mesh::usbLoggingPort().printf(
"WC: result read -> done (reboot=%d armed=%d all_ok=%d)\n",
(int)_batch_reboot, (int)_batch_reboot_armed,
(int)_batch_all_ok);
DynamicJsonDocument doc(6144);
doc["state"] = "done";
doc["reboot"] =
@@ -2206,7 +2248,9 @@ void WebConfigServer::handleCliPost(AsyncWebServerRequest* req) {
strncpy(_batch_reqid, reqid, sizeof(_batch_reqid) - 1);
_batch_reqid[sizeof(_batch_reqid) - 1] = 0;
_batch_state = BATCH_PENDING; // tick() picks it up on the loop task
Serial.printf("WC: cli POST accepted, %d cmds, reboot=%d\n", count, (int)defer_reboot);
mesh::usbLoggingPort().printf(
"WC: cli POST accepted, %d cmds, reboot=%d\n",
count, (int)defer_reboot);
StaticJsonDocument<96> ack;
ack["state"] = "running";
+10 -5
View File
@@ -8,6 +8,7 @@
#include <helpers/WiFiOtaSeederPolicy.h>
#include <helpers/WiFiOtaSeederStatus.h>
#include <helpers/UsbLogging.h>
#include <helpers/ota/FolderMotaStore.h>
#include <helpers/ota/MotaSourceSerial.h>
#include <helpers/ota/OtaContext.h>
@@ -60,8 +61,9 @@ void WiFiOtaSeeder::loop() {
case ListenerAction::Start:
seeder_server.begin();
listener_active = true;
Serial.printf("OTA seeder listening on :%u (motatool serve --tcp)\n",
static_cast<unsigned>(OTA_SEEDER_TCP_PORT));
mesh::usbLoggingPort().printf(
"OTA seeder listening on :%u (motatool serve --tcp)\n",
static_cast<unsigned>(OTA_SEEDER_TCP_PORT));
break;
case ListenerAction::Stop:
stop();
@@ -90,7 +92,8 @@ void WiFiOtaSeeder::loop() {
if (!WiFiOtaSeederPolicy::canAttachTcpFolder(context.folder_active,
tcp_folder_attached)) {
incoming.stop();
Serial.println("OTA seeder rejected TCP client: another folder link is active");
mesh::usbLoggingPort().println(
"OTA seeder rejected TCP client: another folder link is active");
return;
}
@@ -99,7 +102,8 @@ void WiFiOtaSeeder::loop() {
if (!context.attach_folder_source(&seeder_source, OtaContext::FOLDER_LINK_TCP,
"tcp", attach_reply, sizeof(attach_reply))) {
seeder_client.stop();
Serial.printf("OTA seeder rejected TCP client: %s\n", attach_reply);
mesh::usbLoggingPort().printf(
"OTA seeder rejected TCP client: %s\n", attach_reply);
return;
}
@@ -114,7 +118,8 @@ void WiFiOtaSeeder::loop() {
context.manager.resumeStaged(context.manager.fetchManifestId());
}
context.manager.announce();
Serial.printf("OTA seeder client connected (%s)\n", link_info);
mesh::usbLoggingPort().printf(
"OTA seeder client connected (%s)\n", link_info);
}
void WiFiOtaSeeder::stop() {
+6 -2
View File
@@ -54,8 +54,12 @@ struct EspNowBootChannelState {
inline uint8_t loadConfiguredEspNowChannel() {
uint8_t channel = kDefaultEspNowChannel;
Preferences prefs;
if (prefs.begin("mesh-wifi", true)) {
channel = prefs.getUChar("espnow_ch", kDefaultEspNowChannel);
// A missing namespace is the normal first-boot state. Read-write creates it
// without Arduino Preferences emitting ESP_ERR_NVS_NOT_FOUND on Serial.
if (prefs.begin("mesh-wifi", false)) {
if (prefs.isKey("espnow_ch")) {
channel = prefs.getUChar("espnow_ch", kDefaultEspNowChannel);
}
prefs.end();
}
return validEspNowChannelOrDefault(channel, kDefaultEspNowChannel);
+3 -1
View File
@@ -133,7 +133,9 @@ bool ota_installed_bootloader_identity(OtaBootloaderIdentity& out);
inline uint8_t ota_nrf52_boot_result_or_zero(uint8_t value) {
return ((value >= 0x90u && value <= 0x9Fu) ||
(value >= 0xB0u && value <= 0xBCu) ||
// B0..BC are the ordinary apply progress/failure/success results;
// SD-backed OTAFIX additionally uses BD for an authorization failure.
(value >= 0xB0u && value <= 0xBDu) ||
(value >= 0xC0u && value <= 0xCFu)) ? value : 0u;
}
+497 -81
View File
@@ -1,5 +1,7 @@
#include "EnvironmentSensorManager.h"
#include "I2CAddressClaimPolicy.h"
#include "EnvironmentI2CConfig.h"
#include "NmeaSentenceProbe.h"
#include <Wire.h>
@@ -9,7 +11,122 @@
#define TELEM_WIRE &Wire // Use default I2C bus for Environment Sensors
#endif
#ifdef NRF52_PLATFORM
static bool isValidNrfI2cPinPair(int32_t sda, int32_t scl) {
if (!mesh::isValidI2cPinPair(sda, scl, PINS_COUNT)) return false;
#ifdef NRF_P1
static const uint32_t MAX_PHYSICAL_NRF_PIN = 48;
#else
static const uint32_t MAX_PHYSICAL_NRF_PIN = 32;
#endif
return digitalPinToPinName(static_cast<uint32_t>(sda))
< MAX_PHYSICAL_NRF_PIN
&& digitalPinToPinName(static_cast<uint32_t>(scl))
< MAX_PHYSICAL_NRF_PIN;
}
#endif
// The pinned Adafruit nRF52 Wire core has no transaction timeout. Reject a
// bus which is already held low, and make one bounded standard nine-clock
// recovery attempt, before entering this manager's blocking transaction loops.
// This cannot protect I2C users which ran earlier in boot or cure a peripheral
// which wedges mid-transaction, but it prevents discovery from entering a bus
// which is already visibly stuck and limits the number of exposed transactions.
static bool ensureI2cBusReleased(TwoWire* wire) {
#ifdef NRF52_PLATFORM
// Board::begin() may remap the primary Wire instance away from the variant's
// PIN_WIRE_* defaults (ProMicro is one example). Use the same board-level
// pins first so recovery never probes or drives an unrelated GPIO.
int32_t sda = -1;
int32_t scl = -1;
#if ENV_HAS_SECONDARY_I2C
if (wire == &Wire1) {
sda = ENV_PIN_SDA;
scl = ENV_PIN_SCL;
} else
#endif
{
#if defined(PIN_BOARD_SDA) && defined(PIN_BOARD_SCL)
sda = PIN_BOARD_SDA;
scl = PIN_BOARD_SCL;
#elif defined(PIN_WIRE_SDA) && defined(PIN_WIRE_SCL)
sda = PIN_WIRE_SDA;
scl = PIN_WIRE_SCL;
#endif
}
if (!isValidNrfI2cPinPair(sda, scl)) return false;
if (digitalRead(sda) == HIGH && digitalRead(scl) == HIGH) return true;
wire->end();
auto releaseLine = [](int32_t pin) {
// OUTPUT_S0D1 is nRF open drain: drive zero, disconnect for one. The input
// pull-up then observes the external bus without ever driving it high.
digitalWrite(pin, HIGH);
pinMode(pin, INPUT_PULLUP);
};
auto driveLineLow = [](int32_t pin) {
// Prime the output latch before enabling an output, avoiding a brief
// push-pull high pulse if the previous latch happened to contain one.
digitalWrite(pin, LOW);
pinMode(pin, OUTPUT_S0D1);
};
auto waitLineHigh = [](int32_t pin) {
for (uint8_t wait = 0; wait < 20; wait++) {
if (digitalRead(pin) == HIGH) return true;
delayMicroseconds(5);
}
return digitalRead(pin) == HIGH;
};
releaseLine(sda);
releaseLine(scl);
delayMicroseconds(10);
// A secondary may have stopped halfway through a byte. Clock it to a byte
// boundary while never driving either open-drain line high.
if (digitalRead(scl) == HIGH) {
for (uint8_t pulse = 0; pulse < 9 && digitalRead(sda) == LOW; pulse++) {
driveLineLow(scl);
delayMicroseconds(5);
releaseLine(scl);
if (!waitLineHigh(scl)) break;
}
if (waitLineHigh(scl)) {
// Generate a STOP (SDA low-to-high while SCL is confirmed high).
driveLineLow(sda);
delayMicroseconds(5);
releaseLine(scl);
if (waitLineHigh(scl)) {
releaseLine(sda);
delayMicroseconds(10);
}
}
}
#if ENV_HAS_SECONDARY_I2C
if (wire == &Wire1) {
Wire1.setPins(static_cast<uint8_t>(sda), static_cast<uint8_t>(scl));
Wire1.begin();
Wire1.setClock(100000);
} else
#endif
{
Wire.setPins(static_cast<uint8_t>(sda), static_cast<uint8_t>(scl));
Wire.begin();
}
delayMicroseconds(10);
return digitalRead(sda) == HIGH && digitalRead(scl) == HIGH;
#else
(void)wire;
return true;
#endif
}
bool EnvironmentSensorManager::i2c_probe(TwoWire& wire, uint8_t addr) {
if (!mesh::isValidI2cPeripheralAddress(addr)) return false;
wire.beginTransmission(addr);
uint8_t error = wire.endTransmission();
return error == 0;
@@ -189,11 +306,105 @@ static uint32_t gpsResetPin = -1;
static bool i2cGPSFlag = false;
static bool serialGPSFlag = false;
#ifndef TELEM_RAK12500_ADDRESS
#ifdef GPS_ADDRESS
#define TELEM_RAK12500_ADDRESS GPS_ADDRESS
#else
#define TELEM_RAK12500_ADDRESS 0x42 //RAK12500 Ublox GPS via i2c
#endif
#endif
#include <SparkFun_u-blox_GNSS_Arduino_Library.h>
static SFE_UBLOX_GNSS ublox_GNSS;
#ifndef RAK_UART_GPS_PROBE_TIMEOUT_MS
#define RAK_UART_GPS_PROBE_TIMEOUT_MS 1200UL
#endif
static uint8_t rakGpsControlActiveLevel() {
#ifdef PIN_GPS_EN_ACTIVE
return PIN_GPS_EN_ACTIVE;
#else
return HIGH;
#endif
}
static void setRakGpsControl(uint8_t pin, bool shared_power_rail,
bool enabled) {
pinMode(pin, OUTPUT);
if (shared_power_rail) {
// WB_IO2 controls every 3V3_S peripheral, not just the GPS. It must never
// be dropped as a GPS power-saving operation.
digitalWrite(pin, HIGH);
return;
}
const uint8_t active = rakGpsControlActiveLevel();
digitalWrite(pin, enabled ? active : static_cast<uint8_t>(!active));
}
static bool serialHasValidGpsSentence(Stream& serial, uint32_t timeout_ms) {
mesh::NmeaSentenceProbe probe;
const uint32_t started = millis();
do {
while (serial.available()) {
if (probe.ingest(static_cast<uint8_t>(serial.read()))) return true;
}
delay(5);
} while (static_cast<uint32_t>(millis() - started) < timeout_ms);
return false;
}
#if ENV_INCLUDE_INA3221
static mesh::I2cRegisterProbeStatus readI2cRegister16(TwoWire* wire,
uint8_t address,
uint8_t reg,
uint16_t& value) {
wire->beginTransmission(address);
if (wire->write(reg) != 1) {
return mesh::I2cRegisterProbeStatus::Inconclusive;
}
const uint8_t error = wire->endTransmission(false);
if (error == 2) return mesh::I2cRegisterProbeStatus::NoResponse;
if (error != 0) return mesh::I2cRegisterProbeStatus::Inconclusive;
if (wire->requestFrom(address, static_cast<uint8_t>(2)) != 2) {
return mesh::I2cRegisterProbeStatus::Inconclusive;
}
value = static_cast<uint16_t>(wire->read()) << 8;
value |= static_cast<uint8_t>(wire->read());
return mesh::I2cRegisterProbeStatus::Success;
}
static mesh::I2cIdentityProbeResult probeIna3221Identity(TwoWire* wire,
uint8_t address) {
uint16_t manufacturer = 0;
const mesh::I2cRegisterProbeStatus manufacturer_result = readI2cRegister16(
wire, address, INA3221_REG_MANUFACTURER_ID, manufacturer);
if (manufacturer_result != mesh::I2cRegisterProbeStatus::Success) {
return mesh::classifyIna3221Identity(
manufacturer_result, manufacturer,
mesh::I2cRegisterProbeStatus::Inconclusive, 0,
INA3221_MANUFACTURER_ID, INA3221_DIE_ID);
}
if (manufacturer != INA3221_MANUFACTURER_ID) {
// Require two successful non-INA reads. The bytes exposed by u-blox at
// 0xFE/0xFF are dynamic, so their values need not equal one another. This
// still cannot make a physical address collision safe.
uint16_t repeated_manufacturer = 0;
const mesh::I2cRegisterProbeStatus repeated_result = readI2cRegister16(
wire, address, INA3221_REG_MANUFACTURER_ID, repeated_manufacturer);
return mesh::classifyIna3221Identity(
manufacturer_result, manufacturer,
repeated_result, repeated_manufacturer,
INA3221_MANUFACTURER_ID, INA3221_DIE_ID);
}
uint16_t die = 0;
const mesh::I2cRegisterProbeStatus die_result = readI2cRegister16(
wire, address, INA3221_REG_DIE_ID, die);
return mesh::classifyIna3221Identity(
manufacturer_result, manufacturer, die_result, die,
INA3221_MANUFACTURER_ID, INA3221_DIE_ID);
}
#endif
class RAK12500LocationProvider : public LocationProvider {
long _lat = 0;
long _lng = 0;
@@ -221,7 +432,23 @@ public:
bool isValid() override { return _fix; }
long getTimestamp() override { return _epoch; }
void sendSentence(const char * sentence) override { }
void reset() override { }
void reset() override {
// Discovery can replace and later reselect this singleton provider. Never
// expose the previous receiver's fix or time samples while the new device
// is still acquiring.
_lat = 0;
_lng = 0;
_alt = 0;
_sats = 0;
_epoch = 0;
_fix = false;
_next_time_check = 0;
_last_time_sync = 0;
_valid_time_samples = 0;
_time_sync_needed = true;
_time_sync_applied = false;
_last_valid_time_sync = 0;
}
void begin() override { }
void stop() override { }
void loop() override {
@@ -271,20 +498,6 @@ public:
static RAK12500LocationProvider RAK12500_provider;
#endif
// ============================================================
// I2C bus scanner
// Probes every valid address and records which ones ACK.
// This runs before any sensor library is touched, so a missing
// or misbehaving device cannot stall or crash the boot sequence.
// ============================================================
static void scanI2CBus(TwoWire* wire, bool found[128]) {
for (uint8_t addr = 0x08; addr < 0x78; addr++) {
wire->beginTransmission(addr);
found[addr] = (wire->endTransmission() == 0);
}
}
// ============================================================
// Per-sensor init and query functions
//
@@ -630,14 +843,15 @@ static void query_bme680_bsec(uint8_t ch, uint8_t, CayenneLPP& lpp) {
// ============================================================
struct SensorDef {
uint8_t address;
uint32_t address; // preserve invalid build overrides until validation
const char* name;
uint8_t (*init)(TwoWire* wire, uint8_t address);
void (*query)(uint8_t channel, uint8_t sub_channel, CayenneLPP& telemetry);
bool (*query_voltage)(uint8_t sub_channel, float& voltage);
};
#define TELEM_BOSCH_ALT_ADDR(addr) ((uint8_t)((addr) == 0x76 ? 0x77 : 0x76))
#define TELEM_BOSCH_ALT_ADDR(addr) \
((addr) == 0x76 ? 0x77U : ((addr) == 0x77 ? 0x76U : (addr)))
static const SensorDef SENSOR_TABLE[] = {
#if ENV_INCLUDE_AHTX0
@@ -704,13 +918,15 @@ static const SensorDef SENSOR_TABLE[] = {
static const size_t SENSOR_TABLE_SIZE = (sizeof(SENSOR_TABLE) / sizeof(SENSOR_TABLE[0])) - 1;
// ============================================================
// begin() - scan the I2C bus, then initialize only what was
// found. A sensor whose address does not ACK during the scan
// is never touched by a library call, preventing hangs or
// crashes caused by absent or misbehaving hardware.
// begin() - initialize an optional board GPS, then scan the I2C bus and invoke
// only table-driven sensor initializers whose address ACKed. GPS uses a
// device-specific probe outside SENSOR_TABLE; an address it positively claims
// is not handed to another driver.
// ============================================================
bool EnvironmentSensorManager::begin() {
_active_sensor_count = 0;
#if ENV_INCLUDE_GPS
#ifdef RAK_WISBLOCK_GPS
// A volatile read anchors the externally linked marker even under LTO.
@@ -725,45 +941,82 @@ bool EnvironmentSensorManager::begin() {
#if ENV_HAS_SECONDARY_I2C
#ifdef NRF52_PLATFORM
Wire1.setPins(ENV_PIN_SDA, ENV_PIN_SCL);
Wire1.setClock(100000);
if (!isValidNrfI2cPinPair(ENV_PIN_SDA, ENV_PIN_SCL)) {
MESH_DEBUG_PRINTLN("Second I2C skipped: invalid SDA/SCL pin pair");
return true;
}
Wire1.setPins(static_cast<uint8_t>(ENV_PIN_SDA),
static_cast<uint8_t>(ENV_PIN_SCL));
Wire1.begin();
Wire1.setClock(100000);
#else
Wire1.begin(ENV_PIN_SDA, ENV_PIN_SCL, 100000);
#endif
MESH_DEBUG_PRINTLN("Second I2C initialized on pins SDA: %d SCL: %d", ENV_PIN_SDA, ENV_PIN_SCL);
#endif
_active_sensor_count = 0;
// Avoid touching a shared I2C bus when no environmental drivers were built.
if (SENSOR_TABLE_SIZE == 0) {
return true;
}
// Scan the I2C bus before touching any sensor library.
if (!ensureI2cBusReleased(TELEM_WIRE)) {
MESH_DEBUG_PRINTLN(
"I2C discovery skipped: bus pins unavailable or SDA/SCL remained low");
return true;
}
// Probe only unique addresses compiled into this image before invoking any
// table-driven sensor library. The old all-address scan performed 112
// blocking Wire transactions even when only a few drivers were present.
bool detected[128] = {};
scanI2CBus(TELEM_WIRE, detected);
bool probed[128] = {};
for (size_t i = 0; i < SENSOR_TABLE_SIZE; i++) {
const uint32_t configured_address = SENSOR_TABLE[i].address;
if (!mesh::isValidI2cPeripheralAddress(configured_address)) {
MESH_DEBUG_PRINTLN("Skipping invalid I2C sensor address %lX",
(unsigned long)configured_address);
continue;
}
const uint8_t address = static_cast<uint8_t>(configured_address);
if (!probed[address]) {
probed[address] = true;
detected[address] = i2c_probe(*TELEM_WIRE, address);
}
}
// Walk the sensor table and initialize only detected devices.
for (size_t i = 0; i < SENSOR_TABLE_SIZE && _active_sensor_count < MAX_ACTIVE_SENSORS; i++) {
const SensorDef& def = SENSOR_TABLE[i];
if (!mesh::isValidI2cPeripheralAddress(def.address)) continue;
const uint8_t address = static_cast<uint8_t>(def.address);
#ifdef RAK_WISBLOCK_GPS
if (mesh::shouldSkipSensorAtClaimedGpsAddress(
i2cGPSFlag, TELEM_WIRE == &Wire,
address, TELEM_RAK12500_ADDRESS)) {
MESH_DEBUG_PRINTLN(
"Skipping %s at I2C address %02X: address is claimed by RAK12500 GPS",
def.name, address);
continue;
}
#endif
// One static driver instance per type: an alternate address is a fallback, not a second device.
bool already_active = false;
for (int j = 0; j < _active_sensor_count; j++) {
if (_active_sensors[j].query == def.query) { already_active = true; break; }
}
if (already_active) continue;
if (!detected[def.address]) {
MESH_DEBUG_PRINTLN("%s not detected at I2C address %02X", def.name, def.address);
if (!detected[address]) {
MESH_DEBUG_PRINTLN("%s not detected at I2C address %02X", def.name, address);
continue;
}
uint8_t n = def.init(TELEM_WIRE, def.address);
uint8_t n = def.init(TELEM_WIRE, address);
if (n == 0) {
MESH_DEBUG_PRINTLN("%s found at %02X but failed to initialize", def.name, def.address);
MESH_DEBUG_PRINTLN("%s found at %02X but failed to initialize", def.name, address);
continue;
}
MESH_DEBUG_PRINTLN("Found %s at address: %02X", def.name, def.address);
detected[def.address] = false; // consumed; later entries must not re-claim this device
MESH_DEBUG_PRINTLN("Found %s at address: %02X", def.name, address);
detected[address] = false; // consumed; later entries must not re-claim this device
for (uint8_t sub = 0; sub < n && _active_sensor_count < MAX_ACTIVE_SENSORS; sub++) {
_active_sensors[_active_sensor_count++] = {
def.query, def.query_voltage, sub
@@ -858,16 +1111,13 @@ bool EnvironmentSensorManager::setSettingValue(const char* name, const char* val
if (gps_detected && strcmp(name, "gps") == 0) {
bool enabled = strcmp(value, "0") != 0;
#if defined(RAK_WISBLOCK_GPS) && defined(FORCE_GPS_ALIVE)
// RAK3401 must keep 3V3_S on for its radio FEM. RAK12501/L76K has no
// separately wired standby control, so claiming it is off would only stop
// parsing while the receiver continued drawing full power.
if (!enabled && serialGPSFlag) {
setGpsTelemetryUserEnabled(true);
return false;
}
if (enabled && serialGPSFlag) {
// A UART L76K cannot remove power from the shared 3V3_S rail. "Off" stops
// parsing and releases the MCU UART, but the still-powered receiver keeps
// driving its TX pin. It therefore does not make that pin safe for an
// external UART bridge.
if (serialGPSFlag) {
_location->setGPSPowerSaving(false);
setGpsTelemetryUserEnabled(true);
setGpsTelemetryUserEnabled(enabled);
return true;
}
#endif
@@ -893,7 +1143,11 @@ void EnvironmentSensorManager::setPowerSavingEnabled(bool enabled) {
#if defined(RAK_WISBLOCK_GPS) && defined(FORCE_GPS_ALIVE)
if (serialGPSFlag) {
_location->setGPSPowerSaving(false);
if (!gps_active) start_gps();
if (gps_user_enabled) {
if (!gps_active) start_gps();
} else if (gps_active) {
stop_gps();
}
return;
}
#endif
@@ -916,6 +1170,17 @@ void EnvironmentSensorManager::setPowerSavingEnabled(bool enabled) {
#if ENV_INCLUDE_GPS
void EnvironmentSensorManager::initBasicGPS() {
// A repeated discovery pass must not steal a UART which an active bridge
// already owns. The bridge release path explicitly restores availability.
if (gps_serial_transport_blocked) {
MESH_DEBUG_PRINTLN("GPS discovery skipped: serial transport is owned by bridge");
return;
}
resetGpsTelemetryTransportState();
gps_serial_transport = false;
gps_serial_transport_blocked = false;
Serial1.setPins(PIN_GPS_TX, PIN_GPS_RX);
#ifdef GPS_BAUD_RATE
@@ -943,6 +1208,7 @@ void EnvironmentSensorManager::initBasicGPS() {
#endif
if (gps_detected) {
gps_serial_transport = true;
MESH_DEBUG_PRINTLN("GPS detected");
#ifdef PERSISTANT_GPS
gps_active = true;
@@ -960,6 +1226,26 @@ void EnvironmentSensorManager::initBasicGPS() {
// or make a new location provider ...
#ifdef RAK_WISBLOCK_GPS
void EnvironmentSensorManager::rakGPSInit() {
// Preserve the established owner across repeated begin() calls. Clearing
// this flag and starting Serial1 here would silently take UART1 back from an
// active bridge.
if (gps_serial_transport_blocked) {
MESH_DEBUG_PRINTLN("RAK GPS discovery skipped: UART1 is owned by bridge");
return;
}
// A repeated begin() must not retain ownership or a provider from an older
// hardware probe.
i2cGPSFlag = false;
serialGPSFlag = false;
resetGpsTelemetryTransportState();
gpsResetPin = static_cast<uint32_t>(-1);
gps_active = false;
gps_detected = false;
gps_serial_transport = false;
gps_serial_transport_blocked = false;
_location = _configured_location;
Serial1.setPins(PIN_GPS_TX, PIN_GPS_RX);
#ifdef GPS_BAUD_RATE
@@ -968,9 +1254,18 @@ void EnvironmentSensorManager::rakGPSInit() {
Serial1.begin(9600);
#endif
// search for the correct IO standby pin depending on socket used
if (gpsIsAwake(WB_IO2)) {
_location->setPinEn(WB_IO2); // WB_IO2 is the power switch for all sensor and IO slots
// A RAK-derived board with a real GPS-enable pin must use it. Stock WisBlock
// bases have no dedicated GPS switch, so their fallback is shared WB_IO2.
#if defined(PIN_GPS_EN) && PIN_GPS_EN >= 0
const uint8_t gps_control_pin = PIN_GPS_EN;
const bool shared_power_rail = false;
#else
const uint8_t gps_control_pin = WB_IO2;
const bool shared_power_rail = true;
#endif
if (gpsIsAwake(gps_control_pin, shared_power_rail)) {
_location->setPinEn(gps_control_pin);
} else {
MESH_DEBUG_PRINTLN("No GPS found");
gps_active = false;
@@ -993,28 +1288,69 @@ void EnvironmentSensorManager::rakGPSInit() {
#endif
}
bool EnvironmentSensorManager::gpsIsAwake(uint8_t ioPin) {
#if defined(ETHERNET_ENABLED) && defined(RAK_BOARD)
if (ioPin == WB_IO2) {
// WB_IO2 powers the Ethernet module on RAK baseboards.
return false;
bool EnvironmentSensorManager::gpsIsAwake(uint8_t ioPin,
bool shared_power_rail) {
if (!shared_power_rail) {
setRakGpsControl(ioPin, false, false);
delay(500);
}
#endif
// RAK3401 shares WB_IO2 with the radio PA supply. Probing a GPS must never
// pulse that rail low or turn the pin back into an input.
#ifndef RAK_3401
// set initial waking state
pinMode(ioPin, OUTPUT);
digitalWrite(ioPin, LOW);
delay(500);
digitalWrite(ioPin, HIGH);
#endif
setRakGpsControl(ioPin, shared_power_rail, true);
// give the receiver time to become responsive
delay(500);
// Try to init RAK12500 on I2C
if (ublox_GNSS.begin(Wire) == true) {
// Prove the UART device with a complete checksum-valid GPS sentence. This
// must precede I2C probing so a UART GPS can coexist with INA3221 at 0x42.
if (serialHasValidGpsSentence(Serial1, RAK_UART_GPS_PROBE_TIMEOUT_MS)) {
MESH_DEBUG_PRINTLN("RAK12501 UART GPS identified with pin %i", ioPin);
gpsResetPin = ioPin;
serialGPSFlag = true;
gps_serial_transport = true;
gps_active = true;
gps_detected = true;
return true;
}
if (!ensureI2cBusReleased(&Wire)) {
MESH_DEBUG_PRINTLN(
"Skipping RAK12500 probe: I2C pins unavailable or bus remains low");
setRakGpsControl(ioPin, shared_power_rail, false);
return false;
}
const uint32_t configured_gps_address =
static_cast<uint32_t>(TELEM_RAK12500_ADDRESS);
if (!mesh::isValidI2cPeripheralAddress(configured_gps_address)) {
MESH_DEBUG_PRINTLN("Skipping invalid RAK12500 I2C address");
setRakGpsControl(ioPin, shared_power_rail, false);
return false;
}
const uint8_t gps_i2c_address =
static_cast<uint8_t>(configured_gps_address);
bool probe_i2c_gps = true;
#if ENV_INCLUDE_INA3221
// Inspect the actual device at the GPS address. This must not depend on the
// configured INA address or telemetry bus: an unstrapped INA3221 can still
// physically remain at 0x42 when firmware expects it at 0x43.
const mesh::I2cIdentityProbeResult ina_identity =
probeIna3221Identity(&Wire, gps_i2c_address);
probe_i2c_gps = mesh::shouldProbeI2cGps(ina_identity);
if (!probe_i2c_gps) {
if (ina_identity == mesh::I2cIdentityProbeResult::Match) {
MESH_DEBUG_PRINTLN(
"Skipping RAK12500 probe at I2C address %02X: INA3221 identity confirmed",
gps_i2c_address);
} else {
MESH_DEBUG_PRINTLN(
"Skipping RAK12500 probe at I2C address %02X: INA identity read was inconclusive",
gps_i2c_address);
}
}
#endif
// After two successful non-INA manufacturer reads, use the u-blox-specific
// probe. No software can make two physical devices at one address safe.
if (probe_i2c_gps
&& ublox_GNSS.begin(Wire, gps_i2c_address) == true) {
MESH_DEBUG_PRINTLN("RAK12500 GPS init correctly with pin %i", ioPin);
ublox_GNSS.setI2COutput(COM_TYPE_UBX);
ublox_GNSS.enableGNSS(true, SFE_UBLOX_GNSS_ID_GPS);
@@ -1028,24 +1364,17 @@ bool EnvironmentSensorManager::gpsIsAwake(uint8_t ioPin) {
ublox_GNSS.saveConfigSelective(VAL_CFG_SUBSEC_IOPORT);
gpsResetPin = ioPin;
i2cGPSFlag = true;
gps_serial_transport = false;
gps_active = true;
gps_detected = true;
RAK12500_provider.setRTCClock(_location->getRTCClock());
RAK12500_provider.reset();
_location = &RAK12500_provider;
return true;
} else if (Serial1.available()) { // RAK12501 (L76K) on UART
MESH_DEBUG_PRINTLN("Serial GPS init correctly and is turned on");
gpsResetPin = ioPin;
serialGPSFlag = true;
gps_active = true;
gps_detected = true;
return true;
}
#ifndef RAK_3401
pinMode(ioPin, INPUT);
#endif
setRakGpsControl(ioPin, shared_power_rail, false);
MESH_DEBUG_PRINTLN("GPS did not init with this IO pin... try the next");
return false;
}
@@ -1059,7 +1388,15 @@ void EnvironmentSensorManager::armGpsPowerSavingCycle() {
}
void EnvironmentSensorManager::start_gps() {
if (gps_active) return;
if (gps_active || gps_serial_transport_blocked) return;
if (gps_serial_transport) {
Serial1.setPins(PIN_GPS_TX, PIN_GPS_RX);
#ifdef GPS_BAUD_RATE
Serial1.begin(GPS_BAUD_RATE);
#else
Serial1.begin(9600);
#endif
}
gps_active = true;
#ifdef RAK_WISBLOCK_GPS
#ifdef FORCE_GPS_ALIVE
@@ -1067,8 +1404,7 @@ void EnvironmentSensorManager::start_gps() {
// an I2C u-blox receiver can also be explicitly returned to full power.
if (i2cGPSFlag) ublox_GNSS.powerSaveMode(false);
#else
pinMode(gpsResetPin, OUTPUT);
digitalWrite(gpsResetPin, HIGH); // WB_IO2 is the shared sensor power rail
setRakGpsControl(gpsResetPin, false, true);
#endif
#else
_location->begin();
@@ -1095,12 +1431,15 @@ void EnvironmentSensorManager::stop_gps() {
#ifdef RAK_WISBLOCK_GPS
#ifdef FORCE_GPS_ALIVE
// Keep the shared rail alive for the RAK3401 radio FEM. The I2C u-blox can
// still enter its internal power-save mode. UART L76K builds reject GPS off
// above because that module has no independent standby connection.
if (i2cGPSFlag) ublox_GNSS.powerSaveMode(true);
// still enter its internal power-save mode. Ending Serial1 stops the MCU
// parser, but a UART L76K remains powered and continues driving its TX pin.
if (i2cGPSFlag) {
ublox_GNSS.powerSaveMode(true);
} else if (serialGPSFlag) {
Serial1.end();
}
#else
pinMode(gpsResetPin, OUTPUT);
digitalWrite(gpsResetPin, LOW); // WB_IO2
setRakGpsControl(gpsResetPin, false, false);
#endif
#else
_location->stop();
@@ -1112,6 +1451,83 @@ void EnvironmentSensorManager::stop_gps() {
}
#endif // ENV_INCLUDE_GPS
bool EnvironmentSensorManager::gpsUsesSerialUart(uint8_t uart) const {
#if ENV_INCLUDE_GPS
return uart == 1 && gps_detected && gps_serial_transport;
#else
(void)uart;
return false;
#endif
}
bool EnvironmentSensorManager::gpsSerialTransportMayConflict(
uint8_t uart) const {
#if ENV_INCLUDE_GPS
#if defined(RAK_WISBLOCK_GPS) \
&& defined(WITH_RS232_BRIDGE_GPS_CONFLICT_UART)
// Silence is not proof of physical absence: a cold RAK12501/L76K can start
// emitting NMEA after the bounded boot probe. Reserve the declared shared
// connector in the merged image. Exact legacy Serial1 bridge targets omit
// GPS support and this reservation; the merged image retains UART2.
if (uart == WITH_RS232_BRIDGE_GPS_CONFLICT_UART) return true;
#endif
return gpsUsesSerialUart(uart);
#else
(void)uart;
return false;
#endif
}
bool EnvironmentSensorManager::gpsSerialTransportCanYield(uint8_t uart) const {
#if ENV_INCLUDE_GPS
if (!gpsUsesSerialUart(uart)) return false;
#if defined(RAK_WISBLOCK_GPS) && defined(FORCE_GPS_ALIVE)
// RAK12501 exposes no independently controlled standby/power pin. WB_IO2 is
// the shared 3V3_S rail and must remain high, so its L76K keeps transmitting
// NMEA after Serial1.end(). Two TX drivers on UART1 would electrically
// contend; require UART2 or physical removal/isolation of this GPS instead.
return false;
#elif defined(RAK_WISBLOCK_GPS)
// This profile is allowed to remove power with its validated GPS control.
return true;
#endif
// Generic NMEA receivers may share the same serial API but are safe to hand
// off only when the provider has a real enable pin that stop() deasserts.
return _location != NULL && _location->getPinEn() >= 0;
#else
(void)uart;
return false;
#endif
}
bool EnvironmentSensorManager::setGpsSerialTransportBlocked(uint8_t uart,
bool blocked) {
#if ENV_INCLUDE_GPS
if (!gpsUsesSerialUart(uart)) return false;
if (gps_serial_transport_blocked == blocked) return true;
if (blocked && !gpsSerialTransportCanYield(uart)) return false;
if (blocked) {
// Cancel remote-query acquisition/hold state before releasing the UART.
setGpsTelemetryTransportAvailable(false);
gps_serial_transport_blocked = true;
if (gps_active) stop_gps();
Serial1.end();
} else {
gps_serial_transport_blocked = false;
// Restoring availability restarts the receiver only when the user's GPS
// preference is on. Otherwise a future authorized location query may
// acquire it on demand.
setGpsTelemetryTransportAvailable(true);
}
return true;
#else
(void)uart;
(void)blocked;
return false;
#endif
}
#if ENV_INCLUDE_GPS || defined(ENV_INCLUDE_BME680_BSEC)
void EnvironmentSensorManager::loop() {
+10 -2
View File
@@ -22,9 +22,12 @@ protected:
bool gps_detected = false;
bool gps_active = false;
bool gps_serial_transport = false;
bool gps_serial_transport_blocked = false;
#if ENV_INCLUDE_GPS
LocationProvider* _location;
LocationProvider* _configured_location;
void armGpsPowerSavingCycle();
void start_gps();
void stop_gps();
@@ -35,13 +38,14 @@ protected:
void initBasicGPS();
#ifdef RAK_BOARD
void rakGPSInit();
bool gpsIsAwake(uint8_t ioPin);
bool gpsIsAwake(uint8_t ioPin, bool shared_power_rail);
#endif
#endif
public:
#if ENV_INCLUDE_GPS
EnvironmentSensorManager(LocationProvider &location): _location(&location){};
EnvironmentSensorManager(LocationProvider &location):
_location(&location), _configured_location(&location) {};
LocationProvider* getLocationProvider() { return _location; }
#else
EnvironmentSensorManager(){};
@@ -61,4 +65,8 @@ public:
const char* getSettingValue(int i) const override;
bool setSettingValue(const char* name, const char* value) override;
void setPowerSavingEnabled(bool enabled) override;
bool gpsUsesSerialUart(uint8_t uart) const override;
bool gpsSerialTransportMayConflict(uint8_t uart) const override;
bool gpsSerialTransportCanYield(uint8_t uart) const override;
bool setGpsSerialTransportBlocked(uint8_t uart, bool blocked) override;
};
@@ -0,0 +1,75 @@
#pragma once
#include <stdint.h>
namespace mesh {
enum class I2cIdentityProbeResult : uint8_t {
NoResponse,
Match,
NotMatch,
Inconclusive,
};
enum class I2cRegisterProbeStatus : uint8_t {
NoResponse,
Success,
Inconclusive,
};
inline bool isValidI2cPeripheralAddress(uint32_t address) {
// 0x00..0x07 and 0x78..0x7f are reserved in the 7-bit address space.
return address >= 0x08 && address <= 0x77;
}
inline bool isValidI2cPinPair(int32_t sda, int32_t scl,
uint32_t pin_count) {
return sda >= 0 && scl >= 0
&& static_cast<uint32_t>(sda) < pin_count
&& static_cast<uint32_t>(scl) < pin_count
&& sda != scl;
}
inline I2cIdentityProbeResult classifyIna3221Identity(
I2cRegisterProbeStatus first_status, uint16_t first_value,
I2cRegisterProbeStatus second_status, uint16_t second_value,
uint16_t expected_manufacturer, uint16_t expected_die) {
if (first_status == I2cRegisterProbeStatus::NoResponse) {
return I2cIdentityProbeResult::NoResponse;
}
if (first_status != I2cRegisterProbeStatus::Success
|| second_status != I2cRegisterProbeStatus::Success) {
return I2cIdentityProbeResult::Inconclusive;
}
if (first_value == expected_manufacturer) {
return second_value == expected_die
? I2cIdentityProbeResult::Match
: I2cIdentityProbeResult::Inconclusive;
}
return second_value != expected_manufacturer
? I2cIdentityProbeResult::NotMatch
: I2cIdentityProbeResult::Inconclusive;
}
// Once a device-specific probe has positively identified the I2C GPS, do not
// hand the same address to a table-driven sensor initializer. An ACK scan can
// prove only that something answered; it cannot distinguish two devices wired
// to the same address or make that electrical configuration safe.
inline bool shouldSkipSensorAtClaimedGpsAddress(bool gps_claimed,
bool same_bus,
uint8_t sensor_address,
uint8_t gps_address) {
return gps_claimed && same_bus && sensor_address == gps_address;
}
// A universal RAK image may support either an INA3221 or an I2C u-blox GPS at
// the GPS address. Check the actual device there first, independent of where
// the telemetry table expected an INA3221. An incomplete identity transaction
// is not proof that the device is safe to receive u-blox traffic.
inline bool shouldProbeI2cGps(I2cIdentityProbeResult identity) {
// Absence/NACK can be transient while an INA powers up. Only a stable,
// definitive non-INA result permits the device-specific u-blox exchange.
return identity == I2cIdentityProbeResult::NotMatch;
}
} // namespace mesh
+121
View File
@@ -0,0 +1,121 @@
#pragma once
#include <stddef.h>
#include <stdint.h>
namespace mesh {
// Bounded, allocation-free proof that a UART stream contains a standard GPS
// NMEA sentence. Merely seeing one byte is not enough: RS-232 traffic or line
// noise must not be allowed to claim the GPS UART.
class NmeaSentenceProbe {
public:
bool ingest(uint8_t byte) {
if (_found) return true;
if (byte == '$') {
resetSentence();
_state = State::Body;
return false;
}
switch (_state) {
case State::Idle:
return false;
case State::Body:
if (byte == '*') {
if (_body_length < 6 || !_header_valid) {
resetSentence();
} else {
_state = State::ChecksumHigh;
}
return false;
}
if (byte < 0x20 || byte > 0x7e || _body_length >= kMaxBodyLength) {
resetSentence();
return false;
}
validateHeaderByte(byte);
_checksum ^= byte;
++_body_length;
return false;
case State::ChecksumHigh: {
const int nibble = hexNibble(byte);
if (nibble < 0) {
resetSentence();
} else {
_expected_checksum = static_cast<uint8_t>(nibble << 4);
_state = State::ChecksumLow;
}
return false;
}
case State::ChecksumLow: {
const int nibble = hexNibble(byte);
if (nibble >= 0) {
_expected_checksum |= static_cast<uint8_t>(nibble);
_found = _header_valid && recognizedTalker()
&& _expected_checksum == _checksum;
}
resetSentence();
return _found;
}
}
return false;
}
bool found() const { return _found; }
private:
enum class State : uint8_t { Idle, Body, ChecksumHigh, ChecksumLow };
static constexpr size_t kMaxBodyLength = 79;
State _state = State::Idle;
uint8_t _checksum = 0;
uint8_t _expected_checksum = 0;
size_t _body_length = 0;
char _header[5] = {};
bool _header_valid = true;
bool _found = false;
static int hexNibble(uint8_t byte) {
if (byte >= '0' && byte <= '9') return byte - '0';
if (byte >= 'A' && byte <= 'F') return byte - 'A' + 10;
if (byte >= 'a' && byte <= 'f') return byte - 'a' + 10;
return -1;
}
void validateHeaderByte(uint8_t byte) {
if (_body_length < 5) {
if (byte < 'A' || byte > 'Z') _header_valid = false;
_header[_body_length] = static_cast<char>(byte);
} else if (_body_length == 5 && byte != ',') {
_header_valid = false;
}
}
bool recognizedTalker() const {
if (_header[0] == 'G') {
switch (_header[1]) {
case 'A': // Galileo
case 'B': // BeiDou
case 'L': // GLONASS
case 'N': // combined GNSS
case 'P': // GPS
case 'Q': // QZSS
return true;
}
}
return _header[0] == 'B' && _header[1] == 'D';
}
void resetSentence() {
_state = State::Idle;
_checksum = 0;
_expected_checksum = 0;
_body_length = 0;
_header_valid = true;
for (char& byte : _header) byte = 0;
}
};
} // namespace mesh
+81
View File
@@ -0,0 +1,81 @@
#pragma once
#include <helpers/ui/DisplayDriver.h>
namespace mesh {
namespace ui {
// Draw complete text across a bounded number of rows. Lines may break in the
// middle of a word (which is important for SSIDs, where every space is
// significant), but never in the middle of a UTF-8 codepoint. If the text
// cannot fit in max_lines, only the final row is ellipsized.
inline int drawTextWrapped(DisplayDriver& display, int x, int y, int max_width,
int line_height, int max_lines, const char* str) {
if (str == nullptr || str[0] == 0 || max_width <= 0
|| line_height <= 0 || max_lines <= 0) {
return 0;
}
int lines = 0;
size_t offset = 0;
while (str[offset] != 0 && lines < max_lines) {
// A display row is necessarily much shorter than this, but retain the
// same generous bound used by DisplayDriver::drawTextEllipsized().
char row[256];
size_t row_length = 0;
while (str[offset + row_length] != 0) {
size_t codepoint_length = 1;
const uint8_t first = (uint8_t)str[offset + row_length];
if (first >= 0xC2 && first <= 0xDF) {
codepoint_length = 2;
} else if (first >= 0xE0 && first <= 0xEF) {
codepoint_length = 3;
} else if (first >= 0xF0 && first <= 0xF4) {
codepoint_length = 4;
}
for (size_t i = 1; i < codepoint_length; ++i) {
if (str[offset + row_length + i] == 0
|| ((uint8_t)str[offset + row_length + i] & 0xC0) != 0x80) {
codepoint_length = 1;
break;
}
}
const size_t candidate_length = row_length + codepoint_length;
if (candidate_length >= sizeof(row)) break;
memcpy(row, str + offset, candidate_length);
row[candidate_length] = 0;
if (display.getTextWidth(row) > max_width) break;
row_length = candidate_length;
}
// Ensure forward progress even for a glyph wider than the viewport.
if (row_length == 0) {
row_length = 1;
while (str[offset + row_length] != 0
&& ((uint8_t)str[offset + row_length] & 0xC0) == 0x80
&& row_length + 1 < sizeof(row)) {
++row_length;
}
}
if (lines + 1 == max_lines && str[offset + row_length] != 0) {
display.drawTextEllipsized(x, y + lines * line_height, max_width,
str + offset);
++lines;
break;
}
memcpy(row, str + offset, row_length);
row[row_length] = 0;
display.setCursor(x, y + lines * line_height);
display.print(row);
offset += row_length;
++lines;
}
return lines;
}
} // namespace ui
} // namespace mesh