| 1 | use std::io::{self, Write};
|
| 2 | use std::time::Duration;
|
| 3 |
|
| 4 | use serialport::SerialPortType;
|
| 5 |
|
| 6 | #[derive(Debug, Clone, PartialEq, Eq)]
|
| 7 | pub struct PrinterDevice {
|
| 8 | pub id: String,
|
| 9 | pub display_name: String,
|
| 10 | pub port_name: String,
|
| 11 | }
|
| 12 |
|
| 13 | #[derive(Debug)]
|
| 14 | pub enum PrintError {
|
| 15 | NotFound,
|
| 16 | Open(String),
|
| 17 | Write(String),
|
| 18 | Serial(serialport::Error),
|
| 19 | }
|
| 20 |
|
| 21 | pub trait PrinterTransport {
|
| 22 | fn write_all(&mut self, data: &[u8]) -> io::Result<()>;
|
| 23 | fn flush(&mut self) -> io::Result<()>;
|
| 24 | }
|
| 25 |
|
| 26 | pub struct SerialTransport {
|
| 27 | port: Box<dyn serialport::SerialPort>,
|
| 28 | }
|
| 29 |
|
| 30 | impl SerialTransport {
|
| 31 | pub fn open(port_name: &str) -> Result<Self, PrintError> {
|
| 32 | let port = serialport::new(port_name, 9600)
|
| 33 | .timeout(Duration::from_millis(2000))
|
| 34 | .open()
|
| 35 | .map_err(|e| PrintError::Open(e.to_string()))?;
|
| 36 | Ok(Self { port })
|
| 37 | }
|
| 38 | }
|
| 39 |
|
| 40 | impl PrinterTransport for SerialTransport {
|
| 41 | fn write_all(&mut self, data: &[u8]) -> io::Result<()> {
|
| 42 | self.port.write_all(data)
|
| 43 | }
|
| 44 |
|
| 45 | fn flush(&mut self) -> io::Result<()> {
|
| 46 | self.port.flush()
|
| 47 | }
|
| 48 | }
|
| 49 |
|
| 50 | pub fn list_usb_serial_printers() -> Result<Vec<PrinterDevice>, serialport::Error> {
|
| 51 | let mut devices = Vec::new();
|
| 52 | for port in serialport::available_ports()? {
|
| 53 | let label = match &port.port_type {
|
| 54 | SerialPortType::UsbPort(info) => format!(
|
| 55 | "{} — USB {}:{}",
|
| 56 | port.port_name,
|
| 57 | fmt_vid_pid(info.vid),
|
| 58 | fmt_vid_pid(info.pid)
|
| 59 | ),
|
| 60 | _ => format!("{} — Serial", port.port_name),
|
| 61 | };
|
| 62 | devices.push(PrinterDevice {
|
| 63 | id: format!("serial:{}", port.port_name),
|
| 64 | display_name: label,
|
| 65 | port_name: port.port_name.clone(),
|
| 66 | });
|
| 67 | }
|
| 68 | devices.sort_by(|a, b| a.display_name.cmp(&b.display_name));
|
| 69 | Ok(devices)
|
| 70 | }
|
| 71 |
|
| 72 | fn fmt_vid_pid(v: u16) -> String {
|
| 73 | format!("{v:04x}")
|
| 74 | }
|
| 75 |
|
| 76 | pub fn print_bytes<T: PrinterTransport>(transport: &mut T, data: &[u8]) -> Result<(), PrintError> {
|
| 77 | transport
|
| 78 | .write_all(data)
|
| 79 | .map_err(|e| PrintError::Write(e.to_string()))?;
|
| 80 | transport
|
| 81 | .flush()
|
| 82 | .map_err(|e| PrintError::Write(e.to_string()))?;
|
| 83 | Ok(())
|
| 84 | }
|
| 85 |
|
| 86 | pub struct MockTransport {
|
| 87 | pub written: Vec<u8>,
|
| 88 | }
|
| 89 |
|
| 90 | impl MockTransport {
|
| 91 | pub fn new() -> Self {
|
| 92 | Self { written: Vec::new() }
|
| 93 | }
|
| 94 | }
|
| 95 |
|
| 96 | impl Default for MockTransport {
|
| 97 | fn default() -> Self {
|
| 98 | Self::new()
|
| 99 | }
|
| 100 | }
|
| 101 |
|
| 102 | impl PrinterTransport for MockTransport {
|
| 103 | fn write_all(&mut self, data: &[u8]) -> io::Result<()> {
|
| 104 | self.written.extend_from_slice(data);
|
| 105 | Ok(())
|
| 106 | }
|
| 107 |
|
| 108 | fn flush(&mut self) -> io::Result<()> {
|
| 109 | Ok(())
|
| 110 | }
|
| 111 | }
|
| 112 |
|
| 113 | #[cfg(test)]
|
| 114 | mod tests {
|
| 115 | use super::*;
|
| 116 |
|
| 117 | #[test]
|
| 118 | fn mock_transport_records_bytes() {
|
| 119 | let mut mock = MockTransport::new();
|
| 120 | print_bytes(&mut mock, &[1, 2, 3]).unwrap();
|
| 121 | assert_eq!(mock.written, vec![1, 2, 3]);
|
| 122 | }
|
| 123 |
|
| 124 | #[test]
|
| 125 | fn list_printers_returns_vec() {
|
| 126 | // May be empty on CI; must not error.
|
| 127 | let list = list_usb_serial_printers();
|
| 128 | assert!(list.is_ok());
|
| 129 | }
|
| 130 | }
|