4 Commits
Author SHA1 Message Date
scottp 4f5834a467 0.2.0: USB-C and the header share a port, and a real 9704 on the Stamp-C3
The 9704's USB-C goes through an FTDI chip to the modem's UART, on the
same lines as the header. With the cable plugged in, that chip drives
the modem's RX: a board on the header hears the modem but cannot reach
it, and the computer on USB gets no answer either. Unplug the USB-C and
power the 9704 from the header. The README says so beside the overlay
example, and docs/CLOUDLOOP.md lists it under "When begin fails".

The M5Stamp-C3 is the first microcontroller to run against a real 9704:
TX and RX only, the modem powered from the Stamp's 5 V pin. begin, info
and signal all answer, with nothing dropped. docs/boards/stamp_c3.md
has the power section and what has run.

no-control-pins.overlay takes P_EN, I_EN and I_BTD out of any board's
overlay at build time, for a modem on four wires. The modem node is
labelled rb9704 in every overlay so it can.

The module, the sample and the Python tools are 0.2.0.
2026-10-25 16:02:45 +11:00
scottp d08364ce58 Sample: the M5Stamp-C3, the shell over WiFi, and the control lines wired
overlay-wifi.conf puts the shell on telnet on any ESP32. At boot it joins
the network stored in flash with `wifi cred add`, and rejoins it after a
drop, for a board out under the sky with no USB.

The M5Stamp-C3 (ESP32-C3, RISC-V) has an overlay: the modem on uart1,
GPIO4 and GPIO5, with P_EN, I_EN and I_BTD on GPIO10, 6 and 7. Its RGB
LED, driven by spi2 on GPIO2, shows the modem's state, and its button
begins, asks for the signal and ends. docs/boards/stamp_c3.md has the
pins, the WiFi commands and the LED's colours. So far it has run WiFi
and telnet, not yet the modem.

The ESP32-S3-DevKitC, ESP32 DevKitC and NUCLEO-U575ZI-Q overlays now
wire the three control lines as well; the table is in docs/TESTING.md.

The README gives the Gitea home and the GitHub mirror, and the boards
as a table of CPU and what each has run.
2026-10-25 13:54:09 +11:00
scottp f97fcab74b 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.
2026-10-21 22:43:05 +11:00
scottp 509b9b5b6d Power pins on by default, and a request slot that came back
CONFIG_RB9704_POWER's default read a DT_COMPAT_ variable nothing defined,
so it was never y on its own and the pins went undriven; define it.

A request that ended in -ETIMEDOUT of its own accord, a begin whose
modem never signalled booted, looked to the caller like one it had
abandoned, so neither side gave the slot back and every later call got
-EAGAIN. submit() now reports abandonment apart from the result.

On that boot timeout the supply and enable pins are dropped again, so the
next attempt starts from off. The CLI's messages named paths from the
tree it was carried over from.

Checked on native_sim: the suite against the fake, and begin twice with
the pins on the GPIO emulator, where the second begin now times out
instead of returning EAGAIN.
2026-10-21 22:38:00 +11:00
36 changed files with 1129 additions and 72 deletions

No files matched your search

+45
View File
@@ -1,5 +1,50 @@
# Changes # Changes
## 0.2.0, 2026-10-25
- The shell sample over WiFi: `overlay-wifi.conf` puts the shell on
telnet on any ESP32, joining the network `wifi cred add` stored in
flash at boot and rejoining it after a drop.
- The shell sample on the M5Stamp-C3 (ESP32-C3, RISC-V): the modem on
`uart1`, GPIO4 and GPIO5. Its RGB LED shows the modem's state and its
button begins, asks for the signal and ends. `docs/boards/stamp_c3.md`
has its pins, the WiFi commands and the LED's colours.
- The sample's overlays for the M5Stamp-C3, ESP32-S3-DevKitC, ESP32
DevKitC and NUCLEO-U575ZI-Q wire P_EN, I_EN and I_BTD; the wiring table
is in `docs/TESTING.md`. `no-control-pins.overlay` takes them out at
build time, for a modem on TX and RX alone; the modem node is labelled
`rb9704` in every overlay so it can.
- A real 9704 on a microcontroller for the first time: the M5Stamp-C3,
on TX and RX, powered from the Stamp's 5 V. The 9704's USB-C and its
header share the modem's UART, and with USB-C plugged in a board on the
header cannot reach the modem; the README, `docs/CLOUDLOOP.md` and
`docs/boards/stamp_c3.md` say so.
- `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
option was set by hand.
- A request whose own result was `-ETIMEDOUT`, such as a begin whose modem
never signalled booted, lost the request slot for good and every later
call returned `-EAGAIN`. The caller's abandonment of a request is now
reported apart from the request's result.
- When the booted pin does not rise in time, the supply and enable pins are
dropped again, so the next attempt starts from off.
- `rb9704`: paths in its messages that belonged to the tree it came from.
## 0.1.0, 2026-10-09 ## 0.1.0, 2026-10-09
The first release. The first release.
+2
View File
@@ -26,6 +26,8 @@ config RB9704_MESSAGE_MAX
this module for the copy rb9704_send takes. 2 kB is three buffers of this module for the copy rb9704_send takes. 2 kB is three buffers of
2 kB; raise it as far as the RAM allows. 2 kB; raise it as far as the RAM allows.
DT_COMPAT_ROCK7_ROCKBLOCK_9704 := rock7,rockblock-9704
config RB9704_POWER config RB9704_POWER
bool "Drive the power pins from devicetree" bool "Drive the power pins from devicetree"
default y if $(dt_compat_any_has_prop,$(DT_COMPAT_ROCK7_ROCKBLOCK_9704),power-gpios) default y if $(dt_compat_any_has_prop,$(DT_COMPAT_ROCK7_ROCKBLOCK_9704),power-gpios)
+43 -5
View File
@@ -18,6 +18,13 @@ projects that send data home by satellite:
[OGLAS](https://oglas.au/), a fleet of LoRa sensors, repeaters and hubs. [OGLAS](https://oglas.au/), a fleet of LoRa sensors, repeaters and hubs.
Both run it, and neither is needed to use it. Both run it, and neither is needed to use it.
The source lives at
[gitea.sh3d.com.au/Sh3d/rockblock9704-zephyr](https://gitea.sh3d.com.au/Sh3d/rockblock9704-zephyr)
and is mirrored to
[github.com/SH3D/rockblock9704-zephyr](https://github.com/SH3D/rockblock9704-zephyr).
Open issues and pull requests on the GitHub mirror; the Gitea instance does
not allow public sign-ups.
## Ground Control's library ## Ground Control's library
This module does not reimplement or fork the protocol. Ground Control's This module does not reimplement or fork the protocol. Ground Control's
@@ -49,6 +56,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 the reader discards lines it is not waiting for. Info and signal
requests are refused with `-EBUSY` while a message is moving. requests are refused with `-EBUSY` while a message is moving.
- **No locking.** Every library call is on the worker thread. - **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: 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 `setState` waits for a misspelt target, a line with no status code reads
@@ -63,7 +76,7 @@ library, pinned, at the path the module looks in, and nothing else:
```yaml ```yaml
- name: rockblock9704-zephyr - name: rockblock9704-zephyr
url: https://github.com/SH3D/rockblock9704-zephyr url: https://github.com/SH3D/rockblock9704-zephyr
revision: v0.1.0 revision: v0.2.0
path: modules/lib/rockblock9704-zephyr path: modules/lib/rockblock9704-zephyr
import: import:
name-allowlist: name-allowlist:
@@ -87,6 +100,15 @@ without them the modem is taken to be powered:
}; };
``` ```
**USB-C and the header are the same serial port.** The 9704's USB-C goes
through an FTDI chip to the modem's UART, on the same lines as the
header's TX and RX. With the USB-C cable plugged in, that chip drives the
modem's RX, and a board on the header can hear the modem but not reach
it: `rb9704_begin` fails with `-EIO`, and the computer on USB gets no
answer either. Unplug the USB-C and power the 9704 from the header; a
board's 5 V pin will do, as the modem draws a few hundred mA
(`docs/boards/stamp_c3.md`).
`CONFIG_RB9704` follows the node. Then `<rb9704/rb9704.h>`: `CONFIG_RB9704` follows the node. Then `<rb9704/rb9704.h>`:
```c ```c
@@ -106,6 +128,7 @@ rb9704_set_callbacks(&cb);
rb9704_begin(K_SECONDS(30)); 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_SECONDS(10)); /* costs airtime */
rb9704_send(RB9704_TOPIC_RAW, buf, len, K_NO_WAIT); /* queues, never blocks */ 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 Every request takes a timeout and waits no longer; with `K_NO_WAIT` a send
@@ -131,6 +154,7 @@ rb9704 status what is known, without asking the modem
rb9704 info IMEI, serial, versions, ICCID, SIM, temperature rb9704 info IMEI, serial, versions, ICCID, SIM, temperature
rb9704 signal bars now rb9704 signal bars now
rb9704 send <topic> <text> | sendhex <topic> <hex> costs airtime 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 rb9704 spy on|off every JSPR line, both ways
``` ```
@@ -161,10 +185,23 @@ real 9704 from Python and from `native_sim`.
## Boards ## Boards
Any board with a free UART. The sample has overlays for `native_sim`, Any board with a free UART, on any architecture Zephyr runs on. The
NUCLEO-U575ZI-Q, Seeed XIAO ESP32S3, ESP32-S3-DevKitC, ESP32 DevKitC and library is portable C and the module has nothing tied to one CPU. The
LilyGO T3-S3 (an out-of-tree board in OGLAST2: build with its sample has overlays for:
`-DBOARD_ROOT`). It has run on the first three; all six build.
| Board | CPU | Run on |
| --- | --- | --- |
| `native_sim` | the host (x86-64) | yes |
| NUCLEO-U575ZI-Q | STM32U5, Arm Cortex-M33 | yes |
| Seeed XIAO ESP32S3 | ESP32-S3, Xtensa | yes |
| M5Stamp-C3 | ESP32-C3, RISC-V | yes, a real 9704 on TX and RX; `docs/boards/stamp_c3.md` |
| ESP32-S3-DevKitC | ESP32-S3, Xtensa | builds |
| ESP32 DevKitC | ESP32, Xtensa | builds |
| LilyGO T3-S3 | ESP32-S3, Xtensa | builds; an out-of-tree board in OGLAST2, with its `-DBOARD_ROOT` |
On an ESP32, `-DEXTRA_CONF_FILE=overlay-wifi.conf` puts the shell on
telnet as well, for a board out under the sky with no USB
(`docs/TESTING.md`).
## Layout ## Layout
@@ -179,6 +216,7 @@ python/ rb9704, rb9704-fake, the tests
docs/JSPR.md the protocol as the library speaks it docs/JSPR.md the protocol as the library speaks it
docs/CLOUDLOOP.md account to first message docs/CLOUDLOOP.md account to first message
docs/TESTING.md the tests and how to run them docs/TESTING.md the tests and how to run them
docs/boards/ notes for one board each: pins, setup
west.yml the pins west.yml the pins
``` ```
+8 -1
View File
@@ -18,7 +18,11 @@ have not been tried yet.
- **Its USB-C port.** An FTDI FT234XD (USB id `0403:6015`) bridges it to - **Its USB-C port.** An FTDI FT234XD (USB id `0403:6015`) bridges it to
the modem's UART, and the port also powers the board. It needs a port the modem's UART, and the port also powers the board. It needs a port
that supplies 500 mA at 4.0 to 5.3 V; an unpowered hub is not supported. that supplies 500 mA at 4.0 to 5.3 V; an unpowered hub is not supported.
The supercapacitor takes about 40 s to charge from USB. LEDs: red PWR is The supercapacitor takes about 40 s to charge from USB. The FTDI is on
the same UART lines as the 10-way header, so with USB-C plugged in a
microcontroller on the header can hear the modem but not reach it; a
board on the header powers the 9704 from the header, with USB-C
unplugged (`boards/stamp_c3.md`). LEDs: red PWR is
input voltage present, green RDY is the modem powered and booted, blue input voltage present, green RDY is the modem powered and booted, blue
XMT is transmitting. XMT is transmitting.
- **The library.** Ground Control's C library (MIT) is what this - **The library.** Ground Control's C library (MIT) is what this
@@ -184,6 +188,9 @@ version, SIM, operational state). In order of likelihood:
blocks it. The `--udev` rule stops the first. blocks it. The `--udev` rule stops the first.
- **Not in `dialout`.** `install.sh` checks; `sudo usermod -aG dialout - **Not in `dialout`.** `install.sh` checks; `sudo usermod -aG dialout
$USER` and log in again. $USER` and log in again.
- **USB-C and the header at once.** A board on the header with the
USB-C cable plugged in: the FTDI drives the modem's RX, and neither side
gets an answer. Unplug one.
- **Not booted.** No green RDY: the port gives too little current (a hub, - **Not booted.** No green RDY: the port gives too little current (a hub,
a front-panel port), or the supercapacitor is still charging. a front-panel port), or the supercapacitor is still charging.
- **Something odd.** `rb9704 jspr --setup 'GET hwInfo {}' - **Something odd.** `rb9704 jspr --setup 'GET hwInfo {}'
+6 -1
View File
@@ -747,7 +747,12 @@ Everything else is ignored.
ignores the failed add (`queued >= 0`, `src/rockblock_9704.c:400`) and 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 **re-sends the old stuck message** with a new `PUT messageOriginate`. A late
`299 messageOriginateStatus` for the old id, read by any later `rbPoll`, `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 9. **`200 messageOriginate` alone means started**, whatever
`message_response` says (4.3 step 2). `message_response` says (4.3 step 2).
10. **`rbReceiveMessage` has no timeout** once an MT has been announced. 10. **`rbReceiveMessage` has no timeout** once an MT has been announced.
+71
View File
@@ -82,6 +82,72 @@ round:
The ESP32-S3 sits in its ROM loader after `west flash` until it is reset; The ESP32-S3 sits in its ROM loader after `west flash` until it is reset;
toggle RTS on its USB port, or press reset, before the tests. toggle RTS on its USB port, or press reset, before the tests.
## Out of doors: the shell over WiFi
A real modem needs the sky, and the sky is rarely where the USB cable
reaches. `samples/shell/overlay-wifi.conf` puts the same shell on telnet,
on any ESP32 board, so the board needs only power:
```sh
west build -b stamp_c3 samples/shell -- -DEXTRA_CONF_FILE=overlay-wifi.conf
west flash
```
Once, on the USB console, store the network; it is kept in flash:
```
wifi cred add -s "<SSID>" -k 1 -p "<password>"
```
At every boot after, the board joins it, logs `address 192.168.1.50:
telnet 192.168.1.50`, and rejoins after a drop. A network added after boot
is joined within 30 s. `wifi cred list` and `wifi cred delete <SSID>` look
after the stored list; `net iface` shows the address again.
```sh
telnet 192.168.1.50
rb9704 begin
rb9704 spy on
rb9704 info
```
Telnet has no password and no encryption, and `rb9704 send` costs
airtime: use it on a network you trust.
The Linux `telnet` client stays in line mode, where the up arrow and line
editing do nothing: `Ctrl-]` then `mode character` fixes it, or connect
with `socat -,rawer,escape=0x1d TCP:<address>:23`.
On the M5Stamp-C3 the board's RGB LED shows the modem's state and its
button begins and ends it; `boards/stamp_c3.md` has the table, the pins
and the WiFi commands.
### Wiring
The board overlays for the M5Stamp-C3, ESP32-S3-DevKitC, ESP32 DevKitC
and NUCLEO-U575ZI-Q wire all three control lines, so `rb9704 begin`
powers the modem up in order and waits for it to say it has booted.
| 9704 | M5Stamp-C3 | ESP32-S3-DevKitC | ESP32 DevKitC | NUCLEO-U575ZI-Q |
| --- | --- | --- | --- | --- |
| RX (board TX) | GPIO4 | GPIO17 | GPIO17 | PD8 |
| TX (board RX) | GPIO5 | GPIO18 | GPIO16 | PD9 |
| P_EN | GPIO10 | GPIO6 | GPIO27 | PF15 (D2) |
| I_EN | GPIO6 | GPIO4 | GPIO25 | PF14 (D4) |
| I_BTD | GPIO7 | GPIO5 | GPIO26 | PF13 (D7) |
| GND | GND | GND | GND | GND |
The modem's supply is its own, at the voltage and peak current Ground
Control's manual gives, not the board's 3.3 V regulator. With `booted-gpios` in the overlay,
`rb9704 begin` waits up to 30 s for I_BTD. A fake modem on a USB-serial
adapter in place of the 9704 has no I_BTD, so tie the board's I_BTD pin
to 3.3 V for those runs, or build with the rig overlays, which have no
control lines.
For a modem on TX and RX alone, `samples/shell/no-control-pins.overlay`
takes the three lines out of any board's overlay at build time:
`-DEXTRA_DTC_OVERLAY_FILE=no-control-pins.overlay`.
## What has passed ## What has passed
On 2026-10-09, Zephyr v4.4.0, Ground Control's library v1.0.1, the On 2026-10-09, Zephyr v4.4.0, Ground Control's library v1.0.1, the
@@ -95,6 +161,11 @@ binding 1.0.2:
| NUCLEO-U575ZI-Q through the rig | 12 | all pass | | NUCLEO-U575ZI-Q through the rig | 12 | all pass |
| a real 9704 (firmware v1.5.14), binding and native_sim, free checks | 2 | all pass | | a real 9704 (firmware v1.5.14), binding and native_sim, free checks | 2 | all pass |
On 2026-10-25, the M5Stamp-C3 (ESP32-C3, RISC-V) with the shell over
WiFi, and a real 9704 on its header pins, TX and RX only, powered from
the Stamp's 5V: `begin`, `info` and `signal` all answer, nothing dropped
(`boards/stamp_c3.md`).
Not yet: a message through a real modem and satellite, which costs Not yet: a message through a real modem and satellite, which costs
airtime and needs the sky (`CLOUDLOOP.md`, "The order to test in"), and airtime and needs the sky (`CLOUDLOOP.md`, "The order to test in"), and
the power pins on a board that has them wired. the power pins on a board that has them wired.
+176
View File
@@ -0,0 +1,176 @@
# M5Stamp-C3
M5Stack's Stamp-C3: an ESP32-C3, a single RISC-V core with WiFi and
400 kB of RAM, on a small board with a USB-C serial bridge, an RGB LED
and a button. Zephyr's name for it is `stamp_c3`, and it is in Zephyr
upstream. It is the board for taking the modem outside: powered from a
battery or a supply, reached over WiFi, and showing on its LED how things
stand.
The overlay is `samples/shell/boards/stamp_c3.overlay`, with
`stamp_c3.conf` beside it for the LED and button.
## Pins
| Stamp-C3 | Signal | Notes |
| --- | --- | --- |
| GPIO4 | `uart1` TX → 9704 RX | 230400 8N1 |
| GPIO5 | `uart1` RX ← 9704 TX | |
| GPIO10 | P_EN | the supply; without it the module drives none of the three |
| GPIO6 | I_EN | the modem enable, 10 ms after P_EN |
| GPIO7 | I_BTD | `rb9704 begin` waits up to 30 s for it to go high |
| GND | GND | |
| 5V | the 9704's supply in | the Stamp's USB-C supply, passed through |
| GPIO2 | the RGB LED, an SK6812 | on the board |
| GPIO3 | the button | on the board |
| GPIO20, GPIO21 | `uart0`, the console | through the USB-C bridge |
Kept clear: GPIO8 and GPIO9 (strapping pins, and the board's I2C) and
GPIO18 and GPIO19 (USB).
## Power: the Stamp's 5V, and the 9704's USB-C unplugged
The 9704's header UART and its USB-C port are the same serial lines. With
USB-C plugged in, the 9704's FTDI chip is powered and drives the modem's
RX, and a board on the header cannot talk over it: the modem answers
nobody, the computer on USB included. Its TX still reaches the header, so
a board can listen alongside USB, but not send.
So the 9704 is powered from the header with its USB-C unplugged. The
Stamp's 5V pin does it: the modem draws a few hundred mA, and its
supercapacitor charges slowly, about 40 s to the green RDY LED. Both
boards then run from the Stamp's USB-C; on a laptop's 500 mA port a
Stamp that resets by itself while the 9704 charges is the supply sagging,
and a charger or a powered hub gives the margin.
The control lines are optional. With fewer wired, take the matching lines
out of the overlay's `rockblock` node, or `rb9704 begin` waits on a pin
that is not there:
- None: four wires, and the modem is taken to be powered. No edit
needed: `-DEXTRA_DTC_OVERLAY_FILE=no-control-pins.overlay` takes all
three out at build time (below).
- P_EN only: `rb9704 power off` and `power on` over telnet restart a
modem that has hung, with nobody walking out to it. The one most worth
wiring.
- I_BTD as well: a slow or failed boot is a clear timeout, not JSPR
errors after a fixed 4 s (`boot-delay-ms`).
- I_EN adds little here. The ESP32-C3's ROM prints at reset on GPIO21,
the console, so nothing reaches the modem's pins before Zephyr runs.
## Build and flash
From a west workspace that has this module:
```sh
west build -b stamp_c3 samples/shell -- -DEXTRA_CONF_FILE=overlay-wifi.conf
west flash
```
Without `-DEXTRA_CONF_FILE=overlay-wifi.conf` the shell is on the USB
console only, and the LED and button work the same.
TX and RX only, no control lines:
```sh
west build -b stamp_c3 samples/shell -- -DEXTRA_CONF_FILE=overlay-wifi.conf \
-DEXTRA_DTC_OVERLAY_FILE=no-control-pins.overlay
```
With no P_EN, the long press on the button ends without turning anything
off, and `rb9704 power` answers `-ENOTSUP`.
## WiFi
Once, on the USB console (115200), store the network. It is kept in flash
across reboots and reflashing:
```
wifi cred add -s "<SSID>" -k 1 -p "<password>"
```
`-k 1` is WPA2-PSK; `-k 0` is an open network. The board joins at every
boot after, tries again every 30 s while the network is away, and logs:
```
address 192.168.1.50: telnet 192.168.1.50
```
| Command | |
| --- | --- |
| `wifi cred list` | the stored networks |
| `wifi cred delete <SSID>` | forget one |
| `wifi cred auto_connect` | join a stored network now |
| `wifi status` | the network joined, the channel, the signal |
| `wifi scan` | the networks in range |
| `net iface` | the address, again |
## Telnet
```sh
telnet 192.168.1.50
```
Zephyr's telnet server does not offer character mode, so the client stays
in line mode, and the up arrow, Tab and line editing do nothing. Ask for
it: `Ctrl-]`, then `mode character`. For every session, `~/.telnetrc`:
```
192.168.1.50
mode character
```
Or raw, with every key going to the shell and `Ctrl-]` to leave:
```sh
socat -,rawer,escape=0x1d TCP:192.168.1.50:23
```
Telnet has no password and no encryption, and `rb9704 send` costs
airtime: use it on a network you trust.
## The LED and button
`samples/shell/src/indicator.c`.
| LED | Meaning |
| --- | --- |
| blue | not begun |
| red / yellow / green | begun: no signal or no satellite / 1-2 bars / 3-5 bars |
| magenta | a message is with the modem, on its way |
| green flash, 1 s | a message went |
| red flash, 2 s | a message, or a button action, failed |
| cyan flash, 2 s | a message arrived |
| white, fast blink | a button action is running |
| slow blink of any of the above | no WiFi: telnet will not reach it |
| Button | |
| --- | --- |
| short press | not begun: `rb9704 begin`. Begun: ask for the signal |
| 2 s or more | end, and the supply off when P_EN is wired |
Nothing on the button costs airtime. The LED runs at 24 of 255
(`LEVEL` in `indicator.c`).
## First power-up
1. Without the modem: the LED blinks blue until WiFi joins, then stays
blue. A short press runs `begin` with nothing there: white, then a red
flash.
2. With the modem wired: a short press goes white, then red, yellow or
green with the signal.
3. Over telnet: `rb9704 spy on`, `rb9704 info`, `rb9704 signal`. All
free.
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.
## What has run
| | |
| --- | --- |
| WiFi, the stored network, telnet | works (2026-10-24) |
| a real 9704 on TX and RX, powered from the Stamp's 5V: `begin`, `info`, `signal` | works (2026-10-25) |
| the same with the 9704's USB-C plugged in | fails: the FTDI holds the modem's RX |
| the LED and button | built, not yet run |
| P_EN, I_EN, I_BTD | not yet wired |
+16 -1
View File
@@ -81,6 +81,8 @@ struct rb9704_status {
/* messages */ /* messages */
bool mo_in_flight; bool mo_in_flight;
uint16_t mo_topic; 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 mo_sent, mo_failed;
uint32_t mt_received, mt_failed; uint32_t mt_received, mt_failed;
/* the serial port */ /* the serial port */
@@ -99,7 +101,8 @@ struct rb9704_mt {
* blocking rb9704_* request from one: the worker is the thread that would * blocking rb9704_* request from one: the worker is the thread that would
* have to answer it. Any member may be NULL. */ * have to answer it. Any member may be NULL. */
struct rb9704_callbacks { 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); 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 /* An MT has arrived whole. It is acknowledged to the modem after this
* returns, so copy what is wanted. */ * 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); 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. */ /* Ask the modem who it is. Free, milliseconds. */
int rb9704_info(struct rb9704_info *out, k_timeout_t timeout); int rb9704_info(struct rb9704_info *out, k_timeout_t timeout);
+2 -2
View File
@@ -4,10 +4,10 @@ build-backend = "setuptools.build_meta"
[project] [project]
name = "rockblock9704-tools" name = "rockblock9704-tools"
version = "0.1.0" version = "0.2.0"
description = "Host tools for the RockBLOCK 9704: a command line for the modem and Cloudloop, and a fake modem for testing" description = "Host tools for the RockBLOCK 9704: a command line for the modem and Cloudloop, and a fake modem for testing"
readme = "README.md" readme = "README.md"
license = { text = "MIT" } license = "MIT"
authors = [{ name = "Scott Penrose", email = "scottp@dd.com.au" }] authors = [{ name = "Scott Penrose", email = "scottp@dd.com.au" }]
requires-python = ">=3.10" requires-python = ">=3.10"
dependencies = ["pyserial>=3.5"] dependencies = ["pyserial>=3.5"]
+1 -1
View File
@@ -2,4 +2,4 @@
# Copyright (c) 2026 Scott Penrose <scottp@dd.com.au> # Copyright (c) 2026 Scott Penrose <scottp@dd.com.au>
"""Host tools for the RockBLOCK 9704.""" """Host tools for the RockBLOCK 9704."""
__version__ = "0.1.0" __version__ = "0.2.0"
+33 -10
View File
@@ -38,6 +38,7 @@ import json
import os import os
import sys import sys
import time import time
import urllib.error
import urllib.parse import urllib.parse
import urllib.request import urllib.request
@@ -76,7 +77,7 @@ def find_ports():
try: try:
from serial.tools import list_ports from serial.tools import list_ports
except ImportError: except ImportError:
die("pyserial is missing; run host/rockblock/install.sh") die("pyserial is missing; run python/install.sh")
out = [] out = []
for p in list_ports.comports(): for p in list_ports.comports():
is_rb = p.vid == FTDI_VID and p.pid == FT234X_PID is_rb = p.vid == FTDI_VID and p.pid == FT234X_PID
@@ -95,7 +96,7 @@ def pick_port(arg):
return rbs[0].device return rbs[0].device
if not rbs: if not rbs:
die("no FTDI FT234XD attached; plug the 9704's USB-C in, or give -p PORT " die("no FTDI FT234XD attached; plug the 9704's USB-C in, or give -p PORT "
"(rb9704.py ports lists them)") "(rb9704 ports lists them)")
die("more than one FT234XD attached (" + ", ".join(p.device for p in rbs) + die("more than one FT234XD attached (" + ", ".join(p.device for p in rbs) +
"); give -p PORT") "); give -p PORT")
@@ -122,7 +123,7 @@ def open_rb(port):
try: try:
from rockblock9704 import RockBlock9704 from rockblock9704 import RockBlock9704
except ImportError: except ImportError:
die("rockblock9704 is missing; run host/rockblock/install.sh") die("rockblock9704 is missing; run python/install.sh")
rb = RockBlock9704() rb = RockBlock9704()
if not rb.begin(port): if not rb.begin(port):
die(f"begin({port}) failed: wrong port, modem not booted (green RDY " die(f"begin({port}) failed: wrong port, modem not booted (green RDY "
@@ -311,9 +312,9 @@ def cmd_listen(a):
def cmd_session(a): def cmd_session(a):
"""One MO, then listen until a.quiet seconds pass with no new MT. This is """One MO, then listen until a.quiet seconds pass with no new MT: a
the 9704 session designed in docs/PLAN.md, "The session", run from the buoy's or a hub's session, run from the host so the quiet window can
host so the quiet window can be chosen from what is seen.""" be chosen from what is seen."""
data = payload(a) data = payload(a)
port = pick_port(a.port) port = pick_port(a.port)
confirm(data, a.topic, a.yes) confirm(data, a.topic, a.yes)
@@ -361,7 +362,10 @@ class Jspr:
def __init__(self, port): def __init__(self, port):
import serial import serial
try:
self.s = serial.Serial(port, BAUD, timeout=0.1) self.s = serial.Serial(port, BAUD, timeout=0.1)
except serial.SerialException as e:
die(f"cannot open {port}: {e}")
self.buf = b"" self.buf = b""
self.s.reset_input_buffer() self.s.reset_input_buffer()
@@ -382,7 +386,10 @@ class Jspr:
def cmd(self, line, target=None, secs=3.0, show=False): def cmd(self, line, target=None, secs=3.0, show=False):
"""Send a line, return the first response for its target. Anything """Send a line, return the first response for its target. Anything
else that arrives meanwhile is shown as it goes past.""" 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()) self.s.write((line + "\r").encode())
for code, tgt, js, raw in self.lines(secs): for code, tgt, js, raw in self.lines(secs):
if show or tgt != target or code == 299: if show or tgt != target or code == 299:
@@ -494,11 +501,27 @@ def api(path, **params):
them, in the query string.""" them, in the query string."""
q = urllib.parse.urlencode({"token": token(), **params}) q = urllib.parse.urlencode({"token": token(), **params})
req = urllib.request.Request(f"{CLOUDLOOP}{path}?{q}", data=b"", method="POST") req = urllib.request.Request(f"{CLOUDLOOP}{path}?{q}", data=b"", method="POST")
try:
with urllib.request.urlopen(req, timeout=30) as r: with urllib.request.urlopen(req, timeout=30) as r:
body = json.load(r) body = json.load(r)
for k in ("DispatcherException", "DispatcherValidationException"): except urllib.error.HTTPError as e:
if k in body: die(f"{path}: HTTP {e.code} {e.reason}" +
die(f"{path}: {json.dumps(body[k])}") (": 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 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) topics <id>[,<id>...] the provisioning from now on (empty: none)
mo-fail <status> the next MO ends with this final_mo_status mo-fail <status> the next MO ends with this final_mo_status
mo-refuse the next PUT messageOriginate is refused (406) 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) segment <n> ask for MO segments of n bytes (default 1446)
state <state> the operationalState from now on state <state> the operationalState from now on
quit quit
@@ -89,6 +93,8 @@ class FakeModem:
self.mo = None # the MO being received self.mo = None # the MO being received
self.mo_fail = None # final status for the next MO self.mo_fail = None # final status for the next MO
self.mo_refuse = False 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.imei = "300434030000000"
self.serial = "123456" self.serial = "123456"
self.iccid = "8988169712345678901" self.iccid = "8988169712345678901"
@@ -236,18 +242,35 @@ class FakeModem:
status = self.mo_fail or ("mo_ack_received" if good else "crc_error_in_transfer") status = self.mo_fail or ("mo_ack_received" if good else "crc_error_in_transfer")
self.mo_fail = None self.mo_fail = None
self.mo = 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}) "final_mo_status": status})
def on_put_messageOriginateStatus(self, body): def on_put_messageOriginateStatus(self, body):
# Cancel: the library does not read the reply, only the status after. # Cancel: the library does not read the reply, only the status after.
self.send(200, "messageOriginateStatus", {}) 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 mo, self.mo = self.mo, None
self.send(299, "messageOriginateStatus", {"topic_id": mo["topic"], self.mo_status(mo["topic"], mo["id"], "message_cancelled_pre_transit")
"message_id": mo["id"], elif self.held is not None and self.held[1] == body.get("message_id"):
"final_mo_status": topic, mid, _ = self.held
"message_cancelled_pre_transit"}) 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 -------------------------------------------- # --- what the network does --------------------------------------------
@@ -293,6 +316,10 @@ class FakeModem:
self.mo_fail = w[1] self.mo_fail = w[1]
elif cmd == "mo-refuse": elif cmd == "mo-refuse":
self.mo_refuse = True self.mo_refuse = True
elif cmd == "mo-hold":
self.mo_hold = True
elif cmd == "mo-release":
self.release()
elif cmd == "segment": elif cmd == "segment":
self.segment = max(1, min(MO_SEGMENT_MAX, int(w[1]))) self.segment = max(1, min(MO_SEGMENT_MAX, int(w[1])))
elif cmd == "state": elif cmd == "state":
+1 -1
View File
@@ -203,7 +203,7 @@ def zephyr(request):
cfg = request.config cfg = request.config
if request.param == "none": if request.param == "none":
pytest.skip("no Zephyr target: --zephyr-exe or --board-console") 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" topics = topics.args[0] if topics else "244"
if request.param == "board" and not cfg.getoption("--board-modem"): if request.param == "board" and not cfg.getoption("--board-modem"):
pytest.skip("--board-console needs --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) 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(): def test_unprovisioned_topic_is_refused():
w = Wire(topics=()) w = Wire(topics=())
w.put('PUT messageOriginate {"topic_id":244, "message_length":7, "request_reference":1}') 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") 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): def test_topic_below_64_is_refused_here(zephyr):
c, f = zephyr c, f = zephyr
begin(zephyr) begin(zephyr)
+4
View File
@@ -4,3 +4,7 @@ cmake_minimum_required(VERSION 3.20.0)
find_package(Zephyr REQUIRED HINTS $ENV{ZEPHYR_BASE}) find_package(Zephyr REQUIRED HINTS $ENV{ZEPHYR_BASE})
project(rb9704_shell) project(rb9704_shell)
target_sources(app PRIVATE src/main.c) target_sources(app PRIVATE src/main.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.*).
target_sources_ifdef(CONFIG_LED_STRIP app PRIVATE src/indicator.c)
@@ -1,12 +1,16 @@
/* ESP32 DevKitC (the original ESP32): the modem on uart2, GPIO17 (TX) and /* ESP32 DevKitC (the original ESP32): the modem on uart2, GPIO17 (TX) and
* GPIO16 (RX). The console stays on uart0 through the board's USB bridge. * GPIO16 (RX), with its control lines on GPIO27 (P_EN), GPIO25 (I_EN) and
* GPIO26 (I_BTD). The console stays on uart0 through the board's USB bridge.
* On WROVER modules GPIO16 and GPIO17 belong to the PSRAM: use a WROOM * On WROVER modules GPIO16 and GPIO17 belong to the PSRAM: use a WROOM
* module, or move uart2's pins here. */ * module, or move uart2's pins here. */
&uart2 { &uart2 {
current-speed = <230400>; current-speed = <230400>;
status = "okay"; status = "okay";
rockblock { rb9704: rockblock {
compatible = "rock7,rockblock-9704"; compatible = "rock7,rockblock-9704";
power-gpios = <&gpio0 27 GPIO_ACTIVE_HIGH>; /* P_EN */
iridium-enable-gpios = <&gpio0 25 GPIO_ACTIVE_HIGH>; /* I_EN */
booted-gpios = <&gpio0 26 GPIO_ACTIVE_HIGH>; /* I_BTD */
}; };
}; };
@@ -1,4 +1,5 @@
/* ESP32-S3-DevKitC: the modem on uart1, GPIO17 (TX) and GPIO18 (RX). */ /* ESP32-S3-DevKitC: the modem on uart1, GPIO17 (TX) and GPIO18 (RX), with
* its control lines on GPIO6 (P_EN), GPIO4 (I_EN) and GPIO5 (I_BTD). */
&pinctrl { &pinctrl {
uart1_rb9704: uart1_rb9704 { uart1_rb9704: uart1_rb9704 {
group1 { group1 {
@@ -18,7 +19,10 @@
current-speed = <230400>; current-speed = <230400>;
status = "okay"; status = "okay";
rockblock { rb9704: rockblock {
compatible = "rock7,rockblock-9704"; compatible = "rock7,rockblock-9704";
power-gpios = <&gpio0 6 GPIO_ACTIVE_HIGH>; /* P_EN */
iridium-enable-gpios = <&gpio0 4 GPIO_ACTIVE_HIGH>; /* I_EN */
booted-gpios = <&gpio0 5 GPIO_ACTIVE_HIGH>; /* I_BTD */
}; };
}; };
@@ -8,7 +8,7 @@
current-speed = <230400>; current-speed = <230400>;
status = "okay"; status = "okay";
rockblock { rb9704: rockblock {
compatible = "rock7,rockblock-9704"; compatible = "rock7,rockblock-9704";
}; };
}; };
+1 -1
View File
@@ -7,7 +7,7 @@
current-speed = <230400>; current-speed = <230400>;
status = "okay"; status = "okay";
rockblock { rb9704: rockblock {
compatible = "rock7,rockblock-9704"; compatible = "rock7,rockblock-9704";
}; };
}; };
@@ -7,7 +7,7 @@
current-speed = <230400>; current-speed = <230400>;
status = "okay"; status = "okay";
rockblock { rb9704: rockblock {
compatible = "rock7,rockblock-9704"; compatible = "rock7,rockblock-9704";
}; };
}; };
+9 -3
View File
@@ -1,6 +1,9 @@
/* NUCLEO-U575ZI-Q: the modem on USART3, PD8 (TX) and PD9 (RX). /* NUCLEO-U575ZI-Q: the modem on USART3, PD8 (TX) and PD9 (RX), with its
* control lines on the Arduino header: D2, PF15 (P_EN); D4, PF14 (I_EN);
* D7, PF13 (I_BTD). PB0 would match the README's example, but the board
* gives it to adc4.
* *
* On this board those pins share solder bridges with the ST-LINK's virtual * On this board PD8 and PD9 share solder bridges with the ST-LINK's virtual
* COM port; check UM2861 before wiring. To test without a modem, the fake * COM port; check UM2861 before wiring. To test without a modem, the fake
* modem (python/rb9704tools/fakemodem.py) on a 3.3 V USB-serial adapter * modem (python/rb9704tools/fakemodem.py) on a 3.3 V USB-serial adapter
* wired to the same pins stands in for it. */ * wired to the same pins stands in for it. */
@@ -10,7 +13,10 @@
current-speed = <230400>; current-speed = <230400>;
status = "okay"; status = "okay";
rockblock { rb9704: rockblock {
compatible = "rock7,rockblock-9704"; compatible = "rock7,rockblock-9704";
power-gpios = <&gpiof 15 GPIO_ACTIVE_HIGH>; /* P_EN */
iridium-enable-gpios = <&gpiof 14 GPIO_ACTIVE_HIGH>; /* I_EN */
booted-gpios = <&gpiof 13 GPIO_ACTIVE_HIGH>; /* I_BTD */
}; };
}; };
+4
View File
@@ -0,0 +1,4 @@
# The RGB LED and the button (src/indicator.c).
CONFIG_SPI=y
CONFIG_LED_STRIP=y
CONFIG_INPUT=y
+74
View File
@@ -0,0 +1,74 @@
/* M5Stamp-C3: the modem on uart1, GPIO4 (TX) and GPIO5 (RX), with its
* three control lines on GPIO10 (P_EN), GPIO6 (I_EN) and GPIO7 (I_BTD). The
* console stays on uart0 through the board's USB bridge; with
* overlay-wifi.conf the shell is on telnet as well, for a board with power
* and no USB.
*
* The board's RGB LED, an SK6812 on GPIO2, is driven by spi2 with MOSI
* alone on that pin (src/indicator.c); the board's own spi2 pins put SCLK
* on GPIO4, the modem's TX. The button on GPIO3 is the board's sw0.
*
* Kept clear: GPIO8 and 9 (strapping, and the I2C), GPIO18 and 19 (USB),
* GPIO20 and 21 (the console).
*
* docs/boards/stamp_c3.md has the wiring, the WiFi set-up and the LED. */
#include <zephyr/dt-bindings/led/led.h>
&pinctrl {
spim2_led: spim2_led {
group1 {
pinmux = <SPIM2_MOSI_GPIO2>;
output-low;
};
};
uart1_rb9704: uart1_rb9704 {
group1 {
pinmux = <UART1_TX_GPIO4>;
output-high;
};
group2 {
pinmux = <UART1_RX_GPIO5>;
bias-pull-up;
};
};
};
/ {
aliases {
led-strip = &led_strip;
};
};
&spi2 {
pinctrl-0 = <&spim2_led>;
pinctrl-names = "default";
/* The SK6812 reads a high idle line as data. */
line-idle-low;
led_strip: ws2812@0 {
compatible = "worldsemi,ws2812-spi";
reg = <0>;
spi-max-frequency = <6400000>;
chain-length = <1>;
spi-cpha;
spi-one-frame = <0xf0>; /* 625 ns high, 625 ns low */
spi-zero-frame = <0xc0>; /* 312.5 ns high, 937.5 ns low */
color-mapping = <LED_COLOR_ID_GREEN LED_COLOR_ID_RED LED_COLOR_ID_BLUE>;
};
};
&uart1 {
pinctrl-0 = <&uart1_rb9704>;
pinctrl-names = "default";
current-speed = <230400>;
status = "okay";
rb9704: rockblock {
compatible = "rock7,rockblock-9704";
power-gpios = <&gpio0 10 GPIO_ACTIVE_HIGH>; /* P_EN */
iridium-enable-gpios = <&gpio0 6 GPIO_ACTIVE_HIGH>; /* I_EN */
booted-gpios = <&gpio0 7 GPIO_ACTIVE_HIGH>; /* I_BTD */
};
};
@@ -23,7 +23,7 @@
current-speed = <230400>; current-speed = <230400>;
status = "okay"; status = "okay";
rockblock { rb9704: rockblock {
compatible = "rock7,rockblock-9704"; compatible = "rock7,rockblock-9704";
}; };
}; };
+15
View File
@@ -0,0 +1,15 @@
/* SPDX-License-Identifier: MIT
* Copyright (c) 2026 Scott Penrose <scottp@dd.com.au>
*
* The modem on TX and RX alone: P_EN, I_EN and I_BTD taken out of the
* board overlay's node, for a modem wired with four wires. The module
* then takes it to be powered, as the RockBLOCK is with the pins open.
*
* west build -b stamp_c3 samples/shell -- \
* -DEXTRA_DTC_OVERLAY_FILE=no-control-pins.overlay
*/
&rb9704 {
/delete-property/ power-gpios;
/delete-property/ iridium-enable-gpios;
/delete-property/ booted-gpios;
};
+54
View File
@@ -0,0 +1,54 @@
# SPDX-License-Identifier: MIT
# Copyright (c) 2026 Scott Penrose <scottp@dd.com.au>
#
# The shell over WiFi, for a board out in the open with power and no USB:
#
# west build -b stamp_c3 samples/shell -- -DEXTRA_CONF_FILE=overlay-wifi.conf
#
# Once, on the USB console:
#
# wifi cred add -s "<SSID>" -k 1 -p "<password>"
#
# The board joins that network at every boot after (src/wifi.c), logs its
# address, and `telnet <address>` gives the same shell as the console. There
# is no password on telnet and `rb9704 send` costs airtime: keep it on a
# network you trust.
# --- WiFi -------------------------------------------------------------------
CONFIG_WIFI=y
CONFIG_NET_L2_WIFI_MGMT=y
CONFIG_NET_L2_WIFI_SHELL=y
# The ESP32 driver reconnects by itself after the access point drops it.
CONFIG_ESP32_WIFI_STA_RECONNECT=y
CONFIG_NETWORKING=y
CONFIG_NET_IPV4=y
CONFIG_NET_IPV6=n
CONFIG_NET_DHCPV4=y
CONFIG_NET_TCP=y
CONFIG_NET_SOCKETS=y
CONFIG_NET_SHELL=y
CONFIG_NET_MGMT=y
CONFIG_NET_MGMT_EVENT=y
CONFIG_NET_MGMT_EVENT_INFO=y
# --- credentials, kept in flash --------------------------------------------
CONFIG_WIFI_CREDENTIALS=y
CONFIG_WIFI_CREDENTIALS_CONNECT_STORED=y
CONFIG_SETTINGS=y
CONFIG_SETTINGS_NVS=y
CONFIG_NVS=y
CONFIG_FLASH=y
CONFIG_FLASH_MAP=y
# --- the shell on telnet ----------------------------------------------------
CONFIG_SHELL_BACKEND_TELNET=y
# Character mode and echo negotiated with the client, so line editing and
# history work as on the console. Zephyr's own telnet sample sets it.
CONFIG_SHELL_TELNET_SUPPORT_COMMAND=y
CONFIG_SHELL_STACK_SIZE=4096
# --- memory -----------------------------------------------------------------
CONFIG_MAIN_STACK_SIZE=4096
CONFIG_NET_TX_STACK_SIZE=2048
CONFIG_NET_RX_STACK_SIZE=2048
+206
View File
@@ -0,0 +1,206 @@
/* SPDX-License-Identifier: MIT
* Copyright (c) 2026 Scott Penrose <scottp@dd.com.au>
*
* indicator.c - the board's RGB LED and button, for a board out in the open
* with nobody at its console. Built on boards whose devicetree has a
* led-strip alias (one LED is enough) and an sw0 button.
*
* The LED, by priority:
*
* white, fast blink a button action is running (begin, end)
* green flash a message went (1 s)
* red flash a message, or a button action, failed (2 s)
* cyan flash a message arrived (2 s)
* magenta a message is with the modem, on its way
* red/yellow/green begun: no signal or no satellite / 1-2 bars / 3-5
* blue not begun
*
* On a WiFi build the steady colours blink slowly while there is no WiFi:
* blinking means telnet will not reach it.
*
* The button, both free of airtime:
*
* short press not begun: rb9704_begin. Begun: ask for the signal.
* long press rb9704_end, and the supply off when there is a power pin.
*/
#include <zephyr/kernel.h>
#include <zephyr/device.h>
#include <zephyr/devicetree.h>
#include <zephyr/drivers/led_strip.h>
#include <zephyr/input/input.h>
#include <zephyr/logging/log.h>
#include <rb9704/rb9704.h>
#include "indicator.h"
#ifdef CONFIG_WIFI
#include "wifi.h"
#endif
LOG_MODULE_REGISTER(sample_indicator, LOG_LEVEL_INF);
#define TICK_MS 100
#define LONG_MS 2000
/* Out of 255: the SK6812 at full is too bright to look at. */
#define LEVEL 24
static const struct device *const strip = DEVICE_DT_GET(DT_ALIAS(led_strip));
enum flash { FLASH_NONE, FLASH_SENT, FLASH_FAILED, FLASH_MT };
static atomic_t flash;
static int64_t flash_until;
static atomic_t busy;
static uint32_t ticks;
static K_SEM_DEFINE(press_sem, 0, 1);
static bool press_long;
static struct led_rgb rgb(uint8_t r, uint8_t g, uint8_t b)
{
return (struct led_rgb){.r = r, .g = g, .b = b};
}
static const struct led_rgb off = {0};
static bool wifi_up(void)
{
#ifdef CONFIG_WIFI
return sample_wifi_connected();
#else
return true;
#endif
}
void indicator_flash_mo(int result)
{
atomic_set(&flash, result == 0 ? FLASH_SENT : FLASH_FAILED);
flash_until = k_uptime_get() + (result == 0 ? 1000 : 2000);
}
void indicator_flash_mt(void)
{
atomic_set(&flash, FLASH_MT);
flash_until = k_uptime_get() + 2000;
}
static struct led_rgb pick(void)
{
struct rb9704_status st;
struct led_rgb c;
ticks++;
if (atomic_get(&busy)) {
return (ticks & 1) ? rgb(LEVEL, LEVEL, LEVEL) : off;
}
if (atomic_get(&flash) != FLASH_NONE) {
if (k_uptime_get() < flash_until) {
switch (atomic_get(&flash)) {
case FLASH_SENT:
return rgb(0, LEVEL, 0);
case FLASH_FAILED:
return rgb(LEVEL, 0, 0);
default:
return rgb(0, LEVEL, LEVEL);
}
}
atomic_set(&flash, FLASH_NONE);
}
rb9704_status(&st);
if (st.mo_in_flight) {
c = rgb(LEVEL, 0, LEVEL);
} else if (!st.begun) {
c = rgb(0, 0, LEVEL);
} else if (!st.signal_known || st.signal_bars == 0 ||
(st.visibility_known && !st.constellation_visible)) {
c = rgb(LEVEL, 0, 0);
} else if (st.signal_bars < 3) {
c = rgb(LEVEL, LEVEL, 0);
} else {
c = rgb(0, LEVEL, 0);
}
/* Half a second on, half off, while telnet cannot reach the board. */
if (!wifi_up() && (ticks / 5) % 2) {
return off;
}
return c;
}
static void tick(struct k_work *work)
{
struct led_rgb c = pick();
(void)led_strip_update_rgb(strip, &c, 1);
k_work_schedule(k_work_delayable_from_work(work), K_MSEC(TICK_MS));
}
static K_WORK_DELAYABLE_DEFINE(tick_work, tick);
/* The input thread must not wait on the modem: a press is handed to the
* button thread, and a press during an action is dropped. */
static void on_key(struct input_event *evt, void *user)
{
static int64_t down;
ARG_UNUSED(user);
if (evt->type != INPUT_EV_KEY) {
return;
}
if (evt->value) {
down = k_uptime_get();
return;
}
if (atomic_get(&busy)) {
return;
}
press_long = k_uptime_get() - down >= LONG_MS;
k_sem_give(&press_sem);
}
INPUT_CALLBACK_DEFINE(DEVICE_DT_GET(DT_PARENT(DT_ALIAS(sw0))), on_key, NULL);
static void button_thread(void *a, void *b, void *c)
{
struct rb9704_status st;
int rc;
ARG_UNUSED(a);
ARG_UNUSED(b);
ARG_UNUSED(c);
for (;;) {
k_sem_take(&press_sem, K_FOREVER);
rb9704_status(&st);
atomic_set(&busy, 1);
if (press_long) {
LOG_INF("button: end");
/* rb9704_power ends the library first. */
rc = rb9704_power(false);
if (rc == -ENOTSUP) {
rc = st.begun ? rb9704_end(K_SECONDS(10)) : 0;
}
} else if (!st.begun) {
LOG_INF("button: begin");
rc = rb9704_begin(K_SECONDS(60));
} else {
LOG_INF("button: signal");
rc = rb9704_signal(K_SECONDS(10));
}
atomic_set(&busy, 0);
if (rc < 0) {
LOG_WRN("button: failed (%d)", rc);
indicator_flash_mo(rc);
}
}
}
K_THREAD_DEFINE(button_tid, 2048, button_thread, NULL, NULL, NULL, 10, 0, 0);
void indicator_start(void)
{
if (!device_is_ready(strip)) {
LOG_ERR("LED not ready");
return;
}
k_work_schedule(&tick_work, K_NO_WAIT);
}
+14
View File
@@ -0,0 +1,14 @@
/* SPDX-License-Identifier: MIT
* Copyright (c) 2026 Scott Penrose <scottp@dd.com.au>
*/
#ifndef SAMPLE_INDICATOR_H
#define SAMPLE_INDICATOR_H
/* The RGB LED shows the modem's state; the button begins and ends it. */
void indicator_start(void);
/* A short flash for a finished send (result as mo_done gives it) and for
* a message arrived. */
void indicator_flash_mo(int result);
void indicator_flash_mt(void);
#endif /* SAMPLE_INDICATOR_H */
+19
View File
@@ -15,12 +15,22 @@
#include <rb9704/rb9704.h> #include <rb9704/rb9704.h>
#ifdef CONFIG_WIFI
#include "wifi.h"
#endif
#ifdef CONFIG_LED_STRIP
#include "indicator.h"
#endif
LOG_MODULE_REGISTER(sample, LOG_LEVEL_INF); LOG_MODULE_REGISTER(sample, LOG_LEVEL_INF);
static void on_mo_done(uint16_t topic, uint16_t id, int result, void *user) static void on_mo_done(uint16_t topic, uint16_t id, int result, void *user)
{ {
ARG_UNUSED(user); ARG_UNUSED(user);
LOG_INF("mo done topic %u id %u result %d", topic, id, result); LOG_INF("mo done topic %u id %u result %d", topic, id, result);
#ifdef CONFIG_LED_STRIP
indicator_flash_mo(result);
#endif
} }
static void on_mt(const struct rb9704_mt *mt, void *user) static void on_mt(const struct rb9704_mt *mt, void *user)
@@ -37,6 +47,9 @@ static void on_mt(const struct rb9704_mt *mt, void *user)
text[n] = '\0'; text[n] = '\0';
LOG_INF("mt topic %u id %u len %u crc %08x: %s", mt->topic, mt->id, (unsigned int)mt->len, 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); crc32_ieee(mt->data, mt->len), text);
#ifdef CONFIG_LED_STRIP
indicator_flash_mt();
#endif
} }
static void on_signal(uint8_t bars, bool visible, void *user) static void on_signal(uint8_t bars, bool visible, void *user)
@@ -61,6 +74,12 @@ static const struct rb9704_callbacks cb = {
int main(void) int main(void)
{ {
rb9704_set_callbacks(&cb); rb9704_set_callbacks(&cb);
#ifdef CONFIG_WIFI
sample_wifi_start();
#endif
#ifdef CONFIG_LED_STRIP
indicator_start();
#endif
LOG_INF("rb9704 shell sample: `rb9704 begin`, then `rb9704 info`"); LOG_INF("rb9704 shell sample: `rb9704 begin`, then `rb9704 info`");
return 0; return 0;
} }
+106
View File
@@ -0,0 +1,106 @@
/* SPDX-License-Identifier: MIT
* Copyright (c) 2026 Scott Penrose <scottp@dd.com.au>
*
* wifi.c - join the stored network at boot, and keep trying, so a board out
* in the open is reachable by telnet with nobody at its USB port. Built with
* overlay-wifi.conf only.
*
* The credentials are the ones `wifi cred add` kept in flash. The ESP32
* driver reconnects by itself after a drop (CONFIG_ESP32_WIFI_STA_RECONNECT);
* the retry here covers a network that was not there at boot.
*/
#include <zephyr/kernel.h>
#include <zephyr/logging/log.h>
#include <zephyr/net/net_if.h>
#include <zephyr/net/net_mgmt.h>
#include <zephyr/net/wifi_mgmt.h>
#include <zephyr/net/wifi_credentials.h>
#include "wifi.h"
LOG_MODULE_REGISTER(sample_wifi, LOG_LEVEL_INF);
#define RETRY K_SECONDS(30)
static struct net_mgmt_event_callback wifi_cb;
static struct net_mgmt_event_callback ip_cb;
static struct k_work_delayable retry;
static bool connected;
static void try_connect(struct k_work *work)
{
static bool warned;
struct net_if *iface = net_if_get_wifi_sta();
ARG_UNUSED(work);
if (connected || iface == NULL) {
return;
}
if (wifi_credentials_is_empty()) {
/* Checked again in 30 s, so a network added now is joined
* without a reboot. */
if (!warned) {
LOG_WRN("no network stored: wifi cred add -s \"<SSID>\" -k 1 -p \"<password>\"");
warned = true;
}
k_work_reschedule(&retry, RETRY);
return;
}
if (net_mgmt(NET_REQUEST_WIFI_CONNECT_STORED, iface, NULL, 0) != 0) {
k_work_reschedule(&retry, RETRY);
}
}
static void on_wifi(struct net_mgmt_event_callback *cb, uint64_t event, struct net_if *iface)
{
const struct wifi_status *status = cb->info;
ARG_UNUSED(iface);
if (event == NET_EVENT_WIFI_CONNECT_RESULT) {
connected = status->status == 0;
if (connected) {
LOG_INF("wifi connected, waiting for an address");
} else {
LOG_WRN("wifi connect failed (%d), again in 30 s", status->status);
k_work_reschedule(&retry, RETRY);
}
} else if (event == NET_EVENT_WIFI_DISCONNECT_RESULT) {
connected = false;
LOG_WRN("wifi disconnected");
k_work_reschedule(&retry, RETRY);
}
}
static void on_ip(struct net_mgmt_event_callback *cb, uint64_t event, struct net_if *iface)
{
char addr[NET_IPV4_ADDR_LEN];
ARG_UNUSED(cb);
ARG_UNUSED(event);
ARRAY_FOR_EACH(iface->config.ip.ipv4->unicast, i) {
const struct net_if_addr *a = &iface->config.ip.ipv4->unicast[i].ipv4;
if (a->is_used && a->addr_type == NET_ADDR_DHCP) {
net_addr_ntop(AF_INET, &a->address.in_addr, addr, sizeof(addr));
LOG_INF("address %s: telnet %s", addr, addr);
}
}
}
bool sample_wifi_connected(void)
{
return connected;
}
void sample_wifi_start(void)
{
k_work_init_delayable(&retry, try_connect);
net_mgmt_init_event_callback(&wifi_cb, on_wifi,
NET_EVENT_WIFI_CONNECT_RESULT |
NET_EVENT_WIFI_DISCONNECT_RESULT);
net_mgmt_add_event_callback(&wifi_cb);
net_mgmt_init_event_callback(&ip_cb, on_ip, NET_EVENT_IPV4_ADDR_ADD);
net_mgmt_add_event_callback(&ip_cb);
/* A moment for the driver to bring the interface up. */
k_work_reschedule(&retry, K_SECONDS(1));
}
+13
View File
@@ -0,0 +1,13 @@
/* SPDX-License-Identifier: MIT
* Copyright (c) 2026 Scott Penrose <scottp@dd.com.au>
*/
#ifndef SAMPLE_WIFI_H
#define SAMPLE_WIFI_H
#include <stdbool.h>
/* Join the network `wifi cred add` stored, and rejoin it after a drop. */
void sample_wifi_start(void);
bool sample_wifi_connected(void);
#endif /* SAMPLE_WIFI_H */
+5
View File
@@ -83,6 +83,11 @@ int rb9704_power_set(bool want)
while (gpio_pin_get_dt(&btd) != 1) { while (gpio_pin_get_dt(&btd) != 1) {
if (k_uptime_get() > until) { if (k_uptime_get() > until) {
LOG_ERR("modem did not signal booted in %d ms", BOOT_TIMEOUT_MS); LOG_ERR("modem did not signal booted in %d ms", BOOT_TIMEOUT_MS);
/* Back down, so the next attempt starts from off. */
if (en.port != NULL) {
(void)gpio_pin_set_dt(&en, 0);
}
(void)gpio_pin_set_dt(&pwr, 0);
return -ETIMEDOUT; return -ETIMEDOUT;
} }
k_msleep(50); k_msleep(50);
+23 -11
View File
@@ -34,6 +34,8 @@ static const char *err_name(int rc)
case EINPROGRESS: return "EINPROGRESS"; case EINPROGRESS: return "EINPROGRESS";
case ENOTSUP: return "ENOTSUP"; case ENOTSUP: return "ENOTSUP";
case EDEADLK: return "EDEADLK"; case EDEADLK: return "EDEADLK";
case ENOENT: return "ENOENT";
case ECANCELED: return "ECANCELED";
default: return "?"; default: return "?";
} }
} }
@@ -90,8 +92,11 @@ static int cmd_status(const struct shell *sh, size_t argc, char **argv)
} else { } else {
shell_print(sh, "topics provisioning not seen yet"); shell_print(sh, "topics provisioning not seen yet");
} }
shell_print(sh, "mo %u sent, %u failed%s", s.mo_sent, s.mo_failed, shell_print(sh, "mo %u sent, %u failed", s.mo_sent, s.mo_failed);
s.mo_in_flight ? ", one in flight" : ""); 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, "mt %u received, %u failed", s.mt_received, s.mt_failed);
shell_print(sh, "serial %u bytes dropped", s.rx_dropped); shell_print(sh, "serial %u bytes dropped", s.rx_dropped);
return 0; 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 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); unsigned long topic = strtoul(argv[1], NULL, 10);
bool hex = strcmp(argv[0], "sendhex") == 0; const uint8_t *data = (const uint8_t *)argv[2];
int len; int len = strlen(argv[2]);
ARG_UNUSED(argc); ARG_UNUSED(argc);
if (hex) { if (strcmp(argv[0], "sendhex") == 0) {
len = unhex(argv[2], buf, sizeof(buf)); len = unhex(argv[2], hexbuf, sizeof(hexbuf));
} else { data = hexbuf;
len = MIN(strlen(argv[2]), sizeof(buf));
memcpy(buf, argv[2], len);
} }
if (len <= 0) { if (len <= 0) {
shell_error(sh, "nothing to send (%d)", len); shell_error(sh, "nothing to send (%d)", len);
return -EINVAL; return -EINVAL;
} }
shell_print(sh, "%d bytes on topic %lu: this costs airtime", len, topic); 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) 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(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(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_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_CMD_ARG(spy, NULL, "spy on|off: print every JSPR line", cmd_spy, 2, 0),
SHELL_SUBCMD_SET_END); SHELL_SUBCMD_SET_END);
+75 -22
View File
@@ -46,7 +46,7 @@
LOG_MODULE_REGISTER(rb9704, CONFIG_RB9704_LOG_LEVEL); 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 }; enum req_state { REQ_PENDING, REQ_DONE, REQ_ABANDONED };
static struct { static struct {
@@ -74,6 +74,7 @@ static K_MUTEX_DEFINE(rb9704_st_lock);
static const struct rb9704_callbacks *app; static const struct rb9704_callbacks *app;
static bool mt_waiting; static bool mt_waiting;
static bool mo_cancel_asked; /* so the failure that follows reads -ECANCELED */
#if !IS_ENABLED(CONFIG_RB9704_POWER) #if !IS_ENABLED(CONFIG_RB9704_POWER)
int rb9704_power_init(void) int rb9704_power_init(void)
@@ -99,14 +100,19 @@ bool rb9704_power_present(void)
static void cb_mo_started(const uint16_t id) 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); LOG_DBG("MO accepted by the modem: id %u", id);
} }
static void cb_mo_complete(const uint16_t id, const rbMsgStatus_t status) static void cb_mo_complete(const uint16_t id, const rbMsgStatus_t status)
{ {
uint16_t topic; 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); k_mutex_lock(&rb9704_st_lock, K_FOREVER);
st.mo_in_flight = false; st.mo_in_flight = false;
topic = st.mo_topic; topic = st.mo_topic;
@@ -116,7 +122,8 @@ static void cb_mo_complete(const uint16_t id, const rbMsgStatus_t status)
st.mo_failed++; st.mo_failed++;
} }
k_mutex_unlock(&rb9704_st_lock); 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) { if (app != NULL && app->mo_done != NULL) {
app->mo_done(topic, id, result, app->user); app->mo_done(topic, id, result, app->user);
} }
@@ -180,6 +187,16 @@ static const rbCallbacks_t callbacks = {
/* --- the requests, on this thread --------------------------------------- */ /* --- 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) static int op_begin(void)
{ {
if (st.begun) { 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 */ if (!rbBegin("zephyr")) { /* the port name is unused: the UART is in devicetree */
return -EIO; 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); k_mutex_lock(&rb9704_st_lock, K_FOREVER);
st.begun = true; st.begun = true;
st.mo_in_flight = false;
k_mutex_unlock(&rb9704_st_lock); k_mutex_unlock(&rb9704_st_lock);
return 0; 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 * 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 * 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 * what it kept, clear the cache and the library asks again: one free JSPR
* round trip. messageProvisioningInfo is the library's own global. */ * round trip. */
extern jsprMessageProvisioning_t messageProvisioningInfo;
static int op_send(void) static int op_send(void)
{ {
bool known; bool known;
@@ -271,6 +289,24 @@ static int op_send(void)
return 0; 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) static void copy_str(char *dst, size_t cap, const char *src)
{ {
if (src != NULL) { if (src != NULL) {
@@ -349,6 +385,7 @@ static int dispatch(void)
case OP_BEGIN: return op_begin(); case OP_BEGIN: return op_begin();
case OP_END: return op_end(); case OP_END: return op_end();
case OP_SEND: return op_send(); case OP_SEND: return op_send();
case OP_CANCEL: return op_cancel();
case OP_INFO: return op_info(); case OP_INFO: return op_info();
case OP_SIGNAL: return op_signal(); case OP_SIGNAL: return op_signal();
case OP_POWER: return op_power(); case OP_POWER: return op_power();
@@ -377,8 +414,11 @@ static void complete(void)
} }
/* Caller side. The slot is held from here until the caller has read the /* Caller side. The slot is held from here until the caller has read the
* result, or until the worker finishes a request the caller gave up on. */ * result, or until the worker finishes a request the caller gave up on.
static int submit(k_timeout_t timeout, bool async_ok) * Abandonment is reported apart from the result: a request can itself end
* in -ETIMEDOUT (a begin whose modem never signals booted), and then the
* slot is still the caller's to give back. */
static int submit(k_timeout_t timeout, bool *abandoned)
{ {
k_spinlock_key_t key; k_spinlock_key_t key;
int rc; int rc;
@@ -388,13 +428,12 @@ static int submit(k_timeout_t timeout, bool async_ok)
k_event_post(&rb9704_ev, EV_REQ); k_event_post(&rb9704_ev, EV_REQ);
rc = k_sem_take(&rb9704_done, timeout); rc = k_sem_take(&rb9704_done, timeout);
key = k_spin_lock(&req_lock); key = k_spin_lock(&req_lock);
if (rc != 0 && req.state != REQ_DONE) { *abandoned = rc != 0 && req.state != REQ_DONE;
if (*abandoned) {
req.state = REQ_ABANDONED; req.state = REQ_ABANDONED;
k_spin_unlock(&req_lock, key);
return async_ok ? -EINPROGRESS : -ETIMEDOUT;
} }
k_spin_unlock(&req_lock, key); k_spin_unlock(&req_lock, key);
return req.result; return *abandoned ? 0 : req.result;
} }
static int take_slot(k_timeout_t timeout) static int take_slot(k_timeout_t timeout)
@@ -407,16 +446,18 @@ static int take_slot(k_timeout_t timeout)
static int simple(enum op op, k_timeout_t timeout) static int simple(enum op op, k_timeout_t timeout)
{ {
bool abandoned;
int rc = take_slot(timeout); int rc = take_slot(timeout);
if (rc != 0) { if (rc != 0) {
return rc; return rc;
} }
req.op = op; req.op = op;
rc = submit(timeout, false); rc = submit(timeout, &abandoned);
if (rc != -ETIMEDOUT) { if (abandoned) {
k_sem_give(&rb9704_slot); return -ETIMEDOUT;
} }
k_sem_give(&rb9704_slot);
return rc; return rc;
} }
@@ -429,6 +470,7 @@ void rb9704_set_callbacks(const struct rb9704_callbacks *cb)
int rb9704_power(bool on) int rb9704_power(bool on)
{ {
bool abandoned;
int rc; int rc;
if (!rb9704_power_present()) { if (!rb9704_power_present()) {
@@ -440,7 +482,10 @@ int rb9704_power(bool on)
} }
req.op = OP_POWER; req.op = OP_POWER;
req.on = on; req.on = on;
rc = submit(K_FOREVER, false); rc = submit(K_FOREVER, &abandoned);
if (abandoned) {
return -ETIMEDOUT;
}
k_sem_give(&rb9704_slot); k_sem_give(&rb9704_slot);
return rc; return rc;
} }
@@ -460,17 +505,23 @@ int rb9704_signal(k_timeout_t timeout)
return simple(OP_SIGNAL, 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) int rb9704_info(struct rb9704_info *out, k_timeout_t timeout)
{ {
bool abandoned;
int rc = take_slot(timeout); int rc = take_slot(timeout);
if (rc != 0) { if (rc != 0) {
return rc; return rc;
} }
req.op = OP_INFO; req.op = OP_INFO;
rc = submit(timeout, false); rc = submit(timeout, &abandoned);
if (rc == -ETIMEDOUT) { if (abandoned) {
return rc; return -ETIMEDOUT;
} }
if (rc == 0) { if (rc == 0) {
*out = req.info; *out = req.info;
@@ -481,6 +532,7 @@ int rb9704_info(struct rb9704_info *out, k_timeout_t timeout)
int rb9704_send(uint16_t topic, const void *data, size_t len, k_timeout_t timeout) int rb9704_send(uint16_t topic, const void *data, size_t len, k_timeout_t timeout)
{ {
bool abandoned;
int rc; int rc;
if (topic < RB9704_TOPIC_MIN || data == NULL || len == 0 || len > sizeof(mo_buf)) { if (topic < RB9704_TOPIC_MIN || data == NULL || len == 0 || len > sizeof(mo_buf)) {
@@ -494,10 +546,11 @@ int rb9704_send(uint16_t topic, const void *data, size_t len, k_timeout_t timeou
req.topic = topic; req.topic = topic;
req.len = len; req.len = len;
memcpy(mo_buf, data, len); memcpy(mo_buf, data, len);
rc = submit(timeout, true); rc = submit(timeout, &abandoned);
if (rc != -EINPROGRESS) { if (abandoned) {
k_sem_give(&rb9704_slot); return -EINPROGRESS;
} }
k_sem_give(&rb9704_slot);
return rc; return rc;
} }
+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); uint32_t n = ring_buf_get_claim(back, &p, 64);
if (n == 0) { 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); uart_irq_tx_disable(dev);
} else { } else {
int w = uart_fifo_fill(dev, p, n); int w = uart_fifo_fill(dev, p, n);