Improve Morse timing adaptation and repair CI regression coverage

This commit is contained in:
mikecarper committed 2026-10-13 03:02:52 -07:00
1 parent 1b2c1cf2b3
commit b1198b6e3e
20 files changed
+1240 -74

No files matched your search

+108
View File
@@ -0,0 +1,108 @@
#include <helpers/MorseTx.h>
#include <cassert>
#include <cstring>
#include <string>
#include <vector>
using mesh::MorseTx;
using Result = mesh::MorseTxResult;
static std::vector<uint32_t> phases(const char* text, uint8_t wpm, uint32_t start,
bool hardware_delay = false) {
uint32_t planned = 0;
const auto valid = MorseTx::validate(text, wpm, &planned);
MorseTx timer;
if (valid != Result::Started) {
assert(valid == Result::TooLong && timer.start(text, wpm, start) == valid);
assert(!timer.active() && !timer.keyed());
return {};
}
assert(timer.start(text, wpm, start) == Result::Started);
std::vector<uint32_t> result;
uint32_t now = start, total = 0;
while (timer.active()) {
const uint32_t phase = timer.nextDeadline() - now;
assert(phase > 0 && phase < 65536);
assert(timer.remainingMillis(now) == planned - total);
assert(timer.advance(now + phase - 1) == MorseTx::Edge::None);
now += phase; total += phase; result.push_back(phase);
const auto edge = timer.advance(now);
assert(edge != MorseTx::Edge::None && edge != MorseTx::Edge::Expired);
if (timer.active() && hardware_delay) {
now += 3; timer.edgeApplied(now);
assert(timer.nextDeadline() > now); // The native transition owns its delay.
}
assert(result.size() < 2000);
}
assert(total == planned && timer.remainingMillis(now) == 0);
return result;
}
int main() {
#if defined(MESH_MORSE_HIL) && MESH_MORSE_HIL
using mesh::MorseHilTimingConfig;
assert(mesh::morseHilTiming().jitter_percent == 0);
const auto baseline = phases("SOS E T", 25, 100);
for (const auto config : {MorseHilTimingConfig(), MorseHilTimingConfig(20,0,0,1),
MorseHilTimingConfig(0,20,0,1), MorseHilTimingConfig(0,-20,0,1),
MorseHilTimingConfig(0,0,50,1), MorseHilTimingConfig(15,10,25,12345),
MorseHilTimingConfig(20,-20,50,0xffffffff)}) {
assert(mesh::setMorseHilTiming(config));
for (const uint8_t wpm : {uint8_t(1),uint8_t(25),uint8_t(60),uint8_t(200),uint8_t(255)}) {
for (const char* text : {"E", "SOS E T", " a B ", ". , ? ' ! / ( ) & : ; = + - _ \" $ @"}) {
const auto first = phases(text, wpm, 100);
assert(first == phases(text, wpm, 0xffffffe0));
}
}
}
assert(mesh::setMorseHilTiming(MorseHilTimingConfig(15,10,25,12345)));
const auto expected = phases("SOS E T",25,100);
assert(expected != baseline);
assert(expected == phases("SOS E T",25,100,true));
MorseTx running;
assert(running.start("SOS E T",25,100) == Result::Started);
assert(mesh::setMorseHilTiming(MorseHilTimingConfig(20,-20,50,54321)));
uint32_t now=100;
std::vector<uint32_t> actual;
while(running.active()) {
const uint32_t phase=running.nextDeadline()-now;
actual.push_back(phase); now+=phase; running.advance(now);
}
assert(actual == expected); // Active settings are a snapshot, not live globals.
assert(mesh::setMorseHilTiming(MorseHilTimingConfig(10,0,0,12345)));
const auto fast = phases(std::string(80,'E').c_str(),255,100);
bool changed_mark=false;
for(size_t index=0;index<fast.size();index+=2) if(fast[index]!=5) changed_mark=true;
assert(changed_mark); // Fractional jitter must survive at five-ms nominal dots.
assert(mesh::setMorseHilTiming(MorseHilTimingConfig()));
uint32_t duration=0;
assert(MorseTx::validate(std::string(38,'E').c_str(),1,&duration)==Result::Started && duration==178800);
assert(mesh::setMorseHilTiming(MorseHilTimingConfig(0,0,50,1)));
duration=0xaabbccdd;
assert(MorseTx::validate(std::string(38,'E').c_str(),1,&duration)==Result::TooLong);
assert(duration==0xaabbccdd);
assert(!mesh::setMorseHilTiming(MorseHilTimingConfig(21,0,0,1)));
assert(!mesh::setMorseHilTiming(MorseHilTimingConfig(0,21,0,1)));
assert(!mesh::setMorseHilTiming(MorseHilTimingConfig(0,-21,0,1)));
assert(!mesh::setMorseHilTiming(MorseHilTimingConfig(0,0,51,1)));
assert(!mesh::setMorseHilTiming(MorseHilTimingConfig(0,0,0,0)));
assert(mesh::morseHilTiming().extra_gap_percent==50);
MorseTx deadline;
assert(deadline.start("SOS",25,0xffffffe0)==Result::Started);
assert(deadline.advance(deadline.hardDeadline())==MorseTx::Edge::Expired);
assert(!deadline.active() && !deadline.keyed());
assert(mesh::setMorseHilTiming(MorseHilTimingConfig()));
#else
struct ShippingLayout {
char text[MorseTx::MaxTextLength+1];
uint32_t next,hard_end,remaining;
uint16_t unit,phase;
uint8_t character,symbol,code,count;
bool active,keyed;
};
static_assert(sizeof(MorseTx)==sizeof(ShippingLayout),"production TX layout must not grow");
assert(phases("SOS",25,100)==std::vector<uint32_t>({48,48,48,48,48,144,144,48,144,48,144,144,48,48,48,48,48}));
#endif
}
+53
View File
@@ -0,0 +1,53 @@
#include <helpers/MorseRx.h>
#include <cassert>
#include <cstdio>
#include <cstring>
#include <initializer_list>
#if !defined(MESH_MORSE_HIL) || !MESH_MORSE_HIL
#error "This end-to-end fixture requires the actual HIL transmitter"
#endif
int main() {
const struct { const char* name; mesh::MorseHilTimingConfig timing; } profiles[] = {
{"normal", {0, 0, 0, 1}},
{"bench_preset", {15, 10, 25, 12345}},
{"jitter20", {20, 0, 0, 1}},
{"speeding20", {0, -20, 0, 2}},
{"slowing20", {0, 20, 0, 2}},
{"spacing50", {0, 0, 50, 3}},
{"mixed_speeding", {15, -10, 25, 6789}}
};
constexpr const char* message = "CQ DE TEST 73 SOS";
unsigned failures = 0;
// Rates above production's 60 WPM ceiling are explicit lab-only stress
// vectors, including the fractional 5 ms phase quantization at 240 WPM.
for (uint8_t wpm : {5, 10, 15, 20, 25, 30, 40, 60, 120, 200, 240}) {
for (uint32_t cadence : {1U, 2U}) {
for (const auto& profile : profiles) {
assert(mesh::setMorseHilTiming(profile.timing));
mesh::MorseTx sender;
mesh::MorseRx receiver;
assert(receiver.start(wpm, mesh::MorseRx::MaxDurationMillis, 0) == mesh::MorseRxResult::Started);
uint32_t now = 0;
for (; now < 600; ++now) if (now % cadence == 0) receiver.sample(-120, now);
assert(sender.start(message, wpm, now) == mesh::MorseTxResult::Started);
while (sender.active()) {
const auto edge = sender.advance(now);
if (edge != mesh::MorseTx::Edge::None) sender.edgeApplied(now);
if (now % cadence == 0) receiver.sample(sender.keyed() ? -60 : -120, now);
++now;
}
const uint32_t finish = now + mesh::MorseTx::unitMillis(wpm) * 8U;
for (; now < finish; ++now) if (now % cadence == 0) receiver.sample(-120, now);
receiver.stop(now);
const bool exact = strcmp(receiver.text(), "CQ DE TEST 73 SOS ") == 0;
printf("%u\t%u\t%s\t%s\t%s\n", wpm, cadence, profile.name,
exact ? "PASS" : "FAIL", receiver.text());
if (!exact) ++failures;
}
}
}
assert(mesh::setMorseHilTiming({}));
return failures ? 1 : 0;
}
+99
View File
@@ -0,0 +1,99 @@
#include <helpers/MorseRx.h>
#include <algorithm>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <string>
#include <vector>
struct Segment { bool keyed; uint32_t duration; };
enum class Style { Standard, Jitter, Slowing, Speeding, Mixed, Farnsworth, WideFarnsworth };
static uint32_t scaled(double millis) { return std::max(1U, uint32_t(std::lround(millis))); }
static std::vector<Segment> waveform(const char* text, uint32_t nominal, Style style) {
constexpr double dot_jitter[] = {.85, 1.10, .95, 1.15, 1.0};
constexpr double dash_ratio[] = {2.5, 3.1, 3.5, 2.8, 3.2};
constexpr double intra_jitter[] = {.80, 1.10, 1.20, .95};
constexpr double letter_jitter[] = {2.8, 3.2, 3.5, 3.0};
constexpr double word_jitter[] = {6.5, 7.0, 8.0};
std::vector<Segment> result;
unsigned marks = 0, letters = 0, words = 0;
const size_t size = strlen(text);
for (size_t index = 0; index < size; ++index) {
if (text[index] == ' ') continue;
const double progress = double(index) / double(size - 1);
double unit = nominal;
if (style == Style::Slowing || style == Style::Mixed) unit *= 1.0 + .20 * progress;
if (style == Style::Speeding) unit *= 1.0 - .20 * progress;
const bool jitter = style == Style::Jitter || style == Style::Mixed;
const uint8_t code = mesh::MorseTx::codeFor(text[index]);
assert(code);
const uint8_t count = mesh::MorseTx::symbolCount(code);
for (uint8_t bit = count; bit; --bit) {
const bool dash = ((code >> (bit - 1)) & 1) != 0;
const double mark = dash ? (jitter ? dash_ratio[marks % 5] : 3.0)
: (jitter ? dot_jitter[marks % 5] : 1.0);
result.push_back({true, scaled(unit * mark)});
++marks;
if (bit > 1) result.push_back({false, scaled(unit * (jitter ? intra_jitter[marks % 4] : 1.0))});
}
const bool word = index + 1 < size && text[index + 1] == ' ';
const double spacing = style == Style::Farnsworth ? 1.5 : style == Style::WideFarnsworth ? 2.0 : 1.0;
const double gap = word ? (jitter ? word_jitter[words++ % 3] : 7.0)
: (jitter ? letter_jitter[letters++ % 4] : 3.0);
result.push_back({false, scaled(unit * gap * spacing)});
}
return result;
}
static std::string run(uint8_t wpm, Style style, uint32_t cadence, uint16_t& learned) {
constexpr const char* text = "CQ DE TEST 73 SOS";
mesh::MorseRx decoder;
assert(decoder.start(wpm, mesh::MorseRx::MaxDurationMillis, 0) == mesh::MorseRxResult::Started);
const auto segments = waveform(text, mesh::MorseTx::unitMillis(wpm), style);
uint32_t elapsed = 0;
for (; elapsed < 600; elapsed += cadence) decoder.sample(-120.0f, elapsed);
size_t position = 0;
uint32_t end = elapsed + segments[0].duration;
while (position < segments.size()) {
while (elapsed >= end && ++position < segments.size()) end += segments[position].duration;
if (position == segments.size()) break;
decoder.sample(segments[position].keyed ? -60.0f : -120.0f, elapsed);
elapsed += cadence;
}
const uint32_t finish = elapsed + mesh::MorseTx::unitMillis(wpm) * 8U;
for (; elapsed < finish; elapsed += cadence) decoder.sample(-120.0f, elapsed);
assert(decoder.active() && !decoder.truncated());
decoder.stop(elapsed);
learned = decoder.unitMillis();
return decoder.text();
}
int main() {
const struct { const char* name; Style style; } styles[] = {
{"standard", Style::Standard}, {"jitter", Style::Jitter},
{"slowing", Style::Slowing}, {"speeding", Style::Speeding},
{"mixed", Style::Mixed}, {"farnsworth_1_5", Style::Farnsworth},
{"farnsworth_2_0", Style::WideFarnsworth}
};
unsigned failures = 0;
for (uint8_t wpm : {5, 10, 15, 20, 25, 30, 40}) {
for (uint32_t cadence : {1U, 2U}) {
for (const auto& style : styles) {
uint16_t learned = 0;
const auto actual = run(wpm, style.style, cadence, learned);
// The final quiet word gap intentionally leaves one trailing space.
// Compare every captured byte; do not normalize extra spaces or noise.
const bool exact = actual == "CQ DE TEST 73 SOS ";
printf("%u\t%u\t%s\t%u\t%s\t%s\n", wpm, cadence, style.name, learned,
exact ? "PASS" : "FAIL", actual.c_str());
#ifdef REQUIRE_HUMAN_PASS
if (!exact) ++failures;
#endif
}
}
}
return failures ? 1 : 0;
}
+175
View File
@@ -0,0 +1,175 @@
#include <helpers/MorseTx.h>
#include <cassert>
#include <cstdio>
#include <cstring>
#include <initializer_list>
#include <string>
#include <type_traits>
// Exercise the actual timing methods independently of RF threshold acquisition.
// Production gains no test-only public API or state.
#define private public
#include <helpers/MorseRx.h>
#undef private
using mesh::MorseRx;
static_assert(std::is_same<decltype(MorseRx::_unit_q5), uint16_t>::value,
"fractional timing must reuse the 16-bit timing field");
#if defined(MESH_MORSE_HIL) && MESH_MORSE_HIL
static_assert(sizeof(MorseRx) == 4168 + sizeof(void*), "HIL decoder size changed");
#else
static_assert(sizeof(MorseRx) == 4168, "production decoder must remain 4168 bytes");
#endif
static void begin(MorseRx& rx, uint8_t wpm, uint32_t now = 100) {
assert(rx.start(wpm, 300000, now) == mesh::MorseRxResult::Started);
assert(rx._unit_q5 == uint32_t(rx._nominal_unit) * 32);
assert(rx.unitMillis() == rx._nominal_unit);
}
static void mark(MorseRx& rx, uint32_t duration) {
rx.recordMark(duration);
assert(!rx._bad_pattern && rx._symbols == 1);
rx.flushLetter();
}
static void fractional_drift_and_integer_negative_control() {
for (uint8_t wpm : {1, 25, 60, 120, 200, 240}) {
for (int difference : {-1, 1}) {
for (bool dash : {false, true}) {
MorseRx rx;
begin(rx, wpm);
const uint16_t nominal = rx._nominal_unit;
const uint16_t observed = uint16_t(int(nominal) + difference);
uint16_t old_unit = nominal;
for (unsigned count = 0; count < 64; ++count) {
old_unit = uint16_t((uint32_t(old_unit) * 7 + observed + 4) / 8);
mark(rx, uint32_t(observed) * (dash ? 3 : 1));
}
assert(old_unit == nominal); // the former whole-ms update never moves
assert(rx.unitMillis() == observed);
const int error = int(rx._unit_q5) - int(observed) * 32;
assert(error >= -4 && error <= 4);
mesh::MorseRxDiagnostics stats;
rx.diagnostics(stats);
assert(stats.unit_ms == observed); // API still reports rounded ms
}
}
}
}
static void first_ambiguous_and_warmed_borderline_marks() {
MorseRx first;
begin(first, 240);
first.recordMark(10);
first.flushLetter();
assert(std::strcmp(first.text(), "T") == 0); // no history can identify this first ambiguous mark
MorseRx trained;
begin(trained, 240);
mark(trained, 6);
assert(trained._unit_q5 == 164 && trained.unitMillis() == 5); // 5.125 ms, not 5 ms
trained.clear(); // retain timing, clear only the already captured training E
trained.recordMark(10);
trained.flushLetter();
assert(std::strcmp(trained.text(), "E") == 0);
assert(trained._unit_q5 == 168); // observed 10 is still clamped to the existing 6-ms upper limit
}
static void unchanged_bounds_and_checked_duration_limits() {
for (uint8_t wpm : {1, 25, 60, 120, 200, 240}) {
MorseRx rx;
begin(rx, wpm);
const uint16_t nominal = rx._nominal_unit;
const uint32_t lower = uint32_t(nominal) * 3 / 4;
const uint32_t upper = uint32_t(nominal) * 5 / 4;
for (unsigned count = 0; count < 64; ++count) {
mark(rx, 3 * (upper + 1));
assert(rx._unit_q5 >= lower * 32 && rx._unit_q5 <= upper * 32);
}
assert(rx.unitMillis() == upper);
for (unsigned count = 0; count < 96; ++count) {
mark(rx, nominal / 2);
assert(rx._unit_q5 >= lower * 32 && rx._unit_q5 <= upper * 32);
}
assert(rx.unitMillis() == lower);
begin(rx, wpm);
const uint16_t before = rx._unit_q5;
rx.recordMark(uint32_t(nominal) * 7);
assert(rx._bad_pattern && rx._symbols == 0 && rx._unit_q5 == before);
rx.clear();
rx.recordMark(nominal / 4);
assert(rx._symbols == 0 && rx._unit_q5 == before); // rejected sub-third-dot must not train timing
}
}
static void fractional_gap_comparisons() {
MorseRx rx;
begin(rx, 240);
rx._unit_q5 = 132; // 4.125 ms: faster than the nominal five-ms unit
rx._last_edge = 100;
rx._code = 2;
rx._symbols = 1;
rx.flushGap(109);
assert(rx.length() == 0); // nine ms is still shorter than 2.25 fractional units
rx.flushGap(110);
assert(std::strcmp(rx.text(), "E") == 0);
rx.flushGap(122);
assert(std::strcmp(rx.text(), "E") == 0); // 22 ms is shorter than 5.5 fractional units
rx.flushGap(123);
assert(std::strcmp(rx.text(), "E ") == 0);
begin(rx, 240);
rx._unit_q5 = 192; // a slower learned unit must not inflate the gap thresholds
rx._last_edge = 100;
rx._code = 2;
rx._symbols = 1;
rx.flushGap(111);
assert(rx.length() == 0);
rx.flushGap(112);
assert(std::strcmp(rx.text(), "E") == 0);
rx.flushGap(127);
assert(std::strcmp(rx.text(), "E") == 0);
rx.flushGap(128);
assert(std::strcmp(rx.text(), "E ") == 0);
}
struct SampledReceiver {
MorseRx rx;
uint32_t now;
explicit SampledReceiver(uint32_t started) : now(started) {
begin(rx, 240, now);
level(-110, 520);
}
void level(float dbm, uint32_t duration) {
for (uint32_t sample = 0; sample < duration; ++sample) rx.sample(dbm, now++);
}
};
static void actual_envelope_and_rollover() {
for (uint32_t started : {100U, 0xffffff00U}) {
SampledReceiver first(started);
first.level(-80, 10);
first.level(-110, 40);
first.rx.stop(first.now);
assert(std::strcmp(first.rx.text(), "T ") == 0);
SampledReceiver trained(started);
trained.level(-80, 6);
trained.level(-110, 20);
assert(trained.rx._unit_q5 == 164);
trained.level(-80, 10);
trained.level(-110, 40);
trained.rx.stop(trained.now);
assert(std::strcmp(trained.rx.text(), "EE ") == 0);
assert(trained.rx._unit_q5 == 168 && !trained.rx.active());
}
}
int main() {
fractional_drift_and_integer_negative_control();
first_ambiguous_and_warmed_borderline_marks();
unchanged_bounds_and_checked_duration_limits();
fractional_gap_comparisons();
actual_envelope_and_rollover();
std::printf("Q5 timing checks passed; MorseRx size: %zu bytes\n", sizeof(MorseRx));
}
+20 -3
View File
@@ -14,6 +14,8 @@ MOCKS = r'''
#include <vector>
#include <algorithm>
#include <array>
#include <cstdio>
#include <helpers/bridges/RS232Heartbeat.h>
#define MAX_TRANS_UNIT 255
using portMUX_TYPE=int;
#define portMUX_INITIALIZER_UNLOCKED 0
@@ -84,6 +86,7 @@ class Stream {
public:
std::vector<uint8_t> input,output;size_t position=0,write_limit=1000;unsigned reads=0;
int available(){return input.size()-position;}
int availableForWrite(){return static_cast<int>(write_limit);}
int read(){++reads;return position<input.size()?input[position++]:-1;}
size_t write(const uint8_t* bytes,size_t length){
length=std::min(length,write_limit);output.insert(output.end(),bytes,bytes+length);return length;
@@ -127,6 +130,12 @@ static void append(HardwareSerial& serial,const std::vector<uint8_t>& frame){
static mesh::Packet packet(uint8_t id,size_t length=4){
mesh::Packet p;p.length=length;memset(p.data,id,sizeof(p.data));return p;
}
static std::vector<uint8_t> uart_frame(const mesh::Packet& p){
const uint16_t sum=BridgeBase::fletcher16(p.data,p.length);
std::vector<uint8_t> result={0xc0,0x3e,uint8_t(p.length>>8),uint8_t(p.length)};
result.insert(result.end(),p.data,p.data+p.length);
result.push_back(uint8_t(sum>>8));result.push_back(uint8_t(sum));return result;
}
static void complete(ESPNowBridge& bridge,int status=ESP_NOW_SEND_SUCCESS){
const uint8_t mac[6]={255,255,255,255,255,255};
bridge.onDataSent(mac,static_cast<esp_now_send_status_t>(status));bridge.loop();
@@ -172,9 +181,17 @@ int main(){
serial.position=serial.input.size();append(serial,uart_frame(5));mgr.exhausted=true;
bridge.loop();assert(bridge._rx_packet_ready);bridge.end();mgr.exhausted=false;bridge.begin();
bridge.loop();assert((mgr.received==std::vector<uint8_t>{1,2,4})); // held frame cannot cross restart
auto outgoing=packet(6);serial.write_limit=2;bridge.sendPacket(&outgoing);
assert(!bridge._seen_packets.wasSeen(&outgoing)); // failed admission can retry
serial.write_limit=1000;bridge.sendPacket(&outgoing);assert(bridge._seen_packets.wasSeen(&outgoing));
auto outgoing=packet(6),waiting=packet(8);serial.write_limit=2;bridge.sendPacket(&outgoing);
assert(bridge._seen_packets.wasSeen(&outgoing)&&bridge._tx_size==10&&bridge._tx_pos==2);
// A short hardware write retains the accepted complete frame. A caller's
// additional packet cannot overwrite or interleave it, and remains retryable.
bridge.sendPacket(&waiting);assert(!bridge._seen_packets.wasSeen(&waiting));
assert(bridge._tx_size==10&&bridge._tx_pos==4);
serial.write_limit=1000;bridge.loop();assert(serial.output==uart_frame(outgoing)&&bridge._tx_size==0);
bridge.sendPacket(&outgoing);assert(serial.output==uart_frame(outgoing)); // duplicate does not replay the short-written prefix
bridge.sendPacket(&waiting);assert(bridge._seen_packets.wasSeen(&waiting));
auto expected=uart_frame(outgoing);auto tail=uart_frame(waiting);expected.insert(expected.end(),tail.begin(),tail.end());
assert(serial.output==expected); // retry preserves byte-exact ordering
bridge.allowed=false;auto blocked=packet(7);auto total=serial.output.size();
bridge.sendPacket(&blocked);assert(serial.output.size()==total);
bridge.allowed=true;serial.input.clear();serial.position=0;
+7 -3
View File
@@ -127,8 +127,6 @@ struct RadioLibWrapper : mesh::Radio {
uint8_t _morse_wpm=mesh::MorseTx::DefaultWpm;
uint32_t _morse_generation[2]={};
@MORSE_RX_FIELDS@
bool _morse_rx_owned=false, _morse_rx_fsk_mode=false;
uint8_t _morse_rx_read_errors=0;
bool receiver_allocation_ok=true, fail_morse_params=false;
float rssi=-110, morse_bandwidth=0;
uint32_t rssi_latency=0;
@@ -187,6 +185,7 @@ struct RadioLibWrapper : mesh::Radio {
virtual float getCurrentRSSI() { ++rssi_reads; g_mock_millis+=rssi_latency; return rssi; }
bool setTxPower(int8_t dbm);
@NATIVE_HOOKS@
#if MESH_ENABLE_MORSE_RX || !defined(STM32_PLATFORM)
@RX_HOOKS@
@RX_START_HOOKS@
// Explicit stand-in for a proven native-RSSI modem. Concrete production
@@ -197,6 +196,7 @@ struct RadioLibWrapper : mesh::Radio {
if (!applyParams(freq,morseReceiverBandwidthKHz(),7,5)) return RADIOLIB_ERR_UNKNOWN;
return RADIOLIB_ERR_NONE;
}
#endif
virtual bool supportsRadioDeepInit() const { return deep_supported; }
uint8_t beginReconfigure();
void endReconfigure(bool resume) { if (resume) startRecv(); }
@@ -236,6 +236,9 @@ struct RadioLibWrapper : mesh::Radio {
void onSendFinished() override {}
};
@METHODS@
#if MESH_ENABLE_MORSE_RX || !defined(STM32_PLATFORM)
// SX1276/DAC declarations are exercised on their actual non-STM targets;
// compact integrated-STM builds do not compile these other native chips.
struct CustomSX1276Wrapper : RadioLibWrapper {
CustomSX1276Wrapper() { reset_ok=true; }
@SX1276_METHODS@
@@ -251,6 +254,7 @@ struct DacCarrier : CustomSX1276Wrapper {
void writeGainControl(uint8_t value) { gain=value; }
@DAC_METHODS@
};
#endif
static void advance(uint32_t ms) { g_mock_millis+=ms; }
int main() {
using Result=mesh::RadioParamApplyResult;
@@ -472,7 +476,7 @@ def production_harness():
code = HARNESS.replace('@METHODS@', '\n'.join(extract_transition(s) for s in signatures))
header = (ROOT/'src/helpers/radiolib/RadioLibWrappers.h').read_text()
fields_start = header.rfind('#if MESH_ENABLE_MORSE_RX',0,header.index('mesh::MorseRx* _morse_rx'))
fields_end = header.index(' bool _morse_rx_owned',fields_start)
fields_end = header.index(' // End Morse RX state.',fields_start)
code = code.replace('@MORSE_RX_FIELDS@',header[fields_start:fields_end])
code = code.replace('@MORSE_DESTRUCTOR@',method(header,'~RadioLibWrapper('))
code = code.replace('@NATIVE_HOOKS@', '\n'.join(method(header, s) for s in (
+237
View File
@@ -0,0 +1,237 @@
#!/usr/bin/env python3
"""Execute lab-only device TX timing, command ownership and runner metadata."""
from pathlib import Path
import argparse
import importlib.util
import sys
import types
import unittest
from unittest.mock import patch
from test_morse_tx import compile_run, portable_radio_header
ROOT = Path(__file__).resolve().parents[1]
class MorseHilTimingTests(unittest.TestCase):
def test_console_correlates_delayed_echo_response_and_closes_failed_session_safely(self):
serial = types.ModuleType("serial")
serial_tools = types.ModuleType("serial.tools")
serial_tools.list_ports = types.SimpleNamespace(comports=lambda: [])
with patch.dict(sys.modules, {"serial":serial,"serial.tools":serial_tools}):
spec = importlib.util.spec_from_file_location("timed_console", ROOT / "tools/hil/morse_bench.py")
bench = importlib.util.module_from_spec(spec)
spec.loader.exec_module(bench)
class Clock:
now=0
def monotonic(self): return self.now
class Port:
in_waiting=0
def __init__(self,clock,chunks):
self.clock=clock; self.chunks=list(chunks); self.writes=[]; self.closed=False
def write(self,data): self.writes.append(data)
def read(self,length):
if self.chunks and self.clock.now >= self.chunks[0][0]:
return self.chunks.pop(0)[1]
self.clock.now += .5
return b""
def close(self): self.closed=True
def console(companion,chunks):
clock=Clock(); device=object.__new__(bench.Console)
device.serial_number="verified-test"; device.companion=companion
device.commands=[]; device.failed=False; device.port=Port(clock,chunks)
return device,clock
command="set morse.hil.timing 0,0,0,1"
stale=b"set morse.wpm 25\r\n -> OK - morse.wpm 25\r\n> "
own_echo=(command+"\r\n").encode()
device,clock=console(True,[(0,stale),(4,own_echo),(6,b" -> OK - HIL timing\r\n"),(7,b"> ")])
with patch.object(bench,"time",clock):
reply=device.command(command)
self.assertEqual(reply,"> "+command+"\r\n -> OK - HIL timing\r\n> ")
self.assertGreaterEqual(clock.now,7)
self.assertNotIn("morse.wpm",reply)
self.assertEqual(device.port.writes,[(command+"\r\n").encode()])
self.assertFalse(device.failed)
# An infrastructure reply has no owned ASCII prompt; its response must
# still follow this request's exact echo rather than an unrelated line.
device,clock=console(False,[(0,b"old\r\n -> stale\r\n"),
(4,b"get morse\r\n\r\n -> > off;\r\n")])
with patch.object(bench,"time",clock):
self.assertEqual(device.command("get morse"),"get morse\r\n\r\n -> > off;\r\n")
for chunks in ([(0,stale)],[(0,own_echo+b" -> delayed\r\n")],
[(0,own_echo+b"> ")]):
with self.subTest(chunks=chunks):
device,clock=console(True,chunks)
with patch.object(bench,"time",clock):
with self.assertRaisesRegex(RuntimeError,"Incomplete CLI response"):
device.command(command)
self.assertTrue(device.failed)
device.port.chunks.append((clock.now,b" -> late\r\n> "))
with self.assertRaisesRegex(RuntimeError,"refusing further"):
device.command("morse stop")
device.close()
self.assertTrue(device.port.closed)
self.assertEqual(device.port.writes,[(command+"\r\n").encode()])
self.assertTrue(device.commands[-1]["failed"])
self.assertIn("+00:00",device.commands[-1]["utc"])
# A complete CLI error is synchronized and can safely be followed up.
device,clock=console(True,[(0,b"set tx -9\r\n -> Error: radio busy\r\n> ")])
with patch.object(bench,"time",clock):
with self.assertRaisesRegex(RuntimeError,"radio busy"):
device.command("set tx -9")
self.assertFalse(device.failed)
calls=[]
device.command=lambda text,**options: (calls.append((text,options)),"OK")[1]
with patch.object(bench,"time",clock): device.start_when_idle("set tx -9")
self.assertEqual(calls,[("set tx -9",{"timeout":15,"allow_error":True})])
def test_actual_scheduler_exact_planner_snapshot_wrap_and_shipping_layout(self):
fixture = (ROOT / "test/fixtures/morse_hil_timing.cpp").read_text(encoding="ascii")
for hil in (0, 1):
with self.subTest(hil=hil):
compile_run(self, fixture, flags=(f"-DMESH_MORSE_HIL={hil}", "-DMESH_MORSE_MAX_WPM=255"))
def test_shared_cli_bounds_busy_replies_no_persistence_and_disabled_error(self):
prefix = (ROOT / "test/fixtures/morse_cli.cpp").read_text(encoding="ascii").split("int main() {", 1)[0]
prefix = prefix.replace("struct TestRadio : mesh::Radio {", "struct TestRadio : mesh::Radio {\n bool packet=false; bool isReceiving() override { return packet; }")
code = prefix + r'''
int main() {
TestRadio radio;
struct Guard { char reply[157]; uint32_t after=0xaabbccdd; } out;
const auto run=[&](const char* text) {
assert(mesh::handleMorseCommand(&radio,text,out.reply,sizeof(out.reply)));
assert(out.after==0xaabbccdd && strlen(out.reply)<sizeof(out.reply));
return std::string(out.reply);
};
#if defined(MESH_MORSE_HIL) && MESH_MORSE_HIL
assert(run("get morse.hil.timing").find("jitter=0%; drift=0%; extraGap=0%; seed=1")!=std::string::npos);
assert(run("set morse.hil.timing 20,-20,50,4294967295").find("OK -")==0);
assert(run("get morse.hil.timing").find("jitter=20%; drift=-20%; extraGap=50%; seed=4294967295")!=std::string::npos);
assert(mesh::saves==0 && radio.starts==0);
for(const char* invalid : {"", "1,2,3", "1,2,3,4,5", "21,0,0,1", "0,21,0,1", "0,-21,0,1",
"0,0,51,1", "0,0,0,0", "0,0,0,4294967296", "1.5,0,0,1", "1,0,0,1x", "nan,0,0,1"}) {
const auto command=std::string("set morse.hil.timing ")+invalid;
assert(run(command.c_str()).find("Error:")==0);
assert(mesh::morseHilTiming().seed==0xffffffff);
}
for(bool* busy : {&radio.active,&radio.cw,&radio.rx_active,&radio.packet}) {
*busy=true;
assert(run("set morse.hil.timing 0,0,0,1").find("busy")!=std::string::npos);
assert(run("get morse.hil.timing").find("seed=4294967295")!=std::string::npos);
*busy=false;
}
radio.receiving=false;
assert(run("set morse.hil.timing 0,0,0,1").find("busy")!=std::string::npos);
radio.receiving=true;
assert(run("get morse.hil.timing extra").find("Error:")==0);
assert(run("morse.hil.timing 0,0,0,1").find("Error:")==0);
assert(run("set morse.hil.timing 0,0,0,1").find("OK -")==0);
assert(mesh::saves==0 && radio.starts==0 && radio.stops==0);
#else
(void)run;
for(const char* command : {"get morse.hil.timing","set morse.hil.timing 0,0,0,1","morse.hil.timing"}) {
strcpy(out.reply,"unchanged");
assert(!mesh::handleMorseCommand(&radio,command,out.reply,sizeof(out.reply)));
assert(!strcmp(out.reply,"unchanged") && out.after==0xaabbccdd);
}
assert(mesh::saves==0 && radio.starts==0 && radio.stops==0);
#endif
}
'''
fs_mock = (ROOT / "test/fixtures/radio_profiles/mocks/helpers/IdentityStore.h").read_text(encoding="ascii")
for hil in (0, 1):
with self.subTest(hil=hil):
compile_run(self, code, flags=("-Wno-unused-parameter", f"-DMESH_MORSE_HIL={hil}"),
headers={"Dispatcher.h": portable_radio_header(), "helpers/IdentityStore.h": fs_mock})
def test_bench_human_arguments_readback_and_standard_reset(self):
serial = types.ModuleType("serial")
serial_tools = types.ModuleType("serial.tools")
serial_tools.list_ports = types.SimpleNamespace(comports=lambda: [])
with patch.dict(sys.modules, {"serial":serial,"serial.tools":serial_tools}):
spec = importlib.util.spec_from_file_location("human_bench", ROOT / "tools/hil/morse_bench.py")
bench = importlib.util.module_from_spec(spec)
spec.loader.exec_module(bench)
human = bench.parse_human_timing("15,-10,25,12345")
self.assertEqual(human, {"jitter_percent":15,"drift_percent":-10,"extra_gap_percent":25,"seed":12345})
for invalid in ("", "1,2,3", "21,0,0,1", "0,21,0,1", "0,0,51,1", "0,0,0,0", "0,0,0,4294967296", "1.5,0,0,1"):
with self.subTest(invalid=invalid), self.assertRaises(argparse.ArgumentTypeError):
bench.parse_human_timing(invalid)
device = object.__new__(bench.Console)
commands=[]
device.start_when_idle=lambda command: commands.append(command)
device.command=lambda command: (commands.append(command),"> jitter=15%; drift=-10%; extraGap=25%; seed=12345; volatile HIL TX only")[1]
self.assertIn("seed=12345",device.set_hil_timing(human))
self.assertEqual(commands,["set morse.hil.timing 15,-10,25,12345","get morse.hil.timing"])
device.command=lambda command: "> jitter=0%; drift=0%; extraGap=0%; seed=1"
with self.assertRaisesRegex(RuntimeError,"readback mismatch"):
device.set_hil_timing(human)
device.start_when_idle=lambda command: (_ for _ in ()).throw(RuntimeError("Error: HIL-only"))
self.assertEqual(device.set_hil_timing(),"production image: standard timing only")
with self.assertRaisesRegex(RuntimeError,"HIL-only"):
device.set_hil_timing(human)
device.start_when_idle=lambda command: (_ for _ in ()).throw(RuntimeError("Error: radio busy"))
with self.assertRaisesRegex(RuntimeError,"busy"):
device.set_hil_timing()
device.start_when_idle=lambda command: (_ for _ in ()).throw(RuntimeError("set morse.hil.timing 0,0,0,1: Error: unknown setting: morse.hil.timing"))
self.assertEqual(device.set_hil_timing(),"production image: standard timing only")
with self.assertRaisesRegex(RuntimeError,"unknown setting"):
device.set_hil_timing(human)
device.failed=True
with self.assertRaisesRegex(RuntimeError,"unknown setting"):
device.set_hil_timing()
def test_actual_trial_records_device_profile_without_relaxing_exact_text(self):
serial = types.ModuleType("serial")
serial_tools = types.ModuleType("serial.tools")
serial_tools.list_ports = types.SimpleNamespace(comports=lambda: [])
with patch.dict(sys.modules, {"serial":serial,"serial.tools":serial_tools}):
spec = importlib.util.spec_from_file_location("human_trial", ROOT / "tools/hil/morse_bench.py")
bench = importlib.util.module_from_spec(spec)
spec.loader.exec_module(bench)
actions=[]
class Device:
def __init__(self,name,decoded="SOS"):
self.serial_number=name; self.decoded=decoded
def command(self,command):
actions.append((self.serial_number,command))
return "> off;" if command=="get morse" else "OK"
def set_hil_timing(self,timing):
actions.append((self.serial_number,"device timing",timing))
return "> jitter=15%; drift=10%; extraGap=25%; seed=12345"
def start_when_idle(self,command): return self.command(command)
def capture(self): return self.decoded
human=bench.parse_human_timing("15,10,25,12345")
with patch.object(bench.time,"sleep"):
result=bench.trial(Device("tx"),Device("rx"," SOS "),25,"SOS",human_timing=human)
self.assertTrue(result["passed"])
self.assertEqual(result["human_timing"],human)
self.assertIn("seed=12345",result["tx_timing_status"])
self.assertLess(actions.index(("tx","device timing",human)),actions.index(("tx","morse send SOS")))
for decoded in ("E SOS", "SOS E", "S OS", "SO?"):
with self.subTest(decoded=decoded),patch.object(bench.time,"sleep"):
result=bench.trial(Device("tx"),Device("rx",decoded),25,"SOS",human_timing=human)
self.assertFalse(result["passed"])
self.assertEqual(result["decoded"],decoded)
class Output:
text=None
def exists(self): return False
def write_text(self,text): self.text=text
output=Output(); opened=[]; supplied=[]
class Console:
def __init__(self,identity): self.commands=[]; opened.append(identity)
def setup(self,frequency): pass
def close(self): pass
def trial(*args,**kwargs): supplied.append(kwargs); return {"passed":True}
with patch.object(bench,"Console",Console),patch.object(bench,"trial",trial), \
patch.object(bench,"Path",lambda path:output),patch("builtins.print"), \
patch.object(sys,"argv",["bench","--output","memory","--rates","25","--messages","1","--human-timing"]):
bench.main()
self.assertEqual(len(opened),2)
self.assertEqual([call["human_timing"] for call in supplied],[human,human])
import json
self.assertEqual(json.loads(output.text)["human_timing"],human)
if __name__ == "__main__":
unittest.main()
+5 -5
View File
@@ -120,19 +120,19 @@ class BenchControlTests(unittest.TestCase):
def __init__(self,chunks): self.chunks=iter(chunks); self.reads=0; self.writes=[]
def write(self,data): self.writes.append(data)
def read(self,length): self.reads+=1; return next(self.chunks,b"")
for parts in ((b"set tempradio 909.5,500,5,5,30\r\n",b" OK\r\n",b"> "),
(b"get morse\r\n -> > off;\r\n",b"> ")):
for command,parts in (("set tempradio 909.5,500,5,5,30",(b"set tempradio 909.5,500,5,5,30\r\n",b" OK\r\n",b"> ")),
("get morse",(b"get morse\r\n -> > off;\r\n",b"> "))):
receiver=object.__new__(actual_bench.Console)
receiver.companion=True; receiver.serial_number="test"; receiver.commands=[]; receiver.port=Port(parts)
with patch.object(actual_bench,"time",types.SimpleNamespace(monotonic=lambda:0)):
reply=receiver.command("set tempradio 909.5,500,5,5,30")
reply=receiver.command(command)
self.assertEqual(reply,b"".join(parts).decode())
self.assertEqual(receiver.port.reads,len(parts))
self.assertEqual(receiver.port.writes,[b"set tempradio 909.5,500,5,5,30\r\n"])
self.assertEqual(receiver.port.writes,[(command+"\r\n").encode()])
receiver=object.__new__(actual_bench.Console)
receiver.companion=True; receiver.serial_number="test"; receiver.commands=[]
receiver.port=Port((b"set tempradio 909.5,500,5,5,30\r\n> ",))
times=iter((0,0,4))
times=iter((0,0,11))
with patch.object(actual_bench,"time",types.SimpleNamespace(monotonic=lambda:next(times))):
with self.assertRaisesRegex(RuntimeError,"Incomplete CLI response"):
receiver.command("set tempradio 909.5,500,5,5,30")
+33 -5
View File
@@ -162,10 +162,36 @@ template<typename T,typename=void> struct HasCapturePointer : std::false_type {}
template<typename T> struct HasCapturePointer<T,std::void_t<decltype(T::_morse_rx)>> : std::true_type {};
template<typename T,typename=void> struct HasCaptureAllocator : std::false_type {};
template<typename T> struct HasCaptureAllocator<T,std::void_t<decltype(&T::canAllocateMorseReceiver)>> : std::true_type {};
template<typename T,typename=void> struct HasCaptureOwner : std::false_type {};
template<typename T> struct HasCaptureOwner<T,std::void_t<decltype(T::_morse_rx_owned)>> : std::true_type {};
template<typename T,typename=void> struct HasCaptureReadErrors : std::false_type {};
template<typename T> struct HasCaptureReadErrors<T,std::void_t<decltype(T::_morse_rx_read_errors)>> : std::true_type {};
template<typename T,typename=void> struct HasFskState : std::false_type {};
template<typename T> struct HasFskState<T,std::void_t<decltype(T::_morse_rx_fsk_mode)>> : std::true_type {};
template<typename T,typename=void> struct HasReceivePreparation : std::false_type {};
template<typename T> struct HasReceivePreparation<T,std::void_t<decltype(&T::prepareMorseReceiver)>> : std::true_type {};
template<typename T,typename=void> struct HasReceiveStart : std::false_type {};
template<typename T> struct HasReceiveStart<T,std::void_t<decltype(&T::startMorseReceiver)>> : std::true_type {};
template<typename T,typename=void> struct HasReceiveRead : std::false_type {};
template<typename T> struct HasReceiveRead<T,std::void_t<decltype(&T::readMorseRssi)>> : std::true_type {};
template<typename T,typename=void> struct HasReceiveBandwidth : std::false_type {};
template<typename T> struct HasReceiveBandwidth<T,std::void_t<decltype(&T::morseReceiverBandwidthKHz)>> : std::true_type {};
int main() {
static_assert(MESH_ENABLE_MORSE_RX==EXPECTED_RX,"STM32 RX opt-in must be explicit");
static_assert(HasCapturePointer<STMReceive>::value==bool(EXPECTED_RX),"disabled RX must exclude capture metadata");
static_assert(HasCaptureAllocator<STMReceive>::value==bool(EXPECTED_RX),"disabled RX must exclude allocation machinery");
static_assert(HasCaptureOwner<STMReceive>::value==bool(EXPECTED_RX),"disabled RX must exclude ownership state");
static_assert(HasCaptureReadErrors<STMReceive>::value==bool(EXPECTED_RX),"disabled RX must exclude read-error state");
#if MESH_ENABLE_MORSE_RX || !defined(STM32_PLATFORM)
constexpr bool expected_native_hooks=true;
#else
constexpr bool expected_native_hooks=false;
#endif
static_assert(HasFskState<STMReceive>::value==expected_native_hooks,"compact STM must exclude the unused FSK byte");
static_assert(HasReceivePreparation<STMReceive>::value==expected_native_hooks,"compact STM must exclude native RX preparation");
static_assert(HasReceiveStart<STMReceive>::value==expected_native_hooks,"compact STM must exclude native RX start");
static_assert(HasReceiveRead<STMReceive>::value==expected_native_hooks,"compact STM must exclude native RSSI read");
static_assert(HasReceiveBandwidth<STMReceive>::value==expected_native_hooks,"compact STM must exclude native bandwidth hook");
advance(0);
STMReceive w;
#if MESH_ENABLE_MORSE_RX
@@ -197,11 +223,13 @@ int main() {
arduino = ("#pragma once\n#include <cstdint>\n#include <cmath>\n#include <cstdio>\n"
"#include <cstdlib>\n#include <cstring>\ninline uint32_t g_mock_millis=0;\n"
"inline uint32_t millis() { return g_mock_millis; }\n")
for enabled in (0,1):
with self.subTest(explicit_rx_opt_in=bool(enabled)):
flags = ["-Wno-unused-parameter", "-DSTM32_PLATFORM", f"-DEXPECTED_RX={enabled}"]
if enabled:
flags.append("-DMESH_ENABLE_MORSE_RX=1")
for platform, enabled in (("STM32_PLATFORM",0),("STM32_PLATFORM",1),(None,0)):
with self.subTest(platform=platform, explicit_rx_opt_in=bool(enabled)):
flags = ["-Wno-unused-parameter", f"-DEXPECTED_RX={enabled}"]
if platform:
flags.append(f"-D{platform}")
if enabled or not platform:
flags.append(f"-DMESH_ENABLE_MORSE_RX={enabled}")
compile_run(self, code, flags=flags, headers={
"Dispatcher.h": portable_radio_header(), "Arduino.h": arduino})
+50
View File
@@ -0,0 +1,50 @@
#!/usr/bin/env python3
"""Measure exact-text decoding of plausible manual Morse timing variations."""
from pathlib import Path
import unittest
from test_morse_tx import compile_run
ROOT = Path(__file__).resolve().parents[1]
class HumanMorseTimingTests(unittest.TestCase):
def test_actual_hil_sender_scheduler_decodes_human_variations_exactly(self):
code = (ROOT / "test/fixtures/morse_rx_hil_human.cpp").read_text(encoding="ascii")
output = compile_run(self, code, flags=("-DMESH_MORSE_HIL=1", "-DMESH_MORSE_MAX_WPM=240",
"-DMESH_MORSE_HIL_FAST_OFF_DEBOUNCE=1"))
rows = [line.split("\t") for line in output.splitlines()]
self.assertEqual(len(rows), 154)
for row in rows:
with self.subTest(wpm=row[0], sample_ms=row[1], timing=row[2]):
self.assertEqual(row[3], "PASS")
self.assertEqual(row[4], "CQ DE TEST 73 SOS ")
def actual_rows(self):
code = (ROOT / "test/fixtures/morse_rx_human.cpp").read_text(encoding="ascii")
output = compile_run(self, code)
rows = [line.split("\t") for line in output.splitlines()]
self.assertEqual(len(rows), 98)
return rows
def test_actual_decoder_supported_human_timing_is_exact_without_normalization(self):
rows = [row for row in self.actual_rows() if row[2] != "farnsworth_2_0"]
self.assertEqual(len(rows), 84)
failures = [row for row in rows if row[4] != "PASS" or row[5] != "CQ DE TEST 73 SOS "]
self.assertEqual(failures, [], "Strict human timing matrix failures:\n" +
"\n".join("\t".join(row) for row in failures))
def test_doubled_character_spacing_is_explicitly_unsupported_not_a_feature_pass(self):
# Without an explicit spacing hint, six dot units can denote either
# a stretched letter gap or a short word gap. Characterize that known
# ambiguity honestly; never count its spaced output as an exact decode.
rows = [row for row in self.actual_rows() if row[2] == "farnsworth_2_0"]
self.assertEqual(len(rows), 14)
for row in rows:
with self.subTest(wpm=row[0], sample_ms=row[1]):
self.assertEqual(row[4], "FAIL")
self.assertEqual(row[5], "C Q D E T E S T 7 3 S O S ")
self.assertNotEqual(row[5], "CQ DE TEST 73 SOS ")
if __name__ == "__main__":
unittest.main()
+24
View File
@@ -0,0 +1,24 @@
"""Execute the real fractional Morse timing without hardware or PlatformIO."""
from pathlib import Path
import unittest
from test_morse_tx import compile_run
ROOT = Path(__file__).resolve().parents[1]
class MorseRxTimingTests(unittest.TestCase):
def test_actual_q5_drift_classification_bounds_fractional_gaps_rollover_and_size(self):
code = (ROOT / "test/fixtures/morse_rx_timing.cpp").read_text(encoding="ascii")
output = compile_run(self, code, flags=("-DMESH_MORSE_MAX_WPM=240", "-DMESH_MORSE_HIL=0"))
self.assertIn("Q5 timing checks passed; MorseRx size: 4168 bytes", output)
def test_hil_fast_off_keeps_the_same_fractional_timing_and_allocation_layout(self):
code = (ROOT / "test/fixtures/morse_rx_timing.cpp").read_text(encoding="ascii")
output = compile_run(self, code, flags=("-DMESH_MORSE_MAX_WPM=240", "-DMESH_MORSE_HIL=1",
"-DMESH_MORSE_HIL_FAST_OFF_DEBOUNCE=1"))
self.assertIn("Q5 timing checks passed", output)
if __name__ == "__main__":
unittest.main()
+26
View File
@@ -41,6 +41,32 @@ def compile_run(testcase, code, includes=(), flags=(), headers=None):
class MorseTxTests(unittest.TestCase):
def test_flash_table_preserves_every_byte_of_the_original_itu_lookup(self):
compile_run(self, r'''
#include <helpers/MorseTx.h>
#include <cassert>
static uint8_t original(char c) {
if (c >= 'a' && c <= 'z') c -= 'a' - 'A';
static const uint8_t letters[] = {5,24,26,12,2,18,14,16,4,23,13,20,7,6,15,22,29,10,8,3,9,17,11,25,27,28};
static const uint8_t digits[] = {63,47,39,35,33,32,48,56,60,62};
if (c >= 'A' && c <= 'Z') return letters[c - 'A'];
if (c >= '0' && c <= '9') return digits[c - '0'];
switch (c) {
case '.': return 85; case ',': return 115; case '?': return 76;
case '\'': return 94; case '!': return 107; case '/': return 50;
case '(': return 54; case ')': return 109; case '&': return 40;
case ':': return 120; case ';': return 106; case '=': return 49;
case '+': return 42; case '-': return 97; case '_': return 77;
case '"': return 82; case '$': return 137; case '@': return 90;
default: return 0;
}
}
int main() {
for (unsigned byte = 0; byte < 256; ++byte)
assert(mesh::MorseTx::codeFor(char(byte)) == original(char(byte)));
}
''')
def test_production_encoder_alphabet_punctuation_limits_and_exact_timing(self):
code = (ROOT / "test/fixtures/morse_encoder.cpp").read_text(encoding="ascii")
compile_run(self, code)