18 Commits
Author SHA1 Message Date
swaits 6c6e74f26f chore: release 1.4.1 2026-04-29 22:38:54 -06:00
swaits 732bd18ac3 fix(deps): pin lora-phy to swaits/lora-rs#fixed for sx127x/sx126x reliability
Switch lora-phy from crates.io to the swaits/lora-rs "fixed" branch
which carries three fixes awaiting upstream PR acceptance:

  - phy: sx127x: clear stale IRQ flags before reconfiguring DIO mapping
    in set_irq_params (fix/sx127x-irq-clear-position)
  - phy: sx127x: clear stale IRQ flags in do_rx before mode change
    (fix/sx127x-rx-irq-clear)
  - phy: sx126x: pre-command BUSY check + standby/IRQ-clear hygiene
    around CAD (fix/sx126x-busy-race)

Validates TBeam classic (sx127x) in particular and tightens reliability
across every board (the sx126x BUSY-race fix lands on every nRF/RP2040
board too). Pinned to commit e8a52ebd via Cargo.lock; revert to
crates.io once the three PRs land upstream.
2026-04-29 22:37:04 -06:00
swaits f7bac5903c fix(display): pick smaller font when board name overflows splash
Cap the splash board-name on a 128 px-wide OLED: every name must fit
the FONT_5X8 fallback (25 ASCII chars) or the const_assert at the
BOARD_NAME definition fails the build. At runtime, names that fit
FONT_6X10 (21 chars) keep the primary font; longer names switch to
FONT_5X8 instead of overflowing. Also drop the URL-line font on the
"learn more" screen from FONT_5X8 to FONT_4X6 so "donglora.com" sits
inside the 64 px column with breathing room instead of touching both
edges.
2026-04-29 22:26:29 -06:00
swaits b56c044d57 refactor(host/usb): bump hsmc to 0.5 and collapse WaitingForFirstFrame into Connected
hsmc 0.5 makes default(...) optional on every state. Drop the
WaitingForFirstFrame substate that existed only because 0.4 required
Connected to declare a default child — Connected itself is now the
resting "DTR up, no traffic yet" state, and on(FrameReceived) => Active
descends into the inactivity-timer state on the first byte. Behavior is
identical (entry/exit chain math unchanged); the chart has one fewer
state and one fewer default().

Display and Radio charts left as-is — their defaults are all classic
descents serving real grouping/lifecycle purposes (Splash grouping,
Bright sub-state isolation, RX/TX session lifecycle), not 0.4 artifacts.
No journal-replay tests in this repo, so the 0.5 journal-format change
does not apply.
2026-04-29 22:26:16 -06:00
swaits f68e5d9be5 fix(host/uart): deliver RX to host and survive sustained bidirectional load
Two regressions on UART boards (heltec_v3_uart, etc.):

1. RADIO_THROTTLED was never cleared on UART. The throttle gate at
   src/radio.rs:2017 (added in 276f941, "chart-first restructure ...
   soak hardening") silently drops async RX while the flag is true.
   USB host_task clears it on first successful write_packet
   (src/host/usb.rs:354/373), but the UART path was never updated --
   every RX event was dropped from boot. The OLED bar lit up
   regardless because record_packet announces PacketRx before the
   gate. Mirror the USB pattern: clear on successful tx.write_all,
   re-arm on failure.

2. Once RX flowed, sustained bidirectional spam tripped the §3.4
   inactivity watchdog spuriously. The select3-based loop serialised
   read and write; tx.write_all (~25 ms per max frame at 115_200
   baud) blocked the read poll long enough for last_frame_at to age
   past 1000 ms under a saturated outbound queue. The Reset cascaded
   to radio (Unconfigured) and display (splash), leaving subsequent
   host TX commands timing out waiting for TX_DONE. Restructure
   host_task into two sub-loops joined in the same task: read_loop
   owns rx + watchdog, write_loop owns tx + throttle. The read future
   re-polls on every executor wake regardless of write progress.
   Same executor, disjoint borrows on the split rx/tx halves, no
   Mutex needed.

Also reset the FrameDecoder when the watchdog fires so a host that
resumes mid-frame resyncs cleanly on the next 0x00 sentinel (USB
gets this for free via DTR-drop reset; UART has no DTR).

Build: bump esp-hal/esp-rtos/esp-backtrace/esp-println version
requirements (1.0->1.1, 0.2->0.3, 0.18->0.19, 0.16->0.17) to match
what the upstream esp-rs/esp-hal main branch now publishes. cargo
update had invalidated the [patch.crates-io] entries since the
patched versions were no longer semver-compatible with the old
top-level requirements, which silently dropped the patches and fell
back to crates.io releases that pin embassy-executor 0.9 (mismatched
with our 0.10).
2026-04-29 22:26:16 -06:00
swaits eb8202058f build: declare ESP toolchain in mise.toml; drop ~/export-esp.sh dependence
mise.toml now owns the ESP cross-toolchain end to end:

- [env] pins PATH (xtensa-esp-elf-gcc bin) and LIBCLANG_PATH so any
  `mise exec` (which the justfile already uses for `set shell`)
  resolves the linker without sourcing espup's stray ~/export-esp.sh.
- [tasks.esp-install] installs the matching crosstool version via
  espup (espup hardcodes ~/.rustup/toolchains/esp/ -- there is no
  --prefix flag -- so the binaries necessarily live there, but the
  project now declaratively owns the version + path knowledge).
- cargo:espup pinned to 0.17.1 to match the [env] paths.

Triggered by a real failure: ~/export-esp.sh was moved to Trash and
the ESP build broke with `linker xtensa-esp32s3-elf-gcc not found`.
The previous setup silently no-op'd `[ -f $HOME/export-esp.sh ] && .
$HOME/export-esp.sh` in justfile, leaving the build with no PATH for
the cross-toolchain. Encoding the paths in mise.toml removes the
stray-file dependency.

justfile changes:
- _cargo: drop the `[ -f $HOME/export-esp.sh ] && . ...` source.
- setup / _require_esp_toolchain: install via `mise run esp-install`
  instead of bare `espup install`, so the version pin and the [env]
  paths stay in sync from a single source.

Bumping ESP versions remains a two-touch change: edit the version
dirs in BOTH [tasks.esp-install] and [env], then re-run the task.
2026-04-29 22:26:16 -06:00
swaits 1c98786ce6 feat(build): per-board memory.x override with MCU-family fallback
build.rs resolves the linker layout in two steps: per-board override
`ld/{board}-memory.x` first, MCU-family default second. Lets a board
deviate from the family default without a per-board build matrix.

Adds `ld/wio_tracker_l1-memory.x` with `ORIGIN = 0x1000` (no-SD
layout). The Wio Tracker L1 ships from Seeed with s140 SoftDevice, but
our earlier `ORIGIN = 0x1000, LENGTH = 0xE9000` linker silently
overwrote it across many UF2 flashes; the bootloader now reports
`SoftDevice: not found`. Until s140 is restored via SWD, the WIO
needs the no-SD layout to match the bootloader's actual boot chain.

Delete the per-board file once SD is restored -- the build will then
fall back to the SD-aware `ld/nrf52840-memory.x` and the WIO matches
every other nRF52840 board.
2026-04-28 11:03:46 -06:00
swaits 16374ca241 refactor(radio): make every lora-phy operation cancel-safe via chart structure
Rewrite the Operational subtree of the radio chart so that every
cancel-unsafe lora-phy future (lora.rx() / lora.cad() / lora.tx() /
lora.init()) runs to natural completion, honoring lora-phy's documented
'must run to completion' contract.

Architectural pivot: every cancel-unsafe future is the body of a leaf-
state during whose host state declares NO outbound event handlers other
than events the during itself emits on natural completion. Per hsmc spec
§6, the chart cannot drop the during because no transition can fire.

RX subtree (RxSession super-state):
  - irq_pump (cancel-safe: wait_for_irq + get_irq_state + clear_irq_status)
    runs at RxSession scope, emits Dio1Asserted(IrqState) to chart
  - try_start_rx_hw chains prepare_for_rx -> start_rx so the chip is
    actually receiving when RxActive is entered (both single SPI ops)
  - RxActive's collect_rx_packet action does post-IRQ get_rx_result work
  - RxDraining's enter_standby cleanly stops RX before transitions out

TX subtree (TxSession super-state):
  - TxCadPrep / TxCadWait / TxBackoff / TxPrep / TxOnAir / TxFanout
    leaf states each owning one cancel-safe SPI op or one sandboxed
    cancel-unsafe await
  - lora.cad() / lora.tx() called AS-IS in states with zero non-self
    event handlers
  - chart timers (on(after Duration)) set context flags for wedge
    detection; the during checks the flag at its next cancel-safe
    wakeup and returns cleanly
  - mark_pending_reset action defers Reset events until natural
    completion (per spec §5 emit() semantics)

Removes lora_setup_with wrappers around lora.cad(), lora.tx(),
lora.init() -- those wrappers used embassy_time::with_timeout which
DROPS the wrapped future on timeout, the proximate cause of every
'lora_setup timeout: do_tx.cad' warn we've seen.

Keeps lora_setup around enter_standby / prepare_for_rx /
prepare_for_cad / prepare_for_tx -- those are short SPI sequences where
drop is documented-safe.

Documented latency budget: chart-cycle overhead <100us; regulatory
LBT (CAD-to-TX <50ms) well within budget.
2026-04-28 11:03:24 -06:00
swaits e5aeb3896a fix(radio): guarantee TX_DONE/TX_FAILED reply on every CmdTx via Transmitting exit action
Add exit: respond_tx_failed on the Transmitting super-state. Per hsmc spec
§6, exit actions fire on every departure from a state, including the
Operational-level on(WedgeDetected) => Recovering transition that bypasses
Transmitting's own on(TransmitFailed) => respond_tx_failed handler.

respond_tx_failed is a clean no-op when last_tx_tag is None (the
normal-completion path consumed it via .take()), so this is a safe
unconditional exit action. Net effect: every CmdTx gets exactly one
tag-correlated TX_DONE/TX_FAILED/CHANNEL_BUSY reply no matter how
Transmitting is exited. The host (mux/ai-bot) stops eating 2s firmware-
timeouts on every CAD wedge mid-TX.
2026-04-28 10:59:28 -06:00
swaits 276f941fbb refactor(radio): chart-first restructure on hsmc 0.3 + soak hardening
Migrate from hsmc 0.2 (local-patched) to hsmc 0.3.0 (crates.io, with
embassy + trace-defmt features). Restructure radio chart and bundle
several adjacent stability changes that need to land together for
soak runs.

Radio chart:
- Booting (default, no handlers) -> Operational (default Unconfigured;
  super-state owning CmdPing/CmdGetInfo/Reset/WedgeDetected handlers
  + Recovering + CheckRecoveryBudget) -> Dead (terminal).
- Cold init's during is structurally un-cancellable.
- radio_task is a 30-line shim that panics if run() returns (chart is
  non-terminating).
- Internal queue capacity bumped 8 -> 32 to cover action-emit bursts.

Host chart:
- Connected splits into WaitingForFirstFrame (default, no timer) +
  Active (chart-owned 1s inactivity timer via on(after) + self-
  transition on FrameReceived). Manual Timer::after + last_frame_at
  removed.

Soak hardening:
- ld/nrf52840-memory.x: app start 0x1000 -> 0x26000 to leave the
  factory s140 SoftDevice dormant in flash.
- hal/nrf52840.rs: dump POWER.RESETREAS on boot -- WARN on DOG/LOCKUP,
  INFO on RESETPIN/SREQ/wake-from-OFF.
- host/usb.rs: read_packet errors discriminated -- Disabled is debug
  (normal during USB enum), BufferOverflow stays warn.
- COBS encode warns now carry type/tag/payload-length for diagnosis.
- RADIO_THROTTLED static initializes to true (no proof of host drain
  at boot).
- driver/sh1106.rs: init retries 3x with 100ms backoff (intermittent
  first-write race on power-up).
- Cargo.toml: unexpected_cfgs allowlist for hsmc's journal/trace-*
  features.

docs/semtech_lora_cad_lbt_guidebook.md: vendor the Semtech CAD/LBT
reference for offline lookup.
2026-04-28 10:59:28 -06:00
swaits 481712930c chore: release 1.4.0 2026-04-25 20:23:39 -06:00
swaits d262abe853 feat(radio): adaptive LBT — scale CAD retries to current LoRa config
The CAD pre-TX loop previously ran up to 10 retries with a fixed 10 ms
sleep — roughly one max-length packet only at SF7/BW500. At SF10/BW125
the 100 ms total was ~4% of one packet; at SF12/BW125 LBT was a no-op.

Now the per-retry sleep is sized to one time-on-air of an assumed-peer
80-byte packet under the active config, cached on RadioContext and
recomputed on every SET_CONFIG. Retries scale as
clamp(floor(BUDGET/T)+1, 1, 10) with BUDGET=2.5 s, so fast configs
still get up to 10 retries while SF11/12 degrade to single-CAD-and-bail
(logged at config-apply). Sleeps are jittered ±20% per iteration to
decorrelate simultaneously-backing-off contenders.

The ToA math, CR→{1..4} mapping, retry-count derivation, and jitter
helper live in a pure src/lbt.rs module so they're host-testable via
DONGLORA_HOST_TEST=1 cargo test (13 tests).

Validated on-device: 20 iterations of the AI Bot test flow that
previously saw ~2 ChannelBusy errors now see zero at the same SF/BW.
2026-04-25 20:15:44 -06:00
swaits 23ddc15557 fix(radio): consume upstream lora-phy pre-command BUSY check
Pick up the proper fix from our fork at swaits/lora-rs@fix/sx126x-busy-race:
move the ready check from *after* to *before* each SPI op per the
Semtech manuals (SX1261/2 §8.3.1, LR1121 UM §3 / §3.5, LR1110 DS
§1.2.5) and rename InterfaceVariant::wait_on_busy to wait_until_ready.

Firmware side is surgical: since the upstream fix keeps the
GenericSx126xInterfaceVariant::new signature at 5 args (no DelayNs
threading), there is nothing to change in the four nRF / ESP / RP2040
board files beyond a one-line comment rename (wait_on_busy ->
wait_until_ready) in the BUSY-pullup comment on the two nRF boards.

Wire in the [patch.crates-io] override pointing at ../../lora-rs/lora-phy,
bump the dep spec to the pre-release 3.0.2-alpha that matches the fork,
and enable the defmt-03 feature that upstream moved behind a gate
between 3.0.1 and the fix branch.

TODO.md rewritten to track the new approach: PR body template with
verbatim citations from all three Semtech chip manuals (SX1261/2,
LR1121 UM, LR1110 DS) plus the SX1276 pin table confirming the family
has no BUSY line.

No change to firmware behavior beyond picking up the upstream fix,
which takes first-TX-after-boot success from ~50% to 20/20 on the
Seeed Wio Tracker L1 repro board.
2026-04-24 12:44:01 -06:00
swaits 4d723a85ce fix(boards): BUSY pin pull-down → none on nRF SX1262 boards
SX1262's BUSY pin has an internal 20 kΩ pull-up (datasheet page 53).
Our Input::new(..., Pull::Down) on BUSY creates contention with that
internal pull-up, leaving BUSY at an indeterminate voltage. This can
cause wait_on_busy to mis-read the chip's ready state — sometimes
commands land while the chip is still busy (ignored or corrupted),
which manifests as TX_DONE never firing on DIO1 because the SX1262
never actually completed the SetTx it received during BUSY=high.

Fix per lora-rs/lora-rs#260: Pull::Down → Pull::None on BUSY.
Matches the official lora-rs nRF52840 examples.

Applied to both Wio Tracker L1 (reported broken by @swaits today) and
RAK4631 (currently works for us, but was affected by the same class
of bug per the upstream issue — this makes it deterministically
correct rather than 'happens to work').
2026-04-24 01:34:32 -06:00
swaits 6380bcbf6a just(flash): add optional extra_features arg for build/flash/flash-probe
Appends comma-separated extra features to the board feature when
building. Enables iteration workflows like:

    just flash wio_tracker_l1 debug-checkpoint

without having to drop to raw cargo + rust-objcopy + uf2 cp.
2026-04-24 01:34:32 -06:00
swaits 7a045edc1a docs: add TODO.md with esp-hal upgrade task 2026-04-24 00:31:14 -06:00
swaits b53570ce66 chore: update tool specs in mise.toml 2026-04-24 00:25:50 -06:00
swaits 647929ff8d feat(boards): RAK4631 WisBlock bring-up + build-system cleanup
RAK4631 board:
- SX126X_POWER_EN on P1.05 driven HIGH at init (radio is power-gated;
  without this the chip has no power and SPI hangs)
- HFXO + LFXO external crystals in embassy_nrf::Config (USB CDC-ACM
  needs +/- 500 ppm which the internal RC oscillator can't provide)
- SoftwareVbusDetect(true, true) so USB enumerates without needing a
  CLOCK_POWER interrupt handler
- Green LED on P1.03 via SimpleLed (RAK19007 Base LED1, active HIGH)
- driver/mod.rs: open simple_led feature gate for rak_wisblock_4631
- Spim::new pin-order comment on SPI setup (arg order is sck/miso/mosi,
  not sck/mosi/miso — easy to get wrong)

debug-checkpoint instrumentation (feature-gated, zero cost in release):
- radio.rs: debug_blink::set(N) at each TX-phase boundary, filling in
  the long-aspirational blink-map doc
- debug_blink.rs: checkpoint 19 between prepare_for_cad and cad(), so
  future bring-ups can distinguish modem-setup hang from DIO1-wait hang

justfile + mise.toml:
- set shell := ["mise", "exec", "--", "sh", "-c"] so recipes
  always resolve tools through mise, not whatever happens to be on PATH
- replace per-board := vars + long if/elif _info chain with a single
  case statement — one place per board, two lists (names + metadata)
- new flash-dfu recipe using adafruit-nrfutil via uvx, with VID:PID
  (239a:0029) port autodetect for the Adafruit nRF52 bootloader
- mise.toml: rust pins now carry ARM targets + clippy, so 'mise install'
  is sufficient bootstrapping (no extra rustup target add steps)

Verified TX on real hardware (RAK19007 Base + RAK4631 Core + RAK1921
OLED, US915 band): ADVERT round-trip with an external receiver.
2026-04-24 00:15:29 -06:00
26 changed files with 4544 additions and 618 deletions

No files matched your search

+170
View File
@@ -7,6 +7,176 @@ and this project adheres to [Semantic Versioning](https://semver.org/).
## [Unreleased]
## [1.4.1] - 2026-04-29
### Fixed
- **Major LoRa reliability boost across every radio family.** Switched
`lora-phy` from crates.io to the
[`swaits/lora-rs#fixed`](https://github.com/swaits/lora-rs/tree/fixed)
fork branch — a merge of three fixes awaiting upstream PR acceptance,
pinned at `e8a52ebd` via `Cargo.lock`:
- [#428](https://github.com/lora-rs/lora-rs/pull/428) — sx126x:
pre-command BUSY check + standby/IRQ-clear hygiene around CAD.
- [#431](https://github.com/lora-rs/lora-rs/pull/431) — sx127x:
clear stale IRQ flags in `do_rx` before mode change.
- [#432](https://github.com/lora-rs/lora-rs/pull/432) — sx127x:
clear stale IRQ flags before reconfiguring DIO mapping in
`set_irq_params`.
Stability gain across the fleet: the sx126x BUSY-race fix lands on
every nRF / RP2040 board, and the sx127x IRQ-clear fixes unblock the
LilyGo T-Beam (classic) in particular.
- **UART host RX delivery on UART-only boards.** `RADIO_THROTTLED` was
never cleared on UART (`heltec_v3_uart`, `elecrow_thinknode_m2`,
`lilygo_tbeam`) — the throttle gate added in v1.3.0's chart-first
restructure silently dropped every async RX from boot. Mirrored the
USB pattern: clear the throttle on successful `tx.write_all`, re-arm
on failure.
- **UART host watchdog spurious-trip under saturated bidirectional
load.** The `select3`-based loop serialised read and write;
`tx.write_all` (~25 ms per max frame at 115200 baud) blocked the read
poll long enough for `last_frame_at` to age past 1000 ms, cascading a
Reset to radio (`Unconfigured`) and display (splash) and leaving
subsequent host TX commands timing out. Restructured `host_task` into
two sub-loops joined in the same task: `read_loop` owns rx +
watchdog, `write_loop` owns tx + throttle. Same executor, disjoint
borrows on the split rx/tx halves, no Mutex needed. Also reset the
`FrameDecoder` on watchdog fire so a host that resumes mid-frame
resyncs cleanly on the next `0x00` sentinel (USB gets this for free
via DTR-drop reset; UART has no DTR).
- **Splash board-name overflow on long names.** Names that don't fit
`FONT_6X10` (21 ASCII chars on a 128 px-wide OLED) now fall back to
`FONT_5X8` (25 chars). A `const_assert` at the `BOARD_NAME`
definition rejects names that overflow even the fallback, so the
board porter shortens `NAME` at compile time rather than getting
silent overflow at runtime. Also dropped the URL-line font on the
"learn more" screen from `FONT_5X8` to `FONT_4X6` so `donglora.com`
sits inside the 64 px column with breathing room instead of touching
both edges.
### Changed
- **`hsmc` 0.4 → 0.5.** `default(...)` is optional on every state in
0.5; collapsed the `WaitingForFirstFrame` substate that existed only
because 0.4 required `Connected` to declare a default child.
`Connected` itself is now the resting "DTR up, no traffic yet" state,
with `on(FrameReceived) => Active` descending into the
inactivity-timer state on the first byte. Behavior is identical
(entry/exit chain math unchanged); the host/usb chart has one fewer
state and one fewer `default()`. Display and Radio charts left as-is
— their defaults serve real grouping/lifecycle purposes, not 0.4
artifacts.
- **ESP cross-toolchain pinned in `mise.toml`.** `[env]` now owns the
PATH (`xtensa-esp-elf-gcc` bin) and `LIBCLANG_PATH`, so any `mise
exec` resolves the linker without sourcing espup's stray
`~/export-esp.sh`. New `[tasks.esp-install]` invokes espup with the
matching crosstool version pin. `cargo:espup` pinned to `0.17.1` to
match the `[env]` paths. Triggered by a real failure where
`~/export-esp.sh` was moved to Trash and the ESP build broke with
`linker xtensa-esp32s3-elf-gcc not found`. Bumping ESP versions
remains a two-touch change: edit version dirs in BOTH
`[tasks.esp-install]` and `[env]`.
- **ESP dependency requirements bumped** to track the upstream
`esp-rs/esp-hal` main branch: `esp-hal 1.0 → 1.1`, `esp-rtos 0.2 →
0.3`, `esp-backtrace 0.18 → 0.19`, `esp-println 0.16 → 0.17`. `cargo
update` had silently invalidated the `[patch.crates-io]` entries (the
patched versions were no longer semver-compatible with the old
top-level requirements), dropping the patches and falling back to
crates.io releases that pin `embassy-executor 0.9` — mismatched with
our `0.10`. Catching this keeps the patch suite consistent until the
planned `[patch.crates-io]`-removal pass.
## [1.4.0] - 2026-04-25
### Added
- **RAK4631 WisBlock board support** (nRF52840 + SX1262, RAK19007 base
+ RAK4631 Core + RAK1921 OLED). The second nRF52840 + SX1262 board
alongside the Wio Tracker L1.
- `SX126X_POWER_EN` (P1.05) driven HIGH at init — the radio is
power-gated on this module; without this the chip has no power
and SPI hangs.
- HFXO + LFXO external crystals selected in `embassy_nrf::Config`.
USB CDC-ACM needs ±500 ppm which the internal RC oscillator
can't provide.
- `SoftwareVbusDetect(true, true)` so USB enumerates without a
`CLOCK_POWER` interrupt handler.
- Green LED on P1.03 (RAK19007 Base LED1, active-HIGH) via
`SimpleLed`.
- Hardware-validated end-to-end: ADVERT round-trip with an external
receiver on US915.
- Added `debug-checkpoint` blink-map coverage at every TX-phase
boundary in `radio.rs`, including a new checkpoint between
`prepare_for_cad` and `cad()` so future bring-ups can distinguish
a modem-setup hang from a DIO1-wait hang.
- **Adaptive listen-before-talk.** The CAD pre-TX retry loop scales to
the active LoRa config instead of running a fixed 10 retries × 10 ms
(which was roughly one max-length packet at SF7/BW500 and a no-op at
SF12/BW125).
- Per-retry sleep is sized to the time-on-air of an assumed-peer
80-byte packet under the current SF/BW/CR — cached on
`RadioContext`, recomputed on every `SET_CONFIG`.
- Retry count = `clamp(floor(BUDGET/T)+1, 1, 10)` with `BUDGET = 2.5
s`. Fast configs still get up to 10 retries; SF11/12 degrade to
single-CAD-and-bail (logged at config-apply).
- Sleeps jittered ±20% per iteration to decorrelate
simultaneously-backing-off contenders.
- ToA math, CR→{1..4} mapping, retry-count derivation, and jitter
helper live in a pure `src/lbt.rs` module — host-testable via
`DONGLORA_HOST_TEST=1 cargo test` (13 tests).
- Validated on-device: 20 iterations of the AI Bot test flow that
previously saw ~2 `ChannelBusy` errors now sees zero at the same
SF/BW.
### Fixed
- **First-TX-after-boot reliability on SX1262 boards.** Picked up the
upstream `lora-phy` fix that moves the BUSY-handshake check from
*after* to *before* each SPI op, per Semtech SX1261/2 §8.3.1, LR1121
UM §3, and LR1110 DS §1.2.5. The existing post-op wait is preserved
as the belt that closes the BUSY-assertion latency window
(T_SW ≤ 600 ns) that a single level-poll can miss. Consumed via
`[patch.crates-io]` against `swaits/lora-rs#fix/sx126x-busy-race`
until the upstream PR merges.
- Hardware-verified on Seeed Wio Tracker L1: 20/20 clean-boot TX
(vs ~50% before).
- Renames `InterfaceVariant::wait_on_busy` → `wait_until_ready` to
match the new semantics.
- **BUSY pin pull-down → none on nRF SX1262 boards.** SX1262's BUSY
pin has an internal 20 kΩ pull-up (datasheet p. 53); our
`Input::new(..., Pull::Down)` was contending with it, leaving BUSY
at an indeterminate voltage and intermittently mis-reading the
chip's ready state. Per `lora-rs/lora-rs#260`, switched to
`Pull::None` on both Wio Tracker L1 and RAK4631. The RAK4631
appeared to work before, but was affected by the same class of bug
per the upstream issue — now deterministically correct rather than
"happens to work".
### Changed
- **Build-system DX.** `just flash`, `just flash-probe`, and
`just build` accept an optional comma-separated `extra_features`
argument that is appended to the board feature, e.g. `just flash
wio_tracker_l1 debug-checkpoint`. No more dropping to raw
`cargo + rust-objcopy + uf2 cp` for iteration loops.
- **`just` recipes now resolve all tools through `mise`** via
`set shell := ["mise", "exec", "--", "sh", "-c"]`. `cargo`,
`espflash`, `rust-objcopy`, `cargo-hex-to-uf2` etc. always pick up
the versions pinned in `mise.toml` regardless of `PATH` ordering.
- **`mise.toml` rust pins now carry ARM targets + clippy**, so a fresh
`mise install` is sufficient bootstrapping — no manual
`rustup target add` for `thumbv6m-none-eabi` /
`thumbv7em-none-eabihf` and no separate clippy install.
- **New `just flash-dfu` recipe** for the Adafruit nRF52 bootloader
(VID:PID `239a:0029`) via `adafruit-nrfutil` under `uvx`, with port
autodetect.
- **Per-board `_info` chain in the justfile** collapsed from a long
per-board `if/elif` ladder + per-board `:=` variables into a single
`case` statement — one place per board, two lists (names +
metadata).
## [1.3.1] - 2026-04-23
### Fixed
Generated
+305 -103
View File
@@ -2,6 +2,17 @@
# It is not intended for manual editing.
version = 4
[[package]]
name = "aes"
version = "0.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "66bd29a732b644c0431c6140f370d097879203d79b80c94a6747ba0872adaef8"
dependencies = [
"cipher",
"cpubits",
"cpufeatures 0.3.0",
]
[[package]]
name = "ahash"
version = "0.8.12"
@@ -114,9 +125,9 @@ checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a"
[[package]]
name = "bitflags"
version = "2.11.0"
version = "2.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "843867be96c8daad0d758b57df9392b6d8d271134fce549de6ce169ff98a92af"
checksum = "c4512299f36f043ab09a583e57bceb5a5aab7a73db1805848e8fef3c9e8c78b3"
[[package]]
name = "block-buffer"
@@ -127,6 +138,15 @@ dependencies = [
"generic-array",
]
[[package]]
name = "block-buffer"
version = "0.12.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cdd35008169921d80bc60d3d0ab416eecb028c4cd653352907921d95084790be"
dependencies = [
"hybrid-array",
]
[[package]]
name = "byte-slice-cast"
version = "1.2.3"
@@ -147,9 +167,9 @@ checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b"
[[package]]
name = "cc"
version = "1.2.60"
version = "1.2.61"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "43c5703da9466b66a946814e1adf53ea2c90f10063b86290cc9eb67ce3478a20"
checksum = "d16d90359e986641506914ba71350897565610e87ce0ad9e6f28569db3dd5c6d"
dependencies = [
"find-msvc-tools",
"shlex",
@@ -172,6 +192,33 @@ dependencies = [
"pure-rust-locales",
]
[[package]]
name = "cipher"
version = "0.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e34d8227fe1ba289043aeb13792056ff80fd6de1a9f49137a5f499de8e8c78ea"
dependencies = [
"crypto-common 0.2.1",
"inout",
]
[[package]]
name = "cmac"
version = "0.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ac78aa94ce13e432b332a4d1bf2eff167d3a2520188ee05b337180a42fd2e62e"
dependencies = [
"cipher",
"dbl",
"digest 0.11.2",
]
[[package]]
name = "cmov"
version = "0.5.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3f88a43d011fc4a6876cb7344703e297c71dda42494fee094d5f7c76bf13f746"
[[package]]
name = "codespan-reporting"
version = "0.11.1"
@@ -225,6 +272,12 @@ dependencies = [
"syn 2.0.117",
]
[[package]]
name = "cpubits"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "15b85f9c39137c3a891689859392b1bd49812121d0d61c9caf00d46ed5ce06ae"
[[package]]
name = "cpufeatures"
version = "0.2.17"
@@ -234,6 +287,15 @@ dependencies = [
"libc",
]
[[package]]
name = "cpufeatures"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8b2a41393f66f16b0823bb79094d54ac5fbd34ab292ddafb9a0456ac9f87d201"
dependencies = [
"libc",
]
[[package]]
name = "crc-any"
version = "2.5.0"
@@ -265,6 +327,24 @@ dependencies = [
"typenum",
]
[[package]]
name = "crypto-common"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "77727bb15fa921304124b128af125e7e3b968275d1b108b379190264f4423710"
dependencies = [
"hybrid-array",
]
[[package]]
name = "ctutils"
version = "0.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7d5515a3834141de9eafb9717ad39eea8247b5674e6066c404e8c4b365d2a29e"
dependencies = [
"cmov",
]
[[package]]
name = "darling"
version = "0.20.11"
@@ -368,6 +448,15 @@ dependencies = [
"syn 2.0.117",
]
[[package]]
name = "dbl"
version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f0d7a944e61df464668c5f51f56cc667396a8821434273112948ea0b66e405d7"
dependencies = [
"hybrid-array",
]
[[package]]
name = "debug-helper"
version = "0.3.13"
@@ -417,12 +506,12 @@ dependencies = [
[[package]]
name = "defmt-rtt"
version = "1.1.0"
version = "0.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "93d5a25c99d89c40f5676bec8cefe0614f17f0f40e916f98e345dae941807f9e"
checksum = "c6eca0aae8aa2cf8333200ecbd236274697bc0a394765c858b3d9372eb1abcfa"
dependencies = [
"critical-section",
"defmt 1.0.1",
"defmt 0.3.100",
]
[[package]]
@@ -442,8 +531,19 @@ version = "0.10.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
dependencies = [
"block-buffer",
"crypto-common",
"block-buffer 0.10.4",
"crypto-common 0.1.7",
]
[[package]]
name = "digest"
version = "0.11.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4850db49bf08e663084f7fb5c87d202ef91a3907271aff24a94eb97ff039153c"
dependencies = [
"block-buffer 0.12.0",
"crypto-common 0.2.1",
"ctutils",
]
[[package]]
@@ -486,13 +586,13 @@ dependencies = [
[[package]]
name = "donglora"
version = "1.3.1"
version = "1.4.1"
dependencies = [
"cfg-if",
"cortex-m",
"cortex-m-rt",
"critical-section",
"defmt 1.0.1",
"defmt 0.3.100",
"defmt-rtt",
"display-interface",
"donglora-protocol",
@@ -643,7 +743,7 @@ version = "0.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b715380574504335c40ec3016bc44598fac3c385f82959b26c41b25c30b7648d"
dependencies = [
"bitflags 2.11.0",
"bitflags 2.11.1",
"cfg-if",
"cortex-m",
"cortex-m-rt",
@@ -780,12 +880,12 @@ dependencies = [
[[package]]
name = "embassy-time-queue-utils"
version = "0.3.0"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "80e2ee86063bd028a420a5fb5898c18c87a8898026da1d4c852af2c443d0a454"
checksum = "168297bf80aaf114b3c9ad589bf38b01b3009b9af7f97cd18086c5bbf96f5693"
dependencies = [
"embassy-executor-timer-queue",
"heapless 0.8.0",
"heapless 0.9.2",
]
[[package]]
@@ -794,7 +894,7 @@ version = "0.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a25746d8b152b72fbf2a217f489a083dbbe243f281f09184a1f2cfbe9bbb245f"
dependencies = [
"bitflags 2.11.0",
"bitflags 2.11.1",
"defmt 1.0.1",
"embassy-futures",
"embassy-net-driver-channel",
@@ -984,8 +1084,8 @@ checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f"
[[package]]
name = "esp-backtrace"
version = "0.18.1"
source = "git+https://github.com/esp-rs/esp-hal.git?branch=main#70930f20d9f681a30ff20aced39d0bd5363126d5"
version = "0.19.0"
source = "git+https://github.com/esp-rs/esp-hal.git?branch=main#54a62c57f1f005020777a4e0843ce03c68312aba"
dependencies = [
"cfg-if",
"defmt 1.0.1",
@@ -1001,8 +1101,8 @@ dependencies = [
[[package]]
name = "esp-config"
version = "0.6.1"
source = "git+https://github.com/esp-rs/esp-hal.git?branch=main#70930f20d9f681a30ff20aced39d0bd5363126d5"
version = "0.7.0"
source = "git+https://github.com/esp-rs/esp-hal.git?branch=main#54a62c57f1f005020777a4e0843ce03c68312aba"
dependencies = [
"document-features",
"esp-metadata-generated",
@@ -1013,16 +1113,16 @@ dependencies = [
[[package]]
name = "esp-hal"
version = "1.0.0"
source = "git+https://github.com/esp-rs/esp-hal.git?branch=main#70930f20d9f681a30ff20aced39d0bd5363126d5"
version = "1.1.0"
source = "git+https://github.com/esp-rs/esp-hal.git?branch=main#54a62c57f1f005020777a4e0843ce03c68312aba"
dependencies = [
"bitfield 0.19.4",
"bitflags 2.11.0",
"bitflags 2.11.1",
"bytemuck",
"cfg-if",
"critical-section",
"delegate",
"digest",
"digest 0.10.7",
"document-features",
"embassy-embedded-hal",
"embassy-futures",
@@ -1056,7 +1156,7 @@ dependencies = [
"nb 1.1.0",
"paste",
"portable-atomic",
"rand_core 0.10.0",
"rand_core 0.10.1",
"rand_core 0.6.4",
"rand_core 0.9.5",
"riscv",
@@ -1070,8 +1170,8 @@ dependencies = [
[[package]]
name = "esp-hal-procmacros"
version = "0.21.0"
source = "git+https://github.com/esp-rs/esp-hal.git?branch=main#70930f20d9f681a30ff20aced39d0bd5363126d5"
version = "0.22.0"
source = "git+https://github.com/esp-rs/esp-hal.git?branch=main#54a62c57f1f005020777a4e0843ce03c68312aba"
dependencies = [
"document-features",
"object",
@@ -1084,13 +1184,13 @@ dependencies = [
[[package]]
name = "esp-metadata-generated"
version = "0.3.0"
source = "git+https://github.com/esp-rs/esp-hal.git?branch=main#70930f20d9f681a30ff20aced39d0bd5363126d5"
version = "0.4.0"
source = "git+https://github.com/esp-rs/esp-hal.git?branch=main#54a62c57f1f005020777a4e0843ce03c68312aba"
[[package]]
name = "esp-println"
version = "0.16.1"
source = "git+https://github.com/esp-rs/esp-hal.git?branch=main#70930f20d9f681a30ff20aced39d0bd5363126d5"
version = "0.17.0"
source = "git+https://github.com/esp-rs/esp-hal.git?branch=main#54a62c57f1f005020777a4e0843ce03c68312aba"
dependencies = [
"defmt 1.0.1",
"document-features",
@@ -1102,8 +1202,8 @@ dependencies = [
[[package]]
name = "esp-riscv-rt"
version = "0.13.0"
source = "git+https://github.com/esp-rs/esp-hal.git?branch=main#70930f20d9f681a30ff20aced39d0bd5363126d5"
version = "0.14.0"
source = "git+https://github.com/esp-rs/esp-hal.git?branch=main#54a62c57f1f005020777a4e0843ce03c68312aba"
dependencies = [
"document-features",
"riscv",
@@ -1112,8 +1212,8 @@ dependencies = [
[[package]]
name = "esp-rom-sys"
version = "0.1.3"
source = "git+https://github.com/esp-rs/esp-hal.git?branch=main#70930f20d9f681a30ff20aced39d0bd5363126d5"
version = "0.1.4"
source = "git+https://github.com/esp-rs/esp-hal.git?branch=main#54a62c57f1f005020777a4e0843ce03c68312aba"
dependencies = [
"cfg-if",
"document-features",
@@ -1124,8 +1224,8 @@ dependencies = [
[[package]]
name = "esp-rtos"
version = "0.2.0"
source = "git+https://github.com/esp-rs/esp-hal.git?branch=main#70930f20d9f681a30ff20aced39d0bd5363126d5"
version = "0.3.0"
source = "git+https://github.com/esp-rs/esp-hal.git?branch=main#54a62c57f1f005020777a4e0843ce03c68312aba"
dependencies = [
"cfg-if",
"document-features",
@@ -1146,8 +1246,8 @@ dependencies = [
[[package]]
name = "esp-sync"
version = "0.1.1"
source = "git+https://github.com/esp-rs/esp-hal.git?branch=main#70930f20d9f681a30ff20aced39d0bd5363126d5"
version = "0.2.1"
source = "git+https://github.com/esp-rs/esp-hal.git?branch=main#54a62c57f1f005020777a4e0843ce03c68312aba"
dependencies = [
"cfg-if",
"document-features",
@@ -1174,67 +1274,73 @@ dependencies = [
[[package]]
name = "esp32"
version = "0.39.0"
source = "git+https://github.com/esp-rs/esp-pacs?rev=fc3e6d4#fc3e6d4b34cfc885f750641d27e6fe3e63bad5d2"
version = "0.40.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5726e07689249d1a2cb7c492077bc424837fb68a64f7eb5d46569325352e9428"
dependencies = [
"critical-section",
"vcell",
]
[[package]]
name = "esp32c2"
version = "0.28.0"
source = "git+https://github.com/esp-rs/esp-pacs?rev=fc3e6d4#fc3e6d4b34cfc885f750641d27e6fe3e63bad5d2"
version = "0.29.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5ef0b623533bbaa37e348c18b6b41cfd5b47c3cb64a4b9e44f0295941d62aa2e"
dependencies = [
"critical-section",
"vcell",
]
[[package]]
name = "esp32c3"
version = "0.31.0"
source = "git+https://github.com/esp-rs/esp-pacs?rev=fc3e6d4#fc3e6d4b34cfc885f750641d27e6fe3e63bad5d2"
version = "0.32.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "21e89ed62cf6c043a6d29c520b02a13b359ec8a75d67b65d4330ed717d15fe97"
dependencies = [
"critical-section",
"vcell",
]
[[package]]
name = "esp32c6"
version = "0.22.0"
source = "git+https://github.com/esp-rs/esp-pacs?rev=fc3e6d4#fc3e6d4b34cfc885f750641d27e6fe3e63bad5d2"
version = "0.23.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c58f34ff2633968c12125efc7f4f8f101078d5d34c7cb60eab82268db20986f9"
dependencies = [
"critical-section",
"vcell",
]
[[package]]
name = "esp32h2"
version = "0.18.0"
source = "git+https://github.com/esp-rs/esp-pacs?rev=fc3e6d4#fc3e6d4b34cfc885f750641d27e6fe3e63bad5d2"
version = "0.19.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c5bab026020ed4606ce113b6fde598dbc48f7eefcc46e9469ece77cc2b1aa4be"
dependencies = [
"critical-section",
"vcell",
]
[[package]]
name = "esp32s2"
version = "0.30.0"
source = "git+https://github.com/esp-rs/esp-pacs?rev=fc3e6d4#fc3e6d4b34cfc885f750641d27e6fe3e63bad5d2"
version = "0.31.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d0ad6f21cdf6ec7b06b7f7e0fbe51f0d975fd6a5fa67c3f8a5a910d3981af531"
dependencies = [
"critical-section",
"vcell",
]
[[package]]
name = "esp32s3"
version = "0.34.0"
source = "git+https://github.com/esp-rs/esp-pacs?rev=fc3e6d4#fc3e6d4b34cfc885f750641d27e6fe3e63bad5d2"
version = "0.35.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8b4b8c4e4d9f187553ecdb7173edec7b2deb2beea106eedefecdb1654b8ee25a"
dependencies = [
"critical-section",
"vcell",
]
[[package]]
name = "fastrand"
version = "2.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9f1f227452a390804cdb637b74a86990f2a7d7ba4b7d5693aac9b4dd6defd8d6"
[[package]]
name = "find-msvc-tools"
version = "0.1.9"
@@ -1283,12 +1389,42 @@ dependencies = [
"gcd",
]
[[package]]
name = "futures"
version = "0.3.32"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8b147ee9d1f6d097cef9ce628cd2ee62288d963e16fb287bd9286455b241382d"
dependencies = [
"futures-channel",
"futures-core",
"futures-io",
"futures-sink",
"futures-task",
"futures-util",
]
[[package]]
name = "futures-channel"
version = "0.3.32"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "07bbe89c50d7a535e539b8c17bc0b49bdb77747034daa8087407d655f3f7cc1d"
dependencies = [
"futures-core",
"futures-sink",
]
[[package]]
name = "futures-core"
version = "0.3.32"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7e3450815272ef58cec6d564423f6e755e25379b217b0bc688e295ba24df6b1d"
[[package]]
name = "futures-io"
version = "0.3.32"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cecba35d7ad927e23624b22ad55235f2239cfa44fd10428eecbeba6d6a717718"
[[package]]
name = "futures-sink"
version = "0.3.32"
@@ -1308,6 +1444,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "389ca41296e6190b48053de0321d02a77f32f8a5d2461dd38762c0593805c6d6"
dependencies = [
"futures-core",
"futures-sink",
"futures-task",
"pin-project-lite",
]
@@ -1374,9 +1511,9 @@ dependencies = [
[[package]]
name = "hashbrown"
version = "0.16.1"
version = "0.17.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100"
checksum = "4f467dd6dccf739c208452f8014c75c18bb8301b050ad1cfb27153803edb0f51"
[[package]]
name = "heapless"
@@ -1406,11 +1543,18 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
[[package]]
name = "hsmc"
version = "0.2.0"
name = "hex"
version = "0.4.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "960effec6ded897c013d5cde8fb7f09bf0137e783efc4c2e0346092a2941c46e"
checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"
[[package]]
name = "hsmc"
version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a3951a3170ce7aa0f0bf4627ac4cc650857f15449c98e97647fa29fcd19c6d33"
dependencies = [
"defmt 0.3.100",
"embassy-futures",
"embassy-sync 0.8.0",
"embassy-time",
@@ -1420,15 +1564,24 @@ dependencies = [
[[package]]
name = "hsmc-macros"
version = "0.2.0"
version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3e1933eea1e95edb4fa03688f969f0a1ffabc4f16fc396b40ead6bedd5c4bdff"
checksum = "4b6d97dd1d31fba9e2f96c65c0ce38d7bc1ff59abe775a0ae18e14dfae01d1d1"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.117",
]
[[package]]
name = "hybrid-array"
version = "0.4.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "08d46837a0ed51fe95bd3b05de33cd64a1ee88fc797477ca48446872504507c5"
dependencies = [
"typenum",
]
[[package]]
name = "ident_case"
version = "1.0.1"
@@ -1437,12 +1590,12 @@ checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39"
[[package]]
name = "indexmap"
version = "2.13.0"
version = "2.14.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7714e70437a7dc3ac8eb7e6f8df75fd8eb422675fc7678aff7364301092b1017"
checksum = "d466e9454f08e4a911e14806c24e16fba1b4c121d1ea474396f396069cf949d9"
dependencies = [
"equivalent",
"hashbrown 0.16.1",
"hashbrown 0.17.0",
]
[[package]]
@@ -1454,6 +1607,15 @@ dependencies = [
"rustversion",
]
[[package]]
name = "inout"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4250ce6452e92010fdf7268ccc5d14faa80bb12fc741938534c58f16804e03c7"
dependencies = [
"hybrid-array",
]
[[package]]
name = "instability"
version = "0.3.12"
@@ -1488,7 +1650,7 @@ version = "0.1.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cb26cec98cce3a3d96cbb7bced3c4b16e3d13f27ec56dbd62cbc8f39cfb9d653"
dependencies = [
"cpufeatures",
"cpufeatures 0.2.17",
]
[[package]]
@@ -1531,9 +1693,9 @@ checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe"
[[package]]
name = "libc"
version = "0.2.184"
version = "0.2.186"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "48f5d2a454e16a5ea0f4ced81bd44e4cfc7bd3a507b61887c99fd3538b28e4af"
checksum = "68ab91017fe16c622486840e4c83c9a37afeff978bd239b5293d61ece587de66"
[[package]]
name = "litrs"
@@ -1572,22 +1734,62 @@ dependencies = [
[[package]]
name = "lora-modulation"
version = "0.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2c96c4a41a1f1ad04de765306e1829c7007a37898fe4033204fa82cf2e055624"
source = "git+https://github.com/swaits/lora-rs.git?branch=fixed#e8a52ebd35352ce0267148fd392a0b1956d7735f"
dependencies = [
"defmt 0.3.100",
]
[[package]]
name = "lora-phy"
version = "3.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "61471c3b2909789e3332083577f6cf6c41a4fcf37674ef15156bcbb20504ac65"
version = "3.0.2-alpha"
source = "git+https://github.com/swaits/lora-rs.git?branch=fixed#e8a52ebd35352ce0267148fd392a0b1956d7735f"
dependencies = [
"defmt 0.3.100",
"document-features",
"embedded-hal 1.0.0",
"embedded-hal-async",
"lora-modulation",
"lorawan-device",
"num-traits",
]
[[package]]
name = "lorawan"
version = "0.9.1"
source = "git+https://github.com/swaits/lora-rs.git?branch=fixed#e8a52ebd35352ce0267148fd392a0b1956d7735f"
dependencies = [
"aes",
"cmac",
"defmt 0.3.100",
"hex",
"lorawan-macros",
]
[[package]]
name = "lorawan-device"
version = "0.12.2"
source = "git+https://github.com/swaits/lora-rs.git?branch=fixed#e8a52ebd35352ce0267148fd392a0b1956d7735f"
dependencies = [
"defmt 0.3.100",
"document-features",
"fastrand",
"futures",
"heapless 0.9.2",
"lora-modulation",
"lorawan",
"rand_core 0.6.4",
]
[[package]]
name = "lorawan-macros"
version = "0.1.0"
source = "git+https://github.com/swaits/lora-rs.git?branch=fixed#e8a52ebd35352ce0267148fd392a0b1956d7735f"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.117",
]
[[package]]
name = "matchers"
version = "0.2.0"
@@ -1630,9 +1832,9 @@ checksum = "c3c8dda44ff03a2f238717214da50f65d5a53b45cd213a7370424ffdb6fae815"
[[package]]
name = "minijinja"
version = "2.18.0"
version = "2.19.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "328251e58ad8e415be6198888fc207502727dc77945806421ab34f35bf012e7d"
checksum = "805bfd7352166bae857ee569628b52bcd85a1cecf7810861ebceb1686b72b75d"
dependencies = [
"memo-map",
"serde",
@@ -1932,7 +2134,7 @@ version = "0.11.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "679341d22c78c6c649893cbd6c3278dcbe9fc4faa62fea3a9296ae2b50c14625"
dependencies = [
"bitflags 2.11.0",
"bitflags 2.11.1",
"memchr",
"unicase",
]
@@ -1975,9 +2177,9 @@ checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c"
[[package]]
name = "rand_core"
version = "0.10.0"
version = "0.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0c8d0fd677905edcbeedbf2edb6494d676f0e98d54d5cf9bda0b061cb8fb8aba"
checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69"
[[package]]
name = "redox_syscall"
@@ -1985,7 +2187,7 @@ version = "0.5.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d"
dependencies = [
"bitflags 2.11.0",
"bitflags 2.11.1",
]
[[package]]
@@ -2214,8 +2416,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e3bf829a2d51ab4a5ddf1352d8470c140cadc8301b2ae1789db023f01cedd6ba"
dependencies = [
"cfg-if",
"cpufeatures",
"digest",
"cpufeatures 0.2.17",
"digest 0.10.7",
]
[[package]]
@@ -2225,8 +2427,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283"
dependencies = [
"cfg-if",
"cpufeatures",
"digest",
"cpufeatures 0.2.17",
"digest 0.10.7",
]
[[package]]
@@ -2237,11 +2439,11 @@ checksum = "5f179d4e11094a893b82fff208f74d448a7512f99f5a0acbd5c679b705f83ed9"
[[package]]
name = "sha3"
version = "0.10.8"
version = "0.10.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "75872d278a8f37ef87fa0ddbda7802605cb18344497949862c0d4dcb291eba60"
checksum = "77fd7028345d415a4034cf8777cd4f8ab1851274233b45f84e3d955502d93874"
dependencies = [
"digest",
"digest 0.10.7",
"keccak",
]
@@ -2464,9 +2666,9 @@ dependencies = [
[[package]]
name = "toml_edit"
version = "0.25.9+spec-1.1.0"
version = "0.25.11+spec-1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "da053d28fe57e2c9d21b48261e14e7b4c8b670b54d2c684847b91feaf4c7dac5"
checksum = "0b59c4d22ed448339746c59b905d24568fcbb3ab65a500494f7b8c3e97739f2b"
dependencies = [
"indexmap",
"toml_datetime",
@@ -2476,9 +2678,9 @@ dependencies = [
[[package]]
name = "toml_parser"
version = "1.1.1+spec-1.1.0"
version = "1.1.2+spec-1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "39ca317ebc49f06bd748bfba29533eac9485569dc9bf80b849024b025e814fb9"
checksum = "a2abe9b86193656635d2411dc43050282ca48aa31c2451210f4202550afb7526"
dependencies = [
"winnow",
]
@@ -2546,9 +2748,9 @@ dependencies = [
[[package]]
name = "typenum"
version = "1.19.0"
version = "1.20.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "562d481066bde0658276a35467c4af00bdc6ee726305698a55b86e61d7ad82bb"
checksum = "40ce102ab67701b8526c123c1bab5cbe42d7040ccfd0f64af1a385808d2f43de"
[[package]]
name = "ucobs"
@@ -2715,9 +2917,9 @@ dependencies = [
[[package]]
name = "winnow"
version = "1.0.1"
version = "1.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "09dac053f1cd375980747450bfc7250c264eaae0583872e845c0c7cd578872b5"
checksum = "2ee1708bef14716a11bae175f579062d4554d95be2c6829f518df847b7b3fdd0"
dependencies = [
"memchr",
]
@@ -2725,15 +2927,15 @@ dependencies = [
[[package]]
name = "xtensa-lx"
version = "0.13.0"
source = "git+https://github.com/esp-rs/esp-hal.git?branch=main#70930f20d9f681a30ff20aced39d0bd5363126d5"
source = "git+https://github.com/esp-rs/esp-hal.git?branch=main#54a62c57f1f005020777a4e0843ce03c68312aba"
dependencies = [
"critical-section",
]
[[package]]
name = "xtensa-lx-rt"
version = "0.21.0"
source = "git+https://github.com/esp-rs/esp-hal.git?branch=main#70930f20d9f681a30ff20aced39d0bd5363126d5"
version = "0.22.0"
source = "git+https://github.com/esp-rs/esp-hal.git?branch=main#54a62c57f1f005020777a4e0843ce03c68312aba"
dependencies = [
"document-features",
"xtensa-lx",
@@ -2743,7 +2945,7 @@ dependencies = [
[[package]]
name = "xtensa-lx-rt-proc-macros"
version = "0.5.0"
source = "git+https://github.com/esp-rs/esp-hal.git?branch=main#70930f20d9f681a30ff20aced39d0bd5363126d5"
source = "git+https://github.com/esp-rs/esp-hal.git?branch=main#54a62c57f1f005020777a4e0843ce03c68312aba"
dependencies = [
"proc-macro2",
"quote",
+87 -23
View File
@@ -3,7 +3,7 @@ members = ["."]
[package]
name = "donglora"
version = "1.3.1"
version = "1.4.1"
edition = "2021"
build = "build.rs"
authors = ["Stephen Waits <steve@waits.net>"]
@@ -14,12 +14,14 @@ homepage = "https://github.com/donglora/firmware"
keywords = ["lora", "radio", "embedded", "usb", "firmware"]
categories = ["embedded", "hardware-support", "no-std"]
# NOTE: esp-rtos patched from GitHub main (see [patch.crates-io] below).
# Remove patches once esp-rtos publishes with embassy-executor 0.10 support.
# NOTE: esp-{hal,rtos,backtrace,println} patched from GitHub main (see
# [patch.crates-io] below). The patch versions must stay semver-compatible
# with the version requirements above, or Cargo silently drops the patch
# and falls back to the (older) crates.io release.
[dependencies]
cfg-if = "1.0"
critical-section = "1.2"
defmt = "1.0"
defmt = "0.3"
embedded-hal = "1.0"
embedded-hal-async = "1.0"
embassy-embedded-hal = "0.6"
@@ -31,9 +33,11 @@ embassy-usb-driver = "0.2"
ucobs = { version = "0.3", features = ["legacy-msrv"] }
heapless = "0.9"
donglora-protocol = "1"
hsmc = { version = "0.2", default-features = false, features = ["embassy"] }
lora-phy = "3.0"
portable-atomic = { version = "1", optional = true, default-features = false, features = ["critical-section"] }
hsmc = { version = "0.5", default-features = false, features = ["embassy", "trace-defmt"] }
# Fork branch carrying CAD IRQ-clear / standby-after-CAD fixes awaiting upstream PRs.
# Switch back to crates.io once changes are upstreamed.
lora-phy = { git = "https://github.com/swaits/lora-rs.git", branch = "fixed", features = ["defmt-03"] }
portable-atomic = { version = "1", default-features = false, features = ["critical-section"] }
static_cell = "2.1"
# Display rendering
@@ -48,17 +52,17 @@ embassy-futures = "0.1"
# Xtensa ESP crates — requires esp toolchain (espup). The chip feature
# (esp32 / esp32s3) is selected per board via the board-level feature flag
# below, so the same dep lines support both classic ESP32 and ESP32-S3.
esp-backtrace = { version = "0.18", optional = true, features = [
esp-backtrace = { version = "0.19", optional = true, features = [
"panic-handler",
"defmt",
] }
esp-hal = { version = "1.0", optional = true, features = [
esp-hal = { version = "1.1", optional = true, features = [
"unstable",
] }
esp-println = { version = "0.16", optional = true, features = [
esp-println = { version = "0.17", optional = true, features = [
"defmt-espflash",
] }
esp-rtos = { version = "0.2", optional = true, features = [
esp-rtos = { version = "0.3", optional = true, features = [
"embassy",
] }
@@ -67,12 +71,22 @@ cortex-m = { version = "0.7", optional = true, features = [
"critical-section-single-core",
] }
cortex-m-rt = { version = "0.7", optional = true }
defmt-rtt = { version = "1.0", optional = true }
defmt-rtt = { version = "0.4", optional = true }
embassy-nrf = { version = "0.10", optional = true, features = [
"nrf52840",
"gpiote",
"time-driver-rtc1",
"defmt",
# UICR pin-config flags — must match what the Adafruit nRF52 bootloader
# actually programmed into UICR on this board. Verified empirically on
# RAK4631 via `probe-rs read b32 0x10001200 4`:
# PSELRESET[0/1] = 0x12 (P0.18 connected as RESET — NOT gpio)
# NFCPINS = 0xFFFFFFFE (bit 0 = 0 → NFC pins as GPIO)
# So `nfc-pins-as-gpio` matches; `reset-pin-as-gpio` would NOT match
# (would request GPIO when UICR has RESET enabled). The bootloader
# uses NRESET for its physical button-reset path, so leaving the pin
# as RESET is the right state.
"nfc-pins-as-gpio",
] }
panic-probe = { version = "1.0", optional = true, features = ["print-defmt"] }
@@ -88,13 +102,22 @@ minijinja = "2.18"
owo-colors = "4.3"
[features]
# The `embassy` feature gates the async-actions codepath inside the `hsmc`
# statechart macro. Its `#[cfg(feature = "embassy")]` attributes are
# evaluated in *this* crate's context (a proc-macro cfg quirk), so every
# board feature must enable it. `tokio` is declared only to silence the
# macro's `#[cfg(feature = "tokio")]` checks.
# Bridge features for hsmc's macro-expanded `#[cfg(feature = "...")]`
# attributes. Macros expand into the *call-site* crate, so any cfg the
# macro emits is evaluated against THIS crate's feature set, not hsmc's.
# That means enabling `hsmc/embassy` or `hsmc/trace-defmt` via the dep
# only activates them inside hsmc's own compilation — for the cfg gates
# inside expanded macro bodies to fire here, we need same-named features
# in this Cargo.toml. `tokio` is declared just to silence the macro's
# `#[cfg(feature = "tokio")]` checks.
#
# `trace-defmt` must be in every board feature so chart trace lines
# (entries, exits, transitions, etc.) actually compile in. Without it,
# hsmc 0.4's `__chart_observe!` macro expands to nothing for the defmt
# arm and you get silent statecharts.
embassy = []
tokio = []
trace-defmt = []
# When enabled, replaces the display task with a LED-based diagnostic
# blinker driven by `crate::debug_blink::CHECKPOINT`. Used for diagnosing
# the firmware on UART-only boards where defmt output would corrupt the
@@ -102,8 +125,26 @@ tokio = []
# a human watches the pattern and reports N to determine where execution
# reached / stopped.
debug-checkpoint = []
# NOTE: chart auto-tracing in hsmc 0.4 emits `__chart_observe!` calls
# whose defmt arm is gated on `#[cfg(feature = "trace-defmt")]`. That
# cfg is evaluated against THIS crate (proc-macro cfg quirk above), so
# every board feature includes `trace-defmt` to keep the arm live. The
# `trace;` keyword in `statechart!` blocks is deprecated in 0.4 and
# no longer gates emission. Whether trace lines actually emit at
# runtime is still controlled by defmt's standard compile-time level
# filter (`DEFMT_LOG` env var) -- release builds with `DEFMT_LOG`
# unset compile the calls out to nothing.
# When enabled, the SH1106 OLED driver emits a defmt::info! line for
# every I2C transaction it issues — bytes, lengths, addresses. Used to
# debug the embassy_nrf::twim assertion panic at twim.rs:541 (cannot
# happen via the documented call path; instrumenting the SH1106 path
# captures the actual transaction sequence preceding the panic so we
# can root-cause). Off by default; opt in via
# `just flash-attach rak_wisblock_4631 debug-twim`.
debug-twim = []
heltec_v3 = [
"embassy",
"trace-defmt",
"dep:esp-backtrace",
"dep:esp-hal",
"dep:esp-println",
@@ -115,6 +156,7 @@ heltec_v3 = [
]
heltec_v3_uart = [
"embassy",
"trace-defmt",
"dep:esp-backtrace",
"dep:esp-hal",
"dep:esp-println",
@@ -126,6 +168,7 @@ heltec_v3_uart = [
]
heltec_v4 = [
"embassy",
"trace-defmt",
"dep:esp-backtrace",
"dep:esp-hal",
"dep:esp-println",
@@ -137,6 +180,7 @@ heltec_v4 = [
]
elecrow_thinknode_m2 = [
"embassy",
"trace-defmt",
"dep:esp-backtrace",
"dep:esp-hal",
"dep:esp-println",
@@ -148,6 +192,7 @@ elecrow_thinknode_m2 = [
]
lilygo_tbeam_supreme = [
"embassy",
"trace-defmt",
"dep:esp-backtrace",
"dep:esp-hal",
"dep:esp-println",
@@ -159,6 +204,7 @@ lilygo_tbeam_supreme = [
]
lilygo_tbeam = [
"embassy",
"trace-defmt",
"dep:esp-backtrace",
"dep:esp-hal",
"dep:esp-println",
@@ -170,6 +216,7 @@ lilygo_tbeam = [
]
rak_wisblock_4631 = [
"embassy",
"trace-defmt",
"dep:cortex-m",
"dep:cortex-m-rt",
"cortex-m-rt/set-vtor",
@@ -181,6 +228,7 @@ rak_wisblock_4631 = [
]
wio_tracker_l1 = [
"embassy",
"trace-defmt",
"dep:cortex-m",
"dep:cortex-m-rt",
"cortex-m-rt/set-vtor",
@@ -192,26 +240,38 @@ wio_tracker_l1 = [
]
waveshare_rp2040_lora = [
"embassy",
"trace-defmt",
"dep:cortex-m",
"dep:cortex-m-rt",
"dep:defmt-rtt",
"dep:embassy-rp",
"dep:panic-probe",
"dep:portable-atomic",
"embassy-executor/platform-cortex-m",
"embassy-executor/executor-thread",
]
# REVISIT: esp-rtos 0.2.0 on crates.io pins embassy-executor ^0.9. The
# esp-rs/esp-hal main branch already supports 0.10. Remove these patches once
# esp-rtos publishes a release with embassy-executor 0.10 support. Track:
# https://github.com/esp-rs/esp-hal/tree/main/esp-rtos
# REVISIT: pulling esp-{hal,rtos,backtrace,println} from esp-rs/esp-hal main
# to ride ahead of crates.io releases (notably for embassy-executor 0.10
# support in esp-rtos). When bumping the upstream rev, also bump the version
# requirements above to stay semver-compatible — Cargo silently ignores a
# patch whose version falls outside the requested range.
[patch.crates-io]
esp-hal = { git = "https://github.com/esp-rs/esp-hal.git", branch = "main" }
esp-rtos = { git = "https://github.com/esp-rs/esp-hal.git", branch = "main" }
esp-backtrace = { git = "https://github.com/esp-rs/esp-hal.git", branch = "main" }
esp-println = { git = "https://github.com/esp-rs/esp-hal.git", branch = "main" }
[lints.rust]
# hsmc 0.3's `statechart!` macro emits `#[cfg(feature = "journal")]`
# attributes (and others). check-cfg evaluates those in the CALLER's
# crate context, so unless donglora declares the same feature names
# (we don't — they're hsmc's, not ours), rustc lints them. Per hsmc's
# README, the documented fix is to allow the lint with an explicit
# check-cfg list so other unexpected cfgs still surface as warnings.
unexpected_cfgs = { level = "allow", check-cfg = [
'cfg(feature, values("tokio", "embassy", "journal", "trace-defmt", "trace-log", "trace-tracing"))',
] }
[lints.clippy]
undocumented_unsafe_blocks = "deny"
@@ -220,4 +280,8 @@ codegen-units = 1
lto = "fat"
opt-level = 3 # "s"/"z" break Xtensa (l32r literal range exceeded)
panic = "abort"
strip = true
# `strip = true` was killing defmt's `_defmt_version_` / `_defmt_encoding_`
# symbols, breaking RTT log decoding via probe-rs. Keep symbols + DWARF
# so probe-rs can show source locations for log lines.
strip = false
debug = 2
+174 -4
View File
@@ -1,4 +1,174 @@
- LED blinking on TX/RX? colored?
- publish new client, mux, bridge (updates in client for UART crap)
- split out mux and client repos
- move to GH organization
# Firmware TODO List
## `lora-phy` fix: drop fork pin once PRs #428 / #431 / #432 merge + release
Upstream PRs (all open):
- [#428 — *phy: add pre-command BUSY checks per Semtech
datasheets*](https://github.com/lora-rs/lora-rs/pull/428) (sx126x):
pre-command BUSY check + standby/IRQ-clear hygiene around CAD.
- [#431 — *phy: sx127x: clear stale IRQ flags in do_rx before mode
change*](https://github.com/lora-rs/lora-rs/pull/431).
- [#432 — *phy: sx127x: clear stale IRQ flags before reconfiguring DIO
mapping in set_irq_params*](https://github.com/lora-rs/lora-rs/pull/432).
Fork branch we ship from:
[`swaits/lora-rs @ fixed`](https://github.com/swaits/lora-rs/tree/fixed)
— a merge of all three fix branches kept up-to-date with upstream
`main`.
Firmware consumes the fixes via a direct `git` dependency in
`Cargo.toml`:
```toml
lora-phy = { git = "https://github.com/swaits/lora-rs.git", branch = "fixed", features = ["defmt-03"] }
```
When all three PRs merge and a `lora-phy` release ships on crates.io
that contains them, switch this line back to a normal
`lora-phy = "X.Y"` crates.io version and drop the explanatory comment
block above it.
Hardware impact: large stability gain on every board — the sx126x
BUSY-race fix lands on every nRF/RP2040 board, and the sx127x IRQ-clear
fixes unblock TBeam classic in particular. Hardware-verified on Wio
Tracker L1 (sx126x): 20/20 clean-boot TX after the fix (vs ~50%
before).
---
## Drop `[patch.crates-io]` + upgrade esp-hal / esp-rtos + add `esp_app_desc!()` + bump espflash to v4
Single coordinated change that clears our last remaining dep-graph debt
on the ESP boards. All four pieces are coupled, so they land together.
### Why
Today `Cargo.toml` overrides `esp-hal`, `esp-rtos`, `esp-backtrace`, and
`esp-println` with a git pin to `esp-rs/esp-hal#main`. The note in that
block explains the historical reason:
> REVISIT: esp-rtos 0.2.0 on crates.io pins embassy-executor ^0.9. The
> esp-rs/esp-hal main branch already supports 0.10. Remove these
> patches once esp-rtos publishes a release with embassy-executor 0.10
> support.
**That condition is now met.** `esp-rtos 0.3.0` is published on crates.io
and depends on `embassy-executor ^0.10` and `esp-hal ~1.1.0-rc.0` — exactly
what our patches were pulling unofficially. Keeping the patches is no
longer free: it blocks `espflash` v4, blocks `esp-bootloader-esp-idf`, and
ties reproducible builds to whatever commit happens to be on
`esp-rs/esp-hal#main`.
The immediate trigger is `espflash` v4's required
`esp_bootloader_esp_idf::esp_app_desc!()` check. `save-image` refuses any
ESP binary that lacks the IDF app descriptor. The crate that provides the
macro (`esp-bootloader-esp-idf`) uses the same `esp-rom-sys` native
library as `esp-hal` — two copies of the same `links = "esp_rom_sys"` is
a hard cargo error, so `esp-bootloader-esp-idf` must come from the _same
source_ as `esp-hal`. Easiest way to guarantee that: both from crates.io,
no patches.
### What changes
1. **`Cargo.toml`** — delete the entire `[patch.crates-io]` block and the
preceding `REVISIT:` comment. Bump the four esp-rs deps to published
versions:
- `esp-hal = "1.0"` → `"1.1.0-rc.0"` (pre-release selector — see Gotchas)
- `esp-rtos = "0.2"` → `"0.3"`
- `esp-backtrace = "0.18"` → whatever matches esp-rtos 0.3 (check its deps)
- `esp-println = "0.16"` → same
Add a new optional dep + feature wiring for
`esp-bootloader-esp-idf = "0.5"` with `defmt` feature, plus per-board
chip feature (`esp-bootloader-esp-idf/esp32s3` for the S3 boards,
`esp-bootloader-esp-idf/esp32` for LilyGo T-Beam classic).
2. **`src/main.rs`** — inside the ESP-family branch of the existing
`cfg_if!` block (around line 51), invoke the macro at module scope:
```rust
esp_bootloader_esp_idf::esp_app_desc!();
```
Zero runtime cost. Emits ~256 bytes in `.rodata_desc` with app
metadata (name, version, build date) that the ESP-IDF 2nd-stage
bootloader + `espflash save-image` look for.
3. **`mise.toml`** — `"cargo:espflash" = "3"` → `"4"`. Drop the deferral
comment on that line.
4. **Possible API drift fixes** — esp-hal's pre-release versions
occasionally rename or move items. Most likely touch points:
- `src/board/esp32.rs`, `src/board/esp32s3.rs`
- Any board file in `src/board/heltec_*.rs`, `lilygo_*.rs`,
`elecrow_*.rs` that calls into esp-hal / esp-rtos init
Run `just check-all` after steps 1–3 and patch up whatever surfaces.
Don't guess — read the actual compiler errors.
### How (step by step)
1. `jj new -m "chore(esp): drop esp-hal patches, bump to published versions, add esp_app_desc!()"`
2. Edit `Cargo.toml` — delete `[patch.crates-io]` + `REVISIT:` comment;
bump the four versions; add `esp-bootloader-esp-idf` dep + feature
wiring for each ESP board feature block.
3. Edit `src/main.rs` — add `esp_bootloader_esp_idf::esp_app_desc!();`
to the ESP branch of the top-level `cfg_if!`.
4. Edit `mise.toml` — espflash `"3"` → `"4"`.
5. `mise install` to pull espflash 4.x.
6. `cargo update` to let the resolver pick a consistent tree with the
new requirements.
7. `just check-all` — expect some compilation errors from API drift on
ESP boards. Fix them one at a time; consult the official examples
in `esp-rs/esp-hal` if in doubt.
8. `just build heltec_v3` (or any ESP board you have) — verify
`espflash save-image` now succeeds end-to-end producing a valid
`.bin`.
9. Flash to real hardware if available. **The RAK4631 and Wio Tracker
L1 (nRF52) boards should be untouched.**
### Verification
- `just check-all` clean on all 9 boards.
- `just test` (host-side protocol tests) still green.
- For each ESP board that has been physically validated before
(Heltec V3, LilyGo T-Beam units): flash + confirm radio TX works
end-to-end via ai-bot or a known peer.
- RAK4631 + Wio Tracker L1 unchanged; re-check via `just check` on
both, but no re-flash needed (they don't go through the ESP code
path).
### Gotchas
- **Pre-release version selector**: `esp-hal = "1.1.0-rc.0"` by itself
does NOT match pre-release versions in cargo's default semver rules.
Use an exact pre-release like `"1.1.0-rc.0"`, `"~1.1.0-rc.0"` (only
`1.1.0-rc.0`, `1.1.0-rc.1`, … with any patch), or `">=1.1.0-rc.0"`.
`"1.1"` will NOT resolve to a pre-release.
- **Two copies of `esp-rom-sys`**: the root cause of the first failed
attempt at this task. If cargo errors with _"Only one package in the
dependency graph may specify the same links value"_ for
`esp_rom_sys`, it means `esp-hal` and `esp-bootloader-esp-idf` are
being pulled from different sources (one crates.io, one git). Either
both from crates.io (this task's plan) or both from the same git
commit.
- **`esp-bootloader-esp-idf` chip features**: the crate needs exactly
one of `esp32 / esp32s3 / esp32c3 / esp32c6 / …` to be enabled.
Without it, the build panics at its `build.rs`: _"Expected exactly
one of the following features to be enabled: esp32, esp32c2, ..."_.
Wire per-board the same way we wire `esp-hal/esp32s3` etc.
- **Probe-less repro**: `mise install` after bumping espflash to "4"
only installs mise's copy. If the user's global
`~/.cargo/bin/espflash` is stale/different, it still wins on PATH.
The justfile `set shell := ["mise", "exec", "--", "sh", "-c"]`
prepends mise's paths but does NOT reorder `~/.cargo/bin` ahead of
them. Either `cargo uninstall espflash` globally, or change the
justfile recipes to call `$(mise which espflash)` explicitly.
### Why not now
Tried it alongside the RAK4631 bring-up in April 2026 and bounced off
the `esp-rom-sys` two-copies problem. Backed out the attempt and left
espflash pinned at v3 + the patches in place so the bring-up commit
stayed atomic and shippable. This task is what's needed to unblock v4
properly, but it deserves its own focused session — not as
"while-I'm-here" scope on a board bring-up.
+19 -7
View File
@@ -108,19 +108,31 @@ fn main() {
println!("cargo:rerun-if-changed=src/board/mod.rs.j2");
println!("cargo:rerun-if-changed={}", board_dir);
// cortex-m-rt's link.x does `INCLUDE memory.x`. Copy the correct layout
// into OUT_DIR based on the target MCU family.
// cortex-m-rt's link.x does `INCLUDE memory.x`. Resolve the layout
// in two steps:
// 1. Per-board override: `ld/{board}-memory.x` if it exists.
// 2. MCU-family default by target triple.
// The override path is for boards that deviate from the family
// default (e.g. WIO Tracker L1 currently has no SoftDevice in flash
// and needs ORIGIN=0x1000 instead of the SD-aware 0x26000). Drop
// the per-board file once the layout matches the family default.
let target = std::env::var("TARGET").unwrap_or_default();
let memory_x = match target.as_str() {
"thumbv7em-none-eabihf" => Some("ld/nrf52840-memory.x"),
"thumbv6m-none-eabi" => Some("ld/rp2040-memory.x"),
_ => None,
let board_specific = format!("ld/{}-memory.x", enabled[0]);
let memory_x: Option<String> = if std::path::Path::new(&board_specific).exists() {
Some(board_specific.clone())
} else {
match target.as_str() {
"thumbv7em-none-eabihf" => Some("ld/nrf52840-memory.x".to_string()),
"thumbv6m-none-eabi" => Some("ld/rp2040-memory.x".to_string()),
_ => None,
}
};
if let Some(src) = memory_x {
let out_dir = std::env::var("OUT_DIR").unwrap();
fs::copy(src, format!("{out_dir}/memory.x")).expect("failed to copy memory.x");
fs::copy(&src, format!("{out_dir}/memory.x")).expect("failed to copy memory.x");
println!("cargo:rustc-link-search={out_dir}");
}
println!("cargo:rerun-if-changed=ld/nrf52840-memory.x");
println!("cargo:rerun-if-changed=ld/rp2040-memory.x");
println!("cargo:rerun-if-changed={}", board_specific);
}
+6
View File
@@ -0,0 +1,6 @@
workers = ["app.routes"]
[settings]
cache = ".script"
address = "127.0.0.1"
port = 3500
File diff suppressed because it is too large. Load diff
+99 -64
View File
@@ -1,43 +1,30 @@
set shell := ["bash", "-c"]
# Board definitions: feature target chip
# Xtensa targets use the self-contained esp toolchain (espup-installed) with
# `-Zbuild-std=core,alloc`. Using `+esp` rather than `+nightly` keeps the
# compiler and rust-src versions aligned — the public nightly drifts ahead of
# the esp fork and breaks core-stdlib compilation otherwise.
# Tool versions are pinned in mise.toml; run `just setup` to install everything.
heltec_v3 := "heltec_v3 xtensa-esp32s3-none-elf esp32s3"
heltec_v3_uart := "heltec_v3_uart xtensa-esp32s3-none-elf esp32s3"
heltec_v4 := "heltec_v4 xtensa-esp32s3-none-elf esp32s3"
elecrow_thinknode_m2 := "elecrow_thinknode_m2 xtensa-esp32s3-none-elf esp32s3"
lilygo_tbeam := "lilygo_tbeam xtensa-esp32-none-elf esp32"
lilygo_tbeam_supreme := "lilygo_tbeam_supreme xtensa-esp32s3-none-elf esp32s3"
rak_wisblock_4631 := "rak_wisblock_4631 thumbv7em-none-eabihf nRF52840_xxAA"
wio_tracker_l1 := "wio_tracker_l1 thumbv7em-none-eabihf nRF52840_xxAA"
waveshare_rp2040_lora := "waveshare_rp2040_lora thumbv6m-none-eabi rp2040"
# Run every recipe with mise's tool versions active — so `just` invocations
# of cargo, espflash, rust-objcopy, etc. always resolve to the pinned
# versions in mise.toml, even if the user has a different version elsewhere
# on PATH (e.g. a stray `cargo install espflash`).
set shell := ["mise", "exec", "--", "sh", "-c"]
builds_dir := "builds"
version := `sed -n 's/^version = "\(.*\)"/\1/p' Cargo.toml`
# All known boards
# All known boards. ADD A NEW BOARD HERE and in the `_info` case below.
#
# Board metadata ("feature target chip") lives in the `_info` recipe —
# Xtensa targets are built with `+esp` + `-Zbuild-std=core,alloc` (the
# self-contained esp toolchain ships its own rust-src; the public
# nightly drifts ahead and breaks core-stdlib compilation).
boards := "heltec_v3 heltec_v3_uart heltec_v4 elecrow_thinknode_m2 lilygo_tbeam lilygo_tbeam_supreme rak_wisblock_4631 waveshare_rp2040_lora wio_tracker_l1"
# Install all required tools and toolchains
setup:
mise trust --yes
mise install
@# ESP Xtensa toolchain (not managed by mise)
@# ESP Xtensa toolchain — installed via the `esp-install` mise task
@# (which pins versions to match mise.toml's [env] paths).
@if ! rustup toolchain list | grep -q "^esp"; then \
echo "ESP toolchain not found, installing via espup (this may take a while)..."; \
espup install || { echo "error: espup install failed" >&2; exit 1; }; \
echo "ESP toolchain not found, installing via mise task (this may take a while)..."; \
mise run esp-install || { echo "error: esp-install task failed" >&2; exit 1; }; \
fi
@# nightly rust-src for -Zbuild-std
@if ! rustup component list --toolchain nightly --installed 2>/dev/null | grep -q "^rust-src"; then \
rustup component add rust-src --toolchain nightly; \
fi
@# ARM targets
@rustup target list --installed | grep -q "^thumbv6m-none-eabi$" || rustup target add thumbv6m-none-eabi
@rustup target list --installed | grep -q "^thumbv7em-none-eabihf$" || rustup target add thumbv7em-none-eabihf
# Build release firmware for all boards, installing toolchains as needed
build-all:
@@ -67,16 +54,20 @@ check-all:
check board:
@just _cargo {{board}} "clippy --release" "-- -D warnings"
# Build release firmware and copy to builds/ with a readable name
build board profile="release":
@just _cargo {{board}} "build --{{profile}}"
# Build release firmware and copy to builds/ with a readable name.
# `extra_features` (comma-separated) is appended to the board feature,
# e.g. `just build wio_tracker_l1 release debug-checkpoint`.
build board profile="release" extra_features="":
@just _cargo {{board}} "build --{{profile}}" "" "{{extra_features}}"
@just _copy_firmware {{board}} {{profile}}
# Build and flash a board (espflash for Xtensa, UF2 DFU for ARM)
flash board:
# Build and flash a board (espflash for Xtensa, UF2 DFU for ARM).
# `extra_features` is passed through to the build, e.g.
# `just flash wio_tracker_l1 debug-checkpoint`.
flash board extra_features="":
@just _ensure_tools
@just build {{board}} release
@read -r feat target chip <<< "$(just _info {{board}})"; \
@just build {{board}} release "{{extra_features}}"
@set -- $(just _info {{board}}); feat=$1; target=$2; chip=$3; \
case "$target" in \
xtensa-*) \
port=$(just _find_port "303a:1001" "1209:5741" "10c4:ea60" "1a86:7522" "1a86:7523"); \
@@ -90,13 +81,50 @@ flash board:
*) just _flash_uf2 {{board}} ;; \
esac
# Flash ARM board via debug probe (requires J-Link or similar)
flash-probe board:
# Flash ARM board via debug probe (requires J-Link or similar).
# `extra_features` is passed through to the build.
# Sets DEFMT_LOG at build time so defmt::info!/warn!/error! are actually
# compiled in (default filter is ERROR-only — strips info logs).
# `embassy_usb=error` silences the benign Linux modem-manager
# `SET_INTERFACE: alt setting out of range` WARN that fires once per
# enumeration; it's a normal STALL response (correct USB behavior),
# the WARN is just embassy_usb noise. Other crates inherit the `info`
# default so chart traces, our own info!/warn!/error! all still fire.
flash-probe board extra_features="":
@just _ensure_tools
@just build {{board}} release
@read -r feat target chip <<< "$(just _info {{board}})"; \
@DEFMT_LOG=info,embassy_usb=error just build {{board}} release "{{extra_features}}"
@set -- $(just _info {{board}}); feat=$1; target=$2; chip=$3; \
probe-rs run --chip $chip "{{builds_dir}}/donglora-{{board}}-v{{version}}.elf"
# UF2-flash via the bootloader, then probe-rs attach for RTT log streaming.
# Required on boards (e.g. RAK4631) where the bootloader gates the app
# behind a "valid app flag" in its settings page that only the bootloader
# itself can set — `probe-rs run`'s direct SWD writes bypass that flag and
# leave the bootloader stuck in DFU mode. UF2 path goes through the
# bootloader, sets the flag, then we attach for RTT (no reset, no reflash).
flash-attach board extra_features="":
@just _ensure_tools
@DEFMT_LOG=info,embassy_usb=error just build {{board}} release "{{extra_features}}"
@just _flash_uf2 {{board}}
@set -- $(just _info {{board}}); feat=$1; target=$2; chip=$3; \
sleep 1; \
probe-rs attach --chip $chip --no-catch-reset \
"{{builds_dir}}/donglora-{{board}}-v{{version}}.elf"
# Attach probe-rs for live RTT/defmt streaming WITHOUT flashing or
# resetting the chip. Logs are tee'd to a UTC-timestamped file in /tmp
# so soak captures don't clobber each other across runs. Use this with
# the dongle already running the desired firmware (flash via `just flash`
# or `just flash-attach` first).
attach board:
@just _ensure_tools
@set -- $(just _info {{board}}); feat=$1; target=$2; chip=$3; \
log="/tmp/donglora-soak-$(date -u +%Y%m%dT%H%M%SZ).log"; \
echo "Logging to $log"; \
probe-rs attach --chip $chip --no-catch-reset \
"{{builds_dir}}/donglora-{{board}}-v{{version}}.elf" 2>&1 \
| tee "$log"
# Show binary size for a release build
size board:
@just _cargo {{board}} "size --release"
@@ -116,16 +144,17 @@ outdated:
_ensure_tools:
@mise trust --yes . 2>/dev/null; mise install --quiet
# Run a cargo command for a board.
# Run a cargo command for a board, optionally with extra Cargo features
# (comma-separated, e.g. "debug-checkpoint").
# Xtensa: esp toolchain (cargo + rustc + rust-src together) + -Zbuild-std=core
[private]
_cargo board cmd extra_args="":
_cargo board cmd extra_args="" extra_features="":
@just _ensure_tools
@read -r feat target chip <<< "$(just _info {{board}})"; \
@set -- $(just _info {{board}}); feat=$1; target=$2; chip=$3; \
[ -n "{{extra_features}}" ] && feat="$feat,{{extra_features}}"; \
extra=""; buildstd=""; \
case "$target" in xtensa-*) \
just _require_esp_toolchain; \
[ -f "$HOME/export-esp.sh" ] && . "$HOME/export-esp.sh"; \
extra="+esp"; buildstd="-Zbuild-std=core,alloc";; \
esac; \
cargo $extra {{cmd}} --target "$target" --features "$feat" $buildstd {{extra_args}}
@@ -133,21 +162,23 @@ _cargo board cmd extra_args="":
# Ensure a board's toolchain is available, auto-installing if needed
[private]
_can_build board:
@read -r feat target chip <<< "$(just _info {{board}})"; \
@set -- $(just _info {{board}}); feat=$1; target=$2; chip=$3; \
case "$target" in \
xtensa-*) just _require_esp_toolchain ;; \
*) rustup target list --installed | grep -q "^$target$" || rustup target add "$target" ;; \
esac
# Ensure the ESP Xtensa toolchain is installed (espup installed via mise).
# The esp toolchain ships with its own cargo, rustc, and rust-src — no extra
# Ensure the ESP Xtensa toolchain is installed. The actual install is
# delegated to the `esp-install` mise task so the version pin lives in
# mise.toml alongside the matching [env] PATH/LIBCLANG_PATH entries.
# The esp toolchain ships its own cargo, rustc, and rust-src — no extra
# components are needed on top.
[private]
_require_esp_toolchain:
@just _ensure_tools
@if ! rustup toolchain list | grep -q "^esp"; then \
echo "ESP toolchain not found, installing via espup (this may take a while)..." >&2; \
espup install || { echo "error: espup install failed" >&2; exit 1; }; \
echo "ESP toolchain not found, installing via mise task (this may take a while)..." >&2; \
mise run esp-install || { echo "error: esp-install task failed" >&2; exit 1; }; \
fi
# Find a serial port matching any of the given VID:PID pairs (checked in order)
@@ -169,25 +200,25 @@ _find_port +vid_pids:
[private]
_copy_firmware board profile:
@mkdir -p {{builds_dir}}
@read -r feat target chip <<< "$(just _info {{board}})"; \
@set -- $(just _info {{board}}); feat=$1; target=$2; chip=$3; \
src="target/$target/{{profile}}/donglora"; \
dst="{{builds_dir}}/donglora-{{board}}-v{{version}}"; \
if [ -f "$src" ]; then \
cp "$src" "$dst.elf"; echo "→ $dst.elf"; \
case "$target" in \
xtensa-*) \
mise exec -- espflash save-image --chip "$chip" --merge --skip-padding "$src" "$dst.bin"; \
espflash save-image --chip "$chip" --merge --skip-padding "$src" "$dst.bin"; \
echo "→ $dst.bin"; \
;; \
thumbv6m-*) \
mise exec -- rust-objcopy -O ihex "$src" "$dst.hex"; \
mise exec -- cargo-hex-to-uf2 hex-to-uf2 --input-path "$dst.hex" --output-path "$dst.uf2" --family rp2040; \
rust-objcopy -O ihex "$src" "$dst.hex"; \
cargo-hex-to-uf2 hex-to-uf2 --input-path "$dst.hex" --output-path "$dst.uf2" --family rp2040; \
rm "$dst.hex"; \
echo "→ $dst.uf2"; \
;; \
thumbv7em-*) \
mise exec -- rust-objcopy -O ihex "$src" "$dst.hex"; \
mise exec -- cargo-hex-to-uf2 hex-to-uf2 --input-path "$dst.hex" --output-path "$dst.uf2" --family nrf52840; \
rust-objcopy -O ihex "$src" "$dst.hex"; \
cargo-hex-to-uf2 hex-to-uf2 --input-path "$dst.hex" --output-path "$dst.uf2" --family nrf52840; \
rm "$dst.hex"; \
echo "→ $dst.uf2"; \
;; \
@@ -210,15 +241,19 @@ _flash_uf2 board:
sync; \
echo "Done — board will reboot automatically"
# Single source of truth for per-board metadata: "feature target chip".
# ADD A NEW BOARD HERE and in the `boards` list near the top of this file.
[private]
_info name:
@if [ "{{name}}" == "heltec_v3" ]; then echo "{{heltec_v3}}"; \
elif [ "{{name}}" == "heltec_v3_uart" ]; then echo "{{heltec_v3_uart}}"; \
elif [ "{{name}}" == "heltec_v4" ]; then echo "{{heltec_v4}}"; \
elif [ "{{name}}" == "elecrow_thinknode_m2" ]; then echo "{{elecrow_thinknode_m2}}"; \
elif [ "{{name}}" == "lilygo_tbeam" ]; then echo "{{lilygo_tbeam}}"; \
elif [ "{{name}}" == "lilygo_tbeam_supreme" ]; then echo "{{lilygo_tbeam_supreme}}"; \
elif [ "{{name}}" == "rak_wisblock_4631" ]; then echo "{{rak_wisblock_4631}}"; \
elif [ "{{name}}" == "waveshare_rp2040_lora" ]; then echo "{{waveshare_rp2040_lora}}"; \
elif [ "{{name}}" == "wio_tracker_l1" ]; then echo "{{wio_tracker_l1}}"; \
else echo "Unknown board: {{name}}" >&2; exit 1; fi
@case "{{name}}" in \
heltec_v3) echo "heltec_v3 xtensa-esp32s3-none-elf esp32s3" ;; \
heltec_v3_uart) echo "heltec_v3_uart xtensa-esp32s3-none-elf esp32s3" ;; \
heltec_v4) echo "heltec_v4 xtensa-esp32s3-none-elf esp32s3" ;; \
elecrow_thinknode_m2) echo "elecrow_thinknode_m2 xtensa-esp32s3-none-elf esp32s3" ;; \
lilygo_tbeam) echo "lilygo_tbeam xtensa-esp32-none-elf esp32" ;; \
lilygo_tbeam_supreme) echo "lilygo_tbeam_supreme xtensa-esp32s3-none-elf esp32s3" ;; \
rak_wisblock_4631) echo "rak_wisblock_4631 thumbv7em-none-eabihf nRF52840_xxAA" ;; \
waveshare_rp2040_lora) echo "waveshare_rp2040_lora thumbv6m-none-eabi rp2040" ;; \
wio_tracker_l1) echo "wio_tracker_l1 thumbv7em-none-eabihf nRF52840_xxAA" ;; \
*) echo "Unknown board: {{name}}" >&2; exit 1 ;; \
esac
+9 -4
View File
@@ -1,16 +1,21 @@
/* nRF52840 memory layout — Adafruit UF2 bootloader
/* nRF52840 memory layout — Adafruit UF2 bootloader + s140 SoftDevice
*
* 0x00000 – 0x01000 MBR (Master Boot Record)
* 0x01000 – 0xEA000 Application ← we live here
* 0x01000 – 0x26000 s140 SoftDevice (dormant — we don't use BLE)
* 0x26000 – 0xEA000 Application ← we live here
* 0xEA000 – 0xF4000 Reserved (app data)
* 0xF4000 – 0xFC000 UF2 Bootloader
* 0xFF000 – 0x100000 Bootloader settings
*
* RAM: first 8 bytes reserved for MBR interrupt forwarding.
* RAM: first 8 bytes reserved for MBR interrupt forwarding. SoftDevice
* RAM (typically 0x20000008–0x20002000) is NOT reserved here because we
* never call sd_softdevice_enable — SD sits dormant in flash and never
* touches RAM. cortex-m-rt's set-vtor feature handles relocating VTOR
* to the app's vector table at 0x26000 at runtime.
*/
MEMORY
{
FLASH : ORIGIN = 0x00001000, LENGTH = 0xE9000
FLASH : ORIGIN = 0x00026000, LENGTH = 0xCE000
RAM : ORIGIN = 0x20000008, LENGTH = 255K
}
+25
View File
@@ -0,0 +1,25 @@
/* Wio Tracker L1 memory layout — UF2 bootloader, NO SoftDevice
*
* 0x00000 – 0x01000 MBR (Master Boot Record)
* 0x01000 – 0xEA000 Application ← we live here (no SD present)
* 0xEA000 – 0xF4000 Reserved (app data)
* 0xF4000 – 0xFC000 UF2 Bootloader
* 0xFF000 – 0x100000 Bootloader settings
*
* Background: Seeed factory firmware ships s140 SoftDevice at
* 0x01000–0x26000, but our earlier UF2 flashes (with the original
* `ORIGIN = 0x1000` layout) silently overwrote that region. The WIO
* bootloader now reports `SoftDevice: not found`; until we restore
* s140 via SWD, the app must live at 0x1000 to match the bootloader's
* no-SD boot chain.
*
* Delete this file once SD is reinstalled — `build.rs` will then fall
* back to `ld/nrf52840-memory.x` (the SD-aware default at 0x26000)
* and the WIO matches every other nRF52840 board.
*/
MEMORY
{
FLASH : ORIGIN = 0x00001000, LENGTH = 0xE9000
RAM : ORIGIN = 0x20000008, LENGTH = 255K
}
+43 -6
View File
@@ -1,9 +1,46 @@
[tools]
rust = "1.94"
just = "latest"
"cargo:cargo-binutils" = "latest" # `cargo size`, `cargo objdump`, etc.
"cargo:cargo-hex-to-uf2" = "latest" # ELF → UF2 via Intel HEX for nRF52840 DFU
"cargo:espup" = "0.16"
"cargo:espflash" = "3" # 4.x has broken nix dependency on current stable Rust
"cargo:probe-rs-tools" = "0.31"
# Cargo-installed tooling via mise's `cargo:` backend.
"cargo:cargo-binutils" = "latest" # rust-objcopy, rust-size
"cargo:cargo-hex-to-uf2" = "latest" # ELF → UF2 for nRF52 / RP2040 DFU drives
"cargo:espup" = "0.17.1" # ESP Xtensa toolchain installer (pinned: [env] paths below match this version's defaults)
"cargo:espflash" = "3" # flash + save-image for ESP targets (4.x requires esp_app_desc!() in app — revisit alongside esp-hal 1.1+ / drop-the-patches cleanup)
"cargo:probe-rs-tools" = "latest" # debug-probe flash/run for ARM targets
# Stable Rust + cross-compile targets. Targets land under $RUSTUP_HOME for
# the pinned toolchain, so they're always available under `mise exec` — no
# extra `rustup target add` step at setup time.
#
# Xtensa ESP targets are NOT listed here — they use the self-contained `esp`
# toolchain populated by `mise run esp-install` (see [tasks] below). That
# toolchain ships its own rust-src for `-Zbuild-std`.
#
# profile = "minimal" (just rustc, rust-std, cargo), "default" (adds rust-docs, rustfmt, clippy)
#
[tools.rust]
version = "1.94"
profile = "default"
targets = "thumbv6m-none-eabi,thumbv7em-none-eabihf"
# ESP Xtensa toolchain. `cargo:espup` above only installs the *installer*;
# the actual rustc-esp + xtensa-esp-elf-gcc + esp-clang toolchains are
# populated by `mise run esp-install` (or `just setup`).
#
# espup hardcodes its install root to ~/.rustup/toolchains/esp/ — there's
# no --prefix or --install-dir flag — so the binaries necessarily live
# there. The [env] block below pins the exact PATH and LIBCLANG_PATH so
# every `mise exec` (which the justfile uses for `set shell`) resolves
# the cross-toolchain without depending on espup's stray ~/export-esp.sh.
#
# Bumping versions: edit the version dirs in BOTH [tasks.esp-install] (so
# espup installs the matching crosstool) AND [env] (so the path resolves).
[env]
_.path = [
"{{env.HOME}}/.rustup/toolchains/esp/xtensa-esp-elf/esp-15.2.0_20250920/xtensa-esp-elf/bin",
]
LIBCLANG_PATH = "{{env.HOME}}/.rustup/toolchains/esp/xtensa-esp32-elf-clang/esp-20.1.1_20250829/esp-clang/lib"
[tasks.esp-install]
description = "Install the ESP Xtensa toolchain (rustc-esp + GCC + clang) at versions matching [env]"
run = "espup install --crosstool-toolchain-version esp-15.2.0_20250920"
+2 -2
View File
@@ -86,8 +86,8 @@ pub fn init_radio(
let reset = Output::new(reset_pin, Level::High, OutputConfig::default());
let dio0 = Input::new(dio0_pin, InputConfig::default().with_pull(Pull::Down));
let iv = GenericSx127xInterfaceVariant::new(reset, dio0, None, None)
.expect("SX1276 interface init");
let iv =
GenericSx127xInterfaceVariant::new(reset, dio0, None, None).expect("SX1276 interface init");
let sx_config = sx127x::Config {
chip: sx127x::Sx1276,
+60 -26
View File
@@ -20,13 +20,20 @@ type RadioSpiDevice = SpiDevice<'static, NoopRawMutex, mcu::SpiBus, Nss>;
pub type RadioDriver = Sx126x<RadioSpiDevice, Iv, Sx1262>;
pub type UsbDriver = mcu::UsbNrfDriver;
pub type DisplayI2c = mcu::I2cBus;
pub type LedDriver = ();
pub type LedDriver = crate::driver::simple_led::SimpleLed<Output<'static>>;
pub type DisplayDriver = ssd1306::Ssd1306Async<
ssd1306::prelude::I2CInterface<DisplayI2c>,
ssd1306::size::DisplaySize128x64,
ssd1306::mode::BufferedGraphicsModeAsync<ssd1306::size::DisplaySize128x64>,
>;
// SH1106 hand-rolled driver instead of the ssd1306 crate. The RAK1921
// OLED ships under various Chinese-OEM packaging (e.g. JMD0.96C) that
// can be either SSD1306 or SH1106 silicon — physically and pin
// identical, but use different addressing modes. The bigger reason
// though: ssd1306 0.10's display-interface-i2c emits I2C transaction
// patterns (consecutive writes, 3+ ops) that embassy_nrf::twim's
// `unreachable!()` rejects, so even on real SSD1306 silicon the panic
// would fire. Our hand-rolled SH1106 driver issues only single writes
// per logical op and is twim-safe. SH1106 init opcodes are similar
// enough that real SSD1306 silicon mostly works (worst case: mirrored
// display until proper runtime detection lands).
pub type DisplayDriver = crate::driver::sh1106::Sh1106<DisplayI2c>;
// ── Peripheral bundles ──────────────────────────────────────────────
@@ -46,22 +53,29 @@ pub struct DisplayParts {
// ── Display init ────────────────────────────────────────────────────
pub async fn create_display(i2c: DisplayI2c) -> Option<DisplayDriver> {
use ssd1306::mode::DisplayConfigAsync;
use ssd1306::prelude::{Brightness, DisplayRotation};
use ssd1306::size::DisplaySize128x64;
use ssd1306::{I2CDisplayInterface, Ssd1306Async};
let mut display = crate::driver::sh1106::Sh1106::new(i2c, 0x3C);
let interface = I2CDisplayInterface::new(i2c);
let mut display = Ssd1306Async::new(interface, DisplaySize128x64, DisplayRotation::Rotate0)
.into_buffered_graphics_mode();
embassy_time::Timer::after_millis(100).await;
if display.init().await.is_err() {
defmt::error!("SSD1306 display init failed");
return None;
// Retry 3× with 100ms backoff. The SH1106's first transaction
// after power-on can return Err if the chip's internal voltage
// converter hasn't fully settled — observed empirically on
// RAK4631/RAK1921. Each attempt is independent (full init
// sequence). Display works visibly even if the FIRST attempt
// failed, because subsequent attempts succeed.
for attempt in 0..3u8 {
embassy_time::Timer::after_millis(100).await;
if display.init().await.is_ok() {
let _ = display.set_brightness(0xFF).await;
return Some(display);
}
if attempt < 2 {
defmt::warn!(
"SH1106 display init attempt {=u8}/3 failed; retrying",
attempt + 1
);
}
}
let _ = display.set_brightness(Brightness::BRIGHTEST).await;
Some(display)
defmt::error!("SH1106 display init failed after 3 attempts");
None
}
// ── Board init ──────────────────────────────────────────────────────
@@ -78,10 +92,14 @@ impl LoRaBoard for Board {
type CommParts = UsbParts;
type DisplayParts = DisplayParts;
type DisplayDriver = DisplayDriver;
type LedDriver = ();
type LedDriver = LedDriver;
fn init() -> Self {
let p = embassy_nrf::init(Default::default());
// USB requires the 32 MHz HFXO (±50 ppm); the RC oscillator is out of spec.
let mut config = embassy_nrf::config::Config::default();
config.hfclk_source = embassy_nrf::config::HfclkSource::ExternalXtal;
config.lfclk_source = embassy_nrf::config::LfclkSource::ExternalXtal;
let p = embassy_nrf::init(config);
Self { p }
}
@@ -89,12 +107,18 @@ impl LoRaBoard for Board {
mcu::mac_address()
}
fn into_parts(self) -> BoardParts<RadioParts, UsbParts, DisplayParts, ()> {
fn into_parts(self) -> BoardParts<RadioParts, UsbParts, DisplayParts, LedDriver> {
let p = self.p;
// SX1262 is power-gated on P1.05 — must be HIGH before any SPI access.
let sx_power_en = Output::new(p.P1_05, Level::High, OutputDrive::Standard);
core::mem::forget(sx_power_en);
// ── SPI bus for SX1262 ──────────────────────────────────
let mut spi_cfg = spim::Config::default();
spi_cfg.frequency = spim::Frequency::M1;
// embassy_nrf::spim::Spim::new args: (spim, irq, sck, miso, mosi, config).
// Per RAK4631 BSP: SCK=P1.11, MISO=P1.13, MOSI=P1.12.
let spi = Spim::new(p.SPI3, mcu::Irqs, p.P1_11, p.P1_13, p.P1_12, spi_cfg);
let spi_bus = mcu::share_spi_bus(spi);
@@ -103,7 +127,11 @@ impl LoRaBoard for Board {
let reset = Output::new(p.P1_06, Level::High, OutputDrive::Standard);
let dio1 = Input::new(p.P1_15, Pull::Down);
let busy = Input::new(p.P1_14, Pull::Down);
// BUSY has an internal 20 kΩ pull-up on the SX1262 die (datasheet
// p. 53); an MCU-side Pull::Down fights it and leaves the line at
// an indeterminate voltage, making wait_on_busy unreliable. See
// lora-rs/lora-rs#260.
let busy = Input::new(p.P1_14, Pull::None);
let iv = GenericSx126xInterfaceVariant::new(reset, dio1, busy, None, None)
.expect("SX1262 interface init");
@@ -121,7 +149,9 @@ impl LoRaBoard for Board {
};
// ── USB ─────────────────────────────────────────────────
let vbus = mcu::alloc_vbus_detect(true, false);
// SoftwareVbusDetect(vbus_detected, power_ready). Mark both true so the
// driver doesn't block waiting for a power-ready signal we never raise.
let vbus = mcu::alloc_vbus_detect(true, true);
let host = UsbParts {
driver: Driver::new(p.USBD, mcu::Irqs, vbus),
};
@@ -138,11 +168,15 @@ impl LoRaBoard for Board {
);
let display = Some(DisplayParts { i2c });
// Green LED on P1.03 (RAK19007 Base, active HIGH).
let led_pin = Output::new(p.P1_03, Level::Low, OutputDrive::Standard);
let led = crate::driver::simple_led::SimpleLed(led_pin);
BoardParts {
radio,
host,
display,
led: (),
led,
mac: Self::mac_address(),
}
}
+5 -1
View File
@@ -96,7 +96,11 @@ impl LoRaBoard for Board {
let reset = Output::new(p.P1_07, Level::High, OutputDrive::Standard);
let dio1 = Input::new(p.P0_07, Pull::Down);
let busy = Input::new(p.P1_10, Pull::Down);
// BUSY has an internal 20 kΩ pull-up on the SX1262 die (datasheet
// p. 53); an MCU-side Pull::Down fights it and leaves the line at
// an indeterminate voltage, making wait_on_busy unreliable. See
// lora-rs/lora-rs#260.
let busy = Input::new(p.P1_10, Pull::None);
// RF switch: RXEN on P1.08 (GPIO, toggled by lora_phy), TX via DIO2 (SX1262 internal).
let rx_enable = Output::new(p.P1_08, Level::Low, OutputDrive::Standard);
+67 -3
View File
@@ -9,9 +9,66 @@
use embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex;
use embassy_sync::channel::Channel;
use portable_atomic::AtomicBool;
use crate::protocol::{Command, DeviceMessage, LoRaConfig};
/// True while a Reset has been queued in `CommandChannel` but not yet
/// consumed by the radio task. Dedupes injections from any host chart
/// (USB DTR-driven OR UART inactivity-driven) that fires `reset_radio`
/// repeatedly during quiet/inactive periods. Without this dedup, a slow
/// or wedged radio causes the host chart's exit action to inject Reset
/// every cycle, filling the commands channel and producing a "queue
/// full" warn flood. Cleared by the radio chart's Reset handler
/// (`reset_to_unconfigured`).
///
/// Uses `portable_atomic::AtomicBool` (not `core::sync::atomic`) because
/// Cortex-M0+ targets (RP2040) lack native CAS for `swap`. portable-atomic
/// transparently uses native atomics on M3+/M4 and critical-section
/// emulation on M0/M0+.
pub static RESET_PENDING: AtomicBool = AtomicBool::new(false);
/// True while the host transport's USB IN endpoint is observed-dead
/// (write_packet returned Err). Set by `host_task::protocol_loop` on the
/// first failed write; cleared on the next successful write. Producers of
/// **async** D→H events — `radio_task::record_packet` (RX) and
/// `host::framing::emit_async_err` — check this flag before pushing into
/// `OutboundChannel` and silently skip when set, so the queue does not
/// fill while the host is gone.
///
/// Tag-correlated responses (OK / sync ERR / TX_DONE) are NOT gated by
/// this flag: they're a small, bounded volume and the protocol contract
/// requires them to be delivered if we ever reach the host again.
///
/// Same `portable_atomic::AtomicBool` rationale as `RESET_PENDING`.
///
/// **Initial value `true`**: at boot we have no proof the host can
/// drain the outbound queue. Until host_task observes its first
/// successful `write_packet` (and clears this), async-RX producers
/// silently skip pushing. Otherwise — at boot, with no client
/// attached or with mux-rs idle — RX events would fill the queue
/// faster than host_task could drain it (which it can't: `write_packet`
/// blocks until the host actually polls), and the depth-64 ring would
/// flood `[WARN] RX dropped: outbound queue full` hundreds of times
/// per second. Pre-throttle is the structural fix.
pub static RADIO_THROTTLED: AtomicBool = AtomicBool::new(true);
/// Set by `radio::lora_setup` / `lora_setup_with` when a SHORT-DURATION
/// lora-phy op blew through its wall-clock budget (almost always BUSY
/// stuck high — chip is wedged). Read by chart actions and `during:`
/// activities that called the helper: when they observe a downstream
/// `Err(_)` AND see this flag set, they emit `WedgeDetected` (which
/// drives the radio chart into `Recovering` for an in-place NRESET +
/// `lora.init()` retry) instead of the per-action failure event. The
/// flag is consumed (`swap(false)`) by whoever reads it so the next
/// independent op gets a fresh signal.
///
/// This is the cleanest plumbing path for "wedge timeout vs ordinary
/// driver error" given the helper sits below the chart-action layer
/// (free function, no chart-emit access). One atomic, one concern,
/// matching the established `RESET_PENDING` / `RADIO_THROTTLED` pattern.
pub static LORA_WEDGED: AtomicBool = AtomicBool::new(false);
// ── Host → Radio: tag-correlated commands ───────────────────────────
/// An event flowing from the host task into the radio task.
@@ -42,9 +99,16 @@ pub struct OutboundFrame {
pub msg: DeviceMessage,
}
/// Radio-to-host outbound channel (depth 32: enough to hold a burst of
/// RX events + queued command responses without stalling the radio ISR).
pub type OutboundChannel = Channel<CriticalSectionRawMutex, OutboundFrame, 32>;
/// Radio-to-host outbound channel.
///
/// Depth 64: absorbs bursts of RX events plus queued command responses
/// plus async ERRs while the host transport drains. Each slot is ~280 B
/// (max RxPayload + envelope), so 64 slots is ~18 KB — well within RAM
/// budget on every supported MCU. The previous depth-32 was provoking
/// "outbound queue full" floods during host stalls; the larger queue
/// plus `RADIO_THROTTLED` backpressure flag (set by host_task on a
/// failed write_packet) together stop the cascade.
pub type OutboundChannel = Channel<CriticalSectionRawMutex, OutboundFrame, 64>;
// ── Internal: display commands (no longer wire-visible) ────────────
+10 -9
View File
@@ -138,15 +138,16 @@ fn phase_depth(n: u8) -> u8 {
match n {
18 => 1, // pre-TX: CmdTransmit just read from commands channel
6 => 2, // perform_tx entered
7 => 3, // in CAD
8 => 4, // in prepare_for_tx
9 => 5, // in tx().await
10 => 6, // do_tx returned Ok
11 => 7, // respond_tx_done entered
12 => 8, // respond_tx_done: responses.send returned
13 => 9, // host_task received response from channel
14 => 10, // host_task wrote response to UART (terminal success)
15 => 11, // TX errored (terminal error)
7 => 3, // in CAD (before prepare_for_cad)
19 => 4, // after prepare_for_cad (awaiting lora.cad IRQ)
8 => 5, // in prepare_for_tx
9 => 6, // in tx().await
10 => 7, // do_tx returned Ok
11 => 8, // respond_tx_done entered
12 => 9, // respond_tx_done: responses.send returned
13 => 10, // host_task received response from channel
14 => 11, // host_task wrote response to UART (terminal success)
15 => 12, // TX errored (terminal error)
_ => 0, // not a TX phase
}
}
+51 -12
View File
@@ -37,8 +37,8 @@ use embassy_time::Timer;
use hsmc::statechart;
use crate::board::{self, Board, DisplayDriver, DisplayParts, LedDriver, LoRaBoard, RgbLed};
use crate::driver::DisplayBrightness;
use crate::channel::{DisplayCommand, DisplayCommandChannel, RadioEvent, RadioEventChannel};
use crate::driver::DisplayBrightness;
use crate::protocol::LoRaConfig;
use render::{BoardInfo, RSSI_HISTORY_LEN};
@@ -46,6 +46,22 @@ use render::{BoardInfo, RSSI_HISTORY_LEN};
const BOARD_NAME: &str = Board::NAME;
const VERSION: &str = env!("CARGO_PKG_VERSION");
// Splash board-name font selection. Every OLED we drive is 128 px wide;
// the primary font (FONT_6X10, 6 px advance) fits up to 21 ASCII chars
// across the screen, the fallback (FONT_5X8, 5 px advance) fits up to
// 25. If even the fallback can't fit, fail at compile time so the board
// porter shortens NAME rather than silently overflowing the splash.
const SPLASH_SCREEN_W_PX: u32 = 128;
const SPLASH_FONT_PRIMARY_W_PX: u32 = 6;
const SPLASH_FONT_FALLBACK_W_PX: u32 = 5;
const BOARD_NAME_FITS_PRIMARY_FONT: bool =
(BOARD_NAME.len() as u32) * SPLASH_FONT_PRIMARY_W_PX <= SPLASH_SCREEN_W_PX;
const _: () = assert!(
(BOARD_NAME.len() as u32) * SPLASH_FONT_FALLBACK_W_PX <= SPLASH_SCREEN_W_PX,
"Board::NAME is too long for the 128 px splash screen even with the FONT_5X8 fallback \
(max 25 ASCII chars). Shorten the NAME constant in src/board/<board>.rs.",
);
/// Sentinel: no packet received in this slot. Below SX1262 sensitivity
/// floor (-120 dBm), so it cannot be confused with a real RSSI value.
const NO_SIGNAL: i16 = -121;
@@ -237,6 +253,8 @@ statechart! {
Display {
context: DisplayContext;
events: DisplayEvent;
// Auto-trace — backend selected by `hsmc/trace-*` cargo feature.
trace;
default(On);
state Off {
@@ -489,7 +507,7 @@ pub async fn display_task(
mod render {
use core::fmt::Write;
use embedded_graphics::mono_font::ascii::{FONT_6X10, FONT_9X15_BOLD};
use embedded_graphics::mono_font::ascii::{FONT_5X8, FONT_6X10, FONT_9X15_BOLD};
use embedded_graphics::mono_font::MonoTextStyle;
use embedded_graphics::pixelcolor::BinaryColor;
use embedded_graphics::prelude::*;
@@ -769,14 +787,31 @@ mod render {
.draw(target)
.ok();
Text::with_alignment(
board.name,
Point::new(center_x, 28),
style,
Alignment::Center,
)
.draw(target)
.ok();
// Board-name font picked at compile time by
// BOARD_NAME_FITS_PRIMARY_FONT (see top of display.rs). If the
// name fits FONT_6X10 we use it; otherwise we fall back to
// FONT_5X8. The const_assert at the BOARD_NAME definition
// rejects names that overflow even the fallback.
if super::BOARD_NAME_FITS_PRIMARY_FONT {
Text::with_alignment(
board.name,
Point::new(center_x, 28),
style,
Alignment::Center,
)
.draw(target)
.ok();
} else {
let small_style = MonoTextStyle::new(&FONT_5X8, BinaryColor::On);
Text::with_alignment(
board.name,
Point::new(center_x, 28),
small_style,
Alignment::Center,
)
.draw(target)
.ok();
}
Text::with_alignment(
board.mac,
@@ -802,7 +837,7 @@ mod render {
/// the left inviting the user to visit the URL.
pub fn learn_more(target: &mut impl DrawTarget<Color = BinaryColor>) {
use embedded_graphics::image::{Image, ImageRaw};
use embedded_graphics::mono_font::ascii::{FONT_5X8, FONT_7X14_BOLD};
use embedded_graphics::mono_font::ascii::{FONT_4X6, FONT_7X14_BOLD};
let bb = target.bounding_box();
let w = bb.size.width as i32;
@@ -819,7 +854,11 @@ mod render {
let col_center = col_w / 2;
let title_style = MonoTextStyle::new(&FONT_7X14_BOLD, BinaryColor::On);
let text_style = MonoTextStyle::new(&FONT_5X8, BinaryColor::On);
// FONT_4X6 (4 px advance) on the URL line so "donglora.com"
// (12 chars × 4 = 48 px) fits the 64 px left column with ~8 px
// breathing room either side, instead of FONT_5X8's 60 px which
// visually touches both edges.
let text_style = MonoTextStyle::new(&FONT_4X6, BinaryColor::On);
// Layout on a 64 px display:
// blank
+5 -2
View File
@@ -1,7 +1,8 @@
#[cfg(any(
feature = "wio_tracker_l1",
feature = "elecrow_thinknode_m2",
feature = "lilygo_tbeam_supreme"
feature = "lilygo_tbeam_supreme",
feature = "rak_wisblock_4631"
))]
pub mod sh1106;
@@ -18,6 +19,7 @@ pub mod inverted_pin;
feature = "elecrow_thinknode_m2",
feature = "lilygo_tbeam_supreme",
feature = "lilygo_tbeam",
feature = "rak_wisblock_4631",
feature = "wio_tracker_l1",
feature = "waveshare_rp2040_lora"
))]
@@ -66,7 +68,8 @@ where
#[cfg(any(
feature = "wio_tracker_l1",
feature = "elecrow_thinknode_m2",
feature = "lilygo_tbeam_supreme"
feature = "lilygo_tbeam_supreme",
feature = "rak_wisblock_4631"
))]
impl<I> DisplayBrightness for sh1106::Sh1106<I>
where
+18
View File
@@ -37,6 +37,12 @@ impl<I: I2c> Sh1106<I> {
/// Send a sequence of commands (each prefixed with the I2C command byte 0x00).
async fn cmd(&mut self, commands: &[u8]) -> Result<(), I::Error> {
for &c in commands {
#[cfg(feature = "debug-twim")]
defmt::info!(
"[sh1106] cmd write: addr=0x{=u8:02X} bytes=[0x00, 0x{=u8:02X}]",
self.addr,
c,
);
self.i2c.write(self.addr, &[0x00, c]).await?;
}
Ok(())
@@ -44,6 +50,8 @@ impl<I: I2c> Sh1106<I> {
/// Initialize the display with sensible defaults.
pub async fn init(&mut self) -> Result<(), I::Error> {
#[cfg(feature = "debug-twim")]
defmt::info!("[sh1106] init: starting");
self.cmd(&[
0xAE, // display off
0xD5, 0x80, // clock div: default
@@ -71,6 +79,8 @@ impl<I: I2c> Sh1106<I> {
page_buf[0] = 0x40;
for page in 0..PAGES {
#[cfg(feature = "debug-twim")]
defmt::info!("[sh1106] flush page {=usize}: addr cmds (3 bytes)", page);
// Set page address and column start (with SH1106 2-column offset).
self.cmd(&[
0xB0 | page as u8, // page address
@@ -81,6 +91,12 @@ impl<I: I2c> Sh1106<I> {
let start = page * WIDTH;
page_buf[1..].copy_from_slice(&self.buffer[start..start + WIDTH]);
#[cfg(feature = "debug-twim")]
defmt::info!(
"[sh1106] flush page {=usize}: data write {=usize} bytes (0x40 prefix + 128 pixels)",
page,
page_buf.len(),
);
self.i2c.write(self.addr, &page_buf).await?;
}
Ok(())
@@ -88,6 +104,8 @@ impl<I: I2c> Sh1106<I> {
/// Set display brightness (contrast).
pub async fn set_brightness(&mut self, value: u8) -> Result<(), I::Error> {
#[cfg(feature = "debug-twim")]
defmt::info!("[sh1106] set_brightness: 0x{=u8:02X}", value);
self.cmd(&[0x81, value]).await
}
}
+70
View File
@@ -56,6 +56,76 @@ pub fn alloc_vbus_detect(
))
}
// ── Reset reason ────────────────────────────────────────────────────
/// Read the POWER.RESETREAS register, log a human-readable summary,
/// then clear it so the next boot reflects only the next reset cause.
///
/// This is the post-mortem diagnostic for soak runs: if the firmware
/// crashes and the chip resets, the next boot's RESETREAS tells us
/// what happened (cortex-m lockup, watchdog, soft reset, debugger,
/// pin reset, etc.). Without this, a self-rebooting firmware just
/// looks like log restarts with no signal as to why.
///
/// nRF52840 `POWER.RESETREAS` (PS §15.4.1): bits are write-1-to-clear.
/// The register accumulates causes across resets until cleared, so
/// always clear after reading.
pub fn dump_reset_reason() {
// POWER.RESETREAS lives at 0x40000400 (POWER base 0x40000000 +
// offset 0x400). Direct memory access avoids requiring embassy_nrf's
// `unstable-pac` feature. Bit layout per nRF52840 PS §15.4.1:
// 0 RESETPIN - external NRESET pin asserted
// 1 DOG - watchdog reset
// 2 SREQ - software-requested reset (cortex SYSRESETREQ)
// 3 LOCKUP - cortex-m core lockup
// 16 OFF - wake from System OFF via DETECT
// 17 LPCOMP - wake from System OFF via ANADETECT
// 18 DIF - wake from System OFF via debug interface
// 24 NFC - wake from System OFF via NFC field
const RESETREAS_ADDR: *mut u32 = 0x4000_0400 as *mut u32;
// SAFETY: 0x40000400 is the POWER.RESETREAS register on nRF52840;
// read/write_volatile is correct for memory-mapped hardware.
let raw = unsafe { core::ptr::read_volatile(RESETREAS_ADDR) };
let dog = (raw & (1 << 1)) != 0;
let lockup = (raw & (1 << 3)) != 0;
if raw == 0 {
defmt::info!("boot: cold POR (RESETREAS=0)");
} else if dog || lockup {
// Real problems: watchdog timeout (hung task) OR CPU lockup
// (HardFault → escalated). Worth a WARN — these are bugs.
defmt::warn!(
"boot: ABNORMAL reset RESETREAS=0x{=u32:08x} resetpin={=bool} dog={=bool} sreq={=bool} lockup={=bool} off={=bool} lpcomp={=bool} dif={=bool} nfc={=bool}",
raw,
(raw & (1 << 0)) != 0,
dog,
(raw & (1 << 2)) != 0,
lockup,
(raw & (1 << 16)) != 0,
(raw & (1 << 17)) != 0,
(raw & (1 << 18)) != 0,
(raw & (1 << 24)) != 0,
);
} else {
// Normal reset paths: RESETPIN (UF2 bootloader pulses NRESET on
// app start; user reset button), SREQ (deliberate sys_reset),
// OFF/LPCOMP/DIF/NFC (wake from System OFF). All expected
// operational reasons; INFO not WARN.
defmt::info!(
"boot: RESETREAS=0x{=u32:08x} resetpin={=bool} sreq={=bool} off={=bool} lpcomp={=bool} dif={=bool} nfc={=bool}",
raw,
(raw & (1 << 0)) != 0,
(raw & (1 << 2)) != 0,
(raw & (1 << 16)) != 0,
(raw & (1 << 17)) != 0,
(raw & (1 << 18)) != 0,
(raw & (1 << 24)) != 0,
);
}
// Clear all bits — write-1-to-clear per nRF52840 PS §15.4.1.
// SAFETY: same justification as the read above.
unsafe { core::ptr::write_volatile(RESETREAS_ADDR, 0xFFFF_FFFF) };
}
// ── MAC address ─────────────────────────────────────────────────────
/// Read the factory-programmed device address from FICR registers.
+28 -3
View File
@@ -54,7 +54,16 @@ pub async fn dispatch_frame(
}
/// Emit an async framing error (tag = 0x0000) per spec §2.5.
///
/// Backpressure: if the host transport's IN endpoint is observed-dead
/// (RADIO_THROTTLED set by host_task), drop silently. Without this gate,
/// a bad-frame burst from a wedged host fills `OutboundChannel` faster
/// than host_task can drain it (because it can't drain it at all when
/// write_packet keeps failing), producing the warn flood seen in soak.
pub async fn emit_async_err(outbound: &OutboundChannel, code: ErrorCode) {
if crate::channel::RADIO_THROTTLED.load(portable_atomic::Ordering::Acquire) {
return;
}
let frame = OutboundFrame {
tag: 0,
msg: DeviceMessage::Err(code),
@@ -106,15 +115,31 @@ pub fn encode_outbound(frame: &OutboundFrame, out: &mut [u8; MAX_WIRE_FRAME]) ->
) {
Ok(n) => Some(n),
Err(FrameEncodeError::BufferTooSmall) => {
warn!("encode_frame: output buffer too small");
warn!(
"encode_frame: output buffer too small (type={=u8}, tag={=u16}, payload={=usize}B, out_buf={=usize}B)",
frame.msg.type_id(),
frame.tag,
payload_len,
out.len(),
);
None
}
Err(FrameEncodeError::PayloadTooLarge) => {
warn!("encode_frame: payload exceeds MAX_PAYLOAD_FIELD");
warn!(
"encode_frame: payload exceeds MAX_PAYLOAD_FIELD (type={=u8}, tag={=u16}, payload={=usize}B)",
frame.msg.type_id(),
frame.tag,
payload_len,
);
None
}
Err(FrameEncodeError::CobsEncode) => {
warn!("encode_frame: COBS encode refused");
warn!(
"encode_frame: COBS encode refused (type={=u8}, tag={=u16}, payload={=usize}B)",
frame.msg.type_id(),
frame.tag,
payload_len,
);
None
}
}
+83 -35
View File
@@ -4,7 +4,7 @@
//! rely entirely on the spec §3.4 inactivity watchdog (1 s of silence
//! → Disconnected → drop radio to Unconfigured).
use defmt::warn;
use defmt::{info, warn};
use embassy_executor::task;
use embassy_time::{Duration, Instant};
use embedded_io_async::Write;
@@ -34,25 +34,32 @@ pub async fn host_task(
display_commands.send(DisplayCommand::On).await;
}
let mut read_buf = [0u8; READ_BUF];
let mut write_buf: [u8; MAX_WIRE_FRAME] = [0u8; MAX_WIRE_FRAME];
let mut decoder = FrameDecoder::new();
let mut last_frame_at = Instant::now();
let mut connected = true;
// Two sub-loops joined in the same task. Splitting read and write
// is what stops a long-running tx.write_all (~25 ms for a max-size
// frame at 115_200 baud, multiplied across a saturated outbound
// queue) from starving the inbound poll. While write_all sits in
// its FIFO-drain await, join re-polls the read future on the next
// wake, so last_frame_at keeps refreshing and the §3.4 watchdog
// does not spuriously fire under sustained bidirectional load.
// Same task = single executor + disjoint borrows on the split
// rx/tx halves, so no Mutex is needed.
let read_loop = async {
let mut read_buf = [0u8; READ_BUF];
let mut decoder = FrameDecoder::new();
let mut last_frame_at = Instant::now();
let mut connected = true;
loop {
use embassy_futures::select::{select3, Either3};
loop {
use embassy_futures::select::{select, Either};
match select3(
embedded_io_async::Read::read(&mut rx, &mut read_buf),
outbound.receive(),
embassy_time::Timer::after(Duration::from_millis(100)),
)
.await
{
Either3::First(result) => match result {
Ok(0) => continue,
Ok(n) => {
match select(
embedded_io_async::Read::read(&mut rx, &mut read_buf),
embassy_time::Timer::after(Duration::from_millis(100)),
)
.await
{
Either::First(Ok(0)) => {}
Either::First(Ok(n)) => {
last_frame_at = Instant::now();
if !connected {
if has_display {
@@ -62,31 +69,72 @@ pub async fn host_task(
}
dispatch_bytes(&mut decoder, &read_buf[..n], commands, outbound).await;
}
Err(_) => {
Either::First(Err(_)) => {
// Byte-level error (FIFO overrun, UART framing,
// parity). Per PROTOCOL.md §3.4: only "byte stream
// activity that results in a complete frame
// arriving" resets the inactivity timer, so we do
// NOT touch last_frame_at here. The 100 ms sleep
// is anti-spin: a stuck driver pumping continuous
// Errs would otherwise burn the executor.
decoder.reset();
embassy_time::Timer::after_millis(100).await;
}
},
Either3::Second(frame) => {
if let Some(n) = encode_outbound(&frame, &mut write_buf) {
if tx.write_all(&write_buf[..n]).await.is_err() {
warn!("UART write failed, frame dropped");
Either::Second(()) => {}
}
// Inactivity watchdog (PROTOCOL.md §3.4, 1000 ms).
if connected && last_frame_at.elapsed() >= Duration::from_millis(INACTIVITY_MS) {
warn!("UART host inactivity timeout fired");
let _ = commands.try_send(InboundEvent::Reset);
if has_display {
let _ = display_commands.try_send(DisplayCommand::Reset);
}
// Drop in-flight frame state. When the host resumes it
// may pick up mid-frame; without resetting the decoder
// we'd chew through garbage until the next 0x00
// sentinel. USB gets the equivalent for free via
// DTR-drop reset (host/usb.rs Disconnected entry); UART
// has no DTR.
decoder.reset();
connected = false;
}
}
};
let write_loop = async {
let mut write_buf: [u8; MAX_WIRE_FRAME] = [0u8; MAX_WIRE_FRAME];
loop {
let frame = outbound.receive().await;
let Some(n) = encode_outbound(&frame, &mut write_buf) else {
continue;
};
// Mirror src/host/usb.rs:349-374. The throttle gate at
// src/radio.rs:2017 silently drops async RX into the
// outbound queue while RADIO_THROTTLED is true; clear it
// on every successful write and re-arm it on failure,
// same contract as USB.
match tx.write_all(&write_buf[..n]).await {
Ok(()) => {
if crate::channel::RADIO_THROTTLED
.load(portable_atomic::Ordering::Acquire)
{
info!("UART write recovered; clearing radio throttle");
crate::channel::RADIO_THROTTLED
.store(false, portable_atomic::Ordering::Release);
}
}
Err(_) => {
warn!("UART write failed, frame dropped, throttling radio");
crate::channel::RADIO_THROTTLED
.store(true, portable_atomic::Ordering::Release);
}
}
Either3::Third(()) => {}
}
};
// Inactivity watchdog.
if connected && last_frame_at.elapsed() >= Duration::from_millis(INACTIVITY_MS) {
warn!("UART host inactivity timeout fired");
let _ = commands.try_send(InboundEvent::Reset);
if has_display {
let _ = display_commands.try_send(DisplayCommand::Reset);
}
connected = false;
}
}
embassy_futures::join::join(read_loop, write_loop).await;
}
async fn dispatch_bytes(
+201 -41
View File
@@ -2,24 +2,35 @@
//!
//! ```text
//! Host
//! ├── Disconnected (default) no DTR, or inactivity timer fired
//! └── Connected host attached, liveness OK
//! entry: wake_display, start_liveness_timer
//! exit: reset_radio, reset_display, stop_liveness_timer
//! ├── Disconnected (default) no DTR
//! └── Connected host attached, DTR up
//! │ resting here means no traffic yet —
//! │ NO inactivity timer (boot quiet is
//! │ normal; chart structurally blocks the
//! │ spurious 1s fire).
//! └── Active ≥1 frame seen since connect
//! inactivity timer (1s) armed and
//! restarted by every frame via
//! self-transition.
//! ```
//!
//! The statechart tracks one state bit: "is a host present?". DTR drives
//! connect edges; the 1-second inactivity watchdog (spec §3.4) drives
//! the disconnect edge when DTR is held high but no bytes arrive.
//! Two chart-level invariants made structurally impossible by the shape:
//! 1. **No spurious inactivity at boot.** The 1-second timer only exists
//! in `Active`, which requires a `FrameReceived` event to enter.
//! A freshly-connected host that holds DTR high but sends nothing
//! rests at `Connected` indefinitely (hsmc 0.5 optional-default
//! "microwave Standby" pattern) — no timer, no warn, no Reset cascade.
//! 2. **Chart-owned timer scope.** Per hsmc README rule §7 (timers
//! armed by state lifecycle), the inactivity timer is cancelled on
//! every exit of `Active`, restarted on every entry. No global
//! `last_frame_at` instant, no manual elapsed check in the loop.
//!
//! The data plane (frame decode, command dispatch, frame encode) stays
//! imperative in `protocol_loop` for the same reason the radio's
//! `rx_once` stayed out of its chart: `read_packet` blocks.
//! imperative in `protocol_loop` because `read_packet` blocks.
use defmt::warn;
use embassy_executor::task;
use embassy_futures::join::join;
use embassy_time::{Duration, Instant};
use embassy_time::Duration;
use embassy_usb::class::cdc_acm::{CdcAcmClass, Receiver, Sender, State};
use embassy_usb::Builder;
use hsmc::{statechart, Duration as HsmcDuration};
@@ -35,17 +46,24 @@ const MAX_USB_PACKET: usize = 64;
/// Spec §3.4: inactivity timer period. The device must see at least one
/// frame (good or bad) every 1000 ms or the session is considered lost.
/// Declared in the chart on `Active` — chart owns timer lifecycle.
const INACTIVITY_MS: u64 = 1000;
/// Poll interval for the DTR edge detector / inactivity check.
/// Poll interval for the DTR edge detector. Chart owns the inactivity
/// timer; this is only the cadence at which protocol_loop wakes when
/// no other event is pending, to re-check DTR.
const POLL_INTERVAL_MS: u64 = 100;
#[derive(Debug, Clone)]
pub enum HostInput {
DtrRaised,
DtrDropped,
/// Host went silent for >1 s; kick the radio back to Unconfigured.
InactivityTimeout,
/// A USB read returned ≥1 byte. Drives `Connected → Active` on
/// the first frame after DTR up, and the `Active → Active`
/// self-transition that restarts the inactivity timer per
/// hsmc README rule §4 (self-transition exits + re-enters target,
/// re-arming its timer).
FrameReceived,
}
pub struct HostContext {
@@ -68,8 +86,22 @@ impl HostContext {
}
fn send_radio_reset(&self) {
use portable_atomic::Ordering;
// Dedupe: if a Reset is already queued (and not yet consumed by
// the radio task), don't queue another. Without this, a slow or
// wedged radio + repeated chart exits (DTR drop, inactivity,
// both transports) fill the commands channel and produce the
// "queue full" warn flood. The radio chart's reset_to_unconfigured
// clears the flag once it processes the queued Reset.
if crate::channel::RESET_PENDING.swap(true, Ordering::AcqRel) {
return;
}
if self.commands.try_send(InboundEvent::Reset).is_err() {
warn!("radio Reset inject: command queue full");
// Channel genuinely full of non-Reset commands; this is the
// edge case worth knowing about. Clear the flag so future
// Reset attempts can re-try once the channel drains.
defmt::warn!("radio Reset inject: command queue full");
crate::channel::RESET_PENDING.store(false, Ordering::Release);
}
}
}
@@ -78,6 +110,8 @@ statechart! {
Host {
context: HostContext;
events: HostInput;
// Auto-trace — backend selected by `hsmc/trace-*` cargo feature.
trace;
default(Disconnected);
state Disconnected {
@@ -88,7 +122,28 @@ statechart! {
entry: wake_display;
exit: reset_radio, reset_display;
on(DtrDropped) => Disconnected;
on(InactivityTimeout) => Disconnected;
// hsmc 0.5 microwave-Standby pattern: Connected itself is the
// resting "DTR up, no traffic yet" state. No inactivity timer
// here — boot quiet is normal (mux-rs holds DTR high before
// any client attaches), so the chart structurally cannot fire
// a 1 s warn before the first byte. The first FrameReceived
// descends into Active, which owns the inactivity timer.
on(FrameReceived) => Active;
// Inactivity timer is chart-scoped: armed on every entry to
// Active (from Connected on the first frame, or from the
// self-transition below on each subsequent frame), cancelled
// on every exit (per hsmc README rule §7). The self-transition
// re-enters Active per rule §4, re-arming the timer —
// equivalent to the "reset last_frame_at on each byte" pattern
// but expressed in chart shape.
//
// hsmc's `after` triggers want `hsmc::Duration` (re-export
// of `core::time::Duration`), not `embassy_time::Duration`.
state Active {
on(after HsmcDuration::from_millis(INACTIVITY_MS)) => Disconnected;
on(FrameReceived) => Active;
}
}
}
}
@@ -133,20 +188,34 @@ pub async fn host_task(
}
config.serial_number = Some(core::str::from_utf8(serial_buf).expect("MAC hex is valid UTF-8"));
// CTRL_BUF was 64 bytes; bumped to 128 because the previous size
// matches the panic site "control buffer too small" in
// embassy_usb/src/lib.rs:758. CdcAcmClass only requires >= 7 for
// SET_LINE_CODING, but composite descriptor handlers and string
// descriptor responses may overrun a 64 B buffer for some host
// enumerations. 128 is safely above the largest CDC-ACM control
// request and well within RAM budget.
static DESC_BUF: StaticCell<[u8; 256]> = StaticCell::new();
static CONF_BUF: StaticCell<[u8; 256]> = StaticCell::new();
static BOS_BUF: StaticCell<[u8; 256]> = StaticCell::new();
static CTRL_BUF: StaticCell<[u8; 64]> = StaticCell::new();
static CTRL_BUF: StaticCell<[u8; 128]> = StaticCell::new();
static CDC_STATE: StaticCell<State> = StaticCell::new();
let desc_buf = DESC_BUF.init([0; 256]);
let conf_buf = CONF_BUF.init([0; 256]);
let bos_buf = BOS_BUF.init([0; 256]);
let ctrl_buf = CTRL_BUF.init([0; 64]);
let ctrl_buf = CTRL_BUF.init([0; 128]);
let cdc_state = CDC_STATE.init(State::new());
let mut builder = Builder::new(parts.driver, config, desc_buf, conf_buf, bos_buf, ctrl_buf);
// Note: when this device enumerates on Linux, modem-manager's
// CDC-ACM probe issues SET_INTERFACE with alt settings beyond what
// we declare, triggering a "SET_INTERFACE: alt setting out of
// range" WARN from embassy_usb. The probe is normal Linux
// behavior; embassy_usb's STALL response is correct USB negotiation.
// The WARN is benign noise — do NOT add dummy alt settings just to
// silence it (risks breaking Windows/macOS enumeration).
let class = CdcAcmClass::new(&mut builder, cdc_state, MAX_USB_PACKET as u16);
let mut usb_dev = builder.build();
let (sender, receiver) = class.split();
@@ -186,8 +255,6 @@ async fn protocol_loop<'d, D: embassy_usb_driver::Driver<'d>>(
let mut write_buf: [u8; MAX_WIRE_FRAME] = [0u8; MAX_WIRE_FRAME];
let mut decoder = FrameDecoder::new();
let mut last_frame_at = Instant::now();
loop {
match select3(
receiver.read_packet(&mut read_buf),
@@ -196,52 +263,145 @@ async fn protocol_loop<'d, D: embassy_usb_driver::Driver<'d>>(
)
.await
{
Either3::First(Ok(0)) => {}
Either3::First(Ok(0)) => {
defmt::info!("host_task: read_packet returned 0 bytes");
}
Either3::First(Ok(n)) => {
last_frame_at = Instant::now();
defmt::info!(
"host_task: read_packet got {=usize}B (DTR={=bool})",
n,
receiver.dtr(),
);
// Drives Connected → Active on first byte and
// Active → Active (timer-restart) on every byte after.
// The chart owns inactivity from here.
let _ = machine.dispatch(HostInput::FrameReceived).await;
dispatch_bytes(&mut decoder, &read_buf[..n], commands, outbound).await;
}
Either3::First(Err(_)) => {
Either3::First(Err(e)) => {
// Per embassy_usb_driver::EndpointError, `read_packet`
// returns one of two errors:
// - `Disabled`: OUT endpoint not enabled by the host
// (USB enumeration in progress, host
// suspended, or interface not yet
// configured). Completely normal during
// bring-up + every host disconnect.
// - `BufferOverflow`: incoming packet larger than read_buf.
// read_buf is sized to MAX_USB_PACKET
// (64) which matches the CDC-ACM EP
// max packet size, so this should
// never happen in practice.
//
// `Disabled` floods at boot before USB enumeration finishes
// (the OS hasn't sent SET_CONFIGURATION yet) — was previously
// logging dozens of "read_packet error" lines per second.
// Demote to debug-level since it's expected; reserve WARN
// for BufferOverflow which IS a real bug.
use embassy_usb_driver::EndpointError;
match e {
EndpointError::Disabled => {
defmt::debug!(
"host_task: read_packet returned Disabled (USB endpoint not yet enabled by host — normal during enumeration)"
);
}
EndpointError::BufferOverflow => {
defmt::warn!(
"host_task: read_packet BufferOverflow — host sent a packet larger than {=usize}B (max EP packet size); decoder reset",
MAX_USB_PACKET,
);
}
}
decoder.reset();
embassy_time::Timer::after_millis(100).await;
}
Either3::Second(frame) => {
let frame_tag = frame.tag;
if let Some(n) = encode_outbound(&frame, &mut write_buf) {
for chunk in write_buf[..n].chunks(MAX_USB_PACKET) {
defmt::info!(
"host_task: sending {=usize}B frame tag={=u16}",
n,
frame_tag,
);
// Per embassy_usb 0.6: write_packet only returns
// EndpointError::Disabled when the IN endpoint is
// dead (host gone or USB suspended). If a chunk
// mid-frame fails, the partial bytes already sent
// are unrecoverable — host's framing layer will see
// corruption until a clean frame arrives. Bail on
// the rest of THIS frame and set RADIO_THROTTLED so
// the radio task stops generating async events
// until the host comes back. Without the throttle,
// every subsequent frame would also fail mid-write
// and produce more wire corruption.
let mut frame_failed = false;
for (chunk_idx, chunk) in
write_buf[..n].chunks(MAX_USB_PACKET).enumerate()
{
defmt::info!(
"host_task: write_packet chunk {=usize} ({=usize}B) tag={=u16}",
chunk_idx,
chunk.len(),
frame_tag,
);
if sender.write_packet(chunk).await.is_err() {
warn!("USB write failed, frame dropped");
defmt::warn!(
"USB write failed (host stalled or gone); frame dropped tag={=u16}, throttling radio",
frame_tag,
);
crate::channel::RADIO_THROTTLED
.store(true, portable_atomic::Ordering::Release);
frame_failed = true;
break;
}
defmt::info!(
"host_task: write_packet OK chunk {=usize} tag={=u16}",
chunk_idx,
frame_tag,
);
}
if !frame_failed
&& crate::channel::RADIO_THROTTLED
.load(portable_atomic::Ordering::Acquire)
{
defmt::info!(
"USB write recovered (tag={=u16}); clearing radio throttle",
frame_tag,
);
crate::channel::RADIO_THROTTLED
.store(false, portable_atomic::Ordering::Release);
}
defmt::info!("host_task: frame done tag={=u16}", frame_tag);
}
}
Either3::Third(()) => {}
Either3::Third(()) => {
// Heartbeat tick — drives DTR edge polling + inactivity
// watchdog below. No log: it would fire every
// POLL_INTERVAL_MS and bury the interesting traffic.
}
}
// DTR edge detection — drives Connected / Disconnected transitions.
let connected = receiver.dtr();
let was_connected = matches!(machine.current_state(), HostState::Connected);
match (was_connected, connected) {
// DTR edge detection — drives Connected / Disconnected
// transitions. The chart's `current_state()` may be
// Disconnected, Connected (resting), or Connected/Active.
// We're connected if current state is anywhere inside
// Connected.
let dtr_high = receiver.dtr();
let was_connected = !matches!(
machine.current_state(),
HostState::Disconnected
);
match (was_connected, dtr_high) {
(false, true) => {
defmt::info!("host_task: DTR raised");
let _ = machine.dispatch(HostInput::DtrRaised).await;
last_frame_at = Instant::now();
}
(true, false) => {
defmt::info!("host_task: DTR dropped");
decoder.reset();
let _ = machine.dispatch(HostInput::DtrDropped).await;
}
_ => {}
}
// Inactivity watchdog (spec §3.4): while Connected, if no frame
// arrived in the last INACTIVITY_MS, drive the session back to
// Disconnected.
if matches!(machine.current_state(), HostState::Connected)
&& last_frame_at.elapsed() >= Duration::from_millis(INACTIVITY_MS)
{
warn!("host inactivity timeout fired");
let _ = machine.dispatch(HostInput::InactivityTimeout).await;
}
}
}
+285
View File
@@ -0,0 +1,285 @@
//! Pure-math helpers for Listen-Before-Talk (CAD) retry timing.
//!
//! The CAD retry loop in `radio::do_tx` scales its backoff to the active
//! LoRa configuration: per-retry sleep is one time-on-air of an assumed
//! peer packet, total retry budget is capped at `CAD_BUDGET_US`. This
//! module owns the ToA math (Semtech AN1200.13) and the retry-count
//! derivation, split out so it can be unit-tested host-side without the
//! radio module's hardware dependencies.
use crate::protocol::{LoRaCodingRate, LoRaConfig, LoRaHeaderMode};
/// Total LBT budget: the maximum time the CAD retry loop is allowed to
/// tie up the radio before returning `ChannelBusy`.
pub const CAD_BUDGET_US: u32 = 2_500_000;
/// Upper bound on retries, independent of budget — caps the work on
/// very fast configs (SF7/BW500 would otherwise get 60+ retries).
pub const CAD_HARD_CAP: u8 = 10;
/// Assumed peer-packet payload (bytes) used to size the per-retry sleep.
/// 80 is a representative median for typical mesh traffic. Peers sending
/// larger packets may be partially under-waited (accepted trade-off —
/// host-level retry handles collisions).
#[allow(dead_code)] // consumed by `radio.rs`, which is gated out of test builds
pub const CAD_ASSUMED_PEER_PAYLOAD_B: u16 = 80;
/// Jitter applied to each sleep, in tenths of a percent (±20 % = 200).
pub const CAD_JITTER_TENTHS_PCT: u32 = 200;
/// ToA formula expects CR ∈ {1..4} for 4/5..4/8 (each coded symbol carries
/// `CR+4` bits). The protocol enum starts at 0, so map explicitly — using
/// `as u32` alone would underestimate airtime by one code bit everywhere.
pub fn cr_numeric(cr: LoRaCodingRate) -> u32 {
match cr {
LoRaCodingRate::Cr4_5 => 1,
LoRaCodingRate::Cr4_6 => 2,
LoRaCodingRate::Cr4_7 => 3,
LoRaCodingRate::Cr4_8 => 4,
}
}
/// Worst-case LoRa time-on-air in microseconds (Semtech AN1200.13).
///
/// Uses `N_preamble + 4.25` quarter-symbols for preamble duration; SX126x
/// uses 6.25 at SF5/SF6, so the result is low by 2·T_sym at those SFs
/// (sub-millisecond — negligible at the LBT-budget scale).
pub fn toa_us(cfg: &LoRaConfig, payload_len: u16) -> u32 {
let sf = cfg.sf as u64;
let bw_hz = cfg.bw.as_hz() as u64;
// Symbol time in µs: (2^SF / BW_Hz) * 1e6. u64 avoids overflow at
// SF12/BW7 where T_sym ≈ 524 ms.
let t_sym_us = (1u64 << sf) * 1_000_000 / bw_hz.max(1);
let de: i64 = if t_sym_us > 16_000 { 1 } else { 0 };
let crc: i64 = if cfg.payload_crc { 1 } else { 0 };
let h: i64 = if matches!(cfg.header_mode, LoRaHeaderMode::Implicit) {
1
} else {
0
};
let pl = payload_len as i64;
let sf_i = sf as i64;
// Payload symbol count (signed intermediates — `num` goes negative
// for small PL at SF12 with H=1, CRC=0).
let num = 8 * pl - 4 * sf_i + 28 + 16 * crc - 20 * h;
let den = 4 * (sf_i - 2 * de);
let payload_sym_ceil = if num <= 0 || den <= 0 {
0i64
} else {
(num + den - 1) / den
};
let cr_num = cr_numeric(cfg.cr) as i64;
let n_payload = 8 + (payload_sym_ceil * (cr_num + 4)).max(0);
let t_payload_us = n_payload as u64 * t_sym_us;
// Preamble duration: (N + 4.25) * T_sym = (4·N + 17) * T_sym / 4.
let t_preamble_us = (cfg.preamble_len as u64 * 4 + 17) * t_sym_us / 4;
(t_preamble_us + t_payload_us).min(u32::MAX as u64) as u32
}
/// Derive the CAD retry count and per-retry sleep from the cached
/// `cad_retry_delay_us`. Retries form: N CADs separated by N-1 sleeps.
/// When one assumed-packet wait exceeds the total budget, `retries = 1`
/// — a single CAD, bail on busy, no sleep.
pub fn cad_retries(cad_retry_delay_us: u32) -> (u8, u32) {
if cad_retry_delay_us == 0 {
// Unconfigured should never reach this path; fall back to a
// single CAD with no sleep rather than divide-by-zero.
return (1, 0);
}
let n_sleeps = CAD_BUDGET_US / cad_retry_delay_us;
let retries = (n_sleeps + 1).clamp(1, CAD_HARD_CAP as u32) as u8;
(retries, cad_retry_delay_us)
}
/// Apply ±`CAD_JITTER_TENTHS_PCT`/10 % jitter around `base_us`.
/// `entropy` is a raw 32-bit source; caller provides it so this stays
/// pure (radio task passes `Instant::now().as_ticks() as u32`).
pub fn jittered_sleep_us(base_us: u32, entropy: u32) -> u32 {
let mixed = entropy.wrapping_mul(0x9E37_79B9);
let span = 2 * CAD_JITTER_TENTHS_PCT + 1; // e.g. 401 for ±20 %
let r = mixed % span; // 0..=2·CAD_JITTER_TENTHS_PCT
// factor_thousandths ∈ [1000 − CAD_JITTER_TENTHS_PCT, 1000 + CAD_JITTER_TENTHS_PCT]
let factor_thousandths = 1000 - CAD_JITTER_TENTHS_PCT + r;
((base_us as u64 * factor_thousandths as u64) / 1000) as u32
}
#[cfg(test)]
mod tests {
use super::*;
use crate::protocol::{LoRaBandwidth, LoRaCodingRate, LoRaConfig, LoRaHeaderMode};
fn cfg(sf: u8, bw: LoRaBandwidth, cr: LoRaCodingRate, preamble: u16, implicit: bool, crc: bool) -> LoRaConfig {
LoRaConfig {
freq_hz: 915_000_000,
sf,
bw,
cr,
preamble_len: preamble,
sync_word: 0x1424,
tx_power_dbm: 0,
header_mode: if implicit {
LoRaHeaderMode::Implicit
} else {
LoRaHeaderMode::Explicit
},
payload_crc: crc,
iq_invert: false,
}
}
/// Helper: assert `actual` is within `tolerance_pct`% of `expected_us`.
fn approx(actual_us: u32, expected_us: u32, tolerance_pct: u32) {
let diff = actual_us.abs_diff(expected_us);
let tol = expected_us * tolerance_pct / 100;
assert!(
diff <= tol,
"actual {} us not within {}% of expected {} us (diff {}, tol {})",
actual_us,
tolerance_pct,
expected_us,
diff,
tol
);
}
// Reference values sanity-checked against Semtech's LoRa calculator
// and AN1200.13.
#[test]
fn toa_sf7_bw125_cr45_pl10_explicit_crc() {
let c = cfg(7, LoRaBandwidth::Khz125, LoRaCodingRate::Cr4_5, 8, false, true);
// Hand-computed reference from AN1200.13:
// T_sym = 128/125 kHz = 1.024 ms
// T_preamble = (8 + 4.25) · 1.024 = 12.544 ms
// n_payload = 8 + ceil((80 − 28 + 28 + 16) / 28) · 5 = 8 + 4·5 = 28
// T_payload = 28 · 1.024 = 28.672 ms
// Total ≈ 41.22 ms
approx(toa_us(&c, 10), 41_216, 2);
}
#[test]
fn toa_sf12_bw125_cr45_pl10_explicit_crc() {
let c = cfg(12, LoRaBandwidth::Khz125, LoRaCodingRate::Cr4_5, 8, false, true);
// Reference: ~991 ms for PL=10 at SF12/BW125/CR4/5 (LDRO on).
approx(toa_us(&c, 10), 991_000, 2);
}
#[test]
fn toa_sf10_bw125_cr45_pl255_max() {
let c = cfg(10, LoRaBandwidth::Khz125, LoRaCodingRate::Cr4_5, 8, false, true);
// Reference: ~2.34 s for PL=255 at SF10/BW125/CR4/5.
approx(toa_us(&c, 255), 2_335_000, 2);
}
#[test]
fn toa_ldro_activates_at_sf11_and_sf12_bw125() {
// T_sym > 16 ms → DE=1. SF11/BW125: T_sym = 16.384 ms. SF10/BW125: 8.192 ms.
let sf10 = cfg(10, LoRaBandwidth::Khz125, LoRaCodingRate::Cr4_5, 8, false, true);
let sf11 = cfg(11, LoRaBandwidth::Khz125, LoRaCodingRate::Cr4_5, 8, false, true);
let sf12 = cfg(12, LoRaBandwidth::Khz125, LoRaCodingRate::Cr4_5, 8, false, true);
// Crude check: each step roughly doubles airtime (LDRO doesn't
// break the doubling trend — it just shifts constants).
let t10 = toa_us(&sf10, 80);
let t11 = toa_us(&sf11, 80);
let t12 = toa_us(&sf12, 80);
assert!(t11 > t10 * 15 / 10, "SF11 should be > 1.5x SF10, got {} vs {}", t11, t10);
assert!(t12 > t11 * 15 / 10, "SF12 should be > 1.5x SF11, got {} vs {}", t12, t11);
}
#[test]
fn toa_assumed_peer_80b_matches_plan_table() {
let mk = |sf, bw| cfg(sf, bw, LoRaCodingRate::Cr4_5, 8, false, true);
// Plan table values (approximate, within 5%).
approx(toa_us(&mk(7, LoRaBandwidth::Khz500), 80), 36_000, 5);
approx(toa_us(&mk(7, LoRaBandwidth::Khz250), 80), 72_000, 5);
approx(toa_us(&mk(7, LoRaBandwidth::Khz125), 80), 144_000, 5);
approx(toa_us(&mk(8, LoRaBandwidth::Khz125), 80), 257_000, 5);
approx(toa_us(&mk(9, LoRaBandwidth::Khz125), 80), 452_000, 5);
approx(toa_us(&mk(10, LoRaBandwidth::Khz125), 80), 862_000, 5);
approx(toa_us(&mk(11, LoRaBandwidth::Khz125), 80), 1_806_000, 5);
approx(toa_us(&mk(12, LoRaBandwidth::Khz125), 80), 3_285_000, 5);
}
#[test]
fn toa_no_underflow_at_small_pl_sf12_implicit_no_crc() {
// num = 8·PL − 4·SF + 28 + 16·CRC − 20·H goes negative here; the
// i64 + max(0) guard must kick in without panicking or wrapping.
let c = cfg(12, LoRaBandwidth::Khz125, LoRaCodingRate::Cr4_5, 8, true, false);
let t = toa_us(&c, 1);
// Only 8 payload symbols survive (the formula floors to 0 extra);
// should be preamble + 8·T_sym ≈ 401 + 262 = 663 ms roughly.
approx(t, 663_000, 5);
}
// Retry-count derivation table from the plan.
#[test]
fn retries_sf7_bw500_hits_hard_cap() {
let (n, s) = cad_retries(36_000);
assert_eq!(n, 10);
assert_eq!(s, 36_000);
}
#[test]
fn retries_sf10_bw125() {
// T_assumed ≈ 862 ms; budget 2.5 s ⇒ 2 sleeps ⇒ 3 retries.
let (n, _) = cad_retries(862_000);
assert_eq!(n, 3);
}
#[test]
fn retries_sf11_bw125() {
// T_assumed ≈ 1.81 s; budget 2.5 s ⇒ 1 sleep ⇒ 2 retries.
let (n, _) = cad_retries(1_806_000);
assert_eq!(n, 2);
}
#[test]
fn retries_sf12_bw125_degraded() {
// T_assumed ≈ 3.29 s > 2.5 s budget ⇒ 0 sleeps ⇒ 1 retry (bail on busy).
let (n, _) = cad_retries(3_285_000);
assert_eq!(n, 1);
}
#[test]
fn retries_zero_delay_falls_back_to_single_cad() {
// Unconfigured safety: avoid divide-by-zero.
let (n, s) = cad_retries(0);
assert_eq!(n, 1);
assert_eq!(s, 0);
}
// Jitter sanity.
#[test]
fn jitter_stays_within_pm_20_pct() {
let base = 1_000_000u32;
// Exhaustive over the low byte — enough to cover the `% span` range.
let mut saw_low = false;
let mut saw_high = false;
for e in 0u32..=u16::MAX as u32 {
let j = jittered_sleep_us(base, e);
// ±20% ⇒ [800_000, 1_200_000].
assert!(
(800_000..=1_200_000).contains(&j),
"jitter {} us out of ±20% bounds for entropy {}",
j,
e
);
if j <= 850_000 {
saw_low = true;
}
if j >= 1_150_000 {
saw_high = true;
}
}
assert!(saw_low && saw_high, "jitter didn't span the expected range");
}
#[test]
fn jitter_zero_base_is_zero() {
for e in [0u32, 1, 42, 0xDEAD_BEEF] {
assert_eq!(jittered_sleep_us(0, e), 0);
}
}
}
+10
View File
@@ -29,6 +29,7 @@ mod driver;
mod hal;
#[cfg(not(test))]
mod host;
mod lbt;
mod protocol;
#[cfg(not(test))]
mod radio;
@@ -83,6 +84,15 @@ cfg_if::cfg_if! {
#[cfg(not(test))]
async fn run(spawner: Spawner) {
let board = <board::Board as LoRaBoard>::init();
// Read + log + clear POWER.RESETREAS before any other boot output so
// the cause of the *previous* reset (if any) lands at the very top
// of the RTT log. Critical for soak-debugging silent crash-reboots:
// a self-rebooting firmware otherwise looks like the log just
// restarted with no explanation. nRF52840-only.
#[cfg(any(feature = "rak_wisblock_4631", feature = "wio_tracker_l1"))]
crate::hal::nrf52840::dump_reset_reason();
let parts = board.into_parts();
// Build the GET_INFO struct once at boot. This is the authoritative
+1671 -273
View File
File diff suppressed because it is too large. Load diff