Add bounded Morse receive and negotiated RS232 autosleep
Add native narrow-band CW capture, ACK-first remote sessions, retained LoRa-readable pages, checked restoration and transport-safe progress. Add stock-compatible negotiated heartbeat/autosleep and recovery. Include host regressions and identity-bound HIL runners; keep unverified faster tuning HIL-only and document outstanding hardware validation.
This commit is contained in:
1 parent
d2bea5fb10
commit
ca9caece53
152 files changed
+12631
-149
No files matched your search
@@ -6,6 +6,8 @@
|
||||
#include <Utils.h>
|
||||
#include <RadioProfiles.h>
|
||||
#include <helpers/MeshtextConfig.h>
|
||||
#include <helpers/MorseTx.h>
|
||||
#include <helpers/MorseRx.h>
|
||||
#ifndef RADIO_LIVENESS_SOFT_ONLY
|
||||
#include <helpers/RadioLivenessTracker.h>
|
||||
#endif
|
||||
@@ -42,6 +44,47 @@ public:
|
||||
virtual bool isCarrierWaveActive() const { return false; }
|
||||
virtual uint8_t carrierWaveProfile() const { return 0; }
|
||||
virtual uint32_t carrierWaveRemainingMillis() const { return 0; }
|
||||
virtual bool supportsMorseTx() const { return false; }
|
||||
virtual MorseTxResult startMorseTx(float frequency_mhz, uint8_t wpm, const char* text) {
|
||||
(void)frequency_mhz; (void)wpm; (void)text;
|
||||
return MorseTxResult::Unsupported;
|
||||
}
|
||||
virtual MorseTxResult stopMorseTx() { return MorseTxResult::Unsupported; }
|
||||
virtual bool isMorseTxActive() const { return false; }
|
||||
virtual float morseTxFrequency() const { return MorseTx::DefaultFrequencyMHz; }
|
||||
virtual uint8_t morseTxWpm() const { return MorseTx::DefaultWpm; }
|
||||
virtual uint32_t morseTxRemainingMillis() const { return 0; }
|
||||
virtual bool supportsMorseRx() const { return false; }
|
||||
virtual MorseRxResult startMorseRx(float frequency_mhz, uint8_t wpm, uint32_t duration_ms) {
|
||||
(void)frequency_mhz; (void)wpm; (void)duration_ms;
|
||||
return MorseRxResult::Unsupported;
|
||||
}
|
||||
virtual MorseRxResult stopMorseRx() { return MorseRxResult::Unsupported; }
|
||||
virtual bool isMorseRxActive() const { return false; }
|
||||
virtual bool morseRxRecovering() const { return false; }
|
||||
virtual bool morseRxLearning() const { return false; }
|
||||
virtual float morseRxFrequency() const { return MorseTx::DefaultFrequencyMHz; }
|
||||
virtual float morseRxBandwidthKHz() const { return 0; }
|
||||
virtual uint32_t morseRxRemainingMillis() const { return 0; }
|
||||
virtual uint32_t morseCaptureGeneration() const { return 0; }
|
||||
virtual bool morseRxDiagnostics(MorseRxDiagnostics& out) const { out = {}; return false; }
|
||||
virtual size_t morseCaptureLength() const { return 0; }
|
||||
virtual bool morseCaptureTruncated() const { return false; }
|
||||
virtual const char* morseCaptureText() const { return ""; }
|
||||
virtual size_t readMorseCapture(size_t offset, char* out, size_t capacity) const {
|
||||
(void)offset;
|
||||
if (out && capacity) out[0] = 0;
|
||||
return 0;
|
||||
}
|
||||
virtual void clearMorseCapture() { }
|
||||
#if defined(MESH_MORSE_HIL) && MESH_MORSE_HIL
|
||||
virtual size_t morseTraceLength() const { return 0; }
|
||||
virtual uint32_t morseTraceTotal() const { return 0; }
|
||||
virtual bool morseTraceTruncated() const { return false; }
|
||||
virtual bool readMorseTrace(size_t offset, MorseRssiTraceEntry& out) const {
|
||||
(void)offset; (void)out; return false;
|
||||
}
|
||||
#endif
|
||||
virtual void begin() { }
|
||||
virtual RadioProfiles* profiles() { return nullptr; }
|
||||
virtual const RadioProfiles* profiles() const { return nullptr; }
|
||||
|
||||
@@ -419,14 +419,17 @@ void BaseChatMesh::onPeerDataRecv(mesh::Packet* packet, uint8_t type, int sender
|
||||
temp[4] = (TXT_TYPE_CLI_DATA << 2);
|
||||
|
||||
auto reply_pkt = createDatagram(PAYLOAD_TYPE_TXT_MSG, from.id, secret, temp, 5 + text_len);
|
||||
onCLIReplyPrepared(from, reply_pkt);
|
||||
bool queued = false;
|
||||
if (reply_pkt) {
|
||||
if (from.out_path_len == OUT_PATH_UNKNOWN) {
|
||||
sendFloodScoped(from, reply_pkt, CLI_REPLY_DELAY_MILLIS);
|
||||
queued = sendFloodScoped(from, reply_pkt, CLI_REPLY_DELAY_MILLIS);
|
||||
} else {
|
||||
sendDirect(reply_pkt, from.getPath(), from.out_path_len, CLI_REPLY_DELAY_MILLIS);
|
||||
queued = sendDirect(reply_pkt, from.getPath(), from.out_path_len, CLI_REPLY_DELAY_MILLIS);
|
||||
}
|
||||
}
|
||||
}
|
||||
onCLIReplyQueued(from, reply_pkt, queued);
|
||||
} else onCLIReplyQueued(from, nullptr, false);
|
||||
} else if (flags == TXT_TYPE_SIGNED_PLAIN) {
|
||||
if (len < 9) return; // timestamp, flags and complete author prefix
|
||||
const uint32_t previous_sync_since = from.sync_since;
|
||||
|
||||
@@ -176,6 +176,10 @@ protected:
|
||||
virtual void onMessageRecv(const ContactInfo& contact, mesh::Packet* pkt, uint32_t sender_timestamp, const char *text) = 0;
|
||||
virtual void onCommandDataRecv(const ContactInfo& contact, mesh::Packet* pkt, uint32_t sender_timestamp, const char *text) = 0;
|
||||
virtual void onCLICommandRecv(const ContactInfo& contact, mesh::Packet* pkt, uint32_t sender_timestamp, const char *text, char* reply) = 0;
|
||||
// Default-no-op admission hooks let a radio-owning maintenance operation
|
||||
// wait for its exact encrypted CLI response without changing the protocol.
|
||||
virtual void onCLIReplyPrepared(const ContactInfo&, mesh::Packet*) {}
|
||||
virtual void onCLIReplyQueued(const ContactInfo&, mesh::Packet*, bool) {}
|
||||
// Return true only after retaining/delivering the room post. A false result
|
||||
// leaves the catch-up cursor unchanged and suppresses the delivery ACK.
|
||||
virtual bool onSignedMessageRecv(const ContactInfo& contact, mesh::Packet* pkt, uint32_t sender_timestamp, const uint8_t *sender_prefix, const char *text) = 0;
|
||||
|
||||
@@ -17,6 +17,13 @@ inline bool handleCarrierWaveCommand(Radio* radio, const char* command,
|
||||
if (!secondary && !(length == 2 && !strncmp(text, "cw", 2))) return false;
|
||||
const char* name = secondary ? "cw2" : "cw";
|
||||
const char* args = cli::skipRecentRepeaterSpaces(text + length);
|
||||
// The shared maintenance guard also excludes packet work during Morse RX.
|
||||
// It is not evidence that the transmitter is emitting a continuous carrier.
|
||||
if (radio && !*args && (radio->isMorseRxActive() || radio->isMorseTxActive())) {
|
||||
snprintf(reply, capacity, "> Morse %s owns radio; use get morse",
|
||||
radio->isMorseRxActive() ? "RX" : "TX");
|
||||
return true;
|
||||
}
|
||||
if (!radio || !radio->supportsCarrierWave()) {
|
||||
snprintf(reply, capacity, "Error: CW unsupported on this radio");
|
||||
return true;
|
||||
|
||||
+153
-7
@@ -5,7 +5,12 @@
|
||||
#include "HilStartupTrace.h"
|
||||
#include <helpers/ui/DisplayPowerSettings.h>
|
||||
#include <helpers/BatteryChargeCLI.h>
|
||||
#include <helpers/MorseCLI.h>
|
||||
#include <helpers/MorseLoopPolicy.h>
|
||||
#include "CLICommandUtils.h"
|
||||
#ifdef WITH_RS232_BRIDGE
|
||||
#include "bridges/RS232PowerSettings.h"
|
||||
#endif
|
||||
#include "GpsPowerPolicy.h"
|
||||
#include "FloodAdvertCLI.h"
|
||||
#include "StorageLayout.h"
|
||||
@@ -155,8 +160,19 @@ static bool isGpioConfig(const char* config) {
|
||||
#endif
|
||||
|
||||
void CommonCLI::loop() {
|
||||
_radio_profiles.loop();
|
||||
loopManagement();
|
||||
#if MESH_ENABLE_MORSE_RX
|
||||
if (_morse_reply.pending()) {
|
||||
const ClientInfo* actor = _acl->getClient(_morse_reply.actor(), PUB_KEY_SIZE);
|
||||
const auto& settings = mesh::morseSettings();
|
||||
_morse_reply.service(_callbacks->getProfileRadio(), millis(),
|
||||
actor && actor->isAdmin(), mesh::morseSettingsUsable(),
|
||||
settings.frequency_khz, settings.wpm);
|
||||
}
|
||||
#endif
|
||||
if (!mesh::morseTimingActive(_callbacks->getProfileRadio())) {
|
||||
_radio_profiles.loop();
|
||||
loopManagement();
|
||||
}
|
||||
#if defined(ESP32_PLATFORM) || defined(USER_GPIO_CONTROL)
|
||||
_user_gpio.loop();
|
||||
UserGpio::Completion completion;
|
||||
@@ -749,6 +765,7 @@ static void formatSnrDbX4Short(char* dest, size_t dest_len, int16_t snr_x4) {
|
||||
void CommonCLI::loadPrefs(FILESYSTEM* fs) {
|
||||
mesh::hilStartupTrace("prefs_profiles_begin");
|
||||
_radio_profiles.begin(fs, _callbacks->getProfileRadio(), _rtc, true);
|
||||
mesh::loadMorseSettings(fs);
|
||||
mesh::hilStartupTrace("prefs_profiles_ready");
|
||||
_prefs->primary_radio_preamble = _radio_profiles.primaryPreamble();
|
||||
#if !defined(WITH_MQTT_BRIDGE) && (defined(ESP32_PLATFORM) || defined(RP2040_PLATFORM))
|
||||
@@ -785,6 +802,9 @@ void CommonCLI::loadPrefs(FILESYSTEM* fs) {
|
||||
_prefs->trace_when_repeat_off = 0;
|
||||
_prefs->ota_channel = 0;
|
||||
#ifdef WITH_RS232_BRIDGE
|
||||
_prefs->rs232_heartbeat = 1;
|
||||
_prefs->rs232_autosleep = 1;
|
||||
_prefs->rs232_idle_seconds = mesh::bridge::rs232power::DEFAULT_IDLE_SECONDS;
|
||||
_prefs->bridge_uart = WITH_RS232_BRIDGE_UART;
|
||||
#else
|
||||
_prefs->bridge_uart = 0;
|
||||
@@ -848,6 +868,12 @@ void CommonCLI::loadPrefs(FILESYSTEM* fs) {
|
||||
#endif
|
||||
#endif
|
||||
if (legacy && _prefs->loadSerial(legacy)) {
|
||||
#ifdef WITH_RS232_BRIDGE
|
||||
// Observer JSON migration can use the checked writer directly. Normalize
|
||||
// runtime fields here too, not just the bytes emitted by that writer.
|
||||
mesh::bridge::rs232power::sanitize(_prefs->rs232_heartbeat,
|
||||
_prefs->rs232_autosleep, _prefs->rs232_idle_seconds);
|
||||
#endif
|
||||
loaded = true;
|
||||
is_upgrade = true;
|
||||
#if defined(WITH_RS232_BRIDGE) && defined(RS232_BRIDGE_MERGED) \
|
||||
@@ -1031,6 +1057,11 @@ void CommonCLI::loadPrefsInt(FILESYSTEM* fs, const char* filename) {
|
||||
_prefs->gps_sync_interval_hours = 0;
|
||||
_prefs->ota_channel = 0;
|
||||
_prefs->rs232_bridge_enabled = 0;
|
||||
#ifdef WITH_RS232_BRIDGE
|
||||
_prefs->rs232_heartbeat = 1;
|
||||
_prefs->rs232_autosleep = 1;
|
||||
_prefs->rs232_idle_seconds = mesh::bridge::rs232power::DEFAULT_IDLE_SECONDS;
|
||||
#endif
|
||||
#if defined(RP2040_PLATFORM)
|
||||
File file = fs->open(filename, "r");
|
||||
#else
|
||||
@@ -1468,6 +1499,15 @@ void CommonCLI::loadPrefsInt(FILESYSTEM* fs, const char* filename) {
|
||||
#ifdef WITH_RS232_BRIDGE
|
||||
has_runtime_rs232_intent = rs232_profile == 0xB1
|
||||
&& rs232_intent <= 1;
|
||||
if (has_runtime_rs232_intent && file.available() > 0) {
|
||||
uint8_t power_tail[mesh::bridge::rs232power::PREFS_SIZE];
|
||||
const size_t count = file.read(power_tail, sizeof(power_tail));
|
||||
if (!mesh::bridge::rs232power::decodePrefs(power_tail, count,
|
||||
_prefs->rs232_heartbeat, _prefs->rs232_autosleep,
|
||||
_prefs->rs232_idle_seconds)) {
|
||||
_com_prefs_needs_upgrade = true;
|
||||
}
|
||||
}
|
||||
#endif
|
||||
}
|
||||
}
|
||||
@@ -1871,6 +1911,13 @@ static bool writeCommonPrefsImage(Writer& writer, NodePrefs* prefs) {
|
||||
const uint8_t rs232_profile = 0;
|
||||
#endif
|
||||
WRITE_COMMON_PREFS(&rs232_profile); // UART intent belongs to this profile
|
||||
#ifdef WITH_RS232_BRIDGE
|
||||
uint8_t power_tail[mesh::bridge::rs232power::PREFS_SIZE];
|
||||
mesh::bridge::rs232power::encodePrefs(power_tail, prefs->rs232_heartbeat,
|
||||
prefs->rs232_autosleep,
|
||||
prefs->rs232_idle_seconds);
|
||||
WRITE_COMMON_PREFS_BYTES(power_tail, sizeof(power_tail));
|
||||
#endif
|
||||
|
||||
#undef WRITE_COMMON_PREFS_BYTES
|
||||
#undef WRITE_COMMON_PREFS
|
||||
@@ -1885,6 +1932,10 @@ void CommonCLI::savePrefs(FILESYSTEM* fs, PrefsSaveRouting::Scope scope) {
|
||||
_common_save_succeeded = false;
|
||||
_prefs->usb_debug_enabled = _prefs->usb_debug_enabled == 1 ? 1 : 0;
|
||||
_prefs->trace_when_repeat_off = _prefs->trace_when_repeat_off == 1 ? 1 : 0;
|
||||
#ifdef WITH_RS232_BRIDGE
|
||||
mesh::bridge::rs232power::sanitize(_prefs->rs232_heartbeat,
|
||||
_prefs->rs232_autosleep, _prefs->rs232_idle_seconds);
|
||||
#endif
|
||||
#if defined(WITH_RS232_BRIDGE) && !defined(WITH_MQTT_BRIDGE)
|
||||
_prefs->rs232_bridge_enabled = _prefs->bridge_enabled == 1 ? 1 : 0;
|
||||
#elif !defined(WITH_RS232_BRIDGE)
|
||||
@@ -2052,6 +2103,13 @@ void CommonCLI::savePrefs(FILESYSTEM* fs, PrefsSaveRouting::Scope scope) {
|
||||
const uint8_t rs232_profile = 0;
|
||||
#endif
|
||||
file.write(&rs232_profile, sizeof(rs232_profile)); // UART intent belongs to this profile
|
||||
#ifdef WITH_RS232_BRIDGE
|
||||
uint8_t power_tail[mesh::bridge::rs232power::PREFS_SIZE];
|
||||
mesh::bridge::rs232power::encodePrefs(power_tail, _prefs->rs232_heartbeat,
|
||||
_prefs->rs232_autosleep,
|
||||
_prefs->rs232_idle_seconds);
|
||||
file.write(power_tail, sizeof(power_tail));
|
||||
#endif
|
||||
|
||||
_common_save_succeeded = file.commit();
|
||||
if (!_common_save_succeeded) {
|
||||
@@ -2866,6 +2924,11 @@ void CommonCLI::handleCommand(uint32_t sender_timestamp, char* command, char* re
|
||||
if (handleManagementCommand(command, reply)) return;
|
||||
if (mesh::wireless::control().handle(command, reply, 160, millis(),
|
||||
_callbacks->wirelessCommandSource(sender_timestamp))) return;
|
||||
// Infrastructure callers can already have reflected a three-byte CLI
|
||||
// request prefix into the same 160-byte reply. Reserve it for bulk pages.
|
||||
if (mesh::handleMorseReplyCommand(_morse_reply, _callbacks->getProfileRadio(),
|
||||
command, reply, 160 - 3, millis())) return;
|
||||
if (mesh::handleMorseCommand(_callbacks->getProfileRadio(), command, reply, 160 - 3)) return;
|
||||
if (_radio_profiles.handle(command, reply, 160, sender_timestamp != 0)) return;
|
||||
#if defined(ENABLE_OTA)
|
||||
const auto* ota_context = mesh::ota::ota_context_if_active();
|
||||
@@ -3928,6 +3991,59 @@ void CommonCLI::handleSetCmd(uint32_t sender_timestamp, char* command, char* rep
|
||||
}
|
||||
#endif
|
||||
#ifdef WITH_RS232_BRIDGE
|
||||
if (strncmp(config, "rs232.heartbeat ", 16) == 0) {
|
||||
bool enable = false;
|
||||
if (!parseOnOffStrict(config + 16, enable)) {
|
||||
strcpy(reply, "Error: use set rs232.heartbeat on|off");
|
||||
return;
|
||||
}
|
||||
const uint8_t previous = _prefs->rs232_heartbeat;
|
||||
_prefs->rs232_heartbeat = enable ? 1 : 0;
|
||||
if (!trySavePrefs()) {
|
||||
_prefs->rs232_heartbeat = previous;
|
||||
strcpy(reply, "Error: RS232 heartbeat not saved; unchanged");
|
||||
} else {
|
||||
strcpy(reply, enable ? "OK - RS232 heartbeat enabled" : "OK - heartbeat and standby disabled");
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (strncmp(config, "rs232.autosleep ", 16) == 0) {
|
||||
bool enable = false;
|
||||
const bool force = strcmp(config + 16, "force") == 0;
|
||||
if (!force && !parseOnOffStrict(config + 16, enable)) {
|
||||
strcpy(reply, "Error: use set rs232.autosleep on|off|force");
|
||||
return;
|
||||
}
|
||||
const uint8_t previous = _prefs->rs232_autosleep;
|
||||
_prefs->rs232_autosleep = force ? 2 : enable ? 1 : 0;
|
||||
if (!trySavePrefs()) {
|
||||
_prefs->rs232_autosleep = previous;
|
||||
strcpy(reply, "Error: RS232 autosleep not saved; unchanged");
|
||||
} else {
|
||||
strcpy(reply, force ? "OK - forced standby; stock/unknown peers can miss packets"
|
||||
: enable ? "OK - standby after peer heartbeat confirmed; stock stays active"
|
||||
: "OK - RS232 standby disabled");
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (strncmp(config, "rs232.idle ", 11) == 0) {
|
||||
uint32_t seconds = 0;
|
||||
if (!mesh::cli::parseUnsignedIntegerStrict(config + 11, seconds)
|
||||
|| seconds < mesh::bridge::rs232power::MIN_IDLE_SECONDS
|
||||
|| seconds > mesh::bridge::rs232power::MAX_IDLE_SECONDS) {
|
||||
strcpy(reply, "Error: use set rs232.idle 60..3600 seconds");
|
||||
return;
|
||||
}
|
||||
const uint16_t previous = _prefs->rs232_idle_seconds;
|
||||
_prefs->rs232_idle_seconds = static_cast<uint16_t>(seconds);
|
||||
if (!trySavePrefs()) {
|
||||
_prefs->rs232_idle_seconds = previous;
|
||||
strcpy(reply, "Error: RS232 idle not saved; unchanged");
|
||||
} else {
|
||||
sprintf(reply, "OK - RS232 idle %us", static_cast<unsigned>(seconds));
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (strncmp(config, "rs232.enabled ", 14) == 0) {
|
||||
bool enable = false;
|
||||
if (!parseOnOffStrict(config + 14, enable)) {
|
||||
@@ -3946,7 +4062,6 @@ void CommonCLI::handleSetCmd(uint32_t sender_timestamp, char* command, char* rep
|
||||
uint8_t& intent = _prefs->bridge_enabled;
|
||||
#endif
|
||||
const uint8_t previous_enabled = intent;
|
||||
const bool previous_running = _callbacks->isRs232BridgeRunning();
|
||||
intent = enable ? 1 : 0;
|
||||
const bool applied = _callbacks->setRs232BridgeState(enable);
|
||||
const bool saved = applied && trySavePrefs();
|
||||
@@ -3955,7 +4070,9 @@ void CommonCLI::handleSetCmd(uint32_t sender_timestamp, char* command, char* rep
|
||||
#ifndef WITH_MQTT_BRIDGE
|
||||
_prefs->rs232_bridge_enabled = _prefs->bridge_enabled == 1 ? 1 : 0;
|
||||
#endif
|
||||
const bool restored = _callbacks->setRs232BridgeState(previous_running);
|
||||
// Saved-on may currently be in soft standby. Restore an owner as well
|
||||
// as its intent, otherwise no object remains to execute the wake timer.
|
||||
const bool restored = _callbacks->setRs232BridgeState(previous_enabled != 0);
|
||||
strcpy(reply, restored
|
||||
? "Error: RS232 change failed; setting unchanged"
|
||||
: "Error: RS232 change failed; previous runtime could not be restored");
|
||||
@@ -4192,6 +4309,11 @@ void CommonCLI::handleSetCmd(uint32_t sender_timestamp, char* command, char* rep
|
||||
strcpy(reply, "Error: unsupported");
|
||||
}
|
||||
} else if (memcmp(config, "radio.fem.rxgain ", 17) == 0) {
|
||||
const auto* radio = _callbacks->getProfileRadio();
|
||||
if (radio && (radio->isMorseTxActive() || radio->isMorseRxActive())) {
|
||||
strcpy(reply, "Error: stop Morse before changing LoRa FEM gain");
|
||||
return;
|
||||
}
|
||||
if (!_board->canControlLoRaFemLna()) {
|
||||
strcpy(reply, "Error: unsupported");
|
||||
} else if (memcmp(&config[17], "on", 2) == 0) {
|
||||
@@ -4218,6 +4340,11 @@ void CommonCLI::handleSetCmd(uint32_t sender_timestamp, char* command, char* rep
|
||||
strcpy(reply, "Error: state must be on or off");
|
||||
}
|
||||
} else if (memcmp(config, "radio.fem.txgain ", 17) == 0) {
|
||||
const auto* radio = _callbacks->getProfileRadio();
|
||||
if (radio && (radio->isMorseTxActive() || radio->isMorseRxActive())) {
|
||||
strcpy(reply, "Error: stop Morse before changing LoRa FEM gain");
|
||||
return;
|
||||
}
|
||||
if (!_board->canControlLoRaFemPaGain()) {
|
||||
strcpy(reply, "Error: unsupported");
|
||||
} else if (memcmp(&config[17], "on", 2) == 0) {
|
||||
@@ -4867,7 +4994,7 @@ void CommonCLI::handleSetCmd(uint32_t sender_timestamp, char* command, char* rep
|
||||
return;
|
||||
}
|
||||
const uint8_t previous_enabled = _prefs->bridge_enabled;
|
||||
const bool previous_running = _callbacks->isRs232BridgeRunning();
|
||||
const bool previous_running = previous_enabled != 0;
|
||||
_prefs->bridge_enabled = enable;
|
||||
const bool applied = _callbacks->setRs232BridgeState(enable);
|
||||
if (applied && trySavePrefs()) {
|
||||
@@ -4942,7 +5069,12 @@ void CommonCLI::handleSetCmd(uint32_t sender_timestamp, char* command, char* rep
|
||||
if (mesh::cli::parseUnsignedIntegerStrict(&config[12], baud)
|
||||
&& baud >= 9600 && baud <= BRIDGE_MAX_BAUD) {
|
||||
const uint32_t previous_baud = _prefs->bridge_baud;
|
||||
const bool previous_running = _callbacks->isRs232BridgeRunning();
|
||||
const bool previous_running =
|
||||
#ifdef WITH_MQTT_BRIDGE
|
||||
_prefs->rs232_bridge_enabled != 0;
|
||||
#else
|
||||
_prefs->bridge_enabled != 0;
|
||||
#endif
|
||||
_prefs->bridge_baud = baud;
|
||||
const bool applied =
|
||||
#ifdef WITH_MQTT_BRIDGE
|
||||
@@ -4994,7 +5126,12 @@ void CommonCLI::handleSetCmd(uint32_t sender_timestamp, char* command, char* rep
|
||||
return;
|
||||
}
|
||||
const uint8_t previous_uart = _prefs->bridge_uart;
|
||||
const bool previous_running = _callbacks->isRs232BridgeRunning();
|
||||
const bool previous_running =
|
||||
#ifdef WITH_MQTT_BRIDGE
|
||||
_prefs->rs232_bridge_enabled != 0;
|
||||
#else
|
||||
_prefs->bridge_enabled != 0;
|
||||
#endif
|
||||
_prefs->bridge_uart = (uint8_t)uart;
|
||||
const bool applied =
|
||||
#ifdef WITH_MQTT_BRIDGE
|
||||
@@ -5565,6 +5702,15 @@ void CommonCLI::handleGetCmd(uint32_t sender_timestamp, char* command, char* rep
|
||||
sprintf(reply, "> %s", _prefs->bridge_pkt_src ? "rx" : "tx");
|
||||
#endif
|
||||
#ifdef WITH_RS232_BRIDGE
|
||||
} else if (configKeyEquals(config, "rs232.heartbeat")) {
|
||||
sprintf(reply, "> %s", _prefs->rs232_heartbeat ? "on" : "off");
|
||||
} else if (configKeyEquals(config, "rs232.autosleep")) {
|
||||
sprintf(reply, "> %s", _prefs->rs232_autosleep == 2 ? "force"
|
||||
: _prefs->rs232_autosleep == 1 ? "on" : "off");
|
||||
} else if (configKeyEquals(config, "rs232.idle")) {
|
||||
sprintf(reply, "> %us", static_cast<unsigned>(_prefs->rs232_idle_seconds));
|
||||
} else if (configKeyEquals(config, "rs232.status")) {
|
||||
_callbacks->formatRs232Status(reply);
|
||||
} else if (configKeyEquals(config, "rs232.enabled")) {
|
||||
sprintf(reply, "> %s",
|
||||
#ifdef WITH_MQTT_BRIDGE
|
||||
|
||||
@@ -14,6 +14,7 @@
|
||||
#include <helpers/DynamicConfigSerializer.h>
|
||||
#include <helpers/RepeaterRadioTiming.h>
|
||||
#include <helpers/RadioProfileCLI.h>
|
||||
#include <helpers/MorseReplyHandoff.h>
|
||||
#include <helpers/WirelessControl.h>
|
||||
#include <helpers/FleetCommand.h>
|
||||
#if MESH_ENABLE_FLEET_CONTROL
|
||||
@@ -213,6 +214,12 @@ public:
|
||||
// retain bridge_enabled as their legacy alias and mirror it on save.
|
||||
// Appended after the profile markers, never beside the legacy bridge byte.
|
||||
uint8_t rs232_bridge_enabled = 0;
|
||||
// Default standby is negotiated by a valid heartbeat reply. Stock peers
|
||||
// never arm it. Explicit force (2) also permits unconfirmed-link standby.
|
||||
// Stored in a checked append-only tail, never in the legacy bridge layout.
|
||||
uint8_t rs232_autosleep = 1;
|
||||
uint8_t rs232_heartbeat = 1;
|
||||
uint16_t rs232_idle_seconds = 300;
|
||||
// Appended after the ESP-NOW intent. Zero keeps the board's legacy cadence.
|
||||
uint16_t gps_sync_interval_hours = 0;
|
||||
uint8_t retry_preset = 0;
|
||||
@@ -352,6 +359,11 @@ private:
|
||||
def("format", _parent->bridge_format);
|
||||
def("usb_log", _parent->usb_logging_enabled);
|
||||
def("usb_dbg", _parent->usb_debug_enabled);
|
||||
#ifdef WITH_RS232_BRIDGE
|
||||
def("rs232_heartbeat", _parent->rs232_heartbeat);
|
||||
def("rs232_autosleep", _parent->rs232_autosleep);
|
||||
def("rs232_idle", _parent->rs232_idle_seconds);
|
||||
#endif
|
||||
}
|
||||
|
||||
public:
|
||||
@@ -623,6 +635,7 @@ public:
|
||||
virtual bool restartRs232Bridge() { return restartBridge(); }
|
||||
virtual bool isEspNowBridgeRunning() { return isBridgeRunning(); }
|
||||
virtual bool isRs232BridgeRunning() const { return isBridgeRunning(); }
|
||||
virtual void formatRs232Status(char* reply) { strcpy(reply, "RS232 unavailable"); }
|
||||
|
||||
virtual void restartBridgeSlot(int slot) {
|
||||
// Default: fall back to full restart
|
||||
@@ -840,6 +853,7 @@ class CommonCLI {
|
||||
bool _common_save_succeeded = false;
|
||||
uint32_t _prefs_save_failures = 0;
|
||||
mesh::RadioProfileCLI _radio_profiles;
|
||||
mesh::MorseReplyHandoff _morse_reply;
|
||||
#if MESH_ENABLE_FLEET_CONTROL
|
||||
mesh::FleetChannel* _fleet_channel = nullptr; // allocate only when enrolled
|
||||
bool handleFleetCommand(const char* command, char* reply);
|
||||
@@ -900,6 +914,8 @@ public:
|
||||
uint16_t preamble);
|
||||
mesh::RadioProfileCLI& radioProfiles() { return _radio_profiles; }
|
||||
const mesh::RadioProfileCLI& radioProfiles() const { return _radio_profiles; }
|
||||
mesh::MorseReplyHandoff& morseReply() { return _morse_reply; }
|
||||
const mesh::MorseReplyHandoff& morseReply() const { return _morse_reply; }
|
||||
#if MESH_ENABLE_FLEET_CONTROL
|
||||
mesh::FleetChannel* fleetChannel() { return _fleet_channel; }
|
||||
#endif
|
||||
|
||||
@@ -0,0 +1,430 @@
|
||||
#pragma once
|
||||
|
||||
#include <Dispatcher.h>
|
||||
#include <helpers/CLICommandUtils.h>
|
||||
#include <helpers/MorseSettings.h>
|
||||
#include <helpers/MorseReplyHandoff.h>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
|
||||
namespace mesh {
|
||||
|
||||
inline const char* morseUsageError() {
|
||||
#if MESH_ENABLE_MORSE_RX
|
||||
return "Error: use morse send <text> | listen <minutes> | read [offset] | stats | clear | stop";
|
||||
#else
|
||||
return "Error: use morse send <text> | stop";
|
||||
#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,
|
||||
const char* command, char* reply,
|
||||
size_t capacity, uint32_t now) {
|
||||
#if MESH_ENABLE_MORSE_RX
|
||||
if (!command || !reply || !capacity) return false;
|
||||
const char* key = command;
|
||||
bool query = false, setting = false;
|
||||
if (!strncmp(key, "get ", 4)) { query = true; key += 4; }
|
||||
else if (!strncmp(key, "set ", 4)) { setting = true; key += 4; }
|
||||
const size_t key_length = strcspn(key, " \t");
|
||||
const bool base = key_length == 5 && !strncmp(key, "morse", 5);
|
||||
const char* action = cli::skipRecentRepeaterSpaces(key + key_length);
|
||||
const size_t action_length = strcspn(action, " \t");
|
||||
const char* argument = cli::skipRecentRepeaterSpaces(action + action_length);
|
||||
const bool stop = base && !query && !setting && action_length == 4
|
||||
&& !strncmp(action, "stop", 4) && !*argument;
|
||||
const bool listen = base && !query && !setting && action_length == 6
|
||||
&& !strncmp(action, "listen", 6);
|
||||
if (stop && handoff.pending()) {
|
||||
handoff.cancel();
|
||||
snprintf(reply, capacity, "OK - pending Morse RX cancelled; packet radio unchanged");
|
||||
return true;
|
||||
}
|
||||
if (handoff.pending()) {
|
||||
if (base && !setting && !*action) {
|
||||
snprintf(reply, capacity, "> Morse RX queued; waiting for command reply to transmit; use morse stop to cancel");
|
||||
return true;
|
||||
}
|
||||
// Prevent a second explicit RF/settings action from replacing the staged
|
||||
// request. Read-only capture/status queries remain available.
|
||||
const bool read_only_morse = base && ((action_length == 4 && !strncmp(action, "read", 4))
|
||||
|| (action_length == 5 && !strncmp(action, "stats", 5))
|
||||
#if defined(MESH_MORSE_HIL) && MESH_MORSE_HIL
|
||||
|| (action_length == 5 && !strncmp(action, "trace", 5))
|
||||
#endif
|
||||
);
|
||||
const bool cw = (key_length == 2 && !strncmp(key, "cw", 2))
|
||||
|| (key_length == 3 && !strncmp(key, "cw2", 3));
|
||||
if (setting || (base && !query && !read_only_morse)
|
||||
|| (!query && cw && *action) || !strncmp(key, "tempradio", 9)
|
||||
|| (!query && key_length == 5 && !strncmp(key, "radio", 5) && *action)
|
||||
|| (!query && key_length == 6 && !strncmp(key, "radio2", 6) && *action)) {
|
||||
snprintf(reply, capacity, "Error: Morse reply handoff pending; use morse stop or retry later");
|
||||
return true;
|
||||
}
|
||||
}
|
||||
if (!handoff.remoteCommand() || !listen) return false;
|
||||
float minutes = 0;
|
||||
if (!radio || !radio->supportsMorseRx() || !morseSettingsUsable()
|
||||
|| !cli::parseDecimalStrict(argument, minutes) || minutes <= 0 || minutes > 5) return false;
|
||||
const uint32_t duration = uint32_t(minutes * 60000.0f + 0.5f);
|
||||
if (duration < 1000 || duration > 300000) return false;
|
||||
if (radio->isCarrierWaveActive() || radio->isMorseTxActive() || radio->isMorseRxActive()) {
|
||||
snprintf(reply, capacity, "Error: radio busy; stop Morse/CW or retry when idle");
|
||||
return true;
|
||||
}
|
||||
const auto& settings = morseSettings();
|
||||
if (!handoff.stage(settings.frequency_khz, settings.wpm, duration, now)) {
|
||||
snprintf(reply, capacity, "Error: Morse reply handoff pending; retry later");
|
||||
return true;
|
||||
}
|
||||
snprintf(reply, capacity,
|
||||
"OK - Morse RX queued %.3f MHz for %.2f min; starts after this reply transmits; keep first 0.5 s quiet",
|
||||
settings.frequencyMHz(), minutes);
|
||||
return true;
|
||||
#else
|
||||
(void)handoff; (void)radio; (void)command; (void)reply; (void)capacity; (void)now;
|
||||
return false;
|
||||
#endif
|
||||
}
|
||||
|
||||
#if MESH_ENABLE_MORSE_RX
|
||||
inline void formatMorseCapturePage(Radio* radio, const char* argument,
|
||||
char* reply, size_t capacity) {
|
||||
uint32_t offset = 0;
|
||||
if (*argument && !cli::parseUnsignedIntegerStrict(argument, offset)) {
|
||||
snprintf(reply, capacity, "Error: use morse read [character offset]");
|
||||
return;
|
||||
}
|
||||
const size_t total = radio->morseCaptureLength();
|
||||
// The current bounded capture is 4096 characters. Fixed-width page headers
|
||||
// reserve their exact space before copying text into a single CLI reply.
|
||||
if (total > MorseRx::CaptureCapacity || total > 9999 || offset > total) {
|
||||
snprintf(reply, capacity, "Error: capture offset must be 0-%u", unsigned(total));
|
||||
return;
|
||||
}
|
||||
const int prefix = snprintf(reply, capacity, "> %04u/%04u next=---- truncated=%u ",
|
||||
unsigned(offset), unsigned(total), unsigned(radio->morseCaptureTruncated()));
|
||||
if (prefix < 0 || size_t(prefix) + 1 >= capacity) {
|
||||
snprintf(reply, capacity, "Error: reply buffer too small for capture page");
|
||||
return;
|
||||
}
|
||||
const size_t copied = radio->readMorseCapture(offset, reply + prefix, capacity - prefix);
|
||||
const size_t next = offset + copied;
|
||||
char following[5];
|
||||
if (next >= total) memcpy(following, "END ", 5);
|
||||
else snprintf(following, sizeof(following), "%04u", unsigned(next));
|
||||
char* marker = strstr(reply, "next=----");
|
||||
if (marker) memcpy(marker + 5, following, 4);
|
||||
}
|
||||
|
||||
#if defined(MESH_MORSE_HIL) && MESH_MORSE_HIL
|
||||
inline void formatMorseTracePage(Radio* radio, const char* argument,
|
||||
char* reply, size_t capacity) {
|
||||
uint32_t offset = 0;
|
||||
if (*argument && !cli::parseUnsignedIntegerStrict(argument, offset)) {
|
||||
snprintf(reply, capacity, "Error: use morse trace [retained entry offset]");
|
||||
return;
|
||||
}
|
||||
const size_t length = radio->morseTraceLength();
|
||||
if (length > 512 || offset > length) {
|
||||
snprintf(reply, capacity, "Error: trace offset must be 0-%u", unsigned(length));
|
||||
return;
|
||||
}
|
||||
// `t` is the absolute total entry count; offset is relative to the retained
|
||||
// oldest sample. A changed t between pages identifies a moving HIL window.
|
||||
const int prefix = snprintf(reply, capacity, "> %03u/%03u t=%lu n=--- x=%u ",
|
||||
unsigned(offset), unsigned(length), (unsigned long)radio->morseTraceTotal(),
|
||||
unsigned(radio->morseTraceTruncated()));
|
||||
if (prefix < 0 || size_t(prefix) + 1 >= capacity) {
|
||||
snprintf(reply, capacity, "Error: reply buffer too small for trace page");
|
||||
return;
|
||||
}
|
||||
size_t used = prefix, next = offset;
|
||||
for (unsigned count = 0; count < 8 && next < length; ++count) {
|
||||
MorseRssiTraceEntry entry{};
|
||||
if (!radio->readMorseTrace(next, entry)) {
|
||||
snprintf(reply, capacity, "Error: trace changed; retry from offset 0");
|
||||
return;
|
||||
}
|
||||
char row[32];
|
||||
const int bytes = snprintf(row, sizeof(row), "%lu,%d,%u;",
|
||||
(unsigned long)entry.millis, int(entry.rssi_dbm), unsigned(entry.flags));
|
||||
if (bytes < 0 || size_t(bytes) >= sizeof(row) || used + size_t(bytes) >= capacity) break;
|
||||
memcpy(reply + used, row, bytes);
|
||||
used += bytes;
|
||||
reply[used] = 0;
|
||||
++next;
|
||||
}
|
||||
if (next == offset && next < length) {
|
||||
snprintf(reply, capacity, "Error: reply buffer too small for trace entry");
|
||||
return;
|
||||
}
|
||||
char following[4];
|
||||
if (next >= length) memcpy(following, "END", 4);
|
||||
else snprintf(following, sizeof(following), "%03u", unsigned(next));
|
||||
char* marker = strstr(reply, "n=---");
|
||||
if (marker) memcpy(marker + 2, following, 3);
|
||||
}
|
||||
#endif
|
||||
#endif // MESH_ENABLE_MORSE_RX
|
||||
|
||||
// Only explicit commands enter TX/listening. Chat, private messages, captured
|
||||
// Morse and boot never trigger a transmission. Caller authentication applies.
|
||||
inline bool handleMorseCommand(Radio* radio, const char* command,
|
||||
char* reply, size_t capacity) {
|
||||
if (!command || !reply || !capacity) return false;
|
||||
bool query = false, setting = false;
|
||||
const char* key = command;
|
||||
if (!strncmp(key, "get ", 4)) { query = true; key += 4; }
|
||||
else if (!strncmp(key, "set ", 4)) { setting = true; key += 4; }
|
||||
const size_t length = strcspn(key, " \t");
|
||||
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())) {
|
||||
snprintf(reply, capacity, "Error: Morse unsupported on this radio");
|
||||
return true;
|
||||
}
|
||||
const char* args = cli::skipRecentRepeaterSpaces(key + length);
|
||||
const auto& current = morseSettings();
|
||||
if ((query || (base && !*args && !setting)) && !morseSettingsUsable()) {
|
||||
snprintf(reply, capacity, "Error: saved Morse settings unavailable; verify and save morse.freq");
|
||||
return true;
|
||||
}
|
||||
if (frequency || speed) {
|
||||
if (query) {
|
||||
if (*args) snprintf(reply, capacity, "Error: unexpected argument");
|
||||
else if (frequency) snprintf(reply, capacity, "> %.3f", current.frequencyMHz());
|
||||
else snprintf(reply, capacity, "> %u", unsigned(current.wpm));
|
||||
return true;
|
||||
}
|
||||
if (!setting) {
|
||||
snprintf(reply, capacity, "Error: use get/set morse.%s", frequency ? "freq" : "wpm");
|
||||
return true;
|
||||
}
|
||||
if (speed && !morseSettingsUsable()) {
|
||||
snprintf(reply, capacity, "Error: verify and save morse.freq before changing Morse WPM");
|
||||
return true;
|
||||
}
|
||||
if (radio->isCarrierWaveActive() || radio->isMorseTxActive() || radio->isMorseRxActive()) {
|
||||
snprintf(reply, capacity, "Error: radio busy; stop Morse/CW before changing settings");
|
||||
return true;
|
||||
}
|
||||
auto candidate = current;
|
||||
if (frequency) {
|
||||
float value = 0;
|
||||
if (!cli::parseDecimalStrict(args, value)
|
||||
|| value < MorseMinFrequencyKHz / 1000.0f
|
||||
|| value > MorseMaxFrequencyKHz / 1000.0f) {
|
||||
snprintf(reply, capacity, "Error: morse.freq must be 100-1000 MHz");
|
||||
return true;
|
||||
}
|
||||
candidate.frequency_khz = uint32_t(value * 1000.0f + 0.5f);
|
||||
} else {
|
||||
uint32_t value = 0;
|
||||
if (!cli::parseUnsignedIntegerStrict(args, value)
|
||||
|| value < MorseMinWpm || value > MorseMaxWpm) {
|
||||
snprintf(reply, capacity, "Error: morse.wpm must be %u-%u",
|
||||
unsigned(MorseMinWpm), unsigned(MorseMaxWpm));
|
||||
return true;
|
||||
}
|
||||
candidate.wpm = uint8_t(value);
|
||||
}
|
||||
if (!saveMorseSettings(candidate)) {
|
||||
snprintf(reply, capacity, "Error: Morse settings could not be saved");
|
||||
} else if (frequency) {
|
||||
snprintf(reply, capacity, "OK - morse.freq %.3f MHz", candidate.frequencyMHz());
|
||||
} else snprintf(reply, capacity, "OK - morse.wpm %u", unsigned(candidate.wpm));
|
||||
return true;
|
||||
}
|
||||
if ((!*args && !setting)) {
|
||||
#if MESH_ENABLE_MORSE_RX
|
||||
if (radio->isMorseRxActive()) {
|
||||
const uint32_t left = radio->morseRxRemainingMillis();
|
||||
if (radio->morseRxRecovering()) snprintf(reply, capacity,
|
||||
"> Morse RX stopped; packet-radio recovery pending; captured=%u; truncated=%u",
|
||||
unsigned(radio->morseCaptureLength()), unsigned(radio->morseCaptureTruncated()));
|
||||
else snprintf(reply, capacity,
|
||||
"> RX%s %.3f MHz; BW %.2f kHz; %lu.%03lu seconds left; captured=%u; truncated=%u",
|
||||
radio->morseRxLearning() ? " learning/keep quiet" : "",
|
||||
radio->morseRxFrequency(), radio->morseRxBandwidthKHz(),
|
||||
(unsigned long)(left / 1000), (unsigned long)(left % 1000),
|
||||
unsigned(radio->morseCaptureLength()), unsigned(radio->morseCaptureTruncated()));
|
||||
} else
|
||||
#endif
|
||||
if (radio->isMorseTxActive()) {
|
||||
const uint32_t left = radio->morseTxRemainingMillis();
|
||||
if (!left) snprintf(reply, capacity, "> RF stop/receive recovery pending; %.3f MHz; TX only",
|
||||
radio->morseTxFrequency());
|
||||
else snprintf(reply, capacity, "> on; %.3f MHz; %u WPM; %lu.%03lu seconds left; TX only",
|
||||
radio->morseTxFrequency(), unsigned(radio->morseTxWpm()),
|
||||
(unsigned long)(left / 1000), (unsigned long)(left % 1000));
|
||||
}
|
||||
#if MESH_ENABLE_MORSE_RX
|
||||
else if (radio->supportsMorseRx()) snprintf(reply, capacity,
|
||||
"> off; %.3f MHz; %u WPM; captured=%u; truncated=%u%s; morse read",
|
||||
current.frequencyMHz(), unsigned(current.wpm),
|
||||
unsigned(radio->morseCaptureLength()), unsigned(radio->morseCaptureTruncated()),
|
||||
radio->morseCaptureTruncated() ? "; capture quota reached; RX ended early" : "");
|
||||
#endif
|
||||
else snprintf(reply, capacity, "> off; %.3f MHz; %u WPM; TX only",
|
||||
current.frequencyMHz(), unsigned(current.wpm));
|
||||
return true;
|
||||
}
|
||||
if (query || setting) {
|
||||
snprintf(reply, capacity, "%s", morseUsageError());
|
||||
return true;
|
||||
}
|
||||
const size_t action_length = strcspn(args, " \t");
|
||||
const char* text = cli::skipRecentRepeaterSpaces(args + action_length);
|
||||
const bool stop = action_length == 4 && !strncmp(args, "stop", 4) && !*text;
|
||||
const bool send = action_length == 4 && !strncmp(args, "send", 4) && *text;
|
||||
const bool listen = action_length == 6 && !strncmp(args, "listen", 6);
|
||||
const bool read = action_length == 4 && !strncmp(args, "read", 4);
|
||||
const bool clear = action_length == 5 && !strncmp(args, "clear", 5) && !*text;
|
||||
const bool stats = action_length == 5 && !strncmp(args, "stats", 5) && !*text;
|
||||
#if defined(MESH_MORSE_HIL) && MESH_MORSE_HIL
|
||||
const bool trace = action_length == 5 && !strncmp(args, "trace", 5);
|
||||
#else
|
||||
const bool trace = false;
|
||||
#endif
|
||||
if (!stop && !send && !listen && !read && !clear && !stats && !trace) {
|
||||
snprintf(reply, capacity, "%s", morseUsageError());
|
||||
return true;
|
||||
}
|
||||
if ((listen || read || clear || stats || trace)
|
||||
#if MESH_ENABLE_MORSE_RX
|
||||
&& !radio->supportsMorseRx()
|
||||
#endif
|
||||
) {
|
||||
snprintf(reply, capacity, "Error: Morse RX unsupported on this radio");
|
||||
return true;
|
||||
}
|
||||
#if MESH_ENABLE_MORSE_RX
|
||||
if (read) {
|
||||
formatMorseCapturePage(radio, text, reply, capacity);
|
||||
return true;
|
||||
}
|
||||
#if defined(MESH_MORSE_HIL) && MESH_MORSE_HIL
|
||||
if (trace) {
|
||||
formatMorseTracePage(radio, text, reply, capacity);
|
||||
return true;
|
||||
}
|
||||
#endif
|
||||
if (stats) {
|
||||
MorseRxDiagnostics data{};
|
||||
if (!radio->morseRxDiagnostics(data)) snprintf(reply, capacity, "> no Morse RX statistics");
|
||||
else snprintf(reply, capacity,
|
||||
"> samples=%lu; noise=%.1f; min=%.1f; max=%.1f; last=%.1f dBm; unit=%u ms; gap=%lu ms; bad=%u",
|
||||
(unsigned long)data.samples, data.noise_dbm, data.minimum_dbm, data.maximum_dbm,
|
||||
data.last_dbm, unsigned(data.unit_ms), (unsigned long)data.max_sample_gap_ms,
|
||||
unsigned(data.read_errors));
|
||||
return true;
|
||||
}
|
||||
if (clear) {
|
||||
if (radio->isMorseRxActive() || radio->isMorseTxActive())
|
||||
snprintf(reply, capacity, "Error: stop Morse before clearing capture");
|
||||
else { radio->clearMorseCapture(); snprintf(reply, capacity, "OK - Morse capture cleared"); }
|
||||
return true;
|
||||
}
|
||||
if (stop && radio->isMorseRxActive()) {
|
||||
const auto result = radio->stopMorseRx();
|
||||
if (result == MorseRxResult::Stopped) snprintf(reply, capacity,
|
||||
"OK - Morse RX stopped; capture retained%s", radio->isInRecvMode() ? "; receive resumed" : "");
|
||||
else snprintf(reply, capacity, "Error: Morse RX stop/receive recovery pending; capture retained");
|
||||
return true;
|
||||
}
|
||||
#endif // MESH_ENABLE_MORSE_RX
|
||||
// Do not stop an unrelated CW meter test through the Morse command.
|
||||
if (stop && !radio->isMorseTxActive()) {
|
||||
snprintf(reply, capacity, "OK - Morse not running");
|
||||
return true;
|
||||
}
|
||||
if ((send || listen) && !morseSettingsUsable()) {
|
||||
snprintf(reply, capacity, "Error: saved Morse settings unavailable; verify and save morse.freq");
|
||||
return true;
|
||||
}
|
||||
#if MESH_ENABLE_MORSE_RX
|
||||
if (listen) {
|
||||
float minutes = 0;
|
||||
if (!cli::parseDecimalStrict(text, minutes) || minutes <= 0 || minutes > 5) {
|
||||
snprintf(reply, capacity, "Error: use morse listen <minutes: 1 second to 5 minutes>");
|
||||
return true;
|
||||
}
|
||||
const uint32_t duration = uint32_t(minutes * 60000.0f + 0.5f);
|
||||
if (duration < 1000 || duration > 300000) {
|
||||
snprintf(reply, capacity, "Error: Morse listening must last 1-300 seconds");
|
||||
return true;
|
||||
}
|
||||
const auto result = radio->startMorseRx(current.frequencyMHz(), current.wpm, duration);
|
||||
switch (result) {
|
||||
case MorseRxResult::Started:
|
||||
snprintf(reply, capacity, "OK - Morse RX %.3f MHz; BW %.2f kHz; %.2f min; keep first 0.5 s quiet; LoRa paused",
|
||||
current.frequencyMHz(), radio->morseRxBandwidthKHz(), minutes);
|
||||
break;
|
||||
case MorseRxResult::Busy:
|
||||
snprintf(reply, capacity, "Error: radio busy; stop Morse/CW or retry when idle"); break;
|
||||
case MorseRxResult::Unsupported:
|
||||
snprintf(reply, capacity, "Error: Morse RX unsupported on this radio"); break;
|
||||
case MorseRxResult::InvalidFrequency:
|
||||
snprintf(reply, capacity, "Error: Morse frequency unsupported by this radio"); break;
|
||||
case MorseRxResult::Overlap:
|
||||
snprintf(reply, capacity, "Error: Morse frequency overlaps radio or radio2; change morse.freq"); break;
|
||||
case MorseRxResult::InvalidSpeed:
|
||||
snprintf(reply, capacity, "Error: morse.wpm must be %u-%u", unsigned(MorseMinWpm), unsigned(MorseMaxWpm)); break;
|
||||
case MorseRxResult::InvalidDuration:
|
||||
snprintf(reply, capacity, "Error: Morse listening must last 1-300 seconds"); break;
|
||||
default:
|
||||
snprintf(reply, capacity, "Error: Morse RX transition failed; check radio recovery"); break;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
#endif
|
||||
if (send && !radio->supportsMorseTx()) {
|
||||
snprintf(reply, capacity, "Error: Morse TX unsupported on this radio");
|
||||
return true;
|
||||
}
|
||||
const auto result = stop ? radio->stopMorseTx()
|
||||
: radio->startMorseTx(current.frequencyMHz(), current.wpm, text);
|
||||
switch (result) {
|
||||
case MorseTxResult::Started:
|
||||
snprintf(reply, capacity, "OK - Morse TX %.3f MHz at %u WPM; RX paused; use morse stop",
|
||||
current.frequencyMHz(), unsigned(current.wpm));
|
||||
break;
|
||||
case MorseTxResult::Stopped:
|
||||
snprintf(reply, capacity, "OK - Morse stopped%s",
|
||||
radio->isInRecvMode() ? "; receive resumed" : "");
|
||||
break;
|
||||
case MorseTxResult::Busy:
|
||||
snprintf(reply, capacity, "Error: radio busy; stop Morse/CW or retry when idle");
|
||||
break;
|
||||
case MorseTxResult::Unsupported:
|
||||
snprintf(reply, capacity, "Error: Morse TX unsupported on this radio");
|
||||
break;
|
||||
case MorseTxResult::InvalidFrequency:
|
||||
snprintf(reply, capacity, "Error: Morse frequency unsupported by this radio");
|
||||
break;
|
||||
case MorseTxResult::Overlap:
|
||||
snprintf(reply, capacity, "Error: Morse frequency overlaps radio or radio2; change morse.freq");
|
||||
break;
|
||||
case MorseTxResult::InvalidText:
|
||||
snprintf(reply, capacity, "Error: supported Morse ASCII only (80 characters max)");
|
||||
break;
|
||||
case MorseTxResult::InvalidSpeed:
|
||||
snprintf(reply, capacity, "Error: morse.wpm must be %u-%u", unsigned(MorseMinWpm), unsigned(MorseMaxWpm));
|
||||
break;
|
||||
case MorseTxResult::TooLong:
|
||||
snprintf(reply, capacity, "Error: limit 80 characters/180 seconds; shorten text or raise WPM");
|
||||
break;
|
||||
default:
|
||||
snprintf(reply, capacity, "Error: Morse failed; check radio recovery");
|
||||
break;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace mesh
|
||||
@@ -0,0 +1,15 @@
|
||||
#pragma once
|
||||
|
||||
#include <Dispatcher.h>
|
||||
|
||||
namespace mesh {
|
||||
|
||||
// Keyed Morse and RSSI-envelope capture require a responsive foreground loop.
|
||||
// Defer optional background work without advancing its deadlines; the next
|
||||
// ordinary pass resumes it. Keep voltage safety/watchdogs and command I/O live.
|
||||
// An unkeyed CW meter test does not opt into this scheduling policy.
|
||||
inline bool morseTimingActive(const Radio* radio) {
|
||||
return radio && (radio->isMorseTxActive() || radio->isMorseRxActive());
|
||||
}
|
||||
|
||||
} // namespace mesh
|
||||
@@ -0,0 +1,159 @@
|
||||
#pragma once
|
||||
|
||||
#include <Dispatcher.h>
|
||||
#include <stdint.h>
|
||||
#if MESH_ENABLE_MORSE_RX
|
||||
#include <helpers/TempRadioReplyBarrier.h>
|
||||
#include <string.h>
|
||||
#endif
|
||||
|
||||
namespace mesh {
|
||||
|
||||
// A remote listen command must acknowledge on the packet radio before giving
|
||||
// that radio to Morse RX. Keep exact packet ownership with Dispatcher; never
|
||||
// infer delivery from a timestamp, ciphertext, a queue delay or another reply.
|
||||
#if MESH_ENABLE_MORSE_RX
|
||||
class MorseReplyHandoff {
|
||||
TempRadioReplyBarrier barrier_;
|
||||
const void* prepared_reply_ = nullptr;
|
||||
const void* prepared_copy_ = nullptr;
|
||||
const uint8_t* command_actor_ = nullptr; // valid only inside the authenticated callback
|
||||
uint8_t actor_[32] = {};
|
||||
uint32_t frequency_khz_ = 0, duration_ms_ = 0, deadline_ = 0, generation_ = 0;
|
||||
uint32_t start_deadline_ = 0, retry_at_ = 0;
|
||||
uint8_t wpm_ = 0;
|
||||
bool pending_ = false, delivered_ = false;
|
||||
bool start_wait_ = false, retry_pending_ = false;
|
||||
|
||||
public:
|
||||
static constexpr uint32_t ReplyDeadlineMillis = 30000;
|
||||
static constexpr uint32_t StartDeadlineMillis = 10000;
|
||||
void beginCommand(const uint8_t* actor) { command_actor_ = actor; }
|
||||
void endCommand() { command_actor_ = nullptr; }
|
||||
bool remoteCommand() const { return command_actor_ != nullptr; }
|
||||
bool pending() const { return pending_; }
|
||||
uint32_t generation() const { return generation_; }
|
||||
const uint8_t* actor() const { return actor_; }
|
||||
bool contains(const void* packet) const { return barrier_.contains(packet); }
|
||||
bool ownsReply(const void* packet) const {
|
||||
return pending_ && packet && (packet == prepared_reply_ || packet == prepared_copy_);
|
||||
}
|
||||
|
||||
bool stage(uint32_t frequency_khz, uint8_t wpm, uint32_t duration_ms, uint32_t now) {
|
||||
if (!command_actor_ || pending_) return false;
|
||||
memcpy(actor_, command_actor_, sizeof(actor_));
|
||||
frequency_khz_ = frequency_khz;
|
||||
wpm_ = wpm;
|
||||
duration_ms_ = duration_ms;
|
||||
deadline_ = now + ReplyDeadlineMillis;
|
||||
++generation_;
|
||||
pending_ = true;
|
||||
delivered_ = false;
|
||||
start_deadline_ = retry_at_ = 0;
|
||||
start_wait_ = retry_pending_ = false;
|
||||
barrier_.clear();
|
||||
prepared_reply_ = prepared_copy_ = nullptr;
|
||||
return true;
|
||||
}
|
||||
void prepareReply(const void* packet) {
|
||||
if (pending_) {
|
||||
prepared_reply_ = packet;
|
||||
prepared_copy_ = nullptr;
|
||||
barrier_.prepare(packet);
|
||||
}
|
||||
}
|
||||
void armReply(const void* packet, bool queued) {
|
||||
if (!pending_) return;
|
||||
if (!queued || !packet) { cancel(); return; }
|
||||
barrier_.arm(packet);
|
||||
}
|
||||
void copy(const void* original, const void* packet) {
|
||||
if (pending_) {
|
||||
if (original && original == prepared_reply_) prepared_copy_ = packet;
|
||||
barrier_.trackCopy(original, packet);
|
||||
}
|
||||
}
|
||||
void complete(const void* packet) {
|
||||
if (barrier_.contains(packet)) {
|
||||
if (packet == prepared_reply_) prepared_reply_ = nullptr;
|
||||
if (packet == prepared_copy_) prepared_copy_ = nullptr;
|
||||
}
|
||||
if (pending_ && barrier_.complete(packet) && !barrier_.waiting()) delivered_ = true;
|
||||
}
|
||||
void fail(const void* packet) {
|
||||
if (!pending_) return;
|
||||
if (barrier_.contains(packet)) {
|
||||
if (packet == prepared_reply_) prepared_reply_ = nullptr;
|
||||
if (packet == prepared_copy_) prepared_copy_ = nullptr;
|
||||
}
|
||||
if (barrier_.fail(packet)) cancel();
|
||||
else if (!barrier_.waiting() && barrier_.succeeded()) delivered_ = true;
|
||||
}
|
||||
void cancel() {
|
||||
pending_ = delivered_ = false;
|
||||
barrier_.clear();
|
||||
prepared_reply_ = prepared_copy_ = nullptr;
|
||||
}
|
||||
|
||||
// Recheck the complete identity, saved settings and driver admission after
|
||||
// acknowledgement, not the possibly compacted ACL slot from command parsing.
|
||||
// The driver revalidates both live profiles before any hardware transition.
|
||||
bool service(Radio* radio, uint32_t now, bool authorized, bool settings_usable,
|
||||
uint32_t current_frequency_khz, uint8_t current_wpm) {
|
||||
if (!pending_) return false;
|
||||
if (!authorized || !settings_usable
|
||||
|| current_frequency_khz != frequency_khz_ || current_wpm != wpm_
|
||||
|| int32_t(now - deadline_) >= 0) {
|
||||
cancel();
|
||||
return false;
|
||||
}
|
||||
if (!delivered_) return false;
|
||||
if (!start_wait_) {
|
||||
start_deadline_ = now + StartDeadlineMillis;
|
||||
start_wait_ = true;
|
||||
}
|
||||
if (int32_t(now - start_deadline_) >= 0) { cancel(); return false; }
|
||||
if (retry_pending_ && int32_t(now - retry_at_) < 0) return false;
|
||||
const auto result = radio
|
||||
? radio->startMorseRx(frequency_khz_ / 1000.0f, wpm_, duration_ms_)
|
||||
: MorseRxResult::Failed;
|
||||
if (result == MorseRxResult::Busy) {
|
||||
retry_at_ = now + 100;
|
||||
retry_pending_ = true;
|
||||
return false;
|
||||
}
|
||||
// Completion already drained the exact barrier, so a late callback or
|
||||
// cached replay cannot start another session. Hard admission failures do
|
||||
// not retry; transient packet-radio Busy is bounded and reauthorized.
|
||||
cancel();
|
||||
return result == MorseRxResult::Started;
|
||||
}
|
||||
};
|
||||
#else
|
||||
// Preserve the role callback API without retaining RX state or ACK handoff
|
||||
// machinery on small-flash builds whose receiver is explicitly disabled.
|
||||
// No command can stage a listen; Morse TX and unrelated replies are unchanged.
|
||||
class MorseReplyHandoff {
|
||||
public:
|
||||
static constexpr uint32_t ReplyDeadlineMillis = 30000;
|
||||
static constexpr uint32_t StartDeadlineMillis = 10000;
|
||||
void beginCommand(const uint8_t*) {}
|
||||
void endCommand() {}
|
||||
bool remoteCommand() const { return false; }
|
||||
bool pending() const { return false; }
|
||||
uint32_t generation() const { return 0; }
|
||||
const uint8_t* actor() const { return nullptr; }
|
||||
bool contains(const void*) const { return false; }
|
||||
bool ownsReply(const void*) const { return false; }
|
||||
bool stage(uint32_t, uint8_t, uint32_t, uint32_t) { return false; }
|
||||
void prepareReply(const void*) {}
|
||||
void armReply(const void*, bool) {}
|
||||
void copy(const void*, const void*) {}
|
||||
void complete(const void*) {}
|
||||
void fail(const void*) {}
|
||||
void cancel() {}
|
||||
bool service(Radio*, uint32_t, bool, bool, uint32_t, uint8_t) { return false; }
|
||||
};
|
||||
#endif // MESH_ENABLE_MORSE_RX
|
||||
|
||||
} // namespace mesh
|
||||
@@ -0,0 +1,421 @@
|
||||
#pragma once
|
||||
|
||||
#include "MorseTx.h"
|
||||
#include <string.h>
|
||||
|
||||
#ifndef MESH_ENABLE_MORSE_RX
|
||||
// Current integrated STM32WL targets have 256 KiB flash. Keep their complete
|
||||
// existing feature set and Morse TX; timed capture is an explicit larger-build
|
||||
// opt-in rather than moving the deployed filesystem boundary.
|
||||
#if defined(STM32_PLATFORM)
|
||||
#define MESH_ENABLE_MORSE_RX 0
|
||||
#else
|
||||
#define MESH_ENABLE_MORSE_RX 1
|
||||
#endif
|
||||
#endif
|
||||
|
||||
#if defined(MESH_MORSE_HIL) && MESH_MORSE_HIL \
|
||||
&& defined(MESH_MORSE_HIL_FAST_OFF_DEBOUNCE) \
|
||||
&& MESH_MORSE_HIL_FAST_OFF_DEBOUNCE != 0 \
|
||||
&& MESH_MORSE_HIL_FAST_OFF_DEBOUNCE != 1
|
||||
#error "HIL Morse fast OFF debounce flag must be 0 or 1"
|
||||
#endif
|
||||
|
||||
namespace mesh {
|
||||
|
||||
enum class MorseRxResult : uint8_t {
|
||||
Started, Stopped, Busy, Unsupported, InvalidFrequency, Overlap,
|
||||
InvalidSpeed, InvalidDuration, Failed
|
||||
};
|
||||
|
||||
struct MorseRxDiagnostics {
|
||||
float noise_dbm = NAN, last_dbm = NAN, minimum_dbm = NAN, maximum_dbm = NAN;
|
||||
uint32_t samples = 0;
|
||||
uint32_t max_sample_gap_ms = 0;
|
||||
uint16_t unit_ms = 0;
|
||||
uint8_t read_errors = 0;
|
||||
};
|
||||
|
||||
#if defined(MESH_MORSE_HIL) && MESH_MORSE_HIL
|
||||
struct MorseRssiTraceEntry {
|
||||
uint32_t millis;
|
||||
int8_t rssi_dbm;
|
||||
uint8_t flags; // raw key=1, committed key=2, candidate=4, learning=8
|
||||
};
|
||||
|
||||
// Lab-only sparse envelope diagnostics. Stored independently on admitted heap,
|
||||
// never as an extra idle BSS buffer. Preserve the latest bounded window.
|
||||
class MorseRssiTrace {
|
||||
public:
|
||||
static constexpr size_t Capacity = 512;
|
||||
void clear() { _length = _next = 0; _total = _last_elapsed = 0; _triggered = _dropped = false; }
|
||||
size_t length() const { return _length; }
|
||||
uint32_t total() const { return _total; }
|
||||
bool truncated() const { return _dropped || _total > Capacity; }
|
||||
bool read(size_t offset, MorseRssiTraceEntry& out) const {
|
||||
if (offset >= _length) return false;
|
||||
size_t index = (_next + Capacity - 1) % Capacity;
|
||||
uint32_t elapsed = _last_elapsed;
|
||||
for (size_t position = _length - 1; position > offset; --position) {
|
||||
elapsed -= _entries[index].delta_ms;
|
||||
index = (index + Capacity - 1) % Capacity;
|
||||
}
|
||||
out = {elapsed, _entries[index].rssi_dbm, _entries[index].flags};
|
||||
return true;
|
||||
}
|
||||
void sample(float rssi, uint32_t elapsed, uint8_t flags) {
|
||||
if (flags & 8) return;
|
||||
// Debounced key edges retain the actual decoder transitions. Suppress
|
||||
// intermediate debounce samples so a full message fits, but retain large
|
||||
// quiet-floor/power changes for AGC/envelope diagnosis.
|
||||
if (!_triggered) {
|
||||
if (!(flags & 2)) return;
|
||||
_triggered = true;
|
||||
}
|
||||
if (flags & 4) return;
|
||||
int16_t value = static_cast<int16_t>(rssi >= 0 ? rssi + 0.5f : rssi - 0.5f);
|
||||
if (value < -128) value = -128;
|
||||
if (value > 127) value = 127;
|
||||
if (_length) {
|
||||
const auto& previous = _entries[(_next + Capacity - 1) % Capacity];
|
||||
const int16_t delta = value - previous.rssi_dbm;
|
||||
if (((flags ^ previous.flags) & 2) == 0 && delta > -6 && delta < 6
|
||||
&& elapsed - _last_elapsed < 60000U) return;
|
||||
}
|
||||
// Quiet anchors at sixty seconds bound the stored deltas even in a full
|
||||
// five-minute capture. Public reads reconstruct exact 32-bit timestamps.
|
||||
uint32_t delta_ms = _length ? elapsed - _last_elapsed : 0;
|
||||
if (delta_ms > UINT16_MAX) {
|
||||
// A long stalled sampler supplies no measurements for the missing span.
|
||||
// Restart the retained window, explicitly marked incomplete, rather
|
||||
// than wrapping the delta or inventing intermediate RF measurements.
|
||||
_length = _next = 0;
|
||||
_dropped = true;
|
||||
delta_ms = 0;
|
||||
}
|
||||
_entries[_next] = {static_cast<uint16_t>(delta_ms), static_cast<int8_t>(value), flags};
|
||||
_next = (_next + 1) % Capacity;
|
||||
if (_length < Capacity) ++_length;
|
||||
++_total;
|
||||
_last_elapsed = elapsed;
|
||||
}
|
||||
private:
|
||||
struct StoredEntry { uint16_t delta_ms; int8_t rssi_dbm; uint8_t flags; };
|
||||
static_assert(sizeof(StoredEntry) == 4, "HIL stored entries must remain four bytes");
|
||||
StoredEntry _entries[Capacity];
|
||||
uint16_t _length = 0, _next = 0;
|
||||
uint32_t _last_elapsed = 0, _total = 0;
|
||||
bool _triggered = false, _dropped = false;
|
||||
};
|
||||
#endif
|
||||
|
||||
// RSSI envelope decoding, not an RF demodulator or an artificial narrow
|
||||
// filter. The real receiver supplies its instantaneous power measurements.
|
||||
// Quiet arming samples establish the noise floor before the sender keys up.
|
||||
class MorseRx {
|
||||
public:
|
||||
#if defined(MESH_MORSE_HIL) && MESH_MORSE_HIL && defined(MESH_MORSE_HIL_SAMPLE_INTERVAL_MS)
|
||||
static constexpr uint32_t SampleIntervalMillis = MESH_MORSE_HIL_SAMPLE_INTERVAL_MS;
|
||||
static_assert(MESH_MORSE_HIL_SAMPLE_INTERVAL_MS >= 1
|
||||
&& MESH_MORSE_HIL_SAMPLE_INTERVAL_MS <= 10,
|
||||
"HIL Morse RSSI sample interval must be 1..10 milliseconds");
|
||||
#else
|
||||
static constexpr uint32_t SampleIntervalMillis = 2;
|
||||
#endif
|
||||
#if defined(MESH_MORSE_HIL) && MESH_MORSE_HIL && defined(MESH_MORSE_HIL_RX_BITRATE_KBPS)
|
||||
static constexpr float ReceiverBitRateKbps = MESH_MORSE_HIL_RX_BITRATE_KBPS;
|
||||
#else
|
||||
static constexpr float ReceiverBitRateKbps = 1.2f;
|
||||
#endif
|
||||
static_assert(ReceiverBitRateKbps >= 0.6f && ReceiverBitRateKbps <= 300.0f,
|
||||
"HIL GFSK receiver clock must remain in the supported range");
|
||||
static constexpr uint32_t MinDurationMillis = 1000UL;
|
||||
static constexpr uint32_t MaxDurationMillis = 300000UL;
|
||||
static constexpr uint32_t NoiseLearningMillis = 500UL;
|
||||
static constexpr size_t CaptureCapacity = 4096;
|
||||
// A startup estimator heuristic, not a guaranteed radio/AGC floor shift.
|
||||
static constexpr float StartupFloorUncertaintyDb = 30.0f;
|
||||
#if defined(MESH_MORSE_HIL) && MESH_MORSE_HIL
|
||||
void setTrace(MorseRssiTrace* trace) { _trace = trace; }
|
||||
#endif
|
||||
|
||||
static MorseRxResult validate(uint8_t wpm, uint32_t duration_ms) {
|
||||
if (!MorseTx::unitMillis(wpm)) return MorseRxResult::InvalidSpeed;
|
||||
if (duration_ms < MinDurationMillis || duration_ms > MaxDurationMillis)
|
||||
return MorseRxResult::InvalidDuration;
|
||||
return MorseRxResult::Started;
|
||||
}
|
||||
|
||||
MorseRxResult start(uint8_t wpm, uint32_t duration_ms, uint32_t now) {
|
||||
const auto result = validate(wpm, duration_ms);
|
||||
if (result != MorseRxResult::Started) return result;
|
||||
clear();
|
||||
_started = _last_edge = now;
|
||||
_until = now + duration_ms;
|
||||
_nominal_unit = _unit = MorseTx::unitMillis(wpm);
|
||||
_noise = _signal = 0;
|
||||
_samples = 0;
|
||||
_last_sample_at = now;
|
||||
_max_sample_gap_ms = 0;
|
||||
_last_rssi = _minimum_rssi = _maximum_rssi = NAN;
|
||||
_have_noise = _candidate_valid = _keyed = _floor_settled = false;
|
||||
_active = true;
|
||||
#if defined(MESH_MORSE_HIL) && MESH_MORSE_HIL
|
||||
if (_trace) _trace->clear();
|
||||
#endif
|
||||
return MorseRxResult::Started;
|
||||
}
|
||||
|
||||
bool active() const { return _active; }
|
||||
bool keyed() const { return _active && _keyed; }
|
||||
bool learning(uint32_t now) const {
|
||||
return _active && static_cast<uint32_t>(now - _started) < NoiseLearningMillis;
|
||||
}
|
||||
uint32_t remainingMillis(uint32_t now) const {
|
||||
if (!_active) return 0;
|
||||
const int32_t left = static_cast<int32_t>(_until - now);
|
||||
return left > 0 ? static_cast<uint32_t>(left) : 0;
|
||||
}
|
||||
const char* text() const { return _capture; }
|
||||
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; }
|
||||
void diagnostics(MorseRxDiagnostics& out) const {
|
||||
out.noise_dbm = _have_noise ? _noise : NAN;
|
||||
out.last_dbm = _last_rssi;
|
||||
out.minimum_dbm = _minimum_rssi;
|
||||
out.maximum_dbm = _maximum_rssi;
|
||||
out.samples = _samples;
|
||||
out.max_sample_gap_ms = _max_sample_gap_ms;
|
||||
out.unit_ms = _unit;
|
||||
out.read_errors = 0;
|
||||
}
|
||||
|
||||
size_t read(size_t offset, char* out, size_t capacity) const {
|
||||
if (!out || !capacity) return 0;
|
||||
if (offset >= _length) { out[0] = 0; return 0; }
|
||||
size_t count = _length - offset;
|
||||
if (count >= capacity) count = capacity - 1;
|
||||
memcpy(out, _capture + offset, count);
|
||||
out[count] = 0;
|
||||
return count;
|
||||
}
|
||||
|
||||
void clear() {
|
||||
_length = 0;
|
||||
_capture[0] = 0;
|
||||
_truncated = _bad_pattern = _letter_flushed = _word_flushed = false;
|
||||
_code = 1;
|
||||
_symbols = 0;
|
||||
}
|
||||
|
||||
void stop(uint32_t now) {
|
||||
if (!_active) return;
|
||||
// A keyed or debounce-pending tail may belong to an unfinished letter.
|
||||
// Never manufacture its last dash merely because the capture timed out.
|
||||
if (!_keyed && !_candidate_valid) flushLetter();
|
||||
_active = false;
|
||||
_keyed = _candidate_valid = false;
|
||||
_last_edge = now;
|
||||
}
|
||||
|
||||
bool service(uint32_t now) {
|
||||
if (!_active) return false;
|
||||
if (_samples) {
|
||||
const uint32_t gap = static_cast<uint32_t>(now - _last_sample_at);
|
||||
if (gap > _max_sample_gap_ms) _max_sample_gap_ms = gap;
|
||||
}
|
||||
if (static_cast<int32_t>(now - _until) >= 0) {
|
||||
stop(now);
|
||||
return false;
|
||||
}
|
||||
if (!learning(now) && !_keyed && !_candidate_valid) flushGap(now);
|
||||
return _active;
|
||||
}
|
||||
|
||||
void sample(float rssi_dbm, uint32_t now) {
|
||||
if (!service(now) || !isfinite(rssi_dbm) || rssi_dbm < -180.0f || rssi_dbm > 20.0f) return;
|
||||
_last_rssi = rssi_dbm;
|
||||
_last_sample_at = now;
|
||||
if (!_samples || rssi_dbm < _minimum_rssi) _minimum_rssi = rssi_dbm;
|
||||
if (!_samples || rssi_dbm > _maximum_rssi) _maximum_rssi = rssi_dbm;
|
||||
++_samples;
|
||||
if (!_have_noise) {
|
||||
_have_noise = true;
|
||||
_noise = rssi_dbm;
|
||||
_signal = rssi_dbm + 12.0f;
|
||||
}
|
||||
if (learning(now)) {
|
||||
_noise += (rssi_dbm - _noise) * 0.05f;
|
||||
_signal = _noise + 12.0f;
|
||||
return;
|
||||
}
|
||||
|
||||
const float span = _signal - _noise;
|
||||
float rise = span * 0.5f;
|
||||
if (rise < 6.0f) rise = 6.0f;
|
||||
float threshold = _noise + rise - (_keyed ? 3.0f : 0.0f);
|
||||
// Before the first confirmed OFF, some receivers still report a stale
|
||||
// pre-carrier floor. Allow for a provisional floor shift without a hard
|
||||
// signal-span discontinuity. This margin is a tested startup heuristic,
|
||||
// not a chip guarantee; after a real OFF the ordinary midpoint takes over
|
||||
// and tolerates strong within-mark fades without producing extra symbols.
|
||||
if (_keyed && !_floor_settled) {
|
||||
float provisional_fall = (span - StartupFloorUncertaintyDb) * 0.5f;
|
||||
if (provisional_fall < 5.0f) provisional_fall = 5.0f;
|
||||
if (threshold < _signal - provisional_fall) threshold = _signal - provisional_fall;
|
||||
}
|
||||
const bool raw_keyed = rssi_dbm >= threshold;
|
||||
if (!_keyed && !raw_keyed && !_candidate_valid) {
|
||||
// Drift slowly while quiet; follow a lower floor faster without letting
|
||||
// an isolated power spike permanently raise the threshold above CW.
|
||||
_noise += (rssi_dbm - _noise) * (rssi_dbm < _noise ? 0.05f : 0.01f);
|
||||
// A falling RF envelope may commit OFF before it reaches the final
|
||||
// valley. Keep the next rise anchored to the subsequently learned floor,
|
||||
// not to a transient shoulder left by the previous strong mark.
|
||||
_signal = _noise + 12.0f;
|
||||
}
|
||||
// Never adapt the mark estimate down toward quiet during OFF debounce:
|
||||
// doing so moves its own threshold before the falling edge can commit.
|
||||
if (_keyed && raw_keyed && rssi_dbm > _noise + 6.0f)
|
||||
_signal += (rssi_dbm - _signal) * 0.1f;
|
||||
|
||||
if (raw_keyed == _keyed) { _candidate_valid = false; traceSample(rssi_dbm, now, raw_keyed); return; }
|
||||
if (!_candidate_valid || _candidate != raw_keyed) {
|
||||
_candidate = raw_keyed;
|
||||
_candidate_at = now;
|
||||
_candidate_valid = true;
|
||||
traceSample(rssi_dbm, now, raw_keyed);
|
||||
return;
|
||||
}
|
||||
uint16_t debounce = _unit / 4;
|
||||
uint16_t minimum_debounce = 2;
|
||||
#if defined(MESH_MORSE_HIL) && MESH_MORSE_HIL \
|
||||
&& defined(MESH_MORSE_HIL_FAST_OFF_DEBOUNCE) \
|
||||
&& MESH_MORSE_HIL_FAST_OFF_DEBOUNCE == 1
|
||||
// Controlled fast-CW bench experiment: permit a one-ms falling-edge
|
||||
// confirmation only for short nominal dots. Keep ON rejection and the
|
||||
// ordinary quarter-dot rule intact; production ignores this lab flag.
|
||||
if (!raw_keyed && _nominal_unit <= 12) minimum_debounce = 1;
|
||||
#endif
|
||||
if (debounce < minimum_debounce) debounce = minimum_debounce;
|
||||
// A brief mark fade is not another symbol. Give OFF a little more time
|
||||
// than ON, but retain a ten-ms ceiling so sparse quiet spikes cannot keep
|
||||
// a very slow message keyed for an entire quarter-dot (up to 300 ms).
|
||||
const uint16_t maximum_debounce = raw_keyed ? 5 : 10;
|
||||
if (debounce > maximum_debounce) debounce = maximum_debounce;
|
||||
if (static_cast<uint32_t>(now - _candidate_at) < debounce) {
|
||||
traceSample(rssi_dbm, now, raw_keyed);
|
||||
return;
|
||||
}
|
||||
const uint32_t edge_at = _candidate_at;
|
||||
_candidate_valid = false;
|
||||
if (raw_keyed) {
|
||||
flushGap(edge_at);
|
||||
if (!_active) return;
|
||||
_keyed = true;
|
||||
// Seed immediately rather than taking a whole fast dot to train an EMA.
|
||||
_signal = rssi_dbm;
|
||||
_last_edge = edge_at;
|
||||
_letter_flushed = _word_flushed = false;
|
||||
} else {
|
||||
recordMark(static_cast<uint32_t>(edge_at - _last_edge));
|
||||
_keyed = false;
|
||||
_noise = rssi_dbm;
|
||||
_floor_settled = true;
|
||||
_signal = _noise + 12.0f; // do not hide the next, weaker mark with an old peak
|
||||
_last_edge = edge_at;
|
||||
}
|
||||
traceSample(rssi_dbm, now, raw_keyed);
|
||||
}
|
||||
|
||||
private:
|
||||
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;
|
||||
uint8_t _code = 1, _symbols = 0;
|
||||
bool _active = false, _keyed = false, _have_noise = false;
|
||||
bool _floor_settled = false;
|
||||
bool _candidate = false, _candidate_valid = false;
|
||||
bool _bad_pattern = false, _letter_flushed = false, _word_flushed = false, _truncated = false;
|
||||
#if defined(MESH_MORSE_HIL) && MESH_MORSE_HIL
|
||||
MorseRssiTrace* _trace = nullptr; // lifetime belongs to the radio wrapper
|
||||
#endif
|
||||
|
||||
void traceSample(float rssi, uint32_t now, bool raw_keyed) {
|
||||
#if defined(MESH_MORSE_HIL) && MESH_MORSE_HIL
|
||||
if (_trace) _trace->sample(rssi, static_cast<uint32_t>(now - _started),
|
||||
(raw_keyed ? 1 : 0) | (_keyed ? 2 : 0) | (_candidate_valid ? 4 : 0)
|
||||
| (learning(now) ? 8 : 0));
|
||||
#else
|
||||
(void)rssi; (void)now; (void)raw_keyed;
|
||||
#endif
|
||||
}
|
||||
|
||||
void append(char c) {
|
||||
if (c == ' ' && (!_length || _capture[_length - 1] == ' ')) return;
|
||||
if (_length >= CaptureCapacity) { capacityStop(); return; }
|
||||
_capture[_length++] = c;
|
||||
_capture[_length] = 0;
|
||||
if (_length == CaptureCapacity) capacityStop();
|
||||
}
|
||||
void capacityStop() {
|
||||
// Full capture is an explicit early stop, not an invisible rolling/drop
|
||||
// buffer. Retain the prefix, expose truncation, and resume the mesh radio.
|
||||
_truncated = true;
|
||||
_active = _keyed = _candidate_valid = false;
|
||||
}
|
||||
void flushLetter() {
|
||||
if (!_symbols && !_bad_pattern) return;
|
||||
char decoded = '?';
|
||||
if (!_bad_pattern) {
|
||||
for (char c = '!'; c <= 'Z'; ++c) {
|
||||
const uint8_t code = MorseTx::codeFor(c);
|
||||
if (code && code == _code) { decoded = c; break; }
|
||||
}
|
||||
// The printable loop ends at Z; '_' is also an ITU punctuation code.
|
||||
if (MorseTx::codeFor('_') == _code) decoded = '_';
|
||||
}
|
||||
append(decoded);
|
||||
_code = 1;
|
||||
_symbols = 0;
|
||||
_bad_pattern = false;
|
||||
_letter_flushed = true;
|
||||
}
|
||||
void flushGap(uint32_t now) {
|
||||
const uint32_t gap = static_cast<uint32_t>(now - _last_edge);
|
||||
// RSSI fall-edge delay lengthens marks while shortening the following
|
||||
// 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) {
|
||||
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) {
|
||||
_bad_pattern = true;
|
||||
return;
|
||||
}
|
||||
const bool dash = duration_ms >= uint32_t(_unit) * 2UL;
|
||||
_code = uint8_t((_code << 1) | (dash ? 1 : 0));
|
||||
++_symbols;
|
||||
uint32_t observed = dash ? (duration_ms + 1) / 3 : duration_ms;
|
||||
const uint32_t lower = uint32_t(_nominal_unit) * 3 / 4;
|
||||
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);
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace mesh
|
||||
@@ -0,0 +1,130 @@
|
||||
#include "MorseSettings.h"
|
||||
#include "FilePresence.h"
|
||||
#if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM)
|
||||
#include "AtomicFileWriter.h"
|
||||
#elif defined(ESP32_PLATFORM) || defined(RP2040_PLATFORM)
|
||||
#include "ContactFileTransaction.h"
|
||||
#endif
|
||||
|
||||
namespace mesh {
|
||||
namespace {
|
||||
FILESYSTEM* settings_fs = nullptr;
|
||||
MorseSettings settings;
|
||||
bool writes_held = false;
|
||||
bool settings_usable = false;
|
||||
constexpr const char* Path = "/morse_prefs";
|
||||
constexpr const char* Backup = "/morse_prefs.bak";
|
||||
|
||||
enum class ReadResult : uint8_t { Missing, Valid, Invalid, Unreadable };
|
||||
|
||||
ReadResult read(const char* path, MorseSettings& result) {
|
||||
if (!settings_fs) return ReadResult::Unreadable;
|
||||
bool present = false;
|
||||
if (!filePresence(settings_fs, path, present)) return ReadResult::Unreadable;
|
||||
if (!present) return ReadResult::Missing;
|
||||
#if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM)
|
||||
File file(*settings_fs);
|
||||
if (!file.open(path, FILE_O_READ)) return ReadResult::Unreadable;
|
||||
#else
|
||||
File file = settings_fs->open(path, "r");
|
||||
if (!file) return ReadResult::Unreadable;
|
||||
#endif
|
||||
uint8_t image[MorseSettingsImageSize];
|
||||
const bool right_size = file.size() == sizeof(image);
|
||||
const bool complete = right_size && file.read(image, sizeof(image)) == int(sizeof(image));
|
||||
file.close();
|
||||
if (!right_size) return ReadResult::Invalid;
|
||||
if (!complete) return ReadResult::Unreadable;
|
||||
return decodeMorseSettings(image, sizeof(image), result)
|
||||
? ReadResult::Valid : ReadResult::Invalid;
|
||||
}
|
||||
|
||||
bool repairBackup(const MorseSettings& candidate) {
|
||||
bool present = false;
|
||||
if (!filePresence(settings_fs, Path, present)
|
||||
|| (present && !settings_fs->remove(Path))
|
||||
|| !settings_fs->rename(Backup, Path)) return false;
|
||||
MorseSettings published;
|
||||
return read(Path, published) == ReadResult::Valid
|
||||
&& published.frequency_khz == candidate.frequency_khz
|
||||
&& published.wpm == candidate.wpm;
|
||||
}
|
||||
|
||||
// An explicit retry may proceed after a transient I/O error has cleared.
|
||||
// Never remove an unreadable committed image or retire the sole valid backup.
|
||||
bool refreshWritableStore() {
|
||||
MorseSettings primary_settings, backup_settings;
|
||||
const auto primary = read(Path, primary_settings);
|
||||
if (primary == ReadResult::Unreadable) return false;
|
||||
if (primary == ReadResult::Valid) return true;
|
||||
const auto backup = read(Backup, backup_settings);
|
||||
if (backup == ReadResult::Unreadable) return false;
|
||||
return backup != ReadResult::Valid || repairBackup(backup_settings);
|
||||
}
|
||||
}
|
||||
|
||||
bool loadMorseSettings(FILESYSTEM* fs) {
|
||||
settings_fs = fs;
|
||||
settings = MorseSettings();
|
||||
writes_held = !fs;
|
||||
settings_usable = false;
|
||||
if (!fs) return false;
|
||||
MorseSettings candidate;
|
||||
const auto primary = read(Path, candidate);
|
||||
if (primary == ReadResult::Valid) {
|
||||
settings = candidate;
|
||||
settings_usable = true;
|
||||
return true;
|
||||
}
|
||||
const auto backup = read(Backup, candidate);
|
||||
writes_held = primary == ReadResult::Unreadable || backup == ReadResult::Unreadable;
|
||||
if (backup != ReadResult::Valid) {
|
||||
settings_usable = primary == ReadResult::Missing && backup == ReadResult::Missing;
|
||||
return false;
|
||||
}
|
||||
settings = candidate;
|
||||
// Keep the sole validated backup protected if its publication cannot be
|
||||
// repaired, rather than allowing the next save to retire it as stale.
|
||||
if (writes_held) return true;
|
||||
writes_held = !repairBackup(candidate);
|
||||
settings_usable = !writes_held;
|
||||
return true;
|
||||
}
|
||||
|
||||
const MorseSettings& morseSettings() { return settings; }
|
||||
bool morseSettingsUsable() { return settings_usable; }
|
||||
|
||||
bool saveMorseSettings(const MorseSettings& candidate) {
|
||||
if (!settings_fs || !validMorseSettings(candidate)) return false;
|
||||
if (writes_held && !refreshWritableStore()) return false;
|
||||
writes_held = false;
|
||||
uint8_t image[MorseSettingsImageSize];
|
||||
encodeMorseSettings(candidate, image);
|
||||
#if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM)
|
||||
AtomicFileWriter writer(settings_fs, Path);
|
||||
#elif defined(ESP32_PLATFORM) || defined(RP2040_PLATFORM)
|
||||
ContactFileTransaction writer(settings_fs, Path, filePresence<FILESYSTEM>);
|
||||
#else
|
||||
return false;
|
||||
#endif
|
||||
#if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM) || defined(ESP32_PLATFORM) || defined(RP2040_PLATFORM)
|
||||
if (!writer || writer.write(image, sizeof(image)) != sizeof(image)
|
||||
|| !writer.commit()) {
|
||||
settings_usable = false;
|
||||
writes_held = true;
|
||||
return false;
|
||||
}
|
||||
MorseSettings checked;
|
||||
if (read(Path, checked) != ReadResult::Valid
|
||||
|| checked.frequency_khz != candidate.frequency_khz || checked.wpm != candidate.wpm) {
|
||||
writes_held = true;
|
||||
settings_usable = false;
|
||||
return false;
|
||||
}
|
||||
settings = candidate;
|
||||
settings_usable = true;
|
||||
return true;
|
||||
#endif
|
||||
}
|
||||
|
||||
} // namespace mesh
|
||||
@@ -0,0 +1,75 @@
|
||||
#pragma once
|
||||
|
||||
#include <helpers/IdentityStore.h>
|
||||
#include <helpers/MorseTx.h>
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
|
||||
namespace mesh {
|
||||
|
||||
struct MorseSettings {
|
||||
// A distinct TX-only channel. Neither packet-radio profile is modified.
|
||||
uint32_t frequency_khz = 902100;
|
||||
uint8_t wpm = MorseTx::DefaultWpm;
|
||||
float frequencyMHz() const { return float(frequency_khz) / 1000.0f; }
|
||||
};
|
||||
|
||||
constexpr uint32_t MorseMinFrequencyKHz = 100000;
|
||||
constexpr uint32_t MorseMaxFrequencyKHz = 1000000;
|
||||
constexpr uint8_t MorseMinWpm = MorseTx::MinWpm;
|
||||
constexpr uint8_t MorseMaxWpm = MorseTx::MaxWpm;
|
||||
constexpr size_t MorseSettingsImageSize = 12;
|
||||
|
||||
inline bool validMorseSettings(const MorseSettings& prefs) {
|
||||
return prefs.frequency_khz >= MorseMinFrequencyKHz
|
||||
&& prefs.frequency_khz <= MorseMaxFrequencyKHz
|
||||
&& prefs.wpm >= MorseMinWpm && prefs.wpm <= MorseMaxWpm;
|
||||
}
|
||||
|
||||
inline uint32_t morseSettingsCRC(const uint8_t* data, size_t size) {
|
||||
uint32_t crc = 0xffffffffUL;
|
||||
while (size--) {
|
||||
crc ^= *data++;
|
||||
for (uint8_t bit = 0; bit < 8; ++bit)
|
||||
crc = (crc >> 1) ^ ((crc & 1U) ? 0xedb88320UL : 0);
|
||||
}
|
||||
return crc;
|
||||
}
|
||||
|
||||
inline void encodeMorseSettings(const MorseSettings& prefs,
|
||||
uint8_t (&image)[MorseSettingsImageSize]) {
|
||||
image[0] = 'M'; image[1] = 'C'; image[2] = 1; image[3] = prefs.wpm;
|
||||
for (unsigned i = 0; i < 4; ++i)
|
||||
image[4 + i] = uint8_t(prefs.frequency_khz >> (i * 8));
|
||||
const uint32_t crc = morseSettingsCRC(image, 8);
|
||||
for (unsigned i = 0; i < 4; ++i) image[8 + i] = uint8_t(crc >> (i * 8));
|
||||
}
|
||||
|
||||
inline bool decodeMorseSettings(const uint8_t* image, size_t size,
|
||||
MorseSettings& prefs) {
|
||||
if (!image || size != MorseSettingsImageSize || image[0] != 'M'
|
||||
|| image[1] != 'C' || image[2] != 1) return false;
|
||||
uint32_t frequency = 0, crc = 0;
|
||||
for (unsigned i = 0; i < 4; ++i) {
|
||||
frequency |= uint32_t(image[4 + i]) << (i * 8);
|
||||
crc |= uint32_t(image[8 + i]) << (i * 8);
|
||||
}
|
||||
MorseSettings candidate;
|
||||
candidate.frequency_khz = frequency;
|
||||
candidate.wpm = image[3];
|
||||
if (crc != morseSettingsCRC(image, 8) || !validMorseSettings(candidate))
|
||||
return false;
|
||||
prefs = candidate;
|
||||
return true;
|
||||
}
|
||||
|
||||
// Independent checked storage leaves legacy node/Companion layouts intact.
|
||||
// Defaults and saved settings never begin transmitting automatically.
|
||||
bool loadMorseSettings(FILESYSTEM* fs);
|
||||
const MorseSettings& morseSettings();
|
||||
// A missing fresh store is ready with defaults. Unreadable/corrupt saved
|
||||
// frequency must not silently become the default transmit frequency.
|
||||
bool morseSettingsUsable();
|
||||
bool saveMorseSettings(const MorseSettings& candidate);
|
||||
|
||||
} // namespace mesh
|
||||
@@ -0,0 +1,190 @@
|
||||
#pragma once
|
||||
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
#include <math.h>
|
||||
|
||||
namespace mesh {
|
||||
|
||||
#ifndef MESH_MORSE_MAX_WPM
|
||||
#define MESH_MORSE_MAX_WPM 60
|
||||
#endif
|
||||
static_assert(MESH_MORSE_MAX_WPM >= 1 && MESH_MORSE_MAX_WPM <= 255,
|
||||
"Morse WPM must fit the command/API byte");
|
||||
|
||||
enum class MorseTxResult : uint8_t {
|
||||
Started, Stopped, Busy, Unsupported, InvalidFrequency, Overlap,
|
||||
InvalidText, InvalidSpeed, TooLong, Failed
|
||||
};
|
||||
|
||||
// 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;
|
||||
// this prevents tuple overlap, not interference with unrelated RF users.
|
||||
inline bool morseFrequencyOverlaps(float carrier_mhz, float profile_mhz,
|
||||
float bandwidth_khz) {
|
||||
return isfinite(carrier_mhz) && isfinite(profile_mhz) && isfinite(bandwidth_khz)
|
||||
&& profile_mhz > 0 && bandwidth_khz > 0
|
||||
// float MHz tuples quantize by about 61 Hz in the 900 MHz band. Keep a
|
||||
// conservative 100 Hz tolerance so a nominal guard-edge value cannot
|
||||
// round outward and accidentally pass the non-overlap check.
|
||||
&& fabsf(carrier_mhz - profile_mhz) * 1000.0f <= bandwidth_khz * 0.5f + 10.1f;
|
||||
}
|
||||
|
||||
// Portable, bounded ITU Morse encoder/timer. The leading 1 in each code is a
|
||||
// length sentinel; subsequent bits are dot=0/dash=1, most significant first.
|
||||
// No heap, delay(), or pre-expanded sequence of hundreds of marks is needed.
|
||||
class MorseTx {
|
||||
public:
|
||||
static constexpr float DefaultFrequencyMHz = 902.100f;
|
||||
static constexpr uint8_t DefaultWpm = 25;
|
||||
static constexpr uint8_t MinWpm = 1;
|
||||
static constexpr uint8_t MaxWpm = MESH_MORSE_MAX_WPM;
|
||||
static constexpr size_t MaxTextLength = 80;
|
||||
static constexpr uint32_t MaxDurationMillis = 180000UL;
|
||||
enum class Edge : uint8_t { None, KeyDown, KeyUp, Complete, Expired };
|
||||
|
||||
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
|
||||
};
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
static uint8_t symbolCount(uint8_t code) {
|
||||
uint8_t count = 0;
|
||||
while (code > 1) { code >>= 1; ++count; }
|
||||
return count;
|
||||
}
|
||||
|
||||
static uint16_t unitMillis(uint8_t wpm) {
|
||||
return wpm >= MinWpm && wpm <= MaxWpm ? (1200U + wpm / 2) / wpm : 0;
|
||||
}
|
||||
|
||||
static MorseTxResult validate(const char* text, uint8_t wpm,
|
||||
uint32_t* duration_ms = nullptr) {
|
||||
const uint16_t unit = unitMillis(wpm);
|
||||
if (!unit) return MorseTxResult::InvalidSpeed;
|
||||
if (!text) return MorseTxResult::InvalidText;
|
||||
uint32_t units = 0;
|
||||
bool have_character = false, have_space = false;
|
||||
size_t length = 0;
|
||||
for (; length <= MaxTextLength && text[length]; ++length) {
|
||||
const char character = text[length];
|
||||
if (character == ' ') { if (have_character) have_space = true; continue; }
|
||||
const uint8_t code = codeFor(character);
|
||||
if (!code) return MorseTxResult::InvalidText;
|
||||
if (have_character) units += have_space ? 7 : 3;
|
||||
const uint8_t count = symbolCount(code);
|
||||
for (uint8_t bit = count; bit; --bit) {
|
||||
units += (code & (1U << (bit - 1))) ? 3 : 1;
|
||||
if (bit > 1) ++units;
|
||||
}
|
||||
have_character = true;
|
||||
have_space = false;
|
||||
}
|
||||
if (length > MaxTextLength) return MorseTxResult::TooLong;
|
||||
if (!have_character) return MorseTxResult::InvalidText;
|
||||
const uint32_t duration = units * unit;
|
||||
if (duration > MaxDurationMillis) return MorseTxResult::TooLong;
|
||||
if (duration_ms) *duration_ms = duration;
|
||||
return MorseTxResult::Started;
|
||||
}
|
||||
|
||||
MorseTxResult start(const char* text, uint8_t wpm, uint32_t now) {
|
||||
uint32_t duration;
|
||||
const auto result = validate(text, wpm, &duration);
|
||||
if (result != MorseTxResult::Started) return result;
|
||||
size_t output = 0;
|
||||
bool space = false;
|
||||
// Canonicalize case and collapse/trim spaces only after full validation.
|
||||
for (size_t input = 0; text[input]; ++input) {
|
||||
char c = text[input];
|
||||
if (c == ' ') { if (output) space = true; continue; }
|
||||
if (space) _text[output++] = ' ';
|
||||
space = false;
|
||||
if (c >= 'a' && c <= 'z') c -= 'a' - 'A';
|
||||
_text[output++] = c;
|
||||
}
|
||||
_text[output] = 0;
|
||||
_unit = unitMillis(wpm);
|
||||
_character = _symbol = 0;
|
||||
_code = codeFor(_text[0]);
|
||||
_count = symbolCount(_code);
|
||||
_active = _keyed = true;
|
||||
_remaining = duration;
|
||||
_phase_ms = markUnits() * _unit;
|
||||
_next = now + _phase_ms;
|
||||
_hard_end = now + MaxDurationMillis;
|
||||
return MorseTxResult::Started;
|
||||
}
|
||||
|
||||
void stop() { _active = _keyed = false; _remaining = 0; }
|
||||
bool active() const { return _active; }
|
||||
bool keyed() const { return _active && _keyed; }
|
||||
uint32_t hardDeadline() const { return _hard_end; }
|
||||
uint32_t nextDeadline() const { return _next; }
|
||||
// Hardware mode commands can take milliseconds. Start the entire next
|
||||
// mark/gap after that command completes, rather than shortening Morse at
|
||||
// the faster WPM values by the SPI/oscillator transition time.
|
||||
void edgeApplied(uint32_t now) { if (_active) _next = now + _phase_ms; }
|
||||
|
||||
uint32_t remainingMillis(uint32_t now) const {
|
||||
if (!_active) return 0;
|
||||
const int32_t phase_left = static_cast<int32_t>(_next - now);
|
||||
const uint32_t other = _remaining > _phase_ms ? _remaining - _phase_ms : 0;
|
||||
return other + (phase_left > 0 ? static_cast<uint32_t>(phase_left) : 0);
|
||||
}
|
||||
|
||||
Edge advance(uint32_t now) {
|
||||
if (!_active) return Edge::None;
|
||||
if (static_cast<int32_t>(now - _hard_end) >= 0) {
|
||||
stop();
|
||||
return Edge::Expired;
|
||||
}
|
||||
if (static_cast<int32_t>(now - _next) < 0) return Edge::None;
|
||||
_remaining = _remaining > _phase_ms ? _remaining - _phase_ms : 0;
|
||||
if (_keyed) {
|
||||
_keyed = false;
|
||||
uint8_t gap = 1;
|
||||
if (++_symbol >= _count) {
|
||||
if (!_text[++_character]) { stop(); return Edge::Complete; }
|
||||
gap = 3;
|
||||
if (_text[_character] == ' ') { ++_character; gap = 7; }
|
||||
_symbol = 0;
|
||||
_code = codeFor(_text[_character]);
|
||||
_count = symbolCount(_code);
|
||||
}
|
||||
_phase_ms = gap * _unit;
|
||||
// Rebase on actual service time. Never key a burst of missed edges.
|
||||
_next = now + _phase_ms;
|
||||
return Edge::KeyUp;
|
||||
}
|
||||
_keyed = true;
|
||||
_phase_ms = markUnits() * _unit;
|
||||
_next = now + _phase_ms;
|
||||
return Edge::KeyDown;
|
||||
}
|
||||
|
||||
private:
|
||||
char _text[MaxTextLength + 1] = {};
|
||||
uint32_t _next = 0, _hard_end = 0, _remaining = 0;
|
||||
uint16_t _unit = 0, _phase_ms = 0;
|
||||
uint8_t _character = 0, _symbol = 0, _code = 0, _count = 0;
|
||||
bool _active = false, _keyed = false;
|
||||
uint8_t markUnits() const { return (_code & (1U << (_count - 1 - _symbol))) ? 3 : 1; }
|
||||
};
|
||||
|
||||
} // namespace mesh
|
||||
@@ -2,18 +2,19 @@
|
||||
#include "RS232UartUtils.h"
|
||||
|
||||
#include <HardwareSerial.h>
|
||||
#include <stdio.h>
|
||||
|
||||
#ifdef WITH_RS232_BRIDGE
|
||||
|
||||
#ifdef ESP32
|
||||
// check_firmware_ram.py reserves this object plus the UART driver's runtime
|
||||
// allocation even when a combined Full image starts with the UART disabled.
|
||||
static_assert(sizeof(RS232Bridge) <= 2304, "Update the ESP32 UART heap budget");
|
||||
static_assert(sizeof(RS232Bridge) <= 2816, "Update the ESP32 UART heap budget");
|
||||
#endif
|
||||
#if defined(NRF52_PLATFORM) && defined(RAK4631_COMBINED_ETHERNET)
|
||||
// The combined RAK RAM policy reserves this object plus allocator metadata
|
||||
// and the UART driver's TX semaphore. Its RX/TX arrays are linked globals.
|
||||
static_assert(sizeof(RS232Bridge) <= 2304, "Update the combined RAK UART heap budget");
|
||||
static_assert(sizeof(RS232Bridge) <= 2816, "Update the combined RAK UART heap budget");
|
||||
#endif
|
||||
|
||||
RS232Bridge::RS232Bridge(NodePrefs *prefs, Stream &serial, int16_t rx_pin,
|
||||
@@ -24,8 +25,7 @@ RS232Bridge::RS232Bridge(NodePrefs *prefs, Stream &serial, int16_t rx_pin,
|
||||
|
||||
void RS232Bridge::begin() {
|
||||
_initialized = false;
|
||||
_rx_buffer_pos = 0;
|
||||
_rx_packet_ready = false;
|
||||
resetTransportState();
|
||||
BRIDGE_DEBUG_PRINTLN("Initializing at %d baud...\n", _prefs->bridge_baud);
|
||||
#if defined(ESP32)
|
||||
if (!((HardwareSerial *)_serial)->setPins(_rx_pin, _tx_pin)) return;
|
||||
@@ -60,8 +60,227 @@ void RS232Bridge::end() {
|
||||
|
||||
// Update bridge state
|
||||
_initialized = false;
|
||||
resetTransportState();
|
||||
}
|
||||
|
||||
void RS232Bridge::resetTransportState() {
|
||||
_rx_buffer_pos = 0;
|
||||
_rx_packet_ready = false;
|
||||
_tx_size = _tx_pos = 0;
|
||||
_tx_wire_pending = false;
|
||||
_tx_is_ping = false;
|
||||
_tx_ping_challenge = 0;
|
||||
_outstanding_challenge = 0;
|
||||
_pong_target = 0;
|
||||
_pong_challenge = 0;
|
||||
_ping_due = true;
|
||||
_partial_suspend_grace = false;
|
||||
}
|
||||
|
||||
void RS232Bridge::setHeartbeatSession(uint64_t session) {
|
||||
if (_session == session) return;
|
||||
_session = session;
|
||||
_challenge_counter = static_cast<uint32_t>(session)
|
||||
^ static_cast<uint32_t>(session >> 32) ^ 0x9E3779B9UL;
|
||||
resetTransportState();
|
||||
_peer_session = 0;
|
||||
_have_ack = false;
|
||||
_ack_fresh = false;
|
||||
_standby_armed = false;
|
||||
_legacy_rx = false;
|
||||
_legacy_fresh = false;
|
||||
_power.resetPeer(millis());
|
||||
}
|
||||
|
||||
void RS232Bridge::setHeartbeatEnabled(bool enabled) {
|
||||
if (enabled && !_heartbeat_enabled) _ping_due = true;
|
||||
_heartbeat_enabled = enabled;
|
||||
if (!enabled) _standby_armed = false;
|
||||
if (!enabled && _tx_is_ping && _tx_pos == 0) {
|
||||
// An unsent PING can be withdrawn. A partially emitted frame must finish
|
||||
// to preserve framing of later mesh data; passive PONGs remain supported.
|
||||
_tx_size = 0;
|
||||
_tx_is_ping = false;
|
||||
_tx_ping_challenge = 0;
|
||||
}
|
||||
}
|
||||
|
||||
uint32_t RS232Bridge::frameAssemblyMs() const {
|
||||
const uint32_t baud = _prefs->bridge_baud ? _prefs->bridge_baud : 115200;
|
||||
// Ten wire bits per byte (8N1), plus loop scheduling margin. Start-relative,
|
||||
// not last-byte-relative: a noise trickle cannot extend an assembly forever.
|
||||
uint32_t duration = static_cast<uint32_t>(
|
||||
(static_cast<uint64_t>(MAX_SERIAL_PACKET_SIZE) * 10000 + baud - 1) / baud) + 1000;
|
||||
if (duration < 1000) duration = 1000;
|
||||
if (duration > 3000) duration = 3000;
|
||||
return duration;
|
||||
}
|
||||
|
||||
void RS232Bridge::expirePartialReceive(uint32_t now) {
|
||||
if (_rx_buffer_pos != 0 && !_rx_packet_ready
|
||||
&& static_cast<uint32_t>(now - _rx_started) >= frameAssemblyMs()) {
|
||||
_rx_buffer_pos = 0;
|
||||
}
|
||||
}
|
||||
|
||||
void RS232Bridge::expireHeartbeatFreshness(uint32_t now) {
|
||||
// Freshness expires permanently until real RX refreshes it. Historical
|
||||
// negotiation remains separate, so dead updated peers can still rendezvous
|
||||
// and an old timestamp cannot appear alive after a full millis() cycle.
|
||||
if (_ack_fresh && static_cast<uint32_t>(now - _last_ack) >= _idle_ms) {
|
||||
_ack_fresh = false;
|
||||
}
|
||||
if (_legacy_fresh && static_cast<uint32_t>(now - _last_legacy_rx) >= _idle_ms) {
|
||||
_legacy_fresh = false;
|
||||
}
|
||||
}
|
||||
|
||||
bool RS232Bridge::txPending(uint32_t now) const {
|
||||
return _tx_size != 0 || (_tx_wire_pending
|
||||
&& !mesh::bridge::rs232heartbeat::due(now, _tx_wire_until));
|
||||
}
|
||||
|
||||
RS232Bridge::PowerAction RS232Bridge::servicePowerPolicy(
|
||||
bool allow_standby, uint32_t idle_ms, uint32_t now, bool force_unconfirmed) {
|
||||
_idle_ms = idle_ms;
|
||||
expireHeartbeatFreshness(now);
|
||||
// Historical successful bidirectional negotiation survives a soft UART stop,
|
||||
// but a fresh object/session has no such capability. Never stop a stock or
|
||||
// never-confirmed peer by default; explicit force mode is for dead settings.
|
||||
const bool armed = allow_standby && _heartbeat_enabled
|
||||
&& (_have_ack || force_unconfirmed);
|
||||
_standby_armed = armed;
|
||||
expirePartialReceive(now);
|
||||
bool partial_blocks = false;
|
||||
if (_rx_buffer_pos != 0 && !_rx_packet_ready
|
||||
&& _power.standbyDue(armed, idle_ms, now)) {
|
||||
// One bounded grace period at the inactivity deadline; repeatedly starting
|
||||
// malformed headers cannot keep UART awake indefinitely.
|
||||
if (!_partial_suspend_grace) {
|
||||
_partial_suspend_grace = true;
|
||||
_partial_suspend_until = now + frameAssemblyMs();
|
||||
}
|
||||
partial_blocks = !mesh::bridge::rs232heartbeat::due(now, _partial_suspend_until);
|
||||
if (!partial_blocks) _rx_buffer_pos = 0;
|
||||
} else if (!_power.standbyDue(armed, idle_ms, now)) {
|
||||
_partial_suspend_grace = false;
|
||||
}
|
||||
return _power.service(armed, idle_ms, now, _initialized,
|
||||
_rx_packet_ready || txPending(now) || partial_blocks);
|
||||
}
|
||||
|
||||
void RS232Bridge::completePowerAction(PowerAction action, bool success, uint32_t now) {
|
||||
_power.complete(action, success, now);
|
||||
}
|
||||
|
||||
uint32_t RS232Bridge::powerWakeDelayMs(uint32_t now) const {
|
||||
return _power.wakeDelay(now);
|
||||
}
|
||||
|
||||
void RS232Bridge::formatHeartbeatStatus(char* out, size_t capacity, uint32_t now) const {
|
||||
if (!out || capacity == 0) return;
|
||||
const bool confirmed = _ack_fresh && static_cast<uint32_t>(now - _last_ack) < _idle_ms;
|
||||
const char* phase = _power.retrying() ? "retrying"
|
||||
: _power.suspended() ? "standby" : _power.probing() ? "probing"
|
||||
: _initialized ? "active" : "stopped";
|
||||
const char* peer = confirmed ? "confirmed" : _legacy_fresh
|
||||
&& static_cast<uint32_t>(now - _last_legacy_rx) < _idle_ms ? "legacy" : "unknown";
|
||||
const uint32_t age = _power.peerAge(now);
|
||||
const uint32_t wake = powerWakeDelayMs(now);
|
||||
snprintf(out, capacity, "state=%s,peer=%s,age_s=%lu,wake_s=%lu,heartbeat=%s,armed=%s",
|
||||
phase, peer, static_cast<unsigned long>(age == UINT32_MAX ? 0 : age / 1000),
|
||||
static_cast<unsigned long>(wake == UINT32_MAX ? 0 : (wake + 999) / 1000),
|
||||
_heartbeat_enabled ? "on" : "passive", _standby_armed ? "on" : "off");
|
||||
out[capacity - 1] = 0;
|
||||
}
|
||||
|
||||
void RS232Bridge::drainTransmit(uint32_t now, bool blocking) {
|
||||
if (!_initialized || _tx_size == 0) return;
|
||||
size_t amount = static_cast<size_t>(_tx_size - _tx_pos);
|
||||
if (!blocking) {
|
||||
const int available = _serial->availableForWrite();
|
||||
if (available <= 0) return;
|
||||
if (amount > static_cast<size_t>(available)) amount = static_cast<size_t>(available);
|
||||
}
|
||||
size_t sent = _serial->write(_tx_buffer + _tx_pos, amount);
|
||||
if (sent > amount) sent = amount;
|
||||
if (sent == 0) return;
|
||||
_tx_pos = static_cast<uint16_t>(_tx_pos + sent);
|
||||
const uint32_t baud = _prefs->bridge_baud ? _prefs->bridge_baud : 115200;
|
||||
uint32_t base = now;
|
||||
if (_tx_wire_pending && !mesh::bridge::rs232heartbeat::due(now, _tx_wire_until)) {
|
||||
base = _tx_wire_until;
|
||||
}
|
||||
_tx_wire_until = base + static_cast<uint32_t>((sent * 10000UL + baud - 1) / baud) + 1;
|
||||
_tx_wire_pending = true;
|
||||
if (_tx_pos == _tx_size) {
|
||||
if (_tx_is_ping) {
|
||||
_outstanding_challenge = _tx_ping_challenge;
|
||||
_outstanding_since = now;
|
||||
}
|
||||
_tx_size = _tx_pos = 0;
|
||||
_tx_is_ping = false;
|
||||
}
|
||||
}
|
||||
|
||||
bool RS232Bridge::queueControl(char opcode, uint64_t target, uint32_t challenge) {
|
||||
if (_tx_size != 0 || _session == 0) return false;
|
||||
mesh::bridge::rs232heartbeat::Control control;
|
||||
control.opcode = opcode;
|
||||
control.sender = _session;
|
||||
control.target = target;
|
||||
control.challenge = challenge;
|
||||
if (!mesh::bridge::rs232heartbeat::encode(_tx_buffer + 4, control)) return false;
|
||||
_tx_buffer[0] = 0xC0; _tx_buffer[1] = 0x3E;
|
||||
_tx_buffer[2] = _tx_buffer[3] = 0;
|
||||
_tx_size = mesh::bridge::rs232heartbeat::FRAME_SIZE;
|
||||
_tx_pos = 0;
|
||||
_tx_is_ping = opcode == 'P';
|
||||
_tx_ping_challenge = challenge;
|
||||
return true;
|
||||
}
|
||||
|
||||
void RS232Bridge::serviceHeartbeat(uint32_t now) {
|
||||
if (_session == 0 || _tx_size != 0) return;
|
||||
if (_pong_target != 0) {
|
||||
if (queueControl('A', _pong_target, _pong_challenge)) {
|
||||
_pong_target = 0;
|
||||
_pong_challenge = 0;
|
||||
}
|
||||
} else if (_heartbeat_enabled && (_ping_due
|
||||
|| mesh::bridge::rs232heartbeat::due(now, _next_ping))) {
|
||||
++_challenge_counter;
|
||||
if (_challenge_counter == 0) ++_challenge_counter;
|
||||
if (queueControl('P', 0, _challenge_counter)) {
|
||||
_ping_due = false;
|
||||
_next_ping = now + (_power.probing()
|
||||
? mesh::bridge::rs232heartbeat::PROBE_PING_MS
|
||||
: mesh::bridge::rs232heartbeat::ACTIVE_PING_MS);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void RS232Bridge::handleControl(uint32_t now) {
|
||||
mesh::bridge::rs232heartbeat::Control control;
|
||||
if (_session == 0 || !mesh::bridge::rs232heartbeat::decode(_rx_buffer + 4, control)
|
||||
|| control.sender == _session) return;
|
||||
if (control.opcode == 'P') {
|
||||
// A replayed PING is not peer liveness. Only a fresh challenge response
|
||||
// proves bidirectional reachability; replying also supports passive peers.
|
||||
_pong_target = control.sender;
|
||||
_pong_challenge = control.challenge;
|
||||
} else if (control.target == _session && _outstanding_challenge != 0
|
||||
&& control.challenge == _outstanding_challenge
|
||||
&& static_cast<uint32_t>(now - _outstanding_since)
|
||||
<= mesh::bridge::rs232heartbeat::ACK_MAX_AGE_MS) {
|
||||
_outstanding_challenge = 0; // A matching ACK can be consumed only once.
|
||||
_peer_session = control.sender;
|
||||
_last_ack = now;
|
||||
_have_ack = true;
|
||||
_ack_fresh = true;
|
||||
_power.notePeer(now);
|
||||
_partial_suspend_grace = false;
|
||||
}
|
||||
}
|
||||
|
||||
void RS232Bridge::drainReceivedPackets() {
|
||||
@@ -72,7 +291,33 @@ void RS232Bridge::drainReceivedPackets() {
|
||||
const bool valid = pkt->readFrom(_rx_buffer + 4, len);
|
||||
_rx_buffer_pos = 0;
|
||||
_rx_packet_ready = false;
|
||||
if (valid) onPacketReceived(pkt);
|
||||
if (valid) {
|
||||
// A cable loopback or replay of our own accepted mesh TX is not peer proof.
|
||||
// Discard here to avoid testing/counting the same duplicate a second time
|
||||
// inside BridgeBase::handleReceivedPacket().
|
||||
if (_seen_packets.wasSeen(pkt)) {
|
||||
_mgr->free(pkt);
|
||||
return;
|
||||
}
|
||||
// Legacy traffic proves inbound reachability, not a bidirectional heartbeat.
|
||||
// If ordinary data continues after heartbeat replies have stopped, a stock
|
||||
// peer may have replaced the negotiated one. Unarm the safe default rather
|
||||
// than eventually sleeping that quiet legacy link. A later fresh ACK can
|
||||
// immediately restore negotiated capability; force mode remains explicit.
|
||||
if (_have_ack && (!_ack_fresh
|
||||
|| static_cast<uint32_t>(_rx_packet_received_ms - _last_ack)
|
||||
> mesh::bridge::rs232heartbeat::ACTIVE_PING_MS
|
||||
+ mesh::bridge::rs232heartbeat::ACK_MAX_AGE_MS)) {
|
||||
_have_ack = false;
|
||||
_peer_session = 0;
|
||||
}
|
||||
_legacy_rx = true;
|
||||
_legacy_fresh = true;
|
||||
_last_legacy_rx = _rx_packet_received_ms;
|
||||
_power.notePeer(_rx_packet_received_ms);
|
||||
_partial_suspend_grace = false;
|
||||
onPacketReceived(pkt);
|
||||
}
|
||||
else _mgr->free(pkt);
|
||||
}
|
||||
|
||||
@@ -82,6 +327,15 @@ void RS232Bridge::loop() {
|
||||
return;
|
||||
}
|
||||
|
||||
const uint32_t now = millis();
|
||||
expireHeartbeatFreshness(now);
|
||||
// Let a tail already buffered by the UART complete first. Flash/admin/sensor
|
||||
// work can pause the loop beyond the assembly deadline even though the peer
|
||||
// transmitted the complete frame on time; expiry before draining would drop
|
||||
// valid legacy traffic. A still-incomplete tail expires after bounded work.
|
||||
if (_serial->available() == 0) expirePartialReceive(now);
|
||||
drainTransmit(now);
|
||||
|
||||
drainReceivedPackets();
|
||||
// Snapshot bounded work; a noisy UART must not starve mesh/radio service.
|
||||
int remaining = _serial->available();
|
||||
@@ -96,12 +350,14 @@ void RS232Bridge::loop() {
|
||||
if ((_rx_buffer_pos == 0 && b == ((BRIDGE_PACKET_MAGIC >> 8) & 0xFF)) ||
|
||||
(_rx_buffer_pos == 1 && b == (BRIDGE_PACKET_MAGIC & 0xFF))) {
|
||||
_rx_buffer[_rx_buffer_pos++] = b;
|
||||
if (_rx_buffer_pos == 1) _rx_started = now;
|
||||
} else {
|
||||
// Invalid magic byte, reset and start over
|
||||
_rx_buffer_pos = 0;
|
||||
// Check if this byte could be the start of a new magic word
|
||||
if (b == ((BRIDGE_PACKET_MAGIC >> 8) & 0xFF)) {
|
||||
_rx_buffer[_rx_buffer_pos++] = b;
|
||||
_rx_started = now;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
@@ -112,18 +368,33 @@ void RS232Bridge::loop() {
|
||||
uint16_t len = (_rx_buffer[2] << 8) | _rx_buffer[3];
|
||||
|
||||
// Validate length field
|
||||
if (len == 0 || len > (MAX_TRANS_UNIT + 1)) {
|
||||
if (len > (MAX_TRANS_UNIT + 1)) {
|
||||
BRIDGE_DEBUG_PRINTLN("RX invalid length %d, resetting\n", len);
|
||||
_rx_buffer_pos = 0; // Invalid length, reset
|
||||
continue;
|
||||
}
|
||||
|
||||
if (len == 0) {
|
||||
// Zero length was invalid in the old mesh parser. The extension body
|
||||
// is fixed-size ASCII, so old receivers cannot find C0 3E within it.
|
||||
// New receivers resync immediately if a real new frame interrupts it.
|
||||
if (_rx_buffer_pos > 4 && b >= 0x80) {
|
||||
_rx_buffer_pos = 0;
|
||||
if (b == 0xC0) { _rx_buffer[0] = b; _rx_buffer_pos = 1; _rx_started = now; }
|
||||
} else if (_rx_buffer_pos == mesh::bridge::rs232heartbeat::FRAME_SIZE) {
|
||||
handleControl(now);
|
||||
_rx_buffer_pos = 0;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if (_rx_buffer_pos == len + SERIAL_OVERHEAD) { // Full packet received
|
||||
uint16_t received_checksum = (_rx_buffer[4 + len] << 8) | _rx_buffer[5 + len];
|
||||
|
||||
if (validateChecksum(_rx_buffer + 4, len, received_checksum)) {
|
||||
BRIDGE_DEBUG_PRINTLN("RX, len=%d crc=0x%04x\n", len, received_checksum);
|
||||
_rx_packet_ready = true;
|
||||
_rx_packet_received_ms = now;
|
||||
drainReceivedPackets(); // continue this bounded batch when the pool is available
|
||||
} else {
|
||||
BRIDGE_DEBUG_PRINTLN("RX checksum mismatch, rcv=0x%04x\n", received_checksum);
|
||||
@@ -134,6 +405,9 @@ void RS232Bridge::loop() {
|
||||
}
|
||||
}
|
||||
drainReceivedPackets();
|
||||
expirePartialReceive(now);
|
||||
serviceHeartbeat(now);
|
||||
drainTransmit(now);
|
||||
}
|
||||
|
||||
void RS232Bridge::sendPacket(mesh::Packet *packet) {
|
||||
@@ -150,14 +424,21 @@ void RS232Bridge::sendPacket(mesh::Packet *packet) {
|
||||
|
||||
if (!allowsPacket(packet)) return;
|
||||
|
||||
// Preserve the legacy data path's blocking UART acceptance/throughput.
|
||||
// Finish a partially emitted control/data frame first, never interleave it.
|
||||
// A genuine failed/short hardware write is retained for later loop service;
|
||||
// only that failure case cannot accept this caller's additional packet.
|
||||
drainTransmit(millis(), true);
|
||||
if (_tx_size != 0) return; // Never interleave mesh traffic with a partial frame.
|
||||
|
||||
if (!_seen_packets.wasSeen(packet)) {
|
||||
const int expected = packet->getRawLength();
|
||||
if (expected <= 0 || expected > MAX_TRANS_UNIT + 1) return;
|
||||
uint8_t buffer[MAX_SERIAL_PACKET_SIZE];
|
||||
uint8_t* buffer = _tx_buffer;
|
||||
uint16_t len = packet->writeTo(buffer + 4);
|
||||
|
||||
// Check if packet fits within our maximum payload size
|
||||
if (len > (MAX_TRANS_UNIT + 1)) {
|
||||
if (len == 0 || len > (MAX_TRANS_UNIT + 1)) {
|
||||
BRIDGE_DEBUG_PRINTLN("TX packet too large (payload=%d, max=%d)\n", len, MAX_TRANS_UNIT + 1);
|
||||
return;
|
||||
}
|
||||
@@ -173,10 +454,14 @@ void RS232Bridge::sendPacket(mesh::Packet *packet) {
|
||||
buffer[4 + len] = (checksum >> 8) & 0xFF; // Checksum high byte
|
||||
buffer[5 + len] = checksum & 0xFF; // Checksum low byte
|
||||
|
||||
// Send complete packet
|
||||
if (_serial->write(buffer, len + SERIAL_OVERHEAD) == static_cast<size_t>(len + SERIAL_OVERHEAD)) {
|
||||
_seen_packets.markSeen(packet);
|
||||
}
|
||||
// Own the complete frame before returning the shared mesh packet. Data
|
||||
// uses the original blocking write contract; control-only loop work stays
|
||||
// nonblocking. Local UART acceptance is never peer liveness.
|
||||
_tx_size = static_cast<uint16_t>(len + SERIAL_OVERHEAD);
|
||||
_tx_pos = 0;
|
||||
_tx_is_ping = false;
|
||||
_seen_packets.markSeen(packet);
|
||||
drainTransmit(millis(), true);
|
||||
|
||||
BRIDGE_DEBUG_PRINTLN("TX, len=%d crc=0x%04x\n", len, checksum);
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
#pragma once
|
||||
|
||||
#include "helpers/bridges/BridgeBase.h"
|
||||
#include "helpers/bridges/RS232Heartbeat.h"
|
||||
|
||||
#include <Stream.h>
|
||||
|
||||
@@ -109,6 +110,19 @@ public:
|
||||
*/
|
||||
void onPacketReceived(mesh::Packet *packet) override;
|
||||
|
||||
using PowerAction = mesh::bridge::RS232PowerPolicy::Action;
|
||||
|
||||
// The owner supplies a fresh, nonzero boot/object session before begin().
|
||||
// This is not a persistent identity or authentication secret.
|
||||
void setHeartbeatSession(uint64_t session);
|
||||
void setHeartbeatEnabled(bool enabled);
|
||||
PowerAction servicePowerPolicy(bool allow_standby, uint32_t idle_ms, uint32_t now,
|
||||
bool force_unconfirmed = false);
|
||||
void completePowerAction(PowerAction action, bool success, uint32_t now);
|
||||
uint32_t powerWakeDelayMs(uint32_t now) const;
|
||||
void formatHeartbeatStatus(char* out, size_t capacity, uint32_t now) const;
|
||||
bool isPowerSuspended() const { return _power.suspended(); }
|
||||
|
||||
private:
|
||||
/**
|
||||
* RS232 Protocol Structure:
|
||||
@@ -149,6 +163,50 @@ private:
|
||||
|
||||
/** Current position in the receive buffer */
|
||||
uint16_t _rx_buffer_pos = 0;
|
||||
|
||||
// Data and control share this owned buffer, so partial UART writes can never
|
||||
// interleave frames. It owns bytes, not a mesh::Packet from the shared pool.
|
||||
uint8_t _tx_buffer[MAX_SERIAL_PACKET_SIZE];
|
||||
uint16_t _tx_size = 0;
|
||||
uint16_t _tx_pos = 0;
|
||||
uint32_t _tx_wire_until = 0;
|
||||
bool _tx_wire_pending = false;
|
||||
bool _tx_is_ping = false;
|
||||
uint32_t _tx_ping_challenge = 0;
|
||||
|
||||
mesh::bridge::RS232PowerPolicy _power;
|
||||
uint64_t _session = 0;
|
||||
uint64_t _peer_session = 0;
|
||||
uint64_t _pong_target = 0;
|
||||
uint32_t _pong_challenge = 0;
|
||||
uint32_t _challenge_counter = 0;
|
||||
uint32_t _outstanding_challenge = 0;
|
||||
uint32_t _outstanding_since = 0;
|
||||
uint32_t _next_ping = 0;
|
||||
uint32_t _last_ack = 0;
|
||||
uint32_t _last_legacy_rx = 0;
|
||||
uint32_t _rx_started = 0;
|
||||
uint32_t _rx_packet_received_ms = 0;
|
||||
uint32_t _partial_suspend_until = 0;
|
||||
uint32_t _idle_ms = 300000;
|
||||
bool _heartbeat_enabled = true;
|
||||
bool _standby_armed = false;
|
||||
bool _ping_due = true;
|
||||
bool _have_ack = false;
|
||||
bool _ack_fresh = false;
|
||||
bool _legacy_rx = false;
|
||||
bool _legacy_fresh = false;
|
||||
bool _partial_suspend_grace = false;
|
||||
|
||||
void resetTransportState();
|
||||
void expirePartialReceive(uint32_t now);
|
||||
void expireHeartbeatFreshness(uint32_t now);
|
||||
uint32_t frameAssemblyMs() const;
|
||||
bool txPending(uint32_t now) const;
|
||||
void drainTransmit(uint32_t now, bool blocking = false);
|
||||
void serviceHeartbeat(uint32_t now);
|
||||
bool queueControl(char opcode, uint64_t target, uint32_t challenge);
|
||||
void handleControl(uint32_t now);
|
||||
};
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,215 @@
|
||||
#pragma once
|
||||
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
|
||||
// Portable wire/power helpers: no Arduino dependency, allocation, mesh packets,
|
||||
// wall clock, or peer-controlled timing values.
|
||||
namespace mesh {
|
||||
namespace bridge {
|
||||
namespace rs232heartbeat {
|
||||
|
||||
static constexpr size_t BODY_SIZE = 48;
|
||||
static constexpr size_t CHECKSUM_OFFSET = 44;
|
||||
static constexpr size_t FRAME_SIZE = 4 + BODY_SIZE;
|
||||
static constexpr uint32_t ACTIVE_PING_MS = 30000;
|
||||
static constexpr uint32_t PROBE_PING_MS = 1000;
|
||||
static constexpr uint32_t ACK_MAX_AGE_MS = 5000;
|
||||
// One long listening window exceeds the other peer's maximum 30 s standby
|
||||
// plus short probe/round-trip margin. The eighth-window rendezvous therefore
|
||||
// reconnects two stopped UARTs at arbitrary phases without lucky random jitter
|
||||
// or assuming that RX bytes can wake a physically ended nRF52 Uart driver.
|
||||
static constexpr uint32_t STANDBY_MS = 30000;
|
||||
static constexpr uint32_t SHORT_PROBE_MS = 2000;
|
||||
static constexpr uint32_t LONG_PROBE_MS = 40000;
|
||||
static constexpr uint32_t ACTION_RETRY_MS = 5000;
|
||||
static constexpr uint8_t LONG_PROBE_EVERY = 8;
|
||||
|
||||
inline bool due(uint32_t now, uint32_t deadline) {
|
||||
return static_cast<int32_t>(now - deadline) >= 0;
|
||||
}
|
||||
|
||||
inline uint32_t delayTo(uint32_t now, uint32_t deadline) {
|
||||
return due(now, deadline) ? 0 : static_cast<uint32_t>(deadline - now);
|
||||
}
|
||||
|
||||
inline uint16_t checksum(const uint8_t* bytes, size_t length) {
|
||||
uint16_t a = 0, b = 0;
|
||||
for (size_t i = 0; i < length; ++i) {
|
||||
a = static_cast<uint16_t>((a + bytes[i]) % 255);
|
||||
b = static_cast<uint16_t>((b + a) % 255);
|
||||
}
|
||||
return static_cast<uint16_t>((b << 8) | a);
|
||||
}
|
||||
|
||||
inline void writeHex(uint8_t* out, uint64_t value, size_t digits) {
|
||||
static const char HEX_DIGITS[] = "0123456789ABCDEF";
|
||||
for (size_t i = digits; i != 0; --i) {
|
||||
out[i - 1] = static_cast<uint8_t>(HEX_DIGITS[value & 15]);
|
||||
value >>= 4;
|
||||
}
|
||||
}
|
||||
|
||||
inline bool readHex(const uint8_t* in, size_t digits, uint64_t& value) {
|
||||
value = 0;
|
||||
for (size_t i = 0; i < digits; ++i) {
|
||||
const uint8_t c = in[i];
|
||||
uint8_t nibble;
|
||||
if (c >= '0' && c <= '9') nibble = static_cast<uint8_t>(c - '0');
|
||||
else if (c >= 'A' && c <= 'F') nibble = static_cast<uint8_t>(c - 'A' + 10);
|
||||
else return false;
|
||||
value = (value << 4) | nibble;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
struct Control {
|
||||
uint64_t sender = 0;
|
||||
uint64_t target = 0;
|
||||
uint32_t challenge = 0;
|
||||
char opcode = 0;
|
||||
};
|
||||
|
||||
inline bool encode(uint8_t* body, const Control& control) {
|
||||
if (!body || control.sender == 0 || control.challenge == 0
|
||||
|| (control.opcode != 'P' && control.opcode != 'A')
|
||||
|| (control.opcode == 'P' && control.target != 0)
|
||||
|| (control.opcode == 'A' && control.target == 0)) return false;
|
||||
body[0] = 'H'; body[1] = 'B'; body[2] = '1';
|
||||
body[3] = static_cast<uint8_t>(control.opcode);
|
||||
writeHex(body + 4, control.sender, 16);
|
||||
writeHex(body + 20, control.target, 16);
|
||||
writeHex(body + 36, control.challenge, 8);
|
||||
writeHex(body + CHECKSUM_OFFSET, checksum(body, CHECKSUM_OFFSET), 4);
|
||||
return true;
|
||||
}
|
||||
|
||||
inline bool decode(const uint8_t* body, Control& control) {
|
||||
if (!body || body[0] != 'H' || body[1] != 'B' || body[2] != '1'
|
||||
|| (body[3] != 'P' && body[3] != 'A')) return false;
|
||||
uint64_t sender, target, challenge, crc;
|
||||
if (!readHex(body + 4, 16, sender) || !readHex(body + 20, 16, target)
|
||||
|| !readHex(body + 36, 8, challenge)
|
||||
|| !readHex(body + CHECKSUM_OFFSET, 4, crc)
|
||||
|| crc != checksum(body, CHECKSUM_OFFSET)
|
||||
|| sender == 0 || challenge == 0
|
||||
|| (body[3] == 'P' && target != 0)
|
||||
|| (body[3] == 'A' && target == 0)) return false;
|
||||
control.sender = sender;
|
||||
control.target = target;
|
||||
control.challenge = static_cast<uint32_t>(challenge);
|
||||
control.opcode = static_cast<char>(body[3]);
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace rs232heartbeat
|
||||
|
||||
class RS232PowerPolicy {
|
||||
public:
|
||||
enum class Action : uint8_t { None, Suspend, Resume };
|
||||
|
||||
void notePeer(uint32_t now) {
|
||||
_started = true;
|
||||
_last_peer = now;
|
||||
_has_peer = true;
|
||||
_probing = false;
|
||||
_probe_count = 0;
|
||||
}
|
||||
|
||||
// Invalidating a session must not trust liveness from the previous session.
|
||||
void resetPeer(uint32_t now) {
|
||||
_started = true;
|
||||
_last_peer = now;
|
||||
_has_peer = false;
|
||||
}
|
||||
|
||||
bool standbyDue(bool allowed, uint32_t idle_ms, uint32_t now) const {
|
||||
if (!allowed || _suspended || _requested != Action::None
|
||||
|| _retry_action != Action::None) return false;
|
||||
return _probing ? rs232heartbeat::due(now, _phase_deadline)
|
||||
: _started && static_cast<uint32_t>(now - _last_peer) >= idle_ms;
|
||||
}
|
||||
|
||||
Action service(bool allowed, uint32_t idle_ms, uint32_t now,
|
||||
bool running, bool blocked) {
|
||||
if (!_started) {
|
||||
_started = true;
|
||||
_last_peer = now;
|
||||
}
|
||||
if (_requested != Action::None) return Action::None;
|
||||
if (_retry_action != Action::None) {
|
||||
if (!rs232heartbeat::due(now, _retry_deadline)) return Action::None;
|
||||
_requested = _retry_action;
|
||||
return _requested;
|
||||
}
|
||||
if (!allowed) {
|
||||
_probing = false;
|
||||
if (_suspended || !running) _requested = Action::Resume;
|
||||
} else if (_suspended) {
|
||||
if (rs232heartbeat::due(now, _phase_deadline)) _requested = Action::Resume;
|
||||
} else if (!running) {
|
||||
_requested = Action::Resume;
|
||||
} else if (standbyDue(allowed, idle_ms, now) && !blocked) {
|
||||
_requested = Action::Suspend;
|
||||
}
|
||||
return _requested;
|
||||
}
|
||||
|
||||
void complete(Action action, bool success, uint32_t now) {
|
||||
if (action == Action::None || action != _requested) return;
|
||||
_requested = Action::None;
|
||||
if (!success) {
|
||||
// A failed physical stop can leave GPS ownership pending although UART
|
||||
// is already ended. Finish that same action, never restart prematurely.
|
||||
_retry_action = action;
|
||||
_retry_deadline = now + rs232heartbeat::ACTION_RETRY_MS;
|
||||
return;
|
||||
}
|
||||
_retry_action = Action::None;
|
||||
if (action == Action::Suspend) {
|
||||
_suspended = true;
|
||||
_probing = false;
|
||||
_phase_deadline = now + rs232heartbeat::STANDBY_MS;
|
||||
} else {
|
||||
const bool was_suspended = _suspended;
|
||||
_suspended = false;
|
||||
if (was_suspended) {
|
||||
_probing = true;
|
||||
_probe_count = static_cast<uint8_t>(_probe_count + 1);
|
||||
const uint32_t window = _probe_count % rs232heartbeat::LONG_PROBE_EVERY == 0
|
||||
? rs232heartbeat::LONG_PROBE_MS : rs232heartbeat::SHORT_PROBE_MS;
|
||||
_phase_deadline = now + window;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
uint32_t wakeDelay(uint32_t now) const {
|
||||
if (_requested != Action::None) return 0;
|
||||
if (_retry_action != Action::None) return rs232heartbeat::delayTo(now, _retry_deadline);
|
||||
if (_suspended || _probing) return rs232heartbeat::delayTo(now, _phase_deadline);
|
||||
return UINT32_MAX;
|
||||
}
|
||||
|
||||
bool suspended() const { return _suspended; }
|
||||
bool probing() const { return _probing; }
|
||||
bool hasPeer() const { return _has_peer; }
|
||||
bool retrying() const { return _retry_action != Action::None; }
|
||||
uint32_t peerAge(uint32_t now) const {
|
||||
return _has_peer ? static_cast<uint32_t>(now - _last_peer) : UINT32_MAX;
|
||||
}
|
||||
|
||||
private:
|
||||
uint32_t _last_peer = 0;
|
||||
uint32_t _phase_deadline = 0;
|
||||
uint32_t _retry_deadline = 0;
|
||||
Action _requested = Action::None;
|
||||
Action _retry_action = Action::None;
|
||||
uint8_t _probe_count = 0;
|
||||
bool _started = false;
|
||||
bool _has_peer = false;
|
||||
bool _suspended = false;
|
||||
bool _probing = false;
|
||||
};
|
||||
|
||||
} // namespace bridge
|
||||
} // namespace mesh
|
||||
@@ -0,0 +1,52 @@
|
||||
#pragma once
|
||||
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
#include "RS232Heartbeat.h"
|
||||
|
||||
namespace mesh {
|
||||
namespace bridge {
|
||||
namespace rs232power {
|
||||
|
||||
static constexpr uint16_t DEFAULT_IDLE_SECONDS = 300;
|
||||
static constexpr uint16_t MIN_IDLE_SECONDS = 60;
|
||||
static constexpr uint16_t MAX_IDLE_SECONDS = 3600;
|
||||
static constexpr size_t PREFS_SIZE = 10;
|
||||
|
||||
inline void sanitize(uint8_t& heartbeat, uint8_t& autosleep, uint16_t& idle) {
|
||||
heartbeat = heartbeat == 1 ? 1 : 0;
|
||||
autosleep = autosleep <= 2 ? autosleep : 0;
|
||||
if (idle < MIN_IDLE_SECONDS || idle > MAX_IDLE_SECONDS) idle = DEFAULT_IDLE_SECONDS;
|
||||
}
|
||||
|
||||
// Append-only, checked modes. A missing, torn or foreign tail defaults to
|
||||
// negotiated standby, which never switches off an unconfirmed stock link.
|
||||
inline void encodePrefs(uint8_t* out, uint8_t heartbeat, uint8_t autosleep, uint16_t idle) {
|
||||
out[0] = 'R'; out[1] = 'S'; out[2] = 'P'; out[3] = 1;
|
||||
out[4] = heartbeat == 1 ? 1 : 0;
|
||||
out[5] = autosleep <= 2 ? autosleep : 0;
|
||||
if (idle < MIN_IDLE_SECONDS || idle > MAX_IDLE_SECONDS) idle = DEFAULT_IDLE_SECONDS;
|
||||
out[6] = static_cast<uint8_t>(idle >> 8);
|
||||
out[7] = static_cast<uint8_t>(idle);
|
||||
const uint16_t crc = rs232heartbeat::checksum(out, 8);
|
||||
out[8] = static_cast<uint8_t>(crc >> 8);
|
||||
out[9] = static_cast<uint8_t>(crc);
|
||||
}
|
||||
|
||||
inline bool decodePrefs(const uint8_t* in, size_t size, uint8_t& heartbeat,
|
||||
uint8_t& autosleep, uint16_t& idle) {
|
||||
if (!in || size != PREFS_SIZE || in[0] != 'R' || in[1] != 'S'
|
||||
|| in[2] != 'P' || in[3] != 1 || in[4] > 1 || in[5] > 2) return false;
|
||||
const uint16_t seconds = static_cast<uint16_t>((in[6] << 8) | in[7]);
|
||||
const uint16_t crc = static_cast<uint16_t>((in[8] << 8) | in[9]);
|
||||
if (seconds < MIN_IDLE_SECONDS || seconds > MAX_IDLE_SECONDS
|
||||
|| crc != rs232heartbeat::checksum(in, 8)) return false;
|
||||
heartbeat = in[4];
|
||||
autosleep = in[5];
|
||||
idle = seconds;
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace rs232power
|
||||
} // namespace bridge
|
||||
} // namespace mesh
|
||||
@@ -1,6 +1,8 @@
|
||||
#pragma once
|
||||
|
||||
#include <RadioLib.h>
|
||||
#include <math.h>
|
||||
#include "SX126xMorseRssi.h"
|
||||
|
||||
#ifndef SX126X_TX_BUSY_TIMEOUT_MS
|
||||
#define SX126X_TX_BUSY_TIMEOUT_MS 1000UL
|
||||
@@ -14,6 +16,14 @@ class CustomLLCC68 : public LLCC68 {
|
||||
|
||||
public:
|
||||
CustomLLCC68(Module *mod) : LLCC68(mod) { }
|
||||
int16_t setMorseFastRssi() {
|
||||
return setSX126xMorseRssiWindow(this);
|
||||
}
|
||||
float getMorseRssi() {
|
||||
uint8_t raw = 0;
|
||||
const int16_t status = this->getMod()->SPIreadStream(RADIOLIB_SX126X_CMD_GET_RSSI_INST, &raw, 1);
|
||||
return status == RADIOLIB_ERR_NONE ? raw * -0.5f : NAN;
|
||||
}
|
||||
|
||||
#ifdef RP2040_PLATFORM
|
||||
bool std_init(SPIClassRP2040* spi = NULL)
|
||||
|
||||
@@ -4,6 +4,8 @@
|
||||
#include "CustomLLCC68.h"
|
||||
#include "RadioLibWrappers.h"
|
||||
#include "SX126xReset.h"
|
||||
#include "SX126xMorseRamp.h"
|
||||
#include "SX126xMorseReceiver.h"
|
||||
|
||||
class CustomLLCC68Wrapper : public RadioLibWrapper {
|
||||
protected:
|
||||
@@ -12,10 +14,37 @@ protected:
|
||||
public:
|
||||
~CustomLLCC68Wrapper() { unregisterInterruptAction(); }
|
||||
CustomLLCC68Wrapper(CustomLLCC68& radio, mesh::MainBoard& board) : RadioLibWrapper(radio, board) { }
|
||||
bool supportsMorseTx() const override { return true; }
|
||||
bool supportsMorseRx() const override { return MESH_ENABLE_MORSE_RX && supportsRadioDeepInit(); }
|
||||
|
||||
void powerOff() { _radio->standby(); _radio->sleep(); }
|
||||
void powerOff() {
|
||||
if (isCarrierWaveActive()) setCarrierWave(0, 0);
|
||||
_radio->standby(); _radio->sleep();
|
||||
}
|
||||
|
||||
protected:
|
||||
int16_t prepareMorseReceiver(float frequency_mhz) override {
|
||||
if (!_board->prepareRadioFrequency(frequency_mhz)) return RADIOLIB_ERR_INVALID_FREQUENCY;
|
||||
_morse_rx_fsk_mode = true;
|
||||
if (!prepareRadioHardReset()) return RADIOLIB_ERR_UNKNOWN;
|
||||
const int16_t status = prepareSX126xMorseReceiver(static_cast<CustomLLCC68*>(_radio), frequency_mhz);
|
||||
return status == RADIOLIB_ERR_NONE && !_board->finishRadioHardReset()
|
||||
? RADIOLIB_ERR_UNKNOWN : status;
|
||||
}
|
||||
float readMorseRssi() override { return static_cast<CustomLLCC68*>(_radio)->getMorseRssi(); }
|
||||
float morseReceiverBandwidthKHz() const override { return 4.8f; }
|
||||
int16_t prepareMorseCarrier(float frequency_mhz) override {
|
||||
const int16_t status = RadioLibWrapper::prepareMorseCarrier(frequency_mhz);
|
||||
return status == RADIOLIB_ERR_NONE
|
||||
? setSX126xMorseRamp(static_cast<CustomLLCC68*>(_radio)) : status;
|
||||
}
|
||||
int16_t leaveMorseCarrier() override {
|
||||
return leaveSX126xMorseCarrier(static_cast<CustomLLCC68*>(_radio));
|
||||
}
|
||||
bool restoreCarrierWaveModem() override {
|
||||
return restoreSX126xPacketRamp(static_cast<CustomLLCC68*>(_radio)) == RADIOLIB_ERR_NONE
|
||||
&& RadioLibWrapper::restoreCarrierWaveModem();
|
||||
}
|
||||
bool applyParams(float freq, float bw, uint8_t sf, uint8_t cr) override {
|
||||
bool success = ((CustomLLCC68 *)_radio)->setFrequency(freq) == RADIOLIB_ERR_NONE
|
||||
&& ((CustomLLCC68 *)_radio)->setSpreadingFactor(sf) == RADIOLIB_ERR_NONE
|
||||
@@ -32,6 +61,7 @@ protected:
|
||||
|
||||
public:
|
||||
bool setCodingRate(uint8_t cr) override {
|
||||
if (isCarrierWaveActive()) return false;
|
||||
return ((CustomLLCC68 *)_radio)->setCodingRate(cr) == RADIOLIB_ERR_NONE;
|
||||
}
|
||||
|
||||
|
||||
@@ -5,6 +5,8 @@
|
||||
#include "RXPowerSaving.h"
|
||||
#include "LR1110RxRecovery.h"
|
||||
#include "LR1110ProfileSwitchState.h"
|
||||
#include "LR11x0MorseRfSwitch.h"
|
||||
#include "../MorseRx.h"
|
||||
|
||||
#ifndef MC_LR1110_FAST_PROFILE_SWITCH
|
||||
// All MeshCore LR1110 targets use the checked FS-mode continuous-RX retune.
|
||||
@@ -26,10 +28,41 @@ class CustomLR1110 : public LR1110 {
|
||||
bool _profileStandbyWarm = false;
|
||||
bool _profilePacketDirty = false;
|
||||
uint32_t _profileFastResumes = 0;
|
||||
LR11x0MorseRfSwitch _morse_rf_switch;
|
||||
|
||||
public:
|
||||
CustomLR1110(Module *mod) : LR1110(mod) { }
|
||||
|
||||
void setRfSwitchTable(const uint32_t (&pins)[Module::RFSWITCH_MAX_PINS],
|
||||
const Module::RfSwitchMode_t table[]) {
|
||||
_morse_rf_switch.capture(this->mod, pins, table);
|
||||
LR1110::setRfSwitchTable(pins, table);
|
||||
}
|
||||
|
||||
int16_t beginMorseReceive(float frequency_mhz) {
|
||||
_profileSwitch.invalidate();
|
||||
_profilePacketDirty = false;
|
||||
int16_t status = LR1110::beginGFSK(frequency_mhz,
|
||||
mesh::MorseRx::ReceiverBitRateKbps, 0.6f, 4.8f, 2, 16, tcxoVoltage);
|
||||
if (status == RADIOLIB_ERR_NONE) status = applyMeshCoreTcxoDelay();
|
||||
if (status == RADIOLIB_ERR_NONE) status = setRegulatorDCDC();
|
||||
if (status == RADIOLIB_ERR_NONE) status = _morse_rf_switch.restore(
|
||||
[this](uint8_t enable, const uint8_t* modes) {
|
||||
return setDioAsRfSwitch(enable, modes[0], modes[1], modes[2],
|
||||
modes[3], modes[4], modes[5], modes[6]);
|
||||
});
|
||||
if (status == RADIOLIB_ERR_NONE) status = LR1110::setRxBoostedGainMode(_rx_boosted);
|
||||
if (status == RADIOLIB_ERR_NONE) {
|
||||
// The LR11xx public sync-word setter rejects length zero. Stage the
|
||||
// native no-lock packet tuple and commit it through checked setCRC.
|
||||
syncWordLength = preambleDetLength = 0;
|
||||
status = LR1110::setCRC(0);
|
||||
}
|
||||
// Infinite continuous RX samples envelope power independently of the
|
||||
// FSK packet detector; no direct-data pin or TX/PA activation is used.
|
||||
return status;
|
||||
}
|
||||
|
||||
void setProfileSwitchOptimization(bool enabled) {
|
||||
_profileSwitch.enabled = enabled;
|
||||
_profileSwitch.invalidate();
|
||||
|
||||
@@ -17,10 +17,47 @@ public:
|
||||
CustomLR1110Wrapper(CustomLR1110& radio, mesh::MainBoard& board)
|
||||
: RadioLibWrapper(radio, board), _deep_init(NULL) { }
|
||||
bool supportsCarrierWave() const override { return true; }
|
||||
bool supportsMorseRx() const override { return MESH_ENABLE_MORSE_RX && supportsRadioDeepInit(); }
|
||||
|
||||
void setDeepInitCallback(DeepInitCallback callback) { _deep_init = callback; }
|
||||
|
||||
protected:
|
||||
int16_t startMorseReceiver() override {
|
||||
return static_cast<CustomLR1110*>(_radio)->LR1110::startReceive(
|
||||
RADIOLIB_LR11X0_RX_TIMEOUT_INF, 0, 0, 0);
|
||||
}
|
||||
float readMorseRssi() override {
|
||||
float rssi = NAN;
|
||||
return static_cast<LR11x0*>(_radio)->getRssiInst(&rssi) == RADIOLIB_ERR_NONE ? rssi : NAN;
|
||||
}
|
||||
float morseReceiverBandwidthKHz() const override { return 4.8f; }
|
||||
int16_t prepareMorseReceiver(float frequency_mhz) override {
|
||||
if (!supportsRadioDeepInit()) return RADIOLIB_ERR_UNSUPPORTED;
|
||||
if (!_board->prepareRadioFrequency(frequency_mhz)) return RADIOLIB_ERR_INVALID_FREQUENCY;
|
||||
_morse_rx_fsk_mode = true; // any partial setup must rebuild LoRa on exit
|
||||
if (!prepareRadioHardReset()) return RADIOLIB_ERR_CHIP_NOT_FOUND;
|
||||
const int16_t status = static_cast<CustomLR1110*>(_radio)->beginMorseReceive(frequency_mhz);
|
||||
const bool finished = _board->finishRadioHardReset();
|
||||
return status == RADIOLIB_ERR_NONE && !finished ? RADIOLIB_ERR_UNKNOWN : status;
|
||||
}
|
||||
int16_t prepareMorseCarrier(float frequency_mhz) override {
|
||||
if (!_board->prepareRadioFrequency(frequency_mhz)) return RADIOLIB_ERR_INVALID_FREQUENCY;
|
||||
auto* radio = static_cast<CustomLR1110*>(_radio);
|
||||
const int16_t status = radio->setFrequency(frequency_mhz);
|
||||
// The public power API preserves PA selection/calibration and converts
|
||||
// the 304 us ramp to the LR11xx's offset encoding.
|
||||
return status == RADIOLIB_ERR_NONE
|
||||
? radio->setOutputPower(_dbm_valid ? _cur_dbm : LORA_TX_POWER, false, 304) : status;
|
||||
}
|
||||
bool restoreCarrierWaveModem() override {
|
||||
if (_morse_rx_fsk_mode) {
|
||||
const bool restored = restoreAfterDeepInit();
|
||||
if (restored) _morse_rx_fsk_mode = false;
|
||||
return restored;
|
||||
}
|
||||
return static_cast<CustomLR1110*>(_radio)->setOutputPower(
|
||||
_dbm_valid ? _cur_dbm : LORA_TX_POWER) == RADIOLIB_ERR_NONE;
|
||||
}
|
||||
void beginProfileRetune(bool continuousRx) override {
|
||||
static_cast<CustomLR1110*>(_radio)->beginProfileSwitch(continuousRx);
|
||||
}
|
||||
|
||||
@@ -2,6 +2,8 @@
|
||||
|
||||
#include <RadioLib.h>
|
||||
#include "MeshCore.h"
|
||||
#include "LR11x0MorseRfSwitch.h"
|
||||
#include "../MorseRx.h"
|
||||
|
||||
class CustomLR1121 : public LR1121 {
|
||||
uint32_t _preambleMillis = 66;
|
||||
@@ -9,10 +11,34 @@ class CustomLR1121 : public LR1121 {
|
||||
uint32_t _activityAt = 0;
|
||||
bool _headerSeen = false;
|
||||
bool _rx_boosted = false;
|
||||
LR11x0MorseRfSwitch _morse_rf_switch;
|
||||
|
||||
public:
|
||||
CustomLR1121(Module *mod) : LR1121(mod) { }
|
||||
|
||||
void setRfSwitchTable(const uint32_t (&pins)[Module::RFSWITCH_MAX_PINS],
|
||||
const Module::RfSwitchMode_t table[]) {
|
||||
_morse_rf_switch.capture(this->mod, pins, table);
|
||||
LR1121::setRfSwitchTable(pins, table);
|
||||
}
|
||||
|
||||
int16_t beginMorseReceive(float frequency_mhz) {
|
||||
int16_t status = LR1121::beginGFSK(frequency_mhz,
|
||||
mesh::MorseRx::ReceiverBitRateKbps, 0.6f, 4.8f, 2, 16, tcxoVoltage);
|
||||
if (status == RADIOLIB_ERR_NONE) status = setRegulatorDCDC();
|
||||
if (status == RADIOLIB_ERR_NONE) status = _morse_rf_switch.restore(
|
||||
[this](uint8_t enable, const uint8_t* modes) {
|
||||
return setDioAsRfSwitch(enable, modes[0], modes[1], modes[2],
|
||||
modes[3], modes[4], modes[5], modes[6]);
|
||||
});
|
||||
if (status == RADIOLIB_ERR_NONE) status = LR1121::setRxBoostedGainMode(_rx_boosted);
|
||||
if (status == RADIOLIB_ERR_NONE) {
|
||||
syncWordLength = preambleDetLength = 0;
|
||||
status = LR1121::setCRC(0);
|
||||
}
|
||||
return status;
|
||||
}
|
||||
|
||||
int16_t begin(float freq = 434.0, float bw = 125.0, uint8_t sf = 9, uint8_t cr = 7,
|
||||
uint8_t syncWord = RADIOLIB_LR11X0_LORA_SYNC_WORD_PRIVATE, int8_t power = 10,
|
||||
uint16_t preambleLength = 8, float tcxoVoltage = 1.6) {
|
||||
@@ -102,4 +128,4 @@ class CustomLR1121 : public LR1121 {
|
||||
}
|
||||
|
||||
uint8_t getSpreadingFactor() const { return spreadingFactor; }
|
||||
};
|
||||
};
|
||||
@@ -5,16 +5,58 @@
|
||||
#include "LR11x0Reset.h"
|
||||
|
||||
class CustomLR1121Wrapper : public RadioLibWrapper {
|
||||
using DeepInitCallback = bool (*)();
|
||||
DeepInitCallback _deep_init = nullptr;
|
||||
public:
|
||||
~CustomLR1121Wrapper() { unregisterInterruptAction(); }
|
||||
CustomLR1121Wrapper(CustomLR1121& radio, mesh::MainBoard& board) : RadioLibWrapper(radio, board) { }
|
||||
bool supportsMorseTx() const override { return true; }
|
||||
bool supportsMorseRx() const override { return MESH_ENABLE_MORSE_RX && supportsRadioDeepInit(); }
|
||||
void setDeepInitCallback(DeepInitCallback callback) { _deep_init = callback; }
|
||||
|
||||
void powerOff() {
|
||||
if (isCarrierWaveActive()) setCarrierWave(0, 0);
|
||||
_radio->standby();
|
||||
_radio->sleep();
|
||||
}
|
||||
|
||||
protected:
|
||||
int16_t startMorseReceiver() override {
|
||||
return static_cast<CustomLR1121*>(_radio)->LR1121::startReceive(
|
||||
RADIOLIB_LR11X0_RX_TIMEOUT_INF, 0, 0, 0);
|
||||
}
|
||||
float readMorseRssi() override {
|
||||
float rssi = NAN;
|
||||
return static_cast<LR11x0*>(_radio)->getRssiInst(&rssi) == RADIOLIB_ERR_NONE ? rssi : NAN;
|
||||
}
|
||||
float morseReceiverBandwidthKHz() const override { return 4.8f; }
|
||||
int16_t prepareMorseReceiver(float frequency_mhz) override {
|
||||
if (!supportsRadioDeepInit()) return RADIOLIB_ERR_UNSUPPORTED;
|
||||
if (!_board->prepareRadioFrequency(frequency_mhz)) return RADIOLIB_ERR_INVALID_FREQUENCY;
|
||||
_morse_rx_fsk_mode = true;
|
||||
if (!prepareRadioHardReset()) return RADIOLIB_ERR_CHIP_NOT_FOUND;
|
||||
const int16_t status = static_cast<CustomLR1121*>(_radio)->beginMorseReceive(frequency_mhz);
|
||||
const bool finished = _board->finishRadioHardReset();
|
||||
return status == RADIOLIB_ERR_NONE && !finished ? RADIOLIB_ERR_UNKNOWN : status;
|
||||
}
|
||||
int16_t prepareMorseCarrier(float frequency_mhz) override {
|
||||
if (!_board->prepareRadioFrequency(frequency_mhz)) return RADIOLIB_ERR_INVALID_FREQUENCY;
|
||||
auto* radio = static_cast<CustomLR1121*>(_radio);
|
||||
const int16_t status = radio->setFrequency(frequency_mhz);
|
||||
return status == RADIOLIB_ERR_NONE
|
||||
? radio->setOutputPower(_dbm_valid ? _cur_dbm : LORA_TX_POWER, false, 304) : status;
|
||||
}
|
||||
bool restoreCarrierWaveModem() override {
|
||||
if (_morse_rx_fsk_mode) {
|
||||
const bool restored = restoreAfterDeepInit();
|
||||
if (restored) _morse_rx_fsk_mode = false;
|
||||
return restored;
|
||||
}
|
||||
auto* radio = static_cast<CustomLR1121*>(_radio);
|
||||
if (!_board->prepareRadioFrequency(_cur_freq)
|
||||
|| radio->setFrequency(_cur_freq) != RADIOLIB_ERR_NONE) return false;
|
||||
return radio->setOutputPower(_dbm_valid ? _cur_dbm : LORA_TX_POWER) == RADIOLIB_ERR_NONE;
|
||||
}
|
||||
bool applyParams(float freq, float bw, uint8_t sf, uint8_t cr) override {
|
||||
if (((CustomLR1121 *)_radio)->setFrequency(freq) != RADIOLIB_ERR_NONE
|
||||
|| ((CustomLR1121 *)_radio)->setSpreadingFactor(sf) != RADIOLIB_ERR_NONE
|
||||
@@ -56,6 +98,13 @@ public:
|
||||
uint8_t getSpreadingFactor() const override { return ((CustomLR1121 *)_radio)->getSpreadingFactor(); }
|
||||
|
||||
protected:
|
||||
bool radioDeepInit() override {
|
||||
return _deep_init && prepareRadioHardReset() && _deep_init()
|
||||
&& _board->finishRadioHardReset();
|
||||
}
|
||||
bool supportsRadioDeepInit() const override {
|
||||
return _deep_init && supportsRadioHardResetPath();
|
||||
}
|
||||
bool applyRxBoostedGainMode(bool en) override {
|
||||
return ((CustomLR1121 *)_radio)->setRxBoostedGainMode(en) == RADIOLIB_ERR_NONE;
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
#include <RadioLib.h>
|
||||
#include "MeshCore.h"
|
||||
#include "LR2021Band.h"
|
||||
#include "../MorseRx.h"
|
||||
|
||||
#ifndef LR2021_TX_BUSY_TIMEOUT_MS
|
||||
#define LR2021_TX_BUSY_TIMEOUT_MS 1000UL
|
||||
@@ -17,10 +18,27 @@ class CustomLR2021 : public LR2021 {
|
||||
uint32_t _rf_switch_pins[Module::RFSWITCH_MAX_PINS] = {};
|
||||
const Module::RfSwitchMode_t* _rf_switch_table = nullptr;
|
||||
|
||||
void restoreRfSwitchTable() {
|
||||
if (_rf_switch_table != nullptr) {
|
||||
LR2021::setRfSwitchTable(_rf_switch_pins, _rf_switch_table);
|
||||
int16_t restoreRfSwitchTable() {
|
||||
if (!_rf_switch_table) return RADIOLIB_ERR_NONE;
|
||||
for (size_t i = 0; i < Module::RFSWITCH_MAX_PINS; ++i) {
|
||||
const uint32_t pin = _rf_switch_pins[i];
|
||||
if (pin == RADIOLIB_NC || !(pin & RFSWITCH_PIN_FLAG)) continue;
|
||||
const uint8_t dio = RADIOLIB_LRXXXX_DIOx_VAL(pin);
|
||||
if (dio >= 7) return RADIOLIB_ERR_UNKNOWN;
|
||||
uint8_t config = 0;
|
||||
for (size_t j = 0; j < 8 && _rf_switch_table[j].mode != LR2021::MODE_END_OF_TABLE; ++j) {
|
||||
const uint8_t mode = _rf_switch_table[j].mode;
|
||||
if (mode > 0 && mode <= 8
|
||||
&& _rf_switch_table[j].values[i] == this->mod->hal->GpioLevelHigh)
|
||||
config |= 1UL << (mode - 1);
|
||||
}
|
||||
const uint8_t pull = dio == 0 ? RADIOLIB_LR2021_DIO_SLEEP_PULL_UP
|
||||
: RADIOLIB_LR2021_DIO_SLEEP_PULL_AUTO;
|
||||
int16_t status = setDioFunction(dio + 5, RADIOLIB_LR2021_DIO_FUNCTION_RF_SWITCH, pull);
|
||||
if (status == RADIOLIB_ERR_NONE) status = setDioRfSwitchConfig(dio + 5, config);
|
||||
if (status != RADIOLIB_ERR_NONE) return status;
|
||||
}
|
||||
return RADIOLIB_ERR_NONE;
|
||||
}
|
||||
|
||||
uint8_t rfSwitchRxMode() const {
|
||||
@@ -34,6 +52,24 @@ class CustomLR2021 : public LR2021 {
|
||||
public:
|
||||
CustomLR2021(Module *mod) : LR2021(mod) { irqDioNum = LR2021_IRQ_DIO; }
|
||||
|
||||
int16_t beginMorseReceive(float frequency_mhz) {
|
||||
const uint8_t gain = mesh::lr2021::isHighBand(frequency_mhz) ? gainModeHf : gainModeLf;
|
||||
int16_t status = LR2021::beginGFSK(frequency_mhz,
|
||||
mesh::MorseRx::ReceiverBitRateKbps, 0.6f, 4.8f, 2, 16, tcxoVoltage);
|
||||
if (status == RADIOLIB_ERR_NONE) status = restoreRfSwitchTable();
|
||||
if (status == RADIOLIB_ERR_NONE) status = LR2021::setRxBoostedGainMode(gain);
|
||||
if (status == RADIOLIB_ERR_NONE) {
|
||||
uint8_t unused_sync = 0;
|
||||
status = LR2021::setSyncWord(&unused_sync, 0);
|
||||
}
|
||||
if (status == RADIOLIB_ERR_NONE) {
|
||||
preambleDetLength = 0;
|
||||
status = LR2021::setCRC(0);
|
||||
}
|
||||
// launchMode() retains this chip's band-aware RX RF switch selection.
|
||||
return status;
|
||||
}
|
||||
|
||||
bool std_init(SPIClass* spi = NULL) {
|
||||
#ifdef LR2021_TCXO_VOLTAGE
|
||||
const float tcxo = LR2021_TCXO_VOLTAGE;
|
||||
@@ -81,7 +117,8 @@ class CustomLR2021 : public LR2021 {
|
||||
#endif
|
||||
|
||||
// begin() resets the radio, including its DIO-controlled RF routing.
|
||||
restoreRfSwitchTable();
|
||||
status = restoreRfSwitchTable();
|
||||
if (status != RADIOLIB_ERR_NONE) return false;
|
||||
|
||||
return true; // success
|
||||
}
|
||||
@@ -108,6 +145,13 @@ class CustomLR2021 : public LR2021 {
|
||||
|
||||
float getFreqMHz() const { return freqMHz; }
|
||||
|
||||
int16_t transmitMorseCarrier() {
|
||||
// RadioLib's generic direct-TX path always selects MODE_TX. Use the
|
||||
// band-aware routing also used by our normal packet transmit path.
|
||||
this->mod->setRfSwitchState(rfSwitchTxMode());
|
||||
return this->setTxTestMode(RADIOLIB_LR2021_TX_TEST_MODE_CW);
|
||||
}
|
||||
|
||||
int16_t setRxBoostedGainMode(uint8_t level) {
|
||||
int16_t status = LR2021::setRxBoostedGainMode(level);
|
||||
if (status == RADIOLIB_ERR_NONE) _rx_boosted = level != 0;
|
||||
|
||||
@@ -18,10 +18,61 @@ class CustomLR2021Wrapper : public RadioLibWrapper {
|
||||
public:
|
||||
~CustomLR2021Wrapper() { unregisterInterruptAction(); }
|
||||
CustomLR2021Wrapper(CustomLR2021& radio, mesh::MainBoard& board) : RadioLibWrapper(radio, board) { }
|
||||
bool supportsMorseTx() const override { return true; }
|
||||
bool supportsMorseRx() const override { return MESH_ENABLE_MORSE_RX && supportsRadioDeepInit(); }
|
||||
|
||||
void powerOff() { _radio->standby(); _radio->sleep(); }
|
||||
void powerOff() {
|
||||
if (isCarrierWaveActive()) setCarrierWave(0, 0);
|
||||
_radio->standby(); _radio->sleep();
|
||||
}
|
||||
|
||||
protected:
|
||||
int16_t startMorseReceiver() override {
|
||||
return static_cast<CustomLR2021*>(_radio)->LR2021::startReceive(
|
||||
RADIOLIB_LR2021_RX_TIMEOUT_INF, 0, 0, 0);
|
||||
}
|
||||
float readMorseRssi() override {
|
||||
float rssi = NAN;
|
||||
return static_cast<LR2021*>(_radio)->getRssiInst(&rssi) == RADIOLIB_ERR_NONE ? rssi : NAN;
|
||||
}
|
||||
float morseReceiverBandwidthKHz() const override { return 4.8f; }
|
||||
int16_t prepareMorseReceiver(float frequency_mhz) override {
|
||||
if (!supportsRadioDeepInit()) return RADIOLIB_ERR_UNSUPPORTED;
|
||||
if (!_board->prepareRadioFrequency(frequency_mhz)) return RADIOLIB_ERR_INVALID_FREQUENCY;
|
||||
_morse_rx_fsk_mode = true;
|
||||
if (!prepareRadioHardReset()) return RADIOLIB_ERR_CHIP_NOT_FOUND;
|
||||
const int16_t status = static_cast<CustomLR2021*>(_radio)->beginMorseReceive(frequency_mhz);
|
||||
const bool finished = _board->finishRadioHardReset();
|
||||
return status == RADIOLIB_ERR_NONE && !finished ? RADIOLIB_ERR_UNKNOWN : status;
|
||||
}
|
||||
bool validateMorseFrequency(float frequency_mhz) const override {
|
||||
return (frequency_mhz >= 150.0f && frequency_mhz <= 1090.0f)
|
||||
|| (frequency_mhz >= 1900.0f && frequency_mhz <= 2500.0f);
|
||||
}
|
||||
int16_t prepareMorseCarrier(float frequency_mhz) override {
|
||||
if (!_board->prepareRadioFrequency(frequency_mhz)) return RADIOLIB_ERR_INVALID_FREQUENCY;
|
||||
auto* radio = static_cast<CustomLR2021*>(_radio);
|
||||
const int16_t status = radio->setFrequency(frequency_mhz);
|
||||
// Re-evaluate the PA and board power limit at the Morse frequency, not
|
||||
// at the cached packet profile, when crossing LF/HF bands.
|
||||
return status == RADIOLIB_ERR_NONE ? radio->setOutputPower(
|
||||
mesh::clampLoRaTxPower(_dbm_valid ? _cur_dbm : LORA_TX_POWER, frequency_mhz), 304) : status;
|
||||
}
|
||||
int16_t enterMorseCarrier() override {
|
||||
return static_cast<CustomLR2021*>(_radio)->transmitMorseCarrier();
|
||||
}
|
||||
bool restoreCarrierWaveModem() override {
|
||||
if (_morse_rx_fsk_mode) {
|
||||
const bool restored = restoreAfterDeepInit();
|
||||
if (restored) _morse_rx_fsk_mode = false;
|
||||
return restored;
|
||||
}
|
||||
auto* radio = static_cast<CustomLR2021*>(_radio);
|
||||
if (!_board->prepareRadioFrequency(_cur_freq)
|
||||
|| radio->setFrequency(_cur_freq) != RADIOLIB_ERR_NONE) return false;
|
||||
return radio->setOutputPower(mesh::clampLoRaTxPower(
|
||||
_dbm_valid ? _cur_dbm : LORA_TX_POWER, _cur_freq)) == RADIOLIB_ERR_NONE;
|
||||
}
|
||||
bool applyParams(float freq, float bw, uint8_t sf, uint8_t cr) override {
|
||||
CustomLR2021* radio = (CustomLR2021 *)_radio;
|
||||
if (!_board->prepareRadioFrequency(freq)) return false;
|
||||
@@ -53,6 +104,7 @@ protected:
|
||||
|
||||
public:
|
||||
bool setCodingRate(uint8_t cr) override {
|
||||
if (isCarrierWaveActive()) return false;
|
||||
return ((CustomLR2021 *)_radio)->setCodingRate(cr) == RADIOLIB_ERR_NONE;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
#pragma once
|
||||
|
||||
#include <RadioLib.h>
|
||||
#include <math.h>
|
||||
#include "SX126xMorseRssi.h"
|
||||
|
||||
class CustomSTM32WLx : public STM32WLx {
|
||||
uint32_t _preambleMillis = 66;
|
||||
@@ -10,6 +12,14 @@ class CustomSTM32WLx : public STM32WLx {
|
||||
|
||||
public:
|
||||
CustomSTM32WLx(STM32WLx_Module *mod) : STM32WLx(mod) { }
|
||||
int16_t setMorseFastRssi() {
|
||||
return setSX126xMorseRssiWindow(this);
|
||||
}
|
||||
float getMorseRssi() {
|
||||
uint8_t raw = 0;
|
||||
const int16_t status = this->getMod()->SPIreadStream(RADIOLIB_SX126X_CMD_GET_RSSI_INST, &raw, 1);
|
||||
return status == RADIOLIB_ERR_NONE ? raw * -0.5f : NAN;
|
||||
}
|
||||
|
||||
int16_t startReceive() override {
|
||||
// include the PREAMBLE_DETECTED irq bit in reported flags
|
||||
@@ -68,4 +78,4 @@ class CustomSTM32WLx : public STM32WLx {
|
||||
MESH_DEBUG_PRINTLN("Set _maxPayloadMillis=%u", _maxPayloadMillis);
|
||||
}
|
||||
|
||||
};
|
||||
};
|
||||
@@ -4,17 +4,63 @@
|
||||
#include "CustomSTM32WLx.h"
|
||||
#include "RadioLibWrappers.h"
|
||||
#include "SX126xReset.h"
|
||||
#include "SX126xMorseRamp.h"
|
||||
#include "SX126xMorseReceiver.h"
|
||||
#include <math.h>
|
||||
|
||||
class CustomSTM32WLxWrapper : public RadioLibWrapper {
|
||||
using DeepInitCallback = bool (*)();
|
||||
DeepInitCallback _deep_init = nullptr;
|
||||
protected:
|
||||
int8_t readReceiveMode() override { return sx126xReceiveMode((SX126x*)_radio); }
|
||||
|
||||
public:
|
||||
~CustomSTM32WLxWrapper() { unregisterInterruptAction(); }
|
||||
CustomSTM32WLxWrapper(CustomSTM32WLx& radio, mesh::MainBoard& board) : RadioLibWrapper(radio, board) { }
|
||||
bool supportsMorseTx() const override { return true; }
|
||||
#if MESH_ENABLE_MORSE_RX
|
||||
bool supportsMorseRx() const override { return supportsRadioDeepInit(); }
|
||||
#endif
|
||||
void setDeepInitCallback(DeepInitCallback callback) { _deep_init = callback; }
|
||||
|
||||
protected:
|
||||
#if MESH_ENABLE_MORSE_RX
|
||||
float morseReceiverBandwidthKHz() const override { return 4.8f; }
|
||||
int16_t prepareMorseReceiver(float frequency_mhz) override {
|
||||
if (!supportsRadioDeepInit()) return RADIOLIB_ERR_UNSUPPORTED;
|
||||
if (!_board->prepareRadioFrequency(frequency_mhz)) return RADIOLIB_ERR_INVALID_FREQUENCY;
|
||||
_morse_rx_fsk_mode = true;
|
||||
return prepareSX126xMorseReceiver(static_cast<CustomSTM32WLx*>(_radio), frequency_mhz);
|
||||
}
|
||||
#endif
|
||||
bool radioDeepInit() override {
|
||||
// STM32WLx begin() owns the integrated radio reset. Reuse target.cpp's
|
||||
// complete RF switch/TCXO setup rather than pretending there is an NRST.
|
||||
return _deep_init && _deep_init();
|
||||
}
|
||||
bool supportsRadioDeepInit() const override { return _deep_init != nullptr; }
|
||||
#if MESH_ENABLE_MORSE_RX
|
||||
float readMorseRssi() override { return static_cast<CustomSTM32WLx*>(_radio)->getMorseRssi(); }
|
||||
#endif
|
||||
int16_t prepareMorseCarrier(float frequency_mhz) override {
|
||||
const int16_t status = RadioLibWrapper::prepareMorseCarrier(frequency_mhz);
|
||||
return status == RADIOLIB_ERR_NONE
|
||||
? setSX126xMorseRamp(static_cast<CustomSTM32WLx*>(_radio)) : status;
|
||||
}
|
||||
int16_t leaveMorseCarrier() override {
|
||||
return leaveSX126xMorseCarrier(static_cast<CustomSTM32WLx*>(_radio));
|
||||
}
|
||||
bool restoreCarrierWaveModem() override {
|
||||
#if MESH_ENABLE_MORSE_RX
|
||||
if (_morse_rx_fsk_mode) {
|
||||
const bool restored = restoreAfterDeepInit();
|
||||
if (restored) _morse_rx_fsk_mode = false;
|
||||
return restored;
|
||||
}
|
||||
#endif
|
||||
return restoreSX126xPacketRamp(static_cast<CustomSTM32WLx*>(_radio)) == RADIOLIB_ERR_NONE
|
||||
&& RadioLibWrapper::restoreCarrierWaveModem();
|
||||
}
|
||||
bool applyParams(float freq, float bw, uint8_t sf, uint8_t cr) override {
|
||||
return ((CustomSTM32WLx *)_radio)->setFrequency(freq) == RADIOLIB_ERR_NONE
|
||||
&& ((CustomSTM32WLx *)_radio)->setSpreadingFactor(sf) == RADIOLIB_ERR_NONE
|
||||
@@ -25,6 +71,7 @@ protected:
|
||||
|
||||
public:
|
||||
bool setCodingRate(uint8_t cr) override {
|
||||
if (isCarrierWaveActive()) return false;
|
||||
return ((CustomSTM32WLx *)_radio)->setCodingRate(cr) == RADIOLIB_ERR_NONE;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
#pragma once
|
||||
|
||||
#include <RadioLib.h>
|
||||
#include <math.h>
|
||||
#include "MeshCore.h"
|
||||
#include "RXPowerSaving.h"
|
||||
#include "SX1262ProfileSwitchState.h"
|
||||
#include "SX126xMorseRssi.h"
|
||||
|
||||
#ifndef MC_SX1262_FAST_PROFILE_SWITCH
|
||||
// CustomSX1262 targets use direct radio I/O unless a board opts out. Keep
|
||||
@@ -42,6 +44,19 @@ class CustomSX1262 : public SX1262 {
|
||||
|
||||
public:
|
||||
CustomSX1262(Module *mod) : SX1262(mod) { }
|
||||
void invalidateMorseModemCache() {
|
||||
_profileSwitch.invalidate();
|
||||
_coldStandby = true;
|
||||
_tcxoWakePending = false;
|
||||
}
|
||||
int16_t setMorseFastRssi() {
|
||||
return setSX126xMorseRssiWindow(this);
|
||||
}
|
||||
float getMorseRssi() {
|
||||
uint8_t raw = 0;
|
||||
const int16_t status = this->getMod()->SPIreadStream(RADIOLIB_SX126X_CMD_GET_RSSI_INST, &raw, 1);
|
||||
return status == RADIOLIB_ERR_NONE ? raw * -0.5f : NAN;
|
||||
}
|
||||
|
||||
void setProfileSwitchOptimization(bool enabled) {
|
||||
_profileSwitch.enabled = enabled;
|
||||
|
||||
@@ -4,6 +4,8 @@
|
||||
#include "CustomSX1262.h"
|
||||
#include "RadioLibWrappers.h"
|
||||
#include "SX126xReset.h"
|
||||
#include "SX126xMorseRamp.h"
|
||||
#include "SX126xMorseReceiver.h"
|
||||
|
||||
#ifndef USE_SX1262
|
||||
#define USE_SX1262
|
||||
@@ -38,11 +40,36 @@ public:
|
||||
~CustomSX1262Wrapper() { unregisterInterruptAction(); }
|
||||
CustomSX1262Wrapper(CustomSX1262& radio, mesh::MainBoard& board) : RadioLibWrapper(radio, board) { }
|
||||
bool supportsCarrierWave() const override { return true; }
|
||||
bool supportsMorseRx() const override { return MESH_ENABLE_MORSE_RX && supportsRadioDeepInit(); }
|
||||
#if MESH_ENABLE_MESHTEXT_CHAT
|
||||
bool supportsMeshtext() const override { return true; }
|
||||
#endif
|
||||
|
||||
protected:
|
||||
float morseReceiverBandwidthKHz() const override { return 4.8f; }
|
||||
int16_t prepareMorseReceiver(float frequency_mhz) override {
|
||||
if (!_board->prepareRadioFrequency(frequency_mhz)) return RADIOLIB_ERR_INVALID_FREQUENCY;
|
||||
_morse_rx_fsk_mode = true; // partial reset/configuration also needs full restoration
|
||||
if (!prepareRadioHardReset()) return RADIOLIB_ERR_UNKNOWN;
|
||||
auto* radio = static_cast<CustomSX1262*>(_radio);
|
||||
radio->invalidateMorseModemCache();
|
||||
const int16_t status = prepareSX126xMorseReceiver(radio, frequency_mhz);
|
||||
return status == RADIOLIB_ERR_NONE && !_board->finishRadioHardReset()
|
||||
? RADIOLIB_ERR_UNKNOWN : status;
|
||||
}
|
||||
float readMorseRssi() override { return static_cast<CustomSX1262*>(_radio)->getMorseRssi(); }
|
||||
int16_t prepareMorseCarrier(float frequency_mhz) override {
|
||||
const int16_t status = RadioLibWrapper::prepareMorseCarrier(frequency_mhz);
|
||||
return status == RADIOLIB_ERR_NONE
|
||||
? setSX126xMorseRamp(static_cast<CustomSX1262*>(_radio)) : status;
|
||||
}
|
||||
int16_t leaveMorseCarrier() override {
|
||||
return leaveSX126xMorseCarrier(static_cast<CustomSX1262*>(_radio));
|
||||
}
|
||||
bool restoreCarrierWaveModem() override {
|
||||
return restoreSX126xPacketRamp(static_cast<CustomSX1262*>(_radio)) == RADIOLIB_ERR_NONE
|
||||
&& RadioLibWrapper::restoreCarrierWaveModem();
|
||||
}
|
||||
#if MESH_ENABLE_MESHTEXT_CHAT
|
||||
bool applyProtocol(mesh::RadioProfileProtocol protocol) override {
|
||||
auto* radio = static_cast<CustomSX1262*>(_radio);
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
#pragma once
|
||||
|
||||
#include <RadioLib.h>
|
||||
#include <math.h>
|
||||
#include "SX126xMorseRssi.h"
|
||||
|
||||
#ifndef SX126X_TX_BUSY_TIMEOUT_MS
|
||||
#define SX126X_TX_BUSY_TIMEOUT_MS 1000UL
|
||||
@@ -14,6 +16,14 @@ class CustomSX1268 : public SX1268 {
|
||||
|
||||
public:
|
||||
CustomSX1268(Module *mod) : SX1268(mod) { }
|
||||
int16_t setMorseFastRssi() {
|
||||
return setSX126xMorseRssiWindow(this);
|
||||
}
|
||||
float getMorseRssi() {
|
||||
uint8_t raw = 0;
|
||||
const int16_t status = this->getMod()->SPIreadStream(RADIOLIB_SX126X_CMD_GET_RSSI_INST, &raw, 1);
|
||||
return status == RADIOLIB_ERR_NONE ? raw * -0.5f : NAN;
|
||||
}
|
||||
|
||||
#ifdef RP2040_PLATFORM
|
||||
bool std_init(SPIClassRP2040* spi = NULL)
|
||||
|
||||
@@ -4,6 +4,8 @@
|
||||
#include "CustomSX1268.h"
|
||||
#include "RadioLibWrappers.h"
|
||||
#include "SX126xReset.h"
|
||||
#include "SX126xMorseRamp.h"
|
||||
#include "SX126xMorseReceiver.h"
|
||||
|
||||
#ifndef USE_SX1268
|
||||
#define USE_SX1268
|
||||
@@ -16,10 +18,40 @@ protected:
|
||||
public:
|
||||
~CustomSX1268Wrapper() { unregisterInterruptAction(); }
|
||||
CustomSX1268Wrapper(CustomSX1268& radio, mesh::MainBoard& board) : RadioLibWrapper(radio, board) { }
|
||||
bool supportsMorseTx() const override { return true; }
|
||||
bool supportsMorseRx() const override { return MESH_ENABLE_MORSE_RX && supportsRadioDeepInit(); }
|
||||
|
||||
void powerOff() { _radio->standby(); _radio->sleep(); }
|
||||
void powerOff() {
|
||||
if (isCarrierWaveActive()) setCarrierWave(0, 0);
|
||||
_radio->standby(); _radio->sleep();
|
||||
}
|
||||
|
||||
protected:
|
||||
float morseReceiverBandwidthKHz() const override { return 4.8f; }
|
||||
int16_t prepareMorseReceiver(float frequency_mhz) override {
|
||||
if (!_board->prepareRadioFrequency(frequency_mhz)) return RADIOLIB_ERR_INVALID_FREQUENCY;
|
||||
_morse_rx_fsk_mode = true;
|
||||
if (!prepareRadioHardReset()) return RADIOLIB_ERR_UNKNOWN;
|
||||
const int16_t status = prepareSX126xMorseReceiver(static_cast<CustomSX1268*>(_radio), frequency_mhz);
|
||||
return status == RADIOLIB_ERR_NONE && !_board->finishRadioHardReset()
|
||||
? RADIOLIB_ERR_UNKNOWN : status;
|
||||
}
|
||||
float readMorseRssi() override { return static_cast<CustomSX1268*>(_radio)->getMorseRssi(); }
|
||||
bool validateMorseFrequency(float frequency_mhz) const override {
|
||||
return frequency_mhz >= 410.0f && frequency_mhz <= 810.0f;
|
||||
}
|
||||
int16_t prepareMorseCarrier(float frequency_mhz) override {
|
||||
const int16_t status = RadioLibWrapper::prepareMorseCarrier(frequency_mhz);
|
||||
return status == RADIOLIB_ERR_NONE
|
||||
? setSX126xMorseRamp(static_cast<CustomSX1268*>(_radio)) : status;
|
||||
}
|
||||
int16_t leaveMorseCarrier() override {
|
||||
return leaveSX126xMorseCarrier(static_cast<CustomSX1268*>(_radio));
|
||||
}
|
||||
bool restoreCarrierWaveModem() override {
|
||||
return restoreSX126xPacketRamp(static_cast<CustomSX1268*>(_radio)) == RADIOLIB_ERR_NONE
|
||||
&& RadioLibWrapper::restoreCarrierWaveModem();
|
||||
}
|
||||
bool applyParams(float freq, float bw, uint8_t sf, uint8_t cr) override {
|
||||
bool success = ((CustomSX1268 *)_radio)->setFrequency(freq) == RADIOLIB_ERR_NONE
|
||||
&& ((CustomSX1268 *)_radio)->setSpreadingFactor(sf) == RADIOLIB_ERR_NONE
|
||||
@@ -36,6 +68,7 @@ protected:
|
||||
|
||||
public:
|
||||
bool setCodingRate(uint8_t cr) override {
|
||||
if (isCarrierWaveActive()) return false;
|
||||
return ((CustomSX1268 *)_radio)->setCodingRate(cr) == RADIOLIB_ERR_NONE;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
#pragma once
|
||||
|
||||
#include <RadioLib.h>
|
||||
#include <math.h>
|
||||
#include "MeshCore.h"
|
||||
#include "../MorseRx.h"
|
||||
|
||||
#define RH_RF95_MODEM_STATUS_CLEAR 0x10
|
||||
#define RH_RF95_MODEM_STATUS_HEADER_INFO_VALID 0x08
|
||||
@@ -13,6 +15,36 @@ class CustomSX1276 : public SX1276 {
|
||||
public:
|
||||
CustomSX1276(Module *mod) : SX1276(mod) { }
|
||||
|
||||
int16_t beginMorseReceive(float frequency_mhz) {
|
||||
int16_t status = SX1276::beginFSK(frequency_mhz,
|
||||
mesh::MorseRx::ReceiverBitRateKbps, 0.6f, 2.6f, 2, 16, false);
|
||||
#ifdef SX127X_CURRENT_LIMIT
|
||||
if (status == RADIOLIB_ERR_NONE) status = setCurrentLimit(SX127X_CURRENT_LIMIT);
|
||||
#endif
|
||||
// The API argument is the register encoding: zero means two samples,
|
||||
// not zero samples. Continuous direct RX has no preamble/sync gating.
|
||||
if (status == RADIOLIB_ERR_NONE) status = setRSSIConfig(0);
|
||||
return status;
|
||||
}
|
||||
|
||||
float getMorseRssi() {
|
||||
// SX127x has no SPI command-status byte. Check modem and chip identity
|
||||
// instead of interpreting an absent/wrong-modem read as valid power.
|
||||
const uint8_t version = getChipVersion();
|
||||
if (getActiveModem() != RADIOLIB_SX127X_FSK_OOK
|
||||
|| (version != RADIOLIB_SX1278_CHIP_VERSION
|
||||
&& version != RADIOLIB_SX1278_CHIP_VERSION_ALT
|
||||
&& version != RADIOLIB_SX1278_CHIP_VERSION_RFM9X)) return NAN;
|
||||
const int16_t raw = this->mod->SPIgetRegValue(RADIOLIB_SX127X_REG_RSSI_VALUE_FSK);
|
||||
return raw < 0 ? NAN : raw * -0.5f;
|
||||
}
|
||||
|
||||
int16_t setMorsePaRamp() {
|
||||
// Slowest supported PA envelope (3400 us), to soften CW keying edges.
|
||||
// std_init() restores RadioLib's normal packet ramp after Morse.
|
||||
return this->mod->SPIsetRegValue(RADIOLIB_SX127X_REG_PA_RAMP, 0, 3, 0);
|
||||
}
|
||||
|
||||
#ifdef RP2040_PLATFORM
|
||||
bool std_init(SPIClassRP2040* spi = NULL)
|
||||
#else
|
||||
|
||||
@@ -12,6 +12,7 @@ public:
|
||||
~CustomSX1276Wrapper() { unregisterInterruptAction(); }
|
||||
CustomSX1276Wrapper(CustomSX1276& radio, mesh::MainBoard& board) : RadioLibWrapper(radio, board) { }
|
||||
bool supportsCarrierWave() const override { return supportsRadioDeepInit(); }
|
||||
bool supportsMorseRx() const override { return MESH_ENABLE_MORSE_RX && supportsRadioDeepInit(); }
|
||||
|
||||
void powerOff() {
|
||||
if (isCarrierWaveActive()) setCarrierWave(0, 0);
|
||||
@@ -19,6 +20,9 @@ public:
|
||||
}
|
||||
|
||||
protected:
|
||||
int16_t startMorseReceiver() override {
|
||||
return static_cast<CustomSX1276*>(_radio)->receiveDirect();
|
||||
}
|
||||
bool applyParams(float freq, float bw, uint8_t sf, uint8_t cr) override {
|
||||
return ((CustomSX1276 *)_radio)->setFrequency(freq) == RADIOLIB_ERR_NONE
|
||||
&& ((CustomSX1276 *)_radio)->setSpreadingFactor(sf) == RADIOLIB_ERR_NONE
|
||||
@@ -46,6 +50,38 @@ public:
|
||||
uint8_t getSpreadingFactor() const override { return ((CustomSX1276 *)_radio)->spreadingFactor; }
|
||||
|
||||
protected:
|
||||
float morseReceiverBandwidthKHz() const override { return 2.6f; }
|
||||
float readMorseRssi() override { return static_cast<CustomSX1276*>(_radio)->getMorseRssi(); }
|
||||
int16_t prepareMorseReceiver(float frequency_mhz) override {
|
||||
if (!supportsRadioDeepInit()) return RADIOLIB_ERR_UNSUPPORTED;
|
||||
if (!_board->prepareRadioFrequency(frequency_mhz)) return RADIOLIB_ERR_INVALID_FREQUENCY;
|
||||
_morse_rx_fsk_mode = true;
|
||||
if (!prepareRadioHardReset()) return RADIOLIB_ERR_CHIP_NOT_FOUND;
|
||||
const int16_t status = static_cast<CustomSX1276*>(_radio)->beginMorseReceive(frequency_mhz);
|
||||
const bool finished = _board->finishRadioHardReset();
|
||||
return status == RADIOLIB_ERR_NONE && !finished ? RADIOLIB_ERR_UNKNOWN : status;
|
||||
}
|
||||
bool validateMorseFrequency(float frequency_mhz) const override {
|
||||
return isfinite(frequency_mhz) && frequency_mhz >= 137.0f && frequency_mhz <= 1020.0f;
|
||||
}
|
||||
|
||||
int16_t prepareMorseCarrier(float frequency_mhz) override {
|
||||
if (!_board->prepareRadioFrequency(frequency_mhz)) return RADIOLIB_ERR_INVALID_FREQUENCY;
|
||||
auto* radio = static_cast<CustomSX1276*>(_radio);
|
||||
// Zero deviation produces an unmodulated carrier regardless of DIO2.
|
||||
// RX bandwidth is immaterial for this TX-only operation. FSK is set up
|
||||
// once per message, never once per dot/dash.
|
||||
int16_t status = radio->beginFSK(frequency_mhz, 4.8, 0.0, 125.0, 2, 16, false);
|
||||
if (status != RADIOLIB_ERR_NONE) return status;
|
||||
status = radio->setMorsePaRamp();
|
||||
if (status != RADIOLIB_ERR_NONE) return status;
|
||||
#ifdef SX127X_CURRENT_LIMIT
|
||||
status = radio->setCurrentLimit(SX127X_CURRENT_LIMIT);
|
||||
if (status != RADIOLIB_ERR_NONE) return status;
|
||||
#endif
|
||||
return applyCachedTxPower(_dbm_valid ? _cur_dbm : LORA_TX_POWER);
|
||||
}
|
||||
|
||||
int16_t enterCarrierWave() override {
|
||||
auto* radio = static_cast<CustomSX1276*>(_radio);
|
||||
// Direct TX needs FSK. Zero deviation prevents a floating DIO2 data input
|
||||
@@ -65,7 +101,9 @@ protected:
|
||||
bool restoreCarrierWaveModem() override {
|
||||
// Restores LoRa, runtime profile/preamble, IRQ mapping and PA calibration.
|
||||
// Shared cleanup retains the stop/retry guard if any restoration fails.
|
||||
return restoreAfterDeepInit();
|
||||
const bool restored = restoreAfterDeepInit();
|
||||
if (restored) _morse_rx_fsk_mode = false;
|
||||
return restored;
|
||||
}
|
||||
|
||||
int16_t performChannelScan() override {
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
#pragma once
|
||||
|
||||
#include <RadioLib.h>
|
||||
|
||||
// Native beginGFSK resets the LR11xx's DIO switch registers. Cache the same
|
||||
// seven mode masks used by RadioLib, then restore them with a checked command
|
||||
// before entering RX (its public setRfSwitchTable otherwise discards errors).
|
||||
class LR11x0MorseRfSwitch {
|
||||
uint8_t enable_ = 0;
|
||||
uint8_t modes_[7] = {};
|
||||
bool configured_ = false;
|
||||
public:
|
||||
void capture(Module* module,
|
||||
const uint32_t (&pins)[Module::RFSWITCH_MAX_PINS],
|
||||
const Module::RfSwitchMode_t table[]) {
|
||||
enable_ = 0;
|
||||
for (auto& mode : modes_) mode = 0;
|
||||
configured_ = table != nullptr;
|
||||
if (!configured_) return;
|
||||
for (size_t i = 0; i < Module::RFSWITCH_MAX_PINS; ++i) {
|
||||
if (pins[i] == RADIOLIB_NC || !(pins[i] & RFSWITCH_PIN_FLAG)) continue;
|
||||
enable_ |= 1UL << RADIOLIB_LRXXXX_DIOx_VAL(pins[i]);
|
||||
}
|
||||
for (size_t i = 0; i < 7 && table[i].mode != LR11x0::MODE_END_OF_TABLE; ++i) {
|
||||
const uint8_t index = table[i].mode - LR11x0::MODE_STBY;
|
||||
if (index >= 7) continue;
|
||||
for (size_t j = 0; j < Module::RFSWITCH_MAX_PINS; ++j) {
|
||||
if (pins[j] == RADIOLIB_NC || !(pins[j] & RFSWITCH_PIN_FLAG)) continue;
|
||||
if (table[i].values[j] == module->hal->GpioLevelHigh) modes_[index] |= 1UL << j;
|
||||
}
|
||||
}
|
||||
}
|
||||
template <typename Apply>
|
||||
int16_t restore(Apply apply) const {
|
||||
return !configured_ ? RADIOLIB_ERR_NONE : apply(enable_, modes_);
|
||||
}
|
||||
};
|
||||
@@ -2,6 +2,15 @@
|
||||
#define RADIOLIB_STATIC_ONLY 1
|
||||
#include "RadioLibWrappers.h"
|
||||
#include "RadioInterruptEvents.h"
|
||||
#include <new>
|
||||
#if defined(ESP32_PLATFORM)
|
||||
#include <esp_heap_caps.h>
|
||||
#elif defined(NRF52_PLATFORM)
|
||||
#include <utility/debug.h>
|
||||
#elif defined(STM32_PLATFORM)
|
||||
#include <sys/types.h>
|
||||
extern "C" caddr_t _sbrk(int increment);
|
||||
#endif
|
||||
|
||||
#define STATE_IDLE 0
|
||||
#define STATE_RX 1
|
||||
@@ -223,6 +232,10 @@ uint32_t RadioLibWrapper::getRngSeed() {
|
||||
}
|
||||
|
||||
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 (_cw_active) {
|
||||
if (_cw_stopping) return false;
|
||||
// Permit meter sweeps through the board's normal power/PA calibration.
|
||||
@@ -992,18 +1005,23 @@ void RadioLibWrapper::checkReceiveMode(uint32_t now) {
|
||||
|
||||
uint32_t RadioLibWrapper::carrierWaveRemainingMillis() const {
|
||||
if (!_cw_active || _cw_stopping) return 0;
|
||||
if (_morse_owned) return morseTxRemainingMillis();
|
||||
if (_morse_rx_owned) return morseRxRemainingMillis();
|
||||
const int32_t remaining = static_cast<int32_t>(_cw_until - millis());
|
||||
return remaining > 0 ? static_cast<uint32_t>(remaining) : 0;
|
||||
}
|
||||
|
||||
mesh::RadioParamApplyResult RadioLibWrapper::setCarrierWave(uint8_t profile, uint32_t duration_ms) {
|
||||
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 (!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 (_cw_stopping || profile != _cw_profile
|
||||
if (_morse_owned || _morse_rx_owned || _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;
|
||||
@@ -1028,6 +1046,7 @@ mesh::RadioParamApplyResult RadioLibWrapper::setCarrierWave(uint8_t profile, uin
|
||||
_wd_observe_until = 0;
|
||||
_cw_profile = profile;
|
||||
_cw_generation = _profiles.generation[profile];
|
||||
_morse_owned = false;
|
||||
_cw_active = true;
|
||||
_cw_stopping = false;
|
||||
_board->setRadioTestActive(true); // service the deadline even without USB
|
||||
@@ -1041,14 +1060,321 @@ mesh::RadioParamApplyResult RadioLibWrapper::setCarrierWave(uint8_t profile, uin
|
||||
return Result::APPLIED;
|
||||
}
|
||||
|
||||
bool RadioLibWrapper::supportsMorseTx() const {
|
||||
return supportsCarrierWave();
|
||||
}
|
||||
|
||||
mesh::MorseTxResult RadioLibWrapper::startMorseTx(float frequency_mhz,
|
||||
uint8_t wpm, const char* text) {
|
||||
using Result = mesh::MorseTxResult;
|
||||
if (!supportsMorseTx()) return Result::Unsupported;
|
||||
if (_cw_active) return Result::Busy;
|
||||
const Result valid_text = mesh::MorseTx::validate(text, wpm);
|
||||
if (valid_text != Result::Started) return valid_text;
|
||||
if (!_params_valid || !isfinite(frequency_mhz)) return Result::InvalidFrequency;
|
||||
// Only the carrier frequency matters here: existing LoRa SF/BW/protocol
|
||||
// constraints must not accidentally limit an unmodulated transmission.
|
||||
if (!validateMorseFrequency(frequency_mhz)) return Result::InvalidFrequency;
|
||||
for (uint8_t profile = 0; profile < 2; ++profile) {
|
||||
const auto& p = _profiles.params(profile);
|
||||
if (mesh::morseFrequencyOverlaps(frequency_mhz, p.freq, p.bw)) return Result::Overlap;
|
||||
}
|
||||
const uint8_t resume = beginReconfigure();
|
||||
if (resume > 1) return Result::Busy;
|
||||
_cw_restore_profile = _active_profile;
|
||||
if (_radio->standby() != RADIOLIB_ERR_NONE
|
||||
|| _radio->clearIrqFlags(UINT32_MAX) != RADIOLIB_ERR_NONE) {
|
||||
endReconfigure(resume);
|
||||
return Result::Failed;
|
||||
}
|
||||
|
||||
// Publish ownership before the first hardware mutation; even a failed SPI
|
||||
// command can have reached the chip, requiring a confirmed stop/restore.
|
||||
_radio->clearPacketReceivedAction();
|
||||
_cw_active = _morse_owned = true;
|
||||
_cw_stopping = false;
|
||||
_cw_profile = _active_profile;
|
||||
_morse_generation[0] = _profiles.generation[0];
|
||||
_morse_generation[1] = _profiles.generation[1];
|
||||
_morse_frequency = frequency_mhz;
|
||||
_morse_wpm = wpm;
|
||||
_rx_ps_armed = false;
|
||||
_rx_hold_continuous = false;
|
||||
_nf_calib_active = false;
|
||||
_wd_observe_until = 0;
|
||||
state = STATE_IDLE;
|
||||
_board->setRadioTestActive(true);
|
||||
if (prepareMorseCarrier(frequency_mhz) != RADIOLIB_ERR_NONE) {
|
||||
stopCarrierWave();
|
||||
return Result::Failed;
|
||||
}
|
||||
_board->onBeforeTransmit();
|
||||
_cw_board_tx = true;
|
||||
if (enterMorseCarrier() != RADIOLIB_ERR_NONE) {
|
||||
stopCarrierWave();
|
||||
return Result::Failed;
|
||||
}
|
||||
// Start timing when the hardware command has finished, not before the
|
||||
// one-time oscillator/modem setup. Validation above guarantees success.
|
||||
_morse.start(text, wpm, static_cast<uint32_t>(millis()));
|
||||
return Result::Started;
|
||||
}
|
||||
|
||||
mesh::MorseTxResult RadioLibWrapper::stopMorseTx() {
|
||||
if (!supportsMorseTx()) return mesh::MorseTxResult::Unsupported;
|
||||
if (!_morse_owned) return mesh::MorseTxResult::Stopped;
|
||||
return stopCarrierWave() ? mesh::MorseTxResult::Stopped : mesh::MorseTxResult::Failed;
|
||||
}
|
||||
|
||||
bool RadioLibWrapper::serviceMorseTx() {
|
||||
if (!_morse_owned || !_cw_active) return false;
|
||||
const uint32_t now = millis();
|
||||
if (_cw_stopping) {
|
||||
if (static_cast<int32_t>(now - _cw_retry_at) >= 0) stopCarrierWave();
|
||||
return true;
|
||||
}
|
||||
if (_morse_generation[0] != _profiles.generation[0]
|
||||
|| _morse_generation[1] != _profiles.generation[1]) {
|
||||
stopCarrierWave();
|
||||
return true;
|
||||
}
|
||||
// The public profile model is also used by board-specific integrations.
|
||||
// Fail closed if one changes a tuple directly without bumping generation.
|
||||
for (uint8_t profile = 0; profile < 2; ++profile) {
|
||||
const auto& p = _profiles.params(profile);
|
||||
if (mesh::morseFrequencyOverlaps(_morse_frequency, p.freq, p.bw)) {
|
||||
stopCarrierWave();
|
||||
return true;
|
||||
}
|
||||
}
|
||||
const auto edge = _morse.advance(now);
|
||||
if (edge == mesh::MorseTx::Edge::Complete || edge == mesh::MorseTx::Edge::Expired) {
|
||||
stopCarrierWave();
|
||||
} else if (edge == mesh::MorseTx::Edge::KeyUp) {
|
||||
const int16_t status = leaveMorseCarrier();
|
||||
if (_cw_board_tx) { _board->onAfterTransmit(); _cw_board_tx = false; }
|
||||
if (status != RADIOLIB_ERR_NONE) stopCarrierWave();
|
||||
else _morse.edgeApplied(static_cast<uint32_t>(millis()));
|
||||
} else if (edge == mesh::MorseTx::Edge::KeyDown) {
|
||||
_board->onBeforeTransmit();
|
||||
_cw_board_tx = true;
|
||||
if (enterMorseCarrier() != RADIOLIB_ERR_NONE) stopCarrierWave();
|
||||
else _morse.edgeApplied(static_cast<uint32_t>(millis()));
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
#if MESH_ENABLE_MORSE_RX
|
||||
bool RadioLibWrapper::canAllocateMorseReceiver() const {
|
||||
// This is a real, opt-in runtime reservation, never hidden in the static
|
||||
// RAM baseline or silently borrowed from an independently running OTA.
|
||||
size_t allocation = _morse_rx ? 0U : sizeof(mesh::MorseRx);
|
||||
#if defined(ESP32_PLATFORM)
|
||||
size_t largest_allocation = allocation;
|
||||
#endif
|
||||
#if defined(MESH_MORSE_HIL) && MESH_MORSE_HIL
|
||||
if (!_morse_trace) {
|
||||
allocation += sizeof(mesh::MorseRssiTrace);
|
||||
#if defined(ESP32_PLATFORM)
|
||||
if (sizeof(mesh::MorseRssiTrace) > largest_allocation)
|
||||
largest_allocation = sizeof(mesh::MorseRssiTrace);
|
||||
#endif
|
||||
}
|
||||
#endif
|
||||
// A retained transcript/trace is reused in place after preparation succeeds.
|
||||
// Require only allocations still missing, while keeping the same reserve.
|
||||
const size_t required = allocation + 4096U;
|
||||
#if defined(ESP32_PLATFORM)
|
||||
return ESP.getFreeHeap() >= required
|
||||
&& (!largest_allocation
|
||||
|| heap_caps_get_largest_free_block(MALLOC_CAP_8BIT) >= largest_allocation);
|
||||
#elif defined(NRF52_PLATFORM)
|
||||
const int available = dbgHeapFree();
|
||||
return available > 0 && static_cast<size_t>(available) >= required;
|
||||
#elif defined(RP2040_PLATFORM)
|
||||
const int available = rp2040.getFreeHeap();
|
||||
return available > 0 && static_cast<size_t>(available) >= required;
|
||||
#elif defined(STM32_PLATFORM)
|
||||
uint8_t stack_marker;
|
||||
const caddr_t heap_end = _sbrk(0);
|
||||
if (heap_end == (caddr_t)-1) return false;
|
||||
const uintptr_t stack_address = reinterpret_cast<uintptr_t>(&stack_marker);
|
||||
const uintptr_t heap_address = reinterpret_cast<uintptr_t>(heap_end);
|
||||
return stack_address > heap_address && stack_address - heap_address >= required;
|
||||
#else
|
||||
return false; // an unmeasured allocator must not consume the safety reserve
|
||||
#endif
|
||||
}
|
||||
|
||||
mesh::MorseRxResult RadioLibWrapper::startMorseRx(float frequency_mhz,
|
||||
uint8_t wpm, uint32_t duration_ms) {
|
||||
using Result = mesh::MorseRxResult;
|
||||
if (!supportsMorseRx()) return Result::Unsupported;
|
||||
if (_cw_active) return Result::Busy;
|
||||
const Result valid = mesh::MorseRx::validate(wpm, duration_ms);
|
||||
if (valid != Result::Started) return valid;
|
||||
if (!_params_valid || !isfinite(frequency_mhz) || !validateMorseFrequency(frequency_mhz))
|
||||
return Result::InvalidFrequency;
|
||||
// Passive reception cannot interfere with either packet profile. Listening
|
||||
// on its centre is useful; only a transmitting Morse carrier needs spacing.
|
||||
if (!canAllocateMorseReceiver()) return Result::Failed;
|
||||
mesh::MorseRx* receiver = _morse_rx;
|
||||
const bool allocated = receiver == nullptr;
|
||||
if (allocated) receiver = new (std::nothrow) mesh::MorseRx;
|
||||
if (!receiver) return Result::Failed;
|
||||
#if defined(MESH_MORSE_HIL) && MESH_MORSE_HIL
|
||||
mesh::MorseRssiTrace* trace = _morse_trace;
|
||||
const bool trace_allocated = trace == nullptr;
|
||||
if (trace_allocated) trace = new (std::nothrow) mesh::MorseRssiTrace;
|
||||
if (!trace) { if (allocated) delete receiver; return Result::Failed; }
|
||||
#endif
|
||||
// Allocation/admission occurs before any hardware change. Keep a previous
|
||||
// transcript untouched until the replacement receiver is proven running.
|
||||
const uint8_t resume = beginReconfigure();
|
||||
if (resume > 1) {
|
||||
if (allocated) delete receiver;
|
||||
#if defined(MESH_MORSE_HIL) && MESH_MORSE_HIL
|
||||
if (trace_allocated) delete trace;
|
||||
#endif
|
||||
return Result::Busy;
|
||||
}
|
||||
_cw_restore_profile = _active_profile;
|
||||
if (_radio->standby() != RADIOLIB_ERR_NONE
|
||||
|| _radio->clearIrqFlags(UINT32_MAX) != RADIOLIB_ERR_NONE) {
|
||||
if (allocated) delete receiver;
|
||||
#if defined(MESH_MORSE_HIL) && MESH_MORSE_HIL
|
||||
if (trace_allocated) delete trace;
|
||||
#endif
|
||||
endReconfigure(resume);
|
||||
return Result::Failed;
|
||||
}
|
||||
_radio->clearPacketReceivedAction();
|
||||
_cw_active = _morse_rx_owned = true;
|
||||
_morse_owned = _cw_stopping = false;
|
||||
_cw_profile = _active_profile;
|
||||
_morse_generation[0] = _profiles.generation[0];
|
||||
_morse_generation[1] = _profiles.generation[1];
|
||||
_rx_ps_armed = _rx_hold_continuous = _nf_calib_active = false;
|
||||
_wd_observe_until = 0;
|
||||
_morse_rx_read_errors = 0;
|
||||
state = STATE_IDLE;
|
||||
_board->setRadioTestActive(true);
|
||||
if (prepareMorseReceiver(frequency_mhz) != RADIOLIB_ERR_NONE
|
||||
|| (_rx_boosted_gain_valid && !applyRxBoostedGainMode(_cur_rx_boosted_gain))
|
||||
|| startMorseReceiver() != RADIOLIB_ERR_NONE) {
|
||||
if (allocated) delete receiver;
|
||||
#if defined(MESH_MORSE_HIL) && MESH_MORSE_HIL
|
||||
if (trace_allocated) delete trace;
|
||||
#endif
|
||||
stopCarrierWave();
|
||||
return Result::Failed;
|
||||
}
|
||||
const float initial_rssi = readMorseRssi();
|
||||
if (!isfinite(initial_rssi) || initial_rssi < -180.0f || initial_rssi > 20.0f) {
|
||||
if (allocated) delete receiver;
|
||||
#if defined(MESH_MORSE_HIL) && MESH_MORSE_HIL
|
||||
if (trace_allocated) delete trace;
|
||||
#endif
|
||||
stopCarrierWave();
|
||||
return Result::Failed;
|
||||
}
|
||||
const uint32_t now = millis();
|
||||
#if defined(MESH_MORSE_HIL) && MESH_MORSE_HIL
|
||||
receiver->setTrace(trace);
|
||||
_morse_trace = trace;
|
||||
#endif
|
||||
receiver->start(wpm, duration_ms, now);
|
||||
receiver->sample(initial_rssi, now);
|
||||
_morse_rx = receiver;
|
||||
_morse_rx_frequency = frequency_mhz;
|
||||
_morse_rx_next_sample = now + mesh::MorseRx::SampleIntervalMillis;
|
||||
++_morse_capture_generation;
|
||||
return Result::Started;
|
||||
}
|
||||
|
||||
mesh::MorseRxResult RadioLibWrapper::stopMorseRx() {
|
||||
if (!supportsMorseRx()) return mesh::MorseRxResult::Unsupported;
|
||||
if (!_morse_rx_owned) return mesh::MorseRxResult::Stopped;
|
||||
return stopCarrierWave() ? mesh::MorseRxResult::Stopped : mesh::MorseRxResult::Failed;
|
||||
}
|
||||
|
||||
size_t RadioLibWrapper::readMorseCapture(size_t offset, char* out, size_t capacity) const {
|
||||
if (_morse_rx) return _morse_rx->read(offset, out, capacity);
|
||||
if (out && capacity) out[0] = 0;
|
||||
return 0;
|
||||
}
|
||||
|
||||
void RadioLibWrapper::clearMorseCapture() {
|
||||
if (isMorseRxActive()) return;
|
||||
delete _morse_rx;
|
||||
_morse_rx = nullptr;
|
||||
#if defined(MESH_MORSE_HIL) && MESH_MORSE_HIL
|
||||
delete _morse_trace;
|
||||
_morse_trace = nullptr;
|
||||
#endif
|
||||
++_morse_capture_generation;
|
||||
}
|
||||
#endif
|
||||
|
||||
bool RadioLibWrapper::serviceMorseRx() {
|
||||
#if !MESH_ENABLE_MORSE_RX
|
||||
return false;
|
||||
#else
|
||||
if (!_morse_rx_owned || !_cw_active) return false;
|
||||
const uint32_t now = millis();
|
||||
if (_cw_stopping) {
|
||||
if (static_cast<int32_t>(now - _cw_retry_at) >= 0) stopCarrierWave();
|
||||
return true;
|
||||
}
|
||||
if (!_morse_rx || !_morse_rx->service(now)
|
||||
|| _morse_generation[0] != _profiles.generation[0]
|
||||
|| _morse_generation[1] != _profiles.generation[1]) {
|
||||
stopCarrierWave();
|
||||
return true;
|
||||
}
|
||||
if (static_cast<int32_t>(now - _morse_rx_next_sample) >= 0) {
|
||||
const float rssi = readMorseRssi();
|
||||
const uint32_t sampled_at = millis();
|
||||
_morse_rx_next_sample = sampled_at + mesh::MorseRx::SampleIntervalMillis;
|
||||
if (!isfinite(rssi) || rssi < -180.0f || rssi > 20.0f) {
|
||||
if (++_morse_rx_read_errors >= 8) stopCarrierWave();
|
||||
} else {
|
||||
_morse_rx_read_errors = 0;
|
||||
_morse_rx->sample(rssi, sampled_at);
|
||||
if (!_morse_rx->active()) stopCarrierWave();
|
||||
}
|
||||
}
|
||||
return true;
|
||||
#endif
|
||||
}
|
||||
|
||||
bool RadioLibWrapper::stopCarrierWave() {
|
||||
_morse.stop();
|
||||
#if MESH_ENABLE_MORSE_RX
|
||||
if (_morse_rx_owned && _morse_rx) _morse_rx->stop(static_cast<uint32_t>(millis()));
|
||||
#endif
|
||||
_cw_stopping = true;
|
||||
// Deassert external TX even if SPI fails. SX127x must also rebuild its LoRa
|
||||
// modem after FSK direct mode before normal packet work can resume.
|
||||
const int16_t status = _radio->finishTransmit();
|
||||
// Some RadioLib finishTransmit() implementations return after a failed IRQ
|
||||
// clear, before their standby command. Always attempt the RF-off command.
|
||||
const int16_t standby_status = _radio->standby();
|
||||
if (_cw_board_tx) { _board->onAfterTransmit(); _cw_board_tx = false; }
|
||||
const bool restored = status == RADIOLIB_ERR_NONE
|
||||
? restoreCarrierWaveModem() : restoreAfterDeepInit();
|
||||
bool restored;
|
||||
#if MESH_ENABLE_MORSE_RX
|
||||
if (_morse_rx_fsk_mode) {
|
||||
// applyParams only changes a LoRa tuple; it cannot rebuild a modem switched
|
||||
// to GFSK. This includes failed partial preparation and cleanup retries.
|
||||
restored = restoreAfterDeepInit();
|
||||
if (restored) _morse_rx_fsk_mode = false;
|
||||
} else {
|
||||
#else
|
||||
{
|
||||
#endif
|
||||
restored = status == RADIOLIB_ERR_NONE || standby_status == RADIOLIB_ERR_NONE
|
||||
? restoreCarrierWaveModem() : restoreAfterDeepInit();
|
||||
}
|
||||
if (!restored) {
|
||||
_cw_retry_at = static_cast<uint32_t>(millis()) + 100;
|
||||
return false; // hold normal work until stopping the carrier is confirmed
|
||||
@@ -1067,11 +1393,23 @@ bool RadioLibWrapper::stopCarrierWave() {
|
||||
recalibrateNoiseFloor();
|
||||
startRecv();
|
||||
if (!isInRecvMode() && restoreAfterDeepInit()) startRecv();
|
||||
if (!tuned || !isInRecvMode()) {
|
||||
// A stopped carrier is not sufficient to hand ownership back if the
|
||||
// configured packet modem/profile could not be restored. Keep the guard
|
||||
// and watchdog wake veto until the bounded retry repairs reception.
|
||||
_cw_active = _cw_stopping = true;
|
||||
_cw_retry_at = static_cast<uint32_t>(millis()) + 100;
|
||||
return false;
|
||||
}
|
||||
_morse_owned = false;
|
||||
_morse_rx_owned = false;
|
||||
_board->setRadioTestActive(false);
|
||||
return tuned && isInRecvMode();
|
||||
return true;
|
||||
}
|
||||
|
||||
bool RadioLibWrapper::serviceCarrierWave() {
|
||||
if (serviceMorseRx()) return true;
|
||||
if (serviceMorseTx()) return true;
|
||||
if (_cw_active) {
|
||||
const uint32_t now = millis();
|
||||
if ((_cw_stopping && static_cast<int32_t>(now - _cw_retry_at) >= 0)
|
||||
|
||||
@@ -109,8 +109,28 @@ protected:
|
||||
bool _cw_board_tx = false;
|
||||
uint8_t _cw_profile = 0, _cw_restore_profile = 0;
|
||||
uint32_t _cw_until = 0, _cw_retry_at = 0, _cw_generation = 0;
|
||||
mesh::MorseTx _morse;
|
||||
bool _morse_owned = false;
|
||||
float _morse_frequency = mesh::MorseTx::DefaultFrequencyMHz;
|
||||
uint8_t _morse_wpm = mesh::MorseTx::DefaultWpm;
|
||||
uint32_t _morse_generation[2] = {};
|
||||
// Allocate the bounded capture only on explicit RX admission. Permanently
|
||||
// reserving 4096 characters would break small nRF52 Companion RAM budgets.
|
||||
#if MESH_ENABLE_MORSE_RX
|
||||
mesh::MorseRx* _morse_rx = nullptr;
|
||||
#if defined(MESH_MORSE_HIL) && MESH_MORSE_HIL
|
||||
mesh::MorseRssiTrace* _morse_trace = nullptr;
|
||||
#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;
|
||||
bool stopCarrierWave();
|
||||
bool serviceCarrierWave();
|
||||
bool serviceMorseTx();
|
||||
bool serviceMorseRx();
|
||||
mesh::RadioParamApplyResult tuneProfile(uint8_t profile);
|
||||
void serviceProfileScan();
|
||||
|
||||
@@ -213,6 +233,32 @@ protected:
|
||||
}
|
||||
virtual bool applyRxBoostedGainMode(bool) { return false; }
|
||||
virtual int16_t enterCarrierWave() { return _radio->transmitDirect(); }
|
||||
virtual bool validateMorseFrequency(float frequency_mhz) const {
|
||||
return isfinite(frequency_mhz) && frequency_mhz >= 150.0f && frequency_mhz <= 960.0f;
|
||||
}
|
||||
// Configure the oscillator/modem once, before the first mark. Subsequent
|
||||
// marks only re-enter direct TX; in particular SX127x must not rebuild FSK
|
||||
// between dots. The cached LoRa tuple is deliberately left untouched.
|
||||
virtual int16_t prepareMorseCarrier(float frequency_mhz) {
|
||||
if (!_board->prepareRadioFrequency(frequency_mhz)) return RADIOLIB_ERR_INVALID_FREQUENCY;
|
||||
int16_t result = _radio->setFrequency(frequency_mhz);
|
||||
if (result == RADIOLIB_ERR_NONE && _dbm_valid) result = applyCachedTxPower(_cur_dbm);
|
||||
return result;
|
||||
}
|
||||
virtual int16_t enterMorseCarrier() { return _radio->transmitDirect(); }
|
||||
virtual int16_t leaveMorseCarrier() { return _radio->standby(); }
|
||||
virtual float morseReceiverBandwidthKHz() const { return 0.0f; }
|
||||
virtual int16_t prepareMorseReceiver(float frequency_mhz) {
|
||||
(void)frequency_mhz;
|
||||
// A native, fully restorable continuous-RSSI modem hook is required.
|
||||
// LoRa's symbol detector is not a proven CW envelope receiver.
|
||||
return RADIOLIB_ERR_UNKNOWN;
|
||||
}
|
||||
virtual int16_t startMorseReceiver() { return _radio->startReceive(); }
|
||||
virtual float readMorseRssi() { return getCurrentRSSI(); }
|
||||
#if MESH_ENABLE_MORSE_RX
|
||||
virtual bool canAllocateMorseReceiver() const;
|
||||
#endif
|
||||
// Native-CW radios keep their modem. Reapply cached power in case a meter
|
||||
// sweep failed halfway through; SX127x also rebuilds its LoRa configuration.
|
||||
virtual bool restoreCarrierWaveModem() {
|
||||
@@ -254,10 +300,17 @@ protected:
|
||||
_cad_scan_timeout_override_ms = 0;
|
||||
}
|
||||
|
||||
// Concrete wrappers detach their callbacks before base destruction. Keep
|
||||
// this destructor trivial so compact targets do not need a base vtable; a
|
||||
// protected lifetime also rejects deletion through a borrowed base pointer.
|
||||
~RadioLibWrapper() = default;
|
||||
// Concrete wrappers detach their callbacks before base destruction. A
|
||||
// protected nonvirtual lifetime rejects deletion through a borrowed base
|
||||
// pointer while releasing any retained, explicitly allocated RX capture.
|
||||
~RadioLibWrapper() {
|
||||
#if MESH_ENABLE_MORSE_RX
|
||||
delete _morse_rx;
|
||||
#if defined(MESH_MORSE_HIL) && MESH_MORSE_HIL
|
||||
delete _morse_trace;
|
||||
#endif
|
||||
#endif
|
||||
}
|
||||
|
||||
public:
|
||||
void begin() override;
|
||||
@@ -265,6 +318,44 @@ public:
|
||||
bool isCarrierWaveActive() const override { return _cw_active; }
|
||||
uint8_t carrierWaveProfile() const override { return _cw_profile; }
|
||||
uint32_t carrierWaveRemainingMillis() const override;
|
||||
bool supportsMorseTx() const override;
|
||||
mesh::MorseTxResult startMorseTx(float frequency_mhz, uint8_t wpm, const char* text) override;
|
||||
mesh::MorseTxResult stopMorseTx() override;
|
||||
bool isMorseTxActive() const override { return _morse_owned && _cw_active; }
|
||||
float morseTxFrequency() const override { return _morse_frequency; }
|
||||
uint8_t morseTxWpm() const override { return _morse_wpm; }
|
||||
uint32_t morseTxRemainingMillis() const override { return _morse.remainingMillis(millis()); }
|
||||
#if MESH_ENABLE_MORSE_RX
|
||||
bool supportsMorseRx() const override { return false; }
|
||||
mesh::MorseRxResult startMorseRx(float frequency_mhz, uint8_t wpm, uint32_t duration_ms) override;
|
||||
mesh::MorseRxResult stopMorseRx() override;
|
||||
bool isMorseRxActive() const override { return _morse_rx_owned && _cw_active; }
|
||||
bool morseRxRecovering() const override { return isMorseRxActive() && _cw_stopping; }
|
||||
bool morseRxLearning() const override { return isMorseRxActive() && _morse_rx && _morse_rx->learning(millis()); }
|
||||
float morseRxFrequency() const override { return _morse_rx_frequency; }
|
||||
float morseRxBandwidthKHz() const override { return morseReceiverBandwidthKHz(); }
|
||||
uint32_t morseRxRemainingMillis() const override { return _morse_rx ? _morse_rx->remainingMillis(millis()) : 0; }
|
||||
uint32_t morseCaptureGeneration() const override { return _morse_capture_generation; }
|
||||
bool morseRxDiagnostics(mesh::MorseRxDiagnostics& out) const override {
|
||||
if (!_morse_rx) { out = {}; return false; }
|
||||
_morse_rx->diagnostics(out);
|
||||
out.read_errors = _morse_rx_read_errors;
|
||||
return true;
|
||||
}
|
||||
size_t morseCaptureLength() const override { return _morse_rx ? _morse_rx->length() : 0; }
|
||||
bool morseCaptureTruncated() const override { return _morse_rx && _morse_rx->truncated(); }
|
||||
const char* morseCaptureText() const override { return _morse_rx ? _morse_rx->text() : ""; }
|
||||
size_t readMorseCapture(size_t offset, char* out, size_t capacity) const override;
|
||||
void clearMorseCapture() override;
|
||||
#if defined(MESH_MORSE_HIL) && MESH_MORSE_HIL
|
||||
size_t morseTraceLength() const override { return _morse_trace ? _morse_trace->length() : 0; }
|
||||
uint32_t morseTraceTotal() const override { return _morse_trace ? _morse_trace->total() : 0; }
|
||||
bool morseTraceTruncated() const override { return _morse_trace && _morse_trace->truncated(); }
|
||||
bool readMorseTrace(size_t offset, mesh::MorseRssiTraceEntry& out) const override {
|
||||
return _morse_trace && _morse_trace->read(offset, out);
|
||||
}
|
||||
#endif
|
||||
#endif
|
||||
mesh::RadioProfiles* profiles() override { return &_profiles; }
|
||||
const mesh::RadioProfiles* profiles() const override { return &_profiles; }
|
||||
bool validateProfile(const mesh::RadioProfileParams& params) const override;
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
#pragma once
|
||||
|
||||
#include <RadioLib.h>
|
||||
|
||||
inline uint8_t sx126xMorsePaRamp() {
|
||||
#if defined(MESH_MORSE_HIL) && MESH_MORSE_HIL && defined(MESH_MORSE_HIL_PA_RAMP_US)
|
||||
constexpr unsigned requested_us = MESH_MORSE_HIL_PA_RAMP_US;
|
||||
static_assert(requested_us == 10 || requested_us == 20 || requested_us == 40
|
||||
|| requested_us == 80 || requested_us == 200 || requested_us == 800
|
||||
|| requested_us == 1700 || requested_us == 3400,
|
||||
"HIL SX126x PA ramp must be 10/20/40/80/200/800/1700/3400 microseconds");
|
||||
constexpr uint8_t requested = requested_us == 10 ? RADIOLIB_SX126X_PA_RAMP_10U
|
||||
: requested_us == 20 ? RADIOLIB_SX126X_PA_RAMP_20U
|
||||
: requested_us == 40 ? RADIOLIB_SX126X_PA_RAMP_40U
|
||||
: requested_us == 80 ? RADIOLIB_SX126X_PA_RAMP_80U
|
||||
: requested_us == 200 ? RADIOLIB_SX126X_PA_RAMP_200U
|
||||
: requested_us == 800 ? RADIOLIB_SX126X_PA_RAMP_800U
|
||||
: requested_us == 1700 ? RADIOLIB_SX126X_PA_RAMP_1700U
|
||||
: RADIOLIB_SX126X_PA_RAMP_3400U;
|
||||
#else
|
||||
constexpr uint8_t requested = RADIOLIB_SX126X_PA_RAMP_3400U;
|
||||
#endif
|
||||
#ifdef SX126X_PA_RAMP_TIME
|
||||
// The hardware ramp encodings increase with duration. A lab override must
|
||||
// never defeat a board's slower external-PA requirement.
|
||||
constexpr uint8_t board_minimum = static_cast<uint8_t>(SX126X_PA_RAMP_TIME);
|
||||
return requested < board_minimum ? board_minimum : requested;
|
||||
#else
|
||||
return requested;
|
||||
#endif
|
||||
}
|
||||
|
||||
// Set only the envelope ramp, using RadioLib's cached chip drive power. This
|
||||
// preserves external-PA board calibration instead of treating user dBm as a
|
||||
// raw PA drive level. A CW transmitter has no receive bandwidth to select.
|
||||
inline int16_t setSX126xMorseRamp(SX126x* radio) {
|
||||
const int16_t status = radio->setPaRampTime(sx126xMorsePaRamp());
|
||||
#if defined(MESH_MORSE_HIL) && MESH_MORSE_HIL && defined(MESH_MORSE_HIL_WARM_TX) && MESH_MORSE_HIL_WARM_TX
|
||||
// Establish XOSC before the first mark too. Do not borrow or overwrite the
|
||||
// scanner's standbyXOSC policy: normal final cleanup restores it unchanged.
|
||||
return status == RADIOLIB_ERR_NONE ? radio->standby(RADIOLIB_SX126X_STANDBY_XOSC) : status;
|
||||
#else
|
||||
return status;
|
||||
#endif
|
||||
}
|
||||
|
||||
inline int16_t leaveSX126xMorseCarrier(SX126x* radio) {
|
||||
#if defined(MESH_MORSE_HIL) && MESH_MORSE_HIL && defined(MESH_MORSE_HIL_WARM_TX) && MESH_MORSE_HIL_WARM_TX
|
||||
return radio->standby(RADIOLIB_SX126X_STANDBY_XOSC);
|
||||
#else
|
||||
return radio->standby();
|
||||
#endif
|
||||
}
|
||||
|
||||
inline int16_t restoreSX126xPacketRamp(SX126x* radio) {
|
||||
#ifdef SX126X_PA_RAMP_TIME
|
||||
return radio->setPaRampTime(static_cast<uint8_t>(SX126X_PA_RAMP_TIME));
|
||||
#else
|
||||
return radio->setPaRampTime(RADIOLIB_SX126X_PA_RAMP_200U);
|
||||
#endif
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
#pragma once
|
||||
|
||||
#include <RadioLib.h>
|
||||
#include "../MorseRx.h"
|
||||
|
||||
#if defined(MESH_MORSE_HIL) && MESH_MORSE_HIL && defined(MESH_MORSE_HIL_PACKET_GATING)
|
||||
static_assert(MESH_MORSE_HIL_PACKET_GATING == 0 || MESH_MORSE_HIL_PACKET_GATING == 1,
|
||||
"HIL GFSK packet gating must be 0 or 1");
|
||||
#endif
|
||||
|
||||
// Real GFSK 4.8 kHz receive filter, not a LoRa symbol/preamble detector.
|
||||
// Keep the board's actual reference supply and regulator policy across the
|
||||
// native one-time modem reset. No RF is transmitted by this preparation.
|
||||
template<class RadioT>
|
||||
int16_t prepareSX126xMorseReceiver(RadioT* radio, float frequency_mhz) {
|
||||
const float tcxo_voltage = radio->tcxoVoltage;
|
||||
const bool use_ldo = radio->useRegulatorLDO;
|
||||
const bool standby_xosc = radio->standbyXOSC;
|
||||
const bool boosted_gain = radio->rxBoostedGainMode;
|
||||
radio->standbyXOSC = false; // TCXO/DIO3 is not restored until beginFSK
|
||||
const int16_t begin_status = radio->beginFSK(
|
||||
frequency_mhz, mesh::MorseRx::ReceiverBitRateKbps, 0.6f, 4.8f, 2, 16, tcxo_voltage, use_ldo);
|
||||
radio->standbyXOSC = standby_xosc;
|
||||
if (begin_status != RADIOLIB_ERR_NONE) return begin_status;
|
||||
int16_t status;
|
||||
#ifdef SX126X_CURRENT_LIMIT
|
||||
status = radio->setCurrentLimit(SX126X_CURRENT_LIMIT);
|
||||
if (status != RADIOLIB_ERR_NONE) return status;
|
||||
#endif
|
||||
#ifdef SX126X_DIO2_AS_RF_SWITCH
|
||||
status = radio->setDio2AsRfSwitch(SX126X_DIO2_AS_RF_SWITCH);
|
||||
if (status != RADIOLIB_ERR_NONE) return status;
|
||||
#endif
|
||||
#if defined(SX126X_RXEN) || defined(SX126X_TXEN)
|
||||
radio->setRfSwitchPins(
|
||||
#ifdef SX126X_RXEN
|
||||
SX126X_RXEN,
|
||||
#else
|
||||
RADIOLIB_NC,
|
||||
#endif
|
||||
#ifdef SX126X_TXEN
|
||||
SX126X_TXEN
|
||||
#else
|
||||
RADIOLIB_NC
|
||||
#endif
|
||||
);
|
||||
#endif
|
||||
#if !(defined(MESH_MORSE_HIL) && MESH_MORSE_HIL && defined(MESH_MORSE_HIL_PACKET_GATING) && MESH_MORSE_HIL_PACKET_GATING)
|
||||
// The default no-lock packet tuple is retained unchanged. The isolated HIL
|
||||
// comparison instead keeps beginFSK's ordinary preamble/sync/CRC settings;
|
||||
// Semtech's spectral-scan example reads instant RSSI before packet lock.
|
||||
uint8_t unused_sync = 0;
|
||||
status = radio->setSyncWord(&unused_sync, 0);
|
||||
if (status != RADIOLIB_ERR_NONE) return status;
|
||||
status = radio->setCRC(0);
|
||||
if (status != RADIOLIB_ERR_NONE) return status;
|
||||
#endif
|
||||
// No Morse data uses the FSK packet parser. Avoid random noise bytes making
|
||||
// arbitrarily short variable-length frames while sampling continuous power.
|
||||
status = radio->fixedPacketLengthMode(255);
|
||||
if (status != RADIOLIB_ERR_NONE) return status;
|
||||
status = radio->setMorseFastRssi();
|
||||
if (status != RADIOLIB_ERR_NONE) return status;
|
||||
// Boards can set the native gain directly at initialization, without an
|
||||
// exposed CLI/cache setting (notably integrated STM32WL targets). Preserve
|
||||
// that actual policy too; a valid wrapper cache is applied afterwards.
|
||||
status = radio->setRxBoostedGainMode(boosted_gain);
|
||||
if (status != RADIOLIB_ERR_NONE) return status;
|
||||
// The wrapper restores the cached gain while still in standby, then enters
|
||||
// RX through its dedicated start hook. No mid-RX gain/AGC mutation.
|
||||
return RADIOLIB_ERR_NONE;
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
#pragma once
|
||||
|
||||
#include <RadioLib.h>
|
||||
|
||||
inline int16_t setSX126xMorseRssiWindow(SX126x* radio) {
|
||||
#if defined(MESH_MORSE_HIL) && MESH_MORSE_HIL && defined(MESH_MORSE_HIL_RSSI_WINDOW)
|
||||
static_assert(MESH_MORSE_HIL_RSSI_WINDOW >= 0 && MESH_MORSE_HIL_RSSI_WINDOW <= 7,
|
||||
"SX126x RSSI averaging exponent must fit bits4:2");
|
||||
constexpr uint8_t window = MESH_MORSE_HIL_RSSI_WINDOW;
|
||||
#else
|
||||
constexpr uint8_t window = 0;
|
||||
#endif
|
||||
// SPIsetRegValue takes an already positioned register value, not a logical
|
||||
// field value. Window exponent2 is0x08 in RSSI_AVG_WINDOW[4:2], not0x02.
|
||||
return radio->getMod()->SPIsetRegValue(RADIOLIB_SX126X_REG_RSSI_AVG_WINDOW,
|
||||
static_cast<uint8_t>(window << 2), 4, 2);
|
||||
}
|
||||
Reference in new issue
Block a user