diff --git a/README.md b/README.md index aee8cfa..c95b9c5 100644 --- a/README.md +++ b/README.md @@ -31,7 +31,7 @@ Frequenzwahl, Bandplan und Sendeleistung liegt beim Betreiber. | **TX-Modi** (`pluto-tx`) | FM (optional mit CTCSS/DCS), SSB (USB/LSB), M17, FreeDV 2020/2020B, RADE V1, File Broadcast, Baseband | | **RX-Modi** (`pluto-advanced-rx`) | FM, SSB (USB/LSB), RADE V1, M17, Baseband | | **Digimodes** (beide Apps, eigener Reiter) | Waterfall Writer (Text im Wasserfall), PSK31-Chat, RTTY, POCSAG (Funkruf), FT8, JS8 (JS8Call-kompatibel, Normal/Fast/Turbo/Slow), Meshtastic (LoRa; nur Pluto/HackRF/RTL-SDR), MeshCore (LoRa, nur RF-Geräte) | -| **Hardware** | PlutoSDR/Pluto+ (TX+RX), HackRF One (TX+RX), RTL-SDR (RX), Soundkarte/externes Funkgerät (TX+RX), AIOC-Adapter/analoges Funkgerät (TX) | +| **Hardware** | PlutoSDR/Pluto+ (TX+RX), HackRF One (TX+RX), RTL-SDR (RX), Soundkarte/externes Funkgerät (TX+RX), AIOC-Adapter/analoges Funkgerät (TX), ESP32-S3-Board (TX, nur 13 cm, nur FM und M17, experimentell) | | **Automatisierung** | `pluto-cli` — dieselbe Codebasis headless, `--json`-Ausgabe | | **Fernbetrieb** | `web-trx` — Browser-Oberfläche (FastAPI + Svelte) auf derselben Codebasis, ein Betreiber, Login, HTTPS | | **Sicherheit** | NOTAUS, von GNU Radio unabhängige Abschalt-Logik, Live-Hardware-Readout | @@ -118,6 +118,40 @@ eigenständige Skript `pluto_tx/tx-stdin.py` (Audio von stdin senden, z. B. für eine TTS-Pipe ohne die GUI) nutzt dieselbe PTT-Logik (`pluto_tx/aioc_ptt.py`) und funktioniert unabhängig von der App weiter. +### Optional: ESP32-S3 als 13-cm-Sender (FM und M17, experimentell) + +Der Gerätetyp "ESP32-S3 (13 cm)" sendet mit einem ESP32-S3-Entwicklungsboard (mit **zwei** USB-Ports) im 13-cm-Band (2320–2450 MHz). Das Board hat +keinen I/Q-Ausgang: Es steuert den Testton seines WLAN-Funkteils in Frequenz (und ein wenig in der Amplitude), 40 000-mal pro Sekunde. Das genügt +für Signale mit **konstanter Hüllkurve**: `pluto-tx` rechnet das Basisband des Flowgraphs in die Momentanfrequenz um, und nur diese geht zum Chip. Deshalb +sind **nur FM und M17** wählbar; alles mit Amplitudenmodulation (SSB, PSK31, FT8, FreeDV, RADE, ...) und LoRa ist bei diesem Gerät gesperrt +(GUI: ausgegraut mit Hinweis, `pluto-cli`: Fehlermeldung, Flowgraph: Rückfall auf FM). + +``` +./install.sh # zuerst +./install-espdr.sh # esptool 5 (pipx), udev-Regel für das Board; --dry-run zeigt nur, was passieren würde +``` + +Der Code für das Board (`espdr/`, einschließlich der Firmware-Images) gehört zu diesem Repository: Er ist eine Kopie aus +[esp32-sdr-trx](https://github.com/jochenhammes/esp32-sdr-trx) (Zero-Clause-BSD-Lizenz, Stand in `espdr/UPSTREAM`), die `tools/sync-espdr.sh` +aktualisiert. **`espdr/` hier nicht ändern**, sondern in esp32-sdr-trx. Es wird nichts nachgeladen; die Firmware kommt bei Bedarf ins **RAM** +des Boards (der Flash bleibt unberührt). Verbindungsfeld: leer (Board an den USB-Ports finden) oder `NATIVER_PORT[,UART_PORT]`, z. B. `/dev/ttyACM1,/dev/ttyACM0`. + +Vor der ersten Sendung einmal den Lizenzhinweis bestätigen (das sendet nichts): +`python3 -m espdr.cli_tx -f 2345 --test-tone 1000 --dry-run --accept-licence`. Dann z. B. `pluto-cli tx m17 --device espdr --freq 2345000000 --src-callsign `. + +**Was du wissen musst** (gemessen mit einem Board und einem PlutoSDR als Empfänger, Einzelheiten in +[`espdr/` → docs/research/PLAN-M17.md in esp32-sdr-trx](https://github.com/jochenhammes/esp32-sdr-trx/blob/feature/m17/docs/research/PLAN-M17.md), Abschnitt 10): +- Die M17-Kette von `pluto-tx` dekodiert das Signal (Rufzeichen und Sprache), auch noch am Ende einer 120-s-Sendung. +- Mit dem Gerät selbst (`pluto-cli`, ein Board, ein PlutoSDR als Empfänger, 2345 MHz, −6 dB) getestet: M17 von einer WAV-Datei wird dekodiert (Rufzeichen, 4,5 s Sprache); + FM sendet und endet sauber; fünf Sendungen hintereinander ohne hängenden Träger (Träger innerhalb der Messauflösung von 0,22 s beim Tasten und beim Loslassen). + **Nicht getestet:** die GUI im echten Betrieb, Mikrofonbetrieb über längere Zeit (Taktdrift Soundkarte gegen Chip), mehr als ein Board, 600-s-Sendungen. +- **Außerhalb des Kanals ist der Sender nicht sauber**: die Nachbarfenster (9 kHz) liegen 37 dB (±12,5 kHz) und 46 dB (±25 kHz) unter der Kanalleistung, + weiter draußen etwa −55 dBc bis ±200 kHz. Oberwellen sind **nicht gemessen**, die Leistung ist **nicht kalibriert** (Standardobergrenze −12 dB gegen den stärksten Wert). +- Die Trägerfrequenz **weicht ab** (der Quarz des Boards, einige kHz, je nach Temperatur) und **driftet** (1,5 kHz in 106 s, gemessen mit aktivem Thermalmodell des Boards und ohne ppm-Korrektur); + M17-Empfänger folgen dem. Bei etwa 10 % der Frequenzen liegt das Signal wegen der Einstellmöglichkeiten des Chips ein paar kHz neben dem Wunsch (die Warnung nennt die tatsächliche Frequenz). +- Die Latenz von PTT bis Träger beträgt mindestens 100 ms, das Ende des Trägers kommt etwa 125 ms nach dem Loslassen; die Frequenz lässt sich während der Sendung nicht ändern. +- Eine Sendung braucht eine **Amateurfunklizenz**, und du bist für das verantwortlich, was du sendest. Nur 2320–2450 MHz. + ### Optional: FT8 ``` @@ -486,10 +520,11 @@ weitere Rezepte) in [`pluto_cli/README.md`](pluto_cli/README.md). | **RTL-SDR** (USB oder per `rtl_tcp` im Netzwerk) | — (kein TX-fähiges Gerät) | alle Modi | | **Soundkarte / externes Funkgerät** | FM, RADE, Waterfall Writer, PSK31, RTTY, POCSAG, FT8, JS8 | alle Modi (Audio Input, z.B. für RADE über ein SSB-Funkgerät) | | **AIOC-Adapter / analoges Funkgerät** (z. B. Quansheng UV-K5) | FM, RADE, Waterfall Writer, PSK31, RTTY, POCSAG, FT8, JS8 (Audio + echtes serielles PTT) | — (kein RX-Backend) | +| **ESP32-S3-Board** (nur 13 cm, experimentell) | nur FM und M17 (konstante Hüllkurve; Frequenz 2320–2450 MHz) | — (kein RX-Backend) | Geräteauswahl per editierbarem Dropdown ("Device") plus Scan- und Connect/Disconnect-Buttons. **Nur `pluto-tx`** hat zusätzlich ein -"Device Type"-Dropdown (PlutoSDR/HackRF/Soundcard/AIOC), das Verbindungsfeld, +"Device Type"-Dropdown (PlutoSDR/HackRF/Soundcard/AIOC/ESP32-S3), das Verbindungsfeld, Frequenzbereich und Pegel-Regler passend umschaltet. ## Sicherheit @@ -516,10 +551,11 @@ Gain-Register allein stoppt die Sendung nachweislich nicht). ## Struktur ``` -install.sh / install-m17.sh / install-rade.sh / install-lora.sh / install-ft8.sh / install-js8.sh / install-web-trx.sh +install.sh / install-m17.sh / install-rade.sh / install-lora.sh / install-ft8.sh / install-js8.sh / install-web-trx.sh / install-espdr.sh +espdr/ # Kopie aus esp32-sdr-trx (0BSD): Host-Teil des ESP32-S3-Senders + Firmware-Images; `tools/sync-espdr.sh`, nicht hier ändern pluto_tx/ # Sende-App ├── config.py # geräteunabhängige Konstanten -├── devices/ # TX-Geräte-Abstraktionsschicht (Pluto/HackRF/Soundcard) +├── devices/ # TX-Geräte-Abstraktionsschicht (Pluto/HackRF/Soundcard/AIOC/ESP32-S3) ├── safety.py # PlutoSafety: rohes python3-libiio, unabhängig von GNU Radio ├── flowgraph.py # PlutoTxFlowgraph: die gesamte Signalkette ├── dynamics.py # Kompressor/Limiter @@ -617,6 +653,10 @@ offene Punkte stehen am Ende dieser Datei. [GPLv3](LICENSE) — Copyright (C) 2026 Jochen Hammes (DA2JH). +Das Verzeichnis `espdr/` (Host-Teil des ESP32-S3-Senders und seine Firmware-Images) ist eine Kopie aus +[esp32-sdr-trx](https://github.com/jochenhammes/esp32-sdr-trx) unter der Zero-Clause-BSD-Lizenz (`espdr/LICENSE`, `espdr/NOTICE`); der Rest dieses +Repositories steht unter GPLv3. Die Kopie erzeugt `tools/sync-espdr.sh`, der Stand steht in `espdr/UPSTREAM`. + Die optionalen Abhängigkeiten `gr-m17` (GPLv2), `rade_c`/RADE (BSD-2-Clause) und `ft8_lib` (MIT) werden von `install-m17.sh`/`install-rade.sh`/ `install-ft8.sh` separat aus ihren jeweiligen Quellen gebaut, nicht in diesem Repo diff --git a/espdr/LICENSE b/espdr/LICENSE new file mode 100644 index 0000000..67d0ed2 --- /dev/null +++ b/espdr/LICENSE @@ -0,0 +1,13 @@ +Zero-Clause BSD +============== + +Permission to use, copy, modify, and/or distribute this software for +any purpose with or without fee is hereby granted. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL +WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES +OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE +FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY +DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN +AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/espdr/NOTICE b/espdr/NOTICE new file mode 100644 index 0000000..6eed8e8 --- /dev/null +++ b/espdr/NOTICE @@ -0,0 +1,15 @@ +esp32-sdr-trx +============= + +This project is built on eSpDR by h0m3us3r (https://github.com/h0m3us3r/eSpDR), published under the Zero-Clause BSD licence (0BSD). +eSpDR found how to read the ESP32-S3's undocumented Wi-Fi I/Q dump path and wrote the firmware around it: the radio bring-up, the +LO tuning (including the 5/6 conversion mode), the capture engine and the control protocol. The firmware in `firmware/` is that code with +changes; it started from upstream commit f279bf8 and went through the fork https://github.com/jochenhammes/eSpDR (branches +`narrowband`, `tx-research`; the research is kept there and in the tag `tx-research-final`). + +What this project adds: the on-chip decimator that makes a 250 or 333 ksps stream out of the 16 Msps dump (no FPGA), the USB stream, the +flash boot, the rtl_tcp bridge, the experimental transmitter (frequency and amplitude steering of the PHY's test tone, FM and SSB voice), +the host tools `espdr-rx` and `espdr-tx`, and their documentation. Most of the code and the documentation was written with Claude +(Anthropic) as the coding assistant; every number in the documentation was measured. + +The vendor PHY library (libphy.a) of ESP-IDF is linked at build time from an ESP-IDF v5.5 installation and is not part of this repository. diff --git a/espdr/UPSTREAM b/espdr/UPSTREAM new file mode 100644 index 0000000..3093649 --- /dev/null +++ b/espdr/UPSTREAM @@ -0,0 +1,10 @@ +repository: https://github.com/jochenhammes/esp32-sdr-trx +commit: 580a0f7a4052410843b89c4f5c2f5973db68ef84 +subject: board: find esptool as a program on the PATH when this Python has no esptool module +date: 2026-10-11T18:55:39+02:00 +licence: 0BSD (espdr/LICENSE); the rest of pluto-tx is GPL-3.0 +images (build products of the firmware of that repository, copied as they were; sha256 in espdr/images/SHA256SUMS.txt): + c5131425d56fb05c44874988ca77652a5c4482296bf206d944683ee131d73678 rx.bin + b017125ac6c1bcbb70c84e3675a0ecee485b3249f84803cae382b6b83c6f7fd6 tx.bin + 09b2386299522e08fad02bfed8bab76bc5e37076b8d529c31811e967780b686b bootloader.bin + 7f00b6c042a89b15b0cac534f82ed988caf29278ff5700b0c511eb1b5bb7c820 partition-table.bin diff --git a/espdr/__init__.py b/espdr/__init__.py new file mode 100644 index 0000000..46698c8 --- /dev/null +++ b/espdr/__init__.py @@ -0,0 +1,2 @@ +"""esp32-sdr-trx: an rtl_tcp receiver and an FM/SSB voice transmitter for one ESP32-S3 board.""" +__version__ = "0.0.0.dev0" diff --git a/espdr/audio.py b/espdr/audio.py new file mode 100644 index 0000000..9f275a1 --- /dev/null +++ b/espdr/audio.py @@ -0,0 +1,210 @@ +"""Audio sources for the transmitter: a WAV file, a pipe on stdin (WAV or raw samples), or a sound card. + +Every source delivers mono float blocks at its own sample rate; `Mono8k` turns that into the 8 kHz stream the modulators take. +""" +import queue +import struct +import sys +import time + +import numpy as np + +from . import dsp + +RAW_FORMATS = {"s16le": (np.dtype(" 1: + a = a[: len(a) // channels * channels].reshape(-1, channels).mean(axis=1) + return a + + +class StreamSource: + """Raw or WAV audio read from a binary file object (a file, or stdin as a pipe).""" + + def __init__(self, fh, rate=None, channels=1, fmt="s16le", block_s=0.02, name="stdin"): + self.fh, self.name, self.block_s = fh, name, block_s + head = fh.read(4) + if head == b"RIFF": + self._read_wav_header() + else: + if rate is None: + raise AudioError(f"{name}: raw audio needs --rate (and --channels, --format if they are not mono s16le)") + if fmt not in RAW_FORMATS: + raise AudioError(f"unknown format {fmt!r}; use one of {', '.join(RAW_FORMATS)}") + self.rate, self.channels = int(rate), int(channels) + self.dtype, self.scale = RAW_FORMATS[fmt] + self.pending = head + self.remaining = None + + def _read_wav_header(self): + fh = self.fh + fh.read(4) # RIFF size + if fh.read(4) != b"WAVE": + raise AudioError(f"{self.name}: not a WAV file") + fmt = None + while True: + hdr = fh.read(8) + if len(hdr) < 8: + raise AudioError(f"{self.name}: no audio data in the WAV file") + cid, size = hdr[:4], struct.unpack("= 26: # WAVE_FORMAT_EXTENSIBLE: the real tag is in the sub format + tag = struct.unpack(" 0 else b"" + if self.remaining is not None: + self.remaining -= len(chunk) + pending += chunk + whole = len(pending) // width * width + if whole >= n or (not chunk and whole): + yield _to_float(pending[:whole], self.dtype, self.scale, self.channels) + pending = pending[whole:] + if not chunk: + return + + def close(self): + if self.fh not in (sys.stdin.buffer,): + self.fh.close() + + +class SoundCardSource: + """A sound card input through PortAudio (the optional `sounddevice` package).""" + + def __init__(self, device=None, rate=None, block_s=0.02): + try: + import sounddevice as sd + except ImportError: + raise AudioError("the sound card needs the sounddevice package: pip install 'esp32-sdr-trx[audio]' " + "(or: pipx inject esp32-sdr-trx sounddevice); on Linux also PortAudio: sudo apt install libportaudio2") + self.sd = sd + if device is not None and str(device).lstrip("-").isdigit(): + device = int(device) + try: + info = sd.query_devices(device, "input") + except Exception as e: + raise AudioError(f"no such sound card input {device!r} ({e}); `espdr-tx --list-devices` shows what there is") + self.name = info["name"] + self.rate = int(rate or info["default_samplerate"]) + self.q = queue.Queue(maxsize=200) + self.overflows = 0 + self.stream = sd.InputStream(device=device, channels=1, samplerate=self.rate, dtype="float32", + blocksize=max(1, int(self.rate * block_s)), callback=self._cb) + + def _cb(self, indata, frames, time_info, status): + if status: + self.overflows += 1 + try: + self.q.put_nowait(indata[:, 0].copy()) + except queue.Full: + self.overflows += 1 + + def blocks(self): + self.stream.start() + while True: + try: + yield self.q.get(timeout=1.0) + except queue.Empty: + raise AudioError(f"the sound card {self.name!r} delivers no audio") + + def close(self): + try: + self.stream.stop() + self.stream.close() + except Exception: + pass + + +def list_devices(): + try: + import sounddevice as sd + except ImportError: + raise AudioError("the sound card needs the sounddevice package: pip install 'esp32-sdr-trx[audio]'") + lines = [] + for i, d in enumerate(sd.query_devices()): + if d["max_input_channels"] > 0: + lines.append(f" {i:3d} {d['name']} ({d['max_input_channels']} in, {int(d['default_samplerate'])} Hz)") + return lines + + +def open_source(spec, rate=None, channels=1, fmt="s16le", device=None): + """spec: a file name, '-' for stdin, or 'soundcard' / 'soundcard:DEVICE' (number or name).""" + if spec == "-": + return StreamSource(sys.stdin.buffer, rate, channels, fmt, name="stdin") + if spec == "soundcard" or spec.startswith("soundcard:"): + dev = device if device is not None else (spec.split(":", 1)[1] if ":" in spec else None) + return SoundCardSource(dev, rate) + try: + fh = open(spec, "rb") + except OSError as e: + raise AudioError(f"{spec}: {e.strerror or e}") + return StreamSource(fh, rate, channels, fmt, name=spec) + + +class Mono8k: + """Blocks of mono audio at the source's rate -> blocks of 8 kHz audio of about 20 ms.""" + + def __init__(self, source, out_rate=8000): + self.source = source + self.rs = dsp.Resampler(source.rate, out_rate) if source.rate != out_rate else None + + def blocks(self): + for b in self.source.blocks(): + y = self.rs.process(b) if self.rs else b + if len(y): + yield y.astype(float) + + def trim(self, ppm): + if self.rs: + self.rs.trim = ppm + + +def test_tone(freq=1000.0, level=0.5, seconds=None, block_s=0.02, rate=8000): + """A sine as an 8 kHz source (for --test-tone); endless when seconds is None.""" + n = int(rate * block_s) + i = 0 + total = None if seconds is None else int(seconds * rate) + while total is None or i < total: + k = n if total is None else min(n, total - i) + t = (np.arange(i, i + k)) / rate + yield level * np.sin(2 * np.pi * freq * t) + i += k diff --git a/espdr/board.py b/espdr/board.py new file mode 100644 index 0000000..72b9f90 --- /dev/null +++ b/espdr/board.py @@ -0,0 +1,239 @@ +"""Finding the board, telling which firmware runs on it, and loading the right image into its RAM. + +A board with two USB ports has a USB-UART bridge (CH343, CH340, CP210x or FTDI) whose RTS/DTR lines drive EN and BOOT: esptool resets +the chip into its ROM loader through it, no button needed. The firmware then talks on the chip's native USB Serial/JTAG port +(USB id 303a:1001). A board with only the native port can be loaded too, with BOOT held and RESET tapped (`native=True`). + +Images run from RAM and nothing is written to the flash unless `flash_receiver()` is used; a reset brings back whatever the flash holds. +""" +import os +import subprocess +import sys +import time +from pathlib import Path + +from . import nb + +# USB-UART bridges used on ESP32-S3 boards: (vendor, product) +BRIDGES = {(0x1A86, 0x55D3), (0x1A86, 0x7523), (0x1A86, 0x55D4), (0x10C4, 0xEA60), (0x0403, 0x6001), (0x0403, 0x6010), + (0x0403, 0x6014)} +NATIVE = (0x303A, 0x1001) + +CTL_BUILD_NARROWBAND, CTL_BUILD_TX = 1, 2 # CTL_INFO argument 3 (firmware/protocol/control.h) +RX, TX = "rx", "tx" + + +class BoardError(Exception): + """Something the user can fix: the message says how.""" + + +def _ports(): + from serial.tools import list_ports + return list(list_ports.comports()) + + +def bridge_ports(): + return [p.device for p in _ports() if (p.vid, p.pid) in BRIDGES] + + +def native_ports(): + return [p.device for p in _ports() if (p.vid, p.pid) == NATIVE] + + +def find_bridge(hint=None): + if hint: + return hint + found = bridge_ports() + if len(found) > 1: + raise BoardError(f"several USB-UART bridges found ({', '.join(found)}); name the board's with --bridge-port") + return found[0] if found else None + + +def find_native(hint=None): + if hint: + return hint + found = native_ports() + if len(found) > 1: + raise BoardError(f"several ESP32-S3 boards found ({', '.join(found)}); choose one with --port") + return found[0] if found else None + + +def probe(port, timeout=1.5): + """Asks the firmware on `port` what it is: returns its build flags (CTL_BUILD_*), or None if nothing sensible answers.""" + import serial + try: + link = nb.open_link(port) + except (serial.SerialException, OSError): + return None + try: + link.send(nb.CTL_INFO, 0) + status, fid = link._response(nb.CTL_INFO, timeout=timeout) + if status != 0 or fid != nb.FIRMWARE_ID: + return None + link.send(nb.CTL_INFO, 3) + status, flags = link._response(nb.CTL_INFO, timeout=timeout) + return flags if status == 0 else CTL_BUILD_NARROWBAND # a receiver image from before the flags existed + except nb.ProtocolError: + return None + finally: + try: + link.ser.close() + except Exception: + pass + + +def kind_of(flags): + return None if flags is None else TX if flags & CTL_BUILD_TX else RX + + +def image_path(kind, override=None): + """The firmware image of this package (or `override`, or a build in a source tree).""" + if override: + p = Path(override) + if not p.exists(): + raise BoardError(f"{p}: no such file") + return p + here = Path(__file__).resolve().parent + candidates = [here / "images" / f"{kind}.bin", here.parents[1] / "firmware" / f"build-{kind}" / "iq-source.bin"] + for p in candidates: + if p.exists(): + return p + raise BoardError(f"no {kind} firmware image found (looked in {', '.join(str(c.parent) for c in candidates)}); " + f"install a release of esp32-sdr-trx, or build one with `make -C firmware{' TX=1' if kind == TX else ''}`") + + +VERBOSE = False # set by the command lines' -v: show esptool's own output + + +def esptool_command(): + """How to run esptool 5 or newer: the module in this Python if there is one, else the `esptool` program on the PATH (what `pipx install + esptool` provides, for a Python that pip may not write to). Raises BoardError with the way to get it if there is neither.""" + import importlib.util + import shutil + if importlib.util.find_spec("esptool") is not None: + return [sys.executable, "-m", "esptool"] + exe = shutil.which("esptool") + if exe: + return [exe] + raise BoardError("esptool (version 5 or newer) is needed to load the firmware into the board and was not found. Install it with " + "`pipx install esptool` (or `pip install esptool` in a virtual environment); the esptool package of Debian and Ubuntu " + "is version 4 and does not work here") + + +def _esptool(args, what): + cmd = esptool_command() + ["--chip", "esp32s3"] + args + try: + if VERBOSE: + rc = subprocess.call(cmd) + out = "" + else: + proc = subprocess.run(cmd, capture_output=True, text=True) + rc, out = proc.returncode, (proc.stdout or "") + (proc.stderr or "") + except OSError as e: + raise BoardError(f"cannot run esptool: {e}") + if rc != 0: + tail = "\n".join(out.strip().splitlines()[-8:]) + raise BoardError(f"esptool failed while {what}:\n{tail}\nCheck the cable and the port, and that no other program " + f"(a terminal, ModemManager, another espdr tool) holds it. Run again with -v for the full output.") + + +def _wait_native(timeout=10.0): + end = time.monotonic() + timeout + while time.monotonic() < end: + found = native_ports() + if found: + return found[0] + time.sleep(0.3) + return None + + +def load_ram(kind, bridge=None, native=False, image=None, log=print): + """Loads the image into the chip's RAM and waits for the native port; returns its device name.""" + path = image_path(kind, image) + if native: + found = native_ports() + if len(found) != 1: + raise BoardError("expected exactly one ESP32-S3 on its native USB port (303a:1001); hold BOOT, tap RESET, and try again") + port, before = found[0], "usb-reset" + else: + port = find_bridge(bridge) + if not port: + raise BoardError("no USB-UART bridge found, so the firmware cannot be loaded. Connect the board's UART port (the " + "second USB-C port) as well, or put a board with only the native port in download mode (hold BOOT, " + "tap RESET) and use --native.") + before = "default-reset" + log(f"loading the {'transmitter' if kind == TX else 'receiver'} firmware into RAM through {port} (about 8 s) ...") + _esptool(["--port", port, "--before", before, "--after", "no-reset", "--no-stub", "load-ram", str(path)], "loading the image") + native_port = _wait_native() + if not native_port: + raise BoardError("the image was loaded, but no native USB port (303a:1001) appeared. Connect the board's native USB port " + "too, not only the UART port.") + return native_port + + +def flash_receiver(bridge=None, image=None, yes=False, log=print): + """Writes the receiver image with ESP-IDF's bootloader and a partition table to the flash: the board then starts the receiver + by itself at every power-up. Overwrites whatever is in the flash.""" + path = image_path(RX, image) + here = Path(__file__).resolve().parent + for base in (here / "images", here.parents[1] / "firmware" / "flash"): + parts = [base / "bootloader.bin", base / "partition-table.bin"] + if all(p.exists() for p in parts): + break + else: + raise BoardError("bootloader.bin and partition-table.bin are missing from the installation") + port = find_bridge(bridge) + if not port: + raise BoardError("no USB-UART bridge found; connect the board's UART port to write its flash") + log("This writes the bootloader (0x0), a partition table (0x8000) and the receiver (0x10000) to the board's flash. Whatever program " + "is in the flash now is lost. To get back to RAM-only use, run: python -m esptool erase-flash") + if not yes: + try: + answer = input("Continue? [y/N] ") + except EOFError: + answer = "" + if answer.strip().lower() != "y": + raise BoardError("not written") + log(f"writing the receiver to flash through {port} ...") + _esptool(["--port", port, "--baud", "921600", "--before", "default-reset", "--after", "hard-reset", "write-flash", + "--flash-mode", "dio", "--flash-freq", "80m", "--flash-size", "detect", + "0x0", str(parts[0]), "0x8000", str(parts[1]), "0x10000", str(path)], "writing the flash") + return _wait_native() + + +def reset(bridge=None): + """Resets the chip through the bridge's RTS/DTR lines so that it boots what its flash holds. Returns False if there is no bridge.""" + import serial + port = find_bridge(bridge) + if not port: + return False + with serial.Serial(port, 115200) as s: + s.dtr = False # GPIO0 high: boot from flash + s.rts = True # EN low + time.sleep(0.15) + s.rts = False + return True + + +def ensure(kind, port=None, bridge=None, load="auto", native=False, image=None, log=print): + """Makes sure that the firmware of `kind` (RX or TX) runs on the board and returns the native port's name. + + load: "auto" loads when another firmware (or none) answers, "never" only checks, "always" loads in any case.""" + found = find_native(port) + state = None + if found and load != "always": + state = kind_of(probe(found)) + if state == kind: + return found + if load == "never": + what = "no native USB port (303a:1001) found" if not found else ( + f"the {'transmitter' if state == TX else 'receiver'} firmware is running, not the {'transmitter' if kind == TX else 'receiver'}" + if state else f"{found} does not answer as an espdr firmware") + raise BoardError(f"{what}; run without --no-load to load the right firmware") + if state and state != kind: + log(f"the {'transmitter' if state == TX else 'receiver'} firmware is running; replacing it") + new = load_ram(kind, bridge=bridge, native=native, image=image, log=log) + flags = probe(new, timeout=3.0) + if kind_of(flags) != kind: + raise BoardError(f"the {kind} firmware was loaded, but {new} does not answer as one. Unplug and replug the board and try again.") + return new diff --git a/espdr/cli_rx.py b/espdr/cli_rx.py new file mode 100644 index 0000000..2876fbd --- /dev/null +++ b/espdr/cli_rx.py @@ -0,0 +1,91 @@ +"""espdr-rx: use an ESP32-S3 board as a receiver for SDR++ and other rtl_tcp programs (1.84 .. 2.79 GHz, 250 or 333 ksps).""" +import argparse +import sys + +from . import __version__, board, nb, rtltcp + +EPILOG = """\ +examples: + espdr-rx load the receiver firmware if needed and start the rtl_tcp server on 127.0.0.1:1234 + espdr-rx --decim 3 333 ksps (+-133 kHz usable) instead of 250 ksps (+-100 kHz) + espdr-rx --listen 0.0.0.0:1234 --ppm -5.7 reachable from other computers; correct the board's crystal by -5.7 ppm + espdr-rx --no-load do not touch the firmware: fail if the receiver is not running + espdr-rx --flash write the receiver into the board's flash: it then starts by itself at power-up + +In SDR++ choose the source "RTL-TCP", host 127.0.0.1, port 1234 and press play. The receiver firmware is loaded into the board's +RAM when it is not running (this needs the board's UART USB port as well as the native one; --no-load forbids it). Whatever runs +on the board, a reset brings back what its flash holds. +""" + + +def build_parser(): + p = argparse.ArgumentParser(prog="espdr-rx", description=__doc__, epilog=EPILOG, + formatter_class=argparse.RawDescriptionHelpFormatter) + p.add_argument("-V", "--version", action="version", version=f"espdr-rx {__version__}") + srv = p.add_argument_group("rtl_tcp server") + srv.add_argument("--listen", default="127.0.0.1:1234", metavar="HOST:PORT", help="address of the rtl_tcp server (default 127.0.0.1:1234)") + srv.add_argument("--decim", type=int, choices=(3, 4), default=4, + help="4: 250 ksps from the radio, +-100 kHz usable (default); 3: 333 ksps, +-133 kHz usable") + srv.add_argument("--ppm", type=float, default=0.0, metavar="PPM", + help="this board's crystal error, positive if it runs fast (a client's ppm setting adds to it)") + srv.add_argument("--gain", type=int, default=60, metavar="N", help="gain selector 0..127 until the client sets one (default 60)") + srv.add_argument("--gain-min", type=int, default=30, metavar="N", help="selector for a client gain of 0 dB (default 30)") + srv.add_argument("--gain-max", type=int, default=80, metavar="N", help="selector for a client gain of 49.6 dB (default 80)") + srv.add_argument("--no-dc-block", action="store_true", help="keep the radio's DC offset") + brd = p.add_argument_group("board") + brd.add_argument("--port", metavar="DEVICE", help="the board's native USB port (default: find it)") + brd.add_argument("--bridge-port", metavar="DEVICE", help="the board's USB-UART port, used to load the firmware (default: find it)") + brd.add_argument("--no-load", action="store_true", help="do not load firmware: fail if the receiver is not running") + brd.add_argument("--reload", action="store_true", help="load the receiver firmware even if it is running") + brd.add_argument("--native", action="store_true", help="load through the native port (board without a UART port: hold BOOT, tap RESET)") + brd.add_argument("--image", metavar="FILE", help="use this receiver image instead of the one of the package") + brd.add_argument("--flash", action="store_true", help="write the receiver to the board's flash (overwrites it), then serve") + brd.add_argument("--yes", action="store_true", help="with --flash: do not ask for confirmation") + p.add_argument("-v", "--verbose", action="store_true", help="more detail") + p.add_argument("--selftest", action="store_true", help="check the server against a simulated chip, no hardware, and exit") + return p + + +def run(args): + if args.selftest: + return rtltcp.selftest() + try: + host, port = rtltcp.parse_listen(args.listen) + except ValueError: + raise SystemExit("espdr-rx: --listen needs HOST:PORT, for example 127.0.0.1:1234") + if args.flash: + board.flash_receiver(bridge=args.bridge_port, image=args.image, yes=args.yes, log=rtltcp.log) + native_port = board.ensure(board.RX, port=args.port, bridge=args.bridge_port, + load="never" if args.no_load else ("always" if args.reload and not args.flash else "auto"), + native=args.native, image=args.image, log=rtltcp.log) + + def open_link(): + link = nb.open_link(board.find_native(args.port) or native_port) # the port can change if the board resets + nb.check_firmware(link) + return link + + bridge = rtltcp.Bridge(open_link, (host, port), ppm=args.ppm, gain=args.gain, gain_range=(args.gain_min, args.gain_max), + dc_block=not args.no_dc_block, decim=args.decim) + rate = rtltcp.SRC_RATES[args.decim] / 1e3 + rtltcp.log(f"espdr-rx {__version__}: receiver on {native_port}; rtl_tcp server on {bridge.address[0]}:{bridge.address[1]}, " + f"{rate:.0f} ksps, ppm {args.ppm:g}. In SDR++ choose RTL-TCP and press play. Ctrl-C ends.") + try: + bridge.run() + except KeyboardInterrupt: + pass + bridge.quit = True + return 0 + + +def main(argv=None): + args = build_parser().parse_args(argv) + board.VERBOSE = bool(args.verbose) + try: + return run(args) + except (board.BoardError, nb.ProtocolError) as e: + print(f"espdr-rx: {e}", file=sys.stderr) + return 1 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/espdr/cli_tx.py b/espdr/cli_tx.py new file mode 100644 index 0000000..d740013 --- /dev/null +++ b/espdr/cli_tx.py @@ -0,0 +1,549 @@ +"""espdr-tx: transmit FM or SSB voice, RTTY, or a constant-envelope IQ signal (M17, FSK, FM) from an ESP32-S3 board on the 13 cm band.""" +import argparse +import queue +import re +import signal +import sys +import threading +import time +from pathlib import Path + +from . import __version__, audio, board, config, iq, nb, polar, rtty, txlink, txmodes +from .config import LICENCE_NOTICE + +EPILOG = """\ +examples: + espdr-tx -f 2350.000 -i speech.wav FM voice from a WAV file + espdr-tx -f 2350.000 -m usb -i speech.wav the same as single sideband (upper) + espdr-tx -f 2350.000 -m usb -i soundcard SSB from the default sound card input + espdr-tx -f 2350.000 -m fm -i soundcard:2 --power -6 FM from input device 2, 6 dB below the strongest setting + arecord -f S16_LE -r 16000 -c 1 | espdr-tx -f 2350 -m usb -i - --rate 16000 raw samples from a pipe + sox music.mp3 -t wav - | espdr-tx -f 2350 -i - a WAV stream from a pipe + espdr-tx -f 2350 --test-tone 1000 --duration 5 a 1 kHz tone for 5 seconds + espdr-tx -f 2350 -m rtty --text "RYRY CQ CQ DE TEST" RTTY, 45.45 baud, 170 Hz shift (true FSK) + espdr-tx -f 2350 -m iq -i m17.cf32 --iq-rate 80000 a recorded constant-envelope IQ signal (M17, FSK, FM) + espdr-tx -f 2350 -i speech.wav --dry-run show what would happen, send nothing + espdr-tx --list-devices list sound card inputs + +The first time, add --accept-licence (the notice you accept is printed). The transmitter firmware is loaded into the board's RAM +automatically when it is not running (this needs the board's UART USB port as well; --no-load forbids it). A reset, or +`--restore`, brings back the receiver from the flash. +""" + + +def _config_dir(): + return config.config_dir() + + +def _licence_accepted(): + return config.licence_accepted() + + +def _accept_licence(): + config.accept_licence(__version__) + + +def build_parser(): + p = argparse.ArgumentParser(prog="espdr-tx", description=__doc__, epilog=EPILOG, + formatter_class=argparse.RawDescriptionHelpFormatter) + p.add_argument("-V", "--version", action="version", version=f"espdr-tx {__version__}") + main = p.add_argument_group("what to send") + main.add_argument("-f", "--freq", type=float, metavar="MHZ", help="carrier frequency in MHz (2320 .. 2450); required") + main.add_argument("-m", "--mode", choices=("fm", "usb", "lsb", "rtty", "iq"), default="fm", + help="fm: narrowband FM; usb or lsb: single sideband; rtty: text as two-tone FSK; iq: a complex baseband signal " + "with a constant envelope (M17, FSK, FM) from a file or a pipe, only its frequency is sent; for rtty and iq the " + "audio, FM and SSB options and --duration do not apply (default fm)") + src = p.add_argument_group("audio source") + src.add_argument("-i", "--input", metavar="SOURCE", + help="a WAV file, '-' for a pipe on stdin (a WAV stream or raw samples), or 'soundcard' / 'soundcard:DEVICE' " + "(DEVICE is a number or part of a name; see --list-devices)") + src.add_argument("--test-tone", type=float, metavar="HZ", help="send a sine tone instead of an audio source") + src.add_argument("--list-devices", action="store_true", help="list the sound card inputs and exit") + src.add_argument("--rate", type=int, metavar="HZ", help="sample rate of raw audio on stdin (required there; sound cards use theirs)") + src.add_argument("--channels", type=int, default=1, metavar="N", help="channels of raw audio on stdin, mixed to mono (default 1)") + src.add_argument("--format", default="s16le", choices=sorted(audio.RAW_FORMATS), help="sample format of raw audio on stdin (default s16le)") + src.add_argument("--loop", action="store_true", help="repeat a file until --duration or Ctrl-C") + src.add_argument("--gain", type=float, default=0.0, metavar="DB", help="raise (or lower) the audio before the automatic level control (default 0)") + src.add_argument("--no-agc", action="store_true", help="no automatic level control: the audio is only clipped at full scale") + lvl = p.add_argument_group("level and tuning") + lvl.add_argument("--power", type=float, default=0.0, metavar="DB", + help="transmit power in dB against the strongest setting, 0 .. -17.9 (default 0). A weaker setting leaves SSB " + "less amplitude range and costs quality; the absolute power is not calibrated") + lvl.add_argument("--ppm", type=float, default=0.0, metavar="PPM", + help="the board's crystal error: positive if the board transmits too high. Measure it against a known signal") + fmg = p.add_argument_group("FM") + fmg.add_argument("--deviation", type=float, default=2500.0, metavar="HZ", help="peak deviation at full scale audio (default 2500)") + fmg.add_argument("--no-preemph", action="store_true", help="no pre-emphasis (+6 dB per octave from 300 to 3000 Hz)") + ssb = p.add_argument_group("SSB") + ssb.add_argument("--carrier", type=float, default=0.05, metavar="FRACTION", + help="the carrier's share of the peak envelope, 0 .. 0.9: 0 suppresses it, 0.05 leaves a faint pilot to tune to (default)") + ssb.add_argument("--ssb-delay", type=float, default=1.0, metavar="UPDATES", + help="delay of the gain path against the frequency path in 25 us updates (default 1.0, measured on one board)") + rt = p.add_argument_group("RTTY (-m rtty)") + rt.add_argument("--text", metavar="TEXT", help="the text to send; the typed characters \\r and \\n are sent as carriage return and line feed. " + "Put your call sign in it: the tool adds none") + rt.add_argument("--text-file", metavar="FILE", help="send the text of this file ('-' for stdin); line ends are sent as CR LF") + rt.add_argument("--mark-hz", type=float, default=rtty.MARK_DEFAULT, metavar="HZ", + help="the mark tone above -f, 300 .. 2700 (default 2125). -f is the dial frequency of an upper-sideband transmitter, " + "as with pluto-tx: the same -f gives the same tones") + rt.add_argument("--shift-hz", type=float, default=rtty.SHIFT_DEFAULT, metavar="HZ", + help="space minus mark, 1 .. 1000 (default 170; common: 170, 425, 850)") + rt.add_argument("--baud-rate", type=float, default=rtty.BAUD_DEFAULT, metavar="BAUD", + help="20 .. 200 (default 45.45; common: 45.45, 50, 75, 100)") + rt.add_argument("--reverse", action="store_true", help="swap which tone is mark (for a station with flipped polarity)") + rt.add_argument("--edge", type=float, default=0.2, metavar="BITS", + help="rise time of the frequency steps in bit periods, 0 .. 0.5 (default 0.2; 0 = abrupt steps)") + rt.add_argument("--repeat-count", type=int, default=1, metavar="N", help="send the text N times, 1 .. 999 (default 1)") + rt.add_argument("--repeat-interval", type=float, default=10.0, metavar="SECONDS", + help="pause between two transmissions, 1 .. 86400; the transmitter is off in between (default 10)") + iqg = p.add_argument_group("IQ input (-m iq)") + iqg.add_argument("--iq-rate", type=float, metavar="HZ", help="sample rate of the IQ input, at least the update rate; required with -m iq. " + "The signal is centred on -f; its envelope is ignored") + iqg.add_argument("--iq-format", choices=sorted(iq.FORMATS), default="cf32", help="sample format of the IQ input: cf32 (float32 I and Q, " + "GNU Radio complex), cs16 or cs8 (default cf32)") + iqg.add_argument("--iq-deviation", type=float, default=4000.0, metavar="HZ", + help="the largest frequency excursion of the signal, 0 .. 15000: the transmitter keeps this much of its +-19 kHz range free " + "when it moves the LO (default 4000, enough for M17)") + run = p.add_argument_group("session") + run.add_argument("--duration", type=float, metavar="SECONDS", help="stop after this many seconds (default: until the source ends)") + run.add_argument("--update-rate", type=int, default=40000, metavar="HZ", help="records per second sent to the chip, 8000 .. 40000 (default 40000)") + run.add_argument("--thermal", choices=("auto", "off", "sensor", "nominal"), default="auto", + help="cancel the carrier's thermal drift with a model of the board: 'sensor' reads the chip's temperature first, 'nominal' assumes its idle " + "temperature, 'auto' (default) is 'sensor' if the board has a model file (thermal-SERIAL.json, SERIAL being that of its USB-UART bridge, or thermal.json " + "in the configuration directory, or --thermal-model) and 'off' otherwise") + run.add_argument("--thermal-model", metavar="FILE", help="JSON file with the thermal model's numbers of this board (see espdr.thermal.DEFAULT and scripts/drift/fit_thermal.py); " + "without it 'sensor' and 'nominal' use the built-in numbers of the first tested board") + run.add_argument("--drift", type=int, default=210, metavar="HZ", + help="thermal frequency drift to cancel at switch-on, measured on one board (default 210; 0 = off)") + run.add_argument("--dry-run", action="store_true", help="show the settings and send nothing (the board is not touched)") + run.add_argument("--accept-licence", action="store_true", help="confirm the notice that is printed (needed once)") + run.add_argument("-q", "--quiet", action="store_true", help="no progress line") + run.add_argument("-v", "--verbose", action="store_true", help="more detail") + brd = p.add_argument_group("board") + brd.add_argument("--port", metavar="DEVICE", help="the board's native USB port (default: find it)") + brd.add_argument("--bridge-port", metavar="DEVICE", help="the board's USB-UART port, used to load the firmware (default: find it)") + brd.add_argument("--no-load", action="store_true", help="do not load firmware: fail if the transmitter is not running") + brd.add_argument("--reload", action="store_true", help="load the transmitter firmware even if it is running") + brd.add_argument("--native", action="store_true", help="load through the native port (board without a UART port: hold BOOT, tap RESET)") + brd.add_argument("--image", metavar="FILE", help="use this transmitter image instead of the one of the package") + brd.add_argument("--restore", action="store_true", help="when done, reset the board so that it boots the receiver from its flash") + p.add_argument("--selftest", action="store_true", help="check the signal processing without hardware and exit") + return p + + +def _modulator(args, power_db, plan=None): + if args.mode == "iq": + return polar.IqModulator(args.iq_rate, rate=args.update_rate, power_db=power_db, static_hz=plan["static_hz"]) + if args.mode == "rtty": + return txmodes.FskModulator(rate=args.update_rate, power_db=power_db, static_hz=plan["static_hz"]) + if args.mode == "fm": + return txmodes.FmModulator(rate=args.update_rate, deviation=args.deviation, power_db=power_db, preemph=not args.no_preemph, + agc=not args.no_agc, gain_db=args.gain) + return txmodes.SsbModulator(rate=args.update_rate, sideband=args.mode, carrier=args.carrier, power_db=power_db, + delay=args.ssb_delay, agc=not args.no_agc, gain_db=args.gain) + + +def _blocks(args, stop): + """(8 kHz audio blocks as a generator, the sound card source or None, a description).""" + if args.test_tone: + return audio.test_tone(args.test_tone, 0.5), None, f"test tone {args.test_tone:g} Hz" + src = audio.open_source(args.input, rate=args.rate, channels=args.channels, fmt=args.format) + live = isinstance(src, audio.SoundCardSource) + desc = f"sound card {src.name!r} at {src.rate} Hz" if live else f"{args.input if args.input != '-' else 'stdin'} ({src.rate} Hz)" + mono = audio.Mono8k(src) + can_loop = args.loop and not live and args.input != "-" + + def gen(): + while not stop.is_set(): + for b in mono.blocks(): + yield b + if stop.is_set(): + return + if not can_loop: + return + mono.source.close() + mono.source = audio.open_source(args.input, rate=args.rate, channels=args.channels, fmt=args.format) + return gen(), (mono if live else None), desc + + +def _rtty_text(args): + if args.text_file: + raw = sys.stdin.read() if args.text_file == "-" else Path(args.text_file).read_text(errors="replace") + return re.sub(r"\r?\n", "\r\n", raw) + return args.text.replace("\\r", "\r").replace("\\n", "\n") + + +def _check_rtty(args): + """Arguments of -m rtty; returns the text.""" + if (args.text is None) == (args.text_file is None): + raise SystemExit("espdr-tx: -m rtty needs exactly one of --text and --text-file") + if args.input or args.test_tone: + raise SystemExit("espdr-tx: -m rtty sends text; -i and --test-tone are for the audio modes") + if not 300 <= args.mark_hz <= 2700: + raise SystemExit("espdr-tx: --mark-hz must be between 300 and 2700") + if not 1 <= args.shift_hz <= 1000: + raise SystemExit("espdr-tx: --shift-hz must be between 1 and 1000") + if not 20 <= args.baud_rate <= 200: + raise SystemExit("espdr-tx: --baud-rate must be between 20 and 200") + if not 0 <= args.edge <= 0.5: + raise SystemExit("espdr-tx: --edge must be between 0 and 0.5") + if not 1 <= args.repeat_count <= 999: + raise SystemExit("espdr-tx: --repeat-count must be between 1 and 999") + if not 1 <= args.repeat_interval <= 86400: + raise SystemExit("espdr-tx: --repeat-interval must be between 1 and 86400") + text = _rtty_text(args) + if rtty.estimate_duration(text, args.baud_rate) > 3500: + raise SystemExit("espdr-tx: the text takes more than 3500 s to send; the chip ends a transmission after 3600 s. Send it in parts") + return text + + +def _rtty_plan(args): + """Where the two tones go. The lower tone is -f + mark; the board's LO is moved to a PLL word that is easy to program (txlink.choose_lo) + and a constant in every record makes up for the move, as far as the records reach (about +-19 kHz). The LO is the one the PLL word + really programs, and the constant and the shift are whole record units (28.6 Hz): the tones are within about 15 Hz of the wanted ones.""" + ppm = 1.0 + args.ppm * 1e-6 + low = args.freq * 1e6 + args.mark_hz + if low < txlink.TX_MIN_HZ or low + args.shift_hz > txlink.TX_MAX_HZ: + raise SystemExit(f"espdr-tx: the tones ({low / 1e6:.6f} and {(low + args.shift_hz) / 1e6:.6f} MHz) are outside 2320 .. 2450 MHz") + lo_hz, _ = txlink.choose_lo(low / ppm) + lo_real = txlink.word_hz(txlink.lo_word(lo_hz)) * ppm + unit = txmodes.Q4_HZ * ppm # one record unit on the air + shift_q4 = max(1, int(round(args.shift_hz / unit))) + static_q4 = int(round((low - lo_real) / unit)) + clamped = min(max(static_q4, -txmodes.MAX_Q4), txmodes.MAX_Q4 - shift_q4) + low_real = lo_real + clamped * unit + return dict(lo_hz=lo_hz, static_hz=clamped * txmodes.Q4_HZ, shift_nominal=shift_q4 * txmodes.Q4_HZ, low_hz=low_real, + shift_real=shift_q4 * unit, miss_hz=low_real - low) + + +def _check_iq(args): + """Arguments of -m iq.""" + if not args.input or args.input == "soundcard" or args.input.startswith("soundcard:") or args.test_tone: + raise SystemExit("espdr-tx: -m iq reads a file or '-' (a pipe) with -i; a sound card and --test-tone are for the audio modes") + if not args.iq_rate: + raise SystemExit("espdr-tx: -m iq needs --iq-rate, the sample rate of the IQ input") + if args.iq_rate < args.update_rate: + raise SystemExit(f"espdr-tx: --iq-rate must be at least the update rate ({args.update_rate} Hz)") + if args.iq_rate > 20e6: + raise SystemExit("espdr-tx: --iq-rate above 20 MHz is not supported") + if not 0 <= args.iq_deviation <= 15000: + raise SystemExit("espdr-tx: --iq-deviation must be between 0 and 15000") + + +def _iq_plan(args): + """Where the LO goes and what the records add so that the signal sits on -f (txlink.plan_lo), with room left for its deviation.""" + p = txlink.plan_lo(args.freq * 1e6, args.ppm, args.iq_deviation) + if not txlink.TX_MIN_HZ <= p["lo_hz"] <= txlink.TX_MAX_HZ: + raise SystemExit(f"espdr-tx: {args.freq:g} MHz is too close to the edge of 2320 .. 2450 MHz") + return p + + +def _model_names(args): + return config.model_names(args.bridge_port) + + +def _board_model(args): + return config.board_model(args.bridge_port) + + +def _thermal(args, session, out): + """The drift correction for this transmission (espdr.thermal.Thermal) or None. 'auto' switches it on when the board has a model file.""" + from . import thermal + mode, path = args.thermal, args.thermal_model + if mode == "auto": + path = path or _board_model(args) + if not path: + if args.verbose: + print(f"thermal drift correction is off: no model file for this board (looked for {' or '.join(_model_names(args))} in {_config_dir()})", file=out) + return None + mode = "sensor" + if mode == "off": + return None + try: + params = thermal.load_params(path) + except (OSError, ValueError) as e: + raise SystemExit(f"espdr-tx: cannot read the thermal model {path}: {e}") + start_c = params["idle"] + if mode == "sensor": + try: + start_c = session.chip_temperature() + except (nb.CommandError, OSError) as e: + print(f"warning: the chip's temperature could not be read ({e}); assuming {start_c:g} C", file=out) + c = thermal.Thermal(start_c, args.update_rate, args.freq * 1e6, params) + peak = max(abs(c.correction_hz(int(args.update_rate * 150)))) + print(f"thermal drift correction ({path or 'built-in model'}): chip {start_c:.1f} C {'(read)' if mode == 'sensor' else '(assumed)'}, " + f"up to {peak:.0f} Hz within 150 s", file=out) + return c + + +def _transmit(args, out, mod, session, lo_hz, stop, interrupted, blocks, live, stream): + """One transmission: configure and begin the chip, feed it, report. Returns (the chip's summary, ended by the user).""" + import numpy as np + correct = _thermal(args, session, out) + session.configure(lo_hz, args.update_rate, drift_hz=args.drift, limit_s=3600) + session.begin(expect_word=txlink.lo_word(lo_hz)) + + q = queue.Queue(maxsize=64) + err = [] + level = [-120.0] # input level in dBFS of the last audio block, shown in the progress line + + def producer(): + try: + for b in blocks: + if stream is None: + level[0] = 20 * np.log10(max(float(np.sqrt(np.mean(np.square(b)))), 1e-6)) + r = mod.process(b) + q.put(correct.apply(r) if correct else r) + if stream is None: + for _ in range(10): # flush the filters with silence + r = mod.process(np.zeros(160)) + q.put(correct.apply(r) if correct else r) + except Exception as e: # noqa: BLE001 - reported by the main thread + err.append(e) + finally: + q.put(None) + + th = threading.Thread(target=producer, daemon=True) + th.start() + started = time.monotonic() + last_print = [0.0] + warned = [False] + trim = [0.0] + by_user = [False] + + def on_status(ev): + if live is not None: + e = (ev["fill"] - 8000) / 8000.0 + trim[0] = max(-1000.0, min(1000.0, trim[0] + 5.0 * e)) # follow the sound card's clock + live.trim(trim[0]) + now = time.monotonic() + if not args.quiet and now - last_print[0] > 0.5: + last_print[0] = now + what = f"sent {100 * stream.fraction():3.0f} %" if stream is not None else f"audio {level[0]:6.1f} dBFS" + print(f"\r on air {now - started:6.1f} s {what} buffer {ev['fill'] * 1000 // args.update_rate:4d} ms underruns {ev['underruns']} late {ev['late']} ", + end="", file=out, flush=True) + if stream is None and level[0] < -70 and now - started > 3 and not warned[0]: + warned[0] = True + print("\nwarning: almost no audio arrives (input level below -70 dBFS). Is the microphone muted or the wrong input chosen? " + "See --list-devices and -i soundcard:NUMBER.", file=out) + if stream is None and args.duration and now - started >= args.duration: + by_user[0] = True + stop.set() + + def on_sigint(*_): + interrupted.set() + by_user[0] = True + stop.set() + + old = signal.signal(signal.SIGINT, on_sigint) + try: + summary = session.stream(q, target_fill=8000, on_status=on_status, stop=stop) + finally: + signal.signal(signal.SIGINT, old) + stop.set() + print("", file=out) + if err: + raise SystemExit(f"espdr-tx: {err[0]}") + print(f"done: {txlink.END_REASONS.get(summary['reason'], summary['reason'])}; underruns {summary['underruns']}, late updates {summary['late']}", file=out) + return summary, by_user[0] + + +def run(args, out=None): + out = out or sys.stderr + if args.selftest: + return selftest() + if args.list_devices: + for line in audio.list_devices() or [" (no sound card input found)"]: + print(line) + return 0 + is_rtty, is_iq = args.mode == "rtty", args.mode == "iq" + if args.freq is None: + raise SystemExit("espdr-tx: --freq is required (for example: espdr-tx -f 2350 -i speech.wav); see espdr-tx -h") + if is_rtty: + text = _check_rtty(args) + else: + if args.text is not None or args.text_file is not None or args.repeat_count != 1: + raise SystemExit("espdr-tx: --text, --text-file and --repeat-count belong to -m rtty") + if is_iq: + _check_iq(args) + elif args.iq_rate is not None: + raise SystemExit("espdr-tx: --iq-rate belongs to -m iq") + elif not args.input and not args.test_tone: + raise SystemExit("espdr-tx: give an audio source with -i (a WAV file, '-' for stdin, or 'soundcard') or use --test-tone") + if not txlink.TX_MIN_HZ / 1e6 <= args.freq <= txlink.TX_MAX_HZ / 1e6: + raise SystemExit(f"espdr-tx: {args.freq:g} MHz is outside 2320 .. 2450 MHz, the only range this transmitter sends in") + if not 8000 <= args.update_rate <= 40000 or args.update_rate % 8000: + raise SystemExit("espdr-tx: --update-rate must be 8000, 16000, 24000, 32000 or 40000") + if not 0 <= args.carrier <= 0.9: + raise SystemExit("espdr-tx: --carrier must be between 0 and 0.9") + plan = _rtty_plan(args) if is_rtty else _iq_plan(args) if is_iq else None + try: + mod = _modulator(args, args.power, plan) + except ValueError as e: + raise SystemExit(f"espdr-tx: {e}") + + if is_rtty: + lo_hz = plan["lo_hz"] + frames = rtty.message_frames(text, args.baud_rate) + duration = rtty.duration_s(frames, args.baud_rate) + low_hz = plan["low_hz"] + mark_is = "high" if args.reverse else "low" + print(f"espdr-tx {__version__}: RTTY (FSK) low tone {low_hz / 1e6:.6f} MHz, high tone {(low_hz + plan['shift_real']) / 1e6:.6f} MHz " + f"(shift {plan['shift_real']:.1f} Hz, mark is the {mark_is} tone), {args.baud_rate:g} baud, {len(text)} characters, about {duration:.1f} s, " + f"power {args.power:g} dB, gain code {txmodes.peak_code(args.power)}, edge {args.edge:g} bit, {args.update_rate} updates/s", file=out) + if abs(plan["miss_hz"]) > 20: + print(f"warning: the PLL word cannot reach the wanted frequency here; the tones are {plan['miss_hz']:+.0f} Hz off. " + f"Tune your receiver to the tones above, or change -f by a few kHz", file=out) + elif is_iq: + lo_hz = plan["lo_hz"] + print(f"espdr-tx {__version__}: IQ input ({args.iq_rate:g} samples/s, {args.iq_format}) centred on {plan['center_hz'] / 1e6:.6f} MHz, " + f"power {args.power:g} dB, gain code {txmodes.peak_code(args.power)}, excursions up to {args.iq_deviation:g} Hz kept free, " + f"{args.update_rate} updates/s", file=out) + if abs(plan["miss_hz"]) > 20: + print(f"warning: the PLL word cannot reach the wanted frequency here; the signal is {plan['miss_hz']:+.0f} Hz off. " + f"Change -f by a few kHz or tune your receiver to {plan['center_hz'] / 1e6:.6f} MHz", file=out) + else: + # the carrier the board has to produce: the request corrected for the crystal, moved a little if its PLL word is near a byte boundary + want_hz = args.freq * 1e6 / (1.0 + args.ppm * 1e-6) + lo_hz, shift = txlink.choose_lo(want_hz) + actual = lo_hz * (1.0 + args.ppm * 1e-6) / 1e6 + print(f"espdr-tx {__version__}: {mod.name} voice at {actual:.4f} MHz" + + (f" (you asked for {args.freq:.4f}; the PLL word allows only this near it)" if abs(actual - args.freq) > 0.00005 else "") + + f", power {args.power:g} dB, gain codes {txmodes.peak_code(args.power)}..{txmodes.GAIN_WEAKEST}" + + (f", carrier {args.carrier:g}" if args.mode != "fm" else f", deviation {args.deviation:g} Hz") + + f", {args.update_rate} updates/s", file=out) + if args.power < -9 and args.mode != "fm": + print(f"note: at {args.power:g} dB the SSB amplitude range shrinks to {txmodes.RANGE_DB + args.power:.1f} dB; expect more distortion", file=out) + if not (_licence_accepted() or args.accept_licence): + print(LICENCE_NOTICE, file=out) + raise SystemExit("espdr-tx: read the notice above; run once with --accept-licence to confirm it") + if args.accept_licence and not _licence_accepted(): + _accept_licence() + + def sources(): + stop = threading.Event() + if is_rtty: + stream = rtty.OffsetStream(frames, args.update_rate, args.baud_rate, plan["shift_nominal"], args.reverse, args.edge) + return stop, stream.blocks(), None, f"RTTY text, {len(text)} characters", stream + if is_iq: + src = iq.open_iq(args.input, args.iq_rate, args.iq_format) + return stop, src.blocks(), None, f"IQ {src.name} ({args.iq_rate:g} Hz, {args.iq_format})", src + blocks, live, desc = _blocks(args, stop) + return stop, blocks, live, desc, None + + stop, blocks, live, desc, stream = sources() + if args.dry_run: + print(f"dry run: would send {desc}; nothing is sent and the board is not touched", file=out) + return 0 + print(f"source: {desc}", file=out) + port = board.ensure(board.TX, port=args.port, bridge=args.bridge_port, load="never" if args.no_load else ("always" if args.reload else "auto"), + native=args.native, image=args.image, log=lambda m: print(m, file=out)) + link = nb.open_link(port) + session = txlink.Session(link) + interrupted = threading.Event() + summary, by_user = None, False + for n in range(args.repeat_count): + if n: + print(f"pause of {args.repeat_interval:g} s; the transmitter is off", file=out) + if interrupted.wait(args.repeat_interval): + break + stop, blocks, live, desc, stream = sources() + print(f"source: {desc} (transmission {n + 1} of {args.repeat_count})", file=out) + summary, by_user = _transmit(args, out, mod, session, lo_hz, stop, interrupted, blocks, live, stream) + if interrupted.is_set() or summary["reason"] not in (0, 2): + break + if args.restore: + print("resetting the board: it boots what its flash holds", file=out) + if not board.reset(args.bridge_port): + print("no UART port found; unplug and replug the board (or press RESET) to get the receiver back", file=out) + return 0 if summary is None or summary["reason"] in (0, 2) or by_user else 1 + + +def selftest(): + """No hardware: modulators against an ideal polar transmitter, the session against a simulated chip.""" + import numpy as np + from . import sim + ok = True + + def check(name, good, detail=""): + nonlocal ok + ok &= bool(good) + print(f"{name}: {'OK' if good else 'FAIL'} {detail}") + + def ideal(rec, rate=40000): + q4 = (rec & 0xFFFF).astype(np.uint16).view(np.int16).astype(float) + ph = 2 * np.pi * np.cumsum(q4 * txmodes.Q4_HZ) / rate + amp = 10 ** (-(txmodes.RANGE_DB - txmodes.db_of_code(((rec >> 16) & 0xFF).astype(float))) / 20) + return np.roll(amp, -1) * np.exp(1j * ph) + + t = np.arange(8000) / 8000.0 + x = 0.5 * np.sin(2 * np.pi * 700 * t) + 0.5 * np.sin(2 * np.pi * 1700 * t) + for carrier in (0.55, 0.05, 0.0): + m = txmodes.SsbModulator(carrier=carrier, agc=False) + rec = np.concatenate([m.process(x[i:i + 160]) for i in range(0, len(x), 160)]) + s = ideal(rec)[8000:-2000] + sp = np.abs(np.fft.fftshift(np.fft.fft(s * np.hanning(len(s))))) + f = np.fft.fftshift(np.fft.fftfreq(len(s), 1 / 40000)) + line = lambda hz: sp[np.abs(f - hz) < 40].max() + r = 20 * np.log10(min(line(700), line(1700)) / max(line(-700), line(-1700))) + check(f"SSB two-tone, carrier {carrier:g}: unwanted sideband", r > 40, f"{r:.1f} dB below the wanted tones") + m = txmodes.FmModulator(deviation=2500, agc=False, preemph=False) + rec = np.concatenate([m.process(0.8 * np.sin(2 * np.pi * 1000 * t)[i:i + 160]) for i in range(0, 8000, 160)]) + dev = np.abs((rec[len(rec) // 2:] & 0xFFFF).astype(np.uint16).view(np.int16)).max() * txmodes.Q4_HZ + check("FM deviation", abs(dev - 2000) < 200, f"{dev:.0f} Hz for 0.8 of 2500 Hz (the band-pass is not flat at 1 kHz)") + audio_hz = 2500 * 0.8 * np.sin(2 * np.pi * 1000 * np.arange(8000) / 40000) + fm_iq = np.exp(2j * np.pi * np.cumsum(np.repeat(audio_hz, 2)) / 80000) # FM at 80 kHz, as an IQ file would hold it + im = polar.IqModulator(80000) + rec = np.concatenate([im.process(fm_iq[i:i + 1600]) for i in range(0, len(fm_iq), 1600)]) + f = (rec[100:] & 0xFFFF).astype(np.uint16).view(np.int16) * txmodes.Q4_HZ + check("IQ input", np.sqrt(np.mean((f - audio_hz[100:len(f) + 100]) ** 2)) < 60, f"FM IQ comes back within {np.sqrt(np.mean((f - audio_hz[100:len(f) + 100]) ** 2)):.0f} Hz rms") + check("power setting", [txmodes.peak_code(p) for p in (0, -6, -12)] == [64, 87, 107], "codes for 0, -6, -12 dB") + + text = "RYRY DE TEST 123. CQ (OK)?" + stream = rtty.OffsetStream(rtty.message_frames(text), 40000, rtty.BAUD_DEFAULT, 6 * txmodes.Q4_HZ) + m = txmodes.FskModulator(static_hz=-3000.0) + rec = np.concatenate([m.process(b) for b in stream.blocks()]) + sig = ideal(rec) + inst = np.angle(sig[1:] * np.conj(sig[:-1])) * 40000 / (2 * np.pi) + check("RTTY text through the polar model", rtty.decode_frequency(inst, 40000) == text and len({int(r >> 16) for r in rec}) == 1, + f"{len(text)} characters") + + lo, _ = txlink.choose_lo(2_350_000_000) + esp = sim.SimTx() + s = txlink.Session(nb.Link(esp)) + s.configure(lo, 40000, 210, 60) + s.begin(expect_word=txlink.lo_word(lo)) + m = txmodes.SsbModulator(carrier=0.05) + q = queue.Queue() + recs = [m.process(x[i:i + 160]) for i in range(0, len(x), 160)] + for r in recs: + q.put(r) + q.put(None) + summary = s.stream(q) + sent = np.concatenate(recs) + same = np.array_equal(np.array(esp.played[:len(sent)], dtype=np.uint32), sent) + check("session against the simulated chip", summary["reason"] == 0 and summary["underruns"] == 0 and same, + f"{len(sent)} records, end: {txlink.END_REASONS[summary['reason']]}") + for hz in (2_320_000_000, 2_385_000_000, 2_449_999_000): + lo2, shift = txlink.choose_lo(hz) + check(f"LO choice near {hz / 1e6:.3f} MHz", txlink.TX_LOW_MARGIN <= txlink.lo_word(lo2) & 0xFF <= 255 - txlink.TX_LOW_MARGIN and abs(shift) <= 22_000, + f"moved by {shift / 1e3:+.1f} kHz") + print("SELFTEST", "PASSED" if ok else "FAILED") + return 0 if ok else 1 + + +def main(argv=None): + args = build_parser().parse_args(argv) + board.VERBOSE = bool(args.verbose) + try: + return run(args) + except (board.BoardError, txlink.TxError, audio.AudioError, iq.IqError, nb.ProtocolError) as e: + print(f"espdr-tx: {e}", file=sys.stderr) + return 1 + except KeyboardInterrupt: + print("", file=sys.stderr) + return 130 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/espdr/config.py b/espdr/config.py new file mode 100644 index 0000000..87aeb63 --- /dev/null +++ b/espdr/config.py @@ -0,0 +1,47 @@ +"""Where the tools keep their settings, and what every front end (the command line, other programs that use the transmitter) needs to know +about them: the licence acceptance, and the thermal model file of a board.""" +import os +from pathlib import Path + +LICENCE_NOTICE = """\ +Transmitting takes an amateur radio licence, and you are responsible for what you send. This transmitter is a Wi-Fi chip's +test tone, steered in frequency and amplitude; it was measured on one board only. Its power is not calibrated (some microwatts +at the antenna of a plain dev board, an estimate), its harmonics and spurious emissions were not measured, and its frequency +is only as good as the board's crystal (up to +-24 kHz; correct it with --ppm). It sends only inside 2320..2450 MHz. +""" + + +def config_dir(): + base = os.environ.get("XDG_CONFIG_HOME") or str(Path.home() / ".config") + return Path(base) / "espdr" + + +def licence_accepted(): + return (config_dir() / "licence-accepted").exists() + + +def accept_licence(version=""): + d = config_dir() + d.mkdir(parents=True, exist_ok=True) + (d / "licence-accepted").write_text(f"accepted with espdr-tx {version}\n") + + +def model_names(bridge_port=None): + """The names of the thermal model files of the board, best first: thermal-.json, then + thermal.json. (The native port reports the same serial number on every board while the firmware runs, the bridge's differs.) With + several boards attached the bridge must be named with `bridge_port`.""" + from serial.tools import list_ports + + from . import board + bridges = [p for p in list_ports.comports() if (p.vid, p.pid) in board.BRIDGES and p.serial_number] + if bridge_port: + bridges = [p for p in bridges if p.device == bridge_port] + return ([f"thermal-{bridges[0].serial_number}.json"] if len(bridges) == 1 else []) + ["thermal.json"] + + +def board_model(bridge_port=None): + """The path of the board's thermal model file, or None if it has none.""" + for n in model_names(bridge_port): + if (config_dir() / n).exists(): + return str(config_dir() / n) + return None diff --git a/espdr/dsp.py b/espdr/dsp.py new file mode 100644 index 0000000..413a07e --- /dev/null +++ b/espdr/dsp.py @@ -0,0 +1,202 @@ +"""Signal processing for the transmitter, numpy only: streaming filters, a resampler with a controllable ratio, a speech AGC. + +Everything works on blocks of any size and keeps its state between calls, so a microphone (or a pipe) can be processed as it arrives. +""" +import numpy as np + + +# ---- filter design (windowed sinc) ----------------------------------------------------------------------------------------- + +def _kaiser(n, beta): + return np.kaiser(n, beta) + + +def lowpass(taps, cutoff, fs, beta=7.0): + """Linear-phase low-pass, `taps` odd, `cutoff` in Hz.""" + n = np.arange(taps) - (taps - 1) / 2 + h = 2 * cutoff / fs * np.sinc(2 * cutoff / fs * n) * _kaiser(taps, beta) + return h / h.sum() + + +def bandpass(taps, lo, hi, fs, beta=7.0): + """Linear-phase band-pass with unity gain in the middle of the band.""" + n = np.arange(taps) - (taps - 1) / 2 + w = _kaiser(taps, beta) + h = (2 * hi / fs * np.sinc(2 * hi / fs * n) - 2 * lo / fs * np.sinc(2 * lo / fs * n)) * w + fc = 0.5 * (lo + hi) + gain = abs(np.sum(h * np.exp(-2j * np.pi * fc / fs * n))) + return h / gain + + +def hilbert(taps, beta=6.0): + """Hilbert-transformer FIR (odd length, type III): positive frequencies get -90 degrees... applied as x + j*h(x) it gives the + analytic signal of x delayed by (taps-1)/2 samples.""" + assert taps % 2 == 1 + m = (taps - 1) // 2 + n = np.arange(-m, m + 1) + h = np.zeros(taps) + odd = n % 2 != 0 + h[odd] = 2.0 / (np.pi * n[odd]) + return h * _kaiser(taps, beta) + + +# ---- streaming blocks -------------------------------------------------------------------------------------------------------- + +class Fir: + """Streaming FIR filter: y[n] = sum h[k] x[n-k]; the output has the length of the input (the first taps-1 outputs see zeros).""" + + def __init__(self, h): + self.h = np.asarray(h, dtype=float) + self.tail = np.zeros(len(self.h) - 1) + + @property + def delay(self): + return (len(self.h) - 1) / 2 + + def process(self, x): + x = np.asarray(x) + buf = np.concatenate([self.tail.astype(x.dtype, copy=False), x]) + y = np.convolve(buf, self.h, mode="valid") + self.tail = buf[len(buf) - (len(self.h) - 1):] + return y + + +class Delay: + def __init__(self, n): + self.tail = np.zeros(n) + self.n = n + + def process(self, x): + buf = np.concatenate([self.tail, x]) + self.tail = buf[len(buf) - self.n:] if self.n else buf[:0] + return buf[:len(x)] + + +class Analytic: + """x -> x + j*H{x} (positive frequencies only: the upper sideband when mixed up), delayed by `delay` samples.""" + + def __init__(self, taps=255): + self.h = Fir(hilbert(taps)) + self.d = Delay((taps - 1) // 2) + self.delay = (taps - 1) // 2 + + def process(self, x): + return self.d.process(x) + 1j * self.h.process(x) + + +class Iir1: + """First-order section y[n] = b0 x[n] + b1 x[n-1] - a1 y[n-1].""" + + def __init__(self, b0, b1, a1): + self.b0, self.b1, self.a1 = b0, b1, a1 + self.x1 = self.y1 = 0.0 + + def process(self, x): + y = np.empty(len(x)) + x1, y1, b0, b1, a1 = self.x1, self.y1, self.b0, self.b1, self.a1 + for i, v in enumerate(x): + y1 = b0 * v + b1 * x1 - a1 * y1 + x1 = v + y[i] = y1 + self.x1, self.y1 = x1, y1 + return y + + +def preemphasis(fs, f_lo=300.0, f_hi=3000.0): + """+6 dB per octave between f_lo and f_hi (the FM voice pre-emphasis), bilinear transform of (1 + s/w1) / (1 + s/w2).""" + w1, w2 = 2 * np.pi * f_lo, 2 * np.pi * f_hi + k = 2 * fs + b0, b1 = (1 + k / w1), (1 - k / w1) + a0, a1 = (1 + k / w2), (1 - k / w2) + # normalise to unity gain at f_lo-ish (DC gain 1) + return Iir1(b0 / a0, b1 / a0, a1 / a0) + + +class Resampler: + """Streaming resampler for any ratio, real or complex input. Polyphase kernel table with linear interpolation between its entries + (better than 70 dB image rejection); `trim_ppm` changes the ratio slightly (to follow a sound card's clock). The delay is `latency` + input samples.""" + + def __init__(self, fs_in, fs_out, taps=24, phases=128, beta=8.0, cutoff=0.45): + self.step0 = fs_in / fs_out # input samples per output sample + self.trim = 0.0 + scale = max(1.0, self.step0) # a downsampler needs a wider kernel in input samples + self.k = int(np.ceil(taps * scale / 2)) * 2 # kernel length in input samples (even) + self.phases = phases + fc = cutoff / scale # cutoff in cycles per input sample + j = np.arange(self.k * phases + 2) + d = (j - self.k * phases / 2) / phases # position in input samples, -k/2 .. k/2 + win = np.kaiser(self.k * phases + 2, beta) + win[np.abs(d) > self.k / 2] = 0 + self.table = 2 * fc * np.sinc(2 * fc * d) * win + self.buf = np.zeros(self.k) # history, so that the first outputs see silence + self.base = -self.k # absolute index of buf[0] + self.n_in = 0 + self.t = 0.0 # absolute input position of the next output + self.latency = self.k / 2 + + @property + def step(self): + return self.step0 * (1.0 + self.trim * 1e-6) + + def process(self, x): + x = np.asarray(x) + if len(x): + self.buf = np.concatenate([self.buf.astype(np.result_type(self.buf, x)), x]) + self.n_in += len(x) + half = self.k // 2 + out = [] + # outputs are possible while floor(t) + half is available + last_ok = self.n_in - 1 + n_out = int(np.floor((last_ok - half - self.t) / self.step)) + 1 if last_ok - half >= self.t else 0 + if n_out > 0: + t = self.t + self.step * np.arange(n_out) + i0 = np.floor(t).astype(np.int64) + frac = t - i0 + m = np.arange(-half + 1, half + 1) # k taps around floor(t) + idx = i0[:, None] + m[None, :] - self.base # position in buf + jf = (frac[:, None] - m[None, :] + half) * self.phases + j0 = np.floor(jf).astype(np.int64) + w = jf - j0 + kern = (1 - w) * self.table[j0] + w * self.table[j0 + 1] + out = np.sum(self.buf[idx] * kern, axis=1) + self.t += self.step * n_out + # keep only what later outputs can still touch + keep_from = int(np.floor(self.t)) - half + 1 + drop = keep_from - self.base + if drop > 0: + self.buf = self.buf[drop:] + self.base += drop + return np.asarray(out) if n_out > 0 else np.zeros(0, dtype=self.buf.dtype) + + +class Agc: + """Speech AGC and limiter for blocks: raises quiet speech up to `target` (a fraction of full scale) with a limited gain, follows + peaks quickly and lets go slowly, and clips at +-1. Gain changes are ramped across the block.""" + + def __init__(self, fs, target=0.5, max_gain_db=30.0, release_s=0.6, gain_db=0.0): + self.fs, self.target = fs, target + self.max_gain = 10 ** (max_gain_db / 20) + self.release = release_s + self.manual = 10 ** (gain_db / 20) + self.env = 1e-3 + self.gain = 1.0 + + def process(self, x): + n = len(x) + if n == 0: + return x + peak = float(np.max(np.abs(x))) * self.manual + self.env = max(peak, self.env * np.exp(-n / self.fs / self.release)) + want = min(self.max_gain, self.target / max(self.env, 1e-6)) + new = want if want < self.gain else self.gain + (want - self.gain) * min(1.0, n / self.fs / 0.3) # fast down, slow up + g = np.linspace(self.gain, new, n, endpoint=False) * self.manual + self.gain = new + return np.clip(x * g, -1.0, 1.0) + + +def clip_magnitude(z, limit=1.0): + """Limits the magnitude of a complex signal and keeps its phase.""" + mag = np.abs(z) + scale = np.where(mag > limit, limit / np.maximum(mag, 1e-12), 1.0) + return z * scale diff --git a/espdr/images/SHA256SUMS.txt b/espdr/images/SHA256SUMS.txt new file mode 100644 index 0000000..29a784d --- /dev/null +++ b/espdr/images/SHA256SUMS.txt @@ -0,0 +1,4 @@ +c5131425d56fb05c44874988ca77652a5c4482296bf206d944683ee131d73678 rx.bin +b017125ac6c1bcbb70c84e3675a0ecee485b3249f84803cae382b6b83c6f7fd6 tx.bin +09b2386299522e08fad02bfed8bab76bc5e37076b8d529c31811e967780b686b bootloader.bin +7f00b6c042a89b15b0cac534f82ed988caf29278ff5700b0c511eb1b5bb7c820 partition-table.bin diff --git a/espdr/images/bootloader.bin b/espdr/images/bootloader.bin new file mode 100644 index 0000000..8f9ed4f Binary files /dev/null and b/espdr/images/bootloader.bin differ diff --git a/espdr/images/partition-table.bin b/espdr/images/partition-table.bin new file mode 100644 index 0000000..b8fa03b Binary files /dev/null and b/espdr/images/partition-table.bin differ diff --git a/espdr/images/rx.bin b/espdr/images/rx.bin new file mode 100644 index 0000000..568f391 Binary files /dev/null and b/espdr/images/rx.bin differ diff --git a/espdr/images/tx.bin b/espdr/images/tx.bin new file mode 100644 index 0000000..7689ce5 Binary files /dev/null and b/espdr/images/tx.bin differ diff --git a/espdr/iq.py b/espdr/iq.py new file mode 100644 index 0000000..48bce20 --- /dev/null +++ b/espdr/iq.py @@ -0,0 +1,60 @@ +"""Complex baseband input for `espdr-tx -m iq`: files and pipes of interleaved I/Q samples, in blocks, any size of read.""" +import os +import sys + +import numpy as np + +# format: (dtype of one value, scale to +-1). cf32 is GNU Radio's complex64 and espdr-rx's `--convert cf32`; cs8 and cs16 are the +# receiver's raw formats. +FORMATS = {"cf32": (np.dtype(" end: + return False + return True + + def _take(self, n): + out = bytes(self.buf[:n]) + del self.buf[:n] + return out + + # -- control + def send(self, op, arg=0): + if arg > 0xFFFF: + self.ser.write(request(ESP_ARG_HIGH, arg >> 16, self._next_seq())) + self._response(ESP_ARG_HIGH) + self.ser.write(request(op, arg, self._next_seq())) + + def _next_seq(self): + self.seq = (self.seq + 1) & 0xFFFF + return self.seq + + def _response(self, op, timeout=5.0): + """Waits for the response to `op`, skipping anything else.""" + end = time.monotonic() + timeout + while time.monotonic() < end: + if not self._fill(1, 0.2): + continue + if self.buf[0] != RESP_MAGIC: + del self.buf[0] + continue + if not self._fill(16, 0.5): + continue + raw = bytes(self.buf[:16]) + if struct.unpack(" 10: + raise ProtocolError("stream stalled for 10 s") + continue + t_last = time.monotonic() + b0 = self.buf[0] + if b0 == RESP_MAGIC: + if not self._fill(16, 1.0): + continue + raw = bytes(self.buf[:16]) + if struct.unpack("> 8 + size = NB_HEADER + count * BYTES_PER_SAMPLE.get(fmt, 4) + if not self._fill(size, 1.0): + continue + pkt = self._take(size) + first = first_lo | first_hi << 16 + h = dict(format=fmt, r2=r2, count=count, dropped=dropped, + seq=seq_lo | seq_hi << 16, first=first, shift=shift) + if expected is not None and first != expected: + stats["lost"] += (first - expected) & 0xFFFFFFFF + expected = (first + count) & 0xFFFFFFFF + stats["packets"] += 1 + stats["samples"] += count + stats["dropped"] = dropped + sink(h, pkt[NB_HEADER:]) + continue + stats["bad"] += 1 + del self.buf[0] + stats["skipped"] += 1 + + # -- throughput test + def bench(self, seconds, mode=0): + self.send(NB_BENCH, seconds | mode << 16) + got = blocks = bad = 0 + counter = None + t0 = None + while True: + if not self._fill(1, 2.0): + raise ProtocolError("bench stalled") + if self.buf[0] == RESP_MAGIC: + if not self._fill(16, 1.0): + continue + raw = bytes(self.buf[:16]) + if struct.unpack(" 1: + raise ProtocolError(f"several ESP32-S3 found ({', '.join(found)}); choose one with -p") + return found[0] + + +def open_link(port): + import serial + if port == "auto": + port = find_port() + # Leave DTR/RTS alone. On the native USB Serial/JTAG port, DTR=0 with RTS=1 resets the chip + # into the ROM loader, so clearing the lines one after the other (DTR first) kills the + # firmware. The kernel and pyserial both open with both asserted, which is harmless; closing + # drops both at once. + return Link(serial.Serial(port, 115200, timeout=0.05)) + + +def check_firmware(link): + _, fid = link.command(CTL_INFO, 0) + if fid != FIRMWARE_ID: + raise ProtocolError(f"unexpected firmware id 0x{fid:08X}") + status, _ = link.command(NB_SET_FORMAT, 1, allow=(CTL_OK, CTL_UNKNOWN_OP)) + if status == CTL_UNKNOWN_OP: + raise ProtocolError("this is not the narrowband firmware (build with NARROWBAND=1)") + if link.stat(ESP_STAT_RADIO) != 0: + raise ProtocolError("radio initialisation failed on the ESP32-S3") + + +def configure_receiver(link, freq, decim, fmt, shift, gain): + """Programs the radio and the decimator; returns the LO the ESP actually settled on, in Hz.""" + link.command(ESP_SET_RATE, ESP_RATE_16M) + link.command(ESP_SET_WIDTH, 20) + _, lo = link.command(ESP_SET_LO, int(round(freq))) + link.command(ESP_SET_GAIN, gain) + link.command(NB_SET_DECIM, decim) + link.command(NB_SET_FORMAT, fmt) + link.command(NB_SET_OUTSHIFT, shift) + return lo + + +def cmd_run(args): + link = open_link(args.port) + check_firmware(link) + fmt = FORMATS[args.format] + shift = args.shift if args.shift is not None else (4 if fmt == 1 else 0) + lo = configure_receiver(link, args.freq, args.decim, fmt, shift, args.gain) + rate = 1e6 / args.decim + need = rate * BYTES_PER_SAMPLE[fmt] / 1e6 + print(f"LO {lo / 1e6:.6f} MHz, {rate / 1e3:.0f} ksps {args.format}, usable +-{rate * 0.4 / 1e3:.0f} kHz, " + f"{need:.2f} MB/s over USB", file=sys.stderr) + out = Output(args) + stop = {"flag": False} + # Ctrl-C asks the ESP to finish the current unit pair; the run's reply follows. + signal.signal(signal.SIGINT, lambda *_: stop.__setitem__("flag", True)) + t0 = time.monotonic() + status, value, stats = link.run(args.seconds, out, stop_flag=lambda: stop["flag"]) + out.close() + return report(link, status, value, stats, time.monotonic() - t0) + + +def report(link, status, value, stats, elapsed): + if stats is None: + return 1 + print(f"{stats['samples']} samples in {stats['packets']} packets, {elapsed:.1f} s", file=sys.stderr) + if stats["lost"] or stats["dropped"] or stats["skipped"]: + print(f"WARNING: {stats['lost']} samples lost, {stats['dropped']} units dropped by the ESP " + f"(USB too slow), {stats['skipped']} stray bytes", file=sys.stderr) + try: + s0, s1 = link.stat(ESP_STAT_SERVICE_MAX0), link.stat(ESP_STAT_SERVICE_MAX1) + peak = link.stat(NB_STAT_FIFO_PEAK) + slips = link.stat(NB_STAT_SLIPS) + print(f"worst unit service time: core0 {s0} / core1 {s1} cycles " + f"({100 * max(s0, s1) / SERVICE_BUDGET_CYCLES:.0f}% of the budget); FIFO peak {peak} bytes", + file=sys.stderr) + if slips > 8: # one per run is normal: the join of two banks that is a few pairs off, see capture.c + print(f"WARNING: {slips} unit joins were a few pairs off (normally 1 per run)", file=sys.stderr) + except ProtocolError: + pass + if value: + why = FAIL_NAMES.get(value, "unknown") + detail = link.stat(ESP_STAT_DETAIL) + print(f"RUN FAILED: code {value} ({why}), detail {detail}", file=sys.stderr) + return 2 + return 0 + + +def cmd_bench(args): + link = open_link(args.port) + check_firmware(link) + r = link.bench(args.seconds, args.mode) + mbs = r["host_bytes"] / r["seconds"] / 1e6 if r["seconds"] else 0 + print(f"{r['host_bytes']} bytes in {r['seconds']:.2f} s = {mbs:.3f} MB/s; " + f"ESP sent {r['esp_bytes']} bytes; {r['bad']} bad blocks") + print(f"=> sustainable: 8-bit IQ up to {mbs * 1e6 / 2 / 1e3:.0f} ksps, 16-bit IQ up to {mbs * 1e6 / 4 / 1e3:.0f} ksps") + return 0 + + +def cmd_dspbench(args): + """Times the on-chip decimator on one 16000-pair unit of noise (no radio, no capture), and checks + that the SIMD FIR gives the same bytes as the plain C one.""" + link = open_link(args.port) + check_firmware(link) + print(f"budget per unit and lane: {SERVICE_BUDGET_CYCLES} cycles") + bad = 0 + for r2 in (4, 3, 2): + for fmt, name in ((1, "cs8"), (0, "cs16")): + for core1 in (0, 1): + what = r2 | fmt << 4 | core1 << 8 + _, diff = link.command(NB_DSPBENCH, what | NB_DSP_VERIFY) + _, cycles = link.command(NB_DSPBENCH, what | NB_DSP_PROFILE_RESET) + bad += diff + print(f"R2={r2} {name} core{core1} copy: {cycles} cycles ({cycles / 16000:.1f} per pair, " + f"{100 * cycles / SERVICE_BUDGET_CYCLES:.0f}% of budget); SIMD vs C: {diff} bytes differ") + if args.profile: + parts = [link.command(NB_DSPBENCH, what | NB_DSP_PROFILE | i << 4)[1] for i in range(3)] + print(f" cic {parts[0]}, comb+history {parts[1]}, FIR+output {parts[2]}, other {cycles - sum(parts)}") + return 1 if bad else 0 + + +# --- selftest with a fake serial port --------------------------------------------------- +class FakeSerial: + """Plays the ESP: answers requests, then streams packets and a final response.""" + + def __init__(self, drop_every=0, garbage=False): + self.out = bytearray() + self.stopped = False + self.packets_sent = 0 + self.drop_every = drop_every + self.garbage = garbage + self.sent_samples = 0 + self.pending_run = False + + in_waiting = 0 + + def _response(self, op, status=0, value=0): + head = struct.pack("> 8]) + bytes(60) + self.out += self._response(op, 0, 50 * 64) + else: + self.out += self._response(op, 0, 0) + + def _packet(self, seq, first, count, dropped): + payload = bytes((first + i) & 0xFF for i in range(count * 2)) + words = [0xE5 | 0x5D << 8, 1 | 4 << 8, count, dropped, seq & 0xFFFF, seq >> 16, first & 0xFFFF, + first >> 16, 4, 0] + words[9] = 0xFFFF - (sum(words[:9]) & 0xFFFF) + return struct.pack("<10H", *words) + payload + + def read(self, n): + if self.pending_run and not self.out: + seq = first = 0 + for _ in range(200): + if self.stopped: + break + if self.drop_every and seq % self.drop_every == self.drop_every - 1: + first += 240 # a dropped unit leaves a gap in the sample index + seq += 1 + self.out += self._packet(seq, first, 240, 1 if self.drop_every else 0) + if self.garbage and seq == 50: + self.out += b"\x00\xE5\x00junk" + first += 240 + seq += 1 + self.sent_samples += 240 + self.out += self._response(ESP_RUN, 0, 0) + self.pending_run = False + chunk = bytes(self.out[:n]) + del self.out[:n] + return chunk + + +def selftest(): + ok = True + for kw, expect_lost in ((dict(), 0), (dict(drop_every=50), 4 * 240), (dict(garbage=True), 0)): + link = Link(FakeSerial(**kw)) + got = [] + status, value, stats = link.run(0, lambda h, p: got.append((h, p))) + good = status == 0 and value == 0 and stats["lost"] == expect_lost and stats["packets"] > 0 + good &= all(len(p) == h["count"] * 2 for h, p in got) + if kw.get("garbage"): + good &= stats["skipped"] >= 1 + print(f"stream {kw or 'clean'}: packets={stats['packets']} lost={stats['lost']} " + f"skipped={stats['skipped']} -> {'OK' if good else 'FAIL'}") + ok &= good + r = Link(FakeSerial()).bench(1) + good = r["bad"] == 0 and r["host_bytes"] == 50 * 64 + print(f"bench: {r['host_bytes']} bytes, {r['bad']} bad -> {'OK' if good else 'FAIL'}") + ok &= good + print("SELFTEST", "PASSED" if ok else "FAILED") + return 0 if ok else 1 + + +def main(): + ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + ap.add_argument("-p", "--port", default="auto", + help="serial port of the ESP32-S3's native USB (e.g. /dev/ttyACM1); default: find it by its USB id") + sub = ap.add_subparsers(dest="cmd", required=True) + r = sub.add_parser("run", help="tune, run and stream") + r.add_argument("--freq", type=float, required=True, help="LO frequency in Hz (e.g. 2400.1e6)") + r.add_argument("--decim", type=int, choices=(2, 3, 4), default=4, + help="4: 250 ksps (+-100 kHz usable, default); 3: 333 ksps (+-133 kHz); 2: 500 ksps, which needs 1.0 MB/s - " + "more than this USB link delivers, so samples are lost") + r.add_argument("--format", choices=sorted(FORMATS), default="cs8") + r.add_argument("--shift", type=int, help="output right shift (default 4 for cs8, 0 for cs16)") + r.add_argument("--gain", type=int, default=60, + help="receive gain selector 0..127 (an AGC table index, not dB; 24 leaves the noise near 2 counts, 60 near 20)") + r.add_argument("--seconds", type=int, default=0, help="0: until Ctrl-C") + r.add_argument("-o", "--out", help="file, or - for stdout") + r.add_argument("--tcp", type=int, help="serve the samples to one TCP client on 127.0.0.1:PORT") + r.add_argument("--udp", help="send the samples as UDP datagrams to HOST:PORT") + r.add_argument("--convert", choices=("raw", "cf32"), default="raw", help="cf32: float32 I/Q, needs numpy") + r.add_argument("--native-iq", action="store_true", + help="cf32 only: keep the radio's convention (I+jQ = LO minus RF, spectrum mirrored) " + "instead of conjugating it to the usual RF-up = frequency-up") + b = sub.add_parser("bench", help="measure the USB throughput") + b.add_argument("--seconds", type=int, default=5) + b.add_argument("--mode", type=int, choices=(0, 1, 2), default=0, + help="how the firmware writes the USB packets: 0 as the stream does (default), 1 byte-wise with a poll " + "per byte (the old way), 2 one check then 64 writes") + d = sub.add_parser("dspbench", help="time the on-chip decimator without a capture") + d.add_argument("--profile", action="store_true", help="per-section cycles (firmware built with PROFILE=1)") + sub.add_parser("selftest", help="check the parser against a simulated ESP") + args = ap.parse_args() + try: + if args.cmd == "selftest": + return selftest() + return {"run": cmd_run, "bench": cmd_bench, "dspbench": cmd_dspbench}[args.cmd](args) + except ProtocolError as e: + print("error:", e, file=sys.stderr) + return 1 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/espdr/polar.py b/espdr/polar.py new file mode 100644 index 0000000..840cf74 --- /dev/null +++ b/espdr/polar.py @@ -0,0 +1,88 @@ +"""Complex baseband (IQ) to the records of the polar transmitter. + +The chip has no I/Q input, but it can move its carrier in frequency 40000 times a second (see `txmodes`). A signal with a constant +envelope (FM, M17, any FSK) is fully described by its instantaneous frequency, so it can be played by taking the frequency out of the +IQ samples and sending it as the frequency field of the records, with a constant gain code. The envelope is ignored. + +`IqToPolar` takes the frequency from the phase difference of consecutive samples: `f = arg(x[n] * conj(x[n-1])) * fs / 2 pi`. A +sample whose magnitude is below `threshold` (silence, or the zeros a muted flowgraph delivers) carries no phase: the last frequency +is held. The state survives block boundaries, so blocks of any size give the same result. +""" +import numpy as np + +from . import dsp, txmodes + + +class IqToPolar: + """The frequency in Hz of a complex baseband signal, one value per update (default 40000 a second), for blocks of any size.""" + + def __init__(self, rate_in, update_rate=40000, threshold=1e-3): + self.rate_in, self.update_rate, self.threshold = float(rate_in), int(update_rate), float(threshold) + if self.rate_in < self.update_rate: + raise ValueError("the IQ rate must be at least the update rate") + ratio = self.rate_in / self.update_rate + # a whole ratio (80 kHz -> 40 kHz) averages groups of samples; any other ratio resamples the frequency track + self.group = int(round(ratio)) if abs(ratio - round(ratio)) < 1e-9 else None + self.res = None if self.group else dsp.Resampler(self.rate_in, self.update_rate) + self.prev = 0j # the last sample of the previous block + self.f_last = 0.0 # the last valid frequency, held through silence + self.rest = np.zeros(0) # frequencies that do not fill a group yet + + def reset(self): + self.prev, self.f_last, self.rest = 0j, 0.0, np.zeros(0) + if self.res is not None: + self.res = dsp.Resampler(self.rate_in, self.update_rate) + + def per_sample(self, x): + """The frequency at every input sample in Hz, held through samples too weak to carry a phase.""" + x = np.asarray(x, dtype=np.complex128) + if not len(x): + return np.zeros(0) + prev = np.concatenate([[self.prev], x[:-1]]) + self.prev = x[-1] + valid = (np.abs(x) > self.threshold) & (np.abs(prev) > self.threshold) + f = np.angle(x * np.conj(prev)) * (self.rate_in / (2 * np.pi)) + idx = np.where(valid, np.arange(len(x)), -1) + np.maximum.accumulate(idx, out=idx) + held = np.concatenate([[self.f_last], f])[idx + 1] # idx -1: nothing valid in this block yet, keep the old value + self.f_last = float(held[-1]) + return held + + def process(self, x): + f = self.per_sample(x) + if self.group is None: + return self.res.process(f) + data = np.concatenate([self.rest, f]) + m = len(data) // self.group + self.rest = data[m * self.group:] + return data[:m * self.group].reshape(m, self.group).mean(axis=1) + + +class IqModulator: + """IQ blocks to records, like the other modulators of `txmodes`: `process(x)` returns uint32 records. `static_hz` is a constant + added to every record (the signal's centre against the LO, see `txlink.plan_lo`); `clipped` counts records the firmware's range + (+-19 kHz around the LO) forced the frequency of.""" + + name = "IQ" + + def __init__(self, rate_in, rate=40000, power_db=0.0, static_hz=0.0, threshold=1e-3): + self.rate = rate + self.polar = IqToPolar(rate_in, rate, threshold) + self.fsk = txmodes.FskModulator(rate=rate, power_db=power_db, static_hz=static_hz) + self.clipped = 0 + + @property + def static_hz(self): + return self.fsk.static_hz + + def set_power(self, power_db): + """Changes the gain code of the records that follow.""" + self.fsk.code = txmodes.peak_code(power_db) + + def process(self, x): + f = self.polar.process(x) + if not len(f): + return np.zeros(0, dtype=np.uint32) + q4 = np.rint(f / txmodes.Q4_HZ) + self.fsk.static_q4 + self.clipped += int((np.abs(q4) > txmodes.MAX_Q4).sum()) + return self.fsk.process(f) diff --git a/espdr/rtltcp.py b/espdr/rtltcp.py new file mode 100644 index 0000000..74faed1 --- /dev/null +++ b/espdr/rtltcp.py @@ -0,0 +1,596 @@ +#!/usr/bin/env python3 +"""The rtl_tcp server for the narrowband ESP32-S3 receiver (the library behind `espdr-rx`). + +SDR++ ("RTL-TCP" source), pluto-advanced-rx (RTL-SDR device, connection "127.0.0.1:1234") and anything else that speaks the rtl_tcp +protocol can use the ESP32-S3 without changes. One client at a time; the radio runs only while a client is connected. + +The radio delivers 250 ksps (+-100 kHz usable) or, with decim 3, 333.3 ksps (+-133 kHz). The sample rate a client asks for is produced by +filtered interpolation, so any rate from 1 MS/s to 3.2 MS/s works; asking for exactly the radio's rate passes the data through. +Frequency and gain changes restart the ESP's run (the radio is reconfigured between runs), which leaves a short gap. +""" +import queue +import socket +import struct +import sys +import threading +import time + +import numpy as np + +from . import nb + +HEADER = b"RTL0" + struct.pack(">II", 5, 29) # "R820T" tuner with 29 gain steps: what clients expect to see +SRC_RATES = {3: 1e6 / 3, 4: 250_000.0} # ESP output per --decim +LO_MIN, LO_MAX = 1_841_666_667, 2_790_000_000 # ESP tuning range, Hz (ESP_LO_MIN_HZ / ESP_LO_MAX_HZ in protocol/control.h) +# R820T gain table in tenths of a dB, for rtl_tcp's "set gain by index" +GAINS_TENTHS = (0, 9, 14, 27, 37, 77, 87, 125, 144, 157, 166, 197, 207, 229, 254, 280, 297, 328, 338, 364, 372, + 386, 402, 421, 434, 439, 445, 480, 496) +CMD_FREQ, CMD_RATE, CMD_GAIN_MODE, CMD_GAIN, CMD_PPM, CMD_AGC, CMD_GAIN_INDEX = 0x01, 0x02, 0x03, 0x04, 0x05, 0x08, 0x0D +DEBOUNCE_S = 0.05 # SDR++ sends many frequency commands while dragging: restart the radio once they stop +SETTLE_S = 0.15 # after a connect, wait for the client's initial commands +FLUSH_SECONDS = 0.01 # process the stream in 10 ms blocks +DC_TAU_S = 0.5 + + +def log(*a): + print(*a, file=sys.stderr, flush=True) + + +# --- signal path --------------------------------------------------------------------------------------- +def _design_up4(): + """100-tap windowed-sinc low-pass for x4 interpolation, cut at the input's Nyquist frequency (250 k -> 1 MS/s: passband + 100 kHz, images from 150 kHz down >70 dB; 333 k -> 1.33 MS/s: the same, scaled).""" + n = 100 + t = np.arange(n) - (n - 1) / 2 + h = np.sinc(2 * 0.125 * t) * np.kaiser(n, 8.0) + h *= 4 / h.sum() + return [h[p::4].astype(np.float32) for p in range(4)] + + +_UP4 = _design_up4() + + +class Up4: + """Streaming x4 polyphase interpolator.""" + + def __init__(self): + self.k = len(_UP4[0]) + self.tail = np.zeros(self.k - 1, np.complex64) + + def process(self, z): + xin = np.concatenate((self.tail, z)) + self.tail = xin[len(xin) - (self.k - 1):].copy() + out = np.empty(4 * len(z), np.complex64) + for p in range(4): + out[p::4] = np.convolve(xin, _UP4[p], mode="valid") + return out + + +class Fractional: + """Streaming cubic-Lagrange resampler; `step` input samples per output sample.""" + + def __init__(self, step): + self.step = float(step) + self.tail = np.zeros(3, np.complex64) + self.t0 = 1.0 + + def process(self, z): + x = np.concatenate((self.tail, z)) + n_out = int(np.floor((len(x) - 3 - self.t0) / self.step)) + 1 + if n_out <= 0: + self.tail = x + self.t0 -= len(z) + return np.zeros(0, np.complex64) + t = self.t0 + self.step * np.arange(n_out) + idx = t.astype(np.int64) + mu = (t - idx).astype(np.float32) + y0, y1, y2, y3 = x[idx - 1], x[idx], x[idx + 1], x[idx + 2] + c1 = -y0 / 3 - y1 / 2 + y2 - y3 / 6 + c2 = y0 / 2 - y1 + y2 / 2 + c3 = -y0 / 6 + y1 / 2 - y2 / 2 + y3 / 6 + out = ((c3 * mu + c2) * mu + c1) * mu + y1 + self.t0 += n_out * self.step - (len(x) - 3) + self.tail = x[len(x) - 3:].copy() + return out.astype(np.complex64) + + +class Chain: + """ESP samples (complex, LO-minus-RF) -> unsigned 8-bit rtl_tcp stream at `dst_rate`.""" + + def __init__(self, dst_rate, shift_hz=0.0, dc_block=True, src_rate=250_000.0): + self.src_rate = src_rate + self.shift_w = 2 * np.pi * shift_hz / src_rate + self.phase = 0.0 + self.dc_block = dc_block + self.dc = None + self.stages = [] + if abs(dst_rate - src_rate) < 1: + pass + elif dst_rate <= 1.2 * src_rate: + self.stages = [Fractional(src_rate / dst_rate)] + else: + self.stages = [Up4()] + if abs(dst_rate - 4 * src_rate) > 1: + self.stages.append(Fractional(4 * src_rate / dst_rate)) + + def process(self, z): + z = np.conj(z) # the radio delivers LO minus RF; clients expect a higher RF to be a higher frequency + if self.dc_block: + m = z.mean() + a = min(1.0, len(z) / (DC_TAU_S * self.src_rate)) + self.dc = m if self.dc is None else self.dc + a * (m - self.dc) + z = z - self.dc + if abs(self.shift_w) > 1e-9: + ph = self.phase + self.shift_w * np.arange(len(z)) + z = z * np.exp(1j * ph).astype(np.complex64) + self.phase = float((self.phase + self.shift_w * len(z)) % (2 * np.pi)) + for st in self.stages: + z = st.process(z) + out = np.empty(2 * len(z), np.float32) + out[0::2], out[1::2] = z.real, z.imag + return np.clip(np.floor(out + 128.0), 0, 255).astype(np.uint8).tobytes() + + +# --- shared settings -------------------------------------------------------------------------------------- +class Params: + def __init__(self, freq, ppm, gain, rate): + self.lock = threading.Lock() + self.freq, self.ppm, self.gain, self.rate = freq, ppm, gain, rate + self.hw_version = 0 + self.last_change = time.monotonic() + + def set(self, **kw): + with self.lock: + hw = False + for k, v in kw.items(): + if getattr(self, k) != v: + setattr(self, k, v) + hw |= k in ("freq", "ppm", "gain") + if hw: + self.hw_version += 1 + self.last_change = time.monotonic() + + def snapshot(self): + with self.lock: + return self.freq, self.ppm, self.gain, self.rate, self.hw_version + + def settled(self, since): + with self.lock: + return time.monotonic() - self.last_change >= since + + +class Session: + """One connected rtl_tcp client: a reader thread for its commands, a writer thread for the stream.""" + + def __init__(self, conn, bridge): + self.conn, self.bridge = conn, bridge + self.closed = threading.Event() + self.q = queue.Queue(maxsize=300) + self.dropped = 0 + conn.settimeout(None) + conn.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) + conn.sendall(HEADER) + threading.Thread(target=self._read, daemon=True).start() + threading.Thread(target=self._write, daemon=True).start() + + def push(self, data): + try: + self.q.put_nowait(data) + except queue.Full: + self.dropped += 1 + + def close(self): + self.closed.set() + try: + self.conn.shutdown(socket.SHUT_RDWR) + except OSError: + pass + self.conn.close() + + def _write(self): + try: + while not self.closed.is_set(): + try: + data = self.q.get(timeout=0.2) + except queue.Empty: + continue + self.conn.sendall(data) + except OSError: + pass + self.closed.set() + + def _read(self): + buf = b"" + try: + while not self.closed.is_set(): + chunk = self.conn.recv(4096) + if not chunk: + break + buf += chunk + while len(buf) >= 5: + cmd, param = struct.unpack(">BI", buf[:5]) + buf = buf[5:] + self.bridge.command(cmd, param) + except OSError: + pass + self.closed.set() + + +# --- bridge ----------------------------------------------------------------------------------------------- +class Bridge: + def __init__(self, open_link, listen, ppm=0.0, gain=60, gain_range=(30, 80), dc_block=True, decim=4): + self.open_link = open_link + self.decim, self.src_rate = decim, SRC_RATES[decim] + self.base_ppm = ppm # --ppm: this unit's crystal; a client's ppm command adds to it + self.params = Params(2_400_000_000, ppm, gain, 2_400_000) + self.gain_range = gain_range + self.dc_block = dc_block + self.quit = False + self.session = None + self.last_good = 2_400_000_000 # the last frequency the ESP accepted (2.4 GHz is where it works best) + self.srv = socket.socket() + self.srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + self.srv.bind(listen) + self.srv.listen(1) + self.srv.settimeout(0.2) + self.address = self.srv.getsockname() + self.stats = dict(restarts=0, failures=0) + + # -- rtl_tcp commands + def _gain_sel(self, tenths_db): + lo, hi = self.gain_range + return int(round(lo + (hi - lo) * max(0, min(496, tenths_db)) / 496.0)) + + def command(self, cmd, param): + if cmd == CMD_FREQ: + f = int(param) + if not LO_MIN <= f <= LO_MAX: + log(f"frequency {f / 1e6:.3f} MHz is outside the ESP's {LO_MIN / 1e9:.2f}-{LO_MAX / 1e9:.2f} GHz range") + f = min(LO_MAX, max(LO_MIN, f)) + self.params.set(freq=f) + elif cmd == CMD_RATE: + self.params.set(rate=int(param)) + elif cmd == CMD_PPM: + self.params.set(ppm=self.base_ppm + struct.unpack(">i", struct.pack(">I", param))[0]) + elif cmd == CMD_GAIN: + self.params.set(gain=self._gain_sel(param)) + elif cmd == CMD_GAIN_INDEX: + self.params.set(gain=self._gain_sel(GAINS_TENTHS[min(param, len(GAINS_TENTHS) - 1)])) + # 0x03/0x08 (gain/AGC mode) and the rest: the ESP has manual gain only; nothing to do + + # -- accepting clients + def serve(self): + while not self.quit: + try: + conn, addr = self.srv.accept() + except socket.timeout: + continue + except OSError: + return + log(f"client {addr[0]}:{addr[1]} connected") + s = Session(conn, self) + self.session = s + s.closed.wait() + self.session = None + s.close() + log(f"client left (dropped {s.dropped} blocks)") + + # -- the ESP side + def run(self): + threading.Thread(target=self.serve, daemon=True).start() + link = None + try: + while not self.quit: + s = self.session + if s is None or s.closed.is_set(): + time.sleep(0.05) + continue + if link is None: + try: + link = self.open_link() + except Exception as e: # noqa: BLE001 - the port may be missing for a while + log("cannot open the ESP:", e) + time.sleep(1.0) + continue + try: + self.stream(link, s) + except (nb.ProtocolError, OSError) as e: + log("ESP link error:", e) + link = None + time.sleep(1.0) + finally: + self.quit = True + + def stream(self, link, s): + """Runs the ESP for as long as the client stays; restarts the run when frequency or gain change.""" + deadline = time.monotonic() + 1.0 + while not self.params.settled(SETTLE_S) and time.monotonic() < deadline: + time.sleep(0.02) + first = True + while not (s.closed.is_set() or self.quit): + freq, ppm, gain, _, version = self.params.snapshot() + hw_freq = int(round(freq / (1 + ppm * 1e-6))) + t0 = time.monotonic() + try: + lo = nb.configure_receiver(link, hw_freq, self.decim, nb.FORMATS["cs8"], 4, gain) + except nb.CommandError as e: + if e.op != nb.ESP_SET_LO: + raise + log(f"the ESP refused {freq / 1e6:.3f} MHz ({e}); staying at {self.last_good / 1e6:.3f} MHz") + self.params.set(freq=self.last_good) + continue + self.last_good = freq + # Where the LO really is (nominal clock: lo; actual crystal: lo*(1+ppm)) against where the client asked: + shift = lo * (1 + ppm * 1e-6) - freq + log(f"tuned {freq / 1e6:.6f} MHz (LO {lo / 1e6:.6f} MHz, fine shift {shift:+.0f} Hz), gain {gain}" + + ("" if first else f", retune took {time.monotonic() - t0:.2f} s")) + first = False + sink = Sink(self, s, shift) + stop = lambda: (s.closed.is_set() or self.quit or + (self.params.hw_version != version and self.params.settled(DEBOUNCE_S))) + status, value, stats = link.run(0, sink, stop_flag=stop) + sink.flush() + if value: + self.stats["failures"] += 1 + log(f"ESP run failed: code {value} ({nb.FAIL_NAMES.get(value, '?')}); restarting") + time.sleep(0.3) + elif stats["lost"] or stats["dropped"]: + log(f"{stats['lost']} samples lost in this run ({stats['dropped']} units dropped by the ESP)") + self.stats["restarts"] += 1 + + +class Sink: + """Collects ESP packets into 10 ms blocks, runs them through the chain and hands them to the client.""" + + def __init__(self, bridge, session, shift_hz): + self.bridge, self.s = bridge, session + self.shift_hz = shift_hz + self.rate = None + self.chain = None + self.parts, self.n = [], 0 + self.expected = None + + def _chain(self): + rate = self.bridge.params.snapshot()[3] + if rate != self.rate: + self.rate = rate + old = self.chain + self.chain = Chain(rate, self.shift_hz, self.bridge.dc_block, self.bridge.src_rate) + if old is not None: + self.chain.dc = old.dc + return self.chain + + def __call__(self, header, payload): + if self.expected is not None and header["first"] != self.expected: + lost = min((header["first"] - self.expected) & 0xFFFFFFFF, int(self.bridge.src_rate)) + self.parts.append(np.zeros(lost, np.complex64)) # keep the time base: a gap becomes silence + self.n += lost + self.expected = (header["first"] + header["count"]) & 0xFFFFFFFF + if header["format"] == 1: + a = np.frombuffer(payload, dtype=np.int8).astype(np.float32) + else: + a = np.frombuffer(payload, dtype="= self.bridge.src_rate * FLUSH_SECONDS: + self.flush() + + def flush(self): + if not self.parts: + return + z = np.concatenate(self.parts).astype(np.complex64) + self.parts, self.n = [], 0 + data = self._chain().process(z) + if data: + self.s.push(data) + + +# --- command line ----------------------------------------------------------------------------------------- +find_port = nb.find_port + + +def parse_listen(text): + host, _, port = text.rpartition(":") + return host or "127.0.0.1", int(port) + + +# --- selftest (simulated ESP, no hardware) ----------------------------------------------------------------- +class SimEsp: + """Plays the ESP for the bridge: a transmitter at `rf_hz`, seen through the LO it is set to, in the radio's + LO-minus-RF convention, with a DC offset and noise; paced `speed` times the real rate (250 ksps, or what NB_SET_DECIM selects).""" + LO_STEP = 381.4697265625 + + def __init__(self, rf_hz, speed=1.0): + self.rf_hz, self.speed = rf_hz, speed + self.ops = [] # (op, arg) in arrival order + self.out = bytearray() + self.lo = 0.0 + self.running = False + self.stopping = False + self.t_last = 0.0 + self.sample = 0 + self.seq = 0 + self.arg_high = 0 + self.rng = np.random.default_rng(1) + self.r2 = 4 + + @property + def in_waiting(self): + self._pump() + return len(self.out) + + def _resp(self, op, status=0, value=0): + head = struct.pack("= 240: + count = min(count, 480) + self.t_last = now + k = np.arange(self.sample, self.sample + count) + f_base = -(self.rf_hz - self.lo) # LO minus RF + z = 40 * np.exp(2j * np.pi * f_base / rate * k) + (-6 + 4j) + z += self.rng.normal(0, 2, count) + 1j * self.rng.normal(0, 2, count) + iq = np.empty(2 * count, np.int8) + iq[0::2], iq[1::2] = np.clip(np.round(z.real), -128, 127), np.clip(np.round(z.imag), -128, 127) + words = [0xE5 | 0x5D << 8, 1 | self.r2 << 8, count, 0, self.seq & 0xFFFF, self.seq >> 16, + self.sample & 0xFFFF, self.sample >> 16, 4, 0] + words[9] = 0xFFFF - (sum(words[:9]) & 0xFFFF) + self.out += struct.pack("<10H", *words) + iq.tobytes() + self.sample += count + self.seq += 1 + if self.stopping: + self.out += self._resp(nb.ESP_RUN) + self.running = False + + +def _tone(u8, rate): + """(frequency Hz, level dB over the median bin, strongest spur far from the tone in dB below it).""" + z = (u8[0::2].astype(np.float32) - 127.5) + 1j * (u8[1::2].astype(np.float32) - 127.5) + z = z[len(z) // 4:] + w = np.hanning(len(z)) + spec = np.abs(np.fft.fftshift(np.fft.fft(z * w))) ** 2 + f = np.fft.fftshift(np.fft.fftfreq(len(z), 1 / rate)) + i = int(np.argmax(spec)) + far = (np.abs(f - f[i]) > 20e3) & (np.abs(f) > 3e3) # the DC bin is judged on its own + return f[i], 10 * np.log10(spec[i] / np.median(spec)), 10 * np.log10(spec[i] / spec[far].max()) + + +def _collect(sock, seconds_of_samples, rate): + need = int(seconds_of_samples * rate) * 2 + got = bytearray() + sock.settimeout(5.0) + while len(got) < need: + chunk = sock.recv(1 << 18) + if not chunk: + break + got += chunk + return np.frombuffer(bytes(got[:need]), np.uint8) + + +def _drain(sock, seconds): + """Discards what arrives for a while: the stream never ends, so wait for a time, not for silence.""" + end = time.monotonic() + seconds + sock.settimeout(0.2) + while time.monotonic() < end: + try: + if not sock.recv(1 << 20): + return + except socket.timeout: + pass + + +def selftest(): + ok = _selftest(4) & _selftest(3) + print("SELFTEST", "PASSED" if ok else "FAILED") + return 0 if ok else 1 + + +def _selftest(decim): + ok = True + src = int(round(SRC_RATES[decim])) + print(f"--- radio at {src / 1e3:.0f} ksps (--decim {decim})") + + def check(name, good, detail=""): + nonlocal ok + ok &= bool(good) + print(f"{name}: {'OK' if good else 'FAIL'} {detail}") + + sim = SimEsp(rf_hz=2_400_050_000) + bridge = Bridge(lambda: nb.Link(sim), ("127.0.0.1", 0), ppm=0.0, decim=decim) + threading.Thread(target=bridge.run, daemon=True).start() + + def connect(): + s = socket.create_connection(bridge.address[:2], timeout=5) + hdr = b"" + while len(hdr) < 12: + hdr += s.recv(12 - len(hdr)) + return s, hdr + + def cmd(s, c, p): + s.sendall(struct.pack(">BI", c, p & 0xFFFFFFFF)) + + s, hdr = connect() + check("header", hdr == b"RTL0" + struct.pack(">II", 5, 29), repr(hdr)) + for rate in (src, 1_024_000, 2_400_000): + cmd(s, CMD_RATE, rate) + cmd(s, CMD_FREQ, 2_400_000_000) + _drain(s, 0.6) # let the new rate take effect, drop the old one + f, level, spur = _tone(_collect(s, 0.4, rate), rate) + # transmitter 50 kHz above the LO; chain fine-shifts by the LO rounding, so the tone must be at +50 kHz + check(f"tone at {rate / 1e6:g} MS/s", abs(f - 50_000) < 400 and level > 25 and spur > 45, + f"{f:+.0f} Hz, {level:.0f} dB over noise, spurs {spur:.0f} dB down") + u8 = _collect(s, 0.3, 2_400_000) + check("DC removed", abs(u8[0::2].mean() - 127.5) < 1.5 and abs(u8[1::2].mean() - 127.5) < 1.5, + f"mean I {u8[0::2].mean():.1f} Q {u8[1::2].mean():.1f}") + + n_lo = sum(1 for op, _ in sim.ops if op == nb.ESP_SET_LO) + cmd(s, CMD_FREQ, 2_400_020_000) + cmd(s, CMD_GAIN, 300) + _drain(s, 1.2) + lo_cmds = [a for op, a in sim.ops if op == nb.ESP_SET_LO] + gain_cmds = [a for op, a in sim.ops if op == nb.ESP_SET_GAIN] + check("retune restarts the run", len(lo_cmds) == n_lo + 1 and lo_cmds[-1] == 2_400_020_000 + and gain_cmds[-1] == bridge._gain_sel(300), f"LO commands {lo_cmds[-2:]}, gain {gain_cmds[-1]}") + f, level, _ = _tone(_collect(s, 0.4, 2_400_000), 2_400_000) + check("tone after retune", abs(f - 30_000) < 400, f"{f:+.0f} Hz (transmitter 30 kHz above the new centre)") + cmd(s, CMD_FREQ, 1_700_000_000) # below the ESP's range: clamped to its lower limit, not refused + _drain(s, 1.0) + lo_cmds = [a for op, a in sim.ops if op == nb.ESP_SET_LO] + check("frequency below the range is clamped", LO_MIN in lo_cmds and LO_MIN == 1_841_666_667, f"LO commands {lo_cmds[-3:]}") + # the simulated ESP refuses that (no PLL lock, as on the test board): the bridge goes back to the last good frequency + # and keeps streaming + f, level, _ = _tone(_collect(s, 0.4, src), src) + check("refused frequency falls back and keeps streaming", lo_cmds[-1] == 2_400_020_000 and level > 25, + f"last LO command {lo_cmds[-1]}, {level:.0f} dB") + cmd(s, CMD_FREQ, 2_400_000_000) + s.close() + time.sleep(0.5) + s, hdr = connect() + cmd(s, CMD_RATE, src) + f, level, _ = _tone(_collect(s, 0.4, src), src) + check("reconnect", hdr[:4] == b"RTL0" and level > 25, f"{f:+.0f} Hz") + s.close() + bridge.quit = True + time.sleep(0.3) + return ok diff --git a/espdr/rtty.py b/espdr/rtty.py new file mode 100644 index 0000000..46b0232 --- /dev/null +++ b/espdr/rtty.py @@ -0,0 +1,196 @@ +"""RTTY (Baudot, two-tone FSK) for the transmitter. + +The text is turned into a list of frames, (bit, duration in bit periods), by the same rules as the RTTY mode of pluto-tx (the US/commercial +Baudot table of dl-fldigi, letters shift and figures shift, unshift on space, 1 start bit, 5 data bits least significant first, 1.5 stop bits, +a second of idle mark before the text). `OffsetStream` turns the frames into the frequency of the two tones, relative to the lower one, at the +update rate of the transmitter: `txmodes.FskModulator` sends that to the PLL, which is true FSK with a constant amplitude. `decode_frequency` +is the other way round, for tests and for checking a recording. + +The mark tone is the one of the logical mark (idle, stop bit); the space tone is `shift` Hz above it. `reverse` swaps which logical state +plays the higher tone, as the Normal/Reverse switch of a terminal unit does. +""" +import numpy as np + +# US/commercial FIGS variant, index = 5-bit code. 27 and 31 are the shift codes (FIGS and LTRS), the table holds a placeholder there. +_LTRS = ["\0", "E", "\n", "A", " ", "S", "I", "U", + "\r", "D", "R", "J", "N", "F", "C", "K", + "T", "Z", "L", "W", "H", "Y", "P", "Q", + "O", "B", "G", " ", "M", "X", "V", " "] +_FIGS = ["\0", "3", "\n", "-", " ", "\a", "8", "7", + "\r", "$", "4", "'", ",", "!", ":", "(", + "5", '"', ")", "2", "#", "6", "0", "1", + "9", "?", "&", " ", ".", "/", ";", " "] +FIGS_SHIFT = 0b11011 +LTRS_SHIFT = 0b11111 + +BAUD_DEFAULT = 45.45 +SHIFT_DEFAULT = 170.0 +MARK_DEFAULT = 2125.0 +STOP_BITS = 1.5 +PREAMBLE_S = 1.0 +TAIL_S = 0.2 + + +def _reverse(table): + rev = {} + for code, ch in enumerate(table): + if code in (FIGS_SHIFT, LTRS_SHIFT) or ch == "\0": + continue + rev.setdefault(ch, code) + return rev + + +_LTRS_CODE = _reverse(_LTRS) +_FIGS_CODE = _reverse(_FIGS) + + +def text_to_codes(text): + """Text -> 5-bit codes with the shift codes inserted. Starts in letters shift; a space returns to letters shift (unshift on space); + CR and LF do not. Letters are upper case, characters that are not in the table are sent as '?'.""" + codes, state = [], "LTRS" + for ch in text: + c = ch.upper() if ch.isalpha() else ch + in_l, in_f = c in _LTRS_CODE, c in _FIGS_CODE + if in_l and in_f: # space, CR, LF: the same in both shifts + codes.append(_LTRS_CODE[c]) + if c == " ": + state = "LTRS" + elif in_l: + if state != "LTRS": + codes.append(LTRS_SHIFT) + state = "LTRS" + codes.append(_LTRS_CODE[c]) + else: + if state != "FIGS": + codes.append(FIGS_SHIFT) + state = "FIGS" + codes.append(_FIGS_CODE[c] if in_f else _FIGS_CODE["?"]) + return codes + + +def codes_to_text(codes): + """The reverse of `text_to_codes` (a receiver's view: shift codes switch the table, a space returns to letters).""" + out, state = [], "LTRS" + for code in codes: + if code == FIGS_SHIFT: + state = "FIGS" + elif code == LTRS_SHIFT: + state = "LTRS" + else: + ch = (_LTRS if state == "LTRS" else _FIGS)[code] + if ch != "\0": + out.append(ch) + if ch == " ": + state = "LTRS" + return "".join(out) + + +def codes_to_frames(codes, stop_bits=STOP_BITS): + """Codes -> (bit, duration in bit periods): start bit (space), five data bits least significant first, stop element (mark).""" + frames = [] + for code in codes: + frames.append((0, 1.0)) + frames.extend(((code >> i) & 1, 1.0) for i in range(5)) + frames.append((1, stop_bits)) + return frames + + +def preamble_frames(preamble_s, baud_rate): + """Idle mark for about `preamble_s` seconds (whole bit periods, as in pluto-tx).""" + return [(1, 1.0) for _ in range(max(0, round(preamble_s * baud_rate)))] + + +def message_frames(text, baud_rate=BAUD_DEFAULT, preamble_s=PREAMBLE_S, tail_s=TAIL_S, stop_bits=STOP_BITS): + """The whole transmission: idle mark, the text, idle mark again (the transmitter stays on its mark tone, it is not keyed off).""" + frames = preamble_frames(preamble_s, baud_rate) + codes_to_frames(text_to_codes(text if text else " "), stop_bits) + if tail_s > 0: + frames.append((1, tail_s * baud_rate)) + return frames + + +def duration_s(frames, baud_rate): + return sum(d for _, d in frames) / baud_rate + + +def estimate_duration(text, baud_rate=BAUD_DEFAULT, preamble_s=PREAMBLE_S, tail_s=TAIL_S, stop_bits=STOP_BITS): + return duration_s(message_frames(text, baud_rate, preamble_s, tail_s, stop_bits), baud_rate) + + +class OffsetStream: + """The frequency of the tone against the lower tone in Hz (0 or `shift_hz`), one value per update, in blocks. + + The steps between the two tones are rounded raised-cosine ramps of `edge` bit periods centred on the bit boundary (edge 0: abrupt, as + pluto-tx makes them). The boundaries come from the accumulated times, so the bit length does not drift at update rates that are not a + whole multiple of the baud rate.""" + + def __init__(self, frames, rate, baud_rate, shift_hz, reverse=False, edge=0.2): + if not frames: + raise ValueError("no frames") + self.rate, self.baud_rate = rate, baud_rate + spb = rate / baud_rate + bounds = np.cumsum([d for _, d in frames]) * spb # end of every frame in updates (float) + high = np.array([bit == 1 for bit, _ in frames]) == bool(reverse) # True: this frame plays the higher tone + level = np.where(high, float(shift_hz), 0.0) + self.total = int(round(bounds[-1])) + self.b = bounds[:-1] # the boundary between frame j and j + 1 + self.start_level = level[0] + delta = np.diff(level) + keep = delta != 0 + self.b, self.delta = self.b[keep], delta[keep] + self.cum = np.concatenate([[0.0], np.cumsum(self.delta)]) # cum[m]: sum of the first m steps + self.h = edge * spb / 2.0 # half the width of a ramp in updates + self.pos = 0 + + def fraction(self): + return min(1.0, self.pos / max(1, self.total)) + + def values(self, start, count): + c = np.arange(start, start + count) + 0.5 # centres of the updates + if self.h <= 0: + done = np.searchsorted(self.b, c, side="right") + return self.start_level + self.cum[done] + done = np.searchsorted(self.b + self.h, c, side="right") # steps whose ramp is complete + y = self.start_level + self.cum[done] + j0 = np.searchsorted(self.b + self.h, c[0], side="right") + j1 = np.searchsorted(self.b - self.h, c[-1], side="left") + for j in range(j0, j1): # the few ramps in progress inside this block + x = c - self.b[j] + ramp = np.where(x < self.h, 0.5 * (1 - np.cos(np.pi * np.clip((x + self.h) / (2 * self.h), 0.0, 1.0))), 0.0) + y = y + self.delta[j] * ramp + return y + + def blocks(self, block=None): + block = block or max(1, int(self.rate * 0.02)) + while self.pos < self.total: + n = min(block, self.total - self.pos) + y = self.values(self.pos, n) + self.pos += n + yield y + + +def decode_frequency(f_hz, rate, baud_rate=BAUD_DEFAULT, reverse=False): + """Text from a series of instantaneous frequencies (any offset): slices at the middle of the two tones, finds start bits and samples the + middle of every data bit, like a UART.""" + f = np.asarray(f_hz, dtype=float) + spb = rate / baud_rate + k = max(1, int(spb / 8)) + if k > 1: + f = np.convolve(f, np.ones(k) / k, mode="same") + lo, hi = np.percentile(f, [3, 97]) + if hi - lo < 1e-9: + return "" + high = f > (lo + hi) / 2 + mark = high if reverse else ~high # True: mark state + n = len(mark) + codes, free = [], 0 + for e in np.flatnonzero(mark[:-1] & ~mark[1:]) + 1: # a mark -> space edge is a start bit + if e < free: + continue + if e + 7 * spb >= n: + break + code = sum(int(mark[int(e + (1.5 + i) * spb)]) << i for i in range(5)) + if not mark[int(e + 6.25 * spb)]: # the stop element must be mark + continue + codes.append(code) + free = int(e + 6.75 * spb) + return codes_to_text(codes) diff --git a/espdr/sim.py b/espdr/sim.py new file mode 100644 index 0000000..0261ce0 --- /dev/null +++ b/espdr/sim.py @@ -0,0 +1,213 @@ +"""A simulated ESP32-S3 for the tests: answers the control protocol and plays the transmit stream in virtual time (no hardware, no waiting). + +It follows firmware/src/radio.c: the same checks of the frequency and its low byte, the ring of 49152 records, the prefill, a status frame +every 5 ms, the watchdog of 500 ms, the end record, and the summary in the final response. +""" +import struct +import time +import zlib +from collections import deque + +from . import nb, txlink as tl + + +class SimTx: + def __init__(self, flags=3, speed=10.0): + self.flags = flags # CTL_INFO argument 3: 1 receiver, 3 receiver + transmitter + self.speed = speed # virtual seconds per real second + self.t_real = None + self.acc = 0.0 + self.out = bytearray() + self.inp = bytearray() + self.timeout = 0.002 + self.write_timeout = 1.0 + self.params = dict(lo=0, rate=40000, drift=0, limit=600) + self.state = "idle" # idle, prefill, running + self.ring = deque() + self.played = [] # every record that was played + self.under = self.late = 0 + self.seq = 0 + self.vtime = 0.0 # virtual seconds since the session began + self.last_rx = 0.0 + self.sent_total = 0 + self.begin_request_seq = 0 + self.arg_high = 0 + self.ended_reason = None + self.carrier_since = None + self.ops = [] + + # ---- serial-like interface + @property + def in_waiting(self): + self._advance() + return len(self.out) + + def read(self, n): + self._advance() + if not self.out and self.timeout: + time.sleep(self.timeout) # a real port blocks until there is data or the timeout is over + self._advance() + chunk = bytes(self.out[:n]) + del self.out[:n] + return chunk + + def write(self, data): + data = bytes(data) + if self.state == "idle": + self.inp += data + self._requests() + else: + self.inp += data + self._records() + return len(data) + + def close(self): + pass + + # ---- control requests + def _resp(self, op, status=0, value=0, seq=0): + head = struct.pack("= 10: + if self.inp[0] != nb.REQ_MAGIC: + del self.inp[0] + continue + raw = bytes(self.inp[:10]) + if struct.unpack("= 32768 else arg + self._resp(op, 0 if -2000 <= v <= 2000 else nb.CTL_BAD_ARGUMENT, 0, seq) + p["drift"] = v + elif op == tl.TX_OP_TEMP and self.flags & 2: + self._resp(op, 0, (arg << 24) | int(16 * (42.0 + 27.88 * (arg - 2) + 20.52) / 0.4386), seq) + elif op == tl.TX_OP_LIMIT and self.flags & 2: + ok = 1 <= arg <= 3600 + p["limit"] = arg if ok else p["limit"] + self._resp(op, 0 if ok else nb.CTL_BAD_ARGUMENT, 0, seq) + elif op == tl.TX_OP_BEGIN and self.flags & 2: + word = tl.lo_word(p["lo"]) if p["lo"] else 0 + low = word & 0xFF + if not p["lo"] or low < tl.TX_LOW_MARGIN or low > 255 - tl.TX_LOW_MARGIN: + self._resp(op, nb.CTL_BAD_ARGUMENT, word, seq) + return + self._resp(op, 0, word, seq) + self.state, self.begin_request_seq = "prefill", seq + self.t_real, self.acc = time.monotonic(), 0.0 + self.ended_reason = None + self.ring.clear() + self.played = [] + self.under = self.late = 0 + self.vtime = self.last_rx = 0.0 + self.next_status = 0.005 + else: + self._resp(op, nb.CTL_UNKNOWN_OP, 0, seq) + + # ---- the stream + def _records(self): + n = len(self.inp) // 4 * 4 + for i in range(0, n, 4): + w = struct.unpack("> 8) & 0xFF, min(self.under, 255), + min(self.late, 255), 1 if carrier else 0, 0]) + f[7] = (0x100 - sum(f[:7])) & 0xFF + self.seq += 1 + self.out += f + + def _advance(self): + """Virtual time runs `speed` times faster than the clock; the chip works in steps of 5 ms.""" + now = time.monotonic() + if self.state == "idle": + self.t_real = now + return + if self.t_real is None: + self.t_real = now + self.acc += (now - self.t_real) * self.speed + self.t_real = now + while self.acc >= 0.005 and self.state != "idle": + self.acc -= 0.005 + self._step() + + def _step(self): + dt = 0.005 + self.vtime += dt + rate = self.params["rate"] + if self.state == "prefill": + have_end = any((w >> 24) & 1 for w in self.ring) + if len(self.ring) >= tl.TX_PREFILL or have_end: + self.state = "running" + self.vtime = 0.0 + self.carrier_since = 0.0 + self.last_rx = 0.0 + self.record = 127 << 16 + self._status(False) + return + if self.vtime > 3.0: + self._finish(1) + return + self._status(False) + return + # running: play rate * dt records + for _ in range(int(rate * dt)): + if self.ring: + self.record = self.ring.popleft() + else: + self.under += 1 + if self.vtime - self.last_rx > 0.5: + self._finish(1) + return + self.played.append(self.record) + if (self.record >> 24) & 1: + self._finish(0) + return + if len(self.played) >= self.params["limit"] * rate: + self._finish(2) + return + self._status(True) + + def _finish(self, reason): + self.ended_reason = reason + self.out += b"" + self._resp(tl.TX_OP_END, 0, reason << 24 | min(self.under, 255) << 16 | min(self.late, 0xFFFF), self.begin_request_seq) + self.state = "idle" diff --git a/espdr/thermal.py b/espdr/thermal.py new file mode 100644 index 0000000..b80e3e1 --- /dev/null +++ b/espdr/thermal.py @@ -0,0 +1,85 @@ +"""The carrier's thermal frequency drift, predicted from the chip temperature and the time since the transmission began, and cancelled in the records. + +The board's frequency follows its crystal, whose frequency has a turning point (a parabola) around a temperature T0. A transmission heats the chip within +minutes from its idle temperature (about 42 C) towards 56 C. The chip's own sensor (TX_OP_TEMP) gives the start temperature; the rest is a model fitted to +measurements on one board (docs/research/FREQUENCY-DRIFT.md on the research branch). The default numbers are those of that board: a measurement series +on another board (scripts/drift/) gives its own, which --thermal-model takes from a JSON file. +""" +import json + +import numpy as np + +from .txmodes import MAX_Q4, Q4_HZ + +REF_HZ = 2350e6 # the frequency the parameters were measured at; the error is in ppm of the carrier + +DEFAULT = dict( + t0=47.09, # turning point of the crystal, degrees C on the chip's sensor scale + k=19.47, # Hz per degree^2 at 2350 MHz + k3=0.0, # Hz per degree^3 at 2350 MHz (the cubic term of an AT-cut crystal) + t_inf=58.0, # temperature the chip heads to while it transmits + tau_chip=137, # s, heating of the chip in a transmission + tau_xtal=0.5, # s, the crystal follows the chip with this lag + idle=42.0, # start temperature assumed without a sensor reading + early_hz=1118, # slow rise at the switch-on that does not follow the sensor (Hz at 2350 MHz): early_hz * (1 - exp(-t / early_tau)) + early_tau=67, + early_cold_c=0.0, # the transient scales with (idle_ref - start temperature) / early_cold_c, 0 = fixed size +) + + +def load_params(path=None): + p = dict(DEFAULT) + if path: + with open(path) as f: + p.update({k: float(v) for k, v in json.load(f).items() if k in DEFAULT}) + return p + + +def crystal_temperature(t, start_c, p): + """Crystal temperature after t seconds of transmission: the chip heats exponentially, the crystal follows with a first-order lag.""" + d = p["t_inf"] - start_c + th, tx = p["tau_chip"], p["tau_xtal"] + if abs(th - tx) < 1e-6: + th += 1e-3 + return p["t_inf"] - d * (th * np.exp(-t / th) - tx * np.exp(-t / tx)) / (th - tx) + + +def error_hz(t, start_c, p, carrier_hz=REF_HZ): + """The predicted frequency error (against the value at the turning point) at t seconds after the start, in Hz at the carrier frequency.""" + tx = crystal_temperature(t, start_c, p) + x = tx - p["t0"] + e = p["k"] * x ** 2 + p["k3"] * x ** 3 + if p["early_hz"]: + scale = 1.0 if not p["early_cold_c"] else max(0.0, (p["idle"] - start_c) / p["early_cold_c"] + 1.0) + e = e + p["early_hz"] * scale * (1.0 - np.exp(-t / p["early_tau"])) + return e * carrier_hz / REF_HZ + + +class Thermal: + """Adds the opposite of the predicted drift to the frequency field of the records, block after block (call apply() in playing order).""" + + def __init__(self, start_c, rate, carrier_hz, params=None): + self.p = params or dict(DEFAULT) + self.start_c, self.rate, self.carrier_hz = float(start_c), float(rate), float(carrier_hz) + self.n = 0 + self.carry = 0.0 + + def correction_hz(self, n): + t = (self.n + np.arange(n)) / self.rate + return -error_hz(t, self.start_c, self.p, self.carrier_hz) + + def apply(self, records): + """records: uint32 array of the transmit protocol. Returns a copy with the correction added to the frequency field (whole record units, + the rounding error carried on so that the mean is exact).""" + n = len(records) + if not n: + return records + want = self.correction_hz(n) / Q4_HZ + cum = np.cumsum(want) + self.carry + whole = np.floor(cum + 0.5) + add = np.diff(whole, prepend=0.0) + self.carry = float(cum[-1] - whole[-1]) + self.n += n + q4 = (records & 0xFFFF).astype(np.uint16).view(np.int16).astype(np.int32) + q4 = np.clip(q4 + add.astype(np.int32), -MAX_Q4, MAX_Q4).astype(np.int16) + return (records & np.uint32(0xFFFF0000)) | q4.view(np.uint16).astype(np.uint32) diff --git a/espdr/txlink.py b/espdr/txlink.py new file mode 100644 index 0000000..66c058d --- /dev/null +++ b/espdr/txlink.py @@ -0,0 +1,348 @@ +"""The host side of the transmit protocol (firmware/protocol/transmit.h): set up a session, stream records, read the chip's status.""" +import collections +import queue +import struct +import threading +import time +import zlib + +import numpy as np + +from . import nb + +TX_OP_LO, TX_OP_RATE, TX_OP_DRIFT, TX_OP_LIMIT, TX_OP_BEGIN, TX_OP_END, TX_OP_TEMP = 40, 41, 42, 43, 44, 45, 46 +TX_MIN_HZ, TX_MAX_HZ = 2_320_000_000, 2_450_000_000 +TX_LOW_MARGIN = 48 +TX_STATUS_MAGIC, TX_STATUS_BYTES = 0xB6, 8 +TX_RING_RECORDS = 3 * 65536 // 4 +TX_PREFILL = 4000 +END_REASONS = {0: "finished", 1: "the chip stopped because no data arrived for 500 ms", 2: "the longest session was reached", + 3: "the receiver could not be set up again"} +PLL_STEP_HZ = 30e6 / 65536 + + +class TxError(Exception): + pass + + +def lo_word(hz): + """The PLL word the firmware programs for an LO of `hz` (esp32s3_plan_lo, normal conversion): LO = 30 MHz * (32 + W / 65536).""" + scaled = (hz * 65536 + 15_000_000) // 30_000_000 + return scaled - 32 * 65536 + + +def word_hz(word): + """The LO a PLL word really programs (the inverse of lo_word): 30 MHz * (32 + W / 65536); it can differ from the requested frequency by up to 229 Hz.""" + return 30e6 * (32 + word / 65536) + + +def choose_lo(hz, max_offset_steps=44): + """Moves the requested LO by the smallest amount that puts the low byte of the PLL word into 48 .. 207, where the offsets of a + modulated signal cannot carry into the next byte. Returns (lo_hz in steps of 100 Hz, shift in Hz).""" + hz = int(round(hz / 100.0)) * 100 + for d in range(0, 400): + for sign in (1, -1): + cand = hz + sign * d * 100 + low = lo_word(cand) & 0xFF + if TX_LOW_MARGIN <= low <= 255 - TX_LOW_MARGIN: + return cand, cand - hz + raise TxError("no usable LO frequency near the request") + + +def plan_lo(center_hz, ppm=0.0, reserve_hz=0.0): + """Where to put the LO for a signal centred on `center_hz`, and what the records have to add. The PLL word's low byte must leave room + for the modulation (`choose_lo`), which moves the LO by up to 22 kHz; a constant in every record (`static_hz`) makes up for that + move. The records reach +-19.2 kHz (`txmodes.MAX_Q4`), of which `reserve_hz` is kept free for the signal's own deviation. `ppm` is the + board's crystal error (positive: the board transmits too high), as for `--ppm`. + + Returns a dict: `lo_hz` (the LO to give the chip, in steps of 100 Hz), `static_hz` (a whole number of record units), `center_hz` (the + centre the signal really gets), `miss_hz` (that against the wanted one, nonzero only when the move was too large for the records).""" + from . import txmodes + k = 1.0 + ppm * 1e-6 + lo_hz, _ = choose_lo(center_hz / k) + lo_real = word_hz(lo_word(lo_hz)) * k + unit = txmodes.Q4_HZ * k # one record unit on the air + limit = txmodes.MAX_Q4 - int(np.ceil(reserve_hz / unit)) + static_q4 = int(round((center_hz - lo_real) / unit)) + static_q4 = min(max(static_q4, -limit), limit) + real = lo_real + static_q4 * unit + return dict(lo_hz=lo_hz, static_hz=static_q4 * txmodes.Q4_HZ, center_hz=real, miss_hz=real - center_hz) + + +class Frames: + """Splits the chip's output during a session into status frames and the final response.""" + + def __init__(self): + self.buf = bytearray() + + def feed(self, data): + self.buf += data + events = [] + i = 0 + b = self.buf + while i < len(b): + if b[i] == TX_STATUS_MAGIC: + if i + TX_STATUS_BYTES > len(b): + break + f = b[i:i + TX_STATUS_BYTES] + if sum(f) & 0xFF == 0: + events.append(("status", dict(seq=f[1], fill=f[2] | f[3] << 8, underruns=f[4], late=f[5], carrier=bool(f[6] & 1)))) + i += TX_STATUS_BYTES + continue + elif b[i] == nb.RESP_MAGIC: + if i + 16 > len(b): + break + raw = bytes(b[i:i + 16]) + if struct.unpack("> 24, (v & 0xFFFFFF) / 16.0 + c = 0.4386 * raw - 27.88 * (idx - 2) - 20.52 + if c < 70: + return c + return c + + def begin(self, expect_word=None): + try: + status, word = self.link.command(TX_OP_BEGIN, 0, allow=(nb.CTL_OK,)) + except nb.CommandError as e: + raise TxError({nb.CTL_BAD_ARGUMENT: "the chip refused the frequency or the settings", + nb.CTL_NOT_READY: "the receiver of the chip is not ready", + nb.CTL_FAILED: "the PLL did not lock at this frequency (try another)"}.get(e.status, f"the chip answered status {e.status}")) + if expect_word is not None and word != expect_word: + raise TxError(f"the chip programmed PLL word 0x{word:06X}, expected 0x{expect_word:06X}") + return word + + def stream(self, records, target_fill=8000, on_status=None, stop=None, idle_s=0.002): + """records: a queue.Queue of numpy uint32 arrays; None ends the transmission. stop: a threading.Event that ends it too. + Returns the chip's summary dict.""" + self.ser.timeout = idle_s + self.ser.write_timeout = 1.0 + + def source(): + try: + return records.get_nowait() + except queue.Empty: + return False + + pump = _Pump(self, source, target_fill, on_status, stop) + while True: + summary = pump.step() + if summary is not None: + return summary + + +class _Pump: + """The work of one transmission, one non-blocking step at a time: read the chip's frames, keep its ring near `target_fill` records, + send the end record, wait for the summary. `source()` returns a numpy array of records, None when the data has ended, or False when + there is nothing right now. Shared by `Session.stream` (the caller's thread) and `Streamer` (a thread of its own).""" + + def __init__(self, session, source, target_fill=8000, on_status=None, stop=None): + self.session, self.ser, self.source = session, session.ser, source + self.target_fill, self.on_status, self.stop = target_fill, on_status, stop + self.frames = Frames() + self.pending = None + self.sent_since = 0 + self.fill = 0 + self.ending = False + self.end_sent = False + self.t_last = time.monotonic() + self.end_by = None + self._abort = False + + def abort(self): + """From any thread: drop what has not been sent and end the transmission at once (the end record goes out regardless of room).""" + self._abort = True + + def step(self): + """One round: returns the chip's summary dict when the transmission is over, otherwise None. Raises TxError.""" + import serial + if self._abort: + self.pending = None + self.ending = True + self._abort = False + ser = self.ser + data = ser.read(ser.in_waiting or 1) + if data: + for kind, ev in self.frames.feed(data): + if kind == "status": + self.session.status = ev + self.fill, self.sent_since = ev["fill"], 0 + if self.on_status: + self.on_status(ev) + elif ev["op"] == TX_OP_END: + v = ev["value"] + self.session.summary = dict(reason=v >> 24, underruns=(v >> 16) & 0xFF, late=v & 0xFFFF, status=ev["status"]) + return self.session.summary + now = time.monotonic() + if not self.ending and self.stop is not None and self.stop.is_set(): + self.ending = True + if not self.end_sent: + room = self.target_fill - self.fill - self.sent_since + if room >= 256 or (self.ending and self.pending is None): + if self.pending is None and not self.ending: + item = self.source() + if item is None: + self.ending = True + elif item is not False: + self.pending = item + if self.pending is not None and len(self.pending): + n = min(room, len(self.pending), 4096) + try: + ser.write(self.pending[:n].astype(" self.end_by: + raise TxError("the chip did not confirm the end of the transmission") + if now - self.t_last > 5.0 and not self.end_sent and self.fill == 0 and self.session.status is None: + raise TxError("the chip sends no status; is the transmitter firmware running?") + return None + + +class Streamer: + """A transmission driven by pushing: `push(records)` from any thread (it blocks while more than `max_buffered` records wait, so the + caller runs at the chip's pace), `finish()` ends it with the end record after everything pushed has played, `abort()` ends it at + once, `close()` always returns. A thread of its own talks to the chip, so the caller needs no loop. Start it after `Session.begin()`. + The carrier comes on when the chip's ring holds `TX_PREFILL` records (100 ms at 40000 a second), so the first 100 ms of what is + pushed is the latency from key to carrier. After `Session.begin()` the first 4000 records must arrive within 3 s, or the chip ends the + session without a carrier. `abort()` cannot be faster than the chip's ring: the end record queues behind what the chip holds + (`target_fill` records, 125 ms at the default), so an abort takes up to about that long to silence the carrier.""" + + def __init__(self, session, target_fill=5000, on_status=None, max_buffered=16384, idle_s=0.002): + self.session = session + self.max_buffered = max_buffered + self.error = None + self.summary = None + self._cv = threading.Condition() + self._buf = collections.deque() + self._n = 0 + self._ending = False + self._dead = False + session.ser.timeout = idle_s + session.ser.write_timeout = 1.0 + self._pump = _Pump(session, self._source, target_fill, on_status) + self._thread = threading.Thread(target=self._run, name="espdr-streamer", daemon=True) + self._thread.start() + + # -- the thread of its own + def _source(self): + with self._cv: + if self._buf: + a = self._buf.popleft() + self._n -= len(a) + self._cv.notify_all() + return a + return None if self._ending else False + + def _run(self): + try: + while True: + summary = self._pump.step() + if summary is not None: + self.summary = summary + return + except Exception as e: # noqa: BLE001 - handed to the caller by finish() and push() + self.error = e + finally: + with self._cv: + self._dead = True + self._buf.clear() + self._n = 0 + self._cv.notify_all() + + # -- the caller's side + @property + def alive(self): + return not self._dead + + @property + def fill(self): + """The chip's ring fill in records, as of its last status frame.""" + return self._pump.fill + + def push(self, records, timeout=None): + """Queues records (numpy uint32). Blocks while the queue is full. Returns False if they were not taken (timeout, or the + transmission is over or ending).""" + import numpy as np + a = np.asarray(records, dtype=np.uint32) + if not len(a): + return True + end = None if timeout is None else time.monotonic() + timeout + with self._cv: + while self._n >= self.max_buffered and not self._dead and not self._ending: + left = None if end is None else end - time.monotonic() + if left is not None and left <= 0: + return False + self._cv.wait(left if left is not None else 0.1) + if self._dead or self._ending: + return False + self._buf.append(a) + self._n += len(a) + return True + + def finish(self, timeout=10.0): + """Ends the transmission after everything pushed has been played; returns the chip's summary dict. Raises TxError if the + chip does not confirm within `timeout` seconds or the transmission broke down before.""" + with self._cv: + self._ending = True + self._cv.notify_all() + self._thread.join(timeout) + if self._thread.is_alive(): + self.abort() + self._thread.join(2.0) + raise TxError("the chip did not confirm the end of the transmission in time") + if self.error is not None: + raise self.error if isinstance(self.error, TxError) else TxError(str(self.error)) + return self.summary + + def abort(self): + """Ends the transmission at once; what has not been sent is dropped. Returns immediately (see close()).""" + self._pump.abort() + with self._cv: + self._ending = True + self._buf.clear() + self._n = 0 + self._cv.notify_all() + + def close(self, timeout=5.0): + """Aborts if still running and waits for the thread, at most `timeout` seconds. Never raises. Returns the summary or None.""" + if self._thread.is_alive(): + self.abort() + self._thread.join(timeout) + return self.summary diff --git a/espdr/txmodes.py b/espdr/txmodes.py new file mode 100644 index 0000000..c2c9b17 --- /dev/null +++ b/espdr/txmodes.py @@ -0,0 +1,176 @@ +"""FM, SSB and FSK modulators for the ESP32-S3 transmitter. + +The chip has no I/Q input. What it can do is move its carrier in frequency (the RF PLL's sigma-delta word, 457.76 Hz per step, updated +40000 times a second) and in amplitude (a gain code, 0.28 dB per step over 18 dB). A modulator turns 8 kHz audio into one 32-bit record per +update (firmware/protocol/transmit.h): the frequency offset in 1/16 word steps, the gain code, flags. + +FM sets the frequency from the audio and keeps the gain constant. +SSB is polar modulation: the analytic signal of the audio (the audio plus j times its Hilbert transform: positive frequencies only, which is + the upper sideband) plus a carrier gives an envelope, sent as the gain code, and a phase, sent as its derivative, the frequency. +FSK sends a given frequency (RTTY: two values) with a constant gain, like FM without audio. +""" +import numpy as np + +from . import dsp + +STEP_HZ = 30e6 / 65536 # one PLL word step +Q4_HZ = STEP_HZ / 16 # unit of the frequency field of a record +MAX_STEPS = 44 # the firmware clamps the offset to +-44 steps (TX_MAX_STEPS) +MAX_Q4 = (MAX_STEPS - 2) * 16 # the host stays two steps inside +GAIN_STRONGEST, GAIN_WEAKEST = 64, 127 +AUDIO_RATE = 8000 + +# Amplitude of the carrier against gain code 127 in dB, measured with a PlutoSDR (docs/research/TX-RESEARCH.md, stage A1). +GAIN_CURVE = [(127, 0.0), (124, 1.32), (121, 1.94), (118, 2.79), (115, 3.82), (112, 4.74), (109, 5.22), (106, 6.05), (103, 7.03), + (100, 8.05), (97, 8.79), (94, 9.78), (91, 10.56), (88, 11.57), (85, 12.26), (82, 13.07), (79, 13.91), (76, 14.76), + (73, 15.51), (70, 16.33), (67, 17.12), (64, 17.90)] +_CODES = np.array([c for c, _ in GAIN_CURVE][::-1], dtype=float) # 64 .. 127 +_DB = np.array([d for _, d in GAIN_CURVE][::-1], dtype=float) # 17.9 .. 0 +RANGE_DB = float(_DB[0]) + + +def peak_code(power_db): + """Gain code of the strongest envelope for a power setting in dB against the strongest possible (0, -17.9 at the weakest).""" + if power_db > 0: + raise ValueError("the power cannot be raised above 0 dB (the strongest setting)") + if power_db < -RANGE_DB: + raise ValueError(f"the weakest possible power is {-RANGE_DB:.1f} dB") + return int(round(float(np.interp(RANGE_DB + power_db, _DB[::-1], _CODES[::-1])))) + + +def db_of_code(code): + return np.interp(code, _CODES, _DB) + + +def codes_for_levels(level, peak): + """Gain codes for envelope values `level` (1.0 = the peak) when the peak is sent with code `peak`.""" + db = db_of_code(peak) + 20 * np.log10(np.maximum(level, 1e-6)) + codes = np.interp(db, _DB[::-1], _CODES[::-1]) # inverse of the curve; below the curve's end it stays at 127 + return np.clip(np.rint(codes), peak, GAIN_WEAKEST).astype(np.uint32) + + +def pack(q4, codes, end=False): + q4 = np.clip(np.rint(q4), -MAX_Q4, MAX_Q4).astype(np.int16) + rec = q4.view(np.uint16).astype(np.uint32) | (np.asarray(codes, dtype=np.uint32) << 16) + if end and len(rec): + rec[-1] |= np.uint32(1 << 24) + return rec + + +def end_record(code=GAIN_WEAKEST): + return np.array([(code << 16) | (1 << 24)], dtype=np.uint32) + + +class _Front: + """Band-pass, AGC (optional) for 8 kHz audio blocks.""" + + def __init__(self, band, agc, gain_db): + self.bp = dsp.Fir(dsp.bandpass(255, band[0], band[1], AUDIO_RATE)) + self.agc = dsp.Agc(AUDIO_RATE, gain_db=gain_db) if agc else None + self.manual = 10 ** (gain_db / 20) + self.delay = self.bp.delay + + def process(self, x): + y = self.bp.process(np.asarray(x, dtype=float)) + return self.agc.process(y) if self.agc else np.clip(y * self.manual, -1, 1) + + +class FmModulator: + """Narrowband FM: `deviation` Hz at full scale, with the usual voice pre-emphasis (+6 dB per octave from 300 to 3000 Hz).""" + + name = "FM" + + def __init__(self, rate=40000, deviation=2500.0, power_db=0.0, preemph=True, agc=True, gain_db=0.0, band=(300.0, 3000.0)): + if deviation / Q4_HZ > MAX_Q4: + raise ValueError(f"the deviation can be at most {MAX_Q4 * Q4_HZ:.0f} Hz") + self.rate, self.deviation = rate, deviation + self.code = peak_code(power_db) + self.front = _Front(band, agc, gain_db) + self.pre = dsp.preemphasis(AUDIO_RATE) if preemph else None + self.up = dsp.Resampler(AUDIO_RATE, rate) + self.latency_s = (self.front.delay + self.up.latency / (rate / AUDIO_RATE)) / AUDIO_RATE + + def process(self, audio): + x = self.front.process(audio) + if self.pre: + x = np.clip(self.pre.process(x), -1, 1) + y = self.up.process(x) + return pack(y * self.deviation / Q4_HZ, np.full(len(y), self.code, dtype=np.uint32)) + + def trim(self, ppm): + self.up.trim = ppm + + +class FskModulator: + """Two-tone FSK (RTTY): the input is the frequency of the tone in Hz against a fixed base frequency, one value per update (not audio). + + The gain code stays constant, like FM. `static_hz` is a constant added to every record: the base frequency against the board's LO, which + makes up for the LO having been moved to a PLL word that is easy to program (the records can carry about +-19 kHz). Records count in + units of Q4_HZ (28.6 Hz): the constant and the steps are rounded to whole units separately, so that the distance of two tones does not + depend on where the constant falls.""" + + name = "RTTY" + + def __init__(self, rate=40000, power_db=0.0, static_hz=0.0): + self.rate = rate + self.code = peak_code(power_db) + self.static_q4 = int(round(static_hz / Q4_HZ)) + + @property + def static_hz(self): + return self.static_q4 * Q4_HZ + + def process(self, offsets_hz): + y = np.asarray(offsets_hz, dtype=float) + return pack(np.rint(y / Q4_HZ) + self.static_q4, np.full(len(y), self.code, dtype=np.uint32)) + + +class SsbModulator: + """Single sideband by polar modulation. `carrier` is the carrier's share of the peak envelope: 0 suppresses it completely (the + envelope then runs through zero, which the 18 dB range of the gain code cannot follow exactly and the frequency cannot follow at + the nulls; measured quality: docs/research), 0.05 leaves a faint pilot to tune to, 0.5 or more is a robust AM-compatible signal. + `delay` (in updates) delays the gain path against the frequency path: the transmitter's amplitude responds 25 us earlier.""" + + def __init__(self, rate=40000, sideband="usb", carrier=0.05, power_db=0.0, delay=1.0, agc=True, gain_db=0.0, band=(300.0, 2700.0)): + if sideband not in ("usb", "lsb"): + raise ValueError("sideband must be usb or lsb") + if not 0.0 <= carrier < 1.0: + raise ValueError("the carrier share must be 0 .. 1") + self.name = sideband.upper() + self.rate, self.lsb, self.c, self.delay = rate, sideband == "lsb", carrier, delay + self.peak = peak_code(power_db) + self.front = _Front(band, agc, gain_db) + self.analytic = dsp.Analytic(255) + self.up = dsp.Resampler(AUDIO_RATE, rate) + self.z_prev = carrier + 0j + self.a_tail = np.full(4, carrier) + self.latency_s = (self.front.delay + self.analytic.delay) / AUDIO_RATE + self.up.latency / rate + + def process(self, audio): + x = self.front.process(audio) + xa = self.analytic.process(x) + if self.lsb: + xa = np.conj(xa) + xa = dsp.clip_magnitude(xa, 1.0) + z = self.c + (1.0 - self.c) * self.up.process(xa) + if len(z) == 0: + return np.zeros(0, dtype=np.uint32) + env = np.minimum(np.abs(z), 1.0) + prev = np.concatenate([[self.z_prev], z[:-1]]) + f = np.angle(z * np.conj(prev)) * self.rate / (2 * np.pi) # instantaneous frequency in Hz + self.z_prev = z[-1] + # the gain path later by `delay` updates (linear interpolation for a fraction) + n = int(np.floor(self.delay)) + frac = self.delay - n + hist = np.concatenate([self.a_tail, env]) + base = len(self.a_tail) + a = (1 - frac) * hist[base - n: base - n + len(env)] + frac * hist[base - n - 1: base - n - 1 + len(env)] + self.a_tail = hist[len(hist) - len(self.a_tail):] + return pack(f / Q4_HZ, codes_for_levels(a, self.peak)) + + def trim(self, ppm): + self.up.trim = ppm + + +def idle_record(code=GAIN_WEAKEST): + return np.array([code << 16], dtype=np.uint32) diff --git a/espdr/udev/70-espdr.rules b/espdr/udev/70-espdr.rules new file mode 100644 index 0000000..1906e19 --- /dev/null +++ b/espdr/udev/70-espdr.rules @@ -0,0 +1,5 @@ +# ESP32-S3 running the eSpDR espdr firmware (native USB Serial/JTAG port, 303a:1001). +# - keeps ModemManager from probing the port with AT commands (any byte it sends would stop a run) +# - gives the logged-in desktop user access without joining the "dialout" group +# Install: sudo cp udev/70-espdr.rules /etc/udev/rules.d/ && sudo udevadm control --reload && sudo udevadm trigger +SUBSYSTEM=="tty", ATTRS{idVendor}=="303a", ATTRS{idProduct}=="1001", ENV{ID_MM_DEVICE_IGNORE}="1", TAG+="uaccess" diff --git a/install-espdr.sh b/install-espdr.sh new file mode 100755 index 0000000..54a7ca9 --- /dev/null +++ b/install-espdr.sh @@ -0,0 +1,119 @@ +#!/usr/bin/env bash +# Optional, separate installer for the ESP32-S3 TX device of pluto-tx ("ESP32-S3 (13 cm)": FM and M17 on 2320..2450 MHz from an ESP32-S3 dev +# board). Kept apart from install.sh like install-m17.sh: the device is optional, and it needs two things apt cannot give: +# +# * esptool 5 or newer, which loads the transmitter firmware into the board's RAM. Debian/Ubuntu's own esptool package is version 4, which +# does not work with this firmware loader, and pip may not write to the system Python (PEP 668): esptool is installed with pipx. +# * the board's udev rule (keeps ModemManager from probing the port with AT commands; any byte it sends would stop a transmission). +# +# The espdr code itself (host side of the ESP32 transmitter) and the firmware images are part of this repository (./espdr), nothing is +# downloaded for them. Needs an ESP32-S3 dev board with TWO USB ports (the second one is the USB-UART bridge that loads the firmware). +# +# Usage: +# ./install.sh # first, if you haven't already +# ./install-espdr.sh [--yes] [--no-udev] [--dry-run] +# +# --yes do not ask before installing the udev rule (it is installed with sudo) +# --no-udev do not offer the udev rule +# --dry-run show what would be done, change nothing +# +# Safe to re-run. Transmitting takes an amateur radio licence: the transmitter asks you to confirm its notice once (see the end of this script). +set -euo pipefail + +if [ "$(id -u)" = "0" ]; then + echo "FEHLER: Dieses Skript nicht mit sudo oder als root ausfuehren." >&2 + echo "Richtig: ./install-espdr.sh (das Skript ruft sudo intern fuer apt-get und die udev-Regel auf)" >&2 + exit 1 +fi + +yes=0; udev=1; dry=0 +for a in "$@"; do + case "$a" in + --yes) yes=1 ;; + --no-udev) udev=0 ;; + --dry-run) dry=1 ;; + -h|--help) sed -n '2,23p' "$0" | sed 's/^# \{0,1\}//'; exit 0 ;; + *) echo "unknown option $a (see --help)" >&2; exit 2 ;; + esac +done + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +RULE_SRC="$SCRIPT_DIR/espdr/udev/70-espdr.rules" +RULE_DST=/etc/udev/rules.d/70-espdr.rules + +say() { printf '\n== %s\n' "$*"; } +run() { if [ "$dry" = 1 ]; then echo "[dry run] $*"; else "$@"; fi; } + +echo "== ESP32-S3 TX device installer ==" +echo "Repo directory: $SCRIPT_DIR" +[ "$dry" = 1 ] && echo "(dry run: nothing is changed)" + +[ -d "$SCRIPT_DIR/espdr" ] && [ -f "$SCRIPT_DIR/espdr/images/tx.bin" ] || { + echo "$SCRIPT_DIR/espdr (with images/tx.bin) is missing: this checkout is incomplete. tools/sync-espdr.sh makes it." >&2; exit 1; } + +say "Python modules (numpy, pyserial) and pipx" +if command -v apt-get >/dev/null 2>&1; then + run sudo apt-get install -y python3-numpy python3-serial pipx +else + echo "apt-get not found: install numpy, pyserial and pipx with your package manager." >&2 +fi + +say "esptool 5 or newer, with pipx" +need_esptool=1 +if command -v esptool >/dev/null 2>&1; then + ver="$(esptool version 2>/dev/null | grep -Eo '[0-9]+\.[0-9]+(\.[0-9]+)?' | head -n1 || true)" + if [ -n "$ver" ] && [ "${ver%%.*}" -ge 5 ] 2>/dev/null; then + echo "esptool $ver is installed, good." + need_esptool=0 + else + echo "an esptool is on the PATH (version '${ver:-unknown}'), but 5 or newer is needed." + fi +fi +if [ "$need_esptool" = 1 ]; then + # --force replaces an older pipx install; a distribution's esptool 4 in /usr/bin is shadowed by ~/.local/bin on the PATH + run pipx install --force esptool + run pipx ensurepath + case ":$PATH:" in + *":$HOME/.local/bin:"*) ;; + *) echo "note: $HOME/.local/bin is not on your PATH in this shell; open a new terminal (pipx ensurepath changed your profile)." ;; + esac +fi + +if [ "$udev" = 1 ]; then + say "udev rule for the board's USB port" + if [ -f "$RULE_DST" ] && cmp -s "$RULE_SRC" "$RULE_DST"; then + echo "$RULE_DST is already installed." + else + ok=$yes + if [ "$ok" = 0 ] && [ "$dry" = 0 ]; then + read -r -p "install $RULE_DST with sudo (keeps ModemManager off the board)? [y/N] " answer || answer=n + case "$answer" in y|Y|yes|YES) ok=1 ;; esac + fi + if [ "$ok" = 1 ] || [ "$dry" = 1 ]; then + run sudo cp "$RULE_SRC" "$RULE_DST" + run sudo udevadm control --reload + run sudo udevadm trigger + else + echo "skipped. Without it, stop ModemManager yourself or the first transmission may fail." + fi + fi +fi + +say "access to the board's serial ports" +if id -nG "$USER" | tr ' ' '\n' | grep -qx dialout; then + echo "$USER is in the group dialout, good." +else + echo "$USER is not in the group dialout; the board's USB-UART port (/dev/ttyACM* or /dev/ttyUSB*) needs it:" + echo " sudo usermod -aG dialout $USER (then log out and in again)" +fi + +say "done" +cat <<'EOF' +Start pluto-tx, choose the device "ESP32-S3 (13 cm)" and leave the connection blank (the board is found by its USB ports), or on the +command line: pluto-cli tx fm --device espdr --freq 2345000000 (and `m17`, with --src-callsign). Only FM and M17 are carried by this device. +The firmware is loaded into the board's RAM when needed; nothing is written to its flash. + +Before the first transmission confirm the licence notice of the ESP32 transmitter once (it sends nothing): + python3 -m espdr.cli_tx -f 2345 --test-tone 1000 --dry-run --accept-licence +Transmitting takes an amateur radio licence, and you are responsible for what you send. +EOF diff --git a/pluto_cli/tx.py b/pluto_cli/tx.py index 823ce1c..c5018a0 100644 --- a/pluto_cli/tx.py +++ b/pluto_cli/tx.py @@ -33,7 +33,8 @@ def add_common_args(parser): parser.add_argument( "--uri", default=None, help="Device connection string (libiio URI for pluto, serial for hackrf, blank for " - "soundcard's system default). Omit to use that backend's own default.", + "soundcard's system default, for espdr blank to find the ESP32-S3 board or NATIVE_PORT[,BRIDGE_PORT]). " + "Omit to use that backend's own default.", ) parser.add_argument( "--freq", type=float, default=tx_config.DEFAULT_FREQUENCY, @@ -122,6 +123,11 @@ def _build(args, mode, connection, **mode_kwargs): def _run(args, mode, emitter, post_construct=None, **mode_kwargs): device_cls = tx_devices.DEVICE_REGISTRY[args.device] + mode_name = PlutoTxFlowgraph.MODE_NAMES.get(mode, "") + if not device_cls.supports_mode(mode_name): + emitter.error(f"the {device_cls.display_name} device cannot send {mode_name}: it carries only {', '.join(sorted(device_cls.supported_modes))} " + f"(it sends the frequency of a constant-envelope signal and nothing else)") + return 1 connection = runtime.resolve_connection(device_cls, args.uri) runtime.probe_or_exit(device_cls, connection, emitter) tb = runtime.build_or_exit(lambda: _build(args, mode, connection, **mode_kwargs), device_cls, connection, emitter) diff --git a/pluto_tx/config.py b/pluto_tx/config.py index df91487..eb780e4 100644 --- a/pluto_tx/config.py +++ b/pluto_tx/config.py @@ -694,6 +694,7 @@ def meshtastic_preset_index(modem: str, region: str) -> int: ("2m", 144_000_000, 146_000_000), ("70cm", 430_000_000, 440_000_000), ("23cm", 1_240_000_000, 1_300_000_000), + ("13cm", 2_320_000_000, 2_450_000_000), # the ESP32-S3 device sends only here ] diff --git a/pluto_tx/devices/__init__.py b/pluto_tx/devices/__init__.py index 70ec688..8d38509 100644 --- a/pluto_tx/devices/__init__.py +++ b/pluto_tx/devices/__init__.py @@ -23,6 +23,16 @@ AIOC_AVAILABLE = False +# The ESP32-S3 needs the espdr package (shipped in this repository as ./espdr: numpy, pyserial) -- same posture as AIOC above: without it the +# device just does not appear. Loading its firmware also needs esptool 5 or newer, which is only checked when the board is first used. +try: + from .espdr import EspdrDevice + DEVICE_REGISTRY["espdr"] = EspdrDevice + ESPDR_AVAILABLE = True +except ImportError: + ESPDR_AVAILABLE = False + + def primary_power_stage(device_type): """The PowerStage with is_primary=True for a device type, without needing an actual device instance -- power_stages is a class attribute.""" diff --git a/pluto_tx/devices/base.py b/pluto_tx/devices/base.py index 81b8be9..7d717bd 100644 --- a/pluto_tx/devices/base.py +++ b/pluto_tx/devices/base.py @@ -87,6 +87,15 @@ class TxDevice(abc.ABC): # (and, for a Soundcard-kind device, the audio-only device itself) completely # untouched on purpose -- see those branches' docstrings. needs_ptt_control: bool = False + # The modes this device can carry, as the names the CLI uses ("fm", "m17", ...; see pluto_cli/tx.py MODES), or None for every mode the + # device's kind can carry at all (RF: everything, audio-only: see is_audio_only()). A device that can only play signals of a certain kind + # (the ESP32-S3 sends the FREQUENCY of a constant-envelope signal and nothing else) lists them here; flowgraph.py falls back to FM for + # any other, pluto_cli refuses them with a message and the GUI greys them out. + supported_modes: Optional[frozenset] = None + + @classmethod + def supports_mode(cls, mode_name: str) -> bool: + return cls.supported_modes is None or mode_name in cls.supported_modes def __init__(self, connection: str, frequency_hz: float, sample_rate_hz: float, bandwidth_hz: Optional[float]): diff --git a/pluto_tx/devices/espdr.py b/pluto_tx/devices/espdr.py new file mode 100644 index 0000000..2fdcfc9 --- /dev/null +++ b/pluto_tx/devices/espdr.py @@ -0,0 +1,292 @@ +"""ESP32-S3 TX backend: a Wi-Fi chip's test tone, steered in frequency 40 000 times a second (polar modulation), on 13 cm (2320..2450 MHz). + +The chip cannot play I/Q samples through this transmitter. What it can do is move its carrier in frequency and (a little) in amplitude, which +is all a signal with a CONSTANT ENVELOPE needs: this device takes the complex baseband the flowgraph produces, keeps its instantaneous frequency +(espdr.polar.IqToPolar) and sends that to the chip as one record per update (espdr.txlink.Streamer). So FM and M17 (and, later, other FSK modes) +work as they are, and everything with amplitude modulation (SSB, PSK, FT8, ...) does not: supported_modes lists what is allowed. + +The host side is the `espdr` package, shipped in this repository as ./espdr (a copy of github.com/jochenhammes/esp32-sdr-trx, Zero-Clause BSD +licence, synchronised by tools/sync-espdr.sh; do not edit it here). Needs numpy and pyserial, and esptool 5 or newer to load the firmware into +the board's RAM (`pipx install esptool`; see install-espdr.sh). + +The chip radiates a carrier whenever a session runs, and a session is what pre_key()/post_unkey() open and close: "off" is the END of the +session, not a power setting. Setting up a session takes a moment (PLL tuning in the chip), so pre_key() blocks briefly like the Pluto's. The +chip's ring buffer holds about 100..200 ms: the carrier comes on that much after pre_key() and ends that much after post_unkey(). + +The frequency cannot change while a session runs: set_frequency() while keyed is applied at the next pre_key() (with a warning). + +Connection string: "" (find the board), "NATIVE_PORT" (the board's own USB port, the firmware must already run), or "NATIVE_PORT,BRIDGE_PORT" +(the board's USB-UART port loads the firmware: "/dev/ttyACM1,/dev/ttyACM0", or ",/dev/ttyACM0" if only the bridge is known).""" +import logging +import threading +import time +from dataclasses import dataclass + +import numpy as np +from gnuradio import gr + +from espdr import board, config as espdr_config, nb, polar, thermal as espdr_thermal, txlink, txmodes + +from .base import PowerStage, TxDevice + +log = logging.getLogger(__name__) + +UPDATE_RATE = 40_000 # records the chip plays a second +SAMPLE_RATE = 80_000 # what the flowgraph runs this device at (2 samples per record, 5/3 of M17's 48 kHz) +DEVIATION_RESERVE_HZ = 4_000.0 # of the +-19.2 kHz range of the records, kept free for the signal itself (M17 peaks at 3.5 kHz) +SESSION_LIMIT_S = 3600 # the chip's own limit on one session +SWITCH_ON_DRIFT_HZ = 210 # espdr-tx's default of --drift (the first seconds of a cold start) +PUSH_TIMEOUT_S = 2.0 +LICENCE_HELP = ("Transmitting takes an amateur radio licence. Read the notice of the ESP32 transmitter and confirm it once with\n" + " python3 -m espdr.cli_tx -f 2345 --test-tone 1000 --dry-run --accept-licence\n" + "(it sends nothing; it only records that you have read it).") + + +def _parse_connection(connection): + """"" -> (None, None); "NATIVE" -> (NATIVE, None); "NATIVE,BRIDGE" or ",BRIDGE" -> (NATIVE or None, BRIDGE).""" + native, _, bridge = (connection or "").strip().partition(",") + return native.strip() or None, bridge.strip() or None + + +@dataclass +class _Session: + """What exists between pre_key() and post_unkey().""" + session: object + streamer: object + modulator: object + thermal: object + plan: dict + started: float + underruns_while_pushing: int = 0 # the chip's count when the last block went to it: later ones are the pause before the end + + +class EspdrSink(gr.sync_block): + """Consumes the flowgraph's complex baseband at SAMPLE_RATE. Not keyed: samples are dropped, but at the real-time rate (the flowgraph + produces samples all the time and gates them with tx_gain; a sink that swallowed them at once would let its sources run away). Keyed: + the samples become records and are pushed to the chip, which slows the flowgraph down to its own pace.""" + + def __init__(self, device): + gr.sync_block.__init__(self, name="EspdrSink", in_sig=[np.complex64], out_sig=None) + self._device = device + self._due = None + + def _pace(self, n): + now = time.monotonic() + if self._due is None or self._due < now - 0.5: + self._due = now + self._due += n / SAMPLE_RATE + delay = self._due - now + if delay > 0: + time.sleep(min(delay, 0.5)) + + def work(self, input_items, output_items): + x = input_items[0] + n = len(x) + if not self._device._consume(x): + self._pace(n) + else: + self._due = None + return n + + +class EspdrDevice(TxDevice): + device_type = "espdr" + display_name = "ESP32-S3 (13 cm)" + connection_kind = "serial" + DEFAULT_CONNECTION = "" + + frequency_range_hz = (txlink.TX_MIN_HZ, txlink.TX_MAX_HZ) + sample_rate_range_hz = (UPDATE_RATE, 160_000) + default_sample_rate_hz = SAMPLE_RATE + default_bandwidth_hz = None + supports_persistent_sink = True # the sink object stays; it drops samples while no session runs + supports_frequency_correction = True # the board's crystal is off by some ppm (a few kHz at 2.3 GHz) + tx_end_loss_s = 0.0 # post_unkey() waits until the chip has played everything + # What a constant-envelope baseband can carry: the frequency is all that is sent. + supported_modes = frozenset({"fm", "m17"}) + + # One stage, in dB against the strongest gain code of the chip (code 64); 0.28 dB per code over 17.9 dB. "Off" is the end of the session. + power_stages = ( + PowerStage(name="gain", label="TX Power (gain)", kind="continuous_db", + min_value=-txmodes.RANGE_DB, max_value=0.0, unit="dB", is_primary=True, off_value=-txmodes.RANGE_DB), + ) + default_power_ceiling = -12.0 # conservative: the output is some microwatts, but nothing here is calibrated + + def __init__(self, connection, frequency_hz, sample_rate_hz, bandwidth_hz): + super().__init__(connection, frequency_hz, sample_rate_hz, bandwidth_hz) + self._native, self._bridge = _parse_connection(connection) + self._lock = threading.RLock() + self._link = None + self._active = None + self._power_db = self.power_stages[0].off_value + self._sink = None + self._status = None + self._clip_warned = False + self._temperature_c = None + + # ---- the board + def _open_link(self): + """Finds the board, loads the transmitter firmware into its RAM if it is not running, and opens its port.""" + if self._link is not None: + return + self._native = board.ensure(board.TX, port=self._native, bridge=self._bridge, load="auto", log=log.info) + self._link = nb.open_link(self._native) + + def prepare_for_start(self): + if not espdr_config.licence_accepted(): + raise RuntimeError(espdr_config.LICENCE_NOTICE + "\n" + LICENCE_HELP) + self._open_link() + + def build_sink(self): + self._sink = EspdrSink(self) + return self._sink + + # ---- settings + def _check_frequency(self, freq_hz): + lo, hi = self.frequency_range_hz + if not lo <= freq_hz <= hi: + raise ValueError(f"{freq_hz / 1e6:.4f} MHz is outside {lo / 1e6:.0f} .. {hi / 1e6:.0f} MHz, the only range the ESP32 transmitter sends in") + + def set_frequency(self, freq_hz): + self._check_frequency(freq_hz) + self.frequency_hz = freq_hz + self._apply_frequency() + + def _apply_frequency(self): + if self._active is not None: + log.warning("the ESP32 transmitter cannot retune while it sends: %.4f MHz applies at the next key-down", self.frequency_hz / 1e6) + + def set_power(self, stage_name, value): + assert stage_name == "gain", f"EspdrDevice has no power stage {stage_name!r}" + stage = self.power_stages[0] + self._power_db = max(stage.min_value, min(stage.max_value, float(value))) + act = self._active + if act is not None: + act.modulator.set_power(self._power_db) + + # ---- keying + def _make_thermal(self, session, carrier_hz): + path = espdr_config.board_model(self._bridge) + if not path: + return None + params = espdr_thermal.load_params(path) + start_c = params["idle"] + try: + start_c = session.chip_temperature() + self._temperature_c = start_c + except Exception as e: # noqa: BLE001 - the correction then assumes the idle temperature + log.warning("the chip's temperature could not be read (%s); assuming %g C", e, start_c) + return espdr_thermal.Thermal(start_c, UPDATE_RATE, carrier_hz, params) + + def pre_key(self): + with self._lock: + if self._active is not None: + return + self._check_frequency(self.frequency_hz) + self._open_link() + # the correction for the board's crystal is the flowgraph's ppm (set_frequency_correction_ppm), applied by plan_lo + plan = txlink.plan_lo(self.frequency_hz, self._frequency_correction_ppm, DEVIATION_RESERVE_HZ) + if abs(plan["miss_hz"]) > 20: + log.warning("the ESP32's PLL word cannot reach %.6f MHz here; the signal will be at %.6f MHz (%+.0f Hz). Change the frequency " + "by a few kHz or tune the receiver there", self.frequency_hz / 1e6, plan["center_hz"] / 1e6, plan["miss_hz"]) + session = txlink.Session(self._link) + thermal = self._make_thermal(session, plan["center_hz"]) + session.configure(plan["lo_hz"], UPDATE_RATE, drift_hz=SWITCH_ON_DRIFT_HZ, limit_s=SESSION_LIMIT_S) + session.begin(expect_word=txlink.lo_word(plan["lo_hz"])) + modulator = polar.IqModulator(self.sample_rate_hz, UPDATE_RATE, power_db=self._power_db, static_hz=plan["static_hz"]) + streamer = txlink.Streamer(session, on_status=self._on_status) + self._clip_warned = False + self._active = _Session(session, streamer, modulator, thermal, plan, time.monotonic()) + + def _on_status(self, ev): + self._status = ev + + def _consume(self, x): + """Called by the sink with a block of baseband; True if it went to the chip, False if there is no session (or it is over).""" + act = self._active + if act is None or not act.streamer.alive: + return False + rec = act.modulator.process(x) + if act.thermal is not None: + rec = act.thermal.apply(rec) + if act.modulator.clipped and not self._clip_warned: + self._clip_warned = True + log.warning("the signal's frequency excursion exceeds what the chip's records carry; it is clipped") + ok = act.streamer.push(rec, timeout=PUSH_TIMEOUT_S) + act.underruns_while_pushing = (self._status or {}).get("underruns", 0) + return ok + + def post_unkey(self): + with self._lock: + act, self._active = self._active, None + if act is None: + return + try: + summary = act.streamer.finish(timeout=10.0) + # Underruns after the last block are only the wait for this call (the flowgraph stops delivering when the signal is over, e.g. + # after the end of an M17 transmission); the chip repeats its last frequency until the end record arrives. + if summary and (summary["reason"] != 0 or act.underruns_while_pushing or summary["late"]): + log.warning("the ESP32 session ended: %s; underruns while sending %d, late updates %d", + txlink.END_REASONS.get(summary["reason"], summary["reason"]), act.underruns_while_pushing, summary["late"]) + except Exception as e: # noqa: BLE001 - post_unkey must not raise into the flowgraph + log.error("the ESP32 session did not end cleanly: %s", e) + act.streamer.close(timeout=3.0) + + def force_safe_state(self): + try: + with self._lock: + act, self._active = self._active, None + link, self._link = self._link, None + if act is not None: + act.streamer.close(timeout=3.0) + if link is not None: + try: + link.ser.close() + except Exception: # noqa: BLE001 + pass + except Exception as e: # noqa: BLE001 - never raises + log.error("force_safe_state: %s", e) + + def read_hw_state(self): + act = self._active + st = self._status or {} + return { + "keyed": act is not None, + "lo_mhz": act.plan["lo_hz"] / 1e6 if act else None, + "center_mhz": act.plan["center_hz"] / 1e6 if act else None, + "fill": st.get("fill"), + "underruns": st.get("underruns"), + "late": st.get("late"), + "temperature_c": None if act else self._temperature_c, + "firmware_loaded": self._link is not None, + } + + # ---- finding the board + @staticmethod + def probe_with_timeout(connection, timeout_s=5.0): + try: + native, bridge = _parse_connection(connection) + ports = board.native_ports() + board.bridge_ports() + if native and native not in ports and not bridge: + return RuntimeError(f"{native} is not a port of an ESP32-S3 board") + if not ports: + return RuntimeError("no ESP32-S3 board found (its USB ports are missing)") + return None + except Exception as e: # noqa: BLE001 + return e + + @staticmethod + def scan_devices_with_timeout(timeout_s=5.0): + try: + from serial.tools import list_ports + natives = board.native_ports() + found = {} + for p in list_ports.comports(): + if (p.vid, p.pid) in board.BRIDGES: + native = natives[0] if len(natives) == 1 else "" + found[f"{native},{p.device}"] = f"ESP32-S3 board, UART port {p.device}" + (f", serial {p.serial_number}" if p.serial_number else "") + if not found and natives: + found[natives[0]] = f"ESP32-S3 board, USB port {natives[0]}" + return found, None + except Exception as e: # noqa: BLE001 + return None, e diff --git a/pluto_tx/flowgraph.py b/pluto_tx/flowgraph.py index c80df30..4b23954 100644 --- a/pluto_tx/flowgraph.py +++ b/pluto_tx/flowgraph.py @@ -139,6 +139,9 @@ class PlutoTxFlowgraph(gr.top_block): MODE_MESHCORE = 13 MODE_FT8 = 14 MODE_JS8 = 15 + # The names the CLI and TxDevice.supported_modes use for the modes. + MODE_NAMES = {0: "fm", 1: "ssb", 2: "m17", 3: "freedv", 4: "rade", 5: "digitext", 6: "filebroadcast", 7: "psk31", 8: "baseband", + 9: "rtty", 10: "meshtastic", 11: "lsb", 12: "pocsag", 13: "meshcore", 14: "ft8", 15: "js8"} def __init__(self, device_type="pluto", connection=None, frequency=config.DEFAULT_FREQUENCY, power_ceiling=None, audio_device="", @@ -165,6 +168,9 @@ def __init__(self, device_type="pluto", connection=None, frequency=config.DEFAUL super().__init__("PlutoTxFlowgraph") device_cls = devices.DEVICE_REGISTRY[device_type] + # The LoRa encoder branch only for a device that can carry LoRa at all: its resampler filter cannot even be designed for a device + # that runs at a few tens of kHz (the ESP32-S3 at 80 kHz), and it would be dead weight there. + self._lora_tx_branch = _LORA_TX_BRANCH and device_cls.supports_mode("meshtastic") if power_ceiling is None: power_ceiling = device_cls.default_power_ceiling @@ -197,6 +203,8 @@ def __init__(self, device_type="pluto", connection=None, frequency=config.DEFAUL if mode == self.MODE_MESHTASTIC and (not LORA_AVAILABLE or device_cls.is_audio_only()): # LoRa is RF-only (125-500 kHz wide) -- a 48 kHz soundcard can't carry it. mode = self.MODE_FM + if not device_cls.supports_mode(self.MODE_NAMES.get(mode, "")): + mode = self.MODE_FM # a device that carries only some modes (the ESP32-S3: constant-envelope ones) self.mode = mode # the ACTUAL mode (post-fallback) -- GUI reads this # to sync mode_combo's initial selection, otherwise it always shows # "FM" regardless of what mode the flowgraph was actually built with. @@ -784,7 +792,7 @@ def __init__(self, device_type="pluto", connection=None, frequency=config.DEFAUL self._meshcore_duty = lora_airtime.DutyCycleLimiter(None) self._lora_rf_bandwidth_active = False self._lora_phy = None - if _LORA_TX_BRANCH: + if self._lora_tx_branch: lp = (config.MESHCORE_PRESETS[self.meshcore_preset_index] if mode == self.MODE_MESHCORE else config.MESHTASTIC_PRESETS[self.meshtastic_preset_index]) self._lora_phy = self._meshtastic_phy(lp) @@ -865,10 +873,15 @@ def __init__(self, device_type="pluto", connection=None, frequency=config.DEFAUL # transition at working_rate*0.3). g_fb = math.gcd(quad_rate, int(config.FILEBROADCAST_WORKING_RATE_HZ)) fb_interp, fb_decim = quad_rate // g_fb, int(config.FILEBROADCAST_WORKING_RATE_HZ) // g_fb - fb_taps = firdes.low_pass( - fb_interp, quad_rate, config.FILEBROADCAST_WORKING_RATE_HZ / 2 * 0.9, - config.FILEBROADCAST_WORKING_RATE_HZ * 0.3, window.WIN_HAMMING, - ) + if device_cls.supports_mode("filebroadcast"): + fb_taps = firdes.low_pass( + fb_interp, quad_rate, config.FILEBROADCAST_WORKING_RATE_HZ / 2 * 0.9, + config.FILEBROADCAST_WORKING_RATE_HZ * 0.3, window.WIN_HAMMING, + ) + else: + # a device that cannot carry this wideband mode (the ESP32-S3 at 80 kHz): the filter cannot even be designed at its rate. The + # branch stays built (see "always built" below) but is never selected: the constructor falls back to FM for this mode. + fb_taps = [1.0] self.filebroadcast_tx_resampler = filter.rational_resampler_ccf( interpolation=fb_interp, decimation=fb_decim, taps=fb_taps, ) @@ -1001,7 +1014,7 @@ def __init__(self, device_type="pluto", connection=None, frequency=config.DEFAUL self._null_sink_digitext = blocks.null_sink(gr.sizeof_gr_complex) # always built, see Digitext branch above self._null_sink_psk31 = blocks.null_sink(gr.sizeof_gr_complex) # always built, see PSK31 branch above self._null_sink_rtty = blocks.null_sink(gr.sizeof_gr_complex) # always built, see RTTY branch above - if _LORA_TX_BRANCH: + if self._lora_tx_branch: self._null_sink_lora = blocks.null_sink(gr.sizeof_gr_complex) self._null_sink_filebroadcast = blocks.null_sink(gr.sizeof_gr_complex) # always built, see File Broadcast branch above self._null_sink_baseband = blocks.null_sink(gr.sizeof_gr_complex) # always built, see Baseband branch above @@ -1226,7 +1239,7 @@ def _tx_gain_producer_map(self): producers[self.MODE_DIGITEXT] = self.digitext_ssb_resampler # always available, see its branch above producers[self.MODE_PSK31] = self.psk31_ssb_resampler # always available, see its branch above producers[self.MODE_RTTY] = self.rtty_ssb_resampler # always available, see its branch above - if _LORA_TX_BRANCH: + if self._lora_tx_branch: producers[self.MODE_MESHTASTIC] = self.lora_tx_resampler producers[self.MODE_MESHCORE] = self.lora_tx_resampler producers[self.MODE_FILEBROADCAST] = self.filebroadcast_tx_resampler # always available, see its branch above @@ -1251,7 +1264,7 @@ def _null_sink_for(self, producer): return self._null_sink_psk31 if producer is self.rtty_ssb_resampler: return self._null_sink_rtty - if _LORA_TX_BRANCH and producer is self.lora_tx_resampler: + if self._lora_tx_branch and producer is self.lora_tx_resampler: return self._null_sink_lora if producer is self.filebroadcast_tx_resampler: return self._null_sink_filebroadcast diff --git a/pluto_tx/gui.py b/pluto_tx/gui.py index 3533d88..95079ef 100644 --- a/pluto_tx/gui.py +++ b/pluto_tx/gui.py @@ -2598,6 +2598,14 @@ def _update_device_connection_labels(self): "e.g. plughw:CARD=AllInOneCable,DEV=0. Use Scan to auto-detect an " "attached AIOC -- fills this AND the Serial Port field below." ) + elif device_cls.device_type == "espdr": + self.device_label.setText("ESP32-S3 (blank = find the board):") + self.uri_combo.setToolTip( + "Leave blank to find the ESP32-S3 board by its USB ports. Otherwise the board's own USB " + "port, optionally followed by its USB-UART port that loads the firmware: " + "/dev/ttyACM1,/dev/ttyACM0. Use Scan to list attached boards. The firmware is loaded " + "into the board's RAM when needed (nothing is written to its flash)." + ) else: self.device_label.setText("HackRF Serial (blank = auto):") self.uri_combo.setToolTip( @@ -2734,6 +2742,38 @@ def _sync_mode_combo_availability(self): self.mode_combo.setCurrentIndex(self.mode_combo.findData(PlutoTxFlowgraph.MODE_RADE)) else: self.mode_tab_widget.setCurrentIndex(1) + self._apply_device_mode_support(device_cls) + + # Modes whose enabled state _sync_mode_combo_availability computes itself on every call (module availability, LoRa): not restored here. + _MODES_SYNCED_ELSEWHERE = ( + PlutoTxFlowgraph.MODE_SSB, PlutoTxFlowgraph.MODE_LSB, PlutoTxFlowgraph.MODE_M17, PlutoTxFlowgraph.MODE_FREEDV, + PlutoTxFlowgraph.MODE_RADE, PlutoTxFlowgraph.MODE_MESHTASTIC, PlutoTxFlowgraph.MODE_MESHCORE, + ) + + def _apply_device_mode_support(self, device_cls): + """Greys out every mode the selected device cannot carry (TxDevice.supported_modes; the ESP32-S3 sends only the frequency of a + constant-envelope signal) and brings back, when the device changes again, what this method had greyed out. Forces a switch to FM + when the current mode just became impossible.""" + was_enabled = self.__dict__.setdefault("_device_mode_disabled", {}) # (combo name, index) -> enabled state before this method + for name, combo in (("mode", self.mode_combo), ("digimode", self.digimode_combo)): + model = combo.model() + for idx in range(combo.count()): + mode = combo.itemData(idx) + item = model.item(idx) + key = (name, idx) + if not device_cls.supports_mode(PlutoTxFlowgraph.MODE_NAMES.get(mode, "")): + was_enabled.setdefault(key, item.isEnabled()) + item.setEnabled(False) + item.setToolTip(f"{device_cls.display_name} cannot send this: it carries only " + f"{', '.join(sorted(device_cls.supported_modes)).upper()} (the frequency of a constant-envelope signal)") + elif key in was_enabled: + before = was_enabled.pop(key) + item.setToolTip("") + if mode not in self._MODES_SYNCED_ELSEWHERE: + item.setEnabled(before) + if not device_cls.supports_mode(PlutoTxFlowgraph.MODE_NAMES.get(self._current_mode, "")): + self.mode_tab_widget.setCurrentIndex(0) + self.mode_combo.setCurrentIndex(self.mode_combo.findData(PlutoTxFlowgraph.MODE_FM)) def _set_indicator_idle(self): self.tx_indicator.setText("READY" if self._armed else "E-STOP - LOCKED") diff --git a/tests/test_espdr_device.py b/tests/test_espdr_device.py new file mode 100644 index 0000000..21130f7 --- /dev/null +++ b/tests/test_espdr_device.py @@ -0,0 +1,358 @@ +"""The ESP32-S3 TX device (pluto_tx/devices/espdr.py), without hardware: the chip is espdr.sim.SimTx, a simulated ESP32-S3 that plays the +records it is sent in virtual time (real time here: speed 1).""" +import logging +import math +import os +import tempfile +import time +import unittest +import wave +from unittest import mock + +os.environ.setdefault("QT_QPA_PLATFORM", "offscreen") + +import numpy as np + +from pluto_tx import config, devices +from pluto_tx import flowgraph as txf +from pluto_tx.flowgraph import PlutoTxFlowgraph as FG + +Q4_HZ = 30e6 / 65536 / 16 # one unit of the frequency field of a record + +espdr_available = devices.ESPDR_AVAILABLE +if espdr_available: + from espdr import config as espdr_config, nb, sim, txlink + from pluto_tx.devices import espdr as dev + + +def tone_wav(path, seconds=3.0, rate=8000): + t = np.arange(int(seconds * rate)) / rate + x = 0.4 * np.sin(2 * np.pi * (500 + 300 * np.sin(2 * np.pi * 1.1 * t)) * t) + 0.2 * np.sin(2 * np.pi * 1700 * t) + with wave.open(path, "wb") as w: + w.setnchannels(1) + w.setsampwidth(2) + w.setframerate(rate) + w.writeframes((x * 20000).astype("> 24) & 1) # the end record + ops = [op for op, _ in self.esp.ops] + self.assertIn(txlink.TX_OP_BEGIN, ops) + self.assertLess(ops.index(txlink.TX_OP_LO), ops.index(txlink.TX_OP_BEGIN)) + f = record_freq_hz(rec[:-1]) + body = f[10_000:-5_000] + self.assertLess(abs(np.median(body) - np.median(f)), 4000) + self.assertGreater(np.abs(body - np.median(body)).max(), 1500) # FM deviation of the default voice setting + self.assertLess(np.abs(body - np.median(body)).max(), 4000) + codes = {int(r >> 16) & 0xFF for r in rec} + self.assertTrue(codes <= set(range(64, 128))) + + def middle_code(self, rec): + codes = [int(r >> 16) & 0xFF for r in rec[:-1]] + return codes[len(codes) // 2] + + def test_the_gain_follows_the_power_setting_up_to_the_ceiling(self): + from espdr import txmodes + fg = self.flowgraph(FG.MODE_FM, power_ceiling=0.0) + fg.set_target_power(-6.0) + self.assertEqual(self.middle_code(self.transmit(fg, 1.5)), txmodes.peak_code(-6.0)) + + def test_the_default_power_is_the_conservative_ceiling(self): + from espdr import txmodes + self.assertEqual(self.middle_code(self.transmit(self.flowgraph(FG.MODE_FM), 1.5)), + txmodes.peak_code(dev.EspdrDevice.default_power_ceiling)) + + def test_the_ppm_correction_moves_the_signal(self): + fg = self.flowgraph(FG.MODE_FM) + fg.device.set_frequency_correction_ppm(5.0) + self.transmit(fg, 1.0) + lo_ops = [a for op, a in self.esp.ops if op == txlink.TX_OP_LO] + plain = txlink.plan_lo(2.345e9, 0.0, 4000.0)["lo_hz"] + corrected = txlink.plan_lo(2.345e9, 5.0, 4000.0)["lo_hz"] + self.assertEqual(lo_ops[-1], corrected // 100) + self.assertNotEqual(plain, corrected) + + def test_a_second_pre_key_does_nothing_and_the_frequency_waits_for_the_next_key(self): + fg = self.flowgraph(FG.MODE_FM) + fg.start() + fg.key_ptt() + d = fg.device + before = d._active + d.pre_key() + self.assertIs(d._active, before) + with self.assertLogs("pluto_tx.devices.espdr", level="WARNING"): + d.set_frequency(2.4e9) + self.assertEqual(d.frequency_hz, 2.4e9) + self.assertEqual(before.plan["center_hz"] // 1_000_000, 2345) # still the old one on the air + fg.unkey_ptt() + fg.stop() + fg.wait() + + def test_an_unsupported_mode_falls_back_to_fm(self): + fg = FG(device_type="espdr", connection="", frequency=2.345e9, mode=FG.MODE_SSB, source=FG.SRC_FILE, wav_path=self.wav) + self.addCleanup(fg.shutdown_safe) + self.assertEqual(fg.mode, FG.MODE_FM) + + def test_the_cli_refuses_modes_the_device_cannot_carry(self): + from pluto_cli import tx as cli_tx + messages = [] + + class Emitter: + def error(self, message, **kw): + messages.append(message) + + args = mock.Mock(device="espdr", uri="") + rc = cli_tx._run(args, FG.MODE_SSB, Emitter()) + self.assertEqual(rc, 1) + self.assertIn("cannot send ssb", messages[0]) + self.assertIn("fm, m17", messages[0]) + + # ---- M17 + @unittest.skipUnless(txf.M17_AVAILABLE, "gr-m17 is not available") + def test_m17_through_the_flowgraph_decodes_with_the_call_sign(self): + from gnuradio import analog, blocks, digital, gr + from gnuradio import m17 as gr_m17 + from gnuradio.filter import firdes, fir_filter_fff + from espdr import dsp + from pluto_advanced_rx.m17_deframer import M17FieldsDeframer + + fg = self.flowgraph(FG.MODE_M17) + self.assertEqual(fg.mode, FG.MODE_M17) + rec = self.transmit(fg, 4.5) + f = record_freq_hz(rec[:-1]) + f = f - np.median(f) + iq = np.exp(2j * np.pi * np.cumsum(f) / 40_000) + iq48 = dsp.Resampler(40_000, 48_000).process(iq).astype(np.complex64) + found = [] + tb = gr.top_block() + src = blocks.vector_source_c(iq48.tolist(), False) + demod = analog.quadrature_demod_cf(config.M17_BASEBAND_RATE / (2 * math.pi * config.M17_DEVIATION_HZ)) + n_avg = int(0.1 * config.M17_BASEBAND_RATE) + avg, sub = blocks.moving_average_ff(n_avg, 1.0 / n_avg, 4000), blocks.sub_ff() + mf = fir_filter_fff(1, firdes.root_raised_cosine(1.0, config.M17_BASEBAND_RATE, config.M17_SYMBOL_RATE, config.M17_RRC_ALPHA, + config.M17_RRC_NTAPS)) + sync = digital.symbol_sync_ff(digital.TED_GARDNER, config.M17_RRC_SPS, 2 * math.pi * 0.0015, 1.0, 1.0, 0.05, 1, + digital.constellation_bpsk().base(), digital.IR_MMSE_8TAP, 128, []) + decoder = gr_m17.m17_decoder(False, False, 2.0, 30.0, True, False, 0, "", "") + deframer = M17FieldsDeframer(lambda fields: found.append(fields)) + voice = blocks.null_sink(gr.sizeof_short) + tb.connect(src, demod, sub) + tb.connect(demod, avg) + tb.connect(avg, (sub, 1)) + tb.connect(sub, mf, sync, decoder) + tb.msg_connect(decoder, "fields", deframer, "fields") + tb.connect(decoder, gr_m17.codec2_decoder(), voice) + tb.run() + self.assertGreaterEqual(len(found), 5) + self.assertEqual({fields["src"] for fields in found}, {"DA2JH"}) + + +@unittest.skipUnless(espdr_available, "the espdr package (./espdr) is not importable here") +class EspdrGuiTests(unittest.TestCase): + @classmethod + def setUpClass(cls): + from PyQt5 import QtCore, QtWidgets + from tests import fakes + QtCore.QStandardPaths.setTestModeEnabled(True) # keep QSettings out of ~/.config + fakes.register_tx() + cls.app = QtWidgets.QApplication.instance() or QtWidgets.QApplication([]) + + def window(self): + from pluto_tx import gui + w = gui.MainWindow("x") + w.device_type_combo.addItem("fake", "fake") + self.addCleanup(lambda: w.tb is not None and w.tb.shutdown_safe()) + return w + + def enabled(self, w, mode): + for combo in (w.mode_combo, w.digimode_combo): + i = combo.findData(mode) + if i >= 0: + return combo.model().item(i).isEnabled() + raise AssertionError(f"mode {mode} is in no combo") + + def select(self, w, device): + w.device_type_combo.setCurrentIndex(w.device_type_combo.findData(device)) + w._sync_mode_combo_availability() + + def test_the_gui_greys_out_what_the_esp32_cannot_send_and_brings_it_back(self): + w = self.window() + before = {m: self.enabled(w, m) for m in FG.MODE_NAMES if m not in (FG.MODE_MESHTASTIC, FG.MODE_MESHCORE) or True} + self.select(w, "espdr") + self.assertTrue(self.enabled(w, FG.MODE_FM)) + for m in (FG.MODE_SSB, FG.MODE_LSB, FG.MODE_PSK31, FG.MODE_RTTY, FG.MODE_FT8, FG.MODE_DIGITEXT, FG.MODE_BASEBAND, FG.MODE_FILEBROADCAST): + self.assertFalse(self.enabled(w, m), FG.MODE_NAMES[m]) + self.assertEqual(self.enabled(w, FG.MODE_M17), txf.M17_AVAILABLE) + self.select(w, "fake") + after = {m: self.enabled(w, m) for m in before} + self.assertEqual(before, after) + + def test_the_connection_label_is_the_ones_of_the_esp32(self): + w = self.window() + self.select(w, "espdr") + w._update_device_connection_labels() + self.assertIn("ESP32", w.device_label.text()) + + def test_the_current_mode_goes_to_fm_when_the_device_cannot_carry_it(self): + w = self.window() + w.mode_combo.setCurrentIndex(w.mode_combo.findData(FG.MODE_SSB)) + w._current_mode = FG.MODE_SSB + self.select(w, "espdr") + self.assertEqual(w.mode_combo.currentData(), FG.MODE_FM) + + +@unittest.skipUnless(espdr_available, "the espdr package (./espdr) is not importable here") +class EspdrCopyTests(unittest.TestCase): + """./espdr is a copy made by tools/sync-espdr.sh; these keep it honest.""" + + root = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "espdr") + + def test_the_images_match_their_sums(self): + import hashlib + sums = dict(line.split()[::-1] for line in open(os.path.join(self.root, "images", "SHA256SUMS.txt")).read().splitlines() if line.strip()) + self.assertEqual(set(sums), {"rx.bin", "tx.bin", "bootloader.bin", "partition-table.bin"}) + for name, digest in sums.items(): + with open(os.path.join(self.root, "images", name), "rb") as fh: + self.assertEqual(hashlib.sha256(fh.read()).hexdigest(), digest, name) + + def test_upstream_records_where_the_copy_came_from(self): + text = open(os.path.join(self.root, "UPSTREAM")).read() + self.assertIn("repository: https://github.com/jochenhammes/esp32-sdr-trx", text) + self.assertRegex(text, r"commit: [0-9a-f]{40}") + self.assertIn("0BSD", text) + with open(os.path.join(self.root, "LICENSE")) as fh: + self.assertIn("Zero-Clause BSD", fh.read()) # the licence text itself + + def test_the_copy_is_the_package_that_is_imported(self): + import espdr + self.assertEqual(os.path.realpath(os.path.dirname(espdr.__file__)), os.path.realpath(self.root)) + self.assertTrue(os.path.exists(txlink.__file__)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/sync-espdr.sh b/tools/sync-espdr.sh new file mode 100755 index 0000000..185c435 --- /dev/null +++ b/tools/sync-espdr.sh @@ -0,0 +1,65 @@ +#!/usr/bin/env bash +# Copies the espdr package (the host side of the ESP32-S3 transmitter, https://github.com/jochenhammes/esp32-sdr-trx, Zero-Clause BSD +# licence) from a checkout of that repository into ./espdr, together with the firmware images the package carries, its licence and its +# NOTICE, and records which commit it came from in espdr/UPSTREAM. pluto-tx ships this copy so that the ESP32-S3 device works on an +# installation that has nothing else of the ESP32 project. +# +# tools/sync-espdr.sh [--from DIR] [--ref REF] +# +# --from the esp32-sdr-trx checkout (default: ../esp32/esp32-sdr-trx next to this repository's parent, or $ESPDR_SRC) +# --ref a branch, tag or commit of that checkout (default: its current HEAD) +# +# The firmware images (rx.bin, tx.bin, bootloader.bin, partition-table.bin) are build products and not in git: they are copied from +# src/espdr/images/ of the checkout (staged by its scripts/stage-images.sh after `make -C firmware images`, or taken from a release) and +# their SHA-256 sums go into espdr/UPSTREAM. The script stops if they are missing; the device in pluto-tx needs tx.bin. +# Never edit espdr/ here: change it in esp32-sdr-trx and run this script again. tests/test_espdr_sync.py checks that the copy and +# UPSTREAM agree with each other. +set -euo pipefail + +here="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +src="${ESPDR_SRC:-$here/../esp32/esp32-sdr-trx}" +ref="" +while [ $# -gt 0 ]; do + case "$1" in + --from) src="$2"; shift 2 ;; + --ref) ref="$2"; shift 2 ;; + -h|--help) sed -n '2,13p' "$0" | sed 's/^# \{0,1\}//'; exit 0 ;; + *) echo "unknown argument: $1 (see --help)" >&2; exit 2 ;; + esac +done + +[ -d "$src/.git" ] || { echo "$src is not a git checkout of esp32-sdr-trx (use --from DIR or set ESPDR_SRC)" >&2; exit 1; } +[ -f "$src/src/espdr/txlink.py" ] || { echo "$src does not look like esp32-sdr-trx (src/espdr/txlink.py is missing)" >&2; exit 1; } +ref="${ref:-$(git -C "$src" rev-parse HEAD)}" +commit="$(git -C "$src" rev-parse --verify "$ref^{commit}")" +if [ -n "$(git -C "$src" status --porcelain -- src/espdr LICENSE NOTICE)" ] && [ "$ref" = "$(git -C "$src" rev-parse HEAD)" ]; then + echo "note: $src has uncommitted changes in src/espdr; only the committed state $commit is copied" >&2 +fi + +tmp="$(mktemp -d)" +trap 'rm -rf "$tmp"' EXIT +git -C "$src" archive "$commit" src/espdr LICENSE NOTICE | tar -x -C "$tmp" + +rm -rf "$here/espdr" +mkdir -p "$here/espdr" +cp -a "$tmp/src/espdr/." "$here/espdr/" +cp "$tmp/LICENSE" "$here/espdr/LICENSE" +cp "$tmp/NOTICE" "$here/espdr/NOTICE" +find "$here/espdr" -name __pycache__ -type d -prune -exec rm -rf {} + +images="$src/src/espdr/images" +for f in rx.bin tx.bin bootloader.bin partition-table.bin; do + [ -f "$images/$f" ] || { echo "$images/$f is missing: stage the images first (scripts/stage-images.sh in esp32-sdr-trx)" >&2; rm -rf "$here/espdr"; exit 1; } +done +mkdir -p "$here/espdr/images" +cp "$images"/rx.bin "$images"/tx.bin "$images"/bootloader.bin "$images"/partition-table.bin "$here/espdr/images/" +( cd "$here/espdr/images" && sha256sum rx.bin tx.bin bootloader.bin partition-table.bin > SHA256SUMS.txt ) +{ + echo "repository: https://github.com/jochenhammes/esp32-sdr-trx" + echo "commit: $commit" + echo "subject: $(git -C "$src" log -1 --format=%s "$commit")" + echo "date: $(git -C "$src" log -1 --format=%cI "$commit")" + echo "licence: 0BSD (espdr/LICENSE); the rest of pluto-tx is GPL-3.0" + echo "images (build products of the firmware of that repository, copied as they were; sha256 in espdr/images/SHA256SUMS.txt):" + sed 's/^/ /' "$here/espdr/images/SHA256SUMS.txt" +} > "$here/espdr/UPSTREAM" +echo "espdr copied from $src at $commit"