From 54b2609a04270dff1223c4097b9ec64769e8eb5b Mon Sep 17 00:00:00 2001 From: JuliDi Date: Fri, 13 Nov 2026 14:46:54 +0100 Subject: [PATCH 01/16] chore: bump dependency versions, add rust-toolchain.toml --- rust-toolchain.toml | 4 + software/firmware/Cargo.lock | 995 +++++++++++++++----- software/firmware/Cargo.toml | 30 +- software/firmware/src/bridge.rs | 84 +- software/firmware/src/common.rs | 11 +- software/firmware/src/main.rs | 102 +- software/firmware/src/measurement/espnow.rs | 26 +- software/firmware/src/measurement/uart.rs | 2 +- software/firmware/src/motor/servo42c.rs | 15 +- software/firmware/src/ota_responder.rs | 66 +- software/firmware/src/role_provision.rs | 12 +- software/firmware/src/rx.rs | 57 +- software/firmware/src/turntable.rs | 53 +- software/firmware/src/tx.rs | 51 +- software/pc/Cargo.lock | 366 +++---- software/pc/Cargo.toml | 8 +- software/pc/src/sim.rs | 176 ++-- software/protocol/Cargo.lock | 85 +- software/protocol/Cargo.toml | 4 +- software/protocol/src/lib.rs | 14 + software/protocol/src/tx_logic.rs | 11 +- 21 files changed, 1379 insertions(+), 793 deletions(-) create mode 100644 rust-toolchain.toml diff --git a/rust-toolchain.toml b/rust-toolchain.toml new file mode 100644 index 0000000..64834b1 --- /dev/null +++ b/rust-toolchain.toml @@ -0,0 +1,4 @@ +[toolchain] +channel = "1.100" +components = ["rustfmt", "clippy"] +targets = ["riscv32imc-unknown-none-elf"] diff --git a/software/firmware/Cargo.lock b/software/firmware/Cargo.lock index c28e18a..1a8679b 100644 --- a/software/firmware/Cargo.lock +++ b/software/firmware/Cargo.lock @@ -3,16 +3,28 @@ version = 4 [[package]] -name = "allocator-api2" -version = "0.3.1" +name = "aead" +version = "0.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c583acf993cf4245c4acb0a2cc2ab1f9cc097de73411bb6d3647ff6af2b1013d" +checksum = "0b613b8e1e3cf911a086f53f03bf286f52fd7a7258e4fa606f0ef220d39d8877" +dependencies = [ + "generic-array", +] + +[[package]] +name = "aho-corasick" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba" +dependencies = [ + "memchr", +] [[package]] -name = "anyhow" -version = "1.0.102" +name = "allocator-api2" +version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7f202df86484c868dbad7eaa557ef785d5c66295e41b460ef922eca0723b842c" +checksum = "c583acf993cf4245c4acb0a2cc2ab1f9cc097de73411bb6d3647ff6af2b1013d" [[package]] name = "atomic-polyfill" @@ -41,10 +53,10 @@ version = "0.1.0" dependencies = [ "beambench-protocol", "critical-section", - "defmt 1.0.1", + "defmt 1.2.0", "embassy-executor", "embassy-futures", - "embassy-sync 0.7.2", + "embassy-sync 0.8.0", "embassy-time", "embedded-io 0.7.1", "embedded-io-async 0.7.0", @@ -53,11 +65,11 @@ dependencies = [ "esp-backtrace", "esp-bootloader-esp-idf", "esp-hal", - "esp-hal-smartled2", + "esp-hal-smartled", "esp-radio", "esp-rtos", "esp-storage", - "heapless 0.9.2", + "heapless 0.9.3", "mks-servo42-rs", "postcard", "rtt-target", @@ -70,8 +82,8 @@ dependencies = [ name = "beambench-protocol" version = "0.1.0" dependencies = [ - "defmt 1.0.1", - "heapless 0.9.2", + "defmt 1.2.0", + "heapless 0.9.3", "postcard", "serde", ] @@ -102,12 +114,6 @@ version = "1.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" -[[package]] -name = "bitflags" -version = "2.11.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "843867be96c8daad0d758b57df9392b6d8d271134fce549de6ce169ff98a92af" - [[package]] name = "block-buffer" version = "0.10.4" @@ -117,19 +123,39 @@ dependencies = [ "generic-array", ] +[[package]] +name = "block-buffer" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa" +dependencies = [ + "hybrid-array", +] + [[package]] name = "bt-hci" -version = "0.6.0" +version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bb938a3b4c5cc6c2409275bad789c0346a0495fa071a0acc5d72b9bd3175a2f7" +checksum = "8f3c66fd0a41a3b3a5906847b1bf5516048ce083e24fa9341a0fa31d3b4cd73d" dependencies = [ "btuuid", - "defmt 1.0.1", - "embassy-sync 0.7.2", - "embedded-io 0.6.1", - "embedded-io-async 0.6.1", + "defmt 1.2.0", + "embassy-sync 0.8.0", + "embedded-io 0.7.1", + "embedded-io-async 0.7.0", "futures-intrusive", - "heapless 0.9.2", + "heapless 0.8.0", +] + +[[package]] +name = "bt-hci-transport" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ffb9819c69cf88877f5eebc8c5ade0ab50f2bf9475bbb3eb714d66c55b0cb64" +dependencies = [ + "defmt 1.2.0", + "embedded-io 0.7.1", + "embedded-io-async 0.7.0", ] [[package]] @@ -141,6 +167,12 @@ dependencies = [ "defmt 0.3.100", ] +[[package]] +name = "byte" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "21c7ab3e4ae80853c7f8dcdcd904dfa25c02cc373534b8d165194325a088a7cc" + [[package]] name = "bytemuck" version = "1.25.0" @@ -153,12 +185,43 @@ version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" +[[package]] +name = "cc" +version = "1.11.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33ef9e3e8154a45c7a95cff4c1299702106ad94062d7bb85fdc5d3a5afd91d45" +dependencies = [ + "find-msvc-tools", + "shlex", +] + +[[package]] +name = "ccm" +version = "0.4.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0a9cf981c7e62b6fb02225592ee7ebf221e0b0b5317984a57a1e9d21af20e317" +dependencies = [ + "aead", + "cipher", + "ctr", + "subtle", +] + [[package]] name = "cfg-if" version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" +[[package]] +name = "cipher" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ee52072ec15386f770805afd189a01c8841be8696bed250fa2f13c4c0d6dfb7" +dependencies = [ + "generic-array", +] + [[package]] name = "cobs" version = "0.3.0" @@ -174,11 +237,21 @@ version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0b396d1f76d455557e1218ec8066ae14bba60b4b36ecd55577ba979f5db7ecaa" +[[package]] +name = "cordyceps" +version = "0.3.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5b9ab7e0ca1d179628fa0172b2b97203c7fa0cd81be2448bd446fb9559ca9261" +dependencies = [ + "loom", + "tracing", +] + [[package]] name = "cpufeatures" -version = "0.2.17" +version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566" dependencies = [ "libc", ] @@ -199,6 +272,24 @@ dependencies = [ "typenum", ] +[[package]] +name = "crypto-common" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453" +dependencies = [ + "hybrid-array", +] + +[[package]] +name = "ctr" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "049bb91fb4aaf0e3c7efa6cd5ef877dbbbd15b39dad06d9948de4ec8a75761ea" +dependencies = [ + "cipher", +] + [[package]] name = "darling" version = "0.20.11" @@ -221,12 +312,12 @@ dependencies = [ [[package]] name = "darling" -version = "0.23.0" +version = "0.24.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "25ae13da2f202d56bd7f91c25fba009e7717a1e4a1cc98a76d844b65ae912e9d" +checksum = "ed17f5901b6630b993ca003def43f2f8ef4014fc13b047b57aad617ff32bc2ec" dependencies = [ - "darling_core 0.23.0", - "darling_macro 0.23.0", + "darling_core 0.24.1", + "darling_macro 0.24.1", ] [[package]] @@ -258,15 +349,15 @@ dependencies = [ [[package]] name = "darling_core" -version = "0.23.0" +version = "0.24.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9865a50f7c335f53564bb694ef660825eb8610e0a53d3e11bf1b0d3df31e03b0" +checksum = "6837e2cf7485aaae18f86181d2f0e9a7ed297a025e220aeabf63fdebd3a2ddff" dependencies = [ "ident_case", "proc-macro2", "quote", "strsim", - "syn 2.0.117", + "syn 3.0.10", ] [[package]] @@ -293,13 +384,13 @@ dependencies = [ [[package]] name = "darling_macro" -version = "0.23.0" +version = "0.24.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ac3984ec7bd6cfa798e62b4a642426a5be0e68f9401cfc2a01e3fa9ea2fcdb8d" +checksum = "2ac7135c3ef02b2f7833bbeb1be5ba7f966dcde8a87c6b87f65a778d71a02785" dependencies = [ - "darling_core 0.23.0", + "darling_core 0.24.1", "quote", - "syn 2.0.117", + "syn 3.0.10", ] [[package]] @@ -308,37 +399,36 @@ version = "0.3.100" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f0963443817029b2024136fc4dd07a5107eb8f977eaf18fcd1fdeb11306b64ad" dependencies = [ - "defmt 1.0.1", + "defmt 1.2.0", ] [[package]] name = "defmt" -version = "1.0.1" +version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "548d977b6da32fa1d1fda2876453da1e7df63ad0304c8b3dae4dbe7b96f39b78" +checksum = "e4a0795ac740cb54d7b3775c9c17345f6aaecf884c01733b39d6017738e0e3e1" dependencies = [ - "bitflags 1.3.2", + "bitflags", "defmt-macros", ] [[package]] name = "defmt-macros" -version = "1.0.1" +version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3d4fc12a85bcf441cfe44344c4b72d58493178ce635338a3f3b78943aceb258e" +checksum = "840bb056bd99c495c9188198a258ab787c79f306d864db3e6e8451442d6d8366" dependencies = [ "defmt-parser", - "proc-macro-error2", "proc-macro2", "quote", - "syn 2.0.117", + "syn 3.0.10", ] [[package]] name = "defmt-parser" -version = "1.0.0" +version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "10d60334b3b2e7c9d91ef8150abfb6fa4c1c39ebbcf4a81c2e346aad939fee3e" +checksum = "71958f69fb2de856c5dd51ac9377e986ca1aa5919f931bf5395a807277f889a0" dependencies = [ "thiserror", ] @@ -360,8 +450,38 @@ 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.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" +dependencies = [ + "block-buffer 0.12.1", + "crypto-common 0.2.2", +] + +[[package]] +name = "docsplay" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8547ea80db62c5bb9d7796fcce5e6e07d1136bdc1a02269095061e806758fab4" +dependencies = [ + "docsplay-macros", +] + +[[package]] +name = "docsplay-macros" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11772ed3eb3db124d826f3abeadf5a791a557f62c19b123e3f07288158a71fdd" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", ] [[package]] @@ -375,13 +495,13 @@ dependencies = [ [[package]] name = "embassy-embedded-hal" -version = "0.5.0" +version = "0.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "554e3e840696f54b4c9afcf28a0f24da431c927f4151040020416e7393d6d0d8" +checksum = "b0641612053b2f34fc250bb63f6630ae75de46e02ade7f457268447081d709ce" dependencies = [ "embassy-futures", "embassy-hal-internal", - "embassy-sync 0.7.2", + "embassy-sync 0.8.0", "embedded-hal 0.2.7", "embedded-hal 1.0.0", "embedded-hal-async", @@ -392,10 +512,11 @@ dependencies = [ [[package]] name = "embassy-executor" -version = "0.9.1" +version = "0.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "06070468370195e0e86f241c8e5004356d696590a678d47d6676795b2e439c6b" +checksum = "5d0d3b15c9d7dc4fec1d8cb77112472fb008b3b28c51ad23838d83587a6d2f1e" dependencies = [ + "cordyceps", "critical-section", "document-features", "embassy-executor-macros", @@ -404,9 +525,9 @@ dependencies = [ [[package]] name = "embassy-executor-macros" -version = "0.7.0" +version = "0.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dfdddc3a04226828316bf31393b6903ee162238576b1584ee2669af215d55472" +checksum = "d11a246f53de5f97a387f40ac24726817cd0b6f833e7603baac784f29d6ff276" dependencies = [ "darling 0.20.11", "proc-macro2", @@ -426,14 +547,14 @@ version = "0.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "dc2d050bdc5c21e0862a89256ed8029ae6c290a93aecefc73084b3002cdebb01" dependencies = [ - "defmt 1.0.1", + "defmt 1.2.0", ] [[package]] name = "embassy-hal-internal" -version = "0.3.0" +version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "95285007a91b619dc9f26ea8f55452aa6c60f7115a4edc05085cd2bd3127cd7a" +checksum = "7f10ce10a4dfdf6402d8e9bd63128986b96a736b1a0a6680547ed2ac55d55dba" dependencies = [ "num-traits", ] @@ -466,18 +587,32 @@ checksum = "73974a3edbd0bd286759b3d483540f0ebef705919a5f56f4fc7709066f71689b" dependencies = [ "cfg-if", "critical-section", - "defmt 1.0.1", "embedded-io-async 0.6.1", "futures-core", "futures-sink", "heapless 0.8.0", ] +[[package]] +name = "embassy-sync" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7bbd85cf5a5ae56bdf26f618364af642d1d0a4e245cdd75cd9aabda382f65a81" +dependencies = [ + "cfg-if", + "critical-section", + "defmt 1.2.0", + "embedded-io-async 0.7.0", + "futures-core", + "futures-sink", + "heapless 0.9.3", +] + [[package]] name = "embassy-time" -version = "0.5.0" +version = "0.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f4fa65b9284d974dad7a23bb72835c4ec85c0b540d86af7fc4098c88cff51d65" +checksum = "592b0c143ec626e821d4d90da51a2bd91d559d6c442b7c74a47d368c9e23d97a" dependencies = [ "cfg-if", "critical-section", @@ -491,9 +626,9 @@ dependencies = [ [[package]] name = "embassy-time-driver" -version = "0.2.1" +version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a0a244c7dc22c8d0289379c8d8830cae06bb93d8f990194d0de5efb3b5ae7ba6" +checksum = "6ee71af1b3a0deaa53eaf2d39252f83504c853646e472400b763060389b9fcc9" dependencies = [ "document-features", ] @@ -557,7 +692,7 @@ version = "0.7.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9eb1aa714776b75c7e67e1da744b81a129b3ff919c8712b5e1b32252c1f07cc7" dependencies = [ - "defmt 1.0.1", + "defmt 1.2.0", ] [[package]] @@ -576,7 +711,7 @@ version = "0.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2564b9f813c544241430e147d8bc454815ef9ac998878d30cc3055449f7fd4c0" dependencies = [ - "defmt 1.0.1", + "defmt 1.2.0", "embedded-io 0.7.1", ] @@ -601,7 +736,7 @@ version = "1.1.10" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "25b07a8dfbbbfc0064c0a6bdf9edcf966de6b1c33ce344bdeca3b41615452634" dependencies = [ - "defmt 1.0.1", + "defmt 1.2.0", "enumset_derive", ] @@ -625,15 +760,15 @@ checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" [[package]] name = "esp-alloc" -version = "0.9.0" +version = "0.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "641e43d6a60244429117ef2fa7a47182120c7561336ea01f6fb08d634f46bae1" +checksum = "f73e8d355019c740f6a5a78429633040617d28a378c271464caadc52c78216e3" dependencies = [ "allocator-api2", - "cfg-if", "document-features", "enumset", "esp-config", + "esp-metadata-generated", "esp-sync", "linked_list_allocator", "rlsf", @@ -641,44 +776,43 @@ dependencies = [ [[package]] name = "esp-backtrace" -version = "0.18.1" +version = "0.20.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3318413fb566c7227387f67736cf70cd74d80a11f2bb31c7b95a9eb48d079669" +checksum = "4fbfed00e884572d620a6958b13456fc2bb8ab75802b5adc8afc224f97cdebad" dependencies = [ - "cfg-if", - "defmt 1.0.1", + "defmt 1.2.0", "document-features", "esp-config", "esp-metadata-generated", "esp-println", - "heapless 0.9.2", + "heapless 0.9.3", "riscv", "xtensa-lx", ] [[package]] name = "esp-bootloader-esp-idf" -version = "0.4.0" +version = "0.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "02a56964ab5479ac20c9cf76fa3b0d3f2233b20b5d8554e81ef5d65f63c20567" +checksum = "ba0e487f6843419bb085d871f6e860da1bb8c267ce1c5db1051b83882e943054" dependencies = [ - "cfg-if", - "defmt 1.0.1", + "defmt 1.2.0", "document-features", - "embedded-storage", "esp-config", "esp-hal-procmacros", "esp-metadata-generated", "esp-rom-sys", + "esp-storage", "jiff", + "sha2", "strum", ] [[package]] name = "esp-config" -version = "0.6.1" +version = "0.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "102871054f8dd98202177b9890cb4b71d0c6fe1f1413b7a379a8e0841fc2473c" +checksum = "fcd577a122ec917691f6820a3df54388ecebc750f071b060f5e83707bc415512" dependencies = [ "document-features", "esp-metadata-generated", @@ -689,22 +823,21 @@ dependencies = [ [[package]] name = "esp-hal" -version = "1.0.0" +version = "1.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "54786287c0a61ca0f78cb0c338a39427551d1be229103b4444591796c579e093" +checksum = "c9e3dfd511fed638fe41fdb4595f8c7f0cbb488d0f0cf2bbc063d76d805057cf" dependencies = [ "bitfield", - "bitflags 2.11.0", "bytemuck", - "cfg-if", "critical-section", - "defmt 1.0.1", + "defmt 1.2.0", "delegate", - "digest", + "digest 0.10.7", + "digest 0.11.3", "document-features", "embassy-embedded-hal", "embassy-futures", - "embassy-sync 0.7.2", + "embassy-sync 0.8.0", "embedded-can", "embedded-hal 1.0.0", "embedded-hal-async", @@ -721,19 +854,26 @@ dependencies = [ "esp-sync", "esp32", "esp32c2", - "esp32c3", + "esp32c3 0.33.0", + "esp32c5", "esp32c6", + "esp32c61", "esp32h2", + "esp32p4", "esp32s2", "esp32s3", + "esp32s31", "fugit", "instability", "nb 1.1.0", "paste", "portable-atomic", + "rand_core 0.10.1", "rand_core 0.6.4", "rand_core 0.9.5", "riscv", + "somni-template", + "static_cell", "strum", "ufmt-write", "xtensa-lx", @@ -742,9 +882,9 @@ dependencies = [ [[package]] name = "esp-hal-procmacros" -version = "0.21.0" +version = "0.23.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3e025a7a7a0affdb4ff913b5c4494aef96ee03d085bf83c27453ae3a71d50da6" +checksum = "1a8733fdeadc349ba1e4a345c7bfb74d195d8c98fd3be9d2c15bfd78601cbc44" dependencies = [ "document-features", "proc-macro-crate", @@ -755,43 +895,46 @@ dependencies = [ ] [[package]] -name = "esp-hal-smartled2" -version = "0.28.1" +name = "esp-hal-smartled" +version = "0.18.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c1a00c36869076635bf254dee6f78ac8b9d3fa71541470538a8fffbdb626d120" +checksum = "5315ad80e19e70920e282676e56fec5fb2115c36c9f9fbe14b154148ba761743" dependencies = [ + "document-features", "esp-hal", "num-traits", "smart-leds-trait", + "thiserror", ] [[package]] name = "esp-metadata-generated" -version = "0.3.0" +version = "0.5.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9a93e39c8ad8d390d248dc7b9f4b59a873f313bf535218b8e2351356972399e3" +checksum = "911aadae41ec99104efa865bd0b6e486b4b735999f9b571963748a46d16495ab" [[package]] name = "esp-phy" -version = "0.1.1" +version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6b1facf348e1e251517278fc0f5dc134e95e518251f5796cfbb532ca226a29bf" +checksum = "08a925ab42e72eaaa77167352bab7c2bd528ea962a0eb40501324f6db594f88c" dependencies = [ - "cfg-if", - "defmt 1.0.1", + "defmt 1.2.0", "document-features", + "embassy-sync 0.8.0", "esp-config", "esp-hal", "esp-metadata-generated", "esp-sync", - "esp-wifi-sys", + "esp-wifi-sys-esp32c3", + "esp32c3 0.34.0", ] [[package]] name = "esp-println" -version = "0.16.1" +version = "0.18.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5a30e6c9fbcc01c348d46706fef8131c7775ab84c254a3cd65d0cd3f6414d592" +checksum = "ebf772a41bc642b57399632aa06ab55391de35b2b8fcbb1b270d282fbd0fe5ff" dependencies = [ "document-features", "esp-metadata-generated", @@ -801,16 +944,18 @@ dependencies = [ [[package]] name = "esp-radio" -version = "0.17.0" +version = "1.0.0-beta.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "684c4de2f8907b73c9b891fbda65286a86d34fced4b856f36a7896c211f2f265" +checksum = "50247f4e91000fc87661e77254126c74acc4535f822ee247f7778807202dc938" dependencies = [ "allocator-api2", "bt-hci", - "cfg-if", - "defmt 1.0.1", + "bt-hci-transport", + "defmt 1.2.0", + "docsplay", "document-features", "embassy-net-driver", + "embassy-sync 0.8.0", "embedded-io 0.6.1", "embedded-io 0.7.1", "embedded-io-async 0.6.1", @@ -823,30 +968,44 @@ dependencies = [ "esp-metadata-generated", "esp-phy", "esp-radio-rtos-driver", + "esp-rom-sys", "esp-sync", - "esp-wifi-sys", - "heapless 0.9.2", + "esp-wifi-sys-esp32", + "esp-wifi-sys-esp32c2", + "esp-wifi-sys-esp32c3", + "esp-wifi-sys-esp32c6", + "esp-wifi-sys-esp32h2", + "esp-wifi-sys-esp32s2", + "esp-wifi-sys-esp32s3", + "esp-wifi-sys-esp32s31", + "esp32c3 0.34.0", + "heapless 0.9.3", + "ieee802154", "instability", "num-derive", "num-traits", "portable-atomic", "portable_atomic_enum", - "smoltcp", + "xarxa-driver", ] [[package]] name = "esp-radio-rtos-driver" -version = "0.2.0" +version = "0.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "543bc31d1851afd062357e7810c1a9633f282fd3993583499a841ab497cbca6c" +checksum = "27d3ad9d7ed96260566acd1a69a908ff805cfaa73a936ae445c1252e1ec983be" +dependencies = [ + "esp-sync", + "portable-atomic", +] [[package]] name = "esp-riscv-rt" -version = "0.13.0" +version = "0.15.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "502744a5b1e7268d27fd2a4e56ad45efe42ead517d6c517a6961540de949b0ee" +checksum = "626c6b1477224c46fb27919d53ac5bf4ef6f7f70344ee26a720373761aaef531" dependencies = [ - "defmt 1.0.1", + "defmt 1.2.0", "document-features", "riscv", "riscv-rt", @@ -854,45 +1013,48 @@ dependencies = [ [[package]] name = "esp-rom-sys" -version = "0.1.3" +version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cd66cccc6dd2d13e9f33668a57717ab14a6d217180ec112e6be533de93e7ecbf" +checksum = "e933ff78374b763b65998b64ad671b4890ed4ba13a80deff9f53afe95ede289d" dependencies = [ - "cfg-if", "document-features", "esp-metadata-generated", + "esp32c3 0.33.0", ] [[package]] name = "esp-rtos" -version = "0.2.0" +version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "162ec711c8d06e79c67b75d01595539e86b0aac209643af98ca87a12250428b3" +checksum = "2f8e99f512a839c78a77c2e55e1f0d208851cfa48935847d5e0b5e8b2c5a6289" dependencies = [ "allocator-api2", - "cfg-if", - "defmt 1.0.1", + "defmt 1.2.0", "document-features", "embassy-executor", - "embassy-sync 0.7.2", + "embassy-sync 0.8.0", "embassy-time-driver", "embassy-time-queue-utils", + "esp-alloc", "esp-config", "esp-hal", "esp-hal-procmacros", "esp-metadata-generated", "esp-radio-rtos-driver", + "esp-rom-sys", "esp-sync", "portable-atomic", + "riscv", + "xtensa-lx", ] [[package]] name = "esp-storage" -version = "0.8.1" +version = "0.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1495fc1f5549bdd840b52d9ceb201746200e1620d2636f46958c11e765623b80" +checksum = "6ef0e785f54e316f64a1e14a7a2f061a2ea0b038b284902ca71e1e1f5574cf47" dependencies = [ - "defmt 1.0.1", + "defmt 1.2.0", "document-features", "embedded-storage", "esp-hal", @@ -900,111 +1062,222 @@ dependencies = [ "esp-metadata-generated", "esp-rom-sys", "esp-sync", + "esp32c3 0.33.0", ] [[package]] name = "esp-sync" -version = "0.1.1" +version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d44974639b4e88914f83fe60d2832c00276657d7d857628fdfc966cc7302e8a8" +checksum = "064fd57eed12b5cbb669b3935e1f647fd6945b89938116d61153fb45fd703422" dependencies = [ - "cfg-if", - "defmt 1.0.1", + "defmt 1.2.0", "document-features", "embassy-sync 0.6.2", "embassy-sync 0.7.2", + "embassy-sync 0.8.0", "esp-metadata-generated", "riscv", "xtensa-lx", ] [[package]] -name = "esp-wifi-sys" -version = "0.8.1" +name = "esp-wifi-sys-esp32" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4644d49bde1bdeb3cd20fcc8c08be09f8f67af4b80123e54f665fdebd9a3358" +dependencies = [ + "defmt 1.2.0", +] + +[[package]] +name = "esp-wifi-sys-esp32c2" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "57b97263761d6fc207eeffa1f4330b7b80dbf78e5ebe201aa32bf9d37d2ee5cc" +dependencies = [ + "defmt 1.2.0", +] + +[[package]] +name = "esp-wifi-sys-esp32c3" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c1345555a7856033077e8ca26572e4739a1b43f8d52daaa0fdf6a1497fe88845" +dependencies = [ + "defmt 1.2.0", +] + +[[package]] +name = "esp-wifi-sys-esp32c6" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5bb01c06a3dbd75121146f619513ee610505b2d80ce3c421ed0c840a19e12f67" +dependencies = [ + "defmt 1.2.0", +] + +[[package]] +name = "esp-wifi-sys-esp32h2" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9d88f3ed22082eae3d9ec3d98723040201f5825b9a707475000a7fda62ab2d9e" +dependencies = [ + "defmt 1.2.0", +] + +[[package]] +name = "esp-wifi-sys-esp32s2" +version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "89b6544f6f0cb86169d1f93ba2101a8d50358a040c5043676ed86b793e09b12c" +checksum = "2f79fe19c5ce6b1eafa6ce7f022e5cd0aca8e6d01c9d1e29b4c9ad62b1f5f82a" dependencies = [ - "anyhow", - "defmt 1.0.1", + "defmt 1.2.0", +] + +[[package]] +name = "esp-wifi-sys-esp32s3" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1e227f3f97c28c6f52bd28758ddb544854fe52d48b3219a5194846ec982fcfb" +dependencies = [ + "defmt 1.2.0", +] + +[[package]] +name = "esp-wifi-sys-esp32s31" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce987bf209ad4d95810c206acce9505d34056758ab5537ed8ced798945dc4131" +dependencies = [ + "defmt 1.2.0", ] [[package]] name = "esp32" -version = "0.39.0" +version = "0.41.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b76170a463d18f888a1ad258031901036fd827a9ef126733053ba5f8739fb0c8" +checksum = "c2f9714c79477940e5c7848b3832af89cd3bcd79abf4067e6938ae90de187a45" dependencies = [ - "critical-section", - "defmt 1.0.1", + "defmt 1.2.0", "vcell", ] [[package]] name = "esp32c2" -version = "0.28.0" +version = "0.30.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e62cf8932966b8d445b6f1832977b468178f0a84effb2e9fda89f60c24d45aa3" +checksum = "496afd4a776ec7c96c90fb665894895a1a9f8a7fd5a9d75779fa09d63f9d40a1" dependencies = [ - "critical-section", - "defmt 1.0.1", + "defmt 1.2.0", "vcell", ] [[package]] name = "esp32c3" -version = "0.31.0" +version = "0.33.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "356af3771d0d6536c735bf71136594f4d1cbb506abf6e0c51a6639e9bf4e7988" +checksum = "ffb892f670ff857033c1624f99ecba1a3f3cafa05c45d734bc129388276715cf" dependencies = [ - "critical-section", - "defmt 1.0.1", + "defmt 1.2.0", + "vcell", +] + +[[package]] +name = "esp32c3" +version = "0.34.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "569e03d871eac998bc62ef95a9a6d31a91fc0aaef0e0017a6b5a6a9c4759768a" +dependencies = [ + "vcell", +] + +[[package]] +name = "esp32c5" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "97afa80d8110c7234f840252baa8ee8de28f78e8dc233d2d430c0ccfbe59a2b5" +dependencies = [ + "defmt 1.2.0", "vcell", ] [[package]] name = "esp32c6" -version = "0.22.0" +version = "0.24.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8f5e511df672d79cd63365c92045135e01ba952b6bddd25b660baff5e1110f6b" +checksum = "a207a5d6886ca89b4f220606dcf3779ca869803df192508314939186ae8de1ee" dependencies = [ - "critical-section", - "defmt 1.0.1", + "defmt 1.2.0", + "vcell", +] + +[[package]] +name = "esp32c61" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8690ba8b6292db301db513bb9b24263499c9a1ecd22b263dd4210ef12d47fe1" +dependencies = [ + "defmt 1.2.0", "vcell", ] [[package]] name = "esp32h2" -version = "0.18.0" +version = "0.20.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "083a75597f85acaabc0b05998f22455d78c33c4d23ff5f12df2b9590e46f571b" +dependencies = [ + "defmt 1.2.0", + "vcell", +] + +[[package]] +name = "esp32p4" +version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ed4a50bbd1380931e095e0973b9b12f782a9c481f2edf1f7c42e7eb4ff736d6d" +checksum = "4c4b1a8cb0d4831d710437f72a73246682919c16ef37a99788f1e26d9f49fe20" dependencies = [ "critical-section", - "defmt 1.0.1", "vcell", ] [[package]] name = "esp32s2" -version = "0.30.0" +version = "0.32.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "98574d4c577fbe888fe3e6df7fc80d25a05624d9998f7d7de1500ae21fcca78f" +checksum = "dbeb62af2f2ca94a85be9ab22f8ad97c23ba79b9b3d3e4e20f3e0957bc5f2b2d" dependencies = [ - "critical-section", - "defmt 1.0.1", + "defmt 1.2.0", "vcell", ] [[package]] name = "esp32s3" -version = "0.34.0" +version = "0.36.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1810d8ee4845ef87542af981e38eb80ab531d0ef1061e1486014ab7af74c337a" +checksum = "ab08eb1f516ba72b7eb272cdd88cd74899552292a294b831b2143a3e60f1666a" +dependencies = [ + "defmt 1.2.0", + "vcell", +] + +[[package]] +name = "esp32s31" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d8b4f101d37c233fe88b2b5e6d27fedab934a52f804e34f52b4b9d4d5ba2ea63" dependencies = [ "critical-section", - "defmt 1.0.1", "vcell", ] +[[package]] +name = "find-msvc-tools" +version = "0.1.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" + [[package]] name = "fnv" version = "1.0.7" @@ -1013,11 +1286,11 @@ checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" [[package]] name = "fugit" -version = "0.3.9" +version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4e639847d312d9a82d2e75b0edcc1e934efcc64e6cb7aa94f0b1fbec0bc231d6" +checksum = "e88e2d6927cbdbbbdc85fc550cee539e63ae0f76445f13094833f63bb65b62f5" dependencies = [ - "defmt 0.3.100", + "defmt 1.2.0", "gcd", ] @@ -1066,6 +1339,20 @@ version = "2.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1d758ba1b47b00caf47f24925c0074ecb20d6dfcffe7f6d53395c0465674841a" +[[package]] +name = "generator" +version = "0.8.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ea6c6a73cd1aa4f4f00c02b109fa55d3a9d6ecc2fc4f53177b74ed6ee23b0c53" +dependencies = [ + "cc", + "libc", + "log", + "rustversion", + "windows-core", + "windows-sys", +] + [[package]] name = "generic-array" version = "0.14.7" @@ -1094,6 +1381,17 @@ dependencies = [ "byteorder", ] +[[package]] +name = "hash32-derive" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59d2aba832b60be25c1b169146b27c64115470981b128ed84c8db18c1b03c6ff" +dependencies = [ + "proc-macro2", + "quote", + "syn 1.0.109", +] + [[package]] name = "hashbrown" version = "0.16.1" @@ -1120,18 +1418,17 @@ version = "0.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0bfb9eb618601c89945a70e254898da93b13be0388091d42117462b265bb3fad" dependencies = [ - "defmt 0.3.100", "hash32 0.3.1", "stable_deref_trait", ] [[package]] name = "heapless" -version = "0.9.2" +version = "0.9.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2af2455f757db2b292a9b1768c4b70186d443bcb3b316252d6b540aec1cd89ed" +checksum = "25ba4bd83f9415b58b4ed8dc5714c76e626a105be4646c02630ad730ad3b5aa4" dependencies = [ - "defmt 1.0.1", + "defmt 1.2.0", "hash32 0.3.1", "serde_core", "stable_deref_trait", @@ -1143,12 +1440,35 @@ version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" +[[package]] +name = "hybrid-array" +version = "0.4.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3944cf8cf766b40e2a1a333ee5e9b563f854d5fa49d6a8ca2764e97c6eddb214" +dependencies = [ + "typenum", +] + [[package]] name = "ident_case" version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39" +[[package]] +name = "ieee802154" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4fcb6de62f20180795db19ae2ab338852a66f8576581554fa8a730e437b450a5" +dependencies = [ + "byte", + "ccm", + "cipher", + "defmt 0.3.100", + "hash32 0.2.1", + "hash32-derive", +] + [[package]] name = "indexmap" version = "2.13.0" @@ -1170,15 +1490,15 @@ dependencies = [ [[package]] name = "instability" -version = "0.3.11" +version = "0.3.14" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "357b7205c6cd18dd2c86ed312d1e70add149aea98e7ef72b9fdf0270e555c11d" +checksum = "4c3b5acc1e2fd9375041a388da33d1eb8aed5f7a8c0dd3543e3ea2805adfbe20" dependencies = [ - "darling 0.23.0", + "darling 0.24.1", "indoc", "proc-macro2", "quote", - "syn 2.0.117", + "syn 3.0.10", ] [[package]] @@ -1211,6 +1531,12 @@ dependencies = [ "syn 2.0.117", ] +[[package]] +name = "lazy_static" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb" + [[package]] name = "libc" version = "0.2.182" @@ -1245,10 +1571,26 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5e5032e24019045c762d3c0f28f5b6b8bbf38563a65908389bf7978758920897" [[package]] -name = "managed" -version = "0.8.0" +name = "loom" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1611ddbf89dc6ae42cfbd51fc207836140130257646eab8d6d2fb16577db2d2" +dependencies = [ + "cfg-if", + "generator", + "scoped-tls", + "tracing", + "tracing-subscriber", +] + +[[package]] +name = "matchers" +version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0ca88d725a0a943b096803bd34e73a4437208b6077654cc4ecb2947a5f91618d" +checksum = "d1525a2a28c7f4fa0fc98bb91ae755d1e2d1505079e05539e35bc876b5d65ae9" +dependencies = [ + "regex-automata", +] [[package]] name = "memchr" @@ -1277,6 +1619,15 @@ version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8d5439c4ad607c3c23abf66de8c8bf57ba8adcd1f129e699851a6e43935d339d" +[[package]] +name = "nu-ansi-term" +version = "0.50.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" +dependencies = [ + "windows-sys", +] + [[package]] name = "num-derive" version = "0.4.2" @@ -1297,6 +1648,12 @@ dependencies = [ "autocfg", ] +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + [[package]] name = "paste" version = "1.0.15" @@ -1377,28 +1734,6 @@ dependencies = [ "toml_edit", ] -[[package]] -name = "proc-macro-error-attr2" -version = "2.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "96de42df36bb9bba5542fe9f1a054b8cc87e172759a1868aa05c1f3acc89dfc5" -dependencies = [ - "proc-macro2", - "quote", -] - -[[package]] -name = "proc-macro-error2" -version = "2.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "11ec05c52be0a07b08061f7dd003e7d7092e0472bc731b4af7bb1ef876109802" -dependencies = [ - "proc-macro-error-attr2", - "proc-macro2", - "quote", - "syn 2.0.117", -] - [[package]] name = "proc-macro2" version = "1.0.106" @@ -1429,6 +1764,29 @@ version = "0.9.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c" +[[package]] +name = "rand_core" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" + +[[package]] +name = "regex-automata" +version = "0.4.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" + [[package]] name = "rgb" version = "0.8.53" @@ -1471,7 +1829,7 @@ version = "0.16.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3d07b9f3a0eff773fc4df11f44ada4fa302e529bff4b7fe7e6a4b98a65ce9174" dependencies = [ - "defmt 1.0.1", + "defmt 1.2.0", "riscv", "riscv-pac", "riscv-rt-macros", @@ -1541,6 +1899,12 @@ version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" +[[package]] +name = "scoped-tls" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1cf6437eb19a8f4a6cc0f7dca544973b0b78843adbfeb3683d1a94a0024a294" + [[package]] name = "scopeguard" version = "1.2.0" @@ -1598,15 +1962,36 @@ dependencies = [ [[package]] name = "sha2" -version = "0.10.9" +version = "0.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +checksum = "47d7069beb7d6ac7b9acd1039986e73443f24234f41074da099d6f994ac9ad19" dependencies = [ "cfg-if", "cpufeatures", - "digest", + "digest 0.11.3", ] +[[package]] +name = "sharded-slab" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f40ca3c46823713e0d4209592e8d6e826aa57e928f09752619fc696c499637f6" +dependencies = [ + "lazy_static", +] + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "smallvec" +version = "1.16.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "149309498a5f7334b12ddae0cad8aba81ce785fe91755068867e017cf98fee46" + [[package]] name = "smart-leds" version = "0.4.0" @@ -1625,34 +2010,31 @@ dependencies = [ "rgb", ] -[[package]] -name = "smoltcp" -version = "0.12.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dad095989c1533c1c266d9b1e8d70a1329dd3723c3edac6d03bbd67e7bf6f4bb" -dependencies = [ - "bitflags 1.3.2", - "byteorder", - "cfg-if", - "defmt 0.3.100", - "heapless 0.8.0", - "managed", -] - [[package]] name = "somni-expr" -version = "0.2.0" +version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3ed9b7648d5e8b2df6c5e49940c54bcdd2b4dd71eafc6e8f1c714eb4581b0f53" +checksum = "f024812d1302010ff9227b80650469e58a3ef129ec5fda36c7a0b6b14ce07371" dependencies = [ + "indexmap", "somni-parser", ] [[package]] name = "somni-parser" -version = "0.2.2" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ba0fb59df288988d1f80eab8a0a32b18222e87b48d07b065c2f69cfc54d946c" + +[[package]] +name = "somni-template" +version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a0f368519fc6c85fc1afdb769fb5a51123f6158013e143656e25a3485a0d401c" +checksum = "f39bb07107650fb128f05f033a97212e946a3c0625cc729c97ed586bf7f226a3" +dependencies = [ + "somni-expr", + "somni-parser", +] [[package]] name = "spin" @@ -1705,6 +2087,12 @@ dependencies = [ "syn 2.0.117", ] +[[package]] +name = "subtle" +version = "2.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6bdef32e8150c2a081110b42772ffe7d7c9032b606bc226c8260fd97e0976601" + [[package]] name = "svgbobdoc" version = "0.3.0" @@ -1740,6 +2128,17 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "syn" +version = "3.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + [[package]] name = "termcolor" version = "1.4.1" @@ -1769,6 +2168,15 @@ dependencies = [ "syn 2.0.117", ] +[[package]] +name = "thread_local" +version = "1.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ad99c4c6d32803332c548b1af0540b357b3f5fc0be8f6c6bfe8b2e6ae784070" +dependencies = [ + "cfg-if", +] + [[package]] name = "toml_datetime" version = "1.0.0+spec-1.1.0" @@ -1799,6 +2207,67 @@ dependencies = [ "winnow", ] +[[package]] +name = "tracing" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" +dependencies = [ + "pin-project-lite", + "tracing-attributes", + "tracing-core", +] + +[[package]] +name = "tracing-attributes" +version = "0.1.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", +] + +[[package]] +name = "tracing-core" +version = "0.1.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" +dependencies = [ + "once_cell", + "valuable", +] + +[[package]] +name = "tracing-log" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee855f1f400bd0e5c02d150ae5de3840039a3f54b025156404e34c23c03f47c3" +dependencies = [ + "log", + "once_cell", + "tracing-core", +] + +[[package]] +name = "tracing-subscriber" +version = "0.3.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb7f578e5945fb242538965c2d0b04418d38ec25c79d160cd279bf0731c8d319" +dependencies = [ + "matchers", + "nu-ansi-term", + "once_cell", + "regex-automata", + "sharded-slab", + "smallvec", + "thread_local", + "tracing", + "tracing-core", + "tracing-log", +] + [[package]] name = "typenum" version = "1.19.0" @@ -1829,6 +2298,12 @@ version = "0.2.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "673aac59facbab8a9007c7f6108d11f63b603f7cabff99fabf650fea5c32b861" +[[package]] +name = "valuable" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65" + [[package]] name = "vcell" version = "0.1.3" @@ -1856,19 +2331,78 @@ dependencies = [ "windows-sys", ] +[[package]] +name = "windows-core" +version = "0.100.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "803590c6856f51d15fa2e9fabe4f4703122c8737f72ef2741b4ac09d4c2192f5" +dependencies = [ + "windows-implement", + "windows-interface", + "windows-link 0.100.0", + "windows-result", + "windows-strings", +] + +[[package]] +name = "windows-implement" +version = "0.100.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1bc1bc82e5a1b1a4d7255861b07881a0407b552f50a4d8543c0c7276fa96f6e8" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", +] + +[[package]] +name = "windows-interface" +version = "0.100.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b3f7005c3b757b9b82c2f40c0e71094ff1080adddaf3e8b6ce99b545d3c48796" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", +] + [[package]] name = "windows-link" version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" +[[package]] +name = "windows-link" +version = "0.100.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b39de7c7fe78858b0144c50c3fc000bab3be17d5e9b85b1053871693c7f7415" + +[[package]] +name = "windows-result" +version = "0.100.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "44873a1ef61c85d5e2991db91fe656cfcf0731097e00dff1ac860f1cb3b752a0" +dependencies = [ + "windows-link 0.100.0", +] + +[[package]] +name = "windows-strings" +version = "0.100.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6a70b590c684f1d2854f74999896f7c0558f1bdde62f599088599e20ea1d2f60" +dependencies = [ + "windows-link 0.100.0", +] + [[package]] name = "windows-sys" version = "0.61.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" dependencies = [ - "windows-link", + "windows-link 0.2.1", ] [[package]] @@ -1880,6 +2414,17 @@ dependencies = [ "memchr", ] +[[package]] +name = "xarxa-driver" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "241eb997638d080753b73e5335427d3a27568678aafa6c0e0564485257e90738" +dependencies = [ + "critical-section", + "defmt 1.2.0", + "document-features", +] + [[package]] name = "xtensa-lx" version = "0.13.0" @@ -1891,11 +2436,11 @@ dependencies = [ [[package]] name = "xtensa-lx-rt" -version = "0.21.0" +version = "0.23.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8709f037fb123fe7ff146d2bce86f9dc0dfc53045c016bfd9d703317b6502845" +checksum = "07933551193a68b5b0a94a7c428e9626adb559661e0f4b048ac5ec1fa4bed334" dependencies = [ - "defmt 1.0.1", + "defmt 1.2.0", "document-features", "xtensa-lx", "xtensa-lx-rt-proc-macros", diff --git a/software/firmware/Cargo.toml b/software/firmware/Cargo.toml index 7166e1d..93cf88e 100644 --- a/software/firmware/Cargo.toml +++ b/software/firmware/Cargo.toml @@ -24,27 +24,27 @@ servo42c = ["dep:mks-servo42-rs"] beambench-protocol = { path = "../protocol", features = ["defmt"] } # ESP32-C3 HAL + radio -esp-hal = { version = "1.0.0", features = ["esp32c3", "unstable", "defmt"] } -esp-rtos = { version = "0.2.0", features = ["esp32c3", "embassy", "esp-radio", "defmt"] } -esp-radio = { version = "0.17.0", features = ["esp32c3", "esp-now", "defmt", "esp-alloc", "unstable"] } -esp-alloc = "0.9.0" -esp-storage = { version = "0.8.1", features = ["esp32c3", "defmt"] } -esp-backtrace = { version = "0.18.1", features = ["esp32c3", "panic-handler", "defmt"] } -esp-bootloader-esp-idf = { version = "0.4.0", features = ["esp32c3", "defmt"] } +esp-hal = { version = "1.2.2", features = ["esp32c3", "unstable", "defmt"] } +esp-rtos = { version = "0.4.0", features = ["esp32c3", "embassy", "esp-radio", "defmt"] } +esp-radio = { version = "1.0.0-beta.1", features = ["esp32c3", "esp-now", "defmt", "esp-alloc", "unstable"] } +esp-alloc = "0.11.0" +esp-storage = { version = "0.10.0", features = ["esp32c3", "defmt", "embedded-storage"] } +esp-backtrace = { version = "0.20.0", features = ["esp32c3", "panic-handler", "defmt"] } +esp-bootloader-esp-idf = { version = "0.6.0", features = ["esp32c3", "defmt"] } # Async runtime -embassy-executor = { version = "0.9.1" } +embassy-executor = { version = "0.10.0" } embassy-futures = "0.1" -embassy-sync = "0.7" -embassy-time = "0.5.0" +embassy-sync = "0.8.0" +embassy-time = "0.5.1" static_cell = "2" # Logging -defmt = "1.0.1" +defmt = "1.2.0" rtt-target = { version = "0.6.2", features = ["defmt"] } # LED (SK6812 on GPIO2 via RMT) -esp-hal-smartled2 = "0.28.1" +esp-hal-smartled = "0.18.0" smart-leds = "0.4.0" # Serial (bridge/rx roles) @@ -56,12 +56,12 @@ embedded-storage = "0.3" # Serialization postcard = { version = "1", features = ["experimental-derive"] } -heapless = "0.9.2" +heapless = "0.9.3" critical-section = "1.2.0" # Motor backends (turntable role) -mks-servo42-rs = { version = "1.0.3", optional = true } -sha2 = { version = "0.10.9", default-features = false } +mks-servo42-rs = { version = "1.0.4", optional = true } +sha2 = { version = "0.11.1", default-features = false } [profile.release] codegen-units = 1 diff --git a/software/firmware/src/bridge.rs b/software/firmware/src/bridge.rs index 9bd5f81..2cd6d34 100644 --- a/software/firmware/src/bridge.rs +++ b/software/firmware/src/bridge.rs @@ -15,15 +15,13 @@ use embassy_sync::{ use embassy_time::{Duration, Instant, Timer}; use embedded_io_async::{Read, Write}; use esp_hal::{ - usb_serial_jtag::{UsbSerialJtagRx, UsbSerialJtagTx}, Async, + usb::usb_serial_jtag::{UsbSerialJtagRx, UsbSerialJtagTx}, }; -use esp_radio::esp_now::{ - EspNowManager, EspNowReceiver, EspNowSender, BROADCAST_ADDRESS, -}; +use esp_radio::esp_now::{BROADCAST_ADDRESS, EspNowManager, EspNowReceiver, EspNowSender}; -use beambench_protocol::{self as proto, DeviceEvent, EspnowMessage, PcCommand, Role}; use beambench_protocol::bridge_logic; +use beambench_protocol::{self as proto, DeviceEvent, EspnowMessage, PcCommand, Role}; use crate::common::*; use crate::mk_static; @@ -102,9 +100,9 @@ impl PeerTable { pub async fn run( spawner: Spawner, - manager: &'static EspNowManager<'static>, - sender: &'static Mutex>, - receiver: EspNowReceiver<'static>, + manager: &'static EspNowManager, + sender: &'static Mutex, + receiver: EspNowReceiver, led_signal: &'static Signal, usb_rx: &'static mut UsbSerialJtagRx<'static, Async>, usb_tx: &'static mut UsbSerialJtagTx<'static, Async>, @@ -117,31 +115,22 @@ pub async fn run( // Channel for DeviceEvent responses to send over serial. let event_ch = mk_static!(Channel::, Channel::new()); - spawner - .spawn(bridge_discovery_task(manager, sender, peers, led_signal)) - .ok(); - spawner - .spawn(bridge_listener_task( + spawner.spawn(bridge_discovery_task(manager, sender, peers, led_signal).unwrap()); + spawner.spawn( + bridge_listener_task( manager, sender, receiver, peers, event_ch.sender(), led_signal, - )) - .ok(); - spawner - .spawn(bridge_serial_rx_task( - usb_rx, - sender, - peers, - event_ch.sender(), - led_signal, - )) - .ok(); - spawner - .spawn(bridge_serial_tx_task(usb_tx, event_ch.receiver())) - .ok(); + ) + .unwrap(), + ); + spawner.spawn( + bridge_serial_rx_task(usb_rx, sender, peers, event_ch.sender(), led_signal).unwrap(), + ); + spawner.spawn(bridge_serial_tx_task(usb_tx, event_ch.receiver()).unwrap()); info!("Bridge role ready, discovering peers..."); @@ -156,7 +145,7 @@ pub async fn run( #[embassy_executor::task] async fn bridge_serial_rx_task( usb_rx: &'static mut UsbSerialJtagRx<'static, Async>, - sender: &'static Mutex>, + sender: &'static Mutex, peers: &'static Mutex, event_tx: Sender<'static, NoopRawMutex, DeviceEvent, 8>, led_signal: &'static Signal, @@ -203,14 +192,17 @@ async fn bridge_serial_rx_task( /// Translates a PcCommand into ESP-NOW messages and sends to the appropriate peer. async fn handle_pc_command( cmd: PcCommand, - sender: &'static Mutex>, + sender: &'static Mutex, peers: &'static Mutex, event_tx: &Sender<'static, NoopRawMutex, DeviceEvent, 8>, led_signal: &'static Signal, ) { if matches!(cmd, PcCommand::OtaBegin { .. }) { OTA_IN_PROGRESS.store(true, core::sync::atomic::Ordering::Relaxed); - led_signal.signal(LedState::Blink { color: COLOR_RED, period_ms: 200 }); + led_signal.signal(LedState::Blink { + color: COLOR_RED, + period_ms: 200, + }); } match bridge_logic::route_command(&cmd) { bridge_logic::RouteAction::SendTo { role, msg } => { @@ -226,7 +218,7 @@ async fn handle_pc_command( /// Send an EspnowMessage to a peer by role. Sends an error event if the peer is not connected. async fn send_to_role( - sender: &'static Mutex>, + sender: &'static Mutex, peers: &'static Mutex, role: Role, msg: &EspnowMessage, @@ -242,7 +234,9 @@ async fn send_to_role( Role::Turntable => "Turntable", Role::Bridge => "Bridge", }); - event_tx.send(DeviceEvent::Error { description: desc }).await; + event_tx + .send(DeviceEvent::Error { description: desc }) + .await; return; }; @@ -279,8 +273,8 @@ async fn bridge_serial_tx_task( #[embassy_executor::task] async fn bridge_discovery_task( - manager: &'static EspNowManager<'static>, - sender: &'static Mutex>, + manager: &'static EspNowManager, + sender: &'static Mutex, peers: &'static Mutex, led_signal: &'static Signal, ) { @@ -298,7 +292,9 @@ async fn bridge_discovery_task( { let mut p = peers.lock().await; for role in [Role::Rx, Role::Tx, Role::Turntable] { - let stale = p.entry(role).map_or(false, |(_, t)| is_heartbeat_stale(Some(t))); + let stale = p + .entry(role) + .map_or(false, |(_, t)| is_heartbeat_stale(Some(t))); if stale { if let Some(mac) = p.peer_for_role(role) { info!( @@ -330,9 +326,9 @@ async fn bridge_discovery_task( #[embassy_executor::task] async fn bridge_listener_task( - manager: &'static EspNowManager<'static>, - sender: &'static Mutex>, - mut receiver: EspNowReceiver<'static>, + manager: &'static EspNowManager, + sender: &'static Mutex, + mut receiver: EspNowReceiver, peers: &'static Mutex, event_tx: Sender<'static, NoopRawMutex, DeviceEvent, 8>, led_signal: &'static Signal, @@ -352,7 +348,12 @@ async fn bridge_listener_task( info!( "Discovered {:?} at {:02x}:{:02x}:{:02x}:{:02x}:{:02x}:{:02x}", defmt::Debug2Format(&role), - src[0], src[1], src[2], src[3], src[4], src[5] + src[0], + src[1], + src[2], + src[3], + src[4], + src[5] ); ensure_peer(manager, &src); peers.lock().await.set_peer(role, src); @@ -390,7 +391,10 @@ async fn bridge_listener_task( } } // Restore LED after OTA completes or fails. - if matches!(espnow_msg, EspnowMessage::OtaComplete | EspnowMessage::OtaError { .. }) { + if matches!( + espnow_msg, + EspnowMessage::OtaComplete | EspnowMessage::OtaError { .. } + ) { OTA_IN_PROGRESS.store(false, core::sync::atomic::Ordering::Relaxed); let all = peers.lock().await.all_connected(); signal_pairing_led(led_signal, all); diff --git a/software/firmware/src/common.rs b/software/firmware/src/common.rs index 2354e47..303787b 100644 --- a/software/firmware/src/common.rs +++ b/software/firmware/src/common.rs @@ -1,8 +1,8 @@ //! Shared code for all firmware roles: LED control, ESP-NOW init, discovery helpers. -use embassy_futures::select::{select, Either}; +use embassy_futures::select::{Either, select}; use embassy_time::{Duration, Timer}; -use smart_leds::{SmartLedsWrite, RGB8}; +use smart_leds::{RGB8, SmartLedsWrite}; use core::sync::atomic::{AtomicBool, Ordering}; use embassy_sync::{blocking_mutex::raw::NoopRawMutex, signal::Signal}; @@ -91,7 +91,7 @@ pub fn ensure_peer(manager: &esp_radio::esp_now::EspNowManager, mac: &[u8; 6]) { if !manager.peer_exists(mac) { manager .add_peer(esp_radio::esp_now::PeerInfo { - interface: esp_radio::esp_now::EspNowWifiInterface::Sta, + interface: esp_radio::esp_now::EspNowWifiInterface::Station, peer_address: *mac, lmk: None, channel: None, @@ -103,10 +103,7 @@ pub fn ensure_peer(manager: &esp_radio::esp_now::EspNowManager, mac: &[u8; 6]) { /// Signal LED to reflect pairing state: solid green when paired, blinking blue otherwise. /// Skipped while OTA is in progress to avoid overriding the red blink. -pub fn signal_pairing_led( - led_signal: &Signal, - paired: bool, -) { +pub fn signal_pairing_led(led_signal: &Signal, paired: bool) { if OTA_IN_PROGRESS.load(Ordering::Relaxed) { return; } diff --git a/software/firmware/src/main.rs b/software/firmware/src/main.rs index 322cbaf..0150e93 100644 --- a/software/firmware/src/main.rs +++ b/software/firmware/src/main.rs @@ -23,22 +23,25 @@ use embassy_sync::{blocking_mutex::raw::NoopRawMutex, mutex::Mutex, signal::Sign use esp_alloc as _; use esp_backtrace as _; use esp_hal::{ + Async, clock::CpuClock, - interrupt::software::SoftwareInterruptControl, rmt::Rmt, time::Rate, timer::timg::TimerGroup, - usb_serial_jtag::{UsbSerialJtag, UsbSerialJtagRx, UsbSerialJtagTx}, - Async, + usb::usb_serial_jtag::{UsbSerialJtag, UsbSerialJtagRx, UsbSerialJtagTx}, }; -use esp_hal_smartled::{buffer_size, color_order, RmtSmartLeds, Sk68xxTiming}; +use esp_hal_smartled::{RmtSmartLeds, SK68XX_TIMING, buffer_size, color_order}; use esp_radio::esp_now::{EspNowManager, EspNowSender}; -use smart_leds::{SmartLedsWrite, RGB8}; +use smart_leds::{RGB8, SmartLedsWrite}; use beambench_protocol::Role; use common::*; -type Led = RmtSmartLeds<'static, { buffer_size::(1) }, esp_hal::Blocking, RGB8, color_order::Grb, Sk68xxTiming>; +/// RMT clock for the LED driver. +const RMT_FREQ: Rate = Rate::from_mhz(80); + +type Led = + RmtSmartLeds<'static, { buffer_size::(1) }, esp_hal::Blocking, RGB8, color_order::Grb>; #[defmt::panic_handler] fn defmt_panic() -> ! { @@ -71,23 +74,15 @@ async fn main(spawner: Spawner) -> ! { // ── RTOS + Embassy setup ───────────────────────────────────────────────── - let sw_int = SoftwareInterruptControl::new(peripherals.SW_INTERRUPT); let timg0 = TimerGroup::new(peripherals.TIMG0); - esp_rtos::start(timg0.timer0, sw_int.software_interrupt0); + esp_rtos::start(timg0.timer0, peripherals.FROM_CPU_INTR0); // ── ESP-NOW setup ──────────────────────────────────────────────────────── - let esp_radio_ctrl = - &*mk_static!(esp_radio::Controller<'static>, esp_radio::init().unwrap()); - - let (mut wifi_controller, interfaces) = - esp_radio::wifi::new(esp_radio_ctrl, peripherals.WIFI, Default::default()).unwrap(); - wifi_controller - .set_mode(esp_radio::wifi::WifiMode::Sta) - .unwrap(); - wifi_controller.start().unwrap(); - - let esp_now = interfaces.esp_now; + // Default config is station mode. ESP-NOW keeps Wi-Fi alive on its own. + let wifi_controller = + esp_radio::wifi::WifiController::new(peripherals.WIFI, Default::default()).unwrap(); + let esp_now = wifi_controller.esp_now(); esp_now.set_channel(DEFAULT_CHANNEL).unwrap(); info!( "ESP-NOW v{} on channel {}", @@ -100,27 +95,28 @@ async fn main(spawner: Spawner) -> ! { // ── LED setup (SK6812 on GPIO2 via RMT) ────────────────────────────────── - let rmt = Rmt::new(peripherals.RMT, Rate::from_mhz(80)).unwrap(); - let mut led = - RmtSmartLeds::<{ buffer_size::(1) }, _, RGB8, color_order::Grb, Sk68xxTiming>::new( - rmt.channel0, - peripherals.GPIO2, - ) - .unwrap(); + let rmt = Rmt::new(peripherals.RMT, RMT_FREQ).unwrap(); + let mut led = RmtSmartLeds::<{ buffer_size::(1) }, _, RGB8, color_order::Grb>::new( + SK68XX_TIMING, + rmt.channel0, + peripherals.GPIO2, + RMT_FREQ, + ) + .unwrap(); let _ = led.write(core::iter::once(COLOR_BLUE)); let led_signal = mk_static!(Signal, Signal::new()); let led = mk_static!(Led, led); - spawner.spawn(led_task(led, led_signal)).ok(); + spawner.spawn(led_task(led, led_signal).unwrap()); // ── ESP-NOW split ──────────────────────────────────────────────────────── let (manager, sender, receiver) = esp_now.split(); - let manager = mk_static!(EspNowManager<'static>, manager); + let manager = mk_static!(EspNowManager, manager); let sender = mk_static!( - Mutex::>, + Mutex::, Mutex::::new(sender) ); @@ -132,7 +128,10 @@ async fn main(spawner: Spawner) -> ! { let (usb_rx, usb_tx) = usb_serial.split(); let usb_rx = mk_static!(UsbSerialJtagRx<'static, Async>, usb_rx); let usb_tx = mk_static!(UsbSerialJtagTx<'static, Async>, usb_tx); - bridge::run(spawner, manager, sender, receiver, led_signal, usb_rx, usb_tx).await; + bridge::run( + spawner, manager, sender, receiver, led_signal, usb_rx, usb_tx, + ) + .await; } Role::Rx => { #[cfg(not(feature = "backend-uart"))] @@ -141,14 +140,12 @@ async fn main(spawner: Spawner) -> ! { } #[cfg(feature = "backend-uart")] { - let uart = esp_hal::uart::Uart::new( - peripherals.UART1, - esp_hal::uart::Config::default(), - ) - .unwrap() - .with_rx(peripherals.GPIO5) - .with_tx(peripherals.GPIO4) - .into_async(); + let uart = + esp_hal::uart::Uart::new(peripherals.UART1, esp_hal::uart::Config::default()) + .unwrap() + .with_rx(peripherals.GPIO5) + .with_tx(peripherals.GPIO4) + .into_async(); rx::run(spawner, manager, sender, receiver, led_signal, flash, uart).await; } } @@ -159,14 +156,12 @@ async fn main(spawner: Spawner) -> ! { } #[cfg(feature = "backend-uart")] { - let uart = esp_hal::uart::Uart::new( - peripherals.UART1, - esp_hal::uart::Config::default(), - ) - .unwrap() - .with_rx(peripherals.GPIO5) - .with_tx(peripherals.GPIO4) - .into_async(); + let uart = + esp_hal::uart::Uart::new(peripherals.UART1, esp_hal::uart::Config::default()) + .unwrap() + .with_rx(peripherals.GPIO5) + .with_tx(peripherals.GPIO4) + .into_async(); tx::run(spawner, manager, sender, receiver, led_signal, flash, uart).await; } } @@ -209,9 +204,14 @@ async fn main(spawner: Spawner) -> ! { } #[embassy_executor::task] -async fn led_task( - led: &'static mut Led, - led_signal: &'static Signal, -) { - run_led_loop(led, led_signal, LedState::Blink { color: COLOR_BLUE, period_ms: 500 }).await; +async fn led_task(led: &'static mut Led, led_signal: &'static Signal) { + run_led_loop( + led, + led_signal, + LedState::Blink { + color: COLOR_BLUE, + period_ms: 500, + }, + ) + .await; } diff --git a/software/firmware/src/measurement/espnow.rs b/software/firmware/src/measurement/espnow.rs index 826c79b..532006d 100644 --- a/software/firmware/src/measurement/espnow.rs +++ b/software/firmware/src/measurement/espnow.rs @@ -3,10 +3,12 @@ //! RX side: wraps `MeasurementState` from the protocol crate, which accumulates //! RSSI values extracted from received ESP-NOW beacon frames. //! -//! TX side: controls a transmit flag checked by a broadcast loop task. +//! TX side: wraps `TxState` from the protocol crate, which holds the transmit +//! flag and interval checked by a broadcast loop task. -use beambench_protocol::rx_logic::MeasurementState; use beambench_protocol::BackendInfo; +use beambench_protocol::rx_logic::MeasurementState; +use beambench_protocol::tx_logic::TxState; use embassy_time::Duration; use super::{MeasurementResult, RxBackend, TxBackend}; @@ -58,49 +60,43 @@ impl RxBackend for EspNowRxBackend { // ── TX ────────────────────────────────────────────────────────────────────── -const DEFAULT_TX_INTERVAL: Duration = Duration::from_millis(100); - /// ESP-NOW TX backend — broadcasts `MeasurementBeacon` frames at a configurable rate. /// /// The actual broadcast happens in a separate transmit loop task that polls /// `is_transmitting()` and `tx_interval()`. pub struct EspNowTxBackend { - transmitting: bool, - tx_interval: Duration, + state: TxState, } impl EspNowTxBackend { pub const fn new() -> Self { Self { - transmitting: false, - tx_interval: DEFAULT_TX_INTERVAL, + state: TxState::new(), } } /// Whether the transmit loop should be broadcasting. pub fn is_transmitting(&self) -> bool { - self.transmitting + self.state.transmitting } /// Current interval between beacon broadcasts. pub fn tx_interval(&self) -> Duration { - self.tx_interval + Duration::from_millis(self.state.tx_interval_ms) } /// Set the beacon broadcast rate. Called on `TxCommand::Configure`. pub fn set_packet_rate(&mut self, packet_rate_hz: u16) { - if packet_rate_hz > 0 { - self.tx_interval = Duration::from_millis(1000 / packet_rate_hz as u64); - } + self.state.set_packet_rate(packet_rate_hz); } } impl TxBackend for EspNowTxBackend { async fn start_transmit(&mut self) { - self.transmitting = true; + self.state.transmitting = true; } async fn stop_transmit(&mut self) { - self.transmitting = false; + self.state.transmitting = false; } } diff --git a/software/firmware/src/measurement/uart.rs b/software/firmware/src/measurement/uart.rs index bdebe3b..35e0bc4 100644 --- a/software/firmware/src/measurement/uart.rs +++ b/software/firmware/src/measurement/uart.rs @@ -11,8 +11,8 @@ use defmt::info; use embassy_time::Duration; -use esp_hal::uart::Uart; use esp_hal::Async; +use esp_hal::uart::Uart; use super::{MeasurementResult, RxBackend, TxBackend}; diff --git a/software/firmware/src/motor/servo42c.rs b/software/firmware/src/motor/servo42c.rs index f864a29..532fbf9 100644 --- a/software/firmware/src/motor/servo42c.rs +++ b/software/firmware/src/motor/servo42c.rs @@ -1,5 +1,5 @@ use embedded_io::Write; -use esp_hal::{delay::Delay, uart::Uart, Blocking}; +use esp_hal::{Blocking, delay::Delay, uart::Uart}; use mks_servo42_rs::{self, Driver, RotationDirection}; use super::{Motor, MotorError, Position}; @@ -31,7 +31,9 @@ impl<'a> Servo42cMotor<'a> { /// Write a command and read the response into `buf`. /// Returns the number of bytes read. fn transact(&mut self, cmd: &[u8], buf: &mut [u8]) -> Result { - self.uart.write_all(cmd).map_err(|_| MotorError::Communication)?; + self.uart + .write_all(cmd) + .map_err(|_| MotorError::Communication)?; self.uart.flush().map_err(|_| MotorError::Communication)?; // Give the motor time to respond. @@ -70,7 +72,10 @@ impl Motor for Servo42cMotor<'_> { } } } - defmt::warn!("Failed to {} motor", if enabled { "enable" } else { "disable" }); + defmt::warn!( + "Failed to {} motor", + if enabled { "enable" } else { "disable" } + ); } fn go_to(&mut self, target: Position) -> Result { @@ -89,7 +94,9 @@ impl Motor for Servo42cMotor<'_> { let pulses = delta.unsigned_abs(); let mut cmd_buf = [0u8; MAX_CMD_LEN]; - let cmd = self.driver.run_motor(direction, MOVE_SPEED, pulses) + let cmd = self + .driver + .run_motor(direction, MOVE_SPEED, pulses) .map_err(|_| MotorError::OutOfRange)?; let len = cmd.len(); cmd_buf[..len].copy_from_slice(cmd); diff --git a/software/firmware/src/ota_responder.rs b/software/firmware/src/ota_responder.rs index 72f2d51..0ad5a97 100644 --- a/software/firmware/src/ota_responder.rs +++ b/software/firmware/src/ota_responder.rs @@ -12,8 +12,8 @@ use sha2::{Digest, Sha256}; use beambench_protocol::{self as proto, EspnowMessage, OTA_CHUNK_SIZE}; use esp_bootloader_esp_idf::partitions; +use crate::common::{COLOR_GREEN, COLOR_RED, LedState, OTA_IN_PROGRESS, SharedFlash}; use core::sync::atomic::Ordering; -use crate::common::{SharedFlash, LedState, COLOR_RED, COLOR_GREEN, OTA_IN_PROGRESS}; const CHUNK_SIZE: u32 = OTA_CHUNK_SIZE as u32; @@ -72,9 +72,7 @@ pub async fn handle_ota_message( pub fn is_ota_message(msg: &EspnowMessage) -> bool { matches!( msg, - EspnowMessage::OtaBegin { .. } - | EspnowMessage::OtaData { .. } - | EspnowMessage::OtaFinish + EspnowMessage::OtaBegin { .. } | EspnowMessage::OtaData { .. } | EspnowMessage::OtaFinish ) } @@ -86,18 +84,24 @@ pub async fn process_and_respond( msg: &EspnowMessage, ota: &Mutex, flash: &SharedFlash, - sender: &Mutex>, + sender: &Mutex, bridge_mac: &[u8; 6], led_signal: &Signal, ) { // Start blinking red on OtaBegin. if matches!(msg, EspnowMessage::OtaBegin { .. }) { OTA_IN_PROGRESS.store(true, Ordering::Relaxed); - led_signal.signal(LedState::Blink { color: COLOR_RED, period_ms: 200 }); + led_signal.signal(LedState::Blink { + color: COLOR_RED, + period_ms: 200, + }); } if let Some(resp) = handle_ota_message(msg, ota, flash).await { - let is_done = matches!(resp, EspnowMessage::OtaComplete | EspnowMessage::OtaError { .. }); + let is_done = matches!( + resp, + EspnowMessage::OtaComplete | EspnowMessage::OtaError { .. } + ); send_ota_response(sender, bridge_mac, &resp).await; if matches!(resp, EspnowMessage::OtaComplete) { schedule_reboot().await; @@ -111,7 +115,7 @@ pub async fn process_and_respond( /// Send an OTA response back to the Bridge. async fn send_ota_response( - sender: &Mutex>, + sender: &Mutex, bridge_mac: &[u8; 6], msg: &EspnowMessage, ) { @@ -145,7 +149,10 @@ async fn handle_begin( let pt = match partitions::read_partition_table(&mut *f, &mut pt_buf) { Ok(pt) => pt, Err(e) => { - defmt::error!("Failed to read partition table: {:?}", defmt::Debug2Format(&e)); + defmt::error!( + "Failed to read partition table: {:?}", + defmt::Debug2Format(&e) + ); return Some(ota_error("partition table read failed")); } }; @@ -194,8 +201,7 @@ async fn handle_begin( info!( "Writing to OTA slot at offset 0x{:X} ({} bytes available)", - target_offset, - target_size + target_offset, target_size ); // Pre-erase the needed flash region. This is much faster than per-write @@ -243,7 +249,11 @@ async fn handle_data( let offset = seq as u32 * CHUNK_SIZE; if offset + data.len() as u32 > session.partition_size { - defmt::error!("OTA chunk out of bounds: offset {} + len {}", offset, data.len()); + defmt::error!( + "OTA chunk out of bounds: offset {} + len {}", + offset, + data.len() + ); return Some(ota_error("chunk out of bounds")); } @@ -255,7 +265,11 @@ async fn handle_data( // Write to flash (pre-erased in handle_begin, so use NorFlash::write directly). let mut f = flash.lock().await; if let Err(e) = NorFlash::write(&mut *f, flash_addr, data.as_slice()) { - defmt::error!("Flash write failed at 0x{:X}: {:?}", flash_addr, defmt::Debug2Format(&e)); + defmt::error!( + "Flash write failed at 0x{:X}: {:?}", + flash_addr, + defmt::Debug2Format(&e) + ); drop(f); state.session = None; return Some(ota_error("flash write failed")); @@ -299,16 +313,20 @@ async fn handle_finish( // Switch the OTA slot. let mut f = flash.lock().await; let mut pt_buf = [0u8; partitions::PARTITION_TABLE_MAX_LEN]; - let mut updater = match esp_bootloader_esp_idf::ota_updater::OtaUpdater::new(&mut *f, &mut pt_buf) { - Ok(u) => u, - Err(e) => { - defmt::error!("OtaUpdater init failed: {:?}", defmt::Debug2Format(&e)); - return Some(ota_error("ota updater init failed")); - } - }; + let mut updater = + match esp_bootloader_esp_idf::ota_updater::OtaUpdater::new(&mut *f, &mut pt_buf) { + Ok(u) => u, + Err(e) => { + defmt::error!("OtaUpdater init failed: {:?}", defmt::Debug2Format(&e)); + return Some(ota_error("ota updater init failed")); + } + }; if let Err(e) = updater.activate_next_partition() { - defmt::error!("Failed to activate partition: {:?}", defmt::Debug2Format(&e)); + defmt::error!( + "Failed to activate partition: {:?}", + defmt::Debug2Format(&e) + ); return Some(ota_error("partition activation failed")); } @@ -339,9 +357,9 @@ pub fn mark_current_valid(flash: &mut esp_storage::FlashStorage<'_>) { let updater = esp_bootloader_esp_idf::ota_updater::OtaUpdater::new(flash, &mut pt_buf); match updater { Ok(mut u) => { - if let Err(e) = u.set_current_ota_state( - esp_bootloader_esp_idf::ota::OtaImageState::Valid, - ) { + if let Err(e) = + u.set_current_ota_state(esp_bootloader_esp_idf::ota::OtaImageState::Valid) + { // Not fatal — might be first boot from factory partition. defmt::debug!( "Could not set OTA state to Valid: {:?}", diff --git a/software/firmware/src/role_provision.rs b/software/firmware/src/role_provision.rs index 437559a..5ac0e0e 100644 --- a/software/firmware/src/role_provision.rs +++ b/software/firmware/src/role_provision.rs @@ -6,7 +6,6 @@ use beambench_protocol::Role; use defmt::info; -use embedded_storage::{ReadStorage, Storage}; use esp_storage::FlashStorage; /// Magic bytes to distinguish a provisioned role from erased flash (0xFF). @@ -23,7 +22,6 @@ const ROLE_RECORD_SIZE: usize = 8; // 4 magic + 1 role + 3 padding /// - If a `role-*` cargo feature is active, write that role to flash and return it. /// - Otherwise, read the role from flash. pub fn resolve_role(storage: &mut FlashStorage<'_>) -> Role { - // Compile-time role from cargo feature (provisioning mode). let feature_role = feature_role(); @@ -82,7 +80,10 @@ fn write_role(storage: &mut FlashStorage<'_>, role: Role) { // Erase the sector before writing (flash can only clear bits, not set them). if let Err(e) = storage.write(ROLE_OFFSET, &buf) { - defmt::error!("Failed to write role to flash: {:?}", defmt::Debug2Format(&e)); + defmt::error!( + "Failed to write role to flash: {:?}", + defmt::Debug2Format(&e) + ); return; } info!("Role written to flash at 0x{:X}", ROLE_OFFSET); @@ -91,7 +92,10 @@ fn write_role(storage: &mut FlashStorage<'_>, role: Role) { fn read_role(storage: &mut FlashStorage<'_>) -> Option { let mut buf = [0u8; ROLE_RECORD_SIZE]; if let Err(e) = storage.read(ROLE_OFFSET, &mut buf) { - defmt::error!("Failed to read role from flash: {:?}", defmt::Debug2Format(&e)); + defmt::error!( + "Failed to read role from flash: {:?}", + defmt::Debug2Format(&e) + ); return None; } diff --git a/software/firmware/src/rx.rs b/software/firmware/src/rx.rs index 5f7c048..5344297 100644 --- a/software/firmware/src/rx.rs +++ b/software/firmware/src/rx.rs @@ -7,9 +7,7 @@ use defmt::info; use embassy_executor::Spawner; use embassy_sync::{blocking_mutex::raw::NoopRawMutex, mutex::Mutex, signal::Signal}; use embassy_time::{Duration, Instant, Timer}; -use esp_radio::esp_now::{ - EspNowManager, EspNowReceiver, EspNowSender, BROADCAST_ADDRESS, -}; +use esp_radio::esp_now::{BROADCAST_ADDRESS, EspNowManager, EspNowReceiver, EspNowSender}; use beambench_protocol::{self as proto, EspnowMessage, Role}; @@ -27,9 +25,9 @@ struct RxState { #[cfg(not(feature = "backend-uart"))] pub async fn run( spawner: Spawner, - manager: &'static EspNowManager<'static>, - sender: &'static Mutex>, - receiver: EspNowReceiver<'static>, + manager: &'static EspNowManager, + sender: &'static Mutex, + receiver: EspNowReceiver, led_signal: &'static Signal, flash: &'static SharedFlash, ) -> ! { @@ -48,9 +46,9 @@ pub async fn run( #[cfg(feature = "backend-uart")] pub async fn run( spawner: Spawner, - manager: &'static EspNowManager<'static>, - sender: &'static Mutex>, - receiver: EspNowReceiver<'static>, + manager: &'static EspNowManager, + sender: &'static Mutex, + receiver: EspNowReceiver, led_signal: &'static Signal, flash: &'static SharedFlash, uart: esp_hal::uart::Uart<'static, esp_hal::Async>, @@ -69,9 +67,9 @@ pub async fn run( async fn run_inner( spawner: Spawner, - manager: &'static EspNowManager<'static>, - sender: &'static Mutex>, - receiver: EspNowReceiver<'static>, + manager: &'static EspNowManager, + sender: &'static Mutex, + receiver: EspNowReceiver, led_signal: &'static Signal, flash: &'static SharedFlash, backend: ActiveRxBackend, @@ -90,8 +88,9 @@ async fn run_inner( Mutex::new(crate::ota_responder::OtaState::new()) ); - spawner.spawn(rx_discovery_task(sender, state, manager, led_signal)).ok(); - spawner.spawn(rx_listener_task(manager, sender, receiver, state, led_signal, flash, ota)).ok(); + spawner.spawn(rx_discovery_task(sender, state, manager, led_signal).unwrap()); + spawner + .spawn(rx_listener_task(manager, sender, receiver, state, led_signal, flash, ota).unwrap()); info!("RX role ready, discovering Bridge..."); @@ -102,9 +101,9 @@ async fn run_inner( #[embassy_executor::task] async fn rx_discovery_task( - sender: &'static Mutex>, + sender: &'static Mutex, state: &'static Mutex, - manager: &'static EspNowManager<'static>, + manager: &'static EspNowManager, led_signal: &'static Signal, ) { let mut buf = [0u8; proto::MAX_MSG_SIZE]; @@ -143,9 +142,9 @@ async fn rx_discovery_task( #[embassy_executor::task] async fn rx_listener_task( - manager: &'static EspNowManager<'static>, - sender: &'static Mutex>, - mut receiver: EspNowReceiver<'static>, + manager: &'static EspNowManager, + sender: &'static Mutex, + mut receiver: EspNowReceiver, state: &'static Mutex, led_signal: &'static Signal, flash: &'static SharedFlash, @@ -191,7 +190,10 @@ async fn rx_listener_task( s.last_bridge_seen = Some(Instant::now()); s.measurement.start().await; info!("Measurement started"); - led_signal.signal(LedState::Blink { color: COLOR_AMBER, period_ms: 200 }); + led_signal.signal(LedState::Blink { + color: COLOR_AMBER, + period_ms: 200, + }); } Ok(EspnowMessage::ReportMeasurement) => { let mut s = state.lock().await; @@ -201,7 +203,10 @@ async fn rx_listener_task( let paired = s.bridge_paired; drop(s); - info!("Measurement report: {} dBm ({} samples)", result.rssi_dbm, result.sample_count); + info!( + "Measurement report: {} dBm ({} samples)", + result.rssi_dbm, result.sample_count + ); led_signal.signal(LedState::Solid(COLOR_GREEN)); if paired { @@ -223,7 +228,15 @@ async fn rx_listener_task( } Ok(ref espnow_msg) if crate::ota_responder::is_ota_message(espnow_msg) => { let bridge_mac = state.lock().await.bridge_mac; - crate::ota_responder::process_and_respond(espnow_msg, ota, flash, sender, &bridge_mac, led_signal).await; + crate::ota_responder::process_and_respond( + espnow_msg, + ota, + flash, + sender, + &bridge_mac, + led_signal, + ) + .await; } _ => {} } diff --git a/software/firmware/src/turntable.rs b/software/firmware/src/turntable.rs index 36e42c4..0becfbe 100644 --- a/software/firmware/src/turntable.rs +++ b/software/firmware/src/turntable.rs @@ -34,9 +34,9 @@ enum MotorResult { pub async fn run( spawner: Spawner, motor: &'static Mutex>, - manager: &'static EspNowManager<'static>, - sender: &'static Mutex>, - receiver: EspNowReceiver<'static>, + manager: &'static EspNowManager, + sender: &'static Mutex, + receiver: EspNowReceiver, led_signal: &'static Signal, flash: &'static SharedFlash, ) -> ! { @@ -49,17 +49,12 @@ pub async fn run( Mutex::new(crate::ota_responder::OtaState::new()) ); - spawner - .spawn(turntable_discovery_task( - sender, - bridge_mac, - last_bridge_seen, - manager, - led_signal, - )) - .ok(); - spawner - .spawn(turntable_listener_task( + spawner.spawn( + turntable_discovery_task(sender, bridge_mac, last_bridge_seen, manager, led_signal) + .unwrap(), + ); + spawner.spawn( + turntable_listener_task( manager, sender, receiver, @@ -69,19 +64,11 @@ pub async fn run( flash, ota, led_signal, - )) - .ok(); - spawner - .spawn(turntable_responder_task(sender, bridge_mac, motor_result)) - .ok(); - spawner - .spawn(motor_task_step_dir( - motor, - motor_cmd, - motor_result, - led_signal, - )) - .ok(); + ) + .unwrap(), + ); + spawner.spawn(turntable_responder_task(sender, bridge_mac, motor_result).unwrap()); + spawner.spawn(motor_task_step_dir(motor, motor_cmd, motor_result, led_signal).unwrap()); info!("Turntable controller ready, discovering Bridge..."); @@ -92,10 +79,10 @@ pub async fn run( #[embassy_executor::task] async fn turntable_discovery_task( - sender: &'static Mutex>, + sender: &'static Mutex, bridge_mac: &'static Mutex>, last_bridge_seen: &'static Mutex>, - manager: &'static EspNowManager<'static>, + manager: &'static EspNowManager, led_signal: &'static Signal, ) { let mut buf = [0u8; proto::MAX_MSG_SIZE]; @@ -135,9 +122,9 @@ async fn turntable_discovery_task( #[embassy_executor::task] async fn turntable_listener_task( - manager: &'static EspNowManager<'static>, - sender: &'static Mutex>, - mut receiver: EspNowReceiver<'static>, + manager: &'static EspNowManager, + sender: &'static Mutex, + mut receiver: EspNowReceiver, bridge_mac: &'static Mutex>, last_bridge_seen: &'static Mutex>, motor_cmd: &'static Signal, @@ -204,7 +191,7 @@ async fn turntable_listener_task( #[embassy_executor::task] async fn turntable_responder_task( - sender: &'static Mutex>, + sender: &'static Mutex, bridge_mac: &'static Mutex>, result_signal: &'static Signal, ) { diff --git a/software/firmware/src/tx.rs b/software/firmware/src/tx.rs index 94e2687..19d7ff3 100644 --- a/software/firmware/src/tx.rs +++ b/software/firmware/src/tx.rs @@ -8,9 +8,7 @@ use defmt::info; use embassy_executor::Spawner; use embassy_sync::{blocking_mutex::raw::NoopRawMutex, mutex::Mutex, signal::Signal}; use embassy_time::{Duration, Instant, Timer}; -use esp_radio::esp_now::{ - EspNowManager, EspNowReceiver, EspNowSender, BROADCAST_ADDRESS, -}; +use esp_radio::esp_now::{BROADCAST_ADDRESS, EspNowManager, EspNowReceiver, EspNowSender}; use beambench_protocol::{self as proto, EspnowMessage, Role}; @@ -28,9 +26,9 @@ struct TxState { #[cfg(not(feature = "backend-uart"))] pub async fn run( spawner: Spawner, - manager: &'static EspNowManager<'static>, - sender: &'static Mutex>, - receiver: EspNowReceiver<'static>, + manager: &'static EspNowManager, + sender: &'static Mutex, + receiver: EspNowReceiver, led_signal: &'static Signal, flash: &'static SharedFlash, ) -> ! { @@ -49,9 +47,9 @@ pub async fn run( #[cfg(feature = "backend-uart")] pub async fn run( spawner: Spawner, - manager: &'static EspNowManager<'static>, - sender: &'static Mutex>, - receiver: EspNowReceiver<'static>, + manager: &'static EspNowManager, + sender: &'static Mutex, + receiver: EspNowReceiver, led_signal: &'static Signal, flash: &'static SharedFlash, uart: esp_hal::uart::Uart<'static, esp_hal::Async>, @@ -70,9 +68,9 @@ pub async fn run( async fn run_inner( spawner: Spawner, - manager: &'static EspNowManager<'static>, - sender: &'static Mutex>, - receiver: EspNowReceiver<'static>, + manager: &'static EspNowManager, + sender: &'static Mutex, + receiver: EspNowReceiver, led_signal: &'static Signal, flash: &'static SharedFlash, backend: ActiveTxBackend, @@ -91,12 +89,13 @@ async fn run_inner( Mutex::new(crate::ota_responder::OtaState::new()) ); - spawner.spawn(tx_discovery_task(manager, sender, state, led_signal)).ok(); - spawner.spawn(tx_listener_task(manager, sender, receiver, state, led_signal, flash, ota)).ok(); + spawner.spawn(tx_discovery_task(manager, sender, state, led_signal).unwrap()); + spawner + .spawn(tx_listener_task(manager, sender, receiver, state, led_signal, flash, ota).unwrap()); // ESP-NOW backend: spawn the beacon broadcast loop. #[cfg(not(feature = "backend-uart"))] - spawner.spawn(tx_transmit_task(sender, state)).ok(); + spawner.spawn(tx_transmit_task(sender, state).unwrap()); info!("TX role ready, broadcasting discovery beacons"); @@ -107,8 +106,8 @@ async fn run_inner( #[embassy_executor::task] async fn tx_discovery_task( - manager: &'static EspNowManager<'static>, - sender: &'static Mutex>, + manager: &'static EspNowManager, + sender: &'static Mutex, state: &'static Mutex, led_signal: &'static Signal, ) { @@ -149,9 +148,9 @@ async fn tx_discovery_task( #[embassy_executor::task] async fn tx_listener_task( - manager: &'static EspNowManager<'static>, - sender: &'static Mutex>, - mut receiver: EspNowReceiver<'static>, + manager: &'static EspNowManager, + sender: &'static Mutex, + mut receiver: EspNowReceiver, state: &'static Mutex, led_signal: &'static Signal, flash: &'static SharedFlash, @@ -208,7 +207,15 @@ async fn tx_listener_task( } Ok(ref espnow_msg) if crate::ota_responder::is_ota_message(espnow_msg) => { let bridge_mac = state.lock().await.bridge_mac; - crate::ota_responder::process_and_respond(espnow_msg, ota, flash, sender, &bridge_mac, led_signal).await; + crate::ota_responder::process_and_respond( + espnow_msg, + ota, + flash, + sender, + &bridge_mac, + led_signal, + ) + .await; } _ => {} } @@ -219,7 +226,7 @@ async fn tx_listener_task( #[cfg(not(feature = "backend-uart"))] #[embassy_executor::task] async fn tx_transmit_task( - sender: &'static Mutex>, + sender: &'static Mutex, state: &'static Mutex, ) { let mut buf = [0u8; proto::MAX_MSG_SIZE]; diff --git a/software/pc/Cargo.lock b/software/pc/Cargo.lock index 9c2072c..8f51705 100644 --- a/software/pc/Cargo.lock +++ b/software/pc/Cargo.lock @@ -145,13 +145,13 @@ dependencies = [ "axum", "beambench-protocol", "clap", - "heapless 0.9.2", + "heapless 0.9.3", "mime_guess", "postcard", "rust-embed", "serde", "serde_json", - "sha2", + "sha2 0.11.1", "tokio", "tokio-serial", "tower-http", @@ -164,7 +164,7 @@ dependencies = [ name = "beambench-protocol" version = "0.1.0" dependencies = [ - "heapless 0.9.2", + "heapless 0.9.3", "postcard", "serde", ] @@ -177,9 +177,9 @@ checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" [[package]] name = "bitflags" -version = "2.11.0" +version = "2.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "843867be96c8daad0d758b57df9392b6d8d271134fce549de6ce169ff98a92af" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" [[package]] name = "block-buffer" @@ -190,6 +190,15 @@ dependencies = [ "generic-array", ] +[[package]] +name = "block-buffer" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa" +dependencies = [ + "hybrid-array", +] + [[package]] name = "byteorder" version = "1.5.0" @@ -198,21 +207,21 @@ checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" [[package]] name = "bytes" -version = "1.11.1" +version = "1.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e748733b7cbc798e1434b6ac524f0c1ff2ab456fe201501e6497c8417a4fc33" +checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" [[package]] name = "cfg-if" -version = "1.0.4" +version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" [[package]] name = "cfg_aliases" -version = "0.2.1" +version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724" +checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527" [[package]] name = "clap" @@ -245,7 +254,7 @@ dependencies = [ "heck", "proc-macro2", "quote", - "syn", + "syn 2.0.119", ] [[package]] @@ -269,6 +278,12 @@ version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b05b61dc5112cbb17e4b6cd61790d9845d13888356391624cbe7e41efeac1e75" +[[package]] +name = "const-oid" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be95d4a884358a21a199689323c29e9256b4a1b315e22f183d155422041d3a9a" + [[package]] name = "core-foundation" version = "0.10.1" @@ -294,6 +309,15 @@ dependencies = [ "libc", ] +[[package]] +name = "cpufeatures" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566" +dependencies = [ + "libc", +] + [[package]] name = "critical-section" version = "1.2.0" @@ -310,6 +334,15 @@ dependencies = [ "typenum", ] +[[package]] +name = "crypto-common" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453" +dependencies = [ + "hybrid-array", +] + [[package]] name = "data-encoding" version = "2.10.0" @@ -322,8 +355,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.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" +dependencies = [ + "block-buffer 0.12.1", + "const-oid", + "crypto-common 0.2.2", ] [[package]] @@ -354,21 +398,6 @@ dependencies = [ "percent-encoding", ] -[[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-executor", - "futures-io", - "futures-sink", - "futures-task", - "futures-util", -] - [[package]] name = "futures-channel" version = "0.3.32" @@ -376,48 +405,19 @@ 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-executor" -version = "0.3.32" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "baf29c38818342a3b26b5b923639e7b1f4a61fc5e76102d4b1981c6dc7a7579d" -dependencies = [ - "futures-core", - "futures-task", - "futures-util", -] - -[[package]] -name = "futures-io" -version = "0.3.32" +version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cecba35d7ad927e23624b22ad55235f2239cfa44fd10428eecbeba6d6a717718" - -[[package]] -name = "futures-macro" -version = "0.3.32" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e835b70203e41293343137df5c0664546da5745f82ec9b84d40be8336958447b" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" [[package]] name = "futures-sink" -version = "0.3.32" +version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c39754e157331b013978ec91992bde1ac089843443c49cbc7f46150b0fad0893" +checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d" [[package]] name = "futures-task" @@ -431,13 +431,9 @@ version = "0.3.32" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "389ca41296e6190b48053de0321d02a77f32f8a5d2461dd38762c0593805c6d6" dependencies = [ - "futures-channel", "futures-core", - "futures-io", - "futures-macro", "futures-sink", "futures-task", - "memchr", "pin-project-lite", "slab", ] @@ -498,9 +494,9 @@ dependencies = [ [[package]] name = "heapless" -version = "0.9.2" +version = "0.9.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2af2455f757db2b292a9b1768c4b70186d443bcb3b316252d6b540aec1cd89ed" +checksum = "25ba4bd83f9415b58b4ed8dc5714c76e626a105be4646c02630ad730ad3b5aa4" dependencies = [ "hash32 0.3.1", "serde_core", @@ -564,6 +560,15 @@ version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" +[[package]] +name = "hybrid-array" +version = "0.4.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3944cf8cf766b40e2a1a333ee5e9b563f854d5fa49d6a8ca2764e97c6eddb214" +dependencies = [ + "typenum", +] + [[package]] name = "hyper" version = "1.8.1" @@ -630,9 +635,9 @@ checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe" [[package]] name = "libc" -version = "0.2.182" +version = "0.2.191" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6800badb6cb2082ffd7b6a67e6125bb39f18782f793520caee8cb8846be06112" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" [[package]] name = "lock_api" @@ -645,9 +650,9 @@ dependencies = [ [[package]] name = "log" -version = "0.4.29" +version = "0.4.35" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5e5032e24019045c762d3c0f28f5b6b8bbf38563a65908389bf7978758920897" +checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" [[package]] name = "mach2" @@ -697,9 +702,9 @@ dependencies = [ [[package]] name = "mio" -version = "1.1.1" +version = "1.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a69bcab0ad47271a0234d9422b131806bf3968021e5dc9328caf2d4cd58557fc" +checksum = "1788edb87fdc09c7e26304471e2f5be8cdefb1b6930d6e3985fc02ff53bf86ee" dependencies = [ "libc", "log", @@ -709,15 +714,15 @@ dependencies = [ [[package]] name = "mio-serial" -version = "5.0.6" +version = "5.0.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "029e1f407e261176a983a6599c084efd322d9301028055c87174beac71397ba3" +checksum = "6d4ba3f20276f21b7cad3f1b54c97489cf096a3894fd627cc6951cb3abdd4c60" dependencies = [ "log", "mio", - "nix 0.29.0", + "nix 0.31.3", "serialport", - "winapi", + "windows-sys 0.61.2", ] [[package]] @@ -750,11 +755,11 @@ dependencies = [ [[package]] name = "nix" -version = "0.29.0" +version = "0.31.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "71e2746dc3a24dd78b3cfcb7be93368c6de9963d30f43a6a73998a9cf4b17b46" +checksum = "cf20d2fde8ff38632c426f1165ed7436270b44f199fc55284c38276f9db47c3d" dependencies = [ - "bitflags 2.11.0", + "bitflags 2.13.2", "cfg-if", "cfg_aliases", "libc", @@ -844,18 +849,18 @@ dependencies = [ [[package]] name = "proc-macro2" -version = "1.0.106" +version = "1.0.107" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" dependencies = [ "unicode-ident", ] [[package]] name = "quote" -version = "1.0.44" +version = "1.0.47" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "21b2ebcf727b7760c461f091f9f0f539b77b8e87f2fd88131e7f1b433b3cece4" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" dependencies = [ "proc-macro2", ] @@ -901,7 +906,7 @@ version = "0.5.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" dependencies = [ - "bitflags 2.11.0", + "bitflags 2.13.2", ] [[package]] @@ -942,7 +947,7 @@ dependencies = [ "proc-macro2", "quote", "rust-embed-utils", - "syn", + "syn 2.0.119", "walkdir", ] @@ -952,7 +957,7 @@ version = "8.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5bcdef0be6fe7f6fa333b1073c949729274b05f123a0ad7efcb8efd878e5c3b1" dependencies = [ - "sha2", + "sha2 0.10.9", "walkdir", ] @@ -988,15 +993,15 @@ checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" [[package]] name = "semver" -version = "1.0.27" +version = "1.0.28" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d767eb0aabc880b29956c35734170f26ed551a859dbd361d140cdbeca61ab1e2" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" [[package]] name = "serde" -version = "1.0.228" +version = "1.0.229" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" dependencies = [ "serde_core", "serde_derive", @@ -1004,22 +1009,22 @@ dependencies = [ [[package]] name = "serde_core" -version = "1.0.228" +version = "1.0.229" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" dependencies = [ "serde_derive", ] [[package]] name = "serde_derive" -version = "1.0.228" +version = "1.0.229" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 3.0.10", ] [[package]] @@ -1060,11 +1065,11 @@ dependencies = [ [[package]] name = "serialport" -version = "4.7.3" +version = "4.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2acaf3f973e8616d7ceac415f53fc60e190b2a686fbcf8d27d0256c741c5007b" +checksum = "6ba5f8f29aa20853c4e3e85a33ec580eb66be1f057142e77a333834a318bacf2" dependencies = [ - "bitflags 2.11.0", + "bitflags 2.13.2", "cfg-if", "core-foundation", "core-foundation-sys", @@ -1073,7 +1078,7 @@ dependencies = [ "nix 0.26.4", "scopeguard", "unescaper", - "winapi", + "windows-sys 0.52.0", ] [[package]] @@ -1083,8 +1088,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]] @@ -1094,8 +1099,19 @@ 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]] +name = "sha2" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d7069beb7d6ac7b9acd1039986e73443f24234f41074da099d6f994ac9ad19" +dependencies = [ + "cfg-if", + "cpufeatures 0.3.1", + "digest 0.11.3", ] [[package]] @@ -1125,25 +1141,25 @@ checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" [[package]] name = "smallvec" -version = "1.15.1" +version = "1.16.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "67b1b7a3b5fe4f1376887184045fcf45c69e92af734b7aaddc05fb777b6fbd03" +checksum = "149309498a5f7334b12ddae0cad8aba81ce785fe91755068867e017cf98fee46" [[package]] name = "socket2" -version = "0.6.2" +version = "0.6.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "86f4aa3ad99f2088c990dfa82d367e19cb29268ed67c574d10d0a4bfe71f07e0" +checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" dependencies = [ "libc", - "windows-sys 0.60.2", + "windows-sys 0.61.2", ] [[package]] name = "spin" -version = "0.9.8" +version = "0.9.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6980e8d7511241f8acf4aebddbb1ff938df5eebe98691418c4468d0b72a96a67" +checksum = "3763264f6b73151db08c50ff20d7d8a0b8796e021cdea7ceedad07b80155fa0e" dependencies = [ "lock_api", ] @@ -1162,9 +1178,20 @@ checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" [[package]] name = "syn" -version = "2.0.117" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e665b8803e7b1d2a727f4023456bbbbe74da67099c585258af0ad9c5013b9b99" +checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" dependencies = [ "proc-macro2", "quote", @@ -1188,22 +1215,22 @@ dependencies = [ [[package]] name = "thiserror" -version = "2.0.18" +version = "2.0.21" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4288b5bcbc7920c07a1149a35cf9590a2aa808e0bc1eafaade0b80947865fbc4" +checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" dependencies = [ "thiserror-impl", ] [[package]] name = "thiserror-impl" -version = "2.0.18" +version = "2.0.21" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ebc4ee7f67670e9b64d05fa4253e753e016c6c95ff35b89b7941d6b856dec1d5" +checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 3.0.10", ] [[package]] @@ -1217,9 +1244,9 @@ dependencies = [ [[package]] name = "tokio" -version = "1.49.0" +version = "1.54.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "72a2903cd7736441aac9df9d7688bd0ce48edccaadf181c3b90be801e81d3d86" +checksum = "b52fd3255258d26fac7264ab5a76b53c13367136dc011d3d6ad4f8ed070396a3" dependencies = [ "bytes", "libc", @@ -1234,23 +1261,24 @@ dependencies = [ [[package]] name = "tokio-macros" -version = "2.6.0" +version = "2.7.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "af407857209536a95c8e56f8231ef2c2e2aff839b22e07a1ffcbc617e9db9fa5" +checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 3.0.10", ] [[package]] name = "tokio-serial" -version = "5.4.5" +version = "5.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aa1d5427f11ba7c5e6384521cfd76f2d64572ff29f3f4f7aa0f496282923fdc8" +checksum = "dd00f5f8b1e01c3e5afccd9e42ed80c2ad2df6d007877f29f8592c62e69cd116" dependencies = [ "cfg-if", - "futures", + "futures-core", + "futures-sink", "log", "mio-serial", "serialport", @@ -1300,11 +1328,11 @@ dependencies = [ [[package]] name = "tower-http" -version = "0.6.8" +version = "0.7.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d4e6559d53cc268e5031cd8429d05415bc4cb4aefc4aa5d6cc35fbf5b924a1f8" +checksum = "08a05a66a4fdd61cbbe0a1d755ffe0ca6aba159dd4820936a0ff8a8278245b9c" dependencies = [ - "bitflags 2.11.0", + "bitflags 2.13.2", "bytes", "futures-core", "futures-util", @@ -1321,7 +1349,6 @@ dependencies = [ "tokio-util", "tower-layer", "tower-service", - "tracing", ] [[package]] @@ -1356,7 +1383,7 @@ checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.119", ] [[package]] @@ -1416,7 +1443,7 @@ checksum = "38d90eea51bc7988ef9e674bf80a85ba6804739e535e9cab48e4bb34a8b652aa" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.119", "termcolor", ] @@ -1445,9 +1472,9 @@ checksum = "562d481066bde0658276a35467c4af00bdc6ee726305698a55b86e61d7ad82bb" [[package]] name = "unescaper" -version = "0.1.8" +version = "0.1.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4064ed685c487dbc25bd3f0e9548f2e34bab9d18cefc700f9ec2dba74ba1138e" +checksum = "7285e83a80ce76f5e7bce79fa41f68d78ba62d1003cf27bf748ab24413808cf4" dependencies = [ "thiserror", ] @@ -1460,9 +1487,9 @@ checksum = "dbc4bc3a9f746d862c45cb89d705aa10f187bb96c76001afab07a0d35ce60142" [[package]] name = "unicode-ident" -version = "1.0.24" +version = "1.0.27" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" [[package]] name = "utf-8" @@ -1513,22 +1540,6 @@ dependencies = [ "wit-bindgen", ] -[[package]] -name = "winapi" -version = "0.3.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" -dependencies = [ - "winapi-i686-pc-windows-gnu", - "winapi-x86_64-pc-windows-gnu", -] - -[[package]] -name = "winapi-i686-pc-windows-gnu" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" - [[package]] name = "winapi-util" version = "0.1.11" @@ -1538,12 +1549,6 @@ dependencies = [ "windows-sys 0.61.2", ] -[[package]] -name = "winapi-x86_64-pc-windows-gnu" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" - [[package]] name = "windows-link" version = "0.2.1" @@ -1552,9 +1557,9 @@ checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" [[package]] name = "windows-sys" -version = "0.60.2" +version = "0.52.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f2f500e4d28234f72040990ec9d39e3a6b950f9f22d3dba18416c35882612bcb" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" dependencies = [ "windows-targets", ] @@ -1570,11 +1575,10 @@ dependencies = [ [[package]] name = "windows-targets" -version = "0.53.5" +version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4945f9f551b88e0d65f3db0bc25c33b8acea4d9e41163edf90dcd0b19f9069f3" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" dependencies = [ - "windows-link", "windows_aarch64_gnullvm", "windows_aarch64_msvc", "windows_i686_gnu", @@ -1587,51 +1591,51 @@ dependencies = [ [[package]] name = "windows_aarch64_gnullvm" -version = "0.53.1" +version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a9d8416fa8b42f5c947f8482c43e7d89e73a173cead56d044f6a56104a6d1b53" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" [[package]] name = "windows_aarch64_msvc" -version = "0.53.1" +version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b9d782e804c2f632e395708e99a94275910eb9100b2114651e04744e9b125006" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" [[package]] name = "windows_i686_gnu" -version = "0.53.1" +version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "960e6da069d81e09becb0ca57a65220ddff016ff2d6af6a223cf372a506593a3" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" [[package]] name = "windows_i686_gnullvm" -version = "0.53.1" +version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fa7359d10048f68ab8b09fa71c3daccfb0e9b559aed648a8f95469c27057180c" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" [[package]] name = "windows_i686_msvc" -version = "0.53.1" +version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e7ac75179f18232fe9c285163565a57ef8d3c89254a30685b57d83a38d326c2" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" [[package]] name = "windows_x86_64_gnu" -version = "0.53.1" +version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9c3842cdd74a865a8066ab39c8a7a473c0778a3f29370b5fd6b4b9aa7df4a499" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" [[package]] name = "windows_x86_64_gnullvm" -version = "0.53.1" +version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0ffa179e2d07eee8ad8f57493436566c7cc30ac536a3379fdf008f47f6bb7ae1" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" [[package]] name = "windows_x86_64_msvc" -version = "0.53.1" +version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d6bbff5f0aada427a1e5a6da5f1f98158182f26556f345ac9e04d36d0ebed650" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" [[package]] name = "wit-bindgen" @@ -1656,7 +1660,7 @@ checksum = "f65c489a7071a749c849713807783f70672b28094011623e200cb86dcb835953" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.119", ] [[package]] diff --git a/software/pc/Cargo.toml b/software/pc/Cargo.toml index 7d86ba5..cb1c545 100644 --- a/software/pc/Cargo.toml +++ b/software/pc/Cargo.toml @@ -16,10 +16,10 @@ sim = [] # Web framework axum = { version = "0.8", features = ["ws", "multipart"] } tokio = { version = "1", features = ["full"] } -tower-http = { version = "0.6", features = ["cors", "fs"] } +tower-http = { version = "0.7.1", features = ["cors", "fs"] } # Serial communication -tokio-serial = "5.4" +tokio-serial = "5.5" # Shared protocol types beambench-protocol = { path = "../protocol" } @@ -43,10 +43,10 @@ clap = { version = "4", features = ["derive"] } mime_guess = "2" # Heapless strings (used by rx-sim for protocol Error messages) -heapless = "0.9.2" +heapless = "0.9.3" # SHA-256 for OTA firmware verification -sha2 = "0.10" +sha2 = "0.11.1" # Generate TypeScript bindings for WebSocket types (see `just gen-types`) ts-rs = "12" diff --git a/software/pc/src/sim.rs b/software/pc/src/sim.rs index 3b15448..54fe212 100644 --- a/software/pc/src/sim.rs +++ b/software/pc/src/sim.rs @@ -2,11 +2,75 @@ //! //! Speaks postcard+COBS using PcCommand/DeviceEvent, generates synthetic //! antenna patterns so you can test the full PC pipeline without hardware. - -use beambench_protocol::{DeviceEvent, PcCommand, MAX_MSG_SIZE}; +//! +//! Routing, response translation and the TX/RX state machines are the same +//! code the firmware runs (`bridge_logic`, `tx_logic`, `rx_logic`). Only the +//! radio link, the motor and the RSSI values are simulated. + +use beambench_protocol::bridge_logic::{self, RouteAction}; +use beambench_protocol::rx_logic::MeasurementState; +use beambench_protocol::tx_logic::TxState; +use beambench_protocol::{ + BackendInfo, DeviceEvent, EspnowMessage, PcCommand, Role, TurntableCommand, + TurntableResponse, MAX_MSG_SIZE, +}; use tokio::io::{AsyncReadExt, AsyncWriteExt}; use tokio::sync::mpsc; +/// Beacons the simulated RX receives per measurement window. +const BEACONS_PER_MEASUREMENT: u16 = 10; + +/// Simulated field devices behind the bridge. +struct FieldDevices { + tx: TxState, + rx: MeasurementState, + angle_deg: f32, +} + +impl FieldDevices { + fn new() -> Self { + Self { + tx: TxState::new(), + rx: MeasurementState::new(), + angle_deg: 0.0, + } + } + + /// Deliver a message to the device with the given role, as the bridge + /// does over ESP-NOW. Returns the device's response, if any. + async fn deliver(&mut self, role: Role, msg: &EspnowMessage) -> Option { + match role { + Role::Tx => self.tx.handle_message(msg), + Role::Rx => { + let resp = self.rx.handle_message(msg, 0); + // The RX only hears beacons while the TX is transmitting. + if matches!(msg, EspnowMessage::StartMeasurement) && self.tx.transmitting { + let rssi = synthetic_rssi(self.angle_deg); + for _ in 0..BEACONS_PER_MEASUREMENT { + self.rx + .handle_message(&EspnowMessage::MeasurementBeacon, rssi); + } + } + resp + } + Role::Turntable => match msg { + EspnowMessage::TurntableCmd(TurntableCommand::MoveTo { angle_deg }) => { + self.angle_deg = *angle_deg; + tokio::time::sleep(std::time::Duration::from_millis(10)).await; + Some(EspnowMessage::TurntableResp( + TurntableResponse::MoveComplete { + angle_deg: *angle_deg, + }, + )) + } + // Like the firmware: Stop halts the motor without a response. + _ => None, + }, + Role::Bridge => None, + } + } +} + /// Handle a single client connection: decode commands, respond with events. pub async fn handle_connection(stream: tokio::net::TcpStream) { let (reader, writer) = tokio::io::split(stream); @@ -16,101 +80,41 @@ pub async fn handle_connection(stream: tokio::net::TcpStream) { tokio::spawn(cobs_reader(reader, cmd_tx)); tokio::spawn(cobs_writer(writer, resp_rx)); - let mut transmitting = false; - let mut rssi_sum: f32 = 0.0; - let mut rssi_count: u16 = 0; - let mut current_angle: f32 = 0.0; - - loop { - let cmd = match cmd_rx.recv().await { - Some(cmd) => cmd, - None => return, + let mut devices = FieldDevices::new(); + + while let Some(cmd) = cmd_rx.recv().await { + let event = match bridge_logic::route_command(&cmd) { + // OTA is not simulated: no device answers those messages. + RouteAction::SendTo { role, msg } => devices + .deliver(role, &msg) + .await + .and_then(|resp| bridge_logic::translate_response(&resp)), + RouteAction::Local => Some(DeviceEvent::Status { + tx_connected: true, + rx_connected: true, + turntable_connected: true, + backend: BackendInfo { + name: heapless::String::try_from("sim").unwrap(), + frequency_mhz: Some(2400), + }, + }), }; - match cmd { - PcCommand::ConfigureTx { .. } => { - let _ = resp_tx.send(DeviceEvent::TxAck).await; - } - PcCommand::StartTransmitting => { - transmitting = true; - let _ = resp_tx.send(DeviceEvent::TxAck).await; - } - PcCommand::StopTransmitting => { - transmitting = false; - let _ = resp_tx.send(DeviceEvent::TxAck).await; - } - PcCommand::MoveTo { angle_deg } => { - // Simulate instant move. - current_angle = angle_deg; - tokio::time::sleep(std::time::Duration::from_millis(10)).await; - let _ = resp_tx - .send(DeviceEvent::MoveComplete { angle_deg }) - .await; - } - PcCommand::StopTurntable => { - let _ = resp_tx - .send(DeviceEvent::MoveComplete { - angle_deg: current_angle, - }) - .await; - } - PcCommand::ReturnHome => { - current_angle = 0.0; - let _ = resp_tx.send(DeviceEvent::HomeComplete).await; - } - PcCommand::StartMeasurement => { - rssi_sum = 0.0; - rssi_count = 0; - - // Simulate beacon reception: generate synthetic RSSI samples. - if transmitting { - let rssi = synthetic_rssi(current_angle); - let n = 10u16; - rssi_sum = rssi * n as f32; - rssi_count = n; - } - } - PcCommand::ReportMeasurement => { - let (rssi_dbm, sample_count) = if rssi_count > 0 { - (rssi_sum / rssi_count as f32, rssi_count) - } else { - (-100.0, 0) - }; - let _ = resp_tx - .send(DeviceEvent::Measurement { - rssi_dbm, - sample_count, - }) - .await; - } - PcCommand::QueryStatus => { - let _ = resp_tx - .send(DeviceEvent::Status { - tx_connected: true, - rx_connected: true, - turntable_connected: true, - backend: beambench_protocol::BackendInfo { - name: heapless::String::try_from("sim").unwrap(), - frequency_mhz: Some(2400), - }, - }) - .await; - } - // OTA not implemented in simulator. - PcCommand::OtaBegin { .. } | PcCommand::OtaData { .. } | PcCommand::OtaFinish { .. } => {} + if let Some(event) = event { + let _ = resp_tx.send(event).await; } } } -/// Synthetic RSSI: cardioid-like pattern peaked at 45°. -fn synthetic_rssi(angle_deg: f32) -> f32 { +/// Synthetic RSSI in whole dBm: cardioid-like pattern peaked at 45°. +fn synthetic_rssi(angle_deg: f32) -> i32 { let rad = (angle_deg - 45.0_f32).to_radians(); - -30.0 + 20.0 * rad.cos() + (-30.0 + 20.0 * rad.cos()).round() as i32 } /// Compute the expected synthetic RSSI for a given angle (matches synthetic_rssi). pub fn expected_rssi(angle_deg: f32) -> f32 { - synthetic_rssi(angle_deg) + synthetic_rssi(angle_deg) as f32 } /// Decode COBS-framed postcard messages from a reader into a channel. diff --git a/software/protocol/Cargo.lock b/software/protocol/Cargo.lock index cdd79aa..ab41e97 100644 --- a/software/protocol/Cargo.lock +++ b/software/protocol/Cargo.lock @@ -16,7 +16,7 @@ name = "beambench-protocol" version = "0.1.0" dependencies = [ "defmt", - "heapless 0.9.2", + "heapless 0.9.3", "postcard", "serde", ] @@ -50,9 +50,9 @@ checksum = "790eea4361631c5e7d22598ecd5723ff611904e3344ce8720784c93e3d83d40b" [[package]] name = "defmt" -version = "1.0.1" +version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "548d977b6da32fa1d1fda2876453da1e7df63ad0304c8b3dae4dbe7b96f39b78" +checksum = "e4a0795ac740cb54d7b3775c9c17345f6aaecf884c01733b39d6017738e0e3e1" dependencies = [ "bitflags", "defmt-macros", @@ -60,12 +60,11 @@ dependencies = [ [[package]] name = "defmt-macros" -version = "1.0.1" +version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3d4fc12a85bcf441cfe44344c4b72d58493178ce635338a3f3b78943aceb258e" +checksum = "840bb056bd99c495c9188198a258ab787c79f306d864db3e6e8451442d6d8366" dependencies = [ "defmt-parser", - "proc-macro-error2", "proc-macro2", "quote", "syn", @@ -73,9 +72,9 @@ dependencies = [ [[package]] name = "defmt-parser" -version = "1.0.0" +version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "10d60334b3b2e7c9d91ef8150abfb6fa4c1c39ebbcf4a81c2e346aad939fee3e" +checksum = "71958f69fb2de856c5dd51ac9377e986ca1aa5919f931bf5395a807277f889a0" dependencies = [ "thiserror", ] @@ -114,9 +113,9 @@ dependencies = [ [[package]] name = "heapless" -version = "0.9.2" +version = "0.9.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2af2455f757db2b292a9b1768c4b70186d443bcb3b316252d6b540aec1cd89ed" +checksum = "25ba4bd83f9415b58b4ed8dc5714c76e626a105be4646c02630ad730ad3b5aa4" dependencies = [ "defmt", "hash32 0.3.1", @@ -144,42 +143,20 @@ dependencies = [ "serde", ] -[[package]] -name = "proc-macro-error-attr2" -version = "2.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "96de42df36bb9bba5542fe9f1a054b8cc87e172759a1868aa05c1f3acc89dfc5" -dependencies = [ - "proc-macro2", - "quote", -] - -[[package]] -name = "proc-macro-error2" -version = "2.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "11ec05c52be0a07b08061f7dd003e7d7092e0472bc731b4af7bb1ef876109802" -dependencies = [ - "proc-macro-error-attr2", - "proc-macro2", - "quote", - "syn", -] - [[package]] name = "proc-macro2" -version = "1.0.106" +version = "1.0.107" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" dependencies = [ "unicode-ident", ] [[package]] name = "quote" -version = "1.0.44" +version = "1.0.47" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "21b2ebcf727b7760c461f091f9f0f539b77b8e87f2fd88131e7f1b433b3cece4" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" dependencies = [ "proc-macro2", ] @@ -201,15 +178,15 @@ checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" [[package]] name = "semver" -version = "1.0.27" +version = "1.0.28" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d767eb0aabc880b29956c35734170f26ed551a859dbd361d140cdbeca61ab1e2" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" [[package]] name = "serde" -version = "1.0.228" +version = "1.0.229" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" dependencies = [ "serde_core", "serde_derive", @@ -217,18 +194,18 @@ dependencies = [ [[package]] name = "serde_core" -version = "1.0.228" +version = "1.0.229" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" dependencies = [ "serde_derive", ] [[package]] name = "serde_derive" -version = "1.0.228" +version = "1.0.229" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" dependencies = [ "proc-macro2", "quote", @@ -237,9 +214,9 @@ dependencies = [ [[package]] name = "spin" -version = "0.9.8" +version = "0.9.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6980e8d7511241f8acf4aebddbb1ff938df5eebe98691418c4468d0b72a96a67" +checksum = "3763264f6b73151db08c50ff20d7d8a0b8796e021cdea7ceedad07b80155fa0e" dependencies = [ "lock_api", ] @@ -252,9 +229,9 @@ checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" [[package]] name = "syn" -version = "2.0.117" +version = "3.0.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e665b8803e7b1d2a727f4023456bbbbe74da67099c585258af0ad9c5013b9b99" +checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" dependencies = [ "proc-macro2", "quote", @@ -263,18 +240,18 @@ dependencies = [ [[package]] name = "thiserror" -version = "2.0.18" +version = "2.0.21" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4288b5bcbc7920c07a1149a35cf9590a2aa808e0bc1eafaade0b80947865fbc4" +checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" dependencies = [ "thiserror-impl", ] [[package]] name = "thiserror-impl" -version = "2.0.18" +version = "2.0.21" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ebc4ee7f67670e9b64d05fa4253e753e016c6c95ff35b89b7941d6b856dec1d5" +checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" dependencies = [ "proc-macro2", "quote", @@ -283,6 +260,6 @@ dependencies = [ [[package]] name = "unicode-ident" -version = "1.0.24" +version = "1.0.27" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" diff --git a/software/protocol/Cargo.toml b/software/protocol/Cargo.toml index 61a58f2..f13ac2e 100644 --- a/software/protocol/Cargo.toml +++ b/software/protocol/Cargo.toml @@ -11,5 +11,5 @@ defmt = ["dep:defmt", "heapless/defmt"] serde = { version = "1", default-features = false, features = ["derive"] } postcard = "1" # heapless provides fixed-capacity String/Vec for no_std contexts -heapless = { version = "0.9.2", features = ["serde"] } -defmt = { version = "1.0.1", optional = true } +heapless = { version = "0.9.3", features = ["serde"] } +defmt = { version = "1.2.0", optional = true } diff --git a/software/protocol/src/lib.rs b/software/protocol/src/lib.rs index c41e7d9..0b680e3 100644 --- a/software/protocol/src/lib.rs +++ b/software/protocol/src/lib.rs @@ -475,6 +475,20 @@ mod test { assert_eq!(&decoded, msg); } + /// Pins the wire format of one command, byte for byte. + #[test] + fn move_to_wire_bytes() { + let cmd = PcCommand::MoveTo { angle_deg: 90.0 }; + let mut buf = [0u8; MAX_MSG_SIZE]; + + // Variant index 3, then 90.0f32 little-endian. + let plain = super::serialize(&cmd, &mut buf).unwrap(); + assert_eq!(plain, [0x03, 0x00, 0x00, 0xB4, 0x42]); + + let len = super::serialize_cobs(&cmd, &mut buf).unwrap(); + assert_eq!(buf[..len], [0x02, 0x03, 0x01, 0x03, 0xB4, 0x42, 0x00]); + } + #[test] fn cobs_round_trip() { let mut buf = [0u8; MAX_MSG_SIZE]; diff --git a/software/protocol/src/tx_logic.rs b/software/protocol/src/tx_logic.rs index d3dd75d..cefad30 100644 --- a/software/protocol/src/tx_logic.rs +++ b/software/protocol/src/tx_logic.rs @@ -20,6 +20,13 @@ impl TxState { } } + /// Set the transmission rate. A rate of 0 Hz is ignored. + pub fn set_packet_rate(&mut self, packet_rate_hz: u16) { + if packet_rate_hz > 0 { + self.tx_interval_ms = 1000 / packet_rate_hz as u64; + } + } + /// Process an incoming ESP-NOW message. Returns a response if applicable. pub fn handle_message(&mut self, msg: &EspnowMessage) -> Option { match msg { @@ -27,9 +34,7 @@ impl TxState { TxCommand::Configure { packet_rate_hz, .. } => { - if *packet_rate_hz > 0 { - self.tx_interval_ms = 1000 / *packet_rate_hz as u64; - } + self.set_packet_rate(*packet_rate_hz); Some(EspnowMessage::TxResp(TxResponse::Ack)) } TxCommand::StartTransmit => { From 7a57a075506dd6de614b393bbf4d33a04abad950 Mon Sep 17 00:00:00 2001 From: JuliDi Date: Fri, 13 Nov 2026 15:05:06 +0100 Subject: [PATCH 02/16] feat: Add protocol version header to all frames Every frame starts with PROTOCOL_VERSION. Receivers do not decode frames from another version and report them instead: the bridge in Status.mismatched_peers, the PC as an error. Golden-bytes tests pin the wire layout of every message variant. --- software/firmware/Cargo.lock | 1 + software/firmware/src/bridge.rs | 48 ++++- software/firmware/src/rx.rs | 7 + software/firmware/src/turntable.rs | 7 + software/firmware/src/tx.rs | 7 + software/pc/Cargo.lock | 1 + software/pc/src/main.rs | 37 +++- software/pc/src/serial.rs | 37 +++- software/pc/src/sim.rs | 4 +- software/protocol/Cargo.lock | 1 + software/protocol/Cargo.toml | 1 + software/protocol/src/golden.rs | 332 +++++++++++++++++++++++++++++ software/protocol/src/lib.rs | 101 +++++++-- 13 files changed, 561 insertions(+), 23 deletions(-) create mode 100644 software/protocol/src/golden.rs diff --git a/software/firmware/Cargo.lock b/software/firmware/Cargo.lock index 1a8679b..ae0d443 100644 --- a/software/firmware/Cargo.lock +++ b/software/firmware/Cargo.lock @@ -82,6 +82,7 @@ dependencies = [ name = "beambench-protocol" version = "0.1.0" dependencies = [ + "cobs", "defmt 1.2.0", "heapless 0.9.3", "postcard", diff --git a/software/firmware/src/bridge.rs b/software/firmware/src/bridge.rs index 2cd6d34..8ba66d6 100644 --- a/software/firmware/src/bridge.rs +++ b/software/firmware/src/bridge.rs @@ -21,7 +21,9 @@ use esp_hal::{ use esp_radio::esp_now::{BROADCAST_ADDRESS, EspNowManager, EspNowReceiver, EspNowSender}; use beambench_protocol::bridge_logic; -use beambench_protocol::{self as proto, DeviceEvent, EspnowMessage, PcCommand, Role}; +use beambench_protocol::{ + self as proto, DecodeError, DeviceEvent, EspnowMessage, PcCommand, PeerMismatch, Role, +}; use crate::common::*; use crate::mk_static; @@ -32,6 +34,8 @@ struct PeerTable { rx: Option<([u8; 6], Instant)>, tx: Option<([u8; 6], Instant)>, turntable: Option<([u8; 6], Instant)>, + /// Boards whose frames were dropped because of another protocol version. + mismatches: heapless::Vec, } impl PeerTable { @@ -40,9 +44,31 @@ impl PeerTable { rx: None, tx: None, turntable: None, + mismatches: heapless::Vec::new(), + } + } + + /// Remember a board that speaks another protocol version. + /// Further boards are ignored once the list is full. + fn record_mismatch(&mut self, mac: [u8; 6], protocol: u16) { + match self.mismatches.iter_mut().find(|m| m.mac == mac) { + Some(m) => m.protocol = protocol, + None => { + if self.mismatches.push(PeerMismatch { mac, protocol }).is_ok() { + info!( + "Peer {:02x}:{:02x}:{:02x}:{:02x}:{:02x}:{:02x} speaks protocol v{}", + mac[0], mac[1], mac[2], mac[3], mac[4], mac[5], protocol + ); + } + } } } + /// Forget a mismatch once the board sends a valid frame, e.g. after reflashing. + fn clear_mismatch(&mut self, mac: &[u8; 6]) { + self.mismatches.retain(|m| m.mac != *mac); + } + fn entry(&self, role: Role) -> &Option<([u8; 6], Instant)> { match role { Role::Rx => &self.rx, @@ -94,6 +120,7 @@ impl PeerTable { rx_connected: self.rx.is_some(), turntable_connected: self.turntable.is_some(), backend: crate::measurement::active_backend_info(), + mismatched_peers: self.mismatches.clone(), } } } @@ -170,11 +197,21 @@ async fn bridge_serial_rx_task( let len = accum.len(); frame_buf[..len].copy_from_slice(&accum); frame_buf[len] = 0x00; - match postcard::from_bytes_cobs::(&mut frame_buf[..len + 1]) { + match proto::deserialize_cobs::(&mut frame_buf[..len + 1]) { Ok(cmd) => { info!("PC cmd: {:?}", defmt::Debug2Format(&cmd)); handle_pc_command(cmd, sender, peers, &event_tx, led_signal).await; } + Err(DecodeError::VersionMismatch { protocol }) => { + // The PC only reads the version header of this reply. + info!("PC speaks protocol v{}, dropping command", protocol); + event_tx + .send(DeviceEvent::Error { + description: heapless::String::try_from("Protocol mismatch") + .unwrap(), + }) + .await; + } Err(_) => { info!("Failed to decode PcCommand ({} bytes)", len); } @@ -339,6 +376,13 @@ async fn bridge_listener_task( let src = received.info.src_address; let msg: Result = proto::deserialize(data); + match msg { + Ok(_) => peers.lock().await.clear_mismatch(&src), + Err(DecodeError::VersionMismatch { protocol }) => { + peers.lock().await.record_mismatch(src, protocol); + } + Err(_) => {} + } match msg { Ok(EspnowMessage::Hello(hello)) if hello.role != Role::Bridge => { let role = hello.role; diff --git a/software/firmware/src/rx.rs b/software/firmware/src/rx.rs index 5344297..0f6089b 100644 --- a/software/firmware/src/rx.rs +++ b/software/firmware/src/rx.rs @@ -238,6 +238,13 @@ async fn rx_listener_task( ) .await; } + Err(proto::DecodeError::VersionMismatch { protocol }) => { + info!( + "Dropped frame with protocol v{}, expected v{}", + protocol, + proto::PROTOCOL_VERSION + ); + } _ => {} } } diff --git a/software/firmware/src/turntable.rs b/software/firmware/src/turntable.rs index 0becfbe..ca1d6a0 100644 --- a/software/firmware/src/turntable.rs +++ b/software/firmware/src/turntable.rs @@ -184,6 +184,13 @@ async fn turntable_listener_task( .await; } } + Err(proto::DecodeError::VersionMismatch { protocol }) => { + info!( + "Dropped frame with protocol v{}, expected v{}", + protocol, + proto::PROTOCOL_VERSION + ); + } _ => {} } } diff --git a/software/firmware/src/tx.rs b/software/firmware/src/tx.rs index 19d7ff3..c8e3674 100644 --- a/software/firmware/src/tx.rs +++ b/software/firmware/src/tx.rs @@ -217,6 +217,13 @@ async fn tx_listener_task( ) .await; } + Err(proto::DecodeError::VersionMismatch { protocol }) => { + info!( + "Dropped frame with protocol v{}, expected v{}", + protocol, + proto::PROTOCOL_VERSION + ); + } _ => {} } } diff --git a/software/pc/Cargo.lock b/software/pc/Cargo.lock index 8f51705..1beb06c 100644 --- a/software/pc/Cargo.lock +++ b/software/pc/Cargo.lock @@ -164,6 +164,7 @@ dependencies = [ name = "beambench-protocol" version = "0.1.0" dependencies = [ + "cobs", "heapless 0.9.3", "postcard", "serde", diff --git a/software/pc/src/main.rs b/software/pc/src/main.rs index 612ff69..658d3cd 100644 --- a/software/pc/src/main.rs +++ b/software/pc/src/main.rs @@ -71,6 +71,8 @@ struct AppState { turntable_connected: AtomicBool, backend_name: Mutex, backend_freq_mhz: Mutex>, + /// Boards with another protocol version, as last reported by the bridge. + mismatched_peers: Mutex>, /// Tracked turntable angle in centi-degrees (×100) for atomic access. turntable_angle_cdeg: AtomicI32, /// Whether a jog move is in progress. @@ -230,6 +232,7 @@ async fn main() { turntable_connected: AtomicBool::new(false), backend_name: Mutex::new(String::new()), backend_freq_mhz: Mutex::new(None), + mismatched_peers: Mutex::new(Vec::new()), turntable_angle_cdeg: AtomicI32::new(0), jogging: AtomicBool::new(false), ota_in_progress: AtomicBool::new(false), @@ -465,7 +468,7 @@ async fn handle_command(cmd: WsCommand, state: &Arc) { .await; match result { - Ok(Some(beambench_protocol::DeviceEvent::Status { tx_connected, rx_connected, turntable_connected, backend })) => { + Ok(Some(beambench_protocol::DeviceEvent::Status { tx_connected, rx_connected, turntable_connected, backend, mismatched_peers })) => { tracing::info!("Device verified as Bridge"); let _ = state2.ws_tx.send(WsEvent::Log { message: format!("{} confirmed as Bridge (TX: {}, RX: {}, Turntable: {})", @@ -476,8 +479,15 @@ async fn handle_command(cmd: WsCommand, state: &Arc) { }); update_peer_status(&state2, tx_connected, rx_connected, turntable_connected); update_backend_info(&state2, &backend).await; + update_mismatched_peers(&state2, &mismatched_peers).await; state2.broadcast_status().await; } + Ok(Some(beambench_protocol::DeviceEvent::Error { description })) => { + state2.broadcast_error( + &format!("{}: {}", port_name, description), + &description, + ); + } Ok(Some(other)) => { tracing::info!("Unexpected response from device: {:?}", other); let _ = state2.ws_tx.send(WsEvent::Log { @@ -813,6 +823,24 @@ async fn update_backend_info(state: &AppState, backend: &beambench_protocol::Bac *state.backend_freq_mhz.lock().await = backend.frequency_mhz; } +/// Report boards with another protocol version, once per change. +async fn update_mismatched_peers(state: &AppState, peers: &[beambench_protocol::PeerMismatch]) { + let mut known = state.mismatched_peers.lock().await; + if known.as_slice() == peers { + return; + } + *known = peers.to_vec(); + for p in peers { + let mac = p.mac.map(|b| format!("{b:02x}")).join(":"); + let msg = format!( + "Board {mac} speaks protocol v{}, PC v{}. Reflash it.", + p.protocol, + beambench_protocol::PROTOCOL_VERSION + ); + state.broadcast_error(&msg, &msg); + } +} + /// Periodically poll the bridge for device connection status. /// /// Stops when the poll generation changes (new connect or disconnect). @@ -855,8 +883,8 @@ async fn status_poll_loop( let mut rx = serial_rx.lock().await; loop { match rx.recv().await { - Some(beambench_protocol::DeviceEvent::Status { tx_connected, rx_connected, turntable_connected, backend }) => { - return Some((tx_connected, rx_connected, turntable_connected, backend)); + Some(beambench_protocol::DeviceEvent::Status { tx_connected, rx_connected, turntable_connected, backend, mismatched_peers }) => { + return Some((tx_connected, rx_connected, turntable_connected, backend, mismatched_peers)); } Some(_) => continue, None => return None, @@ -866,9 +894,10 @@ async fn status_poll_loop( .await; match result { - Ok(Some((tx, rx, turntable, backend))) => { + Ok(Some((tx, rx, turntable, backend, mismatched_peers))) => { update_peer_status(state, tx, rx, turntable); update_backend_info(state, &backend).await; + update_mismatched_peers(state, &mismatched_peers).await; state.broadcast_status().await; } Ok(None) => { diff --git a/software/pc/src/serial.rs b/software/pc/src/serial.rs index 627592f..a6803df 100644 --- a/software/pc/src/serial.rs +++ b/software/pc/src/serial.rs @@ -2,7 +2,7 @@ use std::sync::Arc; -use beambench_protocol::{DeviceEvent, PcCommand}; +use beambench_protocol::{DecodeError, DeviceEvent, PcCommand, PROTOCOL_VERSION}; use tokio::io::{AsyncReadExt, AsyncWriteExt}; use tokio::sync::{Mutex, mpsc}; use tokio_serial::SerialPortBuilderExt; @@ -138,12 +138,19 @@ async fn reader_task( while let Some(zero_pos) = accum.iter().position(|&b| b == 0) { let frame = &accum[..zero_pos + 1]; if frame.len() > 1 { - match postcard::from_bytes_cobs(&mut frame.to_vec()) { + match beambench_protocol::deserialize_cobs(&mut frame.to_vec()) { Ok(msg) => { if responses.send(msg).await.is_err() { return; } } + Err(DecodeError::VersionMismatch { protocol }) => { + let msg = mismatch_error(protocol); + warn!("{:?}", msg); + if responses.send(msg).await.is_err() { + return; + } + } Err(e) => { warn!("Failed to decode COBS frame: {:?}", e); } @@ -166,6 +173,16 @@ async fn reader_task( } } +/// Error event for a frame from a bridge with another protocol version. +fn mismatch_error(protocol: u16) -> DeviceEvent { + let text = format!( + "Protocol mismatch: bridge speaks v{protocol}, PC v{PROTOCOL_VERSION}. Reflash the bridge." + ); + DeviceEvent::Error { + description: heapless::String::try_from(text.as_str()).unwrap_or_default(), + } +} + /// Default address for the bridge-sim simulator. const SIM_ADDR: &str = "127.0.0.1:9876"; @@ -253,6 +270,22 @@ mod tests { assert_eq!(decoded, msg); } + #[tokio::test] + async fn reader_reports_version_mismatch() { + // COBS frame with version 2 and a payload this PC cannot parse. + let frame = [0x03, 0x02, 0xFF, 0x00]; + + let (resp_tx, mut resp_rx) = mpsc::channel::(16); + let (_cancel_tx, cancel_rx) = tokio::sync::watch::channel(false); + let (mut writer, reader) = tokio::io::duplex(1024); + tokio::spawn(reader_task(reader, resp_tx, cancel_rx)); + + writer.write_all(&frame).await.unwrap(); + drop(writer); + + assert_eq!(resp_rx.recv().await, Some(mismatch_error(2))); + } + #[tokio::test] async fn reader_handles_fragmented_frames() { let msg = DeviceEvent::Measurement { diff --git a/software/pc/src/sim.rs b/software/pc/src/sim.rs index 54fe212..7f24078 100644 --- a/software/pc/src/sim.rs +++ b/software/pc/src/sim.rs @@ -97,6 +97,7 @@ pub async fn handle_connection(stream: tokio::net::TcpStream) { name: heapless::String::try_from("sim").unwrap(), frequency_mhz: Some(2400), }, + mismatched_peers: heapless::Vec::new(), }), }; @@ -130,7 +131,8 @@ pub async fn cobs_reader(mut reader: impl AsyncReadExt + Unpin, tx: mpsc::Sender while let Some(zero_pos) = accum.iter().position(|&b| b == 0) { let frame = &accum[..zero_pos + 1]; if frame.len() > 1 { - match postcard::from_bytes_cobs::(&mut frame.to_vec()) { + match beambench_protocol::deserialize_cobs::(&mut frame.to_vec()) + { Ok(msg) => { if tx.send(msg).await.is_err() { return; diff --git a/software/protocol/Cargo.lock b/software/protocol/Cargo.lock index ab41e97..9f075e3 100644 --- a/software/protocol/Cargo.lock +++ b/software/protocol/Cargo.lock @@ -15,6 +15,7 @@ dependencies = [ name = "beambench-protocol" version = "0.1.0" dependencies = [ + "cobs", "defmt", "heapless 0.9.3", "postcard", diff --git a/software/protocol/Cargo.toml b/software/protocol/Cargo.toml index f13ac2e..93da21e 100644 --- a/software/protocol/Cargo.toml +++ b/software/protocol/Cargo.toml @@ -10,6 +10,7 @@ defmt = ["dep:defmt", "heapless/defmt"] [dependencies] serde = { version = "1", default-features = false, features = ["derive"] } postcard = "1" +cobs = { version = "0.3.0", default-features = false } # heapless provides fixed-capacity String/Vec for no_std contexts heapless = { version = "0.9.3", features = ["serde"] } defmt = { version = "1.2.0", optional = true } diff --git a/software/protocol/src/golden.rs b/software/protocol/src/golden.rs new file mode 100644 index 0000000..c264309 --- /dev/null +++ b/software/protocol/src/golden.rs @@ -0,0 +1,332 @@ +//! Golden wire bytes for every message variant. +//! +//! If a test here fails, the wire layout changed. Bump `PROTOCOL_VERSION` and +//! replace the table with the one printed by the failing test. +//! A new variant fails to compile in the `match` of its `samples` function. + +extern crate std; + +use std::{format, string::String, vec::Vec}; + +use serde::Serialize; + +use crate::*; + +/// Protocol version the tables below belong to. +const GOLDEN_VERSION: u16 = 1; + +fn hex(msg: &T) -> String { + let mut buf = [0u8; MAX_MSG_SIZE]; + let bytes = serialize(msg, &mut buf).unwrap(); + let parts: Vec = bytes.iter().map(|b| format!("{b:02x}")).collect(); + parts.join(" ") +} + +fn check(samples: &[(&str, T)], golden: &[(&str, &str)]) { + let actual: Vec<(&str, String)> = samples.iter().map(|(n, m)| (*n, hex(m))).collect(); + let expected: Vec<(&str, String)> = + golden.iter().map(|(n, h)| (*n, String::from(*h))).collect(); + if actual != expected { + let table: Vec = actual + .iter() + .map(|(n, h)| format!(" (\"{n}\", \"{h}\"),")) + .collect(); + panic!( + "Wire layout changed. Bump PROTOCOL_VERSION and GOLDEN_VERSION, then use:\n{}", + table.join("\n") + ); + } +} + +fn s(text: &str) -> heapless::String { + heapless::String::try_from(text).unwrap() +} + +fn v(bytes: &[u8]) -> heapless::Vec { + heapless::Vec::from_slice(bytes).unwrap() +} + +#[test] +fn golden_version_matches() { + assert_eq!( + PROTOCOL_VERSION, GOLDEN_VERSION, + "Regenerate the golden tables for the new protocol version" + ); +} + +// ── PcCommand ─────────────────────────────────────────────────────────────── + +fn pc_command_samples() -> Vec<(&'static str, PcCommand)> { + let all = [ + PcCommand::ConfigureTx { + channel: 6, + tx_power_dbm: -3, + packet_rate_hz: 100, + }, + PcCommand::StartTransmitting, + PcCommand::StopTransmitting, + PcCommand::MoveTo { angle_deg: 90.0 }, + PcCommand::StopTurntable, + PcCommand::ReturnHome, + PcCommand::StartMeasurement, + PcCommand::ReportMeasurement, + PcCommand::QueryStatus, + PcCommand::OtaBegin { + target: Role::Tx, + total_size: 1000, + sha256: [0xAB; 32], + ack_interval: 4, + }, + PcCommand::OtaData { + target: Role::Rx, + seq: 300, + data: v(&[1, 2]), + }, + PcCommand::OtaFinish { + target: Role::Turntable, + }, + ]; + all.into_iter() + .map(|m| { + let name = match m { + PcCommand::ConfigureTx { .. } => "ConfigureTx", + PcCommand::StartTransmitting => "StartTransmitting", + PcCommand::StopTransmitting => "StopTransmitting", + PcCommand::MoveTo { .. } => "MoveTo", + PcCommand::StopTurntable => "StopTurntable", + PcCommand::ReturnHome => "ReturnHome", + PcCommand::StartMeasurement => "StartMeasurement", + PcCommand::ReportMeasurement => "ReportMeasurement", + PcCommand::QueryStatus => "QueryStatus", + PcCommand::OtaBegin { .. } => "OtaBegin", + PcCommand::OtaData { .. } => "OtaData", + PcCommand::OtaFinish { .. } => "OtaFinish", + }; + (name, m) + }) + .collect() +} + +const PC_COMMAND_V1: &[(&str, &str)] = &[ + ("ConfigureTx", "01 00 06 fd 64"), + ("StartTransmitting", "01 01"), + ("StopTransmitting", "01 02"), + ("MoveTo", "01 03 00 00 b4 42"), + ("StopTurntable", "01 04"), + ("ReturnHome", "01 05"), + ("StartMeasurement", "01 06"), + ("ReportMeasurement", "01 07"), + ("QueryStatus", "01 08"), + ("OtaBegin", "01 09 01 e8 07 ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab 04"), + ("OtaData", "01 0a 00 ac 02 02 01 02"), + ("OtaFinish", "01 0b 02"), +]; + +#[test] +fn pc_command_wire_layout() { + check(&pc_command_samples(), PC_COMMAND_V1); +} + +// ── DeviceEvent ───────────────────────────────────────────────────────────── + +fn device_event_samples() -> Vec<(&'static str, DeviceEvent)> { + let all = [ + DeviceEvent::TxAck, + DeviceEvent::MoveComplete { angle_deg: 90.0 }, + DeviceEvent::TurntableError { + description: s("stall"), + }, + DeviceEvent::HomeComplete, + DeviceEvent::Measurement { + rssi_dbm: -42.5, + sample_count: 10, + }, + DeviceEvent::Status { + tx_connected: true, + rx_connected: false, + turntable_connected: true, + backend: BackendInfo { + name: s("espnow"), + frequency_mhz: Some(2400), + }, + mismatched_peers: heapless::Vec::from_slice(&[PeerMismatch { + mac: [1, 2, 3, 4, 5, 6], + protocol: 2, + }]) + .unwrap(), + }, + DeviceEvent::Error { + description: s("oops"), + }, + DeviceEvent::OtaReady, + DeviceEvent::OtaAck { seq: 300 }, + DeviceEvent::OtaComplete, + DeviceEvent::OtaError { + description: s("hash"), + }, + ]; + all.into_iter() + .map(|m| { + let name = match m { + DeviceEvent::TxAck => "TxAck", + DeviceEvent::MoveComplete { .. } => "MoveComplete", + DeviceEvent::TurntableError { .. } => "TurntableError", + DeviceEvent::HomeComplete => "HomeComplete", + DeviceEvent::Measurement { .. } => "Measurement", + DeviceEvent::Status { .. } => "Status", + DeviceEvent::Error { .. } => "Error", + DeviceEvent::OtaReady => "OtaReady", + DeviceEvent::OtaAck { .. } => "OtaAck", + DeviceEvent::OtaComplete => "OtaComplete", + DeviceEvent::OtaError { .. } => "OtaError", + }; + (name, m) + }) + .collect() +} + +const DEVICE_EVENT_V1: &[(&str, &str)] = &[ + ("TxAck", "01 00"), + ("MoveComplete", "01 01 00 00 b4 42"), + ("TurntableError", "01 02 05 73 74 61 6c 6c"), + ("HomeComplete", "01 03"), + ("Measurement", "01 04 00 00 2a c2 0a"), + ( + "Status", + "01 05 01 00 01 06 65 73 70 6e 6f 77 01 e0 12 01 01 02 03 04 05 06 02", + ), + ("Error", "01 06 04 6f 6f 70 73"), + ("OtaReady", "01 07"), + ("OtaAck", "01 08 ac 02"), + ("OtaComplete", "01 09"), + ("OtaError", "01 0a 04 68 61 73 68"), +]; + +#[test] +fn device_event_wire_layout() { + check(&device_event_samples(), DEVICE_EVENT_V1); +} + +// ── EspnowMessage ─────────────────────────────────────────────────────────── + +fn espnow_message_samples() -> Vec<(&'static str, EspnowMessage)> { + let mac = [1, 2, 3, 4, 5, 6]; + let all = [ + EspnowMessage::Hello(HelloBeacon { + role: Role::Rx, + mac, + }), + EspnowMessage::PairConfirm(PairConfirm { + role: Role::Bridge, + mac, + }), + EspnowMessage::TurntableCmd(TurntableCommand::MoveTo { angle_deg: 90.0 }), + EspnowMessage::TurntableCmd(TurntableCommand::Stop), + EspnowMessage::TurntableResp(TurntableResponse::MoveComplete { angle_deg: 90.0 }), + EspnowMessage::TurntableResp(TurntableResponse::Error { + description: s("stall"), + }), + EspnowMessage::TxCmd(TxCommand::Configure { + channel: 6, + tx_power_dbm: -3, + packet_rate_hz: 100, + }), + EspnowMessage::TxCmd(TxCommand::StartTransmit), + EspnowMessage::TxCmd(TxCommand::StopTransmit), + EspnowMessage::TxResp(TxResponse::Ack), + EspnowMessage::TxResp(TxResponse::Status { + transmitting: true, + channel: 6, + tx_power_dbm: -3, + packet_rate_hz: 100, + }), + EspnowMessage::MeasurementBeacon, + EspnowMessage::StartMeasurement, + EspnowMessage::ReportMeasurement, + EspnowMessage::MeasurementResult { + rssi_dbm: -42.5, + sample_count: 10, + }, + EspnowMessage::OtaBegin { + total_size: 1000, + sha256: [0xAB; 32], + ack_interval: 4, + }, + EspnowMessage::OtaReady, + EspnowMessage::OtaData { + seq: 300, + data: v(&[1, 2]), + }, + EspnowMessage::OtaAck { seq: 300 }, + EspnowMessage::OtaFinish, + EspnowMessage::OtaComplete, + EspnowMessage::OtaError { + description: s("hash"), + }, + ]; + all.into_iter() + .map(|m| { + let name = match m { + EspnowMessage::Hello(_) => "Hello", + EspnowMessage::PairConfirm(_) => "PairConfirm", + EspnowMessage::TurntableCmd(TurntableCommand::MoveTo { .. }) => { + "TurntableCmd::MoveTo" + } + EspnowMessage::TurntableCmd(TurntableCommand::Stop) => "TurntableCmd::Stop", + EspnowMessage::TurntableResp(TurntableResponse::MoveComplete { .. }) => { + "TurntableResp::MoveComplete" + } + EspnowMessage::TurntableResp(TurntableResponse::Error { .. }) => { + "TurntableResp::Error" + } + EspnowMessage::TxCmd(TxCommand::Configure { .. }) => "TxCmd::Configure", + EspnowMessage::TxCmd(TxCommand::StartTransmit) => "TxCmd::StartTransmit", + EspnowMessage::TxCmd(TxCommand::StopTransmit) => "TxCmd::StopTransmit", + EspnowMessage::TxResp(TxResponse::Ack) => "TxResp::Ack", + EspnowMessage::TxResp(TxResponse::Status { .. }) => "TxResp::Status", + EspnowMessage::MeasurementBeacon => "MeasurementBeacon", + EspnowMessage::StartMeasurement => "StartMeasurement", + EspnowMessage::ReportMeasurement => "ReportMeasurement", + EspnowMessage::MeasurementResult { .. } => "MeasurementResult", + EspnowMessage::OtaBegin { .. } => "OtaBegin", + EspnowMessage::OtaReady => "OtaReady", + EspnowMessage::OtaData { .. } => "OtaData", + EspnowMessage::OtaAck { .. } => "OtaAck", + EspnowMessage::OtaFinish => "OtaFinish", + EspnowMessage::OtaComplete => "OtaComplete", + EspnowMessage::OtaError { .. } => "OtaError", + }; + (name, m) + }) + .collect() +} + +const ESPNOW_MESSAGE_V1: &[(&str, &str)] = &[ + ("Hello", "01 00 00 01 02 03 04 05 06"), + ("PairConfirm", "01 01 03 01 02 03 04 05 06"), + ("TurntableCmd::MoveTo", "01 02 00 00 00 b4 42"), + ("TurntableCmd::Stop", "01 02 01"), + ("TurntableResp::MoveComplete", "01 03 00 00 00 b4 42"), + ("TurntableResp::Error", "01 03 01 05 73 74 61 6c 6c"), + ("TxCmd::Configure", "01 04 00 06 fd 64"), + ("TxCmd::StartTransmit", "01 04 01"), + ("TxCmd::StopTransmit", "01 04 02"), + ("TxResp::Ack", "01 05 00"), + ("TxResp::Status", "01 05 01 01 06 fd 64"), + ("MeasurementBeacon", "01 06"), + ("StartMeasurement", "01 07"), + ("ReportMeasurement", "01 08"), + ("MeasurementResult", "01 09 00 00 2a c2 0a"), + ("OtaBegin", "01 0a e8 07 ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab 04"), + ("OtaReady", "01 0b"), + ("OtaData", "01 0c ac 02 02 01 02"), + ("OtaAck", "01 0d ac 02"), + ("OtaFinish", "01 0e"), + ("OtaComplete", "01 0f"), + ("OtaError", "01 10 04 68 61 73 68"), +]; + +#[test] +fn espnow_message_wire_layout() { + check(&espnow_message_samples(), ESPNOW_MESSAGE_V1); +} diff --git a/software/protocol/src/lib.rs b/software/protocol/src/lib.rs index 0b680e3..cf50da5 100644 --- a/software/protocol/src/lib.rs +++ b/software/protocol/src/lib.rs @@ -4,8 +4,11 @@ //! and the PC application. Messages are serialized with `postcard`. //! //! Two protocol layers: -//! - **Serial** (PC ↔ RX board): COBS-framed postcard over USB-serial +//! - **Serial** (PC ↔ Bridge): COBS-framed postcard over USB-serial //! - **ESPNOW** (between boards): postcard-serialized payloads in ESPNOW frames +//! +//! Every frame starts with [`PROTOCOL_VERSION`]. A receiver reads only that +//! header first and does not decode frames from another version. #![no_std] @@ -13,11 +16,19 @@ pub mod bridge_logic; pub mod rx_logic; pub mod tx_logic; +#[cfg(test)] +mod golden; + use heapless::{String, Vec}; use serde::{Deserialize, Serialize}; +/// Wire format version. Bump on every change to the serialized layout of any +/// message. The golden-bytes tests fail when the layout changes. +pub const PROTOCOL_VERSION: u16 = 1; + /// Maximum payload per OTA chunk. Must fit in a 250-byte ESP-NOW frame after -/// postcard serialization overhead (tag byte + seq u16 + length varint). +/// postcard serialization overhead (version header + tag byte + seq u16 + +/// length varint). pub const OTA_CHUNK_SIZE: usize = 240; // ── Board roles (used during ESPNOW discovery) ────────────────────────────── @@ -255,6 +266,8 @@ pub enum DeviceEvent { rx_connected: bool, turntable_connected: bool, backend: BackendInfo, + /// Boards whose frames the bridge dropped because of another protocol version. + mismatched_peers: Vec, }, Error { description: String<128> }, @@ -269,6 +282,17 @@ pub enum DeviceEvent { OtaError { description: String<64> }, } +/// Maximum number of mismatched boards reported in `DeviceEvent::Status`. +pub const MAX_MISMATCHED_PEERS: usize = 4; + +/// A board that speaks another protocol version. +#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] +pub struct PeerMismatch { + pub mac: [u8; 6], + pub protocol: u16, +} + // ── Serial protocol v1 (PC ↔ RX, legacy) ─────────────────────────────────── /// Command from PC to RX board (over USB-serial). @@ -352,26 +376,51 @@ pub mod turntable { /// Maximum serialized message size (ESPNOW payload limit is 250 bytes). pub const MAX_MSG_SIZE: usize = 250; -/// Serialize a message into a buffer. Returns the serialized slice. +/// Error when decoding a frame. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum DecodeError { + /// The sender speaks another protocol version. The message was not decoded. + VersionMismatch { protocol: u16 }, + /// The frame is malformed. + Postcard(postcard::Error), +} + +impl From for DecodeError { + fn from(e: postcard::Error) -> Self { + DecodeError::Postcard(e) + } +} + +/// Serialize a message with version header into a buffer. Returns the serialized slice. pub fn serialize<'a, T: Serialize>( msg: &T, buf: &'a mut [u8], ) -> Result<&'a mut [u8], postcard::Error> { - postcard::to_slice(msg, buf) + postcard::to_slice(&(PROTOCOL_VERSION, msg), buf) } -/// Deserialize a message from a byte slice. -pub fn deserialize<'a, T: Deserialize<'a>>(buf: &'a [u8]) -> Result { - postcard::from_bytes(buf) +/// Deserialize a message from a byte slice. Checks the version header first. +pub fn deserialize<'a, T: Deserialize<'a>>(buf: &'a [u8]) -> Result { + let (protocol, msg) = postcard::take_from_bytes::(buf)?; + if protocol != PROTOCOL_VERSION { + return Err(DecodeError::VersionMismatch { protocol }); + } + Ok(postcard::from_bytes(msg)?) } -/// Serialize a message with COBS framing (for serial protocol). +/// Serialize a message with version header and COBS framing (for serial protocol). /// Returns the number of bytes written to `buf`. pub fn serialize_cobs(msg: &T, buf: &mut [u8]) -> Result { - let used = postcard::to_slice_cobs(msg, buf)?; + let used = postcard::to_slice_cobs(&(PROTOCOL_VERSION, msg), buf)?; Ok(used.len()) } +/// Deserialize a COBS frame in place. Checks the version header first. +pub fn deserialize_cobs<'a, T: Deserialize<'a>>(buf: &'a mut [u8]) -> Result { + let len = cobs::decode_in_place(buf).map_err(|_| postcard::Error::DeserializeBadEncoding)?; + deserialize(&buf[..len]) +} + #[cfg(test)] mod test { use core::fmt::Debug; @@ -380,7 +429,8 @@ mod test { use serde::{Deserialize, Serialize}; use crate::{ - BackendInfo, DeviceEvent, EspnowMessage, HelloBeacon, PairConfirm, PcCommand, PcToRx, + BackendInfo, DecodeError, DeviceEvent, EspnowMessage, HelloBeacon, PairConfirm, PcCommand, + PcToRx, PeerMismatch, Role, RxToPc, TurntableCommand, TurntableResponse, TxCommand, TxResponse, MAX_MSG_SIZE, }; @@ -471,7 +521,7 @@ mod test { let len = super::serialize_cobs(msg, buf).expect("COBS serialize failed"); assert_eq!(buf[len - 1], 0x00, "COBS frame must end with zero byte"); let decoded: T = - postcard::from_bytes_cobs(&mut buf[..len]).expect("COBS deserialize failed"); + super::deserialize_cobs(&mut buf[..len]).expect("COBS deserialize failed"); assert_eq!(&decoded, msg); } @@ -481,12 +531,30 @@ mod test { let cmd = PcCommand::MoveTo { angle_deg: 90.0 }; let mut buf = [0u8; MAX_MSG_SIZE]; - // Variant index 3, then 90.0f32 little-endian. + // Version 1, variant index 3, then 90.0f32 little-endian. let plain = super::serialize(&cmd, &mut buf).unwrap(); - assert_eq!(plain, [0x03, 0x00, 0x00, 0xB4, 0x42]); + assert_eq!(plain, [0x01, 0x03, 0x00, 0x00, 0xB4, 0x42]); let len = super::serialize_cobs(&cmd, &mut buf).unwrap(); - assert_eq!(buf[..len], [0x02, 0x03, 0x01, 0x03, 0xB4, 0x42, 0x00]); + assert_eq!(buf[..len], [0x03, 0x01, 0x03, 0x01, 0x03, 0xB4, 0x42, 0x00]); + } + + #[test] + fn version_mismatch_is_not_decoded() { + let mut buf = [0u8; MAX_MSG_SIZE]; + let len = super::serialize(&PcCommand::QueryStatus, &mut buf).unwrap().len(); + buf[0] = 2; + assert_eq!( + super::deserialize::(&buf[..len]), + Err(DecodeError::VersionMismatch { protocol: 2 }) + ); + + // Same for a COBS frame whose payload would not even parse as `PcCommand`. + let mut frame = [0x03, 0x02, 0xFF, 0x00]; + assert_eq!( + super::deserialize_cobs::(&mut frame), + Err(DecodeError::VersionMismatch { protocol: 2 }) + ); } #[test] @@ -678,6 +746,11 @@ mod test { name: String::try_from("espnow").unwrap(), frequency_mhz: Some(2400), }, + mismatched_peers: Vec::from_slice(&[PeerMismatch { + mac: [1, 2, 3, 4, 5, 6], + protocol: 7, + }]) + .unwrap(), }, &mut buf, ); From 5105a28ecb12d916ecc34a1bcbd5fdd2d2082764 Mon Sep 17 00:00:00 2001 From: JuliDi Date: Fri, 13 Nov 2026 15:22:28 +0100 Subject: [PATCH 03/16] fix: format pc and protocol code --- software/pc/src/lib.rs | 14 +- software/pc/src/main.rs | 230 +++++++++++++++++++++--------- software/pc/src/ota.rs | 12 +- software/pc/src/serial.rs | 17 ++- software/pc/src/sim.rs | 4 +- software/pc/src/sweep.rs | 22 ++- software/protocol/src/lib.rs | 126 +++++++++------- software/protocol/src/tx_logic.rs | 4 +- 8 files changed, 283 insertions(+), 146 deletions(-) diff --git a/software/pc/src/lib.rs b/software/pc/src/lib.rs index d940aee..895ae09 100644 --- a/software/pc/src/lib.rs +++ b/software/pc/src/lib.rs @@ -137,7 +137,10 @@ pub enum WsCommand { Jog { delta_deg: f32 }, /// Start an OTA firmware update for the specified target device. /// Target is "rx", "tx", "turntable", or "bridge". - OtaUpload { target: String, firmware_path: String }, + OtaUpload { + target: String, + firmware_path: String, + }, /// Set the motor-to-turntable gear ratio (motor_deg = turntable_deg × ratio). SetTransmissionRatio { ratio: f32 }, } @@ -162,7 +165,10 @@ impl SweepConfig { pub fn export_csv(data: &[DataPoint]) -> String { let mut csv = String::from("angle_deg,rssi_dbm,sample_count\n"); for dp in data { - csv.push_str(&format!("{},{},{}\n", dp.angle_deg, dp.rssi_dbm, dp.sample_count)); + csv.push_str(&format!( + "{},{},{}\n", + dp.angle_deg, dp.rssi_dbm, dp.sample_count + )); } csv } @@ -202,7 +208,9 @@ mod tests { // ── JSON round-trip tests ─────────────────────────────────────────── - fn json_round_trip( + fn json_round_trip< + T: serde::Serialize + serde::de::DeserializeOwned + PartialEq + std::fmt::Debug, + >( val: &T, ) { let json = serde_json::to_string(val).expect("serialize"); diff --git a/software/pc/src/main.rs b/software/pc/src/main.rs index 658d3cd..2684887 100644 --- a/software/pc/src/main.rs +++ b/software/pc/src/main.rs @@ -1,24 +1,24 @@ //! Beambench PC application — Axum server with WebSocket and embedded frontend. -use std::sync::Arc; use std::sync::atomic::{AtomicBool, AtomicI32, AtomicU32, Ordering}; +use std::sync::Arc; use axum::{ - Router, extract::{ - Multipart, State, ws::{Message, WebSocket, WebSocketUpgrade}, + Multipart, State, }, response::{IntoResponse, Json}, routing::{get, post}, + Router, }; use clap::Parser; use rust_embed::Embed; -use tokio::sync::{Mutex, broadcast, watch}; +use tokio::sync::{broadcast, watch, Mutex}; use tracing::info; use beambench_pc::{ - DEFAULT_TRANSMISSION_RATIO, PortInfo, SystemStatus, WsCommand, WsEvent, export_csv, + export_csv, PortInfo, SystemStatus, WsCommand, WsEvent, DEFAULT_TRANSMISSION_RATIO, }; /// Initial delay before sending QueryStatus to a freshly-opened device. @@ -155,7 +155,12 @@ fn spawn_ota( ) { tokio::spawn(async move { match beambench_pc::ota::stream_firmware( - &firmware, role, ack_interval, &serial_tx, &serial_rx, &state.ws_tx, + &firmware, + role, + ack_interval, + &serial_tx, + &serial_rx, + &state.ws_tx, ) .await { @@ -277,10 +282,7 @@ async fn export_csv_handler(State(state): State>) -> impl IntoResp let data = state.data.lock().await; let csv = export_csv(&data); ( - [( - axum::http::header::CONTENT_TYPE, - "text/csv; charset=utf-8", - )], + [(axum::http::header::CONTENT_TYPE, "text/csv; charset=utf-8")], csv, ) } @@ -340,15 +342,19 @@ async fn ota_upload( message: format!("Starting OTA for {}: {} bytes", target_str, size), }); - spawn_ota(state.clone(), firmware, role, ack_interval, serial_tx, serial_rx); + spawn_ota( + state.clone(), + firmware, + role, + ack_interval, + serial_tx, + serial_rx, + ); Json(serde_json::json!({"ok": true, "size": size})) } -async fn ws_handler( - ws: WebSocketUpgrade, - State(state): State>, -) -> impl IntoResponse { +async fn ws_handler(ws: WebSocketUpgrade, State(state): State>) -> impl IntoResponse { ws.on_upgrade(|socket| handle_ws(socket, state)) } @@ -361,7 +367,11 @@ async fn handle_ws(mut socket: WebSocket, state: Arc) { // Send current status on connect. let status = state.status().await; let _ = socket - .send(Message::Text(serde_json::to_string(&WsEvent::Status(status)).unwrap().into())) + .send(Message::Text( + serde_json::to_string(&WsEvent::Status(status)) + .unwrap() + .into(), + )) .await; loop { @@ -456,28 +466,52 @@ async fn handle_command(cmd: WsCommand, state: &Arc) { let port_name = port.clone(); tokio::spawn(async move { tokio::time::sleep(VERIFY_INITIAL_DELAY).await; - let _ = serial_tx.send(beambench_protocol::PcCommand::QueryStatus).await; - - let result = tokio::time::timeout( - VERIFY_TIMEOUT, - async { - let mut rx = serial_rx.lock().await; - rx.recv().await - }, - ) + let _ = serial_tx + .send(beambench_protocol::PcCommand::QueryStatus) + .await; + + let result = tokio::time::timeout(VERIFY_TIMEOUT, async { + let mut rx = serial_rx.lock().await; + rx.recv().await + }) .await; match result { - Ok(Some(beambench_protocol::DeviceEvent::Status { tx_connected, rx_connected, turntable_connected, backend, mismatched_peers })) => { + Ok(Some(beambench_protocol::DeviceEvent::Status { + tx_connected, + rx_connected, + turntable_connected, + backend, + mismatched_peers, + })) => { tracing::info!("Device verified as Bridge"); let _ = state2.ws_tx.send(WsEvent::Log { - message: format!("{} confirmed as Bridge (TX: {}, RX: {}, Turntable: {})", + message: format!( + "{} confirmed as Bridge (TX: {}, RX: {}, Turntable: {})", port_name, - if tx_connected { "connected" } else { "not found" }, - if rx_connected { "connected" } else { "not found" }, - if turntable_connected { "connected" } else { "not found" }), + if tx_connected { + "connected" + } else { + "not found" + }, + if rx_connected { + "connected" + } else { + "not found" + }, + if turntable_connected { + "connected" + } else { + "not found" + } + ), }); - update_peer_status(&state2, tx_connected, rx_connected, turntable_connected); + update_peer_status( + &state2, + tx_connected, + rx_connected, + turntable_connected, + ); update_backend_info(&state2, &backend).await; update_mismatched_peers(&state2, &mismatched_peers).await; state2.broadcast_status().await; @@ -491,19 +525,31 @@ async fn handle_command(cmd: WsCommand, state: &Arc) { Ok(Some(other)) => { tracing::info!("Unexpected response from device: {:?}", other); let _ = state2.ws_tx.send(WsEvent::Log { - message: format!("{}: got unexpected response — may not be Bridge", port_name), + message: format!( + "{}: got unexpected response — may not be Bridge", + port_name + ), }); } Ok(None) => { tracing::warn!("Serial channel closed during verification"); let _ = state2.ws_tx.send(WsEvent::Log { - message: format!("{}: connection lost during verification", port_name), + message: format!( + "{}: connection lost during verification", + port_name + ), }); } Err(_) => { - tracing::warn!("No response from {} — not a Bridge or firmware not running", port_name); + tracing::warn!( + "No response from {} — not a Bridge or firmware not running", + port_name + ); state2.broadcast_error( - &format!("{}: no response — is this the Bridge device?", port_name), + &format!( + "{}: no response — is this the Bridge device?", + port_name + ), "Device did not respond. Is this the Bridge?", ); } @@ -575,7 +621,10 @@ async fn handle_command(cmd: WsCommand, state: &Arc) { let _ = state.ws_tx.send(WsEvent::Log { message: format!( "Sweep started: {}° to {}° (step {}°, {} samples)", - config.start_deg, config.stop_deg, config.step_deg, config.samples_per_angle + config.start_deg, + config.stop_deg, + config.step_deg, + config.samples_per_angle ), }); let _ = state.ws_tx.send(WsEvent::Status(state.status().await)); @@ -609,17 +658,20 @@ async fn handle_command(cmd: WsCommand, state: &Arc) { }); } else { state.sweeping.store(false, Ordering::SeqCst); - state.broadcast_error( - "Sweep failed: not connected", - "Not connected to serial/TCP", - ); + state.broadcast_error("Sweep failed: not connected", "Not connected to serial/TCP"); } } WsCommand::Stop => { let serial = state.serial.lock().await; if let Some(ref handle) = *serial { - let _ = handle.tx.send(beambench_protocol::PcCommand::StopTransmitting).await; - let _ = handle.tx.send(beambench_protocol::PcCommand::StopTurntable).await; + let _ = handle + .tx + .send(beambench_protocol::PcCommand::StopTransmitting) + .await; + let _ = handle + .tx + .send(beambench_protocol::PcCommand::StopTurntable) + .await; } } WsCommand::ConfigureTx(tx_config) => { @@ -638,14 +690,18 @@ async fn handle_command(cmd: WsCommand, state: &Arc) { WsCommand::QueryStatus => { let serial = state.serial.lock().await; if let Some(ref handle) = *serial { - let _ = handle.tx.send(beambench_protocol::PcCommand::QueryStatus).await; + let _ = handle + .tx + .send(beambench_protocol::PcCommand::QueryStatus) + .await; } } WsCommand::ExportCsv => { // CSV export is available via REST endpoint. } WsCommand::ReturnHome => { - if state.sweeping.load(Ordering::SeqCst) || state.ota_in_progress.load(Ordering::SeqCst) { + if state.sweeping.load(Ordering::SeqCst) || state.ota_in_progress.load(Ordering::SeqCst) + { let _ = state.ws_tx.send(WsEvent::Error { message: "Cannot return home while sweep or OTA is in progress".to_string(), }); @@ -665,9 +721,17 @@ async fn handle_command(cmd: WsCommand, state: &Arc) { let state = state.clone(); tokio::spawn(async move { - match send_and_wait_move(&serial_tx, &serial_rx, beambench_protocol::PcCommand::ReturnHome).await { + match send_and_wait_move( + &serial_tx, + &serial_rx, + beambench_protocol::PcCommand::ReturnHome, + ) + .await + { Ok(angle_deg) => { - state.turntable_angle_cdeg.store((angle_deg * 100.0) as i32, Ordering::SeqCst); + state + .turntable_angle_cdeg + .store((angle_deg * 100.0) as i32, Ordering::SeqCst); let _ = state.ws_tx.send(WsEvent::HomeComplete); let _ = state.ws_tx.send(WsEvent::Log { message: "Turntable reached home position".to_string(), @@ -682,10 +746,16 @@ async fn handle_command(cmd: WsCommand, state: &Arc) { }); } else { state.homing.store(false, Ordering::SeqCst); - state.broadcast_error("ReturnHome failed: not connected", "Not connected to serial/TCP"); + state.broadcast_error( + "ReturnHome failed: not connected", + "Not connected to serial/TCP", + ); } } - WsCommand::OtaUpload { target, firmware_path } => { + WsCommand::OtaUpload { + target, + firmware_path, + } => { if state.sweeping.load(Ordering::SeqCst) { let _ = state.ws_tx.send(WsEvent::Error { message: "Cannot start OTA while sweep is in progress".to_string(), @@ -742,10 +812,7 @@ async fn handle_command(cmd: WsCommand, state: &Arc) { ); } else { state.ota_in_progress.store(false, Ordering::SeqCst); - state.broadcast_error( - "OTA failed: not connected", - "Not connected to serial/TCP", - ); + state.broadcast_error("OTA failed: not connected", "Not connected to serial/TCP"); } } WsCommand::SetTransmissionRatio { ratio } => { @@ -762,7 +829,10 @@ async fn handle_command(cmd: WsCommand, state: &Arc) { state.broadcast_status().await; } WsCommand::Jog { delta_deg } => { - if state.sweeping.load(Ordering::SeqCst) || state.homing.load(Ordering::SeqCst) || state.ota_in_progress.load(Ordering::SeqCst) { + if state.sweeping.load(Ordering::SeqCst) + || state.homing.load(Ordering::SeqCst) + || state.ota_in_progress.load(Ordering::SeqCst) + { let _ = state.ws_tx.send(WsEvent::Error { message: "Cannot jog while sweep, homing, or OTA is in progress".to_string(), }); @@ -787,10 +857,20 @@ async fn handle_command(cmd: WsCommand, state: &Arc) { let state = state.clone(); tokio::spawn(async move { - match send_and_wait_move(&serial_tx, &serial_rx, beambench_protocol::PcCommand::MoveTo { angle_deg: motor_target_deg }).await { + match send_and_wait_move( + &serial_tx, + &serial_rx, + beambench_protocol::PcCommand::MoveTo { + angle_deg: motor_target_deg, + }, + ) + .await + { Ok(motor_angle_deg) => { let angle_deg = motor_angle_deg / ratio; - state.turntable_angle_cdeg.store((angle_deg * 100.0) as i32, Ordering::SeqCst); + state + .turntable_angle_cdeg + .store((angle_deg * 100.0) as i32, Ordering::SeqCst); let _ = state.ws_tx.send(WsEvent::Log { message: format!("Turntable at {:.1}°", angle_deg), }); @@ -875,7 +955,11 @@ async fn status_poll_loop( return; // Disconnected. }; - if serial_tx.send(beambench_protocol::PcCommand::QueryStatus).await.is_err() { + if serial_tx + .send(beambench_protocol::PcCommand::QueryStatus) + .await + .is_err() + { return; } @@ -883,8 +967,20 @@ async fn status_poll_loop( let mut rx = serial_rx.lock().await; loop { match rx.recv().await { - Some(beambench_protocol::DeviceEvent::Status { tx_connected, rx_connected, turntable_connected, backend, mismatched_peers }) => { - return Some((tx_connected, rx_connected, turntable_connected, backend, mismatched_peers)); + Some(beambench_protocol::DeviceEvent::Status { + tx_connected, + rx_connected, + turntable_connected, + backend, + mismatched_peers, + }) => { + return Some(( + tx_connected, + rx_connected, + turntable_connected, + backend, + mismatched_peers, + )); } Some(_) => continue, None => return None, @@ -921,18 +1017,20 @@ async fn static_handler(uri: axum::http::Uri) -> impl IntoResponse { let mime = mime_guess::from_path(path) .first_or_octet_stream() .to_string(); - ([(axum::http::header::CONTENT_TYPE, mime)], content.data.into_response()).into_response() + ( + [(axum::http::header::CONTENT_TYPE, mime)], + content.data.into_response(), + ) + .into_response() } None => { // SPA fallback — serve index.html for client-side routing. match FrontendAssets::get("index.html") { - Some(content) => { - ( - [(axum::http::header::CONTENT_TYPE, "text/html".to_string())], - content.data.into_response(), - ) - .into_response() - } + Some(content) => ( + [(axum::http::header::CONTENT_TYPE, "text/html".to_string())], + content.data.into_response(), + ) + .into_response(), None => (axum::http::StatusCode::NOT_FOUND, "Not found").into_response(), } } diff --git a/software/pc/src/ota.rs b/software/pc/src/ota.rs index 79e81a8..9bc5e72 100644 --- a/software/pc/src/ota.rs +++ b/software/pc/src/ota.rs @@ -51,9 +51,9 @@ use std::sync::Arc; -use beambench_protocol::{DeviceEvent, OTA_CHUNK_SIZE, PcCommand, Role}; +use beambench_protocol::{DeviceEvent, PcCommand, Role, OTA_CHUNK_SIZE}; use sha2::{Digest, Sha256}; -use tokio::sync::{Mutex, broadcast, mpsc}; +use tokio::sync::{broadcast, mpsc, Mutex}; use crate::WsEvent; @@ -204,9 +204,11 @@ pub async fn stream_firmware( } // Wait for the batch ack. - match wait_for(&mut rx, OTA_WINDOW_TIMEOUT, |e| { - matches!(e, DeviceEvent::OtaAck { seq } if *seq == expected_ack_seq) - }) + match wait_for( + &mut rx, + OTA_WINDOW_TIMEOUT, + |e| matches!(e, DeviceEvent::OtaAck { seq } if *seq == expected_ack_seq), + ) .await { Ok(()) => { diff --git a/software/pc/src/serial.rs b/software/pc/src/serial.rs index a6803df..f5c0037 100644 --- a/software/pc/src/serial.rs +++ b/software/pc/src/serial.rs @@ -4,7 +4,7 @@ use std::sync::Arc; use beambench_protocol::{DecodeError, DeviceEvent, PcCommand, PROTOCOL_VERSION}; use tokio::io::{AsyncReadExt, AsyncWriteExt}; -use tokio::sync::{Mutex, mpsc}; +use tokio::sync::{mpsc, Mutex}; use tokio_serial::SerialPortBuilderExt; use tracing::{debug, error, info, warn}; @@ -266,7 +266,10 @@ mod tests { writer.write_all(&frame).await.unwrap(); drop(writer); - let decoded = resp_rx.recv().await.expect("should receive decoded message"); + let decoded = resp_rx + .recv() + .await + .expect("should receive decoded message"); assert_eq!(decoded, msg); } @@ -309,7 +312,10 @@ mod tests { writer.write_all(&frame[mid..]).await.unwrap(); drop(writer); - let decoded = resp_rx.recv().await.expect("should reassemble fragmented frame"); + let decoded = resp_rx + .recv() + .await + .expect("should reassemble fragmented frame"); assert_eq!(decoded, msg); } @@ -333,7 +339,10 @@ mod tests { writer.write_all(&frame).await.unwrap(); drop(writer); - let decoded = resp_rx.recv().await.expect("should decode frame after reset"); + let decoded = resp_rx + .recv() + .await + .expect("should decode frame after reset"); assert_eq!(decoded, msg); } diff --git a/software/pc/src/sim.rs b/software/pc/src/sim.rs index 7f24078..ed47da3 100644 --- a/software/pc/src/sim.rs +++ b/software/pc/src/sim.rs @@ -11,8 +11,8 @@ use beambench_protocol::bridge_logic::{self, RouteAction}; use beambench_protocol::rx_logic::MeasurementState; use beambench_protocol::tx_logic::TxState; use beambench_protocol::{ - BackendInfo, DeviceEvent, EspnowMessage, PcCommand, Role, TurntableCommand, - TurntableResponse, MAX_MSG_SIZE, + BackendInfo, DeviceEvent, EspnowMessage, PcCommand, Role, TurntableCommand, TurntableResponse, + MAX_MSG_SIZE, }; use tokio::io::{AsyncReadExt, AsyncWriteExt}; use tokio::sync::mpsc; diff --git a/software/pc/src/sweep.rs b/software/pc/src/sweep.rs index a7a619a..97879fe 100644 --- a/software/pc/src/sweep.rs +++ b/software/pc/src/sweep.rs @@ -8,7 +8,7 @@ use std::time::Duration; use crate::{DataPoint, SweepConfig, WsEvent}; use beambench_protocol::{DeviceEvent, PcCommand}; -use tokio::sync::{Mutex, mpsc}; +use tokio::sync::{mpsc, Mutex}; use tracing::{error, info}; /// Timeout for waiting on a turntable MoveComplete response. @@ -234,9 +234,8 @@ mod tests { let resp_rx = shared_rx(resp_rx); let config = test_config(); - let handle = tokio::spawn(async move { - run_sweep(config, 1.0, &serial_tx, &resp_rx, &ws_tx).await - }); + let handle = + tokio::spawn(async move { run_sweep(config, 1.0, &serial_tx, &resp_rx, &ws_tx).await }); // Respond to commands from the sweep orchestrator. tokio::spawn(async move { @@ -298,9 +297,8 @@ mod tests { let resp_rx = shared_rx(resp_rx); let config = test_config(); - let handle = tokio::spawn(async move { - run_sweep(config, 1.0, &serial_tx, &resp_rx, &ws_tx).await - }); + let handle = + tokio::spawn(async move { run_sweep(config, 1.0, &serial_tx, &resp_rx, &ws_tx).await }); tokio::spawn(async move { while let Some(cmd) = serial_cmd_rx.recv().await { @@ -343,9 +341,8 @@ mod tests { let resp_rx = shared_rx(resp_rx); let config = test_config(); - let handle = tokio::spawn(async move { - run_sweep(config, 1.0, &serial_tx, &resp_rx, &ws_tx).await - }); + let handle = + tokio::spawn(async move { run_sweep(config, 1.0, &serial_tx, &resp_rx, &ws_tx).await }); // Drop the sender to simulate disconnection. drop(resp_tx); @@ -366,9 +363,8 @@ mod tests { tokio::time::pause(); - let handle = tokio::spawn(async move { - run_sweep(config, 1.0, &serial_tx, &resp_rx, &ws_tx).await - }); + let handle = + tokio::spawn(async move { run_sweep(config, 1.0, &serial_tx, &resp_rx, &ws_tx).await }); // Advance past TX ack timeout + move timeout. tokio::time::advance(Duration::from_secs(2) + MOVE_TIMEOUT + Duration::from_secs(1)).await; diff --git a/software/protocol/src/lib.rs b/software/protocol/src/lib.rs index cf50da5..496d9d2 100644 --- a/software/protocol/src/lib.rs +++ b/software/protocol/src/lib.rs @@ -183,27 +183,41 @@ pub enum EspnowMessage { /// Bridge -> RX: stop collecting, report result. ReportMeasurement, /// RX -> Bridge: measurement result. - MeasurementResult { rssi_dbm: f32, sample_count: u16 }, + MeasurementResult { + rssi_dbm: f32, + sample_count: u16, + }, // OTA firmware update (Bridge ↔ field device) /// Bridge -> target: begin OTA update with expected size and hash. /// `ack_interval` controls windowed flow control: the target sends an /// `OtaAck` every `ack_interval` chunks (and always on the last chunk). /// A value of 1 means every chunk is acked (stop-and-wait). - OtaBegin { total_size: u32, sha256: [u8; 32], ack_interval: u16 }, + OtaBegin { + total_size: u32, + sha256: [u8; 32], + ack_interval: u16, + }, /// Target -> Bridge: ready to receive OTA data. OtaReady, /// Bridge -> target: firmware chunk (max 240 bytes to fit ESP-NOW payload). - OtaData { seq: u16, data: Vec }, + OtaData { + seq: u16, + data: Vec, + }, /// Target -> Bridge: acknowledge receipt of chunk. The PC should not send /// more than `ack_interval` chunks beyond the last acked sequence number. - OtaAck { seq: u16 }, + OtaAck { + seq: u16, + }, /// Bridge -> target: all chunks sent. OtaFinish, /// Target -> Bridge: OTA verified and applied, rebooting. OtaComplete, /// Target -> Bridge: OTA failed. - OtaError { description: String<64> }, + OtaError { + description: String<64>, + }, } // ── Serial protocol v2 (PC ↔ Bridge) ──────────────────────────────────────── @@ -225,7 +239,9 @@ pub enum PcCommand { StopTransmitting, // Turntable control - MoveTo { angle_deg: f32 }, + MoveTo { + angle_deg: f32, + }, StopTurntable, ReturnHome, @@ -238,11 +254,22 @@ pub enum PcCommand { // OTA firmware update (PC -> Bridge -> target) /// Begin OTA: target role, firmware size, SHA-256 hash, and ack window. - OtaBegin { target: Role, total_size: u32, sha256: [u8; 32], ack_interval: u16 }, + OtaBegin { + target: Role, + total_size: u32, + sha256: [u8; 32], + ack_interval: u16, + }, /// Stream a firmware chunk (Bridge relays to target via ESP-NOW). - OtaData { target: Role, seq: u16, data: Vec }, + OtaData { + target: Role, + seq: u16, + data: Vec, + }, /// All chunks sent — target should verify and apply. - OtaFinish { target: Role }, + OtaFinish { + target: Role, + }, } /// Event from Bridge to PC (over USB-serial, COBS-framed postcard). @@ -253,12 +280,19 @@ pub enum DeviceEvent { TxAck, // Turntable responses - MoveComplete { angle_deg: f32 }, - TurntableError { description: String<64> }, + MoveComplete { + angle_deg: f32, + }, + TurntableError { + description: String<64>, + }, HomeComplete, // RX responses - Measurement { rssi_dbm: f32, sample_count: u16 }, + Measurement { + rssi_dbm: f32, + sample_count: u16, + }, // System Status { @@ -269,17 +303,23 @@ pub enum DeviceEvent { /// Boards whose frames the bridge dropped because of another protocol version. mismatched_peers: Vec, }, - Error { description: String<128> }, + Error { + description: String<128>, + }, // OTA firmware update (target -> Bridge -> PC) /// Target is ready to receive OTA data. OtaReady, /// Target acknowledged a chunk. - OtaAck { seq: u16 }, + OtaAck { + seq: u16, + }, /// OTA verified and applied, target is rebooting. OtaComplete, /// OTA failed on the target device. - OtaError { description: String<64> }, + OtaError { + description: String<64>, + }, } /// Maximum number of mismatched boards reported in `DeviceEvent::Status`. @@ -430,8 +470,8 @@ mod test { use crate::{ BackendInfo, DecodeError, DeviceEvent, EspnowMessage, HelloBeacon, PairConfirm, PcCommand, - PcToRx, PeerMismatch, - Role, RxToPc, TurntableCommand, TurntableResponse, TxCommand, TxResponse, MAX_MSG_SIZE, + PcToRx, PeerMismatch, Role, RxToPc, TurntableCommand, TurntableResponse, TxCommand, + TxResponse, MAX_MSG_SIZE, }; /// Serialize `msg` into `buf` with postcard, then deserialize and assert equality. @@ -520,8 +560,7 @@ mod test { ) { let len = super::serialize_cobs(msg, buf).expect("COBS serialize failed"); assert_eq!(buf[len - 1], 0x00, "COBS frame must end with zero byte"); - let decoded: T = - super::deserialize_cobs(&mut buf[..len]).expect("COBS deserialize failed"); + let decoded: T = super::deserialize_cobs(&mut buf[..len]).expect("COBS deserialize failed"); assert_eq!(&decoded, msg); } @@ -542,7 +581,9 @@ mod test { #[test] fn version_mismatch_is_not_decoded() { let mut buf = [0u8; MAX_MSG_SIZE]; - let len = super::serialize(&PcCommand::QueryStatus, &mut buf).unwrap().len(); + let len = super::serialize(&PcCommand::QueryStatus, &mut buf) + .unwrap() + .len(); buf[0] = 2; assert_eq!( super::deserialize::(&buf[..len]), @@ -658,14 +699,8 @@ mod test { }), &mut buf, ); - test_ser_deser( - &EspnowMessage::TxCmd(TxCommand::StartTransmit), - &mut buf, - ); - test_ser_deser( - &EspnowMessage::TxCmd(TxCommand::StopTransmit), - &mut buf, - ); + test_ser_deser(&EspnowMessage::TxCmd(TxCommand::StartTransmit), &mut buf); + test_ser_deser(&EspnowMessage::TxCmd(TxCommand::StopTransmit), &mut buf); test_ser_deser(&EspnowMessage::TxResp(TxResponse::Ack), &mut buf); test_ser_deser( &EspnowMessage::TxResp(TxResponse::Status { @@ -719,10 +754,7 @@ mod test { let mut buf = [0u8; MAX_MSG_SIZE]; test_cobs_round_trip(&DeviceEvent::TxAck, &mut buf); - test_cobs_round_trip( - &DeviceEvent::MoveComplete { angle_deg: 90.0 }, - &mut buf, - ); + test_cobs_round_trip(&DeviceEvent::MoveComplete { angle_deg: 90.0 }, &mut buf); test_cobs_round_trip( &DeviceEvent::TurntableError { description: String::try_from("stall").unwrap(), @@ -794,10 +826,7 @@ mod test { test_ser_deser(&EspnowMessage::OtaReady, &mut buf); test_ser_deser(&EspnowMessage::OtaFinish, &mut buf); test_ser_deser(&EspnowMessage::OtaComplete, &mut buf); - test_ser_deser( - &EspnowMessage::OtaAck { seq: 1000 }, - &mut buf, - ); + test_ser_deser(&EspnowMessage::OtaAck { seq: 1000 }, &mut buf); test_ser_deser( &EspnowMessage::OtaError { description: String::try_from("flash write failed").unwrap(), @@ -808,10 +837,7 @@ mod test { // OtaData with max-size payload (240 bytes) let mut data = Vec::::new(); data.resize(240, 0xFF).unwrap(); - test_ser_deser( - &EspnowMessage::OtaData { seq: 0xFFFF, data }, - &mut buf, - ); + test_ser_deser(&EspnowMessage::OtaData { seq: 0xFFFF, data }, &mut buf); } #[test] @@ -1211,10 +1237,8 @@ mod test { #[test] fn handle_message_ignores_unrelated() { let mut state = MeasurementState::new(); - let resp = state.handle_message( - &EspnowMessage::TxCmd(crate::TxCommand::StartTransmit), - 0, - ); + let resp = + state.handle_message(&EspnowMessage::TxCmd(crate::TxCommand::StartTransmit), 0); assert!(resp.is_none()); assert!(!state.is_measuring()); } @@ -1290,10 +1314,7 @@ mod test { } /// Helper: do one measurement cycle at an angle. Returns (rssi_dbm, sample_count). - fn measure_at_angle( - rx: &mut MeasurementState, - rssi_samples: &[i32], - ) -> (f32, u16) { + fn measure_at_angle(rx: &mut MeasurementState, rssi_samples: &[i32]) -> (f32, u16) { let msg = route_expect(&PcCommand::StartMeasurement, Role::Rx); let resp = rx.handle_message(&msg, 0); assert!(resp.is_none()); @@ -1303,10 +1324,15 @@ mod test { } let msg = route_expect(&PcCommand::ReportMeasurement, Role::Rx); - let resp = rx.handle_message(&msg, 0).expect("should produce MeasurementResult"); + let resp = rx + .handle_message(&msg, 0) + .expect("should produce MeasurementResult"); let event = translate_response(&resp).expect("should translate"); match event { - DeviceEvent::Measurement { rssi_dbm, sample_count } => (rssi_dbm, sample_count), + DeviceEvent::Measurement { + rssi_dbm, + sample_count, + } => (rssi_dbm, sample_count), other => panic!("expected Measurement, got {:?}", other), } } diff --git a/software/protocol/src/tx_logic.rs b/software/protocol/src/tx_logic.rs index cefad30..bcdd7a9 100644 --- a/software/protocol/src/tx_logic.rs +++ b/software/protocol/src/tx_logic.rs @@ -31,9 +31,7 @@ impl TxState { pub fn handle_message(&mut self, msg: &EspnowMessage) -> Option { match msg { EspnowMessage::TxCmd(cmd) => match cmd { - TxCommand::Configure { - packet_rate_hz, .. - } => { + TxCommand::Configure { packet_rate_hz, .. } => { self.set_packet_rate(*packet_rate_hz); Some(EspnowMessage::TxResp(TxResponse::Ack)) } From 5ca0f953fe0597d384ed93650e8cbf34a0cf55e6 Mon Sep 17 00:00:00 2001 From: JuliDi Date: Fri, 13 Nov 2026 15:26:00 +0100 Subject: [PATCH 04/16] feat: Upgrade protocol and pc to edition 2024 --- software/pc/Cargo.toml | 2 +- software/pc/src/main.rs | 10 +++++----- software/pc/src/ota.rs | 4 ++-- software/pc/src/serial.rs | 4 ++-- software/pc/src/sim.rs | 4 ++-- software/pc/src/sweep.rs | 2 +- software/pc/tests/integration.rs | 2 +- software/protocol/Cargo.toml | 2 +- software/protocol/src/golden.rs | 10 ++++++++-- software/protocol/src/lib.rs | 12 ++++++------ 10 files changed, 29 insertions(+), 23 deletions(-) diff --git a/software/pc/Cargo.toml b/software/pc/Cargo.toml index cb1c545..6f40155 100644 --- a/software/pc/Cargo.toml +++ b/software/pc/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "beambench-pc" version = "0.1.0" -edition = "2021" +edition = "2024" default-run = "beambench-pc" [[bin]] diff --git a/software/pc/src/main.rs b/software/pc/src/main.rs index 2684887..f689791 100644 --- a/software/pc/src/main.rs +++ b/software/pc/src/main.rs @@ -1,24 +1,24 @@ //! Beambench PC application — Axum server with WebSocket and embedded frontend. -use std::sync::atomic::{AtomicBool, AtomicI32, AtomicU32, Ordering}; use std::sync::Arc; +use std::sync::atomic::{AtomicBool, AtomicI32, AtomicU32, Ordering}; use axum::{ + Router, extract::{ - ws::{Message, WebSocket, WebSocketUpgrade}, Multipart, State, + ws::{Message, WebSocket, WebSocketUpgrade}, }, response::{IntoResponse, Json}, routing::{get, post}, - Router, }; use clap::Parser; use rust_embed::Embed; -use tokio::sync::{broadcast, watch, Mutex}; +use tokio::sync::{Mutex, broadcast, watch}; use tracing::info; use beambench_pc::{ - export_csv, PortInfo, SystemStatus, WsCommand, WsEvent, DEFAULT_TRANSMISSION_RATIO, + DEFAULT_TRANSMISSION_RATIO, PortInfo, SystemStatus, WsCommand, WsEvent, export_csv, }; /// Initial delay before sending QueryStatus to a freshly-opened device. diff --git a/software/pc/src/ota.rs b/software/pc/src/ota.rs index 9bc5e72..ec26911 100644 --- a/software/pc/src/ota.rs +++ b/software/pc/src/ota.rs @@ -51,9 +51,9 @@ use std::sync::Arc; -use beambench_protocol::{DeviceEvent, PcCommand, Role, OTA_CHUNK_SIZE}; +use beambench_protocol::{DeviceEvent, OTA_CHUNK_SIZE, PcCommand, Role}; use sha2::{Digest, Sha256}; -use tokio::sync::{broadcast, mpsc, Mutex}; +use tokio::sync::{Mutex, broadcast, mpsc}; use crate::WsEvent; diff --git a/software/pc/src/serial.rs b/software/pc/src/serial.rs index f5c0037..340416d 100644 --- a/software/pc/src/serial.rs +++ b/software/pc/src/serial.rs @@ -2,9 +2,9 @@ use std::sync::Arc; -use beambench_protocol::{DecodeError, DeviceEvent, PcCommand, PROTOCOL_VERSION}; +use beambench_protocol::{DecodeError, DeviceEvent, PROTOCOL_VERSION, PcCommand}; use tokio::io::{AsyncReadExt, AsyncWriteExt}; -use tokio::sync::{mpsc, Mutex}; +use tokio::sync::{Mutex, mpsc}; use tokio_serial::SerialPortBuilderExt; use tracing::{debug, error, info, warn}; diff --git a/software/pc/src/sim.rs b/software/pc/src/sim.rs index ed47da3..ed763e9 100644 --- a/software/pc/src/sim.rs +++ b/software/pc/src/sim.rs @@ -11,8 +11,8 @@ use beambench_protocol::bridge_logic::{self, RouteAction}; use beambench_protocol::rx_logic::MeasurementState; use beambench_protocol::tx_logic::TxState; use beambench_protocol::{ - BackendInfo, DeviceEvent, EspnowMessage, PcCommand, Role, TurntableCommand, TurntableResponse, - MAX_MSG_SIZE, + BackendInfo, DeviceEvent, EspnowMessage, MAX_MSG_SIZE, PcCommand, Role, TurntableCommand, + TurntableResponse, }; use tokio::io::{AsyncReadExt, AsyncWriteExt}; use tokio::sync::mpsc; diff --git a/software/pc/src/sweep.rs b/software/pc/src/sweep.rs index 97879fe..d3531fc 100644 --- a/software/pc/src/sweep.rs +++ b/software/pc/src/sweep.rs @@ -8,7 +8,7 @@ use std::time::Duration; use crate::{DataPoint, SweepConfig, WsEvent}; use beambench_protocol::{DeviceEvent, PcCommand}; -use tokio::sync::{mpsc, Mutex}; +use tokio::sync::{Mutex, mpsc}; use tracing::{error, info}; /// Timeout for waiting on a turntable MoveComplete response. diff --git a/software/pc/tests/integration.rs b/software/pc/tests/integration.rs index 307ca51..5d9409e 100644 --- a/software/pc/tests/integration.rs +++ b/software/pc/tests/integration.rs @@ -7,7 +7,7 @@ //! Assumes the "sim" feature is activated use beambench_pc::sim; -use beambench_pc::{export_csv, SweepConfig, WsEvent}; +use beambench_pc::{SweepConfig, WsEvent, export_csv}; use tokio::sync::broadcast; #[tokio::test] diff --git a/software/protocol/Cargo.toml b/software/protocol/Cargo.toml index 93da21e..69f4c90 100644 --- a/software/protocol/Cargo.toml +++ b/software/protocol/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "beambench-protocol" version = "0.1.0" -edition = "2021" +edition = "2024" [features] default = [] diff --git a/software/protocol/src/golden.rs b/software/protocol/src/golden.rs index c264309..0e612b9 100644 --- a/software/protocol/src/golden.rs +++ b/software/protocol/src/golden.rs @@ -117,7 +117,10 @@ const PC_COMMAND_V1: &[(&str, &str)] = &[ ("StartMeasurement", "01 06"), ("ReportMeasurement", "01 07"), ("QueryStatus", "01 08"), - ("OtaBegin", "01 09 01 e8 07 ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab 04"), + ( + "OtaBegin", + "01 09 01 e8 07 ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab 04", + ), ("OtaData", "01 0a 00 ac 02 02 01 02"), ("OtaFinish", "01 0b 02"), ]; @@ -317,7 +320,10 @@ const ESPNOW_MESSAGE_V1: &[(&str, &str)] = &[ ("StartMeasurement", "01 07"), ("ReportMeasurement", "01 08"), ("MeasurementResult", "01 09 00 00 2a c2 0a"), - ("OtaBegin", "01 0a e8 07 ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab 04"), + ( + "OtaBegin", + "01 0a e8 07 ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab 04", + ), ("OtaReady", "01 0b"), ("OtaData", "01 0c ac 02 02 01 02"), ("OtaAck", "01 0d ac 02"), diff --git a/software/protocol/src/lib.rs b/software/protocol/src/lib.rs index 496d9d2..ac95a87 100644 --- a/software/protocol/src/lib.rs +++ b/software/protocol/src/lib.rs @@ -469,9 +469,9 @@ mod test { use serde::{Deserialize, Serialize}; use crate::{ - BackendInfo, DecodeError, DeviceEvent, EspnowMessage, HelloBeacon, PairConfirm, PcCommand, - PcToRx, PeerMismatch, Role, RxToPc, TurntableCommand, TurntableResponse, TxCommand, - TxResponse, MAX_MSG_SIZE, + BackendInfo, DecodeError, DeviceEvent, EspnowMessage, HelloBeacon, MAX_MSG_SIZE, + PairConfirm, PcCommand, PcToRx, PeerMismatch, Role, RxToPc, TurntableCommand, + TurntableResponse, TxCommand, TxResponse, }; /// Serialize `msg` into `buf` with postcard, then deserialize and assert equality. @@ -885,7 +885,7 @@ mod test { // ── Bridge routing tests ────────────────────────────────────────────── mod bridge_routing_tests { - use crate::bridge_logic::{route_command, translate_response, RouteAction}; + use crate::bridge_logic::{RouteAction, route_command, translate_response}; use crate::*; #[test] @@ -1148,8 +1148,8 @@ mod test { // ── RX measurement logic tests ─────────────────────────────────────── mod rx_logic_tests { - use crate::rx_logic::MeasurementState; use crate::EspnowMessage; + use crate::rx_logic::MeasurementState; #[test] fn initially_not_measuring() { @@ -1297,7 +1297,7 @@ mod test { // ── End-to-end measurement simulation ──────────────────────────────── mod measurement_simulation { - use crate::bridge_logic::{route_command, translate_response, RouteAction}; + use crate::bridge_logic::{RouteAction, route_command, translate_response}; use crate::rx_logic::MeasurementState; use crate::tx_logic::TxState; use crate::*; From b21a910fff0dc067e6924305e89f02f8da5dcac1 Mon Sep 17 00:00:00 2001 From: JuliDi Date: Fri, 13 Nov 2026 15:31:22 +0100 Subject: [PATCH 05/16] Fix clippy lints and add clippy recipes to justfiles --- justfile | 6 +++++ software/firmware/justfile | 10 +++++++++ software/firmware/src/bridge.rs | 11 ++++----- software/firmware/src/main.rs | 4 +++- software/firmware/src/measurement/mod.rs | 1 + software/firmware/src/measurement/uart.rs | 8 +++---- software/firmware/src/motor/mod.rs | 1 + software/firmware/src/motor/servo42c.rs | 13 +++++------ software/firmware/src/ota_responder.rs | 8 +++---- software/firmware/src/turntable.rs | 7 +++++- software/pc/justfile | 4 ++++ software/pc/src/ota.rs | 2 +- software/pc/src/sim.rs | 27 +++++++++-------------- software/protocol/justfile | 4 ++++ software/protocol/src/bridge_logic.rs | 1 + software/protocol/src/lib.rs | 1 + 16 files changed, 66 insertions(+), 42 deletions(-) diff --git a/justfile b/justfile index 1c71f57..2b3c24e 100644 --- a/justfile +++ b/justfile @@ -22,3 +22,9 @@ check: just software/protocol/check just software/firmware/check just software/pc/check + +# Lint all crates with clippy +clippy: + just software/protocol/clippy + just software/firmware/clippy + just software/pc/clippy diff --git a/software/firmware/justfile b/software/firmware/justfile index c61188e..fc27473 100644 --- a/software/firmware/justfile +++ b/software/firmware/justfile @@ -13,6 +13,16 @@ build: check: cargo check +# Lint all roles and backends with clippy, warnings are errors +clippy: + #!/usr/bin/env bash + set -euo pipefail + for features in "" role-bridge role-rx role-tx role-turntable \ + role-rx,backend-uart role-tx,backend-uart role-turntable,servo42c; do + echo "clippy: [$features]" + cargo clippy --release --features "$features" -- -D warnings + done + # Provision a board: builds with the role feature, flashes bootloader + # partition table + firmware via espflash. Use once per board. flash-rx: diff --git a/software/firmware/src/bridge.rs b/software/firmware/src/bridge.rs index 8ba66d6..4604b33 100644 --- a/software/firmware/src/bridge.rs +++ b/software/firmware/src/bridge.rs @@ -102,12 +102,9 @@ impl PeerTable { } fn role_for_mac(&self, mac: &[u8; 6]) -> Option { - for role in [Role::Rx, Role::Tx, Role::Turntable] { - if self.peer_for_role(role) == Some(*mac) { - return Some(role); - } - } - None + [Role::Rx, Role::Tx, Role::Turntable] + .into_iter() + .find(|&role| self.peer_for_role(role) == Some(*mac)) } fn all_connected(&self) -> bool { @@ -331,7 +328,7 @@ async fn bridge_discovery_task( for role in [Role::Rx, Role::Tx, Role::Turntable] { let stale = p .entry(role) - .map_or(false, |(_, t)| is_heartbeat_stale(Some(t))); + .is_some_and(|(_, t)| is_heartbeat_stale(Some(t))); if stale { if let Some(mac) = p.peer_for_role(role) { info!( diff --git a/software/firmware/src/main.rs b/software/firmware/src/main.rs index 0150e93..323fe86 100644 --- a/software/firmware/src/main.rs +++ b/software/firmware/src/main.rs @@ -45,7 +45,9 @@ type Led = #[defmt::panic_handler] fn defmt_panic() -> ! { - loop {} + loop { + core::hint::spin_loop(); + } } defmt::timestamp!(""); diff --git a/software/firmware/src/measurement/mod.rs b/software/firmware/src/measurement/mod.rs index fbe6b00..90ea9cd 100644 --- a/software/firmware/src/measurement/mod.rs +++ b/software/firmware/src/measurement/mod.rs @@ -4,6 +4,7 @@ //! The default backend is ESP-NOW RSSI; the `backend-uart` feature selects //! an external devboard connected over UART. +#[cfg(not(feature = "backend-uart"))] pub mod espnow; #[cfg(feature = "backend-uart")] pub mod uart; diff --git a/software/firmware/src/measurement/uart.rs b/software/firmware/src/measurement/uart.rs index 35e0bc4..4413517 100644 --- a/software/firmware/src/measurement/uart.rs +++ b/software/firmware/src/measurement/uart.rs @@ -169,10 +169,10 @@ fn parse_report(line: &str) -> MeasurementResult { if let Some(v) = parse_f32(val) { rssi_dbm = v; } - } else if let Some(val) = part.strip_prefix("N:") { - if let Some(v) = parse_u16(val) { - sample_count = v; - } + } else if let Some(val) = part.strip_prefix("N:") + && let Some(v) = parse_u16(val) + { + sample_count = v; } } diff --git a/software/firmware/src/motor/mod.rs b/software/firmware/src/motor/mod.rs index 3549731..77f7e4b 100644 --- a/software/firmware/src/motor/mod.rs +++ b/software/firmware/src/motor/mod.rs @@ -2,6 +2,7 @@ pub mod step_dir; #[cfg(feature = "servo42c")] +#[expect(dead_code, reason = "not wired into the turntable role yet")] pub mod servo42c; /// Position in microsteps from zero (signed). diff --git a/software/firmware/src/motor/servo42c.rs b/software/firmware/src/motor/servo42c.rs index 532fbf9..af40b86 100644 --- a/software/firmware/src/motor/servo42c.rs +++ b/software/firmware/src/motor/servo42c.rs @@ -64,13 +64,12 @@ impl Motor for Servo42cMotor<'_> { cmd_buf[..len].copy_from_slice(cmd); let mut resp = [0u8; 16]; - if let Ok(n) = self.transact(&cmd_buf[..len], &mut resp) { - if let Ok(r) = mks_servo42_rs::parse_success_response(&resp[..n]) { - if r.is_success() { - defmt::info!("Motor {}.", if enabled { "enabled" } else { "disabled" }); - return; - } - } + if let Ok(n) = self.transact(&cmd_buf[..len], &mut resp) + && let Ok(r) = mks_servo42_rs::parse_success_response(&resp[..n]) + && r.is_success() + { + defmt::info!("Motor {}.", if enabled { "enabled" } else { "disabled" }); + return; } defmt::warn!( "Failed to {} motor", diff --git a/software/firmware/src/ota_responder.rs b/software/firmware/src/ota_responder.rs index 0ad5a97..004acb6 100644 --- a/software/firmware/src/ota_responder.rs +++ b/software/firmware/src/ota_responder.rs @@ -135,7 +135,7 @@ async fn handle_begin( sha256: [u8; 32], ack_interval: u16, ) -> Option { - let total_chunks = ((total_size + CHUNK_SIZE - 1) / CHUNK_SIZE) as u16; + let total_chunks = total_size.div_ceil(CHUNK_SIZE) as u16; let ack_interval = ack_interval.max(1); // Ensure at least 1. info!( "OTA begin: {} bytes, {} chunks, ack every {} chunks", @@ -146,7 +146,7 @@ async fn handle_begin( // Read partition table to find the inactive OTA slot. let mut pt_buf = [0u8; partitions::PARTITION_TABLE_MAX_LEN]; - let pt = match partitions::read_partition_table(&mut *f, &mut pt_buf) { + let pt = match partitions::read_partition_table(&mut f, &mut pt_buf) { Ok(pt) => pt, Err(e) => { defmt::error!( @@ -278,7 +278,7 @@ async fn handle_data( // Windowed ack: only ack on interval boundaries and the last chunk. let chunk_num = seq + 1; // 1-based count let is_last = chunk_num >= session.total_chunks; - let is_interval = chunk_num % session.ack_interval == 0; + let is_interval = chunk_num.is_multiple_of(session.ack_interval); if is_interval || is_last { Some(EspnowMessage::OtaAck { seq }) } else { @@ -314,7 +314,7 @@ async fn handle_finish( let mut f = flash.lock().await; let mut pt_buf = [0u8; partitions::PARTITION_TABLE_MAX_LEN]; let mut updater = - match esp_bootloader_esp_idf::ota_updater::OtaUpdater::new(&mut *f, &mut pt_buf) { + match esp_bootloader_esp_idf::ota_updater::OtaUpdater::new(&mut f, &mut pt_buf) { Ok(u) => u, Err(e) => { defmt::error!("OtaUpdater init failed: {:?}", defmt::Debug2Format(&e)); diff --git a/software/firmware/src/turntable.rs b/software/firmware/src/turntable.rs index ca1d6a0..5189b29 100644 --- a/software/firmware/src/turntable.rs +++ b/software/firmware/src/turntable.rs @@ -1,5 +1,10 @@ //! Turntable role — motor controller receiving commands via ESPNOW. +#![expect( + clippy::too_many_arguments, + reason = "embassy tasks receive their static resources as arguments" +)] + use defmt::info; use embassy_executor::Spawner; use embassy_sync::{blocking_mutex::raw::NoopRawMutex, mutex::Mutex, signal::Signal}; @@ -160,7 +165,7 @@ async fn turntable_listener_task( Ok(EspnowMessage::TurntableCmd(cmd)) => { let is_bridge = { let mac = bridge_mac.lock().await; - mac.map_or(false, |m| m == src) + mac.is_some_and(|m| m == src) }; if is_bridge { *last_bridge_seen.lock().await = Some(Instant::now()); diff --git a/software/pc/justfile b/software/pc/justfile index fc7fffa..7c9cd35 100644 --- a/software/pc/justfile +++ b/software/pc/justfile @@ -33,6 +33,10 @@ sim: check: cargo check +# Lint Rust code with clippy, warnings are errors +clippy: + cargo clippy --all-targets --features sim -- -D warnings + # Run unit tests (lib only) test: cargo test --lib diff --git a/software/pc/src/ota.rs b/software/pc/src/ota.rs index ec26911..5e077d4 100644 --- a/software/pc/src/ota.rs +++ b/software/pc/src/ota.rs @@ -121,7 +121,7 @@ pub async fn stream_firmware( ws_tx: &broadcast::Sender, ) -> Result<(), String> { let total_size = firmware.len() as u32; - let total_chunks = (firmware.len() + OTA_CHUNK_SIZE - 1) / OTA_CHUNK_SIZE; + let total_chunks = firmware.len().div_ceil(OTA_CHUNK_SIZE); let ack_interval = ack_interval.max(1) as usize; // Compute SHA-256 before streaming so the target can verify at the end. diff --git a/software/pc/src/sim.rs b/software/pc/src/sim.rs index ed763e9..5a767fe 100644 --- a/software/pc/src/sim.rs +++ b/software/pc/src/sim.rs @@ -130,16 +130,12 @@ pub async fn cobs_reader(mut reader: impl AsyncReadExt + Unpin, tx: mpsc::Sender accum.extend_from_slice(&raw_buf[..n]); while let Some(zero_pos) = accum.iter().position(|&b| b == 0) { let frame = &accum[..zero_pos + 1]; - if frame.len() > 1 { - match beambench_protocol::deserialize_cobs::(&mut frame.to_vec()) - { - Ok(msg) => { - if tx.send(msg).await.is_err() { - return; - } - } - Err(_) => {} - } + if frame.len() > 1 + && let Ok(msg) = + beambench_protocol::deserialize_cobs::(&mut frame.to_vec()) + && tx.send(msg).await.is_err() + { + return; } accum = accum[zero_pos + 1..].to_vec(); } @@ -157,13 +153,10 @@ pub async fn cobs_writer( let mut buf = [0u8; MAX_MSG_SIZE]; while let Some(msg) = rx.recv().await { - match beambench_protocol::serialize_cobs(&msg, &mut buf) { - Ok(len) => { - if writer.write_all(&buf[..len]).await.is_err() { - return; - } - } - Err(_) => {} + if let Ok(len) = beambench_protocol::serialize_cobs(&msg, &mut buf) + && writer.write_all(&buf[..len]).await.is_err() + { + return; } } } diff --git a/software/protocol/justfile b/software/protocol/justfile index 275d55b..23f21b2 100644 --- a/software/protocol/justfile +++ b/software/protocol/justfile @@ -10,3 +10,7 @@ check: # Run tests test: cargo test + +# Lint with clippy, warnings are errors +clippy: + cargo clippy --all-targets --all-features -- -D warnings diff --git a/software/protocol/src/bridge_logic.rs b/software/protocol/src/bridge_logic.rs index b95b804..c891796 100644 --- a/software/protocol/src/bridge_logic.rs +++ b/software/protocol/src/bridge_logic.rs @@ -11,6 +11,7 @@ use crate::{ /// The result of routing a PcCommand: either an ESP-NOW message to send to a /// specific role, or a locally-handled event (e.g. QueryStatus). #[derive(Debug, Clone, PartialEq)] +#[expect(clippy::large_enum_variant, reason = "no_std without alloc; OTA chunks are inline")] pub enum RouteAction { /// Send this EspnowMessage to the given role. SendTo { role: Role, msg: EspnowMessage }, diff --git a/software/protocol/src/lib.rs b/software/protocol/src/lib.rs index ac95a87..85f77cb 100644 --- a/software/protocol/src/lib.rs +++ b/software/protocol/src/lib.rs @@ -228,6 +228,7 @@ pub enum EspnowMessage { /// to the appropriate field device by role. #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] +#[expect(clippy::large_enum_variant, reason = "no_std without alloc; OTA chunks are inline")] pub enum PcCommand { // TX control ConfigureTx { From 8224e4f5df81ebbd749d5c20fc0c55ea36fad570 Mon Sep 17 00:00:00 2001 From: JuliDi Date: Fri, 13 Nov 2026 15:32:29 +0100 Subject: [PATCH 06/16] Remove unused SERVO42C motor backend --- README.md | 2 +- software/firmware/Cargo.lock | 7 -- software/firmware/Cargo.toml | 3 - software/firmware/justfile | 2 +- software/firmware/src/motor/mod.rs | 4 - software/firmware/src/motor/servo42c.rs | 129 ------------------------ 6 files changed, 2 insertions(+), 145 deletions(-) delete mode 100644 software/firmware/src/motor/servo42c.rs diff --git a/README.md b/README.md index 9a7a440..26a590e 100644 --- a/README.md +++ b/README.md @@ -80,7 +80,7 @@ Once the boards are paired, follow-up firmware updates can be pushed wirelessly ## Hardware -Four **ESP32-C3-DevKit-RUST-1** boards plus a stepper-motor driver. Default driver is the **MKS SERVO42D** (step/dir); a UART variant (SERVO42C) is also supported. +Four **ESP32-C3-DevKit-RUST-1** boards plus a stepper-motor driver. The motor driver is the **MKS SERVO42D** (step/dir). **Step/Dir wiring (default):** diff --git a/software/firmware/Cargo.lock b/software/firmware/Cargo.lock index ae0d443..c9f9451 100644 --- a/software/firmware/Cargo.lock +++ b/software/firmware/Cargo.lock @@ -70,7 +70,6 @@ dependencies = [ "esp-rtos", "esp-storage", "heapless 0.9.3", - "mks-servo42-rs", "postcard", "rtt-target", "sha2", @@ -1599,12 +1598,6 @@ version = "2.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8ca58f447f06ed17d5fc4043ce1b10dd205e060fb3ce5b979b8ed8e59ff3f79" -[[package]] -name = "mks-servo42-rs" -version = "1.0.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2c4916d0d777efd8da5545dbbf9092a54f9da825f4426b758b44dcf0e60643f3" - [[package]] name = "nb" version = "0.1.3" diff --git a/software/firmware/Cargo.toml b/software/firmware/Cargo.toml index 93cf88e..105dace 100644 --- a/software/firmware/Cargo.toml +++ b/software/firmware/Cargo.toml @@ -18,7 +18,6 @@ backend-uart = [] # Motor backend for the turntable role. step-dir = [] -servo42c = ["dep:mks-servo42-rs"] [dependencies] beambench-protocol = { path = "../protocol", features = ["defmt"] } @@ -59,8 +58,6 @@ postcard = { version = "1", features = ["experimental-derive"] } heapless = "0.9.3" critical-section = "1.2.0" -# Motor backends (turntable role) -mks-servo42-rs = { version = "1.0.4", optional = true } sha2 = { version = "0.11.1", default-features = false } [profile.release] diff --git a/software/firmware/justfile b/software/firmware/justfile index fc27473..5b865b2 100644 --- a/software/firmware/justfile +++ b/software/firmware/justfile @@ -18,7 +18,7 @@ clippy: #!/usr/bin/env bash set -euo pipefail for features in "" role-bridge role-rx role-tx role-turntable \ - role-rx,backend-uart role-tx,backend-uart role-turntable,servo42c; do + role-rx,backend-uart role-tx,backend-uart; do echo "clippy: [$features]" cargo clippy --release --features "$features" -- -D warnings done diff --git a/software/firmware/src/motor/mod.rs b/software/firmware/src/motor/mod.rs index 77f7e4b..3a6ca7c 100644 --- a/software/firmware/src/motor/mod.rs +++ b/software/firmware/src/motor/mod.rs @@ -1,10 +1,6 @@ #[allow(dead_code)] pub mod step_dir; -#[cfg(feature = "servo42c")] -#[expect(dead_code, reason = "not wired into the turntable role yet")] -pub mod servo42c; - /// Position in microsteps from zero (signed). pub type Position = i32; diff --git a/software/firmware/src/motor/servo42c.rs b/software/firmware/src/motor/servo42c.rs deleted file mode 100644 index af40b86..0000000 --- a/software/firmware/src/motor/servo42c.rs +++ /dev/null @@ -1,129 +0,0 @@ -use embedded_io::Write; -use esp_hal::{Blocking, delay::Delay, uart::Uart}; -use mks_servo42_rs::{self, Driver, RotationDirection}; - -use super::{Motor, MotorError, Position}; - -/// Default UART read timeout in milliseconds. -const READ_TIMEOUT_MS: u32 = 100; - -/// Motor speed for go_to moves (0..=127). -const MOVE_SPEED: u8 = 50; - -/// Maximum command size in the mks-servo42-rs protocol. -const MAX_CMD_LEN: usize = 16; - -pub struct Servo42cMotor<'a> { - driver: Driver, - uart: Uart<'a, Blocking>, - delay: Delay, -} - -impl<'a> Servo42cMotor<'a> { - pub fn new(uart: Uart<'a, Blocking>, delay: Delay) -> Self { - Self { - driver: Driver::default(), - uart, - delay, - } - } - - /// Write a command and read the response into `buf`. - /// Returns the number of bytes read. - fn transact(&mut self, cmd: &[u8], buf: &mut [u8]) -> Result { - self.uart - .write_all(cmd) - .map_err(|_| MotorError::Communication)?; - self.uart.flush().map_err(|_| MotorError::Communication)?; - - // Give the motor time to respond. - self.delay.delay_millis(READ_TIMEOUT_MS); - - let n = self.uart.read(buf).map_err(|_| MotorError::Communication)?; - Ok(n) - } - - fn read_pulse_count(&mut self) -> Result { - let mut cmd_buf = [0u8; MAX_CMD_LEN]; - let cmd = self.driver.read_pulse_count(); - let len = cmd.len(); - cmd_buf[..len].copy_from_slice(cmd); - - let mut resp = [0u8; 16]; - let n = self.transact(&cmd_buf[..len], &mut resp)?; - mks_servo42_rs::parse_pulse_count_response(&resp[..n]) - .map_err(|_| MotorError::Communication) - } -} - -impl Motor for Servo42cMotor<'_> { - fn set_enabled(&mut self, enabled: bool) { - let mut cmd_buf = [0u8; MAX_CMD_LEN]; - let cmd = self.driver.enable_motor(enabled); - let len = cmd.len(); - cmd_buf[..len].copy_from_slice(cmd); - - let mut resp = [0u8; 16]; - if let Ok(n) = self.transact(&cmd_buf[..len], &mut resp) - && let Ok(r) = mks_servo42_rs::parse_success_response(&resp[..n]) - && r.is_success() - { - defmt::info!("Motor {}.", if enabled { "enabled" } else { "disabled" }); - return; - } - defmt::warn!( - "Failed to {} motor", - if enabled { "enable" } else { "disable" } - ); - } - - fn go_to(&mut self, target: Position) -> Result { - let current = self.read_pulse_count()?; - let delta = target - current; - - if delta == 0 { - return Ok(current); - } - - let direction = if delta > 0 { - RotationDirection::Clockwise - } else { - RotationDirection::CounterClockwise - }; - let pulses = delta.unsigned_abs(); - - let mut cmd_buf = [0u8; MAX_CMD_LEN]; - let cmd = self - .driver - .run_motor(direction, MOVE_SPEED, pulses) - .map_err(|_| MotorError::OutOfRange)?; - let len = cmd.len(); - cmd_buf[..len].copy_from_slice(cmd); - - let mut resp = [0u8; 16]; - self.transact(&cmd_buf[..len], &mut resp)?; - - // Poll until motion is complete. - loop { - self.delay.delay_millis(50); - let pos = self.read_pulse_count()?; - if (pos - target).unsigned_abs() < 10 { - return Ok(pos); - } - } - } - - fn stop(&mut self) { - let mut cmd_buf = [0u8; MAX_CMD_LEN]; - let cmd = self.driver.stop(); - let len = cmd.len(); - cmd_buf[..len].copy_from_slice(cmd); - - let mut resp = [0u8; 16]; - let _ = self.transact(&cmd_buf[..len], &mut resp); - } - - fn position(&mut self) -> Result { - self.read_pulse_count() - } -} From ee03c15bb3f5fb9fd825a1e0801673dc184a17ef Mon Sep 17 00:00:00 2001 From: JuliDi Date: Fri, 13 Nov 2026 15:55:52 +0100 Subject: [PATCH 07/16] CI for protocol, firmware and PC app --- .github/workflows/ci.yml | 67 ++++++++++++++++++++++-- software/firmware/.cargo/config.toml | 3 -- software/pc/frontend/eslint.config.js | 7 ++- software/pc/frontend/package.json | 1 + software/pc/frontend/pnpm-workspace.yaml | 2 +- software/pc/frontend/src/plotly.d.ts | 2 + software/protocol/src/bridge_logic.rs | 5 +- software/protocol/src/lib.rs | 5 +- 8 files changed, 82 insertions(+), 10 deletions(-) create mode 100644 software/pc/frontend/src/plotly.d.ts diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index b59c47e..9bebcf3 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -5,18 +5,79 @@ on: branches: [main] pull_request: +env: + CARGO_TERM_COLOR: always + jobs: - ts-bindings: - name: TypeScript bindings up to date + protocol: + name: Protocol + runs-on: ubuntu-latest + defaults: + run: + working-directory: software/protocol + steps: + - uses: actions/checkout@v4 + # Installs the toolchain pinned in rust-toolchain.toml. + - run: rustup toolchain install + - uses: Swatinem/rust-cache@v2 + with: + workspaces: software/protocol + - uses: taiki-e/install-action@just + - run: cargo fmt --check + - run: just clippy + - run: just test + + firmware: + name: Firmware + runs-on: ubuntu-latest + defaults: + run: + working-directory: software/firmware + steps: + - uses: actions/checkout@v4 + - run: rustup toolchain install + - uses: Swatinem/rust-cache@v2 + with: + workspaces: software/firmware + - uses: taiki-e/install-action@just + - run: cargo fmt --check + # Covers all roles and backends. + - run: just clippy + - run: just build + + pc: + name: PC app runs-on: ubuntu-latest defaults: run: working-directory: software/pc steps: - uses: actions/checkout@v4 - - uses: dtolnay/rust-toolchain@stable + - uses: pnpm/action-setup@v4 + with: + version: 12.18.0 + - uses: actions/setup-node@v4 + with: + node-version: lts/* + cache: pnpm + cache-dependency-path: software/pc/frontend/pnpm-lock.yaml + - run: rustup toolchain install - uses: Swatinem/rust-cache@v2 with: workspaces: software/pc - uses: taiki-e/install-action@just + + - name: Frontend + working-directory: software/pc/frontend + run: | + pnpm install --frozen-lockfile + pnpm run format:check + pnpm run lint + pnpm run check + pnpm run build + + # The backend embeds frontend/build, so it runs after the frontend build. + - run: cargo fmt --check + - run: just clippy + - run: just test-all - run: just check-types diff --git a/software/firmware/.cargo/config.toml b/software/firmware/.cargo/config.toml index b41f78b..d0f47d4 100644 --- a/software/firmware/.cargo/config.toml +++ b/software/firmware/.cargo/config.toml @@ -6,9 +6,6 @@ rustflags = [ "-C", "link-arg=-Tlinkall.x", ] -[unstable] -build-std = ["core", "alloc"] - [target.riscv32imc-unknown-none-elf] runner = "probe-rs run --chip esp32c3 --always-print-stacktrace" diff --git a/software/pc/frontend/eslint.config.js b/software/pc/frontend/eslint.config.js index 7399f66..8a91609 100644 --- a/software/pc/frontend/eslint.config.js +++ b/software/pc/frontend/eslint.config.js @@ -43,6 +43,11 @@ export default ts.config( } }, { - ignores: ['.svelte-kit/**', 'build/**', 'node_modules/**', 'src/lib/bindings.ts'] + ignores: [ + '.svelte-kit/**', + 'build/**', + 'node_modules/**', + 'src/lib/bindings.ts' + ] } ); diff --git a/software/pc/frontend/package.json b/software/pc/frontend/package.json index 1212060..17ae7b8 100644 --- a/software/pc/frontend/package.json +++ b/software/pc/frontend/package.json @@ -11,6 +11,7 @@ "check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json", "check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch", "format": "./node_modules/prettier/bin/prettier.cjs --write .", + "format:check": "./node_modules/prettier/bin/prettier.cjs --check .", "lint": "eslint ." }, "devDependencies": { diff --git a/software/pc/frontend/pnpm-workspace.yaml b/software/pc/frontend/pnpm-workspace.yaml index 5ed0b5a..daf11c4 100644 --- a/software/pc/frontend/pnpm-workspace.yaml +++ b/software/pc/frontend/pnpm-workspace.yaml @@ -1,2 +1,2 @@ allowBuilds: - esbuild: true + esbuild: true diff --git a/software/pc/frontend/src/plotly.d.ts b/software/pc/frontend/src/plotly.d.ts new file mode 100644 index 0000000..b66defc --- /dev/null +++ b/software/pc/frontend/src/plotly.d.ts @@ -0,0 +1,2 @@ +// plotly.js-dist-min ships without type declarations. +declare module 'plotly.js-dist-min'; diff --git a/software/protocol/src/bridge_logic.rs b/software/protocol/src/bridge_logic.rs index c891796..64a6a36 100644 --- a/software/protocol/src/bridge_logic.rs +++ b/software/protocol/src/bridge_logic.rs @@ -11,7 +11,10 @@ use crate::{ /// The result of routing a PcCommand: either an ESP-NOW message to send to a /// specific role, or a locally-handled event (e.g. QueryStatus). #[derive(Debug, Clone, PartialEq)] -#[expect(clippy::large_enum_variant, reason = "no_std without alloc; OTA chunks are inline")] +#[expect( + clippy::large_enum_variant, + reason = "no_std without alloc; OTA chunks are inline" +)] pub enum RouteAction { /// Send this EspnowMessage to the given role. SendTo { role: Role, msg: EspnowMessage }, diff --git a/software/protocol/src/lib.rs b/software/protocol/src/lib.rs index 85f77cb..07e92c5 100644 --- a/software/protocol/src/lib.rs +++ b/software/protocol/src/lib.rs @@ -228,7 +228,10 @@ pub enum EspnowMessage { /// to the appropriate field device by role. #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] -#[expect(clippy::large_enum_variant, reason = "no_std without alloc; OTA chunks are inline")] +#[expect( + clippy::large_enum_variant, + reason = "no_std without alloc; OTA chunks are inline" +)] pub enum PcCommand { // TX control ConfigureTx { From f1b7158eda8078285765d3afc11b49820870e03e Mon Sep 17 00:00:00 2001 From: JuliDi Date: Fri, 13 Nov 2026 15:55:58 +0100 Subject: [PATCH 08/16] Update README.md --- README.md | 137 ++++++++++++++++++++++++------------------------------ 1 file changed, 62 insertions(+), 75 deletions(-) diff --git a/README.md b/README.md index 26a590e..8b86dd5 100644 --- a/README.md +++ b/README.md @@ -1,109 +1,96 @@ -# Beambench — Open-Source Antenna Pattern Measurement +# Beambench -Build a desktop antenna-measurement rig out of four ESP32-C3 boards and a motorised turntable. Beambench rotates the antenna under test, measures how strongly a radio signal arrives at each angle, and plots the result live in your browser as a **polar diagram** — so you can actually *see* in which directions an antenna sends or receives best. +Antenna pattern measurement with four ESP32-C3 boards and a turntable. +Firmware, backend and protocol are written in Rust; the UI is Svelte. -Hardware, firmware, and the PC app are all open source. +> **Proof of concept.** Written with [Claude Code](https://claude.com/claude-code), not yet reviewed. -> ⚠️ **Disclaimer — proof of concept** -> -> This entire project was written with [Claude Code](https://claude.com/claude-code) and has **not yet undergone any proper code review**. It exists purely as a proof of concept for demo purposes. Do not rely on it for anything that matters — expect rough edges, missing validation, and untested corners. +![Beambench UI: polar plot of a sweep](docs/ui_screenshot.png) -## Screenshot - -![Beambench UI — live polar plot of a completed sweep](docs/ui_screenshot.png) - -## How it works - -The antenna under test sits on a motorised turntable. A **TX** board sends short radio packets; an **RX** board measures the signal strength of those packets. A **Turntable** board rotates the motor through 360° in small steps, and a **Bridge** board hooks the whole thing up to the PC over USB. The browser UI plots the result as it comes in — angle = direction, distance from the centre = signal strength. +## Architecture ``` - ┌──────────────────────────┐ - │ PC — Browser UI │ - └─────────────┬────────────┘ - │ USB-serial - ┌─────────────┴────────────┐ - │ ESP32-C3 — Bridge │ - └─────────────┬────────────┘ - │ - │ ESP-NOW (2.4 GHz) - │ - ┌────────────────────────┼────────────────────────┐ - │ │ │ - ┌────────┴─────────┐ ┌─────────┴────────┐ ┌──────────┴────────┐ - │ ESP32-C3 — TX │ │ ESP32-C3 — RX │ │ ESP32-C3 — │ - │ on turntable, │ │ fixed position, │ │ Turntable — │ - │ antenna under │ │ reference ant., │ │ drives the │ - │ test, battery │ │ measures signal │ │ stepper motor │ - └──────────────────┘ └──────────────────┘ └───────────────────┘ - │ ▲ - │ radio signal under │ - └────── measurement ─────┘ + PC: Axum backend + browser UI + │ USB-serial (COBS + postcard) + ESP32-C3: Bridge + │ ESP-NOW (postcard) + ┌────────────────┼────────────────┐ + ESP32-C3: TX ESP32-C3: RX ESP32-C3: Turntable + antenna under measures RSSI drives the + test, rotates stepper motor ``` -## Repository layout +The turntable rotates the TX antenna. The RX measures the RSSI of TX beacons at each angle. -``` -software/ -├── protocol/ Shared no_std message types (postcard + serde) -├── firmware/ Unified ESP32-C3 firmware; role chosen via Cargo feature -└── pc/ PC app — Axum backend + Svelte frontend with Plotly polar plot -``` +## Repository -The firmware is **one crate with feature flags** (`role-bridge`, `role-tx`, `role-rx`, `role-turntable`). Every board flashes the same code; only the feature changes. +| Path | Content | +|---|---| +| `software/protocol` | Shared `no_std` message types and routing logic | +| `software/firmware` | One firmware for all boards; role via Cargo feature | +| `software/pc` | Axum backend, Svelte frontend, bridge simulator | -### Protocol layers +## Protocol -- **PC ↔ Bridge:** COBS-framed [postcard](https://docs.rs/postcard) over USB-serial (or TCP for the simulator) -- **Bridge ↔ TX/RX/Turntable:** postcard-serialised messages over ESP-NOW +- Every frame starts with `PROTOCOL_VERSION`. Frames of another version are not decoded, only reported. +- Golden-bytes tests in `protocol/src/golden.rs` pin the wire layout of every message. +- The bridge simulator runs the same `bridge_logic`, `tx_logic` and `rx_logic` as the firmware. -## Quick start +## Requirements -Requires Rust nightly and [probe-rs](https://probe.rs/) for flashing. +- Rust toolchain from `rust-toolchain.toml`, installed automatically by `rustup` +- [`just`](https://github.com/casey/just), [`pnpm`](https://pnpm.io) +- [`espflash`](https://github.com/esp-rs/espflash) for flashing, [`probe-rs`](https://probe.rs) for defmt logs + +## Usage + +Without hardware: ```sh -# Try it with no hardware: bridge simulator + dev server -just sim # in one shell -cd software/pc && just dev # in another → http://localhost:5173 +cd software/pc +just sim # bridge simulator on 127.0.0.1:9876 +just dev # backend + UI on http://localhost:5173 ``` -For real hardware, flash one role per board: +Flash a board. This writes its role to flash once: ```sh cd software/firmware -cargo run --release --no-default-features --features role-bridge -cargo run --release --no-default-features --features role-tx -cargo run --release --no-default-features --features role-rx -cargo run --release --no-default-features --features role-turntable +just flash-bridge # or flash-tx, flash-rx, flash-turntable +just monitor # defmt logs via probe-rs ``` -Once the boards are paired, follow-up firmware updates can be pushed wirelessly with `just ota-`. +Update paired boards over the air (PC app must be running): -## Hardware +```sh +just ota-tx # or ota-rx, ota-turntable +``` -Four **ESP32-C3-DevKit-RUST-1** boards plus a stepper-motor driver. The motor driver is the **MKS SERVO42D** (step/dir). +## Development -**Step/Dir wiring (default):** +```sh +just test # protocol and PC tests +just clippy # all crates, all roles, warnings are errors +just check +``` -| ESP32-C3 | SERVO42D | Function | -|----------|----------|----------| -| 3.3 V | COM | Common anode | -| GPIO4 | STP | Step pulse | -| GPIO5 | DIR | Direction | -| GPIO6 | EN | Enable (active low) | -| GND | GND | Ground | -| — | V+ | 12–24 V supply | +CI runs formatting, clippy, tests and the firmware build for all crates, plus lint, type check and build of the frontend. -Motor: 200 full steps × 16 microsteps = 3200 steps/revolution (≈ 0.1125°/step). The motor-to-turntable gear ratio is configurable in the UI (default 1:3). +## Hardware -## Testing +- 4× ESP32-C3-DevKit-RUST-1 +- MKS SERVO42D stepper driver (step/dir), 12–24 V supply -```sh -just test # all host-side tests -cd software/pc && cargo test --features sim # PC unit + integration suite -``` +| ESP32-C3 | SERVO42D | Function | +|---|---|---| +| 3.3 V | COM | Common anode | +| GPIO7 | STP | Step | +| GPIO8 | DIR | Direction | +| GPIO6 | EN | Enable, active low | +| GND | GND | Ground | -The integration suite spins up an in-process **bridge simulator** that generates synthetic cardioid RSSI data — useful for testing the whole pipeline without flashing anything. +3200 microsteps per revolution. Motor-to-turntable ratio is set in the UI (default 3). ## License -Released under the [MIT License](LICENSE). © 2026 Systemscape GmbH. +[MIT](LICENSE). © 2026 Systemscape GmbH. From 7619603f51fd25ead5536640448b84ffd16529fc Mon Sep 17 00:00:00 2001 From: JuliDi Date: Fri, 13 Nov 2026 15:59:51 +0100 Subject: [PATCH 09/16] Update architecture-v2.md --- docs/architecture-v2.md | 365 +++++++++------------------------------- 1 file changed, 81 insertions(+), 284 deletions(-) diff --git a/docs/architecture-v2.md b/docs/architecture-v2.md index 2d322a4..d585748 100644 --- a/docs/architecture-v2.md +++ b/docs/architecture-v2.md @@ -1,322 +1,119 @@ -# Beambench Architecture v2 +# Beambench Architecture -## Overview - -This document describes the planned architecture changes to beambench: - -1. **Bridge-based topology** — a dedicated USB-connected ESP32-C3 relays between PC and wireless field devices -2. **PC-driven orchestration** — all campaign planning and sweep control lives on the PC; field devices only execute commands -3. **Unified firmware** — a single binary for all ESP32-C3 devices, with role stored in flash -4. **ESP-NOW OTA** — over-the-air firmware updates pushed from PC through the Bridge - -## Device Topology +## Topology ``` PC (Axum + Svelte) - | USB-serial (COBS) + | USB-serial: COBS + postcard Bridge (ESP32-C3, USB powered) - | ESP-NOW - +-------+-------+ - | | | - RX Stepper TX -(battery) (mains) (battery) + | ESP-NOW: postcard + +--------+-----------+ + | | | + TX RX Turntable ``` -- **Bridge**: serial-to-ESP-NOW relay. Receives COBS-framed commands from the PC, routes them to the addressed device via ESP-NOW, and forwards responses back over serial. -- **RX**: measures RSSI (or other RF metrics) from TX packets. Accumulates samples passively, reports on demand. -- **TX**: transmits `MeasurementBeacon` packets at a configured rate when told to. -- **Stepper**: moves the turntable to commanded positions, reports completion. - -All field devices (RX, TX, Stepper) are passive — they act only when instructed by the PC via the Bridge. The Bridge itself has no orchestration logic. - -**Exception — MeasurementBeacon**: TX broadcasts `MeasurementBeacon` packets directly via ESP-NOW broadcast (not routed through the Bridge). RX receives these over the air and reads `rx_control.rssi` from the direct TX->RX RF path. This is the only device-to-device communication that bypasses the Bridge. Broadcast means no MAC-level ACK, but packet loss is acceptable since RSSI samples are averaged. Bridge and Stepper receive these packets too but ignore them. +| Device | Job | +|---|---| +| PC | Plans and runs sweeps, stores data, serves the UI | +| Bridge | Relays between serial and ESP-NOW, routes by role, no sweep logic | +| TX | Broadcasts `MeasurementBeacon` at a configured rate while transmitting | +| RX | Averages the RSSI of beacons between `StartMeasurement` and `ReportMeasurement` | +| Turntable | Moves the step/dir motor to an angle, replies `MoveComplete` | ---- +Field devices only act on commands from the Bridge. +Exception: TX beacons go by ESP-NOW broadcast directly to RX. They are not acknowledged; losses only reduce the sample count. -## Phase 1: Unified Firmware + Role Provisioning +## Crates -### Goal +| Crate | Content | +|---|---| +| `protocol` | `no_std` message types, serialization, `bridge_logic`, `tx_logic`, `rx_logic` | +| `firmware` | One binary for all roles | +| `pc` | Backend, frontend, bridge simulator (`--features sim`) | -Replace the four separate firmware crates (`rx`, `tx`, `stepper`, and the new `bridge`) with a single crate. Each physical device reads its role from a dedicated flash region. +The routing and state machines in `protocol` run on the firmware and in the simulator. -### Role Storage +## Protocol -- A custom partition `role` (type `data`, subtype `nvs` or raw, 4 KB) in the partition table -- Stores a single `Role` enum value: `Bridge`, `Rx`, `Tx`, `Stepper` -- The `Role` enum must use explicit stable discriminants (`#[repr(u8)]` with fixed values) so that the stored byte survives firmware updates that might reorder or add variants -- Read at boot before any peripherals are initialized - -### Cargo Features for Provisioning - -``` -[features] -role-bridge = [] -role-rx = [] -role-tx = [] -role-stepper = [] -``` +| Link | Types | Framing | +|---|---|---| +| PC → Bridge | `PcCommand` | COBS + postcard | +| Bridge → PC | `DeviceEvent` | COBS + postcard | +| Bridge ↔ field devices | `EspnowMessage` | postcard in one ESP-NOW frame (≤ 250 bytes) | -- **Feature set** (e.g. `--features role-tx`): firmware writes that role to the flash partition at boot, then proceeds to run as that role. This is the provisioning step — done once per device (or to re-provision). -- **No feature set**: firmware reads the role from flash. If the partition is empty/invalid, the device panics with a defmt error message indicating it needs provisioning. -- At most one `role-*` feature may be active (enforced with a compile-time check). +`bridge_logic::route_command` maps a `PcCommand` to a target role and an `EspnowMessage`, or handles it locally (`QueryStatus`). +`bridge_logic::translate_response` maps the reply back to a `DeviceEvent`. -### Runtime Dispatch - -After role resolution, the firmware branches into the role-specific task set: - -```rust -match role { - Role::Bridge => bridge::run(spawner, ...).await, - Role::Rx => rx::run(spawner, ...).await, - Role::Tx => tx::run(spawner, ...).await, - Role::Stepper => stepper::run(spawner, ...).await, -} -``` - -Each `run()` function spawns the Embassy tasks for that role. Shared code (ESP-NOW init, discovery, LED control, heartbeat) lives in common modules. - -### Justfile Targets - -``` -just flash-rx # cargo run --features role-rx -just flash-tx # cargo run --features role-tx -just flash-stepper # cargo run --features role-stepper -just flash-bridge # cargo run --features role-bridge -just flash # cargo run (no feature = use stored role) -``` +### Versioning ---- +- Every frame starts with `PROTOCOL_VERSION` (`u16`, varint). +- Receivers read only this header first. Frames of another version are not decoded. +- The Bridge reports boards with another version in `DeviceEvent::Status { mismatched_peers }`. +- The PC reports a Bridge with another version as an error. +- `protocol/src/golden.rs` pins the bytes of every variant. A layout change fails the test; then bump `PROTOCOL_VERSION`. -## Phase 2: Bridge + PC Orchestration +## Firmware -### Bridge Firmware +### Roles -The Bridge is a transparent relay with two jobs: +The role is stored in the `role` partition at `0xF000` (4 bytes magic, 1 byte role). -1. **Serial -> ESP-NOW**: Decode COBS frames from USB-serial, deserialize `PcCommand`, look up the target device's MAC from the discovery table, serialize the inner command as an `EspnowMessage`, and send via ESP-NOW. -2. **ESP-NOW -> Serial**: Receive `EspnowMessage` from any paired device, wrap it as a `DeviceEvent`, COBS-encode, and send over USB-serial. +- Built with `role-`: writes this role at boot, then runs it. Used once per board (`just flash-`). +- Built without a role feature: reads the role from flash. Panics if none is stored. +- At most one `role-*` feature is allowed (`compile_error!`). +- `Role` has fixed `#[repr(u8)]` discriminants, so the stored byte stays valid across updates. -The Bridge maintains an auto-discovery table mapping `Role -> MAC` (one device per role). It pairs with field devices using the existing `Hello`/`PairConfirm` beacon protocol. +`main.rs` dispatches to `bridge::run`, `rx::run`, `tx::run` or `turntable::run`. Each spawns its Embassy tasks. -### Protocol Changes +### Features -#### Serial Protocol (PC <-> Bridge) +| Feature | Effect | +|---|---| +| `role-bridge`, `role-rx`, `role-tx`, `role-turntable` | Provision this role | +| `step-dir` (default) | Step/dir motor backend for the turntable | +| `backend-uart` | RX/TX measure via an external board on UART instead of ESP-NOW RSSI | -The current `PcToRx` / `RxToPc` enums are replaced with role-addressed messages: +### Discovery and heartbeat -```rust -/// PC -> Bridge (serial) -enum PcCommand { - // TX control - ConfigureTx { channel: u8, tx_power_dbm: i8, packet_rate_hz: u16 }, - StartTransmitting, - StopTransmitting, +- Devices broadcast `Hello { role, mac }` every second until paired, then every 10 s as heartbeat. +- The Bridge stores one MAC per role and answers with `PairConfirm`. +- Peers not heard from for 15 s are dropped, on both sides. - // Stepper control - MoveTo { angle_deg: f32 }, - StopStepper, - ReturnHome, +### Partition table - // RX control - StartMeasurement, - ReportMeasurement, - - // System - QueryStatus, - /// Initiate OTA update for a target role (Phase 3) - OtaBegin { target: Role, total_size: u32, sha256: [u8; 32] }, - OtaData { seq: u16, chunk: Vec }, // heapless on firmware side - OtaFinish, -} - -/// Bridge -> PC (serial) -enum DeviceEvent { - // TX responses - TxAck, - TxStatus { transmitting: bool, channel: u8, tx_power_dbm: i8, packet_rate_hz: u16 }, - - // Stepper responses - MoveComplete { angle_deg: f32 }, - StepperError { description: String<64> }, - HomeComplete, - - // RX responses - Measurement { rssi_dbm: f32, sample_count: u16 }, - - // System - Status { tx_connected: bool, rx_connected: bool, stepper_connected: bool }, - Error { description: String<128> }, -} ``` - -The Bridge translates between these serial messages and the existing `EspnowMessage` variants, routing by role. - -#### ESP-NOW Protocol Changes - -Add a new message variant for measurement beacons and RX measurement commands: - -```rust -enum EspnowMessage { - // Existing - Hello(HelloBeacon), - PairConfirm(PairConfirm), - TurntableCmd(TurntableCommand), - TurntableResp(TurntableResponse), - TxCmd(TxCommand), - TxResp(TxResponse), - - // New - /// Sent by TX at configured rate. RX accumulates RSSI from these - /// only when actively measuring. - MeasurementBeacon, - /// Bridge -> RX: reset accumulator and start collecting. - StartMeasurement, - /// Bridge -> RX: stop collecting, report result. - ReportMeasurement, - /// RX -> Bridge: measurement result. - MeasurementResult { rssi_dbm: f32, sample_count: u16 }, -} +# Name, Type, SubType, Offset, Size +nvs, data, nvs, 0x9000, 0x6000 +role, data, phy, 0xf000, 0x1000 +otadata, data, ota, 0x10000, 0x2000 +ota_0, app, ota_0, 0x20000, 0x1C0000 +ota_1, app, ota_1, 0x1E0000, 0x1C0000 ``` -### Sweep Orchestration (PC Side) - -The PC app replaces the current `SweepStateMachine` (which sent a single `StartSweep` to RX) with a step-by-step orchestrator: +## Sweep (PC) ``` -1. PC -> Bridge -> TX: ConfigureTx { ... } -2. PC -> Bridge -> TX: StartTransmit -3. for each angle: - a. PC -> Bridge -> Stepper: MoveTo { angle_deg } - b. wait for MoveComplete - c. settling delay (configurable) - d. PC -> Bridge -> RX: StartMeasurement (resets accumulator, starts collecting) - e. measurement window (configurable) - f. PC -> Bridge -> RX: ReportMeasurement (returns result, stops collecting) - g. record data point -4. PC -> Bridge -> TX: StopTransmit -5. PC -> Bridge -> Stepper: ReturnHome -6. wait for HomeComplete +1. StartTransmitting wait up to 2 s for TxAck +2. per angle: + a. MoveTo { angle_deg } wait for MoveComplete (30 s timeout) + b. settle 200 ms + c. StartMeasurement + d. measurement window + e. ReportMeasurement wait for Measurement (5 s timeout) +3. StopTransmitting ``` -RX ignores `MeasurementBeacon` packets except between `StartMeasurement` and `ReportMeasurement`, ensuring a clean measurement window with no stale data from rotation. - -This gives the PC full control over timing. During steps 3a-3f, the PC ensures no other ESP-NOW commands are in flight (the Bridge sends one command at a time and waits for the response before accepting the next). - -### RX Firmware (Simplified) - -RX's responsibilities shrink to: - -- On `StartMeasurement` from Bridge: reset RSSI accumulator and begin collecting from `MeasurementBeacon` packets (ignored at all other times) -- On `ReportMeasurement` from Bridge: compute average, reply with `MeasurementResult`, stop collecting -- Discovery beacons (shared code) - -No serial handling, no sweep state machine, no turntable control. +The PC sends one command at a time and waits for its reply. +`ConfigureTx` and `ReturnHome` are separate UI commands. -### Discovery +## OTA -All field devices broadcast `Hello { role, mac }` beacons periodically until paired. The Bridge listens for these and builds its role -> MAC table, sending `PairConfirm` to each. The PC can query connection status via `QueryStatus`. +The PC streams the image through the Bridge to one field device. -Heartbeat-based disconnect detection (already implemented for TX) is generalized: the Bridge periodically pings each paired device, and devices unpair from the Bridge if they haven't heard from it within a timeout. - ---- - -## Phase 3: ESP-NOW OTA - -### Partition Table - -All devices use a shared partition table with dual OTA slots: - -``` -# Name, Type, SubType, Offset, Size -nvs, data, nvs, 0x9000, 0x6000 -role, data, nvs, 0xf000, 0x1000 -otadata, data, ota, 0x10000, 0x2000 -ota_0, app, ota_0, 0x20000, 0x1C0000 -ota_1, app, ota_1, 0x1E0000,0x1C0000 -``` - -Each OTA slot is ~1.75 MB, sufficient for the unified binary. - -### OTA Protocol - -The OTA flow is modeled after [Espressif's ESP-NOW OTA example](https://components.espressif.com/components/espressif/esp-now/versions/2.1.1/examples/ota), adapted for the Rust/esp-hal stack: - -#### Initiator (Bridge, commanded by PC) - -1. PC sends `OtaBegin { target: Role, total_size, sha256 }` over serial -2. Bridge looks up the target device's MAC, sends `EspnowOtaBegin { total_size, sha256 }` via ESP-NOW -3. Target responds with `EspnowOtaReady` -4. PC streams `OtaData { seq, chunk }` over serial (chunk size <= 240 bytes to fit ESP-NOW payload) -5. Bridge forwards each chunk as `EspnowOtaData { seq, data }` to the target -6. Target ACKs each chunk with `EspnowOtaAck { seq }` (Bridge relays ACK to PC for flow control) -7. On missing ACK, Bridge retransmits (configurable retry count) -8. PC sends `OtaFinish`, Bridge sends `EspnowOtaFinish` -9. Target verifies SHA-256 over the full image, marks the new OTA slot as bootable, responds with `EspnowOtaComplete`, and reboots - -#### Responder (All Field Devices) - -Implemented as a shared module in the unified firmware: - -1. On `EspnowOtaBegin`: erase the inactive OTA partition, respond `EspnowOtaReady` -2. On `EspnowOtaData { seq, data }`: write chunk at `seq * chunk_size` offset, respond `EspnowOtaAck { seq }` -3. On `EspnowOtaFinish`: compute SHA-256 over written data, compare with expected hash - - Match: set boot partition to the newly written slot, respond `EspnowOtaComplete`, reboot after 2s - - Mismatch: respond `EspnowOtaError`, stay on current partition - -#### ESP-NOW OTA Messages - -```rust -enum EspnowMessage { - // ... existing variants ... - - // OTA - OtaBegin { total_size: u32, sha256: [u8; 32] }, - OtaReady, - OtaData { seq: u16, data: heapless::Vec }, - OtaAck { seq: u16 }, - OtaFinish, - OtaComplete, - OtaError { description: String<64> }, -} -``` - -### PC Side - -- `just ota-rx` / `just ota-tx` / `just ota-stepper`: build the unified firmware, then stream it to the Bridge with the target role specified -- Progress bar and retry stats displayed in the terminal -- Frontend could show OTA status for connected devices (stretch goal) - -### Rollback - -If the new firmware fails to boot (e.g., panic before reaching the "mark as valid" checkpoint), the ESP-IDF bootloader automatically rolls back to the previous OTA slot. The firmware should call the "mark current partition valid" API only after successful initialization (ESP-NOW up, discovery beacons sending). - ---- - -## Phase 2+ : Extensibility for Other Frequencies - -The architecture supports future measurement hardware beyond 2.4 GHz ESP-NOW RSSI: - -- The `MeasurementBeacon` / `ReportMeasurement` / `MeasurementResult` pattern is generic. RX reports whatever its measurement backend produces. -- RX could be extended with an SPI/I2C-connected RF frontend (sub-GHz, 5 GHz, mmWave). The `ReportMeasurement` handler reads from the appropriate backend. -- Alternatively, a completely separate measurement device could be queried directly by the PC (e.g., USB SDR, spectrum analyzer via SCPI), bypassing the ESP-NOW mesh entirely. The PC orchestrator already controls timing, so it can interleave ESP-NOW commands with direct instrument queries. -- The `MeasurementResult` type could be extended to include metadata (frequency, bandwidth, measurement type) when multiple backends are supported. - ---- - -## Implementation Order - -``` -Phase 1: Unified firmware + role provisioning - | -Phase 2: Bridge relay + PC orchestration refactor - | (serial protocol, sweep orchestrator, simplified RX) - | -Phase 3: ESP-NOW OTA - | (dual OTA partitions, chunked transfer, rollback) - | -Future: Multi-frequency measurement backends -``` +1. `OtaBegin { target, total_size, sha256, ack_interval }`. The target erases the inactive slot and replies `OtaReady`. +2. `OtaData { seq, data }` in chunks of up to 240 bytes. The target writes each chunk and sends `OtaAck` every `ack_interval` chunks and on the last one. +3. The PC retries a window up to 3 times on timeout, then aborts. +4. `OtaFinish`. The target checks SHA-256, switches the boot slot, replies `OtaComplete` and reboots. -Phase 1 is prerequisite for Phase 3 (single binary = single OTA image). -Phase 2 is prerequisite for Phase 3 (Bridge is the OTA initiator). -Phases 1 and 2 can be developed concurrently to some degree — the protocol changes in Phase 2 are independent of the firmware unification in Phase 1. +After a successful boot the firmware marks its slot as valid. If it fails before that, the bootloader rolls back. +`just ota-` builds the image and uploads it via the PC app's REST API. From 39c513dcb62ca1e954fd173a86b04c8a3092e375 Mon Sep 17 00:00:00 2001 From: JuliDi Date: Mon, 23 Nov 2026 12:45:12 +0100 Subject: [PATCH 10/16] TX acks every command --- software/firmware/src/tx.rs | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/software/firmware/src/tx.rs b/software/firmware/src/tx.rs index c8e3674..12345a1 100644 --- a/software/firmware/src/tx.rs +++ b/software/firmware/src/tx.rs @@ -204,6 +204,20 @@ async fn tx_listener_task( led_signal.signal(LedState::Solid(COLOR_GREEN)); } } + + // Acknowledge every command, like `tx_logic::TxState::handle_message`. + let (paired, bridge_mac) = { + let s = state.lock().await; + (s.bridge_paired, s.bridge_mac) + }; + if paired { + let ack = EspnowMessage::TxResp(proto::TxResponse::Ack); + let mut buf = [0u8; proto::MAX_MSG_SIZE]; + if let Ok(data) = proto::serialize(&ack, &mut buf) { + let mut s = sender.lock().await; + let _ = s.send_async(&bridge_mac, data).await; + } + } } Ok(ref espnow_msg) if crate::ota_responder::is_ota_message(espnow_msg) => { let bridge_mac = state.lock().await.bridge_mac; From be3f5aca00f857332d8475db64aca0e7fab47d68 Mon Sep 17 00:00:00 2001 From: JuliDi Date: Mon, 23 Nov 2026 14:53:10 +0100 Subject: [PATCH 11/16] Remove legacy protocol v1 (PcToRx, RxToPc) --- software/protocol/src/lib.rs | 181 +---------------------------------- 1 file changed, 2 insertions(+), 179 deletions(-) diff --git a/software/protocol/src/lib.rs b/software/protocol/src/lib.rs index 07e92c5..b5e928f 100644 --- a/software/protocol/src/lib.rs +++ b/software/protocol/src/lib.rs @@ -337,67 +337,6 @@ pub struct PeerMismatch { pub protocol: u16, } -// ── Serial protocol v1 (PC ↔ RX, legacy) ─────────────────────────────────── - -/// Command from PC to RX board (over USB-serial). -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] -#[cfg_attr(feature = "defmt", derive(defmt::Format))] -pub enum PcToRx { - /// Start an antenna pattern sweep. - StartSweep { - /// Start angle in degrees. - start_deg: f32, - /// Stop angle in degrees. - stop_deg: f32, - /// Angular step size in degrees. - step_deg: f32, - /// Number of RSSI samples to average per angle. - samples_per_angle: u16, - }, - /// Configure the TX board (forwarded via ESPNOW). - ConfigureTx { - channel: u8, - tx_power_dbm: i8, - packet_rate_hz: u16, - }, - /// Abort the current sweep. - Stop, - /// Request status from RX. - QueryStatus, - /// Return turntable to home (0°) position. - ReturnHome, -} - -/// Message from RX board to PC (over USB-serial). -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] -#[cfg_attr(feature = "defmt", derive(defmt::Format))] -pub enum RxToPc { - /// One measurement data point. - DataPoint { - /// Turntable angle in degrees. - angle_deg: f32, - /// Measured RSSI in dBm (averaged). - rssi_dbm: f32, - /// Number of samples actually collected. - sample_count: u16, - }, - /// Sweep finished successfully. - SweepComplete, - /// Turntable reached home (0°) after a `PcToRx::ReturnHome` command. - HomeComplete, - /// Error during operation. - Error { description: String<128> }, - /// Status report. - Status { - /// Whether a sweep is in progress. - sweeping: bool, - /// Whether TX peer is connected. - tx_connected: bool, - /// Whether turntable peer is connected. - turntable_connected: bool, - }, -} - // ── Turntable angle conversion (pure math, testable on host) ───────────────── pub mod turntable { @@ -474,8 +413,8 @@ mod test { use crate::{ BackendInfo, DecodeError, DeviceEvent, EspnowMessage, HelloBeacon, MAX_MSG_SIZE, - PairConfirm, PcCommand, PcToRx, PeerMismatch, Role, RxToPc, TurntableCommand, - TurntableResponse, TxCommand, TxResponse, + PairConfirm, PcCommand, PeerMismatch, Role, TurntableCommand, TurntableResponse, TxCommand, + TxResponse, }; /// Serialize `msg` into `buf` with postcard, then deserialize and assert equality. @@ -493,70 +432,6 @@ mod test { ) } - #[test] - fn check_max_msg_size_postcard() { - let mut buf = [0u8; MAX_MSG_SIZE]; - - // RxToPc variants - test_ser_deser( - &RxToPc::Status { - sweeping: true, - tx_connected: true, - turntable_connected: true, - }, - &mut buf, - ); - - test_ser_deser( - &RxToPc::Error { - description: String::try_from( - "ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZ\ - ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZ\ - ABCDEFGHIJKLMNOPQRSTUVWX", - ) - .expect("Convert &str to heapless string"), - }, - &mut buf, - ); - - test_ser_deser( - &RxToPc::DataPoint { - angle_deg: 45.0, - rssi_dbm: -42.5, - sample_count: 10, - }, - &mut buf, - ); - - test_ser_deser(&RxToPc::SweepComplete, &mut buf); - - test_ser_deser(&RxToPc::HomeComplete, &mut buf); - - // PcToRx variants - test_ser_deser( - &PcToRx::StartSweep { - start_deg: 0.0, - stop_deg: 180.0, - step_deg: 10.0, - samples_per_angle: 100, - }, - &mut buf, - ); - - test_ser_deser( - &PcToRx::ConfigureTx { - channel: 6, - tx_power_dbm: 20, - packet_rate_hz: 100, - }, - &mut buf, - ); - - test_ser_deser(&PcToRx::Stop, &mut buf); - - test_ser_deser(&PcToRx::QueryStatus, &mut buf); - } - /// Serialize with COBS, verify zero-delimiter, deserialize and check equality. fn test_cobs_round_trip Deserialize<'a> + PartialEq + Debug>( msg: &T, @@ -602,58 +477,6 @@ mod test { ); } - #[test] - fn cobs_round_trip() { - let mut buf = [0u8; MAX_MSG_SIZE]; - - // PcToRx variants - test_cobs_round_trip( - &PcToRx::StartSweep { - start_deg: 0.0, - stop_deg: 360.0, - step_deg: 5.0, - samples_per_angle: 50, - }, - &mut buf, - ); - test_cobs_round_trip( - &PcToRx::ConfigureTx { - channel: 1, - tx_power_dbm: -10, - packet_rate_hz: 200, - }, - &mut buf, - ); - test_cobs_round_trip(&PcToRx::Stop, &mut buf); - test_cobs_round_trip(&PcToRx::QueryStatus, &mut buf); - - // RxToPc variants - test_cobs_round_trip( - &RxToPc::DataPoint { - angle_deg: 90.0, - rssi_dbm: -30.0, - sample_count: 25, - }, - &mut buf, - ); - test_cobs_round_trip(&RxToPc::SweepComplete, &mut buf); - test_cobs_round_trip(&RxToPc::HomeComplete, &mut buf); - test_cobs_round_trip( - &RxToPc::Error { - description: String::try_from("test error").unwrap(), - }, - &mut buf, - ); - test_cobs_round_trip( - &RxToPc::Status { - sweeping: false, - tx_connected: true, - turntable_connected: false, - }, - &mut buf, - ); - } - #[test] fn espnow_message_round_trip() { let mut buf = [0u8; MAX_MSG_SIZE]; From b0d739ee98aa5dd933e1258a37a5328c61ec9499 Mon Sep 17 00:00:00 2001 From: JuliDi Date: Mon, 23 Nov 2026 14:53:10 +0100 Subject: [PATCH 12/16] Remove unused DeviceEvent::HomeComplete --- software/pc/src/main.rs | 3 --- software/pc/src/serial.rs | 6 +++--- software/protocol/src/golden.rs | 17 +++++++---------- software/protocol/src/lib.rs | 2 -- 4 files changed, 10 insertions(+), 18 deletions(-) diff --git a/software/pc/src/main.rs b/software/pc/src/main.rs index f689791..908724c 100644 --- a/software/pc/src/main.rs +++ b/software/pc/src/main.rs @@ -194,9 +194,6 @@ async fn send_and_wait_move( Some(beambench_protocol::DeviceEvent::MoveComplete { angle_deg }) => { return Ok(angle_deg); } - Some(beambench_protocol::DeviceEvent::HomeComplete) => { - return Ok(0.0); - } Some(beambench_protocol::DeviceEvent::TurntableError { description }) => { return Err(description.to_string()); } diff --git a/software/pc/src/serial.rs b/software/pc/src/serial.rs index 340416d..d0446d8 100644 --- a/software/pc/src/serial.rs +++ b/software/pc/src/serial.rs @@ -253,7 +253,7 @@ mod tests { #[tokio::test] async fn reader_decodes_single_frame() { - let msg = DeviceEvent::HomeComplete; + let msg = DeviceEvent::TxAck; let frame = encode_cobs_frame(&msg); let (resp_tx, mut resp_rx) = mpsc::channel::(16); @@ -334,7 +334,7 @@ mod tests { tokio::task::yield_now().await; // Now write a valid frame — reader should have reset and decode this. - let msg = DeviceEvent::HomeComplete; + let msg = DeviceEvent::TxAck; let frame = encode_cobs_frame(&msg); writer.write_all(&frame).await.unwrap(); drop(writer); @@ -348,7 +348,7 @@ mod tests { #[tokio::test] async fn reader_handles_multiple_frames_in_one_read() { - let msg1 = DeviceEvent::HomeComplete; + let msg1 = DeviceEvent::TxAck; let msg2 = DeviceEvent::Measurement { rssi_dbm: -50.0, sample_count: 5, diff --git a/software/protocol/src/golden.rs b/software/protocol/src/golden.rs index 0e612b9..a1fd409 100644 --- a/software/protocol/src/golden.rs +++ b/software/protocol/src/golden.rs @@ -139,7 +139,6 @@ fn device_event_samples() -> Vec<(&'static str, DeviceEvent)> { DeviceEvent::TurntableError { description: s("stall"), }, - DeviceEvent::HomeComplete, DeviceEvent::Measurement { rssi_dbm: -42.5, sample_count: 10, @@ -174,7 +173,6 @@ fn device_event_samples() -> Vec<(&'static str, DeviceEvent)> { DeviceEvent::TxAck => "TxAck", DeviceEvent::MoveComplete { .. } => "MoveComplete", DeviceEvent::TurntableError { .. } => "TurntableError", - DeviceEvent::HomeComplete => "HomeComplete", DeviceEvent::Measurement { .. } => "Measurement", DeviceEvent::Status { .. } => "Status", DeviceEvent::Error { .. } => "Error", @@ -192,17 +190,16 @@ const DEVICE_EVENT_V1: &[(&str, &str)] = &[ ("TxAck", "01 00"), ("MoveComplete", "01 01 00 00 b4 42"), ("TurntableError", "01 02 05 73 74 61 6c 6c"), - ("HomeComplete", "01 03"), - ("Measurement", "01 04 00 00 2a c2 0a"), + ("Measurement", "01 03 00 00 2a c2 0a"), ( "Status", - "01 05 01 00 01 06 65 73 70 6e 6f 77 01 e0 12 01 01 02 03 04 05 06 02", + "01 04 01 00 01 06 65 73 70 6e 6f 77 01 e0 12 01 01 02 03 04 05 06 02", ), - ("Error", "01 06 04 6f 6f 70 73"), - ("OtaReady", "01 07"), - ("OtaAck", "01 08 ac 02"), - ("OtaComplete", "01 09"), - ("OtaError", "01 0a 04 68 61 73 68"), + ("Error", "01 05 04 6f 6f 70 73"), + ("OtaReady", "01 06"), + ("OtaAck", "01 07 ac 02"), + ("OtaComplete", "01 08"), + ("OtaError", "01 09 04 68 61 73 68"), ]; #[test] diff --git a/software/protocol/src/lib.rs b/software/protocol/src/lib.rs index b5e928f..c96ed0b 100644 --- a/software/protocol/src/lib.rs +++ b/software/protocol/src/lib.rs @@ -290,7 +290,6 @@ pub enum DeviceEvent { TurntableError { description: String<64>, }, - HomeComplete, // RX responses Measurement { @@ -588,7 +587,6 @@ mod test { }, &mut buf, ); - test_cobs_round_trip(&DeviceEvent::HomeComplete, &mut buf); test_cobs_round_trip( &DeviceEvent::Measurement { rssi_dbm: -42.5, From 7dfbc0120564628d18173609a73ba8a7d3e7889c Mon Sep 17 00:00:00 2001 From: JuliDi Date: Mon, 23 Nov 2026 14:53:10 +0100 Subject: [PATCH 13/16] Rename rx-sim to bridge-sim, say bridge instead of RX board --- software/pc/Cargo.toml | 6 +++--- software/pc/justfile | 2 +- software/pc/src/bin/{rx-sim.rs => bridge-sim.rs} | 6 +++--- software/pc/src/lib.rs | 4 ++-- 4 files changed, 9 insertions(+), 9 deletions(-) rename software/pc/src/bin/{rx-sim.rs => bridge-sim.rs} (81%) diff --git a/software/pc/Cargo.toml b/software/pc/Cargo.toml index 6f40155..6f6483e 100644 --- a/software/pc/Cargo.toml +++ b/software/pc/Cargo.toml @@ -5,8 +5,8 @@ edition = "2024" default-run = "beambench-pc" [[bin]] -name = "rx-sim" -path = "src/bin/rx-sim.rs" +name = "bridge-sim" +path = "src/bin/bridge-sim.rs" required-features = ["sim"] [features] @@ -42,7 +42,7 @@ clap = { version = "4", features = ["derive"] } # MIME type detection for static file serving mime_guess = "2" -# Heapless strings (used by rx-sim for protocol Error messages) +# Heapless strings (used by bridge-sim for protocol Error messages) heapless = "0.9.3" # SHA-256 for OTA firmware verification diff --git a/software/pc/justfile b/software/pc/justfile index 7c9cd35..4abb9bd 100644 --- a/software/pc/justfile +++ b/software/pc/justfile @@ -27,7 +27,7 @@ run: build # Run RX simulator sim: - cargo run --bin rx-sim --features sim + cargo run --bin bridge-sim --features sim # Check Rust code only check: diff --git a/software/pc/src/bin/rx-sim.rs b/software/pc/src/bin/bridge-sim.rs similarity index 81% rename from software/pc/src/bin/rx-sim.rs rename to software/pc/src/bin/bridge-sim.rs index 63422b7..a810df6 100644 --- a/software/pc/src/bin/rx-sim.rs +++ b/software/pc/src/bin/bridge-sim.rs @@ -3,7 +3,7 @@ //! Generates synthetic antenna patterns so you can test the full PC app //! UI without any ESP32 hardware. //! -//! Usage: cargo run --bin rx-sim [--listen 127.0.0.1:9876] +//! Usage: cargo run --bin bridge-sim [--listen 127.0.0.1:9876] use clap::Parser; use tokio::net::TcpListener; @@ -20,14 +20,14 @@ async fn main() { tracing_subscriber::fmt() .with_env_filter( tracing_subscriber::EnvFilter::try_from_default_env() - .unwrap_or_else(|_| "rx_sim=debug".into()), + .unwrap_or_else(|_| "bridge_sim=debug".into()), ) .init(); let args = Args::parse(); let listener = TcpListener::bind(&args.listen).await.unwrap(); - tracing::info!("rx-sim listening on {}", args.listen); + tracing::info!("bridge-sim listening on {}", args.listen); loop { let (stream, addr) = listener.accept().await.unwrap(); diff --git a/software/pc/src/lib.rs b/software/pc/src/lib.rs index 895ae09..3950a59 100644 --- a/software/pc/src/lib.rs +++ b/software/pc/src/lib.rs @@ -117,11 +117,11 @@ pub enum WsEvent { pub enum WsCommand { /// Start a new antenna pattern sweep with the given configuration. StartSweep(SweepConfig), - /// Forward TX radio configuration to the TX board via the RX bridge. + /// Forward TX radio configuration to the TX board via the bridge. ConfigureTx(TxConfig), /// Abort the current sweep immediately. Stop, - /// Request a fresh status snapshot from the RX board. + /// Request a fresh status snapshot from the bridge. QueryStatus, /// List available serial ports (response sent via REST, not WS). ListPorts, From 60fbe4198b2ae78d8cfcf4174e6be4cdfeb4ad7b Mon Sep 17 00:00:00 2001 From: JuliDi Date: Mon, 23 Nov 2026 14:53:10 +0100 Subject: [PATCH 14/16] Show boards with another protocol version in the sidebar --- software/pc/frontend/src/lib/bindings.ts | 23 ++++++++++++- software/pc/frontend/src/routes/+page.svelte | 35 ++++++++++++++++++-- software/pc/src/lib.rs | 28 ++++++++++++++++ software/pc/src/main.rs | 20 ++++++++--- 4 files changed, 99 insertions(+), 7 deletions(-) diff --git a/software/pc/frontend/src/lib/bindings.ts b/software/pc/frontend/src/lib/bindings.ts index 99ee7fe..4b2bbb6 100644 --- a/software/pc/frontend/src/lib/bindings.ts +++ b/software/pc/frontend/src/lib/bindings.ts @@ -17,6 +17,19 @@ rssi_dbm: number, */ sample_count: number, }; +/** + * A board that speaks another protocol version than the PC. + */ +export type MismatchedPeer = { +/** + * MAC address as `aa:bb:cc:dd:ee:ff`. + */ +mac: string, +/** + * Protocol version the board speaks. + */ +protocol: number, }; + /** * Serial port information returned by the list_ports endpoint. */ @@ -74,7 +87,15 @@ backend_freq_mhz: number | null, /** * Motor-to-turntable gear ratio (motor_deg = turntable_deg × ratio). */ -transmission_ratio: number, }; +transmission_ratio: number, +/** + * Protocol version of this PC app. + */ +protocol_version: number, +/** + * Boards that speak another protocol version. + */ +mismatched_peers: Array, }; /** * TX configuration. diff --git a/software/pc/frontend/src/routes/+page.svelte b/software/pc/frontend/src/routes/+page.svelte index 9432430..7aafc05 100644 --- a/software/pc/frontend/src/routes/+page.svelte +++ b/software/pc/frontend/src/routes/+page.svelte @@ -37,7 +37,9 @@ data_points: 0, backend_name: '', backend_freq_mhz: null, - transmission_ratio: 3 + transmission_ratio: 3, + protocol_version: 0, + mismatched_peers: [] }); /** Transmission ratio shown in the input. Synced from server Status events. */ @@ -172,7 +174,9 @@ data_points: event.data_points, backend_name: event.backend_name, backend_freq_mhz: event.backend_freq_mhz, - transmission_ratio: event.transmission_ratio + transmission_ratio: event.transmission_ratio, + protocol_version: event.protocol_version, + mismatched_peers: event.mismatched_peers }; transmissionRatioInput = event.transmission_ratio; if (!event.sweeping) stopping = false; @@ -521,6 +525,19 @@ class:active={status.turntable_connected} >Turntable + {#if status.mismatched_peers.length > 0} + + {/if} {#if status.backend_name}

Backend: {status.backend_name}, /// Motor-to-turntable gear ratio (motor_deg = turntable_deg × ratio). pub transmission_ratio: f32, + /// Protocol version of this PC app. + pub protocol_version: u16, + /// Boards that speak another protocol version. + pub mismatched_peers: Vec, +} + +/// A board that speaks another protocol version than the PC. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)] +#[ts(export, export_to = "bindings.ts")] +pub struct MismatchedPeer { + /// MAC address as `aa:bb:cc:dd:ee:ff`. + pub mac: String, + /// Protocol version the board speaks. + pub protocol: u16, +} + +impl From<&beambench_protocol::PeerMismatch> for MismatchedPeer { + fn from(p: &beambench_protocol::PeerMismatch) -> Self { + Self { + mac: p.mac.map(|b| format!("{b:02x}")).join(":"), + protocol: p.protocol, + } + } } /// Serial port information returned by the list_ports endpoint. @@ -278,6 +301,11 @@ mod tests { backend_name: "espnow".to_string(), backend_freq_mhz: Some(2400), transmission_ratio: 3.0, + protocol_version: 1, + mismatched_peers: vec![MismatchedPeer { + mac: "01:02:03:04:05:06".to_string(), + protocol: 2, + }], })); } diff --git a/software/pc/src/main.rs b/software/pc/src/main.rs index 908724c..1998430 100644 --- a/software/pc/src/main.rs +++ b/software/pc/src/main.rs @@ -18,7 +18,8 @@ use tokio::sync::{Mutex, broadcast, watch}; use tracing::info; use beambench_pc::{ - DEFAULT_TRANSMISSION_RATIO, PortInfo, SystemStatus, WsCommand, WsEvent, export_csv, + DEFAULT_TRANSMISSION_RATIO, MismatchedPeer, PortInfo, SystemStatus, WsCommand, WsEvent, + export_csv, }; /// Initial delay before sending QueryStatus to a freshly-opened device. @@ -114,6 +115,17 @@ impl AppState { backend_name: self.backend_name.lock().await.clone(), backend_freq_mhz: *self.backend_freq_mhz.lock().await, transmission_ratio: self.transmission_ratio(), + protocol_version: beambench_protocol::PROTOCOL_VERSION, + mismatched_peers: if serial_connected { + self.mismatched_peers + .lock() + .await + .iter() + .map(MismatchedPeer::from) + .collect() + } else { + Vec::new() + }, } } @@ -907,10 +919,10 @@ async fn update_mismatched_peers(state: &AppState, peers: &[beambench_protocol:: return; } *known = peers.to_vec(); - for p in peers { - let mac = p.mac.map(|b| format!("{b:02x}")).join(":"); + for p in peers.iter().map(MismatchedPeer::from) { let msg = format!( - "Board {mac} speaks protocol v{}, PC v{}. Reflash it.", + "Board {} speaks protocol v{}, PC v{}. Reflash it.", + p.mac, p.protocol, beambench_protocol::PROTOCOL_VERSION ); From 5814ce2c5472b4a8521fc3c6a6b76ca3416cd3ac Mon Sep 17 00:00:00 2001 From: JuliDi Date: Mon, 23 Nov 2026 14:53:10 +0100 Subject: [PATCH 15/16] Detect lost bridge within one beacon interval --- software/firmware/src/common.rs | 10 ++++++++++ software/firmware/src/rx.rs | 22 ++++++++++++++-------- software/firmware/src/turntable.rs | 22 ++++++++++++++-------- software/firmware/src/tx.rs | 22 ++++++++++++++-------- 4 files changed, 52 insertions(+), 24 deletions(-) diff --git a/software/firmware/src/common.rs b/software/firmware/src/common.rs index 303787b..261674e 100644 --- a/software/firmware/src/common.rs +++ b/software/firmware/src/common.rs @@ -83,6 +83,16 @@ pub type SharedFlash = embassy_sync::mutex::Mutex) -> bool { + match last_hello { + Some(t) if paired => embassy_time::Instant::now() - t >= PAIRED_HELLO_INTERVAL, + _ => true, + } +} // ── Shared helpers ────────────────────────────────────────────────────────── diff --git a/software/firmware/src/rx.rs b/software/firmware/src/rx.rs index 0f6089b..4996a50 100644 --- a/software/firmware/src/rx.rs +++ b/software/firmware/src/rx.rs @@ -107,17 +107,14 @@ async fn rx_discovery_task( led_signal: &'static Signal, ) { let mut buf = [0u8; proto::MAX_MSG_SIZE]; + let mut last_hello = None; + let mut led_paired = None; loop { - let paired = state.lock().await.bridge_paired; - if paired { - Timer::after(Duration::from_secs(10)).await; - } else { - Timer::after(BEACON_INTERVAL).await; - } + Timer::after(BEACON_INTERVAL).await; // Check for stale bridge and unpair. - { + let paired = { let mut s = state.lock().await; if s.bridge_paired && is_heartbeat_stale(s.last_bridge_seen) { info!("Bridge heartbeat timeout, unpairing"); @@ -125,8 +122,17 @@ async fn rx_discovery_task( s.bridge_paired = false; s.last_bridge_seen = None; } - signal_pairing_led(led_signal, s.bridge_paired); + s.bridge_paired + }; + if led_paired != Some(paired) { + signal_pairing_led(led_signal, paired); + led_paired = Some(paired); + } + + if !hello_due(paired, last_hello) { + continue; } + last_hello = Some(Instant::now()); let beacon = EspnowMessage::Hello(proto::HelloBeacon { role: Role::Rx, diff --git a/software/firmware/src/turntable.rs b/software/firmware/src/turntable.rs index 5189b29..697e53f 100644 --- a/software/firmware/src/turntable.rs +++ b/software/firmware/src/turntable.rs @@ -91,17 +91,14 @@ async fn turntable_discovery_task( led_signal: &'static Signal, ) { let mut buf = [0u8; proto::MAX_MSG_SIZE]; + let mut last_hello = None; + let mut led_paired = None; loop { - let paired = bridge_mac.lock().await.is_some(); - if paired { - Timer::after(Duration::from_secs(10)).await; - } else { - Timer::after(BEACON_INTERVAL).await; - } + Timer::after(BEACON_INTERVAL).await; // Check for stale bridge and unpair. - { + let paired = { let mut mac = bridge_mac.lock().await; let last = *last_bridge_seen.lock().await; if mac.is_some() && is_heartbeat_stale(last) { @@ -110,8 +107,17 @@ async fn turntable_discovery_task( *mac = None; *last_bridge_seen.lock().await = None; } - signal_pairing_led(led_signal, mac.is_some()); + mac.is_some() + }; + if led_paired != Some(paired) { + signal_pairing_led(led_signal, paired); + led_paired = Some(paired); + } + + if !hello_due(paired, last_hello) { + continue; } + last_hello = Some(Instant::now()); let beacon = EspnowMessage::Hello(proto::HelloBeacon { role: Role::Turntable, diff --git a/software/firmware/src/tx.rs b/software/firmware/src/tx.rs index 12345a1..4386d33 100644 --- a/software/firmware/src/tx.rs +++ b/software/firmware/src/tx.rs @@ -112,17 +112,14 @@ async fn tx_discovery_task( led_signal: &'static Signal, ) { let mut buf = [0u8; proto::MAX_MSG_SIZE]; + let mut last_hello = None; + let mut led_paired = None; loop { - let paired = state.lock().await.bridge_paired; - if paired { - Timer::after(Duration::from_secs(10)).await; - } else { - Timer::after(BEACON_INTERVAL).await; - } + Timer::after(BEACON_INTERVAL).await; // Check for stale bridge and unpair. - { + let paired = { let mut s = state.lock().await; if s.bridge_paired && is_heartbeat_stale(s.last_bridge_seen) { info!("Bridge heartbeat timeout, unpairing"); @@ -131,8 +128,17 @@ async fn tx_discovery_task( s.backend.stop_transmit().await; s.last_bridge_seen = None; } - signal_pairing_led(led_signal, s.bridge_paired); + s.bridge_paired + }; + if led_paired != Some(paired) { + signal_pairing_led(led_signal, paired); + led_paired = Some(paired); + } + + if !hello_due(paired, last_hello) { + continue; } + last_hello = Some(Instant::now()); let beacon = EspnowMessage::Hello(proto::HelloBeacon { role: Role::Tx, From 59fb61bba01df23901f61a784ed5f146d96fd5e2 Mon Sep 17 00:00:00 2001 From: JuliDi Date: Mon, 23 Nov 2026 14:53:10 +0100 Subject: [PATCH 16/16] Fix OTA slot activation, use our partition table in cargo runner --- software/firmware/.cargo/config.toml | 4 +- software/firmware/src/ota_responder.rs | 74 ++++++++++++++++++-------- 2 files changed, 54 insertions(+), 24 deletions(-) diff --git a/software/firmware/.cargo/config.toml b/software/firmware/.cargo/config.toml index d0f47d4..f4440d4 100644 --- a/software/firmware/.cargo/config.toml +++ b/software/firmware/.cargo/config.toml @@ -7,7 +7,9 @@ rustflags = [ ] [target.riscv32imc-unknown-none-elf] -runner = "probe-rs run --chip esp32c3 --always-print-stacktrace" +# Use our partition table; the IDF default puts the app over `otadata`. +# Relative path: run cargo from this directory. +runner = "probe-rs run --chip esp32c3 --always-print-stacktrace --idf-partition-table partitions.csv --idf-target-app-partition ota_0" [env] DEFMT_LOG = "info" diff --git a/software/firmware/src/ota_responder.rs b/software/firmware/src/ota_responder.rs index 004acb6..d5f3538 100644 --- a/software/firmware/src/ota_responder.rs +++ b/software/firmware/src/ota_responder.rs @@ -10,7 +10,10 @@ use esp_radio::esp_now::EspNowSender; use sha2::{Digest, Sha256}; use beambench_protocol::{self as proto, EspnowMessage, OTA_CHUNK_SIZE}; -use esp_bootloader_esp_idf::partitions; +use esp_bootloader_esp_idf::ota::OtaImageState; +use esp_bootloader_esp_idf::partitions::{ + self, AppPartitionSubType, DataPartitionSubType, PartitionType, +}; use crate::common::{COLOR_GREEN, COLOR_RED, LedState, OTA_IN_PROGRESS, SharedFlash}; use core::sync::atomic::Ordering; @@ -19,6 +22,8 @@ const CHUNK_SIZE: u32 = OTA_CHUNK_SIZE as u32; /// Active OTA session state. struct OtaSession { + /// Target OTA slot, the one not currently booted. + target: AppPartitionSubType, /// Absolute flash offset of the target OTA partition. partition_offset: u32, /// Size of the target OTA partition. @@ -176,17 +181,16 @@ async fn handle_begin( // Determine which slot is currently booted (by checking otadata). // If we can't determine, default to writing to ota_0. let booted = pt.booted_partition(); - let (target_offset, target_size) = match booted { + let (target, target_offset, target_size) = match booted { Ok(Some(entry)) - if entry.partition_type() - == partitions::PartitionType::App(partitions::AppPartitionSubType::Ota0) => + if entry.partition_type() == PartitionType::App(AppPartitionSubType::Ota0) => { // Currently on ota_0, write to ota_1. - (ota1.offset(), ota1.len()) + (AppPartitionSubType::Ota1, ota1.offset(), ota1.len()) } _ => { // Currently on ota_1 or factory/unknown, write to ota_0. - (ota0.offset(), ota0.len()) + (AppPartitionSubType::Ota0, ota0.offset(), ota0.len()) } }; @@ -219,6 +223,7 @@ async fn handle_begin( let mut state = ota.lock().await; state.session = Some(OtaSession { + target, partition_offset: target_offset, partition_size: target_size, expected_sha256: sha256, @@ -312,17 +317,16 @@ async fn handle_finish( // Switch the OTA slot. let mut f = flash.lock().await; - let mut pt_buf = [0u8; partitions::PARTITION_TABLE_MAX_LEN]; - let mut updater = - match esp_bootloader_esp_idf::ota_updater::OtaUpdater::new(&mut f, &mut pt_buf) { - Ok(u) => u, - Err(e) => { - defmt::error!("OtaUpdater init failed: {:?}", defmt::Debug2Format(&e)); - return Some(ota_error("ota updater init failed")); - } - }; + let mut result = activate(&mut f, session.target); + if result == Err(partitions::Error::Invalid) { + // otadata holds no valid entries, e.g. an app image left from a + // flash with the default partition table. Erase it and retry. + defmt::warn!("otadata is corrupt, erasing it"); + result = erase_otadata(&mut f).and_then(|()| activate(&mut f, session.target)); + } + drop(f); - if let Err(e) = updater.activate_next_partition() { + if let Err(e) = result { defmt::error!( "Failed to activate partition: {:?}", defmt::Debug2Format(&e) @@ -330,18 +334,42 @@ async fn handle_finish( return Some(ota_error("partition activation failed")); } - if let Err(e) = updater.set_current_ota_state(esp_bootloader_esp_idf::ota::OtaImageState::New) { - defmt::error!("Failed to set OTA state: {:?}", defmt::Debug2Format(&e)); - return Some(ota_error("set ota state failed")); - } - - drop(f); - info!("OTA complete, rebooting in 2 seconds..."); Some(EspnowMessage::OtaComplete) } +/// Select `target` as the next boot slot and mark it as new. +/// +/// Does not use `OtaUpdater::activate_next_partition`: with empty otadata it +/// picks the booted slot. Its `set_current_app_partition(Ota1)` from empty +/// otadata also writes sequence 0. Selecting ota_0 first gives sequence 1, +/// then ota_1 gives sequence 2. +fn activate( + flash: &mut esp_storage::FlashStorage<'_>, + target: AppPartitionSubType, +) -> Result<(), partitions::Error> { + let mut pt_buf = [0u8; partitions::PARTITION_TABLE_MAX_LEN]; + let mut updater = esp_bootloader_esp_idf::ota_updater::OtaUpdater::new(flash, &mut pt_buf)?; + let mut ota = updater.ota_data()?; + if ota.current_app_partition()? == AppPartitionSubType::Factory { + ota.set_current_app_partition(AppPartitionSubType::Ota0)?; + } + ota.set_current_app_partition(target)?; + ota.set_current_ota_state(OtaImageState::New) +} + +/// Erase the whole otadata partition. +fn erase_otadata(flash: &mut esp_storage::FlashStorage<'_>) -> Result<(), partitions::Error> { + let mut pt_buf = [0u8; partitions::PARTITION_TABLE_MAX_LEN]; + let pt = partitions::read_partition_table(flash, &mut pt_buf)?; + let part = pt + .find_partition(PartitionType::Data(DataPartitionSubType::Ota))? + .ok_or(partitions::Error::Invalid)?; + let len = part.len(); + part.as_flash_region(flash).erase(0, len) +} + /// After sending OtaComplete, the caller should schedule a reboot. pub async fn schedule_reboot() { embassy_time::Timer::after(embassy_time::Duration::from_secs(2)).await;