BlueGit

timfa posprint

Files

posprint / src / print / mod.rs

mod.rs

fixes
timfa Tim Falken · pushed by timfa · 4 months ago
4ab2186f History
mod.rs 6.6 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 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
130pub 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.
153pub 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
176fn fmt_vid_pid(v: u16) -> String {
177 format!("{v:04x}")
178}
179
180impl 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
190pub 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
200pub struct MockTransport {
201 pub written: Vec<u8>,
202}
203
204impl MockTransport {
205 pub fn new() -> Self {
206 Self { written: Vec::new() }
207 }
208}
209
210impl Default for MockTransport {
211 fn default() -> Self {
212 Self::new()
213 }
214}
215
216impl 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)]
228mod 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}