//! Printer command-language detection (ESC/POS vs. TSPL/TSPL2). //! //! Detection order (first hit wins): //! 1. IEEE 1284 device ID (`CMD:` / `COMMAND SET:` field) read from the USB //! printer-class `GET_DEVICE_ID` request (or Linux sysfs `ieee1284_id`). //! `TSPL`, `TSPL2`, `TSPL-EZ` → TSPL. If ESC/POS is also listed, ESC/POS wins //! (keeps existing behaviour for multi-language printers). //! 2. USB vendor ID of TSC Auto ID Technology (0x1203; also used by Altec) → TSPL. //! 3. Windows spooler queue name that clearly names a TSPL label printer. //! 4. Otherwise ESC/POS — the existing default, so nothing changes for //! receipt printers. use crate::print::PrinterTarget; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum PrinterProtocol { EscPos, Tspl, } impl PrinterProtocol { pub fn label(self) -> &'static str { match self { Self::EscPos => "ESC/POS", Self::Tspl => "TSPL/TSPL2", } } } /// How the protocol was decided (shown as tooltip, useful for support). #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum DetectionSource { DeviceId, UsbVendor, QueueName, Default, } #[derive(Debug, Clone, PartialEq, Eq, Default)] pub struct DeviceIdInfo { pub manufacturer: Option, pub model: Option, pub command_sets: Vec, pub raw: String, } #[derive(Debug, Clone, PartialEq, Eq)] pub struct Detection { pub protocol: PrinterProtocol, pub source: DetectionSource, /// Stable per-model key for remembering the label format, e.g. `Altec ATP-300 Pro`. pub model_key: String, /// Human-readable model, if known. pub model_name: Option, } /// TSC Auto ID Technology (Altec ATP printers report this vendor too). pub const TSC_USB_VENDOR_ID: u16 = 0x1203; /// Parse an IEEE 1284 device ID (`KEY:value;KEY:value;`). The optional /// two-byte big-endian length prefix must already be stripped. pub fn parse_ieee1284_id(raw: &str) -> DeviceIdInfo { let mut info = DeviceIdInfo { raw: raw.trim_matches(char::from(0)).trim().to_string(), ..Default::default() }; for field in raw.split(';') { let Some((key, value)) = field.split_once(':') else { continue; }; let key = key.trim().to_ascii_uppercase(); let value = value.trim().trim_matches(char::from(0)).trim(); if value.is_empty() { continue; } match key.as_str() { "MFG" | "MANUFACTURER" => info.manufacturer = Some(value.to_string()), "MDL" | "MODEL" => info.model = Some(value.to_string()), "CMD" | "COMMAND SET" | "COMMANDSET" => { info.command_sets = value .split(',') .map(|s| s.trim().to_string()) .filter(|s| !s.is_empty()) .collect(); } _ => {} } } info } /// Protocol from the `CMD:` list, or `None` when nothing is recognised. pub fn protocol_from_command_sets(sets: &[String]) -> Option { let norm: Vec = sets .iter() .map(|s| s.to_ascii_uppercase().replace([' ', '_'], "")) .collect(); if norm .iter() .any(|s| s == "ESC/POS" || s == "ESCPOS" || s == "ESC/POSE" || s.starts_with("ESCPOS")) { return Some(PrinterProtocol::EscPos); } if norm.iter().any(|s| s.starts_with("TSPL")) { return Some(PrinterProtocol::Tspl); } None } fn queue_name_says_tspl(name: &str) -> bool { let n = name.to_ascii_lowercase(); n.contains("tspl") || n.contains("altec atp") || n.starts_with("tsc ") || n.contains(" tsc ") } /// Decide the protocol for a printer. `device_id` is the raw IEEE 1284 ID if it /// could be read (USB direct only). pub fn detect(target: &PrinterTarget, device_id: Option<&str>) -> Detection { let info = device_id.map(parse_ieee1284_id); let model_name = info.as_ref().and_then(|i| match (&i.manufacturer, &i.model) { (Some(m), Some(d)) if d.to_ascii_lowercase().starts_with(&m.to_ascii_lowercase()) => { Some(d.clone()) } (Some(m), Some(d)) => Some(format!("{m} {d}")), (None, Some(d)) => Some(d.clone()), _ => None, }); let fallback_key = match target { PrinterTarget::UsbDirect { vid, pid, .. } => format!("usb:{vid:04x}:{pid:04x}"), PrinterTarget::Serial(p) => format!("serial:{p}"), PrinterTarget::WinSpooler(q) => format!("winspool:{q}"), }; let model_key = model_name.clone().unwrap_or(fallback_key); if let Some(p) = info.as_ref().and_then(|i| protocol_from_command_sets(&i.command_sets)) { return Detection { protocol: p, source: DetectionSource::DeviceId, model_key, model_name }; } if let PrinterTarget::UsbDirect { vid, .. } = target { if *vid == TSC_USB_VENDOR_ID { return Detection { protocol: PrinterProtocol::Tspl, source: DetectionSource::UsbVendor, model_key, model_name, }; } } if let PrinterTarget::WinSpooler(q) = target { if queue_name_says_tspl(q) { return Detection { protocol: PrinterProtocol::Tspl, source: DetectionSource::QueueName, model_key: q.trim().to_string(), model_name: Some(q.trim().to_string()), }; } } Detection { protocol: PrinterProtocol::EscPos, source: DetectionSource::Default, model_key, model_name } } #[cfg(test)] mod tests { use super::*; const ALTEC: &str = "MFG:Altec;CMD:TSPL2;MDL:ATP-300 Pro;CLS:PRINTER;"; fn usb(vid: u16, pid: u16) -> PrinterTarget { PrinterTarget::UsbDirect { vid, pid, bus: 3, address: 16 } } #[test] fn parses_altec_device_id() { let i = parse_ieee1284_id(ALTEC); assert_eq!(i.manufacturer.as_deref(), Some("Altec")); assert_eq!(i.model.as_deref(), Some("ATP-300 Pro")); assert_eq!(i.command_sets, vec!["TSPL2".to_string()]); } #[test] fn altec_is_tspl_with_model_key() { let d = detect(&usb(0x1203, 0x0231), Some(ALTEC)); assert_eq!(d.protocol, PrinterProtocol::Tspl); assert_eq!(d.source, DetectionSource::DeviceId); assert_eq!(d.model_key, "Altec ATP-300 Pro"); } #[test] fn long_keys_and_variants() { for id in [ "MANUFACTURER:TSC;COMMAND SET:TSPL;MODEL:TTP-244 Pro;", "MFG:TSC;CMD:TSPL-EZ,ZPL2,EPL2;MDL:TE200;", "mfg:x;cmd:tspl2;mdl:y;", ] { assert_eq!(detect(&usb(1, 2), Some(id)).protocol, PrinterProtocol::Tspl, "{id}"); } } #[test] fn escpos_and_unknown_stay_escpos() { for id in [ "MFG:EPSON;CMD:ESC/POS;MDL:TM-T20;", "MFG:Xprinter;CMD:ESCPOS,TSPL;MDL:XP-365B;", // multi-language: keep ESC/POS "MFG:Foo;MDL:Bar;", "", "garbage without fields", ] { let d = detect(&usb(0x0416, 0x5011), Some(id)); assert_eq!(d.protocol, PrinterProtocol::EscPos, "{id}"); } let d = detect(&usb(0x0416, 0x5011), None); assert_eq!(d.protocol, PrinterProtocol::EscPos); assert_eq!(d.source, DetectionSource::Default); assert_eq!(d.model_key, "usb:0416:5011"); } #[test] fn tsc_vendor_without_device_id_is_tspl() { let d = detect(&usb(0x1203, 0x0231), None); assert_eq!(d.protocol, PrinterProtocol::Tspl); assert_eq!(d.source, DetectionSource::UsbVendor); assert_eq!(d.model_key, "usb:1203:0231"); } #[test] fn serial_and_plain_queues_are_escpos() { assert_eq!(detect(&PrinterTarget::Serial("COM3".into()), None).protocol, PrinterProtocol::EscPos); assert_eq!( detect(&PrinterTarget::WinSpooler("POS-58".into()), None).protocol, PrinterProtocol::EscPos ); assert_eq!( detect(&PrinterTarget::WinSpooler("Altec ATP-300 Pro".into()), None).protocol, PrinterProtocol::Tspl ); } }