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:
1 parent
7d3ee7200f
commit
30fe0d617b
25 files changed
+2082
-93
No files matched your search
@@ -15,6 +15,34 @@ def record(target: str, profile: str = "full", platform: str = "ESP32_PLATFORM")
|
||||
|
||||
|
||||
class ReleaseFullSelectionTest(unittest.TestCase):
|
||||
def test_meshtower_sd_primary_filters_stale_internal_images_without_relabeling(self):
|
||||
primary = "Heltec_tower_v2_sdcard_repeater_lora_ota_no_external_sensors"
|
||||
variants = []
|
||||
for sensor in ("full", "reduced"):
|
||||
item = record(primary, "auto", "NRF52_PLATFORM")
|
||||
item["manifest"].update(artifact_target=primary + "-" + sensor + "-ota",
|
||||
capabilities=["sensor.profile." + sensor])
|
||||
variants.append(item)
|
||||
companion = record("Heltec_tower_v2_companion_radio_full", platform="NRF52_PLATFORM")
|
||||
room = record("Heltec_tower_v2_room_server_lora_ota_no_external_sensors",
|
||||
platform="NRF52_PLATFORM")
|
||||
legacy = [record(target, "auto", "NRF52_PLATFORM") for target in (
|
||||
"Heltec_tower_v2_repeater",
|
||||
"Heltec_tower_v2_repeater_lora_ota_no_external_sensors",
|
||||
)]
|
||||
selected = select_ordinary_full_records(legacy + variants + [companion, room])
|
||||
self.assertEqual(selected, variants + [companion, room])
|
||||
for before, after in zip(variants, selected):
|
||||
self.assertIs(before, after)
|
||||
self.assertEqual(after["manifest"]["target"], primary)
|
||||
|
||||
def test_meshtower_internal_images_cannot_substitute_for_missing_primary(self):
|
||||
for target in ("Heltec_tower_v2_repeater",
|
||||
"Heltec_tower_v2_repeater_lora_ota_no_external_sensors"):
|
||||
with self.subTest(target=target):
|
||||
with self.assertRaisesRegex(ValueError, "requires the SD primary"):
|
||||
select_ordinary_full_records([record(target, "auto", "NRF52_PLATFORM")])
|
||||
|
||||
def test_nrf52_full_and_reduced_ota_pair_is_never_collapsed(self):
|
||||
for role in ('repeater', 'room_server', 'sensor'):
|
||||
target = 'RAK_3401_' + role
|
||||
|
||||
@@ -4,6 +4,11 @@ set -euo pipefail
|
||||
cd "$(dirname "$0")/.."
|
||||
source build.sh
|
||||
fail() { echo "test_nrf52_ota_profiles: $*" >&2; exit 1; }
|
||||
test_output=$(mktemp -d)
|
||||
trap 'rm -rf -- "$test_output"' EXIT
|
||||
tower_primary=Heltec_tower_v2_sdcard_repeater_lora_ota_no_external_sensors
|
||||
tower_legacy=Heltec_tower_v2_repeater_lora_ota_no_external_sensors
|
||||
tower_base=Heltec_tower_v2_repeater
|
||||
|
||||
# This suite deliberately has no PlatformIO dependency. A mocked one-profile
|
||||
# worker exercises the actual single/bulk/matrix dispatch and fail-closed pair
|
||||
@@ -12,7 +17,7 @@ SUPPORTED_PIO_ENVS=(
|
||||
nrf_repeater nrf_repeater_lora_ota_no_external_sensors
|
||||
nrf_room_server nrf_room_server_lora_ota_no_external_sensors
|
||||
nrf_sensor nrf_sensor_lora_ota_no_external_sensors
|
||||
Xiao_nrf52_repeater Heltec_tower_v2_sdcard_repeater_lora_ota_no_external_sensors
|
||||
Xiao_nrf52_repeater "$tower_primary" "$tower_base" "$tower_legacy"
|
||||
RAK_3401_repeater_unified_lora_ota RAK_3401_sensor
|
||||
RAK_3401_sensor_lora_ota_no_external_sensors nrf_kiss_modem
|
||||
nrf_companion_radio_usb nrf_companion_radio_full nrf_terminal_chat
|
||||
@@ -31,6 +36,9 @@ done
|
||||
PIO_ENV_QSPI_OTA_BY_NAME[Xiao_nrf52_repeater]=1
|
||||
PIO_ENV_QSPI_OTA_BY_NAME[RAK_3401_repeater_unified_lora_ota]=1
|
||||
PIO_ENV_SD_OTA_BY_NAME[Heltec_tower_v2_sdcard_repeater_lora_ota_no_external_sensors]=1
|
||||
ALL_PIO_ENVS=("$tower_base" "$tower_primary")
|
||||
PIO_ENV_BUILD_BASE_BY_NAME[$tower_legacy]=$tower_base
|
||||
PIO_ENV_COMPLETE_OTA_BASE_BY_NAME[$tower_legacy]=$tower_base
|
||||
PIO_CONFIG_JSON='[]'
|
||||
|
||||
for target in nrf_repeater nrf_room_server nrf_sensor Xiao_nrf52_repeater \
|
||||
@@ -54,13 +62,88 @@ done
|
||||
Heltec_tower_v2_sdcard_repeater_lora_ota_no_external_sensors ] \
|
||||
|| fail "SD target lost its exact storage identity"
|
||||
|
||||
# The old base and generated internal-only build names now select the exact
|
||||
# SD primary. A direct alias must warn about its different installed OTA ID,
|
||||
# and all bulk/tagged lists must retain only one Full/Reduced target pair.
|
||||
for alias in "$tower_base" "$tower_legacy"; do
|
||||
[ "$(get_nrf52_sensor_ota_pair_target "$alias")" = "$tower_primary" ] \
|
||||
|| fail "$alias did not resolve to the SD primary"
|
||||
resolve_command_targets build-firmware "$alias" > /dev/null \
|
||||
2> "$test_output/tower-alias-warning"
|
||||
[ "${#RESOLVED_BUILD_TARGETS[@]}" -eq 1 ] \
|
||||
&& [ "${RESOLVED_BUILD_TARGETS[0]}" = "$tower_primary" ] \
|
||||
|| fail "$alias direct dispatch retained an internal-only identity"
|
||||
warning=$(cat "$test_output/tower-alias-warning")
|
||||
[[ "$warning" == *"require local USB/BLE DFU or SWD migration"* \
|
||||
&& "$warning" == *"not a same-target LoRa upgrade"* ]] \
|
||||
|| fail "$alias omitted its installed-identity migration warning"
|
||||
is_redundant_bulk_build_target "$alias" \
|
||||
|| fail "$alias remained a second canonical artifact"
|
||||
done
|
||||
for resolver in resolve_all_firmwares resolve_repeater_firmwares; do
|
||||
mapfile -t tower_targets < <("$resolver")
|
||||
target_list=" ${tower_targets[*]} "
|
||||
[[ "$target_list" == *" $tower_primary "* \
|
||||
&& "$target_list" != *" $tower_base "* \
|
||||
&& "$target_list" != *" $tower_legacy "* ]] \
|
||||
|| fail "$resolver did not publish only the Tower SD primary"
|
||||
done
|
||||
mapfile -t tower_targets < <(print_release_firmware_targets get-repeater-firmwares-to-build)
|
||||
target_list=" ${tower_targets[*]} "
|
||||
[[ "$target_list" == *" $tower_primary "* \
|
||||
&& "$target_list" != *" $tower_base "* \
|
||||
&& "$target_list" != *" $tower_legacy "* ]] \
|
||||
|| fail "tagged repeater list omitted the SD primary or retained a duplicate"
|
||||
for unchanged in Heltec_tower_v2_room_server Heltec_tower_v2_companion_radio_full; do
|
||||
if get_unified_meshtower_repeater_replacement "$unchanged" >/dev/null; then
|
||||
fail "$unchanged was redirected outside the repeater role"
|
||||
fi
|
||||
done
|
||||
|
||||
RESOLVED_BUILD_TARGETS=(nrf_repeater nrf_repeater_lora_ota_no_external_sensors \
|
||||
nrf_sensor nrf_sensor_lora_ota_no_external_sensors Xiao_nrf52_repeater \
|
||||
Heltec_tower_v2_sdcard_repeater_lora_ota_no_external_sensors)
|
||||
normalize_nrf52_sensor_ota_pair_targets
|
||||
"$tower_primary" "$tower_base" "$tower_legacy")
|
||||
normalize_nrf52_sensor_ota_pair_targets 2> "$test_output/tower-alias-warning"
|
||||
[ "${#RESOLVED_BUILD_TARGETS[@]}" -eq 4 ] \
|
||||
|| fail "ordinary/reduced aliases did not deduplicate into exactly one pair"
|
||||
|
||||
# Do not silently resurrect an incompatible internal recipe if the canonical
|
||||
# SD target is absent from a narrowed/misconfigured build inventory.
|
||||
unset 'PIO_ENV_PLATFORM_BY_NAME[Heltec_tower_v2_sdcard_repeater_lora_ota_no_external_sensors]'
|
||||
RESOLVED_BUILD_TARGETS=("$tower_legacy")
|
||||
if normalize_nrf52_sensor_ota_pair_targets > /dev/null 2>&1; then
|
||||
fail "unavailable SD primary silently fell back to the old internal recipe"
|
||||
fi
|
||||
PIO_ENV_PLATFORM_BY_NAME[$tower_primary]=NRF52_PLATFORM
|
||||
|
||||
# The build overlay must not undefine the exact primary's internal fallback.
|
||||
# Other SD targets retain their old SD-only contract even if metadata happens
|
||||
# to contain the Tower macro; no generic SD layout is made dual-storage.
|
||||
NRF52_OTA_SENSOR_PROFILE=full
|
||||
PIO_CONFIG_JSON='[["env:Heltec_tower_v2_sdcard_repeater_lora_ota_no_external_sensors", [["build_flags", ["-DOTA_SD_STORE=1", "-DOTA_FLASH_STORE=1", "-DOTA_TOWER_AUTO_STORE=1"]]]]]'
|
||||
PLATFORMIO_BUILD_FLAGS=""
|
||||
PLATFORMIO_BUILD_UNFLAGS=""
|
||||
apply_lora_ota_override "$tower_primary"
|
||||
[[ "$PLATFORMIO_BUILD_FLAGS" == *"-DOTA_FLASH_STORE=1"* \
|
||||
&& "$PLATFORMIO_BUILD_FLAGS" == *"-DOTA_SD_STORE=1"* \
|
||||
&& "$PLATFORMIO_BUILD_FLAGS" == *"-DOTA_TOWER_AUTO_STORE=1"* \
|
||||
&& "$PLATFORMIO_BUILD_FLAGS" != *"-UOTA_FLASH_STORE"* \
|
||||
&& "$PLATFORMIO_BUILD_UNFLAGS" != *"OTA_FLASH_STORE"* ]] \
|
||||
|| fail "SD primary overlay disabled its qualified internal fallback"
|
||||
other_sd_target=other_sd_repeater_lora_ota_no_external_sensors
|
||||
PIO_ENV_PLATFORM_BY_NAME[$other_sd_target]=NRF52_PLATFORM
|
||||
PIO_ENV_SD_OTA_BY_NAME[$other_sd_target]=1
|
||||
PIO_CONFIG_JSON='[["env:other_sd_repeater_lora_ota_no_external_sensors", [["build_flags", ["-DOTA_SD_STORE=1", "-DOTA_TOWER_AUTO_STORE=1"]]]]]'
|
||||
PLATFORMIO_BUILD_FLAGS=""
|
||||
PLATFORMIO_BUILD_UNFLAGS=""
|
||||
apply_lora_ota_override "$other_sd_target"
|
||||
[[ "$PLATFORMIO_BUILD_FLAGS" == *"-UOTA_FLASH_STORE"* \
|
||||
&& "$PLATFORMIO_BUILD_FLAGS" != *"-DOTA_TOWER_AUTO_STORE"* \
|
||||
&& "$PLATFORMIO_BUILD_UNFLAGS" == *"-D OTA_FLASH_STORE=1"* ]] \
|
||||
|| fail "unrelated SD target gained the Tower internal fallback"
|
||||
PIO_CONFIG_JSON='[]'
|
||||
NRF52_OTA_SENSOR_PROFILE=""
|
||||
|
||||
for selected in auto standard full; do
|
||||
BUILD_PROFILE_OVERRIDE=$selected
|
||||
BUILD_PROFILE_EXPLICIT=1
|
||||
@@ -93,13 +176,17 @@ FIRMWARE_FILENAME_INFIX=outer
|
||||
SKIP_DECLARED_REDUCTIONS=0
|
||||
NRF52_OTA_SENSOR_PROFILE=""
|
||||
for target in nrf_repeater nrf_room_server nrf_sensor Xiao_nrf52_repeater \
|
||||
Heltec_tower_v2_sdcard_repeater_lora_ota_no_external_sensors; do
|
||||
"$tower_primary" "$tower_base" "$tower_legacy"; do
|
||||
calls=()
|
||||
build_firmware "$target" >/dev/null
|
||||
[ "${#calls[@]}" -eq 2 ] || fail "$target did not build exactly two options"
|
||||
[[ "${calls[0]}" == *:full:full-ota:1:1:1 ]] || fail "$target full flags/OTA requirement are wrong"
|
||||
[[ "${calls[1]}" == *:reduced:reduced-ota:0:0:1 ]] || fail "$target reduced flags/OTA requirement are wrong"
|
||||
[ "${calls[0]%%:*}" = "${calls[1]%%:*}" ] || fail "$target profiles have different OTA IDs"
|
||||
if [[ "$target" == Heltec_tower_v2* ]]; then
|
||||
[ "${calls[0]%%:*}" = "$tower_primary" ] \
|
||||
|| fail "$target profile worker built the obsolete internal identity"
|
||||
fi
|
||||
done
|
||||
[ "$ESP32_FULL_BUILD:$BUILD_PROFILE_EFFECTIVE:$REQUIRE_OTA_UPDATES:$FIRMWARE_FILENAME_INFIX:$NRF52_OTA_SENSOR_PROFILE" = \
|
||||
'1:standard:0:outer:' ] || fail "pair state leaked into other platform/Companion builds"
|
||||
@@ -117,8 +204,6 @@ failed_profile=""
|
||||
calls=()
|
||||
run_resolved_build_targets nrf_repeater nrf_sensor Xiao_nrf52_repeater >/dev/null
|
||||
[ "${#calls[@]}" -eq 6 ] || fail "bulk builds did not publish every pair"
|
||||
test_output=$(mktemp -d)
|
||||
trap 'rm -rf -- "$test_output"' EXIT
|
||||
OUTPUT_DIR=$test_output
|
||||
FIRMWARE_FILENAME_INFIX=""
|
||||
calls=()
|
||||
|
||||
@@ -39,6 +39,8 @@ class OtaSelfServePolicyTest(unittest.TestCase):
|
||||
(("NRF52_PLATFORM=1", "OTA_QSPI_STORE=1"), True, True),
|
||||
(("NRF52_PLATFORM=1", "OTA_SD_STORE=1"), True, True),
|
||||
(("NRF52_PLATFORM=1", "OTA_RAK_AUTO_STORE=1"), False, True),
|
||||
(("NRF52_PLATFORM=1", "OTA_TOWER_AUTO_STORE=1", "OTA_SD_STORE=1",
|
||||
"OTA_FLASH_STORE=1"), False, True),
|
||||
(("NRF52_PLATFORM=1", "OTA_RAK_AUTO_STORE=1",
|
||||
"OTA_QSPI_STORE=1"), False, True),
|
||||
(("NRF52_PLATFORM=1", "OTA_RAK_AUTO_STORE=1",
|
||||
@@ -116,6 +118,7 @@ struct Context {
|
||||
uint8_t autoinstall = AUTOINSTALL_OFF;
|
||||
char hw_id[33] = {};
|
||||
struct Cache { void attach(Store&) {} } sd_cache;
|
||||
Store& sdStagingStore() { return fetch_store; }
|
||||
#include "begin.h"
|
||||
};
|
||||
static bool send(void*, const uint8_t*, uint16_t, bool) { return true; }
|
||||
|
||||
@@ -0,0 +1,326 @@
|
||||
"""Compile production Tower context policy and reboot dispatch on the host."""
|
||||
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def method(source, signature):
|
||||
start = source.index(signature)
|
||||
opening = source.index("{", start)
|
||||
depth = 1
|
||||
end = opening + 1
|
||||
while depth:
|
||||
depth += (source[end] == "{") - (source[end] == "}")
|
||||
end += 1
|
||||
return source[start:end]
|
||||
|
||||
|
||||
CONTEXT_SETUP = r'''
|
||||
#include <cassert>
|
||||
#include <cstdint>
|
||||
#include <cstring>
|
||||
#define NRF52_PLATFORM 1
|
||||
#define OTA_SD_STORE 1
|
||||
#define OTA_FLASH_STORE 1
|
||||
#define OTA_SD_BOOTLOADER_UPDATE 1
|
||||
#define OTA_TOWER_AUTO_STORE 1
|
||||
#define MOTA_MIGRATION_TARGET_ID 0x77
|
||||
#define MESHCORE_OTA_DEVICE_DEFLATE 1
|
||||
#include "helpers/ota/OtaSelfServePolicy.h"
|
||||
using namespace mesh::ota;
|
||||
using OtaSend = void (*)();
|
||||
using CodecFunction = void (*)();
|
||||
static constexpr uint8_t CODEC_DETOOLS_INPLACE = 2;
|
||||
static constexpr size_t MOTA_MFL = 197;
|
||||
static void ota_transport_inflate() {}
|
||||
static void ota_transport_deflate() {}
|
||||
struct SelfFwInfo {
|
||||
bool valid = false;
|
||||
uint32_t target_id = 0, fw_version = 0;
|
||||
char hw_id[33] = {};
|
||||
};
|
||||
static SelfFwInfo current;
|
||||
static bool ota_self_firmware(SelfFwInfo& out) { out = current; return current.valid; }
|
||||
struct OtaBlCaps { bool valid = true; };
|
||||
static bool ota_bootloader_self_update_caps_valid(const OtaBlCaps& caps) { return caps.valid; }
|
||||
struct OtaStoreSdNrf52 {};
|
||||
struct TowerStore {
|
||||
enum Mode { Unselected, Sd, Internal, Unsafe };
|
||||
Mode mode = Unselected, fitted = Sd;
|
||||
bool usable = true;
|
||||
unsigned selection_calls = 0, probes = 0;
|
||||
OtaStoreSdNrf52 sd;
|
||||
bool selectStorage() {
|
||||
++selection_calls;
|
||||
if (mode == Unselected) { ++probes; mode = fitted; }
|
||||
return usable && mode != Unsafe;
|
||||
}
|
||||
bool usesExternal() const { return mode == Sd; }
|
||||
bool usesInternal() const { return mode == Internal; }
|
||||
OtaStoreSdNrf52& sdStore() { return sd; }
|
||||
void resetSelection() { mode = Unselected; }
|
||||
};
|
||||
struct Cache {
|
||||
OtaStoreSdNrf52* owner = nullptr;
|
||||
unsigned attachments = 0;
|
||||
void attach(OtaStoreSdNrf52& store) { ++attachments; owner = &store; }
|
||||
};
|
||||
struct Manager {
|
||||
bool full = true, bootloader = true, archive = false, enforce_version = false;
|
||||
uint8_t codec = 0xFF;
|
||||
uint32_t target = 0, migration = 0, floor = 0;
|
||||
CodecFunction encoder = ota_transport_deflate, decoder = nullptr;
|
||||
TowerStore* destination = nullptr;
|
||||
const uint8_t* primary = nullptr;
|
||||
unsigned clear_calls = 0, folder_sources = 3;
|
||||
void begin(uint32_t id, OtaSend, void*) { target = id; }
|
||||
void set_auto_migration_target(uint32_t id) { migration = id; }
|
||||
void set_transport_deflate_decoder(CodecFunction fn) { decoder = fn; }
|
||||
void set_transport_deflate_encoder(CodecFunction fn) { encoder = fn; }
|
||||
void set_auto_version_floor(uint32_t version, bool enforce) { floor = version; enforce_version = enforce; }
|
||||
void set_accept_full(bool value) { full = value; }
|
||||
void set_accept_bootloader(bool value) { bootloader = value; }
|
||||
void set_apply_codec(uint8_t value) { codec = value; }
|
||||
void set_fetch_store(TowerStore* value) { destination = value; }
|
||||
void set_archive_interest(bool value) { archive = value; }
|
||||
bool servingPrimaryManifest(const uint8_t* manifest) const { return primary == manifest; }
|
||||
void clear_primary() { ++clear_calls; primary = nullptr; }
|
||||
};
|
||||
struct Context {
|
||||
TowerStore fetch_store;
|
||||
Cache sd_cache;
|
||||
Manager manager;
|
||||
bool fetch_to_folder = true, self_serve_supported = true, serving = false;
|
||||
char hw_id[33] = {};
|
||||
uint8_t serve_self_manifest[MOTA_MFL] = {};
|
||||
OtaBlCaps caps;
|
||||
unsigned caps_reads = 0;
|
||||
const OtaBlCaps& bootloaderUpdateCaps() { ++caps_reads; return caps; }
|
||||
'''
|
||||
|
||||
CONTEXT_CASES = r'''
|
||||
};
|
||||
static void send() {}
|
||||
int main() {
|
||||
// Startup adopts authenticated self identity without selecting/mounting SD
|
||||
// or enabling a receiver capability that depends on the absent probe.
|
||||
current.valid = true; current.target_id = 0x1234; current.fw_version = 0x01170109;
|
||||
strcpy(current.hw_id, "Heltec_tower_v2");
|
||||
Context sd;
|
||||
sd.begin(0x55, send, nullptr, "fallback");
|
||||
assert(sd.fetch_store.probes == 0 && sd.fetch_store.selection_calls == 0);
|
||||
assert(sd.caps_reads == 0 && !sd.manager.full && !sd.manager.bootloader);
|
||||
assert(!sd.self_serve_supported && sd.manager.encoder == nullptr);
|
||||
assert(sd.manager.decoder == ota_transport_inflate && sd.manager.codec == 2);
|
||||
assert(sd.manager.target == 0x1234 && sd.manager.floor == 0x01170109);
|
||||
assert(sd.manager.enforce_version && sd.manager.migration == 0x77);
|
||||
assert(!sd.fetch_to_folder && strcmp(sd.hw_id, "Heltec_tower_v2") == 0);
|
||||
assert(sd.manager.destination == &sd.fetch_store);
|
||||
assert(sd.sd_cache.owner == &sd.fetch_store.sd && sd.sd_cache.attachments == 1);
|
||||
|
||||
assert(sd.prepareTowerStorage());
|
||||
assert(sd.fetch_store.probes == 1 && sd.manager.full && sd.manager.bootloader);
|
||||
assert(sd.self_serve_supported && sd.manager.encoder == ota_transport_deflate);
|
||||
assert(sd.manager.archive && sd.manager.clear_calls == 0);
|
||||
sd.manager.primary = sd.serve_self_manifest; sd.serving = true;
|
||||
// Mid-session disappearance does not change the selected backend or clear
|
||||
// a successfully offered image: the actual store handles subsequent I/O.
|
||||
sd.fetch_store.fitted = TowerStore::Internal;
|
||||
for (unsigned i = 0; i < 5; ++i) assert(sd.prepareTowerStorage());
|
||||
assert(sd.fetch_store.mode == TowerStore::Sd && sd.fetch_store.probes == 1);
|
||||
assert(sd.serving && sd.manager.primary == sd.serve_self_manifest);
|
||||
|
||||
// A legacy app-capable SD loader does not receive privileged packages.
|
||||
sd.caps.valid = false;
|
||||
assert(sd.prepareTowerStorage());
|
||||
assert(sd.manager.full && sd.self_serve_supported && !sd.manager.bootloader);
|
||||
|
||||
// A deliberate selection reset removes only our automatic primary image.
|
||||
// Attached folder sources are independent and must remain available.
|
||||
sd.fetch_store.resetSelection();
|
||||
assert(sd.prepareTowerStorage());
|
||||
assert(sd.fetch_store.mode == TowerStore::Internal && sd.fetch_store.probes == 2);
|
||||
assert(!sd.manager.full && !sd.manager.bootloader && !sd.manager.archive);
|
||||
assert(!sd.self_serve_supported && sd.manager.encoder == nullptr);
|
||||
assert(!sd.serving && sd.manager.primary == nullptr && sd.manager.clear_calls == 1);
|
||||
assert(sd.manager.folder_sources == 3);
|
||||
for (unsigned i = 0; i < 5; ++i) assert(sd.prepareTowerStorage());
|
||||
assert(sd.manager.clear_calls == 1 && sd.fetch_store.probes == 2);
|
||||
|
||||
// `ota dev serve self` deliberately exports an internal-fallback base for
|
||||
// delta capture. Repeated maintenance/status preparation must preserve that
|
||||
// explicit diagnostic offer while automatic self-serving stays disabled.
|
||||
sd.manager.primary = sd.serve_self_manifest; sd.serving = true;
|
||||
for (unsigned i = 0; i < 5; ++i) assert(sd.prepareTowerStorage());
|
||||
assert(sd.serving && sd.manager.primary == sd.serve_self_manifest);
|
||||
assert(!sd.self_serve_supported && sd.manager.encoder == nullptr);
|
||||
assert(!sd.manager.full && !sd.manager.bootloader && !sd.manager.archive);
|
||||
assert(sd.manager.clear_calls == 1 && sd.fetch_store.probes == 2);
|
||||
|
||||
uint8_t manual_manifest[MOTA_MFL] = {};
|
||||
sd.manager.primary = manual_manifest; sd.serving = true;
|
||||
assert(sd.prepareTowerStorage());
|
||||
assert(sd.manager.primary == manual_manifest && sd.serving);
|
||||
assert(sd.manager.clear_calls == 1 && sd.manager.folder_sources == 3);
|
||||
|
||||
// Unknown storage and a failed compatibility check disable every optional
|
||||
// capability even if the store still reports a physically present SD card.
|
||||
Context unsafe;
|
||||
unsafe.fetch_store.fitted = TowerStore::Unsafe;
|
||||
unsafe.begin(0x55, send, nullptr);
|
||||
assert(!unsafe.prepareTowerStorage());
|
||||
assert(!unsafe.manager.full && !unsafe.manager.bootloader && !unsafe.manager.archive);
|
||||
assert(!unsafe.self_serve_supported && unsafe.manager.encoder == nullptr);
|
||||
Context incompatible;
|
||||
incompatible.fetch_store.fitted = TowerStore::Sd;
|
||||
incompatible.fetch_store.usable = false;
|
||||
incompatible.begin(0x55, send, nullptr);
|
||||
assert(!incompatible.prepareTowerStorage());
|
||||
assert(!incompatible.manager.full && !incompatible.manager.bootloader);
|
||||
assert(!incompatible.self_serve_supported && incompatible.manager.encoder == nullptr);
|
||||
|
||||
current = SelfFwInfo();
|
||||
Context legacy;
|
||||
legacy.begin(0x55, send, nullptr, "fallback");
|
||||
assert(legacy.manager.target == 0x55 && legacy.manager.floor == 0);
|
||||
assert(strcmp(legacy.hw_id, "fallback") == 0 && legacy.fetch_store.probes == 0);
|
||||
}
|
||||
'''
|
||||
|
||||
HANDOFF_SETUP = r'''
|
||||
#include <cassert>
|
||||
#include <cstdint>
|
||||
#define OTA_TOWER_AUTO_STORE 1
|
||||
#define OTA_SD_STORE 1
|
||||
#define OTA_FLASH_STORE 1
|
||||
#define OTA_SD_BOOTLOADER_UPDATE 1
|
||||
static constexpr uint8_t GPREGRET2_OTA_STAGE_LEGACY = 0xD4;
|
||||
static constexpr uint8_t GPREGRET2_OTA_STAGE_EXPANDED = 0xED;
|
||||
static constexpr uint8_t GPREGRET2_OTA_STAGE_SD = 0x53;
|
||||
static constexpr uint8_t GPREGRET2_OTA_STAGE_HYBRID = 0xA6;
|
||||
static constexpr uint8_t GPREGRET2_OTA_STAGE_QSPI = 0x51;
|
||||
static constexpr uint8_t GPREGRET_OTA_APPLY = 0x6A;
|
||||
static constexpr uint8_t GPREGRET_OTA_BOOTLOADER_UPDATE = 0x6B;
|
||||
struct Store {
|
||||
bool hybrid = false, authorized = true;
|
||||
unsigned published = 0;
|
||||
bool is_hybrid() const { return hybrid; }
|
||||
bool publish_hybrid_handoff() { ++published; return authorized; }
|
||||
};
|
||||
static Store* g_nrf52_apply_store = nullptr;
|
||||
static uint32_t ceiling = 0xED000;
|
||||
static bool reset_cleared = true;
|
||||
static uint8_t request = 0, source = 0;
|
||||
static unsigned resets = 0;
|
||||
[[maybe_unused]] static uint32_t ota_nrf52_effective_stage_ceiling() { return ceiling; }
|
||||
[[maybe_unused]] static uint8_t mota_nrf52_flash_stage_handoff(uint32_t n) { return n == 0xED000 ? 0xED : 0xD4; }
|
||||
[[maybe_unused]] static bool ota_nrf52_clear_reset_reasons() { return reset_cleared; }
|
||||
[[maybe_unused]] static void ota_nrf52_set_reset_handoff(uint8_t r, uint8_t s) { request = r; source = s; }
|
||||
[[maybe_unused]] static void NVIC_SystemReset() { ++resets; }
|
||||
'''
|
||||
|
||||
HANDOFF_CASES = r'''
|
||||
int main() {
|
||||
ota_reboot_to_apply();
|
||||
assert(request == 0x6A && source == 0x53 && resets == 1);
|
||||
Store internal;
|
||||
g_nrf52_apply_store = &internal;
|
||||
ota_reboot_to_apply();
|
||||
assert(request == 0x6A && source == 0xED && resets == 2);
|
||||
ceiling = 0xD4000;
|
||||
ota_reboot_to_apply();
|
||||
assert(request == 0x6A && source == 0xD4 && resets == 3);
|
||||
g_nrf52_apply_store = nullptr;
|
||||
ota_reboot_to_apply();
|
||||
assert(request == 0x6A && source == 0x53 && resets == 4);
|
||||
// Shared legacy handling remains fail closed if a retained source cannot be
|
||||
// authorized. Tower's qualified application never enables this RAM store.
|
||||
internal.hybrid = true; internal.authorized = false;
|
||||
g_nrf52_apply_store = &internal;
|
||||
ota_reboot_to_apply();
|
||||
assert(request == 0 && source == 0xBD && resets == 5);
|
||||
internal.authorized = true; reset_cleared = false;
|
||||
ota_reboot_to_apply();
|
||||
assert(request == 0 && source == 0xBD && resets == 6 && internal.published == 1);
|
||||
}
|
||||
'''
|
||||
|
||||
|
||||
class TowerAutoIntegrationTest(unittest.TestCase):
|
||||
def compile_run(self, source, expected=True):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
path = Path(directory)
|
||||
cpp = path / "integration.cpp"
|
||||
cpp.write_text(source, encoding="ascii")
|
||||
executable = path / "integration"
|
||||
subprocess.run(["g++", "-std=c++17", "-Wall", "-Wextra", "-Werror",
|
||||
"-I", str(ROOT / "src"), str(cpp), "-o", str(executable)],
|
||||
check=True, timeout=30)
|
||||
result = subprocess.run([str(executable)], cwd=path, capture_output=True,
|
||||
text=True, timeout=10)
|
||||
self.assertEqual(result.returncode == 0, expected, result.stderr)
|
||||
if not expected:
|
||||
self.assertIn("Assertion", result.stderr)
|
||||
|
||||
def test_production_context_startup_and_deferred_storage_policy(self):
|
||||
context = (ROOT / "src/helpers/ota/OtaContext.h").read_text()
|
||||
methods = "\n".join(method(context, signature) for signature in (
|
||||
"OtaStoreSdNrf52& sdStagingStore()",
|
||||
"bool prepareTowerStorage()",
|
||||
"void begin(uint32_t target_id, OtaSend send, void* ctx",
|
||||
))
|
||||
source = CONTEXT_SETUP + methods + CONTEXT_CASES
|
||||
self.compile_run(source)
|
||||
# Negative controls prove the fixture catches the original startup
|
||||
# probe hazard and policy that accidentally advertises incompatible SD.
|
||||
eager = methods.replace("manager.begin(target_id, send, ctx);",
|
||||
"fetch_store.selectStorage(); manager.begin(target_id, send, ctx);")
|
||||
self.compile_run(CONTEXT_SETUP + eager + CONTEXT_CASES, expected=False)
|
||||
permissive = methods.replace("usable && fetch_store.usesExternal()",
|
||||
"fetch_store.usesExternal()")
|
||||
self.compile_run(CONTEXT_SETUP + permissive + CONTEXT_CASES, expected=False)
|
||||
# The old unconditional cleanup erased explicit internal diagnostic
|
||||
# offers on the very next maintenance loop, blocking base capture.
|
||||
unconditional_clear = methods.replace(
|
||||
" const bool was_self_serve_supported = self_serve_supported;\n", "").replace(
|
||||
"was_self_serve_supported && !self_serve_supported &&",
|
||||
"!self_serve_supported &&")
|
||||
self.assertNotEqual(unconditional_clear, methods)
|
||||
self.compile_run(CONTEXT_SETUP + unconditional_clear + CONTEXT_CASES,
|
||||
expected=False)
|
||||
|
||||
def test_production_reset_handoff_follows_approved_application_store(self):
|
||||
apply = (ROOT / "src/helpers/ota/OtaApply.cpp").read_text()
|
||||
production = method(apply, "void ota_reboot_to_apply() { // public:")
|
||||
self.compile_run(HANDOFF_SETUP + production + HANDOFF_CASES)
|
||||
old_dispatch = production.replace(
|
||||
"#if defined(OTA_RAK_AUTO_STORE) || defined(OTA_TOWER_AUTO_STORE)",
|
||||
"#if defined(OTA_RAK_AUTO_STORE)", 1)
|
||||
# Removing Tower from adaptive dispatch must break the runtime fixture;
|
||||
# it would always request SD even after internal-flash approval.
|
||||
self.compile_run(HANDOFF_SETUP + old_dispatch + HANDOFF_CASES, expected=False)
|
||||
|
||||
def test_selection_precedes_live_resume_and_cli_codec_checks(self):
|
||||
mesh = (ROOT / "src/Mesh.cpp").read_text()
|
||||
maintenance = method(mesh, "void __attribute__((noinline)) Mesh::serviceLoopMaintenance()")
|
||||
self.assertLess(maintenance.index("prepareTowerStorage()"),
|
||||
maintenance.index("resumeStaged(nullptr)"))
|
||||
cli = (ROOT / "src/helpers/ota/OtaCli.cpp").read_text()
|
||||
self.assertLess(cli.index("c.prepareTowerStorage()"), cli.index("c.manager.codecOk(selcodec)"))
|
||||
context = (ROOT / "src/helpers/ota/OtaContext.h").read_text()
|
||||
boot_apply = method(context, "bool apply_fetched_bootloader(")
|
||||
self.assertIn("if (!fetch_store.usesExternal())", boot_apply)
|
||||
self.assertIn("fetch_store.sdStore(), allow", boot_apply)
|
||||
apply = (ROOT / "src/helpers/ota/OtaApply.cpp").read_text()
|
||||
sd_apply = method(apply, "bool ota_apply_mota_nrf52(OtaStoreSdNrf52& store")
|
||||
self.assertLess(sd_apply.index("g_nrf52_apply_store = nullptr"),
|
||||
sd_apply.index("ota_apply_mota_nrf52_external"))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,440 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Run the MeshTower selector with peripheral stores and the real manifest parser."""
|
||||
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
OTA = ROOT / "src/helpers/ota"
|
||||
FLAGS = ["-DNRF52_PLATFORM=1", "-DHELTEC_TOWER_V2_SDCARD=1",
|
||||
"-DOTA_SD_STORE=1", "-DOTA_FLASH_STORE=1", "-DOTA_TOWER_AUTO_STORE=1"]
|
||||
|
||||
CAPS = r'''
|
||||
#pragma once
|
||||
#include <stdint.h>
|
||||
namespace mesh { namespace ota {
|
||||
static const uint8_t OTA_BL_STORAGE_SD = 1;
|
||||
static const uint8_t OTA_BL_STORAGE_STAGE_CEILING = 2;
|
||||
struct OtaBlCaps {
|
||||
bool present = false;
|
||||
uint16_t apply_abi = 3, codec_mask = 5;
|
||||
uint8_t storage_flags = 9, optional_app_storage = 2;
|
||||
};
|
||||
extern OtaBlCaps installed;
|
||||
extern int cap_reads;
|
||||
inline OtaBlCaps ota_bootloader_app_caps() { ++cap_reads; return installed; }
|
||||
} }
|
||||
'''
|
||||
|
||||
STORES = r'''
|
||||
#pragma once
|
||||
#include "OtaStore.h"
|
||||
#include <string.h>
|
||||
namespace mesh {
|
||||
class MainBoard {};
|
||||
namespace ota {
|
||||
struct Medium {
|
||||
int constructors = 0, destructors = 0, probes = 0;
|
||||
int begin_calls = 0, plan_calls = 0, read_calls = 0, write_calls = 0;
|
||||
int clear_calls = 0, discard_calls = 0, reopen_calls = 0;
|
||||
int meta_calls = 0, finalize_calls = 0, checkpoints = 0;
|
||||
int format_calls = 0, erase_calls = 0, space_calls = 0, list_calls = 0;
|
||||
bool present = true, mountable = true, begin_ok = true, layout_ok = true;
|
||||
bool io_ok = true, discard_ok = true, staged = false;
|
||||
uint32_t total = 0, last_target = 0;
|
||||
const uint8_t* last_mid = nullptr;
|
||||
uint8_t bytes[512] = {0};
|
||||
};
|
||||
extern Medium sd_medium, flash_medium;
|
||||
extern int auth_clears;
|
||||
class FakeStore : public OtaStore {
|
||||
protected:
|
||||
Medium& media;
|
||||
uint32_t total = 0;
|
||||
public:
|
||||
explicit FakeStore(Medium& m) : media(m) { ++media.constructors; }
|
||||
~FakeStore() override { ++media.destructors; }
|
||||
bool begin(uint32_t n) override {
|
||||
++media.begin_calls;
|
||||
total = 0;
|
||||
if (!media.present || !media.begin_ok) return false;
|
||||
total = media.total = n; media.staged = true; return true;
|
||||
}
|
||||
bool write(uint32_t p, const uint8_t* d, uint32_t n) override {
|
||||
++media.write_calls;
|
||||
if (!media.present || !media.io_ok || p + n > total || p + n > sizeof(media.bytes)) return false;
|
||||
memcpy(media.bytes + p, d, n); return true;
|
||||
}
|
||||
bool read(uint32_t p, uint8_t* d, uint32_t n) const override {
|
||||
++media.read_calls;
|
||||
if (!media.present || !media.io_ok || p + n > total || p + n > sizeof(media.bytes)) return false;
|
||||
memcpy(d, media.bytes + p, n); return true;
|
||||
}
|
||||
uint32_t capacity() const override { return media.present ? 8192u : 0u; }
|
||||
uint32_t staged_size() const override { return total; }
|
||||
void clear() override { ++media.clear_calls; total = 0; }
|
||||
bool discard() override {
|
||||
++media.discard_calls; total = 0;
|
||||
if (!media.present || !media.discard_ok) return false;
|
||||
media.staged = false; media.total = 0; return true;
|
||||
}
|
||||
bool set_meta_size(uint32_t) override { ++media.meta_calls; return media.io_ok; }
|
||||
bool finalize() override { ++media.finalize_calls; return media.present && media.io_ok; }
|
||||
void checkpoint() override { ++media.checkpoints; }
|
||||
bool reopen() override {
|
||||
++media.reopen_calls;
|
||||
total = media.present && media.staged ? media.total : 0;
|
||||
return total != 0;
|
||||
}
|
||||
bool reopenFor(const uint8_t* mid, uint32_t target) override {
|
||||
media.last_mid = mid; media.last_target = target; return reopen();
|
||||
}
|
||||
bool plan_layout(bool, uint32_t, uint32_t, uint32_t, bool) override {
|
||||
++media.plan_calls; return media.layout_ok;
|
||||
}
|
||||
};
|
||||
class OtaStoreSdNrf52 : public FakeStore {
|
||||
public:
|
||||
OtaStoreSdNrf52() : FakeStore(sd_medium) { ++auth_clears; }
|
||||
bool probeMedia() { ++media.probes; return media.present && media.mountable; }
|
||||
void clear() override { ++media.clear_calls; total = 0; media.staged = false; }
|
||||
const char* last_error() const { return "SD peripheral error"; }
|
||||
bool formatCard(MainBoard&) { ++media.format_calls; return media.present; }
|
||||
bool eraseCard(MainBoard&) { ++media.erase_calls; return media.present; }
|
||||
bool getSpace(MainBoard&, uint64_t& used, uint64_t& free) {
|
||||
++media.space_calls; used = 1; free = 2; return media.present;
|
||||
}
|
||||
bool listFiles(MainBoard&, uint16_t, char*, size_t) { ++media.list_calls; return media.present; }
|
||||
};
|
||||
class OtaStoreFlashNrf52 : public FakeStore {
|
||||
public:
|
||||
OtaStoreFlashNrf52() : FakeStore(flash_medium) { ++auth_clears; }
|
||||
};
|
||||
} }
|
||||
'''
|
||||
|
||||
DRIVER = r'''
|
||||
#include "OtaStoreTowerNrf52.h"
|
||||
#include "OtaByteIO.h"
|
||||
#include <assert.h>
|
||||
#include <string.h>
|
||||
using namespace mesh::ota;
|
||||
namespace mesh { namespace ota {
|
||||
OtaBlCaps installed;
|
||||
Medium sd_medium, flash_medium;
|
||||
int cap_reads = 0, auth_clears = 0;
|
||||
} }
|
||||
|
||||
static void defaults() {
|
||||
installed.present = true;
|
||||
installed.storage_flags = 9;
|
||||
installed.optional_app_storage = 2;
|
||||
}
|
||||
static void manifest(Medium& m, uint8_t flags = 0) {
|
||||
m.staged = true;
|
||||
memset(m.bytes, 0, sizeof(m.bytes));
|
||||
uint8_t* p = m.bytes + 8;
|
||||
const bool boot = flags & MFLAG_BOOTLOADER;
|
||||
p[0] = boot ? MOTA_BOOT_FORMAT_VER : MOTA_APP_FORMAT_VER;
|
||||
p[1] = flags; p[2] = HASH_ALGO_SHA256;
|
||||
wr_u32le(p + 3, 11); wr_u32le(p + 7, 1);
|
||||
wr_u32le(p + 11, boot ? 0xA000u : 1024u);
|
||||
wr_u32le(p + 15, boot ? 0xA000u : 64u);
|
||||
p[19] = 10;
|
||||
p[20] = 1; p[21] = 2; p[22] = 3; p[23] = 4;
|
||||
p[56] = flags & MFLAG_FULL ? CODEC_FULL : CODEC_DETOOLS_INPLACE;
|
||||
m.total = boot ? 41330u : 278u;
|
||||
}
|
||||
static void startup() {
|
||||
OtaStoreTowerNrf52 store;
|
||||
assert(sd_medium.constructors == 1 && flash_medium.constructors == 0 && auth_clears == 1);
|
||||
OtaStoreSdNrf52* owner = &store.sdStore();
|
||||
assert(owner == &store.externalStore());
|
||||
assert(!store.usesExternalStore() && !store.usesExternal() && !store.usesInternal());
|
||||
assert(!store.compatible() && store.capacity() == 0 && store.staged_size() == 0);
|
||||
uint8_t byte = 0;
|
||||
assert(!store.read(0, &byte, 1) && !store.write(0, &byte, 1));
|
||||
assert(!store.set_meta_size(1) && !store.finalize());
|
||||
store.checkpoint(); store.clear(); store.resetSelection();
|
||||
assert(owner == &store.sdStore());
|
||||
assert(sd_medium.probes == 0 && cap_reads == 0 && flash_medium.constructors == 0);
|
||||
assert(sd_medium.clear_calls == 0 && sd_medium.reopen_calls == 0);
|
||||
}
|
||||
static void primary() {
|
||||
defaults(); OtaStoreTowerNrf52 store;
|
||||
assert(store.selectStorage() && store.usesExternalStore() && store.compatible());
|
||||
assert(sd_medium.probes == 1 && sd_medium.reopen_calls == 0 && flash_medium.constructors == 0);
|
||||
assert(store.plan_layout(true, 1024, 209, 64, false));
|
||||
assert(store.begin(278));
|
||||
uint8_t data[4] = {1, 2, 3, 4}, got[4] = {0};
|
||||
assert(store.write(0, data, 4) && store.read(0, got, 4) && memcmp(data, got, 4) == 0);
|
||||
assert(store.set_meta_size(16) && store.finalize()); store.checkpoint();
|
||||
assert(store.staged_size() == 278 && store.capacity() == 8192);
|
||||
assert(store.selectStorage() && sd_medium.probes == 1 && cap_reads == 1);
|
||||
assert(sd_medium.begin_calls == 1 && sd_medium.meta_calls == 1 && sd_medium.finalize_calls == 1);
|
||||
assert(sd_medium.checkpoints == 1 && flash_medium.begin_calls == 0 && auth_clears == 1);
|
||||
assert(store.plan_layout(true, 0xA000, 365, 0xA000, true));
|
||||
}
|
||||
static void fallback(bool unmountable) {
|
||||
defaults(); sd_medium.present = unmountable; sd_medium.mountable = false;
|
||||
OtaStoreTowerNrf52 store;
|
||||
assert(store.selectStorage() && store.usesInternal() && !store.usesExternal());
|
||||
assert(flash_medium.constructors == 1 && auth_clears == 2);
|
||||
assert(!store.begin(278) && flash_medium.begin_calls == 0);
|
||||
assert(!store.plan_layout(true, 1024, 209, 64, false));
|
||||
assert(!store.begin(278) && flash_medium.begin_calls == 0);
|
||||
assert(!store.plan_layout(true, 0xA000, 365, 0xA000, true));
|
||||
assert(!store.begin(41330) && flash_medium.begin_calls == 0);
|
||||
assert(store.plan_layout(false, 1024, 209, 64, false) && store.begin(278));
|
||||
assert(flash_medium.plan_calls == 1 && flash_medium.begin_calls == 1);
|
||||
uint8_t data = 7, got = 0;
|
||||
assert(store.write(0, &data, 1) && store.read(0, &got, 1) && got == data);
|
||||
assert(store.set_meta_size(16) && store.finalize()); store.checkpoint();
|
||||
sd_medium.present = sd_medium.mountable = true;
|
||||
assert(store.selectStorage() && store.usesInternal() && sd_medium.probes == 1);
|
||||
assert(sd_medium.begin_calls == 0 && sd_medium.plan_calls == 0);
|
||||
store.clear();
|
||||
assert(store.usesInternal() && !store.begin(278) && flash_medium.begin_calls == 1);
|
||||
assert(store.plan_layout(false, 1024, 209, 64, false) && store.begin(278));
|
||||
}
|
||||
static void old_or_unqualified() {
|
||||
defaults(); sd_medium.present = false;
|
||||
for (uint8_t option : {0u, 1u, 4u, 6u}) {
|
||||
installed.optional_app_storage = option;
|
||||
OtaStoreTowerNrf52 store;
|
||||
assert(!store.selectStorage() && !store.usesInternal() && !store.usesExternal());
|
||||
assert(!store.begin(278) && store.capacity() == 0);
|
||||
}
|
||||
installed.optional_app_storage = 2; installed.storage_flags = 2;
|
||||
{ OtaStoreTowerNrf52 store; assert(!store.selectStorage()); }
|
||||
installed.storage_flags = 9; installed.present = false;
|
||||
{ OtaStoreTowerNrf52 store; assert(!store.selectStorage()); }
|
||||
assert(flash_medium.constructors == 0 && flash_medium.begin_calls == 0);
|
||||
installed.present = true; installed.optional_app_storage = 0; sd_medium.present = true;
|
||||
{ OtaStoreTowerNrf52 store; assert(store.selectStorage() && store.usesExternal()); }
|
||||
installed.present = false;
|
||||
{ OtaStoreTowerNrf52 store;
|
||||
assert(!store.selectStorage() && store.usesExternal() && !store.compatible());
|
||||
assert(!store.begin(278)); }
|
||||
}
|
||||
static void failures() {
|
||||
defaults(); OtaStoreTowerNrf52 store;
|
||||
assert(store.selectStorage());
|
||||
sd_medium.layout_ok = false;
|
||||
assert(!store.plan_layout(false, 1024, 209, 64, false) && !store.begin(278));
|
||||
assert(sd_medium.begin_calls == 0 && store.usesExternal() && flash_medium.constructors == 0);
|
||||
sd_medium.layout_ok = true; sd_medium.begin_ok = false;
|
||||
assert(store.plan_layout(false, 1024, 209, 64, false) && !store.begin(278));
|
||||
assert(sd_medium.begin_calls == 1 && flash_medium.constructors == 0);
|
||||
sd_medium.begin_ok = true; assert(store.begin(278));
|
||||
sd_medium.present = false; uint8_t byte = 0;
|
||||
assert(!store.write(0, &byte, 1) && !store.read(0, &byte, 1) && !store.finalize());
|
||||
assert(store.usesExternal() && store.selectStorage() && sd_medium.probes == 1);
|
||||
assert(flash_medium.constructors == 0 && !store.discard());
|
||||
store.resetSelection();
|
||||
assert(store.selectStorage() && store.usesInternal() && flash_medium.constructors == 1);
|
||||
}
|
||||
static void resume(bool internal) {
|
||||
defaults(); sd_medium.present = !internal;
|
||||
Medium& m = internal ? flash_medium : sd_medium;
|
||||
manifest(m);
|
||||
OtaStoreTowerNrf52 store;
|
||||
uint8_t good[4] = {1, 2, 3, 4}, wrong[4] = {9, 9, 9, 9};
|
||||
assert(!store.reopenFor(wrong, 11) && store.staged_size() == 0);
|
||||
assert(m.staged && m.clear_calls == 0 && m.discard_calls == 0);
|
||||
assert(!store.reopenFor(nullptr, 22) && store.staged_size() == 0);
|
||||
assert(store.reopenFor(good, 11) && store.staged_size() == m.total);
|
||||
if (internal) assert(m.last_mid == good && m.last_target == 11);
|
||||
assert(store.reopen() && store.staged_size() == m.total);
|
||||
manifest(m, MFLAG_FULL);
|
||||
assert(store.reopen() == !internal);
|
||||
manifest(m, MFLAG_FULL | MFLAG_SIGNED | MFLAG_BOOTLOADER);
|
||||
assert(store.reopen() == !internal);
|
||||
m.bytes[8] = 99;
|
||||
assert(!store.reopen());
|
||||
assert(m.staged && m.clear_calls == 0 && m.discard_calls == 0);
|
||||
assert(sd_medium.probes == 1);
|
||||
}
|
||||
static void cancellation() {
|
||||
defaults(); sd_medium.present = false;
|
||||
OtaStoreTowerNrf52 store; OtaStoreSdNrf52* owner = &store.sdStore();
|
||||
assert(store.plan_layout(false, 1024, 209, 64, false) && store.begin(278));
|
||||
store.clear(); assert(store.staged_size() == 0 && flash_medium.staged);
|
||||
manifest(flash_medium); assert(store.reopen());
|
||||
flash_medium.discard_ok = false; assert(!store.discard() && flash_medium.staged);
|
||||
flash_medium.discard_ok = true; assert(store.discard() && !flash_medium.staged);
|
||||
sd_medium.present = true; store.resetSelection();
|
||||
assert(flash_medium.destructors == 1 && owner == &store.sdStore());
|
||||
assert(store.capacity() == 0 && store.selectStorage() && store.usesExternal());
|
||||
assert(store.begin(278)); store.clear();
|
||||
assert(store.usesExternal() && !sd_medium.staged && sd_medium.clear_calls == 1);
|
||||
assert(sd_medium.probes == 2);
|
||||
}
|
||||
static void management() {
|
||||
defaults(); sd_medium.present = false; OtaStoreTowerNrf52 store;
|
||||
assert(store.selectStorage() && store.usesInternal());
|
||||
mesh::MainBoard board; uint64_t used = 0, free = 0; char out[20];
|
||||
assert(!store.formatCard(board) && !store.eraseCard(board));
|
||||
assert(!store.getSpace(board, used, free) && !store.listFiles(board, 0, out, sizeof(out)));
|
||||
assert(sd_medium.format_calls == 1 && sd_medium.erase_calls == 1);
|
||||
assert(sd_medium.space_calls == 1 && sd_medium.list_calls == 1);
|
||||
sd_medium.present = true;
|
||||
assert(store.formatCard(board) && store.eraseCard(board));
|
||||
assert(store.getSpace(board, used, free) && used == 1 && free == 2);
|
||||
assert(store.listFiles(board, 1, out, sizeof(out)) && store.usesInternal());
|
||||
assert(flash_medium.begin_calls == 0 && sd_medium.probes == 1);
|
||||
}
|
||||
int main(int argc, char** argv) {
|
||||
assert(argc == 2);
|
||||
if (!strcmp(argv[1], "startup")) startup();
|
||||
else if (!strcmp(argv[1], "primary")) primary();
|
||||
else if (!strcmp(argv[1], "missing")) fallback(false);
|
||||
else if (!strcmp(argv[1], "unmountable")) fallback(true);
|
||||
else if (!strcmp(argv[1], "legacy")) old_or_unqualified();
|
||||
else if (!strcmp(argv[1], "failures")) failures();
|
||||
else if (!strcmp(argv[1], "resume-sd")) resume(false);
|
||||
else if (!strcmp(argv[1], "resume-internal")) resume(true);
|
||||
else if (!strcmp(argv[1], "cancel")) cancellation();
|
||||
else if (!strcmp(argv[1], "management")) management();
|
||||
else return 2;
|
||||
}
|
||||
'''
|
||||
|
||||
PROBE = r'''
|
||||
#include "OtaStoreSdNrf52.h"
|
||||
#include <assert.h>
|
||||
#include <stdlib.h>
|
||||
using namespace mesh::ota;
|
||||
static bool mountable;
|
||||
static unsigned mounts, capacity_calls;
|
||||
static uint32_t sectors;
|
||||
namespace mesh { namespace ota {
|
||||
OtaStoreSdNrf52::OtaStoreSdNrf52() {}
|
||||
OtaStoreSdNrf52::~OtaStoreSdNrf52() {}
|
||||
bool OtaStoreSdNrf52::mount() { ++mounts; return mountable; }
|
||||
uint32_t OtaStoreSdNrf52::capacity() const { ++capacity_calls; return sectors * 512u; }
|
||||
bool OtaStoreSdNrf52::begin(uint32_t) { abort(); }
|
||||
bool OtaStoreSdNrf52::write(uint32_t, const uint8_t*, uint32_t) { abort(); }
|
||||
bool OtaStoreSdNrf52::read(uint32_t, uint8_t*, uint32_t) const { abort(); }
|
||||
void OtaStoreSdNrf52::clear() { abort(); }
|
||||
bool OtaStoreSdNrf52::discard() { abort(); }
|
||||
bool OtaStoreSdNrf52::set_meta_size(uint32_t) { abort(); }
|
||||
bool OtaStoreSdNrf52::finalize() { abort(); }
|
||||
void OtaStoreSdNrf52::checkpoint() { abort(); }
|
||||
bool OtaStoreSdNrf52::reopen() { abort(); }
|
||||
bool OtaStoreSdNrf52::plan_layout(bool, uint32_t, uint32_t, uint32_t, bool) { abort(); }
|
||||
} }
|
||||
int main() {
|
||||
OtaStoreSdNrf52 store;
|
||||
assert(mounts == 0 && capacity_calls == 0);
|
||||
mountable = false; sectors = 10;
|
||||
assert(!store.probeMedia() && mounts == 1 && capacity_calls == 0);
|
||||
mountable = true; sectors = 0;
|
||||
assert(!store.probeMedia() && mounts == 2 && capacity_calls == 1);
|
||||
sectors = 10;
|
||||
assert(store.probeMedia() && mounts == 3 && capacity_calls == 2);
|
||||
}
|
||||
'''
|
||||
|
||||
|
||||
class TowerAutoStorageTest(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.compiler = shutil.which("c++")
|
||||
if not cls.compiler:
|
||||
raise unittest.SkipTest("C++ compiler unavailable")
|
||||
cls.temp = tempfile.TemporaryDirectory(prefix="tower-auto-storage-")
|
||||
cls.work = Path(cls.temp.name)
|
||||
for name in ("OtaStore.h", "OtaFormat.h", "MotaContainer.h", "OtaByteIO.h"):
|
||||
shutil.copyfile(OTA / name, cls.work / name)
|
||||
(cls.work / "OtaBlInfo.h").write_text(CAPS)
|
||||
(cls.work / "stores.h").write_text(STORES)
|
||||
for name in ("OtaStoreFlashNrf52.h", "OtaStoreSdNrf52.h"):
|
||||
(cls.work / name).write_text('#include "stores.h"\n')
|
||||
(cls.work / "Utils.h").write_text("""
|
||||
#pragma once
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
namespace mesh { class Utils { public:
|
||||
static void sha256(uint8_t*, size_t, const uint8_t*, int);
|
||||
static void sha256(uint8_t*, size_t, const uint8_t*, int, const uint8_t*, int);
|
||||
}; }
|
||||
""")
|
||||
(cls.work / "test.cpp").write_text('#include <initializer_list>\n' + DRIVER)
|
||||
cls.header = (OTA / "OtaStoreTowerNrf52.h").read_text()
|
||||
cls.exe = cls.compile(cls.header, "selector")
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls):
|
||||
cls.temp.cleanup()
|
||||
|
||||
@classmethod
|
||||
def compile(cls, header, name):
|
||||
(cls.work / "OtaStoreTowerNrf52.h").write_text(header)
|
||||
exe = cls.work / name
|
||||
subprocess.run([cls.compiler, "-std=c++11", "-Wall", "-Wextra", "-Werror",
|
||||
"-ffunction-sections", "-fdata-sections", "-Wl,--gc-sections",
|
||||
*FLAGS, "-I", str(cls.work), "-I", str(OTA),
|
||||
str(cls.work / "test.cpp"), str(OTA / "MotaContainer.cpp"),
|
||||
"-o", str(exe)], check=True, capture_output=True, text=True)
|
||||
return exe
|
||||
|
||||
def test_selection_and_transfer_boundaries(self):
|
||||
for scenario in ("startup", "primary", "missing", "unmountable", "legacy",
|
||||
"failures", "resume-sd", "resume-internal", "cancel", "management"):
|
||||
with self.subTest(scenario=scenario):
|
||||
subprocess.run([str(self.exe), scenario], check=True, capture_output=True)
|
||||
|
||||
def test_exact_real_sd_probe_never_opens_or_removes_files(self):
|
||||
# Keep the source away from the selector's peripheral doubles so its
|
||||
# quoted include resolves to the real production SD header.
|
||||
probe_dir = self.work / "real-probe"
|
||||
probe_dir.mkdir()
|
||||
source = probe_dir / "probe.cpp"
|
||||
source.write_text(PROBE)
|
||||
exe = self.work / "probe"
|
||||
subprocess.run([self.compiler, "-std=c++11", "-Wall", "-Wextra", "-Werror",
|
||||
"-DNRF52_PLATFORM=1", "-DOTA_SD_STORE=1", "-I", str(OTA),
|
||||
str(source), "-o", str(exe)], check=True, capture_output=True, text=True)
|
||||
subprocess.run([str(exe)], check=True, capture_output=True)
|
||||
|
||||
def test_unsupported_recipe_cannot_enable_tower_selection(self):
|
||||
(self.work / "OtaStoreTowerNrf52.h").write_text(self.header)
|
||||
source = self.work / "guard.cpp"
|
||||
source.write_text('#include "OtaStoreTowerNrf52.h"\n')
|
||||
for missing in FLAGS[:-1]:
|
||||
with self.subTest(missing=missing):
|
||||
flags = [flag for flag in FLAGS if flag != missing]
|
||||
result = subprocess.run([self.compiler, "-std=c++11", "-fsyntax-only",
|
||||
*flags, "-I", str(self.work), str(source)],
|
||||
capture_output=True, text=True)
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertIn("requires the qualified nRF52 SD primary", result.stderr)
|
||||
|
||||
def test_negative_controls_expose_unsafe_selection_and_resume(self):
|
||||
mutations = [
|
||||
("startup-probe", "OtaStoreTowerNrf52() = default;",
|
||||
"OtaStoreTowerNrf52() { selectStorage(); }", "startup"),
|
||||
("legacy-fallback", "sd_profile && caps.optional_app_storage == OTA_BL_STORAGE_STAGE_CEILING",
|
||||
"sd_profile", "legacy"),
|
||||
("internal-full", "_mode == INTERNAL_MODE && (full || bootloader)",
|
||||
"false", "missing"),
|
||||
("missing-layout", "_mode == INTERNAL_MODE && !_layout_accepted",
|
||||
"false", "missing"),
|
||||
("resume-identity", "reopened && resumeMatches(mid, target)",
|
||||
"reopened", "resume-sd"),
|
||||
]
|
||||
for name, old, new, scenario in mutations:
|
||||
with self.subTest(mutation=name):
|
||||
self.assertEqual(self.header.count(old), 1)
|
||||
exe = self.compile(self.header.replace(old, new), name)
|
||||
result = subprocess.run([str(exe), scenario], capture_output=True)
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,335 @@
|
||||
"""Check actual nRF52 capability parsing for SD-primary Tower storage."""
|
||||
|
||||
from pathlib import Path
|
||||
import struct
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "tools/mota"))
|
||||
import motalib as ml
|
||||
from test_mota import _generic_bootloader_image, _rewrite_boot_image
|
||||
|
||||
|
||||
SOURCE = r'''
|
||||
#include <cassert>
|
||||
#include <cstring>
|
||||
#include <sys/mman.h>
|
||||
#include "helpers/ota/OtaBlInfo.h"
|
||||
|
||||
using namespace mesh::ota;
|
||||
|
||||
static const uint8_t bundle[32] = {
|
||||
'M','O','T','A','R','A','M','A',1,0,72,0,0,0,1,0,
|
||||
'M','O','T','A','S','T','O','R',1,0,16,0,2,0,0,0,
|
||||
};
|
||||
|
||||
static void imageFor(uint8_t* image, uint8_t primary, uint8_t optional) {
|
||||
memset(image, 0, 256);
|
||||
const uint8_t boot[16] = {
|
||||
'M','O','T','A','B','L','D','R',3,0,5,0,0,0,0,0,
|
||||
};
|
||||
memcpy(image, boot, sizeof(boot));
|
||||
image[12] = primary;
|
||||
if (optional) {
|
||||
memcpy(image + 32, bundle, sizeof(bundle));
|
||||
image[60] = optional;
|
||||
}
|
||||
}
|
||||
|
||||
static void expectViews(const uint8_t* image, uint8_t primary,
|
||||
uint8_t application, uint8_t optional) {
|
||||
const OtaBlCaps app = ota_bl_app_caps_scan(image, 256);
|
||||
assert(app.present && app.storage_flags == application);
|
||||
assert(app.optional_app_storage == optional);
|
||||
const OtaBlCaps update = ota_bl_update_caps_scan_aligned(image, 256, primary);
|
||||
assert(update.present && update.storage_flags == primary);
|
||||
assert(update.optional_app_storage == optional);
|
||||
}
|
||||
|
||||
int main() {
|
||||
uint8_t image[256];
|
||||
imageFor(image, 0x09, 0x02);
|
||||
expectViews(image, 0x09, 0x0B, 0x02);
|
||||
assert(ota_bootloader_supports_expanded_stage(ota_bl_app_caps_scan(image, 256)));
|
||||
assert(ota_nrf52_effective_stage_ceiling(ota_bl_app_caps_scan(image, 256)) == 0xED000);
|
||||
|
||||
// An ordinary SD loader remains valid for SD and privileged SD upgrades,
|
||||
// but its primary marker must never be mistaken for internal support.
|
||||
imageFor(image, 0x09, 0);
|
||||
expectViews(image, 0x09, 0x09, 0);
|
||||
assert(!ota_bootloader_supports_expanded_stage(ota_bl_app_caps_scan(image, 256)));
|
||||
assert(ota_nrf52_effective_stage_ceiling(ota_bl_app_caps_scan(image, 256)) == 0xD4000);
|
||||
|
||||
// RAK keeps the deployed internal privileged contract and optional NOR.
|
||||
imageFor(image, 0x0A, 0x14);
|
||||
expectViews(image, 0x0A, 0x1E, 0x14);
|
||||
imageFor(image, 0x0A, 0);
|
||||
expectViews(image, 0x0A, 0x0A, 0);
|
||||
|
||||
// Optional records are meaningful only under their exact primary profile.
|
||||
for (uint8_t primary : {uint8_t(0x09), uint8_t(0x0A), uint8_t(0x0E), uint8_t(0x1E)}) {
|
||||
for (uint8_t optional : {uint8_t(0x02), uint8_t(0x14)}) {
|
||||
imageFor(image, primary, optional);
|
||||
const bool qualified = (primary == 0x09 && optional == 2) ||
|
||||
(primary == 0x0A && optional == 0x14);
|
||||
expectViews(image, primary, qualified ? primary | optional : primary,
|
||||
qualified ? optional : 0);
|
||||
}
|
||||
}
|
||||
|
||||
// Every field of the frozen adjacent bundle is enforced. A malformed
|
||||
// optional declaration cannot remove the still-valid SD primary profile.
|
||||
for (unsigned byte = 0; byte < sizeof(bundle); ++byte) {
|
||||
imageFor(image, 0x09, 0x02);
|
||||
image[32 + byte] ^= 1;
|
||||
expectViews(image, 0x09, 0x09, 0);
|
||||
}
|
||||
imageFor(image, 0x09, 0x02);
|
||||
memcpy(image + 80, bundle, sizeof(bundle));
|
||||
expectViews(image, 0x09, 0x09, 0); // duplicate RAM and STOR
|
||||
imageFor(image, 0x09, 0x02);
|
||||
memcpy(image + 80, bundle, 16);
|
||||
expectViews(image, 0x09, 0x09, 0); // duplicate RAM alone
|
||||
imageFor(image, 0x09, 0x02);
|
||||
memcpy(image + 80, bundle + 16, 16);
|
||||
expectViews(image, 0x09, 0x09, 0); // duplicate STOR alone
|
||||
imageFor(image, 0x09, 0x02);
|
||||
memmove(image + 52, image + 48, 16);
|
||||
memset(image + 48, 0, 4);
|
||||
expectViews(image, 0x09, 0x09, 0); // separated records
|
||||
imageFor(image, 0x09, 0x02);
|
||||
memmove(image + 33, image + 32, 32);
|
||||
image[32] = 0;
|
||||
expectViews(image, 0x09, 0x09, 0); // byte-shifted bundle
|
||||
imageFor(image, 0x09, 0x02);
|
||||
assert(ota_bl_optional_app_storage(image, 63) == 0);
|
||||
assert(ota_bl_optional_app_storage(nullptr, 256) == 0);
|
||||
|
||||
// A second privileged marker must not be hidden by optional metadata.
|
||||
memcpy(image + 128, image, 16);
|
||||
assert(!ota_bl_update_caps_scan_aligned(image, 256, 0x09).present);
|
||||
|
||||
// Exercise the production memory-mapped entry points without defining the
|
||||
// retained-RAM application flag: this app retains the full SD RAM layout.
|
||||
void* flash = mmap(reinterpret_cast<void*>(uintptr_t(0xF4000)), 0xA000,
|
||||
PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED,
|
||||
-1, 0);
|
||||
assert(flash == reinterpret_cast<void*>(uintptr_t(0xF4000)));
|
||||
memset(flash, 0, 0xA000);
|
||||
#if defined(OTA_INTERNAL_BOOTLOADER_UPDATE)
|
||||
imageFor(static_cast<uint8_t*>(flash), 0x0A, 0x14);
|
||||
assert(ota_bootloader_update_storage_flags() == 0x0A);
|
||||
assert(ota_bootloader_app_caps().storage_flags == 0x1E);
|
||||
assert(ota_bootloader_update_caps().storage_flags == 0x0A);
|
||||
#else
|
||||
imageFor(static_cast<uint8_t*>(flash), 0x09, 0x02);
|
||||
assert(ota_bootloader_update_storage_flags() == 0x09);
|
||||
assert(ota_bootloader_app_caps().storage_flags == 0x0B);
|
||||
OtaBlCaps update = ota_bootloader_update_caps();
|
||||
assert(update.storage_flags == 0x09 && update.optional_app_storage == 2);
|
||||
assert(ota_bootloader_self_update_caps_valid(update));
|
||||
imageFor(static_cast<uint8_t*>(flash), 0x09, 0);
|
||||
update = ota_bootloader_update_caps();
|
||||
assert(update.storage_flags == 0x09 && update.optional_app_storage == 0);
|
||||
assert(ota_bootloader_self_update_caps_valid(update));
|
||||
#endif
|
||||
assert(!ota_bootloader_ram_caps().present);
|
||||
assert(munmap(flash, 0xA000) == 0);
|
||||
}
|
||||
'''
|
||||
|
||||
STREAM_SOURCE = r'''
|
||||
#include <cassert>
|
||||
#include <cstring>
|
||||
#include <fstream>
|
||||
#include <iterator>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include "helpers/ota/OtaBootloaderUpdate.h"
|
||||
using namespace mesh::ota;
|
||||
struct Store {
|
||||
std::vector<uint8_t> bytes;
|
||||
bool fail_read = false;
|
||||
bool read(uint32_t off, uint8_t* out, uint32_t len) {
|
||||
if (uint64_t(off) + len > bytes.size() || (fail_read && off == 37 + 512)) return false;
|
||||
memcpy(out, bytes.data() + off, len);
|
||||
return true;
|
||||
}
|
||||
};
|
||||
int main(int argc, char** argv) {
|
||||
assert(argc == 6);
|
||||
std::ifstream input(argv[1], std::ios::binary);
|
||||
Store store;
|
||||
store.bytes.resize(37, 0xA5);
|
||||
store.bytes.insert(store.bytes.end(), std::istreambuf_iterator<char>(input), {});
|
||||
assert(store.bytes.size() == 37 + OTA_BOOT_IMAGE_SIZE);
|
||||
store.fail_read = std::stoul(argv[5]) != 0;
|
||||
OtaBootloaderIdentity identity;
|
||||
OtaBootloaderCapsMarker caps;
|
||||
const bool actual = ota_bootloader_external_image_metadata(
|
||||
store, 37, uint8_t(std::stoul(argv[2])), identity, caps,
|
||||
uint8_t(std::stoul(argv[3])));
|
||||
assert(actual == (std::stoul(argv[4]) != 0));
|
||||
if (actual) {
|
||||
assert(identity.present && identity.crc_ok && identity.continuity_present);
|
||||
assert(identity.manifest_offset == OTA_BOOT_CANDIDATE_MANIFEST_OFFSET);
|
||||
assert(caps.storage_flags == std::stoul(argv[2]));
|
||||
}
|
||||
}
|
||||
'''
|
||||
|
||||
UTILS_DECLARATIONS = """#pragma once
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
namespace mesh { struct Utils {
|
||||
static void sha256(uint8_t*, size_t, const uint8_t*, int);
|
||||
static void sha256(uint8_t*, size_t, const uint8_t*, int, const uint8_t*, int);
|
||||
}; }
|
||||
"""
|
||||
|
||||
|
||||
class TowerBootloaderCapsTest(unittest.TestCase):
|
||||
def test_sd_primary_and_rak_capability_views(self):
|
||||
for profile in ("OTA_SD_BOOTLOADER_UPDATE", "OTA_INTERNAL_BOOTLOADER_UPDATE"):
|
||||
with self.subTest(profile=profile), tempfile.TemporaryDirectory() as directory:
|
||||
path = Path(directory)
|
||||
source = path / "caps.cpp"
|
||||
source.write_text("#include <initializer_list>\n" + SOURCE, encoding="ascii")
|
||||
executable = path / "caps"
|
||||
subprocess.run([
|
||||
"g++", "-std=c++17", "-Wall", "-Wextra", "-Werror",
|
||||
"-DNRF52_PLATFORM=1", f"-D{profile}=1",
|
||||
"-DMOTA_NRF52_TEST_LAYOUT_STAGE_CEILING=0xED000u",
|
||||
"-I", str(ROOT / "src"), str(source), "-o", str(executable),
|
||||
], check=True, timeout=30)
|
||||
subprocess.run([str(executable)], check=True, timeout=10)
|
||||
|
||||
def test_auto_storage_guard_allows_only_sd_primary_tower(self):
|
||||
required = ["NRF52_PLATFORM", "HELTEC_TOWER_V2_SDCARD", "OTA_SD_STORE",
|
||||
"OTA_FLASH_STORE", "OTA_SD_BOOTLOADER_UPDATE"]
|
||||
forbidden = ["OTA_QSPI_STORE", "QSPIFLASH", "OTA_RAK_AUTO_STORE",
|
||||
"OTA_INTERNAL_BOOTLOADER_UPDATE", "OTA_QSPI_BOOTLOADER_UPDATE",
|
||||
"OTA_HYBRID_RAM_STORE"]
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
path = Path(directory)
|
||||
(path / "Utils.h").write_text(UTILS_DECLARATIONS, encoding="ascii")
|
||||
source = path / "guard.cpp"
|
||||
source.write_text('#include "helpers/ota/OtaBootloaderUpdate.h"\n', encoding="ascii")
|
||||
cases = [(required + ["OTA_TOWER_AUTO_STORE"], True),
|
||||
([item for item in required if item != "OTA_FLASH_STORE"], True),
|
||||
(required, False)]
|
||||
cases += [([item for item in required if item != missing]
|
||||
+ ["OTA_TOWER_AUTO_STORE"], False) for missing in required]
|
||||
cases += [(required + ["OTA_TOWER_AUTO_STORE", item], False) for item in forbidden]
|
||||
for flags, expected in cases:
|
||||
with self.subTest(flags=flags):
|
||||
result = subprocess.run([
|
||||
"g++", "-std=c++17", "-fsyntax-only", "-I", str(path),
|
||||
"-I", str(ROOT / "src"), *[f"-D{flag}=1" for flag in flags],
|
||||
str(source),
|
||||
], capture_output=True, text=True, timeout=30)
|
||||
self.assertEqual(result.returncode == 0, expected, result.stderr)
|
||||
if not expected:
|
||||
self.assertIn("#error", result.stderr)
|
||||
|
||||
def test_streamed_successors_retain_unique_adjacent_optional_storage(self):
|
||||
base = _generic_bootloader_image(0x239A0071, "TOWER_V2_OTA", ml.BOOT_STORAGE_SD_UPDATE)
|
||||
image = self.with_optional(base, 2)
|
||||
ram, optional = image[0x90:0xA0], image[0xA0:0xB0]
|
||||
cases = [(base, 9, 0, True, False), (base, 9, 2, False, False),
|
||||
(image, 9, 2, True, False), (image, 9, 0, True, False),
|
||||
(image, 9, 0x14, False, False), (image, 9, 2, False, True)]
|
||||
for offset in (480, 496, 500, 508, 512, 1020):
|
||||
def move_pair(data, offset=offset):
|
||||
data[0x90:0xB0] = b"\xff" * 32
|
||||
data[offset:offset + 32] = ram + optional
|
||||
cases.append((_rewrite_boot_image(image, move_pair), 9, 2, True, False))
|
||||
mutations = [
|
||||
lambda data: data.__setitem__(slice(0x200, 0x210), ram),
|
||||
lambda data: data.__setitem__(slice(0x200, 0x210), optional),
|
||||
lambda data: data.__setitem__(slice(0x70, 0x80), optional),
|
||||
lambda data: data.__setitem__(0xAC, 0x14),
|
||||
lambda data: data.__setitem__(0xAD, 1),
|
||||
lambda data: data.__setitem__(0x98, 2),
|
||||
lambda data: data.__setitem__(slice(0x90, 0xA0), b"\xff" * 16),
|
||||
]
|
||||
for mutation in mutations:
|
||||
candidate = _rewrite_boot_image(image, mutation)
|
||||
cases += [(candidate, 9, 2, False, False), (candidate, 9, 0, True, False)]
|
||||
rak = self.with_optional(_generic_bootloader_image(), 0x14)
|
||||
cases += [(rak, 0x0A, 0x14, True, False), (rak, 0x0A, 2, False, False)]
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
path = Path(directory)
|
||||
(path / "Utils.h").write_text(UTILS_DECLARATIONS, encoding="ascii")
|
||||
source = path / "stream.cpp"
|
||||
source.write_text(STREAM_SOURCE, encoding="ascii")
|
||||
executable = path / "stream"
|
||||
subprocess.run([
|
||||
"g++", "-std=c++17", "-Wall", "-Wextra", "-Werror",
|
||||
"-I", str(path), "-I", str(ROOT / "src"), str(source),
|
||||
"-o", str(executable),
|
||||
], check=True, timeout=30)
|
||||
for index, (candidate, primary, required, expected, fail_read) in enumerate(cases):
|
||||
with self.subTest(case=index):
|
||||
payload = path / "image.bin"
|
||||
payload.write_bytes(candidate)
|
||||
subprocess.run([str(executable), str(payload), str(primary), str(required),
|
||||
str(int(expected)), str(int(fail_read))], check=True, timeout=10)
|
||||
|
||||
@staticmethod
|
||||
def with_optional(image, optional):
|
||||
def add_storage(data):
|
||||
struct.pack_into("<I", data, 0, 0x20030000)
|
||||
data[0x90:0xB0] = (b"MOTARAMA" + struct.pack("<HHI", 1, 72, 65536)
|
||||
+ b"MOTASTOR" + struct.pack("<HHB3x", 1, 16, optional))
|
||||
return _rewrite_boot_image(image, add_storage)
|
||||
|
||||
def test_python_admits_exact_tower_and_retains_rak_profiles(self):
|
||||
for board, name, primary, optional in (
|
||||
(0x239A0071, "TOWER_V2_OTA", ml.BOOT_STORAGE_SD_UPDATE, 2),
|
||||
(0x239A0029, "3401_DFU", ml.BOOT_STORAGE_INTERNAL_UPDATE, 0x14),
|
||||
(0x239A0029, "4631_DFU", ml.BOOT_STORAGE_INTERNAL_UPDATE, 0x14),
|
||||
):
|
||||
with self.subTest(name=name):
|
||||
base = _generic_bootloader_image(board, name, primary)
|
||||
self.assertEqual(ml.bootloader_optional_app_storage(base), 0)
|
||||
image = self.with_optional(base, optional)
|
||||
self.assertEqual(ml.validate_bootloader_image(image).device_name, name)
|
||||
self.assertEqual(ml.bootloader_caps_storage(image), primary)
|
||||
self.assertEqual(ml.bootloader_optional_app_storage(image), optional)
|
||||
|
||||
def test_python_rejects_corrupt_ambiguous_and_cross_profile_records(self):
|
||||
base = _generic_bootloader_image(0x239A0071, "TOWER_V2_OTA", ml.BOOT_STORAGE_SD_UPDATE)
|
||||
image = self.with_optional(base, 2)
|
||||
ram = image[0x90:0xA0]
|
||||
optional = image[0xA0:0xB0]
|
||||
mutations = [
|
||||
lambda data: data.__setitem__(0xAC, 3),
|
||||
lambda data: data.__setitem__(0xAD, 1),
|
||||
lambda data: data.__setitem__(slice(0xB0, 0xC0), optional),
|
||||
lambda data: data.__setitem__(slice(0xB0, 0xC0), ram),
|
||||
lambda data: data.__setitem__(slice(0x90, 0xA0), b"\xff" * 16),
|
||||
lambda data: struct.pack_into("<I", data, 0, 0x20040000),
|
||||
]
|
||||
for mutation in mutations:
|
||||
with self.subTest(mutation=mutations.index(mutation)):
|
||||
with self.assertRaises(ValueError):
|
||||
ml.validate_bootloader_image(_rewrite_boot_image(image, mutation))
|
||||
for board, name, primary, flags in (
|
||||
(0x239A0071, "TOWER_V2_OTA", ml.BOOT_STORAGE_SD_UPDATE, 0x14),
|
||||
(0x239A0029, "3401_DFU", ml.BOOT_STORAGE_INTERNAL_UPDATE, 2),
|
||||
(0x239A0029, "4631_DFU", ml.BOOT_STORAGE_INTERNAL_UPDATE, 2),
|
||||
(0x239A0071, "TOWER_V2_OTA", ml.BOOT_STORAGE_INTERNAL_UPDATE, 2),
|
||||
):
|
||||
with self.subTest(name=name, primary=primary, flags=flags):
|
||||
candidate = self.with_optional(_generic_bootloader_image(board, name, primary), flags)
|
||||
with self.assertRaises(ValueError):
|
||||
ml.validate_bootloader_image(candidate)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,179 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Canonical QSPI repeater promises must match the compiled USB logger."""
|
||||
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shlex
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
TARGETS = (
|
||||
"ikoka_handheld_nrf_e22_30dbm_repeater",
|
||||
"ikoka_nano_nrf_22dbm_repeater",
|
||||
"ikoka_nano_nrf_30dbm_repeater",
|
||||
"ikoka_nano_nrf_33dbm_repeater",
|
||||
"ikoka_stick_nrf_22dbm_repeater",
|
||||
"ikoka_stick_nrf_30dbm_repeater",
|
||||
"ikoka_stick_nrf_33dbm_repeater",
|
||||
"Xiao_nrf52_repeater",
|
||||
"solarxiao_30S_repeater",
|
||||
"solarxiao_33S_repeater",
|
||||
)
|
||||
|
||||
|
||||
def build_policy(target, *, disable_debug=0, packet="", debug="off",
|
||||
sensor_profile="", infix="", qspi=True):
|
||||
# Source only the production helpers. No PlatformIO command is necessary:
|
||||
# the three inventory facts below are the helper's board-selection input.
|
||||
command = r'''
|
||||
set -euo pipefail
|
||||
source build.sh
|
||||
env_name="$1"
|
||||
DISABLE_DEBUG="$2"
|
||||
PACKET_LOGGING_OVERRIDE="$3"
|
||||
MESHDEBUG_OVERRIDE="$4"
|
||||
NRF52_OTA_SENSOR_PROFILE="$5"
|
||||
FIRMWARE_FILENAME_INFIX="$6"
|
||||
PIO_ENV_PLATFORM_BY_NAME["$env_name"]=NRF52_PLATFORM
|
||||
PIO_ENV_BOARD_BY_NAME["$env_name"]=seeed-xiao-afruitnrf52-nrf52840
|
||||
PIO_ENV_QSPI_OTA_BY_NAME["$env_name"]="$7"
|
||||
BUILD_PROFILE_FOR_TARGET=standard
|
||||
PLATFORMIO_BUILD_FLAGS=""
|
||||
BUILD_APPLICATION_EXPECTATIONS=()
|
||||
disable_debug_flags "$env_name"
|
||||
apply_debug_overrides "$env_name"
|
||||
apply_mqtt_bridge_override "$env_name"
|
||||
disable_usb_logging_for_mqtt "$env_name"
|
||||
apply_merged_standard_usb_logging_profile "$env_name"
|
||||
declare_full_logging_application_contract "$env_name"
|
||||
printf '%s\n' "$PLATFORMIO_BUILD_FLAGS"
|
||||
printf '%s\n' "${BUILD_APPLICATION_EXPECTATIONS[@]}"
|
||||
'''
|
||||
environment = os.environ.copy()
|
||||
# Prevent a caller's global build options from turning a host policy test
|
||||
# into a different, unrelated profile.
|
||||
for name in ("MQTT_BRIDGE_OVERRIDE", "MQTT_DEBUG_OVERRIDE",
|
||||
"PLATFORMIO_BUILD_FLAGS", "MESHDEBUG_OVERRIDE",
|
||||
"PACKET_LOGGING_OVERRIDE", "DISABLE_DEBUG"):
|
||||
environment.pop(name, None)
|
||||
result = subprocess.run(
|
||||
["bash", "-c", command, "xiao-logging-policy", target,
|
||||
str(disable_debug), packet, debug, sensor_profile, infix,
|
||||
"1" if qspi else "0"],
|
||||
cwd=ROOT, env=environment, text=True, capture_output=True, check=True,
|
||||
)
|
||||
lines = result.stdout.splitlines()
|
||||
return shlex.split(lines[0]), lines[1:]
|
||||
|
||||
|
||||
class XiaoCanonicalLoggingTest(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.compiler = shutil.which("g++") or shutil.which("c++")
|
||||
if cls.compiler is None:
|
||||
raise unittest.SkipTest("C++ preprocessor required")
|
||||
cls.temporary = tempfile.TemporaryDirectory()
|
||||
cls.includes = Path(cls.temporary.name)
|
||||
(cls.includes / "Arduino.h").write_text("// No peripherals are needed.\n",
|
||||
encoding="ascii")
|
||||
cls.macros_cache = {}
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls):
|
||||
cls.temporary.cleanup()
|
||||
|
||||
def macros(self, flags):
|
||||
key = tuple(flags)
|
||||
if key in self.macros_cache:
|
||||
return self.macros_cache[key]
|
||||
# PlatformIO emits define flags before undefine flags. Reproduce that
|
||||
# ordering so a trailing -U defeats a superficially correct -D, just
|
||||
# as in the failed packaged Full/Reduced images.
|
||||
defines = [flag for flag in flags if flag.startswith("-D")]
|
||||
undefines = [flag for flag in flags if flag.startswith("-U")]
|
||||
result = subprocess.run(
|
||||
[self.compiler, "-x", "c++", "-E", "-dM", "-",
|
||||
"-DARDUINO=10819", "-DNRF52_PLATFORM=1", "-DUSE_TINYUSB=1",
|
||||
"-DMESH_PACKET_LOGGING=1", "-I", str(self.includes),
|
||||
"-I", str(ROOT / "src"), *defines, *undefines],
|
||||
input='#include <helpers/UsbLogging.h>\n', text=True,
|
||||
capture_output=True, check=True,
|
||||
)
|
||||
macros = {}
|
||||
for line in result.stdout.splitlines():
|
||||
if line.startswith("#define "):
|
||||
parts = line.split(maxsplit=2)
|
||||
macros[parts[1]] = parts[2] if len(parts) == 3 else ""
|
||||
self.macros_cache[key] = macros
|
||||
return macros
|
||||
|
||||
def assert_logger_contract(self, expectations):
|
||||
self.assertIn(
|
||||
"logging.usb.packets=%s: %s, len=%d (type=%d, route=%s, payload_len=%d)",
|
||||
expectations,
|
||||
)
|
||||
self.assertIn("logging.usb.control=OK - USB logging %s (saved)",
|
||||
expectations)
|
||||
|
||||
def test_canonical_sensor_pairs_keep_logger_with_verbose_debug_disabled(self):
|
||||
for target in TARGETS:
|
||||
for sensor_profile in ("", "full", "reduced"):
|
||||
for disable_debug, packet in ((0, ""), (1, ""), (1, "off"),
|
||||
(0, "off")):
|
||||
with self.subTest(target=target, sensors=sensor_profile,
|
||||
disable_debug=disable_debug, packet=packet):
|
||||
flags, expectations = build_policy(
|
||||
target, disable_debug=disable_debug, packet=packet,
|
||||
sensor_profile=sensor_profile,
|
||||
infix="sensor-ota" if sensor_profile else "",
|
||||
)
|
||||
macros = self.macros(flags)
|
||||
self.assertEqual(macros.get("MESH_PACKET_LOGGING"), "1")
|
||||
self.assertEqual(macros.get("MESH_USB_LOGGING_AVAILABLE"), "1")
|
||||
self.assertNotIn("MESH_DEBUG", macros)
|
||||
self.assert_logger_contract(expectations)
|
||||
|
||||
def test_canonical_debug_opt_in_keeps_the_same_packet_contract(self):
|
||||
for disable_debug in (0, 1):
|
||||
with self.subTest(disable_debug=disable_debug):
|
||||
flags, expectations = build_policy(
|
||||
TARGETS[0], disable_debug=disable_debug,
|
||||
debug="on", packet="on",
|
||||
)
|
||||
macros = self.macros(flags)
|
||||
self.assertEqual(macros.get("MESH_PACKET_LOGGING"), "1")
|
||||
self.assertEqual(macros.get("MESH_USB_LOGGING_AVAILABLE"), "1")
|
||||
if disable_debug:
|
||||
self.assertNotIn("MESH_DEBUG", macros)
|
||||
else:
|
||||
self.assertEqual(macros.get("MESH_DEBUG"), "1")
|
||||
self.assert_logger_contract(expectations)
|
||||
|
||||
def test_noncanonical_images_still_honor_explicit_logging_off(self):
|
||||
cases = (
|
||||
(TARGETS[0], {"infix": "custom"}),
|
||||
(TARGETS[0], {"qspi": False}),
|
||||
("Xiao_nrf52_room_server", {}),
|
||||
("Xiao_nrf52_repeater_bridge_rs232", {}),
|
||||
)
|
||||
for target, options in cases:
|
||||
for disable_debug, packet in ((1, ""), (0, "off"), (1, "off")):
|
||||
with self.subTest(target=target, options=options,
|
||||
disable_debug=disable_debug, packet=packet):
|
||||
flags, expectations = build_policy(
|
||||
target, disable_debug=disable_debug, packet=packet,
|
||||
**options,
|
||||
)
|
||||
macros = self.macros(flags)
|
||||
self.assertNotIn("MESH_PACKET_LOGGING", macros)
|
||||
self.assertEqual(macros.get("MESH_USB_LOGGING_AVAILABLE"), "0")
|
||||
self.assertFalse(any(item.startswith("logging.usb.")
|
||||
for item in expectations))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user