Fix OTA resume, CLI identity, radio persistence, and network sessions
Distinguish OTA read failures from missing blocks and select unique raw-flash checkpoints by MID and target. Keep deferred CLI requests and replies bound to immutable command identity and full authenticated keys. Gate radio mutations on their exact reply delivery, recover coding-rate restoration, and roll back failed Companion preference writes. Preserve accepted low duty cycles across reboot. Retain partial network writes, cancel displaced client operations, and reject malformed or stalled framed input. Add regression and CI coverage, and size-optimize the RAK4631 Ethernet build without dropping features.
This commit is contained in:
1 parent
931cb4928f
commit
a88ced23b6
64 files changed
+3504
-369
No files matched your search
+44
-4
@@ -124,15 +124,40 @@ void Dispatcher::updateTxBudget() {
|
||||
}
|
||||
}
|
||||
|
||||
void Dispatcher::restoreOutboundTxOverrides() {
|
||||
if (outbound_restore_cr != 0) {
|
||||
_radio->setCodingRate(outbound_restore_cr);
|
||||
bool Dispatcher::restoreOutboundTxOverrides() {
|
||||
if (!outbound_restore_cr) return true;
|
||||
const uint32_t now = _ms->getMillis();
|
||||
if (outbound_restore_retry_at && (int32_t)(now - outbound_restore_retry_at) < 0) return false;
|
||||
// A scanner or an intervening settings change may have selected another
|
||||
// profile since the failed restore. Restore its configured CR, not a stale
|
||||
// default from the preceding packet.
|
||||
const uint8_t cr = _radio->profiles()
|
||||
? _radio->profiles()->params(_radio->receiveProfile()).cr : getDefaultTxCodingRate();
|
||||
const auto result = _radio->tryRestoreCodingRate(cr >= 4 && cr <= 8 ? cr : outbound_restore_cr);
|
||||
if (result == RadioParamApplyResult::APPLIED) {
|
||||
outbound_restore_cr = 0;
|
||||
outbound_restore_retry_at = outbound_restore_recovery_at = 0;
|
||||
return true;
|
||||
}
|
||||
outbound_restore_retry_at = now + 250;
|
||||
if (result == RadioParamApplyResult::BUSY) {
|
||||
// A legitimate RX/preamble/duty-cycle sleep is not a failed modulation
|
||||
// write. Let receive service drain it without forcing a radio reset.
|
||||
outbound_restore_recovery_at = 0;
|
||||
return false;
|
||||
}
|
||||
if (!outbound_restore_recovery_at) outbound_restore_recovery_at = now + RADIO_PREPARE_BUSY_GRACE_MS;
|
||||
else if ((int32_t)(now - outbound_restore_recovery_at) >= 0) {
|
||||
_err_flags |= ERR_EVENT_RADIO_WATCHDOG;
|
||||
_radio->recoverRadio(true);
|
||||
outbound_restore_recovery_at = now + RADIO_PREPARE_BUSY_GRACE_MS;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
bool Dispatcher::startOutboundTransmit() {
|
||||
if (outbound == NULL) return false;
|
||||
if (!restoreOutboundTxOverrides()) return false;
|
||||
if (!isPacketRadioCurrent(outbound)
|
||||
|| _radio->prepareTransmitProfile(outbound->radio_profile,
|
||||
outbound->radio_reply && outbound->radio_reply_force) != RadioParamApplyResult::APPLIED) return false;
|
||||
@@ -286,6 +311,12 @@ bool Dispatcher::getNextQueueWakeDelay(uint32_t& delay_millis) const {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (outbound_restore_cr) {
|
||||
const int32_t restore_delay = (int32_t)(outbound_restore_retry_at - now);
|
||||
shortest_delay = restore_delay > 0 ? (uint32_t)restore_delay : 0;
|
||||
found = true;
|
||||
}
|
||||
|
||||
uint32_t scheduled_for;
|
||||
if (_mgr->getNextOutboundTime(now, scheduled_for)) {
|
||||
int32_t signed_queue_delay = (int32_t)(scheduled_for - now);
|
||||
@@ -294,7 +325,7 @@ bool Dispatcher::getNextQueueWakeDelay(uint32_t& delay_millis) const {
|
||||
if (signed_tx_delay > 0 && (uint32_t)signed_tx_delay > outbound_delay) {
|
||||
outbound_delay = (uint32_t)signed_tx_delay;
|
||||
}
|
||||
shortest_delay = outbound_delay;
|
||||
if (!found || outbound_delay < shortest_delay) shortest_delay = outbound_delay;
|
||||
found = true;
|
||||
}
|
||||
|
||||
@@ -384,6 +415,12 @@ void Dispatcher::loop() {
|
||||
return;
|
||||
}
|
||||
if (!millisHasNowPassed(outbound_radio_retry_at)) return;
|
||||
if (!restoreOutboundTxOverrides()) {
|
||||
// Release a failed retained retry; restoration itself remains pending
|
||||
// while normal RX/watchdog service and future queued work continue.
|
||||
failOutboundTransmit();
|
||||
return;
|
||||
}
|
||||
const auto prepared = _radio->prepareTransmitProfile(outbound->radio_profile,
|
||||
outbound->radio_reply && outbound->radio_reply_force);
|
||||
if (prepared == RadioParamApplyResult::BUSY) {
|
||||
@@ -799,6 +836,9 @@ bool Dispatcher::isTransmitChannelReady(const Packet* packet, uint32_t& retry_de
|
||||
|
||||
void Dispatcher::checkSend() {
|
||||
if (_radio->isCarrierWaveActive()) return;
|
||||
// Keep queued packets intact while recovering a failed per-packet CR
|
||||
// override. RX processing and ordinary watchdogs continue in loop().
|
||||
if (!restoreOutboundTxOverrides()) return;
|
||||
const uint32_t now = _ms->getMillis();
|
||||
if (ota_tx_airtime && now - ota_tx_finished_at >= ota::packetQuietTime(ota_tx_airtime, getOtaSpeedFactor())) {
|
||||
ota_tx_airtime = 0;
|
||||
|
||||
+6
-1
@@ -97,6 +97,9 @@ public:
|
||||
* \returns true if the radio accepted the coding rate.
|
||||
*/
|
||||
virtual bool setCodingRate(uint8_t cr) { return false; }
|
||||
virtual RadioParamApplyResult tryRestoreCodingRate(uint8_t cr) {
|
||||
return setCodingRate(cr) ? RadioParamApplyResult::APPLIED : RadioParamApplyResult::FAILED;
|
||||
}
|
||||
|
||||
/**
|
||||
* \returns true if the previous 'startSendRaw()' completed successfully.
|
||||
@@ -322,7 +325,9 @@ class Dispatcher {
|
||||
bool scheduleOutboundRadioRetry();
|
||||
bool isTransmitChannelReady(const Packet* packet, uint32_t& retry_delay);
|
||||
void failOutboundTransmit();
|
||||
void restoreOutboundTxOverrides();
|
||||
bool restoreOutboundTxOverrides();
|
||||
uint32_t outbound_restore_retry_at = 0;
|
||||
uint32_t outbound_restore_recovery_at = 0;
|
||||
void updateTxBudget();
|
||||
|
||||
protected:
|
||||
|
||||
@@ -1300,7 +1300,9 @@ void CommonCLI::loadPrefsInt(FILESYSTEM* fs, const char* filename) {
|
||||
_prefs->rx_delay_base = constrain(_prefs->rx_delay_base, 0, 20.0f);
|
||||
_prefs->tx_delay_factor = constrain(_prefs->tx_delay_factor, 0, 2.0f);
|
||||
_prefs->direct_tx_delay_factor = constrain(_prefs->direct_tx_delay_factor, 0, 2.0f);
|
||||
_prefs->airtime_factor = constrain(_prefs->airtime_factor, 0, 9.0f);
|
||||
// Duty cycles down to 1% are accepted and persist factor 99, even though
|
||||
// the legacy `set af` command retains its narrower input range.
|
||||
_prefs->airtime_factor = constrain(_prefs->airtime_factor, 0, 99.0f);
|
||||
_prefs->freq = constrain(_prefs->freq, 150.0f, 2500.0f);
|
||||
_prefs->bw = isValidLoRaBandwidth(_prefs->bw) ? _prefs->bw : defaultLoRaBandwidth();
|
||||
_prefs->sf = constrain(_prefs->sf, 5, 12);
|
||||
@@ -2470,7 +2472,7 @@ void CommonCLI::handleCommand(uint32_t sender_timestamp, char* command, char* re
|
||||
mesh::cli::normalizeCommandVerb(command);
|
||||
if (mesh::wireless::control().handle(command, reply, 160, millis(),
|
||||
_callbacks->wirelessCommandSource(sender_timestamp))) return;
|
||||
if (_radio_profiles.handle(command, reply)) return;
|
||||
if (_radio_profiles.handle(command, reply, 160, sender_timestamp != 0)) return;
|
||||
#if defined(ENABLE_OTA)
|
||||
if (mesh::ota::handleSpeedCommand(command, reply, 160)) return;
|
||||
#endif
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
#pragma once
|
||||
|
||||
#include <MeshCore.h>
|
||||
#include "RemoteCliReplyCache.h"
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
#include <string.h>
|
||||
@@ -14,9 +15,14 @@ namespace mesh {
|
||||
// perform filesystem or cryptographic work.
|
||||
struct DeferredCliCommand {
|
||||
bool pending;
|
||||
int client_index;
|
||||
// ACL entries can move or be reused while a request is pending or executing.
|
||||
// Bind its owner to the complete authenticated key, never an array slot.
|
||||
uint8_t client_pub_key[PUB_KEY_SIZE];
|
||||
uint32_t sender_timestamp;
|
||||
uint32_t request_id;
|
||||
// Command handlers may normalize or tokenize command[] in place. Keep the
|
||||
// authenticated wire identity separately so retries find the stored result.
|
||||
uint32_t command_fingerprint;
|
||||
uint8_t path_hash_size;
|
||||
uint8_t radio_profile = 0;
|
||||
uint32_t radio_generation = 0;
|
||||
@@ -24,26 +30,28 @@ struct DeferredCliCommand {
|
||||
char command[MAX_PACKET_PAYLOAD + 1];
|
||||
|
||||
DeferredCliCommand()
|
||||
: pending(false), client_index(-1), sender_timestamp(0), request_id(0),
|
||||
path_hash_size(1) {
|
||||
: pending(false), sender_timestamp(0), request_id(0),
|
||||
command_fingerprint(0), path_hash_size(1) {
|
||||
memset(client_pub_key, 0, sizeof(client_pub_key));
|
||||
memset(secret, 0, sizeof(secret));
|
||||
command[0] = 0;
|
||||
}
|
||||
|
||||
bool enqueue(int new_client_index, uint32_t new_sender_timestamp,
|
||||
bool enqueue(const uint8_t* new_client_pub_key, uint32_t new_sender_timestamp,
|
||||
uint8_t new_path_hash_size, const uint8_t* new_secret,
|
||||
const char* new_command, size_t command_len,
|
||||
uint32_t new_request_id = 0, uint8_t new_radio_profile = 0,
|
||||
uint32_t new_radio_generation = 0) {
|
||||
if (pending || new_secret == NULL || new_command == NULL
|
||||
if (pending || new_client_pub_key == NULL || new_secret == NULL || new_command == NULL
|
||||
|| command_len >= sizeof(command)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
client_index = new_client_index;
|
||||
memcpy(client_pub_key, new_client_pub_key, sizeof(client_pub_key));
|
||||
sender_timestamp = new_sender_timestamp;
|
||||
request_id = new_request_id != 0
|
||||
? new_request_id : new_sender_timestamp;
|
||||
command_fingerprint = RemoteCliReplyCache::fingerprint(new_command, command_len);
|
||||
path_hash_size = new_path_hash_size;
|
||||
radio_profile = new_radio_profile;
|
||||
radio_generation = new_radio_generation;
|
||||
@@ -54,21 +62,31 @@ struct DeferredCliCommand {
|
||||
return true;
|
||||
}
|
||||
|
||||
bool matches(int other_client_index, uint32_t other_request_id,
|
||||
bool matches(const uint8_t* other_client_pub_key, uint32_t other_request_id,
|
||||
const char* other_command, size_t other_command_len) const {
|
||||
return pending && other_command != NULL
|
||||
&& client_index == other_client_index
|
||||
return pending && other_client_pub_key != NULL && other_command != NULL
|
||||
&& memcmp(client_pub_key, other_client_pub_key, sizeof(client_pub_key)) == 0
|
||||
&& request_id == other_request_id
|
||||
&& other_command_len < sizeof(command)
|
||||
&& command[other_command_len] == 0
|
||||
&& memcmp(command, other_command, other_command_len) == 0;
|
||||
}
|
||||
|
||||
template <typename ACL> int findClientIndex(const ACL& acl) const {
|
||||
if (!pending) return -1;
|
||||
for (int i = 0; i < acl.getNumClients(); ++i) {
|
||||
if (memcmp(client_pub_key, acl.getClientByIdx(i)->id.pub_key,
|
||||
sizeof(client_pub_key)) == 0) return i;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
void clear() {
|
||||
pending = false;
|
||||
client_index = -1;
|
||||
memset(client_pub_key, 0, sizeof(client_pub_key));
|
||||
sender_timestamp = 0;
|
||||
request_id = 0;
|
||||
command_fingerprint = 0;
|
||||
path_hash_size = 1;
|
||||
radio_profile = 0;
|
||||
radio_generation = 0;
|
||||
|
||||
+120
-14
@@ -12,6 +12,9 @@ constexpr size_t ImageSize = 24;
|
||||
const char* const ImagePath = "/radio_profiles";
|
||||
const char* const BackupPath = "/radio_profiles.bak";
|
||||
const char* const TempPath = "/radio_profiles.tmp";
|
||||
// Never considered a boot-time committed image. Losing power before the
|
||||
// acknowledgement leaves the previous saved radio untouched.
|
||||
const char* const ReplyPath = "/radio_profiles.reply";
|
||||
uint32_t checksum(const uint8_t* p, size_t n) {
|
||||
uint32_t crc = 0xffffffffU;
|
||||
while (n--) {
|
||||
@@ -91,6 +94,11 @@ bool RadioProfileCLI::writeImage(const char* path, const uint8_t* bytes, size_t
|
||||
}
|
||||
|
||||
bool RadioProfileCLI::save(const RadioProfileConfig& config, uint16_t preamble, RadioCrossMode cross) {
|
||||
return prepareSavedImage(TempPath, config, preamble, cross) && commitSavedImage(TempPath);
|
||||
}
|
||||
|
||||
bool RadioProfileCLI::prepareSavedImage(const char* path, const RadioProfileConfig& config,
|
||||
uint16_t preamble, RadioCrossMode cross) {
|
||||
if (!fs_ || hold_) return false;
|
||||
uint8_t image[ImageSize] = {'R', '2', 1, (uint8_t)config.mode};
|
||||
memcpy(image + 4, &config.params.freq, 4);
|
||||
@@ -102,12 +110,16 @@ bool RadioProfileCLI::save(const RadioProfileConfig& config, uint16_t preamble,
|
||||
image[19] = reply_setting_;
|
||||
const uint32_t crc = checksum(image, ImageSize - 4);
|
||||
memcpy(image + ImageSize - 4, &crc, 4);
|
||||
if (!writeImage(TempPath, image, sizeof(image))) return false;
|
||||
return writeImage(path, image, sizeof(image));
|
||||
}
|
||||
|
||||
bool RadioProfileCLI::commitSavedImage(const char* path) {
|
||||
if (!fs_ || hold_) return false;
|
||||
if (fs_->exists(ImagePath)) {
|
||||
if (fs_->exists(BackupPath) && !fs_->remove(BackupPath)) return false;
|
||||
if (!fs_->rename(ImagePath, BackupPath)) return false;
|
||||
}
|
||||
if (!fs_->rename(TempPath, ImagePath)) {
|
||||
if (!fs_->rename(path, ImagePath)) {
|
||||
if (fs_->exists(BackupPath) && !fs_->rename(BackupPath, ImagePath)) hold_ = true;
|
||||
return false;
|
||||
}
|
||||
@@ -159,6 +171,7 @@ bool RadioProfileCLI::savePrimaryPreamble(uint16_t symbols) {
|
||||
if (symbols && (symbols < 8 || symbols > RadioProfiles::MaxPreamble)) return false;
|
||||
if (!radio_ || !radio_->profiles()) return symbols == 0;
|
||||
if (symbols == primary_preamble_) return true;
|
||||
if (hasReplyMutation()) return false;
|
||||
if (!save(saved_, symbols, cross_)) return false;
|
||||
primary_preamble_ = symbols;
|
||||
return true;
|
||||
@@ -184,11 +197,73 @@ void RadioProfileCLI::publish() {
|
||||
radio_->profiles()->setSecondary(temp_active_ ? temporary_ : saved_, temp_active_);
|
||||
}
|
||||
|
||||
bool RadioProfileCLI::stageRemoteMutation(RemoteMutation kind, const RadioProfileConfig& config,
|
||||
uint32_t duration_ms, uint8_t delete_mask) {
|
||||
if (hasReplyMutation()) return false;
|
||||
remote_mutation_ = kind;
|
||||
++remote_generation_;
|
||||
remote_config_ = config;
|
||||
remote_duration_ms_ = duration_ms;
|
||||
remote_start_ms_ = millis() + 2000;
|
||||
remote_delete_mask_ = delete_mask;
|
||||
remote_delivered_ = false;
|
||||
remote_commit_retry_ms_ = 0;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool RadioProfileCLI::finishReplyMutation(bool delivered) {
|
||||
if (delivered) { remote_delivered_ = hasReplyMutation(); return true; }
|
||||
const auto kind = remote_mutation_;
|
||||
remote_mutation_ = RemoteMutation::None;
|
||||
remote_delivered_ = false;
|
||||
// This file was never committed, so cancellation needs no risky rollback of
|
||||
// the only saved image. Failure to remove scratch cannot activate it at boot.
|
||||
return (kind != RemoteMutation::Saved && kind != RemoteMutation::Off)
|
||||
|| !fs_ || !fs_->exists(ReplyPath) || fs_->remove(ReplyPath);
|
||||
}
|
||||
|
||||
bool RadioProfileCLI::applyReplyMutation() {
|
||||
const auto kind = remote_mutation_;
|
||||
if ((kind == RemoteMutation::Saved || kind == RemoteMutation::Off)
|
||||
&& !commitSavedImage(ReplyPath)) return false;
|
||||
remote_mutation_ = RemoteMutation::None;
|
||||
remote_delivered_ = false;
|
||||
if (kind == RemoteMutation::None) return true;
|
||||
if (kind == RemoteMutation::Temporary) {
|
||||
pending_temporary_ = remote_config_;
|
||||
pending_duration_ms_ = remote_duration_ms_;
|
||||
temp_start_ms_ = remote_start_ms_; // waiting never extends the hard lease
|
||||
temp_pending_ = true;
|
||||
} else if (kind == RemoteMutation::Saved) {
|
||||
saved_ = remote_config_;
|
||||
publish_pending_ = true; publish_after_ms_ = millis();
|
||||
} else if (kind == RemoteMutation::DeleteTemp) {
|
||||
for (unsigned i = 0; i < 4; ++i) if (remote_delete_mask_ & (1U << i)) {
|
||||
if (schedules_[4+i].started) { temp_active_ = false; temp_remaining_ms_ = 0; }
|
||||
schedules_[4+i] = {};
|
||||
}
|
||||
} else {
|
||||
if (kind == RemoteMutation::Off) { saved_ = {}; schedule_retry_ms_ = 0; }
|
||||
temp_pending_ = temp_active_ = false; temp_remaining_ms_ = 0;
|
||||
for (auto& s : schedules_) if (kind == RemoteMutation::Off || s.temporary) s = {};
|
||||
}
|
||||
// loop() owns publishing, after all completion/failure callbacks have
|
||||
// returned and Dispatcher no longer owns either response packet.
|
||||
return true;
|
||||
}
|
||||
|
||||
void RadioProfileCLI::loop() {
|
||||
if (!radio_ || !radio_->profiles()) return;
|
||||
const uint32_t now = millis(), elapsed = now - last_ms_;
|
||||
last_ms_ = now;
|
||||
if (temp_pending_ && (int32_t)(now - temp_start_ms_) >= 0) {
|
||||
remote_commit_retry_ms_ = elapsed >= remote_commit_retry_ms_ ? 0 : remote_commit_retry_ms_ - elapsed;
|
||||
if (remote_delivered_ && !remote_commit_retry_ms_ && !applyReplyMutation()) {
|
||||
// Keep the accepted operation pending and the old channel live if the
|
||||
// post-ACK atomic rename fails. Never report/apparently apply an unsaved
|
||||
// tuple, and avoid a hot storage retry loop.
|
||||
remote_commit_retry_ms_ = 1000;
|
||||
}
|
||||
if (!hasReplyMutation() && temp_pending_ && (int32_t)(now - temp_start_ms_) >= 0) {
|
||||
temporary_ = pending_temporary_;
|
||||
const uint32_t late = now - temp_start_ms_;
|
||||
temp_remaining_ms_ = late < pending_duration_ms_ ? pending_duration_ms_ - late : 0;
|
||||
@@ -207,7 +282,7 @@ void RadioProfileCLI::loop() {
|
||||
}
|
||||
}
|
||||
schedule_retry_ms_ = elapsed >= schedule_retry_ms_ ? 0 : schedule_retry_ms_ - elapsed;
|
||||
while (!schedule_retry_ms_) {
|
||||
while (!schedule_retry_ms_ && !hasReplyMutation()) {
|
||||
Schedule* next = nullptr;
|
||||
for (auto& s : schedules_) {
|
||||
if (s.active && !s.temporary && epoch >= s.start && (!next || s.start < next->start)) next = &s;
|
||||
@@ -222,7 +297,7 @@ void RadioProfileCLI::loop() {
|
||||
saved_ = next->config; *next = {};
|
||||
}
|
||||
for (auto& s : schedules_) {
|
||||
if (!s.active || !s.temporary || s.started || epoch < s.start || temp_active_ || temp_pending_) continue;
|
||||
if (!s.active || !s.temporary || s.started || epoch < s.start || temp_active_ || temp_pending_ || hasReplyMutation()) continue;
|
||||
temporary_ = s.config;
|
||||
temp_remaining_ms_ = remainingMillis(s.end_ms, now);
|
||||
const uint32_t epoch_left = (s.end - epoch) * 1000UL;
|
||||
@@ -303,7 +378,7 @@ void RadioProfileCLI::formatConfig(char* reply, size_t capacity, const RadioProf
|
||||
appendChirpWarning(reply, capacity, preview);
|
||||
}
|
||||
|
||||
bool RadioProfileCLI::handle(const char* command, char* reply, size_t capacity) {
|
||||
bool RadioProfileCLI::handle(const char* command, char* reply, size_t capacity, bool remote_origin) {
|
||||
if (handleCarrierWaveCommand(radio_, command, reply, capacity)) return true;
|
||||
const char* text = command;
|
||||
enum { Get, Set, Delete } verb = Get;
|
||||
@@ -328,6 +403,13 @@ bool RadioProfileCLI::handle(const char* command, char* reply, size_t capacity)
|
||||
if (!base && !temporary && !scheduled && !crossing && !replies && !status && !scan && !timing) return false;
|
||||
if (!radio_ || !radio_->profiles()) { snprintf(reply, capacity, "Error: radio profiles unsupported"); return true; }
|
||||
if (command == text && *args && verb == Get && (temporary || base)) verb = Set;
|
||||
if (remote_origin && !remote_command_
|
||||
&& (((base || temporary) && verb == Set) || (scheduled_temp && verb == Delete))) {
|
||||
snprintf(reply, capacity, "Error: this role requires local USB for radio2 changes"); return true;
|
||||
}
|
||||
if (hasReplyMutation() && verb != Get) {
|
||||
snprintf(reply, capacity, "Error: radio acknowledgement pending"); return true;
|
||||
}
|
||||
if (replies) {
|
||||
const auto* p = radio_->profiles();
|
||||
if (verb == Get && !*args) {
|
||||
@@ -401,6 +483,11 @@ bool RadioProfileCLI::handle(const char* command, char* reply, size_t capacity)
|
||||
}
|
||||
if (status) {
|
||||
if (verb != Get || *args) { snprintf(reply, capacity, "Error: radio2.status is read-only"); return true; }
|
||||
if (hasReplyMutation()) {
|
||||
snprintf(reply, capacity, "> radio2 change pending %s; previous channel retained",
|
||||
remote_delivered_ ? "storage commit (retrying)" : "reply transmission");
|
||||
return true;
|
||||
}
|
||||
const auto& p = *radio_->profiles();
|
||||
snprintf(reply, capacity, "> %s; RX=%lu,%lu TX=%lu,%lu switches=%lu errors=%lu max=%luus preamble=%u,%u",
|
||||
modeName(p.secondary.mode), (unsigned long)p.rx_packets[0], (unsigned long)p.rx_packets[1],
|
||||
@@ -416,9 +503,16 @@ bool RadioProfileCLI::handle(const char* command, char* reply, size_t capacity)
|
||||
return true;
|
||||
}
|
||||
if ((base || temporary) && verb == Set && !strcmp(args, "off")) {
|
||||
if (base && !save({}, primary_preamble_, cross_)) {
|
||||
if (base && !(remote_command_ ? prepareSavedImage(ReplyPath, {}, primary_preamble_, cross_)
|
||||
: save({}, primary_preamble_, cross_))) {
|
||||
snprintf(reply, capacity, "Error: settings could not be saved"); return true;
|
||||
}
|
||||
if (remote_command_) {
|
||||
stageRemoteMutation(base ? RemoteMutation::Off : RemoteMutation::TempOff);
|
||||
snprintf(reply, capacity, "OK - %s after reply", !base && saved_.mode != RadioProfileMode::Off
|
||||
? "saved radio2 restored" : "single radio");
|
||||
return true;
|
||||
}
|
||||
if (base) { saved_ = {}; schedule_retry_ms_ = 0; }
|
||||
temp_pending_ = temp_active_ = false; temp_remaining_ms_ = 0;
|
||||
for (auto& s : schedules_) if (base || s.temporary) s = {};
|
||||
@@ -433,6 +527,10 @@ bool RadioProfileCLI::handle(const char* command, char* reply, size_t capacity)
|
||||
}
|
||||
const unsigned first = scheduled_temp ? 4 : 0;
|
||||
if (verb == Delete) {
|
||||
if (remote_command_ && scheduled_temp) {
|
||||
stageRemoteMutation(RemoteMutation::DeleteTemp, {}, 0, index ? 1U << (index - 1) : 15);
|
||||
snprintf(reply, capacity, "OK - schedule cleared after reply"); return true;
|
||||
}
|
||||
if (!scheduled_temp) schedule_retry_ms_ = 0;
|
||||
for (unsigned i = 0; i < 4; ++i) if (!index || index == i + 1) {
|
||||
if (schedules_[first+i].started) {
|
||||
@@ -517,17 +615,25 @@ bool RadioProfileCLI::handle(const char* command, char* reply, size_t capacity)
|
||||
for (const auto& s : schedules_) if (s.active && s.temporary) {
|
||||
snprintf(reply, capacity, "Error: clear tempradioat2 schedules first"); return true;
|
||||
}
|
||||
pending_temporary_ = config; pending_duration_ms_ = minutes * 60000UL;
|
||||
temp_start_ms_ = millis() + 2000; temp_pending_ = true;
|
||||
if (remote_command_) stageRemoteMutation(RemoteMutation::Temporary, config, minutes * 60000UL);
|
||||
else {
|
||||
pending_temporary_ = config; pending_duration_ms_ = minutes * 60000UL;
|
||||
temp_start_ms_ = millis() + 2000; temp_pending_ = true;
|
||||
}
|
||||
// An existing session remains active until the new request can take over.
|
||||
snprintf(reply, capacity, "OK - tempradio2 %lud%luh%lum (%lu min); preamble=%u",
|
||||
(unsigned long)(minutes/1440), (unsigned long)(minutes/60%24),
|
||||
(unsigned long)(minutes%60), (unsigned long)minutes, preview.preamble(1, 32));
|
||||
} else if (save(config, primary_preamble_, cross_)) {
|
||||
saved_ = config;
|
||||
publish_pending_ = true; publish_after_ms_ = millis() + 2000;
|
||||
publish();
|
||||
snprintf(reply, capacity, "OK - radio2 %s; preamble=%u", modeName(config.mode), preview.preamble(1, 32));
|
||||
} else if (remote_command_ ? prepareSavedImage(ReplyPath, config, primary_preamble_, cross_)
|
||||
: save(config, primary_preamble_, cross_)) {
|
||||
if (remote_command_) stageRemoteMutation(RemoteMutation::Saved, config);
|
||||
else {
|
||||
saved_ = config;
|
||||
publish_pending_ = true; publish_after_ms_ = millis() + 2000;
|
||||
publish();
|
||||
}
|
||||
snprintf(reply, capacity, "OK - radio2 %s%s; preamble=%u", modeName(config.mode),
|
||||
remote_command_ ? " pending after reply" : "", preview.preamble(1, 32));
|
||||
} else snprintf(reply, capacity, "Error: settings could not be saved");
|
||||
if (!strncmp(reply, "OK", 2)) appendChirpWarning(reply, capacity, preview);
|
||||
return true;
|
||||
|
||||
@@ -37,7 +37,21 @@ class RadioProfileCLI {
|
||||
bool temp_pending_ = false, temp_active_ = false;
|
||||
bool hold_ = false;
|
||||
bool publish_pending_ = false;
|
||||
enum class RemoteMutation : uint8_t { None, Saved, Temporary, Off, TempOff, DeleteTemp };
|
||||
RemoteMutation remote_mutation_ = RemoteMutation::None;
|
||||
RadioProfileConfig remote_config_;
|
||||
uint32_t remote_duration_ms_ = 0, remote_start_ms_ = 0;
|
||||
uint32_t remote_commit_retry_ms_ = 0;
|
||||
uint32_t remote_generation_ = 0;
|
||||
uint8_t remote_delete_mask_ = 0;
|
||||
bool remote_command_ = false, remote_delivered_ = false;
|
||||
bool stageRemoteMutation(RemoteMutation kind, const RadioProfileConfig& config = {},
|
||||
uint32_t duration_ms = 0, uint8_t delete_mask = 0);
|
||||
bool save(const RadioProfileConfig& config, uint16_t preamble, RadioCrossMode cross);
|
||||
bool prepareSavedImage(const char* path, const RadioProfileConfig& config,
|
||||
uint16_t preamble, RadioCrossMode cross);
|
||||
bool commitSavedImage(const char* path);
|
||||
bool applyReplyMutation();
|
||||
bool readImage(const char* path, uint8_t* bytes, size_t size);
|
||||
bool writeImage(const char* path, const uint8_t* bytes, size_t size);
|
||||
void publish();
|
||||
@@ -46,7 +60,14 @@ class RadioProfileCLI {
|
||||
public:
|
||||
void begin(FILESYSTEM* fs, Radio* radio, RTCClock* rtc, bool infrastructure_replies = false);
|
||||
void loop();
|
||||
bool handle(const char* command, char* reply, size_t capacity = 160);
|
||||
bool handle(const char* command, char* reply, size_t capacity = 160, bool remote_origin = false);
|
||||
// Remote infrastructure commands must keep both RX-origin generations alive
|
||||
// until their exact response packets finish, not merely wait a fixed delay.
|
||||
void beginReplyCommand() { remote_command_ = true; }
|
||||
void endReplyCommand() { remote_command_ = false; }
|
||||
bool hasReplyMutation() const { return remote_mutation_ != RemoteMutation::None; }
|
||||
uint32_t replyMutationGeneration() const { return remote_generation_; }
|
||||
bool finishReplyMutation(bool delivered);
|
||||
uint16_t primaryPreamble() const { return primary_preamble_; }
|
||||
bool savePrimaryPreamble(uint16_t symbols);
|
||||
bool acceptsPrimary(float freq, float bw, uint8_t sf, uint8_t cr, uint16_t preamble) const;
|
||||
|
||||
@@ -36,7 +36,8 @@ public:
|
||||
}
|
||||
|
||||
bool remember(const uint8_t* sender_pub_key, uint32_t request_timestamp,
|
||||
uint32_t command_fingerprint, const char* response) {
|
||||
uint32_t command_fingerprint, const char* response,
|
||||
bool authoritative_reply = false) {
|
||||
if (sender_pub_key == NULL || response == NULL) return false;
|
||||
|
||||
Entry* target = NULL;
|
||||
@@ -66,18 +67,21 @@ public:
|
||||
memcpy(target->response, response, response_len);
|
||||
target->response[response_len] = 0;
|
||||
target->valid = true;
|
||||
target->authoritative_reply = authoritative_reply;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool lookup(const uint8_t* sender_pub_key, uint32_t request_timestamp,
|
||||
uint32_t command_fingerprint,
|
||||
const char** response = NULL) const {
|
||||
const char** response = NULL, bool* authoritative_reply = NULL) const {
|
||||
if (authoritative_reply) *authoritative_reply = false;
|
||||
for (size_t i = 0; i < ENTRY_COUNT; ++i) {
|
||||
if (!entryMatches(entries_[i], sender_pub_key, request_timestamp,
|
||||
command_fingerprint)) {
|
||||
continue;
|
||||
}
|
||||
if (response != NULL) *response = entries_[i].response;
|
||||
if (authoritative_reply) *authoritative_reply = entries_[i].authoritative_reply;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
@@ -106,6 +110,7 @@ public:
|
||||
private:
|
||||
struct Entry {
|
||||
bool valid;
|
||||
bool authoritative_reply;
|
||||
uint8_t sender_pub_key[PUB_KEY_SIZE];
|
||||
uint32_t request_timestamp;
|
||||
uint32_t command_fingerprint;
|
||||
|
||||
@@ -36,6 +36,10 @@ public:
|
||||
void clear() { _packet = _copy = nullptr; _armed = _succeeded = false; }
|
||||
|
||||
bool waiting() const { return _armed && (_packet || _copy); }
|
||||
bool succeeded() const { return _armed && _succeeded; }
|
||||
bool contains(const void* packet) const {
|
||||
return _armed && packet && (packet == _packet || packet == _copy);
|
||||
}
|
||||
|
||||
bool complete(const void* packet) {
|
||||
if (!remove(packet)) return false;
|
||||
|
||||
@@ -2,6 +2,8 @@
|
||||
#include "../CompanionFrameQueue.h"
|
||||
#include <WiFi.h>
|
||||
|
||||
static constexpr uint32_t WIFI_FRAME_TIMEOUT_MS = 5000;
|
||||
|
||||
void SerialWifiInterface::clearBuffers() {
|
||||
held_queue_len = send_queue_len = 0;
|
||||
send_offset = 0;
|
||||
@@ -19,7 +21,23 @@ void SerialWifiInterface::expireHeldQueue(uint32_t now) {
|
||||
}
|
||||
|
||||
void SerialWifiInterface::loop() {
|
||||
expireHeldQueue((uint32_t)millis());
|
||||
const uint32_t now = (uint32_t)millis();
|
||||
expireHeldQueue(now);
|
||||
if (deviceConnected && (!client.connected()
|
||||
|| (receive_pending && (uint32_t)(now - receive_started) >= WIFI_FRAME_TIMEOUT_MS))) {
|
||||
disconnectClient(true);
|
||||
}
|
||||
}
|
||||
|
||||
void SerialWifiInterface::disconnectClient(bool cancel_session) {
|
||||
const bool was_connected = deviceConnected;
|
||||
deviceConnected = false;
|
||||
if (client) client.stop();
|
||||
resetReceivedFrameHeader();
|
||||
send_offset = 0; // A reconnect must replay the whole frame, never its suffix.
|
||||
if (cancel_session && was_connected && session_changed != nullptr) {
|
||||
session_changed(session_context);
|
||||
}
|
||||
}
|
||||
|
||||
void SerialWifiInterface::selectClient(const IPAddress& ip, uint32_t now) {
|
||||
@@ -28,8 +46,6 @@ void SerialWifiInterface::selectClient(const IPAddress& ip, uint32_t now) {
|
||||
// IP. An incomplete outgoing frame is retained whole, not just its suffix.
|
||||
send_offset = 0;
|
||||
if (queue_has_ip && queue_ip != ip) {
|
||||
if (session_changed != nullptr) session_changed(session_context);
|
||||
|
||||
if (held_queue_len > 0 && held_ip == ip) {
|
||||
// The previous owner returned: restore its queue and park the displaced
|
||||
// active queue in the same fixed storage. Only one old IP is retained.
|
||||
@@ -83,10 +99,7 @@ void SerialWifiInterface::enable() {
|
||||
|
||||
void SerialWifiInterface::disable() {
|
||||
_isEnabled = false;
|
||||
deviceConnected = false;
|
||||
if (client) client.stop();
|
||||
if (queue_has_ip && session_changed != nullptr) session_changed(session_context);
|
||||
resetReceivedFrameHeader();
|
||||
disconnectClient(true);
|
||||
clearBuffers();
|
||||
}
|
||||
|
||||
@@ -127,10 +140,12 @@ bool SerialWifiInterface::hasReceivedFrameHeader() {
|
||||
void SerialWifiInterface::resetReceivedFrameHeader() {
|
||||
received_frame_header.type = 0;
|
||||
received_frame_header.length = 0;
|
||||
receive_pending = false;
|
||||
receive_started = 0;
|
||||
}
|
||||
|
||||
size_t SerialWifiInterface::checkRecvFrame(uint8_t dest[]) {
|
||||
expireHeldQueue((uint32_t)millis());
|
||||
loop();
|
||||
if (!_isEnabled) return 0;
|
||||
// check if new client connected
|
||||
auto newClient = server.available();
|
||||
@@ -138,8 +153,7 @@ size_t SerialWifiInterface::checkRecvFrame(uint8_t dest[]) {
|
||||
const IPAddress new_ip = newClient.remoteIP();
|
||||
|
||||
// disconnect existing client
|
||||
deviceConnected = false;
|
||||
client.stop();
|
||||
disconnectClient(!queue_has_ip || queue_ip != new_ip);
|
||||
|
||||
// Partition queues and cancel the displaced session before exposing the
|
||||
// new connection to response producers or consuming its first command.
|
||||
@@ -160,7 +174,7 @@ size_t SerialWifiInterface::checkRecvFrame(uint8_t dest[]) {
|
||||
}
|
||||
} else {
|
||||
if (deviceConnected) {
|
||||
deviceConnected = false;
|
||||
disconnectClient(true);
|
||||
WIFI_DEBUG_PRINTLN("Disconnected");
|
||||
}
|
||||
}
|
||||
@@ -189,67 +203,35 @@ size_t SerialWifiInterface::checkRecvFrame(uint8_t dest[]) {
|
||||
memset(&send_queue[send_queue_len], 0, sizeof(send_queue[send_queue_len]));
|
||||
} else {
|
||||
|
||||
// check if we are waiting for a frame header
|
||||
if(!hasReceivedFrameHeader()){
|
||||
|
||||
// make sure we have received enough bytes for a frame header
|
||||
// 3 bytes frame header = (1 byte frame type) + (2 bytes frame length as unsigned 16-bit little endian)
|
||||
int frame_header_length = 3;
|
||||
if(client.available() >= frame_header_length){
|
||||
|
||||
// read frame header
|
||||
client.readBytes(&received_frame_header.type, 1);
|
||||
client.readBytes((uint8_t*)&received_frame_header.length, 2);
|
||||
|
||||
}
|
||||
|
||||
if (!receive_pending && client.available() > 0) {
|
||||
receive_pending = true;
|
||||
receive_started = (uint32_t)millis();
|
||||
}
|
||||
|
||||
// check if we have received a frame header
|
||||
if(hasReceivedFrameHeader()){
|
||||
|
||||
// make sure we have received enough bytes for the required frame length
|
||||
int available = client.available();
|
||||
int frame_type = received_frame_header.type;
|
||||
int frame_length = received_frame_header.length;
|
||||
if(frame_length > available){
|
||||
WIFI_DEBUG_PRINTLN("Waiting for %d more bytes", frame_length - available);
|
||||
if (!hasReceivedFrameHeader()) {
|
||||
if (client.available() < 3) return 0;
|
||||
uint8_t header[3];
|
||||
if (client.readBytes(header, sizeof(header)) != sizeof(header)) {
|
||||
disconnectClient(true);
|
||||
return 0;
|
||||
}
|
||||
|
||||
// skip frames that are larger than MAX_FRAME_SIZE
|
||||
if(frame_length > MAX_FRAME_SIZE){
|
||||
WIFI_DEBUG_PRINTLN("Skipping frame: length=%d is larger than MAX_FRAME_SIZE=%d", frame_length, MAX_FRAME_SIZE);
|
||||
while(frame_length > 0){
|
||||
uint8_t skip[1];
|
||||
int skipped = client.read(skip, 1);
|
||||
frame_length -= skipped;
|
||||
}
|
||||
resetReceivedFrameHeader();
|
||||
received_frame_header.type = header[0];
|
||||
received_frame_header.length = uint16_t(header[1]) | (uint16_t(header[2]) << 8);
|
||||
// Validate before waiting for any payload. Closing an invalid stream
|
||||
// avoids unbounded discard loops and interpreting its tail as commands.
|
||||
if (received_frame_header.type != '<' || received_frame_header.length == 0
|
||||
|| received_frame_header.length > MAX_FRAME_SIZE) {
|
||||
disconnectClient(true);
|
||||
return 0;
|
||||
}
|
||||
|
||||
// skip frames that are not expected type
|
||||
// '<' is 0x3c which indicates a frame sent from app to radio
|
||||
if(frame_type != '<'){
|
||||
WIFI_DEBUG_PRINTLN("Skipping frame: type=0x%x is unexpected", frame_type);
|
||||
while(frame_length > 0){
|
||||
uint8_t skip[1];
|
||||
int skipped = client.read(skip, 1);
|
||||
frame_length -= skipped;
|
||||
}
|
||||
resetReceivedFrameHeader();
|
||||
return 0;
|
||||
}
|
||||
|
||||
// read frame data to provided buffer
|
||||
client.readBytes(dest, frame_length);
|
||||
|
||||
// ready for next frame
|
||||
resetReceivedFrameHeader();
|
||||
return frame_length;
|
||||
|
||||
}
|
||||
const size_t frame_length = received_frame_header.length;
|
||||
if (client.available() < (int)frame_length) return 0;
|
||||
if (dest == nullptr || client.readBytes(dest, frame_length) != frame_length) {
|
||||
disconnectClient(true);
|
||||
return 0; // Never dispatch a truncated command, even after a short read.
|
||||
}
|
||||
resetReceivedFrameHeader();
|
||||
return frame_length;
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@@ -36,12 +36,15 @@ class SerialWifiInterface : public BaseSerialInterface {
|
||||
bool queue_has_ip = false;
|
||||
uint32_t held_since = 0;
|
||||
size_t send_offset = 0;
|
||||
uint32_t receive_started = 0;
|
||||
bool receive_pending = false;
|
||||
void (*session_changed)(void*) = nullptr;
|
||||
void* session_context = nullptr;
|
||||
|
||||
void clearBuffers();
|
||||
void expireHeldQueue(uint32_t now);
|
||||
void selectClient(const IPAddress& ip, uint32_t now);
|
||||
void disconnectClient(bool cancel_session);
|
||||
|
||||
protected:
|
||||
|
||||
@@ -57,8 +60,9 @@ public:
|
||||
|
||||
void begin(int port);
|
||||
void end();
|
||||
// Called synchronously while disconnected, before a different IP can send
|
||||
// commands or receive replies. The owner can cancel route-bound operations.
|
||||
// Called synchronously while disconnected, on teardown or before a different
|
||||
// IP can send commands/receive replies. Same-IP live replacement preserves
|
||||
// the existing owner; actual disconnects cancel its pending operations.
|
||||
void setSessionChangedCallback(void (*callback)(void*), void* context) {
|
||||
session_changed = callback;
|
||||
session_context = context;
|
||||
|
||||
@@ -84,28 +84,35 @@ size_t RAK13800EthernetInterface::write(const uint8_t *buf, size_t size) {
|
||||
}
|
||||
|
||||
bool RAK13800EthernetInterface::isConnected() const {
|
||||
return _isConnected;
|
||||
return isEnabled() && _isConnected;
|
||||
}
|
||||
|
||||
void RAK13800EthernetInterface::disconnectClient() {
|
||||
_isConnected = false;
|
||||
client.stop();
|
||||
}
|
||||
|
||||
void RAK13800EthernetInterface::loop() {
|
||||
|
||||
Ethernet.maintain();
|
||||
const bool wasConnected = _isConnected;
|
||||
if (!isEnabled()) return;
|
||||
if (_isConnected && !client.connected()) {
|
||||
_isConnected = false;
|
||||
onClientDisconnected();
|
||||
}
|
||||
|
||||
auto newClient = server.accept();
|
||||
if (newClient) {
|
||||
IPAddress remoteIp = newClient.remoteIP();
|
||||
uint16_t remotePort = newClient.remotePort();
|
||||
ETHERNET_DEBUG_PRINTLN("New client accepted %u.%u.%u.%u:%u", remoteIp[0], remoteIp[1], remoteIp[2], remoteIp[3], remotePort);
|
||||
if (client) {
|
||||
ETHERNET_DEBUG_PRINTLN("Closing previous client");
|
||||
client.stop();
|
||||
}
|
||||
disconnectClient();
|
||||
onClientConnected((uint32_t)remoteIp);
|
||||
// Finish old-owner cancellation before publishing the replacement socket.
|
||||
client = newClient;
|
||||
onClientConnected();
|
||||
}
|
||||
|
||||
_isConnected = client.connected();
|
||||
if (wasConnected && !_isConnected) onClientDisconnected();
|
||||
if (!_isConnected) onClientDisconnected();
|
||||
|
||||
}
|
||||
@@ -10,6 +10,9 @@ class RAK13800EthernetInterface : public SerialEthernetInterface {
|
||||
EthernetServer server;
|
||||
EthernetClient client;
|
||||
|
||||
protected:
|
||||
void disconnectClient() override;
|
||||
|
||||
public:
|
||||
RAK13800EthernetInterface() : server(EthernetServer(ETHERNET_TCP_PORT)) {
|
||||
_isConnected = false;
|
||||
|
||||
@@ -6,6 +6,10 @@
|
||||
#define RECV_STATE_LEN1_FOUND 2
|
||||
#define RECV_STATE_LEN2_FOUND 3
|
||||
|
||||
#if !ETHERNET_RAW_LINE
|
||||
static constexpr uint32_t ETHERNET_FRAME_TIMEOUT_MS = 5000;
|
||||
#endif
|
||||
|
||||
bool SerialEthernetInterface::begin() {
|
||||
return true;
|
||||
}
|
||||
@@ -18,21 +22,32 @@ void SerialEthernetInterface::enable() {
|
||||
|
||||
void SerialEthernetInterface::disable() {
|
||||
_isEnabled = false;
|
||||
disconnectClient();
|
||||
onClientDisconnected();
|
||||
clearBuffers();
|
||||
}
|
||||
|
||||
bool SerialEthernetInterface::isConnected() const {
|
||||
return _isEnabled && session_active;
|
||||
}
|
||||
|
||||
size_t SerialEthernetInterface::writeFrame(const uint8_t src[], size_t len) {
|
||||
if (len > MAX_FRAME_SIZE) {
|
||||
ETHERNET_DEBUG_PRINTLN("writeFrame(), frame too big, len=%d\n", len);
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (isConnected() && len > 0) {
|
||||
if (!mesh::enqueueCompanionFrame(send_queue, send_queue_len, FRAME_QUEUE_SIZE,
|
||||
if (_isEnabled && isConnected() && src != nullptr && len > 0) {
|
||||
// A partly written frame must remain at the head even if a new response
|
||||
// displaces or reorders lower-priority frames in the waiting tail.
|
||||
const int pinned = send_offset != 0 ? 1 : 0;
|
||||
int tail_len = send_queue_len - pinned;
|
||||
if (!mesh::enqueueCompanionFrame(send_queue + pinned, tail_len, FRAME_QUEUE_SIZE - pinned,
|
||||
src, len)) {
|
||||
ETHERNET_DEBUG_PRINTLN("writeFrame(), send_queue is full!");
|
||||
return 0;
|
||||
}
|
||||
send_queue_len = tail_len + pinned;
|
||||
return len;
|
||||
}
|
||||
return 0;
|
||||
@@ -43,37 +58,66 @@ bool SerialEthernetInterface::isWriteBusy() const {
|
||||
}
|
||||
|
||||
bool SerialEthernetInterface::isReadBusy() const {
|
||||
return _state != RECV_STATE_IDLE;
|
||||
return _state != RECV_STATE_IDLE || _rx_len > 0;
|
||||
}
|
||||
|
||||
bool SerialEthernetInterface::hasPendingIO() const {
|
||||
// Ethernet is polled, so an active connection must keep receiving loop
|
||||
// service even when no complete frame is queued yet.
|
||||
return isConnected() || send_queue_len > 0 || _state != RECV_STATE_IDLE;
|
||||
return _isEnabled && isConnected();
|
||||
}
|
||||
|
||||
void SerialEthernetInterface::onClientConnected() {
|
||||
clearBuffers();
|
||||
void SerialEthernetInterface::onClientConnected(uint32_t remote_ip) {
|
||||
const bool different_owner = queue_has_ip && queue_ip != remote_ip;
|
||||
if (different_owner) {
|
||||
// Cancel response producers while the displaced route is unavailable.
|
||||
// Ethernet has only its original four-frame queue: unlike WiFi there is
|
||||
// no spare queue for a different IP's backlog, so discard it on takeover.
|
||||
onClientDisconnected();
|
||||
send_queue_len = 0;
|
||||
}
|
||||
resetInput();
|
||||
send_offset = 0; // Replay a complete frame on a fresh TCP stream.
|
||||
queue_ip = remote_ip;
|
||||
queue_has_ip = true;
|
||||
session_active = true;
|
||||
}
|
||||
|
||||
void SerialEthernetInterface::onClientDisconnected() {
|
||||
clearBuffers();
|
||||
const bool was_active = session_active;
|
||||
session_active = false;
|
||||
resetInput();
|
||||
send_offset = 0;
|
||||
if (was_active && session_changed != nullptr) session_changed(session_context);
|
||||
}
|
||||
|
||||
void SerialEthernetInterface::rejectInput() {
|
||||
disconnectClient();
|
||||
onClientDisconnected();
|
||||
}
|
||||
|
||||
size_t SerialEthernetInterface::checkRecvFrame(uint8_t dest[]) {
|
||||
|
||||
if (!_isEnabled) return 0;
|
||||
if (isConnected()) {
|
||||
#if !ETHERNET_RAW_LINE
|
||||
if (isReadBusy() && (uint32_t)((uint32_t)millis() - _rx_started) >= ETHERNET_FRAME_TIMEOUT_MS) {
|
||||
rejectInput();
|
||||
return 0;
|
||||
}
|
||||
#endif
|
||||
if (send_queue_len > 0) { // first, check send queue
|
||||
|
||||
_last_write = millis();
|
||||
int len = send_queue[0].len;
|
||||
|
||||
uint8_t pkt[MAX_FRAME_SIZE + 3];
|
||||
#if ETHERNET_RAW_LINE
|
||||
ETHERNET_DEBUG_PRINTLN("TX line len=%d", len);
|
||||
write(send_queue[0].buf, len);
|
||||
write((const uint8_t *)"\r\n", 2);
|
||||
memcpy(pkt, send_queue[0].buf, len);
|
||||
pkt[len] = '\r';
|
||||
pkt[len + 1] = '\n';
|
||||
const size_t total = len + 2U;
|
||||
#else
|
||||
uint8_t pkt[3+len]; // use same header as serial interface so client can delimit frames
|
||||
pkt[0] = '>';
|
||||
pkt[1] = (len & 0xFF); // LSB
|
||||
pkt[2] = (len >> 8); // MSB
|
||||
@@ -82,8 +126,13 @@ size_t SerialEthernetInterface::checkRecvFrame(uint8_t dest[]) {
|
||||
#if ETHERNET_DEBUG_LOGGING && ARDUINO
|
||||
ETHERNET_DEBUG_PRINTLN("TX frame len=%d", len);
|
||||
#endif
|
||||
write(pkt, 3 + len);
|
||||
const size_t total = len + 3U;
|
||||
#endif
|
||||
const size_t remaining = total - send_offset;
|
||||
const size_t written = write(pkt + send_offset, remaining);
|
||||
send_offset += written < remaining ? written : remaining;
|
||||
if (send_offset < total) return 0;
|
||||
send_offset = 0;
|
||||
send_queue_len--;
|
||||
for (int i = 0; i < send_queue_len; i++) { // delete top item from queue
|
||||
send_queue[i] = send_queue[i + 1];
|
||||
@@ -99,20 +148,25 @@ size_t SerialEthernetInterface::checkRecvFrame(uint8_t dest[]) {
|
||||
continue;
|
||||
}
|
||||
uint16_t out_len = _rx_len;
|
||||
if (out_len > MAX_FRAME_SIZE) out_len = MAX_FRAME_SIZE;
|
||||
if (dest == nullptr) { rejectInput(); return 0; }
|
||||
memcpy(dest, _rx_buf, out_len);
|
||||
_rx_len = 0;
|
||||
resetInput();
|
||||
return out_len;
|
||||
}
|
||||
if (_rx_len < MAX_FRAME_SIZE) {
|
||||
if (_rx_len == 0) _rx_started = (uint32_t)millis();
|
||||
_rx_buf[_rx_len] = (uint8_t)c;
|
||||
_rx_len++;
|
||||
} else {
|
||||
rejectInput(); // Never execute the prefix of an overlong command.
|
||||
return 0;
|
||||
}
|
||||
#else
|
||||
switch (_state) {
|
||||
case RECV_STATE_IDLE:
|
||||
if (c == '<') {
|
||||
_state = RECV_STATE_HDR_FOUND;
|
||||
_rx_started = (uint32_t)millis();
|
||||
}
|
||||
break;
|
||||
case RECV_STATE_HDR_FOUND:
|
||||
@@ -121,8 +175,12 @@ size_t SerialEthernetInterface::checkRecvFrame(uint8_t dest[]) {
|
||||
break;
|
||||
case RECV_STATE_LEN1_FOUND:
|
||||
_frame_len |= ((uint16_t)c) << 8;
|
||||
if (_frame_len == 0 || _frame_len > MAX_FRAME_SIZE) {
|
||||
rejectInput();
|
||||
return 0;
|
||||
}
|
||||
_rx_len = 0;
|
||||
_state = _frame_len > 0 ? RECV_STATE_LEN2_FOUND : RECV_STATE_IDLE;
|
||||
_state = RECV_STATE_LEN2_FOUND;
|
||||
break;
|
||||
default:
|
||||
if (_rx_len < MAX_FRAME_SIZE) {
|
||||
@@ -130,15 +188,14 @@ size_t SerialEthernetInterface::checkRecvFrame(uint8_t dest[]) {
|
||||
}
|
||||
_rx_len++;
|
||||
if (_rx_len >= _frame_len) {
|
||||
if (_frame_len > MAX_FRAME_SIZE) {
|
||||
_frame_len = MAX_FRAME_SIZE;
|
||||
}
|
||||
#if ETHERNET_DEBUG_LOGGING && ARDUINO
|
||||
ETHERNET_DEBUG_PRINTLN("RX frame len=%d", _frame_len);
|
||||
#endif
|
||||
memcpy(dest, _rx_buf, _frame_len);
|
||||
_state = RECV_STATE_IDLE;
|
||||
return _frame_len;
|
||||
if (dest == nullptr) { rejectInput(); return 0; }
|
||||
const size_t out_len = _frame_len;
|
||||
memcpy(dest, _rx_buf, out_len);
|
||||
resetInput();
|
||||
return out_len;
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
@@ -16,6 +16,13 @@ class SerialEthernetInterface : public BaseSerialInterface {
|
||||
uint16_t _frame_len;
|
||||
uint16_t _rx_len;
|
||||
uint8_t _rx_buf[MAX_FRAME_SIZE];
|
||||
uint32_t _rx_started = 0;
|
||||
size_t send_offset = 0;
|
||||
bool session_active = false;
|
||||
bool queue_has_ip = false;
|
||||
uint32_t queue_ip = 0;
|
||||
void (*session_changed)(void*) = nullptr;
|
||||
void* session_context = nullptr;
|
||||
|
||||
struct Frame {
|
||||
uint8_t len;
|
||||
@@ -28,12 +35,21 @@ class SerialEthernetInterface : public BaseSerialInterface {
|
||||
|
||||
void clearBuffers() {
|
||||
send_queue_len = 0;
|
||||
queue_has_ip = false;
|
||||
resetInput();
|
||||
send_offset = 0;
|
||||
}
|
||||
|
||||
void resetInput() {
|
||||
_state = 0;
|
||||
_frame_len = 0;
|
||||
_rx_len = 0;
|
||||
_rx_started = 0;
|
||||
}
|
||||
void rejectInput();
|
||||
|
||||
protected:
|
||||
virtual void disconnectClient() = 0;
|
||||
|
||||
public:
|
||||
SerialEthernetInterface() {
|
||||
@@ -46,8 +62,14 @@ class SerialEthernetInterface : public BaseSerialInterface {
|
||||
}
|
||||
bool begin();
|
||||
|
||||
void onClientConnected();
|
||||
// Drivers call this while isConnected() is false and BEFORE exposing the
|
||||
// new socket. Same-IP live replacement retains the existing logical owner.
|
||||
void onClientConnected(uint32_t remote_ip);
|
||||
void onClientDisconnected();
|
||||
void setSessionChangedCallback(void (*callback)(void*), void* context) {
|
||||
session_changed = callback;
|
||||
session_context = context;
|
||||
}
|
||||
|
||||
// BaseSerialInterface methods
|
||||
void enable() override;
|
||||
|
||||
@@ -69,11 +69,20 @@ size_t CH390EthernetInterface::write(const uint8_t *buf, size_t size) {
|
||||
}
|
||||
|
||||
bool CH390EthernetInterface::isConnected() const {
|
||||
return _isConnected;
|
||||
return isEnabled() && _isConnected;
|
||||
}
|
||||
|
||||
void CH390EthernetInterface::disconnectClient() {
|
||||
_isConnected = false;
|
||||
client.stop();
|
||||
}
|
||||
|
||||
void CH390EthernetInterface::loop() {
|
||||
const bool wasConnected = _isConnected;
|
||||
if (!isEnabled()) return;
|
||||
if (_isConnected && !client.connected()) {
|
||||
_isConnected = false;
|
||||
onClientDisconnected();
|
||||
}
|
||||
|
||||
if (server.hasClient()) {
|
||||
auto newClient = server.available();
|
||||
@@ -81,16 +90,15 @@ void CH390EthernetInterface::loop() {
|
||||
IPAddress remoteIp = newClient.remoteIP();
|
||||
uint16_t remotePort = newClient.remotePort();
|
||||
ETHERNET_DEBUG_PRINTLN("New client accepted %u.%u.%u.%u:%u", remoteIp[0], remoteIp[1], remoteIp[2], remoteIp[3], remotePort);
|
||||
if (client) {
|
||||
ETHERNET_DEBUG_PRINTLN("Closing previous client");
|
||||
client.stop();
|
||||
}
|
||||
disconnectClient();
|
||||
onClientConnected((uint32_t)remoteIp);
|
||||
// The old owner's producers are cancelled before the new socket can
|
||||
// become visible to the serial manager or receive any queued replies.
|
||||
client = newClient;
|
||||
onClientConnected();
|
||||
}
|
||||
}
|
||||
|
||||
_isConnected = client.connected();
|
||||
if (wasConnected && !_isConnected) onClientDisconnected();
|
||||
if (!_isConnected) onClientDisconnected();
|
||||
|
||||
}
|
||||
@@ -13,6 +13,9 @@ class CH390EthernetInterface : public SerialEthernetInterface {
|
||||
WiFiServer server;
|
||||
WiFiClient client;
|
||||
|
||||
protected:
|
||||
void disconnectClient() override;
|
||||
|
||||
public:
|
||||
CH390EthernetInterface(){
|
||||
_isConnected = false;
|
||||
|
||||
@@ -1607,7 +1607,9 @@ bool OtaManager::resumeStaged(const uint8_t* want_mid) {
|
||||
|| _fstate == WANT_LEAVES || _fstate == VERIFYING_STAGED) {
|
||||
return false;
|
||||
}
|
||||
if (!_fetch->reopen()) return false; // nothing persisted in the store
|
||||
const bool automatic_resume = want_mid == nullptr;
|
||||
const uint32_t expected_target = automatic_resume ? _target : _fexpected_target;
|
||||
if (!_fetch->reopenFor(want_mid, expected_target)) return false;
|
||||
uint32_t total = _fetch->staged_size();
|
||||
uint8_t hdr[8];
|
||||
if (total < 8u + MOTA_MFL + 5u || !_fetch->read(0, hdr, sizeof(hdr))
|
||||
@@ -1617,11 +1619,9 @@ bool OtaManager::resumeStaged(const uint8_t* want_mid) {
|
||||
MotaManifest m;
|
||||
if (!_fetch->read(8, mbuf, sizeof(mbuf)) || !mota_parse_manifest(mbuf, sizeof(mbuf), m)) return false;
|
||||
if (want_mid && memcmp(m.merkle_root, want_mid, 4) != 0) return false; // a different fw is staged
|
||||
const bool automatic_resume = want_mid == nullptr;
|
||||
// A boot-time resume is an automatic fetch decision and therefore belongs
|
||||
// only to this node. An explicit pull retains target=0 as an intentional
|
||||
// MID-only wildcard instead of silently narrowing it to the local target.
|
||||
const uint32_t expected_target = automatic_resume ? _target : _fexpected_target;
|
||||
if (expected_target != 0 && m.target_id != expected_target) return false;
|
||||
if (automatic_resume) {
|
||||
if (_autofetch == AUTOFETCH_OFF) return false;
|
||||
@@ -1670,10 +1670,11 @@ uint32_t OtaManager::blockLen(uint32_t i) const {
|
||||
return (off + _fbs <= _fpsize) ? _fbs : (_fpsize - off);
|
||||
}
|
||||
|
||||
bool OtaManager::blockPresent(uint32_t i) const {
|
||||
bool OtaManager::readBlockPresent(uint32_t i, bool& present) const {
|
||||
uint8_t leaf[4];
|
||||
if (!_fetch->read(_floff + i * 4, leaf, 4)) return false;
|
||||
return !(leaf[0]==0xFF && leaf[1]==0xFF && leaf[2]==0xFF && leaf[3]==0xFF);
|
||||
present = !(leaf[0]==0xFF && leaf[1]==0xFF && leaf[2]==0xFF && leaf[3]==0xFF);
|
||||
return true;
|
||||
}
|
||||
|
||||
bool OtaManager::storedLeavesRootMatches(FetchError& error) const {
|
||||
@@ -1772,7 +1773,12 @@ bool OtaManager::handleData(const uint8_t* m, uint16_t n) {
|
||||
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
|
||||
bool present;
|
||||
if (!readBlockPresent(dm.block_idx, present)) {
|
||||
failFetch(FETCH_ERROR_STORAGE);
|
||||
return true;
|
||||
}
|
||||
if (present) return true; // late duplicate for this terminal
|
||||
int slot_index = findReassemblySlot(dm.block_idx);
|
||||
if (slot_index < 0) return false; // not one of this node's requested blocks
|
||||
ReassemblySlot& slot = _reasm[slot_index];
|
||||
@@ -1890,7 +1896,14 @@ bool OtaManager::handleProof(const uint8_t* m, uint16_t n) {
|
||||
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 blockPresent(pm.block_idx);
|
||||
if (slot_index < 0 || !_reasm[slot_index].awaiting_proof) {
|
||||
bool present;
|
||||
if (!readBlockPresent(pm.block_idx, present)) {
|
||||
failFetch(FETCH_ERROR_STORAGE);
|
||||
return true;
|
||||
}
|
||||
return present;
|
||||
}
|
||||
ReassemblySlot& slot = _reasm[slot_index];
|
||||
uint32_t block = slot.block;
|
||||
uint32_t blen = blockLen(block);
|
||||
@@ -2012,6 +2025,7 @@ bool OtaManager::fillPipeline() {
|
||||
int slot_index = findEmptyReassemblySlot();
|
||||
if (slot_index < 0) break;
|
||||
uint32_t block = pickMissingBlock();
|
||||
if (_fstate != FETCHING) return false; // a leaf read failed; slots were cleared
|
||||
if (block >= _fbc) break;
|
||||
ReassemblySlot& slot = _reasm[slot_index];
|
||||
slot.block = block;
|
||||
@@ -2087,7 +2101,15 @@ void OtaManager::requestMissing() {
|
||||
uint32_t OtaManager::pickMissingBlock() {
|
||||
if (_fbc == 0) return _fbc;
|
||||
for (uint32_t i = 0; i < _fbc; i++) {
|
||||
if (!blockInPipeline(i) && !blockPresent(i)) return i;
|
||||
if (blockInPipeline(i)) continue;
|
||||
bool present;
|
||||
if (!readBlockPresent(i, present)) {
|
||||
// Unknown is not missing: requesting a committed block would retain an
|
||||
// occupied slot after its duplicate DATA is discarded on recovery.
|
||||
failFetch(FETCH_ERROR_STORAGE);
|
||||
return _fbc;
|
||||
}
|
||||
if (!present) return i;
|
||||
}
|
||||
return _fbc;
|
||||
}
|
||||
|
||||
@@ -361,6 +361,8 @@ public:
|
||||
// resume and must match exactly. Re-parses the stored manifest, recomputes geometry, then incrementally
|
||||
// rehashes every staged payload block before continuing FETCHING the holes. A fully staged image also has
|
||||
// to reproduce the manifest Merkle root before it can become COMPLETE. Returns true if it adopted one.
|
||||
// Raw-flash stores require a unique candidate: boot resume cannot guess age
|
||||
// from header address, and explicit resume selects by MID/expected target.
|
||||
bool resumeStaged(const uint8_t* want_mid);
|
||||
|
||||
// Explicit operator/debug re-adoption of one known MID without starting a network fetch. This installs
|
||||
@@ -631,7 +633,7 @@ private:
|
||||
}
|
||||
}
|
||||
void setDigest(uint8_t out[4]) const; // sha2-256:4 over our served mids
|
||||
bool blockPresent(uint32_t i) const;
|
||||
bool readBlockPresent(uint32_t i, bool& present) const;
|
||||
bool storedLeavesRootMatches(FetchError& error) const;
|
||||
void beginStagedVerification();
|
||||
void verifyStagedStep();
|
||||
|
||||
@@ -61,6 +61,15 @@ public:
|
||||
// OtaManager then reads + parses the stored manifest to recompute geometry and resume the fetch.
|
||||
virtual bool reopen() { return false; }
|
||||
|
||||
// Resume a selected image. Single-container stores can use reopen() and let
|
||||
// the manager validate MID/target. Raw stores that may retain several headers
|
||||
// must select before adoption: a physical address is not a creation timestamp.
|
||||
// A null MID means automatic resume; refuse ambiguous candidates instead of
|
||||
// guessing which capture is newest. A zero target is an explicit wildcard.
|
||||
virtual bool reopenFor(const uint8_t* want_mid, uint32_t expected_target) {
|
||||
(void)want_mid; (void)expected_target; return reopen();
|
||||
}
|
||||
|
||||
// External host stores can disappear temporarily while retaining their file.
|
||||
// Preserve the selected fetch on an I/O failure until that link reconnects.
|
||||
virtual bool canReconnect() const { return false; }
|
||||
|
||||
@@ -70,14 +70,14 @@ bool OtaStoreFlashEsp32::begin(uint32_t total_size) {
|
||||
if (!_meta) { _total = 0; return false; }
|
||||
memset(_meta, 0xFF, _meta_flush);
|
||||
memset(_trailer, 0xFF, sizeof(_trailer));
|
||||
_pay_open = false; _pay_sec = 0; _pay_max_sec = 0; _flushed = false;
|
||||
_pay_open = false; _pay_sec = 0; _pay_seen_end = 0; _flushed = false;
|
||||
_io_ok = true;
|
||||
return true;
|
||||
}
|
||||
|
||||
void OtaStoreFlashEsp32::clear() {
|
||||
free(_meta); _meta = nullptr;
|
||||
_total = 0; _pay_open = false; _flushed = false; // _part kept (re-acquire is fine)
|
||||
_total = 0; _pay_open = false; _pay_seen_end = 0; _flushed = false; // _part kept (re-acquire is fine)
|
||||
}
|
||||
|
||||
OtaStoreFlashEsp32::CandidateProbe OtaStoreFlashEsp32::probe_candidate(
|
||||
@@ -137,6 +137,8 @@ OtaStoreFlashEsp32::CandidateProbe OtaStoreFlashEsp32::probe_candidate(
|
||||
candidate.image_size = manifest.image_size;
|
||||
candidate.meta_bytes = (uint32_t)payload_off64;
|
||||
candidate.pay_size = manifest.payload_size;
|
||||
memcpy(candidate.mid, manifest.merkle_root, sizeof(candidate.mid));
|
||||
candidate.target = manifest.target_id;
|
||||
return CandidateProbe::VALID;
|
||||
}
|
||||
|
||||
@@ -237,19 +239,24 @@ void OtaStoreFlashEsp32::flush_pay() {
|
||||
|
||||
void OtaStoreFlashEsp32::open_pay(uint32_t sec) {
|
||||
if (_pay_open) flush_pay();
|
||||
if (sec < _pay_max_sec) {
|
||||
// revisiting an already-flushed sector (out-of-order block) -> read it back so the gaps we don't
|
||||
// touch are preserved (they were programmed as 0xFF or earlier block data); we erase+reprogram on flush.
|
||||
if (sec < _pay_seen_end) {
|
||||
// Any sector up to and INCLUDING the highest opened sector may contain
|
||||
// acknowledged blocks. Preserve it even after visiting a lower sector
|
||||
// (e.g. full-image blocks 4,3,5 visit sectors 1,0,1). An exclusive bound
|
||||
// also distinguishes a genuinely fresh sector 0 from a revisit to it.
|
||||
// Some gaps below the bound may be unvisited, but their leaves are absent;
|
||||
// conservatively keeping those bytes cannot erase a committed block.
|
||||
if (esp_partition_read(_part, (size_t)sec * SEC, _pay, SEC) != ESP_OK) _io_ok = false;
|
||||
} else {
|
||||
memset(_pay, 0xFF, SEC); // fresh sector
|
||||
_pay_max_sec = sec;
|
||||
_pay_seen_end = sec + 1u;
|
||||
}
|
||||
_pay_sec = sec; _pay_open = true;
|
||||
}
|
||||
|
||||
bool OtaStoreFlashEsp32::write(uint32_t offset, const uint8_t* d, uint32_t len) {
|
||||
if ((uint64_t)offset + len > _total || !_io_ok) return false;
|
||||
if (len != 0) _flushed = false; // a later finalize/checkpoint must persist continued writes
|
||||
for (uint32_t pos = offset, end = offset + len; pos < end; ) {
|
||||
uint32_t n = run(pos, end - pos);
|
||||
if (uint8_t* dst = meta_slot(pos)) { // meta / leaves / trailer -> pinned RAM
|
||||
@@ -327,39 +334,59 @@ void OtaStoreFlashEsp32::checkpoint() {
|
||||
// (MOTA_MAGIC + total) sits at a sector boundary (meta_part for full, write_start for delta - both
|
||||
// sector-aligned), so scan sector starts from the bottom up. A candidate is accepted only if: magic +
|
||||
// plausible total, the manifest parses, the container geometry is self-consistent with the total, AND the
|
||||
// recomputed placement lands the meta exactly where we found the magic. Any miss -> false (fetch fresh),
|
||||
// so a stray/stale match can only cost a restart, never a corrupt adopt.
|
||||
// recomputed placement lands the meta exactly where we found the magic. Scan all candidates before
|
||||
// adoption: a smaller, older container can have a higher address than a newer checkpoint.
|
||||
bool OtaStoreFlashEsp32::reopen() {
|
||||
return reopenFor(nullptr, 0);
|
||||
}
|
||||
|
||||
bool OtaStoreFlashEsp32::reopenFor(const uint8_t* want_mid, uint32_t expected_target) {
|
||||
if (!acquire() || _psize < SEC) return false;
|
||||
bool found = false;
|
||||
StagedCandidate selected;
|
||||
// The meta/container is staged at the bottom of the slot. Large delta containers can begin well above
|
||||
// the final 512 KB, so scan the complete partition rather than silently losing resumability after reboot.
|
||||
for (uint32_t o = mota_esp32_align_down(_psize - SEC, SEC); ; o -= SEC) {
|
||||
StagedCandidate candidate;
|
||||
if (probe_candidate(o, candidate) == CandidateProbe::VALID) {
|
||||
_full = candidate.full;
|
||||
_image_size = candidate.image_size;
|
||||
_meta_bytes = candidate.meta_bytes;
|
||||
_pay_size = candidate.pay_size;
|
||||
set_layout(candidate.layout);
|
||||
free(_meta); _meta = (uint8_t*)malloc(_meta_flush);
|
||||
if (!_meta) { _total = 0; return false; }
|
||||
if (esp_partition_read(_part, _meta_part, _meta, _meta_flush) != ESP_OK) {
|
||||
free(_meta); _meta = nullptr; _total = 0; return false;
|
||||
const CandidateProbe probe = probe_candidate(o, candidate);
|
||||
if (probe == CandidateProbe::IO_ERROR) return false;
|
||||
if (probe == CandidateProbe::VALID) {
|
||||
// No generation marker exists. Unqualified boot resume must not infer
|
||||
// recency from scan order, target, version, or apparent block progress.
|
||||
const bool matches = !want_mid ||
|
||||
(memcmp(candidate.mid, want_mid, sizeof(candidate.mid)) == 0 &&
|
||||
(expected_target == 0 || candidate.target == expected_target));
|
||||
if (matches) {
|
||||
if (found) return false;
|
||||
selected = candidate;
|
||||
found = true;
|
||||
}
|
||||
// Raw staging defers the fixed trailer; an unvisited sector may still
|
||||
// contain old firmware bytes after an early checkpoint. Restore framing
|
||||
// from the validated layout, not that stale tail. The manager separately
|
||||
// revalidates the selected image and every present payload block.
|
||||
memcpy(_trailer, MOTA_TRAILER, sizeof(_trailer));
|
||||
if (_full) memcpy(_meta + _meta_bytes, MOTA_TRAILER, sizeof(_trailer));
|
||||
_pay_open = false; _pay_sec = 0; _flushed = false; _io_ok = true;
|
||||
_pay_max_sec = (_pay_part0 + _pay_size + SEC) / SEC; // treat all payload sectors as seen -> RMW preserves committed blocks
|
||||
OTA_DBG("OTA esp32: reopen %s total=%u meta_part=%u\n", _full ? "FULL" : "DELTA", (unsigned)_total, (unsigned)o);
|
||||
return true;
|
||||
}
|
||||
if (o == 0) break;
|
||||
}
|
||||
return false;
|
||||
if (!found || (expected_target != 0 && selected.target != expected_target)) return false;
|
||||
_full = selected.full;
|
||||
_image_size = selected.image_size;
|
||||
_meta_bytes = selected.meta_bytes;
|
||||
_pay_size = selected.pay_size;
|
||||
set_layout(selected.layout);
|
||||
free(_meta); _meta = (uint8_t*)malloc(_meta_flush);
|
||||
if (!_meta) { _total = 0; return false; }
|
||||
if (esp_partition_read(_part, _meta_part, _meta, _meta_flush) != ESP_OK) {
|
||||
free(_meta); _meta = nullptr; _total = 0; return false;
|
||||
}
|
||||
// Raw staging defers the fixed trailer; an unvisited sector may still
|
||||
// contain old firmware bytes after an early checkpoint. Restore framing
|
||||
// from the validated layout, not that stale tail. The manager separately
|
||||
// revalidates the selected image and every present payload block.
|
||||
memcpy(_trailer, MOTA_TRAILER, sizeof(_trailer));
|
||||
if (_full) memcpy(_meta + _meta_bytes, MOTA_TRAILER, sizeof(_trailer));
|
||||
_pay_open = false; _pay_sec = 0; _flushed = false; _io_ok = true;
|
||||
// No volatile visit history survives reboot. Treat the entire partition
|
||||
// as potentially written so every resumed sector preserves committed data.
|
||||
_pay_seen_end = _psize / SEC;
|
||||
OTA_DBG("OTA esp32: reopen %s total=%u meta_part=%u\n", _full ? "FULL" : "DELTA", (unsigned)_total, (unsigned)_meta_part);
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace ota
|
||||
|
||||
@@ -25,7 +25,7 @@
|
||||
//
|
||||
// RX-safety: an ESP32 flash erase+write disables the XIP instruction cache and stalls code running from
|
||||
// flash (the dispatcher loop), exactly like the nRF52 page erase that starved the LoRa RX. So writes are
|
||||
// COALESCED to the 4 KB sector and each sector is programmed once. The meta region (header+manifest+
|
||||
// COALESCED to the 4 KB sector (revisited sectors are read-modify-written). The meta region (header+manifest+
|
||||
// leaves -- written all transfer long as blocks/leaves arrive, often out of order) is PINNED in RAM and
|
||||
// flushed at finalize() with the radio idle; the bulk payload streams through ONE sliding sector buffer,
|
||||
// flushing the sector it leaves behind (~1 flush per 4 KB, off the per-packet path). A brief stall still
|
||||
@@ -49,6 +49,8 @@ class OtaStoreFlashEsp32 : public OtaStore {
|
||||
uint32_t image_size = 0;
|
||||
uint32_t meta_bytes = 0;
|
||||
uint32_t pay_size = 0;
|
||||
uint8_t mid[4] = {};
|
||||
uint32_t target = 0;
|
||||
};
|
||||
|
||||
const esp_partition_t* _part = nullptr; // inactive OTA slot (acquired in plan_layout/begin)
|
||||
@@ -73,10 +75,10 @@ class OtaStoreFlashEsp32 : public OtaStore {
|
||||
// RX-safe staging buffers
|
||||
uint8_t* _meta = nullptr; // heap, sized per fetch: header+manifest+leaves(+full trailer)
|
||||
alignas(4) uint8_t _pay[SEC]; // one sliding payload sector (slot-sector aligned)
|
||||
uint32_t _pay_sec = 0; // slot sector index currently in _pay (0 = none open)
|
||||
uint32_t _pay_sec = 0; // slot sector index currently in _pay (valid if _pay_open)
|
||||
uint8_t _trailer[5];
|
||||
uint32_t _meta_flush = 0; // whole-sector byte count to program for the meta buffer
|
||||
uint32_t _pay_max_sec = 0; // highest payload slot-sector opened (out-of-order detection)
|
||||
uint32_t _pay_seen_end = 0; // exclusive highest opened sector; 0 = none seen this fetch
|
||||
bool _pay_open = false; // a sliding sector is currently buffered in _pay
|
||||
bool _flushed = false;
|
||||
bool _io_ok = true; // cleared if any flash erase/write/read fails
|
||||
@@ -113,6 +115,7 @@ public:
|
||||
bool finalize() override;
|
||||
void checkpoint() override; // persist meta(leaves) + open payload sector so a reboot can resume
|
||||
bool reopen() override; // re-attach to a container already staged in the slot (scan + rebuild geometry)
|
||||
bool reopenFor(const uint8_t* want_mid, uint32_t expected_target) override;
|
||||
|
||||
// No contiguous RAM/mmap view: the staged container lives in the slot (split for FULL). The ESP32
|
||||
// apply path reads what it needs via read()/esp_partition_read instead of a data() pointer, so this
|
||||
|
||||
@@ -562,10 +562,13 @@ void OtaStoreFlashNrf52::checkpoint() {
|
||||
|
||||
// Re-attach to a container already staged in flash (after a reboot), without erasing. The container is
|
||||
// bottom-aligned (begin: start = (ceiling - total) & ~(PG-1)) and flash is memory-mapped, so scan page
|
||||
// starts from just below that ceiling down to the app end for MOTA_MAGIC with a self-consistent total; adopt
|
||||
// the first match (highest address = most recent for the common single-container case). The manager then
|
||||
// parses the loaded manifest and validates geometry/root, so a stale leftover is rejected there.
|
||||
// starts from just below that ceiling down to the app end for MOTA_MAGIC with a self-consistent total.
|
||||
// Address ordering does not establish age: an old small container can mask a newer larger checkpoint.
|
||||
bool OtaStoreFlashNrf52::reopen() {
|
||||
return reopenFor(nullptr, 0);
|
||||
}
|
||||
|
||||
bool OtaStoreFlashNrf52::reopenFor(const uint8_t* want_mid, uint32_t expected_target) {
|
||||
// A retained-SRAM suffix cannot survive a power cycle or app restart as a
|
||||
// resumable store. Reset all in-memory split state and adopt only a complete
|
||||
// flash span whose advertised total fits before the selected ceiling.
|
||||
@@ -574,6 +577,10 @@ bool OtaStoreFlashNrf52::reopen() {
|
||||
const uint32_t stage_ceiling = ota_nrf52_effective_stage_ceiling();
|
||||
uint32_t app_end;
|
||||
if (!protected_app_end(app_base, stage_ceiling, app_end)) return false;
|
||||
uint32_t selected_start = 0;
|
||||
uint32_t selected_total = 0;
|
||||
uint32_t selected_target = 0;
|
||||
bool selected_bootloader = false;
|
||||
for (uint32_t start = align_down(stage_ceiling - PG, PG); start >= app_end; start -= PG) {
|
||||
const uint8_t* p = (const uint8_t*)(uintptr_t)start;
|
||||
if (memcmp(p, MOTA_MAGIC, 4) != 0) continue;
|
||||
@@ -583,8 +590,10 @@ bool OtaStoreFlashNrf52::reopen() {
|
||||
continue;
|
||||
uint32_t want; // must be valid + placed exactly where begin() would have staged it (same bounds fn)
|
||||
MotaManifest manifest;
|
||||
const bool manifest_ok = mota_parse_manifest(p + 8u, MOTA_MFL, manifest);
|
||||
const bool bootloader = manifest_ok && manifest.is_bootloader();
|
||||
if (!mota_parse_manifest(p + 8u, MOTA_MFL, manifest)) continue;
|
||||
const uint64_t payload_off = 8u + (uint64_t)MOTA_MFL + (uint64_t)manifest.block_count * 4u;
|
||||
if (payload_off > PG || payload_off + manifest.payload_size + 5u != total) continue;
|
||||
const bool bootloader = manifest.is_bootloader();
|
||||
if (bootloader) {
|
||||
#if defined(OTA_INTERNAL_BOOTLOADER_UPDATE)
|
||||
SelfFwInfo fi;
|
||||
@@ -600,29 +609,39 @@ bool OtaStoreFlashNrf52::reopen() {
|
||||
total, app_base, app_end, stage_ceiling, want) || want != start) {
|
||||
continue;
|
||||
}
|
||||
_write_start = start;
|
||||
_stage_ceiling = stage_ceiling;
|
||||
_flash_len = stage_ceiling - start;
|
||||
_ram_len = 0;
|
||||
_total = total;
|
||||
_hybrid = false;
|
||||
_preserve_payload_pages = true;
|
||||
memcpy(_meta_page, p, PG); // load page 0 (header+manifest+leaves) into RAM to continue
|
||||
// The tail is deferred until finalize and can still hold old flash bytes.
|
||||
// Reconstruct only fixed framing; the manager must verify the manifest and
|
||||
// rehash every present payload block before the container becomes complete.
|
||||
memcpy(_trailer, MOTA_TRAILER, sizeof(_trailer));
|
||||
_pay_idx = 0;
|
||||
_flushed = false;
|
||||
_io_ok = true;
|
||||
_planned_bootloader = bootloader;
|
||||
_planned_total = bootloader ? total : 0u;
|
||||
_planned_start = bootloader ? start : 0u;
|
||||
OTA_DBG("OTA flash: reopen total=%u start=%08x ceiling=%08x\n",
|
||||
(unsigned)total, (unsigned)start, (unsigned)stage_ceiling);
|
||||
return true;
|
||||
if (want_mid && (memcmp(manifest.merkle_root, want_mid, 4) != 0 ||
|
||||
(expected_target != 0 && manifest.target_id != expected_target))) continue;
|
||||
// Without an explicit MID, every valid candidate participates in ambiguity
|
||||
// detection; neither target nor firmware version proves which was newest.
|
||||
if (selected_start != 0) return false;
|
||||
selected_start = start;
|
||||
selected_total = total;
|
||||
selected_target = manifest.target_id;
|
||||
selected_bootloader = bootloader;
|
||||
}
|
||||
return false;
|
||||
if (selected_start == 0 ||
|
||||
(expected_target != 0 && selected_target != expected_target)) return false;
|
||||
_write_start = selected_start;
|
||||
_stage_ceiling = stage_ceiling;
|
||||
_flash_len = stage_ceiling - selected_start;
|
||||
_ram_len = 0;
|
||||
_total = selected_total;
|
||||
_hybrid = false;
|
||||
_preserve_payload_pages = true;
|
||||
memcpy(_meta_page, (const uint8_t*)(uintptr_t)selected_start, PG);
|
||||
// The tail is deferred until finalize and can still hold old flash bytes.
|
||||
// Reconstruct only fixed framing; the manager must verify the manifest and
|
||||
// rehash every present payload block before the container becomes complete.
|
||||
memcpy(_trailer, MOTA_TRAILER, sizeof(_trailer));
|
||||
_pay_idx = 0;
|
||||
_flushed = false;
|
||||
_io_ok = true;
|
||||
_planned_bootloader = selected_bootloader;
|
||||
_planned_total = selected_bootloader ? selected_total : 0u;
|
||||
_planned_start = selected_bootloader ? selected_start : 0u;
|
||||
OTA_DBG("OTA flash: reopen total=%u start=%08x ceiling=%08x\n",
|
||||
(unsigned)_total, (unsigned)_write_start, (unsigned)stage_ceiling);
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace ota
|
||||
|
||||
@@ -87,6 +87,7 @@ public:
|
||||
bool finalize() override;
|
||||
void checkpoint() override; // persist page 0 (leaves) + the open payload page so a reboot can resume
|
||||
bool reopen() override; // re-attach to a container already staged in flash (scan for it)
|
||||
bool reopenFor(const uint8_t* want_mid, uint32_t expected_target) override;
|
||||
|
||||
// Mark a verified application package approved. For a hybrid package this
|
||||
// also prepares (but does not yet publish) the reset-retained authorization;
|
||||
|
||||
@@ -341,6 +341,15 @@ mesh::RadioParamApplyResult RadioLibWrapper::prepareTransmitProfile(uint8_t prof
|
||||
return tuneProfile(profile);
|
||||
}
|
||||
|
||||
mesh::RadioParamApplyResult RadioLibWrapper::tryRestoreCodingRate(uint8_t cr) {
|
||||
const uint8_t resume_rx = beginReconfigure();
|
||||
if (resume_rx > 1) return mesh::RadioParamApplyResult::BUSY;
|
||||
const bool applied = setCodingRate(cr);
|
||||
if (!applied) _profile_refresh_required = true;
|
||||
endReconfigure(resume_rx);
|
||||
return applied ? mesh::RadioParamApplyResult::APPLIED : mesh::RadioParamApplyResult::FAILED;
|
||||
}
|
||||
|
||||
void RadioLibWrapper::serviceProfileScan() {
|
||||
if (_cw_active) return;
|
||||
if (!_params_valid || (_profile_retry_at && (int32_t)(millis() - _profile_retry_at) < 0)) return;
|
||||
|
||||
@@ -211,6 +211,7 @@ public:
|
||||
uint32_t receiveProfileGeneration() const override { return _profile_generation; }
|
||||
mesh::RadioParamApplyResult prepareTransmitProfile(uint8_t profile) override;
|
||||
mesh::RadioParamApplyResult prepareTransmitProfile(uint8_t profile, bool reply_rx_override) override;
|
||||
mesh::RadioParamApplyResult tryRestoreCodingRate(uint8_t cr) override;
|
||||
mesh::RadioParamApplyResult trySetPrimaryParams(const mesh::RadioProfileParams& params,
|
||||
bool temporary, const uint32_t* timings = nullptr) override;
|
||||
uint16_t profilePreamble(uint8_t profile) const override {
|
||||
|
||||
Reference in new issue
Block a user