use std::sync::Arc;
use std::time::{Duration, Instant};
use rmcp::{
model::{
LoggingLevel, LoggingMessageNotificationParam, ProgressNotificationParam, ProgressToken,
},
service::Peer,
Json, RoleServer,
};
use tracing::{error, warn};
use crate::codec::{self, Encoding};
use crate::error::SerialError;
use crate::serial::{
ConnectionConfig, ConnectionManager, DataBits, FlowControl, Parity, SerialConnection, StopBits,
};
use crate::tools::types::*;
pub use crate::limits::{
MAX_READ_BYTES, MAX_STREAM_CHUNK_BYTES, MAX_TIMEOUT_MS, MAX_WAIT_BYTES, MAX_WRITE_BYTES,
MIN_POLL_INTERVAL_MS, MIN_READ_BYTES, MIN_STREAM_CHUNK_BYTES, MIN_WAIT_BYTES,
};
pub(crate) const DEFAULT_READ_TIMEOUT_MS: u64 = 1000;
pub fn clamp_or_err(name: &str, value: usize, max: usize) -> Result<usize, String> {
if value > max {
Err(format!("{name}={value} exceeds maximum {max}"))
} else {
Ok(value)
}
}
pub fn require_min_or_err(name: &str, value: usize, min: usize) -> Result<usize, String> {
if value < min {
Err(format!("{name}={value} is below minimum {min}"))
} else {
Ok(value)
}
}
pub fn clamp_timeout_or_err(name: &str, value: u64, max: u64) -> Result<u64, String> {
if value > max {
Err(format!("{name}={value}ms exceeds maximum {max}ms"))
} else {
Ok(value)
}
}
pub fn clamp_poll_interval_or_err(name: &str, value: u64, min: u64) -> Result<u64, String> {
if value < min {
Err(format!("{name}={value}ms is below minimum {min}ms"))
} else {
Ok(value)
}
}
pub async fn lookup_connection(
connections: &Arc<ConnectionManager>,
id: &str,
) -> Result<Arc<SerialConnection>, String> {
connections
.get(id)
.await
.map_err(|_| format!("Connection ID {id} not found"))
}
pub struct ReadOutcome {
pub bytes: Vec<u8>,
pub timed_out: bool,
pub elapsed_ms: u64,
}
pub async fn read_bytes(
connection: &SerialConnection,
max_bytes: usize,
timeout_ms: Option<u64>,
ct: &tokio_util::sync::CancellationToken,
progress_token: Option<ProgressToken>,
peer: Option<&Peer<RoleServer>>,
) -> Result<ReadOutcome, String> {
const SETTLE_MS: u64 = 50;
let effective_timeout = timeout_ms.unwrap_or(DEFAULT_READ_TIMEOUT_MS);
let deadline = Instant::now() + Duration::from_millis(effective_timeout);
let read_start = Instant::now();
let mut buf = vec![0u8; max_bytes];
let mut last_progress = Instant::now();
let first_n = loop {
let remaining = deadline.saturating_duration_since(Instant::now());
if remaining.is_zero() {
return Ok(ReadOutcome {
bytes: Vec::new(),
timed_out: true,
elapsed_ms: read_start.elapsed().as_millis() as u64,
});
}
let poll_ms = remaining.as_millis() as u64;
let poll_ms = poll_ms.clamp(1, 250);
match tokio::select! {
_ = ct.cancelled() => return Err("Cancelled".into()),
res = connection.read(&mut buf, Some(poll_ms)) => res,
} {
Ok(n) if n > 0 => break n,
Ok(_) => {}
Err(SerialError::ReadTimeout) => {}
Err(e) => return Err(log_tool_err("read", "Data reading failed", e)),
}
if let (Some(token), Some(peer)) = (progress_token.clone(), peer) {
if last_progress.elapsed() >= Duration::from_millis(250) {
last_progress = Instant::now();
let remaining = deadline.saturating_duration_since(Instant::now());
let elapsed_ms = effective_timeout.saturating_sub(remaining.as_millis() as u64);
let _ = peer
.notify_progress(ProgressNotificationParam {
progress_token: token,
progress: elapsed_ms as f64,
total: Some(effective_timeout as f64),
message: Some("waiting for data".into()),
})
.await;
}
}
};
let mut total = first_n;
while total < max_bytes {
let remaining = deadline
.saturating_duration_since(Instant::now())
.as_millis() as u64;
let settle = remaining.min(SETTLE_MS);
if settle == 0 {
break;
}
let res = tokio::select! {
_ = ct.cancelled() => return Err("Cancelled".into()),
res = connection.read(&mut buf[total..], Some(settle)) => res,
};
match res {
Ok(n) if n > 0 => {
total += n;
if let (Some(token), Some(peer)) = (progress_token.clone(), peer) {
let remaining = deadline.saturating_duration_since(Instant::now());
let elapsed_ms = effective_timeout.saturating_sub(remaining.as_millis() as u64);
if last_progress.elapsed() >= Duration::from_millis(250) {
last_progress = Instant::now();
let _ = peer
.notify_progress(ProgressNotificationParam {
progress_token: token,
progress: elapsed_ms as f64,
total: Some(effective_timeout as f64),
message: Some(format!("read {total} bytes")),
})
.await;
}
}
}
_ => break,
}
}
buf.truncate(total);
Ok(ReadOutcome {
bytes: buf,
timed_out: false,
elapsed_ms: read_start.elapsed().as_millis() as u64,
})
}
pub struct WaitOutcome {
pub bytes: Vec<u8>,
pub match_index: Option<usize>,
pub timed_out: bool,
}
pub async fn read_until_pattern(
connection: &SerialConnection,
pattern: &[u8],
timeout_ms: u64,
max_bytes: usize,
ct: &tokio_util::sync::CancellationToken,
progress_token: Option<ProgressToken>,
peer: Option<&Peer<RoleServer>>,
) -> Result<WaitOutcome, String> {
const CHUNK_CAPACITY: usize = 256;
let deadline = Instant::now() + Duration::from_millis(timeout_ms);
let mut accumulated: Vec<u8> = Vec::with_capacity(CHUNK_CAPACITY.min(max_bytes));
let mut last_progress = Instant::now();
if let (Some(token), Some(peer)) = (progress_token.clone(), peer) {
let _ = peer
.notify_progress(ProgressNotificationParam {
progress_token: token,
progress: 0.0,
total: Some(timeout_ms as f64),
message: Some("wait_for started".to_string()),
})
.await;
}
loop {
if ct.is_cancelled() {
return Err("Cancelled".into());
}
if let Some(idx) = find_subslice(&accumulated, pattern) {
return Ok(WaitOutcome {
bytes: accumulated,
match_index: Some(idx),
timed_out: false,
});
}
if accumulated.len() >= max_bytes {
return Ok(WaitOutcome {
bytes: accumulated,
match_index: None,
timed_out: false,
});
}
let now = Instant::now();
if now >= deadline {
return Ok(WaitOutcome {
bytes: accumulated,
match_index: None,
timed_out: true,
});
}
if let (Some(token), Some(peer)) = (progress_token.clone(), peer) {
if last_progress.elapsed() >= Duration::from_millis(250) {
last_progress = Instant::now();
let remaining = deadline.saturating_duration_since(Instant::now());
let elapsed_ms = timeout_ms.saturating_sub(remaining.as_millis() as u64);
let _ = peer
.notify_progress(ProgressNotificationParam {
progress_token: token,
progress: elapsed_ms as f64,
total: Some(timeout_ms as f64),
message: Some(format!("wait_for {} bytes", accumulated.len())),
})
.await;
}
}
let remaining_ms = (deadline - now).as_millis() as u64;
let remaining_ms = remaining_ms.clamp(1, 250);
let room = (max_bytes - accumulated.len()).min(CHUNK_CAPACITY);
let mut chunk = vec![0u8; room];
match tokio::select! {
_ = ct.cancelled() => return Err("Cancelled".into()),
res = connection.read(&mut chunk, Some(remaining_ms)) => res,
} {
Ok(0) => continue,
Ok(n) => {
chunk.truncate(n);
accumulated.extend_from_slice(&chunk);
}
Err(SerialError::ReadTimeout) => {
continue;
}
Err(e) => return Err(log_tool_err("wait_for", "Read failed during wait", e)),
}
}
}
pub(crate) fn find_subslice(haystack: &[u8], needle: &[u8]) -> Option<usize> {
if needle.is_empty() || haystack.len() < needle.len() {
return None;
}
haystack
.windows(needle.len())
.position(|window| window == needle)
}
pub async fn stream_rx(
peer: Peer<rmcp::RoleServer>,
connection: Arc<SerialConnection>,
encoding: Encoding,
max_chunk_bytes: usize,
poll_interval_ms: u64,
) {
let logger = format!("serial:{}", connection.id());
let mut buf = vec![0u8; max_chunk_bytes];
loop {
match connection.read(&mut buf, Some(poll_interval_ms)).await {
Ok(0) | Err(SerialError::ReadTimeout) => continue,
Ok(n) => {
let chunk = &buf[..n];
let encoded = match codec::encode(encoding, chunk) {
Ok(s) => s,
Err(e) => {
warn!(
"RX encoding error on {}: {encoding} cannot encode {} bytes — dropped",
connection.id(),
n
);
let payload = serde_json::json!({
"connection_id": connection.id(),
"encoding_error": true,
"encoding": encoding.to_string(),
"bytes_dropped": n,
"reason": e.to_string(),
});
let param = LoggingMessageNotificationParam {
level: LoggingLevel::Warning,
logger: Some(logger.clone()),
data: payload,
};
if let Err(e) = peer.notify_logging_message(param).await {
error!("RX stream peer disconnected: {}", e);
break;
}
continue;
}
};
let payload = serde_json::json!({
"connection_id": connection.id(),
"bytes_read": n,
"encoding": encoding.to_string(),
"data": encoded,
});
let param = LoggingMessageNotificationParam {
level: LoggingLevel::Info,
logger: Some(logger.clone()),
data: payload,
};
if let Err(e) = peer.notify_logging_message(param).await {
error!("RX stream peer disconnected: {}", e);
break;
}
}
Err(e) => {
error!("RX stream read error on {}: {}", connection.id(), e);
break;
}
}
}
}
pub fn build_read_result(
outcome: ReadOutcome,
connection_id: String,
encoding: Encoding,
requested_timeout_ms: Option<u64>,
) -> Result<Json<ReadResult>, String> {
let timeout_ms = requested_timeout_ms.unwrap_or(DEFAULT_READ_TIMEOUT_MS);
if outcome.timed_out {
return Err(format!(
"Read timed out after {timeout_ms}ms on {connection_id}"
));
}
let bytes_read = outcome.bytes.len();
let elapsed_ms = outcome.elapsed_ms;
let data = codec::encode(encoding, &outcome.bytes)
.map_err(|e| format!("Data encoding failed - {e}"))?;
Ok(Json(ReadResult {
connection_id,
bytes_read,
encoding: encoding.to_string(),
data,
timeout_ms,
elapsed_ms,
}))
}
pub fn parse_encoding(raw: &str) -> Result<Encoding, String> {
raw.parse::<Encoding>()
.map_err(|e| format!("Unsupported encoding - {e}"))
}
pub fn parse_open_args(args: OpenArgs) -> Result<ConnectionConfig, String> {
Ok(ConnectionConfig {
port: args.port,
baud_rate: args.baud_rate.0,
data_bits: parse_data_bits(&args.data_bits)?,
stop_bits: parse_stop_bits(&args.stop_bits)?,
parity: parse_parity(&args.parity)?,
flow_control: parse_flow_control(&args.flow_control)?,
})
}
pub fn parse_data_bits(raw: &str) -> Result<DataBits, String> {
match raw {
"5" => Ok(DataBits::Five),
"6" => Ok(DataBits::Six),
"7" => Ok(DataBits::Seven),
"8" => Ok(DataBits::Eight),
other => Err(format!("Invalid data_bits {other:?} (expected 5/6/7/8)")),
}
}
pub fn parse_stop_bits(raw: &str) -> Result<StopBits, String> {
match raw {
"1" => Ok(StopBits::One),
"2" => Ok(StopBits::Two),
other => Err(format!("Invalid stop_bits {other:?} (expected 1/2)")),
}
}
pub fn parse_parity(raw: &str) -> Result<Parity, String> {
match raw.to_lowercase().as_str() {
"none" => Ok(Parity::None),
"odd" => Ok(Parity::Odd),
"even" => Ok(Parity::Even),
other => Err(format!("Invalid parity {other:?} (expected none/odd/even)")),
}
}
pub fn parse_flow_control(raw: &str) -> Result<FlowControl, String> {
match raw.to_lowercase().as_str() {
"none" => Ok(FlowControl::None),
"software" => Ok(FlowControl::Software),
"hardware" => Ok(FlowControl::Hardware),
other => Err(format!(
"Invalid flow_control {other:?} (expected none/software/hardware)"
)),
}
}
pub fn log_tool_err<E: std::fmt::Display>(op: &str, context: &str, err: E) -> String {
error!("{op} failed: {err}");
format!("{context} - {err}")
}
#[cfg(test)]
mod tests {
use super::*;
use crate::flex_deserialize::FlexibleU32;
use tokio::io::AsyncWriteExt;
use crate::serial::test_support::loopback_connection;
#[test]
fn open_args_parsed_strictly() {
let args = OpenArgs {
port: "/dev/ttyUSB0".into(),
baud_rate: FlexibleU32(115200),
data_bits: "8".into(),
stop_bits: "1".into(),
parity: "none".into(),
flow_control: "none".into(),
};
let config = parse_open_args(args).unwrap();
assert_eq!(config.port, "/dev/ttyUSB0");
assert_eq!(config.baud_rate, 115200);
}
#[test]
fn open_args_reject_invalid_data_bits() {
let args = OpenArgs {
port: "X".into(),
baud_rate: FlexibleU32(9600),
data_bits: "9".into(),
stop_bits: "1".into(),
parity: "none".into(),
flow_control: "none".into(),
};
let err = parse_open_args(args).unwrap_err();
assert!(err.contains("data_bits"));
}
#[test]
fn open_args_reject_invalid_parity() {
assert!(parse_parity("weird").is_err());
assert!(parse_parity("none").is_ok());
assert!(parse_parity("Even").is_ok());
}
#[test]
fn parse_encoding_rejects_garbage() {
assert!(parse_encoding("rot13").is_err());
assert!(parse_encoding("utf-8").is_ok());
}
#[test]
fn build_read_result_timeout_returns_err() {
let outcome = ReadOutcome {
bytes: Vec::new(),
timed_out: true,
elapsed_ms: 250,
};
match build_read_result(outcome, "abc".into(), Encoding::Utf8, Some(250)) {
Err(err) => {
assert!(err.contains("timed out"));
assert!(err.contains("250ms"));
}
Ok(_) => panic!("timeout must return Err"),
}
}
#[test]
fn build_read_result_timeout_uses_default() {
let outcome = ReadOutcome {
bytes: Vec::new(),
timed_out: true,
elapsed_ms: DEFAULT_READ_TIMEOUT_MS,
};
match build_read_result(outcome, "abc".into(), Encoding::Hex, None) {
Err(err) => {
assert!(err.contains("timed out"));
assert!(err.contains(&DEFAULT_READ_TIMEOUT_MS.to_string()));
}
Ok(_) => panic!("timeout must return Err"),
}
}
#[test]
fn build_read_result_data_branch_encodes_hex() {
let outcome = ReadOutcome {
bytes: b"Hi".to_vec(),
timed_out: false,
elapsed_ms: 42,
};
let Json(result) = build_read_result(outcome, "abc".into(), Encoding::Hex, Some(500))
.expect("data result must build");
assert_eq!(result.bytes_read, 2);
assert_eq!(result.encoding, "hex");
assert_eq!(result.data, "48 69");
assert_eq!(result.elapsed_ms, 42);
}
#[test]
fn find_subslice_locates_pattern() {
assert_eq!(find_subslice(b"hello OK> world", b"OK>"), Some(6));
assert_eq!(find_subslice(b"OK>at-start", b"OK>"), Some(0));
assert_eq!(find_subslice(b"trailing OK>", b"OK>"), Some(9));
}
#[test]
fn find_subslice_missing_returns_none() {
assert_eq!(find_subslice(b"hello world", b"OK>"), None);
assert_eq!(find_subslice(b"", b"x"), None);
}
#[test]
fn find_subslice_empty_needle_returns_none() {
assert_eq!(find_subslice(b"hello", b""), None);
}
#[test]
fn find_subslice_needle_longer_than_haystack() {
assert_eq!(find_subslice(b"hi", b"hello"), None);
}
#[tokio::test]
async fn read_until_pattern_matches_when_pattern_arrives() {
let (conn, mut peer) = loopback_connection("test");
let writer = tokio::spawn(async move {
peer.write_all(b"junk before OK> and tail").await.unwrap();
});
let ct = tokio_util::sync::CancellationToken::new();
let outcome = read_until_pattern(&conn, b"OK>", 1_000, 1024, &ct, None, None)
.await
.unwrap();
writer.await.unwrap();
assert_eq!(outcome.match_index, Some(12));
assert!(!outcome.timed_out);
assert!(outcome.bytes.starts_with(b"junk before OK>"));
}
#[tokio::test]
async fn read_until_pattern_times_out_with_no_match() {
let (conn, mut peer) = loopback_connection("test");
peer.write_all(b"only noise here").await.unwrap();
let ct = tokio_util::sync::CancellationToken::new();
let outcome = read_until_pattern(&conn, b"OK>", 60, 1024, &ct, None, None)
.await
.unwrap();
assert!(outcome.timed_out);
assert!(outcome.match_index.is_none());
assert!(outcome.bytes.windows(3).all(|w| w != b"OK>"));
}
#[tokio::test]
async fn read_until_pattern_stops_at_max_bytes() {
let (conn, mut peer) = loopback_connection("test");
let blob = vec![b'.'; 600];
peer.write_all(&blob).await.unwrap();
let ct = tokio_util::sync::CancellationToken::new();
let outcome = read_until_pattern(&conn, b"OK>", 1_000, 256, &ct, None, None)
.await
.unwrap();
assert!(!outcome.timed_out);
assert!(outcome.match_index.is_none());
assert_eq!(outcome.bytes.len(), 256);
}
#[test]
fn clamp_or_err_rejects_oversized_values() {
assert!(clamp_or_err("test.max_bytes", 1024 * 1024, MAX_READ_BYTES).is_ok());
assert!(clamp_or_err("test.max_bytes", 1024 * 1024 + 1, MAX_READ_BYTES).is_err());
assert!(clamp_or_err("test.max_bytes", usize::MAX, MAX_WRITE_BYTES).is_err());
}
#[test]
fn require_min_or_err_rejects_undersized_values() {
assert!(require_min_or_err("test.max_bytes", 1, MIN_READ_BYTES).is_ok());
assert!(require_min_or_err("test.max_bytes", 0, MIN_READ_BYTES).is_err());
}
#[test]
fn clamp_timeout_or_err_rejects_oversized_timeout() {
assert!(clamp_timeout_or_err("test.timeout_ms", 1000, MAX_TIMEOUT_MS).is_ok());
assert!(
clamp_timeout_or_err("test.timeout_ms", MAX_TIMEOUT_MS + 1, MAX_TIMEOUT_MS).is_err()
);
}
#[test]
fn clamp_poll_interval_or_err_rejects_undersized_interval() {
assert!(clamp_poll_interval_or_err("test.poll_ms", 10, MIN_POLL_INTERVAL_MS).is_ok());
assert!(clamp_poll_interval_or_err("test.poll_ms", 9, MIN_POLL_INTERVAL_MS).is_err());
assert!(clamp_poll_interval_or_err("test.poll_ms", 0, MIN_POLL_INTERVAL_MS).is_err());
}
}