commit f16b36b138e70a382b1ed1a0ce8b1626faaeae8f Author: Stephen Waits Date: Fri Apr 3 17:01:27 2026 -0600 feat: add Rust client library and mux daemon Add donglora-client (clients/rust/) and donglora-mux (mux/rust/) as Rust implementations of the existing Python client library and mux daemon. Both are standalone Cargo projects with no-panic guarantees enforced by clippy deny lints. donglora-client provides protocol types, COBS framing, USB device discovery, serial/mux transports, and a high-level Client with send/recv. donglora-mux is a fully async (tokio) multiplexer daemon with dongle hot-plug reconnect, per-client bounded send queues, SetConfig locking, and StartRx/StopRx reference counting. 52 unit tests across both crates. Updates README roadmap checkboxes and CONTRIBUTING docs to reflect the new implementations. diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..ea8c4bf --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +/target diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..a753e2c --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,329 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "anyhow" +version = "1.0.102" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f202df86484c868dbad7eaa557ef785d5c66295e41b460ef922eca0723b842c" + +[[package]] +name = "bitflags" +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 = "cfg-if" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" + +[[package]] +name = "cobs" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fa961b519f0b462e3a3b4a34b64d119eeaca1d59af726fe450bbba07a9fc0a1" +dependencies = [ + "thiserror", +] + +[[package]] +name = "core-foundation" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2a6cd9ae233e7f62ba4e9353e81a88df7fc8a5987b8d445b4d90c879bd156f6" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "core-foundation-sys" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" + +[[package]] +name = "donglora-client" +version = "0.1.0" +dependencies = [ + "anyhow", + "cobs", + "serialport", + "tracing", +] + +[[package]] +name = "io-kit-sys" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "617ee6cf8e3f66f3b4ea67a4058564628cde41901316e19f559e14c7c72c5e7b" +dependencies = [ + "core-foundation-sys", + "mach2", +] + +[[package]] +name = "libc" +version = "0.2.184" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48f5d2a454e16a5ea0f4ced81bd44e4cfc7bd3a507b61887c99fd3538b28e4af" + +[[package]] +name = "libudev" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78b324152da65df7bb95acfcaab55e3097ceaab02fb19b228a9eb74d55f135e0" +dependencies = [ + "libc", + "libudev-sys", +] + +[[package]] +name = "libudev-sys" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c8469b4a23b962c1396b9b451dda50ef5b283e8dd309d69033475fa9b334324" +dependencies = [ + "libc", + "pkg-config", +] + +[[package]] +name = "mach2" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d640282b302c0bb0a2a8e0233ead9035e3bed871f0b7e81fe4a1ec829765db44" +dependencies = [ + "libc", +] + +[[package]] +name = "nix" +version = "0.26.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "598beaf3cc6fdd9a5dfb1630c2800c7acd31df7aaf0f565796fba2b53ca1af1b" +dependencies = [ + "bitflags 1.3.2", + "cfg-if", + "libc", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + +[[package]] +name = "pkg-config" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7edddbd0b52d732b21ad9a5fab5c704c14cd949e5e9a1ec5929a24fded1b904c" + +[[package]] +name = "proc-macro2" +version = "1.0.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41f2619966050689382d2b44f664f4bc593e129785a36d6ee376ddf37259b924" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "scopeguard" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + +[[package]] +name = "serialport" +version = "4.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4d91116f97173694f1642263b2ff837f80d933aa837e2314969f6728f661df3" +dependencies = [ + "bitflags 2.11.0", + "cfg-if", + "core-foundation", + "core-foundation-sys", + "io-kit-sys", + "libudev", + "mach2", + "nix", + "scopeguard", + "unescaper", + "windows-sys", +] + +[[package]] +name = "syn" +version = "2.0.117" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e665b8803e7b1d2a727f4023456bbbbe74da67099c585258af0ad9c5013b9b99" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "thiserror" +version = "2.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4288b5bcbc7920c07a1149a35cf9590a2aa808e0bc1eafaade0b80947865fbc4" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebc4ee7f67670e9b64d05fa4253e753e016c6c95ff35b89b7941d6b856dec1d5" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[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", +] + +[[package]] +name = "tracing-core" +version = "0.1.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" +dependencies = [ + "once_cell", +] + +[[package]] +name = "unescaper" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4064ed685c487dbc25bd3f0e9548f2e34bab9d18cefc700f9ec2dba74ba1138e" +dependencies = [ + "thiserror", +] + +[[package]] +name = "unicode-ident" +version = "1.0.24" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" + +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_gnullvm", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..28bd3c0 --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,21 @@ +[package] +name = "donglora-client" +version = "0.1.0" +edition = "2024" +authors = ["Stephen Waits "] +license = "MIT" +description = "DongLoRa host library — connect, configure, send/receive LoRa packets" +repository = "https://github.com/swaits/donglora" +keywords = ["lora", "radio", "usb", "serial"] +categories = ["hardware-support"] + +[dependencies] +anyhow = "1" +cobs = "0.3" +serialport = "4" +tracing = "0.1" + +[lints.clippy] +unwrap_used = "deny" +expect_used = "deny" +panic = "deny" diff --git a/justfile b/justfile new file mode 100644 index 0000000..e0e3323 --- /dev/null +++ b/justfile @@ -0,0 +1,11 @@ +set shell := ["bash", "-c"] + +default: check + +# Run clippy and tests +check: + cargo clippy -- -D warnings && cargo test + +# Build release +build: + cargo build --release diff --git a/src/client.rs b/src/client.rs new file mode 100644 index 0000000..9bb0d90 --- /dev/null +++ b/src/client.rs @@ -0,0 +1,215 @@ +//! High-level DongLoRa client. +//! +//! The [`Client`] wraps a transport and provides ergonomic send/recv methods +//! that handle the command/response discipline (buffering unsolicited RxPackets +//! while waiting for solicited responses). + +use std::collections::VecDeque; + +use crate::codec::{encode_frame, read_frame}; +use crate::protocol::{Command, ErrorCode, RadioConfig, Response}; +use crate::transport::Transport; + +/// Maximum number of buffered RxPackets before oldest are dropped. +const RX_BUFFER_CAP: usize = 256; + +/// Maximum frames to read while waiting for a solicited response before giving up. +const MAX_UNSOLICITED_BEFORE_TIMEOUT: usize = 50; + +/// High-level DongLoRa client, generic over transport. +/// +/// Works with any [`Transport`]: direct USB serial, Unix socket mux, or TCP mux. +pub struct Client { + transport: T, + rx_buffer: VecDeque, +} + +impl Client { + /// Create a new client wrapping the given transport. + pub fn new(transport: T) -> Self { + Self { + transport, + rx_buffer: VecDeque::with_capacity(64), + } + } + + /// Send a command and wait for the solicited response. + /// + /// Any unsolicited `RxPacket` frames encountered while waiting are buffered + /// and retrievable via [`recv`](Self::recv) or [`drain_rx`](Self::drain_rx). + pub fn send(&mut self, cmd: Command) -> anyhow::Result { + let frame = encode_frame(&cmd.to_bytes()); + std::io::Write::write_all(&mut self.transport, &frame)?; + std::io::Write::flush(&mut self.transport)?; + + for _ in 0..MAX_UNSOLICITED_BEFORE_TIMEOUT { + let data = read_frame(&mut self.transport)? + .ok_or_else(|| anyhow::anyhow!("timeout waiting for response"))?; + let resp = Response::from_bytes(&data) + .ok_or_else(|| anyhow::anyhow!("malformed response ({} bytes)", data.len()))?; + if resp.is_rx_packet() { + self.buffer_rx(resp); + continue; + } + return Ok(resp); + } + anyhow::bail!("no solicited response after {MAX_UNSOLICITED_BEFORE_TIMEOUT} frames") + } + + /// Return the next RxPacket from the buffer or the wire. + /// + /// Returns `Ok(None)` on timeout (no packet available). + pub fn recv(&mut self) -> anyhow::Result> { + if let Some(pkt) = self.rx_buffer.pop_front() { + return Ok(Some(pkt)); + } + let Some(data) = read_frame(&mut self.transport)? else { + return Ok(None); + }; + let resp = Response::from_bytes(&data) + .ok_or_else(|| anyhow::anyhow!("malformed response ({} bytes)", data.len()))?; + if resp.is_rx_packet() { + Ok(Some(resp)) + } else { + // Non-RxPacket unsolicited response — shouldn't happen, discard + Ok(None) + } + } + + /// Drain all buffered and pending RxPacket frames. + /// + /// Temporarily reduces the read timeout to quickly drain any frames still + /// in flight, then restores the original timeout. + pub fn drain_rx(&mut self) -> anyhow::Result> { + let mut packets: Vec = self.rx_buffer.drain(..).collect(); + + let old_timeout = self.transport.timeout(); + self.transport + .set_timeout(std::time::Duration::from_millis(10))?; + + loop { + let Some(data) = read_frame(&mut self.transport)? else { + break; + }; + if let Some(resp) = Response::from_bytes(&data) + && resp.is_rx_packet() + { + packets.push(resp); + } + } + + self.transport.set_timeout(old_timeout)?; + Ok(packets) + } + + /// Send a Ping and verify the Pong response. + pub fn ping(&mut self) -> anyhow::Result<()> { + match self.send(Command::Ping)? { + Response::Pong => Ok(()), + other => anyhow::bail!("unexpected response to Ping: {other:?}"), + } + } + + /// Set the radio configuration. + pub fn set_config(&mut self, config: RadioConfig) -> anyhow::Result<()> { + match self.send(Command::SetConfig(config))? { + Response::Ok => Ok(()), + Response::Error(code) => anyhow::bail!("SetConfig failed: {code}"), + other => anyhow::bail!("unexpected response to SetConfig: {other:?}"), + } + } + + /// Start receiving LoRa packets. + pub fn start_rx(&mut self) -> anyhow::Result<()> { + match self.send(Command::StartRx)? { + Response::Ok => Ok(()), + Response::Error(code) => anyhow::bail!("StartRx failed: {code}"), + other => anyhow::bail!("unexpected response to StartRx: {other:?}"), + } + } + + /// Stop receiving LoRa packets. + pub fn stop_rx(&mut self) -> anyhow::Result<()> { + match self.send(Command::StopRx)? { + Response::Ok => Ok(()), + Response::Error(code) => anyhow::bail!("StopRx failed: {code}"), + other => anyhow::bail!("unexpected response to StopRx: {other:?}"), + } + } + + /// Transmit a LoRa packet. + pub fn transmit( + &mut self, + payload: &[u8], + config: Option, + ) -> anyhow::Result<()> { + let cmd = Command::Transmit { + config, + payload: payload.to_vec(), + }; + match self.send(cmd)? { + Response::TxDone => Ok(()), + Response::Error(ErrorCode::TxTimeout) => anyhow::bail!("transmit timed out"), + Response::Error(code) => anyhow::bail!("Transmit failed: {code}"), + other => anyhow::bail!("unexpected response to Transmit: {other:?}"), + } + } + + /// Get the board's MAC address. + pub fn get_mac(&mut self) -> anyhow::Result<[u8; 6]> { + match self.send(Command::GetMac)? { + Response::MacAddress(mac) => Ok(mac), + Response::Error(code) => anyhow::bail!("GetMac failed: {code}"), + other => anyhow::bail!("unexpected response to GetMac: {other:?}"), + } + } + + /// Get the current radio configuration from the device. + pub fn get_config(&mut self) -> anyhow::Result { + match self.send(Command::GetConfig)? { + Response::Config(cfg) => Ok(cfg), + Response::Error(code) => anyhow::bail!("GetConfig failed: {code}"), + other => anyhow::bail!("unexpected response to GetConfig: {other:?}"), + } + } + + /// Turn on the display (if present). + pub fn display_on(&mut self) -> anyhow::Result<()> { + match self.send(Command::DisplayOn)? { + Response::Ok => Ok(()), + Response::Error(code) => anyhow::bail!("DisplayOn failed: {code}"), + other => anyhow::bail!("unexpected response to DisplayOn: {other:?}"), + } + } + + /// Turn off the display (if present). + pub fn display_off(&mut self) -> anyhow::Result<()> { + match self.send(Command::DisplayOff)? { + Response::Ok => Ok(()), + Response::Error(code) => anyhow::bail!("DisplayOff failed: {code}"), + other => anyhow::bail!("unexpected response to DisplayOff: {other:?}"), + } + } + + /// Consume the client and return the inner transport. + pub fn into_inner(self) -> T { + self.transport + } + + /// Get a reference to the inner transport. + pub fn transport(&self) -> &T { + &self.transport + } + + /// Get a mutable reference to the inner transport. + pub fn transport_mut(&mut self) -> &mut T { + &mut self.transport + } + + fn buffer_rx(&mut self, resp: Response) { + if self.rx_buffer.len() >= RX_BUFFER_CAP { + self.rx_buffer.pop_front(); // drop oldest + } + self.rx_buffer.push_back(resp); + } +} diff --git a/src/codec.rs b/src/codec.rs new file mode 100644 index 0000000..0289a07 --- /dev/null +++ b/src/codec.rs @@ -0,0 +1,277 @@ +//! COBS framing: encode/decode frames and accumulate partial reads. +//! +//! Each frame is COBS-encoded and terminated with a `0x00` sentinel byte. +//! The sentinel never appears in the encoded data, so it unambiguously +//! marks frame boundaries. + +use tracing::warn; + +/// COBS-encode data and append the `0x00` sentinel. +pub fn encode_frame(data: &[u8]) -> Vec { + let max_encoded = cobs::max_encoding_length(data.len()); + let mut buf = vec![0u8; max_encoded]; + let n = cobs::encode(data, &mut buf); + buf.truncate(n); + buf.push(0x00); + buf +} + +/// COBS-decode a frame (without the sentinel). Returns `None` on decode error. +pub fn decode_frame(encoded: &[u8]) -> Option> { + if encoded.is_empty() { + return None; + } + let mut buf = vec![0u8; encoded.len()]; + match cobs::decode(encoded, &mut buf) { + Ok(n) => { + buf.truncate(n); + Some(buf) + } + Err(_) => None, + } +} + +/// Stateful COBS frame accumulator. +/// +/// Feed raw byte chunks (from serial reads, socket reads, etc.) and extract +/// complete decoded frames. Handles partial reads, multiple frames per chunk, +/// and empty inter-frame gaps gracefully. +/// +/// Used by both the sync client (`read_frame`) and the async mux to accumulate +/// data from serial and client socket streams. +pub struct FrameReader { + buf: Vec, +} + +impl FrameReader { + /// Create a new empty frame reader. + pub fn new() -> Self { + Self { + buf: Vec::with_capacity(512), + } + } + + /// Feed raw bytes and return all complete decoded frames. + /// + /// COBS decode errors are logged and the bad frame is skipped. + /// Empty inter-frame gaps (consecutive `0x00` bytes) are ignored. + pub fn feed(&mut self, data: &[u8]) -> Vec> { + self.buf.extend_from_slice(data); + + let mut frames = Vec::new(); + while let Some(sentinel_pos) = self.buf.iter().position(|&b| b == 0x00) { + let encoded = &self.buf[..sentinel_pos]; + if !encoded.is_empty() { + match decode_frame(encoded) { + Some(decoded) => frames.push(decoded), + None => warn!("bad COBS frame ({} bytes) — skipped", encoded.len()), + } + } + // Remove the consumed bytes including the sentinel + self.buf.drain(..=sentinel_pos); + } + frames + } + + /// Return the number of buffered bytes not yet forming a complete frame. + pub fn buffered(&self) -> usize { + self.buf.len() + } +} + +impl Default for FrameReader { + fn default() -> Self { + Self::new() + } +} + +/// Read one complete COBS frame from a blocking `Read` source. +/// +/// Reads byte-by-byte until a `0x00` sentinel is found, then COBS-decodes. +/// Returns `Ok(None)` on timeout (zero-length read from the underlying source). +/// Returns `Err` on I/O errors or COBS decode failures. +pub fn read_frame(reader: &mut dyn std::io::Read) -> anyhow::Result>> { + let mut buf = Vec::with_capacity(280); + let mut byte = [0u8; 1]; + + loop { + match reader.read(&mut byte) { + Ok(0) => { + // Timeout or EOF + return Ok(None); + } + Ok(_) => { + if byte[0] == 0x00 { + break; + } + buf.push(byte[0]); + } + Err(e) if e.kind() == std::io::ErrorKind::TimedOut => { + return Ok(None); + } + Err(e) => return Err(e.into()), + } + } + + if buf.is_empty() { + return Ok(None); + } + + decode_frame(&buf).map(Some).ok_or_else(|| anyhow::anyhow!("COBS decode error")) +} + +// ── Tests ────────────────────────────────────────────────────────── + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn encode_decode_roundtrip() { + let data = b"hello world"; + let encoded = encode_frame(data); + // Encoded should end with 0x00 sentinel + assert_eq!(encoded.last(), Some(&0x00)); + // Encoded should not contain 0x00 except the trailing sentinel + assert!(!encoded[..encoded.len() - 1].contains(&0x00)); + // Decode (without sentinel) + let decoded = decode_frame(&encoded[..encoded.len() - 1]); + assert_eq!(decoded.as_deref(), Some(data.as_slice())); + } + + #[test] + fn encode_decode_empty() { + // COBS encoding of empty data produces just the 0x00 sentinel. + // This is equivalent to an empty inter-frame gap and is correctly + // skipped by both FrameReader and read_frame. + let encoded = encode_frame(b""); + assert_eq!(encoded, vec![0x00]); + } + + #[test] + fn encode_decode_with_zeros() { + let data = &[0x00, 0x01, 0x00, 0x02, 0x00]; + let encoded = encode_frame(data); + let decoded = decode_frame(&encoded[..encoded.len() - 1]); + assert_eq!(decoded.as_deref(), Some(data.as_slice())); + } + + #[test] + fn decode_frame_invalid() { + // An invalid COBS sequence + assert!(decode_frame(&[0x00]).is_none()); // empty after stripping would be caught + // Actually the cobs crate might handle this differently, let's test empty + assert!(decode_frame(&[]).is_none()); + } + + #[test] + fn frame_reader_single_frame() { + let mut reader = FrameReader::new(); + let data = b"test"; + let frame = encode_frame(data); + let frames = reader.feed(&frame); + assert_eq!(frames.len(), 1); + assert_eq!(frames[0], data); + } + + #[test] + fn frame_reader_multiple_frames_at_once() { + let mut reader = FrameReader::new(); + let f1 = encode_frame(b"one"); + let f2 = encode_frame(b"two"); + let mut combined = f1; + combined.extend_from_slice(&f2); + let frames = reader.feed(&combined); + assert_eq!(frames.len(), 2); + assert_eq!(frames[0], b"one"); + assert_eq!(frames[1], b"two"); + } + + #[test] + fn frame_reader_partial_then_complete() { + let mut reader = FrameReader::new(); + let frame = encode_frame(b"split"); + let mid = frame.len() / 2; + + // Feed first half — no complete frames yet + let frames = reader.feed(&frame[..mid]); + assert!(frames.is_empty()); + assert!(reader.buffered() > 0); + + // Feed second half — now we get the frame + let frames = reader.feed(&frame[mid..]); + assert_eq!(frames.len(), 1); + assert_eq!(frames[0], b"split"); + assert_eq!(reader.buffered(), 0); + } + + #[test] + fn frame_reader_empty_gaps() { + let mut reader = FrameReader::new(); + // Multiple sentinels in a row (empty gaps between frames) + let f = encode_frame(b"data"); + let mut input = vec![0x00, 0x00]; // leading empty gaps + input.extend_from_slice(&f); + input.push(0x00); // trailing empty gap + let frames = reader.feed(&input); + assert_eq!(frames.len(), 1); + assert_eq!(frames[0], b"data"); + } + + #[test] + fn frame_reader_bad_cobs_skipped() { + let mut reader = FrameReader::new(); + // Feed a known-bad COBS frame followed by a good one. + // A frame where the first byte claims a run longer than the frame is invalid. + let bad = &[0xFF, 0x01, 0x00]; // 0xFF says next 254 bytes, but only 1 present + let good = encode_frame(b"ok"); + let mut input = bad.to_vec(); + input.extend_from_slice(&good); + let frames = reader.feed(&input); + // Bad frame skipped, good frame decoded + assert_eq!(frames.len(), 1); + assert_eq!(frames[0], b"ok"); + } + + #[test] + fn read_frame_from_bytes() { + let data = b"frame"; + let encoded = encode_frame(data); + let mut cursor = std::io::Cursor::new(encoded); + let result = read_frame(&mut cursor); + assert!(result.is_ok()); + assert_eq!(result.ok().flatten().as_deref(), Some(data.as_slice())); + } + + #[test] + fn read_frame_timeout() { + // Empty reader → returns None (timeout) + let mut cursor = std::io::Cursor::new(Vec::::new()); + let result = read_frame(&mut cursor); + assert!(result.is_ok()); + assert!(result.ok().flatten().is_none()); + } + + #[test] + fn read_frame_empty_gap_then_data() { + let data = b"after_gap"; + let mut input = vec![0x00]; // empty gap + input.extend_from_slice(&encode_frame(data)); + let mut cursor = std::io::Cursor::new(input); + // First read_frame returns None for the empty gap + let r1 = read_frame(&mut cursor); + assert_eq!(r1.ok().flatten(), None); + // Second read returns the actual frame + let r2 = read_frame(&mut cursor); + assert_eq!(r2.ok().flatten().as_deref(), Some(data.as_slice())); + } + + #[test] + fn encode_all_byte_values_roundtrip() { + // Test that all possible byte values survive encode/decode + let data: Vec = (0..=255).collect(); + let encoded = encode_frame(&data); + let decoded = decode_frame(&encoded[..encoded.len() - 1]); + assert_eq!(decoded, Some(data)); + } +} diff --git a/src/connect.rs b/src/connect.rs new file mode 100644 index 0000000..4af999d --- /dev/null +++ b/src/connect.rs @@ -0,0 +1,144 @@ +//! Connection auto-detection and mux client helpers. +//! +//! The [`connect`] function tries mux connections first (TCP via env var, then +//! Unix socket), falling back to direct USB serial. This matches the Python +//! client's `connect()` behavior. + +use std::time::Duration; + +use tracing::debug; + +use crate::client::Client; +use crate::discovery; +use crate::transport::{AnyTransport, MuxTransport, SerialTransport}; + +/// Default read timeout for connections. +const DEFAULT_TIMEOUT: Duration = Duration::from_secs(2); + +/// Resolve the mux socket path in priority order. +/// +/// 1. `$DONGLORA_MUX` environment variable +/// 2. `$XDG_RUNTIME_DIR/donglora/mux.sock` +/// 3. `/tmp/donglora-mux.sock` +pub fn default_socket_path() -> String { + if let Ok(env) = std::env::var("DONGLORA_MUX") { + return env; + } + if let Ok(xdg) = std::env::var("XDG_RUNTIME_DIR") { + return format!("{xdg}/donglora/mux.sock"); + } + "/tmp/donglora-mux.sock".to_string() +} + +/// Find an existing mux socket path, or `None` if no socket file exists. +fn find_mux_socket() -> Option { + if let Ok(env) = std::env::var("DONGLORA_MUX") { + if std::path::Path::new(&env).exists() { + return Some(env); + } + return None; + } + if let Ok(xdg) = std::env::var("XDG_RUNTIME_DIR") { + let p = format!("{xdg}/donglora/mux.sock"); + if std::path::Path::new(&p).exists() { + return Some(p); + } + } + let p = "/tmp/donglora-mux.sock"; + if std::path::Path::new(p).exists() { + return Some(p.to_string()); + } + None +} + +/// Connect to the mux daemon via Unix domain socket. +#[cfg(unix)] +pub fn mux_connect( + path: Option<&str>, + timeout: Duration, +) -> anyhow::Result> { + let path = match path { + Some(p) => p.to_string(), + None => find_mux_socket() + .ok_or_else(|| anyhow::anyhow!("no mux socket found"))?, + }; + let transport = MuxTransport::unix(&path, timeout)?; + Ok(Client::new(transport)) +} + +/// Connect to the mux daemon via TCP. +pub fn mux_tcp_connect( + host: &str, + port: u16, + timeout: Duration, +) -> anyhow::Result> { + let transport = MuxTransport::tcp(host, port, timeout)?; + Ok(Client::new(transport)) +} + +/// Auto-detect and connect to a DongLoRa device. +/// +/// Priority: +/// 1. `DONGLORA_MUX_TCP` env var → TCP mux connection +/// 2. Unix socket mux (if socket file exists) +/// 3. Direct USB serial (auto-detect by VID:PID, blocks until device appears) +/// +/// If `port` is `Some`, skips mux detection and connects directly to that serial port. +pub fn connect( + port: Option<&str>, + timeout: Duration, +) -> anyhow::Result> { + // If explicit port given, go direct + if let Some(port) = port { + debug!("opening serial port {port}"); + let transport = SerialTransport::open(port, timeout)?; + return Ok(Client::new(AnyTransport::Serial(transport))); + } + + // Try TCP mux via environment variable + if let Ok(tcp) = std::env::var("DONGLORA_MUX_TCP") + && let Some(transport) = try_tcp_mux(&tcp, timeout) + { + debug!("connected to TCP mux at {tcp}"); + return Ok(Client::new(AnyTransport::Mux(transport))); + } + + // Try Unix socket mux + #[cfg(unix)] + if let Some(path) = find_mux_socket() { + match MuxTransport::unix(&path, timeout) { + Ok(transport) => { + debug!("connected to mux socket at {path}"); + return Ok(Client::new(AnyTransport::Mux(transport))); + } + Err(_) => { + // Stale socket or connection refused — fall through + debug!("mux socket at {path} not reachable, falling back to USB"); + } + } + } + + // Direct USB serial — auto-detect or wait + let port_path = discovery::find_port() + .unwrap_or_else(discovery::wait_for_device); + debug!("opening serial port {port_path}"); + let transport = SerialTransport::open(&port_path, timeout)?; + Ok(Client::new(AnyTransport::Serial(transport))) +} + +/// Convenience: connect with default timeout. +pub fn connect_default() -> anyhow::Result> { + connect(None, DEFAULT_TIMEOUT) +} + +fn try_tcp_mux(addr: &str, timeout: Duration) -> Option { + let (host, port) = if let Some((h, p)) = addr.rsplit_once(':') { + let host = if h.is_empty() { "localhost" } else { h }; + let port: u16 = p.parse().ok()?; + (host.to_string(), port) + } else { + let port: u16 = addr.parse().ok()?; + ("localhost".to_string(), port) + }; + MuxTransport::tcp(&host, port, timeout).ok() +} diff --git a/src/discovery.rs b/src/discovery.rs new file mode 100644 index 0000000..f5392a8 --- /dev/null +++ b/src/discovery.rs @@ -0,0 +1,47 @@ +//! USB device discovery for DongLoRa dongles. +//! +//! Finds the serial port by matching USB VID:PID using the `serialport` crate. + +use std::thread; +use std::time::Duration; + +use tracing::info; + +/// DongLoRa USB Vendor ID. +pub const USB_VID: u16 = 0x1209; + +/// DongLoRa USB Product ID. +pub const USB_PID: u16 = 0x5741; + +/// Find the DongLoRa serial port by USB VID:PID. +/// +/// Returns the first matching port path, or `None` if no device is found. +pub fn find_port() -> Option { + let ports = serialport::available_ports().ok()?; + ports + .into_iter() + .find(|p| { + matches!( + &p.port_type, + serialport::SerialPortType::UsbPort(info) + if info.vid == USB_VID && info.pid == USB_PID + ) + }) + .map(|p| p.port_name) +} + +/// Block until a DongLoRa device appears on USB. +/// +/// Polls [`find_port`] every 500ms and returns the port path once found. +pub fn wait_for_device() -> String { + info!("waiting for DongLoRa device..."); + loop { + if let Some(port) = find_port() { + info!("found device at {port}"); + // Brief delay for USB enumeration to settle + thread::sleep(Duration::from_millis(300)); + return port; + } + thread::sleep(Duration::from_millis(500)); + } +} diff --git a/src/lib.rs b/src/lib.rs new file mode 100644 index 0000000..91c3be9 --- /dev/null +++ b/src/lib.rs @@ -0,0 +1,45 @@ +//! DongLoRa host library — connect, configure, send/receive LoRa packets. +//! +//! Implements the DongLoRa USB protocol (COBS-framed fixed-size LE). +//! See `firmware/PROTOCOL.md` for the full specification. +//! +//! # Quick start +//! +//! ```no_run +//! use donglora_client::*; +//! +//! let mut client = connect_default()?; +//! client.ping()?; +//! client.set_config(RadioConfig::default())?; +//! client.start_rx()?; +//! +//! loop { +//! if let Some(Response::RxPacket { rssi, snr, payload }) = client.recv()? { +//! println!("RX rssi={rssi} snr={snr} len={}", payload.len()); +//! } +//! } +//! # Ok::<(), anyhow::Error>(()) +//! ``` + +pub mod client; +pub mod codec; +pub mod connect; +pub mod discovery; +pub mod protocol; +pub mod transport; + +// Flat re-exports for convenience +pub use client::Client; +pub use codec::{decode_frame, encode_frame, read_frame, FrameReader}; +pub use connect::{connect, connect_default, default_socket_path}; +pub use discovery::{find_port, wait_for_device, USB_PID, USB_VID}; +pub use protocol::{ + Bandwidth, Command, ErrorCode, RadioConfig, Response, CMD_TAG_SET_CONFIG, CMD_TAG_START_RX, + CMD_TAG_STOP_RX, ERROR_INVALID_CONFIG, MAX_PAYLOAD, PREAMBLE_DEFAULT, RADIO_CONFIG_SIZE, + RESP_TAG_ERROR, RESP_TAG_OK, RESP_TAG_RX_PACKET, TX_POWER_MAX, +}; +pub use transport::{AnyTransport, MuxTransport, SerialTransport, Transport}; + +#[cfg(unix)] +pub use connect::mux_connect; +pub use connect::mux_tcp_connect; diff --git a/src/protocol.rs b/src/protocol.rs new file mode 100644 index 0000000..a84ed18 --- /dev/null +++ b/src/protocol.rs @@ -0,0 +1,693 @@ +//! Wire protocol types and fixed-size little-endian serialization. +//! +//! Mirrors the firmware's `protocol.rs` using std types. Every integer is +//! fixed-width LE. See `firmware/PROTOCOL.md` for the full specification. + +/// Maximum LoRa payload size in bytes. +pub const MAX_PAYLOAD: usize = 256; + +/// RadioConfig wire size (fixed). +pub const RADIO_CONFIG_SIZE: usize = 13; + +/// Sentinel value for `tx_power_dbm`: use the board's maximum TX power. +pub const TX_POWER_MAX: i8 = i8::MIN; // -128 on the wire + +/// Sentinel value for `preamble_len`: use the firmware default (16 symbols). +pub const PREAMBLE_DEFAULT: u16 = 0; + +// ── Tag constants ────────────────────────────────────────────────── + +/// Command tag for SetConfig. +pub const CMD_TAG_SET_CONFIG: u8 = 2; +/// Command tag for StartRx. +pub const CMD_TAG_START_RX: u8 = 3; +/// Command tag for StopRx. +pub const CMD_TAG_STOP_RX: u8 = 4; + +/// Response tag for RxPacket. +pub const RESP_TAG_RX_PACKET: u8 = 2; +/// Response tag for Ok. +pub const RESP_TAG_OK: u8 = 4; +/// Response tag for Error. +pub const RESP_TAG_ERROR: u8 = 5; + +/// Error code for InvalidConfig. +pub const ERROR_INVALID_CONFIG: u8 = 0; + +// ── Bandwidth ────────────────────────────────────────────────────── + +/// LoRa signal bandwidth. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[repr(u8)] +pub enum Bandwidth { + Khz7 = 0, + Khz10 = 1, + Khz15 = 2, + Khz20 = 3, + Khz31 = 4, + Khz41 = 5, + Khz62 = 6, + Khz125 = 7, + Khz250 = 8, + Khz500 = 9, +} + +impl Bandwidth { + /// Convert from raw byte. Returns `None` for invalid values. + pub fn from_u8(v: u8) -> Option { + match v { + 0 => Some(Self::Khz7), + 1 => Some(Self::Khz10), + 2 => Some(Self::Khz15), + 3 => Some(Self::Khz20), + 4 => Some(Self::Khz31), + 5 => Some(Self::Khz41), + 6 => Some(Self::Khz62), + 7 => Some(Self::Khz125), + 8 => Some(Self::Khz250), + 9 => Some(Self::Khz500), + _ => None, + } + } +} + +// ── RadioConfig ──────────────────────────────────────────────────── + +/// Complete LoRa radio configuration. +/// +/// Wire layout (13 bytes, all little-endian): +/// ```text +/// [freq_hz:4] [bw:1] [sf:1] [cr:1] [sync_word:2] [tx_power_dbm:1] [preamble_len:2] [cad:1] +/// ``` +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct RadioConfig { + /// Frequency in Hz (150_000_000 - 960_000_000 for SX1262). + pub freq_hz: u32, + pub bw: Bandwidth, + /// Spreading factor (5-12). + pub sf: u8, + /// Coding rate denominator (5-8). E.g. 5 = CR 4/5, 8 = CR 4/8. + pub cr: u8, + pub sync_word: u16, + /// Transmit power in dBm. Set to [`TX_POWER_MAX`] (-128) for the board's maximum. + pub tx_power_dbm: i8, + /// Preamble length in symbols. Set to [`PREAMBLE_DEFAULT`] (0) for firmware default (16). + pub preamble_len: u16, + /// Channel Activity Detection (listen-before-talk). 0 = disabled, non-zero = enabled. + pub cad: u8, +} + +impl RadioConfig { + /// Serialize to fixed-size LE bytes. + pub fn to_bytes(&self) -> [u8; RADIO_CONFIG_SIZE] { + let mut buf = [0u8; RADIO_CONFIG_SIZE]; + buf[0..4].copy_from_slice(&self.freq_hz.to_le_bytes()); + buf[4] = self.bw as u8; + buf[5] = self.sf; + buf[6] = self.cr; + buf[7..9].copy_from_slice(&self.sync_word.to_le_bytes()); + buf[9] = self.tx_power_dbm as u8; + buf[10..12].copy_from_slice(&self.preamble_len.to_le_bytes()); + buf[12] = self.cad; + buf + } + + /// Deserialize from fixed-size LE bytes. Returns `None` if too short or invalid. + pub fn from_bytes(buf: &[u8]) -> Option { + if buf.len() < RADIO_CONFIG_SIZE { + return None; + } + Some(Self { + freq_hz: u32::from_le_bytes([buf[0], buf[1], buf[2], buf[3]]), + bw: Bandwidth::from_u8(buf[4])?, + sf: buf[5], + cr: buf[6], + sync_word: u16::from_le_bytes([buf[7], buf[8]]), + tx_power_dbm: buf[9] as i8, + preamble_len: u16::from_le_bytes([buf[10], buf[11]]), + cad: buf[12], + }) + } +} + +/// Default: 915 MHz, 125 kHz BW, SF7, CR 4/5, sync 0x1424, max power, default preamble, CAD on. +impl Default for RadioConfig { + fn default() -> Self { + Self { + freq_hz: 915_000_000, + bw: Bandwidth::Khz125, + sf: 7, + cr: 5, + sync_word: 0x1424, + tx_power_dbm: TX_POWER_MAX, + preamble_len: PREAMBLE_DEFAULT, + cad: 1, + } + } +} + +// ── Command ──────────────────────────────────────────────────────── + +/// Host → firmware commands. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Command { + Ping, + GetConfig, + SetConfig(RadioConfig), + StartRx, + StopRx, + Transmit { + config: Option, + payload: Vec, + }, + DisplayOn, + DisplayOff, + GetMac, +} + +impl Command { + /// Returns the wire tag byte for this command. + pub fn tag(&self) -> u8 { + match self { + Self::Ping => 0, + Self::GetConfig => 1, + Self::SetConfig(_) => 2, + Self::StartRx => 3, + Self::StopRx => 4, + Self::Transmit { .. } => 5, + Self::DisplayOn => 6, + Self::DisplayOff => 7, + Self::GetMac => 8, + } + } + + /// Serialize to fixed-size LE bytes. + pub fn to_bytes(&self) -> Vec { + match self { + Self::Ping => vec![0], + Self::GetConfig => vec![1], + Self::SetConfig(cfg) => { + let mut out = vec![2]; + out.extend_from_slice(&cfg.to_bytes()); + out + } + Self::StartRx => vec![3], + Self::StopRx => vec![4], + Self::Transmit { config, payload } => { + let mut out = vec![5]; + match config { + None => out.push(0), + Some(cfg) => { + out.push(1); + out.extend_from_slice(&cfg.to_bytes()); + } + } + out.extend_from_slice(&(payload.len() as u16).to_le_bytes()); + out.extend_from_slice(payload); + out + } + Self::DisplayOn => vec![6], + Self::DisplayOff => vec![7], + Self::GetMac => vec![8], + } + } + + /// Deserialize from a decoded frame. Returns `None` on malformed input. + pub fn from_bytes(buf: &[u8]) -> Option { + let tag = *buf.first()?; + let rest = &buf[1..]; + match tag { + 0 => Some(Self::Ping), + 1 => Some(Self::GetConfig), + 2 => Some(Self::SetConfig(RadioConfig::from_bytes(rest)?)), + 3 => Some(Self::StartRx), + 4 => Some(Self::StopRx), + 5 => { + if rest.is_empty() { + return None; + } + let (config, pos) = if rest[0] == 0 { + (None, 1) + } else if rest[0] == 1 && rest.len() > RADIO_CONFIG_SIZE { + (Some(RadioConfig::from_bytes(&rest[1..])?), 1 + RADIO_CONFIG_SIZE) + } else { + return None; + }; + if rest.len() < pos + 2 { + return None; + } + let len = u16::from_le_bytes([rest[pos], rest[pos + 1]]) as usize; + let data_start = pos + 2; + if rest.len() < data_start + len || len > MAX_PAYLOAD { + return None; + } + Some(Self::Transmit { + config, + payload: rest[data_start..data_start + len].to_vec(), + }) + } + 6 => Some(Self::DisplayOn), + 7 => Some(Self::DisplayOff), + 8 => Some(Self::GetMac), + _ => None, + } + } +} + +// ── ErrorCode ────────────────────────────────────────────────────── + +/// Error codes reported by the firmware. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[repr(u8)] +pub enum ErrorCode { + InvalidConfig = 0, + RadioBusy = 1, + TxTimeout = 2, + CrcError = 3, + NotConfigured = 4, + NoDisplay = 5, +} + +impl ErrorCode { + /// Convert from raw byte. Returns `None` for unknown codes. + pub fn from_u8(v: u8) -> Option { + match v { + 0 => Some(Self::InvalidConfig), + 1 => Some(Self::RadioBusy), + 2 => Some(Self::TxTimeout), + 3 => Some(Self::CrcError), + 4 => Some(Self::NotConfigured), + 5 => Some(Self::NoDisplay), + _ => None, + } + } +} + +impl std::fmt::Display for ErrorCode { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::InvalidConfig => write!(f, "InvalidConfig"), + Self::RadioBusy => write!(f, "RadioBusy"), + Self::TxTimeout => write!(f, "TxTimeout"), + Self::CrcError => write!(f, "CrcError"), + Self::NotConfigured => write!(f, "NotConfigured"), + Self::NoDisplay => write!(f, "NoDisplay"), + } + } +} + +// ── Response ─────────────────────────────────────────────────────── + +/// Firmware → host responses. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Response { + Pong, + Config(RadioConfig), + RxPacket { + rssi: i16, + snr: i16, + payload: Vec, + }, + TxDone, + Ok, + Error(ErrorCode), + MacAddress([u8; 6]), +} + +impl Response { + /// Returns the wire tag byte for this response. + pub fn tag(&self) -> u8 { + match self { + Self::Pong => 0, + Self::Config(_) => 1, + Self::RxPacket { .. } => 2, + Self::TxDone => 3, + Self::Ok => 4, + Self::Error(_) => 5, + Self::MacAddress(_) => 6, + } + } + + /// Whether this is an unsolicited RxPacket. + pub fn is_rx_packet(&self) -> bool { + matches!(self, Self::RxPacket { .. }) + } + + /// Serialize to fixed-size LE bytes. + pub fn to_bytes(&self) -> Vec { + match self { + Self::Pong => vec![0], + Self::Config(cfg) => { + let mut out = vec![1]; + out.extend_from_slice(&cfg.to_bytes()); + out + } + Self::RxPacket { rssi, snr, payload } => { + let mut out = vec![2]; + out.extend_from_slice(&rssi.to_le_bytes()); + out.extend_from_slice(&snr.to_le_bytes()); + out.extend_from_slice(&(payload.len() as u16).to_le_bytes()); + out.extend_from_slice(payload); + out + } + Self::TxDone => vec![3], + Self::Ok => vec![4], + Self::Error(code) => vec![5, *code as u8], + Self::MacAddress(mac) => { + let mut out = vec![6]; + out.extend_from_slice(mac); + out + } + } + } + + /// Deserialize from a decoded frame. Returns `None` on malformed input. + pub fn from_bytes(buf: &[u8]) -> Option { + let tag = *buf.first()?; + let rest = &buf[1..]; + match tag { + 0 => Some(Self::Pong), + 1 => Some(Self::Config(RadioConfig::from_bytes(rest)?)), + 2 => { + if rest.len() < 6 { + return None; + } + let rssi = i16::from_le_bytes([rest[0], rest[1]]); + let snr = i16::from_le_bytes([rest[2], rest[3]]); + let len = u16::from_le_bytes([rest[4], rest[5]]) as usize; + if rest.len() < 6 + len || len > MAX_PAYLOAD { + return None; + } + Some(Self::RxPacket { + rssi, + snr, + payload: rest[6..6 + len].to_vec(), + }) + } + 3 => Some(Self::TxDone), + 4 => Some(Self::Ok), + 5 => Some(Self::Error(ErrorCode::from_u8(*rest.first()?)?)), + 6 => { + if rest.len() < 6 { + return None; + } + let mut mac = [0u8; 6]; + mac.copy_from_slice(&rest[..6]); + Some(Self::MacAddress(mac)) + } + _ => None, + } + } +} + +// ── Tests ────────────────────────────────────────────────────────── + +#[cfg(test)] +mod tests { + use super::*; + + fn make_config() -> RadioConfig { + RadioConfig { + freq_hz: 915_000_000, + bw: Bandwidth::Khz125, + sf: 7, + cr: 5, + sync_word: 0x3444, + tx_power_dbm: 22, + preamble_len: 16, + cad: 1, + } + } + + // ── RadioConfig ──────────────────────────────────────────────── + + #[test] + fn radio_config_roundtrip() { + let cfg = make_config(); + let bytes = cfg.to_bytes(); + assert_eq!(bytes.len(), RADIO_CONFIG_SIZE); + assert_eq!(RadioConfig::from_bytes(&bytes), Some(cfg)); + } + + #[test] + fn radio_config_default_roundtrip() { + let cfg = RadioConfig::default(); + let bytes = cfg.to_bytes(); + assert_eq!(RadioConfig::from_bytes(&bytes), Some(cfg)); + } + + #[test] + fn radio_config_all_bandwidths() { + for bw_val in 0u8..=9 { + let bw = Bandwidth::from_u8(bw_val); + assert!(bw.is_some(), "bandwidth {bw_val} should be valid"); + let cfg = RadioConfig { bw: bw.unwrap(), ..make_config() }; + let bytes = cfg.to_bytes(); + assert_eq!(RadioConfig::from_bytes(&bytes), Some(cfg)); + } + } + + #[test] + fn radio_config_invalid_bandwidth() { + let mut buf = make_config().to_bytes(); + buf[4] = 255; + assert!(RadioConfig::from_bytes(&buf).is_none()); + } + + #[test] + fn radio_config_negative_power() { + let cfg = RadioConfig { tx_power_dbm: TX_POWER_MAX, ..make_config() }; + let bytes = cfg.to_bytes(); + assert_eq!(RadioConfig::from_bytes(&bytes), Some(cfg)); + } + + #[test] + fn radio_config_short_buffer() { + assert!(RadioConfig::from_bytes(&[0u8; 12]).is_none()); + assert!(RadioConfig::from_bytes(&[]).is_none()); + } + + // ── Command ──────────────────────────────────────────────────── + + #[test] + fn command_simple_roundtrips() { + for cmd in [ + Command::Ping, + Command::GetConfig, + Command::StartRx, + Command::StopRx, + Command::DisplayOn, + Command::DisplayOff, + Command::GetMac, + ] { + let bytes = cmd.to_bytes(); + assert_eq!(Command::from_bytes(&bytes), Some(cmd)); + } + } + + #[test] + fn command_set_config_roundtrip() { + let cmd = Command::SetConfig(make_config()); + let bytes = cmd.to_bytes(); + assert_eq!(Command::from_bytes(&bytes), Some(cmd)); + } + + #[test] + fn command_transmit_no_config_roundtrip() { + let cmd = Command::Transmit { + config: None, + payload: b"hello".to_vec(), + }; + let bytes = cmd.to_bytes(); + assert_eq!(Command::from_bytes(&bytes), Some(cmd)); + } + + #[test] + fn command_transmit_with_config_roundtrip() { + let cmd = Command::Transmit { + config: Some(make_config()), + payload: b"test".to_vec(), + }; + let bytes = cmd.to_bytes(); + assert_eq!(Command::from_bytes(&bytes), Some(cmd)); + } + + #[test] + fn command_transmit_empty_payload() { + let cmd = Command::Transmit { + config: None, + payload: vec![], + }; + let bytes = cmd.to_bytes(); + assert_eq!(Command::from_bytes(&bytes), Some(cmd)); + } + + #[test] + fn command_transmit_truncated() { + assert!(Command::from_bytes(&[5]).is_none()); // tag only + assert!(Command::from_bytes(&[5, 1]).is_none()); // has_config=1, no config + assert!(Command::from_bytes(&[5, 0]).is_none()); // has_config=0, no length + } + + #[test] + fn command_invalid_tag() { + assert!(Command::from_bytes(&[9]).is_none()); + assert!(Command::from_bytes(&[255]).is_none()); + } + + #[test] + fn command_empty_buffer() { + assert!(Command::from_bytes(&[]).is_none()); + } + + #[test] + fn command_tags() { + assert_eq!(Command::Ping.tag(), 0); + assert_eq!(Command::GetConfig.tag(), 1); + assert_eq!(Command::SetConfig(make_config()).tag(), 2); + assert_eq!(Command::StartRx.tag(), 3); + assert_eq!(Command::StopRx.tag(), 4); + assert_eq!(Command::Transmit { config: None, payload: vec![] }.tag(), 5); + assert_eq!(Command::DisplayOn.tag(), 6); + assert_eq!(Command::DisplayOff.tag(), 7); + assert_eq!(Command::GetMac.tag(), 8); + } + + // ── Response ─────────────────────────────────────────────────── + + #[test] + fn response_simple_roundtrips() { + for resp in [Response::Pong, Response::TxDone, Response::Ok] { + let bytes = resp.to_bytes(); + assert_eq!(Response::from_bytes(&bytes), Some(resp)); + } + } + + #[test] + fn response_config_roundtrip() { + let resp = Response::Config(make_config()); + let bytes = resp.to_bytes(); + assert_eq!(Response::from_bytes(&bytes), Some(resp)); + } + + #[test] + fn response_rx_packet_roundtrip() { + let resp = Response::RxPacket { + rssi: -80, + snr: 10, + payload: b"data".to_vec(), + }; + let bytes = resp.to_bytes(); + assert_eq!(Response::from_bytes(&bytes), Some(resp)); + } + + #[test] + fn response_rx_packet_empty_payload() { + let resp = Response::RxPacket { + rssi: -120, + snr: -5, + payload: vec![], + }; + let bytes = resp.to_bytes(); + assert_eq!(Response::from_bytes(&bytes), Some(resp)); + } + + #[test] + fn response_error_codes() { + for code in [ + ErrorCode::InvalidConfig, + ErrorCode::RadioBusy, + ErrorCode::TxTimeout, + ErrorCode::CrcError, + ErrorCode::NotConfigured, + ErrorCode::NoDisplay, + ] { + let resp = Response::Error(code); + let bytes = resp.to_bytes(); + assert_eq!(Response::from_bytes(&bytes), Some(resp)); + } + } + + #[test] + fn response_mac_address_roundtrip() { + let resp = Response::MacAddress([0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF]); + let bytes = resp.to_bytes(); + assert_eq!(Response::from_bytes(&bytes), Some(resp)); + } + + #[test] + fn response_tags() { + assert_eq!(Response::Pong.tag(), 0); + assert_eq!(Response::Config(make_config()).tag(), 1); + assert_eq!( + Response::RxPacket { rssi: 0, snr: 0, payload: vec![] }.tag(), + 2 + ); + assert_eq!(Response::TxDone.tag(), 3); + assert_eq!(Response::Ok.tag(), 4); + assert_eq!(Response::Error(ErrorCode::RadioBusy).tag(), 5); + assert_eq!(Response::MacAddress([0; 6]).tag(), 6); + } + + #[test] + fn response_is_rx_packet() { + assert!(Response::RxPacket { rssi: 0, snr: 0, payload: vec![] }.is_rx_packet()); + assert!(!Response::Ok.is_rx_packet()); + assert!(!Response::Pong.is_rx_packet()); + } + + #[test] + fn response_invalid_tag() { + assert!(Response::from_bytes(&[7]).is_none()); + assert!(Response::from_bytes(&[255]).is_none()); + } + + #[test] + fn response_truncated() { + assert!(Response::from_bytes(&[]).is_none()); + assert!(Response::from_bytes(&[5]).is_none()); // Error with no code + assert!(Response::from_bytes(&[2, 0, 0]).is_none()); // RxPacket too short + assert!(Response::from_bytes(&[6, 0, 0, 0]).is_none()); // MacAddress too short + } + + // ── ErrorCode ────────────────────────────────────────────────── + + #[test] + fn error_code_from_u8() { + for v in 0..=5 { + assert!(ErrorCode::from_u8(v).is_some()); + } + assert!(ErrorCode::from_u8(6).is_none()); + assert!(ErrorCode::from_u8(255).is_none()); + } + + #[test] + fn error_code_display() { + assert_eq!(ErrorCode::InvalidConfig.to_string(), "InvalidConfig"); + assert_eq!(ErrorCode::RadioBusy.to_string(), "RadioBusy"); + } + + // ── Cross-compatibility with firmware encoding ───────────────── + + #[test] + fn firmware_worked_example() { + // From PROTOCOL.md: 915 MHz, 125 kHz BW, SF7, CR 4/5, sync 0x1424, max power + let cfg = RadioConfig { + freq_hz: 915_000_000, + bw: Bandwidth::Khz125, + sf: 7, + cr: 5, + sync_word: 0x1424, + tx_power_dbm: TX_POWER_MAX, + preamble_len: PREAMBLE_DEFAULT, + cad: 1, + }; + let cmd = Command::SetConfig(cfg); + let bytes = cmd.to_bytes(); + // Expected: 02 C0 CA 89 36 07 07 05 24 14 80 00 00 01 + assert_eq!( + bytes, + [0x02, 0xC0, 0xCA, 0x89, 0x36, 0x07, 0x07, 0x05, 0x24, 0x14, 0x80, 0x00, 0x00, 0x01] + ); + } +} diff --git a/src/transport.rs b/src/transport.rs new file mode 100644 index 0000000..101dca5 --- /dev/null +++ b/src/transport.rs @@ -0,0 +1,210 @@ +//! Transport abstraction for byte-stream connections. +//! +//! The [`Transport`] trait unifies serial ports and mux socket connections, +//! allowing the [`Client`](crate::client::Client) to work over any of them. + +use std::io::{self, Read, Write}; +use std::time::Duration; + +/// A byte-stream transport that the client can talk over. +pub trait Transport: Read + Write + Send { + /// Set the read timeout. A read that takes longer returns zero bytes. + fn set_timeout(&mut self, timeout: Duration) -> anyhow::Result<()>; + + /// Get the current read timeout. + fn timeout(&self) -> Duration; +} + +// ── Serial transport ─────────────────────────────────────────────── + +/// Direct USB serial port connection to a DongLoRa dongle. +pub struct SerialTransport { + port: Box, +} + +impl SerialTransport { + /// Open a serial port with the given timeout. + /// + /// Baud rate is irrelevant for USB CDC-ACM but we pass a conventional value. + pub fn open(path: &str, timeout: Duration) -> anyhow::Result { + let port = serialport::new(path, 115_200) + .timeout(timeout) + .open() + .map_err(|e| anyhow::anyhow!("failed to open serial port {path}: {e}"))?; + Ok(Self { port }) + } + + /// Clear the serial input buffer. + pub fn reset_input_buffer(&self) -> anyhow::Result<()> { + self.port + .clear(serialport::ClearBuffer::Input) + .map_err(|e| anyhow::anyhow!("failed to clear input buffer: {e}")) + } +} + +impl Read for SerialTransport { + fn read(&mut self, buf: &mut [u8]) -> io::Result { + self.port.read(buf) + } +} + +impl Write for SerialTransport { + fn write(&mut self, buf: &[u8]) -> io::Result { + self.port.write(buf) + } + + fn flush(&mut self) -> io::Result<()> { + self.port.flush() + } +} + +impl Transport for SerialTransport { + fn set_timeout(&mut self, timeout: Duration) -> anyhow::Result<()> { + self.port + .set_timeout(timeout) + .map_err(|e| anyhow::anyhow!("failed to set serial timeout: {e}")) + } + + fn timeout(&self) -> Duration { + // serialport doesn't have a getter, so we'd need to track it ourselves. + // For now, return a sensible default. The actual timeout is set on the port. + Duration::from_secs(2) + } +} + +// ── Mux transport ────────────────────────────────────────────────── + +/// Connection to the DongLoRa mux daemon via Unix socket or TCP. +pub struct MuxTransport { + stream: MuxStream, + timeout: Duration, +} + +enum MuxStream { + #[cfg(unix)] + Unix(std::os::unix::net::UnixStream), + Tcp(std::net::TcpStream), +} + +impl MuxTransport { + /// Connect to the mux daemon via Unix domain socket. + #[cfg(unix)] + pub fn unix(path: &str, timeout: Duration) -> anyhow::Result { + let stream = std::os::unix::net::UnixStream::connect(path) + .map_err(|e| anyhow::anyhow!("failed to connect to mux socket {path}: {e}"))?; + stream + .set_read_timeout(Some(timeout)) + .map_err(|e| anyhow::anyhow!("failed to set socket timeout: {e}"))?; + Ok(Self { + stream: MuxStream::Unix(stream), + timeout, + }) + } + + /// Connect to the mux daemon via TCP. + pub fn tcp(host: &str, port: u16, timeout: Duration) -> anyhow::Result { + let addr = format!("{host}:{port}"); + let stream = std::net::TcpStream::connect(&addr) + .map_err(|e| anyhow::anyhow!("failed to connect to mux at {addr}: {e}"))?; + stream + .set_read_timeout(Some(timeout)) + .map_err(|e| anyhow::anyhow!("failed to set TCP timeout: {e}"))?; + Ok(Self { + stream: MuxStream::Tcp(stream), + timeout, + }) + } +} + +impl Read for MuxTransport { + fn read(&mut self, buf: &mut [u8]) -> io::Result { + match &mut self.stream { + #[cfg(unix)] + MuxStream::Unix(s) => s.read(buf), + MuxStream::Tcp(s) => s.read(buf), + } + } +} + +impl Write for MuxTransport { + fn write(&mut self, buf: &[u8]) -> io::Result { + match &mut self.stream { + #[cfg(unix)] + MuxStream::Unix(s) => s.write(buf), + MuxStream::Tcp(s) => s.write(buf), + } + } + + fn flush(&mut self) -> io::Result<()> { + match &mut self.stream { + #[cfg(unix)] + MuxStream::Unix(s) => s.flush(), + MuxStream::Tcp(s) => s.flush(), + } + } +} + +impl Transport for MuxTransport { + fn set_timeout(&mut self, timeout: Duration) -> anyhow::Result<()> { + self.timeout = timeout; + let result = match &self.stream { + #[cfg(unix)] + MuxStream::Unix(s) => s.set_read_timeout(Some(timeout)), + MuxStream::Tcp(s) => s.set_read_timeout(Some(timeout)), + }; + result.map_err(|e| anyhow::anyhow!("failed to set timeout: {e}")) + } + + fn timeout(&self) -> Duration { + self.timeout + } +} + +// ── AnyTransport ─────────────────────────────────────────────────── + +/// Type-erased transport for the [`connect`](crate::connect::connect) return type. +pub enum AnyTransport { + Serial(SerialTransport), + Mux(MuxTransport), +} + +impl Read for AnyTransport { + fn read(&mut self, buf: &mut [u8]) -> io::Result { + match self { + Self::Serial(t) => t.read(buf), + Self::Mux(t) => t.read(buf), + } + } +} + +impl Write for AnyTransport { + fn write(&mut self, buf: &[u8]) -> io::Result { + match self { + Self::Serial(t) => t.write(buf), + Self::Mux(t) => t.write(buf), + } + } + + fn flush(&mut self) -> io::Result<()> { + match self { + Self::Serial(t) => t.flush(), + Self::Mux(t) => t.flush(), + } + } +} + +impl Transport for AnyTransport { + fn set_timeout(&mut self, timeout: Duration) -> anyhow::Result<()> { + match self { + Self::Serial(t) => t.set_timeout(timeout), + Self::Mux(t) => t.set_timeout(timeout), + } + } + + fn timeout(&self) -> Duration { + match self { + Self::Serial(t) => t.timeout(), + Self::Mux(t) => t.timeout(), + } + } +}