BlueGit

timfa posprint

Files

posprint / src / print / usb_direct.rs

usb_direct.rs

usb_direct.rs 12.1 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
86/// IEEE 1284 device ID of a USB printer (`MFG:…;CMD:…;MDL:…;`).
87///
88/// Linux: read from sysfs (`ieee1284_id`, provided by the `usblp` driver) so the
89/// kernel driver is never detached. Otherwise the printer-class
90/// `GET_DEVICE_ID` control request is used, only when no kernel driver owns the
91/// interface. Read-only: nothing is sent to the print path.
92pub fn read_device_id(vid: u16, pid: u16, bus: u8, address: u8) -> Option<String> {
93 #[cfg(target_os = "linux")]
94 if let Some(id) = sysfs_device_id(bus, address) {
95 return Some(id);
96 }
97 let context = Context::new().ok()?;
98 let device = find_device(&context, vid, pid, bus, address)?;
99 let config = device
100 .active_config_descriptor()
101 .or_else(|_| device.config_descriptor(0))
102 .ok()?;
103 let config_index = 0u16;
104 let (iface, alt) = config.interfaces().find_map(|i| {
105 i.descriptors()
106 .find(|d| d.class_code() == USB_CLASS_PRINTER)
107 .map(|d| (d.interface_number(), d.setting_number()))
108 })?;
109 let handle = device.open().ok()?;
110 #[cfg(any(target_os = "linux", target_os = "macos"))]
111 if handle.kernel_driver_active(iface).unwrap_or(false) {
112 return None;
113 }
114 let claimed = handle.claim_interface(iface).is_ok();
115 let mut buf = [0u8; 1024];
116 let result = handle.read_control(
117 0xA1, // device-to-host, class, interface
118 0x00, // GET_DEVICE_ID
119 config_index,
120 (u16::from(iface) << 8) | u16::from(alt),
121 &mut buf,
122 Duration::from_millis(500),
123 );
124 if claimed {
125 let _ = handle.release_interface(iface);
126 }
127 let n = result.ok()?;
128 parse_device_id_reply(&buf[..n])
129}
130
131/// Reply = 2-byte big-endian length (including itself) + ID string.
132pub fn parse_device_id_reply(buf: &[u8]) -> Option<String> {
133 if buf.len() < 2 {
134 return None;
135 }
136 let len = (usize::from(buf[0]) << 8 | usize::from(buf[1])).min(buf.len());
137 let body = if len >= 2 { &buf[2..len] } else { &buf[2..] };
138 let s = String::from_utf8_lossy(body).trim_matches(char::from(0)).trim().to_string();
139 if s.contains(':') {
140 Some(s)
141 } else {
142 None
143 }
144}
145
146#[cfg(target_os = "linux")]
147fn sysfs_device_id(bus: u8, address: u8) -> Option<String> {
148 let root = std::path::Path::new("/sys/bus/usb/devices");
149 for entry in std::fs::read_dir(root).ok()?.flatten() {
150 let dev = entry.path();
151 let read_num = |name: &str| -> Option<u32> {
152 std::fs::read_to_string(dev.join(name)).ok()?.trim().parse().ok()
153 };
154 if read_num("busnum") != Some(u32::from(bus)) || read_num("devnum") != Some(u32::from(address)) {
155 continue;
156 }
157 for iface in std::fs::read_dir(&dev).ok()?.flatten() {
158 let p = iface.path().join("ieee1284_id");
159 if let Ok(id) = std::fs::read_to_string(&p) {
160 let id = id.trim().to_string();
161 if id.contains(':') {
162 return Some(id);
163 }
164 }
165 }
166 }
167 None
168}
169
170/// Send `request` and collect the reply from the bulk IN endpoint (bidirectional
171/// printers). Used only for TSPL settings/status queries.
172pub fn query(vid: u16, pid: u16, bus: u8, address: u8, request: &[u8], timeout: Duration) -> Option<Vec<u8>> {
173 let context = Context::new().ok()?;
174 let device = find_device(&context, vid, pid, bus, address)?;
175 let config = device
176 .active_config_descriptor()
177 .or_else(|_| device.config_descriptor(0))
178 .ok()?;
179 let mut found = None;
180 for interface in config.interfaces() {
181 for d in interface.descriptors() {
182 if d.class_code() != USB_CLASS_PRINTER {
183 continue;
184 }
185 let mut out_ep = None;
186 let mut in_ep = None;
187 for ep in d.endpoint_descriptors() {
188 if ep.transfer_type() != TransferType::Bulk {
189 continue;
190 }
191 match ep.direction() {
192 Direction::Out => out_ep = Some(ep.address()),
193 Direction::In => in_ep = Some(ep.address()),
194 }
195 }
196 if let (Some(o), Some(i)) = (out_ep, in_ep) {
197 found = Some((d.interface_number(), o, i));
198 }
199 }
200 }
201 let (iface, out_ep, in_ep) = found?;
202 let handle = device.open().ok()?;
203 #[cfg(any(target_os = "linux", target_os = "macos"))]
204 let reattach = if handle.kernel_driver_active(iface).unwrap_or(false) {
205 handle.detach_kernel_driver(iface).ok()?;
206 true
207 } else {
208 false
209 };
210 let mut reply = None;
211 if handle.claim_interface(iface).is_ok() {
212 if handle.write_bulk(out_ep, request, Duration::from_millis(500)).is_ok() {
213 let mut buf = [0u8; 512];
214 let mut got = Vec::new();
215 let deadline = std::time::Instant::now() + timeout;
216 while std::time::Instant::now() < deadline {
217 match handle.read_bulk(in_ep, &mut buf, Duration::from_millis(200)) {
218 Ok(n) if n > 0 => got.extend_from_slice(&buf[..n]),
219 Ok(_) => {}
220 Err(rusb::Error::Timeout) if !got.is_empty() => break,
221 Err(rusb::Error::Timeout) => {}
222 Err(_) => break,
223 }
224 }
225 if !got.is_empty() {
226 reply = Some(got);
227 }
228 }
229 let _ = handle.release_interface(iface);
230 }
231 #[cfg(any(target_os = "linux", target_os = "macos"))]
232 if reattach {
233 let _ = handle.attach_kernel_driver(iface);
234 }
235 reply
236}
237
238pub struct UsbDirectTransport {
239 handle: DeviceHandle<Context>,
240 endpoint: u8,
241 timeout: Duration,
242}
243
244impl UsbDirectTransport {
245 pub fn open(vid: u16, pid: u16, bus: u8, address: u8) -> Result<Self, PrintError> {
246 let context = Context::new().map_err(|e| PrintError::Open(e.to_string()))?;
247 let device = find_device(&context, vid, pid, bus, address)
248 .ok_or(PrintError::NotFound)?;
249
250 let handle = device
251 .open()
252 .map_err(|e| PrintError::Open(e.to_string()))?;
253
254 #[cfg(any(target_os = "linux", target_os = "macos"))]
255 if handle.kernel_driver_active(0).unwrap_or(false) {
256 let _ = handle.detach_kernel_driver(0);
257 }
258
259 let (interface, endpoint) = find_printer_out_endpoint(&device)?;
260 handle
261 .claim_interface(interface)
262 .map_err(|e| PrintError::Open(e.to_string()))?;
263
264 Ok(Self {
265 handle,
266 endpoint,
267 timeout: Duration::from_secs(5),
268 })
269 }
270}
271
272impl super::PrinterTransport for UsbDirectTransport {
273 fn write_all(&mut self, data: &[u8]) -> io::Result<()> {
274 for chunk in data.chunks(WRITE_CHUNK) {
275 self.handle
276 .write_bulk(self.endpoint, chunk, self.timeout)
277 .map_err(io::Error::other)?;
278 }
279 Ok(())
280 }
281
282 fn flush(&mut self) -> io::Result<()> {
283 Ok(())
284 }
285}
286
287fn find_device(
288 context: &Context,
289 vid: u16,
290 pid: u16,
291 bus: u8,
292 address: u8,
293) -> Option<Device<Context>> {
294 let devices = context.devices().ok()?;
295 for device in devices.iter() {
296 let Ok(desc) = device.device_descriptor() else {
297 continue;
298 };
299 if desc.vendor_id() == vid
300 && desc.product_id() == pid
301 && device.bus_number() == bus
302 && device.address() == address
303 {
304 return Some(device);
305 }
306 }
307 None
308}
309
310fn find_printer_out_endpoint(device: &Device<Context>) -> Result<(u8, u8), PrintError> {
311 let config = device
312 .active_config_descriptor()
313 .or_else(|_| device.config_descriptor(0))
314 .map_err(|e| PrintError::Open(e.to_string()))?;
315
316 for interface in config.interfaces() {
317 for descriptor in interface.descriptors() {
318 if descriptor.class_code() != USB_CLASS_PRINTER {
319 continue;
320 }
321 let iface = descriptor.interface_number();
322 for endpoint in descriptor.endpoint_descriptors() {
323 if endpoint.direction() == Direction::Out {
324 return Ok((iface, endpoint.address()));
325 }
326 }
327 }
328 }
329
330 for interface in config.interfaces() {
331 for descriptor in interface.descriptors() {
332 let iface = descriptor.interface_number();
333 for endpoint in descriptor.endpoint_descriptors() {
334 if endpoint.transfer_type() == TransferType::Bulk
335 && endpoint.direction() == Direction::Out
336 {
337 return Ok((iface, endpoint.address()));
338 }
339 }
340 }
341 }
342
343 Err(PrintError::Open("no USB OUT endpoint found".into()))
344}
345
346#[cfg(test)]
347mod tests {
348 use super::*;
349
350 #[test]
351 fn list_usb_devices_does_not_panic() {
352 let _ = list_usb_printer_devices();
353 }
354
355 #[test]
356 fn parses_get_device_id_reply() {
357 let id = b"MFG:Altec;CMD:TSPL2;MDL:ATP-300 Pro;CLS:PRINTER;";
358 let mut buf = vec![0u8, (id.len() + 2) as u8];
359 buf.extend_from_slice(id);
360 buf.extend_from_slice(&[0, 0, 0]);
361 assert_eq!(
362 parse_device_id_reply(&buf).as_deref(),
363 Some("MFG:Altec;CMD:TSPL2;MDL:ATP-300 Pro;CLS:PRINTER;")
364 );
365 assert_eq!(parse_device_id_reply(&[0]), None);
366 assert_eq!(parse_device_id_reply(&[0, 2]), None);
367 }
368}