Skip to main content

marlin_binary_transfer/adapters/
serialport.rs

1//! Convenience integration with the [`serialport`] crate.
2//!
3//! [`serialport::SerialPort`] already implements [`std::io::Read`] +
4//! [`std::io::Write`], so the [blocking adapter](crate::adapters::blocking)
5//! works on it directly. This module provides a tiny `open` helper that
6//! configures sensible defaults for talking to Marlin in binary mode.
7
8use std::time::Duration;
9
10use ::serialport::{SerialPort, SerialPortBuilder};
11
12/// Open a serial port with defaults suitable for Marlin BFT:
13///
14/// - 8N1
15/// - read timeout 100 ms (so the host can pump retransmits without
16///   hanging in `read`)
17/// - DTR/RTS not asserted explicitly — the OS-default behaviour applies
18pub fn open(path: &str, baud_rate: u32) -> std::io::Result<Box<dyn SerialPort>> {
19    builder(path, baud_rate).open().map_err(map_err)
20}
21
22/// Return a [`SerialPortBuilder`] preconfigured with the same defaults
23/// as [`open`], but unopened, so the caller can apply further tweaks
24/// before calling `.open()`.
25pub fn builder(path: &str, baud_rate: u32) -> SerialPortBuilder {
26    ::serialport::new(path, baud_rate).timeout(Duration::from_millis(100))
27}
28
29fn map_err(e: ::serialport::Error) -> std::io::Error {
30    std::io::Error::other(e.to_string())
31}