Share radio2 raw transport for Ethernet and negotiated direct LoRa OTA
This commit is contained in:
1 parent
e57ab1309f
commit
23c9648789
77 files changed
+7061
-260
No files matched your search
@@ -166,6 +166,16 @@ class DataStore {
|
||||
#endif
|
||||
struct IdentityAdapter {
|
||||
bool recover(const char*) { return true; }
|
||||
#if defined(ESP32_PLATFORM)
|
||||
IdentityLoadResult loadResult(const char* name, mesh::LocalIdentity& identity) {
|
||||
// The ESP32 entry point now delegates absence/error discrimination to
|
||||
// IdentityStore, not a separate exists() short circuit. This fixture's
|
||||
// adapter has no NVS; end-to-end migration cases use the real store.
|
||||
if (filesystem.stat_error) return IdentityLoadResult::Unreadable;
|
||||
if (!filesystem.files.count(identity_path)) return IdentityLoadResult::Missing;
|
||||
return load(name, identity) ? IdentityLoadResult::Loaded : IdentityLoadResult::Unreadable;
|
||||
}
|
||||
#endif
|
||||
bool load(const char*, mesh::LocalIdentity&) {
|
||||
File file = filesystem.open(identity_path);
|
||||
uint8_t data[96];
|
||||
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
#pragma once
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
namespace fake { inline uint32_t now = 0; }
|
||||
inline unsigned long millis() { return fake::now; }
|
||||
Vendored
+97
@@ -0,0 +1,97 @@
|
||||
#pragma once
|
||||
#include <Arduino.h>
|
||||
#include <algorithm>
|
||||
#include <deque>
|
||||
#include <map>
|
||||
#include <memory>
|
||||
#include <vector>
|
||||
|
||||
static constexpr int WIFI_OFF = 0, WIFI_STA = 1, WIFI_AP = 2, WIFI_AP_STA = 3;
|
||||
static constexpr int WL_DISCONNECTED = 6, WL_CONNECTED = 3;
|
||||
|
||||
class IPAddress {
|
||||
uint32_t _value;
|
||||
public:
|
||||
explicit IPAddress(uint32_t value = 0) : _value(value) {}
|
||||
operator uint32_t() const { return _value; }
|
||||
};
|
||||
|
||||
struct FakeSocket {
|
||||
bool connected = true;
|
||||
bool eof = false;
|
||||
int readError = 0, writeError = 0;
|
||||
size_t writeQuota = 128;
|
||||
size_t reads = 0, writes = 0;
|
||||
std::deque<uint8_t> input;
|
||||
std::vector<uint8_t> output;
|
||||
};
|
||||
|
||||
namespace fake {
|
||||
inline std::map<int, std::shared_ptr<FakeSocket>> sockets;
|
||||
inline std::deque<int> pending;
|
||||
inline int nextFd = 3;
|
||||
inline uint32_t boundAddress = 0;
|
||||
inline uint16_t boundPort = 0;
|
||||
inline bool listenFails = false;
|
||||
inline unsigned begins = 0, ends = 0;
|
||||
inline int newSocket() {
|
||||
const int fd = nextFd++;
|
||||
sockets[fd] = std::make_shared<FakeSocket>();
|
||||
pending.push_back(fd);
|
||||
return fd;
|
||||
}
|
||||
}
|
||||
|
||||
class WiFiClient {
|
||||
std::shared_ptr<FakeSocket> _socket;
|
||||
int _fd = -1;
|
||||
public:
|
||||
WiFiClient() = default;
|
||||
explicit WiFiClient(int fd) : _socket(fake::sockets.at(fd)), _fd(fd) {}
|
||||
explicit operator bool() { return connected(); }
|
||||
bool connected() { return _socket && _socket->connected; }
|
||||
void stop() { if (_socket) _socket->connected = false; _socket.reset(); _fd = -1; }
|
||||
void setNoDelay(bool) {}
|
||||
int fd() const { return _fd; }
|
||||
};
|
||||
|
||||
class WiFiServer {
|
||||
uint32_t _address;
|
||||
uint16_t _port;
|
||||
bool _listening = false;
|
||||
public:
|
||||
explicit WiFiServer(uint16_t port = 80, uint8_t = 4) : _address(0), _port(port) {}
|
||||
WiFiServer(const IPAddress& address, uint16_t port, uint8_t = 4)
|
||||
: _address(address), _port(port) {}
|
||||
void begin() {
|
||||
++fake::begins;
|
||||
_listening = !fake::listenFails;
|
||||
if (_listening) { fake::boundAddress = _address; fake::boundPort = _port; }
|
||||
}
|
||||
void end() {
|
||||
++fake::ends;
|
||||
_listening = false;
|
||||
while (!fake::pending.empty()) {
|
||||
fake::sockets.at(fake::pending.front())->connected = false;
|
||||
fake::pending.pop_front();
|
||||
}
|
||||
}
|
||||
explicit operator bool() { return _listening; }
|
||||
WiFiClient available() {
|
||||
if (!_listening || fake::pending.empty()) return WiFiClient();
|
||||
const int fd = fake::pending.front();
|
||||
fake::pending.pop_front();
|
||||
return WiFiClient(fd);
|
||||
}
|
||||
};
|
||||
|
||||
class WiFiClass {
|
||||
public:
|
||||
int mode = WIFI_STA;
|
||||
int state = WL_CONNECTED;
|
||||
uint32_t address = 0x01020304;
|
||||
int getMode() const { return mode; }
|
||||
int status() const { return state; }
|
||||
IPAddress localIP() const { return IPAddress(address); }
|
||||
};
|
||||
inline WiFiClass WiFi;
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
#pragma once
|
||||
#include <WiFi.h>
|
||||
#include <errno.h>
|
||||
#include <string.h>
|
||||
|
||||
static constexpr int MSG_DONTWAIT = 0x40;
|
||||
|
||||
inline int recv(int fd, void* destination, size_t length, int flags) {
|
||||
if (flags != MSG_DONTWAIT) { errno = EINVAL; return -1; }
|
||||
FakeSocket& socket = *fake::sockets.at(fd);
|
||||
++socket.reads;
|
||||
if (socket.readError) { errno = socket.readError; return -1; }
|
||||
if (!socket.connected || (socket.eof && socket.input.empty())) return 0;
|
||||
if (socket.input.empty()) { errno = EAGAIN; return -1; }
|
||||
length = std::min(length, socket.input.size());
|
||||
for (size_t i = 0; i < length; ++i) {
|
||||
static_cast<uint8_t*>(destination)[i] = socket.input.front();
|
||||
socket.input.pop_front();
|
||||
}
|
||||
return static_cast<int>(length);
|
||||
}
|
||||
|
||||
inline int send(int fd, const void* source, size_t length, int flags) {
|
||||
if (flags != MSG_DONTWAIT) { errno = EINVAL; return -1; }
|
||||
FakeSocket& socket = *fake::sockets.at(fd);
|
||||
++socket.writes;
|
||||
if (socket.writeError) { errno = socket.writeError; return -1; }
|
||||
if (!socket.connected) { errno = EPIPE; return -1; }
|
||||
if (!socket.writeQuota) { errno = EAGAIN; return -1; }
|
||||
length = std::min(length, socket.writeQuota);
|
||||
const uint8_t* bytes = static_cast<const uint8_t*>(source);
|
||||
socket.output.insert(socket.output.end(), bytes, bytes + length);
|
||||
return static_cast<int>(length);
|
||||
}
|
||||
+320
@@ -0,0 +1,320 @@
|
||||
#include <cassert>
|
||||
#include <cstring>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <helpers/esp32/EthernetKissServer.h>
|
||||
|
||||
using namespace mesh::ethernet;
|
||||
|
||||
static std::vector<uint8_t> frame(size_t length = 244) {
|
||||
std::vector<uint8_t> data(length);
|
||||
for (size_t i = 0; i < length; ++i) data[i] = static_cast<uint8_t>(i);
|
||||
return data;
|
||||
}
|
||||
|
||||
static std::vector<uint8_t> encoded(const std::vector<uint8_t>& data, uint8_t command = 0) {
|
||||
std::vector<uint8_t> output{Fend, command};
|
||||
for (const uint8_t byte : data) {
|
||||
if (byte == Fend || byte == Fesc) {
|
||||
output.push_back(Fesc);
|
||||
output.push_back(byte == Fend ? Tfend : Tfesc);
|
||||
} else output.push_back(byte);
|
||||
}
|
||||
output.push_back(Fend);
|
||||
return output;
|
||||
}
|
||||
|
||||
static void feed(KissCodec& codec, const std::vector<uint8_t>& input) {
|
||||
for (uint8_t byte : input) assert(codec.feed(byte));
|
||||
}
|
||||
|
||||
static void expect(KissCodec& codec, const std::vector<uint8_t>& expected) {
|
||||
const uint8_t* bytes;
|
||||
size_t length;
|
||||
assert(codec.peekTransmit(bytes, length));
|
||||
assert(length == expected.size() && !memcmp(bytes, expected.data(), length));
|
||||
codec.consumeTransmit();
|
||||
}
|
||||
|
||||
static void append(int fd, const std::vector<uint8_t>& data) {
|
||||
auto& input = fake::sockets.at(fd)->input;
|
||||
input.insert(input.end(), data.begin(), data.end());
|
||||
}
|
||||
|
||||
static int connect(KissServer& server) {
|
||||
server.loop(true);
|
||||
const int fd = fake::newSocket();
|
||||
server.loop(true);
|
||||
assert(server.status().connected);
|
||||
return fd;
|
||||
}
|
||||
|
||||
static void codecRoundtrip() {
|
||||
for (size_t length = MinimumFrameSize; length <= MaxFrameSize; ++length) {
|
||||
const auto data = frame(length);
|
||||
const auto wire = encoded(data);
|
||||
for (size_t cut = 0; cut <= wire.size(); ++cut) {
|
||||
KissCodec codec;
|
||||
for (size_t i = 0; i < cut; ++i) assert(codec.feed(wire[i]));
|
||||
for (size_t i = cut; i < wire.size(); ++i) assert(codec.feed(wire[i]));
|
||||
expect(codec, data);
|
||||
assert(codec.receivedFrames() == 1);
|
||||
}
|
||||
}
|
||||
KissCodec codec;
|
||||
const std::vector<uint8_t> worst(MaxFrameSize, Fend);
|
||||
assert(codec.queueReceive(worst.data(), worst.size()));
|
||||
const uint8_t* bytes;
|
||||
size_t length;
|
||||
assert(codec.peekOutput(bytes, length) && length == MaxEncodedSize);
|
||||
assert(std::vector<uint8_t>(bytes, bytes + length) == encoded(worst));
|
||||
codec.consumeOutput(length);
|
||||
assert(codec.sentFrames() == 1);
|
||||
}
|
||||
|
||||
static void codecMalformed() {
|
||||
KissCodec codec;
|
||||
feed(codec, {1, 2, 3, Fesc, Tfend});
|
||||
feed(codec, encoded(frame(), 0x10)); // Not port 0.
|
||||
feed(codec, encoded(frame(), 0x01)); // Not DATA.
|
||||
feed(codec, encoded(frame(13)));
|
||||
feed(codec, encoded(frame(256)));
|
||||
feed(codec, {Fend, 0, 1, Fesc, 42, 2, Fend});
|
||||
feed(codec, {Fend, 0, Fesc, Fend});
|
||||
assert(codec.pendingTransmit() == 0 && codec.malformedFrames() == 4);
|
||||
feed(codec, encoded(frame()));
|
||||
expect(codec, frame());
|
||||
assert(!codec.queueReceive(nullptr, 15));
|
||||
assert(!codec.queueReceive(frame(13).data(), 13));
|
||||
assert(!codec.queueReceive(frame(256).data(), 256));
|
||||
}
|
||||
|
||||
static void codecBackpressure() {
|
||||
KissCodec codec;
|
||||
const auto data = frame();
|
||||
feed(codec, encoded(data));
|
||||
feed(codec, encoded(data));
|
||||
assert(!codec.canAcceptByte() && !codec.feed(0));
|
||||
expect(codec, data);
|
||||
assert(codec.canAcceptByte());
|
||||
feed(codec, encoded(data));
|
||||
expect(codec, data);
|
||||
expect(codec, data);
|
||||
assert(codec.queueReceive(data.data(), data.size()));
|
||||
assert(codec.queueReceive(data.data(), data.size()));
|
||||
assert(!codec.queueReceive(data.data(), data.size()));
|
||||
std::vector<uint8_t> actual;
|
||||
const uint8_t* bytes;
|
||||
size_t length;
|
||||
while (codec.peekOutput(bytes, length)) {
|
||||
const size_t count = length < 7 ? length : 7;
|
||||
actual.insert(actual.end(), bytes, bytes + count);
|
||||
codec.consumeOutput(count);
|
||||
}
|
||||
auto expected = encoded(data);
|
||||
const auto second = expected;
|
||||
expected.insert(expected.end(), second.begin(), second.end());
|
||||
assert(actual == expected && codec.sentFrames() == 2 && codec.droppedFrames() == 1);
|
||||
}
|
||||
|
||||
static void codecResetFuzz() {
|
||||
KissCodec codec;
|
||||
auto data = frame();
|
||||
feed(codec, encoded(data));
|
||||
feed(codec, {Fend, 0, Fesc});
|
||||
assert(codec.queueReceive(data.data(), data.size()));
|
||||
codec.consumeOutput(5);
|
||||
codec.resetPending();
|
||||
assert(!codec.pendingReceive() && !codec.pendingTransmit());
|
||||
assert(codec.receivedFrames() == 1);
|
||||
feed(codec, {Tfend, 1, 2, 3, Fend});
|
||||
assert(!codec.pendingTransmit());
|
||||
uint32_t random = 0x12345678;
|
||||
for (unsigned i = 0; i < 100000; ++i) {
|
||||
random = random * 1664525U + 1013904223U;
|
||||
if ((random & 127) == 0) codec.resetPending();
|
||||
else if ((random & 7) == 0) codec.consumeTransmit();
|
||||
else codec.feed(static_cast<uint8_t>(random >> 24));
|
||||
assert(codec.pendingTransmit() <= QueueDepth);
|
||||
}
|
||||
codec.resetPending();
|
||||
feed(codec, encoded(data));
|
||||
expect(codec, data);
|
||||
}
|
||||
|
||||
static void serverStation() {
|
||||
KissServer server;
|
||||
server.loop(false);
|
||||
assert(!fake::begins && !server.status().enabled);
|
||||
WiFi.mode = WIFI_AP;
|
||||
server.loop(true);
|
||||
assert(!fake::begins && !server.status().listening);
|
||||
WiFi.mode = WIFI_AP_STA;
|
||||
WiFi.address = 0;
|
||||
server.loop(true);
|
||||
assert(!fake::begins);
|
||||
WiFi.address = 0x0a020304;
|
||||
server.loop(true);
|
||||
assert(server.status().listening && fake::boundAddress == WiFi.address);
|
||||
assert(fake::boundPort == 5003);
|
||||
const int fd = fake::newSocket();
|
||||
server.loop(true);
|
||||
assert(server.status().accepted == 1);
|
||||
const int extra = fake::newSocket();
|
||||
server.loop(true);
|
||||
assert(!fake::sockets.at(extra)->connected && fake::sockets.at(fd)->connected);
|
||||
assert(server.status().rejected == 1);
|
||||
server.loop(false);
|
||||
assert(!fake::sockets.at(fd)->connected && !server.status().listening);
|
||||
assert(server.status().disconnects == 1);
|
||||
}
|
||||
|
||||
static void serverBudgetBackpressure() {
|
||||
KissServer server;
|
||||
const int fd = connect(server);
|
||||
const auto data = frame(14);
|
||||
const auto wire = encoded(data);
|
||||
for (unsigned i = 0; i < 20; ++i) append(fd, wire);
|
||||
const auto socket = fake::sockets.at(fd);
|
||||
const size_t before = socket->input.size();
|
||||
server.loop(true);
|
||||
assert(server.status().pendingTransmit == 2);
|
||||
assert(before - socket->input.size() == wire.size() * 2);
|
||||
const size_t paused = socket->input.size();
|
||||
server.loop(true);
|
||||
assert(socket->input.size() == paused);
|
||||
const uint8_t* bytes;
|
||||
size_t length;
|
||||
assert(server.peekTransmit(bytes, length));
|
||||
assert(length == data.size() && !memcmp(bytes, data.data(), length));
|
||||
server.consumeTransmit();
|
||||
server.loop(true);
|
||||
assert(server.status().pendingTransmit == 2);
|
||||
const int oldPending = fake::newSocket();
|
||||
server.resetPending();
|
||||
assert(!socket->connected && server.status().pendingTransmit == 0);
|
||||
assert(!fake::sockets.at(oldPending)->connected && !server.status().listening);
|
||||
const int next = fake::newSocket();
|
||||
server.loop(true);
|
||||
const auto large = encoded(frame());
|
||||
append(next, large);
|
||||
server.loop(true);
|
||||
assert(fake::sockets.at(next)->reads == KissServer::ReadBudget + 1); // accept poll read + bounded poll
|
||||
assert(!server.status().pendingTransmit);
|
||||
server.loop(true);
|
||||
assert(server.status().pendingTransmit == 1);
|
||||
}
|
||||
|
||||
static void serverPartialWrites() {
|
||||
KissServer server;
|
||||
const int fd = connect(server);
|
||||
const auto socket = fake::sockets.at(fd);
|
||||
const auto data = frame();
|
||||
assert(server.queueReceive(data.data(), data.size()));
|
||||
socket->writeQuota = 0;
|
||||
for (unsigned i = 0; i < 50; ++i) server.loop(true);
|
||||
assert(socket->output.empty() && server.status().pendingReceive == 1);
|
||||
socket->writeQuota = 3;
|
||||
while (server.status().pendingReceive) {
|
||||
const size_t before = socket->output.size();
|
||||
server.loop(true);
|
||||
assert(socket->output.size() - before <= 3);
|
||||
}
|
||||
assert(socket->output == encoded(data) && server.status().txFrames == 1);
|
||||
socket->writeQuota = 5000;
|
||||
assert(server.queueReceive(data.data(), data.size()));
|
||||
const size_t before = socket->output.size();
|
||||
server.loop(true);
|
||||
assert(socket->output.size() - before == KissServer::WriteBudget);
|
||||
}
|
||||
|
||||
static void serverSessionReset() {
|
||||
KissServer server;
|
||||
int fd = connect(server);
|
||||
const auto data = frame(14);
|
||||
append(fd, encoded(data));
|
||||
append(fd, {Fend, 0, 1, Fesc});
|
||||
server.loop(true);
|
||||
assert(server.status().pendingTransmit == 1);
|
||||
assert(server.queueReceive(data.data(), data.size()));
|
||||
fake::sockets.at(fd)->writeQuota = 1;
|
||||
server.loop(true);
|
||||
fake::sockets.at(fd)->connected = false;
|
||||
const int next = fake::newSocket();
|
||||
server.loop(true);
|
||||
assert(server.status().connected && server.status().accepted == 2);
|
||||
assert(!server.status().pendingTransmit && !server.status().pendingReceive);
|
||||
assert(fake::sockets.at(next)->output.empty());
|
||||
append(next, {Tfend, 1, 2, Fend});
|
||||
server.loop(true);
|
||||
assert(!server.status().pendingTransmit);
|
||||
append(next, encoded(data));
|
||||
server.loop(true);
|
||||
assert(server.status().pendingTransmit == 1);
|
||||
WiFi.address += 1;
|
||||
server.loop(true);
|
||||
assert(!server.status().connected && !server.status().pendingTransmit);
|
||||
assert(!fake::sockets.at(next)->connected && fake::boundAddress == WiFi.address);
|
||||
fd = fake::newSocket();
|
||||
server.loop(true);
|
||||
append(fd, encoded(data));
|
||||
server.loop(true);
|
||||
WiFi.state = WL_DISCONNECTED;
|
||||
server.loop(true);
|
||||
assert(!server.status().listening && !server.status().connected);
|
||||
assert(!server.status().pendingTransmit);
|
||||
}
|
||||
|
||||
static void serverFailures() {
|
||||
KissServer server;
|
||||
fake::listenFails = true;
|
||||
server.loop(true);
|
||||
assert(server.status().listenFailures == 1);
|
||||
for (unsigned i = 0; i < 100; ++i) server.loop(true);
|
||||
assert(fake::begins == 1);
|
||||
fake::now = 1000;
|
||||
server.loop(true);
|
||||
assert(fake::begins == 2);
|
||||
fake::listenFails = false;
|
||||
fake::now = 2000;
|
||||
server.loop(true);
|
||||
assert(server.status().listening);
|
||||
int fd = fake::newSocket();
|
||||
server.loop(true);
|
||||
fake::sockets.at(fd)->readError = EINTR;
|
||||
server.loop(true);
|
||||
assert(server.status().connected);
|
||||
fake::sockets.at(fd)->readError = ECONNRESET;
|
||||
server.loop(true);
|
||||
assert(!server.status().connected);
|
||||
fd = fake::newSocket();
|
||||
server.loop(true);
|
||||
const auto data = frame(14);
|
||||
assert(server.queueReceive(data.data(), data.size()));
|
||||
fake::sockets.at(fd)->writeError = EAGAIN;
|
||||
server.loop(true);
|
||||
assert(server.status().connected && server.status().pendingReceive == 1);
|
||||
fake::sockets.at(fd)->writeError = EPIPE;
|
||||
server.loop(true);
|
||||
assert(!server.status().connected && !server.status().pendingReceive);
|
||||
fd = fake::newSocket();
|
||||
server.loop(true);
|
||||
fake::sockets.at(fd)->eof = true;
|
||||
server.loop(true);
|
||||
assert(!server.status().connected);
|
||||
}
|
||||
|
||||
int main(int argc, char** argv) {
|
||||
assert(argc == 2);
|
||||
const std::string test = argv[1];
|
||||
if (test == "codec-roundtrip") codecRoundtrip();
|
||||
else if (test == "codec-malformed") codecMalformed();
|
||||
else if (test == "codec-backpressure") codecBackpressure();
|
||||
else if (test == "codec-reset-fuzz") codecResetFuzz();
|
||||
else if (test == "server-station") serverStation();
|
||||
else if (test == "server-budget-backpressure") serverBudgetBackpressure();
|
||||
else if (test == "server-partial-writes") serverPartialWrites();
|
||||
else if (test == "server-session-reset") serverSessionReset();
|
||||
else if (test == "server-failures") serverFailures();
|
||||
else assert(false);
|
||||
}
|
||||
+37
-2
@@ -39,7 +39,8 @@ struct OtaManager {
|
||||
enum FetchState { IDLE, WANT_MANIFEST, WANT_LEAVES, VERIFYING_STAGED, FETCHING, COMPLETE, PAUSED, FAILED };
|
||||
enum FetchError { FETCH_ERROR_MANIFEST, FETCH_ERROR_HASH_ALGO, FETCH_ERROR_VERSION,
|
||||
FETCH_ERROR_CODEC, FETCH_ERROR_GEOMETRY, FETCH_ERROR_TOO_LARGE, FETCH_ERROR_STORAGE,
|
||||
FETCH_ERROR_INTEGRITY, FETCH_ERROR_MANIFEST_TIMEOUT, FETCH_ERROR_LEAVES_TIMEOUT };
|
||||
FETCH_ERROR_INTEGRITY, FETCH_ERROR_MANIFEST_TIMEOUT, FETCH_ERROR_LEAVES_TIMEOUT,
|
||||
FETCH_ERROR_RADIO_SESSION };
|
||||
struct CatRow {
|
||||
uint8_t mid[4] = {1, 2, 3, 4};
|
||||
uint32_t target_id = 0, fw_version = 0x01020300, last_ms = 9000;
|
||||
@@ -49,6 +50,8 @@ struct OtaManager {
|
||||
unsigned count = 0, queries = 0, clock_calls = 0, speed_calls = 0;
|
||||
uint32_t target_id = 0;
|
||||
FetchState state = IDLE;
|
||||
FetchError error = FETCH_ERROR_STORAGE;
|
||||
bool direct = false, direct_confirmed = false;
|
||||
bool codec_supported = true;
|
||||
uint8_t served = 3;
|
||||
float adaptivePacketSpeed() const { return 2.5f; }
|
||||
@@ -58,6 +61,8 @@ struct OtaManager {
|
||||
uint16_t catalogCount() const { return count; }
|
||||
unsigned sourceCount() const { return 2; }
|
||||
FetchState fetchState() const { return state; }
|
||||
bool directFetchActive() const { return direct; }
|
||||
bool directFetchConfirmed() const { return direct && direct_confirmed; }
|
||||
const uint8_t* fetchManifestId() const { return rows[0].mid; }
|
||||
uint32_t target() const { return target_id; }
|
||||
const CatRow* catalogRow(uint16_t index) const { return index < count ? &rows[index] : nullptr; }
|
||||
@@ -66,7 +71,7 @@ struct OtaManager {
|
||||
void servedDigest(uint8_t* digest) const { memcpy(digest, rows[0].mid, 4); }
|
||||
unsigned blocksHave() const { return 1; }
|
||||
unsigned blocksTotal() const { return 2; }
|
||||
FetchError fetchError() const { return FETCH_ERROR_STORAGE; }
|
||||
FetchError fetchError() const { return error; }
|
||||
bool fetched_is_bootloader() const { return false; }
|
||||
};
|
||||
struct OtaContext {
|
||||
@@ -199,6 +204,35 @@ static void listing_tests() {
|
||||
context.manager.rows[0].flags = MFLAG_BOOTLOADER;
|
||||
invoke("ota ls", reply); assert(strstr(reply.text, "[bootloader unsupported]"));
|
||||
}
|
||||
static void direct_status_tests() {
|
||||
reset(); Reply reply;
|
||||
context.manager.state = OtaManager::FETCHING;
|
||||
context.manager.direct = true;
|
||||
invoke("ota status", reply);
|
||||
#if !defined(OTA_SEEDER_ONLY)
|
||||
assert(strstr(reply.text, "direct240 probe"));
|
||||
context.manager.direct_confirmed = true;
|
||||
invoke("ota status", reply);
|
||||
assert(strstr(reply.text, "direct240") && !strstr(reply.text, "probe"));
|
||||
context.manager.state = OtaManager::COMPLETE;
|
||||
invoke("ota status", reply);
|
||||
assert(strstr(reply.text, "ready to install") && !strstr(reply.text, "direct240"));
|
||||
context.manager.state = OtaManager::PAUSED;
|
||||
invoke("ota status", reply);
|
||||
assert(strstr(reply.text, "folder link lost") && !strstr(reply.text, "direct240"));
|
||||
context.manager.state = OtaManager::FETCHING;
|
||||
context.manager.direct = false;
|
||||
invoke("ota status", reply);
|
||||
assert(!strstr(reply.text, "direct240"));
|
||||
context.manager.state = OtaManager::FAILED;
|
||||
context.manager.error = OtaManager::FETCH_ERROR_RADIO_SESSION;
|
||||
invoke("ota status", reply);
|
||||
assert(strstr(reply.text, "radio session changed"));
|
||||
#else
|
||||
assert(strstr(reply.text, "OTA seeder | install:disabled"));
|
||||
assert(!strstr(reply.text, "direct240"));
|
||||
#endif
|
||||
}
|
||||
static void name_tests(unsigned id, const char* name) {
|
||||
reset(); Reply reply; context.manager.count = 1;
|
||||
context.manager.rows[0].target_id = id;
|
||||
@@ -212,6 +246,7 @@ static void name_tests(unsigned id, const char* name) {
|
||||
int main() {
|
||||
mesh::ota::dispatch_tests();
|
||||
mesh::ota::listing_tests();
|
||||
mesh::ota::direct_status_tests();
|
||||
unsigned id; char name[68];
|
||||
while (scanf("%x %67s", &id, name) == 2) mesh::ota::name_tests(id, name);
|
||||
}
|
||||
+20
-5
@@ -124,7 +124,7 @@ int main() {
|
||||
if (!p.automaticPreambleFits()) continue;
|
||||
if (p.automaticPreamble(0)>Profiles::MaxAutomaticPreamble
|
||||
|| p.automaticPreamble(1)>Profiles::MaxAutomaticPreamble) {
|
||||
assert(p.preamble(0,32)<=128 && p.preamble(1,32)<=128);
|
||||
assert(p.preamble(0,32)<=512 && p.preamble(1,32)<=512);
|
||||
continue;
|
||||
}
|
||||
auto actual=p.chirpTiming();
|
||||
@@ -141,7 +141,8 @@ int main() {
|
||||
}
|
||||
Profiles p;p.primary=params(7,62.5);p.secondary.params=params(7,500);
|
||||
p.secondary.mode=mesh::RadioProfileMode::Rx;
|
||||
assert(p.preamble(0,32)==128 && p.preamble(1,32)==128 && !p.switchTestReady());
|
||||
assert(Profiles::MaxAutomaticPreamble==512);
|
||||
assert(p.preamble(0,32)==512 && p.preamble(1,32)==512 && !p.switchTestReady());
|
||||
for (unsigned n=0;n<Profiles::SwitchTestSamplesPerDirection;++n) {
|
||||
p.sampleSwitch(0,1,545);p.sampleSwitch(1,0,545);
|
||||
}
|
||||
@@ -188,7 +189,7 @@ int main() {
|
||||
measured.secondary.params=params(7,500);
|
||||
measured.secondary.mode=mesh::RadioProfileMode::Rx;
|
||||
assert(!measured.switchTestReady() && measured.switchBudgetUs()==0);
|
||||
assert(measured.preamble(0,32)==128 && measured.preamble(1,32)==128);
|
||||
assert(measured.preamble(0,32)==512 && measured.preamble(1,32)==512);
|
||||
measured.sampleSwitch(0,0,10000); measured.sampleSwitch(0,1,0);
|
||||
assert(measured.switch_test_samples[0]==0);
|
||||
for (unsigned n=0;n<Profiles::SwitchTestSamplesPerDirection;++n) {
|
||||
@@ -200,13 +201,27 @@ int main() {
|
||||
measured.sampleSwitch(0,1,8428);
|
||||
assert(measured.switchBudgetUs()==9271);
|
||||
assert(measured.automaticPreamble(0)>128);
|
||||
assert(measured.preamble(0,32)==128 && measured.chirpTiming().preamble[0]>128);
|
||||
assert(measured.preamble(0,32)==168 && measured.chirpTiming().preamble[0]==168);
|
||||
// Ratios requiring 129..512 symbols must no longer be clipped at 128.
|
||||
Profiles usa_fast;
|
||||
usa_fast.primary=params(7,62.5);usa_fast.secondary.params=params(5,500);
|
||||
usa_fast.secondary.mode=mesh::RadioProfileMode::RxTx;
|
||||
for (unsigned n=0;n<Profiles::SwitchTestSamplesPerDirection;++n) {
|
||||
usa_fast.sampleSwitch(0,1,2400);usa_fast.sampleSwitch(1,0,2400);
|
||||
}
|
||||
assert(usa_fast.automaticPreamble(1)>128 && usa_fast.automaticPreamble(1)<=512);
|
||||
assert(usa_fast.preamble(1,32)==usa_fast.automaticPreamble(1));
|
||||
assert(usa_fast.preamble(1,32)%8==0);
|
||||
// Keep the new cap and uncapped diagnostics independently tested.
|
||||
measured.sampleSwitch(0,1,40000);
|
||||
assert(measured.automaticPreamble(0)>512 && measured.preamble(0,32)==512);
|
||||
assert(measured.chirpTiming().preamble[0]>512);
|
||||
measured.secondary.params.preamble=88; // explicit overrides remain unchanged
|
||||
assert(measured.preamble(1,32)==88);
|
||||
auto replacement=measured.secondary;replacement.params.freq=910.5;
|
||||
measured.setSecondary(replacement,true);
|
||||
assert(!measured.switchTestReady() && measured.switchBudgetUs()==0);
|
||||
assert(measured.preamble(0,32)==128 && measured.preamble(1,32)==88);
|
||||
assert(measured.preamble(0,32)==512 && measured.preamble(1,32)==88);
|
||||
|
||||
// A T1000-E-sized 977 us hop calibrates to 1075 us, yet SF8/500 no longer
|
||||
// inherits the historical 88-symbol floor or a fixed 300 us loop pad.
|
||||
|
||||
+7
-3
@@ -487,9 +487,13 @@ int main(int argc, char** argv) {
|
||||
f.advance(2000);
|
||||
f.finishTimingTest(8428);
|
||||
assert(f.radio.p.switchBudgetUs()==9271);
|
||||
assert(f.radio.p.preamble(0,32)==128);
|
||||
assert(strstr(f.cmd("get radio2.timing"),"WARN need >128: radio"));
|
||||
assert(strstr(f.cmd("get radio2.status"),"WARN need >128: radio"));
|
||||
assert(f.radio.p.preamble(0,32)==168);
|
||||
assert(!strstr(f.cmd("get radio2.timing"),"WARN need >"));
|
||||
assert(!strstr(f.cmd("get radio2.status"),"WARN need >"));
|
||||
f.finishTimingTest(40000);
|
||||
assert(f.radio.p.preamble(0,32)==512);
|
||||
assert(strstr(f.cmd("get radio2.timing"),"WARN need >512: radio"));
|
||||
assert(strstr(f.cmd("get radio2.status"),"WARN need >512: radio"));
|
||||
}
|
||||
{
|
||||
Fixture f;
|
||||
|
||||
@@ -77,6 +77,7 @@ struct Bluetooth {
|
||||
int motaStream() { return 0; }
|
||||
bool isMotaChannelReady() const { return ready; }
|
||||
bool isMotaStreamActive() const { return active; }
|
||||
uint16_t motaResponseCapacity() const { return ready && active ? 197 : 0; }
|
||||
void setMotaStreamActive(bool value) { active = value; }
|
||||
} bluetooth_interface;
|
||||
namespace mesh {
|
||||
@@ -91,6 +92,8 @@ public:
|
||||
assert(::bluetooth_interface.active);
|
||||
++session_resets;
|
||||
}
|
||||
protected:
|
||||
virtual uint16_t responseFrameCapacity() const { return 197; }
|
||||
};
|
||||
} }
|
||||
#include "ble_control_under_test.h"
|
||||
|
||||
@@ -17,6 +17,7 @@ public:
|
||||
virtual RadioProfiles* profiles() { return nullptr; }
|
||||
virtual const RadioProfiles* profiles() const { return nullptr; }
|
||||
virtual bool validateProfile(const RadioProfileParams&) const { return false; }
|
||||
virtual bool supportsEthernetTunnel() const { return false; }
|
||||
virtual uint8_t receiveProfile() const { return 0; }
|
||||
virtual uint32_t receiveProfileGeneration() const {
|
||||
const RadioProfiles* p = profiles();
|
||||
|
||||
@@ -32,14 +32,14 @@ int main(){
|
||||
assert(mesh.savePrefs());
|
||||
const auto on_disk=mesh.store.fs.files["/new_prefs"];
|
||||
#if defined(TBEAM_1W)
|
||||
assert(on_disk.size()==243);
|
||||
assert(on_disk.size()==251);
|
||||
#elif defined(RP2040_PLATFORM) && defined(ENABLE_WIFI_INTERFACE)
|
||||
assert(on_disk.size()==333);
|
||||
assert(on_disk.size()==341);
|
||||
#else
|
||||
assert(on_disk.size()==236);
|
||||
assert(on_disk.size()==244);
|
||||
#endif
|
||||
const size_t bluetooth_offset=on_disk.size()-5;
|
||||
assert(on_disk[bluetooth_offset]==1&&on_disk.back()==0);
|
||||
const size_t bluetooth_offset=on_disk.size()-mesh::companion::traffic::FooterSize-5;
|
||||
assert(on_disk[bluetooth_offset]==1&&on_disk[bluetooth_offset+4]==0);
|
||||
// Both choices survive a fresh instance reading the actual on-device image.
|
||||
for(bool enabled : {false,true,false}){
|
||||
assert(mesh.setBluetoothEnabledPreference(enabled));
|
||||
@@ -51,7 +51,7 @@ int main(){
|
||||
assert(prefs.bluetooth_stealth_mode==2&&prefs.one_key_dm_enabled==1);
|
||||
assert(prefs.wifi_enabled==0&&prefs.usb_logging_enabled==1);
|
||||
const auto& saved=reboot.fs.files["/new_prefs"];
|
||||
assert(saved[bluetooth_offset]==enabled&&saved.back()==0);
|
||||
assert(saved[bluetooth_offset]==enabled&&saved[bluetooth_offset+4]==0);
|
||||
}
|
||||
const auto off_disk=mesh.store.fs.files["/new_prefs"];
|
||||
// The public setter must roll live state back when the atomic save fails.
|
||||
|
||||
@@ -0,0 +1,566 @@
|
||||
"""Exercise actual Companion Ethernet settings/lifecycle at host boundaries.
|
||||
|
||||
No PlatformIO, hardware, network listener or NVS device is used. The portable
|
||||
settings image and extracted Companion method bodies remain production code.
|
||||
"""
|
||||
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
from cpp_source import body
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
SETTINGS_HARNESS = r'''
|
||||
#include <cassert>
|
||||
#include <cmath>
|
||||
#include <cstring>
|
||||
#include <initializer_list>
|
||||
#include <limits>
|
||||
#include <helpers/EthernetTunnelSettings.h>
|
||||
using namespace mesh;
|
||||
using namespace mesh::ethernet;
|
||||
|
||||
static void checksum(uint8_t* bytes) {
|
||||
const uint32_t crc=settingsChecksum(bytes,SettingsSize-4);
|
||||
memcpy(bytes+SettingsSize-4,&crc,sizeof(crc));
|
||||
}
|
||||
static Settings configured() {
|
||||
Settings value;
|
||||
value.configured=true;
|
||||
value.radio.freq=909.5;
|
||||
value.radio.bw=500;
|
||||
value.radio.sf=5;
|
||||
value.radio.cr=5;
|
||||
value.radio.preamble=32;
|
||||
return value;
|
||||
}
|
||||
int main() {
|
||||
uint8_t bytes[SettingsSize];
|
||||
Settings value,loaded;
|
||||
assert(validSettings(value));
|
||||
encodeSettings(bytes,value);
|
||||
assert(decodeSettings(bytes,sizeof(bytes),loaded));
|
||||
assert(!loaded.enabled && !loaded.configured);
|
||||
assert(loaded.radio.protocol==RadioProfileProtocol::Ethernet);
|
||||
assert(!decodeSettings(nullptr,sizeof(bytes),loaded));
|
||||
for (size_t size=0;size<SettingsSize;++size) assert(!decodeSettings(bytes,size,loaded));
|
||||
assert(!decodeSettings(bytes,SettingsSize+1,loaded));
|
||||
value=configured(); value.enabled=true;
|
||||
encodeSettings(bytes,value);
|
||||
assert(decodeSettings(bytes,sizeof(bytes),loaded));
|
||||
assert(loaded.enabled && loaded.configured && loaded.radio==value.radio);
|
||||
const auto original=loaded;
|
||||
for(size_t at=0;at<sizeof(bytes);++at) {
|
||||
bytes[at]^=1;
|
||||
assert(!decodeSettings(bytes,sizeof(bytes),loaded));
|
||||
assert(loaded.enabled==original.enabled && loaded.configured==original.configured
|
||||
&& loaded.radio==original.radio);
|
||||
bytes[at]^=1;
|
||||
}
|
||||
for(size_t at : {size_t(4),size_t(5)}) {
|
||||
bytes[at]=2; checksum(bytes); assert(!decodeSettings(bytes,sizeof(bytes),loaded));
|
||||
encodeSettings(bytes,value);
|
||||
}
|
||||
for(size_t at=18;at<SettingsSize-4;++at) {
|
||||
bytes[at]=1; checksum(bytes); assert(!decodeSettings(bytes,sizeof(bytes),loaded));
|
||||
encodeSettings(bytes,value);
|
||||
}
|
||||
value.configured=false;
|
||||
assert(!validSettings(value));
|
||||
encodeSettings(bytes,value); assert(!decodeSettings(bytes,sizeof(bytes),loaded));
|
||||
value=configured();
|
||||
for(float bad : {0.f,149.f,2501.f,std::numeric_limits<float>::infinity(),
|
||||
std::numeric_limits<float>::quiet_NaN()}) {
|
||||
value.radio.freq=bad; assert(!validSettings(value));
|
||||
encodeSettings(bytes,value); assert(!decodeSettings(bytes,sizeof(bytes),loaded));
|
||||
}
|
||||
value=configured();
|
||||
for(float bad : {0.f,124.f,std::numeric_limits<float>::infinity(),
|
||||
std::numeric_limits<float>::quiet_NaN()}) {
|
||||
value.radio.bw=bad; assert(!validSettings(value));
|
||||
encodeSettings(bytes,value); assert(!decodeSettings(bytes,sizeof(bytes),loaded));
|
||||
}
|
||||
value=configured();
|
||||
for(uint16_t bad : {0,1,7,65529,65535}) {
|
||||
value.radio.preamble=bad; assert(!validSettings(value));
|
||||
encodeSettings(bytes,value); assert(!decodeSettings(bytes,sizeof(bytes),loaded));
|
||||
}
|
||||
value=configured(); value.radio.protocol=RadioProfileProtocol::MeshCore;
|
||||
assert(!validSettings(value));
|
||||
// Foreign profiles bypass MeshCore's scan-preamble recommendation, not the
|
||||
// RadioLib 32-bit microsecond airtime bound. Reject even a CRC-valid tuple
|
||||
// that would overflow that clock before it can be persisted or used at boot.
|
||||
value=configured(); value.radio.bw=7.8f; value.radio.sf=12;
|
||||
value.radio.preamble=65528;
|
||||
assert(!validSettings(value));
|
||||
encodeSettings(bytes,value); assert(!decodeSettings(bytes,sizeof(bytes),loaded));
|
||||
value=configured();
|
||||
for(uint8_t bad : {0,4,13,255}) {
|
||||
value.radio.sf=bad; assert(!validSettings(value));
|
||||
encodeSettings(bytes,value); assert(!decodeSettings(bytes,sizeof(bytes),loaded));
|
||||
}
|
||||
value=configured();
|
||||
for(uint8_t bad : {0,4,9,255}) {
|
||||
value.radio.cr=bad; assert(!validSettings(value));
|
||||
encodeSettings(bytes,value); assert(!decodeSettings(bytes,sizeof(bytes),loaded));
|
||||
}
|
||||
}
|
||||
'''
|
||||
|
||||
|
||||
COMPANION_HARNESS = r'''
|
||||
@RADIO_FIXTURE@
|
||||
#include <helpers/EthernetTunnelSettings.h>
|
||||
#include <helpers/EthernetKiss.h>
|
||||
#include <helpers/CLICommandUtils.h>
|
||||
#include <helpers/CompanionChannelAlias.h>
|
||||
#include <deque>
|
||||
#include <vector>
|
||||
|
||||
struct Preferences {
|
||||
static inline std::vector<uint8_t> blob;
|
||||
static inline bool fail_begin=false,fail_write=false,fail_read=false,fail_remove=false;
|
||||
static inline unsigned writes=0;
|
||||
bool begin(const char* name,bool read_only) {
|
||||
assert(!strcmp(name,"mesh-eth") && !read_only); return !fail_begin;
|
||||
}
|
||||
size_t getBytesLength(const char* key) { assert(!strcmp(key,"settings")); return blob.size(); }
|
||||
size_t getBytes(const char*,void* out,size_t size) {
|
||||
if(fail_read)return 0;
|
||||
size=std::min(size,blob.size()); memcpy(out,blob.data(),size); return size;
|
||||
}
|
||||
size_t putBytes(const char*,const void* in,size_t size) {
|
||||
++writes; if(fail_write)return 0;
|
||||
const auto* bytes=static_cast<const uint8_t*>(in); blob.assign(bytes,bytes+size); return size;
|
||||
}
|
||||
bool remove(const char*) { if(fail_remove)return false; blob.clear(); return true; }
|
||||
void end() {}
|
||||
static void reset() { blob.clear(); writes=0; fail_begin=fail_write=fail_read=fail_remove=false; }
|
||||
};
|
||||
|
||||
namespace mesh { namespace ethernet {
|
||||
// Socket lifecycle is a boundary substitute. Every byte in both directions
|
||||
// still traverses the production bounded KISS codec.
|
||||
class KissServer {
|
||||
KissCodec codec;
|
||||
public:
|
||||
static constexpr uint16_t Port=5003;
|
||||
struct Status { bool enabled=false,listening=false,connected=false; uint32_t accepted=0,disconnects=0; };
|
||||
Status state;
|
||||
bool wifi=true;
|
||||
bool attach_pending=false,detach_pending=false;
|
||||
unsigned resets=0;
|
||||
void resetPending() {
|
||||
++resets;
|
||||
if(state.connected)++state.disconnects;
|
||||
state.connected=false;
|
||||
codec.resetPending();
|
||||
}
|
||||
void loop(bool enabled) {
|
||||
state.enabled=enabled; state.listening=enabled && wifi;
|
||||
if(!state.listening) {resetPending();attach_pending=detach_pending=false;return;}
|
||||
if(detach_pending) {resetPending();detach_pending=false;}
|
||||
if(attach_pending) {codec.resetPending();state.connected=true;++state.accepted;attach_pending=false;}
|
||||
}
|
||||
Status status() const { return state; }
|
||||
void connect() { assert(state.listening);attach_pending=true; }
|
||||
void disconnect() { detach_pending=true; }
|
||||
bool peekTransmit(const uint8_t*& bytes,size_t& size) const { return codec.peekTransmit(bytes,size); }
|
||||
void consumeTransmit() { codec.consumeTransmit(); }
|
||||
bool queueReceive(const uint8_t* bytes,size_t size) { return state.connected && codec.queueReceive(bytes,size); }
|
||||
void feed(const std::vector<uint8_t>& frame) {
|
||||
assert(state.connected);
|
||||
for(uint8_t byte:frame)assert(codec.feed(byte));
|
||||
}
|
||||
std::vector<uint8_t> output() {
|
||||
const uint8_t* bytes;size_t size;
|
||||
if(!codec.peekOutput(bytes,size))return {};
|
||||
std::vector<uint8_t> out(bytes,bytes+size);codec.consumeOutput(size);return out;
|
||||
}
|
||||
};
|
||||
} }
|
||||
|
||||
static constexpr int MAX_GROUP_CHANNELS=4;
|
||||
struct ChannelDetails {char name[32]={};};
|
||||
struct BaseChatMesh {
|
||||
ChannelDetails channels[MAX_GROUP_CHANNELS];
|
||||
unsigned channel_reads=0;
|
||||
bool getChannel(int index,ChannelDetails& out) {++channel_reads;out=channels[index];return true;}
|
||||
bool setChannel(int index,const ChannelDetails& value) {channels[index]=value;return true;}
|
||||
};
|
||||
struct EthernetRadio : Radio {
|
||||
bool supported=true;
|
||||
mutable unsigned validations=0;
|
||||
bool supportsEthernetTunnel() const override {return supported;}
|
||||
bool validateProfile(const mesh::RadioProfileParams& value) const override {
|
||||
++validations;return Radio::validateProfile(value);
|
||||
}
|
||||
};
|
||||
class MyMesh : public BaseChatMesh {
|
||||
public:
|
||||
MemoryFS fs;Clock clock;EthernetRadio radio;mesh::Radio* _radio=&radio;
|
||||
mesh::RadioProfileCLI _radio_profiles;
|
||||
mesh::ethernet::Settings _ethernet_settings;
|
||||
bool _ethernet_settings_valid=true,_ethernet_active=false,_ethernet_owned=false;
|
||||
uint32_t _ethernet_generation=0;
|
||||
uint32_t _ethernet_intent_generation=0,_ethernet_channel_generation=0;
|
||||
uint32_t _ethernet_checked_channels=UINT32_MAX;
|
||||
bool _ethernet_channels_conflict=false;
|
||||
const char* _ethernet_status="off";
|
||||
mesh::ethernet::KissServer _ethernet_kiss;
|
||||
uint32_t _ethernet_received=0,_ethernet_sent=0,_ethernet_failed=0;
|
||||
bool _radio_available=true,foreign_pending=false,admit_foreign=true;
|
||||
mesh::RadioProfileProtocol foreign_protocol=mesh::RadioProfileProtocol::MeshCore;
|
||||
uint8_t foreign_profile=255;
|
||||
uint32_t foreign_generation=0;
|
||||
unsigned admissions=0,discards=0;
|
||||
std::vector<uint8_t> foreign_bytes;
|
||||
MyMesh() {g_mock_millis=0;_radio_profiles.begin(&fs,&radio,&clock);}
|
||||
void beginEthernetTunnel();
|
||||
bool ethernetChannelConflict();
|
||||
void releaseEthernetProfile();
|
||||
bool saveEthernetSettings(const mesh::ethernet::Settings&);
|
||||
bool eraseEthernetSettings();
|
||||
bool ethernetRadioConflict(const mesh::ethernet::Settings&);
|
||||
bool handleEthernetTunnelCommand(const char*,char*,size_t);
|
||||
void loopEthernetTunnel();
|
||||
bool onEthernetFrame(const uint8_t*,size_t,uint8_t,uint32_t);
|
||||
bool setChannel(int,const ChannelDetails&);
|
||||
bool onForeignRadioFrame(const uint8_t*,size_t,uint8_t,uint32_t,float,float);
|
||||
void onForeignRadioSendComplete(bool);
|
||||
mesh::RadioProfileProtocol queuedForeignRadioProtocol() const {return foreign_protocol;}
|
||||
bool hasForeignRadioFrame() const {return foreign_pending;}
|
||||
void discardQueuedForeignRadioFrame(mesh::RadioProfileProtocol protocol) {
|
||||
if(foreign_pending && protocol==foreign_protocol) {foreign_pending=false;++discards;}
|
||||
}
|
||||
bool queueForeignRadioFrame(const uint8_t* bytes,size_t size,uint8_t profile,uint32_t generation,
|
||||
mesh::RadioProfileProtocol protocol) {
|
||||
if(foreign_pending || !admit_foreign)return false;
|
||||
foreign_pending=true;++admissions;foreign_bytes.assign(bytes,bytes+size);
|
||||
foreign_profile=profile;foreign_generation=generation;foreign_protocol=protocol;return true;
|
||||
}
|
||||
const char* command(const char* text) {
|
||||
static char reply[256];memset(reply,0x55,sizeof(reply));
|
||||
assert(handleEthernetTunnelCommand(text,reply,sizeof(reply)));
|
||||
assert(memchr(reply,0,sizeof(reply)));return reply;
|
||||
}
|
||||
void cli(const char* text) {
|
||||
char reply[160];assert(_radio_profiles.handle(text,reply,sizeof(reply)));
|
||||
if(strncmp(reply,"OK",2)) {fprintf(stderr,"%s -> %s\n",text,reply);assert(false);}
|
||||
g_mock_millis+=2000;clock.epoch+=2;_radio_profiles.loop();
|
||||
}
|
||||
};
|
||||
@METHODS@
|
||||
|
||||
static void ok(MyMesh& node,const char* text) {assert(!strncmp(node.command(text),"OK",2));}
|
||||
static void error(MyMesh& node,const char* text) {assert(!strncmp(node.command(text),"Error",5));}
|
||||
static void active(MyMesh& node) {
|
||||
node.beginEthernetTunnel();
|
||||
ok(node,"set ethernet.radio 909.5,500,5,5");
|
||||
ok(node,"set ethernet on");node.loopEthernetTunnel();
|
||||
assert(node._ethernet_active && node._ethernet_owned && node.radio.p.enabled());
|
||||
assert(node.radio.p.secondary.params.protocol==mesh::RadioProfileProtocol::Ethernet);
|
||||
}
|
||||
static std::vector<uint8_t> ethernet(uint16_t type=0x0800,size_t size=244) {
|
||||
std::vector<uint8_t> frame(size);
|
||||
for(size_t i=0;i<size;++i)frame[i]=static_cast<uint8_t>(i);
|
||||
frame[12]=type>>8;frame[13]=type&255;frame[14]=0xc0;frame[15]=0xdb;
|
||||
return frame;
|
||||
}
|
||||
static std::vector<uint8_t> kiss(const std::vector<uint8_t>& ethernet) {
|
||||
std::vector<uint8_t> out={0xc0,0};
|
||||
for(auto byte:ethernet) {
|
||||
if(byte==0xc0)out.insert(out.end(),{0xdb,0xdc});
|
||||
else if(byte==0xdb)out.insert(out.end(),{0xdb,0xdd});
|
||||
else out.push_back(byte);
|
||||
}
|
||||
out.push_back(0xc0);return out;
|
||||
}
|
||||
static void defaults_cli_and_reboot() {
|
||||
Preferences::reset();MyMesh node;node.beginEthernetTunnel();node.loopEthernetTunnel();
|
||||
assert(node._ethernet_settings_valid && !node._ethernet_active && !node.radio.p.enabled());
|
||||
assert(strstr(node.command("get ethernet"),"ethernet=off"));
|
||||
assert(strstr(node.command("get ethernet.radio"),"unset"));
|
||||
error(node,"set ethernet on");assert(Preferences::writes==0);
|
||||
for(const char* bad:{"set ethernet","set ethernet ON","set ethernet on extra",
|
||||
"set ethernet.radio","set ethernet.radio 909.5,500,5",
|
||||
"set ethernet.radio 909.5,500,5,5,garbage","set ethernet.radio 909.5,500,4,5",
|
||||
"set ethernet.radio 909.5,500,5,5,7","set ethernet.radio 0,500,5,5"})error(node,bad);
|
||||
assert(Preferences::writes==0);
|
||||
char reply[8];assert(!node.handleEthernetTunnelCommand("get ethernetx",reply,sizeof(reply)));
|
||||
assert(!node.handleEthernetTunnelCommand("set ethernetx on",reply,sizeof(reply)));
|
||||
ok(node,"set ethernet.radio 909.5,500,5,5");
|
||||
assert(node._ethernet_settings.radio.preamble==32 && !node._ethernet_settings.enabled);
|
||||
ok(node,"set ethernet on");node.loopEthernetTunnel();
|
||||
const auto generation=node.radio.p.generation[1];
|
||||
assert(node._ethernet_active && node._ethernet_kiss.status().listening);
|
||||
assert(node._ethernet_settings.radio.protocol==mesh::RadioProfileProtocol::Ethernet);
|
||||
assert(node.fs.files.empty());
|
||||
const auto validations=node.radio.validations;
|
||||
const auto scans=node.channel_reads;
|
||||
for(int i=0;i<100;++i)node.loopEthernetTunnel();
|
||||
assert(node.radio.p.generation[1]==generation && Preferences::writes==2);
|
||||
assert(node.radio.validations==validations && node.channel_reads==scans);
|
||||
for(const char* command:{"get ethernet","get ethernet.radio","get ethernet.status"}) {
|
||||
char bounded[4]={'a','b','c','d'};
|
||||
assert(node.handleEthernetTunnelCommand(command,bounded+1,1));
|
||||
assert(bounded[0]=='a' && bounded[1]==0 && bounded[2]=='c' && bounded[3]=='d');
|
||||
bounded[1]='b';assert(node.handleEthernetTunnelCommand(command,bounded+1,0));
|
||||
assert(bounded[0]=='a' && bounded[1]=='b' && bounded[2]=='c' && bounded[3]=='d');
|
||||
}
|
||||
MyMesh reboot;reboot.beginEthernetTunnel();reboot.loopEthernetTunnel();
|
||||
assert(reboot._ethernet_active && reboot._ethernet_settings.radio==node._ethernet_settings.radio);
|
||||
ok(node,"set ethernet off");node.loopEthernetTunnel();
|
||||
assert(!node._ethernet_active && !node.radio.p.enabled() && !node._ethernet_kiss.status().listening);
|
||||
MyMesh off;off.beginEthernetTunnel();off.loopEthernetTunnel();assert(!off._ethernet_active);
|
||||
}
|
||||
static void persistence_faults() {
|
||||
for(int fault=0;fault<3;++fault) {
|
||||
Preferences::reset();MyMesh node;active(node);
|
||||
const auto before=Preferences::blob;
|
||||
if(fault==0)Preferences::fail_begin=true;
|
||||
if(fault==1)Preferences::fail_write=true;
|
||||
if(fault==2)Preferences::fail_read=true;
|
||||
error(node,"set ethernet off");
|
||||
if(fault==0)assert(node._ethernet_active && node._ethernet_settings_valid);
|
||||
else assert(!node._ethernet_active && !node._ethernet_settings_valid && !node.radio.p.enabled());
|
||||
Preferences::fail_begin=Preferences::fail_write=Preferences::fail_read=false;
|
||||
if(fault<2)assert(Preferences::blob==before);
|
||||
MyMesh reboot;reboot.beginEthernetTunnel();reboot.loopEthernetTunnel();
|
||||
assert(reboot._ethernet_active==(fault!=2));
|
||||
}
|
||||
Preferences::reset();MyMesh source;active(source);const auto good=Preferences::blob;
|
||||
for(size_t at=0;at<good.size();++at) {
|
||||
Preferences::blob=good;Preferences::blob[at]^=1;
|
||||
MyMesh boot;boot.beginEthernetTunnel();boot.loopEthernetTunnel();
|
||||
assert(!boot._ethernet_settings_valid && !boot._ethernet_active && !boot.radio.p.enabled());
|
||||
}
|
||||
for(size_t size:{size_t(1),size_t(31),size_t(33)}) {
|
||||
Preferences::blob=good;Preferences::blob.resize(size);
|
||||
MyMesh boot;boot.beginEthernetTunnel();boot.loopEthernetTunnel();assert(!boot._ethernet_active);
|
||||
}
|
||||
Preferences::blob=good;MyMesh erase;erase.beginEthernetTunnel();erase.loopEthernetTunnel();
|
||||
Preferences::fail_remove=true;assert(!erase.eraseEthernetSettings());
|
||||
assert(!erase._ethernet_active && !erase._ethernet_settings_valid);
|
||||
Preferences::fail_remove=false;assert(erase.eraseEthernetSettings());
|
||||
assert(Preferences::blob.empty() && !erase._ethernet_settings.enabled && erase._ethernet_settings_valid);
|
||||
MyMesh reboot;reboot.beginEthernetTunnel();reboot.loopEthernetTunnel();assert(!reboot._ethernet_active);
|
||||
}
|
||||
static void profile_conflicts_and_recovery() {
|
||||
for(const char* name:{"#r2-emergency","#mt-longfast"}) {
|
||||
Preferences::reset();MyMesh node;node.beginEthernetTunnel();
|
||||
ok(node,"set ethernet.radio 909.5,500,5,5,32");strcpy(node.channels[0].name,name);++node._ethernet_channel_generation;
|
||||
error(node,"set ethernet on");assert(!node._ethernet_active);
|
||||
node.channels[0].name[0]=0;++node._ethernet_channel_generation;ok(node,"set ethernet on");node.loopEthernetTunnel();
|
||||
assert(node._ethernet_active);strcpy(node.channels[0].name,name);++node._ethernet_channel_generation;node.loopEthernetTunnel();
|
||||
assert(!node._ethernet_active && !node.radio.p.enabled());
|
||||
node.channels[0].name[0]=0;++node._ethernet_channel_generation;node.loopEthernetTunnel();assert(node._ethernet_active);
|
||||
}
|
||||
for(const char* tuple:{"set radio2 off","set radio2 909.5,500,5,5,rx,32",
|
||||
"set radio2 909.6,500,5,5,rxtx,32","set radio2 909.5,500,5,5,rxtx,40"}) {
|
||||
Preferences::reset();MyMesh node;node.beginEthernetTunnel();node.cli(tuple);
|
||||
const auto saved=node.radio.p.secondary;
|
||||
ok(node,"set ethernet.radio 909.5,500,5,5,32");error(node,"set ethernet on");
|
||||
assert(node.radio.p.secondary.mode==saved.mode && node.radio.p.secondary.params==saved.params);
|
||||
}
|
||||
Preferences::reset();MyMesh manual;manual.beginEthernetTunnel();
|
||||
manual.cli("set radio2 909.5,500,5,5,rxtx,32");const auto saved_files=manual.fs.files;
|
||||
ok(manual,"set ethernet.radio 909.5,500,5,5,32");ok(manual,"set ethernet on");manual.loopEthernetTunnel();
|
||||
assert(manual._ethernet_active && manual.fs.files==saved_files);
|
||||
ok(manual,"set ethernet off");manual.loopEthernetTunnel();
|
||||
assert(manual.radio.p.secondary.mode==mesh::RadioProfileMode::RxTx
|
||||
&& manual.radio.p.secondary.params.protocol==mesh::RadioProfileProtocol::MeshCore);
|
||||
assert(manual.fs.files==saved_files);
|
||||
Preferences::reset();MyMesh unavailable;active(unavailable);
|
||||
unavailable._radio_available=false;unavailable.loopEthernetTunnel();assert(!unavailable._ethernet_active);
|
||||
unavailable._radio_available=true;unavailable.loopEthernetTunnel();assert(unavailable._ethernet_active);
|
||||
unavailable.radio.supported=false;unavailable.loopEthernetTunnel();assert(!unavailable._ethernet_active);
|
||||
unavailable.radio.supported=true;unavailable.loopEthernetTunnel();assert(unavailable._ethernet_active);
|
||||
unavailable._ethernet_kiss.wifi=false;unavailable.loopEthernetTunnel();
|
||||
assert(unavailable._ethernet_active && !unavailable._ethernet_kiss.status().listening);
|
||||
unavailable._ethernet_kiss.wifi=true;unavailable.loopEthernetTunnel();
|
||||
assert(unavailable._ethernet_kiss.status().listening);
|
||||
}
|
||||
static void opaque_frames_and_no_primary_fallback() {
|
||||
Preferences::reset();MyMesh node;active(node);node._ethernet_kiss.connect();node.loopEthernetTunnel();
|
||||
for(uint16_t type:{0x0800,0x0806,0x86dd,0x1234}) {
|
||||
const auto frame=ethernet(type);
|
||||
node._ethernet_kiss.feed(kiss(frame));node.admit_foreign=false;node.loopEthernetTunnel();
|
||||
assert(!node.foreign_pending);node.admit_foreign=true;node.loopEthernetTunnel();
|
||||
assert(node.foreign_pending && node.foreign_bytes==frame && node.foreign_profile==1);
|
||||
assert(node.foreign_protocol==mesh::RadioProfileProtocol::Ethernet);
|
||||
assert(node.foreign_generation==node.radio.p.generation[1]);
|
||||
error(node,"set ethernet off");assert(node._ethernet_active);
|
||||
node.foreign_pending=false;
|
||||
assert(node.onEthernetFrame(frame.data(),frame.size(),1,node.radio.p.generation[1]));
|
||||
assert(node._ethernet_kiss.output()==kiss(frame));
|
||||
assert(!node.onEthernetFrame(frame.data(),frame.size(),0,node.radio.p.generation[0]));
|
||||
assert(!node.onEthernetFrame(frame.data(),frame.size(),1,node.radio.p.generation[1]-1));
|
||||
}
|
||||
assert(node.admissions==4 && node._ethernet_received==4);
|
||||
node.foreign_protocol=mesh::RadioProfileProtocol::Ethernet;
|
||||
node.onForeignRadioSendComplete(true);node.onForeignRadioSendComplete(false);
|
||||
assert(node._ethernet_sent==1 && node._ethernet_failed==1);
|
||||
node.foreign_protocol=mesh::RadioProfileProtocol::Meshtext;
|
||||
node.onForeignRadioSendComplete(true);node.onForeignRadioSendComplete(false);
|
||||
assert(node._ethernet_sent==1 && node._ethernet_failed==1);
|
||||
for(size_t size:{size_t(13),size_t(256)}) {
|
||||
const std::vector<uint8_t> invalid(size,0x11);
|
||||
assert(!node.onEthernetFrame(invalid.data(),invalid.size(),1,node.radio.p.generation[1]));
|
||||
}
|
||||
const auto frame=ethernet();node._ethernet_kiss.feed(kiss(frame));node.loopEthernetTunnel();
|
||||
const auto admissions=node.admissions;assert(node.foreign_pending);
|
||||
node._radio_available=false;node.loopEthernetTunnel();
|
||||
assert(!node.foreign_pending && node.discards>=1 && node.admissions==admissions && !node._ethernet_active);
|
||||
node._radio_available=true;node.loopEthernetTunnel();
|
||||
assert(node._ethernet_active && !node._ethernet_kiss.status().connected);
|
||||
assert(!node.onEthernetFrame(frame.data(),frame.size(),1,node.radio.p.generation[1]));
|
||||
node._ethernet_kiss.connect();node.loopEthernetTunnel();
|
||||
node._ethernet_kiss.feed(kiss(frame));node.loopEthernetTunnel();assert(node.foreign_pending);
|
||||
node._ethernet_kiss.disconnect();node.loopEthernetTunnel();
|
||||
assert(!node.foreign_pending && !node._ethernet_kiss.status().connected);
|
||||
node._ethernet_kiss.connect();node.loopEthernetTunnel();
|
||||
node._ethernet_kiss.feed(kiss(frame));node.loopEthernetTunnel();assert(node.foreign_pending);
|
||||
assert(node.eraseEthernetSettings());assert(!node.foreign_pending && !node._ethernet_active);
|
||||
}
|
||||
static void temporary_and_scheduled_ownership() {
|
||||
Preferences::reset();MyMesh node;active(node);
|
||||
node.cli("set tempradio2 910.5,500,5,5,rxtx,1,32");node.loopEthernetTunnel();
|
||||
assert(!node._ethernet_active && node.radio.p.secondary_temporary
|
||||
&& node.radio.p.secondary.params.freq==910.5f);
|
||||
const auto temporary=node.radio.p.secondary.params;
|
||||
error(node,"set ethernet on");assert(node.radio.p.secondary.params==temporary);
|
||||
node.cli("set tempradio2 off");node.loopEthernetTunnel();assert(node._ethernet_active);
|
||||
char command[128];
|
||||
snprintf(command,sizeof(command),"set radioat2 911.5,500,5,5,rxtx,%lu,32",
|
||||
static_cast<unsigned long>(node.clock.epoch+120));
|
||||
node.cli(command);node.loopEthernetTunnel();assert(!node._ethernet_active);
|
||||
assert(!node.radio.p.enabled());error(node,"set ethernet on");
|
||||
node.cli("del radioat2 all");node.loopEthernetTunnel();assert(node._ethernet_active);
|
||||
}
|
||||
static void unused_meshtext_owner_handoff() {
|
||||
Preferences::reset();MyMesh node;node.beginEthernetTunnel();
|
||||
mesh::RadioProfileConfig old;
|
||||
old.mode=mesh::RadioProfileMode::RxTx;old.params.freq=906.875;old.params.bw=250;
|
||||
old.params.sf=11;old.params.cr=5;old.params.preamble=16;
|
||||
old.params.protocol=mesh::RadioProfileProtocol::Meshtext;
|
||||
assert(node._radio_profiles.requestAutoSecondary(old));
|
||||
assert(node._radio_profiles.autoSecondaryActive());
|
||||
ok(node,"set ethernet.radio 909.5,500,5,5,32");
|
||||
assert(node.radio.p.secondary.params.protocol==mesh::RadioProfileProtocol::Meshtext);
|
||||
ok(node,"set ethernet on");node.loopEthernetTunnel();
|
||||
assert(node._ethernet_active && node.radio.p.secondary.params.protocol==mesh::RadioProfileProtocol::Ethernet);
|
||||
}
|
||||
static void real_channel_setter_invalidates_cache_without_evicting() {
|
||||
Preferences::reset();MyMesh node;active(node);
|
||||
const auto generation=node._ethernet_channel_generation;
|
||||
ChannelDetails candidate;
|
||||
for(const char* name:{"#r2-emergency","#mt-longfast","#r2-"}) {
|
||||
strcpy(candidate.name,name);assert(!node.setChannel(0,candidate));
|
||||
assert(node._ethernet_channel_generation==generation && !node.channels[0].name[0]);
|
||||
}
|
||||
strcpy(candidate.name,"#emergency");assert(node.setChannel(0,candidate));
|
||||
assert(node._ethernet_channel_generation==generation+1);
|
||||
node.loopEthernetTunnel();assert(node._ethernet_active && !node.ethernetChannelConflict());
|
||||
candidate={};assert(node.setChannel(0,candidate));
|
||||
assert(node._ethernet_channel_generation==generation+2);
|
||||
node.loopEthernetTunnel();assert(node._ethernet_active);
|
||||
}
|
||||
int main() {
|
||||
defaults_cli_and_reboot();persistence_faults();profile_conflicts_and_recovery();
|
||||
opaque_frames_and_no_primary_fallback();temporary_and_scheduled_ownership();unused_meshtext_owner_handoff();
|
||||
real_channel_setter_invalidates_cache_without_evicting();
|
||||
}
|
||||
'''
|
||||
|
||||
|
||||
class CompanionEthernetTest(unittest.TestCase):
|
||||
def compile_run(self, text, sources=(), includes=(), definitions=()):
|
||||
compiler = os.environ.get("CXX") or shutil.which("g++") or shutil.which("clang++")
|
||||
if not compiler:
|
||||
self.skipTest("a host C++ compiler is required")
|
||||
with tempfile.TemporaryDirectory(prefix="meshcore-ethernet-companion-") as directory:
|
||||
work = Path(directory)
|
||||
(work / "test.cpp").write_text(text, encoding="utf-8")
|
||||
command = [compiler, "-std=c++17", "-Wall", "-Wextra",
|
||||
"-fsanitize=address,undefined", "-fno-pie", "-no-pie"]
|
||||
command.extend("-D" + item for item in definitions)
|
||||
for path in (*includes, ROOT / "src"):
|
||||
command.extend(("-I", str(path)))
|
||||
command.extend((str(work / "test.cpp"), *(str(path) for path in sources),
|
||||
"-o", str(work / "test")))
|
||||
build = subprocess.run(command, capture_output=True, text=True)
|
||||
diagnostics = build.stdout + build.stderr
|
||||
errors = "\n".join(line for line in diagnostics.splitlines()
|
||||
if "error:" in line or "undefined reference" in line)
|
||||
self.assertEqual(build.returncode, 0, errors or diagnostics)
|
||||
run = subprocess.run([str(work / "test")], capture_output=True, text=True)
|
||||
self.assertEqual(run.returncode, 0, run.stdout + run.stderr)
|
||||
|
||||
def test_checked_settings_image_is_atomic_and_fail_closed(self):
|
||||
self.compile_run(SETTINGS_HARNESS)
|
||||
|
||||
def test_production_companion_lifecycle_routing_and_persistence(self):
|
||||
source = (ROOT / "examples/companion_radio/EthernetCompanion.cpp").read_text(encoding="utf-8")
|
||||
methods = source[source.index("void MyMesh::beginEthernetTunnel()"):].rsplit("#endif", 1)[0]
|
||||
companion = (ROOT / "examples/companion_radio/MyMesh.cpp").read_text(encoding="utf-8")
|
||||
methods += "\n" + body(companion, "bool MyMesh::setChannel(")
|
||||
fixture = (ROOT / "test/fixtures/radio_profiles/cli_test.cpp").read_text(encoding="utf-8")
|
||||
fixture = fixture[:fixture.index("struct Fixture {")]
|
||||
harness = COMPANION_HARNESS.replace("@RADIO_FIXTURE@", fixture).replace("@METHODS@", methods)
|
||||
self.compile_run(
|
||||
harness,
|
||||
sources=(ROOT / "src/helpers/RadioProfileCLI.cpp",),
|
||||
includes=(ROOT / "test/fixtures/radio_profiles/mocks", ROOT / "test/mocks"),
|
||||
definitions=("MESH_ENABLE_MESHTEXT_CHAT=0",
|
||||
"MESH_ENABLE_TX_BEACONS=0", "MESH_ENABLE_ETHERNET_TUNNEL=1"),
|
||||
)
|
||||
|
||||
def test_full_esp32_wifi_only_compile_gate(self):
|
||||
harness = ("#include <helpers/EthernetTunnelConfig.h>\n"
|
||||
"static_assert(MESH_ENABLE_ETHERNET_TUNNEL==EXPECTED,\"feature gate\");\n"
|
||||
"int main() {}\n")
|
||||
for definitions, expected in (
|
||||
(("ESP32_PLATFORM=1", "COMPANION_RADIO_FULL=1", "WIFI_SSID=1"), 1),
|
||||
(("ESP32_PLATFORM=1", "COMPANION_RADIO_FULL=1"), 0),
|
||||
(("ESP32_PLATFORM=1", "WIFI_SSID=1"), 0),
|
||||
(("NRF52_PLATFORM=1", "COMPANION_RADIO_FULL=1", "WIFI_SSID=1"), 0),
|
||||
(("ESP32_PLATFORM=1", "COMPANION_RADIO_FULL=1", "WIFI_SSID=1", "MESH_PRIMARY_ESPNOW=1"), 0),
|
||||
):
|
||||
with self.subTest(definitions=definitions):
|
||||
self.compile_run(harness, definitions=(*definitions, f"EXPECTED={expected}"))
|
||||
|
||||
def test_production_companion_wiring_keeps_transports_isolated(self):
|
||||
source = (ROOT / "examples/companion_radio/MyMesh.cpp").read_text(encoding="utf-8")
|
||||
# begin() contains old alternative platform branches that intentionally
|
||||
# split a common outer body; take its stable next-method boundary.
|
||||
begin = source[source.index("void MyMesh::begin("):source.index("bool MyMesh::handleTxRoutingCommand(")]
|
||||
self.assertLess(begin.index("beginEthernetTunnel();"), begin.index("beginMeshtext();"))
|
||||
loop = body(source, "void MyMesh::loop()")
|
||||
self.assertLess(loop.index("loopEthernetTunnel();"), loop.index("BaseChatMesh::loop();"))
|
||||
self.assertIn("handleEthernetTunnelCommand(command, reply, reply_size)",
|
||||
body(source, "bool MyMesh::handleLocalControlCommand("))
|
||||
self.assertEqual(source.count("if (!eraseEthernetSettings())"), 1)
|
||||
self.assertEqual(source.count("if (success && !eraseEthernetSettings())"), 1)
|
||||
setting = body(source, "bool MyMesh::setChannel(")
|
||||
self.assertIn("_ethernet_settings.enabled", setting)
|
||||
self.assertIn("CompanionChannelKind::MeshCore", setting)
|
||||
mt = (ROOT / "examples/companion_radio/MeshtextCompanion.cpp").read_text(encoding="utf-8")
|
||||
refresh = body(mt, "void MyMesh::refreshMeshtextProfile()")
|
||||
self.assertLess(refresh.index("if (_ethernet_settings.enabled)"),
|
||||
refresh.index("_radio_profiles.clearAutoSecondary();"))
|
||||
self.assertIn("onEthernetFrame(bytes, length, profile, generation)",
|
||||
body(mt, "bool MyMesh::onForeignRadioFrame("))
|
||||
self.assertIn("queuedForeignRadioProtocol() == mesh::RadioProfileProtocol::Ethernet",
|
||||
body(mt, "void MyMesh::onForeignRadioSendComplete("))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -23,6 +23,9 @@ HARNESS = r'''
|
||||
#endif
|
||||
#include "examples/companion_radio/NodePrefs.h"
|
||||
#include "examples/companion_radio/PrefsStorageLayout.h"
|
||||
#if defined(RAK_4631)
|
||||
#include <helpers/PeripheralModePrefs.h>
|
||||
#endif
|
||||
#define MESH_DEBUG_PRINTLN(...) ((void)0)
|
||||
struct DataStore {
|
||||
MemoryFS fs;
|
||||
@@ -59,6 +62,11 @@ int main(int argc,char** argv){
|
||||
original.gps_sync_interval_hours=336;
|
||||
original.usb_debug_enabled=1;
|
||||
original.lost_reply=2;
|
||||
original.tx_media=mesh::RADIO_TX_SECONDARY;
|
||||
original.tx_ssh=mesh::RADIO_TX_OFF;
|
||||
#if defined(RAK_4631)
|
||||
original.peripherals_shared=1;
|
||||
#endif
|
||||
#ifdef TBEAM_1W
|
||||
strcpy(original.fan_mode,"on");original.fan_lo=33;original.fan_hi=42;
|
||||
#endif
|
||||
@@ -67,6 +75,11 @@ int main(int argc,char** argv){
|
||||
#endif
|
||||
assert(store.savePrefs(original,47.1,-122.2));
|
||||
const auto disk=store.fs.files["/new_prefs"];
|
||||
const size_t historical_size=disk.size()-mesh::companion::traffic::FooterSize
|
||||
#if defined(RAK_4631)
|
||||
-mesh::peripherals::FooterSize
|
||||
#endif
|
||||
;
|
||||
CompanionNodePrefs changed=original;changed.freq=910.1f;
|
||||
if(scenario==0){
|
||||
store.fs.fail_write=true;
|
||||
@@ -98,6 +111,10 @@ int main(int argc,char** argv){
|
||||
assert(loaded.gps_sync_interval_hours==336);
|
||||
assert(loaded.usb_debug_enabled==1);
|
||||
assert(loaded.lost_reply==2);
|
||||
assert(loaded.tx_media==mesh::RADIO_TX_SECONDARY&&loaded.tx_ssh==mesh::RADIO_TX_OFF);
|
||||
#if defined(RAK_4631)
|
||||
assert(loaded.peripherals_shared==1);
|
||||
#endif
|
||||
#ifdef TBEAM_1W
|
||||
assert(!strcmp(loaded.fan_mode,"on")&&loaded.fan_lo==33&&loaded.fan_hi==42);
|
||||
#endif
|
||||
@@ -203,7 +220,7 @@ int main(int argc,char** argv){
|
||||
} else if(scenario==7){
|
||||
// Pre-consent image: all earlier settings survive with default-off consent.
|
||||
DataStore legacy;legacy.fs.files["/new_prefs"]=disk;
|
||||
legacy.fs.files["/new_prefs"].resize(disk.size()-6);
|
||||
legacy.fs.files["/new_prefs"].resize(historical_size-6);
|
||||
CompanionNodePrefs loaded;double lat=0,lon=0;
|
||||
assert(legacy.loadPrefs(loaded,lat,lon));
|
||||
assert(loaded.flood_retry_advert_enabled==0);
|
||||
@@ -212,7 +229,7 @@ int main(int argc,char** argv){
|
||||
// The previous complete image loads with the board policy even when the
|
||||
// receiving prefs object previously held an explicit configured interval.
|
||||
DataStore legacy;legacy.fs.files["/new_prefs"]=disk;
|
||||
legacy.fs.files["/new_prefs"].resize(disk.size()-4);
|
||||
legacy.fs.files["/new_prefs"].resize(historical_size-4);
|
||||
CompanionNodePrefs loaded;loaded.gps_sync_interval_hours=24;loaded.usb_debug_enabled=1;
|
||||
double lat=0,lon=0;
|
||||
assert(legacy.loadPrefs(loaded,lat,lon));
|
||||
@@ -220,12 +237,12 @@ int main(int argc,char** argv){
|
||||
assert(loaded.usb_debug_enabled==0);
|
||||
// Half of the two-byte append is never accepted as a complete image.
|
||||
DataStore torn;torn.fs.files["/new_prefs"]=disk;
|
||||
torn.fs.files["/new_prefs"].resize(disk.size()-3);
|
||||
torn.fs.files["/new_prefs"].resize(historical_size-3);
|
||||
assert(!torn.loadPrefsInt("/new_prefs",loaded,lat,lon));
|
||||
// The complete published GPS image is accepted without borrowing either
|
||||
// GPS byte as the new debug preference.
|
||||
DataStore gps_image;gps_image.fs.files["/new_prefs"]=disk;
|
||||
gps_image.fs.files["/new_prefs"].resize(disk.size()-2);
|
||||
gps_image.fs.files["/new_prefs"].resize(historical_size-2);
|
||||
loaded.usb_debug_enabled=1;
|
||||
assert(gps_image.loadPrefsInt("/new_prefs",loaded,lat,lon));
|
||||
assert(loaded.gps_sync_interval_hours==336&&loaded.usb_debug_enabled==0);
|
||||
@@ -235,6 +252,68 @@ int main(int argc,char** argv){
|
||||
oversized.fs.files["/new_prefs"].resize(disk.size()+65536);
|
||||
assert(!oversized.loadPrefsInt("/new_prefs",loaded,lat,lon));
|
||||
assert(loaded.gps_sync_interval_hours==336&&loaded.usb_debug_enabled==0);
|
||||
} else if(scenario==10){
|
||||
// Even a checksum-consistent unknown policy tag must not become AUTO or
|
||||
// update just one output. Version/size and both enum fields are checked.
|
||||
for(unsigned value=0;value<256;++value){
|
||||
uint8_t footer[mesh::companion::traffic::FooterSize];
|
||||
mesh::companion::traffic::encodeFooter(footer,mesh::RADIO_TX_SECONDARY,mesh::RADIO_TX_OFF);
|
||||
for(unsigned field : {4u,5u}){
|
||||
mesh::companion::traffic::encodeFooter(footer,mesh::RADIO_TX_SECONDARY,mesh::RADIO_TX_OFF);
|
||||
footer[field]=uint8_t(value);
|
||||
uint16_t crc=mesh::companion::traffic::checksum(footer,6);
|
||||
footer[6]=uint8_t(crc>>8);footer[7]=uint8_t(crc);
|
||||
uint8_t media=mesh::RADIO_TX_BOTH,ssh=mesh::RADIO_TX_PRIMARY;
|
||||
bool valid=value==0||(value>=0xa1&&value<=0xa4);
|
||||
assert(mesh::companion::traffic::decodeFooter(footer,sizeof(footer),media,ssh)==valid);
|
||||
if(!valid)assert(media==mesh::RADIO_TX_BOTH&&ssh==mesh::RADIO_TX_PRIMARY);
|
||||
}
|
||||
}
|
||||
// Legacy preference files cannot borrow a configured live traffic route.
|
||||
for(size_t size : {historical_size, disk.size()}){
|
||||
DataStore boot;boot.fs.files["/new_prefs"]=disk;
|
||||
boot.fs.files["/new_prefs"].resize(size);
|
||||
CompanionNodePrefs loaded;loaded.tx_media=mesh::RADIO_TX_BOTH;
|
||||
loaded.tx_ssh=mesh::RADIO_TX_PRIMARY;double lat=1,lon=2;
|
||||
assert(boot.loadPrefsInt("/new_prefs",loaded,lat,lon));
|
||||
assert(loaded.tx_media==(size==disk.size()?mesh::RADIO_TX_SECONDARY:mesh::RADIO_TX_AUTO));
|
||||
assert(loaded.tx_ssh==(size==disk.size()?mesh::RADIO_TX_OFF:mesh::RADIO_TX_AUTO));
|
||||
assert(loaded.freq==original.freq&&loaded.ble_pin==original.ble_pin);
|
||||
}
|
||||
#if defined(RAK_4631)
|
||||
DataStore old_rak;old_rak.fs.files["/new_prefs"]=disk;
|
||||
old_rak.fs.files["/new_prefs"].resize(disk.size()-mesh::companion::traffic::FooterSize);
|
||||
CompanionNodePrefs rak;rak.tx_media=mesh::RADIO_TX_BOTH;double lat=1,lon=2;
|
||||
assert(old_rak.loadPrefsInt("/new_prefs",rak,lat,lon));
|
||||
assert(rak.peripherals_shared==1&&rak.tx_media==mesh::RADIO_TX_AUTO);
|
||||
#endif
|
||||
// Every torn and bit-flipped checked footer fails without any live mutation.
|
||||
const size_t start=disk.size()-mesh::companion::traffic::FooterSize;
|
||||
for(size_t offset=0;offset<mesh::companion::traffic::FooterSize;++offset){
|
||||
for(bool truncate : {false,true}){
|
||||
DataStore boot;auto candidate=disk;
|
||||
if(truncate)candidate.resize(start+offset);
|
||||
else candidate[start+offset]^=0x80;
|
||||
boot.fs.files["/new_prefs"]=candidate;
|
||||
CompanionNodePrefs loaded;loaded.freq=900;loaded.tx_media=mesh::RADIO_TX_BOTH;
|
||||
loaded.tx_ssh=mesh::RADIO_TX_PRIMARY;double lat=1,lon=2;
|
||||
const bool legacy=truncate&&offset==0;
|
||||
assert(boot.loadPrefsInt("/new_prefs",loaded,lat,lon)==legacy);
|
||||
if(!legacy)assert(loaded.freq==900&&loaded.tx_media==mesh::RADIO_TX_BOTH
|
||||
&&loaded.tx_ssh==mesh::RADIO_TX_PRIMARY&&lat==1&&lon==2);
|
||||
assert(boot.fs.files["/new_prefs"]==candidate);
|
||||
}
|
||||
}
|
||||
// Check every valid independent policy pair through real persistence.
|
||||
for(uint8_t media=0;media<=mesh::RADIO_TX_OFF;++media){
|
||||
for(uint8_t ssh=0;ssh<=mesh::RADIO_TX_OFF;++ssh){
|
||||
original.tx_media=media;original.tx_ssh=ssh;
|
||||
assert(store.savePrefs(original,47.1,-122.2));
|
||||
CompanionNodePrefs loaded;double lat=1,lon=2;
|
||||
assert(store.loadPrefs(loaded,lat,lon));
|
||||
assert(loaded.tx_media==media&&loaded.tx_ssh==ssh);
|
||||
}
|
||||
}
|
||||
} else if(scenario==8){
|
||||
for(uint8_t enabled : {0,1}){
|
||||
CompanionNodePrefs saved=original;saved.wifi_enabled=enabled;
|
||||
@@ -321,7 +400,8 @@ inline char* utoa(unsigned int value,char* output,int base){
|
||||
'#include "IdentityStore.h"', '#include <helpers/IdentityStore.h>'))
|
||||
(work / 'test.cpp').write_text(HARNESS.replace('@METHODS@', methods))
|
||||
for platform in ('ESP32_PLATFORM', 'RP2040_PLATFORM', 'STM32_PLATFORM', 'NRF52_PLATFORM',
|
||||
'ESP32_PLATFORM,TBEAM_1W', 'RP2040_PLATFORM,ENABLE_WIFI_INTERFACE'):
|
||||
'ESP32_PLATFORM,TBEAM_1W', 'RP2040_PLATFORM,ENABLE_WIFI_INTERFACE',
|
||||
'NRF52_PLATFORM,RAK_4631'):
|
||||
with self.subTest(platform=platform):
|
||||
binary = work / 'test'
|
||||
sanitizer_flags = [] if os.name == 'nt' else [
|
||||
@@ -341,7 +421,7 @@ inline char* utoa(unsigned int value,char* output,int base){
|
||||
str(ROOT / 'src/helpers/TxtDataHelpers.cpp'),
|
||||
'-o', str(binary)], capture_output=True, text=True)
|
||||
self.assertEqual(build.returncode, 0, build.stdout + build.stderr)
|
||||
for scenario in range(10):
|
||||
for scenario in range(11):
|
||||
with self.subTest(scenario=scenario):
|
||||
run = subprocess.run([str(binary), str(scenario)], capture_output=True, text=True)
|
||||
self.assertEqual(run.returncode, 0, run.stdout + run.stderr)
|
||||
|
||||
@@ -61,6 +61,8 @@ static void seed(CompanionNodePrefs& prefs, uint32_t& random) {
|
||||
}
|
||||
};
|
||||
@SEED@
|
||||
prefs.tx_media = random % 5;
|
||||
prefs.tx_ssh = (random >> 8) % 5;
|
||||
}
|
||||
|
||||
static std::vector<uint8_t> golden(const CompanionNodePrefs& prefs,
|
||||
@@ -78,6 +80,18 @@ static std::vector<uint8_t> golden(const CompanionNodePrefs& prefs,
|
||||
#else
|
||||
assert(bytes.size() == 236);
|
||||
#endif
|
||||
// Independent wire definition of the new checked traffic footer. Keep
|
||||
// every historical byte above unchanged and encode the public policy tags.
|
||||
bytes.insert(bytes.end(), {'T', 'X', 'R', 1,
|
||||
uint8_t(prefs.tx_media ? 0xa0 | prefs.tx_media : 0),
|
||||
uint8_t(prefs.tx_ssh ? 0xa0 | prefs.tx_ssh : 0)});
|
||||
uint16_t crc = 0xffff;
|
||||
for(size_t i=bytes.size()-6;i<bytes.size();++i){
|
||||
crc ^= uint16_t(bytes[i]) << 8;
|
||||
for(unsigned bit=0;bit<8;++bit)
|
||||
crc = (crc&0x8000) ? uint16_t((crc<<1)^0x1021) : uint16_t(crc<<1);
|
||||
}
|
||||
bytes.push_back(uint8_t(crc>>8));bytes.push_back(uint8_t(crc));
|
||||
return bytes;
|
||||
}
|
||||
|
||||
@@ -105,14 +119,18 @@ int main() {
|
||||
|
||||
CompanionNodePrefs original;
|
||||
assert(original.lost_reply == 0);
|
||||
assert(original.tx_media == mesh::RADIO_TX_AUTO && original.tx_ssh == mesh::RADIO_TX_AUTO);
|
||||
strcpy(original.node_name, "durable image");
|
||||
original.freq = 915.25f; original.ble_pin = 123456;
|
||||
original.bluetooth_enabled = 1; original.usb_debug_enabled = 1;
|
||||
original.gps_sync_interval_hours = 336;
|
||||
original.lost_reply = 2;
|
||||
original.tx_media = mesh::RADIO_TX_SECONDARY;
|
||||
original.tx_ssh = mesh::RADIO_TX_OFF;
|
||||
DataStore initial;
|
||||
assert(initial.savePrefs(original, 47.125, -122.25));
|
||||
const auto before = golden(original, 47.125, -122.25);
|
||||
const size_t historical_size=before.size()-mesh::companion::traffic::FooterSize;
|
||||
assert(initial.fs.files.at("/new_prefs") == before);
|
||||
|
||||
// Every complete historical wire boundary stays readable, and an old
|
||||
@@ -135,10 +153,12 @@ int main() {
|
||||
auto historical = before; historical.resize(length);
|
||||
reboot.fs.files["/new_prefs"] = historical;
|
||||
CompanionNodePrefs live; live.lost_reply = 2;
|
||||
live.tx_media=mesh::RADIO_TX_BOTH;live.tx_ssh=mesh::RADIO_TX_PRIMARY;
|
||||
live.getCustom()->setByKey("local_tag", "unchanged");
|
||||
double lat = 1, lon = 2;
|
||||
assert(reboot.loadPrefsInt("/new_prefs", live, lat, lon));
|
||||
assert(live.lost_reply == 0 && live.ble_pin == original.ble_pin);
|
||||
assert(live.tx_media==mesh::RADIO_TX_AUTO&&live.tx_ssh==mesh::RADIO_TX_AUTO);
|
||||
assert(live.freq == original.freq && !strcmp(live.node_name, original.node_name));
|
||||
assert(lat == 47.125 && lon == -122.25);
|
||||
assert(reboot.fs.files.at("/new_prefs") == historical);
|
||||
@@ -151,6 +171,7 @@ int main() {
|
||||
// a full extra byte range, including sizes that could alias legacy values
|
||||
// if the underlying file size were accidentally narrowed with the table.
|
||||
std::vector<size_t> accepted_sizes = legacy_sizes;
|
||||
accepted_sizes.push_back(historical_size);
|
||||
accepted_sizes.push_back(before.size());
|
||||
for (size_t length = 0; length <= before.size() + 256; ++length) {
|
||||
DataStore reboot;
|
||||
@@ -167,7 +188,9 @@ int main() {
|
||||
assert(reboot.loadPrefsInt("/new_prefs", live, lat, lon) == expected);
|
||||
if (expected) {
|
||||
assert(live.freq == original.freq);
|
||||
assert(live.lost_reply == (length == before.size() ? 2 : 0));
|
||||
assert(live.lost_reply == (length >= historical_size ? 2 : 0));
|
||||
assert(live.tx_media == (length == before.size() ? mesh::RADIO_TX_SECONDARY : mesh::RADIO_TX_AUTO));
|
||||
assert(live.tx_ssh == (length == before.size() ? mesh::RADIO_TX_OFF : mesh::RADIO_TX_AUTO));
|
||||
assert(lat == 47.125 && lon == -122.25);
|
||||
} else {
|
||||
assert(live.freq == 920.5f && live.lost_reply == 1);
|
||||
@@ -189,8 +212,9 @@ int main() {
|
||||
DataStore writer;
|
||||
assert(writer.savePrefs(saved, 47.125, -122.25));
|
||||
const auto disk = writer.fs.files.at("/new_prefs");
|
||||
assert(disk.back() == value);
|
||||
assert(std::equal(disk.begin(), disk.end() - 1, before.begin()));
|
||||
assert(disk[historical_size-1] == value);
|
||||
assert(std::equal(disk.begin(), disk.begin()+historical_size-1, before.begin()));
|
||||
assert(std::equal(disk.begin()+historical_size, disk.end(), before.begin()+historical_size));
|
||||
DataStore reboot; reboot.fs.files["/new_prefs"] = disk;
|
||||
CompanionNodePrefs live; live.lost_reply = 2;
|
||||
double lat = 1, lon = 2;
|
||||
@@ -272,6 +296,7 @@ int main() {
|
||||
assert(loaded.freq == changed.freq && loaded.ble_pin == changed.ble_pin);
|
||||
assert(loaded.gps_sync_interval_hours == 24 && loaded.usb_debug_enabled == 0);
|
||||
assert(loaded.lost_reply == 1);
|
||||
assert(loaded.tx_media == original.tx_media && loaded.tx_ssh == original.tx_ssh);
|
||||
assert(lat == 42.25 && lon == -121.125);
|
||||
|
||||
#if defined(STM32_PLATFORM)
|
||||
|
||||
@@ -55,22 +55,23 @@ int main() {
|
||||
assert(compact.savePrefs(prefs,47.1,-122.2));
|
||||
assert(legacy.savePrefsLegacy(prefs,47.1,-122.2));
|
||||
const auto& image=compact.fs.files["/new_prefs"];
|
||||
assert(image==legacy.fs.files["/new_prefs"]);
|
||||
const size_t historical_size=image.size()-mesh::companion::traffic::FooterSize;
|
||||
assert(std::vector<uint8_t>(image.begin(),image.begin()+historical_size)==legacy.fs.files["/new_prefs"]);
|
||||
#if defined(TBEAM_1W)
|
||||
assert(image.size()==243);
|
||||
assert(historical_size==243);
|
||||
#elif defined(RP2040_PLATFORM) && defined(ENABLE_WIFI_INTERFACE)
|
||||
assert(image.size()==333);
|
||||
assert(historical_size==333);
|
||||
#else
|
||||
assert(image.size()==236);
|
||||
assert(historical_size==236);
|
||||
#endif
|
||||
const uint8_t expected[]={prefs.flood_retry_attempts,prefs.flood_retry_max_path,
|
||||
prefs.flood_retry_group_max_path,prefs.flood_retry_advert_enabled,
|
||||
prefs.one_key_dm_enabled,prefs.bluetooth_enabled,0,0,prefs.usb_debug_enabled,
|
||||
prefs.lost_reply};
|
||||
assert(!memcmp(image.data()+image.size()-10,expected,6));
|
||||
assert(!memcmp(image.data()+image.size()-4,&prefs.gps_sync_interval_hours,2));
|
||||
assert(image[image.size()-2]==prefs.usb_debug_enabled);
|
||||
assert(image.back()==prefs.lost_reply);
|
||||
assert(!memcmp(image.data()+historical_size-10,expected,6));
|
||||
assert(!memcmp(image.data()+historical_size-4,&prefs.gps_sync_interval_hours,2));
|
||||
assert(image[historical_size-2]==prefs.usb_debug_enabled);
|
||||
assert(image[historical_size-1]==prefs.lost_reply);
|
||||
}
|
||||
DataStore initial; assert(initial.savePrefs(original,47.1,-122.2));
|
||||
const auto disk=initial.fs.files["/new_prefs"];
|
||||
@@ -94,9 +95,9 @@ int main() {
|
||||
};
|
||||
// A short return at each boundary of the single final write must abort the
|
||||
// transaction, including either byte of the two-byte GPS field.
|
||||
for (unsigned boundary=0; boundary<10; ++boundary) {
|
||||
for (unsigned boundary=0; boundary<10+mesh::companion::traffic::FooterSize; ++boundary) {
|
||||
DataStore store; store.fs.files["/new_prefs"]=disk;
|
||||
store.fs.fail_write_after=int(disk.size()-10+boundary);
|
||||
store.fs.fail_write_after=int(disk.size()-mesh::companion::traffic::FooterSize-10+boundary);
|
||||
assert(!store.savePrefs(changed,42.3,-121.2)); expectOld(store);
|
||||
store.fs.fail_write_after=-1;
|
||||
assert(store.savePrefs(changed,42.3,-121.2));
|
||||
@@ -104,9 +105,9 @@ int main() {
|
||||
}
|
||||
// Fully written bytes still cannot replace the live image until readback
|
||||
// verifies every final-tail boundary. LittleFS's retries also must fail.
|
||||
for (unsigned boundary=0; boundary<10; ++boundary) {
|
||||
for (unsigned boundary=0; boundary<10+mesh::companion::traffic::FooterSize; ++boundary) {
|
||||
DataStore store; store.fs.files["/new_prefs"]=disk;
|
||||
store.fs.fail_read_after=int(disk.size()-10+boundary);
|
||||
store.fs.fail_read_after=int(disk.size()-mesh::companion::traffic::FooterSize-10+boundary);
|
||||
assert(!store.savePrefs(changed,42.3,-121.2)); expectOld(store);
|
||||
}
|
||||
{
|
||||
|
||||
@@ -36,9 +36,9 @@ static size_t adapterOffset(const CompanionNodePrefs& prefs) {
|
||||
// The value helper does not copy the adapters or their inter-field padding.
|
||||
// Use the complete object's byte representation for bounded observation.
|
||||
const uintptr_t first = reinterpret_cast<uintptr_t>(&prefs);
|
||||
const uintptr_t last = reinterpret_cast<uintptr_t>(&prefs.lost_reply);
|
||||
const uintptr_t last = reinterpret_cast<uintptr_t>(&prefs.tx_ssh);
|
||||
assert(last >= first && last - first < sizeof(prefs));
|
||||
return static_cast<size_t>(last - first) + sizeof(prefs.lost_reply);
|
||||
return static_cast<size_t>(last - first) + sizeof(prefs.tx_ssh);
|
||||
}
|
||||
|
||||
static std::vector<uint8_t> adapterBytes(const CompanionNodePrefs& prefs) {
|
||||
@@ -92,7 +92,10 @@ int main() {
|
||||
saved.bluetooth_enabled = static_cast<uint8_t>(trial);
|
||||
DataStore image_store;
|
||||
assert(image_store.savePrefs(saved, 47.125, -122.25));
|
||||
const auto image = image_store.fs.files["/new_prefs"];
|
||||
auto image = image_store.fs.files["/new_prefs"];
|
||||
// The frozen reference remains authoritative only for the historical
|
||||
// prefix. Checked new-footer behavior has dedicated persistence tests.
|
||||
image.resize(image.size()-mesh::companion::traffic::FooterSize);
|
||||
// Test every possible old/torn image length, including every officially
|
||||
// supported append boundary and unknown lengths beyond the current tail.
|
||||
for (size_t length = 0; length <= image.size() + 5; ++length) {
|
||||
@@ -124,7 +127,9 @@ int main() {
|
||||
"/new_prefs", actual, lat, lon);
|
||||
assert(got == expected);
|
||||
assert(READ_CALLS == expected_reads);
|
||||
assert(AVAILABLE_CALLS == expected_available);
|
||||
// The common footer reader adds one EOF probe after any recognized
|
||||
// historical image; no original field read or ordering changes.
|
||||
assert(AVAILABLE_CALLS == expected_available+(expected_reads.empty()?0:1));
|
||||
if (length == 84 && quota == 84) {
|
||||
// The original mandatory prefix has 21 reads, ending at ble_pin.
|
||||
// This order is an independent wire contract, not the new table.
|
||||
@@ -141,8 +146,9 @@ int main() {
|
||||
#endif
|
||||
// Every absent optional field observes EOF, then the completed
|
||||
// image receives the existing final trailing-byte check.
|
||||
assert(AVAILABLE_CALLS == optional_fields + 1);
|
||||
assert(AVAILABLE_CALLS == optional_fields + 2);
|
||||
}
|
||||
if(got)legacy.tx_media=legacy.tx_ssh=mesh::RADIO_TX_AUTO;
|
||||
equalValues(actual, legacy);
|
||||
assert(!memcmp(&lat, &legacy_lat, sizeof(lat)));
|
||||
assert(!memcmp(&lon, &legacy_lon, sizeof(lon)));
|
||||
@@ -185,7 +191,7 @@ class CompanionPrefsValuesTests(unittest.TestCase):
|
||||
r'^\s*(?:float|char|u?int(?:8|16|32)_t)\s+([A-Za-z_][A-Za-z_0-9]*)',
|
||||
prefix, re.M)
|
||||
self.assertEqual(declarations[0], 'airtime_factor')
|
||||
self.assertEqual(declarations[-2:], ['lost_reply', 'peripherals_shared'])
|
||||
self.assertEqual(declarations[-2:], ['tx_media', 'tx_ssh'])
|
||||
optional = {
|
||||
'fan_mode': 'TBEAM_1W', 'fan_lo': 'TBEAM_1W', 'fan_hi': 'TBEAM_1W',
|
||||
'wifi_ssid': 'defined(RP2040_PLATFORM) && defined(ENABLE_WIFI_INTERFACE)',
|
||||
|
||||
@@ -122,15 +122,13 @@ class CompanionSettingsPersistenceContractTests(unittest.TestCase):
|
||||
"bool copyPersistedValuesFrom(const CompanionNodePrefs& source)",
|
||||
)
|
||||
self.assertIn("reinterpret_cast<uintptr_t>(&airtime_factor)", copy)
|
||||
# RAK4631 appends its peripheral-mode byte; every other target stops
|
||||
# at lost-reply. Neither endpoint may include a runtime adapter.
|
||||
self.assertIn("const auto& last_value = peripherals_shared;", copy)
|
||||
self.assertIn("const auto& last_value = lost_reply;", copy)
|
||||
# Both common traffic preferences follow the optional RAK policy.
|
||||
# The final value may never include either runtime adapter.
|
||||
self.assertIn("const auto& last_value = tx_ssh;", copy)
|
||||
self.assertIn("reinterpret_cast<uintptr_t>(&last_value)", copy)
|
||||
self.assertIn("&values.peripherals_shared", copy)
|
||||
self.assertIn("&values.lost_reply", copy)
|
||||
self.assertIn("+ sizeof(lost_reply)", copy)
|
||||
self.assertIn("end - begin == size - sizeof(values.lost_reply)", copy)
|
||||
self.assertIn("&values.tx_ssh", copy)
|
||||
self.assertIn("+ sizeof(tx_ssh)", copy)
|
||||
self.assertIn("end - begin == size - sizeof(values.tx_ssh)", copy)
|
||||
self.assertIn("reinterpret_cast<uintptr_t>(&values.radio)", copy)
|
||||
self.assertIn("reinterpret_cast<uintptr_t>(&values.custom)", copy)
|
||||
self.assertIn("size <= radio_begin - begin", copy)
|
||||
|
||||
@@ -0,0 +1,419 @@
|
||||
"""Exercise production Companion media/SSH routing without radios or flash writes."""
|
||||
from pathlib import Path
|
||||
import re
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
from test_radio_receive_contract import method
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
HEADER_HARNESS = r'''
|
||||
#include <cassert>
|
||||
#include <cstdint>
|
||||
#include <cstring>
|
||||
#include <initializer_list>
|
||||
#include <vector>
|
||||
#include <helpers/CompanionTrafficRouting.h>
|
||||
|
||||
int main() {
|
||||
using namespace mesh;
|
||||
using namespace mesh::companion;
|
||||
for (const auto kind : {TrafficKind::Media, TrafficKind::Ssh}) {
|
||||
const char* name=kind==TrafficKind::Media ? "media" : "ssh";
|
||||
char text[96];
|
||||
snprintf(text,sizeof(text),"get tx.%s",name);
|
||||
auto parsed=parseTrafficRouteCommand(text);
|
||||
assert(parsed.matched && parsed.valid && !parsed.set && parsed.kind==kind);
|
||||
for (uint8_t policy=RADIO_TX_AUTO; policy<=RADIO_TX_OFF; ++policy) {
|
||||
snprintf(text,sizeof(text),"set tx.%s %s",name,radioTxPolicyName(policy));
|
||||
parsed=parseTrafficRouteCommand(text);
|
||||
assert(parsed.matched && parsed.valid && parsed.set && parsed.kind==kind && parsed.policy==policy);
|
||||
}
|
||||
for (const char* value : {"", "radio3", "RADIO", "radio trailing", "-1", "auto both"}) {
|
||||
snprintf(text,sizeof(text),"set tx.%s %s",name,value);
|
||||
parsed=parseTrafficRouteCommand(text);
|
||||
assert(parsed.matched && !parsed.valid);
|
||||
}
|
||||
snprintf(text,sizeof(text),"get tx.%s extra",name);
|
||||
parsed=parseTrafficRouteCommand(text);
|
||||
assert(parsed.matched && !parsed.valid);
|
||||
}
|
||||
for (const char* text : {"get tx.mediax", "set tx.sshx radio", "get tx.user Bob", "get tx.channel 0", "set tx.radio both", ""})
|
||||
assert(!parseTrafficRouteCommand(text).matched);
|
||||
assert(!parseTrafficRouteCommand(nullptr).matched);
|
||||
|
||||
assert(rawTrafficKind(nullptr,0)==TrafficKind::Other);
|
||||
assert(rawTrafficKind(nullptr,20)==TrafficKind::Other);
|
||||
const uint8_t normal[]={0x56,0,1,2,3,0,99};
|
||||
const uint8_t salted[]={0x57,0,1,2,3,0,99,42};
|
||||
assert(rawTrafficKind(normal,sizeof(normal))==TrafficKind::Media);
|
||||
assert(rawTrafficKind(salted,sizeof(salted))==TrafficKind::Media);
|
||||
for (size_t n=0;n<sizeof(normal);++n) assert(rawTrafficKind(normal,n)==TrafficKind::Other);
|
||||
for (size_t n=0;n<sizeof(salted);++n) assert(rawTrafficKind(salted,n)==TrafficKind::Other);
|
||||
// A complete binary media fetch is media, including optional missing indices
|
||||
// and reverse-path hint. A truncated packet cannot commandeer a TX policy.
|
||||
const uint8_t fetch_all[]={0x72,0,1,2,3,0,1,2,3,4,5,6,0};
|
||||
const uint8_t fetch_missing[]={0x72,0,1,2,3,3,1,2,3,4,5,6,2,0,17};
|
||||
const uint8_t fetch_path[]={0x72,0,1,2,3,7,1,2,3,4,5,6,2,0,17,2,11,12};
|
||||
for (const auto* data : {fetch_all,fetch_missing,fetch_path}) {
|
||||
const size_t n=data==fetch_all ? sizeof(fetch_all) : data==fetch_missing ? sizeof(fetch_missing) : sizeof(fetch_path);
|
||||
assert(rawTrafficKind(data,n)==TrafficKind::Media);
|
||||
}
|
||||
for (size_t n=0;n<sizeof(fetch_all);++n) assert(rawTrafficKind(fetch_all,n)==TrafficKind::Other);
|
||||
assert(rawTrafficKind(fetch_missing,sizeof(fetch_missing)-1)==TrafficKind::Other);
|
||||
assert(rawTrafficKind(fetch_path,sizeof(fetch_path)-1)==TrafficKind::Other);
|
||||
std::vector<uint8_t> reserved(fetch_all,fetch_all+sizeof(fetch_all));
|
||||
reserved[5]=0x80;
|
||||
assert(rawTrafficKind(reserved.data(),reserved.size())==TrafficKind::Other);
|
||||
|
||||
const uint8_t ssh[]={0x53,0x53,0x48,0x01,0x99};
|
||||
assert(rawTrafficKind(ssh,sizeof(ssh))==TrafficKind::Ssh);
|
||||
for (size_t n=0;n<sizeof(ssh);++n) assert(rawTrafficKind(ssh,n)==TrafficKind::Other);
|
||||
for (unsigned i=0;i<4;++i) {
|
||||
uint8_t unknown[sizeof(ssh)]; memcpy(unknown,ssh,sizeof(ssh)); unknown[i]^=0x20;
|
||||
assert(rawTrafficKind(unknown,sizeof(unknown))==TrafficKind::Other);
|
||||
}
|
||||
const uint8_t opaque[]={0x9f,0x5c,0x53,0x53,0x48,0x01,0x11};
|
||||
const uint8_t ssh_banner[]={'S','S','H','-','2','.','0'};
|
||||
const uint8_t ipv4[]={0x45,0,0,20,0,0,0,0,64,6,0,0,10,0,0,1,10,0,0,2};
|
||||
assert(rawTrafficKind(opaque,sizeof(opaque))==TrafficKind::Other);
|
||||
assert(rawTrafficKind(ssh_banner,sizeof(ssh_banner))==TrafficKind::Other);
|
||||
assert(rawTrafficKind(ipv4,sizeof(ipv4))==TrafficKind::Other);
|
||||
assert(groupTrafficKind(0x5643)==TrafficKind::Media);
|
||||
assert(groupTrafficKind(0x5353)==TrafficKind::Ssh);
|
||||
for (uint16_t type : {0,1,0x5654,0x5642,0x5352,0xffff}) assert(groupTrafficKind(type)==TrafficKind::Other);
|
||||
for (uint8_t media=0;media<=4;++media) for (uint8_t ssh_policy=0;ssh_policy<=4;++ssh_policy) {
|
||||
assert(trafficPolicy(TrafficKind::Other,media,ssh_policy)==RADIO_TX_AUTO);
|
||||
assert(trafficPolicy(TrafficKind::Media,media,ssh_policy)==media);
|
||||
assert(trafficPolicy(TrafficKind::Ssh,media,ssh_policy)==ssh_policy);
|
||||
}
|
||||
|
||||
RadioProfiles profiles;
|
||||
profiles.cross=RadioCrossMode::Off;
|
||||
for (const auto mode : {RadioProfileMode::Off,RadioProfileMode::Rx,RadioProfileMode::RxTx}) {
|
||||
profiles.secondary.mode=mode;
|
||||
const bool secondary=mode==RadioProfileMode::RxTx;
|
||||
assert(trafficTransmitMask(RADIO_TX_AUTO,&profiles)==1);
|
||||
assert(trafficTransmitMask(RADIO_TX_PRIMARY,&profiles)==1);
|
||||
assert(trafficTransmitMask(RADIO_TX_SECONDARY,&profiles)==(secondary ? 2 : 0));
|
||||
assert(trafficTransmitMask(RADIO_TX_BOTH,&profiles)==(secondary ? 3 : 1));
|
||||
assert(trafficTransmitMask(RADIO_TX_OFF,&profiles)==0);
|
||||
}
|
||||
profiles.secondary.mode=RadioProfileMode::RxTx;
|
||||
profiles.cross=RadioCrossMode::On;
|
||||
assert(trafficTransmitMask(RADIO_TX_AUTO,&profiles)==3);
|
||||
profiles.secondary.params.protocol=RadioProfileProtocol::Meshtext;
|
||||
assert(trafficTransmitMask(RADIO_TX_SECONDARY,&profiles)==0);
|
||||
assert(trafficTransmitMask(RADIO_TX_BOTH,&profiles)==1);
|
||||
assert(trafficTransmitMask(RADIO_TX_AUTO,&profiles)==1);
|
||||
profiles.primary.protocol=RadioProfileProtocol::Meshtext;
|
||||
assert(trafficTransmitMask(RADIO_TX_PRIMARY,&profiles)==0);
|
||||
assert(trafficTransmitMask(RADIO_TX_BOTH,&profiles)==0);
|
||||
assert(trafficTransmitMask(RADIO_TX_AUTO,&profiles)==0);
|
||||
for (uint8_t policy=0;policy<=4;++policy)
|
||||
assert(trafficTransmitMask(policy,nullptr)==((policy==RADIO_TX_AUTO || policy==RADIO_TX_PRIMARY || policy==RADIO_TX_BOTH) ? 1 : 0));
|
||||
}
|
||||
'''
|
||||
|
||||
|
||||
METHOD_HARNESS = r'''
|
||||
#include <cassert>
|
||||
#include <cstdio>
|
||||
#include <cstdint>
|
||||
#include <cstring>
|
||||
#include <initializer_list>
|
||||
#include <vector>
|
||||
#include <helpers/CompanionTrafficRouting.h>
|
||||
#define OUT_PATH_UNKNOWN 0xff
|
||||
#define MAX_GROUP_DATA_LENGTH 163
|
||||
namespace mesh {
|
||||
struct GroupChannel { uint8_t secret[32]={},hash[1]={},tx_radio=RADIO_TX_AUTO; };
|
||||
struct Packet { uint8_t tx_radio=RADIO_TX_AUTO; };
|
||||
}
|
||||
struct Radio {
|
||||
mesh::RadioProfiles config;
|
||||
bool available=true;
|
||||
mesh::RadioProfiles* profiles() { return available ? &config : nullptr; }
|
||||
};
|
||||
struct Prefs { uint8_t tx_media=mesh::RADIO_TX_AUTO,tx_ssh=mesh::RADIO_TX_AUTO; };
|
||||
class MyMesh {
|
||||
public:
|
||||
Prefs _prefs,saved;
|
||||
Radio radio; Radio* _radio=&radio;
|
||||
unsigned writes=0,group_calls=0,raw_calls=0,direct_calls=0;
|
||||
uint8_t last_policy=0,last_path_len=0;
|
||||
uint16_t last_type=0;
|
||||
std::vector<uint8_t> last_data;
|
||||
mesh::Packet raw_packet;
|
||||
bool save_ok=true,allocate_ok=true,send_ok=true;
|
||||
bool savePrefs() { ++writes; if (!save_ok) return false; saved=_prefs; return true; }
|
||||
template<typename T> bool savePreference(T& field,T value) {
|
||||
const T before=field; field=value; if (savePrefs()) return true; field=before; return false;
|
||||
}
|
||||
mesh::Packet* createRawData(const uint8_t* data,size_t len) {
|
||||
++raw_calls; if (!allocate_ok) return nullptr; raw_packet.tx_radio=mesh::RADIO_TX_AUTO;
|
||||
last_data.assign(data,data+len); return &raw_packet;
|
||||
}
|
||||
bool sendDirect(mesh::Packet* packet,uint8_t*,uint8_t n) {
|
||||
++direct_calls; last_policy=packet->tx_radio; last_path_len=n;
|
||||
return send_ok && mesh::companion::trafficTransmitMask(last_policy,_radio->profiles());
|
||||
}
|
||||
bool sendGroupData(mesh::GroupChannel& channel,uint8_t*,uint8_t n,uint16_t type,const uint8_t* data,int len) {
|
||||
++group_calls; last_policy=channel.tx_radio; last_type=type; last_path_len=n;
|
||||
if (len<0 || len>MAX_GROUP_DATA_LENGTH) return false;
|
||||
last_data.assign(data,data+len);
|
||||
return send_ok && mesh::companion::trafficTransmitMask(channel.tx_radio,_radio->profiles());
|
||||
}
|
||||
bool handleTrafficRoutingCommand(const char*,char*,size_t);
|
||||
bool sendClientGroupData(mesh::GroupChannel&,uint8_t*,uint8_t,uint16_t,const uint8_t*,int);
|
||||
bool sendClientRawData(const uint8_t*,size_t,uint8_t*,uint8_t);
|
||||
};
|
||||
@METHODS@
|
||||
|
||||
int main() {
|
||||
using namespace mesh;
|
||||
MyMesh node;
|
||||
node.radio.config.secondary.mode=RadioProfileMode::RxTx;
|
||||
node.radio.config.cross=RadioCrossMode::Off;
|
||||
char reply[160];
|
||||
auto cmd=[&](const char* text) { memset(reply,0,sizeof(reply)); assert(node.handleTrafficRoutingCommand(text,reply,sizeof(reply))); };
|
||||
assert(!node.handleTrafficRoutingCommand("get tx.user Bob",reply,sizeof(reply)));
|
||||
for (const char* name : {"media","ssh"}) {
|
||||
char text[64];
|
||||
snprintf(text,sizeof(text),"get tx.%s",name); cmd(text);
|
||||
assert(strstr(reply,"auto") && strstr(reply,"active=channel/global"));
|
||||
for (uint8_t policy=0;policy<=4;++policy) {
|
||||
snprintf(text,sizeof(text),"set tx.%s %s",name,radioTxPolicyName(policy)); cmd(text);
|
||||
assert(!strncmp(reply,"OK",2));
|
||||
assert((!strcmp(name,"media") ? node._prefs.tx_media : node._prefs.tx_ssh)==policy);
|
||||
}
|
||||
}
|
||||
assert(node.saved.tx_media==RADIO_TX_OFF && node.saved.tx_ssh==RADIO_TX_OFF);
|
||||
const Prefs durable=node.saved;
|
||||
const auto previous_writes=node.writes;
|
||||
for (const char* text : {"set tx.media", "set tx.ssh radio3", "get tx.ssh extra"}) {
|
||||
cmd(text); assert(!strncmp(reply,"Error",5));
|
||||
assert(node._prefs.tx_media==durable.tx_media && node._prefs.tx_ssh==durable.tx_ssh);
|
||||
}
|
||||
assert(node.writes==previous_writes);
|
||||
node.save_ok=false;
|
||||
// Even setting the current value must attempt a durable save; otherwise a
|
||||
// boot following a failed flash-time preference write can report false OK.
|
||||
cmd("set tx.media off"); assert(!strncmp(reply,"Error",5) && node.writes==previous_writes+1);
|
||||
cmd("set tx.media both"); assert(!strncmp(reply,"Error",5));
|
||||
assert(node._prefs.tx_media==RADIO_TX_OFF && node.saved.tx_media==durable.tx_media);
|
||||
cmd("set tx.ssh radio2"); assert(!strncmp(reply,"Error",5));
|
||||
assert(node._prefs.tx_ssh==RADIO_TX_OFF && node.saved.tx_ssh==durable.tx_ssh);
|
||||
node.save_ok=true;
|
||||
cmd("set tx.media radio2");
|
||||
node.radio.config.secondary.mode=RadioProfileMode::Rx;
|
||||
cmd("get tx.media"); assert(strstr(reply,"unavailable") && strstr(reply,"active=off"));
|
||||
node.radio.config.secondary.mode=RadioProfileMode::RxTx;
|
||||
node.radio.config.secondary.params.protocol=RadioProfileProtocol::Meshtext;
|
||||
cmd("get tx.media"); assert(strstr(reply,"unavailable") && strstr(reply,"active=off"));
|
||||
node.radio.config.secondary.params.protocol=RadioProfileProtocol::MeshCore;
|
||||
cmd("set tx.media auto"); cmd("set tx.ssh auto");
|
||||
const uint8_t media[]={0x56,0,1,2,3,0,99};
|
||||
const uint8_t ssh[]={'S','S','H',1,42};
|
||||
const uint8_t unknown[]={1,2,3,4,5,6,7};
|
||||
uint8_t path[]={0x11,0x22};
|
||||
GroupChannel channel;
|
||||
channel.tx_radio=RADIO_TX_SECONDARY;
|
||||
channel.secret[0]=0x42;
|
||||
const auto original=channel;
|
||||
for (uint8_t policy=0;policy<=4;++policy) {
|
||||
node._prefs.tx_media=policy; node._prefs.tx_ssh=RADIO_TX_BOTH;
|
||||
bool result=node.sendClientGroupData(channel,path,2,0x5643,media,sizeof(media));
|
||||
const uint8_t expected=policy==RADIO_TX_AUTO ? original.tx_radio : policy;
|
||||
assert(result==(expected!=RADIO_TX_OFF));
|
||||
if (result) { assert(node.last_policy==expected && node.last_type==0x5643 && node.last_path_len==2); }
|
||||
assert(!memcmp(&channel,&original,sizeof(channel)));
|
||||
result=node.sendClientRawData(media,sizeof(media),path,2);
|
||||
assert(result==(policy!=RADIO_TX_OFF));
|
||||
if (result) assert(node.last_policy==policy && node.last_data==std::vector<uint8_t>(media,media+sizeof(media)));
|
||||
}
|
||||
node._prefs.tx_media=RADIO_TX_OFF;
|
||||
for (uint8_t policy=0;policy<=4;++policy) {
|
||||
node._prefs.tx_ssh=policy;
|
||||
bool result=node.sendClientGroupData(channel,path,2,0x5353,ssh,sizeof(ssh));
|
||||
const uint8_t expected=policy==RADIO_TX_AUTO ? original.tx_radio : policy;
|
||||
assert(result==(expected!=RADIO_TX_OFF));
|
||||
if (result) assert(node.last_policy==expected);
|
||||
result=node.sendClientRawData(ssh,sizeof(ssh),path,2);
|
||||
assert(result==(policy!=RADIO_TX_OFF));
|
||||
if (result) assert(node.last_policy==policy && node.last_data==std::vector<uint8_t>(ssh,ssh+sizeof(ssh)));
|
||||
assert(!memcmp(&channel,&original,sizeof(channel)));
|
||||
}
|
||||
node._prefs.tx_media=node._prefs.tx_ssh=RADIO_TX_OFF;
|
||||
assert(node.sendClientGroupData(channel,path,2,0x5654,unknown,sizeof(unknown)));
|
||||
assert(node.last_policy==original.tx_radio && node.last_type==0x5654);
|
||||
assert(node.sendClientRawData(unknown,sizeof(unknown),path,2));
|
||||
assert(node.last_policy==RADIO_TX_AUTO);
|
||||
node._prefs.tx_media=RADIO_TX_SECONDARY;
|
||||
node.radio.config.secondary.mode=RadioProfileMode::Off;
|
||||
assert(!node.sendClientRawData(media,sizeof(media),path,2));
|
||||
assert(!node.sendClientGroupData(channel,path,2,0x5643,media,sizeof(media)));
|
||||
node.radio.config.secondary.mode=RadioProfileMode::Rx;
|
||||
assert(!node.sendClientRawData(media,sizeof(media),path,2));
|
||||
node.radio.config.secondary.mode=RadioProfileMode::RxTx;
|
||||
node.radio.config.secondary.params.protocol=RadioProfileProtocol::Meshtext;
|
||||
assert(!node.sendClientRawData(media,sizeof(media),path,2));
|
||||
node.radio.config.secondary.params.protocol=RadioProfileProtocol::MeshCore;
|
||||
node.allocate_ok=false;
|
||||
assert(!node.sendClientRawData(media,sizeof(media),path,2));
|
||||
node.allocate_ok=true; node.send_ok=false;
|
||||
assert(!node.sendClientRawData(media,sizeof(media),path,2));
|
||||
assert(!node.sendClientGroupData(channel,path,2,0x5643,media,sizeof(media)));
|
||||
assert(!node.sendClientRawData(nullptr,20,path,2));
|
||||
assert(!node.sendClientRawData(media,3,path,2));
|
||||
assert(!node.sendClientGroupData(channel,path,2,0x5643,media,-1));
|
||||
assert(!node.sendClientGroupData(channel,path,2,0x5643,media,MAX_GROUP_DATA_LENGTH+1));
|
||||
assert(!node.sendClientGroupData(channel,path,2,0x5643,nullptr,1));
|
||||
assert(!node.handleTrafficRoutingCommand("get tx.media",nullptr,1));
|
||||
assert(!node.handleTrafficRoutingCommand("get tx.media",reply,0));
|
||||
// Reply formatting never writes past the caller's advertised capacity.
|
||||
node.send_ok=true;
|
||||
for (size_t cap=1;cap<12;++cap) {
|
||||
char bounded[16]; memset(bounded,0x6b,sizeof(bounded));
|
||||
assert(node.handleTrafficRoutingCommand("get tx.media",bounded,cap));
|
||||
assert(bounded[cap-1]==0);
|
||||
for (size_t i=cap;i<sizeof(bounded);++i) assert(bounded[i]==0x6b);
|
||||
}
|
||||
}
|
||||
'''
|
||||
|
||||
|
||||
RAW_FRAME_HARNESS = r'''
|
||||
#include <cassert>
|
||||
#include <cstdint>
|
||||
#include <cstring>
|
||||
#include <initializer_list>
|
||||
#include <memory>
|
||||
#pragma GCC diagnostic push
|
||||
#pragma GCC diagnostic ignored "-Wunused-parameter"
|
||||
#include <Packet.h>
|
||||
#pragma GCC diagnostic pop
|
||||
@CONSTANTS@
|
||||
namespace mesh {
|
||||
@PACKET_METHODS@
|
||||
}
|
||||
class MyMesh {
|
||||
public:
|
||||
unsigned ok=0,errors=0,sends=0;
|
||||
uint8_t error=0;
|
||||
bool send_ok=true;
|
||||
const uint8_t* frame=nullptr;
|
||||
size_t frame_length=0;
|
||||
void writeOKFrame() { ++ok; }
|
||||
void writeErrFrame(uint8_t value) { ++errors; error=value; }
|
||||
bool sendClientRawData(const uint8_t* data,size_t n,uint8_t* path,uint8_t encoded) {
|
||||
++sends;
|
||||
const size_t bytes=(encoded & 63)*((encoded >> 6)+1);
|
||||
assert(frame_length>=2+bytes+4);
|
||||
assert(data==frame+2+bytes && n==frame_length-2-bytes);
|
||||
assert(!memcmp(path,frame+2,bytes));
|
||||
return send_ok;
|
||||
}
|
||||
void onFrame(uint8_t* cmd_frame,size_t len) {
|
||||
@RAW_CLAUSE@
|
||||
else writeErrFrame(ERR_CODE_UNSUPPORTED_CMD);
|
||||
}
|
||||
};
|
||||
|
||||
int main() {
|
||||
// Every buffer is allocated to its exact advertised frame length. Reading
|
||||
// even one byte past the received frame is therefore an ASan failure.
|
||||
for (size_t length=6;length<=80;++length) for (unsigned encoded=0;encoded<256;++encoded) {
|
||||
auto frame=std::unique_ptr<uint8_t[]>(new uint8_t[length]);
|
||||
for (size_t i=0;i<length;++i) frame[i]=static_cast<uint8_t>(i*29+encoded);
|
||||
frame[0]=CMD_SEND_RAW_DATA;
|
||||
frame[1]=static_cast<uint8_t>(encoded);
|
||||
const unsigned width=(encoded >> 6)+1;
|
||||
const size_t bytes=(encoded & 63)*width;
|
||||
const bool valid=width!=4 && bytes<=MAX_PATH_SIZE;
|
||||
const bool fits=length>=2+bytes+4;
|
||||
for (const bool result : {false,true}) {
|
||||
MyMesh node;
|
||||
node.send_ok=result; node.frame=frame.get(); node.frame_length=length;
|
||||
node.onFrame(frame.get(),length);
|
||||
if (!valid) {
|
||||
assert(node.errors==1 && node.error==ERR_CODE_UNSUPPORTED_CMD && !node.sends && !node.ok);
|
||||
} else if (!fits) {
|
||||
assert(node.errors==1 && node.error==ERR_CODE_ILLEGAL_ARG && !node.sends && !node.ok);
|
||||
} else {
|
||||
assert(node.sends==1);
|
||||
if (result) assert(node.ok==1 && !node.errors);
|
||||
else assert(!node.ok && node.errors==1 && node.error==ERR_CODE_BAD_STATE);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
'''
|
||||
|
||||
|
||||
class CompanionTrafficRoutingTest(unittest.TestCase):
|
||||
def compile_and_run(self, source):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
work = Path(directory)
|
||||
cpp = work / 'test.cpp'
|
||||
cpp.write_text(source)
|
||||
build = subprocess.run([
|
||||
'g++', '-std=c++17', '-Wall', '-Wextra', '-Werror',
|
||||
'-include', 'cstdio', '-fsanitize=address,undefined',
|
||||
'-fno-pie', '-no-pie', '-I', str(ROOT / 'src'),
|
||||
str(cpp), '-o', str(work / 'test'),
|
||||
], capture_output=True, text=True)
|
||||
self.assertEqual(build.returncode, 0, build.stdout + build.stderr)
|
||||
run = subprocess.run([str(work / 'test')], capture_output=True, text=True)
|
||||
self.assertEqual(run.returncode, 0, run.stdout + run.stderr)
|
||||
|
||||
def test_classification_parser_and_profile_permissions(self):
|
||||
self.compile_and_run(HEADER_HARNESS)
|
||||
|
||||
def test_real_cli_and_client_sends(self):
|
||||
source = (ROOT / 'examples/companion_radio/MyMesh.cpp').read_text()
|
||||
methods = '\n'.join(method(source, signature) for signature in (
|
||||
'bool MyMesh::handleTrafficRoutingCommand(',
|
||||
'bool MyMesh::sendClientGroupData(',
|
||||
'bool MyMesh::sendClientRawData(',
|
||||
))
|
||||
self.compile_and_run(METHOD_HARNESS.replace('@METHODS@', methods))
|
||||
|
||||
def test_binary_and_local_control_paths_use_routing(self):
|
||||
source = (ROOT / 'examples/companion_radio/MyMesh.cpp').read_text()
|
||||
local = method(source, 'bool MyMesh::handleLocalControlCommand(')
|
||||
self.assertIn('handleTrafficRoutingCommand(command, reply, reply_size)', local)
|
||||
raw_start = source.index('cmd_frame[0] == CMD_SEND_RAW_DATA')
|
||||
raw_end = source.index('} else if (cmd_frame[0] == CMD_SEND_LOGIN', raw_start)
|
||||
self.assertIn('sendClientRawData(', source[raw_start:raw_end])
|
||||
self.assertNotIn('createRawData(', source[raw_start:raw_end])
|
||||
group_start = source.index('cmd_frame[0] == CMD_SEND_CHANNEL_DATA')
|
||||
group_end = source.index('} else if (cmd_frame[0] == CMD_GET_CONTACTS', group_start)
|
||||
self.assertIn('sendClientGroupData(', source[group_start:group_end])
|
||||
|
||||
def test_real_raw_frame_path_bounds_and_failed_send_response(self):
|
||||
source = (ROOT / 'examples/companion_radio/MyMesh.cpp').read_text()
|
||||
packet = (ROOT / 'src/Packet.cpp').read_text()
|
||||
clause = method(source, '} else if (cmd_frame[0] == CMD_SEND_RAW_DATA')
|
||||
# The extracted clause is still production code: strip only the
|
||||
# previous command's closing brace and its `else` connective.
|
||||
clause = clause.removeprefix('} else ')
|
||||
names = ('CMD_SEND_RAW_DATA', 'ERR_CODE_UNSUPPORTED_CMD',
|
||||
'ERR_CODE_ILLEGAL_ARG', 'ERR_CODE_BAD_STATE')
|
||||
constants = '\n'.join(re.search(
|
||||
r'^#define\s+' + name + r'\s+\d+.*$', source, re.MULTILINE).group(0)
|
||||
for name in names)
|
||||
packet_methods = '\n'.join(method(packet, signature) for signature in (
|
||||
'bool Packet::isValidPathLen(', 'size_t Packet::writePath(',
|
||||
))
|
||||
self.compile_and_run(RAW_FRAME_HARNESS.replace('@CONSTANTS@', constants)
|
||||
.replace('@PACKET_METHODS@', packet_methods)
|
||||
.replace('@RAW_CLAUSE@', clause))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -55,17 +55,17 @@ int main(){
|
||||
assert(node.savePrefs());
|
||||
const auto original=node.store.fs.files["/new_prefs"];
|
||||
#if defined(TBEAM_1W)
|
||||
assert(original.size()==243);
|
||||
assert(original.size()==251);
|
||||
#elif defined(RP2040_PLATFORM) && defined(ENABLE_WIFI_INTERFACE)
|
||||
assert(original.size()==333);
|
||||
assert(original.size()==341);
|
||||
#else
|
||||
assert(original.size()==236);
|
||||
assert(original.size()==244);
|
||||
#endif
|
||||
const size_t debug_offset=original.size()-2;
|
||||
const size_t debug_offset=original.size()-mesh::companion::traffic::FooterSize-2;
|
||||
assert(original[debug_offset]==0&&original[debug_offset-3]==0);
|
||||
assert(original[debug_offset-2]==1&&original[debug_offset-1]==1);
|
||||
assert(original[debug_offset-4]==1&&original[158]==1);
|
||||
assert(original.back()==0);
|
||||
assert(original[debug_offset+1]==0);
|
||||
char reply[160]={};
|
||||
for(const char* malformed : {"set usb.debug","set usb.debug ",
|
||||
"set usb.debug 1","set usb.debug ON","set usb.debug on ",
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
"""Run the actual bounded Ethernet KISS codec and TCP service with fake sockets."""
|
||||
from pathlib import Path
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
FIXTURE = ROOT / "test" / "fixtures" / "ethernet_kiss"
|
||||
|
||||
|
||||
class EthernetKissTests(unittest.TestCase):
|
||||
def test_kiss_port_does_not_collide_with_companion_services(self):
|
||||
companion = (ROOT / "examples/companion_radio/main.cpp").read_text(encoding="utf-8")
|
||||
server = (ROOT / "src/helpers/esp32/EthernetKissServer.h").read_text(encoding="utf-8")
|
||||
terminal = re.search(r"#define\s+OTA_CONSOLE_TCP_PORT\s+(\d+)", companion)
|
||||
kiss = re.search(r"static constexpr uint16_t Port\s*=\s*(\d+)", server)
|
||||
self.assertIsNotNone(terminal)
|
||||
self.assertIsNotNone(kiss)
|
||||
self.assertEqual(int(terminal.group(1)), 5002)
|
||||
self.assertEqual(int(kiss.group(1)), 5003)
|
||||
self.assertNotIn(int(kiss.group(1)), {5000, 5001, int(terminal.group(1))})
|
||||
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.directory = tempfile.TemporaryDirectory()
|
||||
cls.executable = Path(cls.directory.name) / "ethernet-kiss"
|
||||
command = [
|
||||
"g++", "-std=c++17", "-Wall", "-Wextra", "-Werror", "-g",
|
||||
"-fsanitize=address,undefined", "-fno-omit-frame-pointer", "-no-pie",
|
||||
"-I", str(FIXTURE), "-I", str(ROOT / "src"),
|
||||
str(FIXTURE / "test_ethernet_kiss.cpp"), "-o", str(cls.executable),
|
||||
]
|
||||
result = subprocess.run(command, capture_output=True, text=True)
|
||||
if result.returncode:
|
||||
cls.directory.cleanup()
|
||||
raise AssertionError(result.stdout + result.stderr)
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls):
|
||||
cls.directory.cleanup()
|
||||
|
||||
def run_case(self, name):
|
||||
environment = dict(os.environ, ASAN_OPTIONS="detect_leaks=1:halt_on_error=1")
|
||||
result = subprocess.run([str(self.executable), name], env=environment,
|
||||
capture_output=True, text=True, timeout=30)
|
||||
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
|
||||
|
||||
def test_every_ethernet_length_and_tcp_split(self):
|
||||
self.run_case("codec-roundtrip")
|
||||
|
||||
def test_malformed_escapes_ports_short_and_oversized_frames(self):
|
||||
self.run_case("codec-malformed")
|
||||
|
||||
def test_queue_backpressure_and_partial_output(self):
|
||||
self.run_case("codec-backpressure")
|
||||
|
||||
def test_reset_and_bounded_random_input(self):
|
||||
self.run_case("codec-reset-fuzz")
|
||||
|
||||
def test_station_only_binding_single_client_and_disable(self):
|
||||
self.run_case("server-station")
|
||||
|
||||
def test_per_poll_budgets_and_tcp_backpressure(self):
|
||||
self.run_case("server-budget-backpressure")
|
||||
|
||||
def test_nonblocking_writes_resume_without_duplicate_bytes(self):
|
||||
self.run_case("server-partial-writes")
|
||||
|
||||
def test_disconnect_reconnect_address_change_discards_stale_work(self):
|
||||
self.run_case("server-session-reset")
|
||||
|
||||
def test_listener_retry_eof_and_socket_errors(self):
|
||||
self.run_case("server-failures")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,334 @@
|
||||
"""Exercise the actual foreign-radio isolation and Ethernet ownership layer.
|
||||
|
||||
These host tests prove routing/state contracts, not RF delivery or TCP speed.
|
||||
"""
|
||||
from pathlib import Path
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
from test_meshtext_transport import HARNESS as TRANSPORT_HARNESS
|
||||
from test_radio_profile_scan import HARNESS as SCAN_HARNESS
|
||||
from test_radio_receive_contract import method
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
class EthernetRadioTest(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.compiler = os.environ.get("CXX") or shutil.which("g++") or shutil.which("clang++")
|
||||
if not cls.compiler:
|
||||
raise unittest.SkipTest("a host C++17 compiler is required")
|
||||
|
||||
def compile_run(self, code, flags=(), sources=(), includes=(), arduino_stub=False):
|
||||
with tempfile.TemporaryDirectory(prefix="meshcore-ethernet-radio-") as folder:
|
||||
cpp, binary = Path(folder) / "test.cpp", Path(folder) / "test"
|
||||
cpp.write_text(code, encoding="utf-8")
|
||||
command = [self.compiler, "-std=c++17", "-Wall", "-Wextra", *flags]
|
||||
if arduino_stub:
|
||||
(Path(folder) / "Arduino.h").write_text("#pragma once\n#include <cstdint>\n#include <cmath>\n")
|
||||
command += ["-I", folder]
|
||||
if os.name != "nt":
|
||||
command += ["-fsanitize=address,undefined", "-fno-omit-frame-pointer", "-fno-pie", "-no-pie"]
|
||||
for include in includes:
|
||||
command += ["-I", str(ROOT / include)]
|
||||
command += ["-I", str(ROOT), "-I", str(ROOT / "test/mocks"), "-I", str(ROOT / "src")]
|
||||
command += [str(ROOT / source) for source in sources] + [str(cpp), "-o", str(binary)]
|
||||
result = subprocess.run(command, capture_output=True, text=True, timeout=60)
|
||||
self.assertEqual(result.returncode, 0, (result.stdout + result.stderr)[-16000:])
|
||||
env = os.environ.copy()
|
||||
env["ASAN_OPTIONS"] = env.get("ASAN_OPTIONS", "") + ":detect_leaks=0"
|
||||
result = subprocess.run([str(binary)], capture_output=True, text=True, timeout=20, env=env)
|
||||
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
|
||||
|
||||
def test_feature_matrix_and_late_chip_discovery(self):
|
||||
code = r'''
|
||||
#include <helpers/MeshtextConfig.h>
|
||||
#if !defined(USE_SX1262)
|
||||
#define USE_SX1262 1
|
||||
#endif
|
||||
static_assert(MESH_ENABLE_ETHERNET_TUNNEL == EXPECT_ETH, "Ethernet feature scope");
|
||||
static_assert(bool(MESH_ENABLE_FOREIGN_RADIO) == bool(EXPECT_ETH || MESH_ENABLE_MESHTEXT_CHAT), "shared queue");
|
||||
int main() {}
|
||||
'''
|
||||
cases = [
|
||||
([], 0),
|
||||
(["ESP32_PLATFORM", "COMPANION_RADIO_FULL", "WIFI_SSID=\"\""], 1),
|
||||
(["ESP32_PLATFORM", "COMPANION_RADIO_FULL"], 0),
|
||||
(["ESP32_PLATFORM", "WIFI_SSID=\"\""], 0),
|
||||
(["NRF52_PLATFORM", "RAK_4631", "COMPANION_RADIO_FULL", "WIFI_SSID=\"\""], 0),
|
||||
(["ESP32_PLATFORM", "COMPANION_RADIO_FULL", "WIFI_SSID=\"\"", "MESH_PRIMARY_ESPNOW=1"], 0),
|
||||
(["ESP32_PLATFORM", "COMPANION_RADIO_FULL", "WIFI_SSID=\"\"", "MESH_PRIMARY_ESPNOW=0"], 1),
|
||||
(["ESP32_PLATFORM", "COMPANION_RADIO_FULL", "WIFI_SSID=\"\"", "MESH_ENABLE_ETHERNET_TUNNEL=0"], 0),
|
||||
]
|
||||
for defines, expected in cases:
|
||||
with self.subTest(defines=defines):
|
||||
self.compile_run(code, [*("-D" + item for item in defines), "-DEXPECT_ETH=" + str(expected)])
|
||||
|
||||
def test_dispatcher_ethernet_only_and_shared_queue(self):
|
||||
code = TRANSPORT_HARNESS.split("int main() {", 1)[0]
|
||||
code = code.replace("bool incoming=false;", "bool incoming=false, ethernet_supported=true;")
|
||||
code = code.replace("uint8_t active=0;", "uint8_t active=0; uint32_t rx_generation=0;")
|
||||
code = code.replace("uint8_t receiveProfile() const override { return active; }",
|
||||
"uint8_t receiveProfile() const override { return active; }\n"
|
||||
" uint32_t receiveProfileGeneration() const override { return rx_generation ? rx_generation : p.generation[active]; }")
|
||||
code = code.replace("bool supportsMeshtext() const override { return supported; }",
|
||||
"bool supportsMeshtext() const override { return supported; }\n"
|
||||
" bool supportsEthernetTunnel() const override { return ethernet_supported; }")
|
||||
code = code.replace("std::vector<bool> done;",
|
||||
"std::vector<bool> done; std::vector<RadioProfileProtocol> done_protocols;")
|
||||
code = code.replace("done.push_back(ok);",
|
||||
"done.push_back(ok); done_protocols.push_back(queuedForeignRadioProtocol());")
|
||||
code = code.replace("using Dispatcher::hasForeignRadioFrame;",
|
||||
"using Dispatcher::hasForeignRadioFrame;\n using Dispatcher::discardQueuedForeignRadioFrame;")
|
||||
code += r'''
|
||||
static void ethernet(Fixture& f) {
|
||||
f.radio.p.secondary.params.protocol=RadioProfileProtocol::Ethernet;
|
||||
f.radio.p.secondary.params.preamble=32;
|
||||
}
|
||||
static bool enqueue(Fixture& f) {
|
||||
return f.d.queueForeignRadioFrame(bytes,sizeof(bytes),1,f.radio.p.generation[1],RadioProfileProtocol::Ethernet);
|
||||
}
|
||||
int main() {
|
||||
using P=RadioProfileProtocol;
|
||||
{ Fixture f;ethernet(f);assert(enqueue(f));f.tick();
|
||||
assert(f.radio.sends==1 && f.radio.active==1 && f.radio.sent==std::vector<uint8_t>(bytes,bytes+3));
|
||||
f.radio.complete=true;f.tick();assert(f.d.done.size()==1 && f.d.done[0]);
|
||||
assert(f.d.done_protocols[0]==P::Ethernet && f.radio.p.tx_packets[1]==1);
|
||||
assert(!f.d.getNumSentFlood() && !f.d.getNumSentDirect());
|
||||
}
|
||||
{ Fixture f;ethernet(f);assert(enqueue(f));
|
||||
f.radio.p.secondary.params.protocol=P::Meshtext; // even a bad external owner not bumping generation
|
||||
f.tick();assert(!f.radio.sends && f.d.done.size()==1 && !f.d.done[0]);
|
||||
assert(f.d.done_protocols[0]==P::Ethernet);
|
||||
}
|
||||
{ Fixture f;ethernet(f);assert(enqueue(f));++f.radio.p.generation[1];f.tick();
|
||||
assert(!f.radio.sends && !f.d.done[0]);
|
||||
}
|
||||
{ Fixture f;ethernet(f);f.radio.active=1;f.radio.incoming=true;f.tick();
|
||||
assert(f.d.foreign_rx==1 && !f.d.mc_rx && !f.d.raw_logs && !f.d.getLastMeshCoreRecvMillis());
|
||||
f.radio.ethernet_supported=false;f.radio.incoming=true;f.tick();
|
||||
assert(f.d.foreign_rx==1 && !f.d.mc_rx && !f.d.raw_logs);
|
||||
f.radio.p.secondary.params.protocol=P(99);f.radio.incoming=true;f.tick();
|
||||
assert(f.d.foreign_rx==1 && !f.d.mc_rx && !f.d.raw_logs && f.radio.processed==3);
|
||||
}
|
||||
{ Fixture f;ethernet(f);f.radio.active=1;
|
||||
f.radio.rx_generation=f.radio.p.generation[1];
|
||||
f.radio.p.secondary.params.protocol=P::MeshCore;++f.radio.p.generation[1];
|
||||
f.radio.incoming=true;f.tick();
|
||||
assert(!f.d.foreign_rx && !f.d.mc_rx && !f.d.raw_logs && f.radio.processed==1);
|
||||
}
|
||||
{ Fixture f;ethernet(f);f.radio.ethernet_supported=false;assert(!enqueue(f));
|
||||
f.radio.ethernet_supported=true;f.radio.p.secondary.mode=RadioProfileMode::Rx;assert(!enqueue(f));
|
||||
f.radio.p.secondary.mode=RadioProfileMode::RxTx;
|
||||
assert(!f.d.queueForeignRadioFrame(bytes,3,0,f.radio.p.generation[0],P::Ethernet));
|
||||
assert(!f.d.queueForeignRadioFrame(bytes,3,1,f.radio.p.generation[1],P::MeshCore));
|
||||
assert(!f.d.queueForeignRadioFrame(bytes,3,1,f.radio.p.generation[1],P(99)));
|
||||
}
|
||||
{ Fixture f;ethernet(f);assert(enqueue(f));
|
||||
assert(!f.d.discardQueuedForeignRadioFrame(P::Meshtext));
|
||||
assert(f.d.discardQueuedForeignRadioFrame(P::Ethernet));
|
||||
assert(!f.d.hasForeignRadioFrame() && f.d.done.size()==1 && !f.d.done[0]);
|
||||
f.tick();assert(!f.radio.sends);
|
||||
assert(enqueue(f));f.tick();assert(!f.d.discardQueuedForeignRadioFrame(P::Ethernet));
|
||||
f.radio.complete=true;f.tick();assert(f.d.done.size()==2 && f.d.done[1]);
|
||||
}
|
||||
{ Fixture f;ethernet(f);assert(enqueue(f));f.tick();f.tick(1151);
|
||||
assert(f.radio.sends==1 && f.radio.recovery==1 && !f.d.done[0]);
|
||||
f.tick(5000);assert(f.radio.sends==1);
|
||||
}
|
||||
{ Fixture f;ethernet(f);auto* pkt=newPacket(f.d);f.radio.p.cross=RadioCrossMode::On;
|
||||
assert(!f.radio.p.canCross() && f.d.getTransmitProfileMask(pkt)==1);
|
||||
assert(f.d.sendPacket(pkt,0));f.tick();assert(f.radio.active==0);
|
||||
auto* denied=newPacket(f.d,RADIO_TX_SECONDARY);assert(!f.d.sendPacket(denied,0));
|
||||
}
|
||||
{ Fixture f;ethernet(f);assert(enqueue(f));assert(!f.d.queue(bytes));
|
||||
f.d.setRadioAvailable(false);assert(!f.d.hasForeignRadioFrame() && !f.d.done[0]);
|
||||
assert(!enqueue(f));
|
||||
}
|
||||
{ Fixture f;f.radio.active=1;f.radio.incoming=true;f.tick();
|
||||
#if MESH_ENABLE_MESHTEXT_CHAT
|
||||
assert(f.d.foreign_rx==1);assert(f.d.queue(bytes));
|
||||
#else
|
||||
assert(!f.d.foreign_rx);assert(!f.d.queue(bytes));
|
||||
#endif
|
||||
assert(!f.d.mc_rx && !f.d.raw_logs);
|
||||
}
|
||||
}
|
||||
'''
|
||||
for chat in (0, 1):
|
||||
with self.subTest(chat=chat):
|
||||
self.compile_run(code, ["-DMESH_ENABLE_ETHERNET_TUNNEL=1", f"-DMESH_ENABLE_MESHTEXT_CHAT={chat}"],
|
||||
["src/Dispatcher.cpp", "src/Packet.cpp", "src/helpers/StaticPoolPacketManager.cpp"])
|
||||
|
||||
def test_ethernet_auto_and_manual_ownership_without_chat(self):
|
||||
code = r'''
|
||||
#define main existing_cli_main
|
||||
#include "test/fixtures/radio_profiles/cli_test.cpp"
|
||||
#undef main
|
||||
int main() {
|
||||
using P=mesh::RadioProfileProtocol;
|
||||
Fixture f;
|
||||
mesh::RadioProfileConfig config;
|
||||
config.params=f.radio.p.primary;config.params.freq=910.5f;config.params.preamble=32;
|
||||
config.params.protocol=P::Ethernet;config.mode=mesh::RadioProfileMode::RxTx;
|
||||
assert(f.cli.canAutoSecondary() && f.cli.requestAutoSecondary(config));
|
||||
assert(f.cli.autoSecondaryActive() && f.radio.p.secondary.params.protocol==P::Ethernet);
|
||||
assert(f.radio.profilePreamble(1)==32 && f.fs.files.empty());
|
||||
const auto generation=f.radio.p.generation[1];
|
||||
assert(f.cli.requestAutoSecondary(config));assert(f.radio.p.generation[1]==generation);
|
||||
auto conflict=config;conflict.params.protocol=P::Meshtext;
|
||||
assert(!f.cli.requestAutoSecondary(conflict));
|
||||
f.cli.clearAutoSecondary();assert(!f.radio.p.enabled());
|
||||
f.cmd("set radio2 910.5,500,8,5,rxtx,80");f.advance(2000);
|
||||
const auto saved=f.fs.files["/radio_profiles"];
|
||||
assert(f.cli.useSecondaryProtocol(P::Ethernet));
|
||||
assert(f.radio.p.secondary.params.protocol==P::Ethernet && f.radio.profilePreamble(1)==80);
|
||||
assert(f.fs.files["/radio_profiles"]==saved);
|
||||
assert(!f.cli.useSecondaryProtocol(P::Meshtext));
|
||||
assert(f.radio.p.secondary.params.protocol==P::Ethernet);
|
||||
f.cli.clearSecondaryProtocol();assert(f.radio.p.secondary.params.protocol==P::MeshCore);
|
||||
assert(f.radio.profilePreamble(1)==80 && f.fs.files["/radio_profiles"]==saved);
|
||||
assert(f.cli.useSecondaryProtocol(P::Ethernet));
|
||||
f.cmd("set tempradio2 911.5,500,8,5,rxtx,1,80");f.advance(2000);
|
||||
f.cli.clearSecondaryProtocol();
|
||||
assert(f.radio.p.secondary.params.protocol==P::MeshCore && f.radio.p.secondary.params.freq==911.5f);
|
||||
assert(!f.cli.useSecondaryProtocol(P::Ethernet));
|
||||
Fixture veto;veto.cmd("set radio2 off");veto.advance(2000);
|
||||
assert(!veto.cli.canAutoSecondary() && !veto.cli.requestAutoSecondary(config));
|
||||
}
|
||||
'''
|
||||
for chat in (0, 1):
|
||||
with self.subTest(chat=chat):
|
||||
self.compile_run(code, ["-DMESH_ENABLE_ETHERNET_TUNNEL=1", f"-DMESH_ENABLE_MESHTEXT_CHAT={chat}"],
|
||||
["src/helpers/RadioProfileCLI.cpp"], ["test/fixtures/radio_profiles/mocks"])
|
||||
|
||||
def test_actual_sx1262_and_sx1276_syncword_selection(self):
|
||||
for chip in ("SX1262", "SX1276"):
|
||||
source = (ROOT / f"src/helpers/radiolib/Custom{chip}Wrapper.h").read_text()
|
||||
protocol = method(source, "bool applyProtocol(").replace(" override", "")
|
||||
code = r'''
|
||||
#include <helpers/MeshtextConfig.h>
|
||||
#include <RadioProfiles.h>
|
||||
#include <cassert>
|
||||
#define RADIOLIB_ERR_NONE 0
|
||||
struct Custom@CHIP@ {
|
||||
unsigned writes=0;uint8_t sync=0;
|
||||
int result=0;
|
||||
int setProfileProtocol(uint8_t value) { ++writes;sync=value;return result; }
|
||||
};
|
||||
struct Driver {
|
||||
Custom@CHIP@ chip;Custom@CHIP@* _radio=&chip;
|
||||
bool supportsMeshtext() const { return MESH_ENABLE_MESHTEXT_WIRE; }
|
||||
bool supportsEthernetTunnel() const { return MESH_ENABLE_ETHERNET_TUNNEL; }
|
||||
@METHOD@
|
||||
};
|
||||
int main() {
|
||||
using P=mesh::RadioProfileProtocol;Driver d;
|
||||
assert(d.applyProtocol(P::MeshCore) && d.chip.sync==0x12);
|
||||
#if MESH_ENABLE_ETHERNET_TUNNEL
|
||||
assert(d.applyProtocol(P::Ethernet) && d.chip.sync==0x16);
|
||||
assert(d.applyProtocol(P::MeshCore) && d.chip.sync==0x12);
|
||||
#else
|
||||
const auto before_eth=d.chip.writes;assert(!d.applyProtocol(P::Ethernet));assert(d.chip.writes==before_eth);
|
||||
#endif
|
||||
#if MESH_ENABLE_MESHTEXT_WIRE
|
||||
assert(d.applyProtocol(P::Meshtext) && d.chip.sync==0x2b);
|
||||
#else
|
||||
const auto before_mt=d.chip.writes;assert(!d.applyProtocol(P::Meshtext));assert(d.chip.writes==before_mt);
|
||||
#endif
|
||||
const auto before=d.chip.writes;assert(!d.applyProtocol(P(99)));assert(d.chip.writes==before);
|
||||
d.chip.result=-1;assert(!d.applyProtocol(P::MeshCore));
|
||||
}
|
||||
'''.replace("@CHIP@", chip).replace("@METHOD@", protocol)
|
||||
for wire, ethernet in ((0, 1), (1, 1), (1, 0)):
|
||||
with self.subTest(chip=chip, wire=wire, ethernet=ethernet):
|
||||
self.compile_run(code, [f"-DMESH_ENABLE_MESHTEXT_WIRE={wire}",
|
||||
f"-DMESH_ENABLE_ETHERNET_TUNNEL={ethernet}"])
|
||||
|
||||
def test_driver_validator_rejects_disabled_or_unsupported_ethernet(self):
|
||||
source = (ROOT / "src/helpers/radiolib/RadioLibWrappers.cpp").read_text()
|
||||
validator = method(source, "bool RadioLibWrapper::validateProfile(")
|
||||
code = r'''
|
||||
#include <helpers/MeshtextConfig.h>
|
||||
#include <RadioProfiles.h>
|
||||
#include <cassert>
|
||||
struct RadioLibWrapper {
|
||||
bool ethernet=true;
|
||||
bool supportsMeshtext() const { return true; }
|
||||
bool supportsEthernetTunnel() const { return ethernet; }
|
||||
bool validateProfile(const mesh::RadioProfileParams&) const;
|
||||
};
|
||||
@VALIDATOR@
|
||||
int main() {
|
||||
RadioLibWrapper driver;mesh::RadioProfileParams p;
|
||||
p.freq=909.5;p.bw=500;p.sf=8;p.cr=5;p.preamble=32;
|
||||
p.protocol=mesh::RadioProfileProtocol::Ethernet;
|
||||
assert(driver.validateProfile(p)==bool(MESH_ENABLE_ETHERNET_TUNNEL));
|
||||
driver.ethernet=false;assert(!driver.validateProfile(p));
|
||||
p.protocol=mesh::RadioProfileProtocol::MeshCore;assert(driver.validateProfile(p));
|
||||
p.protocol=mesh::RadioProfileProtocol(99);assert(!driver.validateProfile(p));
|
||||
}
|
||||
'''.replace("@VALIDATOR@", validator)
|
||||
for enabled in (0, 1):
|
||||
self.compile_run(code, [f"-DMESH_ENABLE_ETHERNET_TUNNEL={enabled}", "-DMESH_RADIO_PROFILE_CHIP=1262"])
|
||||
|
||||
def test_ethernet_only_physical_retune_and_failed_protocol_rollback(self):
|
||||
source = (ROOT / "src/helpers/radiolib/RadioLibWrappers.cpp").read_text()
|
||||
names = [("uint8_t", "beginReconfigure"), ("void", "endReconfigure"),
|
||||
("void", "serviceProfileScan")] + [("mesh::RadioParamApplyResult", name) for name in
|
||||
("tuneProfile", "prepareTransmitProfile", "tryRestoreCodingRate", "trySetParams", "trySetPrimaryParams")]
|
||||
methods = "\n".join(method(source, f"{kind} RadioLibWrapper::{name}(") for kind, name in names)
|
||||
methods += "\n" + method(source, "mesh::RadioParamApplyResult RadioLibWrapper::prepareTransmitProfile(uint8_t profile, bool")
|
||||
wrapper = (ROOT / "src/helpers/radiolib/CustomSX1262Wrapper.h").read_text()
|
||||
methods += "\n" + method(wrapper, "void setProfileStandbyWarm(").replace(
|
||||
"void setProfileStandbyWarm(bool enabled) override",
|
||||
"void RadioLibWrapper::setProfileStandbyWarm(bool enabled)")
|
||||
harness = "#include <helpers/EthernetTunnelConfig.h>\n" + SCAN_HARNESS.split("@METHODS@")[0]
|
||||
harness = harness.replace("uint16_t _physical_preamble=32;", r'''
|
||||
uint16_t _physical_preamble=32;
|
||||
mesh::RadioProfileProtocol _physical_protocol=mesh::RadioProfileProtocol::MeshCore;
|
||||
mesh::RadioProfileProtocol applied_protocol=mesh::RadioProfileProtocol::MeshCore;
|
||||
bool fail_protocol=false;unsigned protocol_writes=0;
|
||||
bool applyProtocol(mesh::RadioProfileProtocol protocol) {
|
||||
++protocol_writes;
|
||||
if (fail_protocol && protocol==mesh::RadioProfileProtocol::Ethernet) return false;
|
||||
applied_protocol=protocol;return true;
|
||||
}
|
||||
''')
|
||||
harness += methods + r'''
|
||||
int main() {
|
||||
using P=mesh::RadioProfileProtocol;using R=mesh::RadioParamApplyResult;
|
||||
{ RadioLibWrapper driver;mesh::RadioProfileConfig config;
|
||||
config.params=driver._profiles.primary;config.params.protocol=P::Ethernet;
|
||||
config.params.preamble=80;config.mode=mesh::RadioProfileMode::RxTx;
|
||||
driver._profiles.setSecondary(config,false);
|
||||
assert(driver.tuneProfile(1)==R::APPLIED);
|
||||
assert(driver._physical_protocol==P::Ethernet && driver.applied_protocol==P::Ethernet);
|
||||
assert(driver._physical_preamble==80 && driver.protocol_writes==1);
|
||||
assert(driver.tuneProfile(0)==R::APPLIED);
|
||||
assert(driver._physical_protocol==P::MeshCore && driver.applied_protocol==P::MeshCore);
|
||||
assert(driver.protocol_writes==2);
|
||||
}
|
||||
{ RadioLibWrapper driver;mesh::RadioProfileConfig config;
|
||||
config.params=driver._profiles.primary;config.params.protocol=P::Ethernet;
|
||||
config.params.preamble=32;config.mode=mesh::RadioProfileMode::RxTx;
|
||||
driver._profiles.setSecondary(config,false);driver.fail_protocol=true;
|
||||
assert(driver.tuneProfile(1)==R::FAILED);
|
||||
assert(driver._physical_protocol==P::MeshCore && driver.applied_protocol==P::MeshCore);
|
||||
assert(driver._active_profile==0 && driver._profile_generation==1);
|
||||
assert(driver.protocol_writes==2);
|
||||
}
|
||||
}
|
||||
'''
|
||||
for flags in (("-DMESH_ENABLE_ETHERNET_TUNNEL=1",),
|
||||
("-DMESH_ENABLE_ETHERNET_TUNNEL=0", "-DMESH_ENABLE_ETHERNET_WIRE=1")):
|
||||
with self.subTest(flags=flags):
|
||||
self.compile_run(harness, [*flags, "-DMESH_ENABLE_MESHTEXT_WIRE=0"], arduino_stub=True)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,193 @@
|
||||
"""Execute actual TX entry points with the opt-in lab RF boundary enabled."""
|
||||
from pathlib import Path
|
||||
import os
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
import test_beacon_radio
|
||||
from test_beacon_radio import method
|
||||
from test_carrier_wave import production_harness
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
SOURCE = ROOT / "src/helpers/radiolib/RadioLibWrappers.cpp"
|
||||
|
||||
|
||||
class HilTxFrequencyGuardTest(unittest.TestCase):
|
||||
def compile_run(self, code, defines=(), guard=True):
|
||||
with tempfile.TemporaryDirectory(prefix="meshcore-hil-tx-") as directory:
|
||||
cpp, binary = Path(directory) / "test.cpp", Path(directory) / "test"
|
||||
cpp.write_text(code)
|
||||
command = [os.environ.get("CXX", "g++"), "-std=c++17", "-Wall", "-Wextra",
|
||||
"-I", str(ROOT / "test/mocks"), "-I", str(ROOT / "src"),
|
||||
*(["-DMESH_HIL_TX_FREQ_MHZ=909.5"] if guard else []),
|
||||
*defines, str(cpp), "-o", str(binary)]
|
||||
built = subprocess.run(command, capture_output=True, text=True)
|
||||
self.assertEqual(built.returncode, 0, built.stdout + built.stderr)
|
||||
ran = subprocess.run([str(binary)], capture_output=True, text=True)
|
||||
self.assertEqual(ran.returncode, 0, ran.stdout + ran.stderr)
|
||||
|
||||
def test_packet_and_beacon_actual_entry_points(self):
|
||||
code = test_beacon_radio.BeaconRadioTest().source().split("int main() {", 1)[0]
|
||||
code = code.replace("#include <cassert>", "#include <cassert>\n#include <limits>\n"
|
||||
"#include <helpers/radiolib/HilTxFrequencyGuard.h>")
|
||||
code = code.replace("int startTransmit(uint8_t*, int) { return tx_result; }",
|
||||
"unsigned starts=0; int startTransmit(uint8_t*, int) { ++starts; return tx_result; }")
|
||||
code = code.replace("bool _beacon_owned = false, _beacon_restoring = false;",
|
||||
"bool _beacon_owned = false, _beacon_restoring = false;\n"
|
||||
"float _hil_beacon_tx_frequency_mhz=0; bool hilPacketTransmitAllowed() const;")
|
||||
code += method(SOURCE.read_text(), "bool RadioLibWrapper::hilPacketTransmitAllowed() const")
|
||||
code += r'''
|
||||
void configure(RadioLibWrapper& w, float f=909.5f) {
|
||||
w._profiles.primary.freq=w._cur_freq=f;
|
||||
w._profiles.primary.bw=w._cur_bw=500;
|
||||
w._profiles.primary.sf=w._cur_sf=5;
|
||||
w._profiles.primary.cr=w._cur_cr=5;
|
||||
w._physical_preamble=w.profilePreamble(0);
|
||||
}
|
||||
void blocked(RadioLibWrapper& w) {
|
||||
uint8_t bytes[14]={};
|
||||
assert(!w.startSendRaw(bytes,sizeof(bytes)));
|
||||
assert(w.board.before==0 && w.modem.starts==0);
|
||||
}
|
||||
int main() {
|
||||
uint8_t bytes[14]={};
|
||||
{ RadioLibWrapper w; configure(w,910.525f); blocked(w); }
|
||||
{ RadioLibWrapper w; configure(w); assert(w.startSendRaw(bytes,14));
|
||||
assert(w.board.before==1 && w.modem.starts==1); }
|
||||
{ RadioLibWrapper w; configure(w); w._params_valid=false; blocked(w); }
|
||||
{ RadioLibWrapper w; configure(w); w._profile_refresh_required=true; blocked(w); }
|
||||
{ RadioLibWrapper w; configure(w); ++w._profiles.generation[0]; blocked(w); }
|
||||
{ RadioLibWrapper w; configure(w); w._active_profile=2; blocked(w); }
|
||||
{ RadioLibWrapper w; configure(w); w._active_profile=1; blocked(w); }
|
||||
{ RadioLibWrapper w; configure(w); w._cur_freq=910.525f; blocked(w); }
|
||||
{ RadioLibWrapper w; configure(w); w._profiles.primary.freq=910.525f; blocked(w); }
|
||||
{ RadioLibWrapper w; configure(w); w._cur_bw=250; blocked(w); }
|
||||
{ RadioLibWrapper w; configure(w); w._cur_sf=6; blocked(w); }
|
||||
{ RadioLibWrapper w; configure(w); w._cur_cr=6; blocked(w); }
|
||||
{ RadioLibWrapper w; configure(w); ++w._physical_preamble; blocked(w); }
|
||||
{ RadioLibWrapper w; configure(w); w._physical_protocol=mesh::RadioProfileProtocol::Ethernet; blocked(w); }
|
||||
{ RadioLibWrapper w; configure(w); w._cur_freq=std::numeric_limits<float>::quiet_NaN(); blocked(w); }
|
||||
{ RadioLibWrapper w; configure(w); auto p=beacon(); p.freq=910.525f;
|
||||
assert(w.prepareBeaconTransmit(p,10)==Result::FAILED);
|
||||
assert(w.applications==0 && !w._beacon_owned); blocked(w); }
|
||||
{ RadioLibWrapper w; configure(w,910.525f); auto p=beacon(); p.freq=909.5f;
|
||||
assert(w.prepareBeaconTransmit(p,10)==Result::APPLIED);
|
||||
assert(w._cur_freq==910.525f && w.modem.freq==909.5f);
|
||||
assert(w.startSendRaw(bytes,14)); assert(w.board.before==1 && w.modem.starts==1);
|
||||
w.onSendFinished(); w.modem.param_fail=true; w.deep_ok=false;
|
||||
assert(w.restoreBeaconReceive()==Result::BUSY);
|
||||
assert(w._hil_beacon_tx_frequency_mhz==0 && !w.hilPacketTransmitAllowed()); }
|
||||
{ RadioLibWrapper w; configure(w); auto p=beacon(); p.freq=909.5f;
|
||||
w.modem.param_fail=true;
|
||||
assert(w.prepareBeaconTransmit(p,10)==Result::FAILED);
|
||||
assert(w._hil_beacon_tx_frequency_mhz==0); blocked(w); }
|
||||
}
|
||||
'''
|
||||
# After rejecting an unsafe beacon, the normal allowed profile can
|
||||
# still transmit. That case only checks the beacon's absence of RF.
|
||||
code = code.replace("assert(w.applications==0 && !w._beacon_owned); blocked(w);",
|
||||
"assert(w.applications==0 && !w._beacon_owned && w.board.before==0 && w.modem.starts==0);")
|
||||
self.compile_run(code)
|
||||
|
||||
def test_transmit_preparation_rejects_unsafe_tuple_before_retune(self):
|
||||
code = r'''
|
||||
#include <cassert>
|
||||
#include <RadioProfiles.h>
|
||||
#include <helpers/radiolib/HilTxFrequencyGuard.h>
|
||||
namespace mesh { enum class RadioParamApplyResult { APPLIED, BUSY, FAILED }; }
|
||||
struct RadioLibWrapper {
|
||||
mesh::RadioProfiles _profiles;
|
||||
unsigned tunes=0;
|
||||
bool isChipBusy() const { return false; }
|
||||
bool isPacketPendingOrReceiving() const { return false; }
|
||||
mesh::RadioParamApplyResult tuneProfile(uint8_t) { ++tunes; return mesh::RadioParamApplyResult::APPLIED; }
|
||||
mesh::RadioParamApplyResult prepareTransmitProfile(uint8_t, bool);
|
||||
};
|
||||
'''
|
||||
code += method(SOURCE.read_text(), "mesh::RadioParamApplyResult RadioLibWrapper::prepareTransmitProfile(uint8_t profile, bool")
|
||||
code += r'''
|
||||
int main() {
|
||||
using Result=mesh::RadioParamApplyResult;
|
||||
RadioLibWrapper w; w._profiles.primary.freq=910.525f;
|
||||
w._profiles.secondary.params.freq=909.5f;
|
||||
w._profiles.secondary.mode=mesh::RadioProfileMode::RxTx;
|
||||
assert(w.prepareTransmitProfile(0,false)==Result::FAILED && w.tunes==0);
|
||||
assert(w.prepareTransmitProfile(255,false)==Result::FAILED && w.tunes==0);
|
||||
assert(w.prepareTransmitProfile(1,false)==Result::APPLIED && w.tunes==1);
|
||||
}
|
||||
'''
|
||||
self.compile_run(code)
|
||||
|
||||
def test_carrier_and_morse_actual_entry_points(self):
|
||||
code = production_harness().split("int main() {", 1)[0]
|
||||
code = code.replace("#include <cassert>", "#include <cassert>\n"
|
||||
"#include <helpers/radiolib/HilTxFrequencyGuard.h>")
|
||||
code = code.replace("float _cur_freq=909.5;", "float _cur_freq=909.5, _cur_bw=500;\n"
|
||||
"uint8_t _cur_sf=5, _cur_cr=5; uint16_t _physical_preamble=128;\n"
|
||||
"uint32_t _profile_generation=1; bool hilPacketTransmitAllowed() const;\n"
|
||||
"uint16_t profilePreamble(uint8_t p) const { return _profiles.preamble(p,32); }")
|
||||
code = code.replace("_profiles.primary.bw=500;", "_profiles.primary.bw=500;\n"
|
||||
"_profiles.primary.sf=_profiles.secondary.params.sf=5;\n"
|
||||
"_profiles.primary.cr=_profiles.secondary.params.cr=5;")
|
||||
code = code.replace("chip.frequency=frequency;", "chip.frequency=frequency;\n"
|
||||
"_cur_bw=_profiles.params(target).bw; _cur_sf=_profiles.params(target).sf;\n"
|
||||
"_cur_cr=_profiles.params(target).cr; _profile_generation=_profiles.generation[target];\n"
|
||||
"_physical_preamble=profilePreamble(target);")
|
||||
code += method(SOURCE.read_text(), "bool RadioLibWrapper::hilPacketTransmitAllowed() const")
|
||||
code += r'''
|
||||
int main() {
|
||||
using Result=mesh::RadioParamApplyResult;
|
||||
{ RadioLibWrapper w; w._profiles.primary.freq=910.525f;
|
||||
assert(w.setCarrierWave(0,100)==Result::FAILED);
|
||||
assert(w.board.before==0 && w.chip.starts==0 && w.tunes==0); }
|
||||
{ RadioLibWrapper w; assert(w.setCarrierWave(0,100)==Result::APPLIED);
|
||||
assert(w.board.before==1 && w.chip.starts==1);
|
||||
++w._profiles.generation[0]; assert(!w.setTxPower(10));
|
||||
assert(w.chip.starts==1); assert(w.serviceCarrierWave()); assert(!w.chip.carrier); }
|
||||
{ RadioLibWrapper w; w._profile_refresh_required=true;
|
||||
assert(w.setCarrierWave(0,100)==Result::FAILED);
|
||||
assert(w.board.before==0 && w.chip.starts==0); }
|
||||
{ RadioLibWrapper w;
|
||||
assert(w.startMorseTx(910.525f,25,"EE")==mesh::MorseTxResult::InvalidFrequency);
|
||||
assert(w.board.before==0 && w.chip.starts==0 && w.board.frequency_prepares==0); }
|
||||
{ RadioLibWrapper w; w._profiles.primary.freq=910.525f;
|
||||
assert(w.startMorseTx(909.5f,25,"EE")==mesh::MorseTxResult::Started);
|
||||
assert(w.board.before==1 && w.chip.starts==1 && w.chip.frequency==909.5f);
|
||||
w._morse_frequency=910.525f; assert(w.serviceMorseTx());
|
||||
assert(w.chip.starts==1 && !w.chip.carrier); }
|
||||
}
|
||||
'''
|
||||
self.compile_run(code, ("-DMESH_ENABLE_MORSE_RX=0",))
|
||||
|
||||
def test_read_only_runtime_preflight_and_production_default(self):
|
||||
code = r'''
|
||||
#include <cassert>
|
||||
#include <cstring>
|
||||
#include <limits>
|
||||
#include <helpers/radiolib/HilTxFrequencyGuard.h>
|
||||
int main() {
|
||||
char reply[160]="unchanged";
|
||||
#if defined(MESH_HIL_TX_FREQ_MHZ)
|
||||
assert(mesh::handleHilTxFrequencyCommand("get lab.tx",reply,sizeof(reply)));
|
||||
assert(strcmp(reply,"> HIL TX lock=909.500 MHz; off-frequency TX blocked; primary RX-only when off-frequency")==0);
|
||||
assert(mesh::hilTransmitFrequencyAllowed(909.5f));
|
||||
assert(!mesh::hilTransmitFrequencyAllowed(910.525f));
|
||||
assert(!mesh::hilTransmitFrequencyAllowed(std::numeric_limits<float>::quiet_NaN()));
|
||||
assert(!mesh::handleHilTxFrequencyCommand("set lab.tx 910.525",reply,sizeof(reply)));
|
||||
#else
|
||||
assert(!mesh::handleHilTxFrequencyCommand("get lab.tx",reply,sizeof(reply)));
|
||||
assert(strcmp(reply,"unchanged")==0);
|
||||
assert(mesh::hilTransmitFrequencyAllowed(910.525f));
|
||||
#endif
|
||||
}
|
||||
'''
|
||||
self.compile_run(code)
|
||||
self.compile_run(code, guard=False)
|
||||
source = (ROOT / "examples/companion_radio/MyMesh.cpp").read_text()
|
||||
self.assertIn("#if defined(MESH_HIL_TX_FREQ_MHZ)\n"
|
||||
" if (mesh::handleHilTxFrequencyCommand(command, reply, reply_size)) return true;\n#endif", source)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,86 @@
|
||||
"""Lab startup trace is opt-in and cannot enter native/dedicated KISS UARTs."""
|
||||
from pathlib import Path
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import unittest
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
SOURCE = (ROOT / "examples/kiss_modem/main.cpp").read_text(encoding="utf-8")
|
||||
TRACE = "#if" + SOURCE.split("// Lab-only boot diagnostics", 1)[1].split(
|
||||
"#if", 1
|
||||
)[1].split("#if MESH_ESP32_HWCDC_SESSION_GUARD", 1)[0]
|
||||
|
||||
|
||||
class KissBootTraceTests(unittest.TestCase):
|
||||
def test_actual_trace_preprocessor_is_uart_only_and_opt_in(self):
|
||||
compiler = os.environ.get("CXX") or shutil.which("g++") or shutil.which("clang++")
|
||||
if not compiler:
|
||||
self.skipTest("a host C++ preprocessor is required")
|
||||
cases = [
|
||||
(["ESP32=1", "MESH_HIL_KISS_BOOT_TRACE=1"], True),
|
||||
(["ESP32=1", "MESH_HIL_KISS_BOOT_TRACE=1", "ARDUINO_USB_CDC_ON_BOOT=0"], True),
|
||||
(["ESP32=1"], False),
|
||||
(["ESP32=1", "MESH_HIL_KISS_BOOT_TRACE=0"], False),
|
||||
(["NRF52_PLATFORM=1", "MESH_HIL_KISS_BOOT_TRACE=1"], False),
|
||||
(["ESP32=1", "MESH_HIL_KISS_BOOT_TRACE=1", "ARDUINO_USB_MODE=0",
|
||||
"ARDUINO_USB_CDC_ON_BOOT=1"], False),
|
||||
(["ESP32=1", "MESH_HIL_KISS_BOOT_TRACE=1", "ARDUINO_USB_MODE=1",
|
||||
"ARDUINO_USB_CDC_ON_BOOT=1"], False),
|
||||
(["ESP32=1", "MESH_HIL_KISS_BOOT_TRACE=1", "KISS_UART_RX=5",
|
||||
"KISS_UART_TX=6"], False),
|
||||
]
|
||||
for defines, enabled in cases:
|
||||
with self.subTest(defines=defines):
|
||||
result = subprocess.run(
|
||||
[compiler, "-E", "-P", "-x", "c++", *[f"-D{x}" for x in defines], "-"],
|
||||
input=TRACE + '\nKISS_UART_BOOT_TRACE\nKISS_BOOT_STAGE("probe");\n',
|
||||
capture_output=True, text=True, timeout=10,
|
||||
)
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertEqual(result.stdout.strip().splitlines()[0], "1" if enabled else "0")
|
||||
self.assertEqual("Serial.println" in result.stdout, enabled)
|
||||
|
||||
def test_fixed_stages_bracket_startup_before_binary_loop(self):
|
||||
setup = SOURCE.split("void setup() {", 1)[1].split("void loop() {", 1)[0]
|
||||
self.assertLess(setup.index("Serial.begin(115200)"), setup.index("board.begin()"))
|
||||
for operation, before, after in [
|
||||
("board.begin()", "board.before", "board.after"),
|
||||
("radio_driver.begin()", "driver.before", "driver.after"),
|
||||
("loadOrCreateIdentity()", "identity.before", "identity.after"),
|
||||
("sensors.begin()", "sensors.before", "sensors.after"),
|
||||
("modem->begin()", "modem.before", "modem.after"),
|
||||
]:
|
||||
self.assertLess(setup.index(f'KISS_BOOT_STAGE("{before}")'), setup.index(operation))
|
||||
self.assertLess(setup.index(operation), setup.index(f'KISS_BOOT_STAGE("{after}")'))
|
||||
self.assertNotIn("KISS_BOOT_STAGE", SOURCE.split("void loop() {", 1)[1])
|
||||
|
||||
def test_esp32_mount_precedes_radio_and_failed_mount_cannot_generate_key(self):
|
||||
identity = SOURCE.split("void loadOrCreateIdentity() {", 1)[1].split(
|
||||
"void onSetRadio(", 1
|
||||
)[0]
|
||||
setup = SOURCE.split("void setup() {", 1)[1].split("void loop() {", 1)[0]
|
||||
self.assertNotIn("SPIFFS.begin", identity)
|
||||
self.assertEqual(SOURCE.count("SPIFFS.begin(true)"), 1)
|
||||
self.assertLess(setup.index("board.begin()"), setup.index("SPIFFS.begin(true)"))
|
||||
self.assertLess(setup.index("SPIFFS.begin(true)"), setup.index("while (!radio_init())"))
|
||||
mount = setup.split("#if defined(ESP32)", 1)[1].split("#endif", 1)[0]
|
||||
self.assertIn("const bool filesystem_ready = SPIFFS.begin(true);", mount)
|
||||
failure = mount.split("if (!filesystem_ready) {", 1)[1]
|
||||
self.assertIn("board.reboot();", failure)
|
||||
self.assertIn("halt();", failure)
|
||||
self.assertNotIn("loadOrCreateIdentity", failure)
|
||||
|
||||
def test_identity_stages_never_export_identity_bytes(self):
|
||||
for line in SOURCE.splitlines():
|
||||
if "KISS_BOOT_STAGE(" in line and not line.lstrip().startswith("#define"):
|
||||
self.assertRegex(line.strip(), r'^KISS_BOOT_STAGE\("[a-z_.]+"\);$')
|
||||
before = SOURCE.index('KISS_BOOT_STAGE("filesystem.before")')
|
||||
after = SOURCE.index('KISS_BOOT_STAGE("filesystem.after")')
|
||||
self.assertLess(before, SOURCE.index("SPIFFS.begin(true)"))
|
||||
self.assertLess(SOURCE.index("SPIFFS.begin(true)"), after)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,112 @@
|
||||
"""Raw KISS wire-only support: no Companion tunnel, dispatcher slot or RF."""
|
||||
from pathlib import Path
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
from test_radio_receive_contract import method
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
class KissEthernetWireTests(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.compiler = os.environ.get("CXX") or shutil.which("g++") or shutil.which("clang++")
|
||||
if not cls.compiler:
|
||||
raise unittest.SkipTest("a host C++17 compiler is required")
|
||||
|
||||
def compile_run(self, code, *flags):
|
||||
with tempfile.TemporaryDirectory(prefix="meshcore-kiss-wire-") as folder:
|
||||
source, binary = Path(folder) / "test.cpp", Path(folder) / "test"
|
||||
source.write_text(code, encoding="utf-8")
|
||||
command = [self.compiler, "-std=c++17", "-Wall", "-Wextra", *flags,
|
||||
"-I", str(ROOT / "src"), str(source), "-o", str(binary)]
|
||||
result = subprocess.run(command, capture_output=True, text=True, timeout=45)
|
||||
self.assertEqual(result.returncode, 0, result.stderr[-12000:])
|
||||
result = subprocess.run([str(binary)], capture_output=True, text=True, timeout=10)
|
||||
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
|
||||
|
||||
def test_wire_only_does_not_enable_companion_tunnel_or_foreign_queue(self):
|
||||
self.compile_run(r'''
|
||||
#include <helpers/MeshtextConfig.h>
|
||||
static_assert(MESH_ENABLE_ETHERNET_WIRE == 1, "raw wire must be enabled");
|
||||
static_assert(MESH_ENABLE_ETHERNET_TUNNEL == 0, "no Companion tunnel");
|
||||
static_assert(MESH_ENABLE_FOREIGN_RADIO == 0, "no foreign dispatcher slot");
|
||||
int main() {}
|
||||
''', "-DMESH_ENABLE_ETHERNET_WIRE=1", "-DMESH_ENABLE_ETHERNET_TUNNEL=0",
|
||||
"-DMESH_ENABLE_MESHTEXT_CHAT=0", "-DNRF52_PLATFORM=1")
|
||||
|
||||
def test_actual_sx1262_and_sx1276_protocol_switching_with_wire_only(self):
|
||||
for chip in ("SX1262", "SX1276"):
|
||||
source = (ROOT / f"src/helpers/radiolib/Custom{chip}Wrapper.h").read_text()
|
||||
protocol = method(source, "bool applyProtocol(").replace(" override", "")
|
||||
code = r'''
|
||||
#include <helpers/MeshtextConfig.h>
|
||||
#include <RadioProfiles.h>
|
||||
#include <cassert>
|
||||
#define RADIOLIB_ERR_NONE 0
|
||||
struct Custom@CHIP@ {
|
||||
unsigned writes=0;uint8_t sync=0;int result=0;
|
||||
int setProfileProtocol(uint8_t value) { ++writes;sync=value;return result; }
|
||||
};
|
||||
struct Driver {
|
||||
Custom@CHIP@ chip;Custom@CHIP@* _radio=&chip;bool supported=true;
|
||||
bool supportsMeshtext() const { return false; }
|
||||
bool supportsEthernetTunnel() const { return supported; }
|
||||
@METHOD@
|
||||
};
|
||||
int main() {
|
||||
using P=mesh::RadioProfileProtocol;Driver d;
|
||||
assert(d.applyProtocol(P::Ethernet) && d.chip.sync==0x16);
|
||||
assert(d.applyProtocol(P::MeshCore) && d.chip.sync==0x12);
|
||||
const auto before=d.chip.writes;d.supported=false;
|
||||
assert(!d.applyProtocol(P::Ethernet) && d.chip.writes==before);
|
||||
assert(!d.applyProtocol(P::Meshtext) && d.chip.writes==before);
|
||||
assert(!d.applyProtocol(P(99)) && d.chip.writes==before);
|
||||
d.chip.result=-1;assert(!d.applyProtocol(P::MeshCore));
|
||||
}
|
||||
'''.replace("@CHIP@", chip).replace("@METHOD@", protocol)
|
||||
with self.subTest(chip=chip):
|
||||
self.compile_run(code, "-DMESH_ENABLE_ETHERNET_WIRE=1",
|
||||
"-DMESH_ENABLE_ETHERNET_TUNNEL=0", "-DMESH_ENABLE_MESHTEXT_WIRE=0")
|
||||
|
||||
def test_actual_validator_gates_wire_and_chip_capability(self):
|
||||
source = (ROOT / "src/helpers/radiolib/RadioLibWrappers.cpp").read_text()
|
||||
validator = method(source, "bool RadioLibWrapper::validateProfile(")
|
||||
code = r'''
|
||||
#include <helpers/MeshtextConfig.h>
|
||||
#include <RadioProfiles.h>
|
||||
#include <cassert>
|
||||
struct RadioLibWrapper {
|
||||
bool supported=true;
|
||||
bool supportsMeshtext() const { return false; }
|
||||
bool supportsEthernetTunnel() const { return supported; }
|
||||
bool validateProfile(const mesh::RadioProfileParams&) const;
|
||||
};
|
||||
@VALIDATOR@
|
||||
int main() {
|
||||
using P=mesh::RadioProfileProtocol;
|
||||
RadioLibWrapper d;mesh::RadioProfileParams p;
|
||||
p.freq=909.5;p.bw=500;p.sf=5;p.cr=5;p.preamble=512;p.protocol=P::Ethernet;
|
||||
#if MESH_RADIO_PROFILE_CHIP == 1262
|
||||
assert(d.validateProfile(p)==bool(MESH_ENABLE_ETHERNET_WIRE));
|
||||
#else
|
||||
assert(!d.validateProfile(p)); // SX1276 cannot use SF5.
|
||||
p.sf=7;assert(d.validateProfile(p)==bool(MESH_ENABLE_ETHERNET_WIRE));
|
||||
#endif
|
||||
d.supported=false;assert(!d.validateProfile(p));
|
||||
p.protocol=P::MeshCore;assert(d.validateProfile(p));
|
||||
}
|
||||
'''.replace("@VALIDATOR@", validator)
|
||||
for wire in (0, 1):
|
||||
for chip in (1262, 1276):
|
||||
with self.subTest(wire=wire, chip=chip):
|
||||
self.compile_run(code, f"-DMESH_ENABLE_ETHERNET_WIRE={wire}",
|
||||
"-DMESH_ENABLE_ETHERNET_TUNNEL=0", f"-DMESH_RADIO_PROFILE_CHIP={chip}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -130,8 +130,10 @@ public:
|
||||
|
||||
mesh::RadioProfiles* profiles() override { return &_profiles; }
|
||||
const mesh::RadioProfiles* profiles() const override { return &_profiles; }
|
||||
bool supportsEthernetTunnel() const override { return _ethernet_supported; }
|
||||
bool validateProfile(const mesh::RadioProfileParams& params) const override {
|
||||
return mesh::RadioProfiles::valid(params);
|
||||
return mesh::RadioProfiles::valid(params) && _profile_supported
|
||||
&& (params.protocol != mesh::RadioProfileProtocol::Ethernet || _ethernet_supported);
|
||||
}
|
||||
uint8_t receiveProfile() const override { return _active_profile; }
|
||||
mesh::RadioParamApplyResult prepareTransmitProfile(uint8_t profile) override {
|
||||
@@ -171,6 +173,8 @@ public:
|
||||
void setSendComplete(bool complete) { _send_complete = complete; }
|
||||
void setPrepareResult(mesh::RadioParamApplyResult result) { _prepare_result = result; }
|
||||
void setReceiveProfile(uint8_t profile) { _active_profile = profile; }
|
||||
void setEthernetSupported(bool enabled) { _ethernet_supported = enabled; }
|
||||
void setProfileSupported(bool enabled) { _profile_supported = enabled; }
|
||||
int startSendCount() const { return _start_send_count; }
|
||||
int sendFinishedCount() const { return _send_finished_count; }
|
||||
uint8_t lastSentProfile() const { return _sent_profiles.empty() ? 0xff : _sent_profiles.back(); }
|
||||
@@ -185,6 +189,8 @@ private:
|
||||
uint8_t _active_profile = 0;
|
||||
bool _start_send_result = true;
|
||||
bool _send_complete = true;
|
||||
bool _ethernet_supported = true;
|
||||
bool _profile_supported = true;
|
||||
int _start_send_count = 0;
|
||||
int _send_finished_count = 0;
|
||||
mesh::RadioParamApplyResult _prepare_result = mesh::RadioParamApplyResult::APPLIED;
|
||||
@@ -555,6 +561,151 @@ TEST_F(KissModemFixture, TempRadio2RestoresSavedProfileAndLeavesSavedUpdatesDefe
|
||||
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, KISS_FEND}));
|
||||
}
|
||||
|
||||
TEST_F(KissModemFixture, ExtendedRadio2RoundTripKeepsLegacyCommandsExactlyThirteenBytes) {
|
||||
auto payload = radio2Payload(909500000, 500000, 5, 5,
|
||||
(uint8_t)mesh::RadioProfileMode::RxTx, 512);
|
||||
const auto legacy = payload;
|
||||
payload.push_back((uint8_t)mesh::RadioProfileProtocol::Ethernet);
|
||||
sendHardware(HW_CMD_SET_RADIO2_EXT, payload);
|
||||
EXPECT_EQ(serial.writesSnapshot(), hardwareFrame(HW_RESP_OK));
|
||||
EXPECT_EQ(radio.profileConfig().secondary.params.protocol, mesh::RadioProfileProtocol::Ethernet);
|
||||
EXPECT_EQ(radio.profileConfig().secondary.params.preamble, 512);
|
||||
|
||||
serial.clearWrites();
|
||||
sendHardware(HW_CMD_GET_RADIO2_EXT);
|
||||
EXPECT_EQ(serial.writesSnapshot(), hardwareFrame(HW_RESP(HW_CMD_GET_RADIO2_EXT), payload));
|
||||
serial.clearWrites();
|
||||
sendHardware(HW_CMD_GET_RADIO2);
|
||||
EXPECT_EQ(serial.writesSnapshot(), hardwareFrame(HW_RESP(HW_CMD_GET_RADIO2), legacy));
|
||||
|
||||
serial.clearWrites();
|
||||
sendHardware(HW_CMD_SET_RADIO2, legacy);
|
||||
EXPECT_EQ(serial.writesSnapshot(), hardwareFrame(HW_RESP_OK));
|
||||
EXPECT_EQ(radio.profileConfig().secondary.params.protocol, mesh::RadioProfileProtocol::MeshCore);
|
||||
serial.clearWrites();
|
||||
sendHardware(HW_CMD_GET_RADIO2_EXT);
|
||||
payload.back() = (uint8_t)mesh::RadioProfileProtocol::MeshCore;
|
||||
EXPECT_EQ(serial.writesSnapshot(), hardwareFrame(HW_RESP(HW_CMD_GET_RADIO2_EXT), payload));
|
||||
}
|
||||
|
||||
TEST_F(KissModemFixture, LabTransmitGuardIsReadOnlyAndExistsOnlyInExplicitHilBuilds) {
|
||||
sendHardware(HW_CMD_GET_LAB_TX_GUARD);
|
||||
#if defined(MESH_HIL_TX_FREQ_MHZ)
|
||||
static_assert(MESH_HIL_TX_FREQ_MHZ == 909.5, "This test fixture requires the standard lab lock");
|
||||
EXPECT_EQ(serial.writesSnapshot(), hardwareFrame(HW_RESP(HW_CMD_GET_LAB_TX_GUARD),
|
||||
{0x60, 0xDE, 0x35, 0x36})); // 909500000 Hz, little endian.
|
||||
serial.clearWrites();
|
||||
sendHardware(HW_CMD_GET_LAB_TX_GUARD, {0});
|
||||
EXPECT_EQ(serial.writesSnapshot(), hardwareFrame(HW_RESP_ERROR, {HW_ERR_INVALID_LENGTH}));
|
||||
#else
|
||||
EXPECT_EQ(serial.writesSnapshot(), hardwareFrame(HW_RESP_ERROR, {HW_ERR_UNKNOWN_CMD}));
|
||||
#endif
|
||||
EXPECT_EQ(radio.startSendCount(), 0);
|
||||
}
|
||||
|
||||
TEST_F(KissModemFixture, ExtendedRadio2RejectsInvalidLengthsProtocolsAndUnsupportedChipWithoutMutation) {
|
||||
auto payload = radio2Payload(909500000, 500000, 5, 5,
|
||||
(uint8_t)mesh::RadioProfileMode::RxTx, 512);
|
||||
payload.push_back((uint8_t)mesh::RadioProfileProtocol::Ethernet);
|
||||
sendHardware(HW_CMD_SET_RADIO2_EXT, payload);
|
||||
const auto generation = radio.profileConfig().generation[1];
|
||||
const auto original = radio.profileConfig().secondary.params;
|
||||
for (size_t length : {size_t(0), size_t(13), size_t(15)}) {
|
||||
auto changed = payload; changed.resize(length);
|
||||
serial.clearWrites();
|
||||
sendHardware(HW_CMD_SET_RADIO2_EXT, changed);
|
||||
EXPECT_EQ(serial.writesSnapshot(), hardwareFrame(HW_RESP_ERROR, {HW_ERR_INVALID_LENGTH}));
|
||||
EXPECT_EQ(radio.profileConfig().generation[1], generation);
|
||||
}
|
||||
for (uint8_t protocol : {uint8_t(1), uint8_t(3), uint8_t(255)}) {
|
||||
auto changed = payload; changed.back() = protocol;
|
||||
serial.clearWrites();
|
||||
sendHardware(HW_CMD_SET_RADIO2_EXT, changed);
|
||||
EXPECT_EQ(serial.writesSnapshot(), hardwareFrame(HW_RESP_ERROR, {HW_ERR_INVALID_PARAM}));
|
||||
EXPECT_EQ(radio.profileConfig().generation[1], generation);
|
||||
}
|
||||
radio.setEthernetSupported(false);
|
||||
for (uint8_t mode : {uint8_t(0), uint8_t(2)}) {
|
||||
auto changed = payload; changed[10] = mode;
|
||||
serial.clearWrites();
|
||||
sendHardware(HW_CMD_SET_RADIO2_EXT, changed);
|
||||
EXPECT_EQ(serial.writesSnapshot(), hardwareFrame(HW_RESP_ERROR, {HW_ERR_INVALID_PARAM}));
|
||||
EXPECT_EQ(radio.profileConfig().generation[1], generation);
|
||||
}
|
||||
radio.setEthernetSupported(true);
|
||||
radio.setProfileSupported(false); // e.g. modem cannot use the requested SF/BW.
|
||||
serial.clearWrites();
|
||||
sendHardware(HW_CMD_SET_RADIO2_EXT, payload);
|
||||
EXPECT_EQ(serial.writesSnapshot(), hardwareFrame(HW_RESP_ERROR, {HW_ERR_INVALID_PARAM}));
|
||||
EXPECT_EQ(radio.profileConfig().secondary.params, original);
|
||||
EXPECT_EQ(radio.profileConfig().generation[1], generation);
|
||||
|
||||
serial.clearWrites();
|
||||
sendHardware(HW_CMD_GET_RADIO2_EXT, {0});
|
||||
EXPECT_EQ(serial.writesSnapshot(), hardwareFrame(HW_RESP_ERROR, {HW_ERR_INVALID_LENGTH}));
|
||||
}
|
||||
|
||||
TEST_F(KissModemFixture, ExtendedSavedProtocolDoesNotInterruptTemporaryMeshCoreLease) {
|
||||
auto temporary = radio2Payload(868000000, 125000, 7, 5,
|
||||
(uint8_t)mesh::RadioProfileMode::RxTx, 32);
|
||||
appendU16(temporary, 1);
|
||||
sendHardware(HW_CMD_SET_TEMPRADIO2, temporary);
|
||||
ASSERT_TRUE(radio.profileConfig().secondary_temporary);
|
||||
auto saved = radio2Payload(909500000, 500000, 5, 5,
|
||||
(uint8_t)mesh::RadioProfileMode::RxTx, 512);
|
||||
saved.push_back((uint8_t)mesh::RadioProfileProtocol::Ethernet);
|
||||
const auto temporary_generation = radio.profileConfig().generation[1];
|
||||
serial.clearWrites();
|
||||
sendHardware(HW_CMD_SET_RADIO2_EXT, saved);
|
||||
EXPECT_EQ(serial.writesSnapshot(), hardwareFrame(HW_RESP_OK));
|
||||
EXPECT_EQ(radio.profileConfig().secondary.params.protocol, mesh::RadioProfileProtocol::MeshCore);
|
||||
EXPECT_EQ(radio.profileConfig().generation[1], temporary_generation);
|
||||
serial.clearWrites();
|
||||
sendHardware(HW_CMD_GET_RADIO2_EXT);
|
||||
EXPECT_EQ(serial.writesSnapshot(), hardwareFrame(HW_RESP(HW_CMD_GET_RADIO2_EXT), saved));
|
||||
delay(60000);
|
||||
modem.loop();
|
||||
EXPECT_FALSE(radio.profileConfig().secondary_temporary);
|
||||
EXPECT_EQ(radio.profileConfig().secondary.params.protocol, mesh::RadioProfileProtocol::Ethernet);
|
||||
EXPECT_FLOAT_EQ(radio.profileConfig().secondary.params.freq, 909.5f);
|
||||
}
|
||||
|
||||
TEST_F(KissModemFixture, TemporaryCancelRestoresSavedEthernetProtocol) {
|
||||
auto saved = radio2Payload(909500000, 500000, 5, 5,
|
||||
(uint8_t)mesh::RadioProfileMode::RxTx, 512);
|
||||
saved.push_back((uint8_t)mesh::RadioProfileProtocol::Ethernet);
|
||||
sendHardware(HW_CMD_SET_RADIO2_EXT, saved);
|
||||
auto temporary = radio2Payload(868000000, 125000, 7, 5,
|
||||
(uint8_t)mesh::RadioProfileMode::RxTx, 32);
|
||||
appendU16(temporary, 1);
|
||||
sendHardware(HW_CMD_SET_TEMPRADIO2, temporary);
|
||||
EXPECT_EQ(radio.profileConfig().secondary.params.protocol, mesh::RadioProfileProtocol::MeshCore);
|
||||
serial.clearWrites();
|
||||
sendHardware(HW_CMD_SET_TEMPRADIO2, std::vector<uint8_t>(KISS_TEMPRADIO2_PARAMS_SIZE, 0));
|
||||
EXPECT_EQ(serial.writesSnapshot(), hardwareFrame(HW_RESP_OK));
|
||||
EXPECT_FALSE(radio.profileConfig().secondary_temporary);
|
||||
EXPECT_EQ(radio.profileConfig().secondary.params.protocol, mesh::RadioProfileProtocol::Ethernet);
|
||||
}
|
||||
|
||||
TEST_F(KissModemFixture, ProtocolOnlyChangeInvalidatesQueuedSecondaryTransmitWithoutPrimaryFallback) {
|
||||
auto payload = radio2Payload(909500000, 500000, 5, 5,
|
||||
(uint8_t)mesh::RadioProfileMode::RxTx, 512);
|
||||
sendHardware(HW_CMD_SET_RADIO2, payload);
|
||||
serial.clearWrites();
|
||||
serial.pushRx(dataFrame({0x42}, 1));
|
||||
modem.loop(); // Bind the pending port-one packet before the protocol changes.
|
||||
const auto generation = radio.profileConfig().generation[1];
|
||||
payload.push_back((uint8_t)mesh::RadioProfileProtocol::Ethernet);
|
||||
sendHardware(HW_CMD_SET_RADIO2_EXT, payload);
|
||||
EXPECT_NE(radio.profileConfig().generation[1], generation);
|
||||
serial.clearWrites();
|
||||
delay(KISS_DEFAULT_TXDELAY * 10);
|
||||
modem.loop();
|
||||
modem.loop();
|
||||
EXPECT_EQ(radio.startSendCount(), 0);
|
||||
EXPECT_EQ(serial.writesSnapshot(), hardwareFrame(HW_RESP_TX_DONE, {0}));
|
||||
}
|
||||
|
||||
TEST_F(KissModemFixture, SecondaryReceiveUsesPortOneWithoutChangingPacketOrRxMeta) {
|
||||
const std::vector<uint8_t> radio2 = radio2Payload(910500000, 62500, 7, 5,
|
||||
(uint8_t)mesh::RadioProfileMode::RxTx, 0);
|
||||
|
||||
@@ -0,0 +1,396 @@
|
||||
"""Host-only direct KISS OTA source tests; no serial device is opened."""
|
||||
from collections import deque
|
||||
from pathlib import Path
|
||||
import struct
|
||||
import sys
|
||||
from types import SimpleNamespace
|
||||
import unittest
|
||||
from unittest.mock import Mock, patch
|
||||
import zlib
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "tools/lora_ota"))
|
||||
import mota_kiss_direct as ota
|
||||
|
||||
|
||||
def container(payload, block_size=2048):
|
||||
ml = ota.motalib
|
||||
leaves = ml.leaf_hashes(payload, block_size)
|
||||
manifest = ml.Manifest(flags=ml.FLAG_FULL, target_id=123, fw_version=0x01170000,
|
||||
image_size=len(payload), payload_size=len(payload), block_size_log2=block_size.bit_length() - 1,
|
||||
merkle_root=ml.merkle_root(leaves), image_hash=ml.mh32(payload), leaves=leaves)
|
||||
return ml.build_container(manifest, payload)
|
||||
|
||||
|
||||
def request(source, *items, wide=True):
|
||||
message = bytes((ota.REQ,)) + source.mid + b"".join(struct.pack("<HH", *item) for item in items)
|
||||
return ota.wrap_radio(message, wide=wide)
|
||||
|
||||
|
||||
def hw(code, body=b""):
|
||||
return ota.encode_frame(6, bytes((code,)) + body)
|
||||
|
||||
|
||||
class Clock:
|
||||
def __init__(self):
|
||||
self.now = 0.0
|
||||
|
||||
def __call__(self):
|
||||
self.now += .001
|
||||
return self.now
|
||||
|
||||
|
||||
class FakePort:
|
||||
def __init__(self):
|
||||
self.decoder, self.pending, self.writes = ota.Decoder(), deque(), []
|
||||
self.public = bytes(range(32))
|
||||
self.radio = (ota.GUARD_HZ, 500000, 5, 5, 2, 512, 0)
|
||||
self.overrides = {}
|
||||
self.tx_reply = hw(0xF8, b"\1")
|
||||
self.before_tx_done = b""
|
||||
|
||||
def write(self, data):
|
||||
for frame in self.decoder.feed(data):
|
||||
self.writes.append(frame)
|
||||
if frame[0] in (0, 0x10):
|
||||
result = self.before_tx_done + self.tx_reply
|
||||
elif frame[0] == 6:
|
||||
command = frame[1]
|
||||
bodies = {0x21: struct.pack("<I", ota.GUARD_HZ), 0x11: b"\2\0",
|
||||
0x01: self.public, 0x17: b"", 0x20: ota.SECONDARY_STRUCT.pack(*self.radio),
|
||||
0x1E: bytes(15),
|
||||
0x0B: ota.PRIMARY_STRUCT.pack(*self.radio[:4])}
|
||||
result = self.overrides.get(command, hw(command | 0x80, bodies.get(command, b"")))
|
||||
else:
|
||||
result = b""
|
||||
self.pending.extend(result[i:i + 3] for i in range(0, len(result), 3))
|
||||
return len(data)
|
||||
|
||||
def read(self, _):
|
||||
return self.pending.popleft() if self.pending else b""
|
||||
|
||||
def flush(self):
|
||||
pass
|
||||
|
||||
|
||||
class DirectWireTests(unittest.TestCase):
|
||||
def source(self, payload=None, block_size=2048, compressor=lambda data: data):
|
||||
return ota.MotaSource(container(payload or bytes(range(256)) * 8, block_size), b"seed", compressor=compressor)
|
||||
|
||||
def test_canonical_wire_maximum_and_kiss_binary_escaping(self):
|
||||
for port in (0, 1):
|
||||
radio = ota.wrap_radio(bytes((ota.DATA,)) + bytes((0xC0, 0xDB)) * 126, wide=True)
|
||||
self.assertEqual(len(radio), 255)
|
||||
frame = ota.kiss_data(port, radio)
|
||||
decoder = ota.Decoder()
|
||||
decoded = []
|
||||
for byte in frame:
|
||||
decoded.extend(decoder.feed(bytes((byte,))))
|
||||
self.assertEqual(decoded, [bytes((port << 4,)) + radio])
|
||||
for raw in (b"\xf2\1\6", b"\xf2\0\1", b"\xf2\0\2", b"\xf2\0\6" + b"x" * 253,
|
||||
b"\x30\0\6", b"\x33\0\6", b"\x32\xc0\6"):
|
||||
self.assertIsNone(ota.decode_radio(raw))
|
||||
with self.assertRaises(ValueError):
|
||||
ota.wrap_radio(b"\7" * 254, wide=True)
|
||||
|
||||
def test_zero_hop_2k_raw_is_nine_wide_vs_twelve_normal_frames(self):
|
||||
source = self.source()
|
||||
for wide, size, frames in ((True, 240, 9), (False, 171, 12)):
|
||||
replies = source.replies(request(source, (0, 0xAFFF), wide=wide))
|
||||
messages = [ota.decode_radio(r).message for r in replies]
|
||||
data = [m for m in messages if m[0] == ota.DATA]
|
||||
self.assertEqual(len(data), frames)
|
||||
self.assertEqual(messages[-1][0], ota.PROOF)
|
||||
reconstructed = bytearray()
|
||||
for number, message in enumerate(data):
|
||||
packed = struct.unpack_from("<H", message, 7)[0]
|
||||
self.assertEqual((packed & 0x7800) >> 11, number)
|
||||
self.assertEqual((packed & 2047) + 1, 2048)
|
||||
self.assertEqual(message[9:13], ota.motalib.mh4(source.block(0)))
|
||||
self.assertLessEqual(len(message[13:]), size)
|
||||
reconstructed.extend(message[13:])
|
||||
self.assertEqual(reconstructed, source.block(0))
|
||||
self.assertEqual(max(map(len, replies)), 255 if wide else 186)
|
||||
|
||||
def test_1k_tail_descriptor_and_legacy160_fallback(self):
|
||||
source = self.source(bytes(range(256)) * 5, block_size=1024)
|
||||
self.assertEqual(len(source.replies(request(source, (0, 0x9FFF)))), 6) # 5DATA+PROOF
|
||||
legacy = source.replies(request(source, (0, 0xFFFF), wide=False))
|
||||
data = [ota.decode_radio(r).message for r in legacy if ota.decode_radio(r).message[0] == ota.DATA]
|
||||
self.assertEqual(len(data), 7)
|
||||
self.assertEqual([struct.unpack_from("<H", m, 7)[0] for m in data], [i * 160 for i in range(7)])
|
||||
tail = source.replies(request(source, (1, 0x9FFF)))
|
||||
self.assertEqual(len(tail), 3) # 256B tail /240 +proof
|
||||
self.assertEqual(struct.unpack_from("<H", ota.decode_radio(tail[0]).message, 7)[0] & 1023, 255)
|
||||
|
||||
def test_compressed_stream_identity_cached_and_resumable_masks(self):
|
||||
calls = []
|
||||
def compress(data):
|
||||
calls.append(data)
|
||||
obj = zlib.compressobj(9, wbits=-15)
|
||||
return obj.compress(data) + obj.flush()
|
||||
source = self.source(b"abc" * 650, block_size=2048, compressor=compress)
|
||||
source.prepare()
|
||||
source.prepare() # deterministic preparation may be called independently
|
||||
replies = source.replies(request(source, (0, 0xEFFF)))
|
||||
message = ota.decode_radio(replies[0]).message
|
||||
encoded = message[13:]
|
||||
self.assertEqual(zlib.decompress(encoded, -15), source.block(0))
|
||||
self.assertEqual(message[9:13], ota.motalib.mh4(encoded))
|
||||
before = len(calls)
|
||||
self.assertEqual(source.replies(request(source, (0, 0xE001))), replies)
|
||||
self.assertEqual(len(calls), before)
|
||||
source.note_sent(replies[0]); source.note_sent(replies[0])
|
||||
self.assertEqual(source.stats["repeated_data_frames"], 1)
|
||||
|
||||
def test_compression_non_winner_stays_raw_and_zopfli_uses_1000(self):
|
||||
source = self.source(compressor=lambda data: data + b"bigger")
|
||||
source.prepare()
|
||||
self.assertEqual(source.compressed[0], source.block(0))
|
||||
fake = SimpleNamespace(MAXIMUM_ITERATIONS=1000, raw_deflate_compress=Mock(return_value=b"compressed"))
|
||||
with patch.dict(sys.modules, {"zopfli_compress": fake}):
|
||||
self.assertEqual(ota.zopfli1000(b"payload"), b"compressed")
|
||||
fake.raw_deflate_compress.assert_called_once_with(b"payload", numiterations=1000)
|
||||
|
||||
def test_discovery_manifest_and_merkle_proof_use_real_container(self):
|
||||
source = self.source(bytes(range(256)) * 21)
|
||||
query = b"\2seed" + source.digest + struct.pack("<II", 123, 0)
|
||||
have = ota.decode_radio(source.replies(ota.wrap_radio(query, flood=True))[0]).message
|
||||
self.assertEqual(have[:12], b"\3seed" + source.digest + b"\0\1\1")
|
||||
self.assertEqual(have[12:16], source.mid)
|
||||
metadata = ota.wrap_radio(b"\4" + source.mid + b"\xff\xff")
|
||||
messages = [ota.decode_radio(r).message for r in source.replies(metadata)]
|
||||
self.assertEqual(b"".join(m[7:] for m in messages), source.manifest_bytes)
|
||||
self.assertEqual(len(source.manifest_bytes), 197)
|
||||
proof = source.proof(2)
|
||||
self.assertEqual(proof[8:], ota.motalib.proof_siblings(source.manifest.leaves, 2))
|
||||
self.assertTrue(ota.motalib.verify_proof(source.manifest.leaves[2], 2,
|
||||
ota.motalib.merkle_proof(source.manifest.leaves, 2), source.mid, source.manifest.block_count))
|
||||
|
||||
def test_malformed_batch_wrong_geometry_and_routed_wide_are_rejected(self):
|
||||
source = self.source()
|
||||
for raw in (request(source, (0, 0x9FFF)), request(source, (0, 0xFFFF)),
|
||||
request(source, (0, 0xAFFF), (99, 0xAFFF)),
|
||||
request(source, *((0, 0xAFFF),) * 5),
|
||||
ota.wrap_radio(b"\6" + source.mid + b"\0\0\xff" , wide=True),
|
||||
b"\x32\1A" + b"\6" + source.mid + struct.pack("<HH", 0, 0xAFFF)):
|
||||
self.assertEqual(source.replies(raw), [])
|
||||
self.assertGreater(source.stats["invalid_requests"], 0)
|
||||
damaged = bytearray(container(b"valid" * 400)); damaged[-6] ^= 1
|
||||
with self.assertRaises(ValueError):
|
||||
ota.MotaSource(bytes(damaged), b"seed")
|
||||
|
||||
def test_legacy_flood_path_uses_ordinary_flood_reply_not_wide(self):
|
||||
source = self.source()
|
||||
message = b"\6" + source.mid + struct.pack("<HH", 0, 0xAFFF)
|
||||
replies = source.replies(b"\x31\2AB" + message)
|
||||
self.assertEqual(len(replies), 13)
|
||||
self.assertTrue(all(reply[:2] == b"\x31\0" for reply in replies))
|
||||
self.assertTrue(all(not ota.decode_radio(reply).wide for reply in replies))
|
||||
|
||||
|
||||
class KissSafetyTests(unittest.TestCase):
|
||||
def link(self, port=None):
|
||||
return ota.KissLink(port or FakePort(), 1, timeout=.5, clock=Clock())
|
||||
|
||||
def test_reads_wait_for_one_byte_or_drain_only_available_bounded_bytes(self):
|
||||
class SizeAwarePort:
|
||||
def __init__(self, data=b""):
|
||||
self.buffer = data
|
||||
self.read_sizes = []
|
||||
|
||||
@property
|
||||
def in_waiting(self):
|
||||
return len(self.buffer)
|
||||
|
||||
def read(self, size):
|
||||
self.read_sizes.append(size)
|
||||
data, self.buffer = self.buffer[:size], self.buffer[size:]
|
||||
return data
|
||||
|
||||
empty = SizeAwarePort(); link = self.link(empty)
|
||||
self.assertIsNone(link._next(.005))
|
||||
self.assertTrue(empty.read_sizes)
|
||||
self.assertTrue(all(size == 1 for size in empty.read_sizes))
|
||||
|
||||
reply = hw(0xF8, b"\1")
|
||||
short = SizeAwarePort(reply); link = self.link(short)
|
||||
self.assertEqual(link._next(.1), b"\6\xf8\1")
|
||||
self.assertEqual(short.read_sizes, [len(reply)])
|
||||
|
||||
backlog = SizeAwarePort(bytes(2048) + reply); link = self.link(backlog)
|
||||
self.assertEqual(link._next(.1), b"\6\xf8\1")
|
||||
self.assertEqual(backlog.read_sizes, [1024, 1024, len(reply)])
|
||||
|
||||
def test_probe_defaults_read_only_and_bench_guard_precedes_setters(self):
|
||||
port = FakePort(); link = self.link(port)
|
||||
report, identity = link.preflight(expected_frequency=ota.GUARD_HZ, require_lab_lock=True)
|
||||
self.assertEqual(identity, port.public)
|
||||
self.assertFalse(report["serve"])
|
||||
self.assertEqual(port.writes[0], b"\6\x21")
|
||||
self.assertTrue(all(frame[0] == 6 for frame in port.writes))
|
||||
with self.assertRaises(ota.ProtocolError):
|
||||
link.send_radio(b"\xf2\0\6")
|
||||
with self.assertRaises(ValueError):
|
||||
self.link().preflight(zero_pacing=True)
|
||||
|
||||
def test_production_no_hil_command_and_explicit_pacing_only_after_proof(self):
|
||||
port = FakePort(); link = self.link(port)
|
||||
link.preflight(expected_frequency=ota.GUARD_HZ, expected_public_key=port.public,
|
||||
serve=True, zero_pacing=True)
|
||||
self.assertNotIn(b"\6\x21", port.writes)
|
||||
self.assertEqual(port.writes[-3:], [b"\1\0", b"\2\xff", b"\3\1"])
|
||||
self.assertTrue(all(frame[0] == 6 for frame in port.writes[:-3]))
|
||||
|
||||
def test_wrong_identity_frequency_protocol_and_missing_guard_never_set_or_send(self):
|
||||
for kind in ("identity", "frequency", "protocol", "guard", "version"):
|
||||
port = FakePort(); link = self.link(port)
|
||||
if kind == "protocol": port.radio = (*port.radio[:6], 2)
|
||||
if kind == "guard": port.overrides[0x21] = hw(0xF1, b"\5")
|
||||
if kind == "version": port.overrides[0x11] = hw(0x91, b"\1\0")
|
||||
with self.subTest(kind=kind), self.assertRaises((ota.ProtocolError, ValueError)):
|
||||
link.preflight(expected_frequency=910525000 if kind == "frequency" else ota.GUARD_HZ,
|
||||
expected_public_key=b"x" * 32 if kind == "identity" else None,
|
||||
require_lab_lock=True, serve=True, zero_pacing=True)
|
||||
self.assertTrue(all(frame[0] == 6 for frame in port.writes))
|
||||
|
||||
def test_real_txdone_required_and_rx_requests_survive_while_waiting(self):
|
||||
port = FakePort(); link = self.link(port)
|
||||
link.preflight(expected_frequency=ota.GUARD_HZ, serve=True)
|
||||
request = b"\xf2\0\6seed\0\0\xff\xaf"
|
||||
port.before_tx_done = ota.kiss_data(1, request)
|
||||
link.send_radio(b"\xf2\0\7payload")
|
||||
self.assertEqual(link.tx_frames, 1)
|
||||
self.assertEqual(link.rf_bytes, 10)
|
||||
self.assertEqual(link.poll(), request)
|
||||
self.assertGreater(link.tx_done_wait_seconds, 0)
|
||||
self.assertGreater(link.estimated_airtime_seconds, 0)
|
||||
for bad in (hw(0xF0), hw(0xF8, b"\0"), b""):
|
||||
port = FakePort(); link = self.link(port)
|
||||
link.preflight(expected_frequency=ota.GUARD_HZ, serve=True)
|
||||
port.tx_reply = bad
|
||||
with self.assertRaises(ota.ProtocolError):
|
||||
link.send_radio(b"\xf2\0\7payload")
|
||||
self.assertEqual(sum(frame[0] == 0x10 for frame in port.writes), 1)
|
||||
|
||||
def test_frequency_generation_change_before_rf_fails_closed(self):
|
||||
port = FakePort(); link = self.link(port)
|
||||
link.preflight(expected_frequency=ota.GUARD_HZ, serve=True)
|
||||
port.radio = (910525000, *port.radio[1:])
|
||||
with self.assertRaises(ota.ProtocolError):
|
||||
link.send_radio(b"\xf2\0\7payload")
|
||||
self.assertFalse(any(frame[0] in (0, 0x10) for frame in port.writes))
|
||||
|
||||
def test_saved_radio2_cannot_hide_active_temporary_lease_before_setters(self):
|
||||
# Even an expiring lease or the expected frequency is not a stable
|
||||
# profile: require the entire temporary tuple to be zero.
|
||||
for temporary in (struct.pack("<IIBBBHH", 910525000, 62500, 7, 5, 2, 32, 1),
|
||||
struct.pack("<IIBBBHH", ota.GUARD_HZ, 500000, 5, 5, 2, 512, 0),
|
||||
bytes(13) + b"\1\0"):
|
||||
with self.subTest(temporary=temporary.hex()):
|
||||
port = FakePort(); link = self.link(port)
|
||||
port.overrides[0x1E] = hw(0x9E, temporary)
|
||||
with self.assertRaisesRegex(ota.ProtocolError, "temporary radio2"):
|
||||
link.preflight(expected_frequency=ota.GUARD_HZ, serve=True, zero_pacing=True)
|
||||
self.assertTrue(all(frame[0] == 6 for frame in port.writes))
|
||||
self.assertFalse(link.authorized)
|
||||
port = FakePort(); link = self.link(port)
|
||||
port.overrides[0x1E] = hw(0xF1, b"\5")
|
||||
with self.assertRaises(ota.ProtocolError):
|
||||
link.preflight(expected_frequency=ota.GUARD_HZ, serve=True, zero_pacing=True)
|
||||
self.assertTrue(all(frame[0] == 6 for frame in port.writes))
|
||||
|
||||
def test_temporary_lease_started_after_preflight_refuses_next_data(self):
|
||||
port = FakePort(); link = self.link(port)
|
||||
link.preflight(expected_frequency=ota.GUARD_HZ, serve=True)
|
||||
port.overrides[0x1E] = hw(0x9E,
|
||||
struct.pack("<IIBBBHH", 910525000, 62500, 7, 5, 2, 32, 1))
|
||||
with self.assertRaisesRegex(ota.ProtocolError, "temporary radio2"):
|
||||
link.send_radio(b"\xf2\0\7payload")
|
||||
self.assertFalse(any(frame[0] in (0, 0x10) for frame in port.writes))
|
||||
|
||||
def test_primary_getter_effective_override_change_refuses_data(self):
|
||||
port = FakePort(); link = ota.KissLink(port, 0, timeout=.5, clock=Clock())
|
||||
link.preflight(expected_frequency=ota.GUARD_HZ, serve=True)
|
||||
self.assertNotIn(b"\6\x1e", port.writes) # no primary-lease KISS API
|
||||
port.radio = (910525000, *port.radio[1:])
|
||||
with self.assertRaisesRegex(ota.ProtocolError, "Radio changed"):
|
||||
link.send_radio(b"\xf2\0\7payload")
|
||||
self.assertFalse(any(frame[0] in (0, 0x10) for frame in port.writes))
|
||||
|
||||
|
||||
class PacingTests(unittest.TestCase):
|
||||
def test_sparse_distinct_losses_downshift_duplicates_do_not_compound(self):
|
||||
pace = ota.AdaptivePace()
|
||||
self.assertEqual(pace.quiet(.1), 0)
|
||||
pace.observe(0, 1, 0x1FF)
|
||||
self.assertEqual(pace.effective, .5)
|
||||
self.assertAlmostEqual(pace.quiet(.1), .1)
|
||||
for _ in range(20):
|
||||
pace.observe(0, 1, 0x1FF)
|
||||
self.assertEqual(pace.effective, .5)
|
||||
pace.observe(1, 2, 0x1FF)
|
||||
self.assertEqual(pace.effective, .25)
|
||||
self.assertAlmostEqual(pace.quiet(.1), .3)
|
||||
self.assertEqual(pace.report()["duplicate_sparse_requests"], 20)
|
||||
floor = ota.AdaptivePace(.5)
|
||||
for block in range(5):
|
||||
floor.observe(block, 1, 0x1FF)
|
||||
self.assertEqual(floor.effective, .5)
|
||||
|
||||
def test_sixteen_forward_clean_blocks_recover_point_one_only(self):
|
||||
pace = ota.AdaptivePace()
|
||||
pace.observe(0, 1, 0x1FF)
|
||||
for _ in range(20):
|
||||
pace.observe(0, 0x1FF, 0x1FF)
|
||||
self.assertEqual(pace.effective, .5)
|
||||
for block in range(1, 16):
|
||||
pace.observe(block, 0x1FF, 0x1FF)
|
||||
self.assertEqual(pace.effective, .5)
|
||||
pace.observe(16, 0x1FF, 0x1FF)
|
||||
self.assertEqual(pace.effective, .6)
|
||||
for block in range(17, 33):
|
||||
pace.observe(block, 0x1FF, 0x1FF)
|
||||
self.assertEqual(pace.effective, .7)
|
||||
pace.observe(100, 0, 0x1FF)
|
||||
self.assertEqual(pace.effective, .7)
|
||||
|
||||
def test_source_validated_retry_masks_drive_geometry_specific_pace(self):
|
||||
source = ota.MotaSource(container(bytes(range(256)) * 24), b"seed", compressor=lambda data: data)
|
||||
source.replies(request(source, (0, 0xA1FF))) # complete2KiBwide mask
|
||||
self.assertEqual(source.pace.effective, 1)
|
||||
source.replies(request(source, (0, 0xA001)))
|
||||
self.assertEqual(source.pace.effective, .5)
|
||||
source.replies(request(source, (0, 0xA001)))
|
||||
self.assertEqual(source.pace.effective, .5)
|
||||
source.replies(request(source, (1, 0xA001)))
|
||||
self.assertEqual(source.pace.effective, .25)
|
||||
before = source.pace.report()
|
||||
source.replies(request(source, (0, 0xA001), (500, 0xA001)))
|
||||
self.assertEqual(source.pace.report(), before)
|
||||
|
||||
def test_wide_proof_immediate_legacy_proof_gap_and_subone_quiet_only(self):
|
||||
source = ota.MotaSource(container(bytes(range(256)) * 8), b"seed", compressor=lambda data: data)
|
||||
class Link:
|
||||
radio = (ota.GUARD_HZ, 500000, 5, 5, 2, 512, 0)
|
||||
last_airtime_seconds = .05
|
||||
def __init__(self): self.sent = []
|
||||
def send_radio(self, frame): self.sent.append(frame)
|
||||
for wide in (True, False):
|
||||
link, sleeps = Link(), []
|
||||
batch = source.replies(request(source, (0, 0xAFFF), wide=wide))
|
||||
ota.send_batch(link, source, batch, sleep=sleeps.append, clock=lambda: 0)
|
||||
self.assertEqual(link.sent, batch)
|
||||
self.assertEqual(sleeps, [] if wide else [.1])
|
||||
source.pace.observe(0, 1, 0x1FF)
|
||||
link, sleeps = Link(), []
|
||||
batch = source.replies(request(source, (0, 0xA001)))
|
||||
ota.send_batch(link, source, batch, sleep=sleeps.append, clock=lambda: 0)
|
||||
self.assertEqual(sleeps, [.05, .05]) # oneDATA and onePROOF; no wide gap
|
||||
stopped = Link()
|
||||
ota.send_batch(stopped, source, batch, sleep=sleeps.append, clock=lambda: 10, deadline=10)
|
||||
self.assertEqual(stopped.sent, [])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -1044,35 +1044,37 @@ class Nrf52ExtraFsContractTest(unittest.TestCase):
|
||||
|
||||
def test_channel_update_rolls_back_when_atomic_save_fails(self):
|
||||
mesh = MESH.read_text(encoding="utf-8")
|
||||
handler = function_body(mesh, "void MyMesh::handleCmdFrame(")
|
||||
channel_at = handler.index(
|
||||
"cmd_frame[0] == CMD_SET_CHANNEL && len >= 2 + 32 + 16"
|
||||
)
|
||||
next_command_at = handler.index(
|
||||
"cmd_frame[0] == CMD_SIGN_START", channel_at
|
||||
)
|
||||
channel_update = handler[channel_at:next_command_at]
|
||||
# Both wire encodings must snapshot the raw persisted representation.
|
||||
# getChannel() resolves aliases into effective wire keys/TX routing;
|
||||
# using it for rollback would corrupt a prefixed channel after failure.
|
||||
# Exact-byte rollback is also executed by the native channel-alias and
|
||||
# Meshtext command fixtures, not merely checked as source ordering.
|
||||
for key_bytes in (16, 32):
|
||||
with self.subTest(key_bytes=key_bytes):
|
||||
channel_update = function_body(mesh,
|
||||
f"if (cmd_frame[0] == CMD_SET_CHANNEL && len >= 2 + 32 + {key_bytes})")
|
||||
snapshot_at = channel_update.index(
|
||||
"getChannelForSave(channel_idx, previous)"
|
||||
)
|
||||
self.assertNotIn("getChannel(channel_idx, previous)", channel_update)
|
||||
mutate_at = channel_update.index(
|
||||
"setChannel(channel_idx, channel)"
|
||||
)
|
||||
save_at = channel_update.index("saveChannels()")
|
||||
rollback_at = channel_update.index(
|
||||
"setChannel(channel_idx, previous)", save_at
|
||||
)
|
||||
error_at = channel_update.index(
|
||||
"writeErrFrame(ERR_CODE_FILE_IO_ERROR)", rollback_at
|
||||
)
|
||||
ok_at = channel_update.index("writeOKFrame()")
|
||||
|
||||
snapshot_at = channel_update.index(
|
||||
"getChannel(channel_idx, previous)"
|
||||
)
|
||||
mutate_at = channel_update.index(
|
||||
"setChannel(channel_idx, channel)"
|
||||
)
|
||||
save_at = channel_update.index("saveChannels()")
|
||||
rollback_at = channel_update.index(
|
||||
"setChannel(channel_idx, previous)", save_at
|
||||
)
|
||||
error_at = channel_update.index(
|
||||
"writeErrFrame(ERR_CODE_FILE_IO_ERROR)", rollback_at
|
||||
)
|
||||
ok_at = channel_update.index("writeOKFrame()")
|
||||
|
||||
self.assertLess(snapshot_at, mutate_at)
|
||||
self.assertLess(mutate_at, save_at)
|
||||
self.assertLess(save_at, ok_at)
|
||||
self.assertLess(save_at, rollback_at)
|
||||
self.assertLess(rollback_at, error_at)
|
||||
self.assertLess(snapshot_at, mutate_at)
|
||||
self.assertLess(mutate_at, save_at)
|
||||
self.assertLess(save_at, ok_at)
|
||||
self.assertLess(save_at, rollback_at)
|
||||
self.assertLess(rollback_at, error_at)
|
||||
self.assertEqual(channel_update.count("writeOKFrame()"), 1)
|
||||
|
||||
def test_absent_advert_delete_avoids_bucket_rewrite_without_legacy_cache(self):
|
||||
store = STORE.read_text(encoding="utf-8")
|
||||
|
||||
@@ -5768,6 +5768,8 @@ TEST(OtaSpeed, MissingProofFallbackStaysArmedAtMillisRollover) {
|
||||
EXPECT_EQ(ota_msg_type(sent.items.back().data(), sent.items.back().size()), OTA_REQ_PROOF);
|
||||
}
|
||||
|
||||
#include "test_ota_direct_manager.inc"
|
||||
|
||||
int main(int argc, char** argv) {
|
||||
::testing::InitGoogleTest(&argc, argv);
|
||||
return RUN_ALL_TESTS();
|
||||
|
||||
@@ -0,0 +1,467 @@
|
||||
// Included after the shared OTA vectors/codecs in test_ota_core.cpp.
|
||||
namespace {
|
||||
struct DirectManagerBus {
|
||||
struct Frame { OtaManager* destination; std::vector<uint8_t> bytes; OtaReplyRoute route; };
|
||||
struct End { DirectManagerBus* bus; OtaManager* sender; OtaManager* destination; };
|
||||
OtaManager server, client;
|
||||
OtaStoreRam<16384> store;
|
||||
End from_server{this, &server, &client}, from_client{this, &client, &server};
|
||||
std::vector<Frame> queue;
|
||||
std::vector<std::vector<uint8_t>> direct_requests;
|
||||
std::vector<Frame> requests;
|
||||
std::vector<uint32_t> request_times;
|
||||
std::vector<Frame> data;
|
||||
bool downgrade_probe = false;
|
||||
bool drop_one = false;
|
||||
bool dropped = false;
|
||||
bool lose_direct_after_first_block = false;
|
||||
unsigned drop_direct_requests_after_first_block = 0;
|
||||
unsigned reject_direct_requests_after_first_block = 0;
|
||||
unsigned dropped_direct_requests = 0;
|
||||
unsigned rejected_direct_requests = 0;
|
||||
unsigned legacy_requests = 0;
|
||||
unsigned direct_proofs = 0;
|
||||
uint32_t now = 0;
|
||||
|
||||
static bool send(void* context, const uint8_t* bytes, uint16_t length, bool) {
|
||||
End& end = *static_cast<End*>(context);
|
||||
DirectManagerBus& bus = *end.bus;
|
||||
OtaReplyRoute route = end.sender->replyRoute();
|
||||
const bool direct = route.direct;
|
||||
EXPECT_LE(length, direct ? OTA_DIRECT_MESSAGE_MAX : MAX_PACKET_PAYLOAD);
|
||||
route.profile = 1;
|
||||
route.generation = 19;
|
||||
if (bytes[0] == OTA_REQ) {
|
||||
if (direct && bus.client.blocksHave() != 0 &&
|
||||
bus.reject_direct_requests_after_first_block != 0) {
|
||||
--bus.reject_direct_requests_after_first_block;
|
||||
++bus.rejected_direct_requests;
|
||||
return false;
|
||||
}
|
||||
if (direct) bus.direct_requests.emplace_back(bytes, bytes + length);
|
||||
else ++bus.legacy_requests;
|
||||
bus.requests.push_back({end.destination, {bytes, bytes + length}, route});
|
||||
bus.request_times.push_back(bus.now);
|
||||
if (direct && bus.client.blocksHave() != 0 &&
|
||||
(bus.lose_direct_after_first_block || bus.drop_direct_requests_after_first_block)) {
|
||||
if (bus.drop_direct_requests_after_first_block) --bus.drop_direct_requests_after_first_block;
|
||||
++bus.dropped_direct_requests;
|
||||
return true;
|
||||
}
|
||||
if (direct && bus.downgrade_probe) route.direct = false;
|
||||
}
|
||||
if (direct && bus.lose_direct_after_first_block && bus.client.blocksHave() != 0) {
|
||||
return true;
|
||||
}
|
||||
Frame frame{end.destination, {bytes, bytes + length}, route};
|
||||
if (bytes[0] == OTA_DATA) {
|
||||
bus.data.push_back(frame);
|
||||
if (bus.drop_one && direct && !bus.dropped) {
|
||||
bus.dropped = true;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
if (bytes[0] == OTA_PROOF && direct) ++bus.direct_proofs;
|
||||
bus.queue.push_back(std::move(frame));
|
||||
return true;
|
||||
}
|
||||
|
||||
void begin(const uint8_t* mota, uint32_t length, bool direct_client = true,
|
||||
bool direct_server = true, uint8_t hops = 0) {
|
||||
server.begin(0, send, &from_server);
|
||||
client.begin(SIM_TARGET_ID, send, &from_client);
|
||||
server.set_direct_transport_enabled(direct_server);
|
||||
client.set_direct_transport_enabled(direct_client);
|
||||
client.set_max_hops(hops);
|
||||
client.set_fetch_store(&store);
|
||||
server.set_clock(now); client.set_clock(now);
|
||||
ASSERT_TRUE(server.serve(mota, length));
|
||||
}
|
||||
|
||||
void pull(const MotaManifest& manifest) {
|
||||
ASSERT_EQ(client.pull(manifest.merkle_root, manifest.target_id), OtaManager::PULL_STARTED);
|
||||
}
|
||||
|
||||
void deliver() {
|
||||
unsigned bounded = 1000;
|
||||
while (!queue.empty() && bounded--) {
|
||||
Frame frame = std::move(queue.front());
|
||||
queue.erase(queue.begin());
|
||||
frame.destination->note_rx_path_hops(0);
|
||||
frame.destination->on_message(frame.bytes.data(), frame.bytes.size(), frame.route);
|
||||
}
|
||||
ASSERT_GT(bounded, 0u);
|
||||
}
|
||||
|
||||
void tick() {
|
||||
server.set_clock(now); client.set_clock(now);
|
||||
server.serviceEgress(); client.serviceEgress();
|
||||
deliver();
|
||||
server.loop(); client.loop();
|
||||
deliver();
|
||||
now += 10;
|
||||
}
|
||||
|
||||
void finish(const uint8_t* expected, uint32_t length) {
|
||||
for (unsigned i = 0; i < 30000 && client.fetchState() != OtaManager::COMPLETE &&
|
||||
client.fetchState() != OtaManager::FAILED; ++i) tick();
|
||||
ASSERT_EQ(client.fetchState(), OtaManager::COMPLETE);
|
||||
ASSERT_EQ(store.staged_size(), length);
|
||||
EXPECT_EQ(0, memcmp(store.data(), expected, length));
|
||||
EXPECT_EQ(client.blocksHave(), client.blocksTotal());
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
TEST(OtaDirectManager, RoutePaddingAndLegacyPayloadCapacityAreUnchanged) {
|
||||
EXPECT_EQ(sizeof(OtaReplyRoute), 8u);
|
||||
EXPECT_EQ(MAX_PACKET_PAYLOAD, 184);
|
||||
EXPECT_EQ(OTA_MAX_BLOCK, 2048);
|
||||
EXPECT_EQ(OTA_DIRECT_FRAG_DATA, 240);
|
||||
OtaReplyRoute normal;
|
||||
OtaReplyRoute direct = normal; direct.direct = true;
|
||||
EXPECT_FALSE(normal == direct);
|
||||
}
|
||||
|
||||
TEST(OtaDirectManager, RawOneAndTwoKiBBlocksUseFullDirectMtu) {
|
||||
for (const auto& vector : {std::make_pair(SIM_MOTA_1K, SIM_MOTA_1K_LEN),
|
||||
std::make_pair(SIM_MOTA_2K, SIM_MOTA_2K_LEN)}) {
|
||||
DirectManagerBus bus;
|
||||
MotaManifest manifest;
|
||||
ASSERT_TRUE(mota_parse(vector.first, vector.second, manifest));
|
||||
bus.begin(vector.first, vector.second);
|
||||
bus.pull(manifest);
|
||||
bus.finish(vector.first, vector.second);
|
||||
EXPECT_TRUE(bus.client.directFetchConfirmed());
|
||||
EXPECT_FALSE(bus.direct_requests.empty());
|
||||
EXPECT_EQ(bus.direct_proofs, manifest.block_count);
|
||||
bool full = false;
|
||||
for (const auto& frame : bus.data) {
|
||||
EXPECT_TRUE(frame.route.direct);
|
||||
if (frame.bytes.size() == OTA_DIRECT_MESSAGE_MAX) full = true;
|
||||
}
|
||||
EXPECT_TRUE(full);
|
||||
}
|
||||
}
|
||||
|
||||
TEST(OtaDirectManager, CompressionAndRawTailRetainMerkleIntegrity) {
|
||||
DirectManagerBus bus;
|
||||
MotaManifest manifest;
|
||||
ASSERT_TRUE(mota_parse(SIM_MOTA_2K, SIM_MOTA_2K_LEN, manifest));
|
||||
bus.begin(SIM_MOTA_2K, SIM_MOTA_2K_LEN);
|
||||
VectorDeflateCodec codec{&manifest};
|
||||
bus.server.set_transport_deflate_encoder(vector_2k_wire_encode, &codec);
|
||||
bus.client.set_transport_deflate_decoder(ota_transport_inflate);
|
||||
bus.pull(manifest);
|
||||
bus.finish(SIM_MOTA_2K, SIM_MOTA_2K_LEN);
|
||||
EXPECT_GT(codec.calls, 0u);
|
||||
EXPECT_TRUE(bus.client.directFetchConfirmed());
|
||||
}
|
||||
|
||||
TEST(OtaDirectManager, CompressedOneKiBRetainsDirectIdentityAndProofs) {
|
||||
DirectManagerBus bus;
|
||||
MotaManifest manifest;
|
||||
ASSERT_TRUE(mota_parse(SIM_MOTA_1K, SIM_MOTA_1K_LEN, manifest));
|
||||
bus.begin(SIM_MOTA_1K, SIM_MOTA_1K_LEN);
|
||||
TestWireCodec codec{&manifest};
|
||||
bus.server.set_transport_deflate_encoder(test_wire_encode, &codec);
|
||||
bus.client.set_transport_deflate_decoder(test_wire_decode, &codec);
|
||||
bus.pull(manifest);
|
||||
bus.finish(SIM_MOTA_1K, SIM_MOTA_1K_LEN);
|
||||
EXPECT_TRUE(bus.client.directFetchConfirmed());
|
||||
EXPECT_GT(codec.calls, 0u);
|
||||
}
|
||||
|
||||
TEST(OtaDirectManager, OldSourceDropsProbeThenUses171ByteFallback) {
|
||||
DirectManagerBus bus;
|
||||
MotaManifest manifest;
|
||||
ASSERT_TRUE(mota_parse(SIM_MOTA_2K, SIM_MOTA_2K_LEN, manifest));
|
||||
bus.begin(SIM_MOTA_2K, SIM_MOTA_2K_LEN, true, false);
|
||||
bus.pull(manifest);
|
||||
bus.finish(SIM_MOTA_2K, SIM_MOTA_2K_LEN);
|
||||
EXPECT_EQ(bus.direct_requests.size(), 1u);
|
||||
EXPECT_GT(bus.legacy_requests, 0u);
|
||||
EXPECT_FALSE(bus.client.directFetchActive());
|
||||
EXPECT_EQ(bus.client.directFetchRoute().profile, 1);
|
||||
EXPECT_EQ(bus.client.directFetchRoute().generation, 19u);
|
||||
for (const auto& frame : bus.data) {
|
||||
EXPECT_FALSE(frame.route.direct);
|
||||
EXPECT_LE(frame.bytes.size(), 184u);
|
||||
}
|
||||
}
|
||||
|
||||
TEST(OtaDirectManager, SourceVanishingAfterCommittedBlockFallsBackWithoutRewritingIt) {
|
||||
DirectManagerBus bus;
|
||||
MotaManifest manifest;
|
||||
ASSERT_TRUE(mota_parse(SIM_MOTA_2K, SIM_MOTA_2K_LEN, manifest));
|
||||
bus.begin(SIM_MOTA_2K, SIM_MOTA_2K_LEN);
|
||||
bus.lose_direct_after_first_block = true;
|
||||
bus.pull(manifest);
|
||||
for (unsigned i = 0; i < 1000 && bus.client.blocksHave() == 0; ++i) bus.tick();
|
||||
ASSERT_EQ(bus.client.blocksHave(), 1u);
|
||||
const uint32_t epoch = bus.client.directTransportEpoch();
|
||||
bus.finish(SIM_MOTA_2K, SIM_MOTA_2K_LEN);
|
||||
EXPECT_FALSE(bus.client.directFetchActive());
|
||||
EXPECT_NE(bus.client.directTransportEpoch(), epoch);
|
||||
ASSERT_EQ(bus.direct_requests.size(), 3u); // first block, next flight, one same-mode sparse retry
|
||||
EXPECT_EQ(bus.dropped_direct_requests, 2u);
|
||||
ASSERT_GE(bus.requests.size(), 4u);
|
||||
EXPECT_GE(uint32_t(bus.request_times[2] - bus.request_times[1]), OTA_FETCH_RETRY_FALLBACK_MS);
|
||||
EXPECT_GE(uint32_t(bus.request_times[3] - bus.request_times[2]), OTA_FETCH_RETRY_FALLBACK_MS);
|
||||
for (size_t i = 1; i < bus.requests.size(); ++i) {
|
||||
ReqWindowMsg request{};
|
||||
ASSERT_TRUE(decode_req_window(bus.requests[i].bytes.data(), bus.requests[i].bytes.size(), request));
|
||||
for (uint8_t item = 0; item < request.n_items; ++item) EXPECT_NE(request.items[item].block_idx, 0u);
|
||||
}
|
||||
bool saw_normal = false;
|
||||
for (const auto& frame : bus.data) {
|
||||
if (!frame.route.direct) {
|
||||
saw_normal = true;
|
||||
DataMsg message{};
|
||||
ASSERT_TRUE(decode_data(frame.bytes.data(), frame.bytes.size(), message));
|
||||
EXPECT_NE(message.block_idx, 0u);
|
||||
}
|
||||
}
|
||||
EXPECT_TRUE(saw_normal);
|
||||
}
|
||||
|
||||
TEST(OtaDirectManager, ConfirmedEmptyFlightsRetryWideAndResetGraceAfterProgress) {
|
||||
for (uint32_t started : {0u, UINT32_MAX - 2000u}) {
|
||||
DirectManagerBus bus;
|
||||
bus.now = started;
|
||||
MotaManifest manifest;
|
||||
ASSERT_TRUE(mota_parse(SIM_MOTA_1K, SIM_MOTA_1K_LEN, manifest));
|
||||
ASSERT_EQ(manifest.block_count, 3u);
|
||||
bus.begin(SIM_MOTA_1K, SIM_MOTA_1K_LEN);
|
||||
bus.drop_direct_requests_after_first_block = 1;
|
||||
bus.pull(manifest);
|
||||
bus.finish(SIM_MOTA_1K, SIM_MOTA_1K_LEN);
|
||||
EXPECT_TRUE(bus.client.directFetchConfirmed());
|
||||
EXPECT_EQ(bus.legacy_requests, 0u);
|
||||
EXPECT_EQ(bus.dropped_direct_requests, 1u);
|
||||
ASSERT_EQ(bus.direct_requests.size(), 4u);
|
||||
// The lost two-block flight is repaired one slot per deadline. Progress on
|
||||
// block 1 must renew the grace for still-empty block 2, not downgrade it.
|
||||
const uint8_t expected_items[] = {1, 2, 1, 1};
|
||||
const uint16_t expected_first[] = {0, 1, 1, 2};
|
||||
for (size_t i = 0; i < bus.direct_requests.size(); ++i) {
|
||||
ReqWindowMsg request{};
|
||||
const auto& bytes = bus.direct_requests[i];
|
||||
ASSERT_TRUE(decode_req_window(bytes.data(), bytes.size(), request));
|
||||
EXPECT_EQ(request.n_items, expected_items[i]);
|
||||
EXPECT_EQ(request.items[0].block_idx, expected_first[i]);
|
||||
}
|
||||
for (const auto& frame : bus.data) EXPECT_TRUE(frame.route.direct);
|
||||
EXPECT_EQ(bus.client.directFetchRoute().profile, 1);
|
||||
EXPECT_EQ(bus.client.directFetchRoute().generation, 19u);
|
||||
}
|
||||
}
|
||||
|
||||
TEST(OtaDirectManager, ConfirmedEmptyRetryAdmissionDoesNotConsumeGrace) {
|
||||
DirectManagerBus bus;
|
||||
MotaManifest manifest;
|
||||
ASSERT_TRUE(mota_parse(SIM_MOTA_2K, SIM_MOTA_2K_LEN, manifest));
|
||||
bus.begin(SIM_MOTA_2K, SIM_MOTA_2K_LEN);
|
||||
bus.lose_direct_after_first_block = true;
|
||||
bus.pull(manifest);
|
||||
for (unsigned i = 0; i < 1000 && bus.client.blocksHave() == 0; ++i) bus.tick();
|
||||
ASSERT_EQ(bus.client.blocksHave(), 1u);
|
||||
ASSERT_TRUE(bus.client.directFetchConfirmed());
|
||||
ASSERT_EQ(bus.direct_requests.size(), 2u);
|
||||
const uint32_t epoch = bus.client.directTransportEpoch();
|
||||
bus.reject_direct_requests_after_first_block = 3;
|
||||
bus.now += bus.client.fetchRetryTimeoutMs();
|
||||
for (unsigned i = 1; i <= 3; ++i) {
|
||||
bus.tick();
|
||||
EXPECT_EQ(bus.rejected_direct_requests, i);
|
||||
EXPECT_EQ(bus.direct_requests.size(), 2u);
|
||||
EXPECT_EQ(bus.legacy_requests, 0u);
|
||||
EXPECT_TRUE(bus.client.directFetchConfirmed());
|
||||
EXPECT_EQ(bus.client.directTransportEpoch(), epoch);
|
||||
}
|
||||
bus.tick(); // one accepted wide retry; its RF loss must use a fresh deadline
|
||||
ASSERT_EQ(bus.direct_requests.size(), 3u);
|
||||
bus.tick();
|
||||
EXPECT_EQ(bus.direct_requests.size(), 3u);
|
||||
EXPECT_EQ(bus.legacy_requests, 0u);
|
||||
EXPECT_TRUE(bus.client.directFetchConfirmed());
|
||||
bus.finish(SIM_MOTA_2K, SIM_MOTA_2K_LEN);
|
||||
EXPECT_FALSE(bus.client.directFetchActive());
|
||||
EXPECT_EQ(bus.direct_requests.size(), 3u);
|
||||
EXPECT_NE(bus.client.directTransportEpoch(), epoch);
|
||||
}
|
||||
|
||||
TEST(OtaDirectManager, ConfirmedEmptyRetryCannotOutliveItsRadioSession) {
|
||||
DirectManagerBus bus;
|
||||
MotaManifest manifest;
|
||||
ASSERT_TRUE(mota_parse(SIM_MOTA_2K, SIM_MOTA_2K_LEN, manifest));
|
||||
bus.begin(SIM_MOTA_2K, SIM_MOTA_2K_LEN);
|
||||
bus.lose_direct_after_first_block = true;
|
||||
bus.pull(manifest);
|
||||
for (unsigned i = 0; i < 1000 && bus.client.blocksHave() == 0; ++i) bus.tick();
|
||||
ASSERT_EQ(bus.client.blocksHave(), 1u);
|
||||
bus.now += bus.client.fetchRetryTimeoutMs();
|
||||
bus.tick();
|
||||
ASSERT_EQ(bus.direct_requests.size(), 3u);
|
||||
ASSERT_TRUE(bus.client.directFetchConfirmed());
|
||||
const uint32_t epoch = bus.client.directTransportEpoch();
|
||||
bus.client.serviceEgress([](void*, const OtaReplyRoute&) { return false; }, nullptr);
|
||||
EXPECT_EQ(bus.client.fetchState(), OtaManager::FAILED);
|
||||
EXPECT_EQ(bus.client.fetchError(), OtaManager::FETCH_ERROR_RADIO_SESSION);
|
||||
EXPECT_NE(bus.client.directTransportEpoch(), epoch);
|
||||
bus.now += OTA_FETCH_RETRY_FALLBACK_MS;
|
||||
bus.tick();
|
||||
EXPECT_EQ(bus.direct_requests.size(), 3u);
|
||||
EXPECT_EQ(bus.legacy_requests, 0u);
|
||||
}
|
||||
|
||||
TEST(OtaDirectManager, CanonicalNormalAnswerBeforeConfirmationDowngradesWholeFlight) {
|
||||
DirectManagerBus bus;
|
||||
MotaManifest manifest;
|
||||
ASSERT_TRUE(mota_parse(SIM_MOTA_1K, SIM_MOTA_1K_LEN, manifest));
|
||||
bus.begin(SIM_MOTA_1K, SIM_MOTA_1K_LEN);
|
||||
bus.downgrade_probe = true;
|
||||
bus.pull(manifest);
|
||||
bus.finish(SIM_MOTA_1K, SIM_MOTA_1K_LEN);
|
||||
EXPECT_EQ(bus.direct_requests.size(), 1u);
|
||||
EXPECT_FALSE(bus.client.directFetchActive());
|
||||
}
|
||||
|
||||
TEST(OtaDirectManager, FeatureOffAndRoutedSettingsNeverProbe) {
|
||||
for (unsigned mode = 0; mode < 2; ++mode) {
|
||||
DirectManagerBus bus;
|
||||
MotaManifest manifest;
|
||||
ASSERT_TRUE(mota_parse(SIM_MOTA_1K, SIM_MOTA_1K_LEN, manifest));
|
||||
bus.begin(SIM_MOTA_1K, SIM_MOTA_1K_LEN, mode != 0, true, mode ? 1 : 0);
|
||||
bus.pull(manifest);
|
||||
bus.finish(SIM_MOTA_1K, SIM_MOTA_1K_LEN);
|
||||
EXPECT_TRUE(bus.direct_requests.empty());
|
||||
}
|
||||
}
|
||||
|
||||
TEST(OtaDirectManager, LostDirectFragmentRecoversOnlyHolesAndWorksAcrossRollover) {
|
||||
DirectManagerBus bus;
|
||||
bus.now = UINT32_MAX - 200;
|
||||
MotaManifest manifest;
|
||||
ASSERT_TRUE(mota_parse(SIM_MOTA_2K, SIM_MOTA_2K_LEN, manifest));
|
||||
bus.begin(SIM_MOTA_2K, SIM_MOTA_2K_LEN);
|
||||
bus.drop_one = true;
|
||||
bus.pull(manifest);
|
||||
bus.finish(SIM_MOTA_2K, SIM_MOTA_2K_LEN);
|
||||
ASSERT_GT(bus.direct_requests.size(), 1u);
|
||||
bool recovered_one = false;
|
||||
for (const auto& bytes : bus.direct_requests) {
|
||||
ReqWindowMsg request{};
|
||||
ASSERT_TRUE(decode_req_window(bytes.data(), bytes.size(), request));
|
||||
if (request.n_items == 1 && ota_req_v2_fragments(request.items[0].want_mask) == 1u)
|
||||
recovered_one = true;
|
||||
}
|
||||
EXPECT_TRUE(recovered_one);
|
||||
EXPECT_TRUE(bus.client.directFetchConfirmed());
|
||||
}
|
||||
|
||||
TEST(OtaDirectManager, ConfirmedDirectRejectsNormalMetadataAndExpiredSession) {
|
||||
DirectManagerBus bus;
|
||||
MotaManifest manifest;
|
||||
ASSERT_TRUE(mota_parse(SIM_MOTA_2K, SIM_MOTA_2K_LEN, manifest));
|
||||
bus.begin(SIM_MOTA_2K, SIM_MOTA_2K_LEN);
|
||||
bus.pull(manifest);
|
||||
for (unsigned i = 0; i < 100 && bus.data.empty(); ++i) bus.tick();
|
||||
ASSERT_FALSE(bus.data.empty());
|
||||
ASSERT_TRUE(bus.client.directFetchConfirmed());
|
||||
const auto& frame = bus.data.front();
|
||||
OtaReplyRoute normal = frame.route; normal.direct = false;
|
||||
EXPECT_FALSE(bus.client.on_message(frame.bytes.data(), frame.bytes.size(), normal));
|
||||
OtaReplyRoute stale = frame.route; ++stale.generation;
|
||||
EXPECT_FALSE(bus.client.on_message(frame.bytes.data(), frame.bytes.size(), stale));
|
||||
EXPECT_FALSE(bus.client.on_message(frame.bytes.data(), frame.bytes.size() - 1, frame.route));
|
||||
auto oversized = frame.bytes; oversized.push_back(0);
|
||||
EXPECT_FALSE(bus.client.on_message(oversized.data(), oversized.size(), frame.route));
|
||||
const uint32_t epoch = bus.client.directTransportEpoch();
|
||||
bus.client.serviceEgress([](void*, const OtaReplyRoute&) { return false; }, nullptr);
|
||||
EXPECT_EQ(bus.client.fetchState(), OtaManager::FAILED);
|
||||
EXPECT_EQ(bus.client.fetchError(), OtaManager::FETCH_ERROR_RADIO_SESSION);
|
||||
EXPECT_NE(bus.client.directTransportEpoch(), epoch);
|
||||
}
|
||||
|
||||
TEST(OtaDirectManager, EpochRetiresClearResetRecreatedContextsAndNeverUsesZero) {
|
||||
uint32_t previous = 0;
|
||||
{
|
||||
OtaManager manager;
|
||||
previous = manager.directTransportEpoch();
|
||||
EXPECT_NE(previous, 0u);
|
||||
manager.clearPendingEgress();
|
||||
EXPECT_NE(manager.directTransportEpoch(), previous);
|
||||
previous = manager.directTransportEpoch();
|
||||
manager.reset_session();
|
||||
EXPECT_NE(manager.directTransportEpoch(), previous);
|
||||
previous = manager.directTransportEpoch();
|
||||
}
|
||||
OtaManager replacement;
|
||||
EXPECT_NE(replacement.directTransportEpoch(), previous);
|
||||
EXPECT_EQ(ota_advance_direct_epoch(UINT32_MAX), 1u);
|
||||
EXPECT_EQ(ota_advance_direct_epoch(0), 1u);
|
||||
}
|
||||
|
||||
TEST(OtaDirectManager, CompletionAndDirectPauseRetireAdmittedRawFrames) {
|
||||
for (bool pause : {false, true}) {
|
||||
DirectManagerBus bus;
|
||||
MotaManifest manifest;
|
||||
ASSERT_TRUE(mota_parse(SIM_MOTA_1K, SIM_MOTA_1K_LEN, manifest));
|
||||
bus.begin(SIM_MOTA_1K, SIM_MOTA_1K_LEN);
|
||||
bus.pull(manifest);
|
||||
for (unsigned i = 0; i < 100 && !bus.client.directFetchConfirmed(); ++i) bus.tick();
|
||||
ASSERT_TRUE(bus.client.directFetchConfirmed());
|
||||
const uint32_t epoch = bus.client.directTransportEpoch();
|
||||
if (pause) {
|
||||
ASSERT_TRUE(bus.client.pauseFetchForDisconnect());
|
||||
EXPECT_EQ(bus.client.fetchState(), OtaManager::PAUSED);
|
||||
} else {
|
||||
bus.finish(SIM_MOTA_1K, SIM_MOTA_1K_LEN);
|
||||
}
|
||||
EXPECT_NE(bus.client.directTransportEpoch(), epoch);
|
||||
}
|
||||
}
|
||||
|
||||
namespace {
|
||||
class PrecompressedSource : public RamMotaSource {
|
||||
public:
|
||||
explicit PrecompressedSource(const MotaManifest& manifest) : m(manifest) {
|
||||
add(SIM_MOTA_1K, SIM_MOTA_1K_LEN);
|
||||
setSourceCaps(MOTA_SOURCE_CAP_DEFLATE_BLOCK);
|
||||
}
|
||||
MotaManifest m;
|
||||
unsigned raw_reads = 0, encoded_reads = 0;
|
||||
int bad = 0;
|
||||
bool read(uint8_t idx, uint32_t off, uint8_t* out, uint32_t len) override {
|
||||
if (off >= uint32_t(m.payload - SIM_MOTA_1K) && len) ++raw_reads;
|
||||
return RamMotaSource::read(idx, off, out, len);
|
||||
}
|
||||
bool read_deflated_block(uint8_t, uint16_t block, uint8_t* out,
|
||||
uint16_t cap, uint16_t* length) override {
|
||||
++encoded_reads;
|
||||
if (bad) { *length = bad == 1 ? 0 : (bad == 3 ? cap + 1 : cap); return bad != 4; }
|
||||
out[0] = 0xD1; out[1] = uint8_t(block); *length = 2;
|
||||
return true;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
TEST(OtaDirectManager, HostPrecompressedFirstAvoidsRedundantRawHostReads) {
|
||||
for (int bad : {0, 1, 2, 3, 4}) {
|
||||
DirectManagerBus bus;
|
||||
MotaManifest manifest;
|
||||
ASSERT_TRUE(mota_parse(SIM_MOTA_1K, SIM_MOTA_1K_LEN, manifest));
|
||||
bus.begin(SIM_MOTA_1K, SIM_MOTA_1K_LEN);
|
||||
bus.server.clear_primary();
|
||||
PrecompressedSource source(manifest); source.bad = bad;
|
||||
ASSERT_TRUE(bus.server.add_source(&source));
|
||||
TestWireCodec codec{&manifest};
|
||||
bus.client.set_transport_deflate_decoder(test_wire_decode, &codec);
|
||||
bus.pull(manifest);
|
||||
bus.finish(SIM_MOTA_1K, SIM_MOTA_1K_LEN);
|
||||
EXPECT_GT(source.encoded_reads, 0u);
|
||||
if (bad) EXPECT_GT(source.raw_reads, 0u);
|
||||
else EXPECT_EQ(source.raw_reads, 0u);
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
"""Exercise the actual outlined OTA dispatch/listing with the real name decoder."""
|
||||
"""Exercise real OTA listing, direct-transfer status, and the name decoder."""
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Run the actual complete OTA core suite without invoking PlatformIO."""
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
class OtaDirectManagerTests(unittest.TestCase):
|
||||
def test_actual_ota_core_with_direct_interop_and_sanitizers(self):
|
||||
googletest = ROOT / ".pio/libdeps/native/googletest/googletest"
|
||||
self.assertTrue(googletest.is_dir())
|
||||
with tempfile.TemporaryDirectory(prefix="ota-direct-core-") as directory:
|
||||
directory = Path(directory)
|
||||
objects = []
|
||||
flags = ["-fsanitize=address,undefined", "-fno-sanitize-recover=all",
|
||||
"-fno-pie", "-no-pie", "-g", "-O1"]
|
||||
for source in ("OtaTinf.c", "detools/detools.c"):
|
||||
obj = directory / (Path(source).name + ".o")
|
||||
built = subprocess.run([
|
||||
"gcc", "-DOTA_TRANSPORT_DEFLATE_TEST=1", *flags,
|
||||
"-c", str(ROOT / "src/helpers/ota" / source), "-o", str(obj)],
|
||||
capture_output=True, text=True)
|
||||
self.assertEqual(built.returncode, 0, built.stdout + built.stderr)
|
||||
objects.append(str(obj))
|
||||
sources = ("OtaManager.cpp", "OtaProtocol.cpp", "MotaContainer.cpp",
|
||||
"MerkleTree.cpp", "FirmwareInfo.cpp", "OtaDeflate.cpp",
|
||||
"OtaApply.cpp", "MotaSourceSerial.cpp", "FolderMotaStore.cpp")
|
||||
binary = directory / "ota-core"
|
||||
built = subprocess.run([
|
||||
"g++", "-std=c++17", "-pthread", *flags,
|
||||
"-DOTA_TRANSPORT_DEFLATE_TEST=1", "-DOTA_FETCH_PIPELINE=4",
|
||||
"-I", str(ROOT / "src"), "-I", str(ROOT / "test/mocks"),
|
||||
"-I", str(googletest / "include"), "-I", str(googletest),
|
||||
str(ROOT / "test/test_ota/test_ota_core.cpp"),
|
||||
*[str(ROOT / "src/helpers/ota" / source) for source in sources],
|
||||
str(ROOT / "src/Utils.cpp"), str(googletest / "src/gtest-all.cc"),
|
||||
*objects, "-o", str(binary)], capture_output=True, text=True, timeout=180)
|
||||
self.assertEqual(built.returncode, 0, built.stdout + built.stderr)
|
||||
checked = subprocess.run([str(binary), "--gtest_brief=1"],
|
||||
capture_output=True, text=True, timeout=90)
|
||||
self.assertEqual(checked.returncode, 0, checked.stdout + checked.stderr)
|
||||
print(checked.stdout.strip())
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,472 @@
|
||||
"""Exercise direct OTA wire framing and the real bounded Dispatcher owner.
|
||||
|
||||
These native host tests do not transmit RF, invoke PlatformIO, or claim that a
|
||||
hosted modem delivered a frame. OtaManager negotiation/geometry has separate
|
||||
coverage; this file tests the scheduler and its admission-policy boundary.
|
||||
"""
|
||||
from pathlib import Path
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
from test_meshtext_transport import HARNESS as TRANSPORT_HARNESS
|
||||
from test_radio_receive_contract import method
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def dispatcher_harness():
|
||||
code = TRANSPORT_HARNESS.split("int main() {", 1)[0]
|
||||
code = code.replace(
|
||||
"#include <Dispatcher.h>",
|
||||
"#include <Dispatcher.h>\n#include <helpers/ota/OtaDirectWire.h>\n"
|
||||
"#include <helpers/ota/OtaTiming.h>\n#include <cstdio>",
|
||||
)
|
||||
code = code.replace(
|
||||
"bool incoming=false;",
|
||||
"bool incoming=false; uint32_t rx_generation=0; std::vector<uint8_t> rx;",
|
||||
)
|
||||
code = code.replace(
|
||||
"uint8_t receiveProfile() const override { return active; }",
|
||||
"uint8_t receiveProfile() const override { return active; }\n"
|
||||
" uint32_t receiveProfileGeneration() const override {\n"
|
||||
" return rx_generation ? rx_generation : p.generation[active];\n }",
|
||||
)
|
||||
start = code.index(" int recvRaw(")
|
||||
end = code.index(" void onReceiveProcessed()", start)
|
||||
code = code[:start] + r'''
|
||||
int recvRaw(uint8_t* bytes,int capacity) override {
|
||||
if (!incoming) return 0;
|
||||
incoming=false;
|
||||
assert(rx.size()<=size_t(capacity));
|
||||
if (!rx.empty()) memcpy(bytes,rx.data(),rx.size());
|
||||
return int(rx.size());
|
||||
}
|
||||
''' + code[end:]
|
||||
code = code.replace(
|
||||
"bool allow_foreign=true;",
|
||||
"bool allow_foreign=true, allow_direct=false;\n"
|
||||
" unsigned direct_calls=0, direct_rx=0; float speed=1; uint32_t epoch=1;\n"
|
||||
" std::vector<uint8_t> direct_message;",
|
||||
)
|
||||
code = code.replace(
|
||||
"using Dispatcher::queueForeignRadioFrame;",
|
||||
"using Dispatcher::queueForeignRadioFrame;\n"
|
||||
" using Dispatcher::discardQueuedForeignRadioFrame;\n"
|
||||
"#if MESH_ENABLE_OTA_KISS_DIRECT\n"
|
||||
" using Dispatcher::queueDirectOtaRadioFrame;\n"
|
||||
" uint32_t directOtaEpoch() const override { return epoch; }\n"
|
||||
" bool allowDirectOtaTransmit(uint8_t,uint32_t) const override { return allow_direct; }\n"
|
||||
" bool onDirectOtaRadioFrame(const uint8_t* b,size_t n,uint8_t,uint32_t) override {\n"
|
||||
" ++direct_calls; const uint8_t* msg=nullptr;uint16_t size=0;\n"
|
||||
" if (!allow_direct || !ota::ota_direct_wire_decode(b,n,msg,size)) return false;\n"
|
||||
" ++direct_rx;direct_message.assign(msg,msg+size);return true;\n"
|
||||
" }\n#endif\n"
|
||||
" float getOtaPacketSpeedFactor() const override { return speed; }",
|
||||
)
|
||||
code += r'''
|
||||
static void directProfile(Fixture& f,uint8_t profile=1) {
|
||||
f.radio.p.secondary.params.protocol=RadioProfileProtocol::MeshCore;
|
||||
f.radio.p.secondary.params.preamble=32;
|
||||
f.radio.p.primary_temporary=profile==0;
|
||||
f.radio.p.secondary_temporary=profile==1;
|
||||
f.d.allow_direct=true;
|
||||
}
|
||||
#if MESH_ENABLE_OTA_KISS_DIRECT
|
||||
static bool enqueue(Fixture& f,uint8_t profile=1) {
|
||||
const uint8_t msg[]={ota::OTA_REQ,0xc0,0xdb};
|
||||
return f.d.queueDirectOtaRadioFrame(msg,sizeof(msg),profile,f.radio.p.generation[profile]);
|
||||
}
|
||||
#endif
|
||||
static void receive(Fixture& f,const std::vector<uint8_t>& frame,uint8_t profile=1) {
|
||||
f.radio.active=profile;f.radio.rx=frame;f.radio.incoming=true;f.tick();
|
||||
}
|
||||
'''
|
||||
return code
|
||||
|
||||
|
||||
class OtaKissDirectTest(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.compiler = os.environ.get("CXX") or shutil.which("g++") or shutil.which("clang++")
|
||||
if not cls.compiler:
|
||||
raise unittest.SkipTest("a host C++17 compiler is required")
|
||||
|
||||
def compile_run(self, code, flags=(), dispatcher=False, expect_compile=True):
|
||||
with tempfile.TemporaryDirectory(prefix="meshcore-ota-kiss-direct-") as folder:
|
||||
cpp, binary = Path(folder) / "test.cpp", Path(folder) / "test.exe"
|
||||
cpp.write_text(code, encoding="utf-8")
|
||||
command = [self.compiler, "-std=c++17", "-Wall", "-Wextra", *flags]
|
||||
if os.name != "nt":
|
||||
command += ["-fsanitize=address,undefined", "-fno-omit-frame-pointer", "-fno-pie", "-no-pie"]
|
||||
command += ["-I", str(ROOT / "test/mocks"), "-I", str(ROOT / "src")]
|
||||
if dispatcher:
|
||||
command += [str(ROOT / source) for source in (
|
||||
"src/Dispatcher.cpp", "src/Packet.cpp", "src/helpers/StaticPoolPacketManager.cpp")]
|
||||
command += [str(cpp), "-o", str(binary)]
|
||||
result = subprocess.run(command, capture_output=True, text=True, timeout=60)
|
||||
if not expect_compile:
|
||||
self.assertNotEqual(result.returncode, 0, "invalid configuration unexpectedly compiled")
|
||||
return result.stdout + result.stderr
|
||||
self.assertEqual(result.returncode, 0, (result.stdout + result.stderr)[-16000:])
|
||||
env = os.environ.copy()
|
||||
env["ASAN_OPTIONS"] = env.get("ASAN_OPTIONS", "") + ":detect_leaks=0"
|
||||
result = subprocess.run([str(binary)], capture_output=True, text=True, timeout=20, env=env)
|
||||
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
|
||||
return result.stdout
|
||||
|
||||
def test_wire_full_frame_binary_escaping_and_rejection(self):
|
||||
code = r'''
|
||||
#include <helpers/ota/OtaDirectWire.h>
|
||||
#include <helpers/EthernetKiss.h>
|
||||
#include <cassert>
|
||||
#include <vector>
|
||||
using namespace mesh;
|
||||
int main() {
|
||||
static_assert(ota::OTA_DIRECT_FRAG_DATA==240,"full data budget");
|
||||
uint8_t message[253];message[0]=ota::OTA_DATA;
|
||||
for (unsigned i=1;i<sizeof(message);++i) message[i]=uint8_t(i);
|
||||
message[1]=0xc0;message[2]=0xdb;message[3]=0;
|
||||
uint8_t raw[256]={};
|
||||
assert(ota::ota_direct_wire_encode(raw,255,message,sizeof(message))==255);
|
||||
assert(raw[0]==0xf2 && raw[1]==0);
|
||||
const uint8_t* decoded=nullptr;uint16_t length=0;
|
||||
assert(ota::ota_direct_wire_decode(raw,255,decoded,length));
|
||||
assert(length==253 && !memcmp(decoded,message,length));
|
||||
// Verify KISS quoting round trips the complete RF255, including both escapes.
|
||||
ethernet::KissCodec sender,receiver;
|
||||
assert(sender.queueReceive(raw,255));const uint8_t* encoded;size_t count;
|
||||
assert(sender.peekOutput(encoded,count));assert(count>258);
|
||||
for (size_t i=0;i<count;++i) assert(receiver.feed(encoded[i]));
|
||||
const uint8_t* roundtrip;size_t roundtrip_len;
|
||||
assert(receiver.peekTransmit(roundtrip,roundtrip_len));
|
||||
assert(roundtrip_len==255 && !memcmp(roundtrip,raw,255));
|
||||
assert(!ota::ota_direct_wire_encode(raw,254,message,253));
|
||||
assert(!ota::ota_direct_wire_encode(nullptr,255,message,253));
|
||||
assert(!ota::ota_direct_wire_encode(raw,255,nullptr,1));
|
||||
assert(!ota::ota_direct_wire_encode(raw,255,message,0));
|
||||
assert(!ota::ota_direct_wire_encode(raw,256,message,254));
|
||||
assert(!ota::ota_direct_wire_decode(nullptr,3,decoded,length));
|
||||
assert(!decoded && !length);
|
||||
for (unsigned header=0;header<256;++header) {
|
||||
uint8_t frame[]={uint8_t(header),0,ota::OTA_REQ};
|
||||
assert(ota::ota_direct_wire_decode(frame,3,decoded,length)==(header==0xf2));
|
||||
}
|
||||
uint8_t short_frame[]={0xf2,0,ota::OTA_REQ};
|
||||
for (size_t n=0;n<3;++n) assert(!ota::ota_direct_wire_decode(short_frame,n,decoded,length));
|
||||
for (unsigned path=1;path<256;++path) {
|
||||
short_frame[1]=uint8_t(path);assert(!ota::ota_direct_wire_decode(short_frame,3,decoded,length));
|
||||
}
|
||||
raw[1]=0;assert(!ota::ota_direct_wire_decode(raw,256,decoded,length));
|
||||
for (unsigned type=0;type<256;++type) {
|
||||
short_frame[1]=0;short_frame[2]=uint8_t(type);
|
||||
assert(ota::ota_direct_wire_decode(short_frame,3,decoded,length)==ota::ota_is_transfer_message(uint8_t(type)));
|
||||
assert(bool(ota::ota_direct_wire_encode(raw,255,short_frame+2,1))==ota::ota_is_transfer_message(uint8_t(type)));
|
||||
}
|
||||
}
|
||||
'''
|
||||
self.compile_run(code)
|
||||
|
||||
def test_feature_defaults_invalid_configuration_and_packet_footprint(self):
|
||||
code = r'''
|
||||
#include <Dispatcher.h>
|
||||
#include <cstdio>
|
||||
static_assert(MESH_ENABLE_OTA_KISS_DIRECT==EXPECT_DIRECT,"feature scope");
|
||||
static_assert(bool(MESH_ENABLE_FOREIGN_RADIO)==bool(EXPECT_DIRECT),"shared slot scope");
|
||||
static_assert(MAX_PACKET_PAYLOAD==184,"routed payload remains unchanged");
|
||||
int main() { std::printf("%zu\n",sizeof(mesh::Packet)); }
|
||||
'''
|
||||
sizes = set()
|
||||
for flags, enabled in (
|
||||
([], 0), (["-DENABLE_OTA"], 1),
|
||||
(["-DENABLE_OTA", "-DMESH_PRIMARY_ESPNOW=1"], 0),
|
||||
(["-DENABLE_OTA", "-DMESH_PRIMARY_ESPNOW=0"], 1),
|
||||
(["-DENABLE_OTA", "-DMESH_ENABLE_OTA_KISS_DIRECT=0"], 0),
|
||||
(["-DENABLE_OTA", "-DMESH_ENABLE_FOREIGN_RADIO=0"], 0),
|
||||
):
|
||||
with self.subTest(flags=flags):
|
||||
sizes.add(self.compile_run(code, [*flags, f"-DEXPECT_DIRECT={enabled}",
|
||||
"-DMESH_ENABLE_MESHTEXT_CHAT=0", "-DMESH_ENABLE_ETHERNET_TUNNEL=0"]).strip())
|
||||
self.assertEqual(len(sizes), 1, "direct support must not enlarge each Packet")
|
||||
for flags in (["-DMESH_ENABLE_OTA_KISS_DIRECT=1"],
|
||||
["-DENABLE_OTA", "-DMESH_ENABLE_OTA_KISS_DIRECT=2"],
|
||||
["-DENABLE_OTA", "-DMESH_ENABLE_OTA_KISS_DIRECT=1", "-DMESH_ENABLE_FOREIGN_RADIO=0"]):
|
||||
diagnostic = self.compile_run("#include <helpers/ota/OtaDirectConfig.h>\nint main() {}",
|
||||
flags, expect_compile=False)
|
||||
self.assertIn("direct", diagnostic.lower())
|
||||
|
||||
def test_real_dispatcher_profile_affinity_admission_and_accounting(self):
|
||||
code = dispatcher_harness() + r'''
|
||||
int main() {
|
||||
using P=RadioProfileProtocol;
|
||||
for (uint8_t profile: {0,1}) {
|
||||
Fixture f;directProfile(f,profile);const auto free=f.manager.getFreeCount();
|
||||
uint8_t message[253];message[0]=ota::OTA_DATA;
|
||||
for (unsigned i=1;i<253;++i) message[i]=uint8_t(i);
|
||||
assert(f.d.queueDirectOtaRadioFrame(message,253,profile,f.radio.p.generation[profile]));
|
||||
assert(f.manager.getFreeCount()==free && f.manager.getOutboundTotal()==0);
|
||||
assert(!enqueue(f,profile));f.tick();
|
||||
assert(f.radio.sends==1 && f.radio.active==profile && f.radio.sent.size()==255);
|
||||
assert(f.radio.sent[0]==0xf2 && !f.radio.sent[1] && !memcmp(f.radio.sent.data()+2,message,253));
|
||||
f.tick(20);f.radio.complete=true;f.tick();
|
||||
assert(!f.d.hasOutbound() && f.d.done.empty() && !f.d.mc_sent);
|
||||
assert(f.radio.p.tx_packets[profile]==1 && f.d.getNumSentDirect()==1 && !f.d.getNumSentFlood());
|
||||
assert(f.d.getTotalAirTime()==21 && f.manager.getFreeCount()==free);
|
||||
}
|
||||
{ Fixture f;directProfile(f);f.d.allow_direct=false;assert(!enqueue(f));
|
||||
f.d.allow_direct=true;f.radio.carrier=true;assert(!enqueue(f));f.radio.carrier=false;
|
||||
f.radio.p.secondary.mode=RadioProfileMode::Rx;assert(!enqueue(f));
|
||||
f.radio.p.secondary.mode=RadioProfileMode::Off;assert(!enqueue(f));
|
||||
f.radio.p.secondary.mode=RadioProfileMode::RxTx;
|
||||
assert(!f.d.queueDirectOtaRadioFrame(bytes,3,2,1));
|
||||
assert(!f.d.queueDirectOtaRadioFrame(bytes,3,1,f.radio.p.generation[1]+1));
|
||||
f.radio.p.secondary.params.protocol=P::Ethernet;assert(!enqueue(f));
|
||||
f.radio.p.secondary.params.protocol=P::MeshCore;
|
||||
assert(!f.d.queueDirectOtaRadioFrame(nullptr,3,1,f.radio.p.generation[1]));
|
||||
const uint8_t discover[]={ota::OTA_ADV};
|
||||
assert(!f.d.queueDirectOtaRadioFrame(discover,1,1,f.radio.p.generation[1]));
|
||||
assert(!f.d.queueForeignRadioFrame(bytes,3,1,f.radio.p.generation[1],P::MeshCore));
|
||||
}
|
||||
for (unsigned changed=0;changed<4;++changed) {
|
||||
Fixture f;directProfile(f);assert(enqueue(f));
|
||||
if (changed==0) ++f.radio.p.generation[1];
|
||||
if (changed==1) f.radio.p.secondary.params.protocol=P::Meshtext;
|
||||
if (changed==2) f.radio.p.secondary.mode=RadioProfileMode::Off;
|
||||
if (changed==3) f.d.allow_direct=false;
|
||||
f.tick();assert(!f.radio.sends && !f.d.hasOutbound() && f.d.done.empty());
|
||||
assert(!f.d.getNumSentDirect() && !f.radio.p.tx_packets[1]);
|
||||
}
|
||||
{ Fixture f;directProfile(f);assert(enqueue(f));f.tick();
|
||||
++f.radio.p.generation[1];f.radio.complete=true;f.tick(10);
|
||||
assert(!f.d.hasOutbound() && f.d.done.empty() && !f.d.getNumSentDirect());
|
||||
assert(f.d.getTotalAirTime()==10 && !f.radio.p.tx_packets[1]);
|
||||
}
|
||||
{ Fixture f;directProfile(f);assert(enqueue(f));
|
||||
assert(!f.d.discardQueuedForeignRadioFrame(P::Ethernet));
|
||||
assert(f.d.discardQueuedForeignRadioFrame(P::MeshCore));
|
||||
f.tick();assert(!f.radio.sends && !f.d.hasOutbound() && f.d.done.empty());
|
||||
assert(enqueue(f));f.tick();assert(!f.d.discardQueuedForeignRadioFrame(P::MeshCore));
|
||||
f.radio.complete=true;f.tick();assert(f.d.getNumSentDirect()==1);
|
||||
}
|
||||
}
|
||||
'''
|
||||
self.compile_run(code, ["-DENABLE_OTA", "-DMESH_ENABLE_MESHTEXT_CHAT=0",
|
||||
"-DMESH_ENABLE_ETHERNET_TUNNEL=0"], dispatcher=True)
|
||||
|
||||
def test_real_dispatcher_epoch_retires_abort_fallback_and_old_context(self):
|
||||
code = dispatcher_harness() + r'''
|
||||
int main() {
|
||||
{ Fixture f;directProfile(f);f.d.epoch=0;assert(!enqueue(f));assert(!f.d.hasOutbound()); }
|
||||
// The manager changes the opaque token on abort, fallback and context
|
||||
// reconstruction. Neither a stable radio generation nor a live temp window
|
||||
// can authorize an already-admitted frame belonging to the former token.
|
||||
for (uint32_t retired: {0u,2u,0xffffffffu}) {
|
||||
Fixture f;directProfile(f);assert(enqueue(f));f.d.epoch=retired;f.tick();
|
||||
assert(!f.radio.sends && !f.d.hasOutbound() && f.d.done.empty());
|
||||
assert(!f.d.getNumSentDirect() && !f.radio.p.tx_packets[1]);
|
||||
f.d.epoch=3;assert(enqueue(f));f.tick();assert(f.radio.sends==1);
|
||||
f.radio.complete=true;f.tick();assert(f.d.getNumSentDirect()==1 && f.d.done.empty());
|
||||
}
|
||||
{ Fixture f;directProfile(f);f.radio.prepare=RadioParamApplyResult::BUSY;
|
||||
assert(enqueue(f));f.tick();f.d.epoch=2;f.tick(20);
|
||||
assert(!f.radio.sends && !f.d.hasOutbound() && !f.radio.recovery && f.d.done.empty());
|
||||
}
|
||||
{ Fixture f;directProfile(f);assert(enqueue(f));f.tick();f.d.epoch=2;
|
||||
f.radio.complete=true;f.tick(10);
|
||||
assert(f.radio.sends==1 && f.radio.finishes==1 && !f.d.hasOutbound());
|
||||
assert(f.d.getTotalAirTime()==10 && !f.d.getNumSentDirect() && !f.radio.p.tx_packets[1]);
|
||||
assert(f.d.done.empty());f.tick(5000);assert(f.radio.sends==1);
|
||||
assert(enqueue(f));f.tick();assert(f.radio.sends==2); // new token remains usable
|
||||
}
|
||||
{ Fixture f;directProfile(f);assert(enqueue(f));f.tick();f.d.epoch=0;f.tick(1151);
|
||||
assert(f.radio.sends==1 && f.radio.finishes==1 && f.radio.recovery==1 && !f.d.hasOutbound());
|
||||
assert(f.d.getTotalAirTime()==1151 && !f.d.getNumSentDirect() && f.d.done.empty());
|
||||
}
|
||||
}
|
||||
'''
|
||||
self.compile_run(code, ["-DENABLE_OTA", "-DMESH_ENABLE_MESHTEXT_CHAT=0",
|
||||
"-DMESH_ENABLE_ETHERNET_TUNNEL=0"], dispatcher=True)
|
||||
|
||||
def test_real_dispatcher_failures_cad_duty_quiet_and_packet_fairness(self):
|
||||
code = dispatcher_harness() + r'''
|
||||
int main() {
|
||||
{ Fixture f;directProfile(f);f.radio.start_ok=false;assert(enqueue(f));f.tick();f.tick(10000);
|
||||
assert(f.radio.sends==1 && !f.d.hasOutbound() && f.d.done.empty() && !f.d.getNumSentDirect());
|
||||
}
|
||||
{ Fixture f;directProfile(f);assert(enqueue(f));f.tick();f.tick(1151);
|
||||
assert(f.radio.sends==1 && f.radio.finishes==1 && f.radio.recovery==1 && !f.d.hasOutbound());
|
||||
f.tick(10000);assert(f.radio.sends==1 && f.d.done.empty());
|
||||
}
|
||||
{ Fixture f;directProfile(f);f.radio.prepare=RadioParamApplyResult::FAILED;assert(enqueue(f));f.tick();
|
||||
assert(!f.radio.sends && !f.d.hasOutbound() && f.d.done.empty());
|
||||
}
|
||||
{ Fixture f;directProfile(f);f.radio.prepare=RadioParamApplyResult::BUSY;assert(enqueue(f));f.tick();f.tick(8151);
|
||||
assert(!f.radio.sends && !f.d.hasOutbound() && f.radio.recovery==1 && f.d.done.empty());
|
||||
}
|
||||
{ Fixture f;directProfile(f);f.radio.receiving=true;assert(enqueue(f));f.tick();f.tick(201);
|
||||
assert(!f.radio.sends && f.d.hasOutbound());f.radio.receiving=false;f.tick(201);assert(f.radio.sends==1);
|
||||
}
|
||||
{ Fixture f;directProfile(f);assert(enqueue(f));f.tick();f.d.setRadioAvailable(false);f.tick(10000);
|
||||
assert(f.radio.sends==1 && f.radio.finishes==1 && !f.d.hasOutbound() && !enqueue(f) && f.d.done.empty());
|
||||
}
|
||||
{ Fixture f;directProfile(f);assert(enqueue(f));f.tick();f.d.begin();
|
||||
assert(f.radio.finishes==1 && !f.d.hasOutbound() && !f.d.getNumSentDirect() && f.d.done.empty());
|
||||
}
|
||||
{ Fixture f;directProfile(f);f.d.duty_window=200;f.d.begin();assert(enqueue(f));f.tick();
|
||||
f.clock.now+=100;f.radio.complete=true;f.d.loop();assert(f.d.getRemainingTxBudget()==0);
|
||||
assert(enqueue(f));f.tick(100);assert(f.radio.sends==1);f.tick(101);assert(f.radio.sends==2);
|
||||
}
|
||||
{ Fixture f;directProfile(f);f.d.speed=0.5;assert(enqueue(f));f.tick();f.tick(99);
|
||||
f.radio.complete=true;f.tick();assert(f.d.getTotalAirTime()==100);
|
||||
assert(enqueue(f));f.tick(99);assert(f.radio.sends==1);f.tick(2);assert(f.radio.sends==2);
|
||||
}
|
||||
{ Fixture f;directProfile(f);assert(enqueue(f));f.tick();f.radio.complete=true;f.tick();
|
||||
assert(enqueue(f));auto* packet=newPacket(f.d,RADIO_TX_PRIMARY);assert(f.d.sendPacket(packet,0));f.tick();
|
||||
assert(f.radio.sends==2 && f.radio.active==0);f.radio.complete=true;f.tick();f.tick();
|
||||
assert(f.radio.sends==3 && f.radio.active==1 && f.d.mc_sent==1 && f.d.done.empty());
|
||||
}
|
||||
}
|
||||
'''
|
||||
self.compile_run(code, ["-DENABLE_OTA", "-DMESH_ENABLE_MESHTEXT_CHAT=0",
|
||||
"-DMESH_ENABLE_ETHERNET_TUNNEL=0"], dispatcher=True)
|
||||
|
||||
def test_real_dispatcher_receive_isolation_without_packet_credit(self):
|
||||
code = dispatcher_harness() + r'''
|
||||
int main() {
|
||||
const std::vector<uint8_t> valid={0xf2,0,ota::OTA_REQ,0xc0,0xdb};
|
||||
{ Fixture f;directProfile(f);std::vector<Packet*> reserved;
|
||||
while (auto* p=f.d.obtainNewPacket()) reserved.push_back(p);
|
||||
assert(!f.manager.getFreeCount());receive(f,valid);
|
||||
assert(f.d.direct_rx==1 && f.d.direct_message==std::vector<uint8_t>(valid.begin()+2,valid.end()));
|
||||
assert(!f.d.mc_rx && !f.d.foreign_rx && !f.d.raw_logs && !f.d.getLastMeshCoreRecvMillis());
|
||||
assert(f.d.getNumRecvDirect()==1 && !f.d.getNumRecvFlood() && f.radio.p.rx_packets[1]==1);
|
||||
assert(f.radio.processed==1 && f.d.getReceiveAirTime()==100 && !f.manager.getFreeCount());
|
||||
for (auto* p:reserved) f.d.releasePacket(p);
|
||||
}
|
||||
{ Fixture f;directProfile(f);f.d.allow_direct=false;receive(f,valid);
|
||||
assert(f.d.direct_calls==1 && !f.d.direct_rx && !f.d.raw_logs && !f.d.mc_rx && !f.d.foreign_rx);
|
||||
assert(!f.d.getNumRecvDirect() && !f.radio.p.rx_packets[1] && !f.d.getReceiveAirTime());
|
||||
}
|
||||
for (const auto& bad: std::vector<std::vector<uint8_t>>{
|
||||
{0xf2},{0xf2,0},{0xf2,1,ota::OTA_REQ},{0xf2,0,ota::OTA_ADV},{0xf2,0,0xff}}) {
|
||||
Fixture f;directProfile(f);receive(f,bad);
|
||||
assert(f.d.direct_calls==1 && !f.d.direct_rx && !f.d.raw_logs && !f.d.mc_rx && !f.d.foreign_rx);
|
||||
assert(!f.d.getNumRecvDirect() && !f.radio.p.rx_packets[1] && f.radio.processed==1);
|
||||
}
|
||||
{ Fixture f;directProfile(f);f.radio.rx_generation=f.radio.p.generation[1];++f.radio.p.generation[1];receive(f,valid);
|
||||
assert(!f.d.direct_calls && !f.d.raw_logs && !f.d.mc_rx && f.radio.processed==1);
|
||||
}
|
||||
{ Fixture f;directProfile(f,0);receive(f,valid,0);assert(f.d.direct_rx==1 && f.radio.p.rx_packets[0]==1); }
|
||||
{ Fixture f;directProfile(f);auto flood=valid;flood[0]=0xf1;receive(f,flood);
|
||||
assert(!f.d.direct_calls && !f.d.mc_rx && !f.d.getNumRecvFlood() && !f.manager.getOutboundTotal());
|
||||
}
|
||||
}
|
||||
'''
|
||||
self.compile_run(code, ["-DENABLE_OTA", "-DMESH_ENABLE_MESHTEXT_CHAT=0",
|
||||
"-DMESH_ENABLE_ETHERNET_TUNNEL=0"], dispatcher=True)
|
||||
|
||||
def test_real_dispatcher_disabled_and_shared_transport_ownership(self):
|
||||
code = dispatcher_harness() + r'''
|
||||
int main() {
|
||||
#if MESH_ENABLE_OTA_KISS_DIRECT
|
||||
{ Fixture f;directProfile(f);assert(enqueue(f));assert(!f.d.queue(bytes));
|
||||
f.d.discardQueuedForeignRadioFrame(RadioProfileProtocol::MeshCore);
|
||||
f.radio.p.secondary.params.protocol=RadioProfileProtocol::Meshtext;
|
||||
assert(f.d.queue(bytes));assert(!enqueue(f,0));
|
||||
}
|
||||
#else
|
||||
{ Fixture f;directProfile(f);receive(f,{0xf2,0,ota::OTA_REQ});
|
||||
assert(!f.d.direct_calls && !f.d.mc_rx && !f.manager.getOutboundTotal());
|
||||
}
|
||||
#endif
|
||||
// Existing generic Meshtext ownership and its completion callback are unchanged.
|
||||
{ Fixture f;assert(f.d.queue(bytes));f.tick();f.radio.complete=true;f.tick();
|
||||
assert(f.d.done.size()==1 && f.d.done[0] && !f.d.getNumSentDirect());
|
||||
}
|
||||
}
|
||||
'''
|
||||
for enabled in (0, 1):
|
||||
with self.subTest(direct=enabled):
|
||||
self.compile_run(code, ["-DENABLE_OTA", f"-DMESH_ENABLE_OTA_KISS_DIRECT={enabled}",
|
||||
"-DMESH_ENABLE_MESHTEXT_CHAT=1"], dispatcher=True)
|
||||
|
||||
def test_mesh_temp_policy_and_no_unsolicited_context_allocation(self):
|
||||
source = (ROOT / "src/Mesh.cpp").read_text()
|
||||
epoch = method(source, "uint32_t Mesh::directOtaEpoch(")
|
||||
policy = method(source, "bool Mesh::allowDirectOtaTransmit(")
|
||||
receive = method(source, "bool Mesh::onDirectOtaRadioFrame(")
|
||||
code = r'''
|
||||
#include <Dispatcher.h>
|
||||
#include <helpers/ota/OtaDirectWire.h>
|
||||
#include <cassert>
|
||||
namespace mesh { namespace ota {
|
||||
struct OtaReplyRoute { uint8_t profile=255;uint32_t generation=0;bool direct=false; };
|
||||
struct Manager {
|
||||
unsigned calls=0;bool enabled=false;uint8_t hops=255;OtaReplyRoute route;
|
||||
uint32_t directTransportEpoch() const { return 42; }
|
||||
void set_direct_transport_enabled(bool value) { enabled=value; }
|
||||
void note_rx_path_hops(uint8_t value) { hops=value; }
|
||||
bool on_message(const uint8_t*,uint16_t,OtaReplyRoute value) { ++calls;route=value;return true; }
|
||||
uint8_t fetchState() const { return 0; }
|
||||
};
|
||||
struct Context { Manager manager;void track_session(uint8_t,unsigned long) {} } context;
|
||||
bool exists=false;unsigned lookups=0;
|
||||
Context* ota_context_if_active() { ++lookups;return exists ? &context:nullptr; }
|
||||
} }
|
||||
namespace mesh {
|
||||
struct TestRadio { RadioProfiles p;const RadioProfiles* profiles() const { return &p; } };
|
||||
struct Clock { unsigned long getMillis() const { return 1000; } };
|
||||
class Mesh {
|
||||
public:
|
||||
TestRadio radio;TestRadio* _radio=&radio;Clock clock;Clock* _ms=&clock;
|
||||
bool temp=false,primary=false,transmit=true;
|
||||
Mesh() {
|
||||
radio.p.primary.freq=909.5;radio.p.primary.bw=500;radio.p.primary.sf=5;radio.p.primary.cr=5;
|
||||
radio.p.secondary.params=radio.p.primary;radio.p.secondary.mode=RadioProfileMode::RxTx;
|
||||
}
|
||||
bool isAnyTempRadioActive() const { return temp; }
|
||||
bool isTempRadioActive() const { return primary; }
|
||||
bool allowPacketTransmit(const Packet*) const { return transmit; }
|
||||
void syncOtaTiming(ota::Manager&) {}
|
||||
bool allowDirectOtaTransmit(uint8_t,uint32_t) const;
|
||||
uint32_t directOtaEpoch() const;
|
||||
bool onDirectOtaRadioFrame(const uint8_t*,size_t,uint8_t,uint32_t);
|
||||
};
|
||||
@POLICY@
|
||||
@EPOCH@
|
||||
@RECEIVE@
|
||||
}
|
||||
int main() {
|
||||
using namespace mesh;Mesh m;const auto gen=m.radio.p.generation[1];
|
||||
const uint8_t frame[]={0xf2,0,ota::OTA_REQ};
|
||||
assert(!m.directOtaEpoch() && !ota::exists && ota::lookups==1);
|
||||
assert(!m.allowDirectOtaTransmit(1,gen));m.temp=true;
|
||||
assert(!m.allowDirectOtaTransmit(1,gen));m.radio.p.secondary_temporary=true;
|
||||
assert(m.allowDirectOtaTransmit(1,gen));
|
||||
assert(!m.onDirectOtaRadioFrame(frame,3,1,gen) && ota::lookups==2 && !ota::context.manager.calls);
|
||||
ota::exists=true;assert(m.onDirectOtaRadioFrame(frame,3,1,gen));
|
||||
assert(m.directOtaEpoch()==42);
|
||||
assert(ota::context.manager.calls==1 && ota::context.manager.enabled && ota::context.manager.hops==0);
|
||||
assert(ota::context.manager.route.direct && ota::context.manager.route.profile==1 && ota::context.manager.route.generation==gen);
|
||||
m.transmit=false;assert(!m.onDirectOtaRadioFrame(frame,3,1,gen));m.transmit=true;
|
||||
assert(!m.allowDirectOtaTransmit(1,gen+1) && !m.allowDirectOtaTransmit(2,gen));
|
||||
m.radio.p.secondary.mode=RadioProfileMode::Rx;assert(!m.allowDirectOtaTransmit(1,gen));
|
||||
m.radio.p.secondary.mode=RadioProfileMode::RxTx;
|
||||
m.radio.p.secondary.params.protocol=RadioProfileProtocol::Ethernet;assert(!m.allowDirectOtaTransmit(1,gen));
|
||||
m.radio.p.secondary.params.protocol=RadioProfileProtocol::MeshCore;
|
||||
m.radio.p.secondary_temporary=false;m.primary=true;
|
||||
assert(!m.allowDirectOtaTransmit(1,gen));assert(m.allowDirectOtaTransmit(0,m.radio.p.generation[0]));
|
||||
m.primary=false;m.radio.p.primary_temporary=true;
|
||||
assert(m.allowDirectOtaTransmit(0,m.radio.p.generation[0]));
|
||||
m.radio.p.primary_temporary=false;m.radio.p.cross=RadioCrossMode::On;
|
||||
assert(m.allowDirectOtaTransmit(1,gen));m.temp=false;assert(!m.allowDirectOtaTransmit(1,gen));
|
||||
}
|
||||
'''.replace("@POLICY@", policy).replace("@RECEIVE@", receive).replace("@EPOCH@", epoch)
|
||||
self.compile_run(code, ["-DENABLE_OTA", "-DMESH_ENABLE_MESHTEXT_CHAT=0"])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -77,7 +77,7 @@ struct OtaManager {
|
||||
enum FetchError { FETCH_ERROR_NONE, FETCH_ERROR_MANIFEST, FETCH_ERROR_HASH_ALGO,
|
||||
FETCH_ERROR_VERSION, FETCH_ERROR_CODEC, FETCH_ERROR_GEOMETRY, FETCH_ERROR_TOO_LARGE,
|
||||
FETCH_ERROR_STORAGE, FETCH_ERROR_INTEGRITY, FETCH_ERROR_MANIFEST_TIMEOUT,
|
||||
FETCH_ERROR_LEAVES_TIMEOUT };
|
||||
FETCH_ERROR_LEAVES_TIMEOUT, FETCH_ERROR_RADIO_SESSION };
|
||||
enum { AUTOFETCH_ANY = 2, AUTOFETCH_SIGNED = 1 };
|
||||
struct ServeEntry { bool is_self; uint8_t mid[4]; uint32_t fw_version, have_count; };
|
||||
FetchState state = IDLE;
|
||||
@@ -85,6 +85,8 @@ struct OtaManager {
|
||||
unsigned have = 0, total = 26;
|
||||
uint8_t mid[4] = {1, 2, 3, 4};
|
||||
FetchState fetchState() const { return state; }
|
||||
bool directFetchActive() const { return false; }
|
||||
bool directFetchConfirmed() const { return false; }
|
||||
FetchError fetchError() const { return error; }
|
||||
unsigned blocksHave() const { return have; }
|
||||
unsigned blocksTotal() const { return total; }
|
||||
|
||||
@@ -245,7 +245,7 @@ int main(){
|
||||
strcpy(prefs.node_name,"retained name");prefs.ble_pin=654321;prefs.gps_interval=42;
|
||||
assert(prefs.getCustom()->setByKey("snapshot_tag","original"));
|
||||
assert(store.savePrefs(prefs,47.2,-122.1));const auto disk=store.fs.files["/new_prefs"];
|
||||
assert(disk.size()==244);double lat=0,lon=0;
|
||||
assert(disk.size()==252);double lat=0,lon=0;
|
||||
CompanionNodePrefs loaded;assert(loaded.getCustom()->setByKey("snapshot_tag","loaded"));
|
||||
assert(store.loadPrefsInt("/new_prefs",loaded,lat,lon));
|
||||
assert(loaded.peripherals_shared==1&&loaded.ble_pin==654321&&loaded.gps_interval==42);
|
||||
@@ -259,6 +259,11 @@ int main(){
|
||||
assert(ok==(keep==236));if(ok)assert(candidate.peripherals_shared==0);
|
||||
else assert(candidate.peripherals_shared==1&&candidate.ble_pin==123456);
|
||||
}
|
||||
// The previous complete RAK PMO footer remains an accepted legacy image.
|
||||
DataStore old;old.fs.files["/new_prefs"]={disk.begin(),disk.begin()+244};
|
||||
CompanionNodePrefs old_prefs;old_prefs.tx_media=mesh::RADIO_TX_OFF;
|
||||
assert(old.loadPrefsInt("/new_prefs",old_prefs,lat,lon));
|
||||
assert(old_prefs.peripherals_shared==1&&old_prefs.tx_media==mesh::RADIO_TX_AUTO);
|
||||
for(size_t byte=236;byte<244;++byte){
|
||||
DataStore damaged;damaged.fs.files["/new_prefs"]=disk;damaged.fs.files["/new_prefs"][byte]^=1;
|
||||
CompanionNodePrefs candidate;candidate.peripherals_shared=1;candidate.ble_pin=123456;
|
||||
|
||||
@@ -329,6 +329,88 @@ int main(int argc, char** argv) {
|
||||
|
||||
|
||||
class RadioProfileAutoTest(unittest.TestCase):
|
||||
def test_ota_raw_slot_does_not_enable_foreign_ownership_or_v2_settings(self):
|
||||
code = r'''
|
||||
#define main existing_cli_main
|
||||
#include "test/fixtures/radio_profiles/cli_test.cpp"
|
||||
#undef main
|
||||
int main() {
|
||||
Fixture f(true);
|
||||
const bool foreign = MESH_ENABLE_MESHTEXT_CHAT || MESH_ENABLE_ETHERNET_TUNNEL;
|
||||
#if defined(ENABLE_OTA)
|
||||
static_assert(MESH_ENABLE_OTA_KISS_DIRECT, "exercise the actual direct-OTA capability");
|
||||
static_assert(MESH_ENABLE_FOREIGN_RADIO, "exercise the shared raw scheduler");
|
||||
#endif
|
||||
assert(f.cli.canAutoSecondary() == foreign);
|
||||
assert(!f.cli.autoSecondaryActive());
|
||||
mesh::RadioProfileConfig config;
|
||||
config.mode = mesh::RadioProfileMode::RxTx;
|
||||
config.params.freq = 909.5f; config.params.bw = 250;
|
||||
config.params.sf = 11; config.params.cr = 5; config.params.preamble = 16;
|
||||
#if MESH_ENABLE_MESHTEXT_CHAT
|
||||
config.params.protocol = mesh::RadioProfileProtocol::Meshtext;
|
||||
#else
|
||||
config.params.protocol = mesh::RadioProfileProtocol::Ethernet;
|
||||
#endif
|
||||
assert(f.cli.requestAutoSecondary(config) == foreign);
|
||||
f.cli.clearAutoSecondary();
|
||||
assert(!f.radio.p.enabled());
|
||||
assert(f.cli.useSecondaryProtocol(mesh::RadioProfileProtocol::Meshtext) == false);
|
||||
char reply[160] = "unchanged";
|
||||
assert(f.cli.handle("set radio2 auto", reply, sizeof reply));
|
||||
assert((!strncmp(reply, "OK", 2)) == foreign);
|
||||
if (foreign) f.advance(2000);
|
||||
assert(f.cli.savePrimaryPreamble(120));
|
||||
const auto image = f.fs.files["/radio_profiles"];
|
||||
assert(image.size() == 24 && image[2] == (foreign ? 2 : 1));
|
||||
f.cmd("set radio2 off");
|
||||
assert(!f.cli.autoSecondaryActive());
|
||||
assert(f.fs.files["/radio_profiles"][2] == (foreign ? 2 : 1));
|
||||
Radio reboot; mesh::RadioProfileCLI restored;
|
||||
restored.begin(&f.fs, &reboot, &f.clock, true);
|
||||
assert(!reboot.p.enabled() && !restored.canAutoSecondary());
|
||||
#if defined(MESH_HIL_TX_FREQ_MHZ)
|
||||
assert(restored.handle("get lab.tx", reply, sizeof reply));
|
||||
assert(!strcmp(reply, "> HIL TX lock=909.500 MHz; off-frequency TX blocked; primary RX-only when off-frequency"));
|
||||
#else
|
||||
assert(!restored.handle("get lab.tx", reply, sizeof reply));
|
||||
#endif
|
||||
assert(!restored.handle("set lab.tx 909.5", reply, sizeof reply));
|
||||
printf("profile_size=%zu\n", sizeof(mesh::RadioProfileCLI));
|
||||
}
|
||||
'''
|
||||
sizes = {}
|
||||
compiler = os.environ.get("CXX") or shutil.which("g++") or shutil.which("clang++")
|
||||
with tempfile.TemporaryDirectory(prefix="radio-profile-capability-") as work:
|
||||
source, binary = Path(work) / "capability.cpp", Path(work) / "capability"
|
||||
source.write_text(code)
|
||||
for name, ota, meshtext, ethernet, guard in (
|
||||
("baseline", 0, 0, 0, 0), ("ota", 1, 0, 0, 0),
|
||||
("meshtext", 1, 1, 0, 0), ("ethernet", 1, 0, 1, 0),
|
||||
("ota_guard", 1, 0, 0, 1),
|
||||
):
|
||||
flags = [f"-DMESH_ENABLE_MESHTEXT_CHAT={meshtext}",
|
||||
f"-DMESH_ENABLE_ETHERNET_TUNNEL={ethernet}",
|
||||
"-DMESH_ENABLE_FLEET_CONTROL=0"]
|
||||
if ota:
|
||||
flags.append("-DENABLE_OTA=1")
|
||||
if guard:
|
||||
flags.append("-DMESH_HIL_TX_FREQ_MHZ=909.5")
|
||||
result = subprocess.run([
|
||||
compiler, "-std=c++17", "-Wall", "-Wextra", *flags,
|
||||
"-I", str(ROOT), "-I", str(ROOT / "test/fixtures/radio_profiles/mocks"),
|
||||
"-I", str(ROOT / "test/mocks"), "-I", str(ROOT / "src"),
|
||||
str(ROOT / "src/helpers/RadioProfileCLI.cpp"), str(source), "-o", str(binary),
|
||||
], capture_output=True, text=True, timeout=60)
|
||||
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
|
||||
run = subprocess.run([str(binary)], capture_output=True, text=True, timeout=10)
|
||||
self.assertEqual(run.returncode, 0, name + ": " + run.stdout + run.stderr)
|
||||
sizes[name] = int(run.stdout.split("profile_size=", 1)[1].splitlines()[0])
|
||||
self.assertEqual(sizes["baseline"], sizes["ota"])
|
||||
self.assertEqual(sizes["baseline"], sizes["ota_guard"])
|
||||
self.assertGreater(sizes["meshtext"], sizes["ota"])
|
||||
self.assertEqual(sizes["meshtext"], sizes["ethernet"])
|
||||
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
compiler = os.environ.get("CXX") or shutil.which("g++") or shutil.which("clang++")
|
||||
|
||||
@@ -119,16 +119,23 @@ int main() {
|
||||
assert(w._profiles.switchTestReady());
|
||||
assert(w._profiles.switch_test_samples[0]==4 && w._profiles.switch_test_samples[1]==4);
|
||||
assert(w._profiles.switchBudgetUs()==1320); // measured 1200 us plus 10%, no nominal floor
|
||||
assert(w._profiles.preamble(0,32)>=32 && w._profiles.preamble(0,32)<=128);
|
||||
assert(w._profiles.preamble(1,32)>=32 && w._profiles.preamble(1,32)<=128);
|
||||
assert(w._profiles.preamble(0,32)>=32 && w._profiles.preamble(0,32)<=512);
|
||||
assert(w._profiles.preamble(1,32)>=32 && w._profiles.preamble(1,32)<=512);
|
||||
assert(w._profiles.preamble(0,32)%8==0 && w._profiles.preamble(1,32)%8==0);
|
||||
}
|
||||
{
|
||||
RadioLibWrapper w; w._profiles.primary.bw=w._cur_bw=500; w.switch_apply_us=8428;
|
||||
w.enable();
|
||||
assert(w._profiles.switchTestReady() && w._profiles.switchBudgetUs()==9271);
|
||||
assert(w._profiles.preamble(0,32)==128 && w._profiles.preamble(1,32)<=128);
|
||||
assert(w._profiles.chirpTiming().preamble[0]>128);
|
||||
assert(w._profiles.preamble(0,32)==168 && w._profiles.preamble(1,32)<=512);
|
||||
assert(w._profiles.chirpTiming().preamble[0]==168);
|
||||
}
|
||||
{
|
||||
RadioLibWrapper w; w._profiles.primary.bw=w._cur_bw=500; w.switch_apply_us=40000;
|
||||
w.enable();
|
||||
assert(w._profiles.switchTestReady() && w._profiles.switchBudgetUs()==44000);
|
||||
assert(w._profiles.preamble(0,32)==512 && w._profiles.preamble(1,32)<=512);
|
||||
assert(w._profiles.chirpTiming().preamble[0]>512);
|
||||
}
|
||||
{
|
||||
RadioLibWrapper w; w.packet=true; w.enable();
|
||||
|
||||
Reference in new issue
Block a user