Browse Source
- to_sdriq.py: SigMF or raw I/Q to SDRangel .sdriq, for the FileInput device - mcp_call.py: call one tool on an SDRangel MCP server - gen_swg_models.py: SDRangel SWG model classes from a Swagger include YAML - swg_clone_channel.py: register a channel type in SDRangel's aggregate SWG classes by cloning an existing type's blocks - live_tx.sigmf-meta: the transmit recording of the 2026-11-08 live test Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>master
5 changed files with 433 additions and 0 deletions
@ -0,0 +1,62 @@ |
|||||||
|
{ |
||||||
|
"global": { |
||||||
|
"core:datatype": "cf32_le", |
||||||
|
"core:version": "1.2.0", |
||||||
|
"core:sample_rate": 600000.0, |
||||||
|
"core:recorder": "chirpmodem", |
||||||
|
"core:extensions": [ |
||||||
|
{ |
||||||
|
"name": "chirpmodem", |
||||||
|
"version": "0.1.0", |
||||||
|
"optional": true |
||||||
|
} |
||||||
|
], |
||||||
|
"core:description": "chirpmodem transmit file: 3 frame(s), SF9, 62.5 kHz, signal at 223.580000 MHz", |
||||||
|
"core:author": "KD2HSG", |
||||||
|
"chirpmodem:sf": 9, |
||||||
|
"chirpmodem:bw": 62500.0, |
||||||
|
"chirpmodem:signal_freq": 223580000.0, |
||||||
|
"chirpmodem:if_offset": 100000.0, |
||||||
|
"chirpmodem:profile": "licensed" |
||||||
|
}, |
||||||
|
"captures": [ |
||||||
|
{ |
||||||
|
"core:sample_start": 0, |
||||||
|
"core:frequency": 223480000.0, |
||||||
|
"core:datetime": "2026-11-09T00:33:06.365Z" |
||||||
|
} |
||||||
|
], |
||||||
|
"annotations": [ |
||||||
|
{ |
||||||
|
"core:sample_start": 120000, |
||||||
|
"core:sample_count": 443596, |
||||||
|
"core:freq_lower_edge": 223548750.0, |
||||||
|
"core:freq_upper_edge": 223611250.0, |
||||||
|
"core:label": "chirpmodem SF9 62.5 kHz frame 1", |
||||||
|
"core:comment": "live de KD2HSG [1/3]" |
||||||
|
}, |
||||||
|
{ |
||||||
|
"core:sample_start": 863596, |
||||||
|
"core:sample_count": 443596, |
||||||
|
"core:freq_lower_edge": 223548750.0, |
||||||
|
"core:freq_upper_edge": 223611250.0, |
||||||
|
"core:label": "chirpmodem SF9 62.5 kHz frame 2", |
||||||
|
"core:comment": "live de KD2HSG [2/3]" |
||||||
|
}, |
||||||
|
{ |
||||||
|
"core:sample_start": 1607192, |
||||||
|
"core:sample_count": 443596, |
||||||
|
"core:freq_lower_edge": 223548750.0, |
||||||
|
"core:freq_upper_edge": 223611250.0, |
||||||
|
"core:label": "chirpmodem SF9 62.5 kHz frame 3", |
||||||
|
"core:comment": "live de KD2HSG [3/3]" |
||||||
|
}, |
||||||
|
{ |
||||||
|
"core:sample_start": 2230788, |
||||||
|
"core:sample_count": 3060000, |
||||||
|
"core:freq_lower_edge": 223579900.0, |
||||||
|
"core:freq_upper_edge": 223580100.0, |
||||||
|
"core:label": "CW ID DE KD2HSG" |
||||||
|
} |
||||||
|
] |
||||||
|
} |
||||||
@ -0,0 +1,125 @@ |
|||||||
|
#!/usr/bin/env python3 |
||||||
|
"""Generate SDRangel Qt SWG model classes from a Swagger include YAML. |
||||||
|
|
||||||
|
SDRangel's own generator is a fork of swagger-codegen; regenerating the whole |
||||||
|
client touches hundreds of files. This writes only the classes for one YAML, |
||||||
|
in the compact style of the hand-maintained SWGSELCALDemod* models. |
||||||
|
|
||||||
|
./gen_swg_models.py ~/sdrangel/swagger/sdrangel/api/swagger/include/ChirpModemDemod.yaml \ |
||||||
|
~/sdrangel/swagger/sdrangel/code/qt5/client |
||||||
|
""" |
||||||
|
|
||||||
|
import sys |
||||||
|
from pathlib import Path |
||||||
|
|
||||||
|
import yaml |
||||||
|
|
||||||
|
PRIMITIVES = { |
||||||
|
("integer", "int32"): "qint32", |
||||||
|
("integer", "int64"): "qint64", |
||||||
|
("integer", None): "qint32", |
||||||
|
("number", "float"): "float", |
||||||
|
("number", "double"): "double", |
||||||
|
("number", None): "float", |
||||||
|
} |
||||||
|
|
||||||
|
|
||||||
|
def accessor(name): |
||||||
|
"""Method suffix: the codegen capitalises the key and writes API as Api.""" |
||||||
|
return (name[0].upper() + name[1:]).replace("API", "Api") |
||||||
|
|
||||||
|
|
||||||
|
def field_type(prop): |
||||||
|
if "$ref" in prop: |
||||||
|
return "ref", "SWG" + prop["$ref"].rsplit("/", 1)[-1] |
||||||
|
if prop["type"] == "string": |
||||||
|
return "string", "QString" |
||||||
|
return "prim", PRIMITIVES[(prop["type"], prop.get("format"))] |
||||||
|
|
||||||
|
|
||||||
|
def generate(cls, definition, yaml_name): |
||||||
|
name = "SWG" + cls |
||||||
|
fields = [(key, *field_type(prop)) for key, prop in definition["properties"].items()] |
||||||
|
refs = sorted({t for _, kind, t in fields if kind == "ref"}) |
||||||
|
|
||||||
|
h = ["// SPDX-License-Identifier: GPL-3.0-or-later", |
||||||
|
f"// Qt model for {yaml_name}, following the Swagger client model interface.", |
||||||
|
f"// Generated by gen_swg_models.py: edit the YAML, not this file.", |
||||||
|
f"#ifndef {name}_H_", f"#define {name}_H_", "", |
||||||
|
"#include <QJsonObject>", "#include <QString>", "", |
||||||
|
'#include "SWGObject.h"', '#include "export.h"'] |
||||||
|
h += [f'#include "{r}.h"' for r in refs] |
||||||
|
h += ["", "namespace SWGSDRangel {", "", |
||||||
|
f"class SWG_API {name} : public SWGObject {{", "public:", |
||||||
|
f" {name}();", f" explicit {name}(QString* json);", f" ~{name}() override;", |
||||||
|
" void init();", " void cleanup();", " QString asJson() override;", |
||||||
|
" QJsonObject* asJsonObject() override;", " void fromJsonObject(QJsonObject& json) override;", |
||||||
|
f" {name}* fromJson(QString& json) override;", " bool isSet() override;", ""] |
||||||
|
for key, kind, t in fields: |
||||||
|
ctype = t if kind == "prim" else t + "*" |
||||||
|
h += [f" {ctype} get{accessor(key)}();", f" void set{accessor(key)}({ctype} value);"] |
||||||
|
h += ["", "private:"] |
||||||
|
for key, kind, t in fields: |
||||||
|
if kind == "prim": |
||||||
|
h.append(f" {t} m_{key} = 0;") |
||||||
|
else: |
||||||
|
h.append(f" {t}* m_{key} = nullptr;") |
||||||
|
h.append(f" bool m_{key}IsSet = false;") |
||||||
|
h += ["};", "", "}", "", "#endif", ""] |
||||||
|
|
||||||
|
c = ["// SPDX-License-Identifier: GPL-3.0-or-later", |
||||||
|
f"// Generated by gen_swg_models.py from {yaml_name}: edit the YAML, not this file.", |
||||||
|
f'#include "{name}.h"', '#include "SWGHelpers.h"', "", "#include <QJsonDocument>", "", |
||||||
|
"namespace SWGSDRangel {", "", |
||||||
|
f"{name}::{name}() = default;", |
||||||
|
f"{name}::{name}(QString* json) {{ init(); if (json) {{ fromJson(*json); }} }}", |
||||||
|
f"{name}::~{name}() {{ cleanup(); }}", "", |
||||||
|
f"void {name}::cleanup()", "{"] |
||||||
|
c += [f" delete m_{k}; m_{k} = nullptr;" for k, kind, _ in fields if kind != "prim"] |
||||||
|
c += ["}", "", f"void {name}::init()", "{", " cleanup();"] |
||||||
|
for key, kind, t in fields: |
||||||
|
init = "0" if kind == "prim" else f"new {t}()" |
||||||
|
c.append(f" m_{key} = {init}; m_{key}IsSet = false;") |
||||||
|
c += ["}", "", f"{name}* {name}::fromJson(QString& json)", "{", |
||||||
|
" auto object = QJsonDocument::fromJson(json.toUtf8()).object(); fromJsonObject(object); return this;", |
||||||
|
"}", "", f"void {name}::fromJsonObject(QJsonObject& json)", "{"] |
||||||
|
for key, kind, t in fields: |
||||||
|
inner = "" if kind == "prim" else t |
||||||
|
c.append(f' if (json.contains("{key}")) {{ ::SWGSDRangel::setValue(&m_{key},json["{key}"],"{t}","{inner}"); m_{key}IsSet = true; }}') |
||||||
|
c += ["}", "", f"QString {name}::asJson()", "{", |
||||||
|
" auto* object = asJsonObject(); QString result = QJsonDocument(*object).toJson(); delete object; return result;", |
||||||
|
"}", "", f"QJsonObject* {name}::asJsonObject()", "{", " auto* object = new QJsonObject();"] |
||||||
|
for key, kind, t in fields: |
||||||
|
if kind == "prim": |
||||||
|
c.append(f' if (m_{key}IsSet) {{ object->insert("{key}",QJsonValue(m_{key})); }}') |
||||||
|
elif kind == "string": |
||||||
|
c.append(f' if (m_{key} && (m_{key}IsSet || !m_{key}->isEmpty())) {{ toJsonValue(QString("{key}"),m_{key},object,QString("QString")); }}') |
||||||
|
else: |
||||||
|
c.append(f' if (m_{key} && (m_{key}IsSet || m_{key}->isSet())) {{ toJsonValue(QString("{key}"),m_{key},object,QString("{t}")); }}') |
||||||
|
c += [" return object;", "}", "", f"bool {name}::isSet()", "{", |
||||||
|
" return " + " || ".join(f"m_{k}IsSet" for k, _, _ in fields) + ";", "}", ""] |
||||||
|
for key, kind, t in fields: |
||||||
|
a = accessor(key) |
||||||
|
if kind == "prim": |
||||||
|
c += [f"{t} {name}::get{a}() {{ return m_{key}; }}", |
||||||
|
f"void {name}::set{a}({t} value) {{ m_{key} = value; m_{key}IsSet = true; }}"] |
||||||
|
else: |
||||||
|
c += [f"{t}* {name}::get{a}() {{ return m_{key}; }}", |
||||||
|
f"void {name}::set{a}({t}* value) {{ if (m_{key} != value) {{ delete m_{key}; m_{key} = value; }} m_{key}IsSet = true; }}"] |
||||||
|
c += ["", "}", ""] |
||||||
|
return name, "\n".join(h), "\n".join(c) |
||||||
|
|
||||||
|
|
||||||
|
def main(): |
||||||
|
if len(sys.argv) != 3: |
||||||
|
sys.exit(__doc__) |
||||||
|
src, out = Path(sys.argv[1]).expanduser(), Path(sys.argv[2]).expanduser() |
||||||
|
for cls, definition in yaml.safe_load(src.read_text()).items(): |
||||||
|
name, header, source = generate(cls, definition, src.name) |
||||||
|
(out / f"{name}.h").write_text(header) |
||||||
|
(out / f"{name}.cpp").write_text(source) |
||||||
|
print(f"wrote {out / name}.h/.cpp ({len(definition['properties'])} fields)") |
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__": |
||||||
|
main() |
||||||
@ -0,0 +1,67 @@ |
|||||||
|
#!/usr/bin/env python3 |
||||||
|
"""Call one tool on an SDRangel MCP server (streamable HTTP, JSON-RPC). |
||||||
|
|
||||||
|
./mcp_call.py list_channel_types |
||||||
|
./mcp_call.py --url http://127.0.0.1:8096/mcp get_packets '{"limit": 5}' |
||||||
|
./mcp_call.py --list # tool names |
||||||
|
""" |
||||||
|
|
||||||
|
import argparse |
||||||
|
import json |
||||||
|
import sys |
||||||
|
import urllib.request |
||||||
|
|
||||||
|
|
||||||
|
def rpc(url, method, params, session=None, ident=1): |
||||||
|
body = {"jsonrpc": "2.0", "method": method, "params": params} |
||||||
|
if ident is not None: |
||||||
|
body["id"] = ident |
||||||
|
headers = {"Content-Type": "application/json", "Accept": "application/json, text/event-stream"} |
||||||
|
if session: |
||||||
|
headers["Mcp-Session-Id"] = session |
||||||
|
req = urllib.request.Request(url, json.dumps(body).encode(), headers) |
||||||
|
with urllib.request.urlopen(req, timeout=120) as r: |
||||||
|
session = r.headers.get("Mcp-Session-Id", session) |
||||||
|
text = r.read().decode() |
||||||
|
if not text.strip(): |
||||||
|
return None, session |
||||||
|
if text.lstrip().startswith("event:") or text.lstrip().startswith("data:"): |
||||||
|
text = "\n".join(l[5:].strip() for l in text.splitlines() if l.startswith("data:")) |
||||||
|
return json.loads(text), session |
||||||
|
|
||||||
|
|
||||||
|
def main(): |
||||||
|
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) |
||||||
|
ap.add_argument("--url", default="http://127.0.0.1:8096/mcp") |
||||||
|
ap.add_argument("--list", action="store_true", help="list tool names") |
||||||
|
ap.add_argument("tool", nargs="?") |
||||||
|
ap.add_argument("args", nargs="?", default="{}", help="tool arguments as JSON") |
||||||
|
a = ap.parse_args() |
||||||
|
|
||||||
|
init, session = rpc(a.url, "initialize", { |
||||||
|
"protocolVersion": "2025-06-18", "capabilities": {}, |
||||||
|
"clientInfo": {"name": "mcp_call", "version": "0.1"}}) |
||||||
|
rpc(a.url, "notifications/initialized", {}, session, ident=None) |
||||||
|
|
||||||
|
if a.list: |
||||||
|
res, _ = rpc(a.url, "tools/list", {}, session, 2) |
||||||
|
print("\n".join(t["name"] for t in res["result"]["tools"])) |
||||||
|
return |
||||||
|
if not a.tool: |
||||||
|
sys.exit("give a tool name, or --list") |
||||||
|
|
||||||
|
res, _ = rpc(a.url, "tools/call", {"name": a.tool, "arguments": json.loads(a.args)}, session, 2) |
||||||
|
if "error" in res: |
||||||
|
sys.exit(json.dumps(res["error"], indent=2)) |
||||||
|
for item in res["result"].get("content", []): |
||||||
|
text = item.get("text", "") |
||||||
|
try: |
||||||
|
print(json.dumps(json.loads(text), indent=2)) |
||||||
|
except ValueError: |
||||||
|
print(text) |
||||||
|
if res["result"].get("isError"): |
||||||
|
sys.exit(1) |
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__": |
||||||
|
main() |
||||||
@ -0,0 +1,88 @@ |
|||||||
|
#!/usr/bin/env python3 |
||||||
|
"""Register a new channel type in SDRangel's aggregate SWG classes by cloning |
||||||
|
every block of an existing type (SWGChannelSettings, SWGChannelReport, |
||||||
|
SWGChannelActions, SWGModelFactory). Each block that mentions the template |
||||||
|
type is copied right after itself with the names substituted. |
||||||
|
|
||||||
|
./swg_clone_channel.py ~/sdrangel/swagger/sdrangel/code/qt5/client |
||||||
|
(default: template SELCALDemod -> ChirpModemDemod, as for the Rx plugin) |
||||||
|
./swg_clone_channel.py ~/sdrangel/swagger/sdrangel/code/qt5/client \\ |
||||||
|
--template PacketMod --snake packet_mod --new ChirpModemMod --new-snake chirpmodem_mod \\ |
||||||
|
--skip _payload |
||||||
|
|
||||||
|
The template's setters are copied as they are. Stock types (PacketMod) only |
||||||
|
assign; SELCAL's delete the old object, so never use a SELCAL-style setter in |
||||||
|
WebAPIRequestMapper::reset*(), which nulls members after cleanup(). |
||||||
|
""" |
||||||
|
|
||||||
|
import argparse |
||||||
|
import re |
||||||
|
from pathlib import Path |
||||||
|
|
||||||
|
FILES = ["SWGChannelSettings.h", "SWGChannelSettings.cpp", "SWGChannelReport.h", |
||||||
|
"SWGChannelReport.cpp", "SWGChannelActions.h", "SWGChannelActions.cpp", "SWGModelFactory.h"] |
||||||
|
|
||||||
|
|
||||||
|
def main(): |
||||||
|
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) |
||||||
|
ap.add_argument("client", help="swagger/sdrangel/code/qt5/client") |
||||||
|
ap.add_argument("--template", default="SELCALDemod", help="existing type, as in SWG<template>Settings") |
||||||
|
ap.add_argument("--snake", default="selcal_demod", help="its member name stem, as in <snake>_settings") |
||||||
|
ap.add_argument("--new", default="ChirpModemDemod") |
||||||
|
ap.add_argument("--new-snake", default="chirpmodem_demod") |
||||||
|
ap.add_argument("--skip", help="regex: blocks matching it are not cloned") |
||||||
|
a = ap.parse_args() |
||||||
|
|
||||||
|
# Accessors capitalise only the first letter: getSelcalDemodSettings, getPacketModSettings |
||||||
|
accessor = a.template[0] + a.template[1:].lower() if a.template.isupper() or "SELCAL" in a.template else a.template |
||||||
|
if a.template == "SELCALDemod": |
||||||
|
accessor = "SelcalDemod" |
||||||
|
subst = [(a.template, a.new), (accessor, a.new), (a.snake, a.new_snake)] |
||||||
|
match = re.compile(re.escape(a.template) + "|" + re.escape(accessor) + "|" + re.escape(a.snake)) |
||||||
|
skip = re.compile(a.skip) if a.skip else None |
||||||
|
|
||||||
|
def transform(line): |
||||||
|
for old, new in subst: |
||||||
|
line = line.replace(old, new) |
||||||
|
return line |
||||||
|
|
||||||
|
def clone(lines): |
||||||
|
out, i = [], 0 |
||||||
|
while i < len(lines): |
||||||
|
line = lines[i] |
||||||
|
starts_setter = line.strip() == "void" and i + 1 < len(lines) and match.search(lines[i + 1]) |
||||||
|
if not (match.search(line) or starts_setter): |
||||||
|
out.append(line) |
||||||
|
i += 1 |
||||||
|
continue |
||||||
|
stripped = line.strip() |
||||||
|
is_function = starts_setter or (stripped.startswith("SWG" + a.template) and stripped.endswith("*")) |
||||||
|
j, depth, opened = i, 0, False |
||||||
|
while True: |
||||||
|
depth += lines[j].count("{") - lines[j].count("}") |
||||||
|
opened = opened or "{" in lines[j] |
||||||
|
if depth == 0 and (opened or not is_function): |
||||||
|
break |
||||||
|
j += 1 |
||||||
|
block = lines[i:j + 1] |
||||||
|
out += block |
||||||
|
if not (skip and any(skip.search(b) for b in block)): |
||||||
|
out += [transform(b) for b in block] |
||||||
|
i = j + 1 |
||||||
|
return out |
||||||
|
|
||||||
|
client = Path(a.client).expanduser() |
||||||
|
for name in FILES: |
||||||
|
path = client / name |
||||||
|
text = path.read_text() |
||||||
|
if a.new in text: |
||||||
|
print(f"{name}: already has {a.new}") |
||||||
|
continue |
||||||
|
lines = text.split("\n") |
||||||
|
new = clone(lines) |
||||||
|
path.write_text("\n".join(new)) |
||||||
|
print(f"{name}: +{len(new) - len(lines)} lines") |
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__": |
||||||
|
main() |
||||||
@ -0,0 +1,91 @@ |
|||||||
|
#!/usr/bin/env python3 |
||||||
|
"""Convert an I/Q recording to SDRangel's .sdriq format (FileInput device). |
||||||
|
|
||||||
|
SigMF recordings carry their own format, rate and centre frequency. Raw files |
||||||
|
need --format, --fs and --lo. |
||||||
|
|
||||||
|
./to_sdriq.py ../ota_tx # SigMF -> ../ota_tx.sdriq |
||||||
|
./to_sdriq.py ../ota.cu8 --format cu8 --fs 2.4e6 --lo 223.33e6 |
||||||
|
|
||||||
|
Samples are written as 16-bit I/Q. The .sdriq header is 32 bytes, little |
||||||
|
endian: sample rate u32, centre frequency u64, start time u64 (ms since the |
||||||
|
epoch), sample size u32 (16), filler u32, CRC-32 of the first 28 bytes u32. |
||||||
|
""" |
||||||
|
|
||||||
|
import argparse |
||||||
|
import json |
||||||
|
import struct |
||||||
|
import time |
||||||
|
import zlib |
||||||
|
from datetime import datetime |
||||||
|
from pathlib import Path |
||||||
|
|
||||||
|
import numpy as np |
||||||
|
|
||||||
|
CHUNK = 1 << 20 # complex samples per block |
||||||
|
|
||||||
|
|
||||||
|
def sigmf_paths(name): |
||||||
|
p = Path(name) |
||||||
|
base = p.with_suffix("") if p.suffix in (".sigmf-meta", ".sigmf-data") else p |
||||||
|
return base.with_suffix(".sigmf-meta"), base.with_suffix(".sigmf-data") |
||||||
|
|
||||||
|
|
||||||
|
def to_int16(raw, fmt): |
||||||
|
"""Interleaved I/Q of the given format to int16, full scale 32767.""" |
||||||
|
if fmt == "cu8": |
||||||
|
x = (np.frombuffer(raw, np.uint8).astype(np.float32) - 127.5) * (32767 / 127.5) |
||||||
|
elif fmt == "ci8": |
||||||
|
x = np.frombuffer(raw, np.int8).astype(np.float32) * (32767 / 128) |
||||||
|
elif fmt == "ci16": |
||||||
|
return np.frombuffer(raw, "<i2") |
||||||
|
elif fmt == "cf32": |
||||||
|
x = np.frombuffer(raw, "<f4") * 32767 |
||||||
|
else: |
||||||
|
raise SystemExit(f"unknown format {fmt}") |
||||||
|
return np.clip(np.rint(x), -32768, 32767).astype("<i2") |
||||||
|
|
||||||
|
|
||||||
|
def main(): |
||||||
|
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) |
||||||
|
ap.add_argument("input", help="SigMF name or raw I/Q file") |
||||||
|
ap.add_argument("-o", "--output", help="output .sdriq (default: input name with .sdriq)") |
||||||
|
ap.add_argument("--format", choices=["cu8", "ci8", "ci16", "cf32"], help="raw input format") |
||||||
|
ap.add_argument("--fs", type=float, help="raw input sample rate, Hz") |
||||||
|
ap.add_argument("--lo", type=float, help="raw input centre frequency, Hz") |
||||||
|
a = ap.parse_args() |
||||||
|
|
||||||
|
meta_path, data_path = sigmf_paths(a.input) |
||||||
|
start_ms = int(time.time() * 1000) |
||||||
|
|
||||||
|
if a.format is None and meta_path.exists(): |
||||||
|
meta = json.loads(meta_path.read_text()) |
||||||
|
g, cap = meta["global"], meta["captures"][0] |
||||||
|
fmt = g["core:datatype"].replace("_le", "") |
||||||
|
fs, lo = g["core:sample_rate"], cap["core:frequency"] |
||||||
|
if "core:datetime" in cap: |
||||||
|
start_ms = int(datetime.fromisoformat(cap["core:datetime"].replace("Z", "+00:00")).timestamp() * 1000) |
||||||
|
src = data_path |
||||||
|
else: |
||||||
|
if not (a.format and a.fs and a.lo): |
||||||
|
raise SystemExit("raw input needs --format, --fs and --lo") |
||||||
|
fmt, fs, lo, src = a.format, a.fs, a.lo, Path(a.input) |
||||||
|
|
||||||
|
out = Path(a.output) if a.output else src.with_name(src.name.split(".")[0] + ".sdriq") |
||||||
|
header = struct.pack("<IQQII", int(round(fs)), int(round(lo)), start_ms, 16, 0) |
||||||
|
header += struct.pack("<I", zlib.crc32(header)) |
||||||
|
bytes_per_sample = {"cu8": 2, "ci8": 2, "ci16": 4, "cf32": 8}[fmt] |
||||||
|
|
||||||
|
n = 0 |
||||||
|
with open(src, "rb") as fi, open(out, "wb") as fo: |
||||||
|
fo.write(header) |
||||||
|
while raw := fi.read(CHUNK * bytes_per_sample): |
||||||
|
s = to_int16(raw, fmt) |
||||||
|
fo.write(s.tobytes()) |
||||||
|
n += len(s) // 2 |
||||||
|
|
||||||
|
print(f"{out}: {n} samples, {n / fs:.1f} s at {fs / 1e6:g} MS/s, centre {lo / 1e6:.6f} MHz, from {fmt}") |
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__": |
||||||
|
main() |
||||||
Loading…
Reference in new issue