Fix USB radio stalls and add durable replay timestamp recovery
This commit is contained in:
1 parent
f2c15225cc
commit
a8cf4fd12f
44 files changed
+4339
-148
No files matched your search
+9
-7
@@ -23,7 +23,8 @@
|
||||
#define MAX_PATH_SIZE 64
|
||||
#define MAX_TRANS_UNIT 255
|
||||
|
||||
#if defined(ARDUINO) && defined(NRF52_PLATFORM) && \
|
||||
#if defined(ARDUINO) && \
|
||||
(defined(NRF52_PLATFORM) || MESH_ESP32_TINYUSB_NONBLOCKING) && \
|
||||
((defined(MESH_DEBUG) && MESH_DEBUG) || \
|
||||
(defined(BRIDGE_DEBUG) && BRIDGE_DEBUG) || \
|
||||
(defined(POWERSAVING_DEBUG) && POWERSAVING_DEBUG))
|
||||
@@ -39,10 +40,11 @@ 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
|
||||
// output best-effort on native TinyUSB: 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.
|
||||
// the available FIFO or ESP32 software queue. The atomic flag also prevents
|
||||
// overlapping debug formatter calls. The historical helper name
|
||||
// is retained for callers; ESP32 TinyUSB uses the same bounded formatter.
|
||||
inline size_t nrf52DebugPrintf(const char* format, ...) {
|
||||
if (format == nullptr || !isUsbLoggingEnabled()) return 0;
|
||||
|
||||
@@ -84,7 +86,7 @@ inline size_t nrf52DebugPrintf(const char* format, ...) {
|
||||
|
||||
#if MESH_DEBUG && ARDUINO
|
||||
#include <Arduino.h>
|
||||
#if defined(NRF52_PLATFORM)
|
||||
#if defined(NRF52_PLATFORM) || MESH_ESP32_TINYUSB_NONBLOCKING
|
||||
#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
|
||||
@@ -97,7 +99,7 @@ inline size_t nrf52DebugPrintf(const char* format, ...) {
|
||||
#endif
|
||||
|
||||
#if BRIDGE_DEBUG && ARDUINO
|
||||
#if defined(NRF52_PLATFORM)
|
||||
#if defined(NRF52_PLATFORM) || MESH_ESP32_TINYUSB_NONBLOCKING
|
||||
#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)
|
||||
@@ -108,7 +110,7 @@ inline size_t nrf52DebugPrintf(const char* format, ...) {
|
||||
|
||||
#if POWERSAVING_DEBUG && ARDUINO
|
||||
#include <Arduino.h>
|
||||
#if defined(NRF52_PLATFORM)
|
||||
#if defined(NRF52_PLATFORM) || MESH_ESP32_TINYUSB_NONBLOCKING
|
||||
#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
|
||||
|
||||
+179
-34
@@ -3,6 +3,7 @@
|
||||
#include "ClientACLFileIntegrity.h"
|
||||
#include "ClientLoginPersistence.h"
|
||||
#include "ClientPathPersistence.h"
|
||||
#include "FileRead.h"
|
||||
#if defined(NRF52_PLATFORM)
|
||||
#include "AtomicFileWriter.h"
|
||||
#endif
|
||||
@@ -11,11 +12,7 @@ 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
|
||||
return mesh::openFileRead(fs, filename);
|
||||
}
|
||||
|
||||
#if !defined(NRF52_PLATFORM)
|
||||
@@ -106,14 +103,17 @@ static mesh::StoredClientPathView storedClientPathForSave(
|
||||
#if !defined(NRF52_PLATFORM)
|
||||
|
||||
static File openWrite(FILESYSTEM* _fs, const char* filename) {
|
||||
if (_fs == NULL) return mesh::emptyFile(_fs);
|
||||
#if defined(STM32_PLATFORM)
|
||||
_fs->remove(filename);
|
||||
return _fs->open(filename, FILE_O_WRITE);
|
||||
File file = _fs->open(filename, FILE_O_WRITE);
|
||||
#elif defined(RP2040_PLATFORM)
|
||||
return _fs->open(filename, "w");
|
||||
File file = _fs->open(filename, "w");
|
||||
#else
|
||||
return _fs->open(filename, "w", true);
|
||||
File file = _fs->open(filename, "w", true);
|
||||
#endif
|
||||
if (file && file.isDirectory()) file.close();
|
||||
return file;
|
||||
}
|
||||
|
||||
static bool readMatches(File& file, const uint8_t* expected, size_t length) {
|
||||
@@ -220,21 +220,24 @@ static bool verifyContactsFile(
|
||||
}
|
||||
#endif
|
||||
|
||||
static bool loginReplayRecordCount(File& file, size_t* count) {
|
||||
if (!file || file.isDirectory()) return false;
|
||||
const size_t size = file.size();
|
||||
if (size < mesh::CLIENT_LOGIN_REPLAY_TRAILER_SIZE) return false;
|
||||
const size_t payload_size =
|
||||
size - mesh::CLIENT_LOGIN_REPLAY_TRAILER_SIZE;
|
||||
if (payload_size % mesh::CLIENT_LOGIN_REPLAY_RECORD_SIZE != 0
|
||||
|| payload_size / mesh::CLIENT_LOGIN_REPLAY_RECORD_SIZE
|
||||
> mesh::MAX_CLIENT_LOGIN_REPLAY_IDENTITIES) return false;
|
||||
*count = payload_size / mesh::CLIENT_LOGIN_REPLAY_RECORD_SIZE;
|
||||
return true;
|
||||
}
|
||||
|
||||
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) {
|
||||
size_t record_count = 0;
|
||||
if (!loginReplayRecordCount(file, &record_count)) {
|
||||
file.close();
|
||||
return false;
|
||||
}
|
||||
@@ -284,10 +287,11 @@ static bool readClientLoginReplayCeiling(
|
||||
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;
|
||||
size_t record_count = 0;
|
||||
if (!loginReplayRecordCount(file, &record_count)) {
|
||||
file.close();
|
||||
return false;
|
||||
}
|
||||
bool success = true;
|
||||
for (size_t i = 0; success && i < record_count; i++) {
|
||||
uint8_t record_pubkey[PUB_KEY_SIZE];
|
||||
@@ -344,11 +348,18 @@ static bool writeClientLoginReplayCeiling(
|
||||
}
|
||||
#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;
|
||||
File source = mesh::emptyFile(fs);
|
||||
size_t record_count = 0;
|
||||
if (fs->exists(mesh::CLIENT_LOGIN_REPLAY_PRIMARY_PATH)) {
|
||||
source = openRead(fs, mesh::CLIENT_LOGIN_REPLAY_PRIMARY_PATH);
|
||||
// A previously present image becoming unreadable is not a first login.
|
||||
// Check again after opening so disappearance/truncation cannot underflow
|
||||
// the trailer subtraction or replace historical replay boundaries.
|
||||
if (!loginReplayRecordCount(source, &record_count)) {
|
||||
source.close();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
#if defined(NRF52_PLATFORM)
|
||||
mesh::AtomicFileWriter destination(
|
||||
fs, mesh::CLIENT_LOGIN_REPLAY_PRIMARY_PATH);
|
||||
@@ -419,9 +430,147 @@ static bool writeClientLoginReplayCeiling(
|
||||
#endif
|
||||
}
|
||||
|
||||
// Scan the complete source, including its CRC, even when no record is selected.
|
||||
// The optional destination preserves every record in its original order. This
|
||||
// also handles duplicate historical identities without dropping tombstones.
|
||||
template <typename Writer>
|
||||
static bool copyClampedLoginReplay(
|
||||
File& source, Writer* destination, const uint8_t* selected_pubkey,
|
||||
uint32_t now, ClientLoginReplayClampResult& result, uint32_t& source_crc) {
|
||||
size_t record_count = 0;
|
||||
if (!loginReplayRecordCount(source, &record_count)) return false;
|
||||
uint32_t original_crc = 0xFFFFFFFFUL;
|
||||
uint32_t output_crc = 0xFFFFFFFFUL;
|
||||
for (size_t i = 0; i < record_count; i++) {
|
||||
uint8_t pubkey[PUB_KEY_SIZE];
|
||||
uint32_t ceiling;
|
||||
if (source.read(pubkey, sizeof(pubkey)) != (int)sizeof(pubkey)
|
||||
|| source.read((uint8_t*)&ceiling, sizeof(ceiling))
|
||||
!= (int)sizeof(ceiling)
|
||||
|| ceiling == 0) return false;
|
||||
original_crc = mesh::updateClientLoginReplayCRC(
|
||||
original_crc, pubkey, sizeof(pubkey));
|
||||
original_crc = mesh::updateClientLoginReplayCRC(
|
||||
original_crc, (const uint8_t*)&ceiling, sizeof(ceiling));
|
||||
if (selected_pubkey == NULL
|
||||
|| memcmp(pubkey, selected_pubkey, PUB_KEY_SIZE) == 0) {
|
||||
result.stored_matched++;
|
||||
if (ceiling > now) {
|
||||
ceiling = now;
|
||||
result.stored_changed++;
|
||||
}
|
||||
}
|
||||
if (destination != NULL && !writeClientLoginReplayRecord(
|
||||
*destination, pubkey, ceiling, &output_crc)) return false;
|
||||
}
|
||||
uint8_t magic[sizeof(mesh::CLIENT_LOGIN_REPLAY_MAGIC)];
|
||||
uint32_t stored_crc;
|
||||
if (source.read(magic, sizeof(magic)) != (int)sizeof(magic)
|
||||
|| source.read((uint8_t*)&stored_crc, sizeof(stored_crc))
|
||||
!= (int)sizeof(stored_crc)
|
||||
|| memcmp(magic, mesh::CLIENT_LOGIN_REPLAY_MAGIC, sizeof(magic)) != 0
|
||||
|| stored_crc != (original_crc ^ 0xFFFFFFFFUL)) return false;
|
||||
source_crc = stored_crc;
|
||||
if (destination == NULL) return true;
|
||||
const uint32_t final_crc = output_crc ^ 0xFFFFFFFFUL;
|
||||
return destination->write(magic, sizeof(magic)) == sizeof(magic)
|
||||
&& destination->write((const uint8_t*)&final_crc, sizeof(final_crc))
|
||||
== sizeof(final_crc);
|
||||
}
|
||||
|
||||
bool ClientACL::clampLoginReplayTimestamps(
|
||||
const uint8_t* pubkey, uint32_t now,
|
||||
ClientLoginReplayClampResult& result) {
|
||||
result = {};
|
||||
if (_fs == NULL || !login_replay_store_available || now == 0) return false;
|
||||
|
||||
ClientLoginReplayClampResult pending = {};
|
||||
if (_fs->exists(mesh::CLIENT_LOGIN_REPLAY_PRIMARY_PATH)) {
|
||||
File source = openRead(_fs, mesh::CLIENT_LOGIN_REPLAY_PRIMARY_PATH);
|
||||
uint32_t original_crc = 0;
|
||||
const bool valid = copyClampedLoginReplay(
|
||||
source, (File*)NULL, pubkey, now, pending, original_crc);
|
||||
source.close();
|
||||
if (!valid) {
|
||||
login_replay_store_available = false;
|
||||
return false;
|
||||
}
|
||||
if (pending.stored_changed != 0) {
|
||||
#if !defined(NRF52_PLATFORM)
|
||||
// A validated live image is authoritative. Only discard a stale backup
|
||||
// after validation, and never enter publication with an uncleared one.
|
||||
if (!mesh::removeClientLoginReplayArtifact(
|
||||
_fs, mesh::CLIENT_LOGIN_REPLAY_BACKUP_PATH)) return false;
|
||||
#endif
|
||||
source = openRead(_fs, mesh::CLIENT_LOGIN_REPLAY_PRIMARY_PATH);
|
||||
#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) {
|
||||
source.close();
|
||||
return false;
|
||||
}
|
||||
ClientLoginReplayClampResult copied = {};
|
||||
uint32_t copied_crc = 0;
|
||||
const bool copied_ok = copyClampedLoginReplay(
|
||||
source, &destination, pubkey, now, copied, copied_crc)
|
||||
&& copied_crc == original_crc
|
||||
&& copied.stored_matched == pending.stored_matched
|
||||
&& copied.stored_changed == pending.stored_changed;
|
||||
source.close();
|
||||
#if defined(NRF52_PLATFORM)
|
||||
const bool published = destination.commit(copied_ok);
|
||||
#else
|
||||
destination.close();
|
||||
const bool verified = copied_ok && validateLoginReplayFileIntegrity(
|
||||
_fs, mesh::CLIENT_LOGIN_REPLAY_TEMP_PATH);
|
||||
const bool published = mesh::publishClientLoginReplayTemp(
|
||||
_fs, verified, validateLoginReplayFileIntegrity);
|
||||
#endif
|
||||
if (!published) {
|
||||
// Ordinary failed writes retain the old store. If rollback or a read
|
||||
// also failed, do not let a missing/corrupt image become a first login.
|
||||
File retained = openRead(_fs, mesh::CLIENT_LOGIN_REPLAY_PRIMARY_PATH);
|
||||
ClientLoginReplayClampResult ignored = {};
|
||||
uint32_t retained_crc = 0;
|
||||
const bool retained_ok = copyClampedLoginReplay(
|
||||
retained, (File*)NULL, pubkey, now, ignored, retained_crc)
|
||||
&& retained_crc == original_crc;
|
||||
retained.close();
|
||||
if (!retained_ok) login_replay_store_available = false;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
} else if (_fs->exists(mesh::CLIENT_LOGIN_REPLAY_BACKUP_PATH)
|
||||
|| _fs->exists(mesh::CLIENT_LOGIN_REPLAY_TEMP_PATH)) {
|
||||
// Recovery is performed by load(). Do not mistake an interrupted/corrupt
|
||||
// transaction for a never-created store during this explicit operation.
|
||||
login_replay_store_available = false;
|
||||
return false;
|
||||
}
|
||||
|
||||
for (int i = 0; i < num_clients; i++) {
|
||||
ClientInfo& client = clients[i];
|
||||
if (pubkey != NULL && memcmp(client.id.pub_key, pubkey, PUB_KEY_SIZE) != 0)
|
||||
continue;
|
||||
pending.live_matched++;
|
||||
if (client.last_timestamp > now) {
|
||||
client.last_timestamp = now;
|
||||
pending.live_changed++;
|
||||
}
|
||||
}
|
||||
result = pending;
|
||||
return true;
|
||||
}
|
||||
|
||||
void ClientACL::load(FILESYSTEM* fs, const mesh::LocalIdentity& self_id) {
|
||||
_fs = fs;
|
||||
num_clients = 0;
|
||||
login_replay_store_available = false;
|
||||
if (_fs == NULL) return;
|
||||
#if defined(NRF52_PLATFORM)
|
||||
// AtomicFileWriter may leave only a harmless temp image when reset before
|
||||
// rename. The live image remains authoritative.
|
||||
@@ -447,11 +596,7 @@ void ClientACL::load(FILESYSTEM* fs, const mesh::LocalIdentity& self_id) {
|
||||
}
|
||||
#endif
|
||||
if (_fs->exists("/s_contacts")) {
|
||||
#if defined(RP2040_PLATFORM)
|
||||
File file = _fs->open("/s_contacts", "r");
|
||||
#else
|
||||
File file = _fs->open("/s_contacts");
|
||||
#endif
|
||||
File file = openRead(_fs, "/s_contacts");
|
||||
if (file) {
|
||||
bool full = false;
|
||||
while (!full) {
|
||||
|
||||
@@ -51,6 +51,13 @@ struct ClientInfo {
|
||||
#define MAX_CLIENTS 32
|
||||
#endif
|
||||
|
||||
struct ClientLoginReplayClampResult {
|
||||
uint16_t stored_matched;
|
||||
uint16_t stored_changed;
|
||||
uint16_t live_matched;
|
||||
uint16_t live_changed;
|
||||
};
|
||||
|
||||
class ClientACL {
|
||||
FILESYSTEM* _fs;
|
||||
ClientInfo clients[MAX_CLIENTS];
|
||||
@@ -81,6 +88,15 @@ public:
|
||||
uint32_t runtime_last_timestamp,
|
||||
uint8_t login_permissions);
|
||||
|
||||
// Explicitly authorized recovery only: the caller validates its transport,
|
||||
// permissions and clock. A non-null selector is a complete PUB_KEY_SIZE key;
|
||||
// null selects all records, including historical identities outside the ACL.
|
||||
// Only lower existing values to now. Never insert/delete records or raise a
|
||||
// floor. Publish durable changes before live changes; false returns zero
|
||||
// counts and leaves live state untouched. Counts include duplicate records.
|
||||
bool clampLoginReplayTimestamps(const uint8_t* pubkey, uint32_t now,
|
||||
ClientLoginReplayClampResult& result);
|
||||
|
||||
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);
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
#include "ESP32Board.h"
|
||||
#include <target.h>
|
||||
#include "UsbLogging.h"
|
||||
#include "FileRead.h"
|
||||
#include "UserGpioPinPolicy.h"
|
||||
|
||||
namespace mesh {
|
||||
@@ -116,7 +117,7 @@ class LightweightOTAServer {
|
||||
}
|
||||
|
||||
void sendLog(WiFiClient& client) {
|
||||
File log = SPIFFS.open("/packet_log", FILE_READ);
|
||||
File log = mesh::openFileRead(&SPIFFS, "/packet_log");
|
||||
if (!log) {
|
||||
static const char missing[] = "packet log not found";
|
||||
sendResponse(client, 404, "Not Found", "text/plain", missing, sizeof(missing) - 1);
|
||||
@@ -1123,8 +1124,13 @@ void ESP32Board::enterDeepSleep(uint32_t secs) {
|
||||
sensors.getLocationProvider()->stop();
|
||||
}
|
||||
|
||||
// Flush serial buffers
|
||||
// Native TinyUSB must not wait for a host which has stopped reading.
|
||||
// Keep the original flush behavior for UART and USB-Serial-JTAG targets.
|
||||
#if MESH_ESP32_TINYUSB_NONBLOCKING
|
||||
mesh::serviceUsbTerminalPort();
|
||||
#else
|
||||
Serial.flush();
|
||||
#endif
|
||||
delay(100);
|
||||
|
||||
// Clear stale wakeup sources to avoid ghost wakeup
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
#pragma once
|
||||
|
||||
#if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM)
|
||||
#include <InternalFileSystem.h>
|
||||
#endif
|
||||
|
||||
namespace mesh {
|
||||
|
||||
// Adafruit LittleFS has no default File constructor: even a closed handle
|
||||
// needs a valid filesystem owner. Its owner-only constructor does no I/O, so
|
||||
// InternalFS is a safe fallback when the requested filesystem is unavailable.
|
||||
template <typename Filesystem>
|
||||
auto emptyFile(Filesystem* fs)
|
||||
#if defined(RP2040_PLATFORM)
|
||||
-> decltype(fs->open(static_cast<const char*>(nullptr), "r")) {
|
||||
using FileType = decltype(fs->open(static_cast<const char*>(nullptr), "r"));
|
||||
#else
|
||||
-> decltype(fs->open(static_cast<const char*>(nullptr))) {
|
||||
using FileType = decltype(fs->open(static_cast<const char*>(nullptr)));
|
||||
#endif
|
||||
#if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM)
|
||||
if (fs != nullptr) return FileType(*fs);
|
||||
return FileType(InternalFS);
|
||||
#else
|
||||
(void)fs;
|
||||
return FileType();
|
||||
#endif
|
||||
}
|
||||
|
||||
// Arduino-ESP32 SPIFFS can return a truthy directory handle when a missing
|
||||
// pathname is opened for reading. A state-file reader must not interpret that
|
||||
// zero-length directory as a valid empty file. Keep real directory enumeration
|
||||
// on the filesystem's ordinary open() API.
|
||||
template <typename Filesystem>
|
||||
auto openFileRead(Filesystem* fs, const char* path)
|
||||
#if defined(RP2040_PLATFORM)
|
||||
-> decltype(fs->open(path, "r")) {
|
||||
using FileType = decltype(fs->open(path, "r"));
|
||||
#else
|
||||
-> decltype(fs->open(path)) {
|
||||
using FileType = decltype(fs->open(path));
|
||||
#endif
|
||||
if (fs == nullptr || path == nullptr || !fs->exists(path)) return emptyFile(fs);
|
||||
#if defined(RP2040_PLATFORM)
|
||||
FileType file = fs->open(path, "r");
|
||||
#else
|
||||
FileType file = fs->open(path);
|
||||
#endif
|
||||
if (file && file.isDirectory()) file.close();
|
||||
return file;
|
||||
}
|
||||
|
||||
} // namespace mesh
|
||||
@@ -0,0 +1,233 @@
|
||||
#pragma once
|
||||
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
#include <string.h>
|
||||
|
||||
namespace mesh {
|
||||
|
||||
enum class ReplayResetKind : uint8_t {
|
||||
NotReplay,
|
||||
Invalid,
|
||||
ExactKey,
|
||||
ExactKeyConfirm,
|
||||
AllConfirm,
|
||||
};
|
||||
|
||||
struct ReplayResetRequest {
|
||||
ReplayResetKind kind;
|
||||
uint8_t key[32];
|
||||
uint8_t token[16];
|
||||
};
|
||||
|
||||
namespace replay_reset_detail {
|
||||
|
||||
inline bool space(char value) {
|
||||
return value == ' ' || value == '\t' || value == '\r' || value == '\n';
|
||||
}
|
||||
|
||||
inline const char* skipSpace(const char* text) {
|
||||
while (space(*text)) ++text;
|
||||
return text;
|
||||
}
|
||||
|
||||
inline char lower(char value) {
|
||||
return value >= 'A' && value <= 'Z' ? (char)(value + ('a' - 'A')) : value;
|
||||
}
|
||||
|
||||
inline bool word(const char* text, size_t length, const char* expected) {
|
||||
size_t i = 0;
|
||||
while (i < length && expected[i] != 0) {
|
||||
if (lower(text[i]) != expected[i]) return false;
|
||||
++i;
|
||||
}
|
||||
return i == length && expected[i] == 0;
|
||||
}
|
||||
|
||||
inline size_t wordLength(const char* text) {
|
||||
size_t length = 0;
|
||||
while (text[length] != 0 && !space(text[length])) ++length;
|
||||
return length;
|
||||
}
|
||||
|
||||
inline int hexDigit(char value) {
|
||||
if (value >= '0' && value <= '9') return value - '0';
|
||||
value = lower(value);
|
||||
return value >= 'a' && value <= 'f' ? value - 'a' + 10 : -1;
|
||||
}
|
||||
|
||||
inline bool hex(const char* text, size_t length, uint8_t* output,
|
||||
size_t output_length) {
|
||||
if (length != output_length * 2U) return false;
|
||||
for (size_t i = 0; i < output_length; ++i) {
|
||||
const int high = hexDigit(text[2U * i]);
|
||||
const int low = hexDigit(text[2U * i + 1U]);
|
||||
if (high < 0 || low < 0) return false;
|
||||
output[i] = (uint8_t)((high << 4) | low);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace replay_reset_detail
|
||||
|
||||
// Use this same parser before the receiver's timestamp mutation and in the
|
||||
// command handler. Even malformed replay commands must not advance a sender's
|
||||
// live floor: an old consumed confirmation could otherwise poison it again.
|
||||
// This parser supplies no authentication or transport permission by itself.
|
||||
inline ReplayResetKind parseReplayResetCommand(const char* command,
|
||||
ReplayResetRequest& request) {
|
||||
memset(&request, 0, sizeof(request));
|
||||
request.kind = ReplayResetKind::NotReplay;
|
||||
if (command == nullptr) return request.kind;
|
||||
using namespace replay_reset_detail;
|
||||
const char* text = skipSpace(command);
|
||||
// Match the optional two-character companion CLI response prefix.
|
||||
if (text[0] != 0 && text[1] != 0 && text[2] == '|') {
|
||||
text = skipSpace(text + 3);
|
||||
}
|
||||
const size_t verb_length = wordLength(text);
|
||||
if (!word(text, verb_length, "replay")) {
|
||||
// Reserve dotted replay subcommands as malformed members of this family.
|
||||
if (verb_length > 6U && word(text, 6U, "replay") && text[6] == '.') {
|
||||
request.kind = ReplayResetKind::Invalid;
|
||||
}
|
||||
return request.kind;
|
||||
}
|
||||
request.kind = ReplayResetKind::Invalid;
|
||||
text = skipSpace(text + verb_length);
|
||||
const size_t action_length = wordLength(text);
|
||||
if (!word(text, action_length, "reset")) return request.kind;
|
||||
text = skipSpace(text + action_length);
|
||||
const size_t key_length = wordLength(text);
|
||||
if (word(text, key_length, "all")) {
|
||||
text = skipSpace(text + key_length);
|
||||
const size_t confirmation_length = wordLength(text);
|
||||
if (word(text, confirmation_length, "confirm")
|
||||
&& *skipSpace(text + confirmation_length) == 0) {
|
||||
request.kind = ReplayResetKind::AllConfirm;
|
||||
}
|
||||
return request.kind;
|
||||
}
|
||||
if (!hex(text, key_length, request.key, sizeof(request.key))) return request.kind;
|
||||
text = skipSpace(text + key_length);
|
||||
if (*text == 0) {
|
||||
request.kind = ReplayResetKind::ExactKey;
|
||||
return request.kind;
|
||||
}
|
||||
const size_t token_length = wordLength(text);
|
||||
if (!hex(text, token_length, request.token, sizeof(request.token))
|
||||
|| *skipSpace(text + token_length) != 0) return request.kind;
|
||||
request.kind = ReplayResetKind::ExactKeyConfirm;
|
||||
return request.kind;
|
||||
}
|
||||
|
||||
// One short-lived challenge binds a reset to both the authenticated issuer and
|
||||
// exact target. It is deliberately RAM-only: a reboot invalidates all captured
|
||||
// confirmations. Disclose the same token on retries for the first two minutes;
|
||||
// then retain it for confirmation only until the original five-minute deadline.
|
||||
// Retries never replace the token or restart either window.
|
||||
// Call consume() before attempting durable state publication;
|
||||
// a failed write requires a new challenge rather than making an old one usable.
|
||||
class ReplayResetNonce {
|
||||
public:
|
||||
static constexpr size_t KEY_SIZE = 32;
|
||||
static constexpr size_t TOKEN_SIZE = 16;
|
||||
static constexpr uint32_t RESEND_WINDOW_MILLIS = 120000;
|
||||
static constexpr uint32_t LIFETIME_MILLIS = 300000;
|
||||
static constexpr int64_t CLOCK_TOLERANCE_SECONDS = 5;
|
||||
|
||||
enum class IssueResult : uint8_t {
|
||||
Issued, Reused, AwaitingConfirmation, Busy, Invalid
|
||||
};
|
||||
|
||||
ReplayResetNonce() { clear(); }
|
||||
|
||||
IssueResult issue(const uint8_t* issuer, const uint8_t* target,
|
||||
const uint8_t* random_token, uint32_t now_millis,
|
||||
uint32_t now_epoch) {
|
||||
if (issuer == nullptr || target == nullptr || now_epoch == 0) {
|
||||
return IssueResult::Invalid;
|
||||
}
|
||||
if (isCurrent(now_millis, now_epoch)) {
|
||||
if (!sameIdentity(issuer, target)) return IssueResult::Busy;
|
||||
return now_millis - issued_millis_ < RESEND_WINDOW_MILLIS
|
||||
? IssueResult::Reused : IssueResult::AwaitingConfirmation;
|
||||
}
|
||||
clear();
|
||||
if (random_token == nullptr) return IssueResult::Invalid;
|
||||
uint8_t nonzero = 0;
|
||||
for (size_t i = 0; i < TOKEN_SIZE; ++i) nonzero |= random_token[i];
|
||||
if (nonzero == 0) return IssueResult::Invalid;
|
||||
memcpy(issuer_, issuer, KEY_SIZE);
|
||||
memcpy(target_, target, KEY_SIZE);
|
||||
memcpy(token_, random_token, TOKEN_SIZE);
|
||||
issued_millis_ = now_millis;
|
||||
issued_epoch_ = now_epoch;
|
||||
active_ = true;
|
||||
return IssueResult::Issued;
|
||||
}
|
||||
|
||||
bool matches(const uint8_t* issuer, const uint8_t* target,
|
||||
const uint8_t* supplied_token, uint32_t now_millis,
|
||||
uint32_t now_epoch) const {
|
||||
if (issuer == nullptr || target == nullptr || supplied_token == nullptr
|
||||
|| !isCurrent(now_millis, now_epoch) || !sameIdentity(issuer, target)) {
|
||||
return false;
|
||||
}
|
||||
uint8_t difference = 0;
|
||||
for (size_t i = 0; i < TOKEN_SIZE; ++i) {
|
||||
difference |= token_[i] ^ supplied_token[i];
|
||||
}
|
||||
return difference == 0;
|
||||
}
|
||||
|
||||
bool consume(const uint8_t* issuer, const uint8_t* target,
|
||||
const uint8_t* supplied_token, uint32_t now_millis,
|
||||
uint32_t now_epoch) {
|
||||
if (!matches(issuer, target, supplied_token, now_millis, now_epoch)) return false;
|
||||
clear();
|
||||
return true;
|
||||
}
|
||||
|
||||
const uint8_t* token() const { return token_; }
|
||||
|
||||
uint32_t remainingSeconds(uint32_t now_millis, uint32_t now_epoch) const {
|
||||
if (!isCurrent(now_millis, now_epoch)) return 0;
|
||||
return (LIFETIME_MILLIS - (now_millis - issued_millis_)) / 1000U;
|
||||
}
|
||||
|
||||
void clear() {
|
||||
active_ = false;
|
||||
memset(issuer_, 0, sizeof(issuer_));
|
||||
memset(target_, 0, sizeof(target_));
|
||||
memset(token_, 0, sizeof(token_));
|
||||
issued_millis_ = 0;
|
||||
issued_epoch_ = 0;
|
||||
}
|
||||
|
||||
private:
|
||||
bool sameIdentity(const uint8_t* issuer, const uint8_t* target) const {
|
||||
return memcmp(issuer_, issuer, KEY_SIZE) == 0
|
||||
&& memcmp(target_, target, KEY_SIZE) == 0;
|
||||
}
|
||||
|
||||
bool isCurrent(uint32_t now_millis, uint32_t now_epoch) const {
|
||||
if (!active_ || now_epoch == 0) return false;
|
||||
const uint32_t elapsed = now_millis - issued_millis_;
|
||||
if (elapsed >= LIFETIME_MILLIS) return false;
|
||||
const uint64_t expected_epoch = (uint64_t)issued_epoch_ + elapsed / 1000U;
|
||||
if (expected_epoch > UINT32_MAX) return false;
|
||||
const int64_t clock_difference = (int64_t)now_epoch - (int64_t)expected_epoch;
|
||||
return clock_difference >= -CLOCK_TOLERANCE_SECONDS
|
||||
&& clock_difference <= CLOCK_TOLERANCE_SECONDS;
|
||||
}
|
||||
|
||||
uint8_t issuer_[KEY_SIZE];
|
||||
uint8_t target_[KEY_SIZE];
|
||||
uint8_t token_[TOKEN_SIZE];
|
||||
uint32_t issued_millis_;
|
||||
uint32_t issued_epoch_;
|
||||
bool active_;
|
||||
};
|
||||
|
||||
} // namespace mesh
|
||||
@@ -465,6 +465,27 @@ public:
|
||||
const RecentRepeaterInfo* getRecentRepeaterBySortedIdx(int idx_wanted) const {
|
||||
return getRecentRepeaterBySortedIdxFiltered(idx_wanted, NULL, 0);
|
||||
}
|
||||
// Advance a cooperative live view in one bounded table scan. Unlike a
|
||||
// rank lookup, this never replays every earlier rank as the list grows.
|
||||
// The caller copies the last accepted row: intervening RX may change the
|
||||
// live ordering, but cannot invalidate that saved sort key or force a
|
||||
// snapshot allocation. The existing paginated/rank APIs are unchanged.
|
||||
const RecentRepeaterInfo* getNextRecentRepeaterBySortKey(
|
||||
const RecentRepeaterInfo* after, int after_index, int& result_index) const {
|
||||
const RecentRepeaterInfo* best = NULL;
|
||||
result_index = -1;
|
||||
for (int i = 0; i < _recent_repeater_count; ++i) {
|
||||
const RecentRepeaterInfo* info = &_recent_repeaters[i];
|
||||
if (after != NULL && !recentRepeaterComesBefore(*after, after_index, *info, i)) {
|
||||
continue;
|
||||
}
|
||||
if (best == NULL || recentRepeaterComesBefore(*info, i, *best, result_index)) {
|
||||
best = info;
|
||||
result_index = i;
|
||||
}
|
||||
}
|
||||
return best;
|
||||
}
|
||||
int getRecentRepeaterMatchingCount(const uint8_t* search_prefix,
|
||||
uint8_t search_prefix_len) const {
|
||||
if (_max_recent_repeaters == 0 || search_prefix == NULL
|
||||
|
||||
+306
-12
@@ -3,6 +3,7 @@
|
||||
#if defined(ARDUINO)
|
||||
#include <Arduino.h>
|
||||
#include <atomic>
|
||||
#include <stdio.h>
|
||||
|
||||
#if defined(ESP32) && defined(ARDUINO_USB_MODE) && ARDUINO_USB_MODE == 1 \
|
||||
&& defined(ARDUINO_USB_CDC_ON_BOOT) && ARDUINO_USB_CDC_ON_BOOT \
|
||||
@@ -14,9 +15,13 @@
|
||||
#define MESH_ESP32_HWCDC_SESSION_GUARD 0
|
||||
#endif
|
||||
|
||||
#if defined(NRF52_PLATFORM) || MESH_ESP32_HWCDC_SESSION_GUARD
|
||||
#if defined(NRF52_PLATFORM) || MESH_ESP32_HWCDC_SESSION_GUARD \
|
||||
|| MESH_ESP32_TINYUSB_NONBLOCKING
|
||||
#include "NonBlockingWriteStream.h"
|
||||
#endif
|
||||
#if MESH_ESP32_TINYUSB_NONBLOCKING
|
||||
#include "esp32-hal-tinyusb.h"
|
||||
#endif
|
||||
#if MESH_ESP32_HWCDC_SESSION_GUARD
|
||||
#include "UsbAsciiBinarySwitch.h"
|
||||
#endif
|
||||
@@ -72,6 +77,208 @@ class NullUsbLoggingStream : public Stream {
|
||||
|
||||
static NullUsbLoggingStream null_usb_logging_stream;
|
||||
|
||||
#if MESH_ESP32_TINYUSB_NONBLOCKING
|
||||
// Arduino-ESP32 2.0.17 constructs Serial as USBCDC(0). Keep its RX queue and
|
||||
// existing descriptors/callbacks, but never call its potentially unbounded
|
||||
// write()/flush() or its mutex-taking availableForWrite(). The native CDC
|
||||
// application API makes one FIFO attempt and can safely return short; its
|
||||
// flush starts an available endpoint transfer without waiting for the host.
|
||||
// TinyUSB still takes short RTOS FIFO/endpoint mutexes internally: this is a
|
||||
// no-host-progress-wait contract, not a claim that the USB stack is lock-free.
|
||||
static std::atomic<uint32_t> esp32_tinyusb_reset_generation{0};
|
||||
static std::atomic<uint32_t> esp32_tinyusb_clean_generation{0};
|
||||
static std::atomic_flag esp32_tinyusb_queue_busy = ATOMIC_FLAG_INIT;
|
||||
static std::atomic<bool> esp32_tinyusb_terminal_discard_pending{false};
|
||||
static std::atomic<uint32_t> esp32_tinyusb_terminal_dropped_bytes{0};
|
||||
static uint32_t esp32_tinyusb_terminal_reported_dropped_bytes = 0;
|
||||
static uint32_t esp32_tinyusb_taken_reset_generation = 0;
|
||||
static bool esp32_tinyusb_event_handler_registered = false;
|
||||
static bool esp32_tinyusb_was_connected = false;
|
||||
|
||||
static bool canAccessEsp32TinyUsb(void*) {
|
||||
return !xPortInIsrContext() && tud_cdc_n_connected(0)
|
||||
&& esp32_tinyusb_clean_generation.load(std::memory_order_acquire)
|
||||
== esp32_tinyusb_reset_generation.load(std::memory_order_acquire);
|
||||
}
|
||||
|
||||
static void handleEsp32TinyUsbEvent(void*, esp_event_base_t, int32_t event_id,
|
||||
void* event_data) {
|
||||
// This is the Arduino event task, not TinyUSB's owner. Only publish an
|
||||
// epoch: queue cleanup and endpoint access remain in application service.
|
||||
bool closed = event_id == ARDUINO_USB_CDC_DISCONNECTED_EVENT;
|
||||
if (event_id == ARDUINO_USB_CDC_LINE_STATE_EVENT && event_data != nullptr) {
|
||||
const auto* event = static_cast<const arduino_usb_cdc_event_data_t*>(event_data);
|
||||
closed = !event->line_state.dtr;
|
||||
}
|
||||
if (closed) {
|
||||
esp32_tinyusb_reset_generation.fetch_add(1, std::memory_order_acq_rel);
|
||||
}
|
||||
}
|
||||
|
||||
class Esp32TinyUsbFifoStream : public Stream {
|
||||
public:
|
||||
int available() override {
|
||||
const int count = Serial.available();
|
||||
return count > 0 ? count : 0;
|
||||
}
|
||||
int read() override { return Serial.read(); }
|
||||
int peek() override { return Serial.peek(); }
|
||||
void flush() override {}
|
||||
int availableForWrite() override {
|
||||
return canAccessEsp32TinyUsb(nullptr)
|
||||
? static_cast<int>(tud_cdc_n_write_available(0)) : 0;
|
||||
}
|
||||
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 || !canAccessEsp32TinyUsb(nullptr)) return 0;
|
||||
const size_t available = tud_cdc_n_write_available(0);
|
||||
const size_t attempt = size < available ? size : available;
|
||||
if (attempt == 0) return 0;
|
||||
const size_t written = tud_cdc_n_write(0, data, attempt);
|
||||
(void)tud_cdc_n_write_flush(0);
|
||||
return written;
|
||||
}
|
||||
};
|
||||
|
||||
static Esp32TinyUsbFifoStream esp32_tinyusb_fifo_port;
|
||||
static size_t writeEsp32TinyUsbOnce(void*, const uint8_t* data, size_t size) {
|
||||
return esp32_tinyusb_fifo_port.write(data, size);
|
||||
}
|
||||
static SingleAttemptNonBlockingStream nonblocking_esp32_tinyusb_port(
|
||||
esp32_tinyusb_fifo_port, writeEsp32TinyUsbOnce, nullptr,
|
||||
canAccessEsp32TinyUsb);
|
||||
static AtomicWholeRecordNonBlockingStream<11> nonblocking_esp32_tinyusb_mota_port(
|
||||
nonblocking_esp32_tinyusb_port);
|
||||
|
||||
// The ESP32 CDC FIFO is just 64 bytes. Retain complete producer writes in ONE
|
||||
// chronological queue: independent log/reply queues would interleave their
|
||||
// partial lines as that small FIFO drains. Diagnostics leave most of the bounded
|
||||
// queue reserved for functional replies; congestion drops records, not LoRa.
|
||||
static constexpr size_t esp32_tinyusb_text_capacity = 4096;
|
||||
static constexpr size_t esp32_tinyusb_functional_reserve = 3072;
|
||||
static constexpr size_t esp32_tinyusb_log_record_capacity = 640;
|
||||
// ESP32 Print::printf has no Adafruit 256-byte scratch-length bug. Disable
|
||||
// that nRF52-specific sentinel without changing the existing nRF52 facade.
|
||||
static BufferedNonBlockingWriteStream<esp32_tinyusb_text_capacity,
|
||||
esp32_tinyusb_text_capacity + 1> esp32_tinyusb_text_queue(
|
||||
nonblocking_esp32_tinyusb_port);
|
||||
|
||||
template <bool Diagnostic>
|
||||
class Esp32TinyUsbBufferedStream : public Stream {
|
||||
public:
|
||||
int available() override { return nonblocking_esp32_tinyusb_port.available(); }
|
||||
int read() override { return nonblocking_esp32_tinyusb_port.read(); }
|
||||
int peek() override { return nonblocking_esp32_tinyusb_port.peek(); }
|
||||
void flush() override { serviceUsbTerminalPort(); }
|
||||
int availableForWrite() override {
|
||||
if (esp32_tinyusb_queue_busy.test_and_set(std::memory_order_acquire)) return 0;
|
||||
const int available = canQueue()
|
||||
? esp32_tinyusb_text_queue.availableForWrite() : 0;
|
||||
esp32_tinyusb_queue_busy.clear(std::memory_order_release);
|
||||
if (!Diagnostic) return available;
|
||||
// SerialLogLine must admit its entire <=640-byte record instead of
|
||||
// splitting it when only a few bytes of diagnostic capacity remain.
|
||||
return available >= static_cast<int>(esp32_tinyusb_functional_reserve
|
||||
+ esp32_tinyusb_log_record_capacity)
|
||||
? available - esp32_tinyusb_functional_reserve : 0;
|
||||
}
|
||||
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) return 0;
|
||||
if (esp32_tinyusb_queue_busy.test_and_set(std::memory_order_acquire)) {
|
||||
noteDropped(size);
|
||||
return 0;
|
||||
}
|
||||
size_t written = 0;
|
||||
if (canQueue()) {
|
||||
const size_t available = esp32_tinyusb_text_queue.availableForWrite();
|
||||
if (!Diagnostic || (available >= esp32_tinyusb_functional_reserve
|
||||
&& size <= available - esp32_tinyusb_functional_reserve)) {
|
||||
written = esp32_tinyusb_text_queue.write(data, size);
|
||||
}
|
||||
}
|
||||
if (written != size) noteDropped(size - written);
|
||||
esp32_tinyusb_queue_busy.clear(std::memory_order_release);
|
||||
return written;
|
||||
}
|
||||
|
||||
private:
|
||||
bool canQueue() const {
|
||||
return canAccessEsp32TinyUsb(nullptr)
|
||||
&& (Diagnostic ? isUsbLoggingEnabled()
|
||||
: !esp32_tinyusb_terminal_discard_pending.load(
|
||||
std::memory_order_acquire));
|
||||
}
|
||||
void noteDropped(size_t size) {
|
||||
if (!Diagnostic && !xPortInIsrContext() && tud_cdc_n_connected(0)) {
|
||||
esp32_tinyusb_terminal_dropped_bytes.fetch_add(
|
||||
static_cast<uint32_t>(size), std::memory_order_relaxed);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
static Esp32TinyUsbBufferedStream<true> buffered_esp32_tinyusb_logging_port;
|
||||
static Esp32TinyUsbBufferedStream<false> buffered_esp32_tinyusb_terminal_port;
|
||||
|
||||
static void clearEsp32TinyUsbTx(void*) {
|
||||
(void)tud_cdc_n_write_clear(0);
|
||||
}
|
||||
|
||||
static void serviceEsp32TinyUsbPorts() {
|
||||
if (xPortInIsrContext()) return;
|
||||
if (esp32_tinyusb_queue_busy.test_and_set(std::memory_order_acquire)) return;
|
||||
// Polling also catches a physical disconnect without a CDC line-state
|
||||
// event. Events capture quick close/reopen pairs between service calls.
|
||||
const bool connected = tud_cdc_n_connected(0);
|
||||
if (esp32_tinyusb_was_connected && !connected) {
|
||||
esp32_tinyusb_reset_generation.fetch_add(1, std::memory_order_acq_rel);
|
||||
}
|
||||
esp32_tinyusb_was_connected = connected;
|
||||
const uint32_t generation =
|
||||
esp32_tinyusb_reset_generation.load(std::memory_order_acquire);
|
||||
if (generation != esp32_tinyusb_clean_generation.load(std::memory_order_acquire)) {
|
||||
if (!nonblocking_esp32_tinyusb_port.tryRunExclusive(clearEsp32TinyUsbTx)) {
|
||||
esp32_tinyusb_queue_busy.clear(std::memory_order_release);
|
||||
return;
|
||||
}
|
||||
esp32_tinyusb_text_queue.discardPending();
|
||||
esp32_tinyusb_terminal_reported_dropped_bytes =
|
||||
esp32_tinyusb_terminal_dropped_bytes.load(std::memory_order_relaxed);
|
||||
// Do not purge Serial's RX queue here: the new host may already have sent
|
||||
// its first query. Protocol owners reset their partial parser separately.
|
||||
esp32_tinyusb_clean_generation.store(generation, std::memory_order_release);
|
||||
}
|
||||
if (esp32_tinyusb_terminal_discard_pending.exchange(false,
|
||||
std::memory_order_acq_rel)) {
|
||||
esp32_tinyusb_text_queue.discardPending();
|
||||
esp32_tinyusb_terminal_reported_dropped_bytes =
|
||||
esp32_tinyusb_terminal_dropped_bytes.load(std::memory_order_relaxed);
|
||||
}
|
||||
if (canAccessEsp32TinyUsb(nullptr)) {
|
||||
esp32_tinyusb_text_queue.service();
|
||||
const uint32_t dropped =
|
||||
esp32_tinyusb_terminal_dropped_bytes.load(std::memory_order_relaxed);
|
||||
if (dropped != esp32_tinyusb_terminal_reported_dropped_bytes
|
||||
&& esp32_tinyusb_text_queue.availableForWrite() >= 96) {
|
||||
char marker[96];
|
||||
const int length = snprintf(marker, sizeof(marker),
|
||||
"\r\n[USB terminal output dropped %lu bytes]\r\n",
|
||||
static_cast<unsigned long>(
|
||||
dropped - esp32_tinyusb_terminal_reported_dropped_bytes));
|
||||
if (length > 0 && static_cast<size_t>(length) < sizeof(marker)
|
||||
&& esp32_tinyusb_text_queue.write(
|
||||
reinterpret_cast<const uint8_t*>(marker), length)
|
||||
== static_cast<size_t>(length)) {
|
||||
esp32_tinyusb_terminal_reported_dropped_bytes = dropped;
|
||||
}
|
||||
}
|
||||
}
|
||||
esp32_tinyusb_queue_busy.clear(std::memory_order_release);
|
||||
}
|
||||
#endif
|
||||
|
||||
#if MESH_ESP32_HWCDC_SESSION_GUARD
|
||||
// Every primary HWCDC role shares one producer gate. In particular, returning
|
||||
// this facade from usbLoggingPort() means a task which cached its Stream& before
|
||||
@@ -317,7 +524,13 @@ static uint32_t primary_usb_terminal_taken_reset_generation = 0;
|
||||
#endif
|
||||
|
||||
static void setPlatformDebugOutputEnabled(bool enabled) {
|
||||
#if defined(ESP32_PLATFORM) && defined(ENABLE_USB_INTERFACE)
|
||||
#if MESH_ESP32_TINYUSB_NONBLOCKING
|
||||
// The framework putc hook bypasses the common producer gate. MeshCore
|
||||
// diagnostics remain enabled through usbLoggingPort(); keep raw framework
|
||||
// bytes from racing a binary mOTA/Companion record's capacity preflight.
|
||||
(void)enabled;
|
||||
Serial.setDebugOutput(false);
|
||||
#elif 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.
|
||||
#if MESH_ESP32_HWCDC_SESSION_GUARD
|
||||
@@ -549,9 +762,18 @@ bool isUsbLoggingEnabled() {
|
||||
}
|
||||
|
||||
void setUsbLoggingEnabled(bool enabled) {
|
||||
#if MESH_ESP32_TINYUSB_NONBLOCKING
|
||||
const bool was_enabled = isUsbLoggingEnabled();
|
||||
#endif
|
||||
usb_logging_enabled.store(enabled, std::memory_order_relaxed);
|
||||
usb_logging_preference_known.store(true, std::memory_order_relaxed);
|
||||
setPlatformDebugOutputEnabled(enabled);
|
||||
#if MESH_ESP32_TINYUSB_NONBLOCKING
|
||||
// Text shares one chronological queue. When leaving logging mode, discard
|
||||
// its residual application bytes before later Binary/mOTA traffic can start.
|
||||
// An in-flight producer is gated immediately and cleaned by the next service.
|
||||
if (was_enabled && !enabled) discardUsbTerminalOutput();
|
||||
#endif
|
||||
}
|
||||
|
||||
bool saveUsbLoggingBootPreference(bool enabled) {
|
||||
@@ -573,6 +795,12 @@ void beginUsbLoggingPort() {
|
||||
// ESP32 Companion stream; setUsbLoggingEnabled() restores them only when the
|
||||
// saved setting explicitly enables logging.
|
||||
setPlatformDebugOutputEnabled(isUsbLoggingEnabled());
|
||||
#if MESH_ESP32_TINYUSB_NONBLOCKING
|
||||
if (!esp32_tinyusb_event_handler_registered) {
|
||||
Serial.onEvent(ARDUINO_USB_CDC_ANY_EVENT, handleEsp32TinyUsbEvent);
|
||||
esp32_tinyusb_event_handler_registered = true;
|
||||
}
|
||||
#endif
|
||||
#if MESH_ESP32_HWCDC_SESSION_GUARD
|
||||
if (!esp32_hwcdc_event_handler_registered) {
|
||||
Serial.onEvent(ARDUINO_HW_CDC_ANY_EVENT, handleEsp32HwcdcEvent);
|
||||
@@ -603,6 +831,9 @@ void beginUsbLoggingPort() {
|
||||
}
|
||||
|
||||
void serviceUsbLoggingPort() {
|
||||
#if MESH_ESP32_TINYUSB_NONBLOCKING
|
||||
serviceEsp32TinyUsbPorts();
|
||||
#endif
|
||||
#if defined(MESH_DUAL_CDC_LOGGING)
|
||||
const bool connected = dedicated_usb_logging_port_started
|
||||
&& dedicated_usb_logging_port.dtr();
|
||||
@@ -702,7 +933,12 @@ static void purgeEsp32HwcdcQueues(void* opaque) {
|
||||
#endif
|
||||
|
||||
bool resetUsbCompanionTransport() {
|
||||
#if MESH_ESP32_HWCDC_SESSION_GUARD
|
||||
#if MESH_ESP32_TINYUSB_NONBLOCKING
|
||||
esp32_tinyusb_reset_generation.fetch_add(1, std::memory_order_acq_rel);
|
||||
serviceEsp32TinyUsbPorts();
|
||||
return esp32_tinyusb_clean_generation.load(std::memory_order_acquire)
|
||||
== esp32_tinyusb_reset_generation.load(std::memory_order_acquire);
|
||||
#elif MESH_ESP32_HWCDC_SESSION_GUARD
|
||||
// HWCDC owns RTOS queues, a TX mutex, an ISR, and an event task. Calling
|
||||
// end()/begin() here can delete those objects while a WiFi/MQTT/diagnostic
|
||||
// producer is writing. Close the independent transport gate first. Runtime
|
||||
@@ -776,7 +1012,9 @@ Stream& usbLoggingPort() {
|
||||
return null_usb_logging_stream;
|
||||
#else
|
||||
if (!isUsbLoggingEnabled()) return null_usb_logging_stream;
|
||||
#if MESH_ESP32_HWCDC_SESSION_GUARD
|
||||
#if MESH_ESP32_TINYUSB_NONBLOCKING
|
||||
return buffered_esp32_tinyusb_logging_port;
|
||||
#elif MESH_ESP32_HWCDC_SESSION_GUARD
|
||||
return guarded_esp32_hwcdc_port;
|
||||
#elif defined(NRF52_PLATFORM)
|
||||
return nonblocking_primary_usb_logging_port;
|
||||
@@ -787,7 +1025,9 @@ Stream& usbLoggingPort() {
|
||||
}
|
||||
|
||||
Stream& usbCompanionPort() {
|
||||
#if MESH_ESP32_HWCDC_SESSION_GUARD
|
||||
#if MESH_ESP32_TINYUSB_NONBLOCKING
|
||||
return nonblocking_esp32_tinyusb_port;
|
||||
#elif MESH_ESP32_HWCDC_SESSION_GUARD
|
||||
return guarded_esp32_hwcdc_port;
|
||||
#elif MESH_NRF52_PRIMARY_USB_NONBLOCKING
|
||||
return nonblocking_primary_usb_companion_port;
|
||||
@@ -797,7 +1037,9 @@ Stream& usbCompanionPort() {
|
||||
}
|
||||
|
||||
Stream& usbMotaPort() {
|
||||
#if MESH_ESP32_HWCDC_SESSION_GUARD
|
||||
#if MESH_ESP32_TINYUSB_NONBLOCKING
|
||||
return nonblocking_esp32_tinyusb_mota_port;
|
||||
#elif MESH_ESP32_HWCDC_SESSION_GUARD
|
||||
return guarded_esp32_hwcdc_mota_port;
|
||||
#elif MESH_NRF52_PRIMARY_USB_NONBLOCKING
|
||||
return nonblocking_primary_usb_mota_port;
|
||||
@@ -807,15 +1049,36 @@ Stream& usbMotaPort() {
|
||||
}
|
||||
|
||||
Stream& usbTerminalPort() {
|
||||
#if defined(NRF52_PLATFORM) && defined(ENABLE_USB_INTERFACE)
|
||||
#if MESH_ESP32_TINYUSB_NONBLOCKING
|
||||
return buffered_esp32_tinyusb_terminal_port;
|
||||
#elif defined(NRF52_PLATFORM) && defined(ENABLE_USB_INTERFACE)
|
||||
return buffered_primary_usb_terminal_port;
|
||||
#else
|
||||
return usbCompanionPort();
|
||||
#endif
|
||||
}
|
||||
|
||||
Stream& usbConsolePort() {
|
||||
#if MESH_ESP32_TINYUSB_NONBLOCKING
|
||||
return buffered_esp32_tinyusb_terminal_port;
|
||||
#else
|
||||
return Serial;
|
||||
#endif
|
||||
}
|
||||
|
||||
bool canAcceptUsbConsoleCommand() {
|
||||
#if MESH_ESP32_TINYUSB_NONBLOCKING
|
||||
return buffered_esp32_tinyusb_terminal_port.availableForWrite()
|
||||
>= static_cast<int>(esp32_tinyusb_functional_reserve);
|
||||
#else
|
||||
return true;
|
||||
#endif
|
||||
}
|
||||
|
||||
void serviceUsbTerminalPort() {
|
||||
#if defined(NRF52_PLATFORM) && defined(ENABLE_USB_INTERFACE)
|
||||
#if MESH_ESP32_TINYUSB_NONBLOCKING
|
||||
serviceEsp32TinyUsbPorts();
|
||||
#elif defined(NRF52_PLATFORM) && defined(ENABLE_USB_INTERFACE)
|
||||
const uint32_t reset_generation =
|
||||
primaryUsbSessionGeneration();
|
||||
if (reset_generation != primary_usb_terminal_seen_reset_generation) {
|
||||
@@ -829,21 +1092,48 @@ void serviceUsbTerminalPort() {
|
||||
}
|
||||
|
||||
void discardUsbTerminalOutput() {
|
||||
#if defined(NRF52_PLATFORM) && defined(ENABLE_USB_INTERFACE)
|
||||
#if MESH_ESP32_TINYUSB_NONBLOCKING
|
||||
esp32_tinyusb_terminal_discard_pending.store(true, std::memory_order_release);
|
||||
if (esp32_tinyusb_queue_busy.test_and_set(std::memory_order_acquire)) return;
|
||||
esp32_tinyusb_text_queue.discardPending();
|
||||
esp32_tinyusb_terminal_reported_dropped_bytes =
|
||||
esp32_tinyusb_terminal_dropped_bytes.load(std::memory_order_relaxed);
|
||||
esp32_tinyusb_terminal_discard_pending.store(false, std::memory_order_release);
|
||||
esp32_tinyusb_queue_busy.clear(std::memory_order_release);
|
||||
#elif defined(NRF52_PLATFORM) && defined(ENABLE_USB_INTERFACE)
|
||||
buffered_primary_usb_terminal_port.discardPending();
|
||||
#endif
|
||||
}
|
||||
|
||||
bool hasPendingUsbTerminalOutput() {
|
||||
#if defined(NRF52_PLATFORM) && defined(ENABLE_USB_INTERFACE)
|
||||
#if MESH_ESP32_TINYUSB_NONBLOCKING
|
||||
if (esp32_tinyusb_queue_busy.test_and_set(std::memory_order_acquire)) return true;
|
||||
const bool pending = esp32_tinyusb_text_queue.queuedByteCount() != 0;
|
||||
esp32_tinyusb_queue_busy.clear(std::memory_order_release);
|
||||
return pending;
|
||||
#elif defined(NRF52_PLATFORM) && defined(ENABLE_USB_INTERFACE)
|
||||
return buffered_primary_usb_terminal_port.queuedByteCount() != 0;
|
||||
#else
|
||||
return false;
|
||||
#endif
|
||||
}
|
||||
|
||||
uint32_t usbTerminalDroppedBytes() {
|
||||
#if MESH_ESP32_TINYUSB_NONBLOCKING
|
||||
return esp32_tinyusb_terminal_dropped_bytes.load(std::memory_order_relaxed);
|
||||
#else
|
||||
return 0;
|
||||
#endif
|
||||
}
|
||||
|
||||
bool takeUsbTerminalSessionReset() {
|
||||
#if defined(NRF52_PLATFORM) && defined(ENABLE_USB_INTERFACE)
|
||||
#if MESH_ESP32_TINYUSB_NONBLOCKING
|
||||
const uint32_t reset_generation =
|
||||
esp32_tinyusb_reset_generation.load(std::memory_order_acquire);
|
||||
if (reset_generation == esp32_tinyusb_taken_reset_generation) return false;
|
||||
esp32_tinyusb_taken_reset_generation = reset_generation;
|
||||
return true;
|
||||
#elif defined(NRF52_PLATFORM) && defined(ENABLE_USB_INTERFACE)
|
||||
const uint32_t reset_generation =
|
||||
primaryUsbSessionGeneration();
|
||||
if (reset_generation == primary_usb_terminal_taken_reset_generation) {
|
||||
@@ -881,7 +1171,11 @@ static void completePrimaryUsbSessionReset(void*) {
|
||||
#endif
|
||||
|
||||
bool tryCompleteUsbTerminalSessionReset() {
|
||||
#if defined(NRF52_PLATFORM) && defined(ENABLE_USB_INTERFACE)
|
||||
#if MESH_ESP32_TINYUSB_NONBLOCKING
|
||||
serviceEsp32TinyUsbPorts();
|
||||
return esp32_tinyusb_clean_generation.load(std::memory_order_acquire)
|
||||
== esp32_tinyusb_reset_generation.load(std::memory_order_acquire);
|
||||
#elif defined(NRF52_PLATFORM) && defined(ENABLE_USB_INTERFACE)
|
||||
const uint32_t settle_until =
|
||||
primary_usb_reset_settle_until.load(std::memory_order_acquire);
|
||||
if ((int32_t)(millis() - settle_until) < 0) return false;
|
||||
|
||||
@@ -14,6 +14,16 @@
|
||||
#if defined(ARDUINO)
|
||||
#include <Arduino.h>
|
||||
|
||||
// ESP32-S2/S3 native USB CDC uses USBCDC, not the hardware USB-Serial-JTAG
|
||||
// driver. Its write timeout only bounds a mutex, not waiting for FIFO space.
|
||||
// All roles sharing this CDC therefore need the single-attempt transport.
|
||||
#if defined(ESP32) && defined(ARDUINO_USB_MODE) && ARDUINO_USB_MODE == 0 \
|
||||
&& defined(ARDUINO_USB_CDC_ON_BOOT) && ARDUINO_USB_CDC_ON_BOOT
|
||||
#define MESH_ESP32_TINYUSB_NONBLOCKING 1
|
||||
#else
|
||||
#define MESH_ESP32_TINYUSB_NONBLOCKING 0
|
||||
#endif
|
||||
|
||||
namespace mesh {
|
||||
|
||||
#ifndef MESH_ESP32_USB_TX_BUFFER_SIZE
|
||||
@@ -59,11 +69,12 @@ void beginUsbLoggingPort();
|
||||
// such as /dev/ttyACM1 or COM7.
|
||||
void serviceUsbLoggingPort();
|
||||
Stream& usbLoggingPort();
|
||||
// Primary USB Companion data stream. On nRF52 this uses one direct TinyUSB
|
||||
// FIFO attempt per write so a host-side open/close race cannot trap the main
|
||||
// loop in Adafruit_USBD_CDC::write(). Other platforms retain Serial.
|
||||
// Primary USB Companion data stream. Native TinyUSB on nRF52 and ESP32 uses
|
||||
// one FIFO attempt per write, never the framework's wait-for-space loop.
|
||||
// Callers retain and retry unwritten suffixes. Other platforms retain Serial
|
||||
// or their hardware-CDC session facade.
|
||||
Stream& usbCompanionPort();
|
||||
// Serial mOTA requests are binary records of at most 11 bytes. On nRF52 this
|
||||
// Serial mOTA requests are binary records of at most 11 bytes. On TinyUSB this
|
||||
// facade admits a request only when the complete record fits in CDC0's current
|
||||
// TX capacity, so a retry can never append to a prefix from the prior attempt.
|
||||
Stream& usbMotaPort();
|
||||
@@ -72,11 +83,21 @@ Stream& usbMotaPort();
|
||||
// it from the application loop; discard it before changing the CDC protocol or
|
||||
// after a host disconnect so stale text cannot prefix a later Binary session.
|
||||
Stream& usbTerminalPort();
|
||||
// Repeater/room-server console: protect ESP32 TinyUSB while preserving the
|
||||
// historical raw Serial behavior of other platforms and roles.
|
||||
Stream& usbConsolePort();
|
||||
// Diagnostic backlog alone must not starve console input. Native ESP32 CDC
|
||||
// admits another command when its reserved functional capacity is available;
|
||||
// other platforms preserve their existing command-processing policy.
|
||||
bool canAcceptUsbConsoleCommand();
|
||||
void serviceUsbTerminalPort();
|
||||
void discardUsbTerminalOutput();
|
||||
bool hasPendingUsbTerminalOutput();
|
||||
// Bytes refused while an ESP32 TinyUSB terminal host was connected. A visible
|
||||
// overflow marker is emitted once queue capacity recovers; other ports return 0.
|
||||
uint32_t usbTerminalDroppedBytes();
|
||||
// Consume a primary-USB session boundary reported by the USB owner task:
|
||||
// CDC0 DTR-low on nRF52, or a hardware CDC bus reset on ESP32. This is
|
||||
// CDC0 DTR-low on TinyUSB, or a hardware CDC bus reset on ESP32. This is
|
||||
// independent of polling current line/SOF state; ESP32 retains that poll as a
|
||||
// fallback because its bundled framework event queue is finite.
|
||||
bool takeUsbTerminalSessionReset();
|
||||
|
||||
@@ -23,8 +23,10 @@
|
||||
#endif
|
||||
#if defined(OTA_FOLDER_SERIAL)
|
||||
#include "MotaSourceSerial.h" // relay an external folder served by a host daemon over the USB serial
|
||||
#include "../UsbLogging.h"
|
||||
#ifndef OTA_FOLDER_SERIAL_STREAM
|
||||
#if defined(NRF52_PLATFORM) \
|
||||
|| MESH_ESP32_TINYUSB_NONBLOCKING \
|
||||
|| (defined(ESP32) && defined(ARDUINO_USB_MODE) \
|
||||
&& ARDUINO_USB_MODE == 1 \
|
||||
&& defined(ARDUINO_USB_CDC_ON_BOOT) \
|
||||
@@ -33,7 +35,6 @@
|
||||
// Native USB serial-folder requests share the primary session facade.
|
||||
// It prevents a host reset from racing a cached mOTA Stream reference;
|
||||
// dedicated-UART overrides retain their normal stream.
|
||||
#include "../UsbLogging.h"
|
||||
#define OTA_FOLDER_SERIAL_STREAM ::mesh::usbMotaPort()
|
||||
#define MESH_OTA_FOLDER_SERIAL_NONBLOCKING_USB 1
|
||||
#else
|
||||
|
||||
Reference in new issue
Block a user