Integrate upstream fixes and paired nRF52 sensor OTA release profiles

This commit is contained in:
mikecarper committed 2026-10-02 17:52:12 -07:00
1 parent 8a69e73226
commit 29de7820e5
60 files changed
+4014 -842

No files matched your search

+15
View File
@@ -0,0 +1,15 @@
#pragma once
#include <stddef.h>
#include <stdint.h>
#include <math.h>
#include "variant.h"
#define HIGH 1
#define LOW 0
#define AR_INTERNAL_3_0 3
void digitalWrite(int pin, int level);
void analogReference(int reference);
void analogReadResolution(int bits);
int analogRead(int pin);
void delay(unsigned long milliseconds);
+2
View File
@@ -0,0 +1,2 @@
#pragma once
#include <stdint.h>
+56
View File
@@ -0,0 +1,56 @@
#include <Arduino.h>
#include <assert.h>
#include <vector>
#include <utility>
static std::vector<std::pair<int, int>> writes;
static int batteryAdc = 2253, temperatureAdc = 2048, lightAdc = 2048;
void digitalWrite(int pin, int level) { writes.emplace_back(pin, level); }
void analogReference(int reference) { assert(reference == AR_INTERNAL_3_0); }
void analogReadResolution(int bits) { assert(bits == 12); }
void delay(unsigned long milliseconds) { assert(milliseconds == 10); }
int analogRead(int pin) {
if (pin == BATTERY_PIN) return batteryAdc;
if (pin == TEMP_SENSOR) return temperatureAdc;
assert(pin == LUX_SENSOR);
return lightAdc;
}
#include "t1000e_sensors.cpp"
static void checkRailCycle() {
assert(writes.size() == 2);
assert(writes[0] == std::make_pair(38, HIGH));
assert(writes[1] == std::make_pair(38, LOW));
writes.clear();
}
int main() {
static_assert(PIN_3V3_EN == 38, "actual sensor rail must remain P1.06");
static_assert(TEMP_SENSOR == 31 && LUX_SENSOR == 29, "retain real ADC pins");
assert(isfinite(t1000e_get_temperature()));
checkRailCycle();
assert(t1000e_get_light() <= 100);
checkRailCycle();
assert(get_heater_temperature(3300, 0) == -30);
assert(get_heater_temperature(0, 1) == 105);
assert(get_heater_temperature(3300, 3300) == 105);
assert(get_heater_temperature(3300, 4000) == 105);
float previous = -30;
for (unsigned int sample = 0; sample <= 3300; ++sample) {
float temperature = get_heater_temperature(3300, sample);
assert(isfinite(temperature));
assert(temperature >= -30 && temperature <= 105 && temperature >= previous);
previous = temperature;
}
temperatureAdc = 0;
assert(t1000e_get_temperature() == -30);
checkRailCycle();
lightAdc = 0;
assert(t1000e_get_light() == 0);
checkRailCycle();
lightAdc = 4095;
assert(t1000e_get_light() == 100);
checkRailCycle();
}
+75 -33
View File
@@ -517,6 +517,44 @@ for t1000_env in \
)
done
# Every added observer recipe must become the feature base for its exact
# normal-role Full image, without changing that normal target's mOTA identity.
# Only same-partition hardware may advertise an automatic observer successor;
# the four legacy-slot targets must retain their partition-expansion handoff.
for observer_hardware in \
Ebyte_EoRa-S3 Heltec_E213 Heltec_E290 heltec_rc32 \
heltec_rc32_without_display Heltec_Wireless_Tracker Heltec_Wireless_Paper \
LilyGo_T3S3_sx1276 LilyGo_TETH_Elite_sx1262 meshnology_w12 Xiao_S3; do
for observer_role in repeater room_server; do
normal_target="${observer_hardware}_${observer_role}"
observer_target="${normal_target}_observer_mqtt"
if [ "$normal_target" = Ebyte_EoRa-S3_repeater ]; then
normal_target=Ebyte_EoRa-S3_Repeater
fi
is_mqtt_bridge_target "$observer_target" \
|| fail "$observer_target missing its MQTT feature base"
[ "${PIO_ENV_OTA_BY_NAME[$observer_target]:-0}" = 1 ] \
|| fail "$observer_target lost LoRa OTA"
[ "$(get_exact_identity_full_pio_env "$normal_target")" = "$observer_target" ] \
|| fail "$normal_target Full did not use its exact observer recipe"
case "$observer_hardware" in
Ebyte_EoRa-S3|LilyGo_T3S3_sx1276)
is_esp32_partition_migration_full_target "$normal_target" \
|| fail "$normal_target lost its partition-migration boundary"
if get_exact_identity_full_migration_target "$observer_target" >/dev/null; then
fail "$observer_target bypassed partition expansion with an OTA alias"
fi
;;
*)
is_esp32_full_only_bulk_target "$observer_target" \
|| fail "$observer_target lost same-partition Full policy"
[ "$(get_exact_identity_full_migration_target "$observer_target")" = "$normal_target" ] \
|| fail "$observer_target lost its exact same-partition successor"
;;
esac
done
done
# Arduino-ESP32 3.x OTA-only targets that have always declared larger A/B
# slots must be checked against their real partition table, not the legacy
# 1.25 MiB portable ceiling. Keep that exception OTA-only so ordinary RC32
@@ -928,42 +966,40 @@ BUILD_PROFILE_EXPLICIT=0
RESOLVED_BUILD_TARGETS=(nrf_repeater)
configure_effective_build_profile build-firmware >/dev/null
[ "${RESOLVED_BUILD_TARGETS[0]}" = \
nrf_repeater_lora_ota_no_external_sensors ] \
|| fail "nRF52 complete OTA pass did not select the OTA identity"
[ "$AUTO_COMPLETE_FIRST_PASS" = 1 ] \
|| fail "nRF52 complete first pass was not scheduled"
[ "$AUTO_PUBLISH_REDUCED_SECOND_PASS" = 1 ] \
|| fail "internal-flash nRF52 reduced second artifact was not scheduled"
nrf_repeater ] || fail "nRF52 profile configuration changed the selected target"
is_nrf52_sensor_ota_pair_target nrf_repeater \
|| fail "nRF52 repeater did not enter the required two-profile policy"
[ "$AUTO_COMPLETE_FIRST_PASS" = 0 ] \
|| fail "nRF52 retained the permissive size-fallback policy"
BUILD_PROFILE_OVERRIDE=auto
BUILD_PROFILE_EXPLICIT=0
RESOLVED_BUILD_TARGETS=(nrf_room_server)
configure_effective_build_profile build-firmware >/dev/null
[ "${RESOLVED_BUILD_TARGETS[0]}" = \
nrf_room_server_lora_ota_no_external_sensors ] \
|| fail "nRF52 room-server complete OTA pass did not select the OTA identity"
[ "$AUTO_COMPLETE_FIRST_PASS" = 1 ] \
|| fail "nRF52 room-server complete first pass was not scheduled"
[ "$AUTO_PUBLISH_REDUCED_SECOND_PASS" = 1 ] \
|| fail "internal-flash nRF52 room-server reduced second artifact was not scheduled"
nrf_room_server ] || fail "nRF52 room profile configuration changed the selected target"
is_nrf52_sensor_ota_pair_target nrf_room_server \
|| fail "nRF52 room server did not enter the required two-profile policy"
[ "$AUTO_COMPLETE_FIRST_PASS" = 0 ] \
|| fail "nRF52 room server retained the permissive size-fallback policy"
BUILD_PROFILE_OVERRIDE=auto
BUILD_PROFILE_EXPLICIT=0
RESOLVED_BUILD_TARGETS=(nrf_qspi_repeater)
configure_effective_build_profile build-firmware >/dev/null
[ "$AUTO_COMPLETE_FIRST_PASS" = 1 ] \
|| fail "external-storage nRF52 complete first pass was not scheduled"
[ "$AUTO_PUBLISH_REDUCED_SECOND_PASS" = 0 ] \
|| fail "external-storage nRF52 incorrectly scheduled a redundant artifact"
is_nrf52_sensor_ota_pair_target nrf_qspi_repeater \
|| fail "external-storage nRF52 repeater did not enter the pair policy"
[ "$AUTO_COMPLETE_FIRST_PASS" = 0 ] \
|| fail "external-storage nRF52 retained the old fallback policy"
BUILD_PROFILE_OVERRIDE=auto
BUILD_PROFILE_EXPLICIT=0
RESOLVED_BUILD_TARGETS=(nrf_qspi_room_server)
configure_effective_build_profile build-firmware >/dev/null
[ "$AUTO_COMPLETE_FIRST_PASS" = 1 ] \
|| fail "external-storage nRF52 room-server complete first pass was not scheduled"
[ "$AUTO_PUBLISH_REDUCED_SECOND_PASS" = 0 ] \
|| fail "external-storage nRF52 room-server incorrectly scheduled a redundant artifact"
is_nrf52_sensor_ota_pair_target nrf_qspi_room_server \
|| fail "external-storage nRF52 room server did not enter the pair policy"
[ "$AUTO_COMPLETE_FIRST_PASS" = 0 ] \
|| fail "external-storage nRF52 room server retained the old fallback policy"
BUILD_PROFILE_OVERRIDE=auto
BUILD_PROFILE_EXPLICIT=0
@@ -972,9 +1008,9 @@ configure_effective_build_profile build-firmware >/dev/null
[ "$BUILD_PROFILE_EFFECTIVE" = auto ] \
|| fail "nRF52 sensor did not retain its ordinary auto profile"
[ "$AUTO_COMPLETE_FIRST_PASS" = 0 ] \
|| fail "nRF52 sensor incorrectly scheduled OTA profile passes"
[ "$AUTO_PUBLISH_REDUCED_SECOND_PASS" = 0 ] \
|| fail "nRF52 sensor incorrectly scheduled two artifacts"
|| fail "nRF52 sensor retained the permissive size-fallback policy"
is_nrf52_sensor_ota_pair_target nrf_sensor \
|| fail "nRF52 sensor was excluded from the required pair policy"
# Ordinary USB-loggable roles compile their historical logging profile into
# the canonical artifact. LoRa OTA repeaters, KISS, and BLE keep their distinct
@@ -1105,6 +1141,7 @@ fi
# Option 3 must not publish an oversized standard ESP32 image, but its expected
# portable-slot status is satisfied by the mandatory expanded FULL pass.
saved_has_esp32_full_profile=$(declare -f has_esp32_full_profile)
saved_build_firmware=$(declare -f build_firmware)
has_esp32_full_profile() { [ "$1" = esp32_portable_overflow ]; }
build_firmware() { return 42; }
saved_output_dir=$OUTPUT_DIR
@@ -1124,6 +1161,7 @@ fi
OUTPUT_DIR=$saved_output_dir
unset DEFER_ESP32_PORTABLE_OVERFLOW_TO_FULL
eval "$saved_has_esp32_full_profile"
eval "$saved_build_firmware"
reduced_full_alias=Tbeam_SX1262_repeater_lora_ota_no_external_sensors
[ "$(get_esp32_full_profile_target "$reduced_full_alias")" = Tbeam_SX1262_repeater ] \
@@ -1132,8 +1170,9 @@ has_esp32_full_profile "$reduced_full_alias" \
|| fail "reduced ESP32 LoRa OTA alias lost its expanded FULL replacement"
calls=()
build_firmware() {
calls+=("$1:$BUILD_PROFILE_EFFECTIVE:$SKIP_DECLARED_REDUCTIONS:$FIRMWARE_OUTPUT_ENV_NAME")
saved_build_firmware_one_profile=$(declare -f build_firmware_one_profile)
build_firmware_one_profile() {
calls+=("$1:$BUILD_PROFILE_EFFECTIVE:$SKIP_DECLARED_REDUCTIONS:$NRF52_OTA_SENSOR_PROFILE")
if [ "${#calls[@]}" -eq 1 ]; then
return 42
fi
@@ -1146,15 +1185,17 @@ AUTO_REDUCED_FALLBACK_TARGET=nrf_repeater_lora_ota_no_external_sensors
BUILD_PROFILE_EFFECTIVE=auto
FIRMWARE_FILENAME_INFIX=""
SKIP_DECLARED_REDUCTIONS=0
run_auto_two_pass_build nrf_repeater_lora_ota_no_external_sensors >/dev/null
if run_auto_two_pass_build nrf_repeater_lora_ota_no_external_sensors >/dev/null 2>&1; then
fail "failed full nRF52 option was hidden by a successful reduced fallback"
fi
[ "${#calls[@]}" -eq 2 ] || fail "size overflow did not run exactly two passes"
[[ "${calls[0]}" == *:auto:1:* ]] || fail "pass 1 unexpectedly applied reductions"
[[ "${calls[1]}" == *:standard:0:* ]] || fail "pass 2 did not apply standard reductions"
[[ "${calls[1]}" == *:auto:0:reduced ]] || fail "pass 2 did not apply reduced sensor policy"
calls=()
build_firmware() {
calls+=("$1:$BUILD_PROFILE_EFFECTIVE:$SKIP_DECLARED_REDUCTIONS:$FIRMWARE_OUTPUT_ENV_NAME")
build_firmware_one_profile() {
calls+=("$1:$BUILD_PROFILE_EFFECTIVE:$SKIP_DECLARED_REDUCTIONS:$NRF52_OTA_SENSOR_PROFILE")
return 0
}
@@ -1167,10 +1208,11 @@ run_auto_two_pass_build nrf_repeater_lora_ota_no_external_sensors >/dev/null
[ "${#calls[@]}" -eq 2 ] \
|| fail "successful internal-flash nRF52 build did not publish both artifacts"
[[ "${calls[0]}" == *:auto:1:nrf_repeater ]] \
|| fail "complete nRF52 artifact did not use the feature-rich output name"
[[ "${calls[1]}" == *:standard:0: ]] \
|| fail "reduced nRF52 artifact did not use the reduced target name"
[[ "${calls[0]}" == *:auto:1:full ]] \
|| fail "complete nRF52 artifact did not declare the full sensor policy"
[[ "${calls[1]}" == *:auto:0:reduced ]] \
|| fail "reduced nRF52 artifact did not declare the reduced sensor policy"
eval "$saved_build_firmware_one_profile"
is_rak_i2c_voltage_monitor_ota_target \
RAK_3401_repeater_lora_ota_no_external_sensors \
+107
View File
@@ -7,11 +7,14 @@ import unittest
import subprocess
import sys
import hashlib
from unittest.mock import patch
import zipfile
ROOT = Path(__file__).resolve().parents[1]
spec = importlib.util.spec_from_file_location("package_cascade_release", ROOT / "scripts/package_cascade_release.py")
package = importlib.util.module_from_spec(spec)
spec.loader.exec_module(package)
from motalib import FwIdent, Nrf52Layout, ensure_endf, ensure_nrf52_layout, target_id_for_env
class ReleaseQualificationTest(unittest.TestCase):
@@ -62,6 +65,25 @@ class ReleaseQualificationTest(unittest.TestCase):
def test_usb_companion_is_accepted(self):
package.validate_manifest(self.manifest("test_companion_radio_usb", ota_update_verified=False))
def test_nrf52_sensor_profiles_require_actual_qualified_lora_receiver(self):
for role in ('repeater', 'room_server', 'sensor'):
for sensor in ('full', 'reduced'):
manifest = self.manifest('test_' + role, platform='NRF52_PLATFORM', build_profile='auto',
capabilities=['sensor.profile.' + sensor, 'ota.update.lora'], ota_update_methods=['lora'],
verification=[dict(capability='ota.update.lora', present=True, source='linked image')])
package.validate_manifest(manifest)
self.assertEqual(package.nrf52_sensor_profile(manifest), sensor)
self.assertIn('sensors + LoRa OTA', package.release_profile_label(manifest))
self.assertEqual(package.category({'manifest': manifest}), 'lora-ota')
for change in (dict(platform='ESP32_PLATFORM'), dict(target='test_companion_radio_full'),
dict(ota_update_methods=['bluetooth']), dict(verification=[]),
dict(verification=[dict(capability='ota.update.lora', present=True, source='filename')])):
with self.subTest(change=change), self.assertRaisesRegex(ValueError, 'qualified nRF52'):
package.validate_manifest({**manifest, **change})
with self.assertRaisesRegex(ValueError, 'ambiguous'):
package.validate_manifest({**manifest, 'capabilities': manifest['capabilities'] +
['sensor.profile.' + ('reduced' if sensor == 'full' else 'full')]})
def test_full_companion_requires_linked_source_implementation(self):
manifest = self.manifest("test_companion_radio_full", ota_update_verified=False)
with self.assertRaisesRegex(ValueError, "MOTA sending"):
@@ -74,6 +96,91 @@ class ReleaseQualificationTest(unittest.TestCase):
with self.assertRaisesRegex(ValueError, "MOTA sending"):
package.validate_manifest(manifest)
def sensor_record(self, directory, sensor, *, target='test_repeater', target_id=None,
hw_id='TEST', app_base=0x26000, flags=0x10, fw_version=0x01110107):
stem = target + '-' + sensor + '-ota-v1.17.1.7-dev-deadbeef'
application, _ = ensure_endf(ensure_nrf52_layout(b'OTA: status\0invalid in-place patch geometry\0',
Nrf52Layout(app_base, 0xED000, 0xED000, flags)),
FwIdent(fw_version, target_id_for_env(target) if target_id is None else target_id, hw_id))
path = directory / (stem + '.zip')
with zipfile.ZipFile(path, 'w') as archive:
archive.writestr('application.bin', application)
archive.writestr('manifest.json', json.dumps({'manifest': {
'application': {'bin_file': 'application.bin', 'dat_file': 'application.dat'}}}))
archive.writestr('application.dat', b'fixture init')
manifest = self.manifest(target, artifact_target=target + '-' + sensor + '-ota',
platform='NRF52_PLATFORM', build_profile='auto', capabilities=['sensor.profile.' + sensor,
'ota.update.lora'], ota_update_methods=['lora'],
verification=[dict(capability='ota.update.lora', present=True, source='linked image')],
ota_update_requirements={'lora': {'storage': 'internal_flash_and_retained_ram'}})
return {'manifest': manifest, 'files': [path]}
def test_sensor_pair_requires_one_of_each_with_matching_packaged_identity_and_layout(self):
with tempfile.TemporaryDirectory() as temp:
directory = Path(temp)
full = self.sensor_record(directory, 'full')
reduced = self.sensor_record(directory, 'reduced')
package.validate_nrf52_sensor_pairs([full, reduced])
for records in ([full], [reduced], [full, reduced, reduced]):
with self.subTest(count=len(records)), self.assertRaisesRegex(ValueError, 'exactly one full'):
package.validate_nrf52_sensor_pairs(records)
for change in (dict(target='another_repeater'), dict(target_id=456), dict(hw_id='OTHER'),
dict(app_base=0x27000), dict(flags=0x20), dict(fw_version=0x01110108)):
with self.subTest(change=change), self.assertRaisesRegex(ValueError, 'sensor pair'):
package.validate_nrf52_sensor_pairs([full, self.sensor_record(directory, 'reduced', **change)])
reduced = self.sensor_record(directory, 'reduced')
reduced['manifest']['ota_update_requirements']['lora']['storage'] = 'external_qspi'
with self.assertRaisesRegex(ValueError, 'storage layout'):
package.validate_nrf52_sensor_pairs([full, reduced])
with self.assertRaisesRegex(ValueError, 'target ID disagrees with logical target'):
package.validate_nrf52_sensor_pairs([self.sensor_record(directory, 'full', target_id=456),
self.sensor_record(directory, 'reduced', target_id=456)])
def test_sensor_pair_filename_does_not_replace_metadata_or_packaged_layout(self):
with tempfile.TemporaryDirectory() as temp:
directory = Path(temp)
full = self.sensor_record(directory, 'full')
missing = {**full, 'manifest': {**full['manifest'], 'capabilities': ['ota.update.lora']}}
with self.assertRaisesRegex(ValueError, 'lacks qualified metadata'):
package.validate_nrf52_sensor_pairs([missing])
missing['manifest']['artifact_target'] = 'test_repeater'
with self.assertRaisesRegex(ValueError, 'lacks qualified metadata'):
package.validate_nrf52_sensor_pairs([missing])
full['manifest']['artifact_target'] = 'test_repeater-reduced-ota'
with self.assertRaisesRegex(ValueError, 'disagrees with metadata'):
package.validate_nrf52_sensor_pairs([full])
full['manifest']['artifact_target'] = 'different_repeater-full-ota'
with self.assertRaisesRegex(ValueError, 'filename disagrees'):
package.validate_nrf52_sensor_pairs([full])
full = self.sensor_record(directory, 'full')
with zipfile.ZipFile(full['files'][0], 'w') as archive:
archive.writestr('application.bin', b'no EndF identity or layout')
archive.writestr('manifest.json', json.dumps({'manifest': {
'application': {'bin_file': 'application.bin'}}}))
with self.assertRaisesRegex(ValueError, 'valid packaged EndF'):
package.validate_nrf52_sensor_pairs([full])
# The new policy is not retroactively applied to historical files.
package.validate_nrf52_sensor_pairs([{'manifest': self.manifest('legacy_repeater',
platform='NRF52_PLATFORM'), 'files': [directory / 'legacy_repeater-ota-v1.0.zip']}])
def test_collect_artifacts_always_enforces_sensor_pair_even_for_partial_staging(self):
with tempfile.TemporaryDirectory() as temp:
directory = Path(temp)
record = self.sensor_record(directory, 'full')
stem = record['files'][0].stem
(directory / (stem + '.uf2')).write_bytes(b'validated fixture UF2')
(directory / (stem + '.capabilities.json')).write_text(json.dumps(record['manifest']))
memory = dict(passed=True, available_internal_bytes=100000,
required_heap_bytes=10000, elf_sha256='a' * 64)
with patch.object(package, 'check_uf2'), patch.object(package, 'validate_package', return_value=memory), \
patch.object(package, 'validate_artifact_notice', return_value=None):
with self.assertRaisesRegex(ValueError, 'exactly one full'):
package.collect_artifacts(directory, 'v1.17.1.7-dev-deadbeef')
reduced = self.sensor_record(directory, 'reduced')
other = reduced['files'][0].stem
(directory / (other + '.uf2')).write_bytes(b'validated fixture UF2')
(directory / (other + '.capabilities.json')).write_text(json.dumps(reduced['manifest']))
self.assertEqual(len(package.collect_artifacts(directory, 'v1.17.1.7-dev-deadbeef')), 2)
def test_missing_qualification_and_mixed_versions_are_rejected(self):
with tempfile.TemporaryDirectory() as temp:
directory = Path(temp)
+5 -4
View File
@@ -273,11 +273,12 @@ class FirmwareCapabilityCheckerTest(unittest.TestCase):
details = manifest["ota_update_requirements"]["lora"]
self.assertEqual(details["storage"], storage)
self.assertEqual(details["package_types"], types)
self.assertTrue(details["bootloader_release"].endswith("v0.11.0-OTAFIX2.4.11"))
self.assertTrue(any("hardware-pending" in note for note in details["notes"]))
if flags == 48:
self.assertIsNone(details["bootloader_release"])
self.assertIn("Merged RAK", details["bootloader"])
else:
self.assertTrue(details["bootloader_release"].endswith("0.11.0-OTAFIX2.4.6"))
self.assertIn("adaptive OTAFIX", details["bootloader"])
self.assertTrue(any("*_AUTO_DFU" in note for note in details["notes"]))
self.assertFalse(any("self-update is unavailable" in note for note in details["notes"]))
def test_nrf52_full_companion_cannot_claim_lora_self_update(self):
result, manifest = self.run_checker(
+84 -6
View File
@@ -5,7 +5,7 @@ const picker = require("../docs/_javascript/firmware_picker.js");
const bootloaderManifest = require("../docs/_data/bootloader_manifest.json");
const bootloaderCatalog = picker.buildBootloaderCatalog(bootloaderManifest);
assert.strictEqual(bootloaderCatalog.profiles.length, 24);
assert.strictEqual(bootloaderCatalog.profiles.length, 23);
for (const profile of bootloaderCatalog.profiles) {
for (const hardware of profile.meshcoreHardware) {
assert.strictEqual(picker.bootloaderForHardware(bootloaderCatalog, hardware, "nrf52").id, profile.id);
@@ -16,7 +16,8 @@ for (const profile of bootloaderCatalog.profiles) {
assert.strictEqual(picker.bootloaderForHardware(bootloaderCatalog, "Heltec_t096", "nrf52").id, "heltec_t096");
assert.strictEqual(picker.bootloaderForHardware(bootloaderCatalog, "Heltec_t114", "nrf52").id, "heltec_t114");
assert.strictEqual(picker.bootloaderForHardware(bootloaderCatalog, "Heltec_tower_v2_sdcard", "nrf52").storage, "sd");
assert.strictEqual(picker.bootloaderForHardware(bootloaderCatalog, "Heltec_tower_v2", "nrf52").storage, "internal");
assert.strictEqual(picker.bootloaderForHardware(bootloaderCatalog, "Heltec_tower_v2", "nrf52"), null);
assert(picker.unavailableBootloaderForHardware(bootloaderCatalog, "Heltec_tower_v2", "nrf52").reason.includes("one-time local installation"));
assert.strictEqual(picker.bootloaderForHardware(bootloaderCatalog, "RAK_3401", "nrf52").storage, "adaptive");
assert.strictEqual(picker.bootloaderForHardware(bootloaderCatalog, "RAK_4631", "nrf52").id, "wiscore_rak4631_auto");
assert.strictEqual(picker.bootloaderForHardware(bootloaderCatalog, "ThinkNode_M8", "nrf52"), null);
@@ -34,7 +35,7 @@ for (const hardware of nrf52Hardware) {
}
assert.strictEqual(picker.unavailableBootloaderForHardware(bootloaderCatalog, hardware, "esp32"), null);
}
assert.strictEqual(mappedNrf52, 39);
assert.strictEqual(mappedNrf52, 38);
for (const hardware of nrf52Hardware.filter(h => /^(ikoka_|solarxiao_)/.test(h))) {
assert.strictEqual(picker.bootloaderForHardware(bootloaderCatalog, hardware, "nrf52").id, "xiao_nrf52840_ble");
}
@@ -42,8 +43,8 @@ for (const hardware of ["WioTrackerL1-1W", "WioTrackerL1Eink"]) {
assert.strictEqual(picker.bootloaderForHardware(bootloaderCatalog, hardware, "nrf52").id, "wio_tracker_l1");
}
assert(picker.unavailableBootloaderForHardware(bootloaderCatalog, "GAT562_Mesh_Watch13", "nrf52").reason.includes("vibration motor"));
assert(picker.unavailableBootloaderForHardware(bootloaderCatalog, "wio_wm1110", "nrf52").reason.includes("does not make it XIAO"));
const nextBootloaderTag = "v0.11.0-OTAFIX2.4.11";
assert(picker.unavailableBootloaderForHardware(bootloaderCatalog, "wio_wm1110", "nrf52").reason.includes("identity and installation route still need qualification"));
const nextBootloaderTag = "v0.11.0-OTAFIX2.4.12";
const nextBootloaderRelease = {
tag_name: nextBootloaderTag, draft: false, prerelease: false,
html_url: "https://github.com/" + bootloaderManifest.repository + "/releases/tag/" + nextBootloaderTag,
@@ -56,7 +57,7 @@ const nextBootloaderRelease = {
}),
};
const nextBootloaderCatalog = picker.buildBootloaderCatalog(bootloaderManifest, nextBootloaderRelease);
assert.strictEqual(nextBootloaderCatalog.version, "2.4.11");
assert.strictEqual(nextBootloaderCatalog.version, "2.4.12");
assert(picker.bootloaderForHardware(nextBootloaderCatalog, "t1000e", "nrf52").files.uf2.url.includes(nextBootloaderTag));
const ambiguousBootloader = structuredClone(nextBootloaderRelease);
ambiguousBootloader.assets.push(ambiguousBootloader.assets.find(a => a.name.startsWith("update-heltec_t096_")));
@@ -1408,6 +1409,83 @@ assert.strictEqual(picker.firmwareProfileLabel({ota: 'lora-receiver', feature: '
assert(picker.firmwareProfileLabel({ota: 'lora-receiver', feature: 'standard', variant: 'w25q16'})
.includes('External storage board (W25Q16)'));
// New nRF52 releases keep both sensor policies, using verified release-bound
// controls rather than a publication suffix as evidence of compiled drivers.
const sensorSource = 'deadbeef' + '0'.repeat(32);
const sensorFamily = 'v1.17.1.7-halo-keymind-cascade-dev-deadbeef';
const sensorAssets = [];
const sensorControls = {familyTag: sensorFamily, profiles: {}};
for (const role of ['repeater', 'room_server', 'sensor']) {
for (const storage of ['', '_w25q16']) {
const logical = 'RAK_3401_' + role + '_lora_ota_no_external_sensors' + storage;
for (const policy of ['full', 'reduced']) {
const publication = logical + '-' + policy;
for (const extension of ['zip', 'uf2']) {
sensorAssets.push(asset(publication + '-ota-' + sensorFamily + '.' + extension));
}
sensorControls.profiles[publication] = {
platform: 'NRF52_PLATFORM', otaRole: 'lora-receiver', updateMethods: ['lora'],
sensorProfile: policy, sensorProfileSource: sensorSource,
};
}
}
}
const sensorReleases = [release(sensorFamily, '2026-10-02T00:00:00Z', sensorAssets)];
const sensorCatalog = picker.buildCatalog(sensorReleases, sensorControls);
assert.strictEqual(sensorCatalog.profiles.length, 12);
for (const item of sensorCatalog.profiles) {
const policy = item.target.endsWith('-full') ? 'full' : 'reduced';
assert.strictEqual(item.sensorProfile, policy);
assert.strictEqual(item.chipFamily, 'nrf52');
assert.strictEqual(item.ota, 'lora-receiver');
assert.strictEqual(item.feature, policy === 'full' ? 'full' : 'standard');
assert(!item.variant.includes('-reduced'));
if (policy === 'full') assert(!item.variant.includes('no-external-sensors'));
const label = picker.firmwareProfileLabel(item);
assert(label.startsWith(policy === 'full' ? 'Full supported sensors + LoRa OTA' : 'Reduced sensors + LoRa OTA'));
if (item.target.includes('w25q16')) assert(label.includes('W25Q16'));
const choices = picker.firmwareProfileChoices(sensorCatalog.profiles, {
hardware: item.hardware, role: item.role, mode: item.mode, install: 'zip',
});
const choice = choices.find(entry => entry.value === picker.firmwareProfileValue(item));
assert(choice, item.target);
const selected = sensorCatalog.profiles.filter(profile => picker.profileMatchesFacets(profile,
{...choice.filters, hardware: item.hardware, role: item.role, mode: item.mode}));
assert.deepStrictEqual(selected.map(profile => profile.target), [item.target]);
assert.deepStrictEqual(item.installKinds, ['zip', 'uf2']);
const steps = picker.installSteps(item, 'zip');
assert(steps.some(step => step.includes(policy === 'full' ? 'complete sensor drivers' : 'Omits selected optional')));
if (policy === 'full') assert(!steps.some(step => step.includes('compact profile omits')));
}
for (const change of [{sensorProfileSource: 'bad'}, {sensorProfileSource: 'f'.repeat(40)},
{platform: 'ESP32_PLATFORM'}, {updateMethods: []}, {otaRole: 'none'}]) {
const changedControls = structuredClone(sensorControls);
Object.values(changedControls.profiles).forEach(info => Object.assign(info, change));
assert(picker.buildCatalog(sensorReleases, changedControls).profiles.every(item => !item.sensorProfile));
}
assert(picker.buildCatalog(sensorReleases).profiles.every(item => !item.sensorProfile));
assert(picker.buildCatalog(sensorReleases, {...sensorControls, familyTag: 'v0.0.0'}).profiles
.every(item => !item.sensorProfile));
for (const length of [7, 9, 40]) {
const hash = sensorSource.slice(0, length);
const tag = sensorFamily.replace(/-deadbeef$/, '-' + hash);
const files = sensorAssets.map(file => asset(file.name.replace(/-deadbeef\.(zip|uf2)$/, '-' + hash + '.$1')));
const metadata = {...sensorControls, familyTag: tag};
const profiles = picker.buildCatalog([release(tag, '2026-10-02T00:00:00Z', files)], metadata).profiles;
assert.strictEqual(profiles.length, 12, 'Git abbreviation length ' + length);
assert(profiles.every(item => item.sensorProfile), 'Git abbreviation length ' + length);
const wrong = hash.slice(0, -1) + (hash.endsWith('f') ? '1' : 'f');
const badFiles = files.map(file => asset(file.name.replace('-' + hash + '.', '-' + wrong + '.')));
const badProfiles = picker.buildCatalog([release(tag, '2026-10-02T00:00:00Z', badFiles)], metadata).profiles;
assert.strictEqual(badProfiles.length, 12);
assert(badProfiles.every(item => !item.sensorProfile), 'Mismatched source of length ' + length);
}
const mixedSourceFiles = sensorAssets.map(file => asset(file.name.endsWith('.uf2')
? file.name.replace('-deadbeef.uf2', '-deadbeef1.uf2') : file.name));
assert(picker.buildCatalog([release(sensorFamily, '2026-10-02T00:00:00Z', mixedSourceFiles)], sensorControls)
.profiles.every(item => !item.sensorProfile), 'Every file must bind to the exact source');
console.log('nRF52 full and reduced sensor OTA profile pairs and qualification gating passed');
// A combined profile can be replaced in one click even when its former
// OTA/feature/variant facets have narrowed the catalog to a different image.
const replacementChoices = picker.firmwareProfileChoices(catalog.profiles, {
+51
View File
@@ -0,0 +1,51 @@
#!/usr/bin/env python3
"""Offline picker packaging preserves qualified full/reduced OTA choices."""
import importlib.util
import json
from pathlib import Path
import re
import unittest
ROOT = Path(__file__).resolve().parents[1]
SPEC = importlib.util.spec_from_file_location('package_firmware_picker', ROOT / 'scripts/package_firmware_picker.py')
PACKAGE = importlib.util.module_from_spec(SPEC)
SPEC.loader.exec_module(PACKAGE)
class OfflinePickerPackageTests(unittest.TestCase):
def test_sensor_policy_pairs_and_individual_downloads_are_retained(self):
source = 'a' * 40
family = 'v1.17.1.7-dev-aaaaaaaa'
logical = 'RAK_3401_repeater_lora_ota_no_external_sensors'
controls = dict(familyTag=family, source=source, profiles={})
assets = []
for policy in ('full', 'reduced'):
target = logical + '-' + policy
controls['profiles'][target] = dict(platform='NRF52_PLATFORM', otaRole='lora-receiver',
updateMethods=['lora'], sensorProfile=policy, sensorProfileSource=source)
for extension in ('.zip', '.uf2'):
name = target + '-ota-' + family + extension
assets.append(dict(name=name, size=100,
browser_download_url='https://github.com/mikecarper/MeshCore/releases/download/' + family + '/' + name,
uploader={'token': 'not part of the picker'}))
releases = [dict(name=family, tag_name=family, assets=assets, authorization='private')]
packaged = PACKAGE.package(releases, controls)
match = re.search(r'<script type="application/json" id="firmware-picker-data">(.*?)</script>', packaged)
embedded = json.loads(match[1])
self.assertEqual(embedded['controls'], controls)
self.assertEqual(len(embedded['releases'][0]['assets']), 4)
self.assertEqual({asset['name'] for asset in embedded['releases'][0]['assets']},
{asset['name'] for asset in assets})
self.assertNotIn('authorization', embedded['releases'][0])
self.assertTrue(all('uploader' not in asset for asset in embedded['releases'][0]['assets']))
self.assertIn('Full supported sensors', packaged)
self.assertIn('Reduced sensors', packaged)
def test_controls_must_belong_to_the_packaged_release_family(self):
with self.assertRaisesRegex(ValueError, 'match the supplied release family'):
PACKAGE.package([dict(tag_name='v1.17.1.6', assets=[])],
dict(familyTag='v1.17.1.7', profiles={}))
if __name__ == '__main__':
unittest.main()
+2 -2
View File
@@ -89,7 +89,7 @@ for target in "${!PIO_ENV_PLATFORM_BY_NAME[@]}"; do
full_only_count=$((full_only_count + 1))
fi
done
[ "$full_only_count" -eq 129 ] || fail "expected 129 same-partition FULL-only targets, found $full_only_count"
[ "$full_only_count" -eq 147 ] || fail "expected 147 same-partition FULL-only targets, found $full_only_count"
for target in heltec_rc32_repeater Station_G2_repeater_observer_mqtt \
Heltec_v3_repeater heltec_v4_r8_repeater \
@@ -228,7 +228,7 @@ done
}
build_firmware heltec_rc32_repeater >/dev/null
[ "$observed_full" = 1 ] || fail "audited bulk target did not promote to FULL"
[[ "$observed_filename" == heltec_rc32_repeater-full-logging-ota-vtest-* ]] \
[[ "$observed_filename" == heltec_rc32_repeater-full-usb-wifi-ota-vtest-* ]] \
|| fail "FULL-only bulk target lost its exact identity"
)
(
+401
View File
@@ -0,0 +1,401 @@
"""Host regressions for bounded GPS discovery, query sync and BLE LED opt-out.
Uses the real LocationProvider/SensorManager/MicroNMEA-provider headers and
SensorManager.cpp. The cold-start and sensor-request cases execute extracted
production methods, with only their hardware/library boundaries mocked.
"""
from pathlib import Path
import re
import shutil
import subprocess
import sys
import tempfile
import unittest
from test_replay_reset_integration import extract_braced
ROOT = Path(__file__).resolve().parents[1]
ARDUINO = r'''
#pragma once
#include <cstdint>
#include <cstddef>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <deque>
#define HIGH 1
#define LOW 0
#define OUTPUT 1
inline uint32_t now_ms=0;
inline uint32_t delay_count=0;
inline uint32_t millis(){return now_ms;}
inline void delay(uint32_t ms){now_ms+=ms;++delay_count;}
inline void yield(){++now_ms;}
inline void pinMode(int,int){}
inline void digitalWrite(int,int){}
inline int digitalRead(int){return HIGH;}
class Stream {
public:
virtual ~Stream()=default;
virtual int available(){return 0;}
virtual int read(){return -1;}
virtual size_t write(uint8_t){return 1;}
};
using std::isnan;
'''
MESH = r'''
#pragma once
#include <Arduino.h>
namespace mesh {
class RTCClock {
uint32_t utc=1790899200U;
public:
uint32_t getCurrentTime(){return utc;}
void setCurrentTime(uint32_t value){utc=value;}
};
}
'''
NMEA = r'''
#pragma once
#include <Arduino.h>
class MicroNMEA {
bool valid=false;
public:
inline static unsigned clears=0;
MicroNMEA(char*,size_t){}
void clear(){++clears;valid=false;}
bool process(char c){if(c=='\n'){valid=true;return true;}return false;}
static bool testChecksum(const char*){return true;}
static void sendSentence(Stream&,const char*){}
const char* getSentence()const{return "$GPRMC,valid*00";}
const char* getMessageID()const{return "RMC";}
bool isValid()const{return valid;}
long getLatitude()const{return 47610000;}
long getLongitude()const{return -122330000;}
bool getAltitude(long& value)const{value=125000;return valid;}
long getNumSatellites()const{return valid?8:0;}
uint16_t getYear()const{return valid?2026:0;}
uint8_t getMonth()const{return valid?10:0;}
uint8_t getDay()const{return valid?2:0;}
uint8_t getHour()const{return 12;}
uint8_t getMinute()const{return 0;}
uint8_t getSecond()const{return 0;}
};
'''
RTC = r'''
#pragma once
#include <cstdint>
class DateTime {
public:
DateTime(uint16_t,uint8_t,uint8_t,uint8_t,uint8_t,uint8_t){}
uint32_t unixtime()const{return 1790942400U;}
};
'''
CAYENNE = r'''
#pragma once
#include <cstddef>
#include <cstdint>
class CayenneLPP {
uint8_t data[64]={};
public:
unsigned resets=0,gps_count=0;
explicit CayenneLPP(size_t){}
void reset(){++resets;}
void addVoltage(uint8_t,float){}
void addTemperature(uint8_t,float){}
void addGPS(uint8_t,float,float,float){++gps_count;}
const uint8_t* getBuffer()const{return data;}
uint8_t getSize()const{return 0;}
};
'''
QUERY = r'''
#include <cassert>
#include <limits>
#include <helpers/SensorManager.h>
#include <helpers/sensors/MicroNMEALocationProvider.h>
void LocationProvider::sendSentence(const char*){}
struct Uart:Stream {
std::deque<char> incoming;
int available()override{return static_cast<int>(incoming.size());}
int read()override{if(incoming.empty())return -1;char c=incoming.front();incoming.pop_front();return c;}
void fix(){incoming.push_back('\n');}
};
struct TestProvider:MicroNMEALocationProvider {
using MicroNMEALocationProvider::MicroNMEALocationProvider;
void applied(){markTimeSyncApplied();stopTimeSync();}
void resetQueryState(){resetTimeSyncRequestState();}
};
struct TestSensors:SensorManager {
LocationProvider* provider;
bool detected=true,active=true;
unsigned queries=0;
explicit TestSensors(LocationProvider* p):provider(p){}
LocationProvider* getLocationProvider()override{return provider;}
bool telemetryGpsDetected()const override{return detected;}
bool telemetryGpsActive()const override{return active;}
void telemetryGpsStart()override{active=true;}
void telemetryGpsStop()override{active=false;}
void block(bool value){setGpsTelemetryTransportAvailable(!value);}
bool querySensors(uint8_t,CayenneLPP&)override{++queries;return true;}
};
struct Board {
int getBattMilliVolts(){return 4200;}
float getMCUTemperature(){return 25.0f;}
};
uint8_t getTelemetryPermissions(uint8_t perms,int){return perms;}
@CONFIG@
struct SensorRequestHarness {
TestSensors& sensors;
CayenneLPP telemetry{64};
Board board;
struct {int telemetry_access=0;} _prefs;
uint8_t reply_data[128]={};
explicit SensorRequestHarness(TestSensors& s):sensors(s){}
uint8_t request(uint8_t perms,uint8_t mask=0,uint8_t length=1){
uint8_t payload[1]={mask};
size_t payload_len=length;
const unsigned req_type=3;
@REQUEST@
return 0;
}
};
int main(){
// First acquisition already underway: burst requests must preserve a parsed
// fix, not call the NMEA provider's clearing force-sync method.
now_ms=1;Uart uart;mesh::RTCClock clock;
TestProvider gps(uart,&clock,-1,-1);
gps.setGPSPowerSaving(true);uart.fix();gps.loop();assert(gps.isValid());
const unsigned initial_clears=MicroNMEA::clears;
for(unsigned i=0;i<100;++i){now_ms=i+1;assert(!gps.requestTimeSync(60));}
assert(MicroNMEA::clears==initial_clears&&gps.isValid());
// Successful production NMEA sync marks monotonic time and leaves the edge
// notification available for existing mesh clock consumers.
now_ms=1100;gps.loop();now_ms=2200;gps.loop();
assert(!gps.waitingTimeSync());
assert(gps.consumeTimeSyncApplied());assert(!gps.consumeTimeSyncApplied());
now_ms=62199;assert(!gps.requestTimeSync(60));
// A backward/forward RTC correction cannot underflow or defeat the throttle.
clock.setCurrentTime(1);assert(!gps.requestTimeSync(60));
clock.setCurrentTime(UINT32_MAX);assert(!gps.requestTimeSync(60));
now_ms=62200;assert(gps.requestTimeSync(60));
assert(MicroNMEA::clears==initial_clears+1&&!gps.isValid());
for(unsigned i=0;i<100;++i){++now_ms;assert(!gps.requestTimeSync(0));}
assert(MicroNMEA::clears==initial_clears+1);
// Aborted work is still protected by the last request, even without a fix.
gps.stopTimeSync();assert(!gps.requestTimeSync(60));
now_ms=122200;assert(gps.requestTimeSync(60));
gps.stopTimeSync();assert(gps.requestTimeSync(0)); // explicit zero disables pace only
// Forced CLI/startup callers retain their previous behavior.
const unsigned force_clears=MicroNMEA::clears;
gps.syncTime();assert(MicroNMEA::clears==force_clears+1);
// millis rollover, including a valid successful sync at zero, is safe.
TestProvider wrap(uart,&clock,-1,-1);now_ms=UINT32_MAX-1000;wrap.applied();
now_ms=58998;assert(!wrap.requestTimeSync(60));
now_ms=58999;assert(wrap.requestTimeSync(60));
TestProvider zero(uart,&clock,-1,-1);now_ms=0;zero.applied();
now_ms=59999;assert(!zero.requestTimeSync(60));now_ms=60000;assert(zero.requestTimeSync(60));
// Clamp huge/negative-converted overrides before multiplication. Signed-long
// deadline comparisons elsewhere can never see an overflowing long interval.
TestProvider huge(uart,&clock,-1,-1);now_ms=100;huge.applied();
now_ms=100+0x7ffffffeU;assert(!huge.requestTimeSync(UINT64_MAX));
now_ms=100+0x7fffffffU;assert(huge.requestTimeSync(UINT64_MAX));
huge.stopTimeSync();assert(!huge.requestTimeSync(static_cast<uint64_t>(-1)));
// Requests denied by transport/presence/mode/null provider do not consume
// throttle. A powered external rail is not permission to reclaim the UART.
TestProvider owned(uart,&clock,-1,-1);owned.setGPSPowerSaving(true);owned.stopTimeSync();
TestSensors sensors(&owned);now_ms=200;sensors.block(true);
assert(owned.isEnabled());assert(!sensors.requestGpsTelemetryTimeSync(60));
sensors.block(false);sensors.detected=false;assert(!sensors.requestGpsTelemetryTimeSync(60));
sensors.detected=true;owned.setGPSPowerSaving(false);assert(!sensors.requestGpsTelemetryTimeSync(60));
owned.setGPSPowerSaving(true);sensors.provider=nullptr;assert(!sensors.requestGpsTelemetryTimeSync(60));
sensors.provider=&owned;assert(sensors.requestGpsTelemetryTimeSync(60));
// A RAK discovery reset intentionally forgets the old singleton's throttle.
owned.stopTimeSync();owned.resetQueryState();assert(sensors.requestGpsTelemetryTimeSync(60));
// Execute actual SensorMesh permission and query wiring, including the build
// override's seconds units. No-location/masked requests cannot stamp a query.
TestProvider request_gps(uart,&clock,-1,-1);request_gps.setGPSPowerSaving(true);request_gps.stopTimeSync();
TestSensors request_sensors(&request_gps);SensorRequestHarness requests(request_sensors);
now_ms=1000;const unsigned before=MicroNMEA::clears;
requests.request(TELEM_PERM_BASE);requests.request(TELEM_PERM_LOCATION,TELEM_PERM_LOCATION);
requests.request(TELEM_PERM_LOCATION,0,0);assert(MicroNMEA::clears==before);
requests.request(TELEM_PERM_LOCATION);assert(MicroNMEA::clears==before+1);
request_gps.stopTimeSync();
now_ms=1000+static_cast<uint32_t>(GPS_READ_INTERVAL_SECS)*1000U-1;
requests.request(TELEM_PERM_LOCATION);assert(MicroNMEA::clears==before+1);
++now_ms;requests.request(TELEM_PERM_LOCATION);assert(MicroNMEA::clears==before+2);
}
'''
COLD = r'''
#include <cassert>
#include <Arduino.h>
#define PIN_GPS_TX 8
#define PIN_GPS_RX 7
#define MESH_DEBUG_PRINTLN(...) ((void)0)
struct SerialMock {
uint32_t start=0,arrival=UINT32_MAX;
unsigned begins=0,polls=0;
void setPins(int,int){}
void begin(int){++begins;start=millis();}
int available(){++polls;return arrival!=UINT32_MAX&&static_cast<uint32_t>(millis()-start)>=arrival;}
} Serial1;
struct Location {
unsigned begins=0,resets=0,stops=0;
void begin(){++begins;}void reset(){++resets;}void stop(){++stops;}
};
struct EnvironmentSensorManager {
Location* _location;
bool gps_serial_transport_blocked=false,gps_serial_transport=false;
bool gps_detected=false,gps_active=false,user_enabled=false;
unsigned transport_resets=0;
explicit EnvironmentSensorManager(Location& p):_location(&p){}
void resetGpsTelemetryTransportState(){++transport_resets;}
void setGpsTelemetryUserEnabled(bool enabled){user_enabled=enabled;}
void initBasicGPS();
};
@INIT@
int main(){
for(uint32_t arrival:{0U,1U,250U,2600U,5000U,5001U,UINT32_MAX}){
now_ms=UINT32_MAX-1000;delay_count=0;Serial1=SerialMock();Serial1.arrival=arrival;
Location location;EnvironmentSensorManager sensors(location);const uint32_t start=now_ms;
sensors.initBasicGPS();
#ifdef ENV_SKIP_GPS_DETECT
assert(sensors.gps_detected&&now_ms==start&&delay_count==0&&Serial1.polls==0);
#else
const bool found=arrival<=5000;
const uint32_t elapsed=arrival==0?0:found?((arrival+249)/250)*250:5000;
assert(sensors.gps_detected==found&&static_cast<uint32_t>(now_ms-start)==elapsed);
assert(delay_count==elapsed/250&&delay_count<=20);
#endif
assert(location.begins==1&&location.resets==1&&sensors.transport_resets==1);
assert(sensors.gps_serial_transport==sensors.gps_detected);
#ifdef PERSISTANT_GPS
assert(sensors.gps_active==sensors.gps_detected&&sensors.user_enabled==sensors.gps_detected);
assert(location.stops==static_cast<unsigned>(!sensors.gps_detected));
#else
assert(!sensors.gps_active&&location.stops==1);
#endif
}
Location location;EnvironmentSensorManager blocked(location);
blocked.gps_serial_transport_blocked=true;delay_count=0;Serial1=SerialMock();
blocked.initBasicGPS();assert(delay_count==0&&Serial1.begins==0&&Serial1.polls==0);
assert(location.begins==0&&blocked.transport_resets==0);
}
'''
class GpsUpstreamAdaptationsTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.compiler = shutil.which("g++") or shutil.which("clang++")
if cls.compiler is None:
raise unittest.SkipTest("a host C++17 compiler is required")
def compile_run(self, source, defines=(), extra_sources=()):
with tempfile.TemporaryDirectory(prefix="meshcore-gps-upstream-") as directory:
path = Path(directory)
for name, text in {
"Arduino.h": ARDUINO, "Mesh.h": MESH, "MicroNMEA.h": NMEA,
"RTClib.h": RTC, "CayenneLPP.h": CAYENNE,
"Wire.h": "#pragma once\nclass TwoWire {};\n",
}.items():
(path / name).write_text(text, encoding="utf-8")
cpp = path / "test.cpp"
cpp.write_text(source, encoding="utf-8")
binary = path / "test"
subprocess.run([
self.compiler, "-std=c++17", "-Wall", "-Wextra", "-Werror",
"-Wno-unused-parameter",
*(["-fsanitize=address,undefined", "-fno-sanitize-recover=all",
"-fno-pie", "-no-pie"] if sys.platform.startswith("linux") else []),
*[f"-D{define}" for define in defines],
"-I", str(path), "-I", str(ROOT / "src"), str(cpp),
*[str(ROOT / name) for name in extra_sources], "-o", str(binary),
], check=True)
subprocess.run([str(binary)], check=True)
def query_harness(self):
source = (ROOT / "examples/simple_sensor/SensorMesh.cpp").read_text()
config = re.search(r"#ifndef GPS_READ_INTERVAL_SECS\s*[\s\S]*?#endif", source).group()
request = extract_braced(source, "if (req_type == REQ_TYPE_GET_TELEMETRY_DATA && payload_len >= 1)")
return QUERY.replace("@CONFIG@", config).replace("@REQUEST@", request).replace(
"const unsigned req_type=3;", "const unsigned req_type=3;\n#define REQ_TYPE_GET_TELEMETRY_DATA 3")
def test_monotonic_query_throttle_permissions_and_ownership(self):
self.compile_run(self.query_harness(), ("ENV_INCLUDE_GPS=1",),
("src/helpers/SensorManager.cpp",))
def test_build_override_keeps_seconds_separate_from_position_interval(self):
self.compile_run(self.query_harness(), ("ENV_INCLUDE_GPS=1", "GPS_READ_INTERVAL_SECS=2"),
("src/helpers/SensorManager.cpp",))
def test_no_gps_build_keeps_safe_noop(self):
self.compile_run(r'''
#include <cassert>
#include <helpers/SensorManager.h>
void LocationProvider::sendSentence(const char*){}
int main(){SensorManager sensors;assert(!sensors.requestGpsTelemetryTimeSync(UINT64_MAX));}
''', ("ENV_INCLUDE_GPS=0",), ("src/helpers/SensorManager.cpp",))
def test_bounded_discovery_fast_cold_absent_bypass_and_uart_owner(self):
source = (ROOT / "src/helpers/sensors/EnvironmentSensorManager.cpp").read_text()
init = extract_braced(source, "void EnvironmentSensorManager::initBasicGPS()")
for defines in ((), ("ENV_SKIP_GPS_DETECT=1",), ("PERSISTANT_GPS=1",)):
with self.subTest(defines=defines):
self.compile_run(COLD.replace("@INIT@", init), defines)
def test_ble_led_optout_preserves_default_and_begin_order(self):
source = (ROOT / "src/helpers/nrf52/SerialBLEInterface.cpp").read_text()
begin = extract_braced(source, "bool SerialBLEInterface::begin(")
block = re.search(r"#ifdef DISABLE_BLE_LED[\s\S]*?#endif", begin).group()
self.assertLess(begin.index(block), begin.index("Bluefruit.configPrphConn("))
self.assertLess(begin.index(block), begin.index("if (!Bluefruit.begin())"))
self.assertLess(begin.index("if (_begin_attempted)"), begin.index(block))
harness = r'''
#include <cassert>
struct BluefruitMock {
bool controlled=true;unsigned calls=0;
void autoConnLed(bool enabled){controlled=enabled;++calls;}
} Bluefruit;
void configure(){
@BLOCK@
}
int main(){
configure();
#ifdef DISABLE_BLE_LED
assert(!Bluefruit.controlled&&Bluefruit.calls==1);
#else
assert(Bluefruit.controlled&&Bluefruit.calls==0);
#endif
Bluefruit.controlled=false;configure();assert(!Bluefruit.controlled);
}
'''.replace("@BLOCK@", block)
self.compile_run(harness)
self.compile_run(harness, ("DISABLE_BLE_LED=1",))
def test_shared_success_mark_and_rak_discovery_reset_are_wired(self):
provider = (ROOT / "src/helpers/sensors/MicroNMEALocationProvider.h").read_text()
rak = (ROOT / "src/helpers/sensors/EnvironmentSensorManager.cpp").read_text()
self.assertIn("markTimeSyncApplied();", provider)
rak_provider = rak[rak.index("class RAK12500LocationProvider"):rak.index("static RAK12500LocationProvider")]
self.assertIn("markTimeSyncApplied();", rak_provider)
self.assertIn("resetTimeSyncRequestState();", rak_provider)
# Preserve deliberate force-sync callers outside telemetry queries.
self.assertIn("void syncTime() override { nmea.clear(); LocationProvider::syncTime(); }", provider)
self.assertIn("_location->syncTime();", extract_braced(rak, "void EnvironmentSensorManager::armGpsPowerSavingCycle()"))
if __name__ == "__main__":
unittest.main()
+11
View File
@@ -15,6 +15,17 @@ def record(target: str, profile: str = "full", platform: str = "ESP32_PLATFORM")
class ReleaseFullSelectionTest(unittest.TestCase):
def test_nrf52_full_and_reduced_ota_pair_is_never_collapsed(self):
for role in ('repeater', 'room_server', 'sensor'):
target = 'RAK_3401_' + role
variants = []
for sensor in ('full', 'reduced'):
item = record(target, 'auto', 'NRF52_PLATFORM')
item['manifest'].update(artifact_target=target + '-' + sensor + '-ota',
capabilities=['sensor.profile.' + sensor])
variants.append(item)
self.assertEqual(select_ordinary_full_records(variants), variants)
def test_resume_filters_sibling_full_images_only(self):
inputs = [
record("Heltec_v3_repeater_observer_mqtt"),
@@ -0,0 +1,82 @@
#include <gtest/gtest.h>
#include "helpers/MQTTConnectionHealth.h"
using namespace MQTTConnectionHealth;
TEST(MQTTConnectionHealth, WaitingConfigurationIsNotMarkedAsDown) {
EXPECT_TRUE(isOutageSlot(true, true, false));
EXPECT_FALSE(isOutageSlot(true, false, false));
EXPECT_FALSE(isOutageSlot(false, true, false));
EXPECT_FALSE(isOutageSlot(true, true, true));
}
TEST(MQTTConnectionHealth, OnlyPendingNeverConnectedAttemptIsAFailure) {
EXPECT_TRUE(disconnectFailedAttempt(true, false));
EXPECT_FALSE(disconnectFailedAttempt(false, false)); // deliberate stop/duplicate callback
EXPECT_FALSE(disconnectFailedAttempt(true, true)); // late live-session bounce
EXPECT_FALSE(disconnectFailedAttempt(false, true)); // dropped established session
}
TEST(MQTTConnectionHealth, RejectedReconnectPreservesOnlyExistingAttempt) {
EXPECT_TRUE(clearPendingAfterRejectedRequest(true, false));
EXPECT_TRUE(clearPendingAfterRejectedRequest(true, true)); // failed start clears stale state
EXPECT_TRUE(clearPendingAfterRejectedRequest(false, false));
EXPECT_FALSE(clearPendingAfterRejectedRequest(false, true)); // leave CURRENT state untouched
}
TEST(MQTTConnectionHealth, UnreadyAndDisabledSlotsDoNotCreateFalseOutages) {
Totals totals;
addSlot(totals, true, true, true, false, 0, 10000, 2, 3);
addSlot(totals, true, false, false, true, 1, 10000, 5, 7);
addSlot(totals, false, true, false, true, 1, 10000, 11, 13);
EXPECT_EQ(1, totals.up);
EXPECT_EQ(1, totals.total);
EXPECT_EQ(0, totals.breakers);
EXPECT_FALSE(totals.outage_timed);
EXPECT_EQ(41u, totals.failures); // all history, even disabled slots
}
TEST(MQTTConnectionHealth, DisablingSlotDoesNotReduceFailureHistory) {
Totals enabled, disabled;
addSlot(enabled, true, true, false, false, 1000, 9000, 31, 4);
addSlot(disabled, false, true, false, false, 1000, 9000, 31, 4);
EXPECT_EQ(enabled.failures, disabled.failures);
EXPECT_EQ(1, enabled.total);
EXPECT_EQ(0, disabled.total);
}
TEST(MQTTConnectionHealth, ReadyOutagesChooseWorstAndIgnoreHealthyStaleTimer) {
Totals totals;
addSlot(totals, true, true, false, true, 0, 10000, 0, 0); // first attempt still pending
EXPECT_FALSE(totals.outage_timed);
addSlot(totals, true, true, false, false, 5000, 10000, 0, 0);
addSlot(totals, true, true, false, false, 2000, 10000, 0, 0);
addSlot(totals, true, true, true, false, 1, 10000, 0, 0);
EXPECT_TRUE(totals.outage_timed);
EXPECT_EQ(8000u, totals.worst_outage_ms);
EXPECT_EQ(1, totals.up);
EXPECT_EQ(4, totals.total);
EXPECT_EQ(1, totals.breakers);
}
TEST(MQTTConnectionHealth, OutageElapsedIsWrapSafe) {
Totals totals;
addSlot(totals, true, true, false, false, UINT32_MAX - 499, 500, 0, 0);
EXPECT_EQ(1000u, totals.worst_outage_ms);
}
TEST(MQTTConnectionHealth, LifetimeCountersSaturateInsteadOfWrapping) {
EXPECT_EQ(1u, incrementFailures(0));
EXPECT_EQ(UINT32_MAX, incrementFailures(UINT32_MAX));
Totals totals;
addSlot(totals, false, false, false, false, 0, 0, UINT32_MAX, UINT32_MAX);
addSlot(totals, false, false, false, false, 0, 0, UINT32_MAX, UINT32_MAX);
EXPECT_EQ(uint64_t(UINT32_MAX) * 4, totals.failures);
EXPECT_EQ(INT32_MAX, clampFailureTotal(totals.failures));
EXPECT_EQ(31, clampFailureTotal(31));
}
int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
@@ -99,6 +99,93 @@ TEST(MQTTPayloadBuilder, StatusOmissionSentinelsRemainOmitted) {
EXPECT_FALSE(parsed["repeat"].is<JsonVariant>());
}
TEST(MQTTPayloadBuilder, StatusIncludesAllConnectionHealthFields) {
JsonDocument scratch;
char buffer[1024];
MQTTConnHealth health;
health.slots_up = 2;
health.slots_total = 3;
health.worst_outage_secs = 18432;
health.heap_largest = 16116;
health.connect_failures = 57;
health.slots_breaker = 1;
ASSERT_GT(MQTTPayloadBuilder::buildStatusMessage(
scratch, "node", "id", "model", "firmware", "radio", "client", "online",
kTimestamp, buffer, sizeof(buffer), -1, -1, -1, -1, -999,
-1, -1, -1, -1, -1, -1, nullptr, health), 0);
JsonDocument parsed;
ASSERT_FALSE(deserializeJson(parsed, buffer));
JsonObject stats = parsed["stats"].as<JsonObject>();
EXPECT_EQ(2, stats["mqtt_slots_up"].as<int>());
EXPECT_EQ(3, stats["mqtt_slots_total"].as<int>());
EXPECT_EQ(18432, stats["mqtt_outage_secs"].as<int>());
EXPECT_EQ(16116, stats["heap_largest"].as<int>());
EXPECT_EQ(57, stats["mqtt_connect_failures"].as<int>());
EXPECT_EQ(1, stats["mqtt_slots_breaker"].as<int>());
}
TEST(MQTTPayloadBuilder, HealthyStatusOmitsOutageAndZeroFailureKeys) {
JsonDocument scratch;
char buffer[1024];
MQTTConnHealth health;
health.slots_up = 3;
health.slots_total = 3;
health.heap_largest = 54260;
health.connect_failures = 0;
health.slots_breaker = 0;
ASSERT_GT(MQTTPayloadBuilder::buildStatusMessage(
scratch, "node", "id", "model", "firmware", "radio", "client", "online",
kTimestamp, buffer, sizeof(buffer), -1, -1, -1, -1, -999,
-1, -1, -1, -1, -1, -1, nullptr, health), 0);
JsonDocument parsed;
ASSERT_FALSE(deserializeJson(parsed, buffer));
JsonObject stats = parsed["stats"].as<JsonObject>();
EXPECT_EQ(3, stats["mqtt_slots_up"].as<int>());
EXPECT_FALSE(stats["mqtt_outage_secs"].is<JsonVariant>());
EXPECT_FALSE(stats["mqtt_connect_failures"].is<JsonVariant>());
EXPECT_FALSE(stats["mqtt_slots_breaker"].is<JsonVariant>());
}
TEST(MQTTPayloadBuilder, FailedStartsAloneCreateHealthStats) {
JsonDocument scratch;
char buffer[1024];
MQTTConnHealth health;
health.connect_failures = 1;
ASSERT_GT(MQTTPayloadBuilder::buildStatusMessage(
scratch, "node", "id", "model", "firmware", "radio", "client", "online",
kTimestamp, buffer, sizeof(buffer), -1, -1, -1, -1, -999,
-1, -1, -1, -1, -1, -1, nullptr, health), 0);
JsonDocument parsed;
ASSERT_FALSE(deserializeJson(parsed, buffer));
EXPECT_EQ(1, parsed["stats"]["mqtt_connect_failures"].as<int>());
EXPECT_FALSE(parsed["stats"]["mqtt_slots_up"].is<JsonVariant>());
}
TEST(MQTTPayloadBuilder, WorstCaseStatusWithHealthFitsProductionCeiling) {
// Actual bridge field maxima, including legal quote characters doubled by JSON.
const std::string origin(31, '"'), origin_id(64, 'A'), model(63, 'M');
const std::string firmware(63, 'F'), client(63, 'C');
JsonDocument scratch;
char buffer[1024];
MQTTConnHealth health;
health.slots_up = 0;
health.slots_total = 5;
health.worst_outage_secs = 4294967;
health.heap_largest = 8388608;
health.connect_failures = INT32_MAX;
health.slots_breaker = 5;
const int len = MQTTPayloadBuilder::buildStatusMessage(
scratch, origin.c_str(), origin_id.c_str(), model.c_str(), firmware.c_str(),
"9999.999999,1000.0,12,8", client.c_str(), "online", kTimestamp,
buffer, sizeof(buffer), 4200, 2147483, INT32_MAX, 6, -128,
2147483, 2147483, INT32_MAX, 8388608, INT32_MAX, INT32_MAX, "off", health);
ASSERT_GT(len, 0);
EXPECT_LT(len, 1024 - 32);
JsonDocument parsed;
ASSERT_FALSE(deserializeJson(parsed, buffer));
EXPECT_EQ(INT32_MAX, parsed["stats"]["mqtt_connect_failures"].as<int>());
}
TEST(MQTTPayloadBuilder, StringsAreEscapedAndRoundTrip) {
const char* origin = "node \"north\"\\rack\nline";
const char* model = "Heltec\tV3";
@@ -199,6 +286,27 @@ TEST(MQTTPayloadBuilder, RxPacketOmitsUnknownRadioMetrics) {
EXPECT_FALSE(parsed["score"].is<JsonVariant>());
}
TEST(MQTTPayloadBuilder, RxPacketOmitsOnlyTheUnknownRadioMetric) {
JsonDocument scratch;
char buffer[2048];
ASSERT_GT(MQTTPayloadBuilder::buildPacketMessage(
scratch, "node", "id", kTimestamp, "rx", "12:34:56", "18/07/2026",
42, 4, "D", 20, "A0B1", std::nanf(""), -93, std::nanf(""), "hash",
nullptr, 0, 0, 64, buffer, sizeof(buffer)), 0);
JsonDocument parsed;
ASSERT_FALSE(deserializeJson(parsed, buffer));
EXPECT_FALSE(parsed["SNR"].is<JsonVariant>());
EXPECT_STREQ("-93", parsed["RSSI"].as<const char*>());
ASSERT_GT(MQTTPayloadBuilder::buildPacketMessage(
scratch, "node", "id", kTimestamp, "rx", "12:34:56", "18/07/2026",
42, 4, "D", 20, "A0B1", 7.2f, -999, std::nanf(""), "hash",
nullptr, 0, 0, 64, buffer, sizeof(buffer)), 0);
parsed.clear();
ASSERT_FALSE(deserializeJson(parsed, buffer));
EXPECT_STREQ("7.2", parsed["SNR"].as<const char*>());
EXPECT_FALSE(parsed["RSSI"].is<JsonVariant>());
}
TEST(MQTTPayloadBuilder, RawMessageHasExactContractAndEscapesData) {
char buffer[512];
JsonDocument doc;
+203
View File
@@ -0,0 +1,203 @@
#!/usr/bin/env python3
"""Compile the real adapter/bridge attempt methods against controllable SDK calls.
No PlatformIO/network/hardware is used. IDF4 and IDF5 config layouts are covered.
"""
from pathlib import Path
import os
import shutil
import subprocess
import tempfile
import unittest
ROOT = Path(__file__).resolve().parents[1]
def method(path, signature):
source = (ROOT / path).read_text(encoding="utf-8")
start = source.index(signature)
opening = source.index("{", start)
depth = 1
pos = opening + 1
while depth:
depth += (source[pos] == "{") - (source[pos] == "}")
pos += 1
return source[start:pos] + "\n"
PREAMBLE = r'''
#include <cstdlib>
#include <cstdint>
#include <cassert>
#include <functional>
#include "helpers/MQTTConnectionHealth.h"
using esp_err_t = int;
using esp_mqtt_client_handle_t = void*;
constexpr int ESP_OK=0, ESP_FAIL=-1, ESP_ERR_INVALID_STATE=2, ESP_ERR_NO_MEM=3;
constexpr int ESP_ERR_INVALID_ARG=4, MQTT_EVENT_ANY=0, RUNTIME_MQTT_SLOTS=2;
#define ESP_LOGE(...) ((void)0)
#define ESP_LOGW(...) ((void)0)
#define ESP_LOGI(...) ((void)0)
#define ESP_ERROR_CHECK_WITHOUT_ABORT(...) ((void)0)
#define MQTT_DEBUG_PRINTLN(...) ((void)0)
const char* esp_err_to_name(int) { return "mock"; }
struct Config {
struct { struct { const char* uri=nullptr; } address; } broker;
struct { int size=1024; } buffer;
const char* uri=nullptr;
int buffer_size=1024;
};
static bool fail_malloc=false, fail_init=false;
static int register_result=ESP_OK, config_result=ESP_OK;
static int start_result=ESP_OK, reconnect_result=ESP_OK;
static int init_calls=0, register_calls=0, destroy_calls=0, config_calls=0;
static int start_calls=0, reconnect_calls=0;
static std::function<void()> sdk_callback;
void* test_malloc(size_t size) { return fail_malloc ? nullptr : std::malloc(size); }
#define malloc test_malloc
void* esp_mqtt_client_init(Config*) {
++init_calls; return fail_init ? nullptr : reinterpret_cast<void*>(1);
}
int esp_mqtt_client_register_event(void*, int, void(*)(void*,int,int,void*), void*) {
++register_calls; return register_result;
}
int esp_mqtt_client_destroy(void*) { ++destroy_calls; return ESP_OK; }
int esp_mqtt_set_config(void*, Config*) { ++config_calls; return config_result; }
int esp_mqtt_client_start(void*) {
++start_calls; if(sdk_callback) sdk_callback(); return start_result;
}
int esp_mqtt_client_reconnect(void*) {
++reconnect_calls; if(sdk_callback) sdk_callback(); return reconnect_result;
}
struct PsychicMqttClient {
Config _mqtt_cfg;
void* _client=nullptr;
bool _config_dirty=true, _started=false;
char* _buffer=nullptr;
size_t _buffer_capacity=0;
~PsychicMqttClient() { std::free(_buffer); }
static void _onMqttEventStatic(void*,int,int,void*) {}
esp_err_t applyConfig();
esp_err_t connect();
esp_err_t reconnect();
bool isStarted() const { return _started; }
void uri(const char* uri) { _mqtt_cfg.uri=uri; _mqtt_cfg.broker.address.uri=uri; }
};
struct MQTTBridge {
struct MQTTSlot {
PsychicMqttClient* client=nullptr;
uint32_t start_failures=0;
};
MQTTSlot _slots[RUNTIME_MQTT_SLOTS];
volatile bool _slot_attempt_pending[RUNTIME_MQTT_SLOTS] = {};
esp_err_t reconnectSlotClient(int index);
};
'''
MAIN = r'''
int main() {
PsychicMqttClient c;
assert(c.connect()==ESP_ERR_INVALID_STATE && start_calls==0 && init_calls==0);
c.uri("mqtts://broker");
std::free(c._buffer); c._buffer=nullptr;
fail_malloc=true;
assert(c.connect()==ESP_ERR_NO_MEM && start_calls==0 && init_calls==0);
fail_malloc=false;
fail_init=true;
assert(c.connect()==ESP_ERR_NO_MEM && register_calls==0 && start_calls==0);
fail_init=false;
register_result=ESP_FAIL;
assert(c.connect()==ESP_FAIL && c._client==nullptr && c._config_dirty);
assert(destroy_calls==1 && start_calls==0);
register_result=ESP_OK;
start_result=ESP_FAIL;
assert(c.connect()==ESP_FAIL && !c.isStarted());
start_result=ESP_OK;
assert(c.connect()==ESP_OK && c.isStarted());
assert(register_calls==2); // failed registration then one successful registration
c._config_dirty=true;
config_result=ESP_FAIL;
int starts=start_calls;
assert(c.connect()==ESP_FAIL && start_calls==starts && c._config_dirty);
assert(c.reconnect()==ESP_FAIL && reconnect_calls==0 && c._config_dirty);
config_result=ESP_OK;
reconnect_result=ESP_FAIL;
assert(c.reconnect()==ESP_FAIL && !c._config_dirty && reconnect_calls==1);
reconnect_result=ESP_OK;
assert(c.reconnect()==ESP_OK && reconnect_calls==2);
MQTTBridge b;
assert(b.reconnectSlotClient(-1)==ESP_ERR_INVALID_ARG);
assert(b.reconnectSlotClient(1)==ESP_ERR_INVALID_STATE);
b._slots[0].client=&c;
reconnect_result=ESP_FAIL;
assert(b.reconnectSlotClient(0)==ESP_FAIL);
assert(!b._slot_attempt_pending[0] && b._slots[0].start_failures==0);
b._slot_attempt_pending[0]=true;
assert(b.reconnectSlotClient(0)==ESP_FAIL);
assert(b._slot_attempt_pending[0] && b._slots[0].start_failures==0);
sdk_callback=[&]() { b._slot_attempt_pending[0]=false; };
assert(b.reconnectSlotClient(0)==ESP_FAIL && !b._slot_attempt_pending[0]);
sdk_callback=nullptr;
c._started=false;
start_result=ESP_FAIL;
assert(b.reconnectSlotClient(0)==ESP_FAIL);
assert(!b._slot_attempt_pending[0] && b._slots[0].start_failures==1);
start_result=ESP_OK;
sdk_callback=[&]() {
assert(b._slot_attempt_pending[0]); // set before synchronous SDK callback
b._slot_attempt_pending[0]=false; // onConnect completes the attempt
};
assert(b.reconnectSlotClient(0)==ESP_OK && !b._slot_attempt_pending[0]);
sdk_callback=nullptr;
reconnect_result=ESP_OK;
assert(b.reconnectSlotClient(0)==ESP_OK && b._slot_attempt_pending[0]);
return 0;
}
'''
class MqttTransportResultsTests(unittest.TestCase):
def test_real_adapter_and_bridge_methods_for_both_idf_layouts(self):
compiler = shutil.which("g++") or shutil.which("c++")
self.assertIsNotNone(compiler, "a host C++ compiler is required")
adapter = "lib/PsychicMqttClient/src/PsychicMqttClient.cpp"
source = PREAMBLE + "\n".join(method(adapter, signature) for signature in (
"esp_err_t PsychicMqttClient::applyConfig()",
"esp_err_t PsychicMqttClient::connect()",
"esp_err_t PsychicMqttClient::reconnect()"))
source += method("src/helpers/bridges/MQTTBridge.cpp",
"esp_err_t MQTTBridge::reconnectSlotClient(int index)") + MAIN
with tempfile.TemporaryDirectory(prefix="meshcore-mqtt-results-") as temp:
path = Path(temp) / "results.cpp"
path.write_text(source, encoding="utf-8")
for major in (4, 5):
with self.subTest(idf_major=major):
exe = Path(temp) / (f"results-{major}" + (".exe" if os.name == "nt" else ""))
result = subprocess.run([compiler, "-std=c++17", "-Wall", "-Wextra",
f"-DESP_IDF_VERSION_MAJOR={major}",
"-I", str(ROOT / "src"), str(path), "-o", str(exe)],
text=True, capture_output=True)
self.assertEqual(result.returncode, 0, result.stderr)
result = subprocess.run([str(exe)], text=True, capture_output=True)
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
def test_attempt_wiring_covers_stop_bounce_setup_and_both_status_paths(self):
source = (ROOT / "src/helpers/bridges/MQTTBridge.cpp").read_text(encoding="utf-8")
self.assertEqual(source.count("result = slot.client->connect();"), 1)
self.assertEqual(source.count("result = slot.client->reconnect();"), 1)
self.assertEqual(source.count("repeatStatus(), collectConnHealth()"), 2)
for signature in ("void MQTTBridge::teardownSlot(", "void MQTTBridge::destroySlotClients("):
body = method("src/helpers/bridges/MQTTBridge.cpp", signature)
self.assertIn("_slot_attempt_pending[", body)
self.assertNotIn("connect_failures =", body)
self.assertNotIn("start_failures =", body)
callback = source[source.index("slot.client->onDisconnect("):source.index("slot.client->onError(")]
self.assertIn("disconnectFailedAttempt", callback)
self.assertIn("incrementFailures", callback)
stats = method("src/helpers/bridges/MQTTBridge.cpp", "void MQTTBridge::formatMqttStatsReply(")
self.assertEqual(stats.count("MQTTConnectionHealth::isOutageSlot("), 2)
if __name__ == "__main__":
unittest.main()
+218
View File
@@ -0,0 +1,218 @@
#!/usr/bin/env bash
set -euo pipefail
cd "$(dirname "$0")/.."
source build.sh
fail() { echo "test_nrf52_ota_profiles: $*" >&2; exit 1; }
# This suite deliberately has no PlatformIO dependency. A mocked one-profile
# worker exercises the actual single/bulk/matrix dispatch and fail-closed pair
# policy, while the flag/manifest contracts below use production helpers.
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
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
esp_repeater
)
for target in "${SUPPORTED_PIO_ENVS[@]}"; do
PIO_ENV_PLATFORM_BY_NAME[$target]=NRF52_PLATFORM
done
PIO_ENV_PLATFORM_BY_NAME[esp_repeater]=ESP32_PLATFORM
for base in nrf_repeater nrf_room_server nrf_sensor RAK_3401_sensor; do
alias=${base}_lora_ota_no_external_sensors
PIO_ENV_BUILD_BASE_BY_NAME[$alias]=$base
PIO_ENV_COMPLETE_OTA_BASE_BY_NAME[$alias]=$base
PIO_ENV_OTA_BY_NAME[$alias]=1
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
PIO_CONFIG_JSON='[]'
for target in nrf_repeater nrf_room_server nrf_sensor Xiao_nrf52_repeater \
Heltec_tower_v2_sdcard_repeater_lora_ota_no_external_sensors \
RAK_3401_repeater_unified_lora_ota; do
is_nrf52_sensor_ota_pair_target "$target" || fail "$target has no pair policy"
done
for target in nrf_kiss_modem nrf_companion_radio_usb nrf_companion_radio_full \
nrf_terminal_chat esp_repeater; do
if is_nrf52_sensor_ota_pair_target "$target"; then
fail "$target incorrectly gained the nRF52 sensor/OTA manager policy"
fi
done
[ "$(get_reduced_lora_ota_target nrf_sensor)" = nrf_sensor_lora_ota_no_external_sensors ] \
|| fail "sensor reduced alias is not handled"
[ "$(get_nrf52_sensor_ota_pair_target nrf_repeater)" = nrf_repeater_lora_ota_no_external_sensors ] \
|| fail "ordinary internal target lost its historical OTA identity"
[ "$(get_nrf52_sensor_ota_pair_target Xiao_nrf52_repeater)" = Xiao_nrf52_repeater ] \
|| fail "external QSPI target changed its deployed ID"
[ "$(get_nrf52_sensor_ota_pair_target Heltec_tower_v2_sdcard_repeater_lora_ota_no_external_sensors)" = \
Heltec_tower_v2_sdcard_repeater_lora_ota_no_external_sensors ] \
|| fail "SD target lost its exact storage identity"
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
[ "${#RESOLVED_BUILD_TARGETS[@]}" -eq 4 ] \
|| fail "ordinary/reduced aliases did not deduplicate into exactly one pair"
for selected in auto standard full; do
BUILD_PROFILE_OVERRIDE=$selected
BUILD_PROFILE_EXPLICIT=1
RESOLVED_BUILD_TARGETS=(nrf_sensor)
configure_effective_build_profile build-firmware >/dev/null
[ "$BUILD_PROFILE_EFFECTIVE" = auto ] || fail "$selected bypassed strict nRF52 pairing"
[ "$AUTO_COMPLETE_FIRST_PASS" = 0 ] || fail "$selected retained the permissive fallback path"
done
BUILD_PROFILE_EXPLICIT=0
# Use the same explicit source prefix as canonical release packaging, not
# Git's repository-dependent/adaptive abbreviated hash length.
worker_source=$(declare -f build_firmware_one_profile)
[[ "$worker_source" == *'commit_hash=$(git rev-parse HEAD)'* ]] \
|| fail "builder does not derive publication prefix from full source identity"
[[ "$worker_source" == *'commit_hash=${commit_hash:0:8}'* ]] \
|| fail "builder publication hash disagrees with canonical release prefix"
calls=()
failed_profile=""
build_firmware_one_profile() {
calls+=("$1:$NRF52_OTA_SENSOR_PROFILE:$FIRMWARE_FILENAME_INFIX:$SKIP_DECLARED_REDUCTIONS:$COMPLETE_OTA_FIRST_PASS:$REQUIRE_OTA_UPDATES")
if [ -n "$failed_profile" ] && [ "$NRF52_OTA_SENSOR_PROFILE" = "$failed_profile" ]; then return 42; fi
return 0
}
ESP32_FULL_BUILD=1
BUILD_PROFILE_EFFECTIVE=standard
REQUIRE_OTA_UPDATES=0
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
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"
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"
for failed_profile in full reduced; do
calls=()
if build_firmware nrf_repeater >/dev/null 2>&1; then
fail "$failed_profile failure was reported as a complete pair"
fi
[ "${#calls[@]}" -eq 2 ] || fail "$failed_profile failure hid the other option's qualification"
done
failed_profile=""
# Both ordinary bulk and the logged matrix go through the same pair dispatcher.
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=()
run_logged_build_targets nrf_room_server Xiao_nrf52_repeater >/dev/null
[ "${#calls[@]}" -eq 4 ] || fail "logged matrix did not publish external/internal pairs"
# KISS and Companion keep the original one-profile worker and do not gain an
# application receiver merely because another target used the paired overlay.
calls=()
build_firmware nrf_kiss_modem >/dev/null
build_firmware nrf_companion_radio_full >/dev/null
[ "${#calls[@]}" -eq 2 ] || fail "excluded roles gained profile pairs"
[[ "${calls[0]}" == nrf_kiss_modem::* ]] || fail "KISS inherited sensor OTA state"
NRF52_OTA_SENSOR_PROFILE=reduced
BUILD_PROFILE_FOR_TARGET=standard
MQTT_BRIDGE_OVERRIDE=off
PACKET_LOGGING_OVERRIDE=on
MESHDEBUG_OVERRIDE=on
ESP32_FULL_BUILD=0
is_lora_ota_build nrf_sensor || fail "logging/standard settings disabled required OTA"
if is_lora_ota_build nrf_kiss_modem; then fail "KISS gained an OTA application"; fi
for profile in full reduced; do
NRF52_OTA_SENSOR_PROFILE=$profile
BUILD_CAPABILITIES=()
BUILD_EXPECTATIONS=()
BUILD_REDUCTIONS=()
BUILD_APPLICATION_EXPECTATIONS=()
declare_build_capability_contract nrf_sensor NRF52_PLATFORM
[[ " ${BUILD_CAPABILITIES[*]} " == *" sensor.profile.${profile} "* ]] \
|| fail "$profile manifest sensor label is missing"
[[ " ${BUILD_EXPECTATIONS[*]} " == *" ota.update.lora=invalid in-place patch geometry "* ]] \
|| fail "$profile does not verify actual LoRa apply support"
done
# Raw external-storage names have no reduced-alias suffix, but still receive
# the explicit reduced policy; the full profile does not trim these drivers.
NRF52_OTA_SENSOR_PROFILE=reduced
SKIP_DECLARED_REDUCTIONS=0
PLATFORMIO_BUILD_FLAGS=""
PLATFORMIO_BUILD_UNFLAGS=""
BUILD_REDUCTIONS=()
apply_lora_ota_no_external_sensors_profile Xiao_nrf52_repeater
[[ "$PLATFORMIO_BUILD_FLAGS" == *-UENV_INCLUDE_BME280* ]] \
|| fail "external QSPI reduced profile did not trim optional drivers"
NRF52_OTA_SENSOR_PROFILE=full
SKIP_DECLARED_REDUCTIONS=1
PLATFORMIO_BUILD_FLAGS=""
apply_lora_ota_no_external_sensors_profile Xiao_nrf52_repeater
[ -z "$PLATFORMIO_BUILD_FLAGS" ] || fail "full sensor profile was silently trimmed"
NRF52_OTA_SENSOR_PROFILE=reduced
is_rak_i2c_voltage_monitor_ota_target RAK_3401_repeater_unified_lora_ota \
|| fail "adaptive RAK reduced profile dropped the retained INA policy"
is_rak_gps_retaining_ota_target RAK_3401_repeater_unified_lora_ota \
|| fail "adaptive RAK reduced profile dropped compatible GPS"
if is_rak_gps_retaining_ota_target RAK_4631_repeater_bridge_rs232_serial1_lora_ota_no_external_sensors; then
fail "Serial1 bridge incorrectly promises conflicting GPS"
fi
# Resume must requalify the current sensor profile, not accept a legacy
# Bluetooth-only or unlabeled image merely because its hash/UF2 checks pass.
for profile in full reduced; do
for corruption in valid missing_sensor opposite_sensor ambiguous_sensor missing_lora_cap \
no_lora_method unproven_lora unverified_ota unverified_manifest wrong_target wrong_artifact wrong_platform; do
resume_manifest=$test_output/resume.json
python3 - "$resume_manifest" "$profile" "$corruption" <<'PY'
import json, pathlib, sys
path, profile, corruption = sys.argv[1:]
manifest = {"platform": "NRF52_PLATFORM", "target": "nrf_sensor",
"artifact_target": "nrf_sensor-" + profile + "-ota",
"capabilities": ["sensor.profile." + profile, "ota.update.lora"],
"verification": [{"capability": "ota.update.lora", "present": True}],
"verified": True, "ota_update_verified": True, "ota_update_methods": ["lora", "bluetooth"]}
if corruption == "missing_sensor": manifest["capabilities"].pop(0)
elif corruption == "opposite_sensor": manifest["capabilities"][0] = "sensor.profile." + ("reduced" if profile == "full" else "full")
elif corruption == "ambiguous_sensor": manifest["capabilities"].append("sensor.profile." + ("reduced" if profile == "full" else "full"))
elif corruption == "missing_lora_cap": manifest["capabilities"].pop()
elif corruption == "no_lora_method": manifest["ota_update_methods"] = ["bluetooth"]
elif corruption == "unproven_lora": manifest["verification"][0]["present"] = False
elif corruption == "unverified_ota": manifest["ota_update_verified"] = False
elif corruption == "unverified_manifest": manifest["verified"] = False
elif corruption == "wrong_target": manifest["target"] = "other_sensor"
elif corruption == "wrong_artifact": manifest["artifact_target"] = "nrf_sensor"
elif corruption == "wrong_platform": manifest["platform"] = "ESP32_PLATFORM"
pathlib.Path(path).write_text(json.dumps(manifest, indent=2))
PY
if nrf52_sensor_profile_manifest_matches "$resume_manifest" nrf_sensor "$profile" "nrf_sensor-${profile}-ota"; then
[ "$corruption" = valid ] || fail "resume accepted $profile/$corruption"
else
[ "$corruption" != valid ] || fail "resume rejected valid $profile metadata"
fi
done
done
echo "test_nrf52_ota_profiles: OK"
+4 -1
View File
@@ -1,5 +1,7 @@
"""All OTA names survive front coding; original Companion API stays unchanged."""
import re
import os
import shutil
import subprocess
import sys
import tempfile
@@ -35,7 +37,8 @@ class OtaTargetNameTest(unittest.TestCase):
(ROOT / "src/helpers/ota/tinf/tinf.h").read_text(), encoding="utf-8")
decoder = Path(temp_dir) / "tinf.o"
subprocess.run([
"cc", "-Os", "-DMESHCORE_TINF_IMPLEMENTATION=1", "-c",
os.environ.get("CC") or shutil.which("cc") or "gcc",
"-Os", "-DMESHCORE_TINF_IMPLEMENTATION=1", "-c",
str(ROOT / "src/helpers/ota/tinf/tinflate.c"), "-o", str(decoder),
], check=True)
subprocess.run([
+52
View File
@@ -47,6 +47,58 @@ class PickerControlsTests(unittest.TestCase):
manifest['ota_update_methods'] = ['lora']
self.assertEqual(GENERATOR.runtime_metadata(manifest, False)['otaRole'], 'lora-receiver')
def test_sensor_profile_is_qualified_nrf52_receiver_metadata_not_a_filename(self):
source = 'a' * 40
manifest = dict(target='RAK_3401_repeater_lora_ota_no_external_sensors',
platform='NRF52_PLATFORM', verified=True, ota_update_verified=True,
capabilities=['ota.update.lora', 'sensor.profile.full'],
ota_update_methods=['lora'], verification=[
dict(capability='ota.update.lora', present=True, source='linked image')])
result = GENERATOR.runtime_metadata(manifest, False, source)
self.assertEqual(result['sensorProfile'], 'full')
self.assertEqual(result['sensorProfileSource'], source)
manifest['capabilities'][-1] = 'sensor.profile.reduced'
self.assertEqual(GENERATOR.runtime_metadata(manifest, False, source)['sensorProfile'], 'reduced')
for changes in (dict(platform='ESP32_PLATFORM'), dict(target='RAK_3401_companion_radio_full'),
dict(ota_update_verified=False), dict(verification=[]),
dict(verification=[dict(capability='ota.update.lora', present=True, source='filename')])):
with self.subTest(changes=changes), self.assertRaisesRegex(ValueError, 'qualified nRF52'):
GENERATOR.runtime_metadata({**manifest, **changes}, False, source)
with self.assertRaisesRegex(ValueError, 'exact source commit'):
GENERATOR.runtime_metadata(manifest, False, 'aaaaaaaa')
manifest['capabilities'].append('sensor.profile.full')
with self.assertRaisesRegex(ValueError, 'ambiguous'):
GENERATOR.runtime_metadata(manifest, False, source)
def test_generates_independent_controls_for_same_identity_sensor_pair(self):
source = 'a' * 40
family = 'v1.17.1.7-dev-aaaaaaaa'
logical = 'RAK_3401_repeater_lora_ota_no_external_sensors'
manifests = []
for policy in ('full', 'reduced'):
manifests.append(dict(target=logical, artifact_target=logical + '-' + policy + '-ota',
platformio_env='sample', platform='NRF52_PLATFORM', verified=True,
ota_update_verified=True, capabilities=['sensor.profile.' + policy, 'ota.update.lora'],
ota_update_methods=['lora'], verification=[dict(capability='ota.update.lora',
present=True, source='linked image')], files=[logical + '-' + policy + '-ota-' + family + ext
for ext in ('.zip', '.uf2')]))
with tempfile.TemporaryDirectory() as temporary:
stage = Path(temporary)
for group in ('companion', 'lora-ota'):
(stage / group).mkdir()
(stage / 'release-plan.json').write_text(json.dumps(dict(source=source, groups=[
dict(key='companion', tag=family), dict(key='lora-ota', tag='lora-ota-' + family)])))
(stage / 'companion/TARGET-MANIFEST.json').write_text('[]')
(stage / 'lora-ota/TARGET-MANIFEST.json').write_text(json.dumps(manifests))
controls = GENERATOR.generate(stage, [('env:sample', [('build_flags', [])])])
self.assertEqual(set(controls['profiles']), {logical + '-full', logical + '-reduced'})
for policy in ('full', 'reduced'):
profile = controls['profiles'][logical + '-' + policy]
self.assertEqual(profile['sensorProfile'], policy)
self.assertEqual(profile['sensorProfileSource'], source)
self.assertEqual(profile['otaRole'], 'lora-receiver')
self.assertEqual(profile['updateMethods'], ['lora'])
def generate(self, reductions, *, source=None, flags=(), verified=True):
initial = 'a' * 40
manifest = dict(target='sample_companion_radio_full', platformio_env='sample',
+50
View File
@@ -0,0 +1,50 @@
#!/usr/bin/env python3
"""Verify the upstream sensor-rail correction without changing local GPS/OTA."""
from pathlib import Path
import subprocess
import tempfile
import unittest
ROOT = Path(__file__).resolve().parents[1]
VARIANT = ROOT / "variants/t1000-e"
FIXTURES = ROOT / "test/fixtures/t1000e_sensor_power"
class T1000eSensorPowerTests(unittest.TestCase):
def test_obsolete_p0_04_control_is_removed_everywhere(self):
for path in VARIANT.iterdir():
if path.suffix in (".h", ".cpp", ".ini"):
with self.subTest(path=path.name):
self.assertNotIn("SENSOR_EN", path.read_text())
self.assertRegex((VARIANT / "variant.h").read_text(), r"PIN_3V3_EN\s+\(38\)")
def test_real_rail_and_existing_shutdown_and_gps_are_preserved(self):
board = (VARIANT / "T1000eBoard.h").read_text()
self.assertIn("void shutdownPeripherals() override", board)
self.assertIn("NRF52Board::shutdownPeripherals();", board)
for pin in ("GPS_VRTC_EN", "GPS_RESET", "GPS_SLEEP_INT", "GPS_RTC_INT",
"GPS_EN", "PIN_3V3_EN", "PIN_3V3_ACC_EN", "BUZZER_EN"):
self.assertIn(f"digitalWrite({pin}, LOW);", board)
target = (VARIANT / "target.cpp").read_text()
for method in ("armGpsPowerSavingCycle", "loopGpsTelemetry", "processGpsTelemetryFix"):
self.assertIn(method, target)
startup = (VARIANT / "variant.cpp").read_text()
self.assertIn("digitalWrite(GPS_EN, HIGH);", startup)
self.assertIn("digitalWrite(GPS_VRTC_EN, HIGH);", startup)
self.assertIn("pinMode(PIN_3V3_EN, OUTPUT);", startup)
def test_actual_sensor_functions_only_switch_p1_06_and_keep_bounds(self):
with tempfile.TemporaryDirectory(prefix="t1000e-sensor-power-") as temp:
binary = Path(temp) / "power"
compiled = subprocess.run([
"c++", "-std=c++11", "-Wall", "-Wextra", "-Wno-unused-variable",
"-I", str(FIXTURES), "-I", str(VARIANT), str(FIXTURES / "power.cpp"),
"-o", str(binary),
], text=True, capture_output=True)
self.assertEqual(compiled.returncode, 0, compiled.stderr)
executed = subprocess.run([str(binary)], text=True, capture_output=True)
self.assertEqual(executed.returncode, 0, executed.stderr)
if __name__ == "__main__":
unittest.main()
+157
View File
@@ -0,0 +1,157 @@
#!/usr/bin/env python3
"""Host-only contracts for the observer recipes imported from 33f1b1096.
Resolve inheritance and interpolation without starting PlatformIO or a build.
The existing board recipes remain authoritative for hardware and OTA policy.
"""
import configparser
import fnmatch
from pathlib import Path
import re
import unittest
ROOT = Path(__file__).resolve().parents[1]
BOARDS = {
"ebyte_eora_s3": ("Ebyte_EoRa-S3",),
"heltec_e213": ("Heltec_E213",),
"heltec_e290": ("Heltec_E290",),
"heltec_rc32": ("heltec_rc32", "heltec_rc32_without_display"),
"heltec_tracker": ("Heltec_Wireless_Tracker",),
"heltec_wireless_paper": ("Heltec_Wireless_Paper",),
"lilygo_t3s3_sx1276": ("LilyGo_T3S3_sx1276",),
"lilygo_teth_elite": ("LilyGo_TETH_Elite_sx1262",),
"meshnology_w12": ("meshnology_w12",),
"xiao_s3": ("Xiao_S3",),
}
NAMES = tuple(
f"{board}_{role}_observer_mqtt"
for boards in BOARDS.values() for board in boards
for role in ("repeater", "room_server")
)
class Recipes:
def __init__(self):
self.config = configparser.ConfigParser(interpolation=None, strict=True)
self.config.read([ROOT / "platformio.ini", *sorted(ROOT.glob("variants/*/platformio.ini"))])
def value(self, section, key, seen=()):
pair = (section, key)
if pair in seen:
raise AssertionError(f"cyclic recipe reference: {pair}")
seen = (*seen, pair)
if not self.config.has_option(section, key):
for parent in self.config.get(section, "extends", fallback="").split(","):
parent = parent.strip()
if parent:
value = self.value(parent, key, seen)
if value:
return value
return ""
value = self.config.get(section, key)
return re.sub(r"\$\{([^}.]+)\.([^}]+)\}",
lambda m: self.value(m[1], m[2], seen), value)
def includes(self, section, source):
included = False
for sign, pattern in re.findall(r"([+-])<([^>]+)>", self.value(section, "build_src_filter")):
# PlatformIO's file glob does not let a root *.cpp select a file
# outside src. Match path components, then handle directory filters.
source_parts, pattern_parts = source.split("/"), pattern.split("/")
file_match = len(source_parts) == len(pattern_parts) and all(
fnmatch.fnmatchcase(part, glob)
for part, glob in zip(source_parts, pattern_parts)
)
if file_match or source.startswith(pattern.rstrip("/") + "/"):
included = sign == "+"
return included
class UpstreamObserverRecipeTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.recipes = Recipes()
def test_all_22_named_additions_exist_once(self):
self.assertEqual(len(NAMES), 22)
for family, boards in BOARDS.items():
text = (ROOT / "variants" / family / "platformio.ini").read_text()
for board in boards:
for role in ("repeater", "room_server"):
name = f"{board}_{role}_observer_mqtt"
with self.subTest(env=name):
self.assertEqual(text.count(f"[env:{name}]"), 1)
self.assertTrue(self.recipes.config.has_section(f"env:{name}"))
def test_observers_keep_inherited_ota_and_complete_tls_hooks(self):
expected_hooks = (
"generate_webconfig_html.py", "meshcore_image_identity.py",
"portable_esp32_link.py", "esp32_ota_heap_context.py", "merge-bin.py",
"tools/mota/pio_endf.py", "check_esp32_dram.py", "check_firmware_ram.py",
"generate_cert_bundle.py",
)
for name in NAMES:
section = f"env:{name}"
with self.subTest(env=name):
flags = self.recipes.value(section, "build_flags")
for flag in ("ESP32_PLATFORM", "ENABLE_OTA=1", "OTA_FLASH_STORE=1",
"OTA_FOLDER_SERIAL", "WITH_MQTT_BRIDGE=1", "MQTT_MAX_PACKET_SIZE=1024"):
self.assertIn(flag, flags)
hooks = self.recipes.value(section, "extra_scripts")
for hook in expected_hooks:
self.assertIn(hook, hooks)
self.assertEqual(self.recipes.value(section, "board_ssl_cert_source"), "adafruit-full")
self.assertEqual(self.recipes.value(section, "board_build.embed_files"),
"src/certs/x509_crt_bundle.bin")
self.assertTrue((ROOT / "scripts/generate_cert_bundle.py").is_file())
def test_mqtt_sources_dependencies_and_role_entrypoints(self):
for name in NAMES:
section = f"env:{name}"
role = "simple_room_server" if "_room_server_" in name else "simple_repeater"
other = "simple_repeater" if role == "simple_room_server" else "simple_room_server"
with self.subTest(env=name):
for source in ("helpers/bridges/MQTTBridge.cpp", "helpers/MQTTMessageBuilder.cpp",
"helpers/JWTHelper.cpp", f"../examples/{role}/main.cpp",
"helpers/ota/OtaTinf.c"):
self.assertTrue(self.recipes.includes(section, source), source)
self.assertFalse(self.recipes.includes(section, f"../examples/{other}/main.cpp"))
deps = self.recipes.value(section, "lib_deps")
for dependency in ("PsychicMqttClient", "ArduinoJson @ 7.4.3", "NTPClient",
"JChristensen/Timezone", "paulstoffregen/Time@1.6.1"):
self.assertIn(dependency, deps)
if "WITH_SNMP=1" in self.recipes.value(section, "build_flags"):
self.assertTrue(self.recipes.includes(section, "helpers/SNMPAgent.cpp"))
self.assertIn("0neblock/SNMP_Agent", deps)
if "_room_server_" in name:
self.assertIn("ROOM_PASSWORD=", self.recipes.value(section, "build_flags"))
def test_small_flash_and_non_psram_profiles_keep_upstream_limits(self):
for board in ("Ebyte_EoRa-S3", "LilyGo_T3S3_sx1276"):
for role in ("repeater", "room_server"):
section = f"env:{board}_{role}_observer_mqtt"
self.assertEqual(self.recipes.value(section, "board_build.partitions"), "min_spiffs.csv")
self.assertNotIn("WITH_SNMP", self.recipes.value(section, "build_flags"))
for board in ("Heltec_Wireless_Tracker", "Heltec_Wireless_Paper"):
for role in ("repeater", "room_server"):
section = f"env:{board}_{role}_observer_mqtt"
self.assertIn("MQTT_NEIGHBORS_WITHOUT_PSRAM=1", self.recipes.value(section, "build_flags"))
def test_rc32_local_startup_platform_and_safety_remain_inherited(self):
for board in ("heltec_rc32", "heltec_rc32_without_display"):
for role in ("repeater", "room_server"):
section = f"env:{board}_{role}_observer_mqtt"
flags = self.recipes.value(section, "build_flags")
self.assertIn("ESP32_POST_BOOT_CPU_FREQ=160", flags)
self.assertIn("RC32_PERIPHERAL_WARMUP_MS=100", flags)
self.assertIn("-UENV_INCLUDE_GPS", flags)
self.assertNotIn("-D ESP32_CPU_FREQ=", flags)
self.assertNotIn("PIN_GPS_EN=45", flags)
self.assertIn("55.03.311", self.recipes.value(section, "platform"))
self.assertIn("3.3.11", self.recipes.value(section, "platform_packages"))
self.assertEqual(self.recipes.value(section, "board_build.partitions"), "default_16MB.csv")
self.assertEqual("HELTEC_RC32_WITH_DISPLAY" in flags, board == "heltec_rc32")
if __name__ == "__main__":
unittest.main()
+8 -4
View File
@@ -8,7 +8,7 @@ fail() { echo "test_xiao_qspi_combined: $*" >&2; exit 1; }
# Use the resolved PlatformIO recipes, not a board-name allowlist: each
# canonical XIAO repeater must retain the internal bootloader scratch bank,
# raw external-QSPI OTA staging, and packet logging in one application.
# raw external-QSPI OTA staging, and packet logging in both sensor profiles.
init_project_context
BUILD_PROFILE_FOR_TARGET=standard
BUILD_PROFILE_EFFECTIVE=standard
@@ -33,11 +33,14 @@ for target in \
is_xiao_qspi_canonical_repeater_build "$target" \
|| fail "$target lost its combined-image classification"
if is_supported_build_env "${target}_lora_ota_no_external_sensors"; then
fail "$target still publishes a redundant lean OTA sibling"
fail "$target invented a separate lean OTA identity instead of pairing its deployed ID"
fi
if get_reduced_lora_ota_target "$target" >/dev/null; then
fail "$target still falls back to a reduced OTA sibling"
fail "$target still changes its deployed OTA identity for the reduced option"
fi
is_nrf52_sensor_ota_pair_target "$target" || fail "$target lacks the required sensor pair policy"
[ "$(get_nrf52_sensor_ota_pair_target "$target")" = "$target" ] \
|| fail "$target pair changed its deployed QSPI identity"
pio_env_option_contains "$target" board_build.ldscript \
nrf52840_s140_v7_xiao_bootloader_ota.ld \
|| fail "$target lost its 40 KiB internal bootloader scratch reservation"
@@ -68,7 +71,8 @@ for target in \
|| fail "$target no longer verifies the packaged USB logging control"
done
# This consolidation is specific to the external-QSPI XIAO repeater layout.
# The deployed QSPI layout/identity classification stays specific to XIAO
# repeaters, while the new sensor pairing policy also covers other roles.
is_xiao_qspi_combined_repeater_target Xiao_nrf52_room_server \
&& fail "non-QSPI room server was incorrectly consolidated"
is_xiao_qspi_combined_repeater_target RAK_4631_repeater \