use std::collections::{HashMap, HashSet};
use std::fmt;
use std::sync::{Arc, Mutex as StdMutex};
use std::time::{Duration, Instant};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use serialport::{available_ports, SerialPortInfo, SerialPortType};
use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt};
use tokio::sync::Mutex;
use tokio::time::timeout;
use tokio_serial::{ClearBuffer, SerialPort, SerialPortBuilderExt, SerialStream};
use uuid::Uuid;
use crate::error::{Result, SerialError};
pub const MAX_BAUD_RATE: u32 = 4_000_000;
#[derive(Debug, Clone, Copy, Deserialize, JsonSchema)]
pub enum DataBits {
#[serde(rename = "5")]
Five,
#[serde(rename = "6")]
Six,
#[serde(rename = "7")]
Seven,
#[serde(rename = "8")]
Eight,
}
impl From<DataBits> for serialport::DataBits {
fn from(value: DataBits) -> Self {
match value {
DataBits::Five => Self::Five,
DataBits::Six => Self::Six,
DataBits::Seven => Self::Seven,
DataBits::Eight => Self::Eight,
}
}
}
#[derive(Debug, Clone, Copy, Deserialize, JsonSchema)]
pub enum StopBits {
#[serde(rename = "1")]
One,
#[serde(rename = "2")]
Two,
}
impl From<StopBits> for serialport::StopBits {
fn from(value: StopBits) -> Self {
match value {
StopBits::One => Self::One,
StopBits::Two => Self::Two,
}
}
}
#[derive(Debug, Clone, Copy, Deserialize, JsonSchema)]
#[serde(rename_all = "lowercase")]
pub enum Parity {
None,
Odd,
Even,
}
impl From<Parity> for serialport::Parity {
fn from(value: Parity) -> Self {
match value {
Parity::None => Self::None,
Parity::Odd => Self::Odd,
Parity::Even => Self::Even,
}
}
}
#[derive(Debug, Clone, Copy, Deserialize, JsonSchema)]
#[serde(rename_all = "lowercase")]
pub enum FlowControl {
None,
Software,
Hardware,
}
impl From<FlowControl> for serialport::FlowControl {
fn from(value: FlowControl) -> Self {
match value {
FlowControl::None => Self::None,
FlowControl::Software => Self::Software,
FlowControl::Hardware => Self::Hardware,
}
}
}
#[derive(Debug, Clone, JsonSchema)]
pub struct ConnectionConfig {
pub port: String,
pub baud_rate: u32,
pub data_bits: DataBits,
pub stop_bits: StopBits,
pub parity: Parity,
pub flow_control: FlowControl,
}
#[derive(Debug, Serialize, Deserialize, JsonSchema)]
pub struct PortInfo {
pub name: String,
pub description: String,
pub hardware_id: Option<String>,
}
impl PortInfo {
pub fn list_available() -> Result<Vec<PortInfo>> {
let ports = available_ports()?;
Ok(ports.into_iter().map(PortInfo::from_os).collect())
}
fn from_os(port: SerialPortInfo) -> Self {
PortInfo {
hardware_id: format_hardware_id(&port),
description: describe_port(&port),
name: port.port_name,
}
}
}
fn format_hardware_id(port: &SerialPortInfo) -> Option<String> {
match &port.port_type {
SerialPortType::UsbPort(info) => {
Some(format!("USB VID:{:04X} PID:{:04X}", info.vid, info.pid))
}
SerialPortType::PciPort => Some("PCI".to_string()),
SerialPortType::BluetoothPort => Some("Bluetooth".to_string()),
SerialPortType::Unknown => None,
}
}
fn describe_port(port: &SerialPortInfo) -> String {
match &port.port_type {
SerialPortType::UsbPort(info) => format!(
"{} {}",
info.manufacturer.as_deref().unwrap_or("Unknown"),
info.product.as_deref().unwrap_or("USB Serial Device")
),
SerialPortType::PciPort => "PCI Serial Port".to_string(),
SerialPortType::BluetoothPort => "Bluetooth Serial Port".to_string(),
SerialPortType::Unknown => "Serial Port".to_string(),
}
}
pub trait SerialIo: AsyncRead + AsyncWrite + Send + Unpin {
fn clear_os_buffers(&self, target: FlushTarget) -> std::io::Result<()>;
fn set_dtr_rts(&mut self, dtr: bool, rts: bool) -> std::io::Result<()>;
fn set_break_state(&self, asserted: bool) -> std::io::Result<()>;
}
impl SerialIo for SerialStream {
fn clear_os_buffers(&self, target: FlushTarget) -> std::io::Result<()> {
self.clear(target.into()).map_err(io_error_from_serialport)
}
fn set_dtr_rts(&mut self, dtr: bool, rts: bool) -> std::io::Result<()> {
self.write_data_terminal_ready(dtr)
.map_err(io_error_from_serialport)?;
self.write_request_to_send(rts)
.map_err(io_error_from_serialport)
}
fn set_break_state(&self, asserted: bool) -> std::io::Result<()> {
if asserted {
self.set_break().map_err(io_error_from_serialport)
} else {
self.clear_break().map_err(io_error_from_serialport)
}
}
}
fn io_error_from_serialport(err: serialport::Error) -> std::io::Error {
std::io::Error::other(err.to_string())
}
pub struct SerialConnection {
id: String,
port: String,
rx_owner: StdMutex<Option<&'static str>>,
state: Mutex<SerialState>,
}
#[derive(Debug)]
pub struct SerialRxLease {
connection: Arc<SerialConnection>,
owner: &'static str,
}
impl Drop for SerialRxLease {
fn drop(&mut self) {
if let Ok(mut current) = self.connection.rx_owner.lock() {
if current.as_ref() == Some(&self.owner) {
*current = None;
}
}
}
}
struct SerialState {
io: Box<dyn SerialIo>,
unread: Vec<u8>,
}
impl fmt::Debug for SerialConnection {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("SerialConnection")
.field("id", &self.id)
.field("port", &self.port)
.finish()
}
}
impl SerialConnection {
pub async fn open(config: ConnectionConfig) -> Result<Self> {
ensure_valid_baud_rate(config.baud_rate)?;
let stream = build_stream(&config)?;
Ok(Self::from_io(config.port, Box::new(stream)))
}
pub fn from_io(port: String, io: Box<dyn SerialIo>) -> Self {
Self {
id: Uuid::new_v4().to_string(),
port,
rx_owner: StdMutex::new(None),
state: Mutex::new(SerialState {
io,
unread: Vec::new(),
}),
}
}
pub fn id(&self) -> &str {
&self.id
}
pub fn port(&self) -> &str {
&self.port
}
pub fn acquire_rx(
connection: &Arc<Self>,
owner: &'static str,
) -> std::result::Result<SerialRxLease, String> {
let mut current = connection.rx_owner.lock().map_err(|_| {
format!(
"Connection busy: failed to inspect RX owner on {}",
connection.id
)
})?;
if let Some(active_owner) = *current {
return Err(format!("Connection busy: {active_owner} already owns RX"));
}
*current = Some(owner);
Ok(SerialRxLease {
connection: Arc::clone(connection),
owner,
})
}
pub async fn write(&self, data: &[u8]) -> Result<usize> {
let mut state = self.state.lock().await;
let written = state.io.write(data).await?;
state.io.flush().await?;
Ok(written)
}
fn read_from_unread(state: &mut SerialState, dst: &mut [u8]) -> usize {
let to_copy = dst.len().min(state.unread.len());
if to_copy == 0 {
return 0;
}
dst[..to_copy].copy_from_slice(&state.unread[..to_copy]);
state.unread.drain(..to_copy);
to_copy
}
pub async fn read(&self, dst: &mut [u8], timeout_ms: Option<u64>) -> Result<usize> {
const POLL_MS: u64 = 50;
{
let mut state = self.state.lock().await;
let unread = Self::read_from_unread(&mut state, dst);
if unread > 0 {
return Ok(unread);
}
}
match timeout_ms {
None => Ok(self.state.lock().await.io.read(dst).await?),
Some(ms) => {
let deadline = Instant::now() + Duration::from_millis(ms);
loop {
let remaining = deadline.saturating_duration_since(Instant::now());
if remaining.is_zero() {
return Err(SerialError::ReadTimeout);
}
let poll_dur = remaining.min(Duration::from_millis(POLL_MS));
{
let mut state = self.state.lock().await;
let unread = Self::read_from_unread(&mut state, dst);
if unread > 0 {
return Ok(unread);
}
match timeout(poll_dur, state.io.read(dst)).await {
Ok(Ok(n)) if n > 0 => return Ok(n),
Ok(Ok(_)) => {}
Ok(Err(e)) => return Err(SerialError::from(e)),
Err(_elapsed) => {}
}
}
tokio::time::sleep(Duration::from_millis(5)).await;
}
}
}
}
pub async fn read_latest(&self, max_bytes: usize) -> Result<Vec<u8>> {
let mut buf = vec![0u8; max_bytes];
let n = self.read(&mut buf, Some(100)).await?;
buf.truncate(n);
Ok(buf)
}
pub async fn unread(&self, data: &[u8]) {
if data.is_empty() {
return;
}
let mut state = self.state.lock().await;
state.unread.extend_from_slice(data);
}
pub async fn flush_buffers(&self, target: FlushTarget) -> Result<()> {
let mut state = self.state.lock().await;
if matches!(target, FlushTarget::Input | FlushTarget::Both) {
state.unread.clear();
}
state.io.clear_os_buffers(target).map_err(SerialError::from)
}
pub async fn set_dtr_rts(&self, dtr: bool, rts: bool) -> Result<()> {
let mut state = self.state.lock().await;
state.io.set_dtr_rts(dtr, rts).map_err(SerialError::from)
}
pub async fn set_break_state(&self, enabled: bool) -> Result<()> {
let state = self.state.lock().await;
state.io.set_break_state(enabled).map_err(SerialError::from)
}
pub async fn send_break(&self, duration_ms: u64) -> Result<()> {
self.set_break_state(true).await?;
tokio::time::sleep(Duration::from_millis(duration_ms)).await;
self.set_break_state(false).await
}
}
#[derive(Debug, Clone, Copy, Deserialize, Serialize, JsonSchema)]
#[serde(rename_all = "lowercase")]
pub enum FlushTarget {
Input,
Output,
Both,
}
impl From<FlushTarget> for ClearBuffer {
fn from(value: FlushTarget) -> Self {
match value {
FlushTarget::Input => ClearBuffer::Input,
FlushTarget::Output => ClearBuffer::Output,
FlushTarget::Both => ClearBuffer::All,
}
}
}
fn ensure_valid_baud_rate(baud_rate: u32) -> Result<()> {
if baud_rate == 0 || baud_rate > MAX_BAUD_RATE {
Err(SerialError::InvalidBaudRate(baud_rate))
} else {
Ok(())
}
}
fn build_stream(config: &ConnectionConfig) -> Result<SerialStream> {
tokio_serial::new(&config.port, config.baud_rate)
.data_bits(config.data_bits.into())
.stop_bits(config.stop_bits.into())
.parity(config.parity.into())
.flow_control(config.flow_control.into())
.open_native_async()
.map_err(|e| SerialError::OpenFailed(format!("{}: {}", config.port, e)))
}
#[derive(Debug, Default)]
pub struct ConnectionManager {
state: Mutex<ConnectionRegistry>,
}
#[derive(Debug, Default)]
struct ConnectionRegistry {
connections: HashMap<String, Arc<SerialConnection>>,
opening_ports: HashSet<String>,
}
impl ConnectionManager {
pub fn new() -> Self {
Self::default()
}
pub async fn open(&self, config: ConnectionConfig) -> Result<String> {
let port = config.port.clone();
{
let mut state = self.state.lock().await;
if is_port_in_use(&state.connections, &port) || state.opening_ports.contains(&port) {
return Err(SerialError::PortAlreadyOpen(port));
}
state.opening_ports.insert(port.clone());
}
let opened = SerialConnection::open(config).await;
let mut state = self.state.lock().await;
state.opening_ports.remove(&port);
let connection = Arc::new(opened?);
let id = connection.id().to_string();
state.connections.insert(id.clone(), connection);
Ok(id)
}
pub async fn insert(&self, connection: SerialConnection) -> Result<String> {
let mut state = self.state.lock().await;
if is_port_in_use(&state.connections, connection.port())
|| state.opening_ports.contains(connection.port())
{
return Err(SerialError::PortAlreadyOpen(connection.port().to_string()));
}
let id = connection.id().to_string();
state.connections.insert(id.clone(), Arc::new(connection));
Ok(id)
}
pub async fn close(&self, id: &str) -> Result<()> {
self.state
.lock()
.await
.connections
.remove(id)
.ok_or_else(|| SerialError::ConnectionNotFound(id.to_string()))?;
Ok(())
}
pub async fn get(&self, id: &str) -> Result<Arc<SerialConnection>> {
self.state
.lock()
.await
.connections
.get(id)
.cloned()
.ok_or_else(|| SerialError::ConnectionNotFound(id.to_string()))
}
pub async fn count(&self) -> usize {
self.state.lock().await.connections.len()
}
pub async fn list_open(&self) -> Vec<ConnectionSummary> {
self.state
.lock()
.await
.connections
.values()
.map(|c| ConnectionSummary {
connection_id: c.id().to_string(),
port: c.port().to_string(),
})
.collect()
}
}
#[derive(Debug, Clone, Serialize, JsonSchema)]
pub struct ConnectionSummary {
pub connection_id: String,
pub port: String,
}
fn is_port_in_use(connections: &HashMap<String, Arc<SerialConnection>>, port: &str) -> bool {
connections.values().any(|c| c.port() == port)
}
pub mod test_support {
use std::pin::Pin;
use std::task::{Context, Poll};
use tokio::io::{DuplexStream, ReadBuf};
use super::*;
pub struct LoopbackIo(DuplexStream);
impl AsyncRead for LoopbackIo {
fn poll_read(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &mut ReadBuf<'_>,
) -> Poll<std::io::Result<()>> {
Pin::new(&mut self.0).poll_read(cx, buf)
}
}
impl AsyncWrite for LoopbackIo {
fn poll_write(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &[u8],
) -> Poll<std::io::Result<usize>> {
Pin::new(&mut self.0).poll_write(cx, buf)
}
fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
Pin::new(&mut self.0).poll_flush(cx)
}
fn poll_shutdown(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
) -> Poll<std::io::Result<()>> {
Pin::new(&mut self.0).poll_shutdown(cx)
}
}
impl SerialIo for LoopbackIo {
fn clear_os_buffers(&self, _target: FlushTarget) -> std::io::Result<()> {
Ok(())
}
fn set_dtr_rts(&mut self, _dtr: bool, _rts: bool) -> std::io::Result<()> {
Ok(())
}
fn set_break_state(&self, _asserted: bool) -> std::io::Result<()> {
Ok(())
}
}
pub fn loopback_connection(port: &str) -> (SerialConnection, DuplexStream) {
let (a, b) = tokio::io::duplex(4096);
let conn = SerialConnection::from_io(port.to_string(), Box::new(LoopbackIo(a)));
(conn, b)
}
}
#[cfg(test)]
mod tests {
use super::test_support::loopback_connection;
use super::*;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
#[test]
fn baud_rate_zero_rejected() {
assert!(matches!(
ensure_valid_baud_rate(0),
Err(SerialError::InvalidBaudRate(0))
));
}
#[test]
fn baud_rate_over_max_rejected() {
assert!(matches!(
ensure_valid_baud_rate(MAX_BAUD_RATE + 1),
Err(SerialError::InvalidBaudRate(_))
));
}
#[test]
fn baud_rate_within_range_accepted() {
assert!(ensure_valid_baud_rate(115200).is_ok());
assert!(ensure_valid_baud_rate(1).is_ok());
assert!(ensure_valid_baud_rate(MAX_BAUD_RATE).is_ok());
}
#[tokio::test]
async fn write_pushes_bytes_to_peer() {
let (conn, mut peer) = loopback_connection("test");
let n = conn.write(b"hello").await.unwrap();
assert_eq!(n, 5);
let mut buf = [0u8; 5];
peer.read_exact(&mut buf).await.unwrap();
assert_eq!(&buf, b"hello");
}
#[tokio::test]
async fn read_returns_peer_bytes() {
let (conn, mut peer) = loopback_connection("test");
peer.write_all(b"world").await.unwrap();
let mut buf = [0u8; 5];
let n = conn.read(&mut buf, Some(500)).await.unwrap();
assert_eq!(n, 5);
assert_eq!(&buf, b"world");
}
#[tokio::test]
async fn read_times_out_when_no_data() {
let (conn, _peer) = loopback_connection("test");
let mut buf = [0u8; 16];
let result = conn.read(&mut buf, Some(40)).await;
assert!(matches!(result, Err(SerialError::ReadTimeout)));
}
#[tokio::test]
async fn flush_set_dtr_rts_send_break_are_noops_on_loopback() {
let (conn, _peer) = loopback_connection("test");
conn.flush_buffers(FlushTarget::Both).await.unwrap();
conn.set_dtr_rts(true, false).await.unwrap();
conn.send_break(15).await.unwrap();
}
#[tokio::test]
async fn unread_bytes_are_returned_before_os_reads() {
let (conn, mut peer) = loopback_connection("test");
conn.unread(b"hello").await;
peer.write_all(b"world").await.unwrap();
let mut buf = [0u8; 5];
let n = conn.read(&mut buf, Some(100)).await.unwrap();
assert_eq!(n, 5);
assert_eq!(&buf, b"hello");
let n = conn.read(&mut buf, Some(100)).await.unwrap();
assert_eq!(n, 5);
assert_eq!(&buf, b"world");
}
#[tokio::test]
async fn flush_input_clears_unread_bytes() {
let (conn, _peer) = loopback_connection("test");
conn.unread(b"stale").await;
conn.flush_buffers(FlushTarget::Input).await.unwrap();
let mut buf = [0u8; 5];
let result = conn.read(&mut buf, Some(40)).await;
assert!(matches!(result, Err(SerialError::ReadTimeout)));
}
#[tokio::test]
async fn acquire_rx_reports_owner_and_releases_on_drop() {
let (conn, _peer) = loopback_connection("test");
let conn = Arc::new(conn);
let lease = SerialConnection::acquire_rx(&conn, "subscribe").unwrap();
let err = SerialConnection::acquire_rx(&conn, "read").unwrap_err();
assert_eq!(err, "Connection busy: subscribe already owns RX");
drop(lease);
SerialConnection::acquire_rx(&conn, "read").unwrap();
}
#[tokio::test]
async fn manager_rejects_duplicate_port() {
let mgr = ConnectionManager::new();
let (c1, _p1) = loopback_connection("port-a");
mgr.insert(c1).await.unwrap();
let (c2, _p2) = loopback_connection("port-a");
let err = mgr.insert(c2).await.unwrap_err();
assert!(matches!(err, SerialError::PortAlreadyOpen(_)));
}
#[tokio::test]
async fn manager_close_then_get_returns_connection_not_found() {
let mgr = ConnectionManager::new();
let (c, _p) = loopback_connection("port-z");
let id = mgr.insert(c).await.unwrap();
mgr.close(&id).await.unwrap();
let err = mgr.get(&id).await.unwrap_err();
assert!(matches!(err, SerialError::ConnectionNotFound(_)));
}
#[tokio::test]
async fn manager_get_unknown_id_returns_connection_not_found() {
let mgr = ConnectionManager::new();
let err = mgr.get("does-not-exist").await.unwrap_err();
assert!(matches!(err, SerialError::ConnectionNotFound(_)));
}
}