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

+73 -3
View File
@@ -17,6 +17,29 @@ inline const char* morseUsageError() {
#endif
}
#if defined(MESH_MORSE_HIL) && MESH_MORSE_HIL
inline bool parseMorseHilTiming(const char* argument, MorseHilTimingConfig& timing) {
if (!argument || strlen(argument) >= 64) return false;
char fields[64];
strcpy(fields, argument);
char* values[4] = {fields, nullptr, nullptr, nullptr};
for (unsigned index = 0; index < 3; ++index) {
char* separator = strchr(values[index], ',');
if (!separator) return false;
*separator = 0; values[index + 1] = separator + 1;
}
if (strchr(values[3], ',')) return false;
uint32_t jitter = 0, gap = 0, seed = 0;
int32_t drift = 0;
if (!cli::parseUnsignedIntegerStrict(values[0], jitter) || jitter > 20
|| !cli::parseIntegerStrict(values[1], drift) || drift < -20 || drift > 20
|| !cli::parseUnsignedIntegerStrict(values[2], gap) || gap > 50
|| !cli::parseUnsignedIntegerStrict(values[3], seed) || !seed) return false;
timing = MorseHilTimingConfig(uint8_t(jitter), int8_t(drift), uint8_t(gap), seed);
return true;
}
#endif
// Intercept only an explicitly authenticated remote callback. Local USB/BLE
// commands keep immediate listening; a nonzero timestamp alone is not authority.
inline bool handleMorseReplyCommand(MorseReplyHandoff& handoff, Radio* radio,
@@ -184,12 +207,55 @@ inline bool handleMorseCommand(Radio* radio, const char* command,
const bool base = length == 5 && !strncmp(key, "morse", 5);
const bool frequency = length == 10 && !strncmp(key, "morse.freq", 10);
const bool speed = length == 9 && !strncmp(key, "morse.wpm", 9);
if (!base && !frequency && !speed) return false;
if (!radio || (!radio->supportsMorseTx() && !radio->supportsMorseRx())) {
#if defined(MESH_MORSE_HIL) && MESH_MORSE_HIL
const bool hil_timing = length == 16 && !strncmp(key, "morse.hil.timing", 16);
#endif
if (!base && !frequency && !speed
#if defined(MESH_MORSE_HIL) && MESH_MORSE_HIL
&& !hil_timing
#endif
) return false;
if (!radio || (!radio->supportsMorseTx()
#if MESH_ENABLE_MORSE_RX
&& !radio->supportsMorseRx()
#endif
)) {
snprintf(reply, capacity, "Error: Morse unsupported on this radio");
return true;
}
const char* args = cli::skipRecentRepeaterSpaces(key + length);
#if defined(MESH_MORSE_HIL) && MESH_MORSE_HIL
if (hil_timing) {
if (query) {
if (*args) snprintf(reply, capacity, "Error: unexpected argument");
else {
const auto& timing = morseHilTiming();
snprintf(reply, capacity, "> jitter=%u%%; drift=%d%%; extraGap=%u%%; seed=%lu; volatile HIL TX only",
unsigned(timing.jitter_percent), int(timing.drift_percent),
unsigned(timing.extra_gap_percent), (unsigned long)timing.seed);
}
return true;
}
if (!setting) {
snprintf(reply, capacity, "Error: use get/set morse.hil.timing");
return true;
}
if (radio->isCarrierWaveActive() || radio->isMorseTxActive() || radio->isMorseRxActive()
|| !radio->isInRecvMode() || radio->isReceiving()) {
snprintf(reply, capacity, "Error: radio busy; HIL timing changes require idle RX");
return true;
}
MorseHilTimingConfig timing;
if (!parseMorseHilTiming(args, timing) || !setMorseHilTiming(timing)) {
snprintf(reply, capacity, "Error: use jitter0-20,drift-20..20,extraGap0-50,seed1..4294967295");
return true;
}
snprintf(reply, capacity, "OK - HIL Morse timing %u,%d,%u,%lu; volatile TX only",
unsigned(timing.jitter_percent), int(timing.drift_percent),
unsigned(timing.extra_gap_percent), (unsigned long)timing.seed);
return true;
}
#endif
const auto& current = morseSettings();
if ((query || (base && !*args && !setting)) && !morseSettingsUsable()) {
snprintf(reply, capacity, "Error: saved Morse settings unavailable; verify and save morse.freq");
@@ -210,7 +276,11 @@ inline bool handleMorseCommand(Radio* radio, const char* command,
snprintf(reply, capacity, "Error: verify and save morse.freq before changing Morse WPM");
return true;
}
if (radio->isCarrierWaveActive() || radio->isMorseTxActive() || radio->isMorseRxActive()) {
if (radio->isCarrierWaveActive() || radio->isMorseTxActive()
#if MESH_ENABLE_MORSE_RX
|| radio->isMorseRxActive()
#endif
) {
snprintf(reply, capacity, "Error: radio busy; stop Morse/CW before changing settings");
return true;
}
+25 -12
View File
@@ -152,7 +152,8 @@ public:
clear();
_started = _last_edge = now;
_until = now + duration_ms;
_nominal_unit = _unit = MorseTx::unitMillis(wpm);
_nominal_unit = MorseTx::unitMillis(wpm);
_unit_q5 = uint16_t(uint32_t(_nominal_unit) * UnitScale);
_noise = _signal = 0;
_samples = 0;
_last_sample_at = now;
@@ -180,7 +181,7 @@ public:
size_t length() const { return _length; }
bool truncated() const { return _truncated; }
float noiseDbm() const { return _have_noise ? _noise : -200.0f; }
uint16_t unitMillis() const { return _unit; }
uint16_t unitMillis() const { return uint16_t((_unit_q5 + UnitScale / 2) / UnitScale); }
void diagnostics(MorseRxDiagnostics& out) const {
out.noise_dbm = _have_noise ? _noise : NAN;
out.last_dbm = _last_rssi;
@@ -188,7 +189,7 @@ public:
out.maximum_dbm = _maximum_rssi;
out.samples = _samples;
out.max_sample_gap_ms = _max_sample_gap_ms;
out.unit_ms = _unit;
out.unit_ms = unitMillis();
out.read_errors = 0;
}
@@ -289,7 +290,7 @@ public:
traceSample(rssi_dbm, now, raw_keyed);
return;
}
uint16_t debounce = _unit / 4;
uint16_t debounce = _unit_q5 / (4 * UnitScale);
uint16_t minimum_debounce = 2;
#if defined(MESH_MORSE_HIL) && MESH_MORSE_HIL \
&& defined(MESH_MORSE_HIL_FAST_OFF_DEBOUNCE) \
@@ -331,13 +332,19 @@ public:
}
private:
// Keep fractional timing in the existing 16-bit field: a whole-ms 1/8 EMA
// has a four-ms rounding deadband and cannot adapt at fast Morse speeds.
// Q5 supports the full 1 WPM, +25% range without adding receiver memory.
static constexpr uint16_t UnitScale = 32;
static_assert((1200UL * 5 / 4) * UnitScale <= UINT16_MAX,
"fractional Morse timing must fit its existing 16-bit field");
char _capture[CaptureCapacity + 1] = {};
uint32_t _started = 0, _until = 0, _last_edge = 0, _candidate_at = 0;
float _noise = 0, _signal = 0;
float _last_rssi = NAN, _minimum_rssi = NAN, _maximum_rssi = NAN;
uint32_t _samples = 0;
uint32_t _last_sample_at = 0, _max_sample_gap_ms = 0;
uint16_t _length = 0, _unit = 0, _nominal_unit = 0;
uint16_t _length = 0, _unit_q5 = 0, _nominal_unit = 0;
uint8_t _code = 1, _symbols = 0;
bool _active = false, _keyed = false, _have_noise = false;
bool _floor_settled = false;
@@ -393,20 +400,26 @@ private:
// gaps. Never feed that fixed delay back into an even longer gap threshold.
// Faster-peer adaptation still lowers the threshold; slower peers have
// longer physical gaps and remain distinguishable at the nominal timing.
const uint16_t gap_unit = _unit < _nominal_unit ? _unit : _nominal_unit;
if (gap * 2UL >= uint32_t(gap_unit) * 5UL && !_letter_flushed) flushLetter();
if (gap >= uint32_t(gap_unit) * 6UL && !_word_flushed && _letter_flushed) {
const uint16_t nominal_q5 = uint16_t(uint32_t(_nominal_unit) * UnitScale);
const uint16_t gap_unit_q5 = _unit_q5 < nominal_q5 ? _unit_q5 : nominal_q5;
// Ordinary +/-20% gap jitter still separates an intra-letter gap (<=1.2
// units) from a letter gap (>=2.4), and letters (<=3.6) from words (>=5.6).
// Keep some margin at 2.25/5.5 units rather than merging shortened gaps.
// This is not automatic Farnsworth-spacing or unknown-speed acquisition.
if (gap * 4UL * UnitScale >= uint32_t(gap_unit_q5) * 9UL && !_letter_flushed) flushLetter();
if (gap * 2UL * UnitScale >= uint32_t(gap_unit_q5) * 11UL && !_word_flushed && _letter_flushed) {
append(' ');
_word_flushed = true;
}
}
void recordMark(uint32_t duration_ms) {
if (duration_ms * 3UL < _unit) return; // sub-third-dot glitches
if (duration_ms > uint32_t(_unit) * 6UL || _symbols >= 7) {
const uint32_t duration_q5 = duration_ms * UnitScale;
if (duration_q5 * 3UL < _unit_q5) return; // sub-third-dot glitches
if (duration_q5 > uint32_t(_unit_q5) * 6UL || _symbols >= 7) {
_bad_pattern = true;
return;
}
const bool dash = duration_ms >= uint32_t(_unit) * 2UL;
const bool dash = duration_q5 >= uint32_t(_unit_q5) * 2UL;
_code = uint8_t((_code << 1) | (dash ? 1 : 0));
++_symbols;
uint32_t observed = dash ? (duration_ms + 1) / 3 : duration_ms;
@@ -414,7 +427,7 @@ private:
const uint32_t upper = uint32_t(_nominal_unit) * 5 / 4;
if (observed < lower) observed = lower;
if (observed > upper) observed = upper;
_unit = uint16_t((uint32_t(_unit) * 7 + observed + 4) / 8);
_unit_q5 = uint16_t((uint32_t(_unit_q5) * 7 + observed * UnitScale + 4) / 8);
}
};
+121 -15
View File
@@ -17,6 +17,69 @@ enum class MorseTxResult : uint8_t {
InvalidText, InvalidSpeed, TooLong, Failed
};
#if defined(MESH_MORSE_HIL) && MESH_MORSE_HIL
// Lab-only, volatile transmitter timing. Nothing is persisted or enabled by
// boot, and no production encoder fields or timing paths depend on this.
struct MorseHilTimingConfig {
uint8_t jitter_percent;
int8_t drift_percent;
uint8_t extra_gap_percent;
uint32_t seed;
MorseHilTimingConfig(uint8_t jitter = 0, int8_t drift = 0,
uint8_t extra_gap = 0, uint32_t random_seed = 1)
: jitter_percent(jitter), drift_percent(drift),
extra_gap_percent(extra_gap), seed(random_seed) {}
bool valid() const {
return jitter_percent <= 20 && drift_percent >= -20 && drift_percent <= 20
&& extra_gap_percent <= 50 && seed != 0;
}
};
inline MorseHilTimingConfig& morseHilTimingStorage() {
static MorseHilTimingConfig timing;
return timing;
}
inline const MorseHilTimingConfig& morseHilTiming() { return morseHilTimingStorage(); }
inline bool setMorseHilTiming(const MorseHilTimingConfig& timing) {
if (!timing.valid()) return false;
morseHilTimingStorage() = timing;
return true;
}
// The pre-key duration planner and live scheduler use exactly this sequence.
// Carry fractional milliseconds between phases so fast dots do not silently
// lose all sub-ms jitter. Native hardware transitions still rebase deadlines.
class MorseHilTimingSequence {
public:
void begin(const MorseHilTimingConfig& config, uint16_t unit, uint8_t characters) {
_config = config; _unit = unit; _characters = characters;
_random = config.seed; _fraction = 5000;
}
uint16_t phase(uint8_t units, bool mark, uint8_t character) {
if (!_config.jitter_percent && !_config.drift_percent && !_config.extra_gap_percent)
return uint16_t(units * _unit);
int32_t basis_points = 10000;
if (_characters > 1)
basis_points += int32_t(_config.drift_percent) * 100 * character / (_characters - 1);
if (_config.jitter_percent) {
_random ^= _random << 13; _random ^= _random >> 17; _random ^= _random << 5;
const uint32_t spread = uint32_t(_config.jitter_percent) * 100;
basis_points += int32_t(_random % (spread * 2 + 1)) - int32_t(spread);
}
uint64_t scaled = uint64_t(units) * _unit * uint32_t(basis_points);
if (!mark && units >= 3) scaled = scaled * (100 + _config.extra_gap_percent) / 100;
scaled += _fraction;
const uint32_t milliseconds = uint32_t(scaled / 10000);
_fraction = uint16_t(scaled % 10000);
return uint16_t(milliseconds ? milliseconds : 1);
}
private:
MorseHilTimingConfig _config;
uint32_t _random = 1;
uint16_t _unit = 0, _fraction = 5000;
uint8_t _characters = 0;
};
#endif
// A keyed, unmodulated carrier has no LoRa receive-bandwidth setting. Its
// occupied spectrum is determined by the keying envelope and oscillator.
// Keep its centre at least 10 kHz beyond both configured LoRa passbands;
@@ -46,21 +109,18 @@ public:
static uint8_t codeFor(char character) {
if (character >= 'a' && character <= 'z') character -= '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
// A single flash-resident ASCII table avoids a punctuation switch/jump
// table and keeps the complete alphabet on compact targets. Zero entries
// remain unsupported; lowercase still uses its uppercase ITU code.
static const uint8_t codes[] = {
107,82,0,137,0,40,94,54,109,0,42,115,97,85,50, // ! through /
63,47,39,35,33,32,48,56,60,62, // 0 through 9
120,106,0,49,0,76,90, // : through @
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,
0,0,0,0,77 // [ through _
};
static const uint8_t digits[] = {63,47,39,35,33,32,48,56,60,62};
if (character >= 'A' && character <= 'Z') return letters[character - 'A'];
if (character >= '0' && character <= '9') return digits[character - '0'];
switch (character) {
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;
}
const uint8_t index = uint8_t(uint8_t(character) - uint8_t('!'));
return index < sizeof(codes) ? codes[index] : 0;
}
static uint8_t symbolCount(uint8_t code) {
@@ -97,7 +157,30 @@ public:
}
if (length > MaxTextLength) return MorseTxResult::TooLong;
if (!have_character) return MorseTxResult::InvalidText;
const uint32_t duration = units * unit;
uint32_t duration = units * unit;
#if defined(MESH_MORSE_HIL) && MESH_MORSE_HIL
// A fixed seed is restarted for every message, independent of prior sends.
const auto config = morseHilTiming();
if (!config.valid()) return MorseTxResult::Failed;
uint8_t characters = 0;
for (size_t index = 0; text[index]; ++index) if (text[index] != ' ') ++characters;
MorseHilTimingSequence sequence;
sequence.begin(config, unit, characters);
duration = 0;
uint8_t character = 0;
have_character = have_space = false;
for (size_t index = 0; text[index]; ++index) {
if (text[index] == ' ') { if (have_character) have_space = true; continue; }
if (have_character) duration += sequence.phase(have_space ? 7 : 3, false, character);
const uint8_t code = codeFor(text[index]);
const uint8_t count = symbolCount(code);
for (uint8_t bit = count; bit; --bit) {
duration += sequence.phase((code & (1U << (bit - 1))) ? 3 : 1, true, character);
if (bit > 1) duration += sequence.phase(1, false, character);
}
++character; have_character = true; have_space = false;
}
#endif
if (duration > MaxDurationMillis) return MorseTxResult::TooLong;
if (duration_ms) *duration_ms = duration;
return MorseTxResult::Started;
@@ -125,7 +208,15 @@ public:
_count = symbolCount(_code);
_active = _keyed = true;
_remaining = duration;
#if defined(MESH_MORSE_HIL) && MESH_MORSE_HIL
uint8_t characters = 0;
for (size_t index = 0; _text[index]; ++index) if (_text[index] != ' ') ++characters;
_hil_timing.begin(morseHilTiming(), _unit, characters);
_hil_character = 0;
_phase_ms = _hil_timing.phase(markUnits(), true, _hil_character);
#else
_phase_ms = markUnits() * _unit;
#endif
_next = now + _phase_ms;
_hard_end = now + MaxDurationMillis;
return MorseTxResult::Started;
@@ -166,14 +257,25 @@ public:
_symbol = 0;
_code = codeFor(_text[_character]);
_count = symbolCount(_code);
#if defined(MESH_MORSE_HIL) && MESH_MORSE_HIL
++_hil_character;
#endif
}
#if defined(MESH_MORSE_HIL) && MESH_MORSE_HIL
_phase_ms = _hil_timing.phase(gap, false, _hil_character);
#else
_phase_ms = gap * _unit;
#endif
// Rebase on actual service time. Never key a burst of missed edges.
_next = now + _phase_ms;
return Edge::KeyUp;
}
_keyed = true;
#if defined(MESH_MORSE_HIL) && MESH_MORSE_HIL
_phase_ms = _hil_timing.phase(markUnits(), true, _hil_character);
#else
_phase_ms = markUnits() * _unit;
#endif
_next = now + _phase_ms;
return Edge::KeyDown;
}
@@ -184,6 +286,10 @@ private:
uint16_t _unit = 0, _phase_ms = 0;
uint8_t _character = 0, _symbol = 0, _code = 0, _count = 0;
bool _active = false, _keyed = false;
#if defined(MESH_MORSE_HIL) && MESH_MORSE_HIL
MorseHilTimingSequence _hil_timing;
uint8_t _hil_character = 0;
#endif
uint8_t markUnits() const { return (_code & (1U << (_count - 1 - _symbol))) ? 3 : 1; }
};
+21 -3
View File
@@ -235,7 +235,11 @@ bool RadioLibWrapper::setTxPower(int8_t dbm) {
// A CW power-meter sweep may re-key the carrier. During Morse that would
// turn an inter-symbol gap into RF and corrupt the text, so keep the whole
// message exclusive (including cleanup retries).
if ((_morse_owned || _morse_rx_owned) && _cw_active) return false;
if ((_morse_owned
#if MESH_ENABLE_MORSE_RX
|| _morse_rx_owned
#endif
) && _cw_active) return false;
if (_cw_active) {
if (_cw_stopping) return false;
// Permit meter sweeps through the board's normal power/PA calibration.
@@ -1006,7 +1010,9 @@ void RadioLibWrapper::checkReceiveMode(uint32_t now) {
uint32_t RadioLibWrapper::carrierWaveRemainingMillis() const {
if (!_cw_active || _cw_stopping) return 0;
if (_morse_owned) return morseTxRemainingMillis();
#if MESH_ENABLE_MORSE_RX
if (_morse_rx_owned) return morseRxRemainingMillis();
#endif
const int32_t remaining = static_cast<int32_t>(_cw_until - millis());
return remaining > 0 ? static_cast<uint32_t>(remaining) : 0;
}
@@ -1015,13 +1021,21 @@ mesh::RadioParamApplyResult RadioLibWrapper::setCarrierWave(uint8_t profile, uin
using Result = mesh::RadioParamApplyResult;
// The shared emergency stop also covers chips exposing Morse without the
// older profile-CW CLI capability.
if (!duration_ms && (_morse_owned || _morse_rx_owned)) return stopCarrierWave() ? Result::APPLIED : Result::FAILED;
if (!duration_ms && (_morse_owned
#if MESH_ENABLE_MORSE_RX
|| _morse_rx_owned
#endif
)) return stopCarrierWave() ? Result::APPLIED : Result::FAILED;
if (!supportsCarrierWave()) return Result::FAILED;
if (!duration_ms) return !_cw_active || stopCarrierWave() ? Result::APPLIED : Result::FAILED;
if (profile > 1 || duration_ms > CarrierWaveMaxMillis || !_params_valid
|| !_profiles.canTransmit(profile)) return Result::FAILED;
if (_cw_active) {
if (_morse_owned || _morse_rx_owned || _cw_stopping || profile != _cw_profile
if (_morse_owned
#if MESH_ENABLE_MORSE_RX
|| _morse_rx_owned
#endif
|| _cw_stopping || profile != _cw_profile
|| _cw_generation != _profiles.generation[profile]) return Result::BUSY;
_cw_until = static_cast<uint32_t>(millis()) + duration_ms;
return Result::APPLIED;
@@ -1402,13 +1416,17 @@ bool RadioLibWrapper::stopCarrierWave() {
return false;
}
_morse_owned = false;
#if MESH_ENABLE_MORSE_RX
_morse_rx_owned = false;
#endif
_board->setRadioTestActive(false);
return true;
}
bool RadioLibWrapper::serviceCarrierWave() {
#if MESH_ENABLE_MORSE_RX
if (serviceMorseRx()) return true;
#endif
if (serviceMorseTx()) return true;
if (_cw_active) {
const uint32_t now = millis();
+11 -2
View File
@@ -123,10 +123,15 @@ protected:
#endif
float _morse_rx_frequency = mesh::MorseTx::DefaultFrequencyMHz;
uint32_t _morse_rx_next_sample = 0, _morse_capture_generation = 0;
#endif
bool _morse_rx_owned = false;
bool _morse_rx_fsk_mode = false;
uint8_t _morse_rx_read_errors = 0;
#endif
#if MESH_ENABLE_MORSE_RX || !defined(STM32_PLATFORM)
// Non-STM wrappers retain their native hook declarations for an explicit
// RX-disabled build; those hooks may still compile but cannot be admitted.
bool _morse_rx_fsk_mode = false;
#endif
// End Morse RX state.
bool stopCarrierWave();
bool serviceCarrierWave();
bool serviceMorseTx();
@@ -247,6 +252,9 @@ protected:
}
virtual int16_t enterMorseCarrier() { return _radio->transmitDirect(); }
virtual int16_t leaveMorseCarrier() { return _radio->standby(); }
#if MESH_ENABLE_MORSE_RX || !defined(STM32_PLATFORM)
// Compact integrated-STM builds cannot receive Morse. Do not pin unused
// native RX thunks and vtable slots in their already full application slot.
virtual float morseReceiverBandwidthKHz() const { return 0.0f; }
virtual int16_t prepareMorseReceiver(float frequency_mhz) {
(void)frequency_mhz;
@@ -258,6 +266,7 @@ protected:
virtual float readMorseRssi() { return getCurrentRSSI(); }
#if MESH_ENABLE_MORSE_RX
virtual bool canAllocateMorseReceiver() const;
#endif
#endif
// Native-CW radios keep their modem. Reapply cached power in case a meter
// sweep failed halfway through; SX127x also rebuilds its LoRa configuration.