| 1 | use std::io::{self, Write};
|
| 2 | use std::time::Duration;
|
| 3 |
|
| 4 | use serialport::SerialPortType;
|
| 5 |
|
| 6 | mod usb_direct;
|
| 7 | #[cfg(windows)]
|
| 8 | mod win_spool;
|
| 9 |
|
| 10 | /// Common baud rates for USB POS printers (115200 first — many modern devices).
|
| 11 | pub const BAUD_RATES: [u32; 6] = [115200, 9600, 19200, 38400, 57600, 4800];
|
| 12 |
|
| 13 | #[derive(Debug, Clone, PartialEq, Eq)]
|
| 14 | pub enum PrinterTarget {
|
| 15 | Serial(String),
|
| 16 | UsbDirect {
|
| 17 | vid: u16,
|
| 18 | pid: u16,
|
| 19 | bus: u8,
|
| 20 | address: u8,
|
| 21 | },
|
| 22 | WinSpooler(String),
|
| 23 | }
|
| 24 |
|
| 25 | #[derive(Debug, Clone, PartialEq, Eq)]
|
| 26 | pub struct PrinterDevice {
|
| 27 | pub id: String,
|
| 28 | pub display_name: String,
|
| 29 | pub target: PrinterTarget,
|
| 30 | }
|
| 31 |
|
| 32 | #[derive(Debug)]
|
| 33 | pub enum PrintError {
|
| 34 | NotFound,
|
| 35 | Open(String),
|
| 36 | Write(String),
|
| 37 | Serial(serialport::Error),
|
| 38 | }
|
| 39 |
|
| 40 | impl From<serialport::Error> for PrintError {
|
| 41 | fn from(value: serialport::Error) -> Self {
|
| 42 | Self::Serial(value)
|
| 43 | }
|
| 44 | }
|
| 45 |
|
| 46 | pub trait PrinterTransport {
|
| 47 | fn write_all(&mut self, data: &[u8]) -> io::Result<()>;
|
| 48 | fn flush(&mut self) -> io::Result<()>;
|
| 49 | }
|
| 50 |
|
| 51 | pub struct SerialTransport {
|
| 52 | port: Box<dyn serialport::SerialPort>,
|
| 53 | pub baud_rate: u32,
|
| 54 | }
|
| 55 |
|
| 56 | impl SerialTransport {
|
| 57 | pub fn open(port_name: &str) -> Result<Self, PrintError> {
|
| 58 | let mut last_err = String::from("no baud rate succeeded");
|
| 59 | for &baud in &BAUD_RATES {
|
| 60 | match serialport::new(port_name, baud)
|
| 61 | .timeout(Duration::from_millis(2000))
|
| 62 | .open()
|
| 63 | {
|
| 64 | Ok(port) => {
|
| 65 | return Ok(Self { port, baud_rate: baud });
|
| 66 | }
|
| 67 | Err(e) => last_err = format!("{baud} baud: {e}"),
|
| 68 | }
|
| 69 | }
|
| 70 | Err(PrintError::Open(last_err))
|
| 71 | }
|
| 72 | }
|
| 73 |
|
| 74 | impl PrinterTransport for SerialTransport {
|
| 75 | fn write_all(&mut self, data: &[u8]) -> io::Result<()> {
|
| 76 | self.port.write_all(data)
|
| 77 | }
|
| 78 |
|
| 79 | fn flush(&mut self) -> io::Result<()> {
|
| 80 | self.port.flush()
|
| 81 | }
|
| 82 | }
|
| 83 |
|
| 84 | /// List POS printers: USB printer-class devices, Windows spooler queues, then serial ports.
|
| 85 | pub fn list_printers() -> Result<Vec<PrinterDevice>, PrintError> {
|
| 86 | let mut devices = usb_direct::list_usb_printer_devices();
|
| 87 |
|
| 88 | #[cfg(windows)]
|
| 89 | devices.extend(win_spool::list_windows_spooler_printers());
|
| 90 |
|
| 91 | devices.extend(list_serial_devices()?);
|
| 92 | Ok(devices)
|
| 93 | }
|
| 94 |
|
| 95 | pub fn list_usb_serial_printers() -> Result<Vec<PrinterDevice>, serialport::Error> {
|
| 96 | list_serial_devices()
|
| 97 | }
|
| 98 |
|
| 99 | fn list_serial_devices() -> Result<Vec<PrinterDevice>, serialport::Error> {
|
| 100 | let mut devices = Vec::new();
|
| 101 | for port in serialport::available_ports()? {
|
| 102 | let label = match &port.port_type {
|
| 103 | SerialPortType::UsbPort(info) => {
|
| 104 | let product = info
|
| 105 | .product
|
| 106 | .as_deref()
|
| 107 | .or(info.serial_number.as_deref())
|
| 108 | .unwrap_or("USB device");
|
| 109 | format!(
|
| 110 | "{} — {product} (serial {}:{})",
|
| 111 | port.port_name,
|
| 112 | fmt_vid_pid(info.vid),
|
| 113 | fmt_vid_pid(info.pid)
|
| 114 | )
|
| 115 | }
|
| 116 | SerialPortType::BluetoothPort => format!("{} — Bluetooth", port.port_name),
|
| 117 | SerialPortType::PciPort => format!("{} — PCI", port.port_name),
|
| 118 | SerialPortType::Unknown => format!("{} — Serial", port.port_name),
|
| 119 | };
|
| 120 | devices.push(PrinterDevice {
|
| 121 | id: format!("serial:{}", port.port_name),
|
| 122 | display_name: label,
|
| 123 | target: PrinterTarget::Serial(port.port_name.clone()),
|
| 124 | });
|
| 125 | }
|
| 126 | devices.sort_by(|a, b| a.display_name.cmp(&b.display_name));
|
| 127 | Ok(devices)
|
| 128 | }
|
| 129 |
|
| 130 | pub fn open_printer(target: &PrinterTarget) -> Result<Box<dyn PrinterTransport>, PrintError> {
|
| 131 | match target {
|
| 132 | PrinterTarget::Serial(port) => Ok(Box::new(SerialTransport::open(port)?)),
|
| 133 | PrinterTarget::UsbDirect {
|
| 134 | vid,
|
| 135 | pid,
|
| 136 | bus,
|
| 137 | address,
|
| 138 | } => Ok(Box::new(usb_direct::UsbDirectTransport::open(
|
| 139 | *vid, *pid, *bus, *address,
|
| 140 | )?)),
|
| 141 | #[cfg(windows)]
|
| 142 | PrinterTarget::WinSpooler(name) => Ok(Box::new(win_spool::WinSpoolerTransport::new(
|
| 143 | name.clone(),
|
| 144 | ))),
|
| 145 | #[cfg(not(windows))]
|
| 146 | PrinterTarget::WinSpooler(_) => Err(PrintError::Open(
|
| 147 | "Windows spooler printing is only available on Windows".into(),
|
| 148 | )),
|
| 149 | }
|
| 150 | }
|
| 151 |
|
| 152 | /// Open by manual name: tries serial/COM first, then Windows spooler queue name.
|
| 153 | pub fn open_printer_by_name(name: &str) -> Result<Box<dyn PrinterTransport>, PrintError> {
|
| 154 | let name = name.trim();
|
| 155 | if name.is_empty() {
|
| 156 | return Err(PrintError::NotFound);
|
| 157 | }
|
| 158 |
|
| 159 | if let Ok(transport) = SerialTransport::open(name) {
|
| 160 | return Ok(Box::new(transport));
|
| 161 | }
|
| 162 |
|
| 163 | #[cfg(windows)]
|
| 164 | {
|
| 165 | return Ok(Box::new(win_spool::WinSpoolerTransport::new(
|
| 166 | name.to_string(),
|
| 167 | )));
|
| 168 | }
|
| 169 |
|
| 170 | #[cfg(not(windows))]
|
| 171 | Err(PrintError::Open(format!(
|
| 172 | "could not open serial port '{name}'"
|
| 173 | )))
|
| 174 | }
|
| 175 |
|
| 176 | fn fmt_vid_pid(v: u16) -> String {
|
| 177 | format!("{v:04x}")
|
| 178 | }
|
| 179 |
|
| 180 | impl PrinterTransport for Box<dyn PrinterTransport> {
|
| 181 | fn write_all(&mut self, data: &[u8]) -> io::Result<()> {
|
| 182 | (**self).write_all(data)
|
| 183 | }
|
| 184 |
|
| 185 | fn flush(&mut self) -> io::Result<()> {
|
| 186 | (**self).flush()
|
| 187 | }
|
| 188 | }
|
| 189 |
|
| 190 | pub fn print_bytes<T: PrinterTransport + ?Sized>(transport: &mut T, data: &[u8]) -> Result<(), PrintError> {
|
| 191 | transport
|
| 192 | .write_all(data)
|
| 193 | .map_err(|e| PrintError::Write(e.to_string()))?;
|
| 194 | transport
|
| 195 | .flush()
|
| 196 | .map_err(|e| PrintError::Write(e.to_string()))?;
|
| 197 | Ok(())
|
| 198 | }
|
| 199 |
|
| 200 | pub struct MockTransport {
|
| 201 | pub written: Vec<u8>,
|
| 202 | }
|
| 203 |
|
| 204 | impl MockTransport {
|
| 205 | pub fn new() -> Self {
|
| 206 | Self { written: Vec::new() }
|
| 207 | }
|
| 208 | }
|
| 209 |
|
| 210 | impl Default for MockTransport {
|
| 211 | fn default() -> Self {
|
| 212 | Self::new()
|
| 213 | }
|
| 214 | }
|
| 215 |
|
| 216 | impl PrinterTransport for MockTransport {
|
| 217 | fn write_all(&mut self, data: &[u8]) -> io::Result<()> {
|
| 218 | self.written.extend_from_slice(data);
|
| 219 | Ok(())
|
| 220 | }
|
| 221 |
|
| 222 | fn flush(&mut self) -> io::Result<()> {
|
| 223 | Ok(())
|
| 224 | }
|
| 225 | }
|
| 226 |
|
| 227 | #[cfg(test)]
|
| 228 | mod tests {
|
| 229 | use super::*;
|
| 230 |
|
| 231 | #[test]
|
| 232 | fn mock_transport_records_bytes() {
|
| 233 | let mut mock = MockTransport::new();
|
| 234 | print_bytes(&mut mock, &[1, 2, 3]).unwrap();
|
| 235 | assert_eq!(mock.written, vec![1, 2, 3]);
|
| 236 | }
|
| 237 |
|
| 238 | #[test]
|
| 239 | fn list_printers_returns_vec() {
|
| 240 | let list = list_printers();
|
| 241 | assert!(list.is_ok());
|
| 242 | }
|
| 243 | }
|