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

+79
View File
@@ -0,0 +1,79 @@
; Companion applications, with no automatic RF at boot. LoRa control uses the
; lab tuple 909.5/500/SF5/CR5; Morse uses its separate 902.100 MHz default.
; The 255 WPM override is EXPERIMENTAL, never a release or measured guarantee.
[env:morse_bench_rak4631_companion]
extends = env:RAK_4631_companion_radio_usb
build_unflags =
${nrf52_base.build_unflags}
-D LORA_FREQ=869.618
-D ENABLE_ADVERT_ON_BOOT=1
build_flags = ${env:RAK_4631_companion_radio_usb.build_flags}
-DLORA_FREQ=909.5
-DENABLE_ADVERT_ON_BOOT=0
-DMESH_MORSE_MAX_WPM=255
-DMESH_MORSE_HIL=1
-DMESH_MORSE_HIL_WARM_TX=1
-DMESH_MORSE_HIL_RSSI_WINDOW=2
-DMESH_MORSE_HIL_PA_RAMP_US=800
-DMESH_MORSE_HIL_SAMPLE_INTERVAL_MS=1
-DMESH_MORSE_HIL_PACKET_GATING=0
-DMESH_MORSE_HIL_FAST_OFF_DEBOUNCE=1
-DCOMPANION_FEATURE_TEMP_RADIO=1
build_src_filter = ${env:RAK_4631_companion_radio_usb.build_src_filter}
+<helpers/nrf52/SerialBLEInterface.cpp>
[env:morse_bench_t096_companion]
extends = env:Heltec_t096_companion_radio_usb_femon
build_unflags =
${nrf52_base.build_unflags}
-D LORA_FREQ=869.618
-D ENABLE_ADVERT_ON_BOOT=1
build_flags = ${env:Heltec_t096_companion_radio_usb_femon.build_flags}
-DMESH_CONTACT_CACHE=1
-DLORA_FREQ=909.5
-DENABLE_ADVERT_ON_BOOT=0
-DMESH_MORSE_MAX_WPM=255
-DMESH_MORSE_HIL=1
-DMESH_MORSE_HIL_WARM_TX=1
-DMESH_MORSE_HIL_RSSI_WINDOW=2
-DMESH_MORSE_HIL_PA_RAMP_US=800
-DMESH_MORSE_HIL_PACKET_GATING=0
-DMESH_MORSE_HIL_FAST_OFF_DEBOUNCE=1
-DCOMPANION_FEATURE_TEMP_RADIO=1
; Additional identity-bound SX1262 pair with its normal display retained.
[env:morse_bench_pocket_companion]
extends = env:Mesh_pocket_companion_radio_usb
build_unflags =
${nrf52_base.build_unflags}
-D LORA_FREQ=869.618
-D ENABLE_ADVERT_ON_BOOT=1
build_flags = ${env:Mesh_pocket_companion_radio_usb.build_flags}
-DMESH_CONTACT_CACHE=1
-DLORA_FREQ=909.5
-DENABLE_ADVERT_ON_BOOT=0
-DMESH_MORSE_MAX_WPM=255
-DMESH_MORSE_HIL=1
-DMESH_MORSE_HIL_WARM_TX=1
-DMESH_MORSE_HIL_RSSI_WINDOW=2
-DMESH_MORSE_HIL_PA_RAMP_US=800
-DMESH_MORSE_HIL_SAMPLE_INTERVAL_MS=1
-DMESH_MORSE_HIL_PACKET_GATING=0
-DMESH_MORSE_HIL_FAST_OFF_DEBOUNCE=1
-DCOMPANION_FEATURE_TEMP_RADIO=1
; Remote ACK-first capture/retrieval test; every packet uses the lab tuple.
[env:morse_bench_rak4631_repeater]
extends = env:RAK_4631_repeater
build_unflags =
${nrf52_base.build_unflags}
-D LORA_FREQ=869.618
-D LORA_BW=62.5
-D LORA_SF=8
-D ENABLE_ADVERT_ON_BOOT=1
build_flags = ${env:RAK_4631_repeater.build_flags}
-DLORA_FREQ=909.5
-DLORA_BW=500
-DLORA_SF=5
-DENABLE_ADVERT_ON_BOOT=0
-DMESH_MORSE_MAX_WPM=255
+333
View File
@@ -0,0 +1,333 @@
#!/usr/bin/env python3
"""Identity-bound Morse TX/RX trial at 902.1 MHz, low TX power.
No flashing, erasure, service stopping or power cycling. Received text comes
from the actual firmware's CLI capture pages, never a host-side decoder.
The active LoRa packet profile stays at 909.5 MHz, 500 kHz, SF5, CR5.
"""
import argparse
import json
import math
from pathlib import Path
import re
import time
import serial
from serial.tools import list_ports
SERIALS = {"rak": "9AB3B64C641BA927", "t096": "651F8E496197F882",
"pocket": "93DA83ADF7B2092B"}
DEFAULT_CW_FREQUENCY = 902.1
PACKET_RADIO = "909.5,500,5,5"
MESSAGES = (
"SOS TEST DE N0CALL 0123456789 ABCDEFGHIJKLMNOPQRSTUVWXYZ",
"E T I M S O H Z 5 0 PARIS QUICK BROWN FOX JUMPS OVER LAZY DOG",
". , ? ' ! / ( ) & : ; = + - _ \" $ @",
)
def parse_cw_frequency(text):
"""Keep CW in the lab band, clear of the 500 kHz packet RX bandwidth."""
try:
frequency = round(float(text), 6)
except (ValueError, TypeError, OverflowError):
raise argparse.ArgumentTypeError("CW frequency must be a finite MHz value") from None
if not math.isfinite(frequency) or not 902 <= frequency <= 928:
raise argparse.ArgumentTypeError("CW frequency must be between 902 and 928 MHz")
if abs(frequency - 909.5) <= .260 + 1e-9:
raise argparse.ArgumentTypeError("CW frequency overlaps the 909.5 MHz packet radio and guard")
return frequency
def live_temporary_profile(reply):
"""Parse only confirmed live profiles, never saved/pending radio settings."""
fields = r"(\d+(?:\.\d+)?),(\d+(?:\.\d+)?),(\d+),(\d+)"
companion = re.search(r"TempRadio active:\s*" + fields + r"(?=\s|$)", reply)
infrastructure = re.search(
r"(?m)^\s*(?:->\s*)?>\s*" + fields + r"(?:,\d+)?\s*$", reply)
match = companion or infrastructure
if match is None:
return None
return float(match[1]), float(match[2]), int(match[3]), int(match[4])
class Console:
def __init__(self, serial_number, companion=True):
matches = [p for p in list_ports.comports()
if (p.serial_number or "").upper() == serial_number
and p.interface != "MeshCore Logging"]
if len(matches) != 1:
raise RuntimeError(f"Missing/ambiguous application USB identity {serial_number}")
self.serial_number = serial_number
self.companion = companion
self.port = serial.Serial(port=None, baudrate=115200, timeout=.015)
self.port.dtr, self.port.rts = True, False
self.port.port = matches[0].device
self.port.open()
self.commands = []
try:
hello = self.read_quiet(1)
if companion and "WELCOME" not in hello:
self.port.write(b"+++MESHCORE-TERM-START\r\n")
self.read_quiet(1)
self.command("ver")
self.command("board")
except BaseException:
self.port.close()
raise
def read_quiet(self, timeout=2):
data = bytearray()
end = quiet = time.monotonic() + timeout
while time.monotonic() < end and time.monotonic() < quiet:
chunk = self.port.read(self.port.in_waiting or 1)
if chunk:
data.extend(chunk)
quiet = time.monotonic() + .12
return data.decode("utf-8", errors="replace")
def command(self, text, timeout=3, allow_error=False):
if self.port.in_waiting:
self.read_quiet(.15)
self.port.write((text + "\r\n").encode())
data = bytearray()
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
data.extend(self.port.read(self.port.in_waiting or 1))
reply = data.decode("utf-8", errors="replace")
# Flash writes/display callbacks can outlast a quiet interval.
# Await the command response AND its closing owned-terminal prompt,
# not merely an echoed command or asynchronous RX prompt redraw.
complete = reply.endswith("\r\n> ") if self.companion else reply.endswith("\r\n")
if (" -> " in reply or " ERROR:" in reply
or re.search(r"(?:^|\r\n) OK(?:\r\n| -)", reply)) and complete:
break
else:
raise RuntimeError(("Incomplete CLI response", self.serial_number, text,
data.decode("utf-8", errors="replace")))
self.commands.append({"command": text, "reply": reply})
if not reply or (not allow_error and re.search(r"\b(?:Error|ERROR|ERR)\b", reply)):
raise RuntimeError((self.serial_number, text, reply))
return reply
def setup(self, cw_frequency=DEFAULT_CW_FREQUENCY):
self.command("morse stop")
self.start_when_idle("set radio.rxps off")
self.start_when_idle("set tx -9")
self.start_when_idle("set radio2 off")
self.command(f"set morse.freq {cw_frequency:.6f}")
self.command("set morse.wpm 25")
self.apply_live_temporary(PACKET_RADIO)
def apply_live_temporary(self, profile, timeout=12):
expected = tuple(float(value) for value in profile.split(","))
if len(expected) != 4:
raise ValueError("Expected frequency, bandwidth, SF and CR")
self.start_when_idle("set tempradio " + profile + ",30")
deadline = time.monotonic() + timeout
while True:
reply = self.command("get tempradio")
if live_temporary_profile(reply) == expected:
return reply
if time.monotonic() >= deadline:
raise RuntimeError(("Live temporary radio did not apply", self.serial_number,
profile, reply))
time.sleep(.1)
def start_when_idle(self, text):
deadline = time.monotonic() + 10
while True:
reply = self.command(text, allow_error=True)
if "Error: radio busy" not in reply:
if re.search(r"\b(?:Error|ERROR|ERR)\b", reply):
raise RuntimeError((self.serial_number, text, reply))
return reply
if time.monotonic() >= deadline:
raise RuntimeError(("Radio remained busy", self.serial_number, text, reply))
time.sleep(.1)
def capture(self):
text, offset = "", 0
for _ in range(100):
# A valid text capture can itself contain ERROR; only the framed
# page parser can distinguish that payload from a CLI failure.
reply = self.command(f"morse read {offset}", allow_error=True)
page = re.search(
r"> (\d{4})/(\d{4}) next=(\d{4}|END ) truncated=(\d) ([^\r\n]*)",
reply)
if not page or int(page[1]) != offset or int(page[4]):
raise RuntimeError(("Malformed/truncated capture page", reply))
text += page[5]
if page[3].strip() == "END":
return text
following = int(page[3])
if following != len(text) or following <= offset:
raise RuntimeError(("Non-progressing capture", reply))
offset = following
raise RuntimeError("Capture paging did not finish")
def trace(self):
rows, offset, total = [], 0, None
for _ in range(100):
reply = self.command(f"morse trace {offset}")
page = re.search(r"> (\d{3})/(\d{3}) t=(\d+) n=(\d{3}|END) x=([01]) ([^\r\n]*)", reply)
if not page or int(page[1]) != offset:
raise RuntimeError(("Malformed trace page", reply))
if total is not None and total != int(page[3]):
raise RuntimeError("Trace changed during retrieval")
total = int(page[3])
for item in page[6].split(";"):
if item:
at, rssi, flags = map(int, item.split(","))
rows.append({"ms": at, "dbm": rssi, "flags": flags})
if page[4] == "END":
if len(rows) != int(page[2]):
raise RuntimeError("Incomplete retained trace")
return {"total": total, "overwritten": bool(int(page[5])), "rows": rows}
following = int(page[4])
if following != len(rows) or following <= offset:
raise RuntimeError("Non-progressing trace")
offset = following
raise RuntimeError("Trace paging did not finish")
def close(self):
try:
self.command("morse stop", allow_error=True)
self.command("set morse.wpm 25", allow_error=True)
finally:
self.port.close()
def trial(tx, rx, wpm, message, seconds=60, trace=False):
tx.command("morse stop")
rx.command("morse stop")
tx.command(f"set morse.wpm {wpm}")
rx.command(f"set morse.wpm {wpm}")
rx.start_when_idle(f"morse listen {seconds / 60:.4f}")
# Establish a real quiet RSSI floor before any carrier transmission.
time.sleep(.8)
started = time.monotonic()
tx.start_when_idle("morse send " + message)
while time.monotonic() - started < 180:
if "> off;" in tx.command("get morse"):
break
time.sleep(.15)
else:
raise RuntimeError("Transmitter did not stop")
tx_finished = time.monotonic()
time.sleep(.6)
rx_status = rx.command("get morse")
stats = rx.command("morse stats")
rx.command("morse stop")
decoded = rx.capture()
result = {"wpm": wpm, "nominal_dot_ms": (1200 + wpm // 2) // wpm,
"tx_serial": tx.serial_number, "rx_serial": rx.serial_number,
"sent": message, "decoded": decoded, "passed": decoded.strip() == message,
"tx_elapsed_s": round(tx_finished - started, 3),
"rx_status": rx_status, "rx_stats": stats}
if trace:
result["trace"] = rx.trace()
return result
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--output", required=True, type=Path)
parser.add_argument("--cw-frequency", type=parse_cw_frequency, default=DEFAULT_CW_FREQUENCY,
help="CW MHz (default 902.1); must not overlap the packet radio")
parser.add_argument("--rates", default="25,40,60,75,80,100,120,150,200,240")
parser.add_argument("--repeats", type=int, default=1)
parser.add_argument("--messages", type=int, default=3, choices=(1, 2, 3))
parser.add_argument("--partner", choices=("t096", "pocket"), default="t096",
help="Exact USB partner to pair with the RAK; no other radio is opened")
parser.add_argument("--direction", choices=("both", "to-rak", "from-rak"), default="both",
help="Test both directions, partner TX to RAK, or RAK TX to partner")
parser.add_argument("--trace", action="store_true", help="Requires a MESH_MORSE_HIL trace build")
parser.add_argument("--quiet-seconds", type=int, default=0,
help="No-transmitter receive control, 1-30 seconds")
parser.add_argument("--t096-rxgain", choices=("on", "off"),
help="Temporary diagnostic gain setting; restored afterward")
args = parser.parse_args()
if args.output.exists():
parser.error("Refusing to overwrite an existing result")
rates = [int(value) for value in args.rates.split(",")]
if not rates or any(rate < 1 or rate > 255 for rate in rates) or not 1 <= args.repeats <= 10:
parser.error("Rates 1-255 and repeats 1-10 only")
if args.quiet_seconds and not 1 <= args.quiet_seconds <= 30:
parser.error("Quiet control duration must be 1-30 seconds")
if args.t096_rxgain and args.partner != "t096":
parser.error("--t096-rxgain requires --partner t096")
results = {"frequency_mhz": args.cw_frequency, "packet_radio": PACKET_RADIO,
"requested_chip_power_dbm": -9,
"partner": args.partner, "direction": args.direction,
"scope": "Actual production applications on this pair, not all radio families.",
"trials": [], "finished": False}
devices = {}
original_gain = None
try:
for name in ("rak", args.partner):
devices[name] = Console(SERIALS[name])
for device in devices.values():
device.setup(args.cw_frequency)
if args.t096_rxgain:
gain_reply = devices["t096"].command("get radio.fem.rxgain")
match = re.search(r"> (on|off)\b", gain_reply)
if not match:
raise RuntimeError(("Unrecognized gain status", gain_reply))
original_gain = match[1]
devices["t096"].command("set radio.fem.rxgain " + args.t096_rxgain)
if args.quiet_seconds:
for device in devices.values():
device.start_when_idle(f"morse listen {args.quiet_seconds / 60:.4f}")
time.sleep(args.quiet_seconds + .2)
for name, device in devices.items():
result = {"kind": "quiet_control", "receiver": name,
"rx_stats": device.command("morse stats")}
device.command("morse stop")
result["decoded"] = device.capture()
result["passed"] = not result["decoded"]
if args.trace:
result["trace"] = device.trace()
results["trials"].append(result)
print(json.dumps({key: value for key, value in result.items()
if key != "trace"}), flush=True)
results["finished"] = True
return
directions = []
if args.direction in ("both", "to-rak"):
directions.append((args.partner, "rak"))
if args.direction in ("both", "from-rak"):
directions.append(("rak", args.partner))
for rate in rates:
for tx_name, rx_name in directions:
for repeat in range(args.repeats):
for message in MESSAGES[:args.messages]:
result = trial(devices[tx_name], devices[rx_name], rate, message, trace=args.trace)
result["repeat"] = repeat
results["trials"].append(result)
printable = {key: value for key, value in result.items() if key != "trace"}
if "trace" in result:
printable["trace_rows"] = len(result["trace"]["rows"])
print(json.dumps(printable), flush=True)
args.output.write_text(json.dumps(results, indent=2) + "\n")
results["finished"] = True
except BaseException as error:
results["error"] = str(error)
raise
finally:
if original_gain is not None:
try:
devices["t096"].command("morse stop", allow_error=True)
devices["t096"].command("set radio.fem.rxgain " + original_gain)
except Exception as error:
results.setdefault("cleanup_errors", []).append(str(error))
for device in devices.values():
try:
device.close()
except Exception as error:
results.setdefault("cleanup_errors", []).append(str(error))
results["commands"] = {name: device.commands for name, device in devices.items()}
args.output.write_text(json.dumps(results, indent=2) + "\n")
if __name__ == "__main__":
main()
+73
View File
@@ -0,0 +1,73 @@
#!/usr/bin/env bash
# Identity-bound nRF52 bench adapter for the unchanged mcfirmware.sh DFU path.
# No startup, dependency installation, service stopping, erase, or port recovery.
set -euo pipefail
umask 077
[[ $# == 7 ]] || { echo 'Usage: morse_nrf_flash.sh FLASHER BY_ID SERIAL BOARD ZIP INVENTORY WORKDIR' >&2; exit 2; }
bench_flasher=$(realpath -e -- "$1")
bench_link=$2 bench_serial=$3 bench_board=$4
bench_image=$(realpath -e -- "$5")
bench_inventory=$(realpath -e -- "$6")
bench_workdir=$(realpath -e -- "$7")
[[ "$bench_link" == /dev/serial/by-id/* && -L "$bench_link" ]]
[[ "$bench_workdir" == /home/mikec/hwtest/runs/morse-* ]]
bench_port=$(readlink -f -- "$bench_link")
morse_assert_unowned() {
local output status
if output=$(sudo -n fuser "$1" 2>&1); then
echo 'Selected port is busy; no owner will be stopped.' >&2
return 1
else status=$?; fi
[[ "$status" == 1 && -z "$output" ]] || {
echo 'Cannot verify that the selected port is unowned.' >&2
return 1
}
}
python3 "$(dirname "$bench_inventory")/verified_nrf_flash.py" \
--inventory "$bench_inventory" --serial "$bench_serial" --board "$bench_board" \
--artifact "$bench_image" --port "$bench_port"
morse_assert_unowned "$bench_port"
sha256sum -- "$bench_image"
bench_state=$(mktemp -d "$bench_workdir/mcfirmware-session.XXXXXX")
bench_functions="$bench_state/functions.sh"
awk '
{ sub(/\r$/, "") }
/^[A-Za-z_][A-Za-z0-9_]*\(\)[[:space:]]*\{[[:space:]]*$/ {
if (capture) exit 2
capture=1; count++
}
capture { print }
capture && /^}[[:space:]]*$/ { capture=0; print "" }
END { if (capture || count < 100) exit 3 }
' "$bench_flasher" > "$bench_functions"
bash -n "$bench_functions"
source "$bench_functions"
# Do not source the interactive program's globals or unattended cleanup.
PWD_SCRIPT=$(dirname "$bench_flasher")
FIRMWARE_ROOT=$bench_state
DOWNLOAD_DIR="$bench_state/downloads"
mkdir -- "$DOWNLOAD_DIR"
DEVICE_PORT=$bench_port
DEVICE_PORT_FILE="$bench_state/selected-port"
DEVICE_PORT_NAME_FILE="$bench_state/selected-port-name"
MESHFIRMWARE_SERIAL_BY_ID_FILE="$bench_state/by-id"
printf '%s\n' "$bench_link" > "$MESHFIRMWARE_SERIAL_BY_ID_FILE"
NRF52_BOARD_GUARD_PASSED=1
NRF52_SELECTED_BY_ID=$bench_link
NRF52_RUNTIME_SERIAL=$(udev_device_property "$bench_port" ID_SERIAL_SHORT)
NRF52_RUNTIME_PATH_STEM=$(nrf52_usb_path_stem "$(udev_device_property "$bench_port" ID_PATH)")
NRF52_RUNTIME_INSTANCE=$(nrf52_port_instance "$bench_port")
NRF52_LAST_DFU_PORT='' NRF52_LAST_DFU_INSTANCE=''
NRF52_ALLOW_UNMATCHED_DFU=0
NRF52_DFU_REENUMERATE_TIMEOUT_SECONDS=30
NRF52_DFU_REENUMERATE_POLL_SECONDS=0.25
MCFIRMWARE_NO_SUDO=1
# A mismatch, occupied port or failed flash must not trigger broad recovery.
nrf52_confirm_unmatched_dfu_override() { return 1; }
prepare_serial_port_for_flash() { morse_assert_unowned "$1"; }
recover_busy_serial_port() { return 1; }
offer_serial_port_recovery() { return 1; }
offer_identity_safe_1200_touch() { return 1; }
manual_reboot_choice() { return 1; }
run_nrf52_dfu_package_buttonless "$bench_image" "$bench_port"
printf 'Application-only mcfirmware DFU completed for %s (%s).\n' "$bench_board" "$bench_serial"
+68
View File
@@ -0,0 +1,68 @@
"""Read-only CLI/tool inventory for the identity-bound Mercerwood Morse bench."""
import json
import os
from pathlib import Path
import subprocess
import time
import serial
from serial.tools import list_ports
EXPECTED = {"9AB3B64C641BA927": "RAK4631", "651F8E496197F882": "Heltec T096"}
def read_quiet(port, limit=2.0):
data = bytearray()
until = time.monotonic() + limit
quiet = time.monotonic() + 0.2
while time.monotonic() < until and time.monotonic() < quiet:
chunk = port.read(port.in_waiting or 1)
if chunk:
data.extend(chunk)
quiet = time.monotonic() + 0.2
return data.decode("utf-8", errors="replace")
def main():
for command in (["hostname"], ["sudo", "-n", "true"],
["find", "/home/mikec/meshfirmware", "-maxdepth", "2", "-iname", "*custom*"],
["ls", "-la", "/home/mikec/meshfirmware/.customfirmware"]):
result = subprocess.run(command, capture_output=True, text=True, timeout=15)
print(json.dumps({"command": command, "rc": result.returncode,
"out": result.stdout, "err": result.stderr}), flush=True)
for item in list_ports.comports():
ident = (item.serial_number or "").upper()
if ident not in EXPECTED or item.interface == "MeshCore Logging":
continue
owner = subprocess.run(["sudo", "-n", "fuser", "-v", item.device],
capture_output=True, text=True, timeout=10)
if owner.stdout.strip():
print(json.dumps({"board": EXPECTED[ident], "serial": ident,
"port": item.device, "busy": True}), flush=True)
continue
port = serial.Serial(port=None, baudrate=115200, timeout=0.03)
port.dtr = True
port.rts = False
port.port = item.device
entered = False
try:
port.open()
read_quiet(port)
port.write(b"+++MESHCORE-TERM-START\n")
hello = read_quiet(port)
entered = "WELCOME" in hello
results = {}
for command in ("ver", "board", "get name", "get radio", "get tx", "get radio2.status"):
port.write((command + "\n").encode())
results[command] = read_quiet(port)
print(json.dumps({"board": EXPECTED[ident], "serial": ident,
"port": item.device, "hello": hello,
"commands": results}), flush=True)
finally:
if entered:
port.write(b"+++MESHCORE-TERM-STOP\n")
port.close()
if __name__ == "__main__":
main()
+487
View File
@@ -0,0 +1,487 @@
#!/usr/bin/env python3
"""Real LoRa ACK-first Morse RX/capture trial on Mercerwood Mesh.
Identity-bound RAK4631 repeater/T096 or Mesh Pocket Companion only. No flashing, erasure,
reboot, power control or service changes. Packets stay on 909.5 MHz, 500 kHz,
SF5, CR5. Keyed CW defaults to the user's 902.1 MHz, isolated from packet RX.
"""
import argparse
import asyncio
import json
from pathlib import Path
import re
import time
if __package__:
from .morse_bench import (Console, SERIALS, live_temporary_profile,
DEFAULT_CW_FREQUENCY, parse_cw_frequency)
else:
from morse_bench import (Console, SERIALS, live_temporary_profile,
DEFAULT_CW_FREQUENCY, parse_cw_frequency)
PACKET_RADIO = "909.5,500,5,5"
DEFAULT_MESSAGE = "REMOTE MORSE TEST 0123456789"
MORSE_CODES = dict(zip("ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789", (
".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---",
"-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-",
"..-", "...-", ".--", "-..-", "-.--", "--..", "-----", ".----", "..---",
"...--", "....-", ".....", "-....", "--...", "---..", "----.")))
MORSE_CODES.update(dict(zip(".,?'!/()&:;=+-_\"$@", (
".-.-.-", "--..--", "..--..", ".----.", "-.-.--", "-..-.", "-.--.", "-.--.-",
".-...", "---...", "-.-.-.", "-...-", ".-.-.", "-....-", "..--.-", ".-..-.",
"...-..-", ".--.-."))))
ERROR = re.compile(r"\b(?:Error|ERROR|ERR|Err)\b")
CAPTURE_PAGE = re.compile(
r"> (\d{4})/(\d{4}) next=(\d{4}|END ) truncated=([01]) ([^\r\n]*)")
def parse_capture_page(reply, offset):
"""Validate production paging, including its padded END marker."""
match = CAPTURE_PAGE.search(reply)
if not match or int(match[1]) != offset:
raise RuntimeError(("Malformed capture page", offset, reply))
total, fragment = int(match[2]), match[5]
if int(match[4]) or total > 4096 or offset + len(fragment) > total:
raise RuntimeError(("Truncated/inconsistent capture", reply))
if match[3] == "END ":
if offset + len(fragment) != total:
raise RuntimeError(("Incomplete final capture page", reply))
following = None
else:
following = int(match[3])
if following != offset + len(fragment) or following <= offset or following >= total:
raise RuntimeError(("Non-progressing capture page", reply))
return fragment, following, total
async def read_capture(command):
text, offset, expected_total, pages = "", 0, None, []
for _ in range(100):
reply = await command(f"morse read {offset}")
fragment, following, total = parse_capture_page(reply, offset)
if expected_total is not None and expected_total != total:
raise RuntimeError("Capture changed during paging")
expected_total = total
pages.append({"offset": offset, "reply": reply})
text += fragment
if following is None:
return text, pages
offset = following
raise RuntimeError("Capture paging did not finish")
async def apply_live_temporary(command, profile, timeout=12):
"""Wait for the immediate radio change, not a saved-only settings ACK."""
expected = tuple(float(value) for value in profile.split(","))
if len(expected) != 4:
raise ValueError("Expected frequency, bandwidth, SF and CR")
await command("set tempradio " + profile + ",30")
deadline = time.monotonic() + timeout
while True:
reply = await command("get tempradio")
if live_temporary_profile(reply) == expected:
return reply
if time.monotonic() >= deadline:
raise RuntimeError(("Live temporary radio did not apply", profile, reply))
await asyncio.sleep(.1)
def capture_evidence(expected, local_text, local_pages, remote_text=None, remote_pages=None):
"""Retain RF decoding and exact LoRa retrieval as independent evidence."""
return {"expected": expected, "local": local_text, "remote": remote_text,
"local_pages": local_pages, "remote_pages": remote_pages or [],
"exact_remote_match": None if remote_text is None else remote_text == local_text,
"exact_rf_match": local_text.strip() == expected}
def public_key(reply):
keys = re.findall(r"(?<![0-9A-Fa-f])[0-9A-Fa-f]{64}(?![0-9A-Fa-f])", reply)
if len(keys) != 1:
raise RuntimeError(("Missing/ambiguous public key", reply))
return keys[0].lower()
def nominal_seconds(message, wpm):
"""Reject impossible test windows before modifying either radio."""
words = message.split(" ")
if not words or any(not word for word in words):
raise ValueError("Use single spaces, without leading/trailing whitespace")
units = 7 * (len(words) - 1)
for word in words:
units += 3 * (len(word) - 1)
for char in word:
symbols = MORSE_CODES[char]
units += len(symbols) - 1 + sum(3 if symbol == "-" else 1 for symbol in symbols)
return units * ((1200 + wpm // 2) // wpm) / 1000
class BinaryCLI:
"""Process-local SDK compatibility for firmware's local CLI reply 29."""
def __init__(self, mc, reader_class, contact_event, record):
self.mc, self.contact_event, self.record = mc, contact_event, record
self.reader_class, self.original = reader_class, reader_class.handle_rx
self.replies = asyncio.Queue(maxsize=64)
self.counter, self.last_timestamp = 0, 0
self.lock = asyncio.Lock()
original, target_reader, queue = self.original, mc._reader, self.replies
async def handle_rx(reader, data):
if reader is target_reader and data:
self.record("source_frame", opcode=int(data[0]), bytes=len(data))
if reader is target_reader and data and data[0] == 29:
if queue.full():
queue.get_nowait()
queue.put_nowait(bytes(data[1:]).decode("utf-8", "strict"))
return
await original(reader, data)
self.patched = handle_rx
reader_class.handle_rx = handle_rx
def restore_reader(self):
if self.reader_class.handle_rx is self.patched:
self.reader_class.handle_rx = self.original
def nonce(self):
alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
if self.counter >= len(alphabet) ** 2:
raise RuntimeError("Two-character nonce space exhausted")
value = self.counter
self.counter += 1
return alphabet[value // len(alphabet)] + alphabet[value % len(alphabet)]
async def local(self, command, timeout=5, allow_error=False):
async with self.lock:
prefix = self.nonce() + "|"
started = time.monotonic()
# This return only proves USB admission, never receipt of reply29.
await self.mc.commands.send(b"\x42" + (prefix + command).encode("ascii"),
expected_events=None)
while True:
remaining = timeout - (time.monotonic() - started)
if remaining <= 0:
raise RuntimeError(("Local Binary CLI timeout", command))
reply = await asyncio.wait_for(self.replies.get(), remaining)
if reply.startswith(prefix):
reply = reply[len(prefix):]
break
self.record("source_local", command=command, reply=reply)
if not allow_error and ERROR.search(reply):
raise RuntimeError(("Source CLI error", command, reply))
return reply
async def local_when_idle(self, command):
deadline = time.monotonic() + 10
while True:
reply = await self.local(command, allow_error=True)
if "Error: radio busy" not in reply:
if ERROR.search(reply):
raise RuntimeError(("Source CLI error", command, reply))
return reply
if time.monotonic() >= deadline:
raise RuntimeError(("Source remained busy", command, reply))
await asyncio.sleep(.1)
async def remote(self, key, command, timeout=5, allow_error=False):
async with self.lock:
prefix = self.nonce() + "|"
future = asyncio.get_running_loop().create_future()
peer_prefix = key[:12].lower()
def receive(event):
payload = event.payload
text = payload.get("text", "")
if (payload.get("pubkey_prefix", "").lower() == peer_prefix
and payload.get("txt_type") == 1 and text.startswith(prefix)
and not future.done()):
future.set_result(text[len(prefix):])
# Subscribe before send: a fast LoRa reply can precede MSG_SENT.
subscription = self.mc.subscribe(self.contact_event, receive)
try:
# Unique real UTC seconds avoid pushing the peer's anti-replay
# floor into the future when paging rapidly, including next
# runs. Cancellation during this wait must retire the listener.
clock_deadline = time.monotonic() + 2
while int(time.time()) <= self.last_timestamp:
if time.monotonic() >= clock_deadline:
raise RuntimeError("UTC clock stopped/backstepped during remote test")
await asyncio.sleep(.02)
self.last_timestamp = int(time.time())
started = time.monotonic()
event = await self.mc.commands.send_cmd(key, prefix + command,
timestamp=self.last_timestamp)
if event.is_error():
raise RuntimeError(("Remote command not admitted", command, event.payload))
remaining = timeout - (time.monotonic() - started)
if remaining <= 0:
raise RuntimeError(("Remote CLI timeout", command))
reply = await asyncio.wait_for(future, remaining)
finally:
subscription.unsubscribe()
if not future.done():
future.cancel()
elapsed = time.monotonic() - started
self.record("remote", command=command, nonce=prefix[:2], reply=reply,
latency_seconds=round(elapsed, 4))
if not allow_error and ERROR.search(reply):
raise RuntimeError(("Remote CLI error", command, reply))
return reply, elapsed
async def run(args, results, record):
from meshcore import MeshCore, EventType
from meshcore.reader import MessageReader
peer = source_console = bridge = mc = None
source_binary = False
try:
peer = await asyncio.to_thread(Console, SERIALS["rak"], False)
source_console = await asyncio.to_thread(Console, SERIALS[args.source])
async def peer_command(command, allow_error=False):
reply = await asyncio.to_thread(peer.command, command, 5, allow_error)
record("peer_local", command=command, reply=reply)
return reply
peer_key = public_key(await peer_command("get public.key"))
source_key = public_key(await asyncio.to_thread(source_console.command, "get public.key"))
results["public_keys"] = {"peer": peer_key, "source": source_key}
for device in (peer, source_console):
for command in ("morse stop", "set radio.rxps off", "set tx -9", "set radio2 off",
f"set morse.freq {args.cw_frequency:.6f}", f"set morse.wpm {args.wpm}"):
await asyncio.to_thread(device.start_when_idle, command)
await asyncio.to_thread(device.apply_live_temporary, PACKET_RADIO)
await peer_command("setperm " + source_key + " 3")
await asyncio.to_thread(source_console.command, "set radio.fem.rxgain on", 5, True)
source_port = source_console.port.port
record("configured", peer_usb_serial=SERIALS["rak"], source_usb_serial=SERIALS[args.source],
peer_commands=peer.commands, source_commands=source_console.commands)
source_console.port.write(b"+++MESHCORE-TERM-STOP\r\n")
source_binary = True
await asyncio.to_thread(source_console.read_quiet, 1)
# Never Console.close() after STOP: that would inject ASCII into Binary.
source_console.port.close()
mc = await MeshCore.create_serial(source_port, baudrate=115200,
only_error=True, default_timeout=5, auto_reconnect=False)
if mc is None:
raise RuntimeError("Could not start source Binary Companion session")
bridge = BinaryCLI(mc, MessageReader, EventType.CONTACT_MSG_RECV, record)
if public_key(await bridge.local("get public.key")) != source_key:
raise RuntimeError("Source identity changed at transport handoff")
contact = {"public_key": peer_key, "type": 2, "flags": 0,
"out_path_len": 0, "out_path_hash_mode": 0, "out_path": "",
"adv_name": "Morse remote repeater", "last_advert": int(time.time()),
"adv_lat": 0, "adv_lon": 0}
event = await mc.commands.add_contact(contact)
if event.is_error():
raise RuntimeError(("Contact admission failed", event.payload))
await mc.start_auto_message_fetching()
record("binary_ready", source_port=source_port)
denied, _ = await bridge.remote(peer_key, "morse listen 6", allow_error=True)
if not ERROR.search(denied):
raise RuntimeError((">5 minute listen was not rejected", denied))
if "> off;" not in await peer_command("get morse"):
raise RuntimeError("Rejected duration unexpectedly started RX")
source_live = await bridge.local("get tempradio")
peer_live = await peer_command("get tempradio")
if any(live_temporary_profile(reply) != (909.5, 500, 5, 5)
for reply in (source_live, peer_live)):
raise RuntimeError(("Packet profile changed before listen", source_live, peer_live))
record("packet_profiles_verified", source=source_live, peer=peer_live)
ack, latency = await bridge.remote(peer_key, f"morse listen {args.minutes:g}")
if latency >= 5 or "Morse RX queued" not in ack:
raise RuntimeError(("Listen was not acknowledged before RX", ack, latency))
active_deadline = time.monotonic() + 10
while True:
status = await peer_command("get morse")
if re.search(r"> RX(?:\s| learning)", status):
break
if time.monotonic() >= active_deadline:
raise RuntimeError(("Peer never entered Morse RX", status))
await asyncio.sleep(.1)
rx_observed = time.monotonic()
record("listen_active", status=status, acknowledgement_seconds=round(latency, 4))
await asyncio.sleep(.8)
for index in range(args.repeat):
await bridge.local_when_idle("morse send " + args.message)
tx_deadline = time.monotonic() + 185
while "> off;" not in await bridge.local("get morse"):
if time.monotonic() >= tx_deadline:
raise RuntimeError("Source failed to finish Morse TX")
await asyncio.sleep(.15)
if index + 1 < args.repeat:
await asyncio.sleep(.5)
record("cw_complete", transmissions=args.repeat,
source_live_packet_radio=PACKET_RADIO)
expiry_deadline = rx_observed + args.minutes * 60 + 15
while True:
status = await peer_command("get morse")
if "> off;" in status:
break
if time.monotonic() >= expiry_deadline:
raise RuntimeError(("Timed receiver did not recover", status))
await asyncio.sleep(1)
record("listen_expired", elapsed_since_observed_seconds=round(time.monotonic() - rx_observed, 3),
status=status)
await apply_live_temporary(bridge.local_when_idle, PACKET_RADIO)
record("source_packet_radio_verified", live_packet_radio=PACKET_RADIO)
async def local_capture_command(command):
return await peer_command(command, allow_error=True)
local_text, local_pages = await read_capture(local_capture_command)
expected = " ".join([args.message] * args.repeat)
results["capture"] = capture_evidence(expected, local_text, local_pages)
record("local_capture_received", captured_characters=len(local_text),
local_pages=len(local_pages), exact_rf_match=results["capture"]["exact_rf_match"])
async def remote_command(command):
return (await bridge.remote(peer_key, command))[0]
async def remote_capture_command(command):
# Captured Morse may literally contain ERROR/ERR; the production
# page parser, not a keyword in the decoded payload, validates it.
return (await bridge.remote(peer_key, command, allow_error=True))[0]
remote_text, remote_pages = await read_capture(remote_capture_command)
results["capture"] = capture_evidence(expected, local_text, local_pages, remote_text, remote_pages)
record("capture_received", captured_characters=len(local_text), remote_pages=len(remote_pages),
exact_remote_match=results["capture"]["exact_remote_match"],
exact_rf_match=results["capture"]["exact_rf_match"])
radio = await remote_command("get tempradio")
saved_radio = await remote_command("get radio")
secondary = await remote_command("get radio2")
recovered = await remote_command("get morse")
results["recovery"] = {"live_radio": radio, "saved_radio": saved_radio,
"radio2": secondary, "morse": recovered}
recovery_ok = (live_temporary_profile(radio) == (909.5, 500, 5, 5)
and "> off" in secondary and "> off;" in recovered)
results["recovery"]["passed"] = recovery_ok
record("recovery_checked", passed=recovery_ok, live_radio=radio,
saved_radio=saved_radio, radio2=secondary, morse=recovered)
if not recovery_ok:
raise RuntimeError(("Packet profile/Morse recovery failed", radio, secondary, recovered))
if not results["capture"]["exact_remote_match"]:
raise RuntimeError(("Remote/local capture mismatch", local_text, remote_text))
if not results["capture"]["exact_rf_match"]:
raise RuntimeError(("RF decoded text differs from sent text", expected, local_text))
results["passed"] = True
record("passed", captured_characters=len(local_text), remote_pages=len(remote_pages))
finally:
if bridge is not None:
for command in ("morse stop", "set morse.wpm 25"):
try:
await bridge.local_when_idle(command)
except Exception as error:
results.setdefault("cleanup_errors", []).append(str(error))
try:
await apply_live_temporary(bridge.local_when_idle, PACKET_RADIO)
except Exception as error:
results.setdefault("cleanup_errors", []).append(str(error))
if mc is not None:
try:
await mc.disconnect()
except Exception as error:
results.setdefault("cleanup_errors", []).append(str(error))
if bridge is not None:
bridge.restore_reader()
if source_console is not None:
if not source_binary and source_console.port.is_open:
try:
source_console.command("morse stop", allow_error=True)
await asyncio.to_thread(source_console.apply_live_temporary, PACKET_RADIO)
source_console.close()
except Exception as error:
results.setdefault("cleanup_errors", []).append(str(error))
source_console.port.close()
if source_binary and bridge is None:
# A failed SDK handoff cannot use the already-closed Console.
# Reacquire this exact identity only after disconnecting SDK.
recovery = None
try:
recovery = await asyncio.to_thread(Console, SERIALS[args.source])
for command in ("morse stop", "set morse.wpm 25"):
await asyncio.to_thread(recovery.command, command, 5, True)
await asyncio.to_thread(recovery.apply_live_temporary, PACKET_RADIO)
except Exception as error:
results.setdefault("cleanup_errors", []).append(str(error))
finally:
if recovery is not None:
recovery.port.close()
if peer is not None:
try:
for command in ("morse stop", "set morse.wpm 25"):
await asyncio.to_thread(peer.command, command, 5, True)
await asyncio.to_thread(peer.apply_live_temporary, PACKET_RADIO)
peer.close()
except Exception as error:
results.setdefault("cleanup_errors", []).append(str(error))
finally:
peer.port.close()
results["peer_commands"] = peer.commands
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--output", required=True, type=Path)
parser.add_argument("--source", choices=("t096", "pocket"), default="t096")
parser.add_argument("--cw-frequency", type=parse_cw_frequency, default=DEFAULT_CW_FREQUENCY,
help="CW MHz (default 902.1); must not overlap the packet radio")
parser.add_argument("--minutes", type=float, default=.5)
parser.add_argument("--wpm", type=int, default=25)
parser.add_argument("--message", default=DEFAULT_MESSAGE)
parser.add_argument("--repeat", type=int, default=1,
help="For multiple pages use --minutes 2 --repeat 8 --message 'REMOTE MORSE TEST'")
args = parser.parse_args()
if not 1 / 60 <= args.minutes <= 5 or not 1 <= args.wpm <= 255 or not 1 <= args.repeat <= 10:
parser.error("Listen 1 second-5 minutes, WPM 1-255, repeats 1-10 only")
if not 1 <= len(args.message) <= 80 or not args.message.isascii() or args.message != args.message.upper():
parser.error("Use 1-80 uppercase ASCII Morse characters")
try:
duration = nominal_seconds(args.message, args.wpm)
except (ValueError, KeyError):
parser.error("Use supported Morse letters/digits/punctuation and single spaces")
if duration > 180 or args.repeat * duration + (args.repeat - 1) * .5 + 3 > args.minutes * 60:
parser.error("Message/repeats do not fit the requested listening window; shorten text or extend --minutes")
results = {"source": args.source, "packet_radio": PACKET_RADIO,
"cw_frequency_mhz": args.cw_frequency,
"source_packet_radio_during_cw": PACKET_RADIO,
"requested_chip_power_dbm": -9, "minutes": args.minutes,
"wpm": args.wpm, "message": args.message, "repeat": args.repeat,
"passed": False, "finished": False, "events": []}
try:
output = args.output.open("x", encoding="utf-8")
except FileExistsError:
parser.error("Refusing to overwrite an existing result")
with output:
def save():
output.seek(0)
json.dump(results, output, indent=2)
output.write("\n")
output.truncate()
output.flush()
def record(kind, **fields):
item = {"kind": kind, "utc": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), **fields}
results["events"].append(item)
save()
print(json.dumps(item), flush=True)
save()
try:
asyncio.run(run(args, results, record))
results["finished"] = True
except BaseException as error:
results["error"] = str(error)
raise
finally:
save()
if __name__ == "__main__":
main()