use std::io::{self, Write}; use std::time::Duration; use serialport::SerialPortType; #[derive(Debug, Clone, PartialEq, Eq)] pub struct PrinterDevice { pub id: String, pub display_name: String, pub port_name: String, } #[derive(Debug)] pub enum PrintError { NotFound, Open(String), Write(String), Serial(serialport::Error), } pub trait PrinterTransport { fn write_all(&mut self, data: &[u8]) -> io::Result<()>; fn flush(&mut self) -> io::Result<()>; } pub struct SerialTransport { port: Box, } impl SerialTransport { pub fn open(port_name: &str) -> Result { let port = serialport::new(port_name, 9600) .timeout(Duration::from_millis(2000)) .open() .map_err(|e| PrintError::Open(e.to_string()))?; Ok(Self { port }) } } impl PrinterTransport for SerialTransport { fn write_all(&mut self, data: &[u8]) -> io::Result<()> { self.port.write_all(data) } fn flush(&mut self) -> io::Result<()> { self.port.flush() } } pub fn list_usb_serial_printers() -> Result, serialport::Error> { let mut devices = Vec::new(); for port in serialport::available_ports()? { let label = match &port.port_type { SerialPortType::UsbPort(info) => format!( "{} — USB {}:{}", port.port_name, fmt_vid_pid(info.vid), fmt_vid_pid(info.pid) ), _ => format!("{} — Serial", port.port_name), }; devices.push(PrinterDevice { id: format!("serial:{}", port.port_name), display_name: label, port_name: port.port_name.clone(), }); } devices.sort_by(|a, b| a.display_name.cmp(&b.display_name)); Ok(devices) } fn fmt_vid_pid(v: u16) -> String { format!("{v:04x}") } pub fn print_bytes(transport: &mut T, data: &[u8]) -> Result<(), PrintError> { transport .write_all(data) .map_err(|e| PrintError::Write(e.to_string()))?; transport .flush() .map_err(|e| PrintError::Write(e.to_string()))?; Ok(()) } pub struct MockTransport { pub written: Vec, } impl MockTransport { pub fn new() -> Self { Self { written: Vec::new() } } } impl Default for MockTransport { fn default() -> Self { Self::new() } } impl PrinterTransport for MockTransport { fn write_all(&mut self, data: &[u8]) -> io::Result<()> { self.written.extend_from_slice(data); Ok(()) } fn flush(&mut self) -> io::Result<()> { Ok(()) } } #[cfg(test)] mod tests { use super::*; #[test] fn mock_transport_records_bytes() { let mut mock = MockTransport::new(); print_bytes(&mut mock, &[1, 2, 3]).unwrap(); assert_eq!(mock.written, vec![1, 2, 3]); } #[test] fn list_printers_returns_vec() { // May be empty on CI; must not error. let list = list_usb_serial_printers(); assert!(list.is_ok()); } }