| 1 | use std::io::{self, Write};
|
| 2 | use std::time::Duration;
|
| 3 |
|
| 4 | use serialport::{SerialPortInfo, 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, Windows spooler, then USB-serial and
|
| 85 | /// OS-paired Classic Bluetooth SPP ports.
|
| 86 | pub fn list_printers() -> Result<Vec<PrinterDevice>, PrintError> {
|
| 87 | let mut devices = usb_direct::list_usb_printer_devices();
|
| 88 |
|
| 89 | #[cfg(windows)]
|
| 90 | devices.extend(win_spool::list_windows_spooler_printers());
|
| 91 |
|
| 92 | devices.extend(list_serial_devices()?);
|
| 93 | Ok(devices)
|
| 94 | }
|
| 95 |
|
| 96 | pub fn list_usb_serial_printers() -> Result<Vec<PrinterDevice>, serialport::Error> {
|
| 97 | list_serial_devices()
|
| 98 | }
|
| 99 |
|
| 100 | fn list_serial_devices() -> Result<Vec<PrinterDevice>, serialport::Error> {
|
| 101 | let mut devices = Vec::new();
|
| 102 | for port in serialport::available_ports()? {
|
| 103 | if let Some(device) = serial_device_from_port(&port) {
|
| 104 | devices.push(device);
|
| 105 | }
|
| 106 | }
|
| 107 | devices.sort_by(|a, b| a.display_name.cmp(&b.display_name));
|
| 108 | Ok(devices)
|
| 109 | }
|
| 110 |
|
| 111 | /// USB-serial or OS-paired Classic Bluetooth SPP. Skips empty PCI/`ttyS*` noise.
|
| 112 | pub fn is_serial_printer_candidate(port_type: &SerialPortType) -> bool {
|
| 113 | is_usb_serial_candidate(port_type) || is_bluetooth_serial_candidate(port_type)
|
| 114 | }
|
| 115 |
|
| 116 | /// True when a serial port type is a connected USB device (possible POS printer).
|
| 117 | pub fn is_usb_serial_candidate(port_type: &SerialPortType) -> bool {
|
| 118 | matches!(port_type, SerialPortType::UsbPort(_))
|
| 119 | }
|
| 120 |
|
| 121 | /// True when `serialport` reports a Classic Bluetooth SPP / RFCOMM port.
|
| 122 | pub fn is_bluetooth_serial_candidate(port_type: &SerialPortType) -> bool {
|
| 123 | matches!(port_type, SerialPortType::BluetoothPort)
|
| 124 | }
|
| 125 |
|
| 126 | /// Linux RFCOMM node (`/dev/rfcomm0`) even if enumeration typed it as Unknown.
|
| 127 | fn is_rfcomm_device_name(port_name: &str) -> bool {
|
| 128 | let base = port_name.rsplit(['/', '\\']).next().unwrap_or(port_name);
|
| 129 | base.len() >= 6 && base[..6].eq_ignore_ascii_case("rfcomm")
|
| 130 | }
|
| 131 |
|
| 132 | /// Map an enumerated serial port to a printer entry, or skip PCI/`ttyS*` noise.
|
| 133 | pub fn serial_device_from_port(port: &SerialPortInfo) -> Option<PrinterDevice> {
|
| 134 | if !is_serial_printer_candidate(&port.port_type) && !is_rfcomm_device_name(&port.port_name) {
|
| 135 | return None;
|
| 136 | }
|
| 137 | Some(PrinterDevice {
|
| 138 | id: format!("serial:{}", port.port_name),
|
| 139 | display_name: serial_port_display_name(port),
|
| 140 | target: PrinterTarget::Serial(port.port_name.clone()),
|
| 141 | })
|
| 142 | }
|
| 143 |
|
| 144 | fn serial_port_display_name(port: &SerialPortInfo) -> String {
|
| 145 | match &port.port_type {
|
| 146 | SerialPortType::UsbPort(info) => {
|
| 147 | let product = info
|
| 148 | .product
|
| 149 | .as_deref()
|
| 150 | .or(info.serial_number.as_deref())
|
| 151 | .unwrap_or("USB device");
|
| 152 | format!(
|
| 153 | "{} — {product} (serial {}:{})",
|
| 154 | port.port_name,
|
| 155 | fmt_vid_pid(info.vid),
|
| 156 | fmt_vid_pid(info.pid)
|
| 157 | )
|
| 158 | }
|
| 159 | SerialPortType::BluetoothPort => format!("{} — Bluetooth", port.port_name),
|
| 160 | _ if is_rfcomm_device_name(&port.port_name) => {
|
| 161 | format!("{} — Bluetooth", port.port_name)
|
| 162 | }
|
| 163 | _ => format!("{} — serial", port.port_name),
|
| 164 | }
|
| 165 | }
|
| 166 |
|
| 167 | pub fn open_printer(target: &PrinterTarget) -> Result<Box<dyn PrinterTransport>, PrintError> {
|
| 168 | match target {
|
| 169 | PrinterTarget::Serial(port) => Ok(Box::new(SerialTransport::open(port)?)),
|
| 170 | PrinterTarget::UsbDirect {
|
| 171 | vid,
|
| 172 | pid,
|
| 173 | bus,
|
| 174 | address,
|
| 175 | } => Ok(Box::new(usb_direct::UsbDirectTransport::open(
|
| 176 | *vid, *pid, *bus, *address,
|
| 177 | )?)),
|
| 178 | #[cfg(windows)]
|
| 179 | PrinterTarget::WinSpooler(name) => Ok(Box::new(win_spool::WinSpoolerTransport::new(
|
| 180 | name.clone(),
|
| 181 | ))),
|
| 182 | #[cfg(not(windows))]
|
| 183 | PrinterTarget::WinSpooler(_) => Err(PrintError::Open(
|
| 184 | "Windows spooler printing is only available on Windows".into(),
|
| 185 | )),
|
| 186 | }
|
| 187 | }
|
| 188 |
|
| 189 | /// Match a printer from `list_printers()` by `"auto"`, device `id`, preference key (`usb:vid:pid`), or `display_name`.
|
| 190 | pub fn find_matching_printer<'a>(
|
| 191 | printers: &'a [PrinterDevice],
|
| 192 | name: &str,
|
| 193 | ) -> Option<&'a PrinterDevice> {
|
| 194 | let name = name.trim();
|
| 195 | if name.is_empty() {
|
| 196 | return None;
|
| 197 | }
|
| 198 | if name.eq_ignore_ascii_case("auto") {
|
| 199 | return printers.first();
|
| 200 | }
|
| 201 | printers.iter().find(|p| {
|
| 202 | p.id == name || printer_preference_key(&p.target) == name || p.display_name == name
|
| 203 | })
|
| 204 | }
|
| 205 |
|
| 206 | /// Open by manual name: tries discovered printers (`id`, `usb:vid:pid`, `"auto"`), then serial/COM, then Windows spooler queue name.
|
| 207 | pub fn open_printer_by_name(name: &str) -> Result<Box<dyn PrinterTransport>, PrintError> {
|
| 208 | let name = name.trim();
|
| 209 | if name.is_empty() {
|
| 210 | return Err(PrintError::NotFound);
|
| 211 | }
|
| 212 |
|
| 213 | if let Ok(printers) = list_printers() {
|
| 214 | if let Some(matched) = find_matching_printer(&printers, name) {
|
| 215 | return open_printer(&matched.target);
|
| 216 | }
|
| 217 | }
|
| 218 |
|
| 219 | let serial_name = name.strip_prefix("serial:").unwrap_or(name);
|
| 220 | if let Ok(transport) = SerialTransport::open(serial_name) {
|
| 221 | return Ok(Box::new(transport));
|
| 222 | }
|
| 223 |
|
| 224 | #[cfg(windows)]
|
| 225 | {
|
| 226 | return Ok(Box::new(win_spool::WinSpoolerTransport::new(
|
| 227 | name.to_string(),
|
| 228 | )));
|
| 229 | }
|
| 230 |
|
| 231 | #[cfg(not(windows))]
|
| 232 | Err(PrintError::Open(format!(
|
| 233 | "could not open serial port '{name}'"
|
| 234 | )))
|
| 235 | }
|
| 236 |
|
| 237 | fn fmt_vid_pid(v: u16) -> String {
|
| 238 | format!("{v:04x}")
|
| 239 | }
|
| 240 |
|
| 241 | impl PrinterTransport for Box<dyn PrinterTransport> {
|
| 242 | fn write_all(&mut self, data: &[u8]) -> io::Result<()> {
|
| 243 | (**self).write_all(data)
|
| 244 | }
|
| 245 |
|
| 246 | fn flush(&mut self) -> io::Result<()> {
|
| 247 | (**self).flush()
|
| 248 | }
|
| 249 | }
|
| 250 |
|
| 251 | pub fn print_bytes<T: PrinterTransport + ?Sized>(transport: &mut T, data: &[u8]) -> Result<(), PrintError> {
|
| 252 | transport
|
| 253 | .write_all(data)
|
| 254 | .map_err(|e| PrintError::Write(e.to_string()))?;
|
| 255 | transport
|
| 256 | .flush()
|
| 257 | .map_err(|e| PrintError::Write(e.to_string()))?;
|
| 258 | Ok(())
|
| 259 | }
|
| 260 |
|
| 261 | /// Stable key for remembering the last successful printer across reconnects.
|
| 262 | /// USB uses vid:pid only (bus/address change when replugged).
|
| 263 | pub fn printer_preference_key(target: &PrinterTarget) -> String {
|
| 264 | match target {
|
| 265 | PrinterTarget::Serial(port) => format!("serial:{port}"),
|
| 266 | PrinterTarget::WinSpooler(name) => format!("winspool:{name}"),
|
| 267 | PrinterTarget::UsbDirect { vid, pid, .. } => {
|
| 268 | format!("usb:{vid:04x}:{pid:04x}")
|
| 269 | }
|
| 270 | }
|
| 271 | }
|
| 272 |
|
| 273 | pub fn manual_printer_preference_key(name: &str) -> String {
|
| 274 | format!("manual:{}", name.trim())
|
| 275 | }
|
| 276 |
|
| 277 | /// Index of a discovered printer matching a stored preference key, if still connected.
|
| 278 | pub fn find_preferred_printer_index(printers: &[PrinterDevice], key: &str) -> Option<usize> {
|
| 279 | let key = key.trim();
|
| 280 | if key.is_empty() || key.starts_with("manual:") {
|
| 281 | return None;
|
| 282 | }
|
| 283 | printers
|
| 284 | .iter()
|
| 285 | .position(|p| printer_preference_key(&p.target) == key)
|
| 286 | }
|
| 287 |
|
| 288 | pub struct MockTransport {
|
| 289 | pub written: Vec<u8>,
|
| 290 | }
|
| 291 |
|
| 292 | impl MockTransport {
|
| 293 | pub fn new() -> Self {
|
| 294 | Self { written: Vec::new() }
|
| 295 | }
|
| 296 | }
|
| 297 |
|
| 298 | impl Default for MockTransport {
|
| 299 | fn default() -> Self {
|
| 300 | Self::new()
|
| 301 | }
|
| 302 | }
|
| 303 |
|
| 304 | impl PrinterTransport for MockTransport {
|
| 305 | fn write_all(&mut self, data: &[u8]) -> io::Result<()> {
|
| 306 | self.written.extend_from_slice(data);
|
| 307 | Ok(())
|
| 308 | }
|
| 309 |
|
| 310 | fn flush(&mut self) -> io::Result<()> {
|
| 311 | Ok(())
|
| 312 | }
|
| 313 | }
|
| 314 |
|
| 315 | #[cfg(test)]
|
| 316 | mod tests {
|
| 317 | use super::*;
|
| 318 | use serialport::{SerialPortInfo, UsbPortInfo};
|
| 319 |
|
| 320 | #[test]
|
| 321 | fn mock_transport_records_bytes() {
|
| 322 | let mut mock = MockTransport::new();
|
| 323 | print_bytes(&mut mock, &[1, 2, 3]).unwrap();
|
| 324 | assert_eq!(mock.written, vec![1, 2, 3]);
|
| 325 | }
|
| 326 |
|
| 327 | #[test]
|
| 328 | fn list_printers_returns_vec() {
|
| 329 | let list = list_printers();
|
| 330 | assert!(list.is_ok());
|
| 331 | }
|
| 332 |
|
| 333 | fn sample_usb_port_type() -> SerialPortType {
|
| 334 | SerialPortType::UsbPort(UsbPortInfo {
|
| 335 | vid: 0x0416,
|
| 336 | pid: 0x5011,
|
| 337 | serial_number: None,
|
| 338 | manufacturer: None,
|
| 339 | product: Some("POS-58".into()),
|
| 340 | })
|
| 341 | }
|
| 342 |
|
| 343 | #[test]
|
| 344 | fn pci_and_unknown_serial_ports_are_not_candidates() {
|
| 345 | assert!(!is_serial_printer_candidate(&SerialPortType::PciPort));
|
| 346 | assert!(!is_serial_printer_candidate(&SerialPortType::Unknown));
|
| 347 | assert!(!is_usb_serial_candidate(&SerialPortType::BluetoothPort));
|
| 348 | assert!(!is_usb_serial_candidate(&SerialPortType::PciPort));
|
| 349 | assert!(!is_usb_serial_candidate(&SerialPortType::Unknown));
|
| 350 | }
|
| 351 |
|
| 352 | #[test]
|
| 353 | fn usb_and_bluetooth_serial_ports_are_candidates() {
|
| 354 | let usb = sample_usb_port_type();
|
| 355 | assert!(is_usb_serial_candidate(&usb));
|
| 356 | assert!(is_serial_printer_candidate(&usb));
|
| 357 | assert!(is_bluetooth_serial_candidate(&SerialPortType::BluetoothPort));
|
| 358 | assert!(is_serial_printer_candidate(&SerialPortType::BluetoothPort));
|
| 359 | }
|
| 360 |
|
| 361 | #[test]
|
| 362 | fn bluetooth_serial_device_is_labeled() {
|
| 363 | let port = SerialPortInfo {
|
| 364 | port_name: "COM5".into(),
|
| 365 | port_type: SerialPortType::BluetoothPort,
|
| 366 | };
|
| 367 | let device = serial_device_from_port(&port).expect("bluetooth candidate");
|
| 368 | assert_eq!(device.id, "serial:COM5");
|
| 369 | assert_eq!(device.display_name, "COM5 — Bluetooth");
|
| 370 | assert_eq!(device.target, PrinterTarget::Serial("COM5".into()));
|
| 371 | }
|
| 372 |
|
| 373 | #[test]
|
| 374 | fn linux_rfcomm_is_listed_even_if_type_unknown() {
|
| 375 | let port = SerialPortInfo {
|
| 376 | port_name: "/dev/rfcomm0".into(),
|
| 377 | port_type: SerialPortType::Unknown,
|
| 378 | };
|
| 379 | let device = serial_device_from_port(&port).expect("rfcomm candidate");
|
| 380 | assert_eq!(device.display_name, "/dev/rfcomm0 — Bluetooth");
|
| 381 | assert_eq!(device.target, PrinterTarget::Serial("/dev/rfcomm0".into()));
|
| 382 | }
|
| 383 |
|
| 384 | #[test]
|
| 385 | fn empty_pci_ttys_ports_are_not_listed() {
|
| 386 | let pci = SerialPortInfo {
|
| 387 | port_name: "/dev/ttyS0".into(),
|
| 388 | port_type: SerialPortType::PciPort,
|
| 389 | };
|
| 390 | assert!(serial_device_from_port(&pci).is_none());
|
| 391 | let unknown = SerialPortInfo {
|
| 392 | port_name: "/dev/ttyS1".into(),
|
| 393 | port_type: SerialPortType::Unknown,
|
| 394 | };
|
| 395 | assert!(serial_device_from_port(&unknown).is_none());
|
| 396 | }
|
| 397 |
|
| 398 | #[test]
|
| 399 | fn usb_serial_device_keeps_vid_pid_label() {
|
| 400 | let port = SerialPortInfo {
|
| 401 | port_name: "/dev/ttyUSB0".into(),
|
| 402 | port_type: sample_usb_port_type(),
|
| 403 | };
|
| 404 | let device = serial_device_from_port(&port).expect("usb candidate");
|
| 405 | assert!(device.display_name.contains("POS-58"));
|
| 406 | assert!(device.display_name.contains("0416:5011"));
|
| 407 | assert!(!device.display_name.contains("Bluetooth"));
|
| 408 | }
|
| 409 |
|
| 410 | #[test]
|
| 411 | fn preference_key_ignores_usb_bus_address() {
|
| 412 | let a = PrinterTarget::UsbDirect {
|
| 413 | vid: 0x0416,
|
| 414 | pid: 0x5011,
|
| 415 | bus: 1,
|
| 416 | address: 2,
|
| 417 | };
|
| 418 | let b = PrinterTarget::UsbDirect {
|
| 419 | vid: 0x0416,
|
| 420 | pid: 0x5011,
|
| 421 | bus: 3,
|
| 422 | address: 9,
|
| 423 | };
|
| 424 | assert_eq!(printer_preference_key(&a), printer_preference_key(&b));
|
| 425 | assert_eq!(printer_preference_key(&a), "usb:0416:5011");
|
| 426 | }
|
| 427 |
|
| 428 | #[test]
|
| 429 | fn finds_preferred_printer_by_key() {
|
| 430 | let printers = vec![
|
| 431 | PrinterDevice {
|
| 432 | id: "serial:COM1".into(),
|
| 433 | display_name: "COM1".into(),
|
| 434 | target: PrinterTarget::Serial("COM1".into()),
|
| 435 | },
|
| 436 | PrinterDevice {
|
| 437 | id: "winspool:POS".into(),
|
| 438 | display_name: "POS".into(),
|
| 439 | target: PrinterTarget::WinSpooler("POS".into()),
|
| 440 | },
|
| 441 | ];
|
| 442 | assert_eq!(
|
| 443 | find_preferred_printer_index(&printers, "winspool:POS"),
|
| 444 | Some(1)
|
| 445 | );
|
| 446 | assert_eq!(find_preferred_printer_index(&printers, "serial:COM9"), None);
|
| 447 | assert_eq!(
|
| 448 | find_preferred_printer_index(&printers, "manual:COM3"),
|
| 449 | None
|
| 450 | );
|
| 451 | }
|
| 452 |
|
| 453 | #[test]
|
| 454 | fn matches_discovered_printer_by_id_key_or_auto() {
|
| 455 | let printers = vec![
|
| 456 | PrinterDevice {
|
| 457 | id: "usb:28e9:0289:0:1".into(),
|
| 458 | display_name: "micro-printer — USB 28e9:0289 (direct)".into(),
|
| 459 | target: PrinterTarget::UsbDirect {
|
| 460 | vid: 0x28e9,
|
| 461 | pid: 0x0289,
|
| 462 | bus: 0,
|
| 463 | address: 1,
|
| 464 | },
|
| 465 | },
|
| 466 | PrinterDevice {
|
| 467 | id: "serial:/dev/cu.usbserial-1410".into(),
|
| 468 | display_name: "/dev/cu.usbserial-1410 — POS-58 (serial 0416:5011)".into(),
|
| 469 | target: PrinterTarget::Serial("/dev/cu.usbserial-1410".into()),
|
| 470 | },
|
| 471 | ];
|
| 472 | assert_eq!(
|
| 473 | find_matching_printer(&printers, "auto").map(|p| p.id.as_str()),
|
| 474 | Some("usb:28e9:0289:0:1")
|
| 475 | );
|
| 476 | assert_eq!(
|
| 477 | find_matching_printer(&printers, "usb:28e9:0289:0:1").map(|p| p.id.as_str()),
|
| 478 | Some("usb:28e9:0289:0:1")
|
| 479 | );
|
| 480 | assert_eq!(
|
| 481 | find_matching_printer(&printers, "usb:28e9:0289").map(|p| p.id.as_str()),
|
| 482 | Some("usb:28e9:0289:0:1")
|
| 483 | );
|
| 484 | assert_eq!(
|
| 485 | find_matching_printer(&printers, "serial:/dev/cu.usbserial-1410").map(|p| p.id.as_str()),
|
| 486 | Some("serial:/dev/cu.usbserial-1410")
|
| 487 | );
|
| 488 | assert!(find_matching_printer(&printers, "usb:9999:9999").is_none());
|
| 489 | assert!(find_matching_printer(&[], "auto").is_none());
|
| 490 | }
|
| 491 | }
|