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<T> 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.
This commit is contained in:
swaits committed 2026-04-03 17:21:51 -06:00
1 parent f12f72a793
commit 5d66731413
21 files changed
+4049 -6

No files matched your search

+2 -2
View File
@@ -22,8 +22,8 @@ common tasks consume. No shared board code — each board is self-contained.
## Client Libraries
The Python library (`clients/python/`)
is the reference implementation. To add a library in another language:
Client libraries exist in [Python](clients/python/) and [Rust](clients/rust/).
To add a library in another language:
1. Create a directory with the language's standard project layout
2. Implement the wire protocol from [firmware/PROTOCOL.md](firmware/PROTOCOL.md)
+11 -4
View File
@@ -30,8 +30,8 @@ Four components, each self-contained with its own dependencies and tooling:
| Component | What it is | Language |
|-----------|-----------|----------|
| **[firmware/](firmware/)** | Embedded firmware flashed onto a LoRa board. Speaks a simple [binary protocol](firmware/PROTOCOL.md) over USB. | Rust |
| **[clients/](clients/)** | Client libraries that handle device discovery, COBS framing, and protocol encoding/decoding. This is what your code imports. | Python (reference) |
| **[mux/](mux/)** | Optional daemon that lets multiple applications share one dongle. Owns the USB port, exposes a Unix socket (and optional TCP). | Python |
| **[clients/](clients/)** | Client libraries that handle device discovery, COBS framing, and protocol encoding/decoding. This is what your code imports. | [Python](clients/python/), [Rust](clients/rust/) |
| **[mux/](mux/)** | Optional daemon that lets multiple applications share one dongle. Owns the USB port, exposes a Unix socket (and optional TCP). | [Python](mux/python/), [Rust](mux/rust/) |
| **[examples/](examples/)** | Ready-to-run scripts demonstrating the client library — receive, transmit, bridge, MeshCore decoder, AI bot. | Python |
The client library can talk directly to the firmware over USB, or connect
@@ -73,10 +73,17 @@ just telemetry # MeshCore repeater telemetry monitor
To share one dongle across multiple applications, run the mux daemon:
```sh
# Python
cd mux/python
just run # start the mux daemon
just verbose # start with verbose logging
just run --tcp 5741 --port /dev/ttyACM0 # with explicit options
# Rust
cd mux/rust
just run # start the mux daemon
just verbose # start with verbose logging
just run -- --tcp 5741 --port /dev/ttyACM0 # with explicit options
```
The mux owns the USB serial port exclusively and exposes a Unix socket
@@ -139,7 +146,7 @@ just test # host-side protocol unit tests
The protocol is 8 commands over COBS-framed LE. Any language that can
open a serial port can speak DongLoRa.
- [ ] **Rust** crate — async, tokio-native, zero-copy COBS
- [x] **Rust** crate — async, tokio-native, zero-copy COBS
- [ ] **Go** module — goroutine-friendly, cross-platform
- [ ] **C** library — `libdonglora` for FFI from any language
- [ ] **Ruby** gem — simple protocol, weekend gem, new community
@@ -147,7 +154,7 @@ open a serial port can speak DongLoRa.
### Then: Infrastructure and Tooling
- [ ] Cross-platform mux daemon rewritten in Rust (single static binary, no Python required)
- [x] Cross-platform mux daemon rewritten in Rust (single static binary, no Python required)
- [ ] `donglora-ctl` CLI — ping, configure, receive, transmit, scan frequencies. Think `ip link` for LoRa.
- [ ] Protocol versioning — version handshake so client libraries can detect firmware capabilities
- [ ] Firmware OTA over USB — field-upgradeable without a flash tool
+1
View File
@@ -0,0 +1 @@
/target
+329
View File
@@ -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"
+21
View File
@@ -0,0 +1,21 @@
[package]
name = "donglora-client"
version = "0.1.0"
edition = "2024"
authors = ["Stephen Waits <steve@waits.net>"]
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"
+11
View File
@@ -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
+215
View File
@@ -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<T: Transport> {
transport: T,
rx_buffer: VecDeque<Response>,
}
impl<T: Transport> Client<T> {
/// 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<Response> {
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<Option<Response>> {
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<Vec<Response>> {
let mut packets: Vec<Response> = 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<RadioConfig>,
) -> 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<RadioConfig> {
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);
}
}
+277
View File
@@ -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<u8> {
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<Vec<u8>> {
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<u8>,
}
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<Vec<u8>> {
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<Option<Vec<u8>>> {
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::<u8>::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<u8> = (0..=255).collect();
let encoded = encode_frame(&data);
let decoded = decode_frame(&encoded[..encoded.len() - 1]);
assert_eq!(decoded, Some(data));
}
}
+144
View File
@@ -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<String> {
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<Client<MuxTransport>> {
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<Client<MuxTransport>> {
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<Client<AnyTransport>> {
// 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<Client<AnyTransport>> {
connect(None, DEFAULT_TIMEOUT)
}
fn try_tcp_mux(addr: &str, timeout: Duration) -> Option<MuxTransport> {
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()
}
+47
View File
@@ -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<String> {
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));
}
}
+45
View File
@@ -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;
+693
View File
@@ -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<Self> {
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<Self> {
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<RadioConfig>,
payload: Vec<u8>,
},
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<u8> {
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<Self> {
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<Self> {
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<u8>,
},
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<u8> {
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<Self> {
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]
);
}
}
+210
View File
@@ -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<dyn serialport::SerialPort>,
}
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<Self> {
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<usize> {
self.port.read(buf)
}
}
impl Write for SerialTransport {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
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<Self> {
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<Self> {
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<usize> {
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<usize> {
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<usize> {
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<usize> {
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(),
}
}
}
+1
View File
@@ -0,0 +1 @@
/target
+903
View File
@@ -0,0 +1,903 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4
[[package]]
name = "aho-corasick"
version = "1.1.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ddd31a130427c27518df266943a5308ed92d4b226cc639f5a8f1002816174301"
dependencies = [
"memchr",
]
[[package]]
name = "anstream"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d"
dependencies = [
"anstyle",
"anstyle-parse",
"anstyle-query",
"anstyle-wincon",
"colorchoice",
"is_terminal_polyfill",
"utf8parse",
]
[[package]]
name = "anstyle"
version = "1.0.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000"
[[package]]
name = "anstyle-parse"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e"
dependencies = [
"utf8parse",
]
[[package]]
name = "anstyle-query"
version = "1.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc"
dependencies = [
"windows-sys 0.61.2",
]
[[package]]
name = "anstyle-wincon"
version = "3.0.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d"
dependencies = [
"anstyle",
"once_cell_polyfill",
"windows-sys 0.61.2",
]
[[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 = "bytes"
version = "1.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1e748733b7cbc798e1434b6ac524f0c1ff2ab456fe201501e6497c8417a4fc33"
[[package]]
name = "cfg-if"
version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"
[[package]]
name = "cfg_aliases"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724"
[[package]]
name = "clap"
version = "4.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b193af5b67834b676abd72466a96c1024e6a6ad978a1f484bd90b85c94041351"
dependencies = [
"clap_builder",
"clap_derive",
]
[[package]]
name = "clap_builder"
version = "4.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "714a53001bf66416adb0e2ef5ac857140e7dc3a0c48fb28b2f10762fc4b5069f"
dependencies = [
"anstream",
"anstyle",
"clap_lex",
"strsim",
]
[[package]]
name = "clap_derive"
version = "4.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1110bd8a634a1ab8cb04345d8d878267d57c3cf1b38d91b71af6686408bbca6a"
dependencies = [
"heck",
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "clap_lex"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c8d4a3bb8b1e0c1050499d1815f5ab16d04f0959b233085fb31653fbfc9d98f9"
[[package]]
name = "cobs"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0fa961b519f0b462e3a3b4a34b64d119eeaca1d59af726fe450bbba07a9fc0a1"
dependencies = [
"thiserror",
]
[[package]]
name = "colorchoice"
version = "1.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570"
[[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 = "donglora-mux"
version = "0.1.0"
dependencies = [
"anyhow",
"clap",
"donglora-client",
"tokio",
"tokio-serial",
"tokio-util",
"tracing",
"tracing-subscriber",
]
[[package]]
name = "errno"
version = "0.3.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
dependencies = [
"libc",
"windows-sys 0.61.2",
]
[[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"
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"
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",
]
[[package]]
name = "futures-sink"
version = "0.3.32"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c39754e157331b013978ec91992bde1ac089843443c49cbc7f46150b0fad0893"
[[package]]
name = "futures-task"
version = "0.3.32"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "037711b3d59c33004d3856fbdc83b99d4ff37a24768fa1be9ce3538a1cde4393"
[[package]]
name = "futures-util"
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",
]
[[package]]
name = "heck"
version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
[[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 = "is_terminal_polyfill"
version = "1.70.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695"
[[package]]
name = "lazy_static"
version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe"
[[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 = "lock_api"
version = "0.4.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965"
dependencies = [
"scopeguard",
]
[[package]]
name = "log"
version = "0.4.29"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5e5032e24019045c762d3c0f28f5b6b8bbf38563a65908389bf7978758920897"
[[package]]
name = "mach2"
version = "0.4.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d640282b302c0bb0a2a8e0233ead9035e3bed871f0b7e81fe4a1ec829765db44"
dependencies = [
"libc",
]
[[package]]
name = "matchers"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d1525a2a28c7f4fa0fc98bb91ae755d1e2d1505079e05539e35bc876b5d65ae9"
dependencies = [
"regex-automata",
]
[[package]]
name = "memchr"
version = "2.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f8ca58f447f06ed17d5fc4043ce1b10dd205e060fb3ce5b979b8ed8e59ff3f79"
[[package]]
name = "mio"
version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "50b7e5b27aa02a74bac8c3f23f448f8d87ff11f92d3aac1a6ed369ee08cc56c1"
dependencies = [
"libc",
"log",
"wasi",
"windows-sys 0.61.2",
]
[[package]]
name = "mio-serial"
version = "5.0.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "029e1f407e261176a983a6599c084efd322d9301028055c87174beac71397ba3"
dependencies = [
"log",
"mio",
"nix 0.29.0",
"serialport",
"winapi",
]
[[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 = "nix"
version = "0.29.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "71e2746dc3a24dd78b3cfcb7be93368c6de9963d30f43a6a73998a9cf4b17b46"
dependencies = [
"bitflags 2.11.0",
"cfg-if",
"cfg_aliases",
"libc",
]
[[package]]
name = "nu-ansi-term"
version = "0.50.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5"
dependencies = [
"windows-sys 0.61.2",
]
[[package]]
name = "once_cell"
version = "1.21.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
[[package]]
name = "once_cell_polyfill"
version = "1.70.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe"
[[package]]
name = "parking_lot"
version = "0.12.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a"
dependencies = [
"lock_api",
"parking_lot_core",
]
[[package]]
name = "parking_lot_core"
version = "0.9.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1"
dependencies = [
"cfg-if",
"libc",
"redox_syscall",
"smallvec",
"windows-link",
]
[[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 = "redox_syscall"
version = "0.5.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d"
dependencies = [
"bitflags 2.11.0",
]
[[package]]
name = "regex-automata"
version = "0.4.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6e1dd4122fc1595e8162618945476892eefca7b88c52820e74af6262213cae8f"
dependencies = [
"aho-corasick",
"memchr",
"regex-syntax",
]
[[package]]
name = "regex-syntax"
version = "0.8.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dc897dd8d9e8bd1ed8cdad82b5966c3e0ecae09fb1907d58efaa013543185d0a"
[[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 0.26.4",
"scopeguard",
"unescaper",
"windows-sys 0.52.0",
]
[[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 = "signal-hook-registry"
version = "1.4.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b"
dependencies = [
"errno",
"libc",
]
[[package]]
name = "slab"
version = "0.4.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5"
[[package]]
name = "smallvec"
version = "1.15.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "67b1b7a3b5fe4f1376887184045fcf45c69e92af734b7aaddc05fb777b6fbd03"
[[package]]
name = "socket2"
version = "0.6.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3a766e1110788c36f4fa1c2b71b387a7815aa65f88ce0229841826633d93723e"
dependencies = [
"libc",
"windows-sys 0.61.2",
]
[[package]]
name = "strsim"
version = "0.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"
[[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 = "thread_local"
version = "1.1.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f60246a4944f24f6e018aa17cdeffb7818b76356965d03b07d6a9886e8962185"
dependencies = [
"cfg-if",
]
[[package]]
name = "tokio"
version = "1.51.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2bd1c4c0fc4a7ab90fc15ef6daaa3ec3b893f004f915f2392557ed23237820cd"
dependencies = [
"bytes",
"libc",
"mio",
"parking_lot",
"pin-project-lite",
"signal-hook-registry",
"socket2",
"tokio-macros",
"windows-sys 0.61.2",
]
[[package]]
name = "tokio-macros"
version = "2.7.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "385a6cb71ab9ab790c5fe8d67f1645e6c450a7ce006a33de03daa956cf70a496"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "tokio-serial"
version = "5.4.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "aa1d5427f11ba7c5e6384521cfd76f2d64572ff29f3f4f7aa0f496282923fdc8"
dependencies = [
"cfg-if",
"futures",
"log",
"mio-serial",
"serialport",
"tokio",
]
[[package]]
name = "tokio-util"
version = "0.7.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9ae9cec805b01e8fc3fd2fe289f89149a9b66dd16786abd8b19cfa7b48cb0098"
dependencies = [
"bytes",
"futures-core",
"futures-sink",
"pin-project-lite",
"tokio",
]
[[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",
"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 = "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 = "utf8parse"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821"
[[package]]
name = "valuable"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65"
[[package]]
name = "wasi"
version = "0.11.1+wasi-snapshot-preview1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b"
[[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-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"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
[[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-sys"
version = "0.61.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"
dependencies = [
"windows-link",
]
[[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"
+25
View File
@@ -0,0 +1,25 @@
[package]
name = "donglora-mux"
version = "0.1.0"
edition = "2024"
authors = ["Stephen Waits <steve@waits.net>"]
license = "MIT"
description = "DongLoRa USB Multiplexer — share one dongle with multiple applications"
repository = "https://github.com/swaits/donglora"
keywords = ["lora", "radio", "usb", "multiplexer"]
categories = ["hardware-support"]
[dependencies]
donglora-client = { path = "../../clients/rust" }
anyhow = "1"
clap = { version = "4", features = ["derive"] }
tokio = { version = "1", features = ["full"] }
tokio-serial = "5"
tokio-util = "0.7"
tracing = "0.1"
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
[lints.clippy]
unwrap_used = "deny"
expect_used = "deny"
panic = "deny"
+19
View File
@@ -0,0 +1,19 @@
set shell := ["bash", "-c"]
default: run
# Run the mux daemon
run *args:
cargo run -- {{args}}
# Run with verbose logging
verbose *args:
cargo run -- --verbose {{args}}
# Run clippy and tests
check:
cargo clippy -- -D warnings && cargo test
# Build release
build:
cargo build --release
+628
View File
@@ -0,0 +1,628 @@
//! Core mux daemon: dongle I/O, client management, reconnect loop.
//!
//! The daemon owns the USB serial connection and exposes Unix domain socket
//! and optional TCP listeners. It routes commands from clients to the dongle
//! and broadcasts/routes responses back.
use std::collections::HashMap;
use std::path::Path;
use std::sync::Arc;
use std::time::Duration;
use donglora_client::{
encode_frame, FrameReader, CMD_TAG_SET_CONFIG, CMD_TAG_START_RX, CMD_TAG_STOP_RX,
RADIO_CONFIG_SIZE, RESP_TAG_OK, RESP_TAG_RX_PACKET,
};
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::{TcpListener, UnixListener};
use tokio::sync::{mpsc, oneshot, Mutex};
/// A queued command: (client_id, raw_cmd_bytes).
type QueuedCmd = (u64, Vec<u8>);
/// Shared command receiver, wrapped for use across reconnect cycles.
type SharedCmdRx = Arc<Mutex<mpsc::Receiver<QueuedCmd>>>;
use tokio_util::sync::CancellationToken;
use tracing::{debug, error, info, warn};
use crate::intercept::{self, MuxState};
use crate::session::ClientSession;
/// Command timeout waiting for dongle response.
const COMMAND_TIMEOUT: Duration = Duration::from_secs(10);
/// Delay between dongle reconnect attempts.
const RECONNECT_DELAY: Duration = Duration::from_secs(2);
/// Max consecutive dongle read errors before declaring disconnect.
const MAX_CONSECUTIVE_ERRORS: u32 = 3;
/// Sentinel client ID for synthetic commands (e.g. auto StopRx).
const SYNTHETIC_CLIENT_ID: u64 = u64::MAX;
/// Shared mux state, protected by async mutex.
type SharedState = Arc<Mutex<MuxInner>>;
struct MuxInner {
sessions: HashMap<u64, ClientSession>,
mux_state: MuxState,
}
/// The multiplexer daemon.
pub struct MuxDaemon {
serial_port: String,
socket_path: String,
tcp_addr: Option<(String, u16)>,
shutdown: CancellationToken,
}
impl MuxDaemon {
pub fn new(
serial_port: String,
socket_path: String,
tcp_addr: Option<(String, u16)>,
shutdown: CancellationToken,
) -> Self {
Self {
serial_port,
socket_path,
tcp_addr,
shutdown,
}
}
/// Run the mux daemon. Returns when shutdown is signalled.
pub async fn run(&self) -> anyhow::Result<()> {
let state: SharedState = Arc::new(Mutex::new(MuxInner {
sessions: HashMap::new(),
mux_state: MuxState::new(),
}));
// Command channel: client handlers → dongle writer
let (cmd_tx, cmd_rx) = mpsc::channel::<(u64, Vec<u8>)>(64);
let cmd_rx = Arc::new(Mutex::new(cmd_rx));
// Pending response slot: dongle writer installs, dongle reader resolves
let pending_response: Arc<Mutex<Option<oneshot::Sender<Vec<u8>>>>> =
Arc::new(Mutex::new(None));
// Prepare socket directory
let sock_path = Path::new(&self.socket_path);
if let Some(parent) = sock_path.parent() {
tokio::fs::create_dir_all(parent).await.ok();
}
if sock_path.exists() {
tokio::fs::remove_file(sock_path).await.ok();
}
// Start Unix socket server
let unix_listener = UnixListener::bind(&self.socket_path)
.map_err(|e| anyhow::anyhow!("failed to bind Unix socket {}: {e}", self.socket_path))?;
info!("Unix socket listening on {}", self.socket_path);
// Start TCP server (optional)
let tcp_listener = if let Some((ref host, port)) = self.tcp_addr {
let addr = format!("{host}:{port}");
let listener = TcpListener::bind(&addr)
.await
.map_err(|e| anyhow::anyhow!("failed to bind TCP {addr}: {e}"))?;
info!("TCP listening on {addr}");
Some(listener)
} else {
None
};
// Spawn client accept tasks
tokio::spawn(accept_unix_clients(
unix_listener,
state.clone(),
cmd_tx.clone(),
self.shutdown.clone(),
));
if let Some(listener) = tcp_listener {
tokio::spawn(accept_tcp_clients(
listener,
state.clone(),
cmd_tx.clone(),
self.shutdown.clone(),
));
}
// Connect/reconnect loop
self.reconnect_loop(state, cmd_tx, cmd_rx, pending_response)
.await;
// Cleanup
info!("shutting down...");
if Path::new(&self.socket_path).exists() {
tokio::fs::remove_file(&self.socket_path).await.ok();
}
info!("stopped.");
Ok(())
}
async fn reconnect_loop(
&self,
state: SharedState,
_cmd_tx: mpsc::Sender<(u64, Vec<u8>)>, // kept alive to prevent channel close
cmd_rx: SharedCmdRx,
pending_response: Arc<Mutex<Option<oneshot::Sender<Vec<u8>>>>>,
) {
loop {
if self.shutdown.is_cancelled() {
break;
}
info!("opening dongle on {}", self.serial_port);
let serial = loop {
if self.shutdown.is_cancelled() {
return;
}
match open_and_ping(&self.serial_port).await {
Ok(s) => break s,
Err(e) => {
debug!("could not open dongle: {e}");
tokio::select! {
() = self.shutdown.cancelled() => return,
() = tokio::time::sleep(RECONNECT_DELAY) => continue,
}
}
}
};
info!("dongle connected");
let (serial_read, serial_write) = tokio::io::split(serial);
let dongle_lost = CancellationToken::new();
let reader_handle = tokio::spawn(dongle_reader(
serial_read,
state.clone(),
pending_response.clone(),
dongle_lost.clone(),
self.shutdown.clone(),
));
let writer_handle = tokio::spawn(dongle_writer(
serial_write,
cmd_rx.clone(),
state.clone(),
pending_response.clone(),
dongle_lost.clone(),
self.shutdown.clone(),
));
// Wait for dongle loss or shutdown
tokio::select! {
() = self.shutdown.cancelled() => {},
() = dongle_lost.cancelled() => {},
}
reader_handle.abort();
writer_handle.abort();
let _ = reader_handle.await;
let _ = writer_handle.await;
// Drain pending commands
{
let mut rx = cmd_rx.lock().await;
while rx.try_recv().is_ok() {}
}
if !self.shutdown.is_cancelled() {
info!("reconnecting in 2 seconds...");
tokio::select! {
() = self.shutdown.cancelled() => return,
() = tokio::time::sleep(RECONNECT_DELAY) => {},
}
}
}
}
}
// ── Dongle I/O ─────────────────────────────────────────────────────
async fn open_and_ping(port: &str) -> anyhow::Result<tokio_serial::SerialStream> {
let builder = tokio_serial::new(port, 115_200).timeout(Duration::from_secs(2));
let mut serial = tokio_serial::SerialStream::open(&builder)
.map_err(|e| anyhow::anyhow!("failed to open {port}: {e}"))?;
let ping_frame = encode_frame(&[0]);
AsyncWriteExt::write_all(&mut serial, &ping_frame)
.await
.map_err(|e| anyhow::anyhow!("failed to write ping: {e}"))?;
let mut reader = FrameReader::new();
let mut buf = [0u8; 64];
let deadline = tokio::time::Instant::now() + Duration::from_secs(2);
loop {
let remaining = deadline.saturating_duration_since(tokio::time::Instant::now());
if remaining.is_zero() {
anyhow::bail!("ping timeout");
}
let n = tokio::select! {
result = serial.read(&mut buf) => {
result.map_err(|e| anyhow::anyhow!("serial read error: {e}"))?
}
() = tokio::time::sleep(remaining) => {
anyhow::bail!("ping timeout");
}
};
if n == 0 {
anyhow::bail!("serial port closed during ping");
}
for frame in reader.feed(&buf[..n]) {
if frame.first() == Some(&0) {
info!("dongle responded to Ping");
return Ok(serial);
}
}
}
}
async fn dongle_reader(
mut serial: tokio::io::ReadHalf<tokio_serial::SerialStream>,
state: SharedState,
pending_response: Arc<Mutex<Option<oneshot::Sender<Vec<u8>>>>>,
dongle_lost: CancellationToken,
shutdown: CancellationToken,
) {
let mut reader = FrameReader::new();
let mut buf = [0u8; 512];
let mut consecutive_errors: u32 = 0;
loop {
if shutdown.is_cancelled() || dongle_lost.is_cancelled() {
return;
}
let read_result = tokio::select! {
result = serial.read(&mut buf) => result,
() = shutdown.cancelled() => return,
() = dongle_lost.cancelled() => return,
};
match read_result {
Ok(0) => {
error!("serial port closed");
resolve_pending_with_error(&pending_response).await;
dongle_lost.cancel();
return;
}
Ok(n) => {
consecutive_errors = 0;
for frame in reader.feed(&buf[..n]) {
dispatch_frame(&frame, &state, &pending_response).await;
}
}
Err(e) => {
consecutive_errors += 1;
if consecutive_errors >= MAX_CONSECUTIVE_ERRORS {
error!("dongle read error (giving up after {consecutive_errors}): {e}");
resolve_pending_with_error(&pending_response).await;
dongle_lost.cancel();
return;
}
warn!("dongle read glitch ({consecutive_errors}/{MAX_CONSECUTIVE_ERRORS}): {e}");
tokio::time::sleep(Duration::from_millis(100)).await;
}
}
}
}
async fn dispatch_frame(
frame: &[u8],
state: &SharedState,
pending_response: &Arc<Mutex<Option<oneshot::Sender<Vec<u8>>>>>,
) {
let Some(&tag) = frame.first() else {
return;
};
if tag == RESP_TAG_RX_PACKET {
let cobs_frame = encode_frame(frame);
let inner = state.lock().await;
for session in inner.sessions.values() {
session.enqueue(cobs_frame.clone());
}
} else {
let mut slot = pending_response.lock().await;
if let Some(sender) = slot.take() {
let _ = sender.send(frame.to_vec());
} else {
warn!("unsolicited non-RxPacket response (tag {tag}) — dropped");
}
}
}
async fn resolve_pending_with_error(
pending_response: &Arc<Mutex<Option<oneshot::Sender<Vec<u8>>>>>,
) {
let mut slot = pending_response.lock().await;
if let Some(sender) = slot.take() {
let _ = sender.send(vec![5, 1]); // Error(RadioBusy)
}
}
async fn dongle_writer(
mut serial: tokio::io::WriteHalf<tokio_serial::SerialStream>,
cmd_rx: SharedCmdRx,
state: SharedState,
pending_response: Arc<Mutex<Option<oneshot::Sender<Vec<u8>>>>>,
dongle_lost: CancellationToken,
shutdown: CancellationToken,
) {
loop {
// Pull next command from queue
let (client_id, raw_cmd) = {
let mut rx = cmd_rx.lock().await;
tokio::select! {
cmd = rx.recv() => {
match cmd {
Some(c) => c,
None => return,
}
}
() = shutdown.cancelled() => return,
() = dongle_lost.cancelled() => return,
}
};
// Check for interception
let intercepted = {
let mut inner = state.lock().await;
let locked = inner.mux_state.locked_config;
intercept::maybe_intercept(
&raw_cmd,
client_id,
&mut inner.sessions,
&locked,
)
};
if let Some(synthetic) = intercepted {
let inner = state.lock().await;
if let Some(session) = inner.sessions.get(&client_id) {
session.enqueue(encode_frame(&synthetic));
}
continue;
}
// Install oneshot for the response
let (resp_tx, resp_rx) = oneshot::channel();
{
let mut slot = pending_response.lock().await;
*slot = Some(resp_tx);
}
// Send command to dongle
let cobs_frame = encode_frame(&raw_cmd);
if let Err(e) = AsyncWriteExt::write_all(&mut serial, &cobs_frame).await {
error!("dongle write error: {e}");
resolve_pending_with_error(&pending_response).await;
dongle_lost.cancel();
return;
}
// Wait for response
let response = match tokio::time::timeout(COMMAND_TIMEOUT, resp_rx).await {
Ok(Ok(resp)) => resp,
Ok(Err(_)) => {
warn!("response channel dropped");
vec![5, 1]
}
Err(_) => {
error!("dongle response timeout");
let mut slot = pending_response.lock().await;
*slot = None;
vec![5, 1]
}
};
// Track state on successful forward
let cmd_tag = raw_cmd.first().copied().unwrap_or(0xFF);
let resp_tag = response.first().copied().unwrap_or(0xFF);
{
let mut inner = state.lock().await;
if cmd_tag == CMD_TAG_SET_CONFIG && resp_tag == RESP_TAG_OK {
if let Some(config_bytes) = raw_cmd.get(1..1 + RADIO_CONFIG_SIZE) {
let mut locked = [0u8; RADIO_CONFIG_SIZE];
locked.copy_from_slice(config_bytes);
inner.mux_state.locked_config = Some(locked);
info!("radio config locked");
}
} else if cmd_tag == CMD_TAG_START_RX && resp_tag == RESP_TAG_OK {
if let Some(session) = inner.sessions.get_mut(&client_id) {
session.rx_interested = true;
}
} else if cmd_tag == CMD_TAG_STOP_RX
&& resp_tag == RESP_TAG_OK
&& let Some(session) = inner.sessions.get_mut(&client_id)
{
session.rx_interested = false;
}
}
// Route response to commanding client
if client_id != SYNTHETIC_CLIENT_ID {
let inner = state.lock().await;
if let Some(session) = inner.sessions.get(&client_id) {
session.enqueue(encode_frame(&response));
}
}
}
}
// ── Client management ──────────────────────────────────────────────
async fn accept_unix_clients(
listener: UnixListener,
state: SharedState,
cmd_tx: mpsc::Sender<(u64, Vec<u8>)>,
shutdown: CancellationToken,
) {
loop {
let accept_result = tokio::select! {
result = listener.accept() => result,
() = shutdown.cancelled() => return,
};
match accept_result {
Ok((stream, _addr)) => {
let (read_half, write_half) = stream.into_split();
spawn_client(read_half, write_half, state.clone(), cmd_tx.clone(), shutdown.clone());
}
Err(e) => warn!("Unix accept error: {e}"),
}
}
}
async fn accept_tcp_clients(
listener: TcpListener,
state: SharedState,
cmd_tx: mpsc::Sender<(u64, Vec<u8>)>,
shutdown: CancellationToken,
) {
loop {
let accept_result = tokio::select! {
result = listener.accept() => result,
() = shutdown.cancelled() => return,
};
match accept_result {
Ok((stream, addr)) => {
debug!("TCP connection from {addr}");
let (read_half, write_half) = stream.into_split();
spawn_client(read_half, write_half, state.clone(), cmd_tx.clone(), shutdown.clone());
}
Err(e) => warn!("TCP accept error: {e}"),
}
}
}
fn spawn_client<R, W>(
read_half: R,
write_half: W,
state: SharedState,
cmd_tx: mpsc::Sender<(u64, Vec<u8>)>,
shutdown: CancellationToken,
) where
R: AsyncReadExt + Unpin + Send + 'static,
W: AsyncWriteExt + Unpin + Send + 'static,
{
let (session, send_rx) = ClientSession::new();
let client_id = session.id;
let label = session.label();
let state_clone = state.clone();
let cmd_tx_clone = cmd_tx.clone();
tokio::spawn(async move {
{
let mut inner = state_clone.lock().await;
inner.sessions.insert(client_id, session);
info!("{label} connected ({} total)", inner.sessions.len());
}
let writer_shutdown = shutdown.clone();
let writer_handle = tokio::spawn(client_writer(write_half, send_rx, writer_shutdown));
client_reader(read_half, client_id, cmd_tx_clone.clone(), shutdown).await;
writer_handle.abort();
let _ = writer_handle.await;
remove_client(client_id, &state_clone, &label, &cmd_tx_clone).await;
});
}
async fn client_reader<R: AsyncReadExt + Unpin>(
mut read_half: R,
client_id: u64,
cmd_tx: mpsc::Sender<(u64, Vec<u8>)>,
shutdown: CancellationToken,
) {
let mut reader = FrameReader::new();
let mut buf = [0u8; 4096];
loop {
let read_result = tokio::select! {
result = read_half.read(&mut buf) => result,
() = shutdown.cancelled() => return,
};
match read_result {
Ok(0) => return,
Ok(n) => {
for frame in reader.feed(&buf[..n]) {
if cmd_tx.send((client_id, frame)).await.is_err() {
return;
}
}
}
Err(_) => return,
}
}
}
async fn client_writer<W: AsyncWriteExt + Unpin>(
mut write_half: W,
mut send_rx: mpsc::Receiver<Vec<u8>>,
shutdown: CancellationToken,
) {
loop {
let frame = tokio::select! {
f = send_rx.recv() => {
match f {
Some(f) => f,
None => return,
}
}
() = shutdown.cancelled() => return,
};
if AsyncWriteExt::write_all(&mut write_half, &frame)
.await
.is_err()
{
return;
}
}
}
async fn remove_client(
client_id: u64,
state: &SharedState,
label: &str,
cmd_tx: &mpsc::Sender<(u64, Vec<u8>)>,
) {
let mut inner = state.lock().await;
let was_interested = inner
.sessions
.get(&client_id)
.is_some_and(|s| s.rx_interested);
inner.sessions.remove(&client_id);
info!("{label} disconnected ({} remain)", inner.sessions.len());
// If last RX-interested client gone, send synthetic StopRx
if was_interested && intercept::rx_interest_count(&inner.sessions) == 0 {
info!("last RX-interested client gone — sending StopRx");
// Drop the lock before sending to avoid deadlock
drop(inner);
let _ = cmd_tx
.send((SYNTHETIC_CLIENT_ID, vec![CMD_TAG_STOP_RX]))
.await;
return;
}
// Reset locked config when all clients are gone
if inner.sessions.is_empty() && inner.mux_state.locked_config.is_some() {
info!("all clients gone — config lock released");
inner.mux_state.locked_config = None;
}
}
+291
View File
@@ -0,0 +1,291 @@
//! Smart multiplexing: SetConfig locking, StartRx/StopRx reference counting.
//!
//! The mux intercepts certain commands to avoid redundant dongle operations
//! when multiple clients are connected. Intercepted commands get synthetic
//! responses without hitting the physical dongle.
use std::collections::HashMap;
use donglora_client::{
CMD_TAG_SET_CONFIG, CMD_TAG_START_RX, CMD_TAG_STOP_RX, ERROR_INVALID_CONFIG, RADIO_CONFIG_SIZE,
RESP_TAG_ERROR, RESP_TAG_OK,
};
use tracing::{debug, warn};
use crate::session::ClientSession;
/// Mux-level state for interception logic.
pub struct MuxState {
/// Raw 13-byte RadioConfig, locked once set by any client with others connected.
pub locked_config: Option<[u8; RADIO_CONFIG_SIZE]>,
}
impl MuxState {
pub fn new() -> Self {
Self {
locked_config: None,
}
}
}
/// Check if a command should be intercepted (synthetic response) vs forwarded to the dongle.
///
/// Returns `Some(response_bytes)` if intercepted, `None` to forward normally.
pub fn maybe_intercept(
raw_cmd: &[u8],
client_id: u64,
sessions: &mut HashMap<u64, ClientSession>,
locked_config: &Option<[u8; RADIO_CONFIG_SIZE]>,
) -> Option<Vec<u8>> {
let cmd_tag = *raw_cmd.first()?;
match cmd_tag {
CMD_TAG_SET_CONFIG => intercept_set_config(raw_cmd, client_id, sessions, locked_config),
CMD_TAG_START_RX => intercept_start_rx(client_id, sessions),
CMD_TAG_STOP_RX => intercept_stop_rx(client_id, sessions),
_ => None,
}
}
fn intercept_set_config(
raw_cmd: &[u8],
client_id: u64,
sessions: &HashMap<u64, ClientSession>,
locked_config: &Option<[u8; RADIO_CONFIG_SIZE]>,
) -> Option<Vec<u8>> {
let config_bytes = raw_cmd.get(1..1 + RADIO_CONFIG_SIZE)?;
// Single client — allow free config changes (scanner mode)
if sessions.len() <= 1 {
return None;
}
// First SetConfig with multiple clients — forward and lock on success
let Some(locked) = locked_config else {
return None;
};
// Same config — reply Ok without hitting the dongle
if config_bytes == locked.as_slice() {
let label = sessions
.get(&client_id)
.map(ClientSession::label)
.unwrap_or_else(|| format!("id-{client_id}"));
debug!("{label}: SetConfig matches locked config — Ok");
return Some(vec![RESP_TAG_OK]);
}
// Different config — reject
let label = sessions
.get(&client_id)
.map(ClientSession::label)
.unwrap_or_else(|| format!("id-{client_id}"));
warn!("{label}: SetConfig rejected (conflicts with locked config)");
Some(vec![RESP_TAG_ERROR, ERROR_INVALID_CONFIG])
}
fn intercept_start_rx(
client_id: u64,
sessions: &mut HashMap<u64, ClientSession>,
) -> Option<Vec<u8>> {
let client = sessions.get(&client_id)?;
// Already interested — no-op
if client.rx_interested {
return Some(vec![RESP_TAG_OK]);
}
// Others already receiving — just mark this client
if rx_interest_count(sessions) > 0 {
if let Some(c) = sessions.get_mut(&client_id) {
c.rx_interested = true;
}
return Some(vec![RESP_TAG_OK]);
}
// First interested client — forward to dongle
None
}
fn intercept_stop_rx(
client_id: u64,
sessions: &mut HashMap<u64, ClientSession>,
) -> Option<Vec<u8>> {
let client = sessions.get(&client_id)?;
// Wasn't interested — no-op
if !client.rx_interested {
return Some(vec![RESP_TAG_OK]);
}
// Mark as not interested
if let Some(c) = sessions.get_mut(&client_id) {
c.rx_interested = false;
}
// Others still interested — don't stop the dongle
if rx_interest_count(sessions) > 0 {
return Some(vec![RESP_TAG_OK]);
}
// Last interested client — forward StopRx to dongle
None
}
/// Count how many sessions have rx_interested set.
pub fn rx_interest_count(sessions: &HashMap<u64, ClientSession>) -> usize {
sessions.values().filter(|s| s.rx_interested).count()
}
// ── Tests ──────────────────────────────────────────────────────────
#[cfg(test)]
mod tests {
use super::*;
fn make_sessions(n: usize) -> HashMap<u64, ClientSession> {
let mut map = HashMap::new();
for _ in 0..n {
let (session, _rx) = ClientSession::new();
let id = session.id;
map.insert(id, session);
}
map
}
fn first_id(sessions: &HashMap<u64, ClientSession>) -> u64 {
*sessions.keys().min().unwrap()
}
fn second_id(sessions: &HashMap<u64, ClientSession>) -> u64 {
let mut ids: Vec<u64> = sessions.keys().copied().collect();
ids.sort();
ids[1]
}
// ── SetConfig ──────────────────────────────���───────────────────
#[test]
fn set_config_single_client_forwards() {
let mut sessions = make_sessions(1);
let locked = None;
let id = first_id(&sessions);
let cmd = [CMD_TAG_SET_CONFIG, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
assert!(maybe_intercept(&cmd, id, &mut sessions, &locked).is_none());
}
#[test]
fn set_config_first_with_multiple_forwards() {
let mut sessions = make_sessions(2);
let locked = None;
let id = first_id(&sessions);
let cmd = [CMD_TAG_SET_CONFIG, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13];
assert!(maybe_intercept(&cmd, id, &mut sessions, &locked).is_none());
}
#[test]
fn set_config_matching_returns_ok() {
let mut sessions = make_sessions(2);
let config = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13];
let locked = Some(config);
let id = first_id(&sessions);
let mut cmd = vec![CMD_TAG_SET_CONFIG];
cmd.extend_from_slice(&config);
assert_eq!(maybe_intercept(&cmd, id, &mut sessions, &locked), Some(vec![RESP_TAG_OK]));
}
#[test]
fn set_config_conflicting_returns_error() {
let mut sessions = make_sessions(2);
let locked = Some([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]);
let id = first_id(&sessions);
let mut cmd = vec![CMD_TAG_SET_CONFIG];
cmd.extend_from_slice(&[99, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]);
assert_eq!(
maybe_intercept(&cmd, id, &mut sessions, &locked),
Some(vec![RESP_TAG_ERROR, ERROR_INVALID_CONFIG])
);
}
// ── StartRx ────────────────────────────────────────────────────
#[test]
fn start_rx_first_client_forwards() {
let mut sessions = make_sessions(1);
let locked = None;
let id = first_id(&sessions);
assert!(maybe_intercept(&[CMD_TAG_START_RX], id, &mut sessions, &locked).is_none());
}
#[test]
fn start_rx_already_interested_returns_ok() {
let mut sessions = make_sessions(1);
let locked = None;
let id = first_id(&sessions);
sessions.get_mut(&id).unwrap().rx_interested = true;
assert_eq!(
maybe_intercept(&[CMD_TAG_START_RX], id, &mut sessions, &locked),
Some(vec![RESP_TAG_OK])
);
}
#[test]
fn start_rx_others_interested_marks_and_returns_ok() {
let mut sessions = make_sessions(2);
let locked = None;
let id1 = first_id(&sessions);
let id2 = second_id(&sessions);
sessions.get_mut(&id1).unwrap().rx_interested = true;
let result = maybe_intercept(&[CMD_TAG_START_RX], id2, &mut sessions, &locked);
assert_eq!(result, Some(vec![RESP_TAG_OK]));
assert!(sessions.get(&id2).unwrap().rx_interested);
}
// ── StopRx ─────────────────────────────────────────────────────
#[test]
fn stop_rx_not_interested_returns_ok() {
let mut sessions = make_sessions(1);
let locked = None;
let id = first_id(&sessions);
assert_eq!(
maybe_intercept(&[CMD_TAG_STOP_RX], id, &mut sessions, &locked),
Some(vec![RESP_TAG_OK])
);
}
#[test]
fn stop_rx_others_remain_returns_ok() {
let mut sessions = make_sessions(2);
let locked = None;
let id1 = first_id(&sessions);
let id2 = second_id(&sessions);
sessions.get_mut(&id1).unwrap().rx_interested = true;
sessions.get_mut(&id2).unwrap().rx_interested = true;
let result = maybe_intercept(&[CMD_TAG_STOP_RX], id1, &mut sessions, &locked);
assert_eq!(result, Some(vec![RESP_TAG_OK]));
assert!(!sessions.get(&id1).unwrap().rx_interested);
}
#[test]
fn stop_rx_last_interested_forwards() {
let mut sessions = make_sessions(1);
let locked = None;
let id = first_id(&sessions);
sessions.get_mut(&id).unwrap().rx_interested = true;
assert!(maybe_intercept(&[CMD_TAG_STOP_RX], id, &mut sessions, &locked).is_none());
assert!(!sessions.get(&id).unwrap().rx_interested);
}
// ── Other commands ─────────────────────────────────────────────
#[test]
fn other_commands_not_intercepted() {
let mut sessions = make_sessions(1);
let locked = None;
let id = first_id(&sessions);
for tag in [0u8, 1, 5, 6, 7, 8] {
assert!(maybe_intercept(&[tag], id, &mut sessions, &locked).is_none());
}
}
}
+119
View File
@@ -0,0 +1,119 @@
//! DongLoRa USB Multiplexer — share one dongle with multiple applications.
//!
//! Owns the USB serial connection and exposes a Unix domain socket (and
//! optional TCP) that speaks the same COBS-framed protocol. Clients connect
//! and get solicited responses routed, RxPackets broadcast, and StartRx/StopRx
//! reference-counted.
mod daemon;
mod intercept;
mod session;
use clap::Parser;
use tokio_util::sync::CancellationToken;
use tracing::info;
#[derive(Parser)]
#[command(name = "donglora-mux", about = "DongLoRa USB Multiplexer")]
struct Args {
/// Serial port (auto-detect by USB VID:PID if omitted)
#[arg(short, long)]
port: Option<String>,
/// Unix socket path (default: XDG or /tmp/donglora-mux.sock)
#[arg(short, long)]
socket: Option<String>,
/// TCP listen address [HOST:]PORT (default: 0.0.0.0:5741, "none" to disable)
#[arg(short, long, default_value = "0.0.0.0:5741")]
tcp: String,
/// Enable debug logging
#[arg(short, long)]
verbose: bool,
}
#[tokio::main]
async fn main() -> anyhow::Result<()> {
let args = Args::parse();
// Init tracing — daemon-style: wall-clock time, level, message
let filter = if args.verbose { "debug" } else { "info" };
tracing_subscriber::fmt()
.with_env_filter(
tracing_subscriber::EnvFilter::try_from_default_env()
.unwrap_or_else(|_| tracing_subscriber::EnvFilter::new(filter)),
)
.with_target(false)
.init();
// Resolve serial port
let port = match args.port {
Some(p) => p,
None => {
tokio::task::spawn_blocking(|| {
donglora_client::find_port().unwrap_or_else(|| {
info!("waiting for DongLoRa device...");
donglora_client::wait_for_device()
})
})
.await
.map_err(|e| anyhow::anyhow!("device discovery task failed: {e}"))?
}
};
// Resolve socket path
let socket_path = args
.socket
.unwrap_or_else(donglora_client::default_socket_path);
// Parse TCP address
let tcp_addr = parse_tcp_addr(&args.tcp);
// Shutdown token
let shutdown = CancellationToken::new();
// Install signal handlers
let sig_shutdown = shutdown.clone();
tokio::spawn(async move {
if let Err(e) = signal_handler(sig_shutdown).await {
tracing::error!("signal handler error: {e}");
}
});
// Run the daemon
let daemon = daemon::MuxDaemon::new(port, socket_path, tcp_addr, shutdown);
daemon.run().await
}
fn parse_tcp_addr(tcp: &str) -> Option<(String, u16)> {
if tcp.eq_ignore_ascii_case("none") {
return None;
}
if let Some((host, port_str)) = tcp.rsplit_once(':')
&& let Ok(port) = port_str.parse()
{
return Some((host.to_string(), port));
}
if let Ok(port) = tcp.parse() {
return Some(("0.0.0.0".to_string(), port));
}
None
}
async fn signal_handler(shutdown: CancellationToken) -> anyhow::Result<()> {
let mut sigint =
tokio::signal::unix::signal(tokio::signal::unix::SignalKind::interrupt())
.map_err(|e| anyhow::anyhow!("failed to register SIGINT handler: {e}"))?;
let mut sigterm =
tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())
.map_err(|e| anyhow::anyhow!("failed to register SIGTERM handler: {e}"))?;
tokio::select! {
_ = sigint.recv() => info!("received SIGINT"),
_ = sigterm.recv() => info!("received SIGTERM"),
}
shutdown.cancel();
Ok(())
}
+57
View File
@@ -0,0 +1,57 @@
//! Per-client session state and bounded send queue.
//!
//! Each connected client gets a [`ClientSession`] that tracks its ID,
//! RX interest flag, and a bounded channel for outgoing COBS frames.
use std::sync::atomic::{AtomicU64, Ordering};
use tokio::sync::mpsc;
use tracing::warn;
/// Bounded send queue capacity per client.
const SEND_QUEUE_CAP: usize = 256;
/// Global client ID counter.
static NEXT_CLIENT_ID: AtomicU64 = AtomicU64::new(0);
/// Per-client state tracked by the mux daemon.
pub struct ClientSession {
/// Unique client identifier.
pub id: u64,
/// Whether this client has called StartRx.
pub rx_interested: bool,
/// Sender half of the bounded channel to the client's writer task.
tx: mpsc::Sender<Vec<u8>>,
}
impl ClientSession {
/// Create a new session. Returns the session and the receiver half
/// for the client's writer task to drain.
pub fn new() -> (Self, mpsc::Receiver<Vec<u8>>) {
let id = NEXT_CLIENT_ID.fetch_add(1, Ordering::Relaxed);
let (tx, rx) = mpsc::channel(SEND_QUEUE_CAP);
let session = Self {
id,
rx_interested: false,
tx,
};
(session, rx)
}
/// Human-readable label for logging.
pub fn label(&self) -> String {
format!("client-{}", self.id)
}
/// Best-effort enqueue of a COBS frame for sending to this client.
///
/// If the channel is full (slow client), the frame is dropped with a warning.
/// This prevents backpressure from one slow client blocking the entire mux.
pub fn enqueue(&self, frame: Vec<u8>) {
if let Err(mpsc::error::TrySendError::Full(_)) = self.tx.try_send(frame) {
warn!("{}: send queue full, dropping frame", self.label());
}
// Closed channel (client disconnected) is silently ignored — the session
// will be cleaned up when the client handler task exits.
}
}