You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

178 lines
8.4 KiB

#!/usr/bin/env python3
"""Write chirpmodem frames to a SigMF recording for an SDR to transmit.
The recording holds --repeat frames separated by --gap seconds of silence, at
the SDR's sample rate, shifted --if-offset Hz above the SDR's center so the
transmitter's LO leakage (a spike at 0 Hz) sits outside the signal. Tune the
SDR's LO to (signal frequency - if-offset).
./tx_file.py hello --src KD2HSG --msg "test de KD2HSG" --sf 9 --repeat 5 --cw-id
./tx_file.py hello --src KD2HSG --msg "test" --fs 1e6 --freq 223.58e6 --bw 62.5e3
Defaults put a 62.5 kHz signal at 223.580 MHz, inside the ARRL band plan's
digital/packet segment (223.520-223.640 MHz). --cw-id appends the callsign
in Morse (20 WPM keyed carrier at the signal's center), one of the station
identification methods in 47 CFR 97.119(b); the callsign inside the frames
is not one of those methods.
Writes hello.sigmf-meta + hello.sigmf-data. cf32_le (default) is what
GNU Radio and pyadi-iio want; ci16_le is scaled for the Pluto's 12-bit DAC
the way pyadi-iio expects (full scale 2**14 of 2**15).
"""
import argparse, sys
import numpy as np
from phy import PhyParams
from frame import build_frame, LICENSED, UNLICENSED, PolicyError, resolve_mode
import iq_io
def ramp_edges(x, n):
"""Raised-cosine fade in/out over n samples, to limit key clicks."""
if n <= 0 or len(x) < 2 * n:
return x
w = 0.5 - 0.5 * np.cos(np.pi * (np.arange(n) + 0.5) / n)
x = x.copy()
x[:n] *= w
x[-n:] *= w[::-1]
return x
MORSE = {
"A": ".-", "B": "-...", "C": "-.-.", "D": "-..", "E": ".", "F": "..-.", "G": "--.",
"H": "....", "I": "..", "J": ".---", "K": "-.-", "L": ".-..", "M": "--", "N": "-.",
"O": "---", "P": ".--.", "Q": "--.-", "R": ".-.", "S": "...", "T": "-", "U": "..-",
"V": "...-", "W": ".--", "X": "-..-", "Y": "-.--", "Z": "--..", "0": "-----",
"1": ".----", "2": "..---", "3": "...--", "4": "....-", "5": ".....", "6": "-....",
"7": "--...", "8": "---..", "9": "----.", "/": "-..-.",
}
def cw_keying(text, wpm, fs, rise=0.005):
"""Baseband on/off keying envelope for ``text`` (PARIS timing), shaped
with raised-cosine edges of ``rise`` seconds to avoid key clicks."""
dot = int(round(1.2 / wpm * fs))
on = []
for w, word in enumerate(text.upper().split()):
if w:
on.append((0, 7 * dot))
for c, ch in enumerate(word):
if c:
on.append((0, 3 * dot))
for e, el in enumerate(MORSE[ch]):
if e:
on.append((0, dot))
on.append((1, dot if el == "." else 3 * dot))
env = np.concatenate([np.full(n, float(v)) for v, n in on])
k = max(1, int(rise * fs))
w = 0.5 - 0.5 * np.cos(np.pi * np.arange(k) / k)
return np.convolve(env, w / w.sum(), mode="same")
def main():
ap = argparse.ArgumentParser(description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("out", help="output base name (writes OUT.sigmf-meta/.sigmf-data)")
ap.add_argument("--msg", default="test", help="message body (UTF-8)")
ap.add_argument("--msg-file", help="read the body from a file instead")
ap.add_argument("--src", help="source callsign (required for the licensed profile)")
ap.add_argument("--dst", help="destination callsign")
ap.add_argument("--unlicensed", action="store_true", help="unlicensed (ISM) profile")
ap.add_argument("--sf", type=int, default=9)
ap.add_argument("--bw", type=float, default=62.5e3, help="chip rate / bandwidth, Hz")
ap.add_argument("--fs", type=float, default=1e6, help="SDR sample rate, Hz")
ap.add_argument("--freq", type=float, default=223.58e6, help="signal center frequency, Hz")
ap.add_argument("--if-offset", type=float, default=100e3,
help="signal offset above the SDR LO, Hz (LO = freq - if-offset)")
ap.add_argument("--repeat", type=int, default=1)
ap.add_argument("--gap", type=float, default=0.5, help="silence between frames, s")
ap.add_argument("--lead", type=float, default=0.2, help="silence before the first frame, s")
ap.add_argument("--no-seq", action="store_true",
help="don't append ' [n/N]' to the message when repeating")
ap.add_argument("--amp", type=float, default=0.7, help="peak amplitude, 0..1 of full scale")
ap.add_argument("--cw-id", action="store_true",
help="append 'DE <src>' in Morse at 20 WPM after the frames")
ap.add_argument("--wpm", type=float, default=20.0, help="CW ID speed (max 20 if automatic)")
ap.add_argument("--format", default="cf32_le", choices=["cf32_le", "ci16_le"])
ap.add_argument("--coherent", action="store_true",
help="coherent payload (index + QPSK); default only at SF 7-9 above 62.5 kHz")
ap.add_argument("--noncoherent", action="store_true",
help="index-only payload; default at SF >= 10 and at <= 62.5 kHz")
a = ap.parse_args()
p = PhyParams(sf=a.sf, bw=a.bw, osr=2, fc=a.freq)
try:
coherent = resolve_mode(p, a.coherent, a.noncoherent)
except ValueError as e:
sys.exit(str(e))
if a.fs < 2 * (a.bw / 2 + abs(a.if_offset)) * 1.1:
sys.exit(f"--fs {a.fs:g} too low for a {a.bw:g} Hz signal at {a.if_offset:+g} Hz offset")
body = open(a.msg_file, "rb").read() if a.msg_file else a.msg.encode()
profile = UNLICENSED if a.unlicensed else LICENSED
lead = np.zeros(int(a.lead * a.fs), complex)
gap = np.zeros(int(a.gap * a.fs), complex)
full = 2 ** 14 / 2 ** 15 if a.format == "ci16_le" else 1.0
out_meta, out_data = iq_io.sigmf_paths(a.out)
# build every frame first, so a policy refusal leaves no partial files
frames = []
for i in range(a.repeat):
msg = body if (a.repeat == 1 or a.no_seq) else body + f" [{i + 1}/{a.repeat}]".encode()
try:
iq, _ = build_frame(p, msg, profile=profile, src=a.src, dst=a.dst,
coherent=coherent)
except PolicyError as e:
sys.exit(f"refusing to transmit: {e}")
frames.append((msg, iq))
open(out_data, "wb").close()
n_written, annotations = 0, []
def emit(x):
nonlocal n_written
iq_io.write_raw(out_data, x * a.amp * full, a.format, append=True)
n_written += len(x)
emit(lead)
for i, (msg, iq) in enumerate(frames):
y = iq_io.upsample(iq, p.fs, a.fs, a.if_offset)
y = ramp_edges(y, int(round(a.fs / a.bw)) * 8)
annotations.append({
"core:sample_start": n_written, "core:sample_count": len(y),
"core:freq_lower_edge": a.freq - a.bw / 2, "core:freq_upper_edge": a.freq + a.bw / 2,
"core:label": f"chirpmodem SF{a.sf} {a.bw / 1e3:g} kHz frame {i + 1}",
"core:comment": msg.decode(errors="replace")})
emit(y)
if i + 1 < a.repeat:
emit(gap)
if a.cw_id:
if not a.src:
sys.exit("--cw-id needs --src")
emit(np.zeros(int(0.3 * a.fs), complex))
env = cw_keying(f"DE {a.src}", min(a.wpm, 20.0), a.fs)
tone = env * np.exp(2j * np.pi * a.if_offset * np.arange(len(env)) / a.fs)
annotations.append({"core:sample_start": n_written, "core:sample_count": len(tone),
"core:freq_lower_edge": a.freq - 100.0,
"core:freq_upper_edge": a.freq + 100.0,
"core:label": f"CW ID DE {a.src.upper()}"})
emit(tone)
emit(np.zeros(int(0.1 * a.fs), complex))
iq_io.write_sigmf_meta(
a.out, a.format, a.fs, a.freq - a.if_offset,
description=f"chirpmodem transmit file: {a.repeat} frame(s), SF{a.sf}, "
f"{a.bw / 1e3:g} kHz, signal at {a.freq / 1e6:.6f} MHz",
annotations=annotations, author=a.src,
extra=dict(sf=a.sf, bw=a.bw, signal_freq=a.freq, if_offset=a.if_offset,
profile="unlicensed" if a.unlicensed else "licensed"))
dur = n_written / a.fs
frame_s = len(iq) / p.fs
print(f"wrote {out_meta} + {out_data}")
print(f" {a.repeat} {'coherent' if coherent else 'non-coherent'} frame(s) of "
f"{len(frames[-1][0])} B body, {frame_s:.3f} s each, "
f"{dur:.2f} s total, {n_written} samples at {a.fs / 1e6:g} MS/s ({a.format})")
print(f" signal center {a.freq / 1e6:.6f} MHz -> tune the SDR LO to "
f"{(a.freq - a.if_offset) / 1e6:.6f} MHz")
if __name__ == "__main__":
main()