BlueGit

timfa posprint

Files

posprint / src / print / mod.rs

mod.rs

mod.rs 7.3 KiB Download Raw
1use std::io::{self, Write};
2use std::time::Duration;
3
4use serialport::SerialPortType;
5
6mod usb_direct;
7#[cfg(windows)]
8mod win_spool;
9
10/// Common baud rates for USB POS printers (115200 first — many modern devices).
11pub const BAUD_RATES: [u32; 6] = [115200, 9600, 19200, 38400, 57600, 4800];
12
13#[derive(Debug, Clone, PartialEq, Eq)]
14pub 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)]
26pub struct PrinterDevice {
27 pub id: String,
28 pub display_name: String,
29 pub target: PrinterTarget,
30}
31
32#[derive(Debug)]
33pub enum PrintError {
34 NotFound,
35 Open(String),
36 Write(String),
37 Serial(serialport::Error),
38}
39
40impl From<serialport::Error> for PrintError {
41 fn from(value: serialport::Error) -> Self {
42 Self::Serial(value)
43 }
44}
45
46pub trait PrinterTransport {
47 fn write_all(&mut self, data: &[u8]) -> io::Result<()>;
48 fn flush(&mut self) -> io::Result<()>;
49}
50
51pub struct SerialTransport {
52 port: Box<dyn serialport::SerialPort>,
53 pub baud_rate: u32,
54}
55
56impl 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
74impl 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.
85pub 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
95pub fn list_usb_serial_printers() -> Result<Vec<PrinterDevice>, serialport::Error> {
96 list_serial_devices()
97}
98
99fn list_serial_devices() -> Result<Vec<PrinterDevice>, serialport::Error> {
100 let mut devices = Vec::new();
101 for port in serialport::available_ports()? {
102 // Only USB-attached serial devices: Linux often lists dozens of empty
103 // /dev/ttyS* (PCI/Unknown) that are not connected to anything.
104 let SerialPortType::UsbPort(info) = &port.port_type else {
105 continue;
106 };
107 let product = info
108 .product
109 .as_deref()
110 .or(info.serial_number.as_deref())
111 .unwrap_or("USB device");
112 let label = format!(
113 "{} — {product} (serial {}:{})",
114 port.port_name,
115 fmt_vid_pid(info.vid),
116 fmt_vid_pid(info.pid)
117 );
118 devices.push(PrinterDevice {
119 id: format!("serial:{}", port.port_name),
120 display_name: label,
121 target: PrinterTarget::Serial(port.port_name.clone()),
122 });
123 }
124 devices.sort_by(|a, b| a.display_name.cmp(&b.display_name));
125 Ok(devices)
126}
127
128/// True when a serial port type is a connected USB device (possible POS printer).
129pub fn is_usb_serial_candidate(port_type: &SerialPortType) -> bool {
130 matches!(port_type, SerialPortType::UsbPort(_))
131}
132
133pub fn open_printer(target: &PrinterTarget) -> Result<Box<dyn PrinterTransport>, PrintError> {
134 match target {
135 PrinterTarget::Serial(port) => Ok(Box::new(SerialTransport::open(port)?)),
136 PrinterTarget::UsbDirect {
137 vid,
138 pid,
139 bus,
140 address,
141 } => Ok(Box::new(usb_direct::UsbDirectTransport::open(
142 *vid, *pid, *bus, *address,
143 )?)),
144 #[cfg(windows)]
145 PrinterTarget::WinSpooler(name) => Ok(Box::new(win_spool::WinSpoolerTransport::new(
146 name.clone(),
147 ))),
148 #[cfg(not(windows))]
149 PrinterTarget::WinSpooler(_) => Err(PrintError::Open(
150 "Windows spooler printing is only available on Windows".into(),
151 )),
152 }
153}
154
155/// Open by manual name: tries serial/COM first, then Windows spooler queue name.
156pub fn open_printer_by_name(name: &str) -> Result<Box<dyn PrinterTransport>, PrintError> {
157 let name = name.trim();
158 if name.is_empty() {
159 return Err(PrintError::NotFound);
160 }
161
162 if let Ok(transport) = SerialTransport::open(name) {
163 return Ok(Box::new(transport));
164 }
165
166 #[cfg(windows)]
167 {
168 return Ok(Box::new(win_spool::WinSpoolerTransport::new(
169 name.to_string(),
170 )));
171 }
172
173 #[cfg(not(windows))]
174 Err(PrintError::Open(format!(
175 "could not open serial port '{name}'"
176 )))
177}
178
179fn fmt_vid_pid(v: u16) -> String {
180 format!("{v:04x}")
181}
182
183impl PrinterTransport for Box<dyn PrinterTransport> {
184 fn write_all(&mut self, data: &[u8]) -> io::Result<()> {
185 (**self).write_all(data)
186 }
187
188 fn flush(&mut self) -> io::Result<()> {
189 (**self).flush()
190 }
191}
192
193pub fn print_bytes<T: PrinterTransport + ?Sized>(transport: &mut T, data: &[u8]) -> Result<(), PrintError> {
194 transport
195 .write_all(data)
196 .map_err(|e| PrintError::Write(e.to_string()))?;
197 transport
198 .flush()
199 .map_err(|e| PrintError::Write(e.to_string()))?;
200 Ok(())
201}
202
203pub struct MockTransport {
204 pub written: Vec<u8>,
205}
206
207impl MockTransport {
208 pub fn new() -> Self {
209 Self { written: Vec::new() }
210 }
211}
212
213impl Default for MockTransport {
214 fn default() -> Self {
215 Self::new()
216 }
217}
218
219impl PrinterTransport for MockTransport {
220 fn write_all(&mut self, data: &[u8]) -> io::Result<()> {
221 self.written.extend_from_slice(data);
222 Ok(())
223 }
224
225 fn flush(&mut self) -> io::Result<()> {
226 Ok(())
227 }
228}
229
230#[cfg(test)]
231mod tests {
232 use super::*;
233 use serialport::UsbPortInfo;
234
235 #[test]
236 fn mock_transport_records_bytes() {
237 let mut mock = MockTransport::new();
238 print_bytes(&mut mock, &[1, 2, 3]).unwrap();
239 assert_eq!(mock.written, vec![1, 2, 3]);
240 }
241
242 #[test]
243 fn list_printers_returns_vec() {
244 let list = list_printers();
245 assert!(list.is_ok());
246 }
247
248 #[test]
249 fn non_usb_serial_ports_are_not_candidates() {
250 assert!(!is_usb_serial_candidate(&SerialPortType::PciPort));
251 assert!(!is_usb_serial_candidate(&SerialPortType::BluetoothPort));
252 assert!(!is_usb_serial_candidate(&SerialPortType::Unknown));
253 }
254
255 #[test]
256 fn usb_serial_port_is_candidate() {
257 let usb = SerialPortType::UsbPort(UsbPortInfo {
258 vid: 0x0416,
259 pid: 0x5011,
260 serial_number: None,
261 manufacturer: None,
262 product: Some("POS-58".into()),
263 });
264 assert!(is_usb_serial_candidate(&usb));
265 }
266}