Share T096 Full mOTA memory with the offline queue

This commit is contained in:
mikecarper committed 2026-09-08 01:15:19 -07:00
1 parent d28535f503
commit 2ea493994e
26 files changed
+1198 -23

No files matched your search

+3
View File
@@ -35,6 +35,9 @@ python3 test/test_esp32_dram.py # Classic ESP32 static limits an
python3 test/test_esp32_usb_serial_hygiene.py # Single-TTY diagnostics/NVS contract
python3 test/test_esp32_usb_sleep.py # USB/logging sleep guards, G3 button wake and two-minute hold/rollover
python3 test/test_logging_sleep_contract.py # USB enable examples and real Repeater/Room MQTT sleep gates
python3 test/test_t096_full_memory.py # Full profile, shared queue wraparound, heap reserve and sensor OOM
python3 test/test_nrf52_ble_startup.py # Real task wrapper/BLE startup with worker and GATT failures
python3 test/test_shared_mota_queue.py # Real mOTA transfers, BLE stop/disconnect, queue loans and policy retention
python3 test/test_esp32_tinyusb_role_hygiene.py # G2/room USB write coverage and bounded-list contracts
python3 test/test_esp32_tinyusb_cooperative_output.py # Real role dump/list pumps with host C++ stubs
python3 test/test_esp32_tinyusb_nonblocking.py # Native CDC stalled-host/64-byte-FIFO simulation (C++17 compiler)
@@ -0,0 +1,238 @@
#include <helpers/BorrowableFrameBuffer.h>
#include <helpers/ota/OtaContext.h>
#include <helpers/CompanionMotaControl.h>
#include <helpers/ota/MotaStreamWritePolicy.h>
#include <cassert>
#include <cstring>
#include <deque>
#include <vector>
#include "../../test_ota/mota_vectors.h"
using namespace mesh::ota;
// Only the flash identity probe is replaced: the context, queue, session
// engine, source parsing, Merkle proofs and transfer bytes are production code.
namespace mesh { namespace ota {
bool ota_self_firmware(SelfFwInfo& info) { info = SelfFwInfo(); return false; }
} }
struct Frame { uint8_t len; uint8_t buf[176]; };
struct Queue {
mesh::BorrowableFrameBuffer<Frame, 256, 128, OtaContext> buffer;
int count = 129, head = 191;
unsigned released = 0;
static OtaContext* acquire(void* owner) {
Queue& q = *static_cast<Queue*>(owner);
return q.buffer.acquire(q.count, q.head);
}
static void release(void* owner) {
Queue& q = *static_cast<Queue*>(owner);
q.buffer.release(q.head);
++q.released;
}
};
class Folder : public MotaSource {
public:
uint8_t count() override { return 1; }
bool describe(uint8_t idx, MotaDesc& d) override {
if (idx) return false;
MotaManifest m;
if (!mota_parse(MOTA_VEC, MOTA_VEC_LEN, m)) return false;
memcpy(d.mid, m.merkle_root, 4);
d.target_id = m.target_id;
d.fw_version = m.fw_version;
d.codec_id = m.codec_id;
d.flags = m.flags;
d.block_size_log2 = m.block_size_log2;
d.total_size = MOTA_VEC_LEN;
d.leaves_off = m.leaves - MOTA_VEC;
d.block_count = m.block_count;
d.payload_off = m.payload - MOTA_VEC;
d.payload_size = m.payload_size;
return true;
}
bool read(uint8_t idx, uint32_t offset, uint8_t* out, uint32_t length) override {
if (idx || uint64_t(offset) + length > MOTA_VEC_LEN) return false;
memcpy(out, MOTA_VEC + offset, length);
return true;
}
};
// The actual BLE source controller below sees a ready/not-ready link and a
// source with real container bytes. Hardware GATT/serial framing is separate.
struct Bluetooth {
bool ready = false, active = false;
int motaStream() { return 0; }
bool isMotaChannelReady() const { return ready; }
bool isMotaStreamActive() const { return active; }
void setMotaStreamActive(bool value) { active = value; }
} bluetooth_interface;
namespace mesh {
struct Log { void println(const char*) {} };
Log& usbLoggingPort() { static Log log; return log; }
namespace ota {
class SerialMotaSource : public ::Folder {
public:
SerialMotaSource(int, MotaStreamWritePolicy, uint32_t) {}
};
} }
#include "ble_control_under_test.h"
struct Packet { bool to_source; std::vector<uint8_t> bytes; };
static std::deque<Packet> packets;
static bool send(void* to_source, const uint8_t* bytes, uint16_t length, bool) {
packets.push_back({to_source != nullptr, {bytes, bytes + length}});
return true;
}
int main() {
Queue q;
for (int i = 0; i < q.count; ++i) {
Frame& frame = q.buffer.at((q.head + i) % q.buffer.capacity());
frame.len = 176;
memset(frame.buf, i, sizeof frame.buf);
}
auto check_messages = [&]() {
for (int i = 0; i < q.count; ++i) {
const Frame& frame = q.buffer.at((q.head + i) % q.buffer.capacity());
assert(frame.len == 176);
for (auto byte : frame.buf) assert(byte == i);
}
};
char reply[160] = {};
assert(!ota_acquire_context(reply, sizeof reply));
assert(strstr(reply, "not ready"));
ota_set_context_storage(&q, Queue::acquire, Queue::release);
uint8_t identity[4] = {1, 2, 3, 4};
ota_begin_context(0, send, nullptr, "Heltec_t096", identity);
assert(!ota_context_if_active() && q.buffer.capacity() == 256);
assert(ota_hop_limit() == OTA_HOP_LIMIT_DEFAULT);
assert(!ota_acquire_context(reply, sizeof reply));
assert(strstr(reply, "sync unread messages"));
assert(q.head == 191 && q.count == 129 && q.buffer.capacity() == 256);
check_messages();
--q.count;
for (unsigned cycle = 0; cycle < 8; ++cycle) {
assert(ota_acquire_context(reply, sizeof reply));
OtaContext& context = ota_ctx();
assert(q.head == 0 && q.buffer.capacity() == 128);
assert(ota_acquire_context(reply, sizeof reply) && &ota_ctx() == &context);
assert(strcmp(context.hw_id, "Heltec_t096") == 0);
check_messages();
if (cycle) {
assert(context.manager.max_hops() == 5);
assert(context.manager.checkpoint_blocks() == 6);
assert(context.manager.advert_mins() == 42);
assert(context.allow.count() == 1);
}
context.manager.set_max_hops(5);
context.manager.set_checkpoint_blocks(6);
context.manager.set_advert_mins(42);
uint8_t key[32] = {7};
context.allow.add(key);
Folder folder;
const auto link = cycle % 2 ? OtaContext::FOLDER_LINK_BLE
: OtaContext::FOLDER_LINK_SERIAL;
assert(context.attach_folder_source(&folder, link, "test", reply, sizeof reply));
assert(context.manager.servedCount() == 1);
ota_release_context_if_idle(false); // attached sources hold the workspace
assert(ota_context_if_active());
assert(!context.attach_folder_source(&folder,
cycle % 2 ? OtaContext::FOLDER_LINK_SERIAL : OtaContext::FOLDER_LINK_BLE,
"wrong owner", reply, sizeof reply));
assert(context.folderLink() == link);
OtaManager receiver;
OtaStoreRam<8192> destination;
receiver.begin(EXP_TARGET_ID, send, &q);
receiver.set_fetch_store(&destination);
assert(receiver.pull(EXP_MERKLE_ROOT, EXP_TARGET_ID) == OtaManager::PULL_STARTED);
for (uint32_t time = 100; time < 300000 && receiver.fetchState() != OtaManager::COMPLETE;
time += 100) {
context.manager.set_clock(time);
receiver.set_clock(time);
context.manager.serviceEgress();
receiver.serviceEgress();
if (time % 1000 == 0) { context.manager.loop(); receiver.loop(); }
while (!packets.empty()) {
Packet packet = packets.front();
packets.pop_front();
(packet.to_source ? context.manager : receiver).on_message(
packet.bytes.data(), packet.bytes.size());
}
}
assert(receiver.fetchState() == OtaManager::COMPLETE);
assert(destination.staged_size() == MOTA_VEC_LEN);
assert(memcmp(destination.data(), MOTA_VEC, MOTA_VEC_LEN) == 0);
check_messages();
context.detach_folder(); // same cleanup for USB/BLE stop and disconnect
context.manager.announce(); // callers may still use the context until loop boundary
packets.clear();
ota_release_context_if_idle(true); // return slots even if TempRadio is still up
assert(!ota_context_if_active() && q.buffer.capacity() == 256);
assert(ota_hop_limit() == 5 && q.released == cycle + 1);
check_messages();
// Reuse every returned slot, so stale transfer state cannot survive.
for (unsigned i = 128; i < 256; ++i)
memset(&q.buffer.at(i), 0xCC, sizeof(Frame));
ota_release_context_if_idle(false);
assert(q.released == cycle + 1);
}
assert(ota_acquire_context(reply, sizeof reply));
ota_release_context_if_idle(true); // discovery holds storage during TempRadio
assert(ota_context_if_active());
ota_release_context_if_idle(false); // expiry / normalradio releases it
assert(!ota_context_if_active() && q.buffer.capacity() == 256);
assert(ota_acquire_context(reply, sizeof reply));
assert(!ota_ctx().attach_folder_source(nullptr, OtaContext::FOLDER_LINK_SERIAL,
"failed start", reply, sizeof reply));
ota_release_context_if_idle(false);
assert(!ota_context_if_active() && q.buffer.capacity() == 256);
check_messages();
Nrf52BleMotaSourceControl ble;
assert(!ble.start(reply, sizeof reply)); // no subscription, no storage loan
assert(!ota_context_if_active() && q.buffer.capacity() == 256);
for (int disconnect = 0; disconnect < 2; ++disconnect) {
bluetooth_interface.ready = true;
assert(ble.start(reply, sizeof reply));
assert(ble.status().attached && q.buffer.capacity() == 128);
assert(ble.status().offered == 1 && ble.status().advertised == 1);
if (disconnect) {
bluetooth_interface.ready = false;
ble.loop();
} else {
assert(ble.stop(reply, sizeof reply));
}
assert(!ble.status().attached && !bluetooth_interface.active);
ota_release_context_if_idle(true);
assert(!ota_context_if_active() && q.buffer.capacity() == 256);
assert(!ble.status().attached);
assert(ble.stop(reply, sizeof reply)); // idle stop/status/poll never acquire
ble.loop();
assert(!ota_context_if_active());
check_messages();
packets.clear();
}
// BLE start/stop cannot detach a USB-owned source or return its workspace.
assert(ota_acquire_context(reply, sizeof reply));
Folder usb;
assert(ota_ctx().attach_folder_source(&usb, OtaContext::FOLDER_LINK_SERIAL,
"USB", reply, sizeof reply));
bluetooth_interface.ready = true;
assert(!ble.start(reply, sizeof reply));
assert(ble.status().another_link_active);
assert(ble.stop(reply, sizeof reply));
ota_release_context_if_idle(false);
assert(ota_ctx().folder_active && q.buffer.capacity() == 128);
ota_ctx().detach_folder();
ota_release_context_if_idle(true);
assert(!ota_context_if_active() && q.buffer.capacity() == 256);
check_messages();
}
+207
View File
@@ -0,0 +1,207 @@
#!/usr/bin/env python3
"""Run the actual task wrapper and BLE startup with injected allocation failures."""
from pathlib import Path
import subprocess
import tempfile
import unittest
from test_t096_full_memory import method
ROOT = Path(__file__).resolve().parents[1]
RTOS = r'''
#pragma once
#include <cstdint>
using BaseType_t = int;
using UBaseType_t = unsigned;
using TaskHandle_t = void*;
using TaskFunction_t = void (*)(void*);
using configSTACK_DEPTH_TYPE = uint16_t;
constexpr BaseType_t pdPASS = 1;
'''
HARNESS = r'''
#include "Arduino.h"
#include <cassert>
#include <atomic>
#include <cstdio>
#include <cstring>
#include <helpers/BluetoothMac.h>
#include <helpers/BleMotaProtocol.h>
#include <helpers/nrf52/BleTaskStartup.h>
#ifndef COMPANION_FEATURE_BLE_MOTA_SOURCE
#define COMPANION_FEATURE_BLE_MOTA_SOURCE 1
#endif
#define BLE_DEBUG_PRINTLN(...) do {} while (0)
constexpr int BANDWIDTH_MAX = 3, NRF_SUCCESS = 0, ERROR_NONE = 0;
constexpr int BLE_GAP_ADDR_TYPE_RANDOM_STATIC = 1, BLE_TX_POWER = 4;
constexpr int BLE_MIN_CONN_INTERVAL = 12, BLE_MAX_CONN_INTERVAL = 24;
constexpr int BLE_SLAVE_LATENCY = 4, BLE_CONN_SUP_TIMEOUT = 200;
constexpr int SECMODE_ENC_WITH_MITM = 1, SECMODE_NO_ACCESS = 0;
constexpr int CHR_PROPS_NOTIFY = 1, CHR_PROPS_WRITE = 2;
constexpr int BLE_GAP_ADV_TYPE_CONNECTABLE_SCANNABLE_UNDIRECTED = 0;
constexpr int BLE_GAP_ADV_FLAGS_LE_ONLY_GENERAL_DISC_MODE = 2;
constexpr int BLE_ADV_INTERVAL_MIN = 32, BLE_ADV_INTERVAL_MAX = 244, BLE_ADV_FAST_TIMEOUT = 30;
struct ble_gap_addr_t { int addr_type; uint8_t addr[6]; };
struct ble_gap_conn_params_t { unsigned min_conn_interval, max_conn_interval, slave_latency, conn_sup_timeout; };
int sd_ble_gap_addr_set(ble_gap_addr_t*) { return NRF_SUCCESS; }
int sd_ble_gap_addr_get(ble_gap_addr_t* a) { memset(a, 0, sizeof(*a)); return NRF_SUCCESS; }
int sd_ble_gap_ppcp_set(ble_gap_conn_params_t*) { return NRF_SUCCESS; }
namespace mesh {
struct Logging { void println(const char*) {} };
Logging& usbLoggingPort() { static Logging port; return port; }
}
static const char* fail_task = nullptr;
static int fail_service = 0;
static bool fail_softdevice = false;
static unsigned last_depth;
extern "C" BaseType_t __wrap_xTaskCreate(TaskFunction_t, const char*,
configSTACK_DEPTH_TYPE, void*, UBaseType_t, TaskHandle_t*);
extern "C" BaseType_t __real_xTaskCreate(TaskFunction_t, const char* name,
configSTACK_DEPTH_TYPE depth, void*, UBaseType_t, TaskHandle_t* out) {
last_depth = depth;
bool fail = fail_task && name && strcmp(name, fail_task) == 0;
if (out) *out = fail ? nullptr : reinterpret_cast<void*>(1);
return fail ? 0 : pdPASS;
}
struct Settings {
template<class... T> void clearBonds(T...) {}
template<class... T> void setMITM(T...) {}
template<class... T> void setPIN(T...) {}
template<class... T> void setIOCaps(T...) {}
template<class... T> void setPairPasskeyCallback(T...) {}
template<class... T> void setPairCompleteCallback(T...) {}
template<class... T> void setConnectCallback(T...) {}
template<class... T> void setDisconnectCallback(T...) {}
template<class... T> void setSecuredCallback(T...) {}
template<class... T> void setType(T...) {}
template<class... T> void addFlags(T...) {}
template<class... T> void addTxPower(T...) {}
template<class... T> void addService(T...) {}
template<class... T> void addName(T...) {}
template<class... T> void setInterval(T...) {}
template<class... T> void setFastTimeout(T...) {}
template<class... T> void restartOnDisconnect(T...) {}
};
struct BluefruitStub {
Settings Security, Periph, Advertising, ScanResponse;
int starts = 0;
void configPrphBandwidth(int) {}
bool begin() {
++starts;
if (fail_softdevice) return false;
TaskHandle_t task;
// Match the pinned core: it ignores both worker creation return values.
__wrap_xTaskCreate(nullptr, "BLE", 1280, nullptr, 3, &task);
__wrap_xTaskCreate(nullptr, "SOC", 200, nullptr, 3, &task);
return true;
}
void setTxPower(int) {}
void setName(const char*) {}
template<class T> void setEventCallback(T) {}
} Bluefruit;
struct Service {
int id;
int begin() { return fail_service == id ? 1 : ERROR_NONE; }
template<class... T> void setPermission(T...) {}
template<class... T> void setRxCallback(T...) {}
template<class... T> void setProperties(T...) {}
template<class... T> void setMaxLen(T...) {}
template<class... T> void setUserDescriptor(T...) {}
template<class... T> void setWriteCallback(T...) {}
};
struct MotaStream {
template<class... T> void setSender(T...) {}
void setActive(bool) {}
};
struct SerialBLEInterface {
@STARTUP_FIELDS@
std::atomic<bool> _successfulConnectionPending{false};
std::atomic<uint32_t> _successfulConnectionStarted{0};
std::atomic<bool> _bondedOnlyRecoveryPending{false}, _advertisingSuppressed{false};
bool _stealth_pair_once = false, _bonded_only = false, _bonded_only_configure_pending = false;
mesh::companion::BluetoothPeerIdentity _pending_bonded_peer;
Service bleuart{1}, _mota_service{2}, _mota_request{3}, _mota_response{4}, bledfu{5};
MotaStream _mota_stream;
static void onPairingPasskey() {}
static void onPairingComplete() {}
static void onConnect() {}
static void onDisconnect() {}
static void onSecured() {}
static void onBLEEvent() {}
static void onBleUartRX() {}
static void sendMotaRequest() {}
static void onMotaResponse() {}
void configureBondedOnlyAdvertising(const mesh::companion::BluetoothPeerIdentity&, bool) {}
bool begin(const char*, const char*, uint32_t, const uint8_t* = nullptr,
bool = false, bool = false,
const mesh::companion::BluetoothPeerIdentity* = nullptr);
};
static SerialBLEInterface* instance = nullptr;
@BEGIN@
int main() {
mesh::nrf52::resetBleTaskStartup();
assert(!mesh::nrf52::bleTasksStarted());
__wrap_xTaskCreate(nullptr, "loop", 1024, nullptr, 1, nullptr);
assert(last_depth == 2048 && !mesh::nrf52::bleTasksStarted());
__wrap_xTaskCreate(nullptr, "callback", 768, nullptr, 1, nullptr);
assert(last_depth == 768);
__wrap_xTaskCreate(nullptr, nullptr, 100, nullptr, 1, nullptr);
assert(last_depth == 100);
for (int fault = 0; fault <= 8; ++fault) {
#if !COMPANION_FEATURE_BLE_MOTA_SOURCE
if (fault >= 5 && fault <= 7) continue;
#endif
fail_softdevice = fault == 1;
fail_task = fault == 2 ? "BLE" : fault == 3 ? "SOC" : nullptr;
fail_service = fault >= 4 ? fault - 3 : 0;
SerialBLEInterface port;
const int starts = Bluefruit.starts;
const bool expected = fault == 0;
assert(port.begin("MC-", "T096", 123456) == expected);
assert(Bluefruit.starts == starts + 1);
assert((instance == &port) == expected);
// Retrying a failed partial init must never allocate another stack/FIFO.
for (int retry = 0; retry < 4; ++retry) {
assert(port.begin("MC-", "T096", 123456) == expected);
assert(Bluefruit.starts == starts + 1);
}
}
}
'''
class Nrf52BleStartupTest(unittest.TestCase):
def test_all_startup_failures_are_reported_without_reinitializing(self):
begin = method((ROOT / "src/helpers/nrf52/SerialBLEInterface.cpp").read_text(),
"bool SerialBLEInterface::begin(")
header = (ROOT / "src/helpers/nrf52/SerialBLEInterface.h").read_text()
# Use the real in-class startup initializers, too.
fields = "\n".join(line for line in header.splitlines()
if "bool _begin_" in line)
self.assertTrue(fields)
source = HARNESS.replace("@BEGIN@", begin).replace("@STARTUP_FIELDS@", fields)
with tempfile.TemporaryDirectory(prefix="meshcore-ble-start-") as temp:
temp = Path(temp)
(temp / "Arduino.h").write_text(RTOS)
for name in ("FreeRTOS.h", "task.h"):
(temp / name).write_text('#include "Arduino.h"\n')
cpp = temp / "startup.cpp"
cpp.write_text(source)
binary = temp / "startup"
for mota in (0, 1):
with self.subTest(mota=mota):
built = subprocess.run([
"c++", "-std=c++17", "-DNRF52_PLATFORM=1",
f"-DCOMPANION_FEATURE_BLE_MOTA_SOURCE={mota}", "-I" + str(temp),
"-I" + str(ROOT / "src"), str(cpp), str(ROOT / "src/Nrf52LoopStack.cpp"),
"-o", str(binary)], text=True, capture_output=True)
self.assertEqual(built.returncode, 0, built.stderr)
result = subprocess.run([str(binary)], text=True, capture_output=True)
self.assertEqual(result.returncode, 0, result.stderr)
if __name__ == "__main__":
unittest.main()
+47
View File
@@ -0,0 +1,47 @@
#!/usr/bin/env python3
"""Run the actual shared OtaContext and byte-exact mOTA transfers under sanitizers."""
from pathlib import Path
import subprocess
import tempfile
import unittest
from test_t096_full_memory import method
ROOT = Path(__file__).resolve().parents[1]
class SharedMotaQueueTest(unittest.TestCase):
def test_context_lifecycle_and_real_transfers_preserve_unread_messages(self):
with tempfile.TemporaryDirectory(prefix="meshcore-mota-queue-") as temp:
binary = Path(temp) / "transfer"
tinf = Path(temp) / "tinf.o"
control = method((ROOT / "examples/companion_radio/main.cpp").read_text(),
"class Nrf52BleMotaSourceControl")
(Path(temp) / "ble_control_under_test.h").write_text(control + ";\n")
subprocess.run([
"cc", "-DENABLE_OTA=1", "-fsanitize=address,undefined", "-g",
"-c", str(ROOT / "src/helpers/ota/OtaTinf.c"), "-o", str(tinf),
], check=True)
sources = [
"test/fixtures/shared_mota_queue/test_shared_mota_queue.cpp",
"src/helpers/ota/OtaContext.cpp", "src/helpers/ota/OtaManager.cpp",
"src/helpers/ota/OtaProtocol.cpp", "src/helpers/ota/MotaContainer.cpp",
"src/helpers/ota/MerkleTree.cpp", "src/helpers/ota/OtaDeflate.cpp",
"src/Utils.cpp",
]
built = subprocess.run([
"c++", "-std=c++17", "-fsanitize=address,undefined", "-g",
"-DNRF52_PLATFORM=1", "-DOTA_SEEDER_ONLY=1",
"-DCOMPANION_RADIO_FULL=1", "-DOTA_SHARED_COMPANION_QUEUE=1",
"-DENABLE_OTA=1", "-I", str(ROOT / "src"),
"-I", str(ROOT / "test/mocks"), "-I", temp,
*[str(ROOT / source) for source in sources], str(tinf),
"-o", str(binary),
], text=True, capture_output=True)
self.assertEqual(built.returncode, 0, built.stderr)
result = subprocess.run([str(binary)], text=True, capture_output=True)
self.assertEqual(result.returncode, 0, result.stderr)
if __name__ == "__main__":
unittest.main()
+227
View File
@@ -0,0 +1,227 @@
#!/usr/bin/env python3
"""Exercise the Full overlay, real linker reserve, and sensor allocation failure."""
from pathlib import Path
import re
import subprocess
import tempfile
import unittest
ROOT = Path(__file__).resolve().parents[1]
def method(text, signature):
start = text.index(signature)
end = text.index("{", start) + 1
depth = 1
while depth:
depth += (text[end] == "{") - (text[end] == "}")
end += 1
return text[start:end]
def full_flags(target):
result = subprocess.run([
"bash", "-c", r'''
source build.sh
PIO_ENV_PLATFORM_BY_NAME["$1"]=NRF52_PLATFORM
pio_env_option_contains() { return 0; }
apply_companion_radio_full_profile "$1" "$1"
printf '%s\n%s\n' "$PLATFORMIO_BUILD_FLAGS" "$PLATFORMIO_BUILD_UNFLAGS"
''', "test", target], cwd=ROOT, text=True, capture_output=True, check=True)
return result.stdout
class T096FullMemoryTest(unittest.TestCase):
def test_t096_full_overlay_preserves_features_and_reserves_heap(self):
for suffix in ("femon", "femoff"):
with self.subTest(suffix=suffix):
flags = full_flags("Heltec_t096_companion_radio_full_" + suffix)
self.assertIn("-DOFFLINE_QUEUE_SIZE=256", flags.splitlines()[0])
self.assertNotIn("-DOFFLINE_QUEUE_SIZE=128", flags.splitlines()[0])
self.assertIn("-DOTA_SHARED_COMPANION_QUEUE=1", flags)
self.assertIn("--defsym=__mesh_nrf52_min_heap_size=73728", flags)
for feature in ("ENABLE_USB_INTERFACE", "OTA_SEEDER_ONLY",
"COMPANION_FEATURE_BLE_MOTA_SOURCE",
"COMPANION_FEATURE_USB_MOTA_SOURCE",
"COMPANION_FEATURE_DEDICATED_USB_LOGGING"):
self.assertIn("-D" + feature + "=1", flags)
self.assertNotIn("-DMAX_CONTACTS", flags)
self.assertNotIn("-DMAX_GROUP_CHANNELS", flags)
def test_other_nrf52_profiles_keep_their_queue_policy(self):
for target in ("RAK_4631_companion_radio_full",
"Heltec_t096_companion_radio_ble_femon"):
with self.subTest(target=target):
flags = full_flags(target)
self.assertNotIn("-DOTA_SHARED_COMPANION_QUEUE", flags)
self.assertNotIn("__mesh_nrf52_min_heap_size", flags)
def test_real_linker_rejects_release_heap_and_enforces_boundary(self):
flags = full_flags("Heltec_t096_companion_radio_full_femon")
reserve = int(re.search(r"__mesh_nrf52_min_heap_size=(\d+)", flags)[1])
self.assertIn('INCLUDE "boards/nrf52_heap_reserve.ld"',
(ROOT / "boards/nrf52840_s140_v6_extrafs.ld").read_text())
with tempfile.TemporaryDirectory(prefix="meshcore-heap-") as temp:
obj = Path(temp) / "empty.o"
subprocess.run(["cc", "-x", "c", "-c", "-", "-o", str(obj)],
input="int linked_fixture;", text=True, check=True)
# Released 26303793 leaves 54,724 bytes between the real heap
# symbols. Static RAM fitting alone previously admitted it.
for size, minimum, accepted in (
(54724, reserve, False), (reserve - 1, reserve, False),
(reserve, reserve, True), (reserve + 16384, reserve, True),
(-1, reserve, False), (1024, None, True),
):
with self.subTest(size=size, minimum=minimum):
command = ["ld", "-r", str(obj), "-o", str(Path(temp) / "linked.o"),
"-T", str(ROOT / "boards/nrf52_heap_reserve.ld"),
"--defsym=__HeapBase=0x20006008",
f"--defsym=__HeapLimit={0x20006008 + size}"]
if minimum is not None:
command += [f"--defsym=__mesh_nrf52_min_heap_size={minimum}"]
result = subprocess.run(command, text=True, capture_output=True)
self.assertEqual(result.returncode == 0, accepted, result.stderr)
if not accepted:
self.assertIn("nRF52", result.stderr)
def test_sensor_page_survives_failed_cayenne_allocation(self):
refresh = method((ROOT / "examples/companion_radio/ui-new/UITask.cpp").read_text(),
"void refresh_sensors()")
harness = r'''
#include <cassert>
#include <cstdint>
#include <stdexcept>
#define AUTO_OFF_MILLIS 15000
#define UI_RECENT_LIST_SIZE 3
#define TELEM_CHANNEL_SELF 0
unsigned long millis() { return 100; }
struct Lpp {
uint8_t storage[8];
bool allocated = false;
uint8_t size = 0;
uint8_t* getBuffer() { return allocated ? storage : nullptr; }
void reset() { size = 0; }
uint8_t getSize() { return size; }
void addVoltage(int, float) {
if (!getBuffer()) throw std::runtime_error("sensor menu NULL write");
size = 4;
}
};
struct LPPReader {
bool pending;
LPPReader(uint8_t* buf, int size) : pending(buf && size) {}
bool readHeader(uint8_t&, uint8_t&) { bool p = pending; pending = false; return p; }
void skipData(uint8_t) {}
};
struct Board { int getBattMilliVolts() { return 4000; } } board;
struct Sensors { int calls = 0; void querySensors(int, Lpp&) { ++calls; } } sensors;
struct Home {
Lpp sensors_lpp;
int sensors_nb = 5, sensors_scroll_offset = 4, next_sensors_refresh = 0;
bool sensors_scroll = true;
@REFRESH@
};
int main() {
Home home;
home.refresh_sensors();
assert(home.sensors_nb == 0 && !home.sensors_scroll);
assert(home.sensors_scroll_offset == 0 && sensors.calls == 0);
home.sensors_lpp.allocated = true;
home.refresh_sensors();
assert(home.sensors_nb == 1 && sensors.calls == 1);
assert(home.next_sensors_refresh == 5100);
home.refresh_sensors();
assert(sensors.calls == 1);
}
'''.replace("@REFRESH@", refresh)
with tempfile.TemporaryDirectory(prefix="meshcore-sensor-oom-") as temp:
binary = Path(temp) / "menu"
built = subprocess.run(["c++", "-std=c++17", "-x", "c++", "-",
"-o", str(binary)], input=harness,
text=True, capture_output=True)
self.assertEqual(built.returncode, 0, built.stderr)
result = subprocess.run([str(binary)], text=True, capture_output=True)
self.assertEqual(result.returncode, 0, result.stderr)
def test_shared_queue_preserves_fifo_across_wrap_and_workspace_reuse(self):
harness = r'''
#include <helpers/BorrowableFrameBuffer.h>
#include <cassert>
#include <cstdint>
#include <deque>
#include <cstring>
struct Frame { uint8_t len; uint8_t buf[176]; };
struct Workspace {
static int alive;
uint32_t words[4906]; // matches the roughly 19 KiB embedded mOTA context
Workspace() { ++alive; memset(words, 0xA5, sizeof words); }
~Workspace() { --alive; memset(words, 0x5A, sizeof words); }
};
int Workspace::alive = 0;
using Buffer = mesh::BorrowableFrameBuffer<Frame, 256, 128, Workspace>;
int main() {
Buffer buffer;
int head = 0, count = 0;
unsigned sequence = 0;
std::deque<unsigned> expected;
auto add = [&]() {
assert(count < int(buffer.capacity()));
Frame& frame = buffer.at((head + count) % buffer.capacity());
frame.len = 176;
memset(frame.buf, sequence % 251, sizeof frame.buf);
memcpy(frame.buf, &sequence, sizeof sequence);
expected.push_back(sequence++);
++count;
};
auto pop = [&]() {
assert(count > 0);
const Frame& frame = buffer.at(head);
unsigned id;
memcpy(&id, frame.buf, sizeof id);
assert(frame.len == 176 && id == expected.front());
for (unsigned i = sizeof id; i < sizeof frame.buf; ++i)
assert(frame.buf[i] == id % 251);
expected.pop_front();
--count;
head = count ? (head + 1) % buffer.capacity() : 0;
};
for (int cycle = 0; cycle < 300; ++cycle) {
while (count < 256) add();
// A full queue refuses the loan without dropping or reordering messages.
int previous_head = head;
assert(!buffer.acquire(count, head));
assert(count == 256 && head == previous_head && Workspace::alive == 0);
while (count > 129) pop();
assert(!buffer.acquire(count, head));
pop();
// Exercise every possible wrapped head at the exact 128-frame boundary.
for (int i = 0; i < cycle % 256; ++i) { pop(); add(); }
Workspace* workspace = buffer.acquire(count, head);
assert(workspace && head == 0 && buffer.capacity() == 128);
assert(Workspace::alive == 1 && buffer.acquire(count, head) == workspace);
for (auto& word : workspace->words) word = 0xC0DEC0DE;
for (int i = 0; i < cycle % 128; ++i) { pop(); add(); }
buffer.release(head);
assert(head == 0 && buffer.capacity() == 256 && Workspace::alive == 0);
buffer.release(head); // repeated stop is harmless
while (count < 256) add();
while (count) pop();
}
assert(expected.empty());
assert(buffer.acquire(count, head)); // empty queue / destructor while borrowed
}
'''
with tempfile.TemporaryDirectory(prefix="meshcore-shared-queue-") as temp:
binary = Path(temp) / "shared_queue"
built = subprocess.run([
"c++", "-std=c++11", "-fsanitize=address,undefined", "-g",
"-I", str(ROOT / "src"), "-x", "c++", "-", "-o", str(binary),
], input=harness, text=True, capture_output=True)
self.assertEqual(built.returncode, 0, built.stderr)
result = subprocess.run([str(binary)], text=True, capture_output=True)
self.assertEqual(result.returncode, 0, result.stderr)
if __name__ == "__main__":
unittest.main()