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:
mikecarper committed 2026-10-13 01:24:39 -07:00
1 parent d2bea5fb10
commit ca9caece53
152 files changed
+12631 -149

No files matched your search

+162 -8
View File
@@ -1,5 +1,7 @@
#include <helpers/ui/DisplayPowerSettings.h>
#include <helpers/BatteryChargeCLI.h>
#include <helpers/MorseCLI.h>
#include <helpers/MorseLoopPolicy.h>
#include <helpers/ui/StartupScreen.h>
#include "NotificationSettingsFile.h"
#include "MyMesh.h"
@@ -1795,6 +1797,7 @@ void MyMesh::onGroupPacketRecv(mesh::Packet* packet) {
#endif
bool MyMesh::allowFloodRetry(const mesh::Packet* packet) const {
if (_morse_reply.ownsReply(packet)) return false;
if (packet == NULL || _prefs.flood_retry_attempts == 0) return false;
// A companion may retry its own advert once, using the core's deliberately
// slow origin-advert delay. Do not add retries while relaying a neighbour's
@@ -1850,12 +1853,32 @@ bool MyMesh::sendFloodScoped(const mesh::GroupChannel& channel, mesh::Packet* pk
}
}
#if MESH_ENABLE_FLEET_CONTROL
void MyMesh::onRadioProfileCopyQueued(mesh::Packet* packet, const mesh::Packet* original, uint8_t priority) {
mesh::Mesh::onRadioProfileCopyQueued(packet, original, priority);
_morse_reply.copy(original, packet);
#if MESH_ENABLE_FLEET_CONTROL
if (original && original == _fleet_admission_original) _fleet_admission_copy = packet;
#endif
}
void MyMesh::onSendComplete(mesh::Packet* packet) {
mesh::Mesh::onSendComplete(packet);
_morse_reply.complete(packet);
}
void MyMesh::onSendFail(mesh::Packet* packet) {
mesh::Mesh::onSendFail(packet);
_morse_reply.fail(packet);
}
bool MyMesh::allowDirectRetry(const mesh::Packet* packet, const uint8_t* next_hop_hash,
uint8_t next_hop_hash_len) const {
return !_morse_reply.ownsReply(packet)
&& mesh::Mesh::allowDirectRetry(packet, next_hop_hash, next_hop_hash_len);
}
#if MESH_ENABLE_FLEET_CONTROL
bool MyMesh::sendFleetCommandData(mesh::GroupChannel& channel, const uint8_t* envelope, size_t length) {
if (!envelope || !length || length > mesh::FleetCommand::MaxEnvelopeLength) return false;
if (length <= mesh::FleetCommand::MaxPayloadLength) {
@@ -2023,15 +2046,33 @@ void MyMesh::onCLICommandRecv(const ContactInfo &from, mesh::Packet *pkt, uint32
const char *text, char* reply) {
markConnectionActive(from); // in case this is from a server, and we have a connection
if (from.isRemoteCLIAllowed()) {
const uint32_t before = _morse_reply.generation();
_morse_reply.beginCommand(from.id.pub_key);
// A timestamp received over the radio must never grant local-console access.
if (!handleCommand(text, sender_timestamp ? sender_timestamp : 1, reply)) {
strcat(reply, "Unknown command"); // reply may have cmd prefix from 'text'
}
_morse_reply.endCommand();
_morse_reply_admission = _morse_reply.generation() != before;
} else {
queueMessage(from, TXT_TYPE_CLI_COMMAND, pkt, sender_timestamp, NULL, 0, text);
}
}
void MyMesh::onCLIReplyPrepared(const ContactInfo& from, mesh::Packet* reply) {
if (!_morse_reply_admission || !_morse_reply.pending()
|| memcmp(from.id.pub_key, _morse_reply.actor(), PUB_KEY_SIZE) != 0) return;
_morse_reply.prepareReply(reply);
if (reply) reply->radio_reply = true;
}
void MyMesh::onCLIReplyQueued(const ContactInfo& from, mesh::Packet* reply, bool queued) {
if (!_morse_reply_admission) return;
if (memcmp(from.id.pub_key, _morse_reply.actor(), PUB_KEY_SIZE) == 0)
_morse_reply.armReply(reply, queued);
_morse_reply_admission = false;
}
bool MyMesh::onSignedMessageRecv(const ContactInfo &from, mesh::Packet *pkt, uint32_t sender_timestamp,
const uint8_t *sender_prefix, const char *text) {
if (!queueMessage(from, TXT_TYPE_SIGNED_PLAIN, pkt, sender_timestamp, sender_prefix, 4, text)) return false;
@@ -2780,6 +2821,7 @@ void MyMesh::begin(bool has_display, bool radio_available,
initializeOfflineQueue();
BaseChatMesh::begin();
_radio_profiles.begin(_store->getPrimaryFS(), _radio, getRTCClock());
mesh::loadMorseSettings(_store->getPrimaryFS());
#if defined(ENABLE_OTA)
mesh::ota::beginSpeedConfig(_store->getPrimaryFS());
#endif
@@ -3961,6 +4003,8 @@ bool MyMesh::handleLocalControlCommand(const char* command, char* reply,
if (strcmp(value, "on") != 0 && strcmp(value, "off") != 0) {
snprintf(reply, reply_size,
"Error: use set radio.fem.rxgain on|off");
} else if (_radio && (_radio->isMorseTxActive() || _radio->isMorseRxActive())) {
snprintf(reply, reply_size, "Error: stop Morse before changing LoRa FEM gain");
} else if (!board.canControlLoRaFemLna()) {
snprintf(reply, reply_size, "Error: unsupported");
} else if (!applyAndSaveFemRxGain(strcmp(value, "on") == 0)) {
@@ -3990,6 +4034,8 @@ bool MyMesh::handleLocalControlCommand(const char* command, char* reply,
if (strcmp(value, "on") != 0 && strcmp(value, "off") != 0) {
snprintf(reply, reply_size,
"Error: use set radio.fem.txgain on|off");
} else if (_radio && (_radio->isMorseTxActive() || _radio->isMorseRxActive())) {
snprintf(reply, reply_size, "Error: stop Morse before changing LoRa FEM gain");
} else if (!board.canControlLoRaFemPaGain()) {
snprintf(reply, reply_size, "%s", board.isLoRaFemPaGainEnabled()
? "Error: TX PA is fixed on; use set tx to adjust power"
@@ -5250,6 +5296,8 @@ void MyMesh::execCommand(char* cmd, char* reply) {
bool enabled;
if (!wcParseBool(value, enabled)) {
strcpy(reply, "Error: must be on or off");
} else if (_radio && (_radio->isMorseTxActive() || _radio->isMorseRxActive())) {
strcpy(reply, "Error: stop Morse before changing LoRa FEM gain");
} else if (!board.canControlLoRaFemLna()) {
strcpy(reply, "Error: unsupported");
} else if (!applyAndSaveFemRxGain(enabled)) {
@@ -5263,6 +5311,8 @@ void MyMesh::execCommand(char* cmd, char* reply) {
bool enabled;
if (!wcParseBool(value, enabled)) {
strcpy(reply, "Error: must be on or off");
} else if (_radio && (_radio->isMorseTxActive() || _radio->isMorseRxActive())) {
strcpy(reply, "Error: stop Morse before changing LoRa FEM gain");
} else if (!board.canControlLoRaFemPaGain()) {
strcpy(reply, "Error: unsupported");
} else if (!applyAndSaveFemTxGain(enabled)) {
@@ -7929,6 +7979,9 @@ MyMesh::RadioSettingResult MyMesh::applyAndSaveTxPower(int8_t power) {
}
bool MyMesh::applyAndSaveFemRxGain(bool enabled) {
// Binary Companion setters and WebConfig also enter through this helper.
// Do not alter an external FEM while the Morse transmitter owns it.
if (_radio && (_radio->isMorseTxActive() || _radio->isMorseRxActive())) return false;
if (!board.canControlLoRaFemLna()) return false;
const bool previous_hardware = board.isLoRaFemLnaEnabled();
@@ -7951,6 +8004,7 @@ bool MyMesh::applyAndSaveFemRxGain(bool enabled) {
}
bool MyMesh::applyAndSaveFemTxGain(bool enabled) {
if (_radio && (_radio->isMorseTxActive() || _radio->isMorseRxActive())) return false;
if (!board.canControlLoRaFemPaGain()) return false;
const bool previous_hardware = board.isLoRaFemPaGainEnabled();
const uint8_t previous_pref = _prefs.radio_fem_txgain;
@@ -8666,6 +8720,10 @@ void MyMesh::resetTerminalSession() {
#if COMPANION_FEATURE_READER
mesh::cancelReaderCommand();
#endif
_terminal_input_editing = false;
_morse_terminal_owner = nullptr;
_morse_terminal_pending_chars = 0;
_morse_terminal_was_receiving = false;
_terminal_recipient_set = false;
memset(_terminal_recipient_key, 0, sizeof(_terminal_recipient_key));
clearTerminalLogin();
@@ -8680,6 +8738,76 @@ void MyMesh::resetTerminalSession() {
}
}
void MyMesh::serviceMorseTerminal() {
// Only an explicitly owned ASCII terminal receives spontaneous text.
// Never use terminalOutput()'s Serial fallback or append to BLE/USB frames.
if (!_radio || !hasTerminalOutput()) {
_morse_terminal_owner = nullptr;
_morse_terminal_pending_chars = 0;
_morse_terminal_was_receiving = false;
return;
}
// A temporarily silent/paused terminal still owns its cursor. Resuming
// must not replay the capture or reset a pending partial line.
if (!_terminal_morse_atomic || isTerminalWaitingForInput()
|| _terminal_input_editing || _terminal_output->available() > 0
|| _terminal_login_pending || _terminal_trace_pending
|| _terminal_command.isPending()) return;
// The existing USB facade owns all queued suffixes, including replies and
// echo. Never append progress in the middle of an earlier text producer.
if (_terminal_mode && _terminal_output == &mesh::usbTerminalPort()
&& mesh::hasPendingUsbTerminalOutput()) return;
const bool receiving = _radio->isMorseRxActive();
const uint32_t generation = _radio->morseCaptureGeneration();
const size_t total = _radio->morseCaptureLength();
const uint32_t now = _ms->getMillis();
if (_morse_terminal_owner != _terminal_output || _morse_terminal_generation != generation) {
_morse_terminal_owner = _terminal_output;
_morse_terminal_generation = generation;
_morse_terminal_offset = receiving ? 0 : total;
_morse_terminal_pending_chars = 0;
_morse_terminal_was_receiving = receiving;
_morse_terminal_next_at = now;
}
if (receiving) _morse_terminal_was_receiving = true;
if (!_morse_terminal_was_receiving) return;
if (!_morse_terminal_pending_chars) {
if (_morse_terminal_offset >= total) {
if (!receiving) _morse_terminal_was_receiving = false;
return;
}
if (int32_t(now - _morse_terminal_next_at) < 0) return;
const size_t pending = total - _morse_terminal_offset;
_morse_terminal_pending_chars = pending < 48 ? pending : 48;
}
// Admit one complete record to an explicitly atomic stream. Its existing
// queue handles hardware short writes in chronological order with replies;
// Morse never retains an application-level suffix that can overtake input.
char text[49], line[80];
const size_t copied = _radio->readMorseCapture(_morse_terminal_offset, text,
size_t(_morse_terminal_pending_chars) + 1);
if (copied != _morse_terminal_pending_chars) {
_morse_terminal_pending_chars = 0;
return;
}
const int length = snprintf(line, sizeof(line), "\r\n[Morse RX] %s\r\n> ", text);
if (length <= 0 || size_t(length) >= sizeof(line)) return;
const int available = _terminal_output->availableForWrite();
if (available < length) return;
const size_t written = _terminal_output->write(
reinterpret_cast<const uint8_t*>(line), length);
if (written == size_t(length)) {
_morse_terminal_offset += _morse_terminal_pending_chars;
_morse_terminal_pending_chars = 0;
_morse_terminal_next_at = now + 250;
} else if (written) {
// A stream that violates its atomic admission contract is no longer safe
// for unsolicited progress. Keep the full capture available via CLI.
_terminal_morse_atomic = false;
_morse_terminal_pending_chars = 0;
}
}
void MyMesh::printTerminalBanner(bool show_binary_stop) {
Stream& output = terminalOutput();
#if COMPANION_FEATURE_TEMP_RADIO || COMPANION_FEATURE_NETWORK_TERMINAL
@@ -8703,6 +8831,12 @@ void MyMesh::enterTerminalMode(bool show_banner) {
_terminal_mode = true;
_terminal_usb_silent = !show_banner;
_terminal_output = &mesh::usbTerminalPort();
#if MESH_ESP32_TINYUSB_NONBLOCKING \
|| (defined(NRF52_PLATFORM) && (defined(ENABLE_USB_INTERFACE) || defined(USE_TINYUSB)))
_terminal_morse_atomic = true;
#else
_terminal_morse_atomic = false;
#endif
resetTerminalSession();
if (show_banner) printTerminalBanner(true);
}
@@ -8710,14 +8844,16 @@ void MyMesh::enterTerminalMode(bool show_banner) {
void MyMesh::exitTerminalMode() {
_terminal_mode = false;
_terminal_usb_silent = false;
_terminal_morse_atomic = false;
resetTerminalSession();
if (_terminal_output == &mesh::usbTerminalPort()) _terminal_output = NULL;
}
#if COMPANION_FEATURE_NETWORK_TERMINAL || defined(WITH_WEBCONFIG)
bool MyMesh::enterNetworkTerminalMode(Stream& output) {
bool MyMesh::enterNetworkTerminalMode(Stream& output, bool atomic_output) {
if (_terminal_mode || (_terminal_output != NULL && _terminal_output != &output)) return false;
_terminal_output = &output;
_terminal_morse_atomic = atomic_output;
resetTerminalSession();
printTerminalBanner(false);
return true;
@@ -8726,6 +8862,7 @@ bool MyMesh::enterNetworkTerminalMode(Stream& output) {
void MyMesh::exitNetworkTerminalMode(Stream& output) {
if (_terminal_mode || _terminal_output != &output) return;
resetTerminalSession();
_terminal_morse_atomic = false;
_terminal_output = NULL;
}
@@ -9782,6 +9919,8 @@ void MyMesh::handleTerminalCommand(char* command, bool reader_prompt,
while (*value == ' ' || *value == '\t') value++;
if (strcmp(value, "on") != 0 && strcmp(value, "off") != 0) {
terminalOutput().print(" ERROR: use set radio.fem.rxgain <on|off>\r\n");
} else if (_radio && (_radio->isMorseTxActive() || _radio->isMorseRxActive())) {
terminalOutput().print(" ERROR: stop Morse before changing LoRa FEM gain\r\n");
} else if (!board.canControlLoRaFemLna()) {
terminalOutput().print(" ERROR: FEM RX gain control is unsupported on this board\r\n");
} else if (!applyAndSaveFemRxGain(strcmp(value, "on") == 0)) {
@@ -9796,6 +9935,8 @@ void MyMesh::handleTerminalCommand(char* command, bool reader_prompt,
while (*value == ' ' || *value == '\t') value++;
if (strcmp(value, "on") != 0 && strcmp(value, "off") != 0) {
terminalOutput().print(" ERROR: use set radio.fem.txgain <on|off>\r\n");
} else if (_radio && (_radio->isMorseTxActive() || _radio->isMorseRxActive())) {
terminalOutput().print(" ERROR: stop Morse before changing LoRa FEM gain\r\n");
} else if (!board.canControlLoRaFemPaGain()) {
terminalOutput().print(board.isLoRaFemPaGainEnabled()
? " ERROR: TX PA is fixed on; use set tx to adjust power\r\n"
@@ -10312,6 +10453,9 @@ bool MyMesh::handleCommand(const char* command, uint32_t sender_timestamp,
}
#endif
if (mesh::handleMorseReplyCommand(_morse_reply, _radio, command, reply,
reply_capacity, millis())) return true;
if (mesh::handleMorseCommand(_radio, command, reply, reply_capacity)) return true;
if (_radio_profiles.handle(command, reply, reply_capacity, sender_timestamp != 0)) return true;
if (!strncmp(command, "set tempradio ", 14)) command += 4;
if (!strcmp(command, "get tempradio")) command += 4;
@@ -10900,6 +11044,14 @@ void MyMesh::checkSerialInterface() {
}
void MyMesh::loop() {
#if MESH_ENABLE_MORSE_RX
if (_morse_reply.pending()) {
const ContactInfo* actor = lookupContactByPubKey(_morse_reply.actor(), PUB_KEY_SIZE);
const auto& settings = mesh::morseSettings();
_morse_reply.service(_radio, millis(), actor && actor->isRemoteCLIAllowed(),
mesh::morseSettingsUsable(), settings.frequency_khz, settings.wpm);
}
#endif
#if COMPANION_FEATURE_NOTIFICATIONS
_notifications.loop(millis(), _serial->isConnected());
#if defined(PIN_USER_BTN) && defined(USER_BTN_PRESSED)
@@ -10909,14 +11061,14 @@ void MyMesh::loop() {
#endif
#endif
_radio_profiles.loop();
if (!mesh::morseTimingActive(_radio)) _radio_profiles.loop();
#if MESH_ENABLE_MESHTEXT_CHAT
refreshMeshtextProfile();
#endif
#if defined(WITH_MQTT_BRIDGE) && defined(ESP32_PLATFORM) && defined(WIFI_SSID)
if (_mqtt_bridge) _mqtt_bridge->servicePendingClockCorrection();
#endif
if (_scheduled_reboot_at != 0
if (!mesh::morseTimingActive(_radio) && _scheduled_reboot_at != 0
&& (_scheduled_reboot_at == _ms->getMillis()
|| millisHasNowPassed(_scheduled_reboot_at))) {
_scheduled_reboot_at = 0;
@@ -10928,7 +11080,7 @@ void MyMesh::loop() {
return;
}
#if COMPANION_FEATURE_TEMP_RADIO
serviceTempRadio();
if (!mesh::morseTimingActive(_radio)) serviceTempRadio();
#endif
#if defined(OTA_SHARED_COMPANION_QUEUE)
mesh::ota::ota_release_context_if_idle(isAnyTempRadioActive() || _temp_radio_set_at != 0);
@@ -10941,19 +11093,20 @@ void MyMesh::loop() {
#endif
BaseChatMesh::loop();
#ifdef COMPANION_MESH_CLOCK_SYNC
_clock_sync.loop();
if (!mesh::morseTimingActive(_radio)) _clock_sync.loop();
#endif
#if COMPANION_FEATURE_TEXT_TERMINAL
serviceTerminalLogin();
serviceTerminalCommand();
serviceTerminalTrace();
serviceMorseTerminal();
#endif
servicePendingSerialReply();
#if COMPANION_FEATURE_READER
mesh::serviceReaderCommand();
#endif
serviceBinaryTraceReply();
serviceSigningSession();
if (!mesh::morseTimingActive(_radio)) serviceSigningSession();
if (!command_radio_apply_pending && saved_radio_apply_pending && !hasOutbound()
#if COMPANION_FEATURE_TEMP_RADIO
&& !_temp_radio_applied && _temp_radio_set_at == 0
@@ -11006,7 +11159,7 @@ void MyMesh::loop() {
servicePersistence();
#else
// is there are pending dirty contacts write needed?
if (isContactWriteDue()) {
if (!mesh::morseTimingActive(_radio) && isContactWriteDue()) {
const bool success = _store->serviceContactWrites(this, save_filter);
if (!success) {
scheduleContactWriteRetry();
@@ -11036,6 +11189,7 @@ void MyMesh::loop() {
#if defined(ESP32_PLATFORM)
void MyMesh::servicePersistence() {
if (mesh::morseTimingActive(_radio)) return;
// Advert crypto runs before serial service. Defer its cache I/O until here,
// and alternate with due contact work so neither job can starve the other.
// Only one persistence job is serviced in a loop pass.
+25 -2
View File
@@ -27,6 +27,7 @@
#include "DataStore.h"
#include <helpers/RadioProfileCLI.h>
#include <helpers/MorseReplyHandoff.h>
#include <helpers/MeshtextConfig.h>
#if MESH_ENABLE_MESHTEXT_CHAT
#include <helpers/CompanionMeshtextChannel.h>
@@ -305,10 +306,15 @@ public:
bool isTerminalWaitingForInput() const {
return _terminal_mode && _terminal_usb_silent;
}
// The input parser publishes its real edit state for this exact owner.
// Silent default-ASCII ownership above is a separate protocol state.
void setTerminalInputEditing(const Stream& output, bool editing) {
if (_terminal_output == &output) _terminal_input_editing = editing;
}
void handleTerminalCommand(char* command, bool reader_prompt = true,
mesh::ReaderTryWrite reader_try_write = nullptr);
#if COMPANION_FEATURE_NETWORK_TERMINAL || defined(WITH_WEBCONFIG)
bool enterNetworkTerminalMode(Stream& output);
bool enterNetworkTerminalMode(Stream& output, bool atomic_output = false);
void exitNetworkTerminalMode(Stream& output);
bool isNetworkTerminalMode(const Stream& output) const;
bool isAnyNetworkTerminalMode() const {
@@ -406,8 +412,12 @@ protected:
bool sendFloodScoped(const mesh::GroupChannel& channel, mesh::Packet* pkt, uint32_t delay_millis=0) override;
#if MESH_ENABLE_FLEET_CONTROL
bool sendFleetCommandData(mesh::GroupChannel& channel, const uint8_t* envelope, size_t length);
void onRadioProfileCopyQueued(mesh::Packet* packet, const mesh::Packet* original, uint8_t priority) override;
#endif
void onRadioProfileCopyQueued(mesh::Packet* packet, const mesh::Packet* original, uint8_t priority) override;
void onSendComplete(mesh::Packet* packet) override;
void onSendFail(mesh::Packet* packet) override;
bool allowDirectRetry(const mesh::Packet* packet, const uint8_t* next_hop_hash,
uint8_t next_hop_hash_len) const override;
void logRxRaw(float snr, float rssi, const uint8_t raw[], int len) override;
#if MESH_PACKET_LOGGING && !MESH_PACKET_LOGGING_COMPACT
@@ -450,6 +460,8 @@ protected:
const char *text) override;
void onCLICommandRecv(const ContactInfo &from, mesh::Packet *pkt, uint32_t sender_timestamp,
const char *text, char* reply) override;
void onCLIReplyPrepared(const ContactInfo& from, mesh::Packet* reply) override;
void onCLIReplyQueued(const ContactInfo& from, mesh::Packet* reply, bool queued) override;
bool onSignedMessageRecv(const ContactInfo &from, mesh::Packet *pkt, uint32_t sender_timestamp,
const uint8_t *sender_prefix, const char *text) override;
void onChannelMessageRecv(const mesh::GroupChannel &channel, mesh::Packet *pkt, uint32_t timestamp,
@@ -630,6 +642,7 @@ private:
void clearTerminalTrace(uint32_t now);
void serviceTerminalTrace();
void serviceTerminalTrace(uint32_t now);
void serviceMorseTerminal();
void sendTerminalTraceRoute(const uint8_t* route, uint8_t hash_size,
uint8_t hop_count, const char* target);
void sendTerminalTrace(ContactInfo& recipient);
@@ -692,6 +705,8 @@ private:
DataStore* _store;
mesh::RadioProfileCLI _radio_profiles;
mesh::MorseReplyHandoff _morse_reply;
bool _morse_reply_admission = false;
#if MESH_ENABLE_MESHTEXT_CHAT
mesh::mt::Region _mt_region = mesh::mt::Region::Unset;
uint32_t _mt_slot = 0, _mt_node = 0, _mt_packet_id = 0;
@@ -755,6 +770,8 @@ private:
#if COMPANION_FEATURE_TEXT_TERMINAL
bool _terminal_mode;
bool _terminal_usb_silent = false;
bool _terminal_input_editing = false;
bool _terminal_morse_atomic = false;
Stream* _terminal_output;
mesh::TerminalDisplayFilter _terminal_display;
bool _terminal_recipient_set;
@@ -774,6 +791,12 @@ private:
unsigned long _terminal_trace_sent_at;
unsigned long _terminal_trace_expires_at;
char _terminal_trace_target[32];
Stream* _morse_terminal_owner = nullptr;
uint32_t _morse_terminal_generation = 0;
uint32_t _morse_terminal_next_at = 0;
uint16_t _morse_terminal_offset = 0;
uint8_t _morse_terminal_pending_chars = 0;
bool _morse_terminal_was_receiving = false;
#endif
bool saved_radio_apply_pending;
bool _radio_available;
+25 -8
View File
@@ -3,6 +3,7 @@
#include <helpers/ui/DisplayPowerSettings.h>
#include <helpers/UsbLoggingWatchdog.h>
#include <helpers/UsbLoggingClientActivity.h>
#include <helpers/MorseLoopPolicy.h>
#include <Mesh.h>
#include <helpers/BluetoothMac.h>
#include "MyMesh.h"
@@ -683,6 +684,14 @@ static Stream& usbTerminalOutput() {
return mesh::usbTerminalPort();
}
static void syncUsbTerminalInputEditing() {
#if COMPANION_FEATURE_TEXT_TERMINAL
the_mesh.setTerminalInputEditing(usbTerminalOutput(),
usb_terminal_line_len != 0 || usb_terminal_discard_line
|| mesh::usbCompanionPort().available() > 0);
#endif
}
static void clearUsbTerminalLine() {
memset(usb_terminal_line, 0, sizeof(usb_terminal_line));
usb_terminal_line_len = 0;
@@ -1468,7 +1477,7 @@ bool MyMesh::beginStreamTerminal(Stream& output) {
hasObservableActiveUsbTerminalClient(), input_idle,
usb_serial_interface.getCompletedFrameCount())) return false;
if (ascii_selected) leaveUsbTerminalMode(false);
if (enterNetworkTerminalMode(output)) {
if (enterNetworkTerminalMode(output, true)) {
serviceUsbLoggingOwnership(mesh::isUsbLoggingEnabled());
return true;
}
@@ -1489,7 +1498,7 @@ void MyMesh::endStreamTerminal(Stream& output) {
}
#elif defined(WITH_WEBCONFIG)
bool MyMesh::beginStreamTerminal(Stream& output) {
return enterNetworkTerminalMode(output);
return enterNetworkTerminalMode(output, true);
}
void MyMesh::endStreamTerminal(Stream& output) {
@@ -3835,6 +3844,9 @@ void loop() {
#if COMPANION_FEATURE_USB_MOTA_SOURCE
serviceUsbMotaResponseBoundary();
#endif
#endif
#if defined(ENABLE_USB_INTERFACE)
syncUsbTerminalInputEditing();
#endif
the_mesh.loop();
#if defined(NRF52_PLATFORM) && defined(EXTRAFS) && !defined(QSPIFLASH)
@@ -3857,6 +3869,7 @@ void loop() {
#endif
#if defined(ENABLE_USB_INTERFACE)
serviceUsbTerminal();
syncUsbTerminalInputEditing();
// Commands can synchronously enqueue a multi-line reply. Give it the
// remaining CDC FIFO capacity now; later loops retain any unwritten suffix.
mesh::serviceUsbTerminalPort();
@@ -3865,17 +3878,20 @@ void loop() {
#if COMPANION_FEATURE_BLE_MOTA_SOURCE
ble_mota_source_control.loop();
#endif
sensors.loop();
const bool morse_timing = mesh::morseTimingActive(&radio_driver);
if (!morse_timing) sensors.loop();
#if defined(WIO_E5_MINI_HEADLESS_COMPANION_UI) && defined(PIN_USER_BTN)
serviceWioE5HeadlessControls();
#endif
#ifdef DISPLAY_CLASS
// Keep button/touch and critical UI power checks live. UITask itself skips
// only background redraws while the radio needs precise Morse timing.
#ifdef INDICATOR_WIFI_FONT_RECOVERY
// The Indicator keeps rendering with its built-in fallback while a missing
// SD font is recovered by a background TLS task. This poll only launches
// work after station Wi-Fi connects and installs a completed font on the
// main/UI task.
display.serviceFontRecovery();
if (!morse_timing) display.serviceFontRecovery();
#endif
#if defined(ESP32) && defined(WIFI_SSID) && defined(WITH_WEBCONFIG) \
&& UI_WIFI_SETUP_HOME_PAGE != 1
@@ -3887,8 +3903,8 @@ void loop() {
#if defined(TBEAM_1W) && defined(PIN_WIFI_BTN)
ui_task.serviceWiFiToggleButton();
#endif
ui_task.loop(); // Continue button/touch handling while the portal is active.
renderCompanionSetupDisplay();
ui_task.loop();
if (!morse_timing) renderCompanionSetupDisplay();
} else {
ui_task.loop();
}
@@ -3897,7 +3913,7 @@ void loop() {
#endif
#endif
#if defined(COMPANION_PAIRING_UI_HIL)
companionPairingUiHilProbe();
if (!morse_timing) companionPairingUiHilProbe();
#endif
rtc_clock.tick();
board.loop();
@@ -3916,6 +3932,7 @@ void loop() {
// USB power alone (for example, a wall charger) does not inhibit sleep.
// Host sessions, live logging, and button activity still need service.
bool can_sleep = the_mesh.getNodePrefs()->powersaving_enabled
&& !morse_timing
&& !the_mesh.hasPendingWork()
&& !mesh::isUsbLoggingWatchdogArmed()
&& !mesh::wireless::control().pending();
@@ -3967,7 +3984,7 @@ void loop() {
#endif
}
#if defined(ESP32_PLATFORM)
else if (the_mesh.getNodePrefs()->powersaving_enabled) {
else if (!morse_timing && the_mesh.getNodePrefs()->powersaving_enabled) {
delay(1); // CPU idle remains available while USB/logging/button holds are active.
}
#endif
+5 -3
View File
@@ -1,5 +1,6 @@
#include "UITask.h"
#include <helpers/TxtDataHelpers.h>
#include <helpers/MorseLoopPolicy.h>
#if defined(NRF52_POWER_MANAGEMENT)
#include <helpers/NRF52VoltagePolicy.h>
#endif
@@ -2267,6 +2268,7 @@ bool UITask::isButtonGesturePending() const {
}
void UITask::loop() {
const bool morse_timing = mesh::morseTimingActive(&radio_driver);
serviceWiFiToggleButton();
servicePairingState();
@@ -2456,13 +2458,13 @@ void UITask::loop() {
if (buzzer.isPlaying()) buzzer.loop();
#endif
if (curr) curr->poll();
if (!morse_timing && curr) curr->poll();
#if COMPANION_FEATURE_READER
if (reader && curr != reader) reader->poll();
if (!morse_timing && reader && curr != reader) reader->poll();
#endif
if (_display != NULL && _display->isOn()) {
if (millis() >= _next_refresh && curr && !isButtonGesturePending()) {
if (!morse_timing && millis() >= _next_refresh && curr && !isButtonGesturePending()) {
_display->startFrame();
int delay_millis = curr->render(*_display);
renderPairingBanner();
+3 -1
View File
@@ -1,4 +1,5 @@
#include "UITask.h"
#include <helpers/MorseLoopPolicy.h>
#if UI_SMALL_MESSAGE_FONT == 1
#include <helpers/ui/SmallMessageText.h>
#endif
@@ -707,6 +708,7 @@ void UITask::servicePairingState() {
}
void UITask::loop() {
const bool morse_timing = mesh::morseTimingActive(&radio_driver);
#ifdef PIN_VIBRATION
vibration.loop();
#endif
@@ -731,7 +733,7 @@ void UITask::loop() {
servicePendingShutdown();
#endif
if (_display != NULL && _display->isOn()) {
if (!morse_timing && _display != NULL && _display->isOn()) {
if (!isPairingScreenActive() && !_alert[0] && !(_origin[0] && _msg[0])
&& (millis() - ui_started_at) >= BOOT_SCREEN_MILLIS) {
serviceRadioProfileDisplayPage();
+5 -3
View File
@@ -3,6 +3,7 @@
#include <helpers/ui/SmallMessageText.h>
#endif
#include <helpers/TxtDataHelpers.h>
#include <helpers/MorseLoopPolicy.h>
#include <helpers/ui/BluetoothPairingUiPolicy.h>
#include <helpers/ui/RadioProfileDisplayPage.h>
#include <helpers/ui/RadioProfileSystemStatus.h>
@@ -858,6 +859,7 @@ bool UITask::isButtonPressed() const {
}
void UITask::loop() {
const bool morse_timing = mesh::morseTimingActive(&radio_driver);
servicePairingState();
char c = 0;
@@ -949,9 +951,9 @@ void UITask::loop() {
if (buzzer.isPlaying()) buzzer.loop();
#endif
if (curr) curr->poll();
if (!morse_timing && curr) curr->poll();
if (_display != NULL && _display->isOn()) {
if (!morse_timing && _display != NULL && _display->isOn()) {
_statusBar.update(*_display,
_node_prefs->node_name,
_cached_batt_mv,
@@ -1018,7 +1020,7 @@ void UITask::loop() {
next_batt_chck = millis() + 8000;
}
#else
if (_display != NULL && _display->isOn() && millis() >= next_batt_chck) {
if (!morse_timing && _display != NULL && _display->isOn() && millis() >= next_batt_chck) {
_cached_batt_mv = getBattMilliVolts();
next_batt_chck = millis() + 8000;
}
+53 -4
View File
@@ -9,6 +9,7 @@
#endif
#endif
#include <helpers/UsbLogging.h>
#include <helpers/MorseLoopPolicy.h>
#include <helpers/HilStartupTrace.h>
#include <helpers/FileRead.h>
#if MESH_ENABLE_FLEET_CONTROL
@@ -1524,6 +1525,7 @@ uint32_t MyMesh::getDirectRetryAttemptStepMillis() const {
}
bool MyMesh::allowDirectRetry(const mesh::Packet* packet, const uint8_t* next_hop_hash, uint8_t next_hop_hash_len) const {
if (_cli.morseReply().ownsReply(packet)) return false;
if (_prefs.disable_fwd && _prefs.trace_when_repeat_off != 1 && packet
&& packet->isRouteDirect() && packet->getPayloadType() == PAYLOAD_TYPE_TRACE
&& packet->path_len > 0) return false;
@@ -2066,6 +2068,7 @@ MyMesh::FloodRetryBridgeState* MyMesh::floodRetryBridgeStateFor(const mesh::Pack
}
bool MyMesh::allowFloodRetry(const mesh::Packet* packet) const {
if (_cli.morseReply().ownsReply(packet)) return false;
if (_prefs.disable_fwd || constrain(_prefs.flood_retry_attempts, 0, 15) == 0) {
return false;
}
@@ -3053,7 +3056,10 @@ bool MyMesh::sendRemoteCliReply(ClientInfo* client, const uint8_t* secret,
// Prepare before admission so Dispatcher can register its second copy;
// the caller arms the barrier only after admission succeeds.
const bool allow_redundant_copies = queued_packet == NULL;
if (!allow_redundant_copies) temp_radio_reply_barrier.prepare(packet);
if (!allow_redundant_copies) {
if (_cli.morseReply().pending()) _cli.morseReply().prepareReply(packet);
else temp_radio_reply_barrier.prepare(packet);
}
const bool queued = sendClientReplyWithFallbackScope(
client, packet, CLI_REPLY_DELAY_MILLIS, path_hash_size, fallback_scope,
allow_redundant_copies);
@@ -3266,6 +3272,7 @@ void __attribute__((noinline)) MyMesh::processDeferredCliCommand() {
}
const uint32_t primary_mutation_before = primary_radio_mutation_generation;
const uint32_t secondary_mutation_before = _cli.radioProfiles().replyMutationGeneration();
const uint32_t morse_mutation_before = _cli.morseReply().generation();
// setperm may compact the ACL, including removal of this sender. Keep the
// authenticated pre-command destination/path as a fallback if it is removed.
// Command permission checks still use the live ACL entry below.
@@ -3325,10 +3332,12 @@ void __attribute__((noinline)) MyMesh::processDeferredCliCommand() {
} else {
#endif
_cli.radioProfiles().beginReplyCommand();
_cli.morseReply().beginCommand(client->id.pub_key);
handleCommand(deferred_cli_command.sender_timestamp, client,
deferred_cli_command.command, reply, client_index,
deferred_cli_command.path_hash_size);
_cli.radioProfiles().endReplyCommand();
_cli.morseReply().endCommand();
#if MESH_ENABLE_HOST_CLI
}
#endif
@@ -3340,6 +3349,7 @@ void __attribute__((noinline)) MyMesh::processDeferredCliCommand() {
const bool arms_primary_radio = primary_radio_mutation_generation != primary_mutation_before;
const bool arms_secondary_radio = _cli.radioProfiles().replyMutationGeneration() != secondary_mutation_before;
const bool arms_temp_radio = arms_primary_radio || arms_secondary_radio;
const bool arms_morse = _cli.morseReply().generation() != morse_mutation_before;
const char* parsed_command = deferred_cli_command.command;
if (strlen(parsed_command) > 3 && parsed_command[2] == '|') parsed_command += 3;
const bool private_key_backup = strncmp(parsed_command, "backup prv.key ", 15) == 0;
@@ -3348,7 +3358,7 @@ void __attribute__((noinline)) MyMesh::processDeferredCliCommand() {
if (!private_key_backup) {
remote_cli_reply_cache.remember(deferred_cli_command.client_pub_key,
deferred_cli_command.request_id,
command_fingerprint, reply, arms_temp_radio);
command_fingerprint, reply, arms_temp_radio || arms_morse);
}
// Route changes made by this command must apply to its acknowledgement too.
// Resolve the full authenticated key again: compaction may have moved it or
@@ -3362,7 +3372,8 @@ void __attribute__((noinline)) MyMesh::processDeferredCliCommand() {
deferred_cli_command.path_hash_size,
deferred_cli_command.sender_timestamp, reply,
deferred_cli_reply_scoped ? &deferred_cli_reply_scope : NULL,
arms_temp_radio ? &queued_reply : NULL);
(arms_temp_radio || arms_morse) ? &queued_reply : NULL);
if (arms_morse) _cli.morseReply().armReply(queued_reply, reply_queued);
if (arms_temp_radio) {
radio_reply_secondary = arms_secondary_radio;
if (reply_queued && queued_reply != NULL) {
@@ -4176,6 +4187,7 @@ bool MyMesh::sendRepeatersFloodText(const char* text, const TransportKey* scope,
void MyMesh::onSendComplete(mesh::Packet* packet) {
mesh::Mesh::onSendComplete(packet);
_cli.morseReply().complete(packet);
#if MESH_ENABLE_FLEET_CONTROL
if (_cli.fleetChannel()) _cli.fleetChannel()->complete(packet, _cli.radioProfiles());
#endif
@@ -4193,11 +4205,13 @@ void MyMesh::onRadioProfileCopyQueued(mesh::Packet* packet, const mesh::Packet*
if (_cli.fleetChannel()) _cli.fleetChannel()->copy(packet, original);
#endif
temp_radio_reply_barrier.trackCopy(original, packet);
_cli.morseReply().copy(original, packet);
mesh::Mesh::onRadioProfileCopyQueued(packet, original, priority);
}
void MyMesh::onSendFail(mesh::Packet* packet) {
mesh::Mesh::onSendFail(packet);
_cli.morseReply().fail(packet);
#if MESH_ENABLE_FLEET_CONTROL
if (_cli.fleetChannel()) _cli.fleetChannel()->fail(packet, _cli.radioProfiles());
#endif
@@ -5186,6 +5200,14 @@ uint32_t MyMesh::getPowerSaveSleepSeconds(uint32_t max_secs) const {
sleep_secs = limitSleepToMillisTimer(next_battery_alert_check, sleep_secs);
}
sleep_secs = limitSleepToScheduledRadioWork(sleep_secs);
#if defined(WITH_RS232_BRIDGE)
if (bridge && rs232BridgeEnabled()) {
// Floor the deadline, not ceil: the ESP32 timed-light-sleep API uses whole
// seconds and must never sleep past a UART rendezvous or cleanup retry.
const uint32_t bridge_sleep_secs = bridge->powerWakeDelayMs(millis()) / 1000UL;
if (bridge_sleep_secs < sleep_secs) sleep_secs = bridge_sleep_secs;
}
#endif
return sleep_secs;
}
@@ -12250,6 +12272,16 @@ void MyMesh::handleCommand(uint32_t sender_timestamp, ClientInfo* sender, char *
// Compatibility path for manually defined legacy portable builds. Current
// release builds use FULL and do not enter this branch.
// Keep the same permissions as the normal handoff below. In particular,
// RF test/Morse commands must never bypass admin checks in a legacy build.
if (sender && !sender->isAdmin()) {
bool allowed = (sender->isRegionMgr() && isRegionMgrAllowed(command))
|| (sender->isFilterMgr() && isFilterMgrAllowed(command));
if (!allowed) {
strcpy(reply, "Err - not permitted");
return;
}
}
_cli.handleCommand(sender_timestamp, command, reply);
#if defined(WITH_WEBCONFIG) || defined(ETHERNET_ENABLED)
if (_command_output && _local_cli_output.owns(*_command_output)) reply[0] = 0;
@@ -13099,6 +13131,17 @@ void MyMesh::sampleTelemetryHistory() {
#endif
void __attribute__((noinline)) MyMesh::servicePostMeshLoop() {
if (mesh::morseTimingActive(_radio)) {
// RS232 heartbeat/wake servicing remains live; only optional periodic,
// sensor, filesystem and UI/network background work is deferred.
#if defined(WITH_RS232_BRIDGE)
serviceRs232BridgePower();
#endif
const uint32_t now = millis();
uptime_millis += now - last_millis;
last_millis = now;
return;
}
if (pending_self_advert) {
const uint32_t delay_millis = pending_self_advert_delay;
const bool flood = pending_self_advert_flood;
@@ -13135,7 +13178,7 @@ void __attribute__((noinline)) MyMesh::servicePostMeshLoop() {
#endif
#endif
#if defined(WITH_RS232_BRIDGE)
if (isRs232BridgeRunning()) bridge->loop();
serviceRs232BridgePower();
#elif defined(WITH_BRIDGE) && !defined(WITH_MQTT_BRIDGE) \
&& !defined(WITH_ESPNOW_BRIDGE)
AbstractBridge* active_bridge = activeBridge();
@@ -13897,6 +13940,12 @@ bool MyMesh::hasPendingWork() const {
#if defined(WITH_MQTT_BRIDGE) && defined(WITH_RS232_BRIDGE)
if (isRs232BridgeRunning()) return true;
#endif
#if defined(WITH_RS232_BRIDGE)
// A partial GPS release/claim is not a completed standby. Never allow MCU
// sleep while its UART ownership remains unresolved, even if end stopped RX.
if (active_rs232_bridge_uart != 0) return true;
if (bridge && rs232BridgeEnabled() && bridge->powerWakeDelayMs(millis()) == 0) return true;
#endif
#if defined(WITH_ESPNOW_BRIDGE) \
&& (defined(WITH_MQTT_BRIDGE) || defined(WITH_RS232_BRIDGE))
if (espnow_bridge.isRunning()) return true;
+62 -8
View File
@@ -1249,16 +1249,27 @@ public:
#ifdef WITH_RS232_BRIDGE
RS232Bridge* createRS232Bridge() {
RS232Bridge* created;
#ifdef WITH_RS232_BRIDGE_ALT
if (_prefs.bridge_uart == WITH_RS232_BRIDGE_ALT_UART) {
return new (std::nothrow) RS232Bridge(&_prefs, WITH_RS232_BRIDGE_ALT,
created = new (std::nothrow) RS232Bridge(&_prefs, WITH_RS232_BRIDGE_ALT,
WITH_RS232_BRIDGE_ALT_RX,
WITH_RS232_BRIDGE_ALT_TX, _mgr, getRTCClock());
}
} else
#endif
return new (std::nothrow) RS232Bridge(&_prefs, WITH_RS232_BRIDGE,
{
created = new (std::nothrow) RS232Bridge(&_prefs, WITH_RS232_BRIDGE,
WITH_RS232_BRIDGE_RX, WITH_RS232_BRIDGE_TX,
_mgr, getRTCClock());
}
if (created) {
// A new physical owner gets a new control session. Soft UART standby
// retains this object/session; a manual off/restart does not.
uint64_t session = 0;
getRNG()->random(reinterpret_cast<uint8_t*>(&session), sizeof(session));
created->setHeartbeatSession(session ? session : 1);
}
return created;
}
bool beginRS232Bridge() {
@@ -1300,7 +1311,9 @@ public:
}
bool endRS232Bridge() {
#if ENV_INCLUDE_GPS == 1
const uint8_t released_uart = active_rs232_bridge_uart;
#endif
bool stopped = true;
// A fail-closed preflight can reject this object before begin() touches
// its UART. Adafruit nRF Uart::end() is not safe as a generic cleanup for
@@ -1335,6 +1348,47 @@ public:
return bridge && bridge->isRunning();
}
void serviceRs232BridgePower() {
if (!bridge) return;
// Poll only once, before evaluating liveness. The policy must still run
// when UART is stopped, or two sleeping peers can never rendezvous.
bridge->setHeartbeatEnabled(_prefs.rs232_heartbeat == 1);
if (bridge->isRunning()) bridge->loop();
if (!rs232BridgeEnabled()) return;
const uint32_t now = millis();
const RS232Bridge::PowerAction action = bridge->servicePowerPolicy(
(_prefs.rs232_autosleep == 1 || _prefs.rs232_autosleep == 2)
&& _prefs.powersaving_enabled != 0
&& _prefs.rs232_heartbeat == 1,
static_cast<uint32_t>(_prefs.rs232_idle_seconds) * 1000UL, now,
_prefs.rs232_autosleep == 2);
if (action == RS232Bridge::PowerAction::None) return;
bool success;
if (action == RS232Bridge::PowerAction::Suspend) {
// An end may stop UART but fail to release GPS ownership. The driver
// stays in cleanup/retry until both physical owners confirm success.
success = endRS232Bridge();
} else {
// A failed earlier start may have yielded GPS before UART begin failed.
// Release any partial ownership before trying to claim it again.
success = (active_rs232_bridge_uart == 0 || endRS232Bridge())
&& beginRS232Bridge();
}
bridge->completePowerAction(action, success, millis());
}
void formatRs232Status(char* reply) override {
char heartbeat[84];
if (bridge) bridge->formatHeartbeatStatus(heartbeat, sizeof(heartbeat), millis());
else StrHelper::strncpy(heartbeat, "phase=off peer=unknown", sizeof(heartbeat));
snprintf(reply, 160, "saved=%s running=%s heartbeat=%s autosleep=%s idle=%us %s",
rs232BridgeEnabled() ? "on" : "off",
isRs232BridgeRunning() ? "on" : "off",
_prefs.rs232_heartbeat == 1 ? "on" : "off",
_prefs.rs232_autosleep == 2 ? "force" : _prefs.rs232_autosleep == 1 ? "on" : "off",
static_cast<unsigned>(_prefs.rs232_idle_seconds), heartbeat);
}
bool setRs232BridgeState(bool enable) override {
if (!enable) {
const bool stopped = endRS232Bridge();
@@ -1347,7 +1401,10 @@ public:
if (isRs232BridgeRunning()) return true;
// Retry any tracked GPS release before constructing a new UART owner.
if (active_rs232_bridge_uart != 0 && !endRS232Bridge()) return false;
if (!bridge) bridge = createRS232Bridge();
// Explicit enable is a fresh owner, including when soft standby retained
// the previous one. It must not inherit a dormant heartbeat deadline.
delete bridge;
bridge = createRS232Bridge();
return bridge && beginRS232Bridge();
}
@@ -1526,10 +1583,7 @@ public:
}
#endif
#if defined(WITH_RS232_BRIDGE) && !defined(WITH_MQTT_BRIDGE)
if (enable && !bridge) {
bridge = createRS232Bridge();
if (!bridge) return false;
}
if (enable) return setRs232BridgeState(true);
if (!enable) {
const bool stopped = endRS232Bridge();
if (stopped) {
+3 -1
View File
@@ -2,6 +2,7 @@
#include "target.h"
#include <Arduino.h>
#include <helpers/UsbLogging.h>
#include <helpers/MorseLoopPolicy.h>
#include <helpers/CommonCLI.h>
#include <helpers/ui/WiFiSetupQrDisplay.h>
#include <helpers/ui/CompanionHomeLayout.h>
@@ -844,6 +845,7 @@ void UITask::toggleDisplay(const char* source) {
#endif
void UITask::loop() {
const bool morse_timing = mesh::morseTimingActive(the_mesh.getProfileRadio());
if (_display->servicePower(board.isExternalPowered() || board.isUsbHostConnected())) {
if (_display->isOn()) resetRadioProfileDisplayPage();
_next_refresh = 0;
@@ -909,7 +911,7 @@ void UITask::loop() {
}
#endif
if (_display->isOn()) {
if (!morse_timing && _display->isOn()) {
// Apply a live orientation change before drawing, including the first frame
// after a preference was changed while the panel was blanked.
applyDisplayFlip();
+5 -2
View File
@@ -5,6 +5,7 @@
#include <helpers/ui/DisplayPowerSettings.h>
#include <helpers/UsbLoggingWatchdog.h>
#include <helpers/UsbLoggingClientActivity.h>
#include <helpers/MorseLoopPolicy.h>
#include <helpers/HilStartupTrace.h>
#if MESH_PACKET_LOGGING
#include <helpers/SerialPacketLog.h>
@@ -575,7 +576,8 @@ void loop() {
#endif
the_mesh.loop();
sensors.loop();
const bool morse_timing = mesh::morseTimingActive(&radio_driver);
if (!morse_timing) sensors.loop();
#ifdef DISPLAY_CLASS
if (display_ready) ui_task.loop();
#endif
@@ -593,6 +595,7 @@ void loop() {
external_watchdog.loop();
#endif
bool can_power_save = the_mesh.getNodePrefs()->powersaving_enabled
&& !morse_timing
&& !board.isUsbDataConnected()
&& !mesh::isUsbLoggingWatchdogArmed()
&& !mesh::wireless::control().pending();
@@ -621,7 +624,7 @@ void loop() {
}
#if defined(ESP32_PLATFORM)
if (!can_power_save && the_mesh.getNodePrefs()->powersaving_enabled) {
if (!morse_timing && !can_power_save && the_mesh.getNodePrefs()->powersaving_enabled) {
delay(1); // Idle without suspending USB or the button wake interval.
}
#endif
+36 -5
View File
@@ -21,6 +21,7 @@
#include <helpers/ClientACLCLI.h>
#include <helpers/ClientACLResponse.h>
#include <helpers/sensors/LPPDataHelpers.h>
#include <helpers/MorseLoopPolicy.h>
#include <helpers/ClientLoginPersistence.h>
#include <helpers/RoomLoginAuthorization.h>
#include <helpers/RoomTopicStore.h>
@@ -1568,6 +1569,7 @@ uint32_t MyMesh::getDirectRetransmitDelay(const mesh::Packet *packet) {
bool MyMesh::allowDirectRetry(const mesh::Packet* packet, const uint8_t* next_hop_hash,
uint8_t next_hop_hash_len) const {
if (_cli.morseReply().ownsReply(packet)) return false;
(void)packet;
(void)next_hop_hash;
(void)next_hop_hash_len;
@@ -1600,6 +1602,7 @@ uint32_t MyMesh::getDirectRetryAttemptDelay(const mesh::Packet* packet, uint8_t
}
bool MyMesh::allowFloodRetry(const mesh::Packet* packet) const {
if (_cli.morseReply().ownsReply(packet)) return false;
if (_prefs.disable_fwd || _prefs.flood_retry_attempts == 0) return false;
if (packet != NULL
&& packet->flood_retry_policy == mesh::FLOOD_RETRY_POLICY_DENY) {
@@ -1947,6 +1950,7 @@ void MyMesh::onPeerDataRecv(mesh::Packet *packet, uint8_t type, int sender_idx,
uint8_t temp[5 + mesh::RemoteCliReplyCache::MAX_REPLY_TEXT + 1];
temp[5] = 0;
bool send_ack = false;
const uint32_t morse_mutation_before = _cli.morseReply().generation();
if (flags == TXT_TYPE_PLAIN) {
const uint8_t role = client->permissions & PERM_ACL_ROLE_MASK;
@@ -1978,9 +1982,10 @@ void MyMesh::onPeerDataRecv(mesh::Packet *packet, uint8_t type, int sender_idx,
const uint32_t command_fingerprint =
mesh::RemoteCliReplyCache::fingerprint(text, text_len);
const char* cached_response = NULL;
bool cached_authoritative_reply = false;
const bool cached_retry = remote_cli_reply_cache.lookup(
client->id.pub_key, request_id, command_fingerprint,
&cached_response);
&cached_response, &cached_authoritative_reply);
if (sender_timestamp < client->last_timestamp && !cached_retry) {
MESH_DEBUG_PRINTLN("onPeerDataRecv: possible replay attack detected");
@@ -2010,6 +2015,10 @@ void MyMesh::onPeerDataRecv(mesh::Packet *packet, uint8_t type, int sender_idx,
if (cached_retry && !client->isAdmin() && !own_path_allowed) {
strcpy((char*)&temp[5], "Err - admin permission required");
temp[4] = (TXT_TYPE_CLI_DATA << 2);
} else if (cached_retry && cached_authoritative_reply) {
// Only the original exact response owns the listen barrier. Do not
// replay a success-looking handoff reply after failure/cancellation.
return;
} else if (cached_retry) {
MESH_DEBUG_PRINTLN("onPeerDataRecv: replaying cached remote CLI reply");
size_t cached_len = strlen(cached_response);
@@ -2028,8 +2037,10 @@ void MyMesh::onPeerDataRecv(mesh::Packet *packet, uint8_t type, int sender_idx,
&& !handleRoomMailClientCommand(client, text, request_id, (char*)&temp[5],
mesh::RemoteCliReplyCache::MAX_REPLY_TEXT + 1)) {
if (client->isAdmin()) {
_cli.morseReply().beginCommand(client->id.pub_key);
handleCommand(sender_timestamp, (char*)text, (char*)&temp[5],
i, packet->getPathHashSize());
_cli.morseReply().endCommand();
} else {
strcpy((char*)&temp[5], "Err - admin permission required");
}
@@ -2038,7 +2049,8 @@ void MyMesh::onPeerDataRecv(mesh::Packet *packet, uint8_t type, int sender_idx,
if (temp[5] == 0) strcpy((char*)&temp[5], "OK");
remote_cli_reply_cache.remember(client->id.pub_key, request_id,
command_fingerprint,
(char*)&temp[5]);
(char*)&temp[5],
_cli.morseReply().generation() != morse_mutation_before);
temp[4] = (TXT_TYPE_CLI_DATA << 2);
}
// CLI_DATA replies are the result signal; no separate ACK is expected.
@@ -2088,7 +2100,16 @@ void MyMesh::onPeerDataRecv(mesh::Packet *packet, uint8_t type, int sender_idx,
auto reply = createDatagram(PAYLOAD_TYPE_TXT_MSG, client->id, secret,
temp, 5 + reply_text_len);
if (reply) {
if (_cli.morseReply().generation() != morse_mutation_before) {
// One first copy per radio profile, without alternate paths/retries
// that could remain queued after the listen handoff.
_cli.morseReply().prepareReply(reply);
if (reply) reply->radio_reply = true;
const bool queued = reply && (!mesh::Packet::isValidPathLen(client->out_path_len)
? sendFloodReply(reply, delay_millis + SERVER_RESPONSE_DELAY, packet->getPathHashSize())
: sendDirect(reply, client->out_path, client->out_path_len, delay_millis + SERVER_RESPONSE_DELAY));
_cli.morseReply().armReply(reply, queued);
} else if (reply) {
sendClientReply(client, reply, delay_millis + SERVER_RESPONSE_DELAY,
packet->getPathHashSize());
}
@@ -2264,24 +2285,31 @@ void MyMesh::onGroupPacketRecv(mesh::Packet* packet) {
_clock_sync.observeGroupPacket(packet);
}
#if MESH_ENABLE_FLEET_CONTROL
void MyMesh::onSendComplete(mesh::Packet* packet) {
mesh::Mesh::onSendComplete(packet);
_cli.morseReply().complete(packet);
#if MESH_ENABLE_FLEET_CONTROL
if (_cli.fleetChannel()) _cli.fleetChannel()->complete(packet, _cli.radioProfiles());
#endif
}
void MyMesh::onSendFail(mesh::Packet* packet) {
mesh::Mesh::onSendFail(packet);
_cli.morseReply().fail(packet);
#if MESH_ENABLE_FLEET_CONTROL
if (_cli.fleetChannel()) _cli.fleetChannel()->fail(packet, _cli.radioProfiles());
#endif
}
void MyMesh::onRadioProfileCopyQueued(mesh::Packet* packet,
const mesh::Packet* original,
uint8_t priority) {
mesh::Mesh::onRadioProfileCopyQueued(packet, original, priority);
_cli.morseReply().copy(original, packet);
#if MESH_ENABLE_FLEET_CONTROL
if (_cli.fleetChannel()) _cli.fleetChannel()->copy(packet, original);
}
#endif
}
#if defined(WITH_MQTT_NEIGHBORS)
@@ -3846,6 +3874,9 @@ void MyMesh::loop() {
servicePendingSerialOutput();
#endif
_cli.loop();
// Keep the radio and command/reply queues responsive while a Morse session
// owns RF. Deferred periodic work retains its deadlines and resumes after.
if (mesh::morseTimingActive(_radio)) return;
#if MESH_ENABLE_FLEET_CONTROL
if (_cli.fleetChannel()) {
_cli.fleetChannel()->service(*this, _cli.radioProfiles(), _prefs.node_name,
-2
View File
@@ -448,12 +448,10 @@ protected:
void onAckRecv(mesh::Packet* packet, uint32_t ack_crc) override;
void onAdvertRecv(mesh::Packet* packet, const mesh::Identity& id, uint32_t timestamp, const uint8_t* app_data, size_t app_data_len) override;
void onGroupPacketRecv(mesh::Packet* packet) override;
#if MESH_ENABLE_FLEET_CONTROL
void onSendComplete(mesh::Packet* packet) override;
void onSendFail(mesh::Packet* packet) override;
void onRadioProfileCopyQueued(mesh::Packet* packet, const mesh::Packet* original,
uint8_t priority) override;
#endif
#if defined(WITH_MQTT_NEIGHBORS)
void onControlDataRecv(mesh::Packet* packet) override;
#endif
+3 -1
View File
@@ -1,4 +1,5 @@
#include "UITask.h"
#include <helpers/MorseLoopPolicy.h>
#include "target.h"
#include <Arduino.h>
#include <helpers/UsbLogging.h>
@@ -495,6 +496,7 @@ void UITask::toggleDisplay(const char* source) {
#endif
void UITask::loop() {
const bool morse_timing = mesh::morseTimingActive(the_mesh.getProfileRadio());
if (_display->servicePower(board.isExternalPowered() || board.isUsbHostConnected())) {
resetRadioProfileDisplayPage();
_next_refresh = 0;
@@ -582,7 +584,7 @@ void UITask::loop() {
}
#endif
if (_display->isOn()) {
if (!morse_timing && _display->isOn()) {
// Apply a live orientation change before drawing, including the first frame
// after a preference was changed while the panel was blanked.
applyDisplayFlip();
+5 -2
View File
@@ -5,6 +5,7 @@
#include <helpers/ui/DisplayPowerSettings.h>
#include <helpers/UsbLoggingWatchdog.h>
#include <helpers/UsbLoggingClientActivity.h>
#include <helpers/MorseLoopPolicy.h>
#if MESH_PACKET_LOGGING
#include <helpers/SerialPacketLog.h>
#endif
@@ -331,7 +332,8 @@ void loop() {
#endif
the_mesh.loop();
sensors.loop();
const bool morse_timing = mesh::morseTimingActive(&radio_driver);
if (!morse_timing) sensors.loop();
#ifdef DISPLAY_CLASS
if (display_ready) ui_task.loop();
#endif
@@ -348,6 +350,7 @@ void loop() {
external_watchdog.loop();
#endif
bool can_power_save = the_mesh.getNodePrefs()->powersaving_enabled
&& !morse_timing
&& !board.isUsbDataConnected()
&& !mesh::isUsbLoggingWatchdogArmed()
&& !mesh::wireless::control().pending();
@@ -372,7 +375,7 @@ void loop() {
#endif
}
#if defined(ESP32_PLATFORM)
if (!can_power_save && the_mesh.getNodePrefs()->powersaving_enabled) {
if (!morse_timing && !can_power_save && the_mesh.getNodePrefs()->powersaving_enabled) {
delay(1); // Keep USB and the button wake interval serviced while idle.
}
#endif
+37 -3
View File
@@ -8,6 +8,7 @@
#include <helpers/RoutingPolicy.h>
#include <helpers/radiolib/RXPowerSaving.h>
#include <helpers/sensors/LPPDataHelpers.h>
#include <helpers/MorseLoopPolicy.h>
#include <helpers/UsbLogging.h>
#if defined(ENABLE_OTA)
#include <helpers/ota/OtaContext.h>
@@ -442,6 +443,7 @@ uint32_t SensorMesh::getDirectRetransmitDelay(const mesh::Packet* packet) {
bool SensorMesh::allowDirectRetry(const mesh::Packet* packet, const uint8_t* next_hop_hash,
uint8_t next_hop_hash_len) const {
if (_cli.morseReply().ownsReply(packet)) return false;
#if MESH_ENABLE_SENSOR_TRACKER
if (tracker_pending && packet != NULL) {
uint8_t hash[MAX_HASH_SIZE];
@@ -481,6 +483,7 @@ uint32_t SensorMesh::getDirectRetryAttemptDelay(const mesh::Packet* packet, uint
}
bool SensorMesh::allowFloodRetry(const mesh::Packet* packet) const {
if (_cli.morseReply().ownsReply(packet)) return false;
if (packet != NULL && packet->flood_retry_policy == mesh::FLOOD_RETRY_POLICY_DENY) return false;
if (_prefs.disable_fwd || _prefs.flood_retry_attempts == 0) return false;
return packet == NULL || packet->getPayloadType() != PAYLOAD_TYPE_ADVERT
@@ -1018,8 +1021,11 @@ void SensorMesh::onPeerDataRecv(mesh::Packet* packet, uint8_t type, int sender_i
char *command = (char *) &data[5];
char *reply = (char *) &temp[5];
*reply = 0;
const uint32_t morse_mutation_before = _cli.morseReply().generation();
_cli.morseReply().beginCommand(from->id.pub_key);
handleCommand(sender_timestamp, command, reply, i,
packet->getPathHashSize());
_cli.morseReply().endCommand();
int text_len = strlen(reply);
if (text_len > 0) {
@@ -1032,13 +1038,20 @@ void SensorMesh::onPeerDataRecv(mesh::Packet* packet, uint8_t type, int sender_i
temp[4] = (TXT_TYPE_CLI_DATA << 2);
auto reply = createDatagram(PAYLOAD_TYPE_TXT_MSG, from->id, secret, temp, 5 + text_len);
const bool arms_morse = _cli.morseReply().generation() != morse_mutation_before;
if (arms_morse) {
_cli.morseReply().prepareReply(reply);
if (reply) reply->radio_reply = true;
}
bool queued = false;
if (reply) {
if (!mesh::Packet::isValidPathLen(from->out_path_len)) {
sendFloodReply(reply, CLI_REPLY_DELAY_MILLIS, packet->getPathHashSize());
queued = sendFloodReply(reply, CLI_REPLY_DELAY_MILLIS, packet->getPathHashSize());
} else {
sendDirect(reply, from->out_path, from->out_path_len, CLI_REPLY_DELAY_MILLIS);
queued = sendDirect(reply, from->out_path, from->out_path_len, CLI_REPLY_DELAY_MILLIS);
}
}
if (arms_morse) _cli.morseReply().armReply(reply, queued);
}
} else {
MESH_DEBUG_PRINTLN("onPeerDataRecv: unsupported text type received: flags=%02x", (uint32_t)flags);
@@ -1061,6 +1074,24 @@ bool SensorMesh::handleIncomingMsg(ClientInfo& from, uint32_t timestamp, uint8_t
return false;
}
#if !MESH_ENABLE_SENSOR_TRACKER
void SensorMesh::onSendComplete(mesh::Packet* packet) {
mesh::Mesh::onSendComplete(packet);
_cli.morseReply().complete(packet);
}
void SensorMesh::onSendFail(mesh::Packet* packet) {
mesh::Mesh::onSendFail(packet);
_cli.morseReply().fail(packet);
}
#endif
void SensorMesh::onRadioProfileCopyQueued(mesh::Packet* packet,
const mesh::Packet* original, uint8_t priority) {
_cli.morseReply().copy(original, packet);
mesh::Mesh::onRadioProfileCopyQueued(packet, original, priority);
}
#define CTL_TYPE_NODE_DISCOVER_REQ 0x80
#define CTL_TYPE_NODE_DISCOVER_RESP 0x90
@@ -1437,10 +1468,13 @@ bool SensorMesh::getGPS(uint8_t channel, float& lat, float& lon, float& alt) {
void SensorMesh::loop() {
#if MESH_ENABLE_SENSOR_TRACKER
if (tracker.enabled && trackerNeedsRadio()) wakeTrackerRadio();
if (!mesh::morseTimingActive(_radio) && tracker.enabled && trackerNeedsRadio()) wakeTrackerRadio();
#endif
_cli.loop();
mesh::Mesh::loop();
// Do not consume sensor/advert/write deadlines during timed Morse capture.
// USB command service and the physical radio continue on every pass.
if (mesh::morseTimingActive(_radio)) return;
_clock_sync.loop();
#if MESH_ENABLE_SENSOR_TRACKER
serviceTracker();
+2 -2
View File
@@ -218,10 +218,10 @@ protected:
bool onPeerPathRecv(mesh::Packet* packet, int sender_idx, const uint8_t* secret, uint8_t* path, uint8_t path_len, uint8_t extra_type, uint8_t* extra, uint8_t extra_len) override;
void onControlDataRecv(mesh::Packet* packet) override;
void onAckRecv(mesh::Packet* packet, uint32_t ack_crc) override;
#if MESH_ENABLE_SENSOR_TRACKER
void onSendComplete(mesh::Packet* packet) override;
void onSendFail(mesh::Packet* packet) override;
#endif
void onRadioProfileCopyQueued(mesh::Packet* packet, const mesh::Packet* original,
uint8_t priority) override;
void onAdvertRecv(mesh::Packet* packet, const mesh::Identity& id,
uint32_t timestamp, const uint8_t* app_data,
size_t app_data_len) override;
+2
View File
@@ -266,6 +266,7 @@ bool SensorMesh::handleTrackerPath(mesh::Packet* packet, uint8_t* path, uint8_t
void SensorMesh::onSendComplete(mesh::Packet* packet) {
mesh::Mesh::onSendComplete(packet);
_cli.morseReply().complete(packet);
if (!tracker_pending || !packet || packet->getPayloadType() != PAYLOAD_TYPE_REQ) return;
uint8_t hash[MAX_HASH_SIZE];
packet->calculatePacketHash(hash);
@@ -277,6 +278,7 @@ void SensorMesh::onSendComplete(mesh::Packet* packet) {
void SensorMesh::onSendFail(mesh::Packet* packet) {
mesh::Mesh::onSendFail(packet);
_cli.morseReply().fail(packet);
if (!tracker_pending || !packet) return;
uint8_t hash[MAX_HASH_SIZE];
packet->calculatePacketHash(hash);
+3 -1
View File
@@ -1,4 +1,5 @@
#include "UITask.h"
#include <helpers/MorseLoopPolicy.h>
#include "target.h"
#include <Arduino.h>
#include <helpers/CommonCLI.h>
@@ -204,6 +205,7 @@ void UITask::renderCurrScreen() {
}
void UITask::loop() {
const bool morse_timing = mesh::morseTimingActive(activeSensorMesh().getProfileRadio());
if (_display->servicePower(board.isExternalPowered() || board.isUsbHostConnected())) {
resetRadioProfileDisplayPage();
_next_refresh = 0;
@@ -239,7 +241,7 @@ void UITask::loop() {
}
#endif
if (_display->isOn()) {
if (!morse_timing && _display->isOn()) {
if (millis() >= _next_refresh) {
_display->startFrame();
renderCurrScreen();
+5 -2
View File
@@ -10,6 +10,7 @@
#include <helpers/UsbLogging.h>
#include <helpers/UsbLoggingWatchdog.h>
#include <helpers/UsbLoggingClientActivity.h>
#include <helpers/MorseLoopPolicy.h>
#if defined(NRF52_PLATFORM) && MESH_ENABLE_SENSOR_TRACKER
#include <utility/SoftwareTimer.h>
static SoftwareTimer tracker_wake_timer;
@@ -327,7 +328,8 @@ void loop() {
board.loop(); // let the board feed its watchdog, run periodic housekeeping
the_mesh.loop();
sensors.loop();
const bool morse_timing = mesh::morseTimingActive(&radio_driver);
if (!morse_timing) sensors.loop();
#ifdef DISPLAY_CLASS
if (display_ready) ui_task.loop();
#endif
@@ -342,6 +344,7 @@ void loop() {
bool can_power_save = (the_mesh.getNodePrefs()->powersaving_enabled
|| the_mesh.isTrackerModeEnabled())
&& !morse_timing
&& !board.isUsbDataConnected()
&& !mesh::isUsbLoggingWatchdogArmed();
#if defined(MOMENTARY_BUTTON_WAKE_FROM_SLEEP) \
@@ -372,7 +375,7 @@ void loop() {
#endif
}
#if defined(ESP32_PLATFORM)
if (!can_power_save && (the_mesh.getNodePrefs()->powersaving_enabled
if (!morse_timing && !can_power_save && (the_mesh.getNodePrefs()->powersaving_enabled
|| the_mesh.isTrackerModeEnabled())) {
delay(1); // Keep USB and the button wake interval serviced while idle.
}