Merge latest changes and retain TLS headroom during MQTT recovery

This commit is contained in:
mikecarper committed 2026-10-27 11:45:03 -07:00
commit 24e7ab1eaf
61 files changed
+2003 -205

No files matched your search

+16 -3
View File
@@ -6,16 +6,28 @@
namespace mesh {
template<class Frame, size_t Count> class InlineRetainedFrames {
Frame frames[Count];
public:
static constexpr size_t frame_count = Count;
Frame& at(size_t index) { return frames[index]; }
};
// One owner at a time: an offline FIFO borrows the workspace's storage while
// idle. Switching owners compacts the ring in place, without allocating RAM or
// dropping unread frames. The caller owns the FIFO's length and head index.
template<class Frame, size_t Capacity, size_t Reserved, class Workspace>
// Qualified boards can supply a physically separate retained-frame bank. It
// replaces only existing retained slots, never the extra frames or workspace.
template<class Frame, size_t Capacity, size_t Reserved, class Workspace,
class RetainedFrames = InlineRetainedFrames<Frame, Reserved>>
class BorrowableFrameBuffer {
static_assert(Reserved > 0 && Reserved < Capacity, "Invalid shared queue capacities");
static_assert(RetainedFrames::frame_count == Reserved,
"The retained backing must preserve every active-OTA slot");
struct ExtraFrames { Frame frames[Capacity - Reserved]; };
static_assert(sizeof(Workspace) <= sizeof(ExtraFrames), "mOTA exceeds borrowed queue storage");
Frame _retained[Reserved];
RetainedFrames _retained;
union Extra {
ExtraFrames queue;
Workspace workspace;
@@ -45,6 +57,7 @@ class BorrowableFrameBuffer {
public:
BorrowableFrameBuffer() = default;
BorrowableFrameBuffer(Frame* fast, Frame* slow) : _retained(fast, slow) {}
BorrowableFrameBuffer(const BorrowableFrameBuffer&) = delete;
BorrowableFrameBuffer& operator=(const BorrowableFrameBuffer&) = delete;
~BorrowableFrameBuffer() {
@@ -53,7 +66,7 @@ public:
size_t capacity() const { return _borrowed ? Reserved : Capacity; }
Frame& at(size_t physical_index) {
return physical_index < Reserved ? _retained[physical_index]
return physical_index < Reserved ? _retained.at(physical_index)
: _extra.queue.frames[physical_index - Reserved];
}
+6 -2
View File
@@ -16,8 +16,7 @@
#if !defined(ESP32_PLATFORM) || !defined(COMPANION_RADIO_FULL)
#error "RTC offline frames require a qualified ESP32 Full Companion recipe"
#endif
#if defined(BOARD_HAS_PSRAM) || defined(OTA_SHARED_COMPANION_QUEUE) \
|| ONE_KEY_DM_SHARED_OFFLINE_QUEUE
#if defined(BOARD_HAS_PSRAM) || ONE_KEY_DM_SHARED_OFFLINE_QUEUE
#error "RTC offline frames require the independent fixed-capacity queue"
#endif
#include <sdkconfig.h>
@@ -36,6 +35,10 @@
#if COMPANION_RTC_SLOW_OFFLINE_FRAMES && !defined(CONFIG_IDF_TARGET_ESP32S3)
#error "The separate RTC SLOW offline-frame bank requires ESP32-S3"
#endif
#if defined(OTA_SHARED_COMPANION_QUEUE) \
&& (!defined(CONFIG_IDF_TARGET_ESP32C3) || COMPANION_RTC_SLOW_OFFLINE_FRAMES)
#error "RTC retained shared-OTA frames are qualified only on ESP32-C3 FAST memory"
#endif
namespace mesh {
namespace companion_rtc {
@@ -75,6 +78,7 @@ template<typename Frame, size_t Count> class CompanionRtcQueue {
}
public:
static constexpr size_t frame_count = Count;
CompanionRtcQueue(Frame* fast, Frame* slow) : fast_frames(fast), slow_frames(slow) {
if ((FastCount && (!fast || reinterpret_cast<uintptr_t>(fast) % 4))
|| (SlowCount && (!slow || reinterpret_cast<uintptr_t>(slow) % 4))) abort();
+41 -5
View File
@@ -11,6 +11,18 @@ namespace MQTTConnectionAdmission {
static const size_t kDmaReserveBytes = 16384;
static const size_t kDmaLargestBytes = 4096;
// Keep the packet-publishing guard and connection admission on the same floor.
// A new optional broker must not consume the contiguous block that existing
// brokers need to continue forwarding packets.
// SDK QoS0 writes are fragmented into the pinned 896-byte wire buffer.
// PSRAM-backed JSON and TLS need DMA scratch, not another 16 KiB JSON block.
static const size_t kPsramPublishLargestBytes = 4096;
static_assert(kPsramPublishLargestBytes == kDmaLargestBytes,
"Connection and publish DMA scratch floors must agree");
// Incoming TLS handshake/records are not bounded by our outgoing MQTT buffer.
// Preserve the existing TLS connection floor independently of publication.
static const size_t kPsramTlsLargestBytes = 16000;
static const size_t kInternalPublishLargestBytes = 8000;
// A stopped SDK client needs a new internal task stack/TCB. First starts also
// allocate receive/transmit/reassembly buffers and SDK transport/config objects
// after admission. Budget that ordinary allocation separately from AES headroom.
@@ -34,26 +46,50 @@ enum class ClientMemoryState : uint8_t {
Started,
};
static inline size_t publishLargestBytes(bool psram) {
return psram ? kPsramPublishLargestBytes : kInternalPublishLargestBytes;
}
static inline bool hasPublishHeadroom(bool psram, size_t largest) {
return largest >= publishLargestBytes(psram);
}
static inline bool canStart(bool psram, bool tls, ClientMemoryState state,
size_t dma_free, size_t dma_largest) {
size_t dma_free, size_t dma_largest,
bool protect_publish = false) {
size_t allocation_allowance;
size_t largest_required;
size_t sdk_largest;
switch (state) {
case ClientMemoryState::Uninitialized:
allocation_allowance = kColdStartAllowanceBytes;
largest_required = kColdStartLargestBytes;
sdk_largest = kColdStartLargestBytes;
break;
case ClientMemoryState::Stopped:
allocation_allowance = kRestartAllowanceBytes;
largest_required = kRestartLargestBytes;
sdk_largest = kRestartLargestBytes;
break;
case ClientMemoryState::Started:
allocation_allowance = 0;
largest_required = kDmaLargestBytes;
sdk_largest = kDmaLargestBytes;
break;
default:
return false;
}
const size_t publication_floor = publishLargestBytes(psram);
const size_t tls_record = tls ? (psram ? kPsramTlsLargestBytes : kTlsRecordAllocationBytes) : 0;
// Bootstrap/recover one broker without requiring spare capacity for another
// live connection: retained SDK buffers can fragment the heap after an outage.
// With a live peer, conservatively allow startup/TLS allocations to consume
// the largest block while leaving existing forwarding's publication floor.
// Other tasks and TLS allocations can still change/fragment this snapshot;
// these are admission bounds, not an allocation guarantee.
size_t largest_required = publication_floor > sdk_largest ? publication_floor : sdk_largest;
if (tls_record > largest_required) largest_required = tls_record;
if (protect_publish) {
largest_required = psram
? (publication_floor > tls_record ? publication_floor : tls_record) + allocation_allowance
: publication_floor + allocation_allowance + tls_record;
}
const size_t free_required = kDmaReserveBytes + allocation_allowance;
if (dma_free < free_required || dma_largest < largest_required) {
return false;
+11 -5
View File
@@ -7,8 +7,13 @@
namespace {
static int serializeComplete(JsonObject root, char* buffer, size_t buffer_size) {
static int serializeComplete(JsonDocument& doc, char* buffer, size_t buffer_size) {
if (!buffer || buffer_size == 0) return 0;
buffer[0] = '\0';
JsonObject root = doc.as<JsonObject>();
// A document can serialize successfully after some allocations failed.
// Never publish that incomplete object as a complete status or packet.
if (doc.overflowed() || root.isNull()) return 0;
size_t written = serializeJson(root, buffer, buffer_size);
// Preserve MQTTMessageBuilder's existing success criterion while clearing
@@ -97,7 +102,7 @@ int MQTTPayloadBuilder::buildStatusMessage(
if (conn_health.slots_breaker > 0) stats["mqtt_slots_breaker"] = conn_health.slots_breaker;
}
return serializeComplete(root, buffer, buffer_size);
return serializeComplete(doc, buffer, buffer_size);
}
int MQTTPayloadBuilder::buildPacketMessage(
@@ -182,7 +187,7 @@ int MQTTPayloadBuilder::buildPacketMessage(
}
}
return serializeComplete(root, buffer, buffer_size);
return serializeComplete(doc, buffer, buffer_size);
}
int MQTTPayloadBuilder::buildRawMessage(
@@ -203,7 +208,7 @@ int MQTTPayloadBuilder::buildRawMessage(
root["type"] = "RAW";
root["data"] = raw;
return serializeComplete(root, buffer, buffer_size);
return serializeComplete(doc, buffer, buffer_size);
}
static JsonArray buildNeighborsMessageBase(
@@ -294,6 +299,7 @@ int MQTTPayloadBuilder::buildNeighborsMessage(
bool truncated
) {
if (!buffer || buffer_size == 0) return 0;
buffer[0] = '\0';
JsonArray arr = buildNeighborsMessageBase(
doc, origin, origin_id, timestamp, self_scopes, self_default_scope,
@@ -314,5 +320,5 @@ int MQTTPayloadBuilder::buildNeighborsMessage(
}
}
return serializeComplete(doc.as<JsonObject>(), buffer, buffer_size);
return serializeComplete(doc, buffer, buffer_size);
}
+7 -3
View File
@@ -8,7 +8,7 @@ namespace MQTTPublishAdmission {
// QoS0 writes use the SDK's fixed buffer; QoS1 can resend an entire outbox
// record. Keep the existing DMA reserve and account for larger queued records.
static const size_t kLegacyLargestBytes = 8000;
static const size_t kLegacyLargestBytes = MQTTConnectionAdmission::kInternalPublishLargestBytes;
static const size_t kFramingAllowanceBytes = 128;
static const uint32_t kSampleIntervalMs = 5000;
@@ -23,7 +23,8 @@ inline bool canPublish(const Heap& heap, size_t payload_size = 0,
size_t topic_size = 0, uint8_t qos = 0) {
if (payload_size > SIZE_MAX - kFramingAllowanceBytes ||
topic_size > SIZE_MAX - kFramingAllowanceBytes - payload_size) return false;
size_t record = qos ? payload_size + topic_size + kFramingAllowanceBytes : 0;
const size_t queued_bytes = qos ? payload_size + topic_size + kFramingAllowanceBytes : 0;
size_t record = queued_bytes;
if (record > MQTTConnectionAdmission::kTlsRecordAllocationBytes)
record = MQTTConnectionAdmission::kTlsRecordAllocationBytes;
if (!heap.psram) {
@@ -34,7 +35,10 @@ inline bool canPublish(const Heap& heap, size_t payload_size = 0,
? record : MQTTConnectionAdmission::kDmaLargestBytes;
const size_t free = MQTTConnectionAdmission::kDmaReserveBytes
+ largest - MQTTConnectionAdmission::kDmaLargestBytes;
return heap.dma_free >= free && heap.dma_largest >= largest;
// Small SDK outbox records prefer internal RAM. Leave the reserve after
// enqueue as well as room for the subsequent TLS/DMA write.
if (queued_bytes > SIZE_MAX - free) return false;
return heap.dma_free >= free + queued_bytes && heap.dma_largest >= largest;
}
struct State {
+2 -2
View File
@@ -92,7 +92,7 @@ bool secondaryOverlaps(uint32_t primary_hz, float secondary_mhz, uint32_t cleara
return (primary_hz > secondary_hz ? primary_hz - secondary_hz : secondary_hz - primary_hz)
<= clearance_hz;
}
#if !defined(COMPANION_RADIO_FULL)
#if !defined(COMPANION_RADIO_FULL) && !MESH_ROLE_COMPANION
bool isMediaMeshProfile(const RadioProfileConfig& config) {
return config.mode != RadioProfileMode::Off
&& config.params.freq >= 911.1495f && config.params.freq <= 911.1505f
@@ -102,7 +102,7 @@ bool isMediaMeshProfile(const RadioProfileConfig& config) {
#endif
}
#if !defined(COMPANION_RADIO_FULL)
#if !defined(COMPANION_RADIO_FULL) && !MESH_ROLE_COMPANION
void RadioProfileCLI::setMediaMeshScopeHandler(MediaMeshScopeHandler handler, void* context) {
media_scope_handler_ = handler;
media_scope_context_ = context;
+3 -3
View File
@@ -61,7 +61,7 @@ class RadioProfileCLI {
// readable backup. Read/I/O failures and an intact backup remain read-only.
bool recoverable_corrupt_store_ = false;
bool publish_pending_ = false;
#if !defined(COMPANION_RADIO_FULL)
#if !defined(COMPANION_RADIO_FULL) && !MESH_ROLE_COMPANION
MediaMeshScopeHandler media_scope_handler_ = nullptr;
void* media_scope_context_ = nullptr;
uint32_t media_scope_retry_ms_ = 0;
@@ -71,7 +71,7 @@ class RadioProfileCLI {
void retryMediaMeshScope();
bool mediaMeshScopePending() const { return media_scope_pending_; }
#else
// Full Companions have no forwarding RegionMap. Do not retain unreachable
// Companions have no forwarding RegionMap. Do not retain unreachable
// infrastructure callbacks, state or failure text in their tight images.
bool mediaMeshScopeReady(const RadioProfileConfig&) const { return true; }
void updateMediaMeshScope() {}
@@ -141,7 +141,7 @@ class RadioProfileCLI {
#endif
void begin(FILESYSTEM* fs, Radio* radio, RTCClock* rtc, bool infrastructure_replies = false);
// Bind only after RegionMap::load(), so boot reconciliation is not discarded.
#if !defined(COMPANION_RADIO_FULL)
#if !defined(COMPANION_RADIO_FULL) && !MESH_ROLE_COMPANION
void setMediaMeshScopeHandler(MediaMeshScopeHandler handler, void* context);
#else
void setMediaMeshScopeHandler(MediaMeshScopeHandler, void*) {}
+16 -5
View File
@@ -1681,10 +1681,10 @@ bool MQTTBridge::serviceNetworkPower(uint32_t now) {
&& acknowledgments != _network_publish_acks[i];
_network_publish_acks[i] = acknowledgments;
// A flapping CONNACK must not buy another full outage window forever.
// A PUBACK proves delivery immediately; a quiet connection must stay up
// for 30 seconds, leaving time to prove recovery within the probe window.
if (_slots[i].enabled && _slots[i].connected
&& (broker_replied || (now - static_cast<uint32_t>(_slots[i].connected_at_ms)
// A PUBACK proves delivery even if DISCONNECTED arrives before this pass.
// Consume it once; a quiet connection must still stay up for 30 seconds.
if (_slots[i].enabled && (broker_replied || (_slots[i].connected
&& now - static_cast<uint32_t>(_slots[i].connected_at_ms)
>= mesh::wifi::kNetworkHealthyMs))) {
useful_network = true;
}
@@ -2324,9 +2324,16 @@ bool MQTTBridge::canStartSlotConnection(int index) const {
? ClientMemoryState::Uninitialized
: (slot.client->isStarted() ? ClientMemoryState::Started : ClientMemoryState::Stopped);
const uint32_t caps = MALLOC_CAP_INTERNAL | MALLOC_CAP_DMA;
bool protect_publish = false;
for (int i = 0; i < RUNTIME_MQTT_SLOTS; ++i) {
if (i != index && _slots[i].enabled && _slots[i].connected) {
protect_publish = true;
break;
}
}
return MQTTConnectionAdmission::canStart(
ESP.getPsramSize() > 0, tls, memory_state, heap_caps_get_free_size(caps),
heap_caps_get_largest_free_block(caps));
heap_caps_get_largest_free_block(caps), protect_publish);
#else
return true;
#endif
@@ -2735,6 +2742,7 @@ bool MQTTBridge::recoverSlotTransport(int index, uint32_t now) {
slot.last_reconnect_attempt = now;
_last_slot_reconnect_ms = now;
health.recovered();
_publish_memory.invalidate();
updateSlotTransportDiag(index, now);
updateCachedConnectionStatus();
return true;
@@ -2746,6 +2754,7 @@ void MQTTBridge::serviceSlotTransportHealth(uint32_t now) {
MQTTSlot& slot = _slots[i];
auto& health = slot.transport_health;
if (_slot_health_reset_pending[i].exchange(false, std::memory_order_acq_rel)) {
_publish_memory.invalidate();
// A late CONNACK does not release an already-required SDK stop. Its
// session clocks may reset, but only proven cleanup clears recovery.
health.resetSession();
@@ -3214,6 +3223,7 @@ bool MQTTBridge::publishToSlot(int index, const char* topic, const char* payload
// session latch BEFORE enqueueing it, or maintenance would erase its ACK
// watch immediately afterwards. Only this owner task mutates health state.
if (_slot_health_reset_pending[index].exchange(false, std::memory_order_acq_rel)) {
_publish_memory.invalidate();
slot.transport_health.resetSession();
}
if (slot.transport_health.recovery_reason != MQTTTransportHealth::RecoveryReason::None ||
@@ -3269,6 +3279,7 @@ bool MQTTBridge::publishToSlot(int index, const char* topic, const char* payload
}
if (qos > 0) {
slot.transport_health.acceptedQos1(static_cast<uint32_t>(millis()), ack_before);
_publish_memory.invalidate();
// Also reflect an ACK delivered during enqueue, not just on the next tick.
slot.transport_health.observeAck(static_cast<uint32_t>(slot.client->getPublishAck()));
updateSlotTransportDiag(index, static_cast<uint32_t>(millis()));
+3 -5
View File
@@ -334,10 +334,8 @@ void OtaManager::refresh_sources() {
(uint64_t)d.payload_off + d.payload_size + 5 != d.total_size) continue;
if (serveEntryIndex(d.mid) >= 0) continue; // already offered (e.g. our own fw in the folder)
ServeEntry& e = _serve[_n_serve++];
memcpy(e.mid, d.mid, 4);
e.target_id = d.target_id; e.fw_version = d.fw_version;
e.codec_id = d.codec_id; e.flags = d.flags; e.have_count = d.block_count; // a folder mota is fully held
e.is_self = false; e.src = src; e.src_idx = i; e.desc = d;
e.cacheDescriptor(d);
e.is_self = false; e.src = src; e.src_idx = i;
_src_advertised[s]++;
}
}
@@ -409,7 +407,7 @@ OtaManager::ServeView* OtaManager::resolve(const uint8_t* mid) {
// builds also cache leaves here; bounded builds acquire proof metadata through
// cooperative egress steps, without delaying request admission on a full table.
bool OtaManager::loadSource(const ServeEntry& e) {
const MotaDesc& d = e.desc;
const MotaDesc d = e.descriptor();
if (d.leaves_off < 8) return false;
if (!e.src) return false;
uint16_t mfl = (uint16_t)(d.leaves_off - 8);
+41 -13
View File
@@ -2,6 +2,7 @@
#include <stdint.h>
#include <stddef.h>
#include <string.h>
#include "OtaFormat.h"
#include "OtaMemoryPolicy.h"
#include "OtaTiming.h"
@@ -327,19 +328,44 @@ public:
};
// A lightweight catalog entry: what we advertise per mota + how to load its ServeView on demand.
struct ServeEntry {
// Named fields only: this is not a wire/persistent layout. Group aligned
// values ahead of byte flags instead of paying three padding gaps per row.
MotaSource* src; // load from this external source ...
MotaDesc desc; // cached region offsets for the source entry
uint32_t target_id, fw_version;
uint32_t have_count; // blocks we currently hold (== block_count when complete)
uint8_t mid[4];
uint8_t codec_id, flags;
bool is_self; // true => entry is view0 (our own fw / RAM mota)
uint8_t src_idx; // ... at this index
// This is not a wire/persistent layout. Source admission proves the fixed
// header/leaves/payload geometry, so cache each field once and reconstruct
// the three derived offsets/sizes instead of retaining another MotaDesc.
MotaSource* src = nullptr; // load from this external source ...
uint32_t target_id = 0, fw_version = 0;
uint32_t have_count = 0; // complete sources hold every block
uint32_t payload_size = 0;
uint8_t mid[4] = {};
uint8_t codec_id = 0, flags = 0;
bool is_self = false; // true => entry is view0 (our own fw / RAM mota)
uint8_t src_idx = 0; // ... at this index
uint8_t block_size_log2 = 0, source_caps = 0;
void cacheDescriptor(const MotaDesc& d) {
memcpy(mid, d.mid, sizeof(mid));
target_id = d.target_id; fw_version = d.fw_version;
codec_id = d.codec_id; flags = d.flags; have_count = d.block_count;
payload_size = d.payload_size;
block_size_log2 = d.block_size_log2; source_caps = d.source_caps;
}
MotaDesc descriptor() const {
MotaDesc d;
if (!have_count) return d;
memcpy(d.mid, mid, sizeof(mid));
d.target_id = target_id; d.fw_version = fw_version;
d.codec_id = codec_id; d.flags = flags; d.block_count = have_count;
d.payload_size = payload_size;
d.block_size_log2 = block_size_log2; d.source_caps = source_caps;
d.leaves_off = 8u + MOTA_MFL;
d.payload_off = d.leaves_off + have_count * 4u;
d.total_size = d.payload_off + payload_size + 5u;
return d;
}
};
static_assert(sizeof(ServeEntry) <= sizeof(MotaDesc) + sizeof(MotaSource*) + 20u,
"OTA source catalog must not add per-entry alignment padding");
static_assert(sizeof(ServeEntry) ==
((sizeof(MotaSource*) + 28u + alignof(MotaSource*) - 1u)
/ alignof(MotaSource*)) * alignof(MotaSource*),
"OTA source catalog must not duplicate validated descriptor fields");
// Context for the source-payload reader trampoline.
struct SrcReadCtx { MotaSource* src; uint8_t idx; uint32_t payload_off; };
@@ -903,7 +929,9 @@ private:
uint8_t _observed_path_transmissions = 0; // source + relays; 0 falls back to configured max_hops+1
uint32_t _packets_sent = 0; // OTA packets accepted by the radio adapter (wrap-safe)
// multi-fragment manifest reassembly (a signed v2 manifest exceeds one packet)
uint8_t _mf_buf[OTA_MF_MAXFRAG * OTA_MF_FRAG]; // sized to the fragment cap so no valid manifest is silently dropped
// handleManifest admits only the fixed MOTA_MFL bytes and exact fragment
// shapes. The transport's larger fragment-count ceiling adds no valid data.
uint8_t _mf_buf[MOTA_MFL];
uint16_t _mf_retries = 0; // GET_MANIFEST retries while WANT_MANIFEST (give up after a cap)
uint8_t _mf_total = 0; // frag_total of the manifest being reassembled (0 = none)
uint16_t _mf_mask = 0; // received manifest-fragment bitmap