Unify Tower repeater builds on SD-primary OTA storage

Keep the deployed SD target and layout, select qualified internal delta storage when no card is usable, and retain exact SD bootloader-update gates. Add storage, capability, transfer, recipe, and release-selection regression coverage.

Also preserve mandatory runtime packet logging in canonical XIAO images when verbose build debugging is disabled, fixing the four stopped release-matrix qualification failures.
This commit is contained in:
mikecarper committed 2026-10-05 16:38:30 -07:00
1 parent 7d3ee7200f
commit 30fe0d617b
25 files changed
+2082 -93

No files matched your search

+8
View File
@@ -497,6 +497,11 @@ void __attribute__((noinline)) Mesh::serviceLoopMaintenance() {
_next_ota_tick = futureMillis(ota_loop_interval);
}
if (millisHasNowPassed(_next_ota_tick)) {
#if defined(NRF52_PLATFORM) && defined(OTA_TOWER_AUTO_STORE)
// Establish storage policy before resume and codec selection. Startup
// deliberately performs no SD mount so the USB console is ready first.
ota::ota_ctx().prepareTowerStorage();
#endif
// one-shot on first tick: resume an interrupted fetch left staged in flash before a reboot. Only adopt
// a PARTIAL container (continue fetching the holes); a COMPLETE one is left for manual/auto-install,
// not re-adopted at boot. requestMissing() (inside resumeStaged) drives the rest via REQ/DATA.
@@ -518,6 +523,9 @@ void __attribute__((noinline)) Mesh::serviceLoopMaintenance() {
}
if (_ota_announce_timer.ready(_ms->getMillis())) { // auto-advertise so peers discover us (tiny beacon)
ota::OtaContext& oc = ota::ota_ctx();
#if defined(NRF52_PLATFORM) && defined(OTA_TOWER_AUTO_STORE)
oc.prepareTowerStorage();
#endif
bool in_burst = _ota_announce_count < OTA_ANNOUNCE_BURST;
uint32_t mins = oc.manager.advert_mins(); // periodic cadence in minutes; 0 = disabled (boot burst only)
if (in_burst || mins != 0) {
+19 -8
View File
@@ -3294,6 +3294,17 @@ bool CommonCLI::handleSdCardSetCmd(const char* config, char* reply) {
strcpy(reply, "Error: OTA apply is pending");
return true;
}
#if defined(OTA_TOWER_AUTO_STORE)
// Card maintenance must never abandon a fallback update stored internally.
if (context.fetch_store.usesInternal() &&
(context.manager.fetchState() != mesh::ota::OtaManager::IDLE ||
context.fetch_store.staged_size() != 0)) {
strcpy(reply, "Error: internal OTA slot is occupied; use ota cancel first");
return true;
}
#endif
mesh::ota::OtaStoreSdNrf52& card = context.sdStagingStore();
// A card-wide destructive operation invalidates any staged fetch. First let
// an archive capture checkpoint and close its shared card handles.
@@ -3305,9 +3316,9 @@ bool CommonCLI::handleSdCardSetCmd(const char* config, char* reply) {
context.prev_fstate = mesh::ota::OtaManager::IDLE;
if (is_format) {
if (!context.fetch_store.formatCard(*_board)) {
if (!card.formatCard(*_board)) {
char error[80];
strncpy(error, context.fetch_store.last_error(), sizeof(error) - 1);
strncpy(error, card.last_error(), sizeof(error) - 1);
error[sizeof(error) - 1] = 0;
context.finishSdCardReset(millis());
snprintf(reply, 160, "Error: SD card format failed: %s",
@@ -3321,9 +3332,9 @@ bool CommonCLI::handleSdCardSetCmd(const char* config, char* reply) {
return true;
}
if (!context.fetch_store.eraseCard(*_board)) {
if (!card.eraseCard(*_board)) {
char error[80];
strncpy(error, context.fetch_store.last_error(), sizeof(error) - 1);
strncpy(error, card.last_error(), sizeof(error) - 1);
error[sizeof(error) - 1] = 0;
context.finishSdCardReset(millis());
snprintf(reply, 160, "Error: SD card erase failed: %s",
@@ -3333,9 +3344,9 @@ bool CommonCLI::handleSdCardSetCmd(const char* config, char* reply) {
_sdcard_erase_recorded = true;
_sdcard_erase_at = millis();
if (!context.fetch_store.formatCard(*_board)) {
if (!card.formatCard(*_board)) {
char error[80];
strncpy(error, context.fetch_store.last_error(), sizeof(error) - 1);
strncpy(error, card.last_error(), sizeof(error) - 1);
error[sizeof(error) - 1] = 0;
context.finishSdCardReset(millis());
snprintf(reply, 160, "Error: SD card erased but format failed: %s",
@@ -3378,7 +3389,7 @@ bool CommonCLI::handleSdCardGetCmd(const char* config, char* reply) {
} else if (strcmp(query, "free") == 0) {
uint64_t used_bytes = 0;
uint64_t free_bytes = 0;
mesh::ota::OtaStoreSdNrf52& store = mesh::ota::ota_ctx().fetch_store;
mesh::ota::OtaStoreSdNrf52& store = mesh::ota::ota_ctx().sdStagingStore();
if (!store.getSpace(*_board, used_bytes, free_bytes)) {
snprintf(reply, 160, "Error: SD card space query failed: %s",
store.last_error());
@@ -3407,7 +3418,7 @@ bool CommonCLI::handleSdCardGetCmd(const char* config, char* reply) {
}
page = parsed;
}
mesh::ota::OtaStoreSdNrf52& store = mesh::ota::ota_ctx().fetch_store;
mesh::ota::OtaStoreSdNrf52& store = mesh::ota::ota_ctx().sdStagingStore();
if (!store.listFiles(*_board, (uint16_t)page, reply, 160)) {
snprintf(reply, 160, "Error: SD card list failed: %s", store.last_error());
}
+1 -1
View File
@@ -106,7 +106,7 @@ void formatStorageLayout(MainBoard& board, char* reply, size_t reply_size) {
#elif defined(ENABLE_OTA) && defined(OTA_SD_STORE)
uint64_t used_bytes = 0;
uint64_t free_bytes = 0;
mesh::ota::OtaStoreSdNrf52& store = mesh::ota::ota_ctx().fetch_store;
mesh::ota::OtaStoreSdNrf52& store = mesh::ota::ota_ctx().sdStagingStore();
if (store.getSpace(board, used_bytes, free_bytes)) {
char total[24];
char used[24];
+23 -2
View File
@@ -497,7 +497,7 @@ static bool ota_nrf52_clear_reset_reasons() {
void ota_reboot_to_apply() { // public: set the apply magic + reset (does not return)
uint8_t stage_handoff = GPREGRET2_OTA_STAGE_LEGACY;
#if defined(OTA_RAK_AUTO_STORE)
#if defined(OTA_RAK_AUTO_STORE) || defined(OTA_TOWER_AUTO_STORE)
if (g_nrf52_apply_store) {
if (g_nrf52_apply_store->is_hybrid()) {
if (!ota_nrf52_clear_reset_reasons() ||
@@ -511,7 +511,11 @@ void ota_reboot_to_apply() { // public: set the apply magic +
stage_handoff = mota_nrf52_flash_stage_handoff(ota_nrf52_effective_stage_ceiling());
}
} else {
#if defined(OTA_TOWER_AUTO_STORE)
stage_handoff = GPREGRET2_OTA_STAGE_SD;
#else
stage_handoff = g_nrf52_qspi_handoff;
#endif
}
#elif defined(OTA_SD_STORE)
stage_handoff = GPREGRET2_OTA_STAGE_SD;
@@ -1114,10 +1118,21 @@ static bool ota_prepare_bootloader_update_external(Store& store,
OtaBootloaderCapsMarker candidate_caps;
if (!ota_bootloader_external_image_metadata(
store, payload_off, ota_bootloader_update_storage_flags(),
candidate, candidate_caps) ||
candidate, candidate_caps,
#if defined(OTA_TOWER_AUTO_STORE)
current_caps.optional_app_storage
#else
0
#endif
) ||
!ota_bootloader_identity_matches(installed, candidate)) {
strcpy(msg, "candidate bootloader identity/capability/CRC mismatch"); return false;
}
#if defined(OTA_TOWER_AUTO_STORE)
if (current_caps.optional_app_storage && ota_boot_rd32(vectors) > MOTA_NRF52_HYBRID_RAM_START) {
strcpy(msg, "candidate must retain the combined bootloader RAM arena"); return false;
}
#endif
const OtaBootloaderContinuityGate continuity = ota_bootloader_continuity_gate(
installed, candidate, m.fw_version, OTA_BOOT_CONTINUITY_FAMILY_S140,
ota_runtime_softdevice_fwid(), mota_nrf52_app_base(),
@@ -1140,6 +1155,9 @@ static bool ota_prepare_bootloader_update_external(Store& store,
#if defined(OTA_SD_STORE)
bool ota_apply_mota_nrf52(OtaStoreSdNrf52& store, const SignerAllowlist& allow,
ApplyState& st, char* msg) {
#if defined(OTA_TOWER_AUTO_STORE)
g_nrf52_apply_store = nullptr;
#endif
#if defined(OTA_SD_BOOTLOADER_UPDATE)
OtaBootloaderIdentity installed;
if (!ota_installed_bootloader_identity(installed) ||
@@ -1163,6 +1181,9 @@ bool ota_prepare_bootloader_update_nrf52(OtaStoreSdNrf52& store,
const uint8_t operator_mid[4],
const uint8_t operator_hash8[8],
ApplyState& st, char* msg) {
#if defined(OTA_TOWER_AUTO_STORE)
g_nrf52_apply_store = nullptr;
#endif
if (!ota_bootloader_sd_retained_auth_ready(
installed, OTA_BOOT_CONTINUITY_FAMILY_S140,
ota_runtime_softdevice_fwid(), mota_nrf52_app_base(),
+41 -12
View File
@@ -28,7 +28,7 @@ struct OtaBlCaps {
uint16_t apply_abi = 0; // max .mota format_ver the bootloader can apply
uint16_t codec_mask = 0; // bit i set => can apply codec_id i (in-place delta = bit 2)
uint8_t storage_flags = 0; // OTA_BL_STORAGE_* capability bits
uint8_t optional_app_storage = 0; // separate MOTASTOR record, never a boot-update backend
uint8_t optional_app_storage = 0; // separate MOTASTOR record, scoped to its qualified primary profile
};
// Independent marker for the reset-retained hybrid source. Keep this separate
@@ -217,10 +217,10 @@ inline OtaBlCaps ota_bl_legacy_app_caps_scan_halfword(const uint8_t* bytes,
return c;
}
// Unified RAK loaders preserve the deployed board's privileged MOTABLDR=0x0A
// contract. A separate record advertises optional APPLICATION storage. It is
// adjacent to the unchanged, unique 64 KiB RAM marker and grants no new
// bootloader staging backend.
// Unified loaders preserve the deployed primary MOTABLDR contract: 0x0A for
// RAK internal storage and 0x09 for Tower SD. A separate record advertises
// optional application storage, adjacent to the unchanged, unique RAM marker.
// Never infer optional storage from the primary profile alone.
inline uint8_t ota_bl_optional_app_storage(const uint8_t* bytes, size_t len) {
static const uint8_t record[32] = {
'M', 'O', 'T', 'A', 'R', 'A', 'M', 'A', 1, 0, 72, 0, 0, 0, 1, 0,
@@ -228,17 +228,39 @@ inline uint8_t ota_bl_optional_app_storage(const uint8_t* bytes, size_t len) {
};
if (!bytes || !ota_bootloader_supports_hybrid(ota_ram_caps_scan_aligned(bytes, len))) return 0;
unsigned matches = 0;
for (size_t off = 0; off + sizeof(record) <= len; off += 4) {
if (memcmp(bytes + off, record, sizeof(record)) == 0 && ++matches > 1) return 0;
uint8_t result = 0;
for (size_t off = 0; off + 8u <= len; off += 4u) {
if (memcmp(bytes + off, record + 16u, 8u) != 0) continue;
// One aligned STOR record must immediately follow the one valid RAM
// record. A stray, malformed, truncated or duplicate declaration fails
// closed instead of allowing another valid record to hide it.
if (++matches != 1u || off < 16u || off + 16u > len ||
memcmp(bytes + off - 16u, record, 28u) != 0 ||
bytes[off + 13u] || bytes[off + 14u] || bytes[off + 15u]) return 0;
const uint8_t flags = bytes[off + 12u];
if (flags != (OTA_BL_STORAGE_QSPI | OTA_BL_STORAGE_HEADER_W25) &&
flags != OTA_BL_STORAGE_STAGE_CEILING) return 0;
result = flags;
}
return matches == 1 ? OTA_BL_STORAGE_QSPI | OTA_BL_STORAGE_HEADER_W25 : 0;
return matches == 1u ? result : 0;
}
inline uint8_t ota_bl_profile_optional_app_storage(const uint8_t* bytes,
size_t len,
uint8_t primary_storage) {
const uint8_t optional = ota_bl_optional_app_storage(bytes, len);
if (primary_storage == OTA_BL_PROFILE_INTERNAL_BOOT_UPDATE &&
optional == (OTA_BL_STORAGE_QSPI | OTA_BL_STORAGE_HEADER_W25)) return optional;
if (primary_storage == OTA_BL_PROFILE_SD_BOOT_UPDATE &&
optional == OTA_BL_STORAGE_STAGE_CEILING) return optional;
return 0;
}
inline OtaBlCaps ota_bl_app_caps_scan(const uint8_t* bytes, size_t len) {
OtaBlCaps aligned = ota_bl_caps_scan_aligned(bytes, len, false);
if (aligned.present && aligned.apply_abi >= 3 &&
aligned.storage_flags == OTA_BL_PROFILE_INTERNAL_BOOT_UPDATE) {
aligned.optional_app_storage = ota_bl_optional_app_storage(bytes, len);
if (aligned.present && aligned.apply_abi >= 3) {
aligned.optional_app_storage = ota_bl_profile_optional_app_storage(
bytes, len, aligned.storage_flags);
aligned.storage_flags |= aligned.optional_app_storage;
}
if (aligned.present) return aligned;
@@ -248,7 +270,14 @@ inline OtaBlCaps ota_bl_app_caps_scan(const uint8_t* bytes, size_t len) {
inline OtaBlCaps ota_bl_update_caps_scan_aligned(const uint8_t* bytes, size_t len,
uint8_t exact_storage_flags) {
if (exact_storage_flags == 0) return OtaBlCaps();
return ota_bl_caps_scan_aligned(bytes, len, true, exact_storage_flags);
OtaBlCaps caps = ota_bl_caps_scan_aligned(bytes, len, true, exact_storage_flags);
if (caps.present) {
// Preserve the exact privileged storage byte; callers may independently
// require an existing optional application capability in a successor.
caps.optional_app_storage = ota_bl_profile_optional_app_storage(
bytes, len, caps.storage_flags);
}
return caps;
}
// Scan the bootloader flash region for ordinary application-update capabilities.
+43 -3
View File
@@ -10,6 +10,19 @@
#include "OtaBlInfo.h"
#include "OtaByteIO.h"
#if defined(OTA_TOWER_AUTO_STORE)
#if !defined(NRF52_PLATFORM) || !defined(HELTEC_TOWER_V2_SDCARD) || \
!defined(OTA_SD_STORE) || !defined(OTA_FLASH_STORE) || \
!defined(OTA_SD_BOOTLOADER_UPDATE)
#error "OTA_TOWER_AUTO_STORE requires the qualified nRF52 MeshTower SD-primary OTA profile"
#endif
#if defined(OTA_QSPI_STORE) || defined(QSPIFLASH) || \
defined(OTA_RAK_AUTO_STORE) || defined(OTA_INTERNAL_BOOTLOADER_UPDATE) || \
defined(OTA_QSPI_BOOTLOADER_UPDATE) || defined(OTA_HYBRID_RAM_STORE)
#error "MeshTower automatic storage retains the full-RAM SD profile and SD-only bootloader staging"
#endif
#endif
#if defined(OTA_QSPI_BOOTLOADER_UPDATE)
#if !defined(NRF52_PLATFORM) || !defined(OTA_QSPI_STORE)
#error "OTA_QSPI_BOOTLOADER_UPDATE requires nRF52 raw-QSPI staging"
@@ -39,7 +52,8 @@
#if !defined(HELTEC_TOWER_V2_SDCARD)
#error "OTA_SD_BOOTLOADER_UPDATE is restricted to the qualified MeshTower V2 SD target"
#endif
#if defined(OTA_FLASH_STORE) || defined(OTA_QSPI_STORE) || defined(QSPIFLASH)
#if (defined(OTA_FLASH_STORE) && !defined(OTA_TOWER_AUTO_STORE)) || \
defined(OTA_QSPI_STORE) || defined(QSPIFLASH)
#error "SD bootloader staging cannot share another OTA/filesystem store"
#endif
#endif
@@ -556,15 +570,25 @@ inline bool ota_bootloader_external_crc_ok(
template <typename Store>
inline bool ota_bootloader_external_image_metadata(
Store& store, uint32_t payload_off, uint8_t exact_storage_flags,
OtaBootloaderIdentity& candidate, OtaBootloaderCapsMarker& caps) {
OtaBootloaderIdentity& candidate, OtaBootloaderCapsMarker& caps,
uint8_t required_optional_storage = 0) {
candidate = OtaBootloaderIdentity();
caps = OtaBootloaderCapsMarker();
if (exact_storage_flags == 0u) return false;
if (required_optional_storage != 0u &&
!((exact_storage_flags == OTA_BL_PROFILE_SD_BOOT_UPDATE &&
required_optional_storage == OTA_BL_STORAGE_STAGE_CEILING) ||
(exact_storage_flags == OTA_BL_PROFILE_INTERNAL_BOOT_UPDATE &&
required_optional_storage == (OTA_BL_STORAGE_QSPI | OTA_BL_STORAGE_HEADER_W25))))
return false;
static const uint32_t STEP = 512u;
uint8_t buf[STEP + OTA_BOOT_ENVELOPE_SIZE - 1u];
uint8_t valid_identities = 0;
uint8_t valid_caps = 0;
uint8_t valid_ram = 0;
uint8_t storage_records = 0;
uint32_t optional_record_offset = 0;
for (uint32_t base = 0; base < OTA_BOOT_IMAGE_SIZE; base += STEP) {
uint32_t len = OTA_BOOT_IMAGE_SIZE - base;
if (len > sizeof(buf)) len = sizeof(buf);
@@ -573,7 +597,22 @@ inline bool ota_bootloader_external_image_metadata(
? OTA_BOOT_IMAGE_SIZE - base : STEP;
for (uint32_t local = 0; local < starts; ++local) {
const uint32_t absolute = base + local;
if (required_optional_storage && (absolute & 3u) == 0u &&
local + 8u <= len && memcmp(buf + local, "MOTASTOR", 8u) == 0) {
// Scan each aligned start once, including chunk boundaries. A valid
// RAM record is encountered first and binds its immediately following
// STOR; no stray or duplicate declaration may hide beside that pair.
if (++storage_records != 1u || valid_ram != 1u ||
absolute != optional_record_offset) return false;
}
if ((absolute & 3u) == 0u && local + 16u <= len) {
OtaRamCaps ram;
if (required_optional_storage && ota_ram_caps_marker_parse(buf + local, ram)) {
if (++valid_ram != 1u || local + 32u > len ||
ota_bl_optional_app_storage(buf + local, 32u) != required_optional_storage)
return false;
optional_record_offset = absolute + 16u;
}
OtaBootloaderCapsMarker parsed;
if (ota_bootloader_caps_marker_parse(buf + local, parsed) &&
parsed.apply_abi >= MOTA_BOOT_FORMAT_VER &&
@@ -596,7 +635,8 @@ inline bool ota_bootloader_external_image_metadata(
}
}
}
if (valid_identities != 1u || valid_caps != 1u || !caps.present ||
if ((required_optional_storage && (valid_ram != 1u || storage_records != 1u)) ||
valid_identities != 1u || valid_caps != 1u || !caps.present ||
candidate.manifest_offset > OTA_BOOT_IMAGE_SIZE - OTA_BOOT_MANIFEST_SIZE)
return false;
const uint32_t available = OTA_BOOT_IMAGE_SIZE - candidate.manifest_offset;
+55 -5
View File
@@ -158,6 +158,9 @@ bool handle_ota_command(const char* command, char* reply, mesh::MainBoard& board
OtaContext& c = ota_ctx();
c.manager.set_clock(millis());
c.manager.set_speed(speedFactor());
#if defined(NRF52_PLATFORM) && defined(OTA_TOWER_AUTO_STORE)
c.prepareTowerStorage();
#endif
const char* rest = a;
// ---- raw / internal primitives, tucked under `ota dev ...` ----
@@ -196,6 +199,11 @@ bool handle_ota_command(const char* command, char* reply, mesh::MainBoard& board
"folder | config | key");
#endif
#elif defined(NRF52_PLATFORM) && defined(OTA_SD_STORE)
#if defined(OTA_TOWER_AUTO_STORE)
strcpy(reply,
"OTA: status | stats | ls | get <id> flash | install | bootloader | cancel | announce | self | serve | "
"storage | folder | cache | config | key");
#else
#if defined(OTA_SD_BOOTLOADER_UPDATE)
strcpy(reply,
"OTA: status | stats | ls | get <id> flash | install | bootloader | cancel | announce | self | serve | "
@@ -205,6 +213,7 @@ bool handle_ota_command(const char* command, char* reply, mesh::MainBoard& board
"OTA: status | stats | ls | get <id> flash | install | cancel | announce | self | serve | folder | "
"cache | config | key");
#endif
#endif
#else
snprintf(reply, 160,
"OTA: status | stats | ls | get <id> flash | install | cancel | announce | self | serve | folder | "
@@ -253,7 +262,11 @@ bool handle_ota_command(const char* command, char* reply, mesh::MainBoard& board
// nRF52 applies via the bootloader - show (cached) whether it can, so `ota get`/`install` won't surprise.
// blrc = the bootloader's last apply code (diagnostic; 0xB8=success, see ota_delta.c).
const OtaBlCaps& bl = c.bootloaderAppCaps();
#if defined(OTA_RAK_AUTO_STORE)
#if defined(OTA_TOWER_AUTO_STORE)
const char* bl_state = !bl.present ? "NONE" :
c.fetch_store.usesExternal() ? "SD" :
c.fetch_store.usesInternal() ? "internal" : "storage-ERR";
#elif defined(OTA_RAK_AUTO_STORE)
const char* bl_state = !bl.present ? "NONE" :
c.fetch_store.usesExternal() ? "QSPI" :
c.fetch_store.usesInternal() ? "internal" : "storage-ERR";
@@ -415,6 +428,9 @@ bool handle_ota_command(const char* command, char* reply, mesh::MainBoard& board
ota_bootloader_self_update_caps_valid(list_bl_update);
#if defined(OTA_SD_BOOTLOADER_UPDATE)
installable = installable && list_sd_headroom;
#if defined(OTA_TOWER_AUTO_STORE)
installable = installable && c.fetch_store.usesExternal();
#endif
#endif
#endif
fit = installable ? "yours" : "bootloader unsupported";
@@ -423,7 +439,11 @@ bool handle_ota_command(const char* command, char* reply, mesh::MainBoard& board
#if defined(NRF52_PLATFORM)
installable = installable && list_bl.present && list_bl.apply_abi >= MOTA_FORMAT_VER
&& h->codec < 16 && (list_bl.codec_mask & (1u << h->codec));
#if defined(OTA_SD_STORE)
#if defined(OTA_TOWER_AUTO_STORE)
installable = installable && c.fetch_store.compatible();
if (h->codec == CODEC_FULL)
installable = installable && c.fetch_store.usesExternal();
#elif defined(OTA_SD_STORE)
installable = installable && (list_bl.storage_flags & OTA_BL_STORAGE_SD);
#elif defined(OTA_RAK_AUTO_STORE)
if (c.fetch_store.usesExternal())
@@ -567,6 +587,12 @@ bool handle_ota_command(const char* command, char* reply, mesh::MainBoard& board
return true;
}
#if defined(OTA_SD_BOOTLOADER_UPDATE)
#if defined(OTA_TOWER_AUTO_STORE)
if (!c.fetch_store.usesExternal()) {
strcpy(reply, "ERR bootloader packages require a usable SD card");
return true;
}
#endif
SelfFwInfo sd_self;
if (!ota_self_firmware(sd_self) ||
!ota_bootloader_scratch_headroom_valid(
@@ -602,7 +628,12 @@ bool handle_ota_command(const char* command, char* reply, mesh::MainBoard& board
need_abi, (unsigned)selcodec, bl.apply_abi, bl.codec_mask);
return true;
}
#if defined(OTA_SD_STORE)
#if defined(OTA_TOWER_AUTO_STORE)
if (!c.fetch_store.compatible()) {
snprintf(reply, 160, "ERR OTA storage unsafe: %s", c.fetch_store.selectionReason());
return true;
}
#elif defined(OTA_SD_STORE)
if (!(bl.storage_flags & OTA_BL_STORAGE_SD)) {
strcpy(reply, "ERR bootloader cannot apply an update staged on SD; update it over USB first");
return true;
@@ -709,6 +740,12 @@ bool handle_ota_command(const char* command, char* reply, mesh::MainBoard& board
#endif
const bool discarded = !was_folder && !was_sd_archive &&
c.fetch_store.discard();
#if defined(NRF52_PLATFORM) && defined(OTA_TOWER_AUTO_STORE)
if (discarded || (!c.fetch_store.usesExternal() && !c.fetch_store.usesInternal())) {
c.fetch_store.resetSelection();
c.prepareTowerStorage();
}
#endif
// Fetch cancellation and serving are independent. In particular, a
// manual serve view can point into serve_buf, so leave the manager
// view and its caller-owned buffer intact until `ota dev clear` (which
@@ -769,7 +806,10 @@ bool handle_ota_command(const char* command, char* reply, mesh::MainBoard& board
// ---- raw-QSPI staging diagnostics (read-only probe; preserves a latched fetch failure) ----
} else if (is_cmd(a, "qspi|storage", &rest)) {
#if defined(NRF52_PLATFORM) && defined(OTA_RAK_AUTO_STORE)
#if defined(NRF52_PLATFORM) && defined(OTA_TOWER_AUTO_STORE)
snprintf(reply, 160, "OTA storage: %s; capacity=%luK; SD primary, internal application deltas only",
c.fetch_store.selectionReason(), (unsigned long)(c.fetch_store.capacity() / 1024));
#elif defined(NRF52_PLATFORM) && defined(OTA_RAK_AUTO_STORE)
if (c.fetch_store.usesExternal()) {
const uint32_t qspi_capacity = c.fetch_store.qspiCapacity();
snprintf(reply, 160, "QSPI %s jedec=%06lX size=%luK sr1=%02X stage=%s%s%s",
@@ -814,7 +854,11 @@ bool handle_ota_command(const char* command, char* reply, mesh::MainBoard& board
#if defined(NRF52_PLATFORM)
// nRF52 applies via the bootloader, so surface whether THIS device's bootloader can install this store.
const OtaBlCaps& bl = c.bootloaderAppCaps(); // cached (flash scanned once)
#if defined(OTA_RAK_AUTO_STORE)
#if defined(OTA_TOWER_AUTO_STORE)
snprintf(reply + n, 160 - n, " | store:%s | bootloader:%s",
c.fetch_store.usesExternal() ? "SD" : c.fetch_store.usesInternal() ? "internal" : "unsafe",
c.fetch_store.compatible() ? "apply OK" : "unsupported");
#elif defined(OTA_RAK_AUTO_STORE)
if (c.fetch_store.usesExternal()) {
const uint32_t qspi_capacity = c.fetch_store.qspiCapacity();
snprintf(reply + n, 160 - n, " | QSPI store:%s%uK | bootloader: %s",
@@ -1323,6 +1367,12 @@ static bool handle_dev(const char* d, char* reply, OtaContext& c) {
strcpy(reply, "OK cleared SD archive session; partial retained for resume");
} else {
const bool discarded = c.fetch_store.discard();
#if defined(NRF52_PLATFORM) && defined(OTA_TOWER_AUTO_STORE)
if (discarded || (!c.fetch_store.usesExternal() && !c.fetch_store.usesInternal())) {
c.fetch_store.resetSelection();
c.prepareTowerStorage();
}
#endif
strcpy(reply, discarded ? "OK OTA receive slot confirmed clear"
: "ERR RAM state cleared; persistent OTA slot invalidation failed");
}
+84 -10
View File
@@ -27,7 +27,10 @@
#define OTA_DYNAMIC_CONTEXT 0
#endif
#if defined(NRF52_PLATFORM) && defined(OTA_RAK_AUTO_STORE)
#if defined(NRF52_PLATFORM) && defined(OTA_TOWER_AUTO_STORE)
#include "OtaStoreTowerNrf52.h"
#include "OtaCacheSdNrf52.h"
#elif defined(NRF52_PLATFORM) && defined(OTA_RAK_AUTO_STORE)
#include "OtaStoreAdaptiveNrf52.h"
#elif defined(NRF52_PLATFORM) && defined(OTA_QSPI_STORE)
#include "OtaStoreQspiNrf52.h"
@@ -110,6 +113,9 @@ struct OtaContext {
// store object for OtaManager, while folder captures replace it with the
// host-backed FolderMotaStore for the duration of the pull.
OtaStoreRam<1> fetch_store;
#elif defined(NRF52_PLATFORM) && defined(OTA_TOWER_AUTO_STORE)
OtaStoreTowerNrf52 fetch_store; // SD primary, qualified internal delta fallback
OtaCacheSdNrf52 sd_cache; // always owns the stable SD store
#elif defined(NRF52_PLATFORM) && defined(OTA_RAK_AUTO_STORE)
OtaStoreAdaptiveNrf52 fetch_store;
#elif defined(NRF52_PLATFORM) && defined(OTA_QSPI_STORE)
@@ -145,9 +151,9 @@ struct OtaContext {
#endif
uint32_t serve_expected = 0; // size declared by `ota stage`
bool serving = false; // manager.serve() succeeded
// Capture application-storage eligibility once. An adaptive nRF52 may later
// switch to internal flash to stage a bootloader without changing its normal
// ability to offer its running application.
// RAK application-storage eligibility survives privileged staging changes.
// Tower eligibility is established after its deferred SD probe and changes
// only when an operator ends the pinned transfer and selects storage again.
bool self_serve_supported = false;
// flash-backed self-serve: cached merkle leaves (heap, freed on re-serve) + assembled manifest of our
// own running firmware. The payload is read from flash per block; only the metadata is held in RAM.
@@ -291,6 +297,12 @@ struct OtaContext {
strncpy(msg, "refused: use ota bootloader install <MID8> <HASH16>", 96);
msg[95] = 0; return false;
}
#if defined(OTA_TOWER_AUTO_STORE)
if (!mm.is_signed()) {
strncpy(msg, "refused: MeshTower application OTA requires a trusted signature", 96);
msg[95] = 0; return false;
}
#endif
if (trusted_auto) {
SelfFwInfo self;
if (!mm.is_signed()) {
@@ -314,7 +326,7 @@ struct OtaContext {
}
}
bool ok;
#if defined(NRF52_PLATFORM) && defined(OTA_RAK_AUTO_STORE)
#if defined(NRF52_PLATFORM) && (defined(OTA_RAK_AUTO_STORE) || defined(OTA_TOWER_AUTO_STORE))
ok = fetch_store.usesExternal()
? ota_apply_mota_nrf52(fetch_store.externalStore(), allow, apply_st, msg)
: fetch_store.usesInternal()
@@ -363,7 +375,15 @@ struct OtaContext {
msg[95] = 0; return false;
}
const OtaBootloaderIdentity& installed = bootloaderIdentity();
#if defined(OTA_RAK_AUTO_STORE)
#if defined(OTA_TOWER_AUTO_STORE)
if (!fetch_store.usesExternal()) {
strncpy(msg, "bootloader package must be staged on SD", 96);
msg[95] = 0; return false;
}
bool ok = ota_prepare_bootloader_update_nrf52(
fetch_store.sdStore(), allow, installed, manager.fetchManifestId(), operator_mid,
operator_hash8, apply_st, msg);
#elif defined(OTA_RAK_AUTO_STORE)
if (!fetch_store.usesInternal()) {
strncpy(msg, "bootloader package must be staged in internal flash", 96);
msg[95] = 0; return false;
@@ -545,10 +565,45 @@ struct OtaContext {
}
#if defined(NRF52_PLATFORM) && defined(OTA_SD_STORE)
OtaStoreSdNrf52& sdStagingStore() {
#if defined(OTA_TOWER_AUTO_STORE)
return fetch_store.sdStore();
#else
return fetch_store;
#endif
}
#if defined(OTA_TOWER_AUTO_STORE)
// Probe only after startup or an explicit OTA command. Selection is latched
// until operator cancellation, including a failed/paused transfer.
bool prepareTowerStorage() {
const bool usable = fetch_store.selectStorage();
const bool external = usable && fetch_store.usesExternal();
const bool was_self_serve_supported = self_serve_supported;
manager.set_accept_full(external);
manager.set_accept_bootloader(external &&
ota_bootloader_self_update_caps_valid(bootloaderUpdateCaps()));
self_serve_supported = ota_self_serve_supported(external);
if (was_self_serve_supported && !self_serve_supported &&
manager.servingPrimaryManifest(serve_self_manifest)) {
manager.clear_primary();
serving = false;
}
#if MESHCORE_OTA_DEVICE_DEFLATE
manager.set_transport_deflate_encoder(self_serve_supported ? ota_transport_deflate : nullptr);
#endif
if (!external) manager.set_archive_interest(false);
return usable;
}
#endif
// Initialize and attach the persistent source lazily. This lets Mesh::begin finish quickly when no card
// is inserted, while archive interest is already enabled so early OTA advertisements still get queried.
bool ensureSdCache() {
sd_cache.attach(fetch_store);
sd_cache.attach(sdStagingStore());
#if defined(OTA_TOWER_AUTO_STORE)
if (!prepareTowerStorage() || !fetch_store.usesExternal()) return false;
#endif
if (!sd_cache.initialize()) return false;
if (!_sd_cache_source_attached) {
if (!manager.add_source(&sd_cache)) return false;
@@ -598,11 +653,21 @@ struct OtaContext {
void finishSdCardReset(uint32_t now) {
sd_cache.resetMedia();
#if defined(OTA_TOWER_AUTO_STORE)
fetch_store.resetSelection();
#endif
_sd_cache_init_retry_at = now;
ensureSdCache();
}
void serviceSdCache(uint32_t now) {
#if defined(OTA_TOWER_AUTO_STORE)
if (!prepareTowerStorage() || !fetch_store.usesExternal()) {
if (_sd_cache_source_attached) manager.remove_source(&sd_cache);
_sd_cache_source_attached = false;
return;
}
#endif
if (!_sd_cache_source_attached) {
if (_sd_cache_init_retry_at && (int32_t)(now - _sd_cache_init_retry_at) < 0) return;
if (!ensureSdCache()) {
@@ -694,6 +759,11 @@ struct OtaContext {
manager.set_accept_full(true);
manager.set_autofetch(OtaManager::AUTOFETCH_OFF);
autoinstall = AUTOINSTALL_OFF;
#elif defined(NRF52_PLATFORM) && defined(OTA_TOWER_AUTO_STORE)
// An SD probe can block when the socket is empty. Bring up USB and the
// radio before determining the optional storage backend in the main loop.
manager.set_accept_full(false);
manager.set_apply_codec(CODEC_DETOOLS_INPLACE);
#elif defined(NRF52_PLATFORM) && defined(OTA_RAK_AUTO_STORE)
manager.set_accept_full(fetch_store.usesExternal());
manager.set_apply_codec(CODEC_DETOOLS_INPLACE);
@@ -711,7 +781,9 @@ struct OtaContext {
#if defined(NRF52_PLATFORM) && \
(defined(OTA_QSPI_BOOTLOADER_UPDATE) || defined(OTA_INTERNAL_BOOTLOADER_UPDATE) || \
defined(OTA_SD_BOOTLOADER_UPDATE))
#if defined(OTA_RAK_AUTO_STORE)
#if defined(OTA_TOWER_AUTO_STORE)
manager.set_accept_bootloader(false);
#elif defined(OTA_RAK_AUTO_STORE)
manager.set_accept_bootloader(
ota_bootloader_self_update_caps_valid(ota_bootloader_update_caps()));
#else
@@ -721,7 +793,9 @@ struct OtaContext {
manager.set_accept_bootloader(false);
#endif
manager.set_fetch_store(&fetch_store);
#if defined(NRF52_PLATFORM) && defined(OTA_RAK_AUTO_STORE) && !defined(OTA_SEEDER_ONLY)
#if defined(NRF52_PLATFORM) && defined(OTA_TOWER_AUTO_STORE)
self_serve_supported = false;
#elif defined(NRF52_PLATFORM) && defined(OTA_RAK_AUTO_STORE) && !defined(OTA_SEEDER_ONLY)
self_serve_supported = ota_self_serve_supported(fetch_store.usesExternal());
#else
self_serve_supported = ota_self_serve_supported();
@@ -733,7 +807,7 @@ struct OtaContext {
manager.set_transport_deflate_encoder(self_serve_supported ? ota_transport_deflate : nullptr);
#endif
#if defined(NRF52_PLATFORM) && defined(OTA_SD_STORE)
sd_cache.attach(fetch_store);
sd_cache.attach(sdStagingStore());
manager.set_archive_interest(true); // default on; the SD marker can turn it off at first mount
#endif
}
+2 -2
View File
@@ -5,7 +5,7 @@ namespace mesh { namespace ota {
// Default own-image offering is for full-image platforms. Internal-only nRF52
// nodes retain the explicit diagnostic export used to capture delta bases, but
// do not automatically offer a full image their ordinary peers cannot install.
// Adaptive RAK builds must use the qualified application backend, not merely
// Adaptive RAK and Tower builds must use the qualified application backend, not merely
// the presence of a NOR chip (or the temporary bootloader staging backend).
inline bool ota_self_serve_supported(bool external_application_storage = false) {
#if defined(OTA_SEEDER_ONLY)
@@ -14,7 +14,7 @@ inline bool ota_self_serve_supported(bool external_application_storage = false)
#elif defined(ESP32_PLATFORM)
(void)external_application_storage;
return true;
#elif defined(NRF52_PLATFORM) && defined(OTA_RAK_AUTO_STORE)
#elif defined(NRF52_PLATFORM) && (defined(OTA_RAK_AUTO_STORE) || defined(OTA_TOWER_AUTO_STORE))
return external_application_storage;
#elif defined(NRF52_PLATFORM) && (defined(OTA_QSPI_STORE) || defined(OTA_SD_STORE))
(void)external_application_storage;
+3
View File
@@ -52,6 +52,9 @@ public:
bool eraseCard(MainBoard& board);
bool getSpace(MainBoard& board, uint64_t& used_bytes, uint64_t& free_bytes);
bool listFiles(MainBoard& board, uint16_t page, char* reply, size_t cap);
// Mount-only probe for the MeshTower selector. Never opens/removes staging
// files or changes their live session state.
bool probeMedia() { return mount() && capacity() != 0u; }
const char* last_error() const { return _error; }
private:
+216
View File
@@ -0,0 +1,216 @@
#pragma once
#if defined(OTA_TOWER_AUTO_STORE)
#if !defined(NRF52_PLATFORM) || !defined(HELTEC_TOWER_V2_SDCARD) || \
!defined(OTA_SD_STORE) || !defined(OTA_FLASH_STORE)
#error "MeshTower automatic OTA storage requires the qualified nRF52 SD primary"
#endif
#include "OtaBlInfo.h"
#include "OtaStoreFlashNrf52.h"
#include "OtaStoreSdNrf52.h"
#include "MotaContainer.h"
#include <new>
namespace mesh {
namespace ota {
// Keep the SD volume object stable because the archive shares its mounted
// filesystem. Internal construction is deferred: its constructor invalidates
// the same retained authorization bytes used by the SD application handoff.
// Selecting media never opens/removes a staging file, and an operation failure
// never redirects an already selected transfer to a different medium.
class OtaStoreTowerNrf52 : public OtaStore {
enum Mode : uint8_t { UNSELECTED, SD_MODE, INTERNAL_MODE, UNAVAILABLE };
OtaStoreSdNrf52 _sd;
alignas(OtaStoreFlashNrf52) uint8_t _internal_bytes[sizeof(OtaStoreFlashNrf52)];
OtaStoreFlashNrf52* _internal = nullptr;
Mode _mode = UNSELECTED;
bool _compatible = false;
bool _has_stage = false;
bool _layout_rejected = false;
bool _layout_accepted = false;
const char* _reason = "not selected";
const char* _error = nullptr;
OtaStore* active() {
return _mode == SD_MODE ? static_cast<OtaStore*>(&_sd) :
_mode == INTERNAL_MODE ? _internal : nullptr;
}
const OtaStore* active() const {
return _mode == SD_MODE ? static_cast<const OtaStore*>(&_sd) :
_mode == INTERNAL_MODE ? _internal : nullptr;
}
bool resumeMatches(const uint8_t* mid, uint32_t target) {
uint8_t raw[MOTA_MFL];
MotaManifest manifest;
const OtaStore* s = active();
if (!s || !s->read(8u, raw, sizeof(raw)) ||
!mota_parse_manifest(raw, sizeof(raw), manifest)) {
_error = "staged manifest is invalid";
return false;
}
if ((mid && memcmp(manifest.merkle_root, mid, 4u) != 0) ||
(target != 0u && manifest.target_id != target)) {
_error = "staged MID/target does not match";
return false;
}
if (_mode == INTERNAL_MODE && (manifest.is_full() || manifest.is_bootloader())) {
_error = "internal fallback accepts application deltas only";
return false;
}
return true;
}
public:
OtaStoreTowerNrf52() = default;
OtaStoreTowerNrf52(const OtaStoreTowerNrf52&) = delete;
OtaStoreTowerNrf52& operator=(const OtaStoreTowerNrf52&) = delete;
~OtaStoreTowerNrf52() override {
if (_internal) _internal->~OtaStoreFlashNrf52();
}
// Call from the deferred OTA preparation path, after normal board startup.
// Getter/status calls deliberately cannot turn USB startup into an SD probe.
bool selectStorage() {
if (_mode != UNSELECTED) return _compatible;
const bool sd_ready = _sd.probeMedia();
const OtaBlCaps caps = ota_bootloader_app_caps();
const bool sd_profile = caps.present && (caps.storage_flags & OTA_BL_STORAGE_SD) != 0u;
if (sd_ready) {
_mode = SD_MODE;
_compatible = sd_profile;
_reason = sd_profile ? "SD staging" : "SD present; incompatible OTAFIX bootloader";
} else if (sd_profile && caps.optional_app_storage == OTA_BL_STORAGE_STAGE_CEILING) {
_internal = new (_internal_bytes) OtaStoreFlashNrf52();
_mode = INTERNAL_MODE;
_compatible = true;
_reason = "SD unavailable; internal delta staging";
} else {
_mode = UNAVAILABLE;
_reason = "SD unavailable; OTAFIX lacks qualified internal fallback";
}
return _compatible;
}
// The caller must finish/cancel the transfer first. Do not discard durable
// staged bytes here: a following reopen may intentionally resume them.
void resetSelection() {
if (_internal) {
_internal->~OtaStoreFlashNrf52();
_internal = nullptr;
}
_mode = UNSELECTED;
_compatible = false;
_has_stage = false;
_layout_rejected = false;
_layout_accepted = false;
_reason = "not selected";
_error = nullptr;
}
bool usesExternalStore() const { return _mode == SD_MODE; }
bool usesExternal() const { return usesExternalStore(); }
bool usesInternal() const { return _mode == INTERNAL_MODE; }
bool compatible() const { return _compatible; }
const char* selectionReason() const { return _reason; }
OtaStoreSdNrf52& sdStore() { return _sd; }
OtaStoreSdNrf52& externalStore() { return _sd; }
// Only use after usesInternal() succeeds. This accessor must not construct
// an internal store while an SD authorization is being prepared/published.
OtaStoreFlashNrf52& internalStore() { return *_internal; }
const char* last_error() const {
if (_error) return _error;
return _mode == SD_MODE ? _sd.last_error() : _reason;
}
bool begin(uint32_t n) override {
_has_stage = false;
if (!selectStorage() || _layout_rejected) return false;
if (_mode == INTERNAL_MODE && !_layout_accepted) {
_error = "internal fallback requires a planned application delta";
return false;
}
_error = nullptr;
_has_stage = active()->begin(n);
if (!_has_stage && _mode == INTERNAL_MODE) _error = "internal OTA begin failed";
return _has_stage;
}
bool write(uint32_t p, const uint8_t* d, uint32_t n) override {
return _has_stage && active()->write(p, d, n);
}
bool read(uint32_t p, uint8_t* d, uint32_t n) const override {
return _has_stage && active()->read(p, d, n);
}
uint32_t capacity() const override {
const OtaStore* s = active();
return _compatible && s ? s->capacity() : 0u;
}
uint32_t staged_size() const override {
return _has_stage ? active()->staged_size() : 0u;
}
void clear() override {
OtaStore* s = active();
if (s) s->clear();
_has_stage = false;
_layout_rejected = false;
_layout_accepted = false;
_error = nullptr;
}
bool discard() override {
if (!selectStorage()) return false;
const bool ok = active()->discard();
_has_stage = false;
_layout_rejected = false;
_layout_accepted = false;
if (!ok && _mode == INTERNAL_MODE) _error = "internal OTA discard failed";
return ok;
}
bool set_meta_size(uint32_t n) override {
return _has_stage && active()->set_meta_size(n);
}
bool finalize() override { return _has_stage && active()->finalize(); }
void checkpoint() override { if (_has_stage) active()->checkpoint(); }
bool reopen() override { return reopenFor(nullptr, 0u); }
bool reopenFor(const uint8_t* mid, uint32_t target) override {
_has_stage = false;
_layout_rejected = false;
_layout_accepted = false;
_error = nullptr;
if (!selectStorage()) return false;
OtaStore* s = active();
const bool reopened = _mode == SD_MODE ? _sd.reopen() : s->reopenFor(mid, target);
// Rejecting a mismatched SD container must not call SD clear(): that
// method durably deletes the very file a later explicit pull may need.
_has_stage = reopened && resumeMatches(mid, target);
return _has_stage;
}
bool plan_layout(bool full, uint32_t image, uint32_t offset,
uint32_t payload, bool bootloader) override {
_layout_rejected = true;
_layout_accepted = false;
_error = nullptr;
if (!selectStorage()) return false;
if (_mode == INTERNAL_MODE && (full || bootloader)) {
_error = "internal fallback accepts application deltas only";
return false;
}
_layout_rejected = !active()->plan_layout(full, image, offset, payload, bootloader);
_layout_accepted = !_layout_rejected;
return !_layout_rejected;
}
// Management always addresses the physical SD card. These operations never
// switch a selected application transfer between SD and internal storage.
bool formatCard(MainBoard& board) { return _sd.formatCard(board); }
bool eraseCard(MainBoard& board) { return _sd.eraseCard(board); }
bool getSpace(MainBoard& board, uint64_t& used, uint64_t& free) {
return _sd.getSpace(board, used, free);
}
bool listFiles(MainBoard& board, uint16_t page, char* reply, size_t cap) {
return _sd.listFiles(board, page, reply, cap);
}
};
} // namespace ota
} // namespace mesh
#endif