//! USB printer-class device discovery and RAW bulk printing (libusb). use std::io; use std::time::Duration; use rusb::{Context, Device, DeviceHandle, Direction, TransferType, UsbContext}; use super::{PrintError, PrinterDevice, PrinterTarget}; const USB_CLASS_PRINTER: u8 = 0x07; const WRITE_CHUNK: usize = 512; pub fn list_usb_printer_devices() -> Vec { let Ok(context) = Context::new() else { return Vec::new(); }; let Ok(devices) = context.devices() else { return Vec::new(); }; let mut out = Vec::new(); for device in devices.iter() { let Ok(desc) = device.device_descriptor() else { continue; }; if !device_has_printer_interface(&device) { continue; } let vid = desc.vendor_id(); let pid = desc.product_id(); let bus = device.bus_number(); let address = device.address(); let product = read_product_string(&device, &desc).unwrap_or_else(|| { format!("USB printer {vid:04x}:{pid:04x}") }); out.push(PrinterDevice { id: format!("usb:{bus}:{address}:{vid:04x}:{pid:04x}"), display_name: format!("{product} — USB {vid:04x}:{pid:04x} (direct)"), target: PrinterTarget::UsbDirect { vid, pid, bus, address, }, }); } out } fn device_has_printer_interface(device: &Device) -> bool { for config_index in 0..device.device_descriptor().map(|d| d.num_configurations()).unwrap_or(0) { let Ok(config) = device.config_descriptor(config_index) else { continue; }; for interface in config.interfaces() { for descriptor in interface.descriptors() { if descriptor.class_code() == USB_CLASS_PRINTER { return true; } } } } false } fn read_product_string(device: &Device, desc: &rusb::DeviceDescriptor) -> Option { if desc.product_string_index().is_none() { return None; } let handle = device.open().ok()?; let lang = handle .read_languages(Duration::from_millis(200)) .ok()? .into_iter() .next()?; handle .read_product_string(lang, desc, Duration::from_millis(200)) .ok() } /// IEEE 1284 device ID of a USB printer (`MFG:…;CMD:…;MDL:…;`). /// /// Linux: read from sysfs (`ieee1284_id`, provided by the `usblp` driver) so the /// kernel driver is never detached. Otherwise the printer-class /// `GET_DEVICE_ID` control request is used, only when no kernel driver owns the /// interface. Read-only: nothing is sent to the print path. pub fn read_device_id(vid: u16, pid: u16, bus: u8, address: u8) -> Option { #[cfg(target_os = "linux")] if let Some(id) = sysfs_device_id(bus, address) { return Some(id); } let context = Context::new().ok()?; let device = find_device(&context, vid, pid, bus, address)?; let config = device .active_config_descriptor() .or_else(|_| device.config_descriptor(0)) .ok()?; let config_index = 0u16; let (iface, alt) = config.interfaces().find_map(|i| { i.descriptors() .find(|d| d.class_code() == USB_CLASS_PRINTER) .map(|d| (d.interface_number(), d.setting_number())) })?; let handle = device.open().ok()?; #[cfg(any(target_os = "linux", target_os = "macos"))] if handle.kernel_driver_active(iface).unwrap_or(false) { return None; } let claimed = handle.claim_interface(iface).is_ok(); let mut buf = [0u8; 1024]; let result = handle.read_control( 0xA1, // device-to-host, class, interface 0x00, // GET_DEVICE_ID config_index, (u16::from(iface) << 8) | u16::from(alt), &mut buf, Duration::from_millis(500), ); if claimed { let _ = handle.release_interface(iface); } let n = result.ok()?; parse_device_id_reply(&buf[..n]) } /// Reply = 2-byte big-endian length (including itself) + ID string. pub fn parse_device_id_reply(buf: &[u8]) -> Option { if buf.len() < 2 { return None; } let len = (usize::from(buf[0]) << 8 | usize::from(buf[1])).min(buf.len()); let body = if len >= 2 { &buf[2..len] } else { &buf[2..] }; let s = String::from_utf8_lossy(body).trim_matches(char::from(0)).trim().to_string(); if s.contains(':') { Some(s) } else { None } } #[cfg(target_os = "linux")] fn sysfs_device_id(bus: u8, address: u8) -> Option { let root = std::path::Path::new("/sys/bus/usb/devices"); for entry in std::fs::read_dir(root).ok()?.flatten() { let dev = entry.path(); let read_num = |name: &str| -> Option { std::fs::read_to_string(dev.join(name)).ok()?.trim().parse().ok() }; if read_num("busnum") != Some(u32::from(bus)) || read_num("devnum") != Some(u32::from(address)) { continue; } for iface in std::fs::read_dir(&dev).ok()?.flatten() { let p = iface.path().join("ieee1284_id"); if let Ok(id) = std::fs::read_to_string(&p) { let id = id.trim().to_string(); if id.contains(':') { return Some(id); } } } } None } /// Send `request` and collect the reply from the bulk IN endpoint (bidirectional /// printers). Used only for TSPL settings/status queries. pub fn query(vid: u16, pid: u16, bus: u8, address: u8, request: &[u8], timeout: Duration) -> Option> { let context = Context::new().ok()?; let device = find_device(&context, vid, pid, bus, address)?; let config = device .active_config_descriptor() .or_else(|_| device.config_descriptor(0)) .ok()?; let mut found = None; for interface in config.interfaces() { for d in interface.descriptors() { if d.class_code() != USB_CLASS_PRINTER { continue; } let mut out_ep = None; let mut in_ep = None; for ep in d.endpoint_descriptors() { if ep.transfer_type() != TransferType::Bulk { continue; } match ep.direction() { Direction::Out => out_ep = Some(ep.address()), Direction::In => in_ep = Some(ep.address()), } } if let (Some(o), Some(i)) = (out_ep, in_ep) { found = Some((d.interface_number(), o, i)); } } } let (iface, out_ep, in_ep) = found?; let handle = device.open().ok()?; #[cfg(any(target_os = "linux", target_os = "macos"))] let reattach = if handle.kernel_driver_active(iface).unwrap_or(false) { handle.detach_kernel_driver(iface).ok()?; true } else { false }; let mut reply = None; if handle.claim_interface(iface).is_ok() { if handle.write_bulk(out_ep, request, Duration::from_millis(500)).is_ok() { let mut buf = [0u8; 512]; let mut got = Vec::new(); let deadline = std::time::Instant::now() + timeout; while std::time::Instant::now() < deadline { match handle.read_bulk(in_ep, &mut buf, Duration::from_millis(200)) { Ok(n) if n > 0 => got.extend_from_slice(&buf[..n]), Ok(_) => {} Err(rusb::Error::Timeout) if !got.is_empty() => break, Err(rusb::Error::Timeout) => {} Err(_) => break, } } if !got.is_empty() { reply = Some(got); } } let _ = handle.release_interface(iface); } #[cfg(any(target_os = "linux", target_os = "macos"))] if reattach { let _ = handle.attach_kernel_driver(iface); } reply } pub struct UsbDirectTransport { handle: DeviceHandle, endpoint: u8, timeout: Duration, } impl UsbDirectTransport { pub fn open(vid: u16, pid: u16, bus: u8, address: u8) -> Result { let context = Context::new().map_err(|e| PrintError::Open(e.to_string()))?; let device = find_device(&context, vid, pid, bus, address) .ok_or(PrintError::NotFound)?; let handle = device .open() .map_err(|e| PrintError::Open(e.to_string()))?; #[cfg(any(target_os = "linux", target_os = "macos"))] if handle.kernel_driver_active(0).unwrap_or(false) { let _ = handle.detach_kernel_driver(0); } let (interface, endpoint) = find_printer_out_endpoint(&device)?; handle .claim_interface(interface) .map_err(|e| PrintError::Open(e.to_string()))?; Ok(Self { handle, endpoint, timeout: Duration::from_secs(5), }) } } impl super::PrinterTransport for UsbDirectTransport { fn write_all(&mut self, data: &[u8]) -> io::Result<()> { for chunk in data.chunks(WRITE_CHUNK) { self.handle .write_bulk(self.endpoint, chunk, self.timeout) .map_err(io::Error::other)?; } Ok(()) } fn flush(&mut self) -> io::Result<()> { Ok(()) } } fn find_device( context: &Context, vid: u16, pid: u16, bus: u8, address: u8, ) -> Option> { let devices = context.devices().ok()?; for device in devices.iter() { let Ok(desc) = device.device_descriptor() else { continue; }; if desc.vendor_id() == vid && desc.product_id() == pid && device.bus_number() == bus && device.address() == address { return Some(device); } } None } fn find_printer_out_endpoint(device: &Device) -> Result<(u8, u8), PrintError> { let config = device .active_config_descriptor() .or_else(|_| device.config_descriptor(0)) .map_err(|e| PrintError::Open(e.to_string()))?; for interface in config.interfaces() { for descriptor in interface.descriptors() { if descriptor.class_code() != USB_CLASS_PRINTER { continue; } let iface = descriptor.interface_number(); for endpoint in descriptor.endpoint_descriptors() { if endpoint.direction() == Direction::Out { return Ok((iface, endpoint.address())); } } } } for interface in config.interfaces() { for descriptor in interface.descriptors() { let iface = descriptor.interface_number(); for endpoint in descriptor.endpoint_descriptors() { if endpoint.transfer_type() == TransferType::Bulk && endpoint.direction() == Direction::Out { return Ok((iface, endpoint.address())); } } } } Err(PrintError::Open("no USB OUT endpoint found".into())) } #[cfg(test)] mod tests { use super::*; #[test] fn list_usb_devices_does_not_panic() { let _ = list_usb_printer_devices(); } #[test] fn parses_get_device_id_reply() { let id = b"MFG:Altec;CMD:TSPL2;MDL:ATP-300 Pro;CLS:PRINTER;"; let mut buf = vec![0u8, (id.len() + 2) as u8]; buf.extend_from_slice(id); buf.extend_from_slice(&[0, 0, 0]); assert_eq!( parse_device_id_reply(&buf).as_deref(), Some("MFG:Altec;CMD:TSPL2;MDL:ATP-300 Pro;CLS:PRINTER;") ); assert_eq!(parse_device_id_reply(&[0]), None); assert_eq!(parse_device_id_reply(&[0, 2]), None); } }