use std::fmt;
use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering};
use std::sync::Arc;
use std::sync::Mutex as StdMutex;
use std::time::{Duration, Instant};
use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt};
use tokio::sync::Mutex;
use tokio::time::timeout;
use tokio_serial::{SerialPort, SerialPortBuilderExt, SerialStream};
use tokio_util::sync::CancellationToken;
use uuid::Uuid;
use crate::error::{Result, SerialError};
use super::config::{
data_bits_to_str, flow_control_to_str, parity_to_str, stop_bits_to_str, ActiveProfileBinding,
ConnectionConfig, ConnectionState, ConnectionStatus, ConnectionSummary, DataBits, FlowControl,
FlushTarget, Parity, ReconnectPolicy, StopBits, MAX_BAUD_RATE,
};
use super::port_info::PortInfo;
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_flow_control(&mut self, flow_control: FlowControl) -> std::io::Result<()>;
fn set_break_state(&self, asserted: bool) -> std::io::Result<()>;
fn reconfigure_baud_rate(&mut self, _baud_rate: u32) -> std::io::Result<()> {
Ok(())
}
fn reconfigure_data_bits(&mut self, _data_bits: serialport::DataBits) -> std::io::Result<()> {
Ok(())
}
fn reconfigure_stop_bits(&mut self, _stop_bits: serialport::StopBits) -> std::io::Result<()> {
Ok(())
}
fn reconfigure_parity(&mut self, _parity: serialport::Parity) -> std::io::Result<()> {
Ok(())
}
}
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_flow_control(&mut self, flow_control: FlowControl) -> std::io::Result<()> {
SerialPort::set_flow_control(self, flow_control.into()).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 reconfigure_baud_rate(&mut self, baud_rate: u32) -> std::io::Result<()> {
SerialPort::set_baud_rate(self, baud_rate).map_err(io_error_from_serialport)
}
fn reconfigure_data_bits(&mut self, data_bits: serialport::DataBits) -> std::io::Result<()> {
SerialPort::set_data_bits(self, data_bits).map_err(io_error_from_serialport)
}
fn reconfigure_stop_bits(&mut self, stop_bits: serialport::StopBits) -> std::io::Result<()> {
SerialPort::set_stop_bits(self, stop_bits).map_err(io_error_from_serialport)
}
fn reconfigure_parity(&mut self, parity: serialport::Parity) -> std::io::Result<()> {
SerialPort::set_parity(self, parity).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,
name: Option<String>,
baud_rate: StdMutex<u32>,
data_bits: StdMutex<DataBits>,
stop_bits: StdMutex<StopBits>,
parity: StdMutex<Parity>,
flow_control: StdMutex<FlowControl>,
io: Mutex<Option<Box<dyn SerialIo>>>,
close_token: CancellationToken,
closed: AtomicBool,
tx_bytes: AtomicU64,
rx_bytes: AtomicU64,
last_activity: StdMutex<Option<std::time::SystemTime>>,
read_ops: AtomicU64,
write_ops: AtomicU64,
truncation_count: AtomicU64,
port_info: Option<PortInfo>,
log: Arc<crate::log_buffer::LogBuffer>,
state: StdMutex<ConnectionState>,
pub(crate) reconnect_policy: StdMutex<ReconnectPolicy>,
reconnect_attempts: AtomicU64,
last_error: StdMutex<Option<(std::time::SystemTime, String)>>,
tx_framing_default: StdMutex<Option<crate::framing::TxFramingConfig>>,
rx_framing_default: StdMutex<Option<crate::framing::RxFramingConfig>>,
rx_parser_default: StdMutex<Option<crate::framing::ParserConfig>>,
protocol_default: StdMutex<Option<crate::framing::ProtocolPreset>>,
max_buffered_bytes_default: AtomicUsize,
active_profile: StdMutex<Option<ActiveProfileBinding>>,
learning_lock: tokio::sync::Mutex<()>,
control_lock: tokio::sync::Mutex<()>,
rx_buffer_size: usize,
}
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)
.field("name", &self.name)
.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_with_config(config, Box::new(stream)))
}
pub fn from_io(port: String, io: Box<dyn SerialIo>) -> Self {
Self::from_io_with_config(
ConnectionConfig {
port,
name: None,
baud_rate: 115200,
data_bits: DataBits::Eight,
stop_bits: StopBits::One,
parity: Parity::None,
flow_control: FlowControl::None,
port_info: None,
log_capacity: 1024,
log_enabled: true,
tx_framing: None,
rx_framing: None,
rx_parser: None,
protocol: None,
rx_buffer_size: crate::limits::DEFAULT_RX_BUFFER_SIZE,
max_buffered_bytes: 32768,
},
io,
)
}
pub fn from_io_with_config(config: ConnectionConfig, io: Box<dyn SerialIo>) -> Self {
let log = crate::log_buffer::LogBuffer::new_shared(config.log_capacity, config.log_enabled);
log.opened();
Self {
id: Uuid::new_v4().to_string(),
port: config.port,
name: config.name,
baud_rate: StdMutex::new(config.baud_rate),
data_bits: StdMutex::new(config.data_bits),
stop_bits: StdMutex::new(config.stop_bits),
parity: StdMutex::new(config.parity),
flow_control: StdMutex::new(config.flow_control),
io: Mutex::new(Some(io)),
close_token: CancellationToken::new(),
closed: AtomicBool::new(false),
tx_bytes: AtomicU64::new(0),
rx_bytes: AtomicU64::new(0),
last_activity: StdMutex::new(None),
read_ops: AtomicU64::new(0),
write_ops: AtomicU64::new(0),
truncation_count: AtomicU64::new(0),
port_info: config.port_info,
log,
state: StdMutex::new(ConnectionState::Open),
reconnect_policy: StdMutex::new(ReconnectPolicy::default()),
reconnect_attempts: AtomicU64::new(0),
last_error: StdMutex::new(None),
tx_framing_default: StdMutex::new(config.tx_framing),
rx_framing_default: StdMutex::new(config.rx_framing),
rx_parser_default: StdMutex::new(config.rx_parser),
protocol_default: StdMutex::new(config.protocol),
max_buffered_bytes_default: AtomicUsize::new(config.max_buffered_bytes),
active_profile: StdMutex::new(None),
learning_lock: tokio::sync::Mutex::new(()),
control_lock: tokio::sync::Mutex::new(()),
rx_buffer_size: config.rx_buffer_size,
}
}
pub fn id(&self) -> &str {
&self.id
}
pub fn port(&self) -> &str {
&self.port
}
pub fn name(&self) -> Option<&str> {
self.name.as_deref()
}
pub fn baud_rate(&self) -> u32 {
*self.baud_rate.lock().expect("baud_rate mutex poisoned")
}
pub fn flow_control(&self) -> FlowControl {
*self
.flow_control
.lock()
.expect("flow_control mutex poisoned")
}
pub fn data_bits(&self) -> DataBits {
*self.data_bits.lock().expect("data_bits mutex poisoned")
}
pub fn stop_bits(&self) -> StopBits {
*self.stop_bits.lock().expect("stop_bits mutex poisoned")
}
pub fn parity(&self) -> Parity {
*self.parity.lock().expect("parity mutex poisoned")
}
pub fn port_info(&self) -> Option<&PortInfo> {
self.port_info.as_ref()
}
pub fn log(&self) -> &Arc<crate::log_buffer::LogBuffer> {
&self.log
}
pub fn tx_framing_default(&self) -> Option<crate::framing::TxFramingConfig> {
self.tx_framing_default.lock().expect("poisoned").clone()
}
pub fn rx_framing_default(&self) -> Option<crate::framing::RxFramingConfig> {
self.rx_framing_default.lock().expect("poisoned").clone()
}
pub fn rx_parser_default(&self) -> Option<crate::framing::ParserConfig> {
self.rx_parser_default.lock().expect("poisoned").clone()
}
pub fn protocol_default(&self) -> Option<crate::framing::ProtocolPreset> {
*self
.protocol_default
.lock()
.expect("protocol_default mutex poisoned")
}
pub fn max_buffered_bytes_default(&self) -> usize {
self.max_buffered_bytes_default
.load(std::sync::atomic::Ordering::SeqCst)
}
pub fn active_profile_binding(&self) -> Option<ActiveProfileBinding> {
self.active_profile.lock().expect("poisoned").clone()
}
pub(crate) fn set_active_profile_binding(&self, binding: Option<ActiveProfileBinding>) {
*self.active_profile.lock().expect("poisoned") = binding;
}
pub(crate) fn update_active_profile_binding(
&self,
update: impl FnOnce(&mut ActiveProfileBinding),
) {
let mut guard = self.active_profile.lock().expect("poisoned");
if let Some(binding) = guard.as_mut() {
update(binding);
}
}
pub(crate) fn learning_lock(&self) -> &tokio::sync::Mutex<()> {
&self.learning_lock
}
pub(crate) fn control_lock(&self) -> &tokio::sync::Mutex<()> {
&self.control_lock
}
pub(crate) fn effective_defaults(&self) -> crate::profiles::ProfileDefaults {
crate::profiles::ProfileDefaults {
baud_rate: self.baud_rate(),
data_bits: data_bits_to_str(self.data_bits()),
stop_bits: stop_bits_to_str(self.stop_bits()),
parity: parity_to_str(self.parity()),
flow_control: flow_control_to_str(self.flow_control()),
name: self.name.clone(),
tx_framing: self.tx_framing_default(),
rx_framing: self.rx_framing_default(),
rx_parser: self.rx_parser_default(),
protocol: self.protocol_default(),
rx_buffer_size: self.rx_buffer_size(),
max_buffered_bytes: self.max_buffered_bytes_default(),
reconnect_policy: self.reconnect_policy.lock().expect("poisoned").clone(),
log_capacity: self.log.capacity(),
log_enabled: self.log.is_enabled(),
}
}
pub fn rx_buffer_size(&self) -> usize {
self.rx_buffer_size
}
pub(crate) fn set_tx_framing_default(&self, v: Option<crate::framing::TxFramingConfig>) {
*self.tx_framing_default.lock().expect("poisoned") = v;
}
pub(crate) fn set_rx_framing_default(&self, v: Option<crate::framing::RxFramingConfig>) {
*self.rx_framing_default.lock().expect("poisoned") = v;
}
pub(crate) fn set_rx_parser_default(&self, v: Option<crate::framing::ParserConfig>) {
*self.rx_parser_default.lock().expect("poisoned") = v;
}
pub(crate) fn set_protocol_default(&self, v: Option<crate::framing::ProtocolPreset>) {
*self.protocol_default.lock().expect("poisoned") = v;
}
pub(crate) fn set_max_buffered_bytes_default(&self, v: usize) {
self.max_buffered_bytes_default
.store(v, std::sync::atomic::Ordering::SeqCst);
}
pub fn state(&self) -> ConnectionState {
*self.state.lock().expect("state mutex poisoned")
}
fn set_state(&self, new_state: ConnectionState) {
*self.state.lock().expect("state mutex poisoned") = new_state;
}
pub async fn mark_disconnected(&self, error_message: String) {
let was_healthy = self.state().is_healthy();
self.set_state(ConnectionState::Disconnected);
self.last_error
.lock()
.expect("poisoned")
.replace((std::time::SystemTime::now(), error_message.clone()));
self.log.rx_data(0); self.log.record(
None,
crate::log_buffer::LogEvent::Disconnect {
error: error_message,
},
);
let mut io_lock = self.io.lock().await;
if let Some(mut io) = io_lock.take() {
let _ = io.clear_os_buffers(FlushTarget::Input);
let _ = io.shutdown().await;
}
if was_healthy {
tracing::warn!("Connection {} disconnected", self.display_name());
}
}
pub async fn reconnect(&self) -> Result<()> {
let state = self.state();
if state == ConnectionState::Open {
return Ok(()); }
if state == ConnectionState::Closed {
return Err(SerialError::ConnectionClosed(self.display_name()));
}
self.set_state(ConnectionState::Reconnecting);
self.reconnect_attempts.fetch_add(1, Ordering::SeqCst);
let attempt = self.reconnect_attempts.load(Ordering::SeqCst) as u32;
self.log.record(
None,
crate::log_buffer::LogEvent::ReconnectStart { attempt },
);
let config = self.build_config();
match build_stream(&config) {
Ok(stream) => {
let mut io_lock = self.io.lock().await;
*io_lock = Some(Box::new(stream));
self.closed.store(false, Ordering::SeqCst);
self.set_state(ConnectionState::Open);
self.log
.record(None, crate::log_buffer::LogEvent::ReconnectSuccess);
tracing::info!("Connection {} reconnected", self.display_name());
Ok(())
}
Err(e) => {
self.set_state(ConnectionState::Disconnected);
let msg = e.to_string();
self.log.record(
None,
crate::log_buffer::LogEvent::ReconnectFailed {
attempt,
error: msg,
},
);
Err(e)
}
}
}
pub(super) fn reset_reconnect_attempts(&self) {
self.reconnect_attempts.store(0, Ordering::SeqCst);
}
fn build_config(&self) -> ConnectionConfig {
ConnectionConfig {
port: self.port.clone(),
name: self.name.clone(),
baud_rate: self.baud_rate(),
data_bits: self.data_bits(),
stop_bits: self.stop_bits(),
parity: self.parity(),
flow_control: self.flow_control(),
port_info: self.port_info.clone(),
log_capacity: 1024, log_enabled: self.log.is_enabled(),
tx_framing: self.tx_framing_default(),
rx_framing: self.rx_framing_default(),
rx_parser: self.rx_parser_default(),
protocol: self.protocol_default(),
rx_buffer_size: self.rx_buffer_size(),
max_buffered_bytes: self.max_buffered_bytes_default(),
}
}
pub fn record_tx_bytes(&self, n: usize) {
self.tx_bytes.fetch_add(n as u64, Ordering::SeqCst);
*self.last_activity.lock().expect("poisoned") = Some(std::time::SystemTime::now());
}
pub fn record_rx_bytes(&self, n: usize) {
self.rx_bytes.fetch_add(n as u64, Ordering::SeqCst);
*self.last_activity.lock().expect("poisoned") = Some(std::time::SystemTime::now());
}
pub fn last_activity_ms(&self) -> Option<u64> {
self.last_activity.lock().expect("poisoned").and_then(|t| {
t.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_millis() as u64)
.ok()
})
}
pub fn record_read_op(&self) {
self.read_ops.fetch_add(1, Ordering::SeqCst);
}
pub fn record_write_op(&self) {
self.write_ops.fetch_add(1, Ordering::SeqCst);
}
pub fn record_truncation(&self) {
self.truncation_count.fetch_add(1, Ordering::SeqCst);
}
pub fn status_snapshot(&self) -> ConnectionStatus {
ConnectionStatus {
connection_id: self.id().to_string(),
name: self.name().map(str::to_string),
port: self.port().to_string(),
baud_rate: self.baud_rate(),
data_bits: data_bits_to_str(self.data_bits()),
stop_bits: stop_bits_to_str(self.stop_bits()),
parity: parity_to_str(self.parity()),
flow_control: flow_control_to_str(self.flow_control()),
is_closed: self.closed.load(Ordering::SeqCst),
tx_bytes: self.tx_bytes.load(Ordering::SeqCst),
rx_bytes: self.rx_bytes.load(Ordering::SeqCst),
last_activity_ms: self.last_activity_ms(),
read_ops: self.read_ops.load(Ordering::SeqCst),
write_ops: self.write_ops.load(Ordering::SeqCst),
truncation_count: self.truncation_count.load(Ordering::SeqCst),
port_info: self.port_info.clone(),
state: self.state(),
reconnect_attempts: self.reconnect_attempts.load(Ordering::SeqCst),
last_error: self
.last_error
.lock()
.expect("poisoned")
.as_ref()
.map(|(_, msg)| msg.clone()),
profile: self.active_profile_binding().map(|b| b.to_session_result()),
}
}
pub fn cancel_token(&self) -> CancellationToken {
self.close_token.clone()
}
pub fn summary(&self) -> ConnectionSummary {
ConnectionSummary {
connection_id: self.id().to_string(),
name: self.name().map(str::to_string),
port: self.port().to_string(),
baud_rate: self.baud_rate(),
flow_control: self.flow_control(),
profile: self.active_profile_binding().map(|b| b.to_session_result()),
}
}
fn ensure_open(&self) -> Result<()> {
if self.closed.load(Ordering::SeqCst) {
return Err(SerialError::ConnectionClosed(self.display_name()));
}
Ok(())
}
fn display_name(&self) -> String {
self.name.clone().unwrap_or_else(|| self.id.clone())
}
pub async fn write(&self, data: &[u8]) -> Result<usize> {
self.ensure_open()?;
self.log.tx_data(data.len());
let mut io = self.io.lock().await;
let io = io
.as_mut()
.ok_or_else(|| SerialError::ConnectionClosed(self.display_name()))?;
io.write_all(data).await?;
io.flush().await?;
self.record_tx_bytes(data.len());
Ok(data.len())
}
pub async fn read(&self, dst: &mut [u8], timeout_ms: Option<u64>) -> Result<usize> {
const POLL_MS: u64 = 50;
self.ensure_open()?;
match timeout_ms {
None => {
let mut io = self.io.lock().await;
let io = io
.as_mut()
.ok_or_else(|| SerialError::ConnectionClosed(self.display_name()))?;
let n = tokio::select! {
_ = self.close_token.cancelled() => Err(SerialError::ConnectionClosed(self.display_name())),
res = io.read(dst) => Ok(res?),
}?;
self.record_rx_bytes(n);
Ok(n)
}
Some(ms) => {
let deadline = Instant::now() + Duration::from_millis(ms);
loop {
if self.close_token.is_cancelled() {
return Err(SerialError::ConnectionClosed(self.display_name()));
}
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 io = self.io.lock().await;
let io = io
.as_mut()
.ok_or_else(|| SerialError::ConnectionClosed(self.display_name()))?;
match tokio::select! {
_ = self.close_token.cancelled() => return Err(SerialError::ConnectionClosed(self.display_name())),
res = timeout(poll_dur, io.read(dst)) => res,
} {
Ok(Ok(n)) if n > 0 => {
self.record_rx_bytes(n);
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 flush_buffers(&self, target: FlushTarget) -> Result<()> {
self.ensure_open()?;
let io = self.io.lock().await;
io.as_ref()
.ok_or_else(|| SerialError::ConnectionClosed(self.display_name()))?
.clear_os_buffers(target)
.map_err(SerialError::from)
}
pub async fn set_dtr_rts(&self, dtr: bool, rts: bool) -> Result<()> {
let _control = self.control_lock().lock().await;
self.set_dtr_rts_unlocked(dtr, rts).await
}
pub(crate) async fn set_dtr_rts_unlocked(&self, dtr: bool, rts: bool) -> Result<()> {
self.ensure_open()?;
let mut io = self.io.lock().await;
io.as_mut()
.ok_or_else(|| SerialError::ConnectionClosed(self.display_name()))?
.set_dtr_rts(dtr, rts)
.map_err(SerialError::from)
}
pub async fn set_flow_control(&self, flow_control: FlowControl) -> Result<()> {
self.ensure_open()?;
let mut io = self.io.lock().await;
io.as_mut()
.ok_or_else(|| SerialError::ConnectionClosed(self.display_name()))?
.set_flow_control(flow_control)
.map_err(SerialError::from)?;
*self
.flow_control
.lock()
.expect("flow_control mutex poisoned") = flow_control;
Ok(())
}
pub async fn set_break_state(&self, enabled: bool) -> Result<()> {
self.ensure_open()?;
let io = self.io.lock().await;
io.as_ref()
.ok_or_else(|| SerialError::ConnectionClosed(self.display_name()))?
.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
}
pub async fn reconfigure(
&self,
baud_rate: Option<u32>,
data_bits: Option<DataBits>,
stop_bits: Option<StopBits>,
parity: Option<Parity>,
flow_control: Option<FlowControl>,
) -> Result<ConnectionStatus> {
self.ensure_open()?;
if let Some(rate) = baud_rate {
ensure_valid_baud_rate(rate)?;
}
{
let mut io = self.io.lock().await;
let io = io
.as_mut()
.ok_or_else(|| SerialError::ConnectionClosed(self.display_name()))?;
if let Some(rate) = baud_rate {
io.reconfigure_baud_rate(rate).map_err(SerialError::from)?;
}
if let Some(db) = data_bits {
io.reconfigure_data_bits(db.into())
.map_err(SerialError::from)?;
}
if let Some(sb) = stop_bits {
io.reconfigure_stop_bits(sb.into())
.map_err(SerialError::from)?;
}
if let Some(p) = parity {
io.reconfigure_parity(p.into()).map_err(SerialError::from)?;
}
if let Some(fc) = flow_control {
io.set_flow_control(fc).map_err(SerialError::from)?;
}
}
if let Some(rate) = baud_rate {
*self.baud_rate.lock().expect("poisoned") = rate;
}
if let Some(db) = data_bits {
*self.data_bits.lock().expect("poisoned") = db;
}
if let Some(sb) = stop_bits {
*self.stop_bits.lock().expect("poisoned") = sb;
}
if let Some(p) = parity {
*self.parity.lock().expect("poisoned") = p;
}
if let Some(fc) = flow_control {
*self.flow_control.lock().expect("poisoned") = fc;
}
Ok(self.status_snapshot())
}
pub async fn close(&self) -> Result<()> {
if self.closed.swap(true, Ordering::SeqCst) {
return Ok(());
}
self.set_state(ConnectionState::Closed);
self.close_token.cancel();
let mut io = self.io.lock().await;
if let Some(mut io) = io.take() {
io.clear_os_buffers(FlushTarget::Input)
.map_err(SerialError::from)?;
io.shutdown().await?;
}
Ok(())
}
}
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)))
}
#[cfg(test)]
impl SerialConnection {
pub(crate) fn set_state_for_test(&mut self, state: ConnectionState) {
*self.state.lock().unwrap() = state;
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::serial::manager::ConnectionManager;
use crate::serial::test_support::loopback_connection;
use crate::stop_controller::RxStopController;
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 close_cancels_inflight_read() {
let mgr = ConnectionManager::new();
let (conn, _peer) = loopback_connection("port-read-close");
let id = mgr.insert(conn).await.unwrap();
let connection = mgr.get(&id).await.unwrap();
let reader = tokio::spawn(async move {
let mut buf = [0u8; 16];
connection.read(&mut buf, Some(2_000)).await
});
tokio::time::sleep(Duration::from_millis(100)).await;
mgr.close(&id).await.unwrap();
let err = reader.await.unwrap().unwrap_err();
assert!(matches!(err, SerialError::ConnectionClosed(_)));
}
#[test]
fn disconnect_state_maps_connection_state_correctly() {
use crate::tools::rx_consume::{disconnect_state, DisconnectState};
use std::time::Instant;
let (mut conn, _peer) = loopback_connection("test");
let mut ctrl = RxStopController::new(Instant::now(), Some(5000), 0, None);
assert!(matches!(
disconnect_state(&conn, &mut ctrl),
DisconnectState::Active
));
conn.set_state_for_test(ConnectionState::Closed);
assert!(matches!(
disconnect_state(&conn, &mut ctrl),
DisconnectState::Closed
));
conn.set_state_for_test(ConnectionState::Reconnecting);
conn.reconnect_policy.lock().unwrap().enabled = true;
assert!(matches!(
disconnect_state(&conn, &mut ctrl),
DisconnectState::Reconnecting
));
conn.reconnect_policy.lock().unwrap().enabled = false;
assert!(matches!(
disconnect_state(&conn, &mut ctrl),
DisconnectState::Closed
));
}
}