Publish watchdog HWCDC boundaries before reopening USB
This commit is contained in:
1 parent
2554b6472b
commit
14b463025f
7 files changed
+268
-74
No files matched your search
@@ -1123,11 +1123,11 @@ static void serviceUsbTerminalHostSessionReset() {
|
||||
}
|
||||
#elif defined(ESP32) && defined(ARDUINO_USB_MODE) && ARDUINO_USB_MODE == 1 \
|
||||
&& defined(ARDUINO_USB_CDC_ON_BOOT) && ARDUINO_USB_CDC_ON_BOOT
|
||||
// A watchdog detach can start without a host-loss edge. Clear the old USB
|
||||
// protocol state once, then finish that same quarantine through our bounded
|
||||
// retry path even if logging or its watchdog is subsequently disabled.
|
||||
if (!usb_terminal_host_reset_completion_pending
|
||||
&& mesh::isUsbLoggingTransportRecoveryPending()) {
|
||||
// Consume hardware and watchdog boundaries before retrying their cleanup.
|
||||
// This clears the old USB owner exactly once, including when its queues are
|
||||
// already empty, before the same quarantined epoch is allowed to reopen.
|
||||
const bool hardware_bus_reset = mesh::takeUsbTerminalSessionReset();
|
||||
if (hardware_bus_reset) {
|
||||
resetUsbTerminalHostSession();
|
||||
return;
|
||||
}
|
||||
@@ -1148,12 +1148,11 @@ static void serviceUsbTerminalHostSessionReset() {
|
||||
(void)usb_hwcdc_host_presence.observeHost(
|
||||
host_present, millis(), USB_HOST_LOSS_EDGE_MS,
|
||||
USB_HOST_LOSS_GRACE_MS);
|
||||
const bool hardware_bus_reset = mesh::takeUsbTerminalSessionReset();
|
||||
const bool physical_host_loss =
|
||||
usb_hwcdc_host_presence.takeHostLossEdge();
|
||||
const bool sustained_host_loss =
|
||||
usb_hwcdc_host_presence.takeSustainedHostLoss();
|
||||
if (hardware_bus_reset || physical_host_loss || sustained_host_loss) {
|
||||
if (physical_host_loss || sustained_host_loss) {
|
||||
resetUsbTerminalHostSession();
|
||||
}
|
||||
#endif
|
||||
|
||||
+47
-38
@@ -1309,6 +1309,41 @@ static void purgeEsp32HwcdcQueues(void* opaque) {
|
||||
|
||||
while (Serial.read() >= 0) {}
|
||||
}
|
||||
|
||||
static bool beginEsp32HwcdcSessionReset() {
|
||||
if (esp32_hwcdc_cleanup_pending) return false;
|
||||
// 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
|
||||
// logging changes remain preferences while the low-level debug route is
|
||||
// forced off by that gate.
|
||||
portENTER_CRITICAL(&esp32_hwcdc_session_mux);
|
||||
esp32_hwcdc_cleanup_generation =
|
||||
esp32_hwcdc_access_generation.fetch_add(
|
||||
1, std::memory_order_acq_rel) + 1U;
|
||||
esp32_hwcdc_tx_kick_pending.store(false, std::memory_order_release);
|
||||
esp32_hwcdc_tx_primed.store(false, std::memory_order_release);
|
||||
#if MESH_HWCDC_PINNED_TX_BACKPORT
|
||||
meshEsp32HwcdcSetTxAllowed(false);
|
||||
#else
|
||||
usb_serial_jtag_ll_disable_intr_mask(
|
||||
USB_SERIAL_JTAG_INTR_SERIAL_IN_EMPTY);
|
||||
#endif
|
||||
portEXIT_CRITICAL(&esp32_hwcdc_session_mux);
|
||||
setPlatformDebugOutputEnabled(false);
|
||||
|
||||
esp32_hwcdc_restore_pad_enabled = detachEsp32HwcdcPads();
|
||||
esp32_hwcdc_cleanup_pending = true;
|
||||
// Always hold a real host-visible detach interval. The SOF tracker may
|
||||
// already be false when a physical-loss edge reaches the main loop.
|
||||
delay(10);
|
||||
const uint32_t detached_at = millis();
|
||||
while (Serial.isPlugged()
|
||||
&& (uint32_t)(millis() - detached_at) < 50U) {
|
||||
delay(1);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
#endif
|
||||
|
||||
bool resetUsbCompanionTransport() {
|
||||
@@ -1318,39 +1353,7 @@ bool resetUsbCompanionTransport() {
|
||||
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
|
||||
// logging changes remain preferences while the low-level debug route is
|
||||
// forced off by that gate.
|
||||
if (!esp32_hwcdc_cleanup_pending) {
|
||||
portENTER_CRITICAL(&esp32_hwcdc_session_mux);
|
||||
esp32_hwcdc_cleanup_generation =
|
||||
esp32_hwcdc_access_generation.fetch_add(
|
||||
1, std::memory_order_acq_rel) + 1U;
|
||||
esp32_hwcdc_tx_kick_pending.store(false, std::memory_order_release);
|
||||
esp32_hwcdc_tx_primed.store(false, std::memory_order_release);
|
||||
#if MESH_HWCDC_PINNED_TX_BACKPORT
|
||||
meshEsp32HwcdcSetTxAllowed(false);
|
||||
#else
|
||||
usb_serial_jtag_ll_disable_intr_mask(
|
||||
USB_SERIAL_JTAG_INTR_SERIAL_IN_EMPTY);
|
||||
#endif
|
||||
portEXIT_CRITICAL(&esp32_hwcdc_session_mux);
|
||||
setPlatformDebugOutputEnabled(false);
|
||||
|
||||
esp32_hwcdc_restore_pad_enabled = detachEsp32HwcdcPads();
|
||||
esp32_hwcdc_cleanup_pending = true;
|
||||
// Always hold a real host-visible detach interval. The SOF tracker may
|
||||
// already be false when a physical-loss edge reaches the main loop.
|
||||
delay(10);
|
||||
const uint32_t detached_at = millis();
|
||||
while (Serial.isPlugged()
|
||||
&& (uint32_t)(millis() - detached_at) < 50U) {
|
||||
delay(1);
|
||||
}
|
||||
}
|
||||
|
||||
(void)beginEsp32HwcdcSessionReset();
|
||||
// tryRunExclusive() shares the same writer guard as all primary Stream
|
||||
// facades. Retry briefly if a producer entered Serial.write() just before
|
||||
// the access gate closed; HWCDC writes are capped at five milliseconds.
|
||||
@@ -1390,6 +1393,8 @@ bool resetUsbCompanionTransport() {
|
||||
// A concurrent runtime preference change is authoritative; never restore a
|
||||
// stale snapshot taken before the purge.
|
||||
setPlatformDebugOutputEnabled(isUsbDebugLoggingEnabled());
|
||||
return esp32_hwcdc_allowed_generation.load(std::memory_order_acquire)
|
||||
== esp32_hwcdc_access_generation.load(std::memory_order_acquire);
|
||||
#endif
|
||||
return true;
|
||||
}
|
||||
@@ -1753,10 +1758,12 @@ UsbLoggingRecoveryResult recoverUsbLoggingTransport(uint8_t stage) {
|
||||
serviceEsp32HwcdcTxKick();
|
||||
probeUsbLoggingTransport();
|
||||
} else {
|
||||
// The helper always issues the PHY detach before attempting cleanup.
|
||||
// Pending cleanup stays quarantined, but it must not prevent the final
|
||||
// watchdog deadline forever. Attempted means requested, not healthy.
|
||||
(void)resetUsbCompanionTransport();
|
||||
// Publish a boundary even when every queue is already empty. The protocol
|
||||
// owner must clear its old parser/routes before finishing this same reset;
|
||||
// reopening here could hide the detach from its host-loss debounce.
|
||||
if (beginEsp32HwcdcSessionReset()) {
|
||||
esp32_hwcdc_bus_reset_generation.fetch_add(1, std::memory_order_acq_rel);
|
||||
}
|
||||
}
|
||||
return UsbLoggingRecoveryResult::Attempted;
|
||||
#elif defined(NRF52_PLATFORM) && defined(USE_TINYUSB)
|
||||
@@ -1796,7 +1803,9 @@ bool isUsbLoggingTransportRecoveryPending() {
|
||||
const auto state = esp32_tinyusb_reenumeration_state.load(std::memory_order_acquire);
|
||||
return usb_logging_watchdog_detached || state == 1 || state == 3;
|
||||
#elif MESH_ESP32_HWCDC_SESSION_GUARD
|
||||
return esp32_hwcdc_cleanup_pending;
|
||||
return esp32_hwcdc_cleanup_pending
|
||||
|| esp32_hwcdc_allowed_generation.load(std::memory_order_acquire)
|
||||
!= esp32_hwcdc_access_generation.load(std::memory_order_acquire);
|
||||
#else
|
||||
return false;
|
||||
#endif
|
||||
|
||||
+158
-5
@@ -15,6 +15,8 @@
|
||||
#include <cassert>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <deque>
|
||||
#include <functional>
|
||||
#include <string>
|
||||
|
||||
#define portENTER_CRITICAL(value) ((void)0)
|
||||
@@ -22,6 +24,8 @@
|
||||
static bool in_isr = false;
|
||||
static bool xPortInIsrContext() { return in_isr; }
|
||||
static void delay(uint32_t duration) { mock_watchdog_millis += duration; }
|
||||
using esp_event_base_t = int;
|
||||
enum { ARDUINO_HW_CDC_BUS_RESET_EVENT = 1, ARDUINO_HW_CDC_RX_EVENT, ARDUINO_HW_CDC_TX_EVENT };
|
||||
|
||||
namespace mesh {
|
||||
static bool logging_enabled = true, client_active = false;
|
||||
@@ -50,14 +54,19 @@ static UsbSelfResetBurstGuard esp32_hwcdc_self_reset_guard;
|
||||
static bool pads_enabled = true, host_connected = false, reader_connected = false;
|
||||
static size_t ring_available = 0;
|
||||
static unsigned detach_calls = 0, flush_calls = 0;
|
||||
static bool exclusive_busy = false;
|
||||
static bool exclusive_busy = false, drain_on_flush = false;
|
||||
static std::deque<uint8_t> host_rx;
|
||||
static std::function<void()> at_restore;
|
||||
static bool detachEsp32HwcdcPads() {
|
||||
++detach_calls;
|
||||
const bool previous = pads_enabled;
|
||||
pads_enabled = false;
|
||||
return previous;
|
||||
}
|
||||
static void restoreEsp32HwcdcPads(bool enabled) { pads_enabled = enabled; }
|
||||
static void restoreEsp32HwcdcPads(bool enabled) {
|
||||
pads_enabled = enabled;
|
||||
if (at_restore) { auto callback = at_restore; at_restore = nullptr; callback(); }
|
||||
}
|
||||
enum { USB_SERIAL_JTAG_INTR_SERIAL_IN_EMPTY = 1 };
|
||||
[[maybe_unused]] static void usb_serial_jtag_ll_disable_intr_mask(unsigned) {}
|
||||
[[maybe_unused]] static void usb_serial_jtag_ll_ena_intr_mask(unsigned) {}
|
||||
@@ -67,11 +76,18 @@ bool meshEsp32HwcdcDiscardTxStash() { return true; }
|
||||
void meshEsp32HwcdcSetTxAllowed(bool) {}
|
||||
void meshEsp32HwcdcKickTx() {}
|
||||
struct SerialMock {
|
||||
int read() { return -1; }
|
||||
int read() {
|
||||
if (host_rx.empty()) return -1;
|
||||
int value = host_rx.front(); host_rx.pop_front(); return value;
|
||||
}
|
||||
int availableForWrite() { return int(ring_available); }
|
||||
bool isPlugged() { return pads_enabled && host_connected; }
|
||||
explicit operator bool() { return isPlugged() && reader_connected; }
|
||||
void flush() { ++flush_calls; } // A stuck ring deliberately does not drain.
|
||||
void setDebugOutput(bool) {}
|
||||
void flush() {
|
||||
++flush_calls;
|
||||
if (drain_on_flush && !pads_enabled) ring_available = 4096;
|
||||
}
|
||||
} Serial;
|
||||
struct Exclusive {
|
||||
// No writer owns this gate in the fault reproduction. Safety deferrals are
|
||||
@@ -108,7 +124,9 @@ struct MeshMock {
|
||||
bool usb_work = true, ble_work = true, network_work = true;
|
||||
bool usb_stream = true, ble_stream = true, network_stream = true;
|
||||
bool input_stale = true, terminal_mode = true;
|
||||
unsigned input_resets = 0;
|
||||
unsigned input_resets = 0, serial_cancels = 0;
|
||||
void cancelPendingSerialOutput() { ++serial_cancels; }
|
||||
bool hasPendingSerialOutput() const { return false; }
|
||||
void cancelSerialResponseStream(UsbProtocolMock* route) {
|
||||
assert(route == &usb_serial_interface); usb_stream = false;
|
||||
}
|
||||
@@ -133,6 +151,10 @@ static void leaveUsbTerminalMode(bool) {
|
||||
}
|
||||
namespace mesh { void discardUsbTerminalOutput() { ++discarded_output; } }
|
||||
@COMPANION_METHODS@
|
||||
static char command[64];
|
||||
static bool command_overflow = false;
|
||||
namespace mesh { bool canAcceptUsbConsoleCommand() { return true; } }
|
||||
@ORDINARY_METHODS@
|
||||
|
||||
using Policy = mesh::UsbLoggingWatchdogPolicy;
|
||||
using Event = mesh::UsbLoggingWatchdogEvent;
|
||||
@@ -164,10 +186,17 @@ struct Fixture {
|
||||
mesh::esp32_hwcdc_cleanup_pending = false;
|
||||
mesh::esp32_hwcdc_access_generation.store(0);
|
||||
mesh::esp32_hwcdc_allowed_generation.store(0);
|
||||
mesh::esp32_hwcdc_bus_reset_generation.store(0);
|
||||
mesh::esp32_hwcdc_taken_bus_reset_generation = 0;
|
||||
mesh::esp32_hwcdc_startup_pending.store(true);
|
||||
mesh::esp32_hwcdc_self_reset_guard.notePostCleanActivity();
|
||||
mesh::esp32_hwcdc_tx_kick_pending.store(false);
|
||||
mesh::usb_logging_tx_progress.store(0);
|
||||
mesh::pads_enabled = true;
|
||||
mesh::exclusive_busy = false;
|
||||
mesh::drain_on_flush = false;
|
||||
mesh::host_rx.clear();
|
||||
mesh::at_restore = nullptr;
|
||||
mesh::detach_calls = mesh::flush_calls = 0;
|
||||
usb_terminal_host_reset_completion_pending = false;
|
||||
usb_terminal_host_reset_retry_at = 0;
|
||||
@@ -181,6 +210,7 @@ struct Fixture {
|
||||
terminal_leaves = discarded_output = 0;
|
||||
usb_binary_startup_probe.start(mock_watchdog_millis, 7);
|
||||
usb_ascii_session_default.cancel();
|
||||
command[0] = 0; command_overflow = false;
|
||||
#if defined(ENABLE_OTA)
|
||||
mesh::ota::test_ota_context = nullptr;
|
||||
#endif
|
||||
@@ -203,9 +233,26 @@ struct Fixture {
|
||||
assert(status.recovery_count == 2 && status.persistence_ready);
|
||||
assert(status.last_event.action == Event::REENUMERATE && status.last_event.persisted);
|
||||
assert(mesh::detach_calls == 1);
|
||||
assert(mesh::esp32_hwcdc_cleanup_pending && !mesh::pads_enabled);
|
||||
assert(!mesh::canAccessEsp32Hwcdc(nullptr) && mesh::flush_calls == 0);
|
||||
}
|
||||
};
|
||||
|
||||
static void assertFreshAppStartSurvives() {
|
||||
// A complete minimal APP_START frame: marker, little-endian length, payload.
|
||||
const std::deque<uint8_t> app_start{'<', 8, 0, 1, 3, 0, 0, 0, 0, 0, 0};
|
||||
mesh::host_rx = app_start;
|
||||
const unsigned resets = the_mesh.input_resets, detaches = mesh::detach_calls;
|
||||
const uint32_t generation = mesh::esp32_hwcdc_access_generation.load();
|
||||
for (unsigned i = 0; i < 3; ++i) {
|
||||
++mock_watchdog_millis;
|
||||
serviceUsbTerminalHostSessionReset();
|
||||
}
|
||||
assert(mesh::host_rx == app_start && "a consumed watchdog boundary must not discard fresh APP_START");
|
||||
assert(the_mesh.input_resets == resets && mesh::detach_calls == detaches);
|
||||
assert(mesh::esp32_hwcdc_access_generation.load() == generation);
|
||||
}
|
||||
|
||||
int main(int argc, char** argv) {
|
||||
setbuf(stdout, nullptr);
|
||||
assert(argc == 3);
|
||||
@@ -233,6 +280,7 @@ int main(int argc, char** argv) {
|
||||
} else if (scenario == "healthy") {
|
||||
Fixture f(1, step, false, true);
|
||||
f.enter_stage2();
|
||||
serviceUsbTerminalHostSessionReset();
|
||||
assert(!mesh::esp32_hwcdc_cleanup_pending && mesh::pads_enabled);
|
||||
assert(mesh::flush_calls >= 2);
|
||||
mesh::host_connected = mesh::reader_connected = mesh::client_active = true;
|
||||
@@ -332,6 +380,111 @@ int main(int argc, char** argv) {
|
||||
assert(the_mesh.input_resets == 1 && usb_serial_interface.resets == 1);
|
||||
assert(mesh::esp32_hwcdc_access_generation.load() == generation);
|
||||
assert(usb_ascii_session_default.shouldRestore(true, false, 7));
|
||||
} else if (scenario.rfind("success-", 0) == 0) {
|
||||
const bool stalled = scenario.find("stall") != std::string::npos;
|
||||
const bool automatic = scenario.find("auto") != std::string::npos;
|
||||
Fixture f(automatic ? 2 : 1, step, false, !stalled);
|
||||
mesh::host_connected = mesh::reader_connected = mesh::client_active = true;
|
||||
mesh::drain_on_flush = stalled;
|
||||
usb_terminal_line[0] = 0; usb_terminal_line_len = 0;
|
||||
usb_terminal_discard_line = false; usb_logging_reply_pending = false;
|
||||
usb_binary_startup_probe.cancel();
|
||||
serviceUsbTerminalHostSessionReset();
|
||||
assert(!f.run(0));
|
||||
assert(!f.run(1)); // Auto observes the logger before its active policy edge.
|
||||
if (stalled) {
|
||||
assert(!f.run(Policy::STALL_OBSERVE_MS + 1));
|
||||
assert(mesh::usbLoggingStatus().stalled);
|
||||
strcpy(usb_terminal_line, "set password ");
|
||||
usb_terminal_line_len = strlen(usb_terminal_line);
|
||||
} else {
|
||||
mesh::client_active = false;
|
||||
assert(!f.run(2));
|
||||
}
|
||||
const uint32_t fault = stalled ? 1 : 2;
|
||||
assert(!f.run(fault + Policy::EARLY_RECOVERY_MS));
|
||||
assert(!f.run(fault + Policy::EARLY_RECOVERY_MS + Policy::RECOVERY_GRACE_MS));
|
||||
assert(mesh::esp32_hwcdc_cleanup_pending && !mesh::pads_enabled && mesh::flush_calls == 0);
|
||||
assert(the_mesh.input_resets == 0 && usb_serial_interface.resets == 0);
|
||||
const uint32_t generation = mesh::esp32_hwcdc_access_generation.load();
|
||||
serviceUsbTerminalHostSessionReset();
|
||||
assert(!mesh::esp32_hwcdc_cleanup_pending && mesh::pads_enabled);
|
||||
assert(!usb_terminal_line_len && !usb_terminal_discard_line && !the_mesh.terminal_mode);
|
||||
assert(the_mesh.input_resets == 1 && usb_serial_interface.resets == 1);
|
||||
assert(mesh::detach_calls == 1 && mesh::esp32_hwcdc_access_generation.load() == generation);
|
||||
assert(mesh::esp32_hwcdc_taken_bus_reset_generation == mesh::esp32_hwcdc_bus_reset_generation.load());
|
||||
assertFreshAppStartSurvives();
|
||||
} else if (scenario.rfind("ordinary-", 0) == 0) {
|
||||
Fixture f(1, step, false, false);
|
||||
mesh::host_connected = mesh::reader_connected = mesh::client_active = true;
|
||||
mesh::drain_on_flush = true;
|
||||
strcpy(command, "set password "); command_overflow = true;
|
||||
const auto service = scenario == "ordinary-repeater" ? service_simple_repeater
|
||||
: scenario == "ordinary-room" ? service_simple_room_server : service_simple_sensor;
|
||||
service();
|
||||
assert(!f.run(0) && !f.run(Policy::STALL_OBSERVE_MS));
|
||||
assert(mesh::usbLoggingStatus().stalled);
|
||||
assert(!f.run(Policy::EARLY_RECOVERY_MS));
|
||||
assert(!f.run(Policy::EARLY_RECOVERY_MS + Policy::RECOVERY_GRACE_MS));
|
||||
assert(mesh::esp32_hwcdc_cleanup_pending && !mesh::pads_enabled);
|
||||
service();
|
||||
assert(command[0] == 0 && !mesh::esp32_hwcdc_cleanup_pending && mesh::pads_enabled);
|
||||
if (scenario != "ordinary-sensor") assert(the_mesh.serial_cancels == 1);
|
||||
if (scenario == "ordinary-repeater") assert(!command_overflow);
|
||||
strcpy(command, "new host input");
|
||||
service();
|
||||
assert(strcmp(command, "new host input") == 0 && mesh::detach_calls == 1);
|
||||
} else if (scenario == "idempotent-stage2") {
|
||||
Fixture f(1, step, false, true);
|
||||
f.enter_stage2();
|
||||
const uint32_t epoch = mesh::esp32_hwcdc_access_generation.load();
|
||||
const uint32_t boundary = mesh::esp32_hwcdc_bus_reset_generation.load();
|
||||
assert(mesh::recoverUsbLoggingTransport(2) == mesh::UsbLoggingRecoveryResult::Attempted);
|
||||
assert(mesh::esp32_hwcdc_access_generation.load() == epoch);
|
||||
assert(mesh::esp32_hwcdc_bus_reset_generation.load() == boundary && mesh::detach_calls == 1);
|
||||
serviceUsbTerminalHostSessionReset();
|
||||
assert(the_mesh.input_resets == 1 && mesh::detach_calls == 1);
|
||||
assertFreshAppStartSurvives();
|
||||
} else if (scenario == "superseded-before" || scenario == "superseded-during") {
|
||||
Fixture f(1, step, false, true);
|
||||
assert(!mesh::takeUsbTerminalSessionReset()); // Initial owner service, no synthetic edge.
|
||||
f.enter_stage2();
|
||||
const auto reset = [] {
|
||||
mesh::handleEsp32HwcdcEvent(nullptr, 0, ARDUINO_HW_CDC_RX_EVENT, nullptr);
|
||||
mesh::handleEsp32HwcdcEvent(nullptr, 0, ARDUINO_HW_CDC_BUS_RESET_EVENT, nullptr);
|
||||
};
|
||||
if (scenario == "superseded-before") reset();
|
||||
else mesh::at_restore = reset;
|
||||
serviceUsbTerminalHostSessionReset();
|
||||
assert(usb_terminal_host_reset_completion_pending
|
||||
&& "a superseding hardware epoch must keep Companion pending");
|
||||
assert(!mesh::canAccessEsp32Hwcdc(nullptr) && !mesh::esp32_hwcdc_cleanup_pending);
|
||||
assert(mesh::isUsbLoggingTransportRecoveryPending());
|
||||
assert(mesh::esp32_hwcdc_allowed_generation.load() != mesh::esp32_hwcdc_access_generation.load());
|
||||
assert(the_mesh.input_resets == 1);
|
||||
char reply[160];
|
||||
assert(mesh::handleUsbLoggingWatchdogCommand("set usb.watchdog off", reply, sizeof(reply)));
|
||||
mesh::logging_enabled = false;
|
||||
assert(mesh::isUsbLoggingWatchdogArmed());
|
||||
if (scenario == "superseded-before") {
|
||||
// Both edges were consumed together; no event is left to drive retry.
|
||||
mock_watchdog_millis += USB_TRANSPORT_RESET_RETRY_MS - 1;
|
||||
serviceUsbTerminalHostSessionReset();
|
||||
assert(usb_terminal_host_reset_completion_pending && mesh::detach_calls == 1);
|
||||
++mock_watchdog_millis;
|
||||
} else ++mock_watchdog_millis;
|
||||
serviceUsbTerminalHostSessionReset();
|
||||
assert(!usb_terminal_host_reset_completion_pending && mesh::canAccessEsp32Hwcdc(nullptr));
|
||||
assert(!mesh::isUsbLoggingTransportRecoveryPending() && !mesh::isUsbLoggingWatchdogArmed());
|
||||
assert(mesh::detach_calls == 2);
|
||||
assert(the_mesh.input_resets == (scenario == "superseded-before" ? 1U : 2U));
|
||||
assertFreshAppStartSurvives();
|
||||
} else if (scenario == "cold-start") {
|
||||
Fixture f(2, step, false, true);
|
||||
mesh::host_connected = mesh::reader_connected = true;
|
||||
assertFreshAppStartSurvives();
|
||||
assert(!mesh::esp32_hwcdc_startup_pending.load() && mesh::detach_calls == 0);
|
||||
assert(the_mesh.input_resets == 0 && mesh::flush_calls == 0);
|
||||
} else if (scenario == "isr") {
|
||||
Fixture f(1, step);
|
||||
in_isr = true;
|
||||
|
||||
@@ -182,10 +182,10 @@ int main() {
|
||||
self.assertIn("takeSustainedHostLoss()", service)
|
||||
self.assertIn("takeHostLossEdge()", service)
|
||||
self.assertIn("mesh::takeUsbTerminalSessionReset()", service)
|
||||
self.assertIn(
|
||||
"hardware_bus_reset || physical_host_loss || sustained_host_loss",
|
||||
service,
|
||||
)
|
||||
self.assertIn("if (hardware_bus_reset)", service)
|
||||
self.assertIn("if (physical_host_loss || sustained_host_loss)", service)
|
||||
self.assertLess(service.index("const bool hardware_bus_reset"),
|
||||
service.index("if (usb_terminal_host_reset_completion_pending)"))
|
||||
self.assertIn("usb_terminal_host_reset_completion_pending", service)
|
||||
self.assertIn("USB_TRANSPORT_RESET_RETRY_MS", service)
|
||||
self.assertIn("resetUsbTerminalHostSession();", service)
|
||||
@@ -205,11 +205,12 @@ int main() {
|
||||
"Stream& usbLoggingPort()", purge_start
|
||||
)]
|
||||
self.assertIn(
|
||||
"esp32_hwcdc_access_generation.fetch_add(", purge
|
||||
"esp32_hwcdc_access_generation.fetch_add(", helper
|
||||
)
|
||||
self.assertIn("setPlatformDebugOutputEnabled(false);", purge)
|
||||
self.assertIn("detachEsp32HwcdcPads()", purge)
|
||||
self.assertIn("delay(10);", purge)
|
||||
self.assertIn("setPlatformDebugOutputEnabled(false);", helper)
|
||||
self.assertIn("detachEsp32HwcdcPads()", helper)
|
||||
self.assertIn("delay(10);", helper)
|
||||
self.assertIn("(void)beginEsp32HwcdcSessionReset();", purge)
|
||||
self.assertIn("tryRunExclusive(", purge)
|
||||
self.assertIn("Serial.flush();", helper)
|
||||
self.assertIn("flush_attempts >= 2", helper)
|
||||
|
||||
@@ -184,6 +184,7 @@ def application_sources(*, remove_boot_gate=False, remove_owner_hook=False,
|
||||
"static void handleEsp32HwcdcEvent(",
|
||||
"static void serviceEsp32HwcdcTxKickExclusive(",
|
||||
"static void purgeEsp32HwcdcQueues(",
|
||||
"static bool beginEsp32HwcdcSessionReset(",
|
||||
"bool resetUsbCompanionTransport(",
|
||||
"UsbLoggingObservation observeUsbLoggingTransport(",
|
||||
"bool takeUsbTerminalSessionReset()",
|
||||
|
||||
@@ -362,6 +362,7 @@ int main(){
|
||||
'static void handleEsp32HwcdcEvent(',
|
||||
'static void serviceEsp32HwcdcTxKickExclusive(',
|
||||
'static void purgeEsp32HwcdcQueues(',
|
||||
'static bool beginEsp32HwcdcSessionReset(',
|
||||
'bool resetUsbCompanionTransport(',
|
||||
'UsbLoggingObservation observeUsbLoggingTransport('])
|
||||
prefix=self.harness()[:self.harness().index('int main(){')]
|
||||
@@ -443,7 +444,7 @@ int main(){
|
||||
handleEsp32HwcdcEvent(nullptr,0,ARDUINO_HW_CDC_RX_EVENT,nullptr);
|
||||
handleEsp32HwcdcEvent(nullptr,0,ARDUINO_HW_CDC_BUS_RESET_EVENT,nullptr);
|
||||
};
|
||||
assert(resetUsbCompanionTransport());
|
||||
assert(!resetUsbCompanionTransport());
|
||||
assert(!mesh_hwcdc_tx_allowed&&!canAccessEsp32Hwcdc(nullptr));
|
||||
assert(esp32_hwcdc_allowed_generation.load()<esp32_hwcdc_access_generation.load());
|
||||
assert(resetUsbCompanionTransport());assert(mesh_hwcdc_tx_allowed&&canAccessEsp32Hwcdc(nullptr));
|
||||
|
||||
@@ -16,11 +16,15 @@ SIGNATURES = (
|
||||
"static void serviceEsp32HwcdcTxKickExclusive(",
|
||||
"static void serviceEsp32HwcdcTxKick()",
|
||||
"static void purgeEsp32HwcdcQueues(",
|
||||
"static bool beginEsp32HwcdcSessionReset(",
|
||||
"bool resetUsbCompanionTransport()",
|
||||
"UsbLoggingObservation observeUsbLoggingTransport()",
|
||||
"UsbLoggingRecoveryResult recoverUsbLoggingTransport(",
|
||||
"bool isUsbLoggingTransportRecoveryPending()",
|
||||
"bool takeUsbTerminalSessionReset()",
|
||||
"bool tryCompleteUsbTerminalSessionReset()",
|
||||
"void noteUsbLoggingTxComplete()",
|
||||
"static void handleEsp32HwcdcEvent(",
|
||||
)
|
||||
|
||||
|
||||
@@ -39,32 +43,42 @@ class HwcdcLoggingWatchdogTests(unittest.TestCase):
|
||||
cls.companion_methods = "\n".join(body(companion, signature) for signature in (
|
||||
"static void clearUsbTerminalLine()", "static void cancelUsbSerialOperations()",
|
||||
"static void resetUsbTerminalHostSession()", "static void serviceUsbTerminalHostSessionReset()"))
|
||||
cls.ordinary_methods = ""
|
||||
for role in ("simple_repeater", "simple_room_server", "simple_sensor"):
|
||||
text = (ROOT / "examples" / role / "main.cpp").read_text()
|
||||
start = text.index(" if (mesh::takeUsbTerminalSessionReset())")
|
||||
stop = text.index("\n#endif", start)
|
||||
cls.ordinary_methods += ("static void service_" + role + "() {\n"
|
||||
" bool usb_ready = true;\n" + text[start:stop] + "\n (void)usb_ready;\n}\n")
|
||||
cls.binaries = {(backport, ota): cls.compile_backend(backport, ota)
|
||||
for backport in (0, 1) for ota in (False, True)}
|
||||
|
||||
@classmethod
|
||||
def compile_backend(cls, backport, ota, legacy=False, no_bridge=False):
|
||||
suffix = f"{backport}-{int(ota)}-{int(legacy)}-{int(no_bridge)}"
|
||||
def compile_backend(cls, backport, ota, legacy=False, no_bridge=False, stale_ready=False):
|
||||
suffix = f"{backport}-{int(ota)}-{int(legacy)}-{int(no_bridge)}-{int(stale_ready)}"
|
||||
methods = cls.methods
|
||||
request = (" if (beginEsp32HwcdcSessionReset()) {\n"
|
||||
" esp32_hwcdc_bus_reset_generation.fetch_add(1, std::memory_order_acq_rel);\n"
|
||||
" }")
|
||||
if legacy:
|
||||
attempted = " (void)resetUsbCompanionTransport();"
|
||||
assert methods.count(attempted) == 1
|
||||
methods = methods.replace(attempted,
|
||||
assert methods.count(request) == 1
|
||||
methods = methods.replace(request,
|
||||
" if (!resetUsbCompanionTransport())\n"
|
||||
" return UsbLoggingRecoveryResult::Deferred;")
|
||||
if no_bridge:
|
||||
assert methods.count(request) == 1
|
||||
methods = methods.replace(request, " (void)beginEsp32HwcdcSessionReset();")
|
||||
if stale_ready:
|
||||
ready = (" return esp32_hwcdc_allowed_generation.load(std::memory_order_acquire)\n"
|
||||
" == esp32_hwcdc_access_generation.load(std::memory_order_acquire);")
|
||||
assert methods.count(ready) == 1
|
||||
methods = methods.replace(ready, " return true;")
|
||||
source = cls.folder / f"backend-{suffix}.cpp"
|
||||
service = cls.companion_methods
|
||||
if no_bridge:
|
||||
bridge = (" if (!usb_terminal_host_reset_completion_pending\n"
|
||||
" && mesh::isUsbLoggingTransportRecoveryPending()) {\n"
|
||||
" resetUsbTerminalHostSession();\n"
|
||||
" return;\n"
|
||||
" }\n")
|
||||
assert service.count(bridge) == 1
|
||||
service = service.replace(bridge, "")
|
||||
source.write_text((FIXTURE / "hwcdc_backend.cpp").read_text()
|
||||
.replace("@BACKEND_METHODS@", methods)
|
||||
.replace("@COMPANION_METHODS@", service), encoding="ascii")
|
||||
.replace("@COMPANION_METHODS@", service)
|
||||
.replace("@ORDINARY_METHODS@", cls.ordinary_methods), encoding="ascii")
|
||||
# Copy unchanged bytes so the runtime's quoted OTA include resolves
|
||||
# through the isolated dependency fake, not the full firmware graph.
|
||||
runtime = cls.folder / "UsbLoggingWatchdog.cpp"
|
||||
@@ -114,6 +128,16 @@ class HwcdcLoggingWatchdogTests(unittest.TestCase):
|
||||
def test_actual_ota_veto_before_detach_and_at_reboot_deadline(self):
|
||||
self.check_cases(("ota-start", "ota-deadline"), ota_only=True)
|
||||
|
||||
def test_successful_recovery_clears_protocol_before_reopen_exactly_once(self):
|
||||
self.check_cases(("success-appgap", "success-stall", "success-appgap-auto", "success-stall-auto",
|
||||
"idempotent-stage2", "cold-start"))
|
||||
|
||||
def test_all_ordinary_owners_discard_stalled_partial_commands(self):
|
||||
self.check_cases(("ordinary-repeater", "ordinary-room", "ordinary-sensor"))
|
||||
|
||||
def test_newer_hardware_epochs_remain_quarantined_until_their_own_cleanup(self):
|
||||
self.check_cases(("superseded-before", "superseded-during"))
|
||||
|
||||
def test_legacy_deferred_classification_negative_control(self):
|
||||
binary = self.compile_backend(1, True, legacy=True)
|
||||
for scenario in ("zero", "stuck"):
|
||||
@@ -124,7 +148,7 @@ class HwcdcLoggingWatchdogTests(unittest.TestCase):
|
||||
self.assertIn("CHECK: HWCDC stage-2 detach was requested", result.stdout)
|
||||
self.assertIn("HWCDC detach request must count as attempted", result.stderr)
|
||||
|
||||
def test_missing_companion_pending_cleanup_bridge_negative_control(self):
|
||||
def test_missing_watchdog_protocol_boundary_negative_control(self):
|
||||
binary = self.compile_backend(1, True, no_bridge=True)
|
||||
for scenario in ("resume-auto", "resume-off"):
|
||||
with self.subTest(scenario=scenario):
|
||||
@@ -133,6 +157,12 @@ class HwcdcLoggingWatchdogTests(unittest.TestCase):
|
||||
self.assertIn("Companion must adopt a pending watchdog cleanup without a host edge",
|
||||
result.stderr)
|
||||
|
||||
def test_stale_finish_must_not_report_ready_negative_control(self):
|
||||
binary = self.compile_backend(1, True, stale_ready=True)
|
||||
result = self.run_case(binary, "superseded-during", 0)
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertIn("a superseding hardware epoch must keep Companion pending", result.stderr)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user