unistore_serial/
lib.rs

1//! # UniStore Serial
2//!
3//! 串口通信能力模块,提供 RS232/UART 通信支持。
4//!
5//! ## 功能特性
6//!
7//! - 串口发现与枚举
8//! - 配置管理(波特率、数据位、停止位、校验)
9//! - 异步读写操作
10//! - 超时控制
11//! - 流控制(RTS/CTS、XON/XOFF)
12//!
13//! ## 使用示例
14//!
15//! ```ignore
16//! use unistore_serial::{SerialPort, SerialConfig};
17//!
18//! // 列出可用串口
19//! let ports = SerialPort::list_ports()?;
20//!
21//! // 打开串口
22//! let config = SerialConfig::default()
23//!     .with_baud_rate(115200)
24//!     .with_timeout_ms(1000);
25//!
26//! let mut port = SerialPort::open("COM1", config)?;
27//!
28//! // 写入数据
29//! port.write(b"AT\r\n")?;
30//!
31//! // 读取响应
32//! let response = port.read_line()?;
33//! ```
34
35mod config;
36mod error;
37mod port;
38mod discovery;
39
40pub use config::{
41    DataBits, FlowControl, Parity, SerialConfig, SerialConfigBuilder, StopBits,
42};
43pub use discovery::{
44    list_ports, list_usb_ports, find_by_vid_pid, port_exists,
45    PortInfo, PortType,
46};
47pub use error::SerialError;
48pub use port::SerialPort;
49
50use async_trait::async_trait;
51use unistore_core::{Capability, CapabilityError, CapabilityInfo};
52
53/// 串口通信能力
54pub struct SerialCapability {
55    started: std::sync::atomic::AtomicBool,
56}
57
58impl SerialCapability {
59    /// 创建新实例
60    pub fn new() -> Self {
61        Self {
62            started: std::sync::atomic::AtomicBool::new(false),
63        }
64    }
65}
66
67impl Default for SerialCapability {
68    fn default() -> Self {
69        Self::new()
70    }
71}
72
73#[async_trait]
74impl Capability for SerialCapability {
75    fn info(&self) -> CapabilityInfo {
76        CapabilityInfo::new("serial", "0.1.0")
77            .with_description("Serial port communication capability")
78    }
79
80    async fn start(&mut self) -> Result<(), CapabilityError> {
81        self.started
82            .store(true, std::sync::atomic::Ordering::SeqCst);
83        tracing::info!("Serial capability started");
84        Ok(())
85    }
86
87    async fn stop(&mut self) -> Result<(), CapabilityError> {
88        self.started
89            .store(false, std::sync::atomic::Ordering::SeqCst);
90        tracing::info!("Serial capability stopped");
91        Ok(())
92    }
93
94    async fn health_check(&self) -> Result<(), CapabilityError> {
95        if self.started.load(std::sync::atomic::Ordering::SeqCst) {
96            Ok(())
97        } else {
98            Err(CapabilityError::unhealthy("serial", "capability not started"))
99        }
100    }
101}