CPCL mobile printers
Zebra CPCL for mobile printers on vans and shop floors: labels and receipts with magnified text, centred lines, Code 128, EAN-13 and QR codes with their text, boxes, inverse lines and pictures, sent over Wi-Fi.
Version 1.0.0 · 4 functions · 2 crates
Functions
What use cpcl.qwer gives a program, with the types Quillo sees. To take only some, or under other names: use cpcl_label, cpcl_job from cpcl (Quillo 0.6).
cpcl_label(fields: list, options: any) → stror an errorA label as CPCL, written for people (pictures by their size). Each field is a map at x, y in millimetres from the top left (or units: "dots"): { text (ASCII), size: 3 (font 7 magnified to it) or font: 0-7 with font_size, align: "center" (with width), rotate: 90 }, { barcode: "code128" | "code39" | "ean13" | "upca" | "itf" | "qr", data, height, module, ratio, readable, ecc, magnification }, { box: true, width, height, thickness }, { line: true, width, thickness, vertical }, { inverse: true, width, thickness } (white on black over what is there), { image: "logo.png", width } or { raw: "..." }. options: { dpi: 203, width, height (the label or receipt's length), quantity, speed: 0-5, contrast: 0-3, media: "gap" | "mark" | "continuous", journal }.
cpcl_job(fields: list, options: any) → stror an errorThe label's bytes in base64.
cpcl_write(fields: list, options: any, path: str) → intor an errorWrites the label to a file or a device (a Bluetooth serial port such as /dev/rfcomm0). Gives the bytes written.
cpcl_send(fields: list, options: any, host: str, timeout_ms: int) → intor an errorSends the label to a mobile printer over the network (host:6101 for most Zebra mobile printers, 9100 when no port is written). Gives the bytes sent.
Get it
$ quillo install cpcl # cpcl.qwer into this folder$ quillo install cpcl --example # and its example, cpcl.qweOr with curl:
$ curl -O https://quillolang.org/plugins/files/cpcl.qwer$ curl -O https://quillolang.org/plugins/files/cpcl.qwe$ curl -O https://quillolang.org/plugins/files/cpcl_sample.pngThen, in your program, all of it or only what you call:
use cpcl.qweruse cpcl_label, cpcl_job from cpcl // Quillo 0.6: only theseIt uses these crates, which cargo fetches the first time the plugin is built:
image = { version = "0.25", default-features = false, features = ["png", "jpeg"] }base64 = "0.22"Example
// A delivery driver's mobile printer (Zebra ZQ520 on the van's Wi-Fi): a 4 × 3 inch parcel// label with the stop's address and barcodes, and a proof-of-delivery receipt on continuous paper.//// quillo run cpcl.qwe then open http://localhost:8080/label and http://localhost:8080/receipt// PRINTER_HOST=192.168.1.66:6101 quillo run cpcl.qwe and http://localhost:8080/printuse "cpcl.qwer"let STOP = { n: 14, name: "J. Okafor", street: "22 Harbour Lane", town: "Cork T12 X8Y4", parcel: "PCL-2026-0099172", items: [["Boxes", "3"], ["Signed by", "J. Okafor"], ["Time", "14:52"]] }fn label(s) = [ { image: "cpcl_sample.png", x: 2, y: 2, width: 30 }, { text: `STOP ${s.n}`, x: 70, y: 3, size: 6 }, { inverse: true, x: 69, y: 2, width: 30, thickness: 7 }, { text: s.name, x: 3, y: 16, size: 5 }, { text: s.street, x: 3, y: 24, size: 3 }, { text: s.town, x: 3, y: 29, size: 3 }, { barcode: "code128", data: s.parcel, x: 3, y: 38, height: 14, module: 2 }, { barcode: "qr", data: `https://van.example/pod/${s.parcel}`, x: 80, y: 40, magnification: 4 }, { box: true, x: 1, y: 1, width: 99, height: 74, thickness: 0.4 },]let LABEL = { width: 101.6, height: 76.2, quantity: 1, media: "gap" }route GET /label = respond(200, cpcl_label(label(STOP), LABEL)?, { "content-type": "text/plain" })route GET /receipt = respond(200, cpcl_label([ { text: "PROOF OF DELIVERY", x: 0, y: 2, size: 6, align: "center", width: 72 }, { line: true, x: 0, y: 12, width: 72, thickness: 0.3 },] + map(range(len(STOP.items)), (i) => { text: `${STOP.items[i][0]}: ${STOP.items[i][1]}`, x: 2, y: 15 + i * 5, size: 3 }) + [ { barcode: "code128", data: STOP.parcel, x: 6, y: 34, height: 10, module: 1 },], { width: 72, height: 55, media: "continuous", journal: true })?, { "content-type": "text/plain" })route GET /print { let host = env("PRINTER_HOST", null) ?? reply 503 "set PRINTER_HOST to the printer's address (host:6101 for Zebra mobile printers)" { sent: cpcl_send(label(STOP), LABEL, host, 5000)?, saved: cpcl_write(label(STOP), LABEL, "data/stop-14.cpcl")? }}$ quillo run cpcl.qwe$ curl 'localhost:8080/print'$ curl 'localhost:8080/label'$ curl 'localhost:8080/receipt'It talks to the Redis that REDIS_URL names, else Redis on this machine. The site's test runs it against a stand-in.
Source
//! Zebra CPCL labels and receipts for mobile printers (ZQ300, ZQ500, ZQ600, QLn, iMZ), built from fields in millimetres: text in the resident fonts magnified, centred lines, Code 128, Code 39, EAN-13, UPC-A, Interleaved 2 of 5 and QR codes with their text, lines, boxes, inverse lines and pictures (EG), gap or bar sensing and quantity; sent over Wi-Fi to port 6101 or 9100.//! version: 1.0.0//!//! [dependencies]//! image = { version = "0.25", default-features = false, features = ["png", "jpeg"] }//! base64 = "0.22"use serde_json::Value;fn ascii(s: &str) -> String { s.chars().map(|c| if (' '..='~').contains(&c) { c } else { '?' }).collect()}fn build(fields: &[Value], options: &Value) -> Result<Out, String> { if fields.len() > 2000 { return Err("at most 2,000 fields on a label".into()); } let dpi = options["dpi"].as_i64().unwrap_or(203); let dpmm = dots_per_mm(dpi); let units = options["units"].as_str().unwrap_or("mm").to_string(); let d = |v: &Value, def: f64| to_dots(v, def, dpmm, &units); let height = d(&options["height"], 50.0).clamp(1, 65535); let qty = options["quantity"].as_i64().unwrap_or(1).clamp(1, 1024); let mut o = Out::new(); o.s(&format!("! 0 200 200 {} {}\r\n", height, qty)); if !options["width"].is_null() { o.s(&format!("PAGE-WIDTH {}\r\n", d(&options["width"], 50.0))); } if let Some(s) = options["speed"].as_i64() { o.s(&format!("SPEED {}\r\n", s.clamp(0, 5))); } if let Some(c) = options["contrast"].as_i64() { o.s(&format!("CONTRAST {}\r\n", c.clamp(0, 3))); } if options["journal"] == true { o.s("JOURNAL\r\n"); } for f in fields { if let Some(raw) = f["raw"].as_str() { o.s(&ascii(raw)); o.s("\r\n"); continue; } let x = d(&f["x"], 0.0); let y = d(&f["y"], 0.0); let turned = f["rotate"].as_i64().unwrap_or(0).rem_euclid(360); if !f["text"].is_null() { let text = ascii(&text_of(&f["text"])); let (font, size) = (f["font"].as_i64().unwrap_or(7).clamp(0, 7), f["font_size"].as_i64().unwrap_or(0).clamp(0, 7)); // Font 7 size 0 is 24 dots high: magnify it to the size asked (SETMAG 1-16). let mag = if f["font"].is_null() { ((d(&f["size"], 3.0) as f64) / 24.0).round().clamp(1.0, 16.0) as i64 } else { 1 }; let center = matches!(f["align"].as_str(), Some("center") | Some("centre")); if center { let w = if f["width"].is_null() { String::new() } else { format!(" {}", d(&f["width"], 50.0)) }; o.s(&format!("CENTER{}\r\n", w)); } if mag > 1 { o.s(&format!("SETMAG {} {}\r\n", mag, mag)); } let cmd = match turned { 90 => "TEXT270", 180 => "TEXT180", 270 => "TEXT90", _ => "TEXT", }; o.s(&format!("{} {} {} {} {} {}\r\n", cmd, font, size, x, y, text)); if mag > 1 { o.s("SETMAG 0 0\r\n"); } if center { o.s("LEFT\r\n"); } } else if let Some(kind) = f["barcode"].as_str() { let data = ascii(&text_of(&f["data"])); if data.is_empty() { return Err("a barcode needs its `data`".into()); } let vertical = turned == 90 || turned == 270; let cmd = if vertical { "VBARCODE" } else { "BARCODE" }; let digits = data.chars().all(|c| c.is_ascii_digit()); if kind == "qr" { let ecc = match f["ecc"].as_str().unwrap_or("M") { "L" => "L", "Q" => "Q", "H" => "H", _ => "M", }; let u = f["magnification"].as_i64().unwrap_or(6).clamp(1, 32); o.s(&format!("{} QR {} {} M 2 U {}\r\n{}A,{}\r\nENDQR\r\n", cmd, x, y, u, ecc, data)); continue; } let ty = match kind { "code128" => "128", "code39" => "39", "ean13" if digits && (data.len() == 12 || data.len() == 13) => "EAN13", "upca" if digits && (data.len() == 11 || data.len() == 12) => "UPCA", "itf" if digits && data.len() % 2 == 0 => "I2OF5", "ean13" | "upca" | "itf" => return Err(format!("{}: {:?} has the wrong digits", kind, data)), other => return Err(format!("unknown barcode {:?}: code128, code39, ean13, upca, itf or qr", other)), }; let width = f["module"].as_i64().unwrap_or(2).clamp(1, 10); // Ratio code 1 is 2.0:1 (used by Code 39 and ITF; Code 128 and EAN ignore it). let ratio = f["ratio"].as_i64().unwrap_or(1); let h = d(&f["height"], 12.0).max(1); let readable = f["readable"] != false; if readable { o.s("BARCODE-TEXT 7 0 5\r\n"); } o.s(&format!("{} {} {} {} {} {} {} {}\r\n", cmd, ty, width, ratio, h, x, y, data)); if readable { o.s("BARCODE-TEXT OFF\r\n"); } } else if f["box"] == true { let t = d(&f["thickness"], 0.3).max(1); o.s(&format!("BOX {} {} {} {} {}\r\n", x, y, x + d(&f["width"], 10.0), y + d(&f["height"], 10.0), t)); } else if f["line"] == true || f["inverse"] == true { let t = d(&f["thickness"], 0.3).max(1); let cmd = if f["inverse"] == true { "INVERSE-LINE" } else { "LINE" }; if f["vertical"] == true { o.s(&format!("{} {} {} {} {} {}\r\n", cmd, x, y, x, y + d(&f["height"], 10.0), t)); } else { // An inverse line as thick as a text line turns that text white on black. o.s(&format!("{} {} {} {} {} {}\r\n", cmd, x, y, x + d(&f["width"], 10.0), y, t)); } } else if let Some(path) = f["image"].as_str() { let w = if f["width"].is_null() { None } else { Some(d(&f["width"], 0.0) as u32) }; let (pw, ph, rows) = bitmap(path, w, f["threshold"].as_u64().unwrap_or(128).clamp(1, 255) as u8, f["dither"] == true)?; let (bpr, data) = pack_rows(pw, &rows, true); let hex: String = data.iter().map(|b| format!("{:02X}", b)).collect(); o.s(&format!("EG {} {} {} {} ", bpr, ph, x, y)); o.bytes.extend_from_slice(hex.as_bytes()); o.note(&format!("<{} hex digits>", hex.len())); o.s("\r\n"); } else { return Err(format!("a field is text, barcode, box, line, inverse, image or raw: {}", f)); } } match options["media"].as_str().unwrap_or("gap") { "gap" => o.s("GAP-SENSE\r\nFORM\r\n"), "mark" | "bar" => o.s("BAR-SENSE\r\nFORM\r\n"), "continuous" | "receipt" => {} other => return Err(format!("media {:?}: gap, mark or continuous", other)), } o.s("PRINT\r\n"); Ok(o)}/// A label as CPCL, written for people (pictures by their size). Each field is a map at `x`, `y` in millimetres from the top left (or `units: "dots"`):/// `{ text (ASCII), size: 3 (font 7 magnified to it) or font: 0-7 with font_size, align: "center" (with width), rotate: 90 }`,/// `{ barcode: "code128" | "code39" | "ean13" | "upca" | "itf" | "qr", data, height, module, ratio, readable, ecc, magnification }`,/// `{ box: true, width, height, thickness }`, `{ line: true, width, thickness, vertical }`, `{ inverse: true, width, thickness }` (white on black over what is there), `{ image: "logo.png", width }` or `{ raw: "..." }`./// `options`: `{ dpi: 203, width, height (the label or receipt's length), quantity, speed: 0-5, contrast: 0-3, media: "gap" | "mark" | "continuous", journal }`.pub fn cpcl_label(fields: Vec<serde_json::Value>, options: serde_json::Value) -> Result<String, String> { Ok(build(&fields, &options)?.view())}/// The label's bytes in base64.pub fn cpcl_job(fields: Vec<serde_json::Value>, options: serde_json::Value) -> Result<String, String> { Ok(b64(&build(&fields, &options)?.bytes))}/// Writes the label to a file or a device (a Bluetooth serial port such as `/dev/rfcomm0`). Gives the bytes written.pub fn cpcl_write(fields: Vec<serde_json::Value>, options: serde_json::Value, path: &str) -> Result<i64, String> { write_bytes(&build(&fields, &options)?.bytes, path)}/// Sends the label to a mobile printer over the network (`host:6101` for most Zebra mobile printers, 9100 when no port is written). Gives the bytes sent.pub fn cpcl_send(fields: Vec<serde_json::Value>, options: serde_json::Value, host: &str, timeout_ms: i64) -> Result<i64, String> { send_bytes(&build(&fields, &options)?.bytes, host, timeout_ms)}// ---- Shared by the printer plugins: the job's bytes and a readable copy, pictures as bits, the network./// A job's bytes, and the same job written for people: control bytes as `<ESC>`, graphics as `<N bytes>`.struct Out { bytes: Vec<u8>, text: String,}fn control_name(c: u8) -> String { match c { 0x00 => "<NUL>".into(), 0x02 => "<STX>".into(), 0x03 => "<ETX>".into(), 0x0a => "\n".into(), 0x0c => "<FF>".into(), 0x0d => "<CR>".into(), 0x17 => "<ETB>".into(), 0x18 => "<CAN>".into(), 0x1b => "<ESC>".into(), 0x1e => "<RS>".into(), c if c < 0x20 || c == 0x7f => format!("<{:02X}>", c), c => (c as char).to_string(), }}impl Out { fn new() -> Out { Out { bytes: vec![], text: String::new() } } /// Command bytes, shown as they are with control bytes named. fn b(&mut self, data: &[u8]) { self.bytes.extend_from_slice(data); for c in data { self.text.push_str(&control_name(*c)); } } /// ASCII command text. fn s(&mut self, s: &str) { self.b(s.as_bytes()); } /// Text already encoded for the printer (`enc`), shown as written. fn t(&mut self, shown: &str, enc: &[u8]) { self.bytes.extend_from_slice(enc); for c in shown.chars() { if (c as u32) < 0x20 { self.text.push_str(&control_name(c as u8)); } else { self.text.push(c); } } } /// Text for the readable copy only (a line break between commands), not sent. fn note(&mut self, s: &str) { self.text.push_str(s); } /// The job for people: CR LF line ends shown as plain line breaks. fn view(&self) -> String { self.text.replace("<CR>\n", "\n") } /// Binary data (a picture), shown by its size. fn blob(&mut self, data: &[u8]) { self.bytes.extend_from_slice(data); self.text.push_str(&format!("<{} bytes>", data.len())); }}/// Dots per millimetre for a resolution in dpi.fn dots_per_mm(dpi: i64) -> f64 { dpi.clamp(100, 1200) as f64 / 25.4}/// A length given in `units` ("mm", the default, "in" or "dots") as dots.fn to_dots(v: &Value, default: f64, dpmm: f64, units: &str) -> i64 { let x = v.as_f64().unwrap_or(default); let d = match units { "dots" => x, "in" | "inch" | "inches" => x * 25.4 * dpmm, _ => x * dpmm, }; d.round().max(0.0) as i64}/// A picture as rows of bits, true for black: scaled to `width` dots when given, dithered or cut at a threshold, transparency as white.fn bitmap(path: &str, width: Option<u32>, threshold: u8, dither: bool) -> Result<(usize, usize, Vec<Vec<bool>>), String> { let img = image::open(path).map_err(|e| format!("{}: {}", path, e))?; let img = match width { Some(w) if w > 0 && w != img.width() => { let h = ((img.height() as f64) * (w as f64) / (img.width() as f64)).round().max(1.0) as u32; img.resize_exact(w, h, image::imageops::FilterType::Triangle) } _ => img, }; let rgba = img.to_rgba8(); let (w, h) = (rgba.width() as usize, rgba.height() as usize); if w * h > 8_000_000 { return Err("the picture is over 8 million dots: give a width".into()); } let mut lum: Vec<f32> = rgba .pixels() .map(|p| { let a = p[3] as f32 / 255.0; (0.299 * p[0] as f32 + 0.587 * p[1] as f32 + 0.114 * p[2] as f32) * a + 255.0 * (1.0 - a) }) .collect(); let mut rows = vec![vec![false; w]; h]; for y in 0..h { for x in 0..w { let old = lum[y * w + x]; let black = old < threshold as f32; rows[y][x] = black; if dither { let err = old - if black { 0.0 } else { 255.0 }; for (dx, dy, f) in [(1isize, 0usize, 7.0f32 / 16.0), (-1, 1, 3.0 / 16.0), (0, 1, 5.0 / 16.0), (1, 1, 1.0 / 16.0)] { let nx = x as isize + dx; if nx >= 0 && (nx as usize) < w && y + dy < h { lum[(y + dy) * w + nx as usize] += err * f; } } } } } Ok((w, h, rows))}/// Rows of bits packed 8 dots to a byte, the first dot in the high bit; `black_is_one` false for printers where 0 prints.fn pack_rows(w: usize, rows: &[Vec<bool>], black_is_one: bool) -> (usize, Vec<u8>) { let bpr = (w + 7) / 8; let mut out = Vec::with_capacity(bpr * rows.len()); for r in rows { for b in 0..bpr { let mut byte = 0u8; for bit in 0..8 { let x = b * 8 + bit; let black = x < w && r[x]; if black == black_is_one { byte |= 0x80 >> bit; } } out.push(byte); } } (bpr, out)}/// `host`, `host:port` or `[v6]:port` as an address; `port` when none is written.fn printer_addr(host: &str, port: u16) -> Result<std::net::SocketAddr, String> { use std::net::ToSocketAddrs; let h = host.trim(); let with_port = if h.starts_with('[') { if h.contains("]:") { h.to_string() } else { format!("{}:{}", h, port) } } else if h.matches(':').count() == 1 { h.to_string() } else if h.contains(':') { format!("[{}]:{}", h, port) } else { format!("{}:{}", h, port) }; with_port.to_socket_addrs().map_err(|e| format!("{}: {}", host, e))?.next().ok_or(format!("{} has no address", host))}fn connect(host: &str, timeout_ms: i64) -> Result<std::net::TcpStream, String> { let t = std::time::Duration::from_millis(timeout_ms.clamp(100, 120_000) as u64); let addr = printer_addr(host, 9100)?; let s = std::net::TcpStream::connect_timeout(&addr, t).map_err(|e| format!("cannot reach the printer at {}: {}", addr, e))?; s.set_write_timeout(Some(t)).map_err(|e| e.to_string())?; s.set_read_timeout(Some(t)).map_err(|e| e.to_string())?; Ok(s)}/// Sends bytes to a printer's raw port and closes it.fn send_bytes(bytes: &[u8], host: &str, timeout_ms: i64) -> Result<i64, String> { use std::io::Write; let mut s = connect(host, timeout_ms)?; s.write_all(bytes).map_err(|e| format!("sending to the printer: {}", e))?; s.flush().map_err(|e| e.to_string())?; Ok(bytes.len() as i64)}/// Writes bytes to a file or a device (`/dev/usb/lp0`), folders made for a file.fn write_bytes(bytes: &[u8], path: &str) -> Result<i64, String> { use std::io::Write; let p = std::path::Path::new(path); let device = path.starts_with("/dev/"); if !device { if let Some(dir) = p.parent() { if !dir.as_os_str().is_empty() { std::fs::create_dir_all(dir).map_err(|e| e.to_string())?; } } } let mut f = std::fs::OpenOptions::new().write(true).create(!device).truncate(!device).open(p).map_err(|e| format!("{}: {}", path, e))?; f.write_all(bytes).map_err(|e| format!("{}: {}", path, e))?; Ok(bytes.len() as i64)}fn b64(bytes: &[u8]) -> String { use base64::Engine; base64::engine::general_purpose::STANDARD.encode(bytes)}fn text_of(v: &Value) -> String { match v { Value::String(s) => s.clone(), Value::Null => String::new(), other => other.to_string(), }}Related
dpl.qwer · 1.0.0Honeywell and Datamax-O'Neil DPL labels from fields placed in millimetres from the top left: resident fonts, Code 128, EAN-13, QR and Data Matrix, lines and boxes, heat, speed and quantity, sent to port 9100.7 views · 9 downloadsEPL2 labels epl.qwer · 1.0.0Zebra and Eltron EPL2 labels from fields in millimetres: text in the resident fonts, Code 128, EAN-13, Code 39 and QR barcodes, lines, boxes and pictures, with label size, gap, speed and copies, sent to port 9100.6 views · 5 downloadsGodex EZPL labels ezpl.qwer · 1.0.0Godex EZPL labels for G500, RT200 and other Godex printers: text in the resident fonts, Code 128, EAN-13, Code 39 and QR codes, lines and boxes, label size, darkness, speed and copies, sent to port 9100.6 views · 8 downloadsIntermec IPL labels ipl.qwer · 1.0.0Intermec IPL labels for EasyCoder, PM4i and PF2i printers: a format saved with its text, Code 128, SSCC, UPC/EAN, QR and Data Matrix fields, lines and boxes, filled with data for each print, sent to port 9100.7 views · 7 downloadsLabel sheets label_sheets.qwer · 1.0.0Labels on A4 and Letter sheets (Avery L7160, L7163, L7651, 5160 and others, or your own measurements) as a PDF: addresses and tags with text fitted to each label, Code 128 and QR codes, a start position for part-used sheets.8 views · 6 downloadsSATO SBPL labels sbpl.qwer · 1.0.0SATO SBPL labels for CL4NX, CT4-LX and other SATO printers: text in the built-in fonts, Code 128 and GS1-128 with the subsets chosen, EAN-13, Code 39 and QR, lines and frames, speed, darkness and quantity, sent to port 9100.8 views · 7 downloadsThread 0 posts
On CPCL mobile printers: questions, tips, corrections, and code that uses it.
No posts yet. The first one opens the thread.