Harden USB logging and persist watchdog events in management reports

This commit is contained in:
mikecarper committed 2026-10-03 15:29:19 -07:00
1 parent bd55369aa9
commit 3add4695cc
98 files changed
+7207 -372

No files matched your search

@@ -8,6 +8,7 @@ using esp_event_handler_t = void (*)(void*, esp_event_base_t, int32_t, void*);
constexpr int ARDUINO_USB_CDC_ANY_EVENT = -1;
constexpr int ARDUINO_USB_CDC_DISCONNECTED_EVENT = 1;
constexpr int ARDUINO_USB_CDC_LINE_STATE_EVENT = 2;
constexpr int ARDUINO_USB_CDC_TX_EVENT = 3;
struct arduino_usb_cdc_event_data_t {
struct { bool dtr; bool rts; } line_state{};
};
@@ -35,6 +36,7 @@ class MockSerial : public Stream {
assert(false && "mode0 must never call USBCDC::flush");
}
void setDebugOutput(bool enabled) { debug_enabled = enabled; }
void setTxTimeoutMs(unsigned timeout) { tx_timeout_ms = timeout; }
void onEvent(int event, esp_event_handler_t handler) {
assert(event == ARDUINO_USB_CDC_ANY_EVENT);
callback = handler;
@@ -44,6 +46,7 @@ class MockSerial : public Stream {
int rx_count = 0;
int registrations = 0;
bool debug_enabled = true;
unsigned tx_timeout_ms = 99;
esp_event_handler_t callback = nullptr;
};
@@ -7,3 +7,6 @@ uint32_t tud_cdc_n_write_available(uint8_t instance);
uint32_t tud_cdc_n_write(uint8_t instance, const void* data, uint32_t size);
uint32_t tud_cdc_n_write_flush(uint8_t instance);
bool tud_cdc_n_write_clear(uint8_t instance);
bool tud_mounted();
bool tud_connect();
bool tud_disconnect();
@@ -3,10 +3,15 @@
#include <iostream>
#include <string>
#include "helpers/UsbLogging.h"
#include "helpers/UsbLoggingClientActivity.h"
#include "MeshCore.h"
#include "helpers/SerialPacketLog.h"
MockSerial Serial;
static bool connected = true;
static bool mounted = true;
static unsigned disconnect_calls = 0;
static unsigned connect_calls = 0;
static bool auto_drain = false;
static std::string fifo;
static std::string host;
@@ -15,6 +20,10 @@ static unsigned flush_calls = 0;
static unsigned clear_calls = 0;
static void (*during_write)() = nullptr;
bool tud_mounted() { return mounted; }
bool tud_disconnect() { ++disconnect_calls; mounted = false; connected = false; return true; }
bool tud_connect() { ++connect_calls; return true; }
bool tud_cdc_n_connected(uint8_t instance) {
assert(!mock_isr);
assert(instance == 0);
@@ -82,6 +91,50 @@ static void fresh_session() {
auto_drain = false;
}
static void check_logging_watchdog_transport_observations_and_recovery() {
fresh_session();
mesh::setUsbLoggingEnabled(true);
const auto initial = mesh::observeUsbLoggingTransport();
assert(initial.supported && initial.host_connected && initial.reader_connected);
assert(!initial.pending);
assert(!mesh::isUsbLoggingClientActive()); // An open CDC is not an app poll.
mesh::noteUsbLoggingStatsCommand("stats-core");
assert(mesh::isUsbLoggingClientActive());
fresh_session(); // Even a close/reopen between service calls revokes it.
assert(!mesh::isUsbLoggingClientActive());
mesh::noteUsbLoggingStatsCommand("stats-radio");
mesh::setUsbLoggingEnabled(false);
assert(!mesh::isUsbLoggingClientActive());
mesh::setUsbLoggingEnabled(true);
mesh::probeUsbLoggingTransport();
const auto queued = mesh::observeUsbLoggingTransport();
assert(queued.pending && queued.tx_progress == initial.tx_progress);
assert(mesh::recoverUsbLoggingTransport(1) == mesh::UsbLoggingRecoveryResult::Attempted);
// Purge and probe merely change queues; neither is host acknowledgement.
assert(mesh::observeUsbLoggingTransport().tx_progress == initial.tx_progress);
host += fifo; fifo.clear();
Serial.callback(nullptr, nullptr, ARDUINO_USB_CDC_TX_EVENT, nullptr);
const auto completed = mesh::observeUsbLoggingTransport();
assert(completed.tx_progress == initial.tx_progress + 1);
assert(!completed.pending);
const auto detached_at = millis();
assert(mesh::recoverUsbLoggingTransport(2) == mesh::UsbLoggingRecoveryResult::Attempted);
assert(disconnect_calls == 1 && connect_calls == 0);
assert(millis() == detached_at); // No blocking wait or descriptor rebuild.
g_mock_millis += 49;
mesh::serviceUsbLoggingPort();
assert(connect_calls == 0);
++g_mock_millis;
mesh::serviceUsbLoggingPort();
assert(connect_calls == 1 && !mesh::observeUsbLoggingTransport().host_connected);
mock_isr = true;
assert(mesh::recoverUsbLoggingTransport(1) == mesh::UsbLoggingRecoveryResult::Deferred);
mesh::probeUsbLoggingTransport();
mock_isr = false;
mounted = connected = true;
fresh_session();
}
static void check_native_short_writes_and_mota() {
const unsigned before = write_calls;
assert(put(mesh::usbCompanionPort(), std::string(200, 'B')) == 64);
@@ -150,6 +203,7 @@ static void check_disconnect_cleanup_keeps_new_host_input() {
}
static void check_debug_formatter_and_reentrancy() {
mesh::setUsbDebugEnabled(true);
auto_drain = true;
const std::string long_text(1000, 'D');
assert(mesh::nrf52DebugPrintf("%s\n", long_text.c_str()) == 255);
@@ -165,6 +219,39 @@ static void check_debug_formatter_and_reentrancy() {
drain_all();
assert(host == "outer\n");
fresh_session();
mesh::setUsbDebugEnabled(false);
}
static void check_independent_debug_gate() {
assert(!mesh::isUsbDebugEnabled());
assert(mesh::isUsbLoggingEnabled());
const auto before = write_calls;
MESH_DEBUG_PRINTLN("default-off debug");
assert(mesh::nrf52DebugPrintf("also quiet\n") == 0);
assert(write_calls == before && !mesh::hasPendingUsbTerminalOutput());
mesh::SerialLogLine<> raw;
raw.printf("12:34:56 - 3/10/2026 U RAW: 0102");
assert(raw.flush(mesh::usbLoggingPort()));
drain_all();
assert(host == "12:34:56 - 3/10/2026 U RAW: 0102\r\n");
fresh_session();
mesh::setUsbDebugEnabled(true);
assert(mesh::isUsbDebugEnabled() && mesh::isUsbDebugLoggingEnabled());
MESH_DEBUG_PRINTLN("explicit debug");
drain_all();
assert(host == "DEBUG: explicit debug\n");
fresh_session();
mesh::setUsbLoggingEnabled(false);
assert(mesh::isUsbDebugEnabled() && !mesh::isUsbDebugLoggingEnabled());
const auto gated = write_calls;
MESH_DEBUG_PRINTLN("master is off");
assert(write_calls == gated && !mesh::hasPendingUsbTerminalOutput());
mesh::setUsbLoggingEnabled(true);
assert(mesh::isUsbDebugLoggingEnabled());
mesh::setUsbDebugEnabled(false);
assert(mesh::isUsbLoggingEnabled() && !mesh::isUsbDebugLoggingEnabled());
assert(!Serial.debug_enabled); // native raw framework output stays forbidden
}
static void check_cached_logging_gate_and_isr() {
@@ -215,6 +302,8 @@ int main() {
assert(!Serial.debug_enabled);
mesh::serviceUsbLoggingPort();
assert(&mesh::usbConsolePort() == &mesh::usbTerminalPort());
check_logging_watchdog_transport_observations_and_recovery();
check_independent_debug_gate();
check_native_short_writes_and_mota();
check_ordered_text_and_functional_reserve();
check_stalled_host_and_visible_overflow();
@@ -227,6 +316,9 @@ int main() {
assert(&mesh::usbConsolePort() == &Serial);
assert(mesh::canAcceptUsbConsoleCommand());
assert(mesh::usbTerminalDroppedBytes() == 0);
assert(!mesh::observeUsbLoggingTransport().supported);
assert(mesh::recoverUsbLoggingTransport(1) == mesh::UsbLoggingRecoveryResult::Unsupported);
mesh::probeUsbLoggingTransport();
#endif
std::cout << "ESP32 TinyUSB transport checks passed\n";
}
+84 -13
View File
@@ -19,7 +19,7 @@ int main() {
assert(equal(tag, hex("85632d07c6e8f37f950acd320a2ecc93").data(), 16));
assert(p == hex("40c02b9690c4dc04daef7f6afe5c"));
assert(open(k.data(), ad.data(), ad.size(), p.data(), p.size(), tag)); assert(p == plain);
for (size_t n : {size_t(0), size_t(1), size_t(15), size_t(16), size_t(17), size_t(78), size_t(177)}) {
for (size_t n : {size_t(0), size_t(1), size_t(15), size_t(16), size_t(17), size_t(78), size_t(177), MAX_PAYLOAD}) {
std::vector<uint8_t> b(n, 0x39), original = b;
assert(seal(k.data(), ad.data(), ad.size(), b.data(), n, tag));
assert(open(k.data(), ad.data(), ad.size(), b.data(), n, tag)); assert(b == original);
@@ -27,7 +27,7 @@ int main() {
assert(!open(k.data(), ad.data(), ad.size(), b.data(), n, tag));
for (uint8_t c : b) assert(c == 0);
}
assert(!seal(k.data(), ad.data(), ad.size(), p.data(), 178, tag));
assert(!seal(k.data(), ad.data(), ad.size(), p.data(), MAX_PAYLOAD + 1, tag));
History history;
history.sample(0, 3900, -4); history.sample(59, 3100, 98);
assert(history.week().voltage == 3100 && history.week().high == temperature(98));
@@ -58,18 +58,89 @@ int main() {
assert(acl.count == 1 && acl.entries[0][12] == 3);
for (uint8_t i = 1; i < MAX_KEYS; ++i) { token[0] = i; assert(acl.add(token, ADMIN)); }
token[0] = 240; assert(!acl.add(token, ADMIN)); assert(acl.pages() == MAX_PAGES);
// Emit cross-language packets with all header fields and maximum ACL pages.
for (uint8_t page = 0; page < acl.pages(); ++page) {
uint8_t raw[MAX_PAYLOAD] = {}, enc[32]; memcpy(raw, "MGR1", 4); memcpy(raw + 4, radio, 16);
write32(raw + 20, 42); write32(raw + 28, 0x01110105); write16(raw + 76, FIRMWARE);
raw[71] = 5; raw[78] = page; raw[79] = acl.pages(); raw[80] = acl.count;
raw[81] = page * PER_PAGE; raw[82] = PER_PAGE;
memcpy(raw + HEADER, acl.entries[page * PER_PAGE], PER_PAGE * ENTRY);
mesh::UsbLoggingStatus usb;
usb.supported = usb.logging_enabled = usb.watchdog_enabled = true;
usb.host_connected = usb.reader_connected = usb.logger_active = true;
usb.stalled = usb.recovering = usb.recovery_deferred = usb.persistence_ready = true;
usb.watchdog_auto = true; usb.auto_connected_seconds = 1209600;
usb.stage = 2; usb.backoff_step = 8; usb.retry_seconds = 604800;
usb.inactive_seconds = UINT32_MAX;
usb.last_event.reasons = 15;
usb.last_event.action = mesh::UsbLoggingWatchdogEvent::REBOOT_REQUESTED;
usb.last_event.epoch = 1700000001; usb.last_event.uptime_seconds = 777;
usb.last_event.sequence = 42; usb.last_event.persisted = true;
uint8_t usb_block[USB_STATUS_SIZE] = {};
encodeUsbStatus(usb_block, usb);
assert(read16(usb_block) == 2047 && usb_block[2] == (2 | (8 << 2)));
assert(read32(usb_block + 3) == 604800 && read32(usb_block + 7) == UINT32_MAX);
assert(read32(usb_block + 11) == 1209600);
usb.logger_active = false; encodeUsbStatus(usb_block, usb);
assert(read16(usb_block) == 1023); // host/reader connection does not imply a logger
usb.logger_active = true;
// Emit all wire versions for independent Python and browser decoders.
for (const char* magic : {"MGR1", "MGR2", "MGR3"}) {
const auto* version = reinterpret_cast<const uint8_t*>(magic);
const bool current = currentPage(version), has_usb = usbPage(version);
const size_t header = headerSize(version), per_page = entriesPerPage(version);
for (uint8_t page = 0; page < acl.pages(per_page); ++page) {
uint8_t raw[179] = {}, enc[32]; memcpy(raw, magic, 4);
memcpy(raw + 4, radio, 16);
write32(raw + 20, 42); write32(raw + 28, 0x01110105); write16(raw + 76, FIRMWARE);
raw[71] = 5; raw[78] = page; raw[79] = acl.pages(per_page); raw[80] = acl.count;
raw[81] = page * per_page;
raw[82] = acl.count - raw[81] < per_page ? acl.count - raw[81] : per_page;
if (has_usb) encodeUsbStatus(raw + HEADER, usb);
if (current) mesh::encodeUsbWatchdogEvent(raw + WATCHDOG_EVENT_OFFSET, usb.last_event);
const size_t private_len = raw[82] * ENTRY, size = header + private_len + TAG;
memcpy(raw + header, acl.entries[raw[81]], private_len);
deriveKey(root, "MeshCore-MGR1-SIV", radio, enc);
assert(seal(enc, raw, header, raw + header, private_len, raw + header + private_len));
assert(validPage(raw, size)); print(raw, size);
assert(size <= MAX_PAYLOAD && floodSize(size) <= 179);
assert(validPage(raw, floodSize(size), true));
if (floodSize(size) > size) {
raw[floodSize(size) - 1] ^= 1;
assert(!validPage(raw, floodSize(size), true)); raw[floodSize(size) - 1] ^= 1;
}
if (has_usb) {
raw[85] |= 0x40; assert(!validPage(raw, size)); raw[85] &= ~0x40;
raw[84] |= 0x08; assert(!validPage(raw, size)); raw[84] &= ~0x08;
}
if (current) {
const uint8_t original = raw[98];
for (uint8_t invalid : {uint8_t(original & 0xf0), uint8_t(original & 0x8f), uint8_t(0xdf)}) {
raw[98] = invalid; assert(!validPage(raw, size));
}
raw[98] = original;
write32(raw + 107, 0); assert(!validPage(raw, size)); write32(raw + 107, 42);
}
raw[81]++; assert(!validPage(raw, size)); raw[81]--;
assert(!validPage(raw, size - 1)); raw[80] = 37; assert(!validPage(raw, size));
}
}
// A current report with no recorded event is authenticated, not invented.
{
uint8_t raw[179] = {}, enc[32]; memcpy(raw, "MGR3", 4); memcpy(raw + 4, radio, 16);
write32(raw + 20, 43); raw[79] = 1;
deriveKey(root, "MeshCore-MGR1-SIV", radio, enc);
assert(seal(enc, raw, HEADER, raw + HEADER, PER_PAGE * ENTRY, raw + MAX_PAYLOAD - TAG));
assert(validPage(raw, sizeof(raw))); print(raw, sizeof(raw));
raw[81]++; assert(!validPage(raw, sizeof(raw))); raw[81]--;
assert(!validPage(raw, sizeof(raw) - 1)); raw[80] = 37; assert(!validPage(raw, sizeof(raw)));
assert(seal(enc, raw, CURRENT_HEADER, raw + CURRENT_HEADER, 0, raw + CURRENT_HEADER));
assert(validPage(raw, CURRENT_HEADER + TAG)); print(raw, CURRENT_HEADER + TAG);
}
// Every ACL count retains complete coverage and the unchanged flood ceiling.
for (unsigned total = 0; total <= MAX_KEYS; ++total) {
for (unsigned page = 0; page < (total ? (total + 3) / 4 : 1); ++page) {
uint8_t raw[179] = {}; memcpy(raw, "MGR3", 4);
raw[78] = page; raw[79] = total ? (total + 3) / 4 : 1; raw[80] = total;
raw[81] = page * 4; raw[82] = total - raw[81] < 4 ? total - raw[81] : 4;
const size_t size = pageSize(raw);
assert(validPage(raw, size) && floodSize(size) <= 179);
assert(validPage(raw, floodSize(size), true));
}
}
for (size_t n = 0; n < CURRENT_HEADER + TAG; ++n) {
std::vector<uint8_t> truncated(n);
for (size_t i = 0; i < n && i < 4; ++i) truncated[i] = "MGR3"[i];
assert(!validPage(truncated.data(), n));
}
for (size_t n = 0; n < HEADER + TAG; ++n) assert(!validPage(plain.data(), n));
}
+42 -3
View File
@@ -6,6 +6,11 @@
#include <string>
using namespace mesh;
using namespace mesh::management;
namespace mesh {
UsbLoggingStatus test_usb_status;
unsigned usb_status_calls = 0;
UsbLoggingStatus usbLoggingStatus() { ++usb_status_calls; return test_usb_status; }
}
struct Fixture {
MemoryFS fs;
Mesh mesh;
@@ -16,7 +21,7 @@ struct Fixture {
CommonCLI cli;
CommonCLICallbacks callbacks;
std::unique_ptr<ManagementReporter> reporter;
Fixture() { test_millis = 0; reboot(); }
Fixture() { test_millis = 0; test_usb_status = UsbLoggingStatus(); usb_status_calls = 0; reboot(); }
void reboot() { reporter.reset(); test_millis = 0; reporter.reset(new ManagementReporter(mesh, board, sensors, acl, prefs, callbacks, cli, &fs)); }
std::string cmd(const char* text, bool ok = true) {
char b[200], reply[160] = {}; strcpy(b, text);
@@ -100,23 +105,57 @@ int main() {
{
Fixture f;
for (unsigned i = 0; i < 36; ++i) { ClientInfo c; c.id.pub_key[0] = i; f.acl.clients.push_back(c); }
f.configure(false); f.advance(21 * DAY + 600); assert(f.mesh.packets.size() == 6);
for (unsigned i = 0; i < 6; ++i) {
test_usb_status.supported = true; test_usb_status.watchdog_enabled = true;
test_usb_status.host_connected = test_usb_status.reader_connected = true;
test_usb_status.stalled = true; test_usb_status.retry_seconds = 7200;
test_usb_status.inactive_seconds = 3600; test_usb_status.backoff_step = 1;
test_usb_status.last_event.reasons = UsbLoggingWatchdogEvent::TX_STALLED;
test_usb_status.last_event.action = UsbLoggingWatchdogEvent::REENUMERATE;
test_usb_status.last_event.sequence = 17; test_usb_status.last_event.uptime_seconds = 300;
test_usb_status.last_event.persisted = true;
f.configure(false); f.advance(21 * DAY + 600); assert(f.mesh.packets.size() == 9);
assert(usb_status_calls == 1);
for (unsigned i = 0; i < 9; ++i) {
const auto& p = f.mesh.packets[i]; assert(validPage(p.payload, p.payload_len));
assert(p.payload[78] == i && p.payload[80] == 36 && p.flood);
assert(!memcmp(p.payload, "MGR3", 4) && read16(p.payload + HEADER) == 61);
assert(!(read16(p.payload + HEADER) & 1024)); // an open reader is not an active logger
assert(read32(p.payload + HEADER + 3) == 7200);
assert(read32(p.payload + HEADER + 7) == 3600);
UsbLoggingWatchdogEvent event;
assert(decodeUsbWatchdogEvent(p.payload + WATCHDOG_EVENT_OFFSET, event));
assert(event.reasons == UsbLoggingWatchdogEvent::TX_STALLED && event.action == UsbLoggingWatchdogEvent::REENUMERATE);
assert(event.sequence == 17 && event.uptime_seconds == 300 && event.persisted && event.epoch == 0);
assert(floodSize(p.payload_len) <= 179);
}
}
{
Fixture f;
for (unsigned i = 0; i < 7; ++i) { ClientInfo c; c.id.pub_key[0] = i; f.acl.clients.push_back(c); }
f.configure(false); f.advance(21 * DAY); assert(f.mesh.packets.size() == 1);
assert(!memcmp(f.mesh.packets[0].payload, "MGR3", 4));
assert(read16(f.mesh.packets[0].payload + HEADER) == 0); // unsupported is explicit
test_usb_status.supported = true; test_usb_status.retry_seconds = 999;
test_usb_status.watchdog_auto = true; test_usb_status.auto_connected_seconds = 100;
test_usb_status.host_connected = test_usb_status.reader_connected = test_usb_status.logger_active = true;
test_usb_status.last_event.reasons = UsbLoggingWatchdogEvent::CLIENT_INACTIVE;
test_usb_status.last_event.action = UsbLoggingWatchdogEvent::SOFT_RECOVERY;
test_usb_status.last_event.sequence = 1; test_usb_status.last_event.epoch = 1700000001;
f.board.voltage = 2900; f.board.temperature = 60; f.advance(60);
assert(f.mesh.packets.size() == 2);
assert(read16(f.mesh.packets[1].payload + HEADER) == 0); // frozen report snapshot
assert(read32(f.mesh.packets[1].payload + HEADER + 11) == 0);
assert(read32(f.mesh.packets[1].payload + WATCHDOG_EVENT_OFFSET + 9) == 0);
assert(usb_status_calls == 1);
// The low reading was not in the first snapshot and must survive into the next one.
f.board.voltage = 3740; f.board.temperature = 24; f.advance(21 * DAY + 3600);
assert(f.mesh.packets.size() == 4);
assert(read16(f.mesh.packets.back().payload + 66) == 2900);
assert(f.mesh.packets.back().payload[69] == temperature(60));
assert(read16(f.mesh.packets.back().payload + HEADER) == 1561);
assert(read32(f.mesh.packets.back().payload + HEADER + 11) == 100);
assert(read32(f.mesh.packets.back().payload + WATCHDOG_EVENT_OFFSET + 9) == 1);
assert(usb_status_calls == 2);
}
{
Fixture f; f.configure(false); f.mesh.temp = true; f.advance(22 * DAY); assert(f.mesh.packets.empty());
@@ -0,0 +1,17 @@
#pragma once
#include <stdint.h>
#include "class/cdc/cdc.h"
#define CFG_TUD_CDC 1
#define CFG_TUD_CDC_TX_BUFSIZE 64
bool tud_mounted();
bool tud_connect();
bool tud_disconnect();
bool tud_cdc_n_connected(uint8_t);
uint32_t tud_cdc_n_available(uint8_t);
void tud_cdc_n_read_flush(uint8_t);
uint32_t tud_cdc_n_write_available(uint8_t);
uint32_t tud_cdc_n_write(uint8_t, const void*, uint32_t);
uint32_t tud_cdc_n_write_flush(uint8_t);
uint32_t tud_cdc_n_write_clear(uint8_t);
void tud_cdc_get_line_coding(cdc_line_coding_t*);
void TinyUSB_Port_EnterDFU();
+22
View File
@@ -0,0 +1,22 @@
#pragma once
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-parameter"
#pragma GCC diagnostic ignored "-Wsign-compare"
#include "../../../mocks/Arduino.h"
#pragma GCC diagnostic pop
#include <cassert>
uint32_t tud_cdc_n_write_available(uint8_t instance);
class MockSerial : public Stream {
public:
int available() override { return 0; }
int read() override { return -1; }
int peek() override { return -1; }
int availableForWrite() override { return tud_cdc_n_write_available(0); }
size_t write(const uint8_t*, size_t) override {
assert(false && "native nRF52 console must not use retrying Serial.write");
return 0;
}
void flush() override { assert(false && "console must not forward Serial.flush"); }
};
extern MockSerial Serial;
+3
View File
@@ -0,0 +1,3 @@
#pragma once
#include <stdint.h>
struct cdc_line_coding_t { uint32_t bit_rate; };
+131
View File
@@ -0,0 +1,131 @@
#include <Arduino.h>
#include <Adafruit_TinyUSB.h>
#include <helpers/UsbLogging.h>
#include <helpers/UsbLoggingClientActivity.h>
#include <cassert>
#include <cstdio>
#include <functional>
#include <string>
MockSerial Serial;
static bool mounted = true, dtr = true, dfu = false;
static uint32_t baud = 115200;
static std::string fifo, host;
static std::function<void()> during_write;
extern "C" void tud_cdc_line_state_cb(uint8_t, bool, bool);
extern "C" void tud_cdc_line_coding_cb(uint8_t, const cdc_line_coding_t*);
extern "C" void tud_cdc_tx_complete_cb(uint8_t);
extern "C" void tud_umount_cb();
bool tud_mounted() { return mounted; }
bool tud_connect() { mounted = true; return true; }
bool tud_disconnect() { mounted = false; dtr = false; return true; }
bool tud_cdc_n_connected(uint8_t n) { assert(n == 0); return mounted && dtr; }
uint32_t tud_cdc_n_available(uint8_t n) { assert(n == 0); return 0; }
void tud_cdc_n_read_flush(uint8_t n) { assert(n == 0); }
uint32_t tud_cdc_n_write_available(uint8_t n) { assert(n == 0); return 64 - fifo.size(); }
uint32_t tud_cdc_n_write(uint8_t n, const void* data, uint32_t size) {
assert(n == 0 && size <= 64 - fifo.size());
if (during_write) {
auto callback = std::move(during_write);
during_write = nullptr;
callback();
}
fifo.append(static_cast<const char*>(data), size);
return size;
}
uint32_t tud_cdc_n_write_flush(uint8_t n) { assert(n == 0); return 0; }
uint32_t tud_cdc_n_write_clear(uint8_t n) { assert(n == 0); fifo.clear(); return 0; }
void tud_cdc_get_line_coding(cdc_line_coding_t* coding) { coding->bit_rate = baud; }
void TinyUSB_Port_EnterDFU() { dfu = true; }
static void service() {
mesh::serviceUsbLoggingPort();
mesh::serviceUsbTerminalPort();
(void)mesh::takeUsbTerminalSessionReset();
g_mock_millis += 8;
assert(mesh::tryCompleteUsbTerminalSessionReset());
}
static void drain() {
for (unsigned i = 0; i < 200; ++i) {
if (!fifo.empty()) {
host += fifo;
fifo.clear();
tud_cdc_tx_complete_cb(0);
}
service(); // Exercise the actual every-loop completion path too.
if (fifo.empty() && !mesh::hasPendingUsbTerminalOutput()) return;
}
assert(false && "finite queue did not drain");
}
int main() {
static_assert(MESH_USB_CONSOLE_COOPERATIVE, "ordinary native nRF52 must cooperate");
mesh::setUsbLoggingEnabled(true);
tud_cdc_line_state_cb(0, true, false);
service();
auto& console = mesh::usbConsolePort();
const std::string reply = "-> " + std::string(200, 'R') + "\r\n";
assert(console.write(reinterpret_cast<const uint8_t*>(reply.data()), reply.size()) == reply.size());
assert(mesh::hasPendingUsbTerminalOutput());
for (unsigned i = 0; i < 5; ++i) service();
assert(fifo == reply.substr(0, 64)); // Clean epochs must not clear the FIFO.
assert(mesh::usbLoggingPort().write(reinterpret_cast<const uint8_t*>("LOG\r\n"), 5) == 5);
mesh::probeUsbLoggingTransport();
drain();
assert(host == reply + "LOG\r\n[USB watchdog] heartbeat\r\n");
host.clear();
const std::string raw = "RAW: " + std::string(512, 'A') + "\r\n";
assert(mesh::usbLoggingPort().write(reinterpret_cast<const uint8_t*>(raw.data()), raw.size()) == raw.size());
drain();
assert(host == raw); // Shared-queue capacity must not drop >256-byte RAW.
host.clear();
uint8_t stale_printf[256];
std::fill(stale_printf, stale_printf + 255, 'Z');
stale_printf[255] = 0;
assert(mesh::usbLoggingPort().write(stale_printf, 512) == 0); // No OOB read.
during_write = [] {
dtr = false;
tud_cdc_line_state_cb(0, false, false);
dtr = true;
tud_cdc_line_state_cb(0, true, false);
(void)mesh::takeUsbTerminalSessionReset();
g_mock_millis += 8;
// The old producer still owns the buffer and native writer gate.
assert(!mesh::tryCompleteUsbTerminalSessionReset());
};
assert(console.write(reinterpret_cast<const uint8_t*>(reply.data()), reply.size()) == reply.size());
service();
drain();
assert(host.empty()); // Failed busy purge must be retried before reopening.
// A DTR-high host that stops reading never forces a retry/flush wait.
fifo.assign(64, 'X');
const std::string record(100, 'D');
for (unsigned i = 0; i < 100; ++i)
mesh::usbLoggingPort().write(reinterpret_cast<const uint8_t*>(record.data()), record.size());
assert(console.availableForWrite() >= 3072 && mesh::canAcceptUsbConsoleCommand());
const std::string huge(4096, 'F');
assert(console.write(reinterpret_cast<const uint8_t*>(huge.data()), huge.size()) == 0);
for (unsigned i = 0; i < 10000; ++i) mesh::serviceUsbTerminalPort();
assert(fifo.size() == 64); // No progress invented by queue admission.
assert(mesh::observeUsbLoggingTransport().pending);
mesh::noteUsbLoggingStatsCommand("stats-core");
assert(mesh::isUsbLoggingClientActive());
dtr = false;
tud_cdc_line_state_cb(0, false, false);
dtr = true;
tud_cdc_line_state_cb(0, true, false);
service();
assert(!mesh::isUsbLoggingClientActive() && !mesh::hasPendingUsbTerminalOutput());
drain();
assert(host.empty()); // No old response/log leaks across rapid reopen.
mesh::noteUsbLoggingStatsCommand("stats-radio");
mounted = false;
tud_umount_cb();
assert(!mesh::isUsbLoggingClientActive());
mounted = true; dtr = true;
tud_cdc_line_state_cb(0, true, false);
service();
baud = 1200; dtr = false;
tud_cdc_line_state_cb(0, false, false);
assert(dfu); // Existing bootloader entry is preserved.
puts("native nRF52 console transport passed");
}
+8
View File
@@ -0,0 +1,8 @@
#pragma once
#include <stddef.h>
#include <stdint.h>
inline uint32_t mock_watchdog_millis = 0;
inline uint32_t millis() { return mock_watchdog_millis; }
class Stream { public: virtual ~Stream() = default; };
+98
View File
@@ -0,0 +1,98 @@
#pragma once
#include <algorithm>
#include <cerrno>
#include <cstdint>
#include <cstring>
#include <functional>
#include <map>
#include <string>
#include <vector>
namespace fs { class FS; }
class File {
public:
File() = default;
File(fs::FS* fs, std::string path, bool writable)
: _fs(fs), _path(std::move(path)), _writable(writable) {}
explicit operator bool() const { return _fs != nullptr; }
size_t size() const;
size_t read(uint8_t* buffer, size_t count);
size_t write(const uint8_t* buffer, size_t count);
void flush() {}
void close() { _fs = nullptr; }
private:
fs::FS* _fs = nullptr;
std::string _path;
size_t _offset = 0;
bool _writable = false;
};
namespace fs {
class FS {
public:
std::map<std::string, std::vector<uint8_t>> files;
std::string fail_stat, fail_open, short_read;
std::string fail_rename_from, fail_rename_to;
bool fail_write = false, fail_remove = false;
bool corrupt_final_image = false, fail_final_readback = false;
bool final_renamed = false;
unsigned writes = 0, write_opens = 0, renames = 0, removes = 0;
std::function<void()> after_final_rename;
bool exists(const char* path) const { return files.count(path) != 0; }
bool mkdir(const char*) { return true; }
File open(const char* path, const char* mode, bool = false) {
const bool writable = mode[0] == 'w';
if (fail_open == path || (!writable && fail_final_readback
&& final_renamed && std::string(path) == "/usb_wdg"))
return {};
if (writable) {
++write_opens;
files[path].clear();
} else if (!exists(path)) return {};
return File(this, path, writable);
}
bool remove(const char* path) {
++removes;
if (fail_remove) return false;
return files.erase(path) != 0;
}
bool rename(const char* from, const char* to) {
++renames;
if ((fail_rename_from == from && fail_rename_to == to)
|| !exists(from) || exists(to)) return false;
files[to] = std::move(files[from]);
files.erase(from);
if (std::string(from) == "/usb_wdg.tmp" && std::string(to) == "/usb_wdg") {
final_renamed = true;
if (corrupt_final_image) files[to][0] ^= 1;
if (after_final_rename) after_final_rename();
}
return true;
}
};
inline FS* stat_filesystem = nullptr;
} // namespace fs
inline size_t File::size() const {
return _fs ? _fs->files.at(_path).size() : 0;
}
inline size_t File::read(uint8_t* buffer, size_t count) {
if (!_fs || _writable) return 0;
const auto& bytes = _fs->files.at(_path);
size_t available = std::min(count, bytes.size() - _offset);
if (_fs->short_read == _path && available) --available;
std::memcpy(buffer, bytes.data() + _offset, available);
_offset += available;
return available;
}
inline size_t File::write(const uint8_t* buffer, size_t count) {
if (!_fs || !_writable) return 0;
++_fs->writes;
if (_fs->fail_write) return 0;
auto& bytes = _fs->files.at(_path);
bytes.insert(bytes.end(), buffer, buffer + count);
return count;
}
+2
View File
@@ -0,0 +1,2 @@
#pragma once
namespace mesh { struct LocalIdentity {}; }
@@ -0,0 +1,23 @@
#pragma once
#include <stddef.h>
namespace mesh { namespace ota {
struct OtaManager {
enum State { IDLE, FAILED, FETCHING, VERIFYING, COMPLETE };
State state = IDLE;
size_t serve_jobs = 0, manifest_jobs = 0;
State fetchState() const { return state; }
size_t pendingServeJobs() const { return serve_jobs; }
size_t pendingManifestJobs() const { return manifest_jobs; }
};
struct OtaContext {
OtaManager manager;
bool apply_pending = false, bootloader_apply_pending = false;
bool folder_active = false, folder_dest = false, capture_waiting = false;
bool serving = false, serve_expected = false;
bool folderCaptureWaiting() const { return capture_waiting; }
};
inline OtaContext* test_ota_context = nullptr;
inline const OtaContext* ota_context_if_active() { return test_ota_context; }
} } // namespace mesh::ota
+19
View File
@@ -0,0 +1,19 @@
#pragma once
#include <FS.h>
struct stat { size_t st_size = 0; };
inline int stat(const char* absolute, struct stat* info) {
const std::string prefix = "/spiffs";
const std::string path(absolute);
if (!fs::stat_filesystem || path.compare(0, prefix.size(), prefix)) {
errno = EIO;
return -1;
}
const auto relative = path.substr(prefix.size());
if (fs::stat_filesystem->fail_stat == relative) { errno = EIO; return -1; }
const auto found = fs::stat_filesystem->files.find(relative);
if (found == fs::stat_filesystem->files.end()) { errno = ENOENT; return -1; }
info->st_size = found->second.size();
return 0;
}
File diff suppressed because it is too large. Load diff