Skip to main content

some_serial/
lib.rs

1#![no_std]
2
3//! # Some Serial - 嵌入式串口驱动集合
4//!
5//! 本库提供统一的串口驱动接口,支持多种硬件平台:
6//! - ARM PL011 UART
7//! - NS16550/16450 UART(IO Port、MMIO 和 DesignWare APB 版本)
8//!
9//! ## 特性
10//!
11//! - 🏗️ 统一抽象接口 - 驱动层只提供 UART 寄存器语义,运行期队列由 OS runtime 提供
12//! - 🛡️ 无标准库设计 (`no_std`) - 适用于裸机和嵌入式系统
13//! - 📦 模块化架构 - 每个驱动独立模块,按需选择
14//! - 🔒 类型安全 - 使用 Rust 类型系统确保内存安全
15//! - ⚡ 高性能 - 零拷贝数据传输,直接硬件访问
16//!
17//! ## 支持的驱动
18//!
19//! ### ARM PL011 UART
20//! - 广泛用于 ARM Cortex-A、Cortex-M、Cortex-R 系列
21//! - 支持 FIFO、中断、回环等完整功能
22//!
23//! ### NS16550/16450 UART
24//! - 经典 PC 串口控制器,广泛兼容
25//! - 支持 IO Port(x86_64)、MMIO(通用)和 DesignWare APB 访问方式
26//! - 支持 16 字节 FIFO 缓冲
27//!
28//! ## 快速开始
29//!
30//! ```rust,no_run
31//! use core::ptr::NonNull;
32//!
33//! use some_serial::{Config, PollingUart as _, UartPort as _, ns16550::Ns16550, pl011::Pl011};
34//!
35//! // 选择合适的驱动
36//! #[cfg(target_arch = "aarch64")]
37//! let mut uart = Pl011::new(NonNull::new(0x9000000 as *mut u8).unwrap(), 24_000_000);
38//!
39//! #[cfg(not(target_arch = "aarch64"))]
40//! let mut uart = Ns16550::new_mmio(NonNull::new(0x9000000 as *mut u8).unwrap(), 1_843_200, 1);
41//!
42//! // 配置串口
43//! let config = Config::new()
44//!     .baudrate(115200)
45//!     .data_bits(some_serial::DataBits::Eight)
46//!     .stop_bits(some_serial::StopBits::One)
47//!     .parity(some_serial::Parity::None);
48//!
49//! uart.startup(&config).unwrap();
50//!
51//! while !uart.poll_status().tx_ready() {
52//!     core::hint::spin_loop();
53//! }
54//! uart.write_byte(b'h');
55//! ```
56
57#[cfg(test)]
58extern crate std;
59
60pub mod ns16550;
61pub mod pl011;
62
63use bitflags::bitflags;
64
65/// Allocation-free polling interface used by early consoles.
66pub trait PollingUart {
67    fn poll_status(&mut self) -> PollingEvent;
68
69    fn write_byte(&mut self, byte: u8);
70
71    fn read_byte(&mut self, status: PollingEvent) -> Option<Result<u8, TransferError>>;
72}
73
74bitflags! {
75    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
76    pub struct PollingEvent: u32 {
77        const RX_READY = 0x01;
78        const TX_READY = 0x02;
79        const RX_ERROR = 0x04;
80        const TX_ERROR = 0x08;
81        const OVERRUN = 0x10;
82        const MODEM_STATUS = 0x20;
83    }
84}
85
86impl PollingEvent {
87    pub const fn rx_ready(self) -> bool {
88        self.contains(Self::RX_READY)
89    }
90
91    pub const fn tx_ready(self) -> bool {
92        self.contains(Self::TX_READY)
93    }
94
95    pub const fn rx_error(self) -> bool {
96        self.intersects(Self::RX_ERROR.union(Self::OVERRUN))
97    }
98}
99
100pub type SerialEvent = PollingEvent;
101
102#[derive(Debug, Clone, Copy, PartialEq, Eq)]
103pub enum SerialDirection {
104    Input,
105    Output,
106}
107
108#[derive(thiserror::Error, Debug, Clone, Copy, PartialEq, Eq)]
109pub enum TransferError {
110    #[error("data overrun by `{0:#x}`")]
111    Overrun(u8),
112    #[error("parity error")]
113    Parity,
114    #[error("framing error")]
115    Framing,
116    #[error("break condition")]
117    Break,
118    #[error("serial closed")]
119    Closed,
120}
121
122#[derive(thiserror::Error, Debug, Clone, Copy, PartialEq, Eq)]
123#[error("transfer error after transferring {bytes_transferred} bytes: {kind}")]
124pub struct TransBytesError {
125    pub bytes_transferred: usize,
126    #[source]
127    pub kind: TransferError,
128}
129
130// Runtime capability types are re-exported for concrete driver consumers.
131pub use rdif_serial::*;
132
133#[cfg(test)]
134mod tests {
135    use super::*;
136
137    #[test]
138    fn transferred_byte_error_preserves_transfer_source() {
139        let error = TransBytesError {
140            bytes_transferred: 7,
141            kind: TransferError::Framing,
142        };
143
144        assert!(core::error::Error::source(&error).is_some());
145    }
146}