BlueGit

timfa posprint

Files

posprint / src / protocol.rs

protocol.rs

protocol.rs 8.0 KiB Download Raw
1//! Printer command-language detection (ESC/POS vs. TSPL/TSPL2).
2//!
3//! Detection order (first hit wins):
4//! 1. IEEE 1284 device ID (`CMD:` / `COMMAND SET:` field) read from the USB
5//! printer-class `GET_DEVICE_ID` request (or Linux sysfs `ieee1284_id`).
6//! `TSPL`, `TSPL2`, `TSPL-EZ` → TSPL. If ESC/POS is also listed, ESC/POS wins
7//! (keeps existing behaviour for multi-language printers).
8//! 2. USB vendor ID of TSC Auto ID Technology (0x1203; also used by Altec) → TSPL.
9//! 3. Windows spooler queue name that clearly names a TSPL label printer.
10//! 4. Otherwise ESC/POS — the existing default, so nothing changes for
11//! receipt printers.
12
13use crate::print::PrinterTarget;
14
15#[derive(Debug, Clone, Copy, PartialEq, Eq)]
16pub enum PrinterProtocol {
17 EscPos,
18 Tspl,
19}
20
21impl PrinterProtocol {
22 pub fn label(self) -> &'static str {
23 match self {
24 Self::EscPos => "ESC/POS",
25 Self::Tspl => "TSPL/TSPL2",
26 }
27 }
28}
29
30/// How the protocol was decided (shown as tooltip, useful for support).
31#[derive(Debug, Clone, Copy, PartialEq, Eq)]
32pub enum DetectionSource {
33 DeviceId,
34 UsbVendor,
35 QueueName,
36 Default,
37}
38
39#[derive(Debug, Clone, PartialEq, Eq, Default)]
40pub struct DeviceIdInfo {
41 pub manufacturer: Option<String>,
42 pub model: Option<String>,
43 pub command_sets: Vec<String>,
44 pub raw: String,
45}
46
47#[derive(Debug, Clone, PartialEq, Eq)]
48pub struct Detection {
49 pub protocol: PrinterProtocol,
50 pub source: DetectionSource,
51 /// Stable per-model key for remembering the label format, e.g. `Altec ATP-300 Pro`.
52 pub model_key: String,
53 /// Human-readable model, if known.
54 pub model_name: Option<String>,
55}
56
57/// TSC Auto ID Technology (Altec ATP printers report this vendor too).
58pub const TSC_USB_VENDOR_ID: u16 = 0x1203;
59
60/// Parse an IEEE 1284 device ID (`KEY:value;KEY:value;`). The optional
61/// two-byte big-endian length prefix must already be stripped.
62pub fn parse_ieee1284_id(raw: &str) -> DeviceIdInfo {
63 let mut info = DeviceIdInfo {
64 raw: raw.trim_matches(char::from(0)).trim().to_string(),
65 ..Default::default()
66 };
67 for field in raw.split(';') {
68 let Some((key, value)) = field.split_once(':') else {
69 continue;
70 };
71 let key = key.trim().to_ascii_uppercase();
72 let value = value.trim().trim_matches(char::from(0)).trim();
73 if value.is_empty() {
74 continue;
75 }
76 match key.as_str() {
77 "MFG" | "MANUFACTURER" => info.manufacturer = Some(value.to_string()),
78 "MDL" | "MODEL" => info.model = Some(value.to_string()),
79 "CMD" | "COMMAND SET" | "COMMANDSET" => {
80 info.command_sets = value
81 .split(',')
82 .map(|s| s.trim().to_string())
83 .filter(|s| !s.is_empty())
84 .collect();
85 }
86 _ => {}
87 }
88 }
89 info
90}
91
92/// Protocol from the `CMD:` list, or `None` when nothing is recognised.
93pub fn protocol_from_command_sets(sets: &[String]) -> Option<PrinterProtocol> {
94 let norm: Vec<String> = sets
95 .iter()
96 .map(|s| s.to_ascii_uppercase().replace([' ', '_'], ""))
97 .collect();
98 if norm
99 .iter()
100 .any(|s| s == "ESC/POS" || s == "ESCPOS" || s == "ESC/POSE" || s.starts_with("ESCPOS"))
101 {
102 return Some(PrinterProtocol::EscPos);
103 }
104 if norm.iter().any(|s| s.starts_with("TSPL")) {
105 return Some(PrinterProtocol::Tspl);
106 }
107 None
108}
109
110fn queue_name_says_tspl(name: &str) -> bool {
111 let n = name.to_ascii_lowercase();
112 n.contains("tspl") || n.contains("altec atp") || n.starts_with("tsc ") || n.contains(" tsc ")
113}
114
115/// Decide the protocol for a printer. `device_id` is the raw IEEE 1284 ID if it
116/// could be read (USB direct only).
117pub fn detect(target: &PrinterTarget, device_id: Option<&str>) -> Detection {
118 let info = device_id.map(parse_ieee1284_id);
119 let model_name = info.as_ref().and_then(|i| match (&i.manufacturer, &i.model) {
120 (Some(m), Some(d)) if d.to_ascii_lowercase().starts_with(&m.to_ascii_lowercase()) => {
121 Some(d.clone())
122 }
123 (Some(m), Some(d)) => Some(format!("{m} {d}")),
124 (None, Some(d)) => Some(d.clone()),
125 _ => None,
126 });
127 let fallback_key = match target {
128 PrinterTarget::UsbDirect { vid, pid, .. } => format!("usb:{vid:04x}:{pid:04x}"),
129 PrinterTarget::Serial(p) => format!("serial:{p}"),
130 PrinterTarget::WinSpooler(q) => format!("winspool:{q}"),
131 };
132 let model_key = model_name.clone().unwrap_or(fallback_key);
133
134 if let Some(p) = info.as_ref().and_then(|i| protocol_from_command_sets(&i.command_sets)) {
135 return Detection { protocol: p, source: DetectionSource::DeviceId, model_key, model_name };
136 }
137 if let PrinterTarget::UsbDirect { vid, .. } = target {
138 if *vid == TSC_USB_VENDOR_ID {
139 return Detection {
140 protocol: PrinterProtocol::Tspl,
141 source: DetectionSource::UsbVendor,
142 model_key,
143 model_name,
144 };
145 }
146 }
147 if let PrinterTarget::WinSpooler(q) = target {
148 if queue_name_says_tspl(q) {
149 return Detection {
150 protocol: PrinterProtocol::Tspl,
151 source: DetectionSource::QueueName,
152 model_key: q.trim().to_string(),
153 model_name: Some(q.trim().to_string()),
154 };
155 }
156 }
157 Detection { protocol: PrinterProtocol::EscPos, source: DetectionSource::Default, model_key, model_name }
158}
159
160#[cfg(test)]
161mod tests {
162 use super::*;
163
164 const ALTEC: &str = "MFG:Altec;CMD:TSPL2;MDL:ATP-300 Pro;CLS:PRINTER;";
165
166 fn usb(vid: u16, pid: u16) -> PrinterTarget {
167 PrinterTarget::UsbDirect { vid, pid, bus: 3, address: 16 }
168 }
169
170 #[test]
171 fn parses_altec_device_id() {
172 let i = parse_ieee1284_id(ALTEC);
173 assert_eq!(i.manufacturer.as_deref(), Some("Altec"));
174 assert_eq!(i.model.as_deref(), Some("ATP-300 Pro"));
175 assert_eq!(i.command_sets, vec!["TSPL2".to_string()]);
176 }
177
178 #[test]
179 fn altec_is_tspl_with_model_key() {
180 let d = detect(&usb(0x1203, 0x0231), Some(ALTEC));
181 assert_eq!(d.protocol, PrinterProtocol::Tspl);
182 assert_eq!(d.source, DetectionSource::DeviceId);
183 assert_eq!(d.model_key, "Altec ATP-300 Pro");
184 }
185
186 #[test]
187 fn long_keys_and_variants() {
188 for id in [
189 "MANUFACTURER:TSC;COMMAND SET:TSPL;MODEL:TTP-244 Pro;",
190 "MFG:TSC;CMD:TSPL-EZ,ZPL2,EPL2;MDL:TE200;",
191 "mfg:x;cmd:tspl2;mdl:y;",
192 ] {
193 assert_eq!(detect(&usb(1, 2), Some(id)).protocol, PrinterProtocol::Tspl, "{id}");
194 }
195 }
196
197 #[test]
198 fn escpos_and_unknown_stay_escpos() {
199 for id in [
200 "MFG:EPSON;CMD:ESC/POS;MDL:TM-T20;",
201 "MFG:Xprinter;CMD:ESCPOS,TSPL;MDL:XP-365B;", // multi-language: keep ESC/POS
202 "MFG:Foo;MDL:Bar;",
203 "",
204 "garbage without fields",
205 ] {
206 let d = detect(&usb(0x0416, 0x5011), Some(id));
207 assert_eq!(d.protocol, PrinterProtocol::EscPos, "{id}");
208 }
209 let d = detect(&usb(0x0416, 0x5011), None);
210 assert_eq!(d.protocol, PrinterProtocol::EscPos);
211 assert_eq!(d.source, DetectionSource::Default);
212 assert_eq!(d.model_key, "usb:0416:5011");
213 }
214
215 #[test]
216 fn tsc_vendor_without_device_id_is_tspl() {
217 let d = detect(&usb(0x1203, 0x0231), None);
218 assert_eq!(d.protocol, PrinterProtocol::Tspl);
219 assert_eq!(d.source, DetectionSource::UsbVendor);
220 assert_eq!(d.model_key, "usb:1203:0231");
221 }
222
223 #[test]
224 fn serial_and_plain_queues_are_escpos() {
225 assert_eq!(detect(&PrinterTarget::Serial("COM3".into()), None).protocol, PrinterProtocol::EscPos);
226 assert_eq!(
227 detect(&PrinterTarget::WinSpooler("POS-58".into()), None).protocol,
228 PrinterProtocol::EscPos
229 );
230 assert_eq!(
231 detect(&PrinterTarget::WinSpooler("Altec ATP-300 Pro".into()), None).protocol,
232 PrinterProtocol::Tspl
233 );
234 }
235}