Improve companion setup and USB session recovery

This commit is contained in:
mikecarper committed 2026-09-02 03:44:28 -07:00
1 parent ecaa5ac2a0
commit cf70478c51
34 files changed
+6283 -2147

No files matched your search

+11 -10
View File
@@ -158,6 +158,15 @@ void ArduinoSerialInterface::setPassthroughMode(bool enabled) {
resetTransmitState();
}
void ArduinoSerialInterface::resetSessionState() {
_controlSequenceReceived = false;
_secondaryControlSequenceReceived = false;
_has_received_frame = false;
_last_frame_ms = 0;
resetReceiveState();
resetTransmitState();
}
bool ArduinoSerialInterface::takeControlSequence() {
bool received = _controlSequenceReceived;
_controlSequenceReceived = false;
@@ -172,19 +181,11 @@ bool ArduinoSerialInterface::takeSecondaryControlSequence() {
void ArduinoSerialInterface::enable() {
_isEnabled = true;
_controlSequenceReceived = false;
_secondaryControlSequenceReceived = false;
_has_received_frame = false;
resetReceiveState();
resetTransmitState();
resetSessionState();
}
void ArduinoSerialInterface::disable() {
_isEnabled = false;
_controlSequenceReceived = false;
_secondaryControlSequenceReceived = false;
_has_received_frame = false;
resetReceiveState();
resetTransmitState();
resetSessionState();
}
bool ArduinoSerialInterface::isConnected() const {
+4
View File
@@ -95,6 +95,10 @@ public:
// Without it isConnected() assumes true, as a plain UART has no way of knowing.
void setConnectedCheck(ConnectedCheck fn) { _conn_check = fn; }
// Clear all protocol state owned by one host session while retaining the
// monotonic completed-frame counter used by startup handoff arbitration.
void resetSessionState();
// millis() of the last completely received frame, 0 if none since boot.
// Useful as an activity-based connection check where no DTR state exists.
uint32_t getLastFrameMillis() const { return _last_frame_ms; }
+4 -162
View File
@@ -1,6 +1,7 @@
#include <Arduino.h>
#include "CommonCLI.h"
#include "CLICommandUtils.h"
#include "StorageLayout.h"
#include "radiolib/RadioPowerLimits.h"
#include "radiolib/LR2021SideDetectorConfig.h"
#include "TxtDataHelpers.h"
@@ -9,7 +10,6 @@
#include "sensors/EnvironmentI2CConfig.h"
#if defined(NRF52_PLATFORM)
#include "AtomicFileWriter.h"
#include "ota/OtaFlashLayout_nrf52.h"
#endif
#include <RTClib.h>
#include <ctype.h>
@@ -54,8 +54,6 @@ static void resetToUf2Bootloader() {
#ifdef ESP_PLATFORM
#include <WiFi.h>
#include <WiFiClientSecure.h>
#include <esp_ota_ops.h>
#include <esp_partition.h>
#include <esp_wifi.h>
#include <esp_heap_caps.h>
#else
@@ -64,9 +62,6 @@ static void resetToUf2Bootloader() {
#if defined(MESH_PRIMARY_ESPNOW) && MESH_PRIMARY_ESPNOW
#include <helpers/esp32/WiFiRadioPolicy.h>
#endif
#if defined(STM32_PLATFORM)
#include <InternalFileSystem.h>
#endif
#ifdef WITH_MQTT_BRIDGE
#include "bridges/MQTTBridge.h"
#include "CommonPrefsRecovery.h"
@@ -107,30 +102,6 @@ static void formatSdCardElapsed(char* out, size_t out_len, bool recorded,
}
}
static void formatSdCardBytes(char* out, size_t out_len, uint64_t bytes) {
static const char* const units[] = {"B", "KiB", "MiB", "GiB", "TiB"};
uint64_t unit_size = 1;
uint8_t unit = 0;
while (unit < 4 && bytes >= unit_size * 1024ULL) {
unit_size *= 1024ULL;
unit++;
}
if (unit == 0) {
snprintf(out, out_len, "%lu B", (unsigned long)bytes);
return;
}
uint64_t whole = bytes / unit_size;
uint32_t tenths = (uint32_t)(((bytes % unit_size) * 10ULL + unit_size / 2ULL) /
unit_size);
if (tenths == 10) {
whole++;
tenths = 0;
}
snprintf(out, out_len, "%lu.%lu %s", (unsigned long)whole,
(unsigned long)tenths, units[unit]);
}
#endif
#include <helpers/radiolib/RXPowerSaving.h>
@@ -3004,135 +2975,6 @@ void CommonCLI::handleCommand(uint32_t sender_timestamp, char* command, char* re
}
}
bool CommonCLI::handleStorageLayoutGetCmd(const char* config, char* reply) {
static const char key[] = "storage.layout";
const size_t key_len = sizeof(key) - 1;
if (strncmp(config, key, key_len) != 0 ||
(config[key_len] != 0 && config[key_len] != ' ')) {
return false;
}
if (config[key_len] != 0) {
strcpy(reply, "Error: use get storage.layout");
return true;
}
#if defined(ESP32_PLATFORM)
snprintf(reply, 160, "> int:esp32=%luK ext:none; ",
(unsigned long)(ESP.getFlashChipSize() / 1024UL));
const esp_partition_t* running = esp_ota_get_running_partition();
esp_partition_iterator_t iterator = esp_partition_find(
ESP_PARTITION_TYPE_ANY, ESP_PARTITION_SUBTYPE_ANY, NULL);
bool first = true;
bool truncated = false;
while (iterator != NULL) {
const esp_partition_t* partition = esp_partition_get(iterator);
char entry[48];
snprintf(entry, sizeof(entry), "%s%s%s@0x%lX+%luK",
first ? "" : ",", partition->label,
running != NULL && partition->address == running->address ? "*" : "",
(unsigned long)partition->address,
(unsigned long)(partition->size / 1024UL));
const size_t used = strlen(reply);
const size_t entry_len = strlen(entry);
if (used + entry_len + 1 >= 160) {
truncated = true;
break;
}
memcpy(reply + used, entry, entry_len + 1);
first = false;
iterator = esp_partition_next(iterator);
}
if (iterator != NULL) esp_partition_iterator_release(iterator);
if (first) {
snprintf(reply + strlen(reply), 160 - strlen(reply), "partitions=none");
} else if (truncated) {
const size_t used = strlen(reply);
if (used + 4 < 160) memcpy(reply + used, ",...", 5);
}
#elif defined(NRF52_PLATFORM)
const uint32_t flash_bytes =
(uint32_t)NRF_FICR->CODEPAGESIZE * (uint32_t)NRF_FICR->CODESIZE;
const uint32_t app_start = mesh::ota::mota_nrf52_app_base();
const uint32_t app_end =
(uint32_t)(uintptr_t)mesh::ota::__flash_arduino_end;
#if defined(NRF52840_XXAA)
const uint32_t internal_fs_start = 0x000ED000UL;
#else
const uint32_t internal_fs_start = 0x0006D000UL;
#endif
const uint32_t internal_fs_size = 7UL * 4096UL;
snprintf(reply, 160,
"> int:nrf52=%luK app=0x%lX-0x%lX ifs=0x%lX+%luK",
(unsigned long)(flash_bytes / 1024UL),
(unsigned long)app_start, (unsigned long)app_end,
(unsigned long)internal_fs_start,
(unsigned long)(internal_fs_size / 1024UL));
#if defined(ENABLE_OTA) && defined(OTA_QSPI_STORE)
mesh::ota::OtaStoreQspiNrf52& store = mesh::ota::ota_ctx().fetch_store;
const uint32_t capacity = store.capacity();
if (capacity != 0) {
snprintf(reply + strlen(reply), 160 - strlen(reply),
"; ext:qspi=%luK owner=ota-raw id=%06lX",
(unsigned long)(capacity / 1024UL),
(unsigned long)store.jedec_id());
} else {
snprintf(reply + strlen(reply), 160 - strlen(reply),
"; ext:qspi=error(%s)", store.last_error());
}
#elif defined(ENABLE_OTA) && defined(OTA_SD_STORE)
uint64_t used_bytes = 0;
uint64_t free_bytes = 0;
mesh::ota::OtaStoreSdNrf52& store = mesh::ota::ota_ctx().fetch_store;
if (store.getSpace(*_board, used_bytes, free_bytes)) {
char total[24];
char used[24];
char free[24];
formatSdCardBytes(total, sizeof(total), used_bytes + free_bytes);
formatSdCardBytes(used, sizeof(used), used_bytes);
formatSdCardBytes(free, sizeof(free), free_bytes);
snprintf(reply + strlen(reply), 160 - strlen(reply),
"; ext:sd=%s used=%s free=%s owner=ota",
total, used, free);
} else {
snprintf(reply + strlen(reply), 160 - strlen(reply),
"; ext:sd=error(%s)", store.last_error());
}
#elif defined(QSPIFLASH)
snprintf(reply + strlen(reply), 160 - strlen(reply),
"; ext:qspi=configured owner=littlefs");
#else
snprintf(reply + strlen(reply), 160 - strlen(reply), "; ext:none");
#endif
#elif defined(RP2040_PLATFORM)
#if defined(PICO_FLASH_SIZE_BYTES) && defined(FS_START) && defined(FS_END)
snprintf(reply, 160,
"> int:rp2040=%luK ifs=%luK layout=fixed; ext:none",
(unsigned long)(PICO_FLASH_SIZE_BYTES / 1024UL),
(unsigned long)(((uintptr_t)FS_END - (uintptr_t)FS_START) / 1024UL));
#elif defined(PICO_FLASH_SIZE_BYTES)
snprintf(reply, 160, "> int:rp2040=%luK layout=fixed; ext:none",
(unsigned long)(PICO_FLASH_SIZE_BYTES / 1024UL));
#else
strcpy(reply, "> int:rp2040 layout=fixed; ext:none");
#endif
#elif defined(STM32_PLATFORM)
snprintf(reply, 160,
"> int:stm32=%luK ifs=0x%lX+%luK layout=fixed; ext:none",
(unsigned long)((FLASH_END_ADDR - FLASH_BASE + 1UL) / 1024UL),
(unsigned long)LFS_FLASH_ADDR_BASE,
(unsigned long)(LFS_FLASH_TOTAL_SIZE / 1024UL));
#else
strcpy(reply, "Error: storage layout unsupported on this platform");
#endif
return true;
}
#if defined(NRF52_PLATFORM) && defined(OTA_SD_STORE)
bool CommonCLI::handleSdCardSetCmd(const char* config, char* reply) {
if (strncmp(config, "sdcard", 6) != 0 ||
@@ -3267,8 +3109,8 @@ bool CommonCLI::handleSdCardGetCmd(const char* config, char* reply) {
} else {
char used[24];
char free[24];
formatSdCardBytes(used, sizeof(used), used_bytes);
formatSdCardBytes(free, sizeof(free), free_bytes);
mesh::cli::formatStorageBytes(used, sizeof(used), used_bytes);
mesh::cli::formatStorageBytes(free, sizeof(free), free_bytes);
snprintf(reply, 160, "> used: %s, free: %s", used, free);
}
} else if (strncmp(query, "ls", 2) == 0 || strncmp(query, "dir", 3) == 0) {
@@ -4566,7 +4408,7 @@ void CommonCLI::handleGetCmd(uint32_t sender_timestamp, char* command, char* rep
#endif
// Observer/MQTT/WiFi/timezone/alert/SNMP commands live in CommonCLI_Observer.cpp.
if (handleObserverGetCmd(sender_timestamp, config, reply)) return;
if (handleStorageLayoutGetCmd(config, reply)) return;
if (mesh::cli::handleStorageLayoutGet(config, *_board, reply, 160)) return;
#if defined(NRF52_PLATFORM) && defined(OTA_SD_STORE)
if (handleSdCardGetCmd(config, reply)) return;
#endif
-1
View File
@@ -754,7 +754,6 @@ class CommonCLI {
void handleGetCmd(uint32_t sender_timestamp, char* command, char* reply);
void handleSetCmd(uint32_t sender_timestamp, char* command, char* reply);
void handleDelCmd(char* command, char* reply);
bool handleStorageLayoutGetCmd(const char* config, char* reply);
#if defined(NRF52_PLATFORM) && defined(OTA_SD_STORE)
bool handleSdCardGetCmd(const char* config, char* reply);
bool handleSdCardSetCmd(const char* config, char* reply);
+34
View File
@@ -0,0 +1,34 @@
#pragma once
#include <stdint.h>
namespace mesh {
namespace wifi {
// Runtime context supplied when shared WebConfig code describes a Companion-
// owned station. A stopped WebConfig session does not mean that station is off.
struct CompanionWiFiRuntimeState {
bool requested;
bool active;
bool credential_reload_pending;
};
enum class CompanionWiFiFallbackState : uint8_t {
OffDisabled,
Inactive,
ReconnectScheduled,
ConnectingOrRetrying,
};
inline CompanionWiFiFallbackState classifyCompanionWiFiFallback(
const CompanionWiFiRuntimeState& state) {
if (!state.requested) return CompanionWiFiFallbackState::OffDisabled;
if (!state.active) return CompanionWiFiFallbackState::Inactive;
if (state.credential_reload_pending) {
return CompanionWiFiFallbackState::ReconnectScheduled;
}
return CompanionWiFiFallbackState::ConnectingOrRetrying;
}
} // namespace wifi
} // namespace mesh
+162
View File
@@ -0,0 +1,162 @@
#include "StorageLayout.h"
#if defined(ESP32_PLATFORM)
#include <Arduino.h>
#include <esp_ota_ops.h>
#include <esp_partition.h>
#elif defined(NRF52_PLATFORM)
#include <stdarg.h>
#include <nrf.h>
#include "ota/OtaFlashLayout_nrf52.h"
#elif defined(STM32_PLATFORM)
#include <InternalFileSystem.h>
#endif
#if defined(ENABLE_OTA)
#include "ota/OtaContext.h"
#endif
namespace mesh {
namespace cli {
#if defined(NRF52_PLATFORM)
static void appendStorageLayout(char* reply, size_t reply_size,
const char* format, ...) {
if (reply == nullptr || reply_size == 0) return;
const size_t used = strlen(reply);
if (used >= reply_size) return;
va_list args;
va_start(args, format);
vsnprintf(reply + used, reply_size - used, format, args);
va_end(args);
}
#endif
void formatStorageLayout(MainBoard& board, char* reply, size_t reply_size) {
if (reply == nullptr || reply_size == 0) return;
reply[0] = 0;
#if defined(ESP32_PLATFORM)
(void)board;
Esp32StorageLayoutWriter writer(reply, reply_size,
ESP.getFlashChipSize());
const esp_partition_t* running = esp_ota_get_running_partition();
esp_partition_iterator_t iterator = esp_partition_find(
ESP_PARTITION_TYPE_ANY, ESP_PARTITION_SUBTYPE_ANY, NULL);
while (iterator != NULL) {
const esp_partition_t* partition = esp_partition_get(iterator);
if (!writer.append(
partition->label, partition->address, partition->size,
running != NULL && partition->address == running->address)) {
break;
}
iterator = esp_partition_next(iterator);
}
if (iterator != NULL) esp_partition_iterator_release(iterator);
writer.finish();
#elif defined(NRF52_PLATFORM)
const uint32_t flash_bytes =
(uint32_t)NRF_FICR->CODEPAGESIZE * (uint32_t)NRF_FICR->CODESIZE;
const uint32_t app_start = mesh::ota::mota_nrf52_app_base();
const uint32_t app_end =
(uint32_t)(uintptr_t)mesh::ota::__flash_arduino_end;
#if defined(NRF52840_XXAA)
const uint32_t internal_fs_start = 0x000ED000UL;
#else
const uint32_t internal_fs_start = 0x0006D000UL;
#endif
const uint32_t internal_fs_size = 7UL * 4096UL;
snprintf(reply, reply_size,
"> int:nrf52=%luK app=0x%lX-0x%lX ifs=0x%lX+%luK",
(unsigned long)(flash_bytes / 1024UL),
(unsigned long)app_start, (unsigned long)app_end,
(unsigned long)internal_fs_start,
(unsigned long)(internal_fs_size / 1024UL));
#if defined(ENABLE_OTA) && defined(OTA_QSPI_STORE)
(void)board;
mesh::ota::OtaStoreQspiNrf52& store = mesh::ota::ota_ctx().fetch_store;
const uint32_t capacity = store.capacity();
if (capacity != 0) {
appendStorageLayout(reply, reply_size,
"; ext:qspi=%luK owner=ota-raw id=%06lX",
(unsigned long)(capacity / 1024UL),
(unsigned long)store.jedec_id());
} else {
appendStorageLayout(reply, reply_size, "; ext:qspi=error(%s)",
store.last_error());
}
#elif defined(ENABLE_OTA) && defined(OTA_SD_STORE)
uint64_t used_bytes = 0;
uint64_t free_bytes = 0;
mesh::ota::OtaStoreSdNrf52& store = mesh::ota::ota_ctx().fetch_store;
if (store.getSpace(board, used_bytes, free_bytes)) {
char total[24];
char used[24];
char free[24];
formatStorageBytes(total, sizeof(total), used_bytes + free_bytes);
formatStorageBytes(used, sizeof(used), used_bytes);
formatStorageBytes(free, sizeof(free), free_bytes);
appendStorageLayout(reply, reply_size,
"; ext:sd=%s used=%s free=%s owner=ota", total,
used, free);
} else {
appendStorageLayout(reply, reply_size, "; ext:sd=error(%s)",
store.last_error());
}
#elif defined(QSPIFLASH)
(void)board;
appendStorageLayout(reply, reply_size,
"; ext:qspi=configured owner=littlefs");
#else
(void)board;
appendStorageLayout(reply, reply_size, "; ext:none");
#endif
#elif defined(RP2040_PLATFORM)
(void)board;
#if defined(PICO_FLASH_SIZE_BYTES) && defined(FS_START) && defined(FS_END)
snprintf(reply, reply_size,
"> int:rp2040=%luK ifs=%luK layout=fixed; ext:none",
(unsigned long)(PICO_FLASH_SIZE_BYTES / 1024UL),
(unsigned long)(((uintptr_t)FS_END - (uintptr_t)FS_START) /
1024UL));
#elif defined(PICO_FLASH_SIZE_BYTES)
snprintf(reply, reply_size,
"> int:rp2040=%luK layout=fixed; ext:none",
(unsigned long)(PICO_FLASH_SIZE_BYTES / 1024UL));
#else
snprintf(reply, reply_size, "> int:rp2040 layout=fixed; ext:none");
#endif
#elif defined(STM32_PLATFORM)
(void)board;
snprintf(reply, reply_size,
"> int:stm32=%luK ifs=0x%lX+%luK layout=fixed; ext:none",
(unsigned long)((FLASH_END_ADDR - FLASH_BASE + 1UL) / 1024UL),
(unsigned long)LFS_FLASH_ADDR_BASE,
(unsigned long)(LFS_FLASH_TOTAL_SIZE / 1024UL));
#else
(void)board;
snprintf(reply, reply_size,
"Error: storage layout unsupported on this platform");
#endif
}
bool handleStorageLayoutGet(const char* config, MainBoard& board, char* reply,
size_t reply_size) {
const StorageLayoutGetMatch match = classifyStorageLayoutGet(config);
if (match == StorageLayoutGetMatch::NotMatched) return false;
if (reply == nullptr || reply_size == 0) return true;
if (match == StorageLayoutGetMatch::InvalidArguments) {
snprintf(reply, reply_size, "Error: use get storage.layout");
} else {
formatStorageLayout(board, reply, reply_size);
}
return true;
}
} // namespace cli
} // namespace mesh
+126
View File
@@ -0,0 +1,126 @@
#pragma once
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
namespace mesh {
class MainBoard;
namespace cli {
enum class StorageLayoutGetMatch : uint8_t {
NotMatched = 0,
Valid,
InvalidArguments,
};
// `config` is the portion following "get ". Keep recognition independent of
// any role's CLI wrapper so CommonCLI and Companion command 0x42 expose the
// same diagnostic and the same malformed-command response.
inline StorageLayoutGetMatch classifyStorageLayoutGet(const char* config) {
static const char key[] = "storage.layout";
const size_t key_len = sizeof(key) - 1;
if (config == nullptr || strncmp(config, key, key_len) != 0 ||
(config[key_len] != 0 && config[key_len] != ' ' &&
config[key_len] != '\t')) {
return StorageLayoutGetMatch::NotMatched;
}
return config[key_len] == 0 ? StorageLayoutGetMatch::Valid
: StorageLayoutGetMatch::InvalidArguments;
}
inline void formatStorageBytes(char* out, size_t out_len, uint64_t bytes) {
if (out == nullptr || out_len == 0) return;
static const char* const units[] = {"B", "KiB", "MiB", "GiB", "TiB"};
uint64_t unit_size = 1;
uint8_t unit = 0;
while (unit < 4 && bytes >= unit_size * 1024ULL) {
unit_size *= 1024ULL;
unit++;
}
if (unit == 0) {
snprintf(out, out_len, "%lu B", (unsigned long)bytes);
return;
}
uint64_t whole = bytes / unit_size;
uint32_t tenths =
(uint32_t)(((bytes % unit_size) * 10ULL + unit_size / 2ULL) /
unit_size);
if (tenths == 10) {
whole++;
tenths = 0;
}
snprintf(out, out_len, "%lu.%lu %s", (unsigned long)whole,
(unsigned long)tenths, units[unit]);
}
// The hardware-facing formatter walks ESP-IDF's live partition iterator. This
// small writer keeps its bounded text policy host-testable without mocking IDF.
class Esp32StorageLayoutWriter {
public:
Esp32StorageLayoutWriter(char* out, size_t out_len, uint32_t flash_bytes)
: _out(out), _out_len(out_len), _has_partition(false),
_truncated(false) {
if (_out == nullptr || _out_len == 0) return;
snprintf(_out, _out_len, "> int:esp32=%luK ext:none; ",
(unsigned long)(flash_bytes / 1024UL));
}
bool append(const char* label, uint32_t address, uint32_t size,
bool running) {
if (_out == nullptr || _out_len == 0 || _truncated) return false;
char entry[48];
snprintf(entry, sizeof(entry), "%s%s%s@0x%lX+%luK",
_has_partition ? "," : "", label != nullptr ? label : "",
running ? "*" : "", (unsigned long)address,
(unsigned long)(size / 1024UL));
const size_t used = strlen(_out);
const size_t entry_len = strlen(entry);
// Preserve one spare byte beyond the terminator, matching the original
// CommonCLI response policy and leaving room for an ellipsis when possible.
if (used + entry_len + 1 >= _out_len) {
_truncated = true;
return false;
}
memcpy(_out + used, entry, entry_len + 1);
_has_partition = true;
return true;
}
void finish() {
if (_out == nullptr || _out_len == 0) return;
const size_t used = strlen(_out);
if (!_has_partition) {
if (used < _out_len) {
snprintf(_out + used, _out_len - used, "partitions=none");
}
} else if (_truncated && used + 4 < _out_len) {
memcpy(_out + used, ",...", 5);
}
}
bool truncated() const { return _truncated; }
private:
char* _out;
size_t _out_len;
bool _has_partition;
bool _truncated;
};
void formatStorageLayout(MainBoard& board, char* reply, size_t reply_size);
// Returns false only when `config` is not this command. Recognized malformed
// requests are consumed and receive the canonical usage response.
bool handleStorageLayoutGet(const char* config, MainBoard& board, char* reply,
size_t reply_size);
} // namespace cli
} // namespace mesh
+175
View File
@@ -1,5 +1,6 @@
#pragma once
#include <atomic>
#include <stdint.h>
#include <string.h>
@@ -40,6 +41,180 @@ inline bool isUsbMotaOwnerTransitionCommand(const char* command) {
&& isUsbMotaOwnerTransitionCommand(command, strlen(command));
}
// A deliberate HWCDC detach can produce a burst of BUS_RESET callbacks while
// the host enumerates the clean transport. Keep ignoring that whole burst until
// actual post-clean RX/TX activity proves that a new session has begun. Unlike
// a one-shot boolean exchange, repeated reset callbacks do not consume the
// clean-transport proof and cannot start a detach/reset loop.
class UsbSelfResetBurstGuard {
std::atomic<bool> _clean_transport_waiting_for_activity{false};
public:
void expectSelfResetBurst() {
_clean_transport_waiting_for_activity.store(
true, std::memory_order_release);
}
bool shouldIgnoreBusReset() const {
return _clean_transport_waiting_for_activity.load(
std::memory_order_acquire);
}
void notePostCleanActivity() {
_clean_transport_waiting_for_activity.store(
false, std::memory_order_release);
}
};
// HWCDC exposes a physical/SOF host signal but no DTR/open state. Its framework
// filter is only a few milliseconds, so apply a second, meaningful debounce
// before reporting a transport boundary. The response route retains its longer
// grace independently, and sustained loss remains a conservative fallback.
class UsbHostPresenceDebouncer {
bool _host_seen = false;
bool _physical_host_seen = false;
bool _loss_observed = false;
bool _host_loss_edge_reported = false;
bool _host_loss_edge_pending = false;
bool _sustained_loss_pending = false;
bool _completed_frame_seen = false;
bool _finite_reply_was_pending = false;
bool _finite_reply_drain_active = false;
uint32_t _loss_observed_at = 0;
uint32_t _last_completed_frame_count = 0;
uint32_t _finite_reply_drain_started_at = 0;
bool retainFiniteReplyLease(bool pending, uint32_t now,
uint32_t drain_grace_ms) {
if (pending) {
_finite_reply_was_pending = true;
_finite_reply_drain_active = false;
return true;
}
if (_finite_reply_was_pending) {
_finite_reply_was_pending = false;
_finite_reply_drain_active = true;
_finite_reply_drain_started_at = now;
}
if (!_finite_reply_drain_active) return false;
if ((uint32_t)(now - _finite_reply_drain_started_at) < drain_grace_ms) {
return true;
}
_finite_reply_drain_active = false;
return false;
}
public:
bool observeHost(bool host_present, uint32_t now,
uint32_t host_loss_edge_ms,
uint32_t host_loss_grace_ms) {
if (_sustained_loss_pending) return false;
if (host_present) {
_host_seen = true;
_physical_host_seen = true;
_loss_observed = false;
_host_loss_edge_reported = false;
return true;
}
if (!_host_seen) return false;
if (!_loss_observed) {
_loss_observed = true;
_loss_observed_at = now;
return true;
}
const uint32_t loss_age = (uint32_t)(now - _loss_observed_at);
if (!_host_loss_edge_reported && _physical_host_seen
&& loss_age >= host_loss_edge_ms) {
// Keep this shorter than the response-affinity grace, but long enough to
// reject the framework's transient five-millisecond SOF gaps. This still
// recovers an actual unplug/re-enumeration when its BUS_RESET event was
// dropped by the framework's finite event queue.
_host_loss_edge_reported = true;
_host_loss_edge_pending = true;
}
if (loss_age < host_loss_grace_ms) {
return true;
}
_host_seen = false;
_physical_host_seen = false;
_loss_observed = false;
_sustained_loss_pending = true;
return false;
}
void noteClientActivity() {
if (_sustained_loss_pending) return;
_host_seen = true;
_loss_observed = false;
}
bool isClientConnected(bool host_present, uint32_t now,
bool has_received_frame,
uint32_t last_frame_at,
uint32_t completed_frame_count,
uint32_t frame_reply_grace_ms,
uint32_t client_idle_timeout_ms,
uint32_t host_loss_edge_ms,
uint32_t host_loss_grace_ms,
bool finite_reply_pending) {
// A newly completed Binary frame proves a host session even when HWCDC's
// SOF signal was already false. Arm loss tracking once per frame count;
// doing this on every poll would continually restart the debounce timer.
if (has_received_frame
&& (!_completed_frame_seen
|| completed_frame_count != _last_completed_frame_count)) {
_completed_frame_seen = true;
_last_completed_frame_count = completed_frame_count;
noteClientActivity();
}
// Sample the physical signal even during the immediate-frame lease so a
// delayed operation has a fresh last-positive timestamp to rely on.
const bool host_recent =
observeHost(host_present, now, host_loss_edge_ms,
host_loss_grace_ms);
if (_sustained_loss_pending) return false;
if (!has_received_frame) return false;
const uint32_t frame_age = (uint32_t)(now - last_frame_at);
// Only a bounded, already-routed operation may extend the absolute idle
// cap. Its true->false transition grants one short drain window for the
// final frame which was queued just before the operation cleared itself.
const bool finite_reply_lease = retainFiniteReplyLease(
finite_reply_pending, now, frame_reply_grace_ms);
if (frame_age < frame_reply_grace_ms) return true;
return host_recent
&& (frame_age < client_idle_timeout_ms || finite_reply_lease);
}
bool takeSustainedHostLoss() {
const bool pending = _sustained_loss_pending;
_sustained_loss_pending = false;
return pending;
}
bool takeHostLossEdge() {
const bool pending = _host_loss_edge_pending;
_host_loss_edge_pending = false;
return pending;
}
void reset() {
_host_seen = false;
_physical_host_seen = false;
_loss_observed = false;
_host_loss_edge_reported = false;
_host_loss_edge_pending = false;
_sustained_loss_pending = false;
_completed_frame_seen = false;
_finite_reply_was_pending = false;
_finite_reply_drain_active = false;
_loss_observed_at = 0;
_last_completed_frame_count = 0;
_finite_reply_drain_started_at = 0;
}
};
// Coordinates the Full Companion USB startup handoff without consuming the
// '<' byte. ArduinoSerialInterface remains the only binary protocol parser.
class UsbBinaryStartupProbe {
+330 -6
View File
@@ -4,9 +4,22 @@
#include <Arduino.h>
#include <atomic>
#if defined(NRF52_PLATFORM)
#if defined(ESP32) && defined(ARDUINO_USB_MODE) && ARDUINO_USB_MODE == 1 \
&& defined(ARDUINO_USB_CDC_ON_BOOT) && ARDUINO_USB_CDC_ON_BOOT \
&& defined(ENABLE_USB_INTERFACE)
#define MESH_ESP32_HWCDC_SESSION_GUARD 1
#include "esp_idf_version.h"
#include "hal/usb_serial_jtag_ll.h"
#else
#define MESH_ESP32_HWCDC_SESSION_GUARD 0
#endif
#if defined(NRF52_PLATFORM) || MESH_ESP32_HWCDC_SESSION_GUARD
#include "NonBlockingWriteStream.h"
#endif
#if MESH_ESP32_HWCDC_SESSION_GUARD
#include "UsbAsciiBinarySwitch.h"
#endif
#if defined(NRF52_PLATFORM) && \
(defined(ENABLE_USB_INTERFACE) || defined(OTA_FOLDER_SERIAL))
@@ -59,6 +72,156 @@ class NullUsbLoggingStream : public Stream {
static NullUsbLoggingStream null_usb_logging_stream;
#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
// a disconnect still checks the current session at the actual write boundary.
static std::atomic<uint32_t> esp32_hwcdc_access_generation{0};
static std::atomic<uint32_t> esp32_hwcdc_allowed_generation{0};
static std::atomic<uint32_t> esp32_hwcdc_bus_reset_generation{0};
static UsbSelfResetBurstGuard esp32_hwcdc_self_reset_guard;
// HWCDC::write() retains bytes in its software ring when the framework's raw
// five-millisecond SOF detector happens to report false. In that path the core
// does not leave SERIAL_IN_EMPTY enabled, so a valid Companion response can
// remain parked until a later request happens to kick TX. Keep requesting that
// interrupt until the framework reports actual TX progress.
static std::atomic<bool> esp32_hwcdc_tx_kick_pending{false};
static portMUX_TYPE esp32_hwcdc_session_mux = portMUX_INITIALIZER_UNLOCKED;
static uint32_t esp32_hwcdc_taken_bus_reset_generation = 0;
static bool esp32_hwcdc_event_handler_registered = false;
static std::atomic<size_t> esp32_hwcdc_tx_buffer_capacity{
MESH_ESP32_USB_TX_BUFFER_SIZE};
// A busy writer or temporary allocation failure may require more than one main
// loop to purge. Keep the original detach state/generation across retries so a
// failed attempt never reattaches stale bytes or turns into a reboot loop.
static bool esp32_hwcdc_cleanup_pending = false;
static bool esp32_hwcdc_restore_pad_enabled = false;
static uint32_t esp32_hwcdc_cleanup_generation = 0;
static bool canAccessEsp32Hwcdc(void*) {
return esp32_hwcdc_allowed_generation.load(std::memory_order_acquire)
== esp32_hwcdc_access_generation.load(std::memory_order_acquire);
}
static void handleEsp32HwcdcEvent(void*, esp_event_base_t, int32_t event_id,
void*) {
if (event_id == ARDUINO_HW_CDC_BUS_RESET_EVENT) {
// A host may issue several reset requests while enumerating the clean
// transport. Suppress the complete burst; post-clean traffic below ends
// the exemption before any later active-session reset can be ignored.
if (esp32_hwcdc_self_reset_guard.shouldIgnoreBusReset()) {
return;
}
// Quarantine reads and writes before publishing the boundary to the main
// loop. If this callback lands just after that loop sampled the generation,
// no old-session parser or producer can run during the intervening pass.
portENTER_CRITICAL(&esp32_hwcdc_session_mux);
esp32_hwcdc_access_generation.fetch_add(
1, std::memory_order_acq_rel);
esp32_hwcdc_tx_kick_pending.store(false, std::memory_order_release);
usb_serial_jtag_ll_disable_intr_mask(
USB_SERIAL_JTAG_INTR_SERIAL_IN_EMPTY);
portEXIT_CRITICAL(&esp32_hwcdc_session_mux);
Serial.setDebugOutput(false);
esp32_hwcdc_bus_reset_generation.fetch_add(
1, std::memory_order_acq_rel);
return;
}
if (event_id == ARDUINO_HW_CDC_RX_EVENT
|| event_id == ARDUINO_HW_CDC_TX_EVENT) {
// If no self-reset event was delivered, post-clean traffic proves that the
// expected enumeration is over. A subsequent reset must not be ignored.
esp32_hwcdc_self_reset_guard.notePostCleanActivity();
}
}
class Esp32HwcdcSessionStream : public Stream {
public:
int available() override {
const int count = Serial.available();
if (count > 0) noteActivity();
return count;
}
int read() override {
const int value = Serial.read();
if (value >= 0) noteActivity();
return value;
}
int peek() override {
const int value = Serial.peek();
if (value >= 0) noteActivity();
return value;
}
void flush() override { Serial.flush(); }
int availableForWrite() override { return Serial.availableForWrite(); }
size_t write(uint8_t value) override { return write(&value, 1); }
size_t write(const uint8_t* data, size_t size) override {
if (data == nullptr || size == 0) return 0;
esp32_hwcdc_tx_kick_pending.store(true, std::memory_order_release);
return Serial.write(data, size);
}
private:
static void noteActivity() {
esp32_hwcdc_self_reset_guard.notePostCleanActivity();
}
};
static Esp32HwcdcSessionStream esp32_hwcdc_session_stream;
static size_t writeEsp32HwcdcOnce(void*, const uint8_t* data, size_t size) {
return esp32_hwcdc_session_stream.write(data, size);
}
static SingleAttemptNonBlockingStream guarded_esp32_hwcdc_port(
esp32_hwcdc_session_stream, writeEsp32HwcdcOnce, nullptr,
canAccessEsp32Hwcdc);
static AtomicWholeRecordNonBlockingStream<11>
guarded_esp32_hwcdc_mota_port(guarded_esp32_hwcdc_port);
static void serviceEsp32HwcdcTxKickExclusive(void*) {
if (!esp32_hwcdc_tx_kick_pending.load(std::memory_order_acquire)
|| !canAccessEsp32Hwcdc(nullptr)) {
return;
}
// Unlike the asynchronous TX event queue, the ring's free capacity is
// direct proof that every tracked byte has left HWCDC's software queue.
// Sample it while the shared producer gate excludes every MeshCore writer.
const size_t tx_capacity = esp32_hwcdc_tx_buffer_capacity.load(
std::memory_order_acquire);
if (tx_capacity != 0 && Serial.availableForWrite() >= tx_capacity) {
esp32_hwcdc_tx_kick_pending.store(false, std::memory_order_release);
return;
}
if (!Serial.isPlugged()) return;
// Match the framework's normal connected-write kick. Serialize the final
// generation check and register writes with BUS_RESET quarantine so a stale
// service pass cannot re-enable TX after the session has been closed.
portENTER_CRITICAL(&esp32_hwcdc_session_mux);
if (esp32_hwcdc_tx_kick_pending.load(std::memory_order_acquire)
&& canAccessEsp32Hwcdc(nullptr) && Serial.isPlugged()) {
usb_serial_jtag_ll_txfifo_flush();
usb_serial_jtag_ll_ena_intr_mask(
USB_SERIAL_JTAG_INTR_SERIAL_IN_EMPTY);
}
portEXIT_CRITICAL(&esp32_hwcdc_session_mux);
}
static void serviceEsp32HwcdcTxKick() {
if (!esp32_hwcdc_tx_kick_pending.load(std::memory_order_acquire)) return;
(void)guarded_esp32_hwcdc_port.tryRunExclusive(
serviceEsp32HwcdcTxKickExclusive);
}
#endif
#if MESH_NRF52_PRIMARY_USB_NONBLOCKING
#if defined(ENABLE_USB_INTERFACE)
// Writers/readers may access CDC0 only when DTR is high and the application has
@@ -156,9 +319,17 @@ static uint32_t primary_usb_terminal_taken_reset_generation = 0;
static void setPlatformDebugOutputEnabled(bool enabled) {
#if defined(ESP32_PLATFORM) && defined(ENABLE_USB_INTERFACE)
// Arduino-ESP32 log_e()/ESP-IDF diagnostics otherwise write straight to
// the same UART/CDC stream used by Binary Companion. Keep that low-level
// route under the same runtime gate as MeshCore's own diagnostics.
// the same UART/CDC stream used by Binary Companion.
#if MESH_ESP32_HWCDC_SESSION_GUARD
// HWCDC's framework putc hook bypasses the guarded Stream and cannot make
// its check-plus-write atomic with a BUS_RESET callback. Keep that raw route
// disabled on a shared protocol port; MeshCore diagnostics still use the
// guarded usbLoggingPort() below.
(void)enabled;
Serial.setDebugOutput(false);
#else
Serial.setDebugOutput(enabled);
#endif
#else
(void)enabled;
#endif
@@ -388,12 +559,26 @@ bool saveUsbLoggingBootPreference(bool enabled) {
return true;
}
void setUsbCompanionTxBufferCapacity(size_t capacity) {
#if MESH_ESP32_HWCDC_SESSION_GUARD
esp32_hwcdc_tx_buffer_capacity.store(capacity, std::memory_order_release);
#else
(void)capacity;
#endif
}
void beginUsbLoggingPort() {
// setup() calls this once before role preferences are loaded and again
// afterwards. The first call silences framework diagnostics on a protected
// ESP32 Companion stream; setUsbLoggingEnabled() restores them only when the
// saved setting explicitly enables logging.
setPlatformDebugOutputEnabled(isUsbLoggingEnabled());
#if MESH_ESP32_HWCDC_SESSION_GUARD
if (!esp32_hwcdc_event_handler_registered) {
Serial.onEvent(ARDUINO_HW_CDC_ANY_EVENT, handleEsp32HwcdcEvent);
esp32_hwcdc_event_handler_registered = true;
}
#endif
#if defined(MESH_DUAL_CDC_LOGGING)
if (dedicated_usb_logging_port_started
|| !usb_logging_preference_known.load(std::memory_order_relaxed)
@@ -459,6 +644,129 @@ void serviceUsbLoggingPort() {
#endif
}
struct Esp32HwcdcPurgeResult {
bool tx_empty = false;
};
#if MESH_ESP32_HWCDC_SESSION_GUARD
static bool detachEsp32HwcdcPads() {
#if ESP_IDF_VERSION_MAJOR >= 5
// IDF 5.x replaced the C3/S3 state-preserving light-sleep helper with the
// unified PHY query/setter pair also used by C6.
const bool enabled = usb_serial_jtag_ll_phy_is_pad_enabled();
usb_serial_jtag_ll_phy_enable_pad(false);
return enabled;
#else
// IDF 4.x (Arduino-ESP32 2.x C3/S3) supplies this combined helper.
return usb_serial_jtag_ll_pad_backup_and_disable();
#endif
}
static void restoreEsp32HwcdcPads(bool enabled) {
#if ESP_IDF_VERSION_MAJOR >= 5
usb_serial_jtag_ll_phy_enable_pad(enabled);
#else
usb_serial_jtag_ll_enable_pad(enabled);
#endif
}
static void purgeEsp32HwcdcQueues(void* opaque) {
Esp32HwcdcPurgeResult* result =
static_cast<Esp32HwcdcPurgeResult*>(opaque);
size_t tx_capacity = esp32_hwcdc_tx_buffer_capacity.load(
std::memory_order_acquire);
if (tx_capacity == 0) {
// Never replace HWCDC's ring after begin() has enabled its ISR. Without a
// known empty capacity we cannot prove the old session was purged, so keep
// the transport quarantined and let the caller retry at a bounded rate.
while (Serial.read() >= 0) {}
return;
}
const uint32_t purge_started = millis();
uint8_t flush_attempts = 0;
do {
// The bundled HWCDC flush removes only one contiguous BYTEBUF item, and a
// busy TX mutex makes it return without a result. Require at least two
// passes, then verify the configured empty capacity under a deadline.
Serial.flush();
++flush_attempts;
result->tx_empty = flush_attempts >= 2 && tx_capacity != 0
&& Serial.availableForWrite() >= tx_capacity;
if (!result->tx_empty) delay(1);
} while (!result->tx_empty
&& (uint32_t)(millis() - purge_started) < 100U);
while (Serial.read() >= 0) {}
}
#endif
bool resetUsbCompanionTransport() {
#if 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);
usb_serial_jtag_ll_disable_intr_mask(
USB_SERIAL_JTAG_INTR_SERIAL_IN_EMPTY);
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);
}
}
// 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.
Esp32HwcdcPurgeResult result;
const uint32_t writer_deadline = millis();
bool ran_exclusive = false;
do {
ran_exclusive = guarded_esp32_hwcdc_port.tryRunExclusive(
purgeEsp32HwcdcQueues, &result);
if (!ran_exclusive) delay(1);
} while (!ran_exclusive
&& (uint32_t)(millis() - writer_deadline) < 50U);
if (!ran_exclusive || !result.tx_empty) {
// Leave the PHY and producer gate closed. The caller retries from a later
// loop; rebooting here can create an enumeration watchdog/restart cycle.
return false;
}
esp32_hwcdc_self_reset_guard.expectSelfResetBurst();
restoreEsp32HwcdcPads(esp32_hwcdc_restore_pad_enabled);
// Publish only the epoch actually purged. If another BUS_RESET arrived
// during cleanup its newer generation remains quarantined for the next pass.
portENTER_CRITICAL(&esp32_hwcdc_session_mux);
esp32_hwcdc_tx_kick_pending.store(false, std::memory_order_release);
esp32_hwcdc_allowed_generation.store(
esp32_hwcdc_cleanup_generation, std::memory_order_release);
portEXIT_CRITICAL(&esp32_hwcdc_session_mux);
esp32_hwcdc_cleanup_pending = false;
// A concurrent runtime preference change is authoritative; never restore a
// stale snapshot taken before the purge.
setPlatformDebugOutputEnabled(isUsbLoggingEnabled());
#endif
return true;
}
Stream& usbLoggingPort() {
#if defined(MESH_DUAL_CDC_LOGGING)
if (isUsbLoggingEnabled() && dedicated_usb_logging_port_started
@@ -468,7 +776,9 @@ Stream& usbLoggingPort() {
return null_usb_logging_stream;
#else
if (!isUsbLoggingEnabled()) return null_usb_logging_stream;
#if defined(NRF52_PLATFORM)
#if MESH_ESP32_HWCDC_SESSION_GUARD
return guarded_esp32_hwcdc_port;
#elif defined(NRF52_PLATFORM)
return nonblocking_primary_usb_logging_port;
#else
return Serial;
@@ -477,7 +787,9 @@ Stream& usbLoggingPort() {
}
Stream& usbCompanionPort() {
#if MESH_NRF52_PRIMARY_USB_NONBLOCKING
#if MESH_ESP32_HWCDC_SESSION_GUARD
return guarded_esp32_hwcdc_port;
#elif MESH_NRF52_PRIMARY_USB_NONBLOCKING
return nonblocking_primary_usb_companion_port;
#else
return Serial;
@@ -485,7 +797,9 @@ Stream& usbCompanionPort() {
}
Stream& usbMotaPort() {
#if MESH_NRF52_PRIMARY_USB_NONBLOCKING
#if MESH_ESP32_HWCDC_SESSION_GUARD
return guarded_esp32_hwcdc_mota_port;
#elif MESH_NRF52_PRIMARY_USB_NONBLOCKING
return nonblocking_primary_usb_mota_port;
#else
return usbCompanionPort();
@@ -509,6 +823,8 @@ void serviceUsbTerminalPort() {
primary_usb_terminal_seen_reset_generation = reset_generation;
}
buffered_primary_usb_terminal_port.service();
#elif MESH_ESP32_HWCDC_SESSION_GUARD
serviceEsp32HwcdcTxKick();
#endif
}
@@ -535,6 +851,14 @@ bool takeUsbTerminalSessionReset() {
}
primary_usb_terminal_taken_reset_generation = reset_generation;
return true;
#elif MESH_ESP32_HWCDC_SESSION_GUARD && defined(ENABLE_USB_INTERFACE)
const uint32_t reset_generation =
esp32_hwcdc_bus_reset_generation.load(std::memory_order_acquire);
if (reset_generation == esp32_hwcdc_taken_bus_reset_generation) {
return false;
}
esp32_hwcdc_taken_bus_reset_generation = reset_generation;
return true;
#else
return false;
#endif
+18 -3
View File
@@ -16,6 +16,10 @@
namespace mesh {
#ifndef MESH_ESP32_USB_TX_BUFFER_SIZE
#define MESH_ESP32_USB_TX_BUFFER_SIZE 4096
#endif
namespace detail {
// Keep the identity-marker reconnect rule pure so host tests can exercise the
@@ -40,6 +44,11 @@ void setUsbLoggingEnabled(bool enabled);
// the normal role preferences.
bool saveUsbLoggingBootPreference(bool enabled);
// Record the HWCDC TX ring size actually allocated during early setup. A zero
// value keeps reset cleanup quarantined and eligible for a minimum-size retry
// instead of mistaking an allocation failure for a permanently non-empty ring.
void setUsbCompanionTxBufferCapacity(size_t capacity);
// Start the optional dedicated USB logging interface. Ordinary and single-TTY
// builds use Serial; nRF52 Full Companion uses a second CDC ACM port.
void beginUsbLoggingPort();
@@ -66,14 +75,20 @@ Stream& usbTerminalPort();
void serviceUsbTerminalPort();
void discardUsbTerminalOutput();
bool hasPendingUsbTerminalOutput();
// Consume an exact CDC0 DTR-low edge captured in TinyUSB's owner task. This is
// separate from polling the current DTR value: Windows can close and reopen a
// COM handle between two application-loop iterations.
// 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
// independent of polling current line/SOF state; ESP32 retains that poll as a
// fallback because its bundled framework event queue is finite.
bool takeUsbTerminalSessionReset();
// After the application has reset its protocol state, atomically purge any
// CDC0 writer that raced the close callback and reopen the producer gate. A
// false result is a zero-wait busy indication; retry it next loop.
bool tryCompleteUsbTerminalSessionReset();
// Purge platform USB-driver bytes at a confirmed host-session boundary. On
// ESP32 HWCDC this briefly detaches the PHY and gates diagnostics so stale RX
// or TX data cannot cross into a newly enumerated host session. A false result
// leaves that quarantine intact and should be retried from a later loop.
bool resetUsbCompanionTransport();
bool hasDedicatedUsbLoggingPort();
bool isDedicatedUsbLoggingPortConfigured();
bool usbLoggingInterfaceRestartRequired();
File diff suppressed because it is too large. Load diff
+30 -1
View File
@@ -656,7 +656,9 @@ bool WebConfigServer::formatWiFiCliStatus(char* reply, size_t reply_len) {
return true;
}
bool WebConfigServer::formatWiFiStatus(char* reply, size_t reply_len) {
bool WebConfigServer::formatWiFiStatus(
char* reply, size_t reply_len,
const mesh::wifi::CompanionWiFiRuntimeState* companion_runtime) {
if (!reply || reply_len == 0) return false;
char ssid[32] = "";
@@ -700,6 +702,31 @@ bool WebConfigServer::formatWiFiStatus(char* reply, size_t reply_len) {
return true;
}
// Companion owns its station independently of the WebConfig lifecycle. Once
// WebConfig stops, MODE_OFF cannot distinguish a disabled radio from a
// deferred or active Companion reconnect.
if (companion_runtime) {
switch (mesh::wifi::classifyCompanionWiFiFallback(*companion_runtime)) {
case mesh::wifi::CompanionWiFiFallbackState::OffDisabled:
snprintf(reply, reply_len,
"> off, WiFi disabled; configured SSID: %s", ssid);
appendOtaSeederStatus(reply, reply_len);
return true;
case mesh::wifi::CompanionWiFiFallbackState::Inactive:
snprintf(reply, reply_len,
"> inactive, WiFi enabled but services stopped; configured SSID: %s",
ssid);
appendOtaSeederStatus(reply, reply_len);
return true;
case mesh::wifi::CompanionWiFiFallbackState::ReconnectScheduled:
snprintf(reply, reply_len, "> reconnect scheduled, SSID: %s", ssid);
appendOtaSeederStatus(reply, reply_len);
return true;
case mesh::wifi::CompanionWiFiFallbackState::ConnectingOrRetrying:
break;
}
}
switch (status) {
case WL_NO_SSID_AVAIL:
snprintf(reply, reply_len, "> failed, SSID not found: %s", ssid);
@@ -713,6 +740,8 @@ bool WebConfigServer::formatWiFiStatus(char* reply, size_t reply_len) {
default:
if (active && active->_mode == MODE_LAN) {
snprintf(reply, reply_len, "> disconnected, SSID: %s", ssid);
} else if (companion_runtime) {
snprintf(reply, reply_len, "> connecting/retrying, SSID: %s", ssid);
} else {
snprintf(reply, reply_len,
"> off, configured SSID: %s; run 'start webconfig'", ssid);
+4 -1
View File
@@ -27,6 +27,7 @@
#include <Arduino.h>
#include <freertos/FreeRTOS.h>
#include <freertos/semphr.h>
#include <helpers/CompanionWiFiStatus.h>
#include <helpers/WebConfigBatch.h>
#include <helpers/WiFiPowerSave.h>
#include <helpers/WiFiReconnectPolicy.h>
@@ -183,7 +184,9 @@ public:
static bool setWiFiCliEnabled(const char* value, char* reply,
size_t reply_len);
static bool formatWiFiSSID(char* reply, size_t reply_len);
static bool formatWiFiStatus(char* reply, size_t reply_len);
static bool formatWiFiStatus(
char* reply, size_t reply_len,
const mesh::wifi::CompanionWiFiRuntimeState* companion_runtime = NULL);
static bool formatWiFiPowerSave(char* reply, size_t reply_len);
static bool formatWiFiCliStatus(char* reply, size_t reply_len);
+9 -4
View File
@@ -23,10 +23,15 @@
#if defined(OTA_FOLDER_SERIAL)
#include "MotaSourceSerial.h" // relay an external folder served by a host daemon over the USB serial
#ifndef OTA_FOLDER_SERIAL_STREAM
#if defined(NRF52_PLATFORM)
// Adafruit's CDC write waits while an open host stops reading. Every
// default nRF52 serial-folder request uses a whole-record facade over one
// TinyUSB attempt; dedicated-UART overrides retain their normal stream.
#if defined(NRF52_PLATFORM) \
|| (defined(ESP32) && defined(ARDUINO_USB_MODE) \
&& ARDUINO_USB_MODE == 1 \
&& defined(ARDUINO_USB_CDC_ON_BOOT) \
&& ARDUINO_USB_CDC_ON_BOOT \
&& defined(ENABLE_USB_INTERFACE))
// 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