diff --git a/CHANGELOG.md b/CHANGELOG.md index 0be382c..87aaa82 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,19 @@ ## Unreleased +- `rbtest` in the shell sample: airtime tests with a payload that can be + checked at the other end. `rbtest small` sends a few 32-byte messages + one after another and logs how long each took, `rbtest large` sends one + message of up to 50000 bytes and sends nothing without `confirm`, and + `rbtest mt` shows the last MT and checks it if it is a test message. + `rb9704 pattern make` and `check` in `python/` make and check the same + messages. Not yet run against a real modem. +- `rb9704_send_fill`: as `rb9704_send`, with the message written straight + into the module's buffer, so a large generated message is not held + twice. `overlay-large.conf` raises the limit to 50000 bytes; on the + M5Stamp-C3 that fits on the USB console and not beside WiFi + (`docs/boards/stamp_c3.md`). + - Docs: the M5Stamp-C3 left out overnight on 0.3.0, P_EN wired and active low: the modem up and answering for about 11 h 54 min with no drop, and the Stamp did not reboot. P_EN driven the wrong way had diff --git a/README.md b/README.md index 5d68c42..a8032f1 100644 --- a/README.md +++ b/README.md @@ -145,12 +145,15 @@ rb9704_begin(K_SECONDS(30)); rb9704_send(RB9704_TOPIC_RAW, buf, len, K_SECONDS(10)); /* costs airtime */ rb9704_send(RB9704_TOPIC_RAW, buf, len, K_NO_WAIT); /* queues, never blocks */ rb9704_cancel(K_SECONDS(10)); /* the one in flight; -ECANCELED via mo_done */ +rb9704_send_fill(RB9704_TOPIC_RAW, len, fill, user, K_SECONDS(10)); /* fill() writes it in place */ ``` Every request takes a timeout and waits no longer; with `K_NO_WAIT` a send queues and returns `-EINPROGRESS`, and its outcome, a refusal included, comes through `mo_done`. Callbacks run on the worker thread. One modem per -system: the library keeps global state. +system: the library keeps global state. `rb9704_send_fill` hands `fill` +the module's own buffer, so a large message the application makes up as +it goes does not have to be held twice. | Kconfig | Default | | | --- | --- | --- | @@ -174,7 +177,16 @@ rb9704 cancel abandon the message in flight rb9704 spy on|off every JSPR line, both ways ``` -`samples/shell` is the shell plus callbacks that print what arrives. +`samples/shell` is the shell plus callbacks that print what arrives, and +`rbtest`, airtime tests with a payload `rb9704 pattern check` can check at +the other end: + +``` +rbtest small [count=3] [gap_s=60] 32-byte messages one after another, each timed +rbtest large [bytes=50000] confirm one large message; without confirm, only the cost +rbtest status | stop the run so far, or no more after this one +rbtest mt the last MT, checked if it is a test message +``` ## Host tools diff --git a/docs/boards/stamp_c3.md b/docs/boards/stamp_c3.md index cc68893..d5bc58b 100644 --- a/docs/boards/stamp_c3.md +++ b/docs/boards/stamp_c3.md @@ -171,6 +171,110 @@ Nothing on the button costs airtime. The LED runs at 24 of 255 A fake modem (`rb9704-fake`) on a USB-serial adapter in the modem's place has no I_BTD: tie GPIO7 to 3.3 V for those runs. +## Airtime tests: `rbtest` + +`samples/shell/src/rbtest.c`. Every test message has a 16-byte header +(`RBT`, the kind, its number in the run, its length, the uptime it was +made at) and then a ramp, byte k being k % 510 counted up to 255 and back +down, so a lost or repeated segment shows in a hex dump. Cloudloop shows +each message in hex and in Base64; either goes to the command line in +`python/`, which checks every byte: + +```sh +rb9704 pattern check --b64 UkJUAVMBAwAAAAAgAAAXfBAREhMUFRYXGBkaGxwdHh8 +S 1/3, 32 bytes, made at uptime 6.012 s +every byte as expected +``` + +A run is on a thread of its own, so the shell stays free, and each +message is logged when the modem accepts it and when it finishes: + +``` +rbtest small 244 # 3 messages of 32 bytes, 60 s apart +rbtest small 244 5 120 # 5 of them, 120 s apart +rbtest status # how long each took +rbtest stop # no more after the one in flight +``` + +The log lines, with the times left out: + +``` + rbtest: rbtest S 1/3: 32 bytes on topic 244, accepted in ms + rbtest: rbtest S 1/3: sent in s +... + rbtest: rbtest S: 3 of 3 sent +``` + +A message that has not finished after 10 minutes, 30 for a large one, is +cancelled and counted as failed. + +### One large message + +``` +rbtest large 244 # says what it would send, and sends nothing +rbtest large 244 confirm # sends 50000 bytes +rbtest large 244 20000 confirm # or another size +``` + +The size is limited by `CONFIG_RB9704_MESSAGE_MAX`, 2048 bytes unless +raised. 50000 needs `overlay-large.conf`, and on the Stamp-C3 that does +not fit beside WiFi: the module keeps three buffers of that size, the +library's MO and MT buffers and its own copy for sends, and the link +overflows by about 11 kB. Trimming the network buffers and the receive +ring still left it 3 kB over. So the 50000-byte test runs on the USB +console, with a laptop beside the board: + +```sh +west build -b stamp_c3 samples/shell -- -DEXTRA_CONF_FILE=overlay-large.conf +``` + +With WiFi, 40000 bytes links, using 96% of the RAM, which leaves little +for anything added later: + +```sh +west build -b stamp_c3 samples/shell -- -DEXTRA_CONF_FILE=overlay-wifi.conf \ + -DCONFIG_RB9704_MESSAGE_MAX=40000 +``` + +`rbtest large` writes its message straight into the module's buffer +(`rb9704_send_fill`), so the test itself adds no fourth buffer. + +### Messages to the board (MT) + +The module listens for MT whenever it is begun, not only around a send: +the modem sends `messageTerminate` lines unprompted, the board logs each +whole MT (`mt topic 244 id 3 len 32 crc ...`) and the LED flashes cyan. +What has not been seen yet is when the network delivers: straight away +to a modem sitting idle under the sky, or only after it next sends. The +test is set up to find out: + +1. `rb9704 begin` under open sky, and wait for bars. Send nothing. +2. From any computer with the Cloudloop token, queue a 32-byte test + message, which costs airtime: + + ```sh + rb9704 pattern make --size 32 --out mt.bin + rb9704 cloud mt --file mt.bin + ``` + + or `rb9704 cloud mt --text "ping 1"`, or the Cloudloop web interface. +3. Watch the log, then `rbtest mt`: + + ``` + mt 1 since boot, the last 12 s ago + topic 244 id 3, 32 bytes, crc c07a7327 + 52 42 54 01 4d 01 01 00 00 00 00 20 00 00 00 00 10 11 12 ... + RBT.M...... .................... + test message M 1/1, all 32 bytes as expected + ``` + +4. If nothing has arrived after 10 minutes, `rbtest small 244 1` and see + whether the MT follows the send. `rb9704 cloud status ` says what + Cloudloop thinks happened to it. + +An MT larger than `CONFIG_RB9704_MESSAGE_MAX` cannot be received; with +the 2048-byte default, keep test MTs small. + ## What has run | | | @@ -183,7 +287,9 @@ has no I_BTD: tie GPIO7 to 3.3 V for those runs. | staying up while active | failed with P_EN driven the wrong way: see below; with P_EN unconnected, up and answering throughout (2026-10-25) | | provisioning, and a message sent | works (2026-10-25): provisioned with 244 and 313 to 317, and "Stamp-C3 says hi", 16 bytes on topic 244, sent in 10 s with 3 to 4 bars and received in Cloudloop | | the reworked control pins outside: I_EN and I_BTD in Ground Control's sequence, P_EN wired and `GPIO_ACTIVE_LOW` | works (2026-10-25): "Stamp-C3 P_EN low", 17 bytes on topic 244, sent in 6 s and received in Cloudloop, and the modem up overnight; see below | -| an MT message down to the board | not yet | +| an MT message down to the board | not yet: `rbtest mt`, above | +| `rbtest small`, three timed messages | not yet: works against the fake modem on native_sim | +| `rbtest large`, 50000 bytes | not yet: the USB-console build links; works against the fake on native_sim at 2000 bytes | | the LED and button | the button's short press works; the busy colour reads orange, not white, at this brightness | ### The modem stopped answering after a few minutes: P_EN diff --git a/include/rb9704/rb9704.h b/include/rb9704/rb9704.h index c4a8e1a..0d278e6 100644 --- a/include/rb9704/rb9704.h +++ b/include/rb9704/rb9704.h @@ -145,6 +145,16 @@ int rb9704_end(k_timeout_t timeout); */ int rb9704_send(uint16_t topic, const void *data, size_t len, k_timeout_t timeout); +/* Writes len bytes of a message into buf. */ +typedef void (*rb9704_fill_t)(uint8_t *buf, size_t len, void *user); + +/* As rb9704_send, with the message written straight into this module's + * buffer by fill, on the caller's thread, once the request slot is taken. + * A generated message near CONFIG_RB9704_MESSAGE_MAX then needs no buffer + * of the caller's as well: the library already keeps two of that size. */ +int rb9704_send_fill(uint16_t topic, size_t len, rb9704_fill_t fill, void *user, + k_timeout_t timeout); + /* Ask the modem to abandon the message in flight. Returns 0 once the * request is on the wire; the outcome, -ECANCELED when the modem agrees, * comes through mo_done, and until then the message counts as in flight. diff --git a/python/README.md b/python/README.md index fe5ba4e..fc564a3 100644 --- a/python/README.md +++ b/python/README.md @@ -44,6 +44,8 @@ macOS, Windows). Without the `modem` extra, the fake modem, `jspr`, | `cloud msg ID` | | one message record and its Lingo form | | `cloud mt --text/--hex/--file [--thing ID]` | airtime | queue an MT on `IMT_TOPIC_RAW` | | `cloud status ID` | | an MT's delivery status | +| `pattern make [--size N] [--out F]` | | an `rbtest` test message, as hex or a file, to queue with `cloud mt` | +| `pattern check --hex/--b64/--file` | | check every byte of one, as Cloudloop shows it | The verbs that cost airtime print the size and ask; `--yes` skips the question and is the only way to send from a script. diff --git a/python/rb9704tools/cli.py b/python/rb9704tools/cli.py index d685e7d..80b05ae 100644 --- a/python/rb9704tools/cli.py +++ b/python/rb9704tools/cli.py @@ -12,6 +12,8 @@ rb9704 - drive a RockBLOCK 9704 from the host over its USB-C port. rb9704 [-p PORT] listen [--out DIR] [--for S] rb9704 [-p PORT] session (--text T | --hex H | --file F) [--quiet S] [--yes] rb9704 cloud ping | things | mo | msg ID | mt ... | status ID + rb9704 pattern make [--size N] [--seq N] [--count N] [--out F] + rb9704 pattern check (--hex H | --b64 B | --file F) The modem side uses Ground Control's rockblock9704 package, a binding of the same C library this repository builds into Zephyr, so what works here @@ -23,6 +25,10 @@ the provisioning when a message is sent, and asking that way is free. question. Everything else on the modem side is local serial traffic and costs nothing. `cloud mt` costs airtime too. +`pattern` makes and checks the test message the shell sample's `rbtest` +sends (rb9704tools/pattern.py): `check` takes the bytes Cloudloop shows, +in hex or Base64, and `make` gives a message to queue with `cloud mt`. + The port is -p, or $RB9704_PORT, or the one FTDI FT234XD attached (the 9704's USB-C bridge, 0403:6015). --log FILE appends every event as a JSON line, for the bench log. @@ -42,6 +48,8 @@ import urllib.error import urllib.parse import urllib.request +from rb9704tools import pattern + FTDI_VID, FT234X_PID = 0x0403, 0x6015 BAUD = 230400 RAW_TOPIC = 244 @@ -570,6 +578,38 @@ def cmd_cloud(a): ev("cloud_mt", bytes=len(data), topic=a.topic, result=json.dumps(r)) +# ---------------------------------------------------------------- pattern + +def cmd_pattern(a): + if a.verb == "make": + data = pattern.make(a.size, seq=a.seq, count=a.count) + if a.out: + with open(a.out, "wb") as f: + f.write(data) + else: + print(data.hex()) + return + if a.hex is not None: + data = bytes.fromhex(a.hex) + elif a.b64 is not None: + # Cloudloop leaves the padding off + data = base64.b64decode(a.b64 + "=" * (-len(a.b64) % 4)) + else: + with open(a.file, "rb") as f: + data = f.read() + r = pattern.check(data) + if r is None: + die(f"{len(data)} bytes, not a test message: {data[:16].hex()}") + print(f"{r['kind']} {r['seq']}/{r['count']}, {r['got']} bytes, made at uptime " + f"{r['uptime_ms'] / 1000:.3f} s") + if r["ok"]: + print("every byte as expected") + elif r["bad_at"] == 8: + die(f"the header says {r['length']} bytes, {r['got']} arrived") + else: + die(f"wrong from byte {r['bad_at']}") + + # ---------------------------------------------------------------- main def add_payload(p, required=True): @@ -660,6 +700,20 @@ def main(): add_payload(q) p.set_defaults(fn=cmd_cloud) + p = sub.add_parser("pattern", help="make or check an `rbtest` test message (free)") + ps = p.add_subparsers(dest="verb", required=True) + q = ps.add_parser("make", help="one test message, as hex or to a file") + q.add_argument("--size", type=int, default=32) + q.add_argument("--seq", type=int, default=1) + q.add_argument("--count", type=int, default=1) + q.add_argument("--out", help="write the bytes here; default hex on stdout") + q = ps.add_parser("check", help="every byte of one, as Cloudloop shows it") + g = q.add_mutually_exclusive_group(required=True) + g.add_argument("--hex") + g.add_argument("--b64") + g.add_argument("--file") + p.set_defaults(fn=cmd_pattern) + a = ap.parse_args() LOG = a.log a.fn(a) diff --git a/python/rb9704tools/pattern.py b/python/rb9704tools/pattern.py new file mode 100644 index 0000000..84ef15b --- /dev/null +++ b/python/rb9704tools/pattern.py @@ -0,0 +1,52 @@ +# SPDX-License-Identifier: MIT +# Copyright (c) 2026 Scott Penrose +""" +The test message `rbtest` in the shell sample sends, and checks when one +arrives as an MT (samples/shell/src/rbtest.c has the same description). + +A 16-byte header: + + 0..2 b"RBT" + 3 version, 1 + 4 kind: b"S" small, b"L" large, anything else for one made here + 5 seq, from 1 + 6 count in the run + 7 0 + 8..11 the whole message's length, big-endian + 12..15 uptime in ms when it was made, big-endian + +then from byte 16 to the end, byte k is k % 510 counted up 0..255 and back +down 254..1. +""" +import struct + +HEADER = 16 +MAGIC = b"RBT\x01" + + +def ramp(k): + v = k % 510 + return v if v < 256 else 510 - v + + +def make(length, kind="M", seq=1, count=1, uptime_ms=0): + if length <= HEADER: + raise ValueError(f"a test message is more than {HEADER} bytes") + head = MAGIC + struct.pack(">cBBxII", kind.encode()[:1], seq, count, length, uptime_ms) + return head + bytes(ramp(k) for k in range(HEADER, length)) + + +def check(data): + """A dict describing data, with "ok" True when every byte is as made, + or None when it is not a test message at all.""" + if len(data) < HEADER or not data.startswith(MAGIC): + return None + kind, seq, count, length, uptime_ms = struct.unpack(">cBBxII", data[4:HEADER]) + r = {"kind": kind.decode("ascii", "replace"), "seq": seq, "count": count, + "length": length, "got": len(data), "uptime_ms": uptime_ms, "bad_at": None} + if length != len(data): + r["bad_at"] = 8 + else: + r["bad_at"] = next((k for k in range(HEADER, len(data)) if data[k] != ramp(k)), None) + r["ok"] = r["bad_at"] is None + return r diff --git a/python/tests/test_cli.py b/python/tests/test_cli.py index b2b3c62..d2f07ab 100644 --- a/python/tests/test_cli.py +++ b/python/tests/test_cli.py @@ -2,11 +2,14 @@ # Copyright (c) 2026 Scott Penrose """The rb9704 command line against the fake modem.""" +import base64 import subprocess import sys import pytest +from rb9704tools import pattern + def run(*args, timeout=30): return subprocess.run([sys.executable, "-m", "rb9704tools.cli", *args], capture_output=True, @@ -46,3 +49,29 @@ def test_send_with_yes(fake): assert r.returncode == 0, r.stdout + r.stderr m = fake.out.expect(r"^MO 244 \d+ (\w+)") assert bytes.fromhex(m.group(1)) == b"cli-hello" + + +def test_pattern_make_and_check(): + r = run("pattern", "make", "--size", "1000", "--seq", "2", "--count", "3") + assert r.returncode == 0, r.stderr + hexed = r.stdout.strip() + data = bytes.fromhex(hexed) + assert len(data) == 1000 and data[:4] == b"RBT\x01" + # the ramp turns at 255 and comes back down + assert data[255] == 255 and data[256] == 254 and data[510] == 0 + r = run("pattern", "check", "--hex", hexed) + assert r.returncode == 0, r.stdout + r.stderr + assert "M 2/3, 1000 bytes" in r.stdout and "every byte as expected" in r.stdout + b64 = base64.b64encode(data).decode().rstrip("=") + assert run("pattern", "check", "--b64", b64).returncode == 0 + + +def test_pattern_check_finds_the_damage(): + data = bytearray(pattern.make(100)) + data[40] ^= 1 + r = run("pattern", "check", "--hex", data.hex()) + assert r.returncode != 0 and "byte 40" in r.stdout + r.stderr + r = run("pattern", "check", "--hex", pattern.make(100)[:90].hex()) + assert r.returncode != 0 and "says 100 bytes, 90 arrived" in r.stdout + r.stderr + r = run("pattern", "check", "--hex", b"hello".hex()) + assert r.returncode != 0 and "not a test message" in r.stdout + r.stderr diff --git a/python/tests/test_zephyr.py b/python/tests/test_zephyr.py index f02d58a..a6f7c11 100644 --- a/python/tests/test_zephyr.py +++ b/python/tests/test_zephyr.py @@ -10,6 +10,8 @@ import zlib import pytest +from rb9704tools import pattern + def begin(z): c, f = z @@ -181,3 +183,61 @@ def test_end(zephyr): c.out.expect(r"end: ok") c.sh("rb9704 send 244 after-end") c.out.expect(r"send: -\d+ ENOTCONN") + + +def test_rbtest_small_sends_checkable_messages(zephyr): + """`rbtest small`, two messages with no gap: each reaches the network + whole, numbered, and its time is logged.""" + c, f = zephyr + begin(zephyr) + c.sh("rbtest small 244 2 0") + c.out.expect(r"2 messages of 32 bytes on topic 244") + for seq in (1, 2): + m = f.out.expect(r"^MO 244 \d+ (\w+)") + r = pattern.check(bytes.fromhex(m.group(1))) + assert r["ok"] and (r["kind"], r["seq"], r["count"], r["got"]) == ("S", seq, 2, 32) + c.out.expect(r"rbtest S %d/2: sent in \d+\.\d{3} s" % seq) + c.out.expect(r"rbtest S: 2 of 2 sent$") + c.sh("rbtest status") + c.out.expect(r"last run S: 2 of 2 done, 32 bytes each on topic 244") + c.out.expect(r"2: sent in \d+\.\d{3} s") + + +def test_rbtest_small_logs_a_failure(zephyr): + c, f = zephyr + begin(zephyr) + f.cmd("mo-fail network_error") + c.sh("rbtest small 244 1 0") + c.out.expect(r"rbtest S 1/1: failed after \d+ ms: -\d+") + c.out.expect(r"rbtest S: 0 of 1 sent$") + + +def test_rbtest_large_asks_first(zephyr): + """Without confirm nothing goes; with it, one message of the size given + (the 50000 default needs CONFIG_RB9704_MESSAGE_MAX raised).""" + c, f = zephyr + begin(zephyr) + c.sh("rbtest large 244 2000") + c.out.expect(r"Nothing sent. To send it: rbtest large 244 2000 confirm") + with pytest.raises(AssertionError): + f.out.expect(r"^MO ", timeout=2) + c.sh("rbtest large 244 confirm") + c.out.expect(r"50000 bytes: from 17 to \d+") + c.sh("rbtest large 244 2000 confirm") + m = f.out.expect(r"^MO 244 \d+ (\w+)") + r = pattern.check(bytes.fromhex(m.group(1))) + assert r["ok"] and (r["kind"], r["got"]) == ("L", 2000) + c.out.expect(r"rbtest L 1/1: sent in") + + +def test_rbtest_mt_checks_a_test_message(zephyr): + c, f = zephyr + begin(zephyr) + c.sh("rbtest mt") + c.out.expect(r"no MT since boot|mt\s+\d+ since boot") + f.cmd("mthex 244 " + pattern.make(1200, seq=4, count=5).hex()) + c.out.expect(r"rbtest: MT is a test message, M 4/5, all 1200 bytes as expected") + c.sh("rbtest mt") + c.out.expect(r"topic 244 id \d+, 1200 bytes, crc %08x" % zlib.crc32(pattern.make(1200, seq=4, count=5))) + c.out.expect(r"52 42 54 01 4d 04 05 00 00 00 04 b0") + c.out.expect(r"test message M 4/5, all 1200 bytes as expected") diff --git a/samples/shell/CMakeLists.txt b/samples/shell/CMakeLists.txt index c1f09af..bfb6d92 100644 --- a/samples/shell/CMakeLists.txt +++ b/samples/shell/CMakeLists.txt @@ -3,7 +3,7 @@ cmake_minimum_required(VERSION 3.20.0) find_package(Zephyr REQUIRED HINTS $ENV{ZEPHYR_BASE}) project(rb9704_shell) -target_sources(app PRIVATE src/main.c) +target_sources(app PRIVATE src/main.c src/rbtest.c) target_sources_ifdef(CONFIG_WIFI app PRIVATE src/wifi.c) # The RGB LED and button, on boards whose overlay gives a led-strip alias # and an sw0 button (boards/stamp_c3.*). diff --git a/samples/shell/overlay-large.conf b/samples/shell/overlay-large.conf new file mode 100644 index 0000000..58d9aa3 --- /dev/null +++ b/samples/shell/overlay-large.conf @@ -0,0 +1,13 @@ +# SPDX-License-Identifier: MIT +# Copyright (c) 2026 Scott Penrose +# +# Messages up to 50000 bytes, for `rbtest large`: +# +# west build -b stamp_c3 samples/shell -- -DEXTRA_CONF_FILE=overlay-large.conf +# +# Three buffers of this size are kept: the library's MO and MT buffers and +# this module's copy for rb9704_send, about 150 kB in all. On the +# M5Stamp-C3 that fits on the USB console, and with overlay-wifi.conf as +# well it does not: the link overflows by 11 kB. With WiFi, 40000 bytes +# fits (docs/boards/stamp_c3.md). +CONFIG_RB9704_MESSAGE_MAX=50000 diff --git a/samples/shell/src/main.c b/samples/shell/src/main.c index cc17c38..38e2a3c 100644 --- a/samples/shell/src/main.c +++ b/samples/shell/src/main.c @@ -15,6 +15,8 @@ #include +#include "rbtest.h" + #ifdef CONFIG_WIFI #include "wifi.h" #endif @@ -28,6 +30,7 @@ static void on_mo_done(uint16_t topic, uint16_t id, int result, void *user) { ARG_UNUSED(user); LOG_INF("mo done topic %u id %u result %d", topic, id, result); + rbtest_mo_done(topic, id, result); #ifdef CONFIG_LED_STRIP indicator_flash_mo(result); #endif @@ -47,6 +50,7 @@ static void on_mt(const struct rb9704_mt *mt, void *user) text[n] = '\0'; LOG_INF("mt topic %u id %u len %u crc %08x: %s", mt->topic, mt->id, (unsigned int)mt->len, crc32_ieee(mt->data, mt->len), text); + rbtest_mt(mt); #ifdef CONFIG_LED_STRIP indicator_flash_mt(); #endif diff --git a/samples/shell/src/rbtest.c b/samples/shell/src/rbtest.c new file mode 100644 index 0000000..5e5cc9c --- /dev/null +++ b/samples/shell/src/rbtest.c @@ -0,0 +1,409 @@ +/* SPDX-License-Identifier: MIT + * Copyright (c) 2026 Scott Penrose + * + * rbtest.c - `rbtest` on the shell: airtime tests with a payload that is + * easy to check at the other end, and a record of the last MT. + * + * rbtest small [count] [gap_s] count messages of 32 bytes, one + * at a time, gap_s apart + * rbtest large [bytes] [confirm] one message, 50000 bytes unless + * given; without confirm it only + * says what it would cost + * rbtest status the run, and how long each took + * rbtest stop no more messages after this one + * rbtest mt the last message from the network + * + * A run is on a thread of its own, so the shell stays free; each message + * is logged as it is accepted and as it finishes. + * + * Every test message, MO or MT, has the same shape. A 16-byte header: + * + * 0..2 "RBT" + * 3 version, 1 + * 4 kind: 'S' small, 'L' large, anything else from the cloud side + * 5 seq, from 1 + * 6 count in the run + * 7 0 + * 8..11 the whole message's length, big-endian + * 12..15 uptime in ms when it was made, big-endian + * + * then from byte 16 to the end, byte k is k % 510 counted up 0..255 and + * back down 254..1: a ramp that shows a missing or repeated segment at a + * glance in a hex dump. `rb9704 pattern check` in python/ checks one, and + * `rb9704 pattern make` makes one to queue as an MT. + */ +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +#include + +#include "rbtest.h" + +LOG_MODULE_REGISTER(rbtest, LOG_LEVEL_INF); + +#define HEADER 16 +#define SMALL_LEN 32 +#define LARGE_LEN 50000 +#define MAX_COUNT 20 +/* How long one message may take before it is cancelled. The modem retries + * by itself while it waits for a satellite, so these are generous. */ +#define SMALL_TIMEOUT K_SECONDS(600) +#define LARGE_TIMEOUT K_SECONDS(1800) + +struct fill_ctx { + char kind; + uint8_t seq, count; + uint32_t uptime_ms; +}; + +static uint8_t ramp(size_t k) +{ + size_t v = k % 510; + + return v < 256 ? v : 510 - v; +} + +static void fill(uint8_t *buf, size_t len, void *user) +{ + const struct fill_ctx *c = user; + uint8_t h[HEADER] = { 'R', 'B', 'T', 1, c->kind, c->seq, c->count, 0 }; + + sys_put_be32(len, &h[8]); + sys_put_be32(c->uptime_ms, &h[12]); + for (size_t k = 0; k < len; k++) { + buf[k] = k < HEADER ? h[k] : ramp(k); + } +} + +/* -1: not a test message. Otherwise the offset of the first byte that is + * not as expected, and len when every byte is. */ +static long check(const uint8_t *d, size_t len) +{ + if (len < HEADER || memcmp(d, "RBT\x01", 4) != 0) { + return -1; + } + if (sys_get_be32(&d[8]) != len) { + return 8; + } + for (size_t k = HEADER; k < len; k++) { + if (d[k] != ramp(k)) { + return k; + } + } + return len; +} + +/* --- the run --------------------------------------------------------------- */ + +static struct { + bool running; + bool stop; + char kind; + uint16_t topic; + uint8_t count; + uint32_t gap_s; + size_t len; + uint8_t done; + int32_t result[MAX_COUNT]; /* ms to send, or a negative errno */ + int mo_result; +} run; +static K_MUTEX_DEFINE(run_lock); +static K_SEM_DEFINE(run_go, 0, 1); +static K_SEM_DEFINE(run_mo, 0, 1); +static K_SEM_DEFINE(run_stop, 0, 1); +static volatile bool mo_waiting; + +void rbtest_mo_done(uint16_t topic, uint16_t id, int result) +{ + ARG_UNUSED(topic); ARG_UNUSED(id); + if (mo_waiting) { + run.mo_result = result; + k_sem_give(&run_mo); + } +} + +static int32_t one(uint8_t seq) +{ + struct fill_ctx c = { run.kind, seq, run.count, 0 }; + k_timeout_t timeout = run.kind == 'L' ? LARGE_TIMEOUT : SMALL_TIMEOUT; + int64_t t0 = k_uptime_get(); + int rc; + + c.uptime_ms = (uint32_t)t0; + k_sem_reset(&run_mo); + mo_waiting = true; + rc = rb9704_send_fill(run.topic, run.len, fill, &c, K_SECONDS(30)); + if (rc != 0 && rc != -EINPROGRESS) { + mo_waiting = false; + LOG_WRN("rbtest %c %u/%u: not accepted: %d", run.kind, seq, run.count, rc); + return rc; + } + LOG_INF("rbtest %c %u/%u: %u bytes on topic %u, accepted in %lld ms", run.kind, seq, + run.count, (unsigned int)run.len, run.topic, k_uptime_get() - t0); + if (k_sem_take(&run_mo, timeout) != 0) { + LOG_WRN("rbtest %c %u/%u: no result in %lld s, cancelling", run.kind, seq, + run.count, (k_uptime_get() - t0) / 1000); + (void)rb9704_cancel(K_SECONDS(5)); + (void)k_sem_take(&run_mo, K_SECONDS(60)); + mo_waiting = false; + return -ETIMEDOUT; + } + mo_waiting = false; + if (run.mo_result != 0) { + LOG_WRN("rbtest %c %u/%u: failed after %lld ms: %d", run.kind, seq, run.count, + k_uptime_get() - t0, run.mo_result); + return run.mo_result; + } + return (int32_t)(k_uptime_get() - t0); +} + +static void runner(void *a, void *b, void *c) +{ + ARG_UNUSED(a); ARG_UNUSED(b); ARG_UNUSED(c); + + for (;;) { + uint8_t ok = 0; + + k_sem_take(&run_go, K_FOREVER); + for (uint8_t i = 0; i < run.count && !run.stop; i++) { + int32_t r = one(i + 1); + + k_mutex_lock(&run_lock, K_FOREVER); + run.result[i] = r; + run.done = i + 1; + k_mutex_unlock(&run_lock); + if (r >= 0) { + ok++; + LOG_INF("rbtest %c %u/%u: sent in %d.%03d s", run.kind, i + 1, + run.count, r / 1000, r % 1000); + } + if (i + 1 < run.count && !run.stop && + k_sem_take(&run_stop, K_SECONDS(run.gap_s)) == 0) { + break; + } + } + LOG_INF("rbtest %c: %u of %u sent%s", run.kind, ok, run.count, + run.done < run.count ? ", stopped" : ""); + k_mutex_lock(&run_lock, K_FOREVER); + run.running = false; + k_mutex_unlock(&run_lock); + } +} + +K_THREAD_DEFINE(rbtest_tid, 2048, runner, NULL, NULL, NULL, 10, 0, 0); + +static int start(const struct shell *sh, char kind, uint16_t topic, uint8_t count, + uint32_t gap_s, size_t len) +{ + k_mutex_lock(&run_lock, K_FOREVER); + if (run.running) { + k_mutex_unlock(&run_lock); + shell_error(sh, "a run is going: `rbtest status`, `rbtest stop`"); + return -EBUSY; + } + run.running = true; + run.stop = false; + run.kind = kind; + run.topic = topic; + run.count = count; + run.gap_s = gap_s; + run.len = len; + run.done = 0; + k_mutex_unlock(&run_lock); + k_sem_reset(&run_stop); + k_sem_give(&run_go); + return 0; +} + +static int parse_topic(const struct shell *sh, const char *s, uint16_t *topic) +{ + unsigned long t = strtoul(s, NULL, 10); + + if (t < RB9704_TOPIC_MIN || t > UINT16_MAX) { + shell_error(sh, "topic %s: from %u, 244 is raw", s, RB9704_TOPIC_MIN); + return -EINVAL; + } + *topic = (uint16_t)t; + return 0; +} + +static int cmd_small(const struct shell *sh, size_t argc, char **argv) +{ + uint16_t topic; + unsigned long count = argc > 2 ? strtoul(argv[2], NULL, 10) : 3; + unsigned long gap = argc > 3 ? strtoul(argv[3], NULL, 10) : 60; + + if (parse_topic(sh, argv[1], &topic) != 0) { + return -EINVAL; + } + if (count < 1 || count > MAX_COUNT) { + shell_error(sh, "count 1 to %d", MAX_COUNT); + return -EINVAL; + } + shell_print(sh, "%lu messages of %d bytes on topic %u, %lu s apart: this costs airtime", + count, SMALL_LEN, topic, gap); + return start(sh, 'S', topic, count, gap, SMALL_LEN); +} + +static int cmd_large(const struct shell *sh, size_t argc, char **argv) +{ + uint16_t topic; + unsigned long len = LARGE_LEN; + bool confirmed = false; + + if (parse_topic(sh, argv[1], &topic) != 0) { + return -EINVAL; + } + for (size_t i = 2; i < argc; i++) { + if (strcmp(argv[i], "confirm") == 0) { + confirmed = true; + } else { + len = strtoul(argv[i], NULL, 10); + } + } + if (len <= HEADER || len > CONFIG_RB9704_MESSAGE_MAX) { + shell_error(sh, "%lu bytes: from %d to %d, CONFIG_RB9704_MESSAGE_MAX in this build", + len, HEADER + 1, CONFIG_RB9704_MESSAGE_MAX); + return -EINVAL; + } + if (!confirmed) { + shell_print(sh, "one message of %lu bytes on topic %u, %lu times the size of a", + len, topic, len / SMALL_LEN); + shell_print(sh, "small test message. It costs airtime for every byte."); + shell_print(sh, "Nothing sent. To send it: rbtest large %u %lu confirm", topic, len); + return 0; + } + shell_print(sh, "%lu bytes on topic %u: this costs airtime", len, topic); + return start(sh, 'L', topic, 1, 0, len); +} + +static int cmd_status(const struct shell *sh, size_t argc, char **argv) +{ + ARG_UNUSED(argc); ARG_UNUSED(argv); + k_mutex_lock(&run_lock, K_FOREVER); + if (run.count == 0) { + shell_print(sh, "no run since boot"); + } else { + shell_print(sh, "%s %c: %u of %u done, %u bytes each on topic %u", + run.running ? "running" : "last run", run.kind, run.done, run.count, + (unsigned int)run.len, run.topic); + for (int i = 0; i < run.done; i++) { + int32_t r = run.result[i]; + + if (r >= 0) { + shell_print(sh, " %d: sent in %d.%03d s", i + 1, r / 1000, + r % 1000); + } else { + shell_print(sh, " %d: failed, %d", i + 1, r); + } + } + } + k_mutex_unlock(&run_lock); + return 0; +} + +static int cmd_stop(const struct shell *sh, size_t argc, char **argv) +{ + ARG_UNUSED(argc); ARG_UNUSED(argv); + if (!run.running) { + shell_print(sh, "nothing running"); + return 0; + } + run.stop = true; + k_sem_give(&run_stop); + shell_print(sh, "stopping after the message in flight; `rb9704 cancel` abandons it"); + return 0; +} + +/* --- the last MT ------------------------------------------------------------ */ + +static struct { + uint32_t count; + int64_t at_ms; + uint16_t topic, id; + size_t len; + uint32_t crc; + uint8_t head[32]; + long check; +} mt_last; +static K_MUTEX_DEFINE(mt_lock); + +void rbtest_mt(const struct rb9704_mt *mt) +{ + long c = check(mt->data, mt->len); + + k_mutex_lock(&mt_lock, K_FOREVER); + mt_last.count++; + mt_last.at_ms = k_uptime_get(); + mt_last.topic = mt->topic; + mt_last.id = mt->id; + mt_last.len = mt->len; + mt_last.crc = crc32_ieee(mt->data, mt->len); + memcpy(mt_last.head, mt->data, MIN(mt->len, sizeof(mt_last.head))); + mt_last.check = c; + k_mutex_unlock(&mt_lock); + if (c == (long)mt->len) { + LOG_INF("rbtest: MT is a test message, %c %u/%u, all %u bytes as expected", + mt->data[4], mt->data[5], mt->data[6], (unsigned int)mt->len); + } else if (c >= 0) { + LOG_WRN("rbtest: MT is a test message, wrong from byte %ld of %u", c, + (unsigned int)mt->len); + } +} + +static int cmd_mt(const struct shell *sh, size_t argc, char **argv) +{ + char hex[3 * sizeof(mt_last.head) + 1]; + char text[sizeof(mt_last.head) + 1]; + size_t n; + + ARG_UNUSED(argc); ARG_UNUSED(argv); + k_mutex_lock(&mt_lock, K_FOREVER); + if (mt_last.count == 0) { + k_mutex_unlock(&mt_lock); + shell_print(sh, "no MT since boot"); + return 0; + } + n = MIN(mt_last.len, sizeof(mt_last.head)); + for (size_t i = 0; i < n; i++) { + snprintk(&hex[3 * i], 4, "%02x ", mt_last.head[i]); + text[i] = isprint(mt_last.head[i]) ? mt_last.head[i] : '.'; + } + hex[n > 0 ? 3 * n - 1 : 0] = '\0'; + text[n] = '\0'; + shell_print(sh, "mt %u since boot, the last %lld s ago", mt_last.count, + (k_uptime_get() - mt_last.at_ms) / 1000); + shell_print(sh, " topic %u id %u, %u bytes, crc %08x", mt_last.topic, mt_last.id, + (unsigned int)mt_last.len, mt_last.crc); + shell_print(sh, " %s", hex); + shell_print(sh, " %s", text); + if (mt_last.check == (long)mt_last.len) { + shell_print(sh, " test message %c %u/%u, all %u bytes as expected", + mt_last.head[4], mt_last.head[5], mt_last.head[6], + (unsigned int)mt_last.len); + } else if (mt_last.check >= 0) { + shell_print(sh, " test message, wrong from byte %ld", mt_last.check); + } + k_mutex_unlock(&mt_lock); + return 0; +} + +SHELL_STATIC_SUBCMD_SET_CREATE(rbtest_cmds, + SHELL_CMD_ARG(small, NULL, "small [count=3] [gap_s=60]: costs airtime", + cmd_small, 2, 2), + SHELL_CMD_ARG(large, NULL, "large [bytes=50000] [confirm]: costs airtime", + cmd_large, 2, 2), + SHELL_CMD(status, NULL, "the run, and how long each message took", cmd_status), + SHELL_CMD(stop, NULL, "no more messages after the one in flight", cmd_stop), + SHELL_CMD(mt, NULL, "the last message from the network", cmd_mt), + SHELL_SUBCMD_SET_END); + +SHELL_CMD_REGISTER(rbtest, &rbtest_cmds, "airtime tests with a checkable payload", NULL); diff --git a/samples/shell/src/rbtest.h b/samples/shell/src/rbtest.h new file mode 100644 index 0000000..e583fda --- /dev/null +++ b/samples/shell/src/rbtest.h @@ -0,0 +1,14 @@ +/* SPDX-License-Identifier: MIT + * Copyright (c) 2026 Scott Penrose + * + * rbtest.h - the airtime tests, fed from the sample's callbacks. + */ +#ifndef RBTEST_H_ +#define RBTEST_H_ + +#include + +void rbtest_mo_done(uint16_t topic, uint16_t id, int result); +void rbtest_mt(const struct rb9704_mt *mt); + +#endif /* RBTEST_H_ */ diff --git a/src/rb9704_worker.c b/src/rb9704_worker.c index be40cc3..44579c0 100644 --- a/src/rb9704_worker.c +++ b/src/rb9704_worker.c @@ -530,12 +530,26 @@ int rb9704_info(struct rb9704_info *out, k_timeout_t timeout) return rc; } +static void fill_copy(uint8_t *buf, size_t len, void *user) +{ + memcpy(buf, user, len); +} + int rb9704_send(uint16_t topic, const void *data, size_t len, k_timeout_t timeout) +{ + if (data == NULL) { + return -EINVAL; + } + return rb9704_send_fill(topic, len, fill_copy, (void *)data, timeout); +} + +int rb9704_send_fill(uint16_t topic, size_t len, rb9704_fill_t fill, void *user, + k_timeout_t timeout) { bool abandoned; int rc; - if (topic < RB9704_TOPIC_MIN || data == NULL || len == 0 || len > sizeof(mo_buf)) { + if (topic < RB9704_TOPIC_MIN || fill == NULL || len == 0 || len > sizeof(mo_buf)) { return -EINVAL; } rc = take_slot(timeout); @@ -545,7 +559,7 @@ int rb9704_send(uint16_t topic, const void *data, size_t len, k_timeout_t timeou req.op = OP_SEND; req.topic = topic; req.len = len; - memcpy(mo_buf, data, len); + fill(mo_buf, len, user); rc = submit(timeout, &abandoned); if (abandoned) { return -EINPROGRESS;