Accelerate adaptive LoRa OTA transfers
This commit is contained in:
1 parent
e92794eabc
commit
8c5262c6f8
20 files changed
+1059
-307
No files matched your search
+11
-3
@@ -356,6 +356,12 @@ void __attribute__((noinline)) Mesh::serviceLoopMaintenance() {
|
||||
_ota_announce_count = 0;
|
||||
}
|
||||
ota::ota_ctx().manager.set_clock(_ms->getMillis());
|
||||
float ota_spacing = 1.0f + getAirtimeBudgetFactor();
|
||||
if (ota_spacing < 1.0f) ota_spacing = 1.0f;
|
||||
if (ota_spacing > 10.0f) ota_spacing = 10.0f;
|
||||
ota::ota_ctx().manager.set_link_timing(
|
||||
_radio->getEstAirtimeFor(MAX_TRANS_UNIT),
|
||||
(uint16_t)(ota_spacing * 1000.0f + 0.5f));
|
||||
ota::ota_ctx().manager.serviceEgress();
|
||||
if (millisHasNowPassed(_next_ota_tick)) {
|
||||
// one-shot on first tick: resume an interrupted fetch left staged in flash before a reboot. Only adopt
|
||||
@@ -1061,17 +1067,19 @@ DispatcherAction Mesh::onRecvPacket(Packet* pkt) {
|
||||
if (!seen) _tables->markSeen(pkt);
|
||||
const bool primary_ota = isPrimaryOtaTraffic(pkt->payload, pkt->payload_len);
|
||||
const uint8_t ota_priority = otaTrafficPriority(pkt->payload, pkt->payload_len);
|
||||
bool terminal_ota = false;
|
||||
#if defined(ENABLE_OTA)
|
||||
ota::ota_ctx().manager.set_clock(_ms->getMillis()); // discovery jitter/ages
|
||||
ota::ota_ctx().manager.on_message(pkt->payload, pkt->payload_len); // central OTA receive (beacon/query/
|
||||
// have/manifest/data/proof; all roles)
|
||||
ota::ota_ctx().manager.note_rx_path_hops(n); // adaptive fetch timing
|
||||
terminal_ota = ota::ota_ctx().manager.on_message(pkt->payload, pkt->payload_len);
|
||||
// central OTA receive (all roles)
|
||||
ota::ota_ctx().track_session(ota::ota_ctx().manager.fetchState(), _ms->getMillis());
|
||||
onOtaRecv(pkt); // optional per-example hook
|
||||
#endif
|
||||
// Re-flood discovery at background priority, but keep an active transfer primary at every relay hop.
|
||||
// The free-pool reserve still sheds periodic discovery under pressure; requested transfer packets are
|
||||
// protected from that background-only gate. Ordinary hop and forwarding policy remain authoritative.
|
||||
if (!seen && pkt->isRouteFlood() && !pkt->isMarkedDoNotRetransmit()
|
||||
if (!terminal_ota && !seen && pkt->isRouteFlood() && !pkt->isMarkedDoNotRetransmit()
|
||||
#if defined(ENABLE_OTA)
|
||||
&& n < getOtaHopLimit()
|
||||
#endif
|
||||
|
||||
@@ -19,8 +19,11 @@ namespace {
|
||||
|
||||
WiFiServer seeder_server(OTA_SEEDER_TCP_PORT);
|
||||
WiFiClient seeder_client;
|
||||
SerialMotaSource seeder_source(seeder_client, 3000);
|
||||
FolderMotaStore folder_store(seeder_client, 3000);
|
||||
// WiFiClient::flush() clears received bytes rather than flushing TX. Disabling
|
||||
// the serial-only flush prevents a fast host reply from being discarded and
|
||||
// turning every block read into a three-second timeout/retry.
|
||||
SerialMotaSource seeder_source(seeder_client, 3000, false);
|
||||
FolderMotaStore folder_store(seeder_client, 3000, false);
|
||||
bool listener_active = false;
|
||||
bool tcp_folder_attached = false;
|
||||
|
||||
@@ -80,6 +83,8 @@ void WiFiOtaSeeder::loop() {
|
||||
WiFiClient incoming = seeder_server.available();
|
||||
if (!incoming) return;
|
||||
|
||||
incoming.setNoDelay(true); // tiny framed requests should leave immediately
|
||||
|
||||
if (!WiFiOtaSeederPolicy::canAttachTcpFolder(context.folder_active,
|
||||
tcp_folder_attached)) {
|
||||
incoming.stop();
|
||||
|
||||
@@ -27,11 +27,18 @@ bool FolderMotaStore::txn(uint8_t op, const uint8_t* args, uint16_t arglen,
|
||||
while (_io.read() >= 0) {} // drop any stale/partial bytes before a fresh request
|
||||
uint8_t xs = op;
|
||||
for (uint16_t i = 0; i < arglen; i++) xs ^= args[i];
|
||||
_io.write(MOTA_SEEDER_REQ_MAGIC0); _io.write(MOTA_SEEDER_REQ_MAGIC1);
|
||||
_io.write(op);
|
||||
if (arglen) _io.write(args, arglen);
|
||||
_io.write(xs);
|
||||
_io.flush();
|
||||
// Keep one contiguous write for TCP (and fewer calls on UART). The largest
|
||||
// request is OP_WRITE's fixed header plus one bounded data chunk.
|
||||
if (arglen > 10 + MOTA_SEEDER_WRITE_MAX) return false;
|
||||
uint8_t frame[4 + 10 + MOTA_SEEDER_WRITE_MAX];
|
||||
uint16_t frame_len = 0;
|
||||
frame[frame_len++] = MOTA_SEEDER_REQ_MAGIC0;
|
||||
frame[frame_len++] = MOTA_SEEDER_REQ_MAGIC1;
|
||||
frame[frame_len++] = op;
|
||||
if (arglen) { memcpy(frame + frame_len, args, arglen); frame_len += arglen; }
|
||||
frame[frame_len++] = xs;
|
||||
if (_io.write(frame, frame_len) != frame_len) return false;
|
||||
if (_flush_after_write) _io.flush();
|
||||
|
||||
uint32_t t0 = millis(); bool got = false; uint8_t prev = 0;
|
||||
while ((millis() - t0) < _to) { // scan for response magic 'm' 's' (tolerate noise)
|
||||
|
||||
@@ -22,7 +22,9 @@ namespace ota {
|
||||
|
||||
class FolderMotaStore : public OtaStore {
|
||||
public:
|
||||
explicit FolderMotaStore(Stream& io, uint32_t timeout_ms = 3000) : _io(io), _to(timeout_ms) {}
|
||||
explicit FolderMotaStore(Stream& io, uint32_t timeout_ms = 3000,
|
||||
bool flush_after_write = true)
|
||||
: _io(io), _to(timeout_ms), _flush_after_write(flush_after_write) {}
|
||||
|
||||
// The container being pulled - set from the chosen `ota pull` mid before begin()/reopen().
|
||||
void set_mid(const uint8_t mid[4]) { memcpy(_mid, mid, 4); }
|
||||
@@ -49,6 +51,7 @@ private:
|
||||
|
||||
Stream& _io;
|
||||
uint32_t _to;
|
||||
bool _flush_after_write;
|
||||
uint8_t _mid[4] = {0, 0, 0, 0};
|
||||
uint32_t _total = 0;
|
||||
};
|
||||
|
||||
@@ -25,13 +25,18 @@ bool SerialMotaSource::readExact(uint8_t* b, uint32_t n) {
|
||||
bool SerialMotaSource::txn(uint8_t op, const uint8_t* args, uint8_t arglen,
|
||||
uint8_t* payload, uint32_t payload_len) {
|
||||
while (_io.read() >= 0) {} // drop any stale/partial bytes before a fresh request
|
||||
if (arglen > 7) return false; // largest source request is READ(idx,off,len)
|
||||
uint8_t xs = op;
|
||||
for (uint8_t i = 0; i < arglen; i++) xs ^= args[i];
|
||||
_io.write(MOTA_SEEDER_REQ_MAGIC0); _io.write(MOTA_SEEDER_REQ_MAGIC1);
|
||||
_io.write(op);
|
||||
if (arglen) _io.write(args, arglen);
|
||||
_io.write(xs);
|
||||
_io.flush();
|
||||
uint8_t frame[11];
|
||||
uint8_t frame_len = 0;
|
||||
frame[frame_len++] = MOTA_SEEDER_REQ_MAGIC0;
|
||||
frame[frame_len++] = MOTA_SEEDER_REQ_MAGIC1;
|
||||
frame[frame_len++] = op;
|
||||
if (arglen) { memcpy(frame + frame_len, args, arglen); frame_len += arglen; }
|
||||
frame[frame_len++] = xs;
|
||||
if (_io.write(frame, frame_len) != frame_len) return false;
|
||||
if (_flush_after_write) _io.flush();
|
||||
|
||||
// scan for response magic 'm' 's' (tolerate leading noise)
|
||||
uint32_t t0 = millis(); bool got = false;
|
||||
|
||||
@@ -14,7 +14,12 @@ namespace ota {
|
||||
|
||||
class SerialMotaSource : public MotaSource {
|
||||
public:
|
||||
explicit SerialMotaSource(Stream& io, uint32_t timeout_ms = 400) : _io(io), _to(timeout_ms) {}
|
||||
// Hardware serial needs flush() to finish transmitting before waiting for a
|
||||
// reply. NetworkClient/WiFiClient gives flush() receive-side semantics and
|
||||
// discards bytes, so TCP users must pass flush_after_write=false.
|
||||
explicit SerialMotaSource(Stream& io, uint32_t timeout_ms = 400,
|
||||
bool flush_after_write = true)
|
||||
: _io(io), _to(timeout_ms), _flush_after_write(flush_after_write) {}
|
||||
|
||||
uint8_t count() override;
|
||||
bool describe(uint8_t idx, MotaDesc& out) override;
|
||||
@@ -29,6 +34,7 @@ private:
|
||||
|
||||
Stream& _io;
|
||||
uint32_t _to;
|
||||
bool _flush_after_write;
|
||||
};
|
||||
|
||||
} // namespace ota
|
||||
|
||||
+210
-107
@@ -435,33 +435,42 @@ bool OtaManager::loadActiveServeBlock() {
|
||||
return true;
|
||||
}
|
||||
|
||||
void OtaManager::handleReq(const uint8_t* m, uint16_t n) {
|
||||
ReqMsg rq;
|
||||
if (!decode_req(m, n, rq)) return;
|
||||
uint32_t idx = rq.block_idx;
|
||||
bool OtaManager::handleReq(const uint8_t* m, uint16_t n) {
|
||||
ReqWindowMsg rq;
|
||||
if (!decode_req_window(m, n, rq)) return false;
|
||||
ServeView* v = resolve(rq.manifest_id);
|
||||
if (!v || idx >= v->m.block_count || idx > 0xFFFFu) return;
|
||||
uint32_t blen = v->m.block_size();
|
||||
uint32_t off = idx * blen;
|
||||
if (off + blen > v->m.payload_size) blen = v->m.payload_size - off;
|
||||
uint16_t valid_mask = frag_full_mask((blen + OTA_FRAG_DATA - 1) / OTA_FRAG_DATA);
|
||||
uint16_t want = (uint16_t)(rq.want_mask & valid_mask);
|
||||
if (want != 0) queueServeJob(v->m.merkle_root, (uint16_t)idx, want);
|
||||
if (!v) return false;
|
||||
bool accepted = false;
|
||||
const uint32_t block_size = v->m.block_size();
|
||||
for (uint8_t i = 0; i < rq.n_items; i++) {
|
||||
const uint32_t idx = rq.items[i].block_idx;
|
||||
if (idx >= v->m.block_count) continue;
|
||||
uint32_t blen = block_size;
|
||||
const uint32_t off = idx * block_size;
|
||||
if (off + blen > v->m.payload_size) blen = v->m.payload_size - off;
|
||||
const uint16_t valid_mask = frag_full_mask((blen + OTA_FRAG_DATA - 1) / OTA_FRAG_DATA);
|
||||
const uint16_t want = (uint16_t)(rq.items[i].want_mask & valid_mask);
|
||||
if (want != 0) accepted |= queueServeJob(v->m.merkle_root, (uint16_t)idx, want);
|
||||
}
|
||||
return accepted;
|
||||
}
|
||||
|
||||
void OtaManager::handleReqProof(const uint8_t* m, uint16_t n) {
|
||||
bool OtaManager::handleReqProof(const uint8_t* m, uint16_t n) {
|
||||
ReqProofMsg rp;
|
||||
if (!decode_req_proof(m, n, rp)) return;
|
||||
if (!decode_req_proof(m, n, rp)) return false;
|
||||
ServeView* v = resolve(rp.manifest_id);
|
||||
if (!v || rp.block_idx >= v->m.block_count) return;
|
||||
if ((uint64_t)v->m.block_count * 4 > v->scratch_sz) return;
|
||||
queueServeJob(v->m.merkle_root, rp.block_idx, 0); // proof-only, or merge with queued DATA
|
||||
if (!v || rp.block_idx >= v->m.block_count) return false;
|
||||
if ((uint64_t)v->m.block_count * 4 > v->scratch_sz) return false;
|
||||
return queueServeJob(v->m.merkle_root, rp.block_idx, 0); // proof-only, or merge with queued DATA
|
||||
}
|
||||
|
||||
void OtaManager::serviceEgress() {
|
||||
// A proactive proof normally follows the final DATA fragment. If it was lost, or the source is older and
|
||||
// never sent one, issue the legacy proof request after a short grace. Admit at most one fallback per call.
|
||||
if (_fstate == FETCHING) {
|
||||
// never sent one, issue the legacy proof request after a short grace. Stay RX-silent while another slot
|
||||
// still expects DATA, and restart the grace on every new packet, so this fallback cannot collide with a
|
||||
// legitimate multi-block response train. Admit at most one fallback per call.
|
||||
if (_fstate == FETCHING && !flightHasPendingData()
|
||||
&& (uint32_t)(_now_ms - _fetch_wait_since_ms) >= proofGraceMs()) {
|
||||
for (uint8_t i = 0; i < OTA_FETCH_PIPELINE; i++) {
|
||||
ReassemblySlot& slot = _reasm[i];
|
||||
if (!slot.awaiting_proof || slot.proof_request_at == 0
|
||||
@@ -714,8 +723,8 @@ void OtaManager::clearReassembly() {
|
||||
_retry_slot = 0;
|
||||
_req_count = 0;
|
||||
_pipeline_width = OTA_FETCH_PIPELINE_INITIAL;
|
||||
_pipeline_success_streak = 0;
|
||||
_pipeline_stall_streak = 0;
|
||||
_flight_dirty = false;
|
||||
noteFetchActivity();
|
||||
}
|
||||
|
||||
int OtaManager::findReassemblySlot(uint32_t block) const {
|
||||
@@ -732,44 +741,98 @@ int OtaManager::findEmptyReassemblySlot() const {
|
||||
return -1;
|
||||
}
|
||||
|
||||
void OtaManager::notePipelineBlockVerified() {
|
||||
_pipeline_stall_streak = 0;
|
||||
if (_pipeline_width >= OTA_FETCH_PIPELINE) return;
|
||||
if (++_pipeline_success_streak < OTA_FETCH_PIPELINE_GROW_BLOCKS) return;
|
||||
_pipeline_success_streak = 0;
|
||||
_pipeline_width++;
|
||||
OTA_DBG("OTA: request pipeline grew to %u/%u after clean block progress\n",
|
||||
(unsigned)_pipeline_width, (unsigned)OTA_FETCH_PIPELINE);
|
||||
uint8_t OtaManager::activePipelineSlots() const {
|
||||
uint8_t active = 0;
|
||||
for (uint8_t slot = 0; slot < OTA_FETCH_PIPELINE; slot++) {
|
||||
if (_reasm[slot].block != NO_BLOCK) active++;
|
||||
}
|
||||
return active;
|
||||
}
|
||||
|
||||
bool OtaManager::flightHasPendingData() const {
|
||||
for (uint8_t slot = 0; slot < OTA_FETCH_PIPELINE; slot++) {
|
||||
if (_reasm[slot].block != NO_BLOCK && !_reasm[slot].awaiting_proof) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
static uint8_t count_mask_bits(uint16_t mask) {
|
||||
uint8_t count = 0;
|
||||
while (mask) { count += (uint8_t)(mask & 1u); mask >>= 1; }
|
||||
return count;
|
||||
}
|
||||
|
||||
uint32_t OtaManager::fetchRetryTimeoutMs() const {
|
||||
if (_radio_packet_airtime_ms == 0) return OTA_FETCH_RETRY_FALLBACK_MS;
|
||||
|
||||
// Estimate every packet still owed in the current flight, plus the recovery request itself. DATA uses
|
||||
// the measured maximum packet airtime; smaller REQ/PROOF packets are deliberately overestimated. Each
|
||||
// packet must traverse the source+relay path and each transmitter is paced by its configured duty budget.
|
||||
uint32_t packets = 1;
|
||||
uint8_t active = 0;
|
||||
for (uint8_t slot_index = 0; slot_index < OTA_FETCH_PIPELINE; slot_index++) {
|
||||
const ReassemblySlot& slot = _reasm[slot_index];
|
||||
if (slot.block == NO_BLOCK) continue;
|
||||
active++;
|
||||
packets += slot.awaiting_proof ? 1u
|
||||
: (uint32_t)count_mask_bits((uint16_t)(slot.need & ~slot.mask)) + 1u;
|
||||
}
|
||||
if (active == 0) {
|
||||
const uint32_t fragments = (_fbs + OTA_FRAG_DATA - 1) / OTA_FRAG_DATA;
|
||||
packets += (fragments + 1) * _pipeline_width;
|
||||
}
|
||||
uint32_t path_transmissions = _observed_path_transmissions;
|
||||
if (path_transmissions == 0) path_transmissions = (uint32_t)_max_hops + 1u;
|
||||
uint64_t service = (uint64_t)packets * _radio_packet_airtime_ms * path_transmissions;
|
||||
service = (service * _tx_spacing_permille + 999u) / 1000u;
|
||||
service = (service * 5u + 3u) / 4u; // 25% CAD/relay contention allowance
|
||||
service += OTA_FETCH_RETRY_GUARD_MS;
|
||||
if (service < OTA_FETCH_RETRY_MIN_MS) service = OTA_FETCH_RETRY_MIN_MS;
|
||||
if (service > OTA_FETCH_RETRY_MAX_MS) service = OTA_FETCH_RETRY_MAX_MS;
|
||||
return (uint32_t)service;
|
||||
}
|
||||
|
||||
uint32_t OtaManager::proofGraceMs() const {
|
||||
if (_radio_packet_airtime_ms == 0) return OTA_PROOF_GRACE_MS;
|
||||
uint32_t path_transmissions = _observed_path_transmissions;
|
||||
if (path_transmissions == 0) path_transmissions = (uint32_t)_max_hops + 1u;
|
||||
uint64_t grace = (uint64_t)_radio_packet_airtime_ms * path_transmissions;
|
||||
grace = (grace * _tx_spacing_permille + 999u) / 1000u;
|
||||
grace += 100u;
|
||||
if (grace < OTA_PROOF_GRACE_MS) grace = OTA_PROOF_GRACE_MS;
|
||||
if (grace > OTA_FETCH_RETRY_MAX_MS) grace = OTA_FETCH_RETRY_MAX_MS;
|
||||
return (uint32_t)grace;
|
||||
}
|
||||
|
||||
void OtaManager::finishFlight() {
|
||||
const uint8_t old_width = _pipeline_width;
|
||||
if (_flight_dirty) {
|
||||
if (_pipeline_width > OTA_FETCH_PIPELINE_INITIAL) {
|
||||
_pipeline_width = (uint8_t)((_pipeline_width + 1u) / 2u);
|
||||
if (_pipeline_width < OTA_FETCH_PIPELINE_INITIAL) _pipeline_width = OTA_FETCH_PIPELINE_INITIAL;
|
||||
}
|
||||
} else if (_pipeline_width < OTA_FETCH_PIPELINE) {
|
||||
_pipeline_width++;
|
||||
}
|
||||
if (_pipeline_width != old_width) {
|
||||
OTA_DBG("OTA: adaptive flight %s to %u/%u\n", _flight_dirty ? "shrunk" : "grew",
|
||||
(unsigned)_pipeline_width, (unsigned)OTA_FETCH_PIPELINE);
|
||||
}
|
||||
_flight_dirty = false;
|
||||
}
|
||||
|
||||
void OtaManager::notePipelineStall() {
|
||||
_pipeline_success_streak = 0;
|
||||
if (_pipeline_width <= OTA_FETCH_PIPELINE_INITIAL) {
|
||||
_pipeline_stall_streak = 0;
|
||||
return;
|
||||
if (!_flight_dirty) {
|
||||
OTA_DBG("OTA: adaptive flight recovery at width %u/%u\n",
|
||||
(unsigned)_pipeline_width, (unsigned)OTA_FETCH_PIPELINE);
|
||||
}
|
||||
if (++_pipeline_stall_streak < OTA_FETCH_PIPELINE_SHRINK_TICKS) return;
|
||||
_pipeline_stall_streak = 0;
|
||||
_pipeline_width--;
|
||||
OTA_DBG("OTA: request pipeline shrank to %u/%u after stalled ticks\n",
|
||||
(unsigned)_pipeline_width, (unsigned)OTA_FETCH_PIPELINE);
|
||||
_flight_dirty = true;
|
||||
}
|
||||
|
||||
bool OtaManager::blockInPipeline(uint32_t block) const {
|
||||
return findReassemblySlot(block) >= 0;
|
||||
}
|
||||
|
||||
uint32_t OtaManager::pipelineProgress() const {
|
||||
// A small stable fingerprint is sufficient here: equality only suppresses a retry for one service tick.
|
||||
uint32_t progress = 2166136261u;
|
||||
for (uint8_t slot = 0; slot < OTA_FETCH_PIPELINE; slot++) {
|
||||
progress = (progress ^ _reasm[slot].block) * 16777619u;
|
||||
progress = (progress ^ _reasm[slot].mask) * 16777619u;
|
||||
progress = (progress ^ (_reasm[slot].awaiting_proof ? 1u : 0u)) * 16777619u;
|
||||
}
|
||||
return progress;
|
||||
}
|
||||
|
||||
// Begin (or resume) fetching a chosen mid: try a staged-partial resume first, else request the manifest.
|
||||
void OtaManager::startFetch(const uint8_t* mid, uint32_t target, bool validate) {
|
||||
(void)target;
|
||||
@@ -781,6 +844,7 @@ void OtaManager::startFetch(const uint8_t* mid, uint32_t target, bool validate)
|
||||
// real partial), so never adopt it via resumeStaged - always re-begin and run the manifest->leaves->diff.
|
||||
if (!validate && resumeStaged(mid)) return; // (non-validate) resume a partial container left in flash
|
||||
memcpy(_fid, mid, 4);
|
||||
_observed_path_transmissions = 0; // learn the actual source/relay path from this fetch's replies
|
||||
_fstate = WANT_MANIFEST;
|
||||
_mf_total = 0; _mf_mask = 0; _mf_len = 0; _mf_retries = 0; _loop_last_mfmask = 0; // fresh manifest reassembly
|
||||
memset(_mf_buf, 0, sizeof(_mf_buf));
|
||||
@@ -859,7 +923,6 @@ void OtaManager::handleManifest(const uint8_t* m, uint16_t n) {
|
||||
_fpoff = payload_off; _floff = leaves_off; _fpsize = payload_size; _fbc = bc; _fbs = bs;
|
||||
_ftotal = total; _have = 0;
|
||||
clearReassembly(); // fresh transfer: drop any prior per-block state
|
||||
_loop_last_have = 0; _loop_last_progress = pipelineProgress();
|
||||
// Warm-start (folder-capture): if requested and the image is small enough for the fixed leaves bitmap,
|
||||
// bulk-fetch the target leaves and diff the seed already staged in the store; else just transfer normally.
|
||||
if (_validate && beginLeafDiff()) {
|
||||
@@ -868,6 +931,7 @@ void OtaManager::handleManifest(const uint8_t* m, uint16_t n) {
|
||||
}
|
||||
_fstate = FETCHING;
|
||||
OTA_DBG("OTA: FETCHING bc=%u bs=%u total=%u\n", (unsigned)bc, (unsigned)bs, (unsigned)total);
|
||||
requestMissing(); // final manifest fragment arrived: open flight 1 immediately
|
||||
}
|
||||
|
||||
// --- leaf-diff warm-start (fetcher side; motatool folder-capture only) -----------------------------
|
||||
@@ -980,7 +1044,7 @@ bool OtaManager::resumeStaged(const uint8_t* want_mid) {
|
||||
_fpoff = payload_off; _floff = leaves_off; _fpsize = m.payload_size; _fbc = bc; _fbs = bs;
|
||||
_ftotal = total;
|
||||
clearReassembly();
|
||||
_loop_last_have = 0; _loop_last_progress = 0;
|
||||
_observed_path_transmissions = 0;
|
||||
beginStagedVerification();
|
||||
OTA_DBG("OTA: RESUME verifying %u blocks total=%u\n",
|
||||
(unsigned)bc, (unsigned)total);
|
||||
@@ -1077,53 +1141,58 @@ void OtaManager::verifyStagedStep() {
|
||||
? COMPLETE : FAILED;
|
||||
} else {
|
||||
_fstate = FETCHING;
|
||||
_loop_last_have = _have;
|
||||
_loop_last_progress = pipelineProgress();
|
||||
requestMissing();
|
||||
}
|
||||
_resume_merkle.reset();
|
||||
}
|
||||
|
||||
void OtaManager::handleData(const uint8_t* m, uint16_t n) {
|
||||
bool OtaManager::handleData(const uint8_t* m, uint16_t n) {
|
||||
DataMsg dm;
|
||||
if (!decode_data(m, n, dm) || !_fetch) return;
|
||||
if (_fstate != FETCHING || memcmp(dm.manifest_id, _fid, 4) != 0) return;
|
||||
if (dm.block_idx >= _fbc) return;
|
||||
if (blockPresent(dm.block_idx)) return; // already stored + verified
|
||||
if (!decode_data(m, n, dm) || !_fetch) return false;
|
||||
if (_fstate != FETCHING || memcmp(dm.manifest_id, _fid, 4) != 0) return false;
|
||||
if (dm.block_idx >= _fbc) return false;
|
||||
if (blockPresent(dm.block_idx)) return true; // late duplicate for this terminal
|
||||
int slot_index = findReassemblySlot(dm.block_idx);
|
||||
if (slot_index < 0) return; // accept only blocks inside our bounded window
|
||||
if (slot_index < 0) return false; // not one of this node's requested blocks
|
||||
ReassemblySlot& slot = _reasm[slot_index];
|
||||
uint32_t blen = blockLen(dm.block_idx);
|
||||
if (dm.frag_off % OTA_FRAG_DATA != 0) return; // canonical FRAG_DATA-aligned slices only
|
||||
if ((uint32_t)dm.frag_off + dm.data_len > blen) return; // slice out of the block
|
||||
if (dm.frag_off % OTA_FRAG_DATA != 0) return false; // canonical FRAG_DATA-aligned slices only
|
||||
if ((uint32_t)dm.frag_off + dm.data_len > blen) return false; // slice out of the block
|
||||
uint32_t expected_len = blen - dm.frag_off;
|
||||
if (expected_len > OTA_FRAG_DATA) expected_len = OTA_FRAG_DATA;
|
||||
if (dm.data_len != expected_len) return; // do not mark a short slice as complete
|
||||
if (dm.data_len != expected_len) return false; // do not mark a short slice as complete
|
||||
uint32_t kf = dm.frag_off / OTA_FRAG_DATA;
|
||||
if (kf >= 16) return;
|
||||
if (kf >= 16) return false;
|
||||
const uint16_t bit = (uint16_t)(1u << kf);
|
||||
if (slot.mask & bit) return true; // duplicate flood/retry copy is terminal too
|
||||
memcpy(slot.buf + dm.frag_off, dm.data, dm.data_len);
|
||||
slot.mask |= (uint16_t)(1u << kf);
|
||||
if (slot.mask != slot.need || slot.awaiting_proof) return;
|
||||
slot.mask |= bit;
|
||||
noteFetchActivity();
|
||||
if (slot.mask != slot.need || slot.awaiting_proof) return true;
|
||||
// The paced server sends a proof immediately after this block's requested DATA. Wait briefly so that proof
|
||||
// can arrive without another request/response turn. An older server, or a lost proof, falls back through
|
||||
// serviceEgress() to the existing REQ_PROOF wire message.
|
||||
slot.awaiting_proof = true;
|
||||
slot.proof_request_at = _now_ms + OTA_PROOF_GRACE_MS;
|
||||
slot.proof_request_at = _now_ms + proofGraceMs();
|
||||
return true;
|
||||
}
|
||||
|
||||
void OtaManager::handleProof(const uint8_t* m, uint16_t n) {
|
||||
bool OtaManager::handleProof(const uint8_t* m, uint16_t n) {
|
||||
ProofMsg pm;
|
||||
if (!decode_proof(m, n, pm) || !_fetch) return;
|
||||
if (_fstate != FETCHING || memcmp(pm.manifest_id, _fid, 4) != 0) return;
|
||||
if (!decode_proof(m, n, pm) || !_fetch) return false;
|
||||
if (_fstate != FETCHING || memcmp(pm.manifest_id, _fid, 4) != 0) return false;
|
||||
if (pm.block_idx >= _fbc) return false;
|
||||
int slot_index = findReassemblySlot(pm.block_idx);
|
||||
if (slot_index < 0 || !_reasm[slot_index].awaiting_proof) return;
|
||||
if (slot_index < 0 || !_reasm[slot_index].awaiting_proof) return blockPresent(pm.block_idx);
|
||||
ReassemblySlot& slot = _reasm[slot_index];
|
||||
uint32_t block = slot.block;
|
||||
uint32_t blen = blockLen(block);
|
||||
noteFetchActivity();
|
||||
if (!merkle_verify(slot.buf, blen, block, pm.proof, pm.n_proof, _froot, _fbc)) {
|
||||
notePipelineStall();
|
||||
clearReassemblySlot((uint8_t)slot_index); // bad -> drop and re-fetch only this block
|
||||
requestMissing();
|
||||
return;
|
||||
if (activePipelineSlots() == 0) { finishFlight(); requestMissing(); }
|
||||
return true;
|
||||
}
|
||||
// verified -> commit the payload block, then its leaf (the present marker). A write failure here means a
|
||||
// FOLDER destination's seeder link dropped mid-transfer: PAUSE (hold progress on the host, stop
|
||||
@@ -1132,22 +1201,27 @@ void OtaManager::handleProof(const uint8_t* m, uint16_t n) {
|
||||
uint8_t leaf[4]; merkle_leaf(leaf, slot.buf, blen);
|
||||
if (!_fetch->write(_fpoff + block * _fbs, slot.buf, blen) ||
|
||||
!_fetch->write(_floff + block * 4, leaf, 4)) {
|
||||
_fstate = PAUSED; clearReassembly(); return;
|
||||
_fstate = PAUSED; clearReassembly(); return true;
|
||||
}
|
||||
_have++;
|
||||
OTA_DBG("OTA: block %u OK have=%u/%u\n", (unsigned)block, (unsigned)_have, (unsigned)_fbc);
|
||||
notePipelineBlockVerified();
|
||||
clearReassemblySlot((uint8_t)slot_index);
|
||||
// periodically persist progress (meta/leaf page + open payload) so a reboot can resume (no-op for RAM);
|
||||
// cadence is runtime-tunable via `ota config checkpoint <N>` (0 = never)
|
||||
if (_checkpoint_blocks && _have % _checkpoint_blocks == 0) _fetch->checkpoint();
|
||||
if (_have < _fbc) { requestMissing(); return; } // keep the client window full
|
||||
if (_have < _fbc) {
|
||||
// Do not continuously refill a partially completed flight: the remaining response packets are already
|
||||
// queued at the source/relays. Staying silent here is what prevents the old threefold request amplification.
|
||||
if (activePipelineSlots() == 0) { finishFlight(); requestMissing(); }
|
||||
return true;
|
||||
}
|
||||
// Every leaf must be readable and collectively match the manifest root.
|
||||
// A scratch allocation/read failure is an integrity failure, never success.
|
||||
clearReassembly();
|
||||
_fstate = storedLeavesRootMatches() ? COMPLETE : FAILED;
|
||||
if (_fstate == COMPLETE && !_fetch->finalize()) _fstate = FAILED;
|
||||
OTA_DBG("OTA: transfer %s\n", _fstate == COMPLETE ? "COMPLETE" : "FAILED(integrity/storage)");
|
||||
return true;
|
||||
}
|
||||
|
||||
bool OtaManager::requestSlot(uint8_t slot_index) {
|
||||
@@ -1155,16 +1229,14 @@ bool OtaManager::requestSlot(uint8_t slot_index) {
|
||||
ReassemblySlot& slot = _reasm[slot_index];
|
||||
if (slot.block >= _fbc) return false;
|
||||
_req_start = slot.block;
|
||||
_req_count = 0;
|
||||
for (uint8_t i = 0; i < OTA_FETCH_PIPELINE; i++) {
|
||||
if (_reasm[i].block != NO_BLOCK) _req_count++;
|
||||
}
|
||||
_req_count = activePipelineSlots();
|
||||
if (slot.awaiting_proof) {
|
||||
ReqProofMsg rp; memcpy(rp.manifest_id, _fid, 4); rp.block_idx = (uint16_t)slot.block;
|
||||
uint8_t b[16];
|
||||
bool sent = emit(b, encode_req_proof(b, sizeof(b), rp), false);
|
||||
if (sent) {
|
||||
slot.proof_request_at = 0;
|
||||
noteFetchActivity();
|
||||
OTA_DBG("OTA: REQ_PROOF fallback block=%u (have=%u/%u window=%u)\n",
|
||||
(unsigned)slot.block, (unsigned)_have, (unsigned)_fbc, (unsigned)_req_count);
|
||||
}
|
||||
@@ -1178,11 +1250,38 @@ bool OtaManager::requestSlot(uint8_t slot_index) {
|
||||
OTA_DBG("OTA: REQ block=%u want=%04x (have=%u/%u mask=%04x window=%u)\n",
|
||||
(unsigned)slot.block, (unsigned)want, (unsigned)_have, (unsigned)_fbc,
|
||||
(unsigned)slot.mask, (unsigned)_req_count);
|
||||
return emit(b, encode_req(b, sizeof(b), rq), false);
|
||||
bool sent = emit(b, encode_req(b, sizeof(b), rq), false);
|
||||
if (sent) noteFetchActivity();
|
||||
return sent;
|
||||
}
|
||||
|
||||
bool OtaManager::requestFlight() {
|
||||
if (_fstate != FETCHING) return false;
|
||||
ReqWindowMsg request = {};
|
||||
memcpy(request.manifest_id, _fid, 4);
|
||||
for (uint8_t slot_index = 0; slot_index < OTA_FETCH_PIPELINE; slot_index++) {
|
||||
const ReassemblySlot& slot = _reasm[slot_index];
|
||||
if (slot.block == NO_BLOCK || slot.awaiting_proof) continue;
|
||||
ReqItem& item = request.items[request.n_items++];
|
||||
item.block_idx = (uint16_t)slot.block;
|
||||
item.want_mask = (uint16_t)(slot.need & ~slot.mask);
|
||||
if (item.want_mask == 0) item.want_mask = slot.need;
|
||||
}
|
||||
if (request.n_items == 0) return false;
|
||||
_req_start = request.items[0].block_idx;
|
||||
_req_count = request.n_items;
|
||||
uint8_t b[5 + OTA_REQ_MAX_ITEMS * 4];
|
||||
OTA_DBG("OTA: REQ flight first=%u blocks=%u width=%u/%u\n",
|
||||
(unsigned)_req_start, (unsigned)_req_count,
|
||||
(unsigned)_pipeline_width, (unsigned)OTA_FETCH_PIPELINE);
|
||||
bool sent = emit(b, encode_req_window(b, sizeof(b), request), false);
|
||||
if (sent) noteFetchActivity();
|
||||
return sent;
|
||||
}
|
||||
|
||||
bool OtaManager::fillPipeline() {
|
||||
bool requested = false;
|
||||
if (activePipelineSlots() != 0) return false; // flights never overlap/refill
|
||||
uint8_t assigned = 0;
|
||||
while (true) {
|
||||
int slot_index = findEmptyReassemblySlot();
|
||||
if (slot_index < 0) break;
|
||||
@@ -1194,24 +1293,26 @@ bool OtaManager::fillPipeline() {
|
||||
slot.need = frag_full_mask((blockLen(block) + OTA_FRAG_DATA - 1) / OTA_FRAG_DATA);
|
||||
slot.awaiting_proof = false;
|
||||
slot.proof_request_at = 0;
|
||||
requestSlot((uint8_t)slot_index);
|
||||
requested = true;
|
||||
assigned++;
|
||||
}
|
||||
return requested;
|
||||
if (assigned == 0) return false;
|
||||
_flight_dirty = false;
|
||||
requestFlight();
|
||||
return true;
|
||||
}
|
||||
|
||||
void OtaManager::requestMissing() {
|
||||
if (_fstate != FETCHING) return;
|
||||
if (fillPipeline()) return;
|
||||
if (activePipelineSlots() == 0) { fillPipeline(); return; }
|
||||
|
||||
// A full window with no progress is stalled. Retry one slot per service tick, round-robin, so a weak
|
||||
// block cannot trigger a simultaneous multi-block re-burst on a half-duplex channel.
|
||||
// The airtime-aware deadline expired. Retry one slot's holes per deadline, round-robin, so a weak block
|
||||
// cannot trigger a simultaneous multi-block re-burst on a half-duplex channel. Recovery dirties the
|
||||
// flight; its successor is reduced (4->2, 3->2, 2->1) after all current slots finish.
|
||||
notePipelineStall();
|
||||
for (uint8_t offset = 0; offset < OTA_FETCH_PIPELINE; offset++) {
|
||||
uint8_t slot = (uint8_t)((_retry_slot + offset) % OTA_FETCH_PIPELINE);
|
||||
if (_reasm[slot].block == NO_BLOCK) continue;
|
||||
requestSlot(slot);
|
||||
_retry_slot = (uint8_t)((slot + 1) % OTA_FETCH_PIPELINE);
|
||||
if (requestSlot(slot)) _retry_slot = (uint8_t)((slot + 1) % OTA_FETCH_PIPELINE);
|
||||
return;
|
||||
}
|
||||
}
|
||||
@@ -1290,30 +1391,32 @@ void OtaManager::loop() {
|
||||
return;
|
||||
}
|
||||
if (_fstate != FETCHING) return;
|
||||
// Retry only when a whole tick passed with no committed block, fragment, proof transition, or window
|
||||
// assignment. This avoids re-request spam while any pipelined block is making progress.
|
||||
uint32_t progress = pipelineProgress();
|
||||
if (_have == _loop_last_have && progress == _loop_last_progress) requestMissing();
|
||||
_loop_last_have = _have;
|
||||
_loop_last_progress = pipelineProgress();
|
||||
if (activePipelineSlots() == 0) {
|
||||
requestMissing();
|
||||
return;
|
||||
}
|
||||
// The main loop may still tick each second for discovery, but block recovery waits for the calculated
|
||||
// response train: current SF/BW airtime * outstanding packets * source/relay transmissions * duty pacing.
|
||||
// Every newly accepted fragment/proof restarts the deadline; duplicate flood copies do not.
|
||||
if ((uint32_t)(_now_ms - _fetch_wait_since_ms) >= fetchRetryTimeoutMs()) requestMissing();
|
||||
}
|
||||
|
||||
// ---------------- dispatch ----------------
|
||||
|
||||
void OtaManager::on_message(const uint8_t* msg, uint16_t len) {
|
||||
bool OtaManager::on_message(const uint8_t* msg, uint16_t len) {
|
||||
switch (ota_msg_type(msg, len)) {
|
||||
case OTA_ADV: handleAdv(msg, len); break;
|
||||
case OTA_QUERY: handleQuery(msg, len); break;
|
||||
case OTA_HAVE: handleHave(msg, len); break;
|
||||
case OTA_GET_MANIFEST: handleGetManifest(msg, len); break;
|
||||
case OTA_MANIFEST: handleManifest(msg, len); break;
|
||||
case OTA_GET_LEAVES: handleGetLeaves(msg, len); break;
|
||||
case OTA_LEAVES: handleLeaves(msg, len); break;
|
||||
case OTA_REQ: handleReq(msg, len); break;
|
||||
case OTA_DATA: handleData(msg, len); break;
|
||||
case OTA_REQ_PROOF: handleReqProof(msg, len); break;
|
||||
case OTA_PROOF: handleProof(msg, len); break;
|
||||
default: break;
|
||||
case OTA_ADV: handleAdv(msg, len); return false;
|
||||
case OTA_QUERY: handleQuery(msg, len); return false;
|
||||
case OTA_HAVE: handleHave(msg, len); return false;
|
||||
case OTA_GET_MANIFEST: handleGetManifest(msg, len); return false;
|
||||
case OTA_MANIFEST: handleManifest(msg, len); return false;
|
||||
case OTA_GET_LEAVES: handleGetLeaves(msg, len); return false;
|
||||
case OTA_LEAVES: handleLeaves(msg, len); return false;
|
||||
case OTA_REQ: return handleReq(msg, len);
|
||||
case OTA_DATA: return handleData(msg, len);
|
||||
case OTA_REQ_PROOF: return handleReqProof(msg, len);
|
||||
case OTA_PROOF: return handleProof(msg, len);
|
||||
default: return false;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
#include <stdint.h>
|
||||
#include <stddef.h>
|
||||
#include "OtaFormat.h"
|
||||
#include "OtaProtocol.h"
|
||||
#include "OtaByteIO.h"
|
||||
#include "OtaStore.h"
|
||||
#include "MotaContainer.h"
|
||||
@@ -139,32 +140,31 @@ typedef bool (*ServeReadFn)(void* ctx, uint32_t off, uint8_t* buf, uint32_t len)
|
||||
#define OTA_PROOF_GRACE_MS 500 // wait for the server's proactive proof before legacy REQ_PROOF fallback
|
||||
#endif
|
||||
#ifndef OTA_FETCH_PIPELINE
|
||||
#define OTA_FETCH_PIPELINE 2 // concurrent client block slots; keeps one block ready behind proof/flash work
|
||||
#define OTA_FETCH_PIPELINE 2 // max blocks in one adaptive request flight
|
||||
#endif
|
||||
#if OTA_FETCH_PIPELINE < 1
|
||||
#error "OTA_FETCH_PIPELINE must be at least 1"
|
||||
#endif
|
||||
#if OTA_FETCH_PIPELINE > OTA_REQ_MAX_ITEMS
|
||||
#error "OTA_FETCH_PIPELINE exceeds the OTA_REQ window wire limit"
|
||||
#endif
|
||||
#ifndef OTA_FETCH_PIPELINE_INITIAL
|
||||
#if OTA_FETCH_PIPELINE >= 2
|
||||
#define OTA_FETCH_PIPELINE_INITIAL 2
|
||||
#else
|
||||
#define OTA_FETCH_PIPELINE_INITIAL 1
|
||||
#endif
|
||||
#define OTA_FETCH_PIPELINE_INITIAL 1 // probe every session conservatively, then grow one block per clean flight
|
||||
#endif
|
||||
#if OTA_FETCH_PIPELINE_INITIAL < 1 || OTA_FETCH_PIPELINE_INITIAL > OTA_FETCH_PIPELINE
|
||||
#error "OTA_FETCH_PIPELINE_INITIAL must be between 1 and OTA_FETCH_PIPELINE"
|
||||
#endif
|
||||
#ifndef OTA_FETCH_PIPELINE_GROW_BLOCKS
|
||||
#define OTA_FETCH_PIPELINE_GROW_BLOCKS 4 // clean verified blocks before adding one concurrent request slot
|
||||
#ifndef OTA_FETCH_RETRY_MIN_MS
|
||||
#define OTA_FETCH_RETRY_MIN_MS 5000 // quiet-time floor: covers host/queue/turnaround latency on fast links
|
||||
#endif
|
||||
#if OTA_FETCH_PIPELINE_GROW_BLOCKS < 1
|
||||
#error "OTA_FETCH_PIPELINE_GROW_BLOCKS must be at least 1"
|
||||
#ifndef OTA_FETCH_RETRY_MAX_MS
|
||||
#define OTA_FETCH_RETRY_MAX_MS 60000 // bound loss recovery when configured radio settings are impractical
|
||||
#endif
|
||||
#ifndef OTA_FETCH_PIPELINE_SHRINK_TICKS
|
||||
#define OTA_FETCH_PIPELINE_SHRINK_TICKS 2 // consecutive no-progress retry ticks before removing one slot
|
||||
#ifndef OTA_FETCH_RETRY_GUARD_MS
|
||||
#define OTA_FETCH_RETRY_GUARD_MS 500 // processing/CAD/queue jitter beyond calculated on-air service
|
||||
#endif
|
||||
#if OTA_FETCH_PIPELINE_SHRINK_TICKS < 1
|
||||
#error "OTA_FETCH_PIPELINE_SHRINK_TICKS must be at least 1"
|
||||
#ifndef OTA_FETCH_RETRY_FALLBACK_MS
|
||||
#define OTA_FETCH_RETRY_FALLBACK_MS 5000 // portable-host fallback until the Mesh adapter supplies airtime
|
||||
#endif
|
||||
// nRF52 note: a flash page-erase halts the CPU (~85 ms, code runs from flash) and starves the LoRa RX,
|
||||
// so writing to flash on every received packet drops in-flight DATA and the transfer stalls. The SD-safe
|
||||
@@ -301,6 +301,18 @@ public:
|
||||
void queryAll();
|
||||
// Coarse clock for source/catalog ages + LRU (the Mesh adapter feeds millis; 0 in host tests is fine).
|
||||
void set_clock(uint32_t ms) { _now_ms = ms; }
|
||||
// Feed the actual TempRadio packet airtime and dispatcher transmit-spacing factor. The fetch retry
|
||||
// deadline then follows SF/BW, configured airtime budget, flight width, and observed/configured path.
|
||||
void set_link_timing(uint32_t max_packet_airtime_ms, uint16_t tx_spacing_permille) {
|
||||
_radio_packet_airtime_ms = max_packet_airtime_ms;
|
||||
_tx_spacing_permille = tx_spacing_permille < 1000 ? 1000 : tx_spacing_permille;
|
||||
}
|
||||
// `relay_hops` is the received packet's path-hash count; one more radio transmission originated it.
|
||||
// Keep the longest path seen in this fetch so a shorter duplicate cannot make recovery premature.
|
||||
void note_rx_path_hops(uint8_t relay_hops) {
|
||||
uint8_t transmissions = relay_hops == 0xFF ? 0xFF : (uint8_t)(relay_hops + 1);
|
||||
if (transmissions > _observed_path_transmissions) _observed_path_transmissions = transmissions;
|
||||
}
|
||||
|
||||
// Codec compatibility: a node only fetches/accepts firmware it can actually apply. ESP32 A/B accepts
|
||||
// full images; nRF52 single-slot does not and disables them (it requires an in-place delta). A manual
|
||||
@@ -346,7 +358,10 @@ public:
|
||||
// This node's id (pubkey[0:4]), stamped into adverts we send so receivers can count distinct seeders.
|
||||
void set_seeder_id(const uint8_t* id4) { if (id4) for (int i = 0; i < 4; i++) _seeder_id[i] = id4[i]; }
|
||||
|
||||
void on_message(const uint8_t* msg, uint16_t len); // feed one received OTA message
|
||||
// Feed one received OTA message. True means this node terminally consumed a
|
||||
// bulk request/response, so Mesh must not echo it as if this node were an
|
||||
// intermediate relay.
|
||||
bool on_message(const uint8_t* msg, uint16_t len);
|
||||
void loop(); // drive fetch (re-request missing blocks)
|
||||
// Fast, non-blocking service called from the main radio loop. It admits at most one retained server
|
||||
// response or proof fallback per call; the send callback provides packet-pool/queue backpressure.
|
||||
@@ -358,7 +373,7 @@ public:
|
||||
void reset_session() {
|
||||
_fstate = IDLE; _have = 0; _req_count = 0; _mf_retries = 0;
|
||||
clearReassembly();
|
||||
_loop_last_have = 0; _loop_last_progress = pipelineProgress();
|
||||
_observed_path_transmissions = 0;
|
||||
_mf_total = 0; _mf_mask = 0; _mf_len = 0; _loop_last_mfmask = 0;
|
||||
freeLeaves(); _validate = false; _archive_fetch = false;
|
||||
_lv_retries = 0; _loop_last_lvmask = 0;
|
||||
@@ -371,6 +386,8 @@ public:
|
||||
uint32_t blocksTotal() const { return _fbc; }
|
||||
uint8_t fetchPipelineWidth() const { return _pipeline_width; }
|
||||
static constexpr uint8_t fetchPipelineCapacity() { return OTA_FETCH_PIPELINE; }
|
||||
uint32_t fetchRetryTimeoutMs() const;
|
||||
uint32_t proofGraceMs() const;
|
||||
const uint8_t* fetchManifestId() const { return _fid; }
|
||||
|
||||
// --- discovery catalog (for `ota neighbors`): mOTAs heard around us via OTA_HAVE, deduped by mid ---
|
||||
@@ -412,10 +429,10 @@ private:
|
||||
bool beginLeafDiff(); // enter WANT_LEAVES if a seed diff is viable
|
||||
void diffStep(); // diff one batch of seed blocks per loop tick
|
||||
void freeLeaves(); // release the heap leaves buffer + diff state
|
||||
void handleReq(const uint8_t* m, uint16_t n);
|
||||
void handleData(const uint8_t* m, uint16_t n);
|
||||
void handleReqProof(const uint8_t* m, uint16_t n);
|
||||
void handleProof(const uint8_t* m, uint16_t n);
|
||||
bool handleReq(const uint8_t* m, uint16_t n);
|
||||
bool handleData(const uint8_t* m, uint16_t n);
|
||||
bool handleReqProof(const uint8_t* m, uint16_t n);
|
||||
bool handleProof(const uint8_t* m, uint16_t n);
|
||||
void startFetch(const uint8_t* mid, uint32_t target, bool validate = false); // begin/resume a fetch
|
||||
bool wantRow(const uint8_t* mid, uint32_t target, uint8_t codec, uint8_t flags) const; // fetch this row?
|
||||
void clearReassembly(); // forget every in-flight pipeline slot
|
||||
@@ -423,9 +440,11 @@ private:
|
||||
int findReassemblySlot(uint32_t block) const;
|
||||
int findEmptyReassemblySlot() const;
|
||||
bool blockInPipeline(uint32_t block) const;
|
||||
void notePipelineBlockVerified();
|
||||
void notePipelineStall();
|
||||
uint32_t pipelineProgress() const;
|
||||
void finishFlight();
|
||||
uint8_t activePipelineSlots() const;
|
||||
bool flightHasPendingData() const;
|
||||
void noteFetchActivity() { _fetch_wait_since_ms = _now_ms; }
|
||||
uint32_t pickMissingBlock(); // choose the next missing block not already in flight
|
||||
int serveEntryIndex(const uint8_t* mid) const; // registry slot serving this mid (-1 if none)
|
||||
ServeView* resolve(const uint8_t* mid); // pick/load the ServeView for this mid (nullptr)
|
||||
@@ -455,8 +474,9 @@ private:
|
||||
void beginStagedVerification();
|
||||
void verifyStagedStep();
|
||||
bool requestSlot(uint8_t slot); // request DATA holes or the proof for one slot
|
||||
bool fillPipeline(); // assign and request blocks until the window is full
|
||||
void requestMissing(); // fill the window, or retry one stalled slot
|
||||
bool requestFlight(); // send all newly assigned blocks in one OTA_REQ
|
||||
bool fillPipeline(); // assign + send a new flight only when the old one ended
|
||||
void requestMissing(); // start a flight, or recover one stalled slot
|
||||
uint32_t blockLen(uint32_t i) const;
|
||||
|
||||
uint32_t _target = 0;
|
||||
@@ -507,8 +527,7 @@ private:
|
||||
uint32_t _resume_verify_idx = 0;
|
||||
bool _resume_invalidated = false;
|
||||
MerkleAccumulator _resume_merkle;
|
||||
uint32_t _req_start = 0, _req_count = 0; // most recently requested block + active window size
|
||||
uint32_t _loop_last_have = 0; // for stall detection in loop()
|
||||
uint32_t _req_start = 0, _req_count = 0; // most recently requested block + active flight size
|
||||
uint32_t _desired_target = 0; // manual cross-target override (0 = auto / own target)
|
||||
uint8_t _desired_mid[4] = {0,0,0,0}; // pull a specific manifest_id (see want_mid)
|
||||
bool _have_desired_mid = false;
|
||||
@@ -523,9 +542,10 @@ private:
|
||||
uint16_t _advert_mins = OTA_ADVERT_INTERVAL_MINS; // beacon re-advertise cadence, minutes; 0=off (persisted)
|
||||
uint8_t _max_hops = OTA_HOP_LIMIT_DEFAULT; // OTA flood reach in hops; 0=direct only (persisted)
|
||||
uint8_t _fflags = 0; // flags of the manifest currently being fetched
|
||||
// Bounded adaptive multi-block client pipeline. Each slot independently reassembles DATA and awaits its
|
||||
// Merkle proof, so proof/flash work for one block can overlap radio delivery of the next. The live window
|
||||
// grows on clean verified blocks and contracts after stalled service ticks; the wire protocol is unchanged.
|
||||
// Bounded adaptive multi-block client flight. Each slot independently reassembles DATA and awaits its
|
||||
// Merkle proof. One append-only OTA_REQ packet opens the whole flight; the receiver then stays quiet until
|
||||
// every slot completes or an airtime-aware deadline expires. Clean flights grow 1->2->3->4; any recovery
|
||||
// makes the next flight smaller. Logical/signed block geometry remains 1 KB.
|
||||
struct ReassemblySlot {
|
||||
uint32_t block = NO_BLOCK;
|
||||
uint16_t mask = 0; // received FRAG_DATA-slice bitmap
|
||||
@@ -535,11 +555,13 @@ private:
|
||||
uint8_t buf[OTA_MAX_BLOCK];
|
||||
};
|
||||
ReassemblySlot _reasm[OTA_FETCH_PIPELINE];
|
||||
uint32_t _loop_last_progress = 0; // aggregate pipeline progress for stall detection
|
||||
uint8_t _retry_slot = 0; // round-robin stalled-slot retry cursor
|
||||
uint8_t _pipeline_width = OTA_FETCH_PIPELINE_INITIAL; // live request window, adaptive up to array capacity
|
||||
uint8_t _pipeline_success_streak = 0; // verified blocks since the last grow/stall decision
|
||||
uint8_t _pipeline_stall_streak = 0; // consecutive no-progress service ticks
|
||||
bool _flight_dirty = false; // a timeout/bad proof required recovery in this flight
|
||||
uint32_t _fetch_wait_since_ms = 0; // last new fragment/proof/request; retry deadline anchor
|
||||
uint32_t _radio_packet_airtime_ms = 0; // measured for MAX_TRANS_UNIT at active SF/BW
|
||||
uint16_t _tx_spacing_permille = 2000; // 1/duty-cycle; default airtime factor 1 => 50% TX
|
||||
uint8_t _observed_path_transmissions = 0; // source + relays; 0 falls back to configured max_hops+1
|
||||
// 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
|
||||
uint16_t _mf_retries = 0; // GET_MANIFEST retries while WANT_MANIFEST (give up after a cap)
|
||||
|
||||
@@ -110,6 +110,30 @@ bool decode_req(const uint8_t* buf, uint16_t len, ReqMsg& m) {
|
||||
return r.ok;
|
||||
}
|
||||
|
||||
uint16_t encode_req_window(uint8_t* buf, uint16_t cap, const ReqWindowMsg& m) {
|
||||
if (m.n_items == 0 || m.n_items > OTA_REQ_MAX_ITEMS) return 0;
|
||||
W w(buf, cap); w.u8(OTA_REQ); w.raw(m.manifest_id, 4);
|
||||
for (uint8_t i = 0; i < m.n_items; i++) {
|
||||
w.u16(m.items[i].block_idx); w.u16(m.items[i].want_mask);
|
||||
}
|
||||
return w.ok ? w.n : 0;
|
||||
}
|
||||
|
||||
bool decode_req_window(const uint8_t* buf, uint16_t len, ReqWindowMsg& m) {
|
||||
// Five-byte prefix plus one or more complete four-byte rows. Requiring exact row framing keeps a
|
||||
// truncated request from silently turning into a request for the wrong fragments.
|
||||
if (len < 9 || ((len - 5) % 4) != 0) return false;
|
||||
uint16_t count = (len - 5) / 4;
|
||||
if (count == 0 || count > OTA_REQ_MAX_ITEMS) return false;
|
||||
R r(buf, len); if (r.u8() != OTA_REQ) return false;
|
||||
const uint8_t* id = r.raw(4); if (id) memcpy(m.manifest_id, id, 4);
|
||||
m.n_items = (uint8_t)count;
|
||||
for (uint8_t i = 0; i < m.n_items; i++) {
|
||||
m.items[i].block_idx = r.u16(); m.items[i].want_mask = r.u16();
|
||||
}
|
||||
return r.ok && r.remaining() == 0;
|
||||
}
|
||||
|
||||
uint16_t encode_data(uint8_t* buf, uint16_t cap, const DataMsg& m) {
|
||||
W w(buf, cap); w.u8(OTA_DATA); w.raw(m.manifest_id, 4); w.u16(m.block_idx); w.u16(m.frag_off);
|
||||
w.raw(m.data, m.data_len);
|
||||
|
||||
@@ -63,12 +63,24 @@ struct ManifestMsg {
|
||||
const uint8_t* bytes; uint16_t len;
|
||||
};
|
||||
|
||||
// ---- OTA_REQ: request specific fragments of ONE block (direct) ----
|
||||
// body: manifest_id(4) block_idx(2) want_mask(2). want_mask bit k = "send fragment k" (the slice at byte
|
||||
// offset k*OTA_FRAG_DATA). A fetcher requests the full mask ((1<<nf)-1) for a fresh block and only the
|
||||
// missing bits to recover holes, so a lost fragment costs one fragment to re-send - not the whole block
|
||||
// (saves airtime and avoids the re-REQ colliding with a multi-fragment burst on half-duplex radios).
|
||||
// ---- OTA_REQ: request specific fragments of one or more blocks (direct) ----
|
||||
// body: manifest_id(4) { block_idx(2) want_mask(2) }[1..4]. The first row is exactly the original
|
||||
// single-block OTA_REQ body, so an older source safely serves that row and ignores appended rows. A newer
|
||||
// source queues every row. This lets a fetcher open one adaptive flight with one packet, then remain silent
|
||||
// while the source and relays return the requested DATA/PROOF train.
|
||||
//
|
||||
// want_mask bit k = "send fragment k" (the slice at byte offset k*OTA_FRAG_DATA). A recovery request uses
|
||||
// only the missing bits, so one lost fragment costs one fragment to re-send rather than the whole block.
|
||||
struct ReqMsg { uint8_t manifest_id[4]; uint16_t block_idx; uint16_t want_mask; };
|
||||
struct ReqItem { uint16_t block_idx; uint16_t want_mask; };
|
||||
#ifndef OTA_REQ_MAX_ITEMS
|
||||
#define OTA_REQ_MAX_ITEMS 4
|
||||
#endif
|
||||
struct ReqWindowMsg {
|
||||
uint8_t manifest_id[4];
|
||||
uint8_t n_items;
|
||||
ReqItem items[OTA_REQ_MAX_ITEMS];
|
||||
};
|
||||
|
||||
// ---- OTA_DATA: one self-describing fragment of a block's data (proof stays in a separate packet) ----
|
||||
// body: manifest_id(4) block_idx(2) frag_off(2) data[]
|
||||
@@ -122,6 +134,8 @@ bool decode_manifest(const uint8_t* buf, uint16_t len, ManifestMsg& m);
|
||||
|
||||
uint16_t encode_req(uint8_t* buf, uint16_t cap, const ReqMsg& m);
|
||||
bool decode_req(const uint8_t* buf, uint16_t len, ReqMsg& m);
|
||||
uint16_t encode_req_window(uint8_t* buf, uint16_t cap, const ReqWindowMsg& m);
|
||||
bool decode_req_window(const uint8_t* buf, uint16_t len, ReqWindowMsg& m);
|
||||
|
||||
uint16_t encode_data(uint8_t* buf, uint16_t cap, const DataMsg& m);
|
||||
bool decode_data(const uint8_t* buf, uint16_t len, DataMsg& m);
|
||||
|
||||
@@ -2,14 +2,21 @@
|
||||
#include <stdint.h>
|
||||
|
||||
// AUTO-GENERATED by tools/mota/gen_targets.py - do not edit by hand.
|
||||
// 540 OTA-capable PlatformIO envs. Maps target_id (= sha2-256:4 of the env name, LE uint32)
|
||||
// 552 OTA-capable PlatformIO envs. Maps target_id (= sha2-256:4 of the env name, LE uint32)
|
||||
// to the human-readable env name, so a node/tool can name a target seen over the air WITHOUT
|
||||
// transmitting the string in the .mota / LoRa protocol. Regenerate when the OTA env set changes.
|
||||
// Size-constrained receivers can set OTA_TARGET_NAME_TABLE=0. They still match targets by ID;
|
||||
// OTA_LOCAL_TARGET_ID + OTA_LOCAL_TARGET_NAME optionally retain the local human-readable name.
|
||||
|
||||
namespace mesh { namespace ota {
|
||||
|
||||
// target_id -> env name, or nullptr if unknown. Linear scan (table is small; lookups are rare).
|
||||
#ifndef OTA_TARGET_NAME_TABLE
|
||||
#define OTA_TARGET_NAME_TABLE 1
|
||||
#endif
|
||||
|
||||
// target_id -> env name, or nullptr if unknown. Linear scan; lookups are rare.
|
||||
inline const char* ota_target_env_name(uint32_t target_id) {
|
||||
#if OTA_TARGET_NAME_TABLE
|
||||
static const struct { uint32_t id; const char* env; } T[] = {
|
||||
{ 0x149bcb23, "Ebyte_EoRa-S3_companion_radio_ble" },
|
||||
{ 0x30d4e442, "Ebyte_EoRa-S3_companion_radio_usb" },
|
||||
@@ -264,6 +271,7 @@ inline const char* ota_target_env_name(uint32_t target_id) {
|
||||
{ 0xed73ac03, "LilyGo_T-Echo-Lite_room_server" },
|
||||
{ 0xab0d550a, "LilyGo_T-Echo_Card_companion_radio_ble" },
|
||||
{ 0x1bd2a266, "LilyGo_T-Echo_Card_companion_radio_usb" },
|
||||
{ 0x3655c748, "LilyGo_T-Echo_Card_kiss_modem" },
|
||||
{ 0x9a5ae8fc, "LilyGo_T-Echo_Card_repeater" },
|
||||
{ 0x1e9eb97a, "LilyGo_T-Echo_Card_room_server" },
|
||||
{ 0x139536f4, "LilyGo_T-Echo_companion_radio_ble" },
|
||||
@@ -305,6 +313,7 @@ inline const char* ota_target_env_name(uint32_t target_id) {
|
||||
{ 0xd0e2e616, "LilyGo_TDeck_repeater" },
|
||||
{ 0x3f9edfe3, "LilyGo_TETH_Elite_sx1262_companion_radio_ble" },
|
||||
{ 0xc23f8082, "LilyGo_TETH_Elite_sx1262_companion_radio_usb" },
|
||||
{ 0x0e74ae16, "LilyGo_TETH_Elite_sx1262_kiss_modem" },
|
||||
{ 0x8f256e56, "LilyGo_TETH_Elite_sx1262_repeater" },
|
||||
{ 0xf1407f39, "LilyGo_TETH_Elite_sx1262_room_server" },
|
||||
{ 0xe90a3181, "LilyGo_Tlora_C6_companion_radio_ble_" },
|
||||
@@ -341,6 +350,15 @@ inline const char* ota_target_env_name(uint32_t target_id) {
|
||||
{ 0xcea95e20, "Meshadventurer_sx1268_terminal_chat" },
|
||||
{ 0xd45277ff, "Meshimi_companion_radio_ble_" },
|
||||
{ 0x2cad9a9d, "Meshimi_repeater_" },
|
||||
{ 0x02a4a8c1, "meshnology_w12_companion_radio_ble" },
|
||||
{ 0x35d960bd, "meshnology_w12_companion_radio_usb" },
|
||||
{ 0x62977023, "meshnology_w12_companion_radio_wifi" },
|
||||
{ 0x17a7ed8c, "meshnology_w12_kiss_modem" },
|
||||
{ 0x07f5f5b5, "meshnology_w12_repeater" },
|
||||
{ 0xfd0d4b8f, "meshnology_w12_repeater_bridge_espnow" },
|
||||
{ 0xf5afb7dd, "meshnology_w12_room_server" },
|
||||
{ 0x6ebf28cb, "meshnology_w12_sensor" },
|
||||
{ 0x2d589527, "meshnology_w12_terminal_chat" },
|
||||
{ 0x77d0810c, "Minewsemi_me25ls01_repeater" },
|
||||
{ 0xf8259880, "Nano_G2_Ultra_repeater" },
|
||||
{ 0x063f1f00, "nibble_screen_connect_companion_radio_ble_" },
|
||||
@@ -494,6 +512,7 @@ inline const char* ota_target_env_name(uint32_t target_id) {
|
||||
{ 0x236f605c, "ThinkNode_M6_repeater" },
|
||||
{ 0x93994fed, "ThinkNode_M6_room_server" },
|
||||
{ 0x66c47cfd, "ThinkNode_M7_companion_radio_ble" },
|
||||
{ 0x48061a01, "ThinkNode_M7_companion_radio_ethernet" },
|
||||
{ 0xa01688a7, "ThinkNode_M7_companion_radio_usb" },
|
||||
{ 0xa5f4a562, "ThinkNode_M7_companion_radio_wifi" },
|
||||
{ 0xef83222b, "ThinkNode_M7_kiss_modem" },
|
||||
@@ -554,6 +573,11 @@ inline const char* ota_target_env_name(uint32_t target_id) {
|
||||
};
|
||||
for (unsigned i = 0; i < sizeof(T) / sizeof(T[0]); i++)
|
||||
if (T[i].id == target_id) return T[i].env;
|
||||
#elif defined(OTA_LOCAL_TARGET_ID) && defined(OTA_LOCAL_TARGET_NAME)
|
||||
if (target_id == (uint32_t)(OTA_LOCAL_TARGET_ID)) return OTA_LOCAL_TARGET_NAME;
|
||||
#else
|
||||
(void)target_id;
|
||||
#endif
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user