Cancel the message in flight, and the small things from the review

rb9704_cancel() and `rb9704 cancel` ask the modem to abandon the MO in
flight; the modem's final status reaches mo_done as -ECANCELED. The
library's async path has no timeout, so this is how an application
frees a modem that has gone quiet mid-send. The status snapshot carries
the in-flight message's id and start time for the application to decide
with.

rb9704_begin zeroes moQueuedMessages: rbBegin empties the queue but not
the count, and a count above zero makes every later send queue without
transmitting.

The fake modem's mo-hold and mo-release stand in for a modem that has
taken a message and said nothing more; a test drives cancel through it.

Also: the shell's send buffer is a shell line, not a fourth message
buffer; the bridge's TX-disable race has a comment; the CLI turns a
Cloudloop error (a bad token's 200 reply included), an unopenable port
and a one-word jspr line into one line and exit 1; conftest reads
request.node; pyproject uses the current license spelling.
This commit is contained in:
scottp committed 2026-10-21 22:43:05 +11:00
1 parent 509b9b5b6d
commit f97fcab74b
13 files changed
+235 -34

No files matched your search

+14
View File
@@ -2,6 +2,20 @@
## Unreleased
- `rb9704_cancel()` and `rb9704 cancel`: ask the modem to abandon the
message in flight; `mo_done` then reports `-ECANCELED`. The status
snapshot carries the in-flight message's id and start time. The fake
modem's `mo-hold` and `mo-release` stand in for a modem that has taken
a message and gone quiet.
- `rb9704_begin` zeroes the library's count of queued MOs, which `rbBegin`
leaves behind and which would otherwise stop every send after a stuck
one.
- `rb9704 send`: no fourth `CONFIG_RB9704_MESSAGE_MAX` buffer; text goes
straight through, hex into a buffer the size of a shell line.
- `rb9704`: a Cloudloop error, a bad token's `{"error": ...}` in a 200
reply included, and a port that will not open are one line and a
non-zero exit, not a traceback or a quiet success; a one-word `jspr`
line is refused instead of raising.
- `CONFIG_RB9704_POWER` now defaults on when the devicetree node has
`power-gpios`, as documented. The Kconfig default referred to a compat
variable nothing defined, so the pins were never driven unless the
+8
View File
@@ -49,6 +49,12 @@ The library's source shows several things a caller has to work around;
the reader discards lines it is not waiting for. Info and signal
requests are refused with `-EBUSY` while a message is moving.
- **No locking.** Every library call is on the worker thread.
- **A send has no timeout, and the queue's count survives `rbEnd`.** The
async path only reacts to lines from the modem, so a modem that goes
quiet mid-send leaves the message in flight for good; `rb9704_cancel`
asks the modem to abandon it. `rbBegin` empties the queue but not the
count of it, which would make every send after a stuck one queue
without transmitting; `rb9704_begin` zeroes the count.
Others are for upstream to fix, and are listed in `docs/JSPR.md` for that:
`setState` waits for a misspelt target, a line with no status code reads
@@ -106,6 +112,7 @@ rb9704_set_callbacks(&cb);
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 */
```
Every request takes a timeout and waits no longer; with `K_NO_WAIT` a send
@@ -131,6 +138,7 @@ rb9704 status what is known, without asking the modem
rb9704 info IMEI, serial, versions, ICCID, SIM, temperature
rb9704 signal bars now
rb9704 send <topic> <text> | sendhex <topic> <hex> costs airtime
rb9704 cancel abandon the message in flight
rb9704 spy on|off every JSPR line, both ways
```
+6 -1
View File
@@ -747,7 +747,12 @@ Everything else is ignored.
ignores the failed add (`queued >= 0`, `src/rockblock_9704.c:400`) and
**re-sends the old stuck message** with a new `PUT messageOriginate`. A late
`299 messageOriginateStatus` for the old id, read by any later `rbPoll`,
clears it.
clears it. The async path has the same hole with no timeout at all: the
MO is removed only by a final status, and `rbCancelMessage` is the one
way to ask for one. `rbEnd` then `rbBegin` empties the queue
(`imtQueueInit`) but not `moQueuedMessages`, so with the count still 1
the next `rbSendMessageAsync` queues (`moQueuedMessages == 0` is false)
and never transmits. The Zephyr module zeroes the count after `rbBegin`.
9. **`200 messageOriginate` alone means started**, whatever
`message_response` says (4.3 step 2).
10. **`rbReceiveMessage` has no timeout** once an MT has been announced.
+16 -1
View File
@@ -81,6 +81,8 @@ struct rb9704_status {
/* messages */
bool mo_in_flight;
uint16_t mo_topic;
uint16_t mo_id; /* the modem's id for it */
int64_t mo_started_ms; /* uptime when the modem accepted it */
uint32_t mo_sent, mo_failed;
uint32_t mt_received, mt_failed;
/* the serial port */
@@ -99,7 +101,8 @@ struct rb9704_mt {
* blocking rb9704_* request from one: the worker is the thread that would
* have to answer it. Any member may be NULL. */
struct rb9704_callbacks {
/* An MO has finished: result 0 when the network has it. */
/* An MO has finished: result 0 when the network has it, -ECANCELED
* after rb9704_cancel, -EIO otherwise. */
void (*mo_done)(uint16_t topic, uint16_t id, int result, void *user);
/* An MT has arrived whole. It is acknowledged to the modem after this
* returns, so copy what is wanted. */
@@ -141,6 +144,18 @@ int rb9704_end(k_timeout_t timeout);
*/
int rb9704_send(uint16_t topic, const void *data, size_t len, 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.
* The library has no timeout of its own, so this is how an application
* frees a modem that has gone quiet mid-send; a modem that does not answer
* the cancel either is reset by rb9704_end and rb9704_begin.
*
* -ENOTCONN not begun
* -ENOENT nothing in flight
*/
int rb9704_cancel(k_timeout_t timeout);
/* Ask the modem who it is. Free, milliseconds. */
int rb9704_info(struct rb9704_info *out, k_timeout_t timeout);
+1 -1
View File
@@ -7,7 +7,7 @@ name = "rockblock9704-tools"
version = "0.1.0"
description = "Host tools for the RockBLOCK 9704: a command line for the modem and Cloudloop, and a fake modem for testing"
readme = "README.md"
license = { text = "MIT" }
license = "MIT"
authors = [{ name = "Scott Penrose", email = "scottp@dd.com.au" }]
requires-python = ">=3.10"
dependencies = ["pyserial>=3.5"]
+30 -7
View File
@@ -38,6 +38,7 @@ import json
import os
import sys
import time
import urllib.error
import urllib.parse
import urllib.request
@@ -361,7 +362,10 @@ class Jspr:
def __init__(self, port):
import serial
self.s = serial.Serial(port, BAUD, timeout=0.1)
try:
self.s = serial.Serial(port, BAUD, timeout=0.1)
except serial.SerialException as e:
die(f"cannot open {port}: {e}")
self.buf = b""
self.s.reset_input_buffer()
@@ -382,7 +386,10 @@ class Jspr:
def cmd(self, line, target=None, secs=3.0, show=False):
"""Send a line, return the first response for its target. Anything
else that arrives meanwhile is shown as it goes past."""
target = target or line.split()[1]
words = line.split()
if target is None and len(words) < 2:
die(f"not a JSPR line: {line!r} (verb, target, json)")
target = target or words[1]
self.s.write((line + "\r").encode())
for code, tgt, js, raw in self.lines(secs):
if show or tgt != target or code == 299:
@@ -494,11 +501,27 @@ def api(path, **params):
them, in the query string."""
q = urllib.parse.urlencode({"token": token(), **params})
req = urllib.request.Request(f"{CLOUDLOOP}{path}?{q}", data=b"", method="POST")
with urllib.request.urlopen(req, timeout=30) as r:
body = json.load(r)
for k in ("DispatcherException", "DispatcherValidationException"):
if k in body:
die(f"{path}: {json.dumps(body[k])}")
try:
with urllib.request.urlopen(req, timeout=30) as r:
body = json.load(r)
except urllib.error.HTTPError as e:
die(f"{path}: HTTP {e.code} {e.reason}" +
(": the token was not accepted" if e.code in (401, 403) else ""))
except (urllib.error.URLError, TimeoutError) as e:
die(f"{path}: {getattr(e, 'reason', e)}")
except ValueError:
die(f"{path}: the reply was not JSON")
# Failures come back as HTTP 200 with the exception named in the body:
# {"error": "DispatcherAuthenticationException"} for a bad token, or the
# exception's name as a key with its details under it.
if isinstance(body, dict):
if body.get("error"):
die(f"{path}: {body['error']}" +
(" (the token was not accepted)" if "Authentication" in str(body["error"])
else ""))
for k in body:
if k.startswith("Dispatcher") and k.endswith("Exception"):
die(f"{path}: {k} {json.dumps(body[k])}")
return body
+33 -6
View File
@@ -23,6 +23,10 @@ Control is one command per line on stdin, events one per line on stdout:
topics <id>[,<id>...] the provisioning from now on (empty: none)
mo-fail <status> the next MO ends with this final_mo_status
mo-refuse the next PUT messageOriginate is refused (406)
mo-hold the next MO is taken but its final status is
withheld, as a modem waiting for a satellite,
until mo-release or a cancel
mo-release send the withheld final status
segment <n> ask for MO segments of n bytes (default 1446)
state <state> the operationalState from now on
quit
@@ -89,6 +93,8 @@ class FakeModem:
self.mo = None # the MO being received
self.mo_fail = None # final status for the next MO
self.mo_refuse = False
self.mo_hold = False # the next MO's final status waits for mo-release
self.held = None # (topic, id, status) withheld
self.imei = "300434030000000"
self.serial = "123456"
self.iccid = "8988169712345678901"
@@ -236,18 +242,35 @@ class FakeModem:
status = self.mo_fail or ("mo_ack_received" if good else "crc_error_in_transfer")
self.mo_fail = None
self.mo = None
self.send(299, "messageOriginateStatus", {"topic_id": mo["topic"], "message_id": mo["id"],
if self.mo_hold:
self.mo_hold = False
self.held = (mo["topic"], mo["id"], status)
return
self.mo_status(mo["topic"], mo["id"], status)
def mo_status(self, topic, mid, status):
self.send(299, "messageOriginateStatus", {"topic_id": topic, "message_id": mid,
"final_mo_status": status})
def on_put_messageOriginateStatus(self, body):
# Cancel: the library does not read the reply, only the status after.
self.send(200, "messageOriginateStatus", {})
if self.mo is not None and body.get("action") == "cancel":
if body.get("action") != "cancel":
return
if self.mo is not None:
mo, self.mo = self.mo, None
self.send(299, "messageOriginateStatus", {"topic_id": mo["topic"],
"message_id": mo["id"],
"final_mo_status":
"message_cancelled_pre_transit"})
self.mo_status(mo["topic"], mo["id"], "message_cancelled_pre_transit")
elif self.held is not None and self.held[1] == body.get("message_id"):
topic, mid, _ = self.held
self.held = None
self.mo_status(topic, mid, "message_cancelled_in_transit")
def release(self):
with self.lock:
if self.held is not None:
topic, mid, status = self.held
self.held = None
self.mo_status(topic, mid, status)
# --- what the network does --------------------------------------------
@@ -293,6 +316,10 @@ class FakeModem:
self.mo_fail = w[1]
elif cmd == "mo-refuse":
self.mo_refuse = True
elif cmd == "mo-hold":
self.mo_hold = True
elif cmd == "mo-release":
self.release()
elif cmd == "segment":
self.segment = max(1, min(MO_SEGMENT_MAX, int(w[1])))
elif cmd == "state":
+1 -1
View File
@@ -203,7 +203,7 @@ def zephyr(request):
cfg = request.config
if request.param == "none":
pytest.skip("no Zephyr target: --zephyr-exe or --board-console")
topics = getattr(request, "node").get_closest_marker("topics")
topics = request.node.get_closest_marker("topics")
topics = topics.args[0] if topics else "244"
if request.param == "board" and not cfg.getoption("--board-modem"):
pytest.skip("--board-console needs --board-modem")
+27
View File
@@ -85,6 +85,33 @@ def test_mo_with_a_bad_crc():
assert any(e.startswith("MOBAD 244") for e in w.events)
def mo_whole(w, payload):
whole = with_crc(payload)
w.put('PUT messageOriginate {"topic_id":244, "message_length":%d, "request_reference":1}'
% len(whole))
mid = w.lines()[0][2]["message_id"]
w.put('PUT messageOriginateSegment {"topic_id":244, "message_id":%d, "segment_length":%d,'
' "segment_start":0, "data":"%s"}' % (mid, len(whole), base64.b64encode(whole).decode()))
return mid
def test_held_mo_is_released_or_cancelled():
w = Wire()
w.m.control("mo-hold")
mid = mo_whole(w, b"held")
assert [t for _, t, _ in w.lines()] == ["messageOriginateSegment"] # no status yet
w.put('PUT messageOriginateStatus {"topic_id":244, "message_id":%d, "action":"cancel"}' % mid)
got = w.lines()
assert got[-1][1:] == ("messageOriginateStatus", {"topic_id": 244, "message_id": mid,
"final_mo_status":
"message_cancelled_in_transit"})
w.m.control("mo-hold")
mid = mo_whole(w, b"held-again")
w.lines()
w.m.control("mo-release")
assert w.lines()[-1][2]["final_mo_status"] == "mo_ack_received"
def test_unprovisioned_topic_is_refused():
w = Wire(topics=())
w.put('PUT messageOriginate {"topic_id":244, "message_length":7, "request_reference":1}')
+24
View File
@@ -78,6 +78,30 @@ def test_send_refused_by_the_modem(zephyr):
c.out.expect(r"send: -\d+ EIO")
def test_cancel_a_send_the_modem_sits_on(zephyr):
"""The modem took the message and said nothing more, as one waiting for
a satellite does; cancel frees the module, and a send then goes."""
c, f = zephyr
begin(zephyr)
f.cmd("mo-hold")
c.sh("rb9704 send 244 stuck")
c.out.expect(r"send: ok")
m = f.out.expect(r"^MO 244 (\d+) ")
c.sh("rb9704 info")
c.out.expect(r"info: -\d+ EBUSY")
c.sh("rb9704 status")
c.out.expect(r"one in flight: topic 244 id %s" % m.group(1))
c.sh("rb9704 cancel")
c.out.expect(r"cancel: ok")
c.out.expect(r"mo done topic 244 id %s result -\d+" % m.group(1))
c.sh("rb9704 cancel")
c.out.expect(r"cancel: -\d+ ENOENT")
c.sh("rb9704 send 244 after-cancel")
c.out.expect(r"send: ok")
f.out.expect(r"^MO 244 \d+ ")
c.out.expect(r"result 0")
def test_topic_below_64_is_refused_here(zephyr):
c, f = zephyr
begin(zephyr)
+23 -11
View File
@@ -34,6 +34,8 @@ static const char *err_name(int rc)
case EINPROGRESS: return "EINPROGRESS";
case ENOTSUP: return "ENOTSUP";
case EDEADLK: return "EDEADLK";
case ENOENT: return "ENOENT";
case ECANCELED: return "ECANCELED";
default: return "?";
}
}
@@ -90,8 +92,11 @@ static int cmd_status(const struct shell *sh, size_t argc, char **argv)
} else {
shell_print(sh, "topics provisioning not seen yet");
}
shell_print(sh, "mo %u sent, %u failed%s", s.mo_sent, s.mo_failed,
s.mo_in_flight ? ", one in flight" : "");
shell_print(sh, "mo %u sent, %u failed", s.mo_sent, s.mo_failed);
if (s.mo_in_flight) {
shell_print(sh, " one in flight: topic %u id %u, %lld s so far", s.mo_topic,
s.mo_id, (k_uptime_get() - s.mo_started_ms) / 1000);
}
shell_print(sh, "mt %u received, %u failed", s.mt_received, s.mt_failed);
shell_print(sh, "serial %u bytes dropped", s.rx_dropped);
return 0;
@@ -153,24 +158,30 @@ static int unhex(const char *s, uint8_t *out, size_t cap)
static int cmd_send(const struct shell *sh, size_t argc, char **argv)
{
static uint8_t buf[CONFIG_RB9704_MESSAGE_MAX];
/* An argument cannot be longer than the shell's line, and two hex
* digits make a byte. rb9704_send copies, so text goes as it is. */
static uint8_t hexbuf[CONFIG_SHELL_CMD_BUFF_SIZE / 2];
unsigned long topic = strtoul(argv[1], NULL, 10);
bool hex = strcmp(argv[0], "sendhex") == 0;
int len;
const uint8_t *data = (const uint8_t *)argv[2];
int len = strlen(argv[2]);
ARG_UNUSED(argc);
if (hex) {
len = unhex(argv[2], buf, sizeof(buf));
} else {
len = MIN(strlen(argv[2]), sizeof(buf));
memcpy(buf, argv[2], len);
if (strcmp(argv[0], "sendhex") == 0) {
len = unhex(argv[2], hexbuf, sizeof(hexbuf));
data = hexbuf;
}
if (len <= 0) {
shell_error(sh, "nothing to send (%d)", len);
return -EINVAL;
}
shell_print(sh, "%d bytes on topic %lu: this costs airtime", len, topic);
return report(sh, "send", rb9704_send((uint16_t)topic, buf, len, WAIT));
return report(sh, "send", rb9704_send((uint16_t)topic, data, len, WAIT));
}
static int cmd_cancel(const struct shell *sh, size_t argc, char **argv)
{
ARG_UNUSED(argc); ARG_UNUSED(argv);
return report(sh, "cancel", rb9704_cancel(WAIT));
}
static int cmd_spy(const struct shell *sh, size_t argc, char **argv)
@@ -192,6 +203,7 @@ SHELL_STATIC_SUBCMD_SET_CREATE(rb9704_cmds,
SHELL_CMD(signal, NULL, "signal bars now", cmd_signal),
SHELL_CMD_ARG(send, NULL, "send <topic> <text>: one message, costs airtime", cmd_send, 3, 0),
SHELL_CMD_ARG(sendhex, NULL, "sendhex <topic> <hex>: one message, costs airtime", cmd_send, 3, 0),
SHELL_CMD(cancel, NULL, "ask the modem to abandon the message in flight", cmd_cancel),
SHELL_CMD_ARG(spy, NULL, "spy on|off: print every JSPR line", cmd_spy, 2, 0),
SHELL_SUBCMD_SET_END);
+48 -6
View File
@@ -46,7 +46,7 @@
LOG_MODULE_REGISTER(rb9704, CONFIG_RB9704_LOG_LEVEL);
enum op { OP_BEGIN, OP_END, OP_SEND, OP_INFO, OP_SIGNAL, OP_POWER };
enum op { OP_BEGIN, OP_END, OP_SEND, OP_CANCEL, OP_INFO, OP_SIGNAL, OP_POWER };
enum req_state { REQ_PENDING, REQ_DONE, REQ_ABANDONED };
static struct {
@@ -74,6 +74,7 @@ static K_MUTEX_DEFINE(rb9704_st_lock);
static const struct rb9704_callbacks *app;
static bool mt_waiting;
static bool mo_cancel_asked; /* so the failure that follows reads -ECANCELED */
#if !IS_ENABLED(CONFIG_RB9704_POWER)
int rb9704_power_init(void)
@@ -99,14 +100,19 @@ bool rb9704_power_present(void)
static void cb_mo_started(const uint16_t id)
{
k_mutex_lock(&rb9704_st_lock, K_FOREVER);
st.mo_id = id;
st.mo_started_ms = k_uptime_get();
k_mutex_unlock(&rb9704_st_lock);
LOG_DBG("MO accepted by the modem: id %u", id);
}
static void cb_mo_complete(const uint16_t id, const rbMsgStatus_t status)
{
uint16_t topic;
int result = status == RB_MSG_STATUS_OK ? 0 : -EIO;
int result = status == RB_MSG_STATUS_OK ? 0 : mo_cancel_asked ? -ECANCELED : -EIO;
mo_cancel_asked = false;
k_mutex_lock(&rb9704_st_lock, K_FOREVER);
st.mo_in_flight = false;
topic = st.mo_topic;
@@ -116,7 +122,8 @@ static void cb_mo_complete(const uint16_t id, const rbMsgStatus_t status)
st.mo_failed++;
}
k_mutex_unlock(&rb9704_st_lock);
LOG_INF("MO %s: topic %u id %u", result == 0 ? "sent" : "failed", topic, id);
LOG_INF("MO %s: topic %u id %u",
result == 0 ? "sent" : result == -ECANCELED ? "cancelled" : "failed", topic, id);
if (app != NULL && app->mo_done != NULL) {
app->mo_done(topic, id, result, app->user);
}
@@ -180,6 +187,16 @@ static const rbCallbacks_t callbacks = {
/* --- the requests, on this thread --------------------------------------- */
/* Two of the library's globals, as of the commit west.yml pins (v1.0.1);
* neither is static there, and a bump of the pin should check they still
* are not. messageProvisioningInfo is its provisioning cache (op_send).
* moQueuedMessages counts the MOs it holds; rbBegin empties the queue but
* leaves the count, and a count above zero makes the next send queue
* without transmitting, so a begin after a stuck send would never send
* again. */
extern jsprMessageProvisioning_t messageProvisioningInfo;
extern uint16_t moQueuedMessages;
static int op_begin(void)
{
if (st.begun) {
@@ -199,8 +216,11 @@ static int op_begin(void)
if (!rbBegin("zephyr")) { /* the port name is unused: the UART is in devicetree */
return -EIO;
}
moQueuedMessages = 0; /* rbBegin emptied the queue; this is the count of it */
mo_cancel_asked = false;
k_mutex_lock(&rb9704_st_lock, K_FOREVER);
st.begun = true;
st.mo_in_flight = false;
k_mutex_unlock(&rb9704_st_lock);
return 0;
}
@@ -234,9 +254,7 @@ static bool topic_provisioned(uint16_t topic)
* keeps the answer for good, a miss included, so a modem provisioned after
* that would refuse every topic until a reboot. When the topic is not in
* what it kept, clear the cache and the library asks again: one free JSPR
* round trip. messageProvisioningInfo is the library's own global. */
extern jsprMessageProvisioning_t messageProvisioningInfo;
* round trip. */
static int op_send(void)
{
bool known;
@@ -271,6 +289,24 @@ static int op_send(void)
return 0;
}
/* The modem answers a cancel with a 299 messageOriginateStatus, which the
* library reads in rbPoll as a failed MO and removes from its queue; the
* flag set here turns that failure into -ECANCELED in cb_mo_complete. */
static int op_cancel(void)
{
if (!st.begun) {
return -ENOTCONN;
}
if (!st.mo_in_flight) {
return -ENOENT;
}
if (!rbCancelMessage(st.mo_topic, st.mo_id)) {
return -EIO;
}
mo_cancel_asked = true;
return 0;
}
static void copy_str(char *dst, size_t cap, const char *src)
{
if (src != NULL) {
@@ -349,6 +385,7 @@ static int dispatch(void)
case OP_BEGIN: return op_begin();
case OP_END: return op_end();
case OP_SEND: return op_send();
case OP_CANCEL: return op_cancel();
case OP_INFO: return op_info();
case OP_SIGNAL: return op_signal();
case OP_POWER: return op_power();
@@ -468,6 +505,11 @@ int rb9704_signal(k_timeout_t timeout)
return simple(OP_SIGNAL, timeout);
}
int rb9704_cancel(k_timeout_t timeout)
{
return simple(OP_CANCEL, timeout);
}
int rb9704_info(struct rb9704_info *out, k_timeout_t timeout)
{
bool abandoned;
+4
View File
@@ -38,6 +38,10 @@ static void isr(const struct device *dev, void *user)
uint32_t n = ring_buf_get_claim(back, &p, 64);
if (n == 0) {
/* The other port's ISR may have put bytes in `back`
* and re-enabled TX since the claim; they then wait
* for its next byte, which with two-way traffic is
* soon. Not worth a lock here. */
uart_irq_tx_disable(dev);
} else {
int w = uart_fifo_fill(dev, p, n);