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:
1 parent
509b9b5b6d
commit
f97fcab74b
13 files changed
+235
-34
No files matched your search
@@ -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"]
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
|
||||
@@ -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":
|
||||
|
||||
@@ -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")
|
||||
|
||||
@@ -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}')
|
||||
|
||||
@@ -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)
|
||||
|
||||
Reference in new issue
Block a user