BlueGit

timfa posprint

Files

posprint / src / print / usb_direct.rs

usb_direct.rs

fixes
timfa Tim Falken · pushed by timfa · 4 months ago
4ab2186f History
usb_direct.rs 5.9 KiB Download Raw
1//! USB printer-class device discovery and RAW bulk printing (libusb).
2
3use std::io;
4use std::time::Duration;
5
6use rusb::{Context, Device, DeviceHandle, Direction, TransferType, UsbContext};
7
8use super::{PrintError, PrinterDevice, PrinterTarget};
9
10const USB_CLASS_PRINTER: u8 = 0x07;
11const WRITE_CHUNK: usize = 512;
12
13pub fn list_usb_printer_devices() -> Vec<PrinterDevice> {
14 let Ok(context) = Context::new() else {
15 return Vec::new();
16 };
17
18 let Ok(devices) = context.devices() else {
19 return Vec::new();
20 };
21
22 let mut out = Vec::new();
23 for device in devices.iter() {
24 let Ok(desc) = device.device_descriptor() else {
25 continue;
26 };
27 if !device_has_printer_interface(&device) {
28 continue;
29 }
30
31 let vid = desc.vendor_id();
32 let pid = desc.product_id();
33 let bus = device.bus_number();
34 let address = device.address();
35
36 let product = read_product_string(&device, &desc).unwrap_or_else(|| {
37 format!("USB printer {vid:04x}:{pid:04x}")
38 });
39
40 out.push(PrinterDevice {
41 id: format!("usb:{bus}:{address}:{vid:04x}:{pid:04x}"),
42 display_name: format!("{product} — USB {vid:04x}:{pid:04x} (direct)"),
43 target: PrinterTarget::UsbDirect {
44 vid,
45 pid,
46 bus,
47 address,
48 },
49 });
50 }
51 out
52}
53
54fn device_has_printer_interface(device: &Device<Context>) -> bool {
55 for config_index in 0..device.device_descriptor().map(|d| d.num_configurations()).unwrap_or(0)
56 {
57 let Ok(config) = device.config_descriptor(config_index) else {
58 continue;
59 };
60 for interface in config.interfaces() {
61 for descriptor in interface.descriptors() {
62 if descriptor.class_code() == USB_CLASS_PRINTER {
63 return true;
64 }
65 }
66 }
67 }
68 false
69}
70
71fn read_product_string(device: &Device<Context>, desc: &rusb::DeviceDescriptor) -> Option<String> {
72 if desc.product_string_index().is_none() {
73 return None;
74 }
75 let handle = device.open().ok()?;
76 let lang = handle
77 .read_languages(Duration::from_millis(200))
78 .ok()?
79 .into_iter()
80 .next()?;
81 handle
82 .read_product_string(lang, desc, Duration::from_millis(200))
83 .ok()
84}
85
86pub struct UsbDirectTransport {
87 handle: DeviceHandle<Context>,
88 endpoint: u8,
89 timeout: Duration,
90}
91
92impl UsbDirectTransport {
93 pub fn open(vid: u16, pid: u16, bus: u8, address: u8) -> Result<Self, PrintError> {
94 let context = Context::new().map_err(|e| PrintError::Open(e.to_string()))?;
95 let device = find_device(&context, vid, pid, bus, address)
96 .ok_or(PrintError::NotFound)?;
97
98 let handle = device
99 .open()
100 .map_err(|e| PrintError::Open(e.to_string()))?;
101
102 #[cfg(any(target_os = "linux", target_os = "macos"))]
103 if handle.kernel_driver_active(0).unwrap_or(false) {
104 let _ = handle.detach_kernel_driver(0);
105 }
106
107 let (interface, endpoint) = find_printer_out_endpoint(&device)?;
108 handle
109 .claim_interface(interface)
110 .map_err(|e| PrintError::Open(e.to_string()))?;
111
112 Ok(Self {
113 handle,
114 endpoint,
115 timeout: Duration::from_secs(5),
116 })
117 }
118}
119
120impl super::PrinterTransport for UsbDirectTransport {
121 fn write_all(&mut self, data: &[u8]) -> io::Result<()> {
122 for chunk in data.chunks(WRITE_CHUNK) {
123 self.handle
124 .write_bulk(self.endpoint, chunk, self.timeout)
125 .map_err(io::Error::other)?;
126 }
127 Ok(())
128 }
129
130 fn flush(&mut self) -> io::Result<()> {
131 Ok(())
132 }
133}
134
135fn find_device(
136 context: &Context,
137 vid: u16,
138 pid: u16,
139 bus: u8,
140 address: u8,
141) -> Option<Device<Context>> {
142 let devices = context.devices().ok()?;
143 for device in devices.iter() {
144 let Ok(desc) = device.device_descriptor() else {
145 continue;
146 };
147 if desc.vendor_id() == vid
148 && desc.product_id() == pid
149 && device.bus_number() == bus
150 && device.address() == address
151 {
152 return Some(device);
153 }
154 }
155 None
156}
157
158fn find_printer_out_endpoint(device: &Device<Context>) -> Result<(u8, u8), PrintError> {
159 let config = device
160 .active_config_descriptor()
161 .or_else(|_| device.config_descriptor(0))
162 .map_err(|e| PrintError::Open(e.to_string()))?;
163
164 for interface in config.interfaces() {
165 for descriptor in interface.descriptors() {
166 if descriptor.class_code() != USB_CLASS_PRINTER {
167 continue;
168 }
169 let iface = descriptor.interface_number();
170 for endpoint in descriptor.endpoint_descriptors() {
171 if endpoint.direction() == Direction::Out {
172 return Ok((iface, endpoint.address()));
173 }
174 }
175 }
176 }
177
178 for interface in config.interfaces() {
179 for descriptor in interface.descriptors() {
180 let iface = descriptor.interface_number();
181 for endpoint in descriptor.endpoint_descriptors() {
182 if endpoint.transfer_type() == TransferType::Bulk
183 && endpoint.direction() == Direction::Out
184 {
185 return Ok((iface, endpoint.address()));
186 }
187 }
188 }
189 }
190
191 Err(PrintError::Open("no USB OUT endpoint found".into()))
192}
193
194#[cfg(test)]
195mod tests {
196 use super::*;
197
198 #[test]
199 fn list_usb_devices_does_not_panic() {
200 let _ = list_usb_printer_devices();
201 }
202}