Printing subsystem
Direct raw-byte printing to POS thermal printers over USB-serial, USB printer class, and Bluetooth SPP — without submitting jobs through the OS print spooler (Windows) or CUPS (Linux).
---
Goals
1. Discover connected POS-capable devices 2. Let the user pick a printer in a dialog 3. Generate ESC/POS bytes from the document AST (after parameter substitution) 4. Write bytes to the device and confirm completion (best-effort)
---
Protocol: ESC/POS
Target Epson ESC/POS compatible printers (majority of 58 mm / 80 mm thermal printers).
Supported in v1
| Feature | Command family |
|---|---|
| Text, bold, size | ESC !, ESC E, GS ! |
| Alignment | ESC a |
| Line feed | LF, ESC d |
| Partial cut | GS V |
| Barcode | GS k, GS h, GS H |
| QR Code | GS ( k |
| Raster image | GS v 0 |
| Initialize | ESC @ |
Printer initialization sequence
Every print job starts with:
ESC @ ; reset printer
ESC t n ; select code page (from metadata.codepage)
; ... document bytes ...
[optional feed + cut]
---
Transport layers
┌─────────────────┐
│ PrintPipeline │
└────────┬────────┘
│
┌──────────────┼──────────────┐
▼ ▼ ▼
SerialTransport UsbTransport BtTransport
│ │ │
serialport nusb / serialport
usbprint (RFCOMM port)
Transport trait
trait PrinterTransport {
fn open(&mut self) -> Result<()>;
fn write(&mut self, data: &[u8]) -> Result<()>;
fn flush(&mut self) -> Result<()>;
fn close(&mut self) -> Result<()>;
}
Phase rollout
| Phase | Transport | Discovery |
|---|---|---|
| MVP | USB-serial (CDC, CH340, FTDI, Prolific) | serialport::available_ports() |
| v1 | USB printer class (bulk OUT) | USB VID/PID filter + interface scan |
| v1.1 | Bluetooth Classic SPP | Paired COM / rfcomm ports |
---
Device discovery
USB-serial (MVP)
Use serialport crate:
// Pseudocode
for port in serialport::available_ports()? {
match port.port_type {
SerialPortType::UsbPort(info) => {
// Filter: known POS vendor IDs optional
// Include all USB-serial for user selection
}
_ => {}
}
}
Linux: User must be in dialout group. Show actionable error if permission denied.
Windows: COM ports appear after driver install (usually automatic for CDC).
USB printer class (v1)
- Linux:
nusb— find interface class 7 (printer), bulk OUT endpoint - Windows:
escposusbprintfeature — open via\\.\USBPRINT\...without replacing system driver
Filter candidates by:
- Interface class 7
- Optional known VID list (Epson
0x04b8, Star, Bixolon, etc.)
Bluetooth SPP (v1.1)
- Windows: Enumerate COM ports associated with paired Bluetooth devices
- Linux:
/dev/rfcomm*or bind via BlueZ; may requirebluetoothgroup
Discovery is harder than USB; show paired devices and let user refresh after OS pairing.
---
Printer picker UI
┌─────────────────────────────────────────┐
│ Select printer │
├─────────────────────────────────────────┤
│ ○ COM3 — USB Serial (VID:04b8 PID:0e15)│
│ ○ /dev/ttyUSB0 — CH340 │
│ ○ \\.\USBPRINT\epson-tm-t20 │
│ │
│ [ Refresh ] [ Print ] │
└─────────────────────────────────────────┘
Each PrinterDevice has:
| Field | Example |
|---|---|
id | serial:COM3 or usb:04b8:0e15:iface0 |
display_name | Epson TM-T20 (COM3) |
transport | Serial { port: "COM3", baud: 9600 } |
last_used | timestamp for default selection |
Default baud: 9600 or 115200 — probe common rates or expose advanced setting if open fails.
---
Print pipeline
Document body (DSL)
│
▼
Parse → AST
│
▼
Collect parameters (UI dialog)
│
▼
Substitute params
│
▼
ESC/POS encoder (escpos crate)
│
▼
Transport.write(all bytes)
│
▼
Optional: read status (paper out, cover open)
Error handling
| Error | User message |
|---|---|
| Port busy | “Printer in use by another application” |
| Permission denied | “Add user to dialout group” (Linux) |
| Write timeout | “Printer not responding — check power and cable” |
| Paper out (if status read) | “Paper out” |
---
Parameter integration at print
1. collect_parameters(body) → ["DocumentNumber", "GrandTotal", ...] 2. Modal collects values; same name used once 3. Store in last_print_params for next run 4. substitute(body, params) then encode
Barcode/QR validation:
- EAN13 must be 12–13 digits after substitution
- Show validation errors before opening printer
---
Images on printer
1. Load image from path (or fail if param path invalid) 2. Convert to grayscale → threshold/dither 3. Scale to target width (dots), respecting page_width_mm 4. Emit GS v 0 raster command
Large images slow printing; warn if > 50% of paper width × tall.
---
Preview width vs print width
| Setting | Preview | |
|---|---|---|
autoscale | Scale preview to panel width | Always full paper width |
fixed | Render at exact mm width | Full paper width |
Print always uses physical paper width from metadata; preview is a visual aid.
---
Security considerations
- Raw USB access: only write to user-selected device; no automatic writes
- Path traversal: image paths must resolve under
.posdirectory or explicit absolute paths user provided - Bluetooth: only paired devices user selects
---
Testing without hardware
| Method | Use |
|---|---|
FileTransport | Write .bin ESC/POS to disk for hex inspection |
| ESC/POS emulator | escpos-printer-emulator / serial port loopback |
| Snapshot tests | Compare generated bytes to golden files |
---
Dependencies (Rust)
escpos = { version = "...", features = ["barcodes", "codes_2d", "graphics", "serial_port", "native_usb", "usbprint"] }
serialport = "4"
nusb = "0.2" # optional USB class
image = "0.25"
Platform-specific features enabled per target in build.rs or Cargo features.
---
Open questions (resolve during implementation)
1. Baud rate autodetect — try 9600, 19200, 115200 on failure? 2. Status polling — DLE EOT real-time status vs fire-and-forget? 3. Concurrent prints — mutex per printer ID 4. Network printers — add TCP 9100 in v2?
Source
| 1 | # Printing subsystem |
| 2 | |
| 3 | Direct raw-byte printing to POS thermal printers over USB-serial, USB printer class, and Bluetooth SPP — without submitting jobs through the OS print spooler (Windows) or CUPS (Linux). |
| 4 | |
| 5 | --- |
| 6 | |
| 7 | ## Goals |
| 8 | |
| 9 | 1. Discover connected POS-capable devices |
| 10 | 2. Let the user pick a printer in a dialog |
| 11 | 3. Generate ESC/POS bytes from the document AST (after parameter substitution) |
| 12 | 4. Write bytes to the device and confirm completion (best-effort) |
| 13 | |
| 14 | --- |
| 15 | |
| 16 | ## Protocol: ESC/POS |
| 17 | |
| 18 | Target **Epson ESC/POS** compatible printers (majority of 58 mm / 80 mm thermal printers). |
| 19 | |
| 20 | ### Supported in v1 |
| 21 | |
| 22 | | Feature | Command family | |
| 23 | |---------|----------------| |
| 24 | | Text, bold, size | ESC !, ESC E, GS ! | |
| 25 | | Alignment | ESC a | |
| 26 | | Line feed | LF, ESC d | |
| 27 | | Partial cut | GS V | |
| 28 | | Barcode | GS k, GS h, GS H | |
| 29 | | QR Code | GS ( k | |
| 30 | | Raster image | GS v 0 | |
| 31 | | Initialize | ESC @ | |
| 32 | |
| 33 | ### Printer initialization sequence |
| 34 | |
| 35 | Every print job starts with: |
| 36 | |
| 37 | ``` |
| 38 | ESC @ ; reset printer |
| 39 | ESC t n ; select code page (from metadata.codepage) |
| 40 | ; ... document bytes ... |
| 41 | [optional feed + cut] |
| 42 | ``` |
| 43 | |
| 44 | --- |
| 45 | |
| 46 | ## Transport layers |
| 47 | |
| 48 | ``` |
| 49 | ┌─────────────────┐ |
| 50 | │ PrintPipeline │ |
| 51 | └────────┬────────┘ |
| 52 | │ |
| 53 | ┌──────────────┼──────────────┐ |
| 54 | ▼ ▼ ▼ |
| 55 | SerialTransport UsbTransport BtTransport |
| 56 | │ │ │ |
| 57 | serialport nusb / serialport |
| 58 | usbprint (RFCOMM port) |
| 59 | ``` |
| 60 | |
| 61 | ### Transport trait |
| 62 | |
| 63 | ```rust |
| 64 | trait PrinterTransport { |
| 65 | fn open(&mut self) -> Result<()>; |
| 66 | fn write(&mut self, data: &[u8]) -> Result<()>; |
| 67 | fn flush(&mut self) -> Result<()>; |
| 68 | fn close(&mut self) -> Result<()>; |
| 69 | } |
| 70 | ``` |
| 71 | |
| 72 | ### Phase rollout |
| 73 | |
| 74 | | Phase | Transport | Discovery | |
| 75 | |-------|-----------|-----------| |
| 76 | | **MVP** | USB-serial (CDC, CH340, FTDI, Prolific) | `serialport::available_ports()` | |
| 77 | | **v1** | USB printer class (bulk OUT) | USB VID/PID filter + interface scan | |
| 78 | | **v1.1** | Bluetooth Classic SPP | Paired COM / rfcomm ports | |
| 79 | |
| 80 | --- |
| 81 | |
| 82 | ## Device discovery |
| 83 | |
| 84 | ### USB-serial (MVP) |
| 85 | |
| 86 | Use `serialport` crate: |
| 87 | |
| 88 | ```rust |
| 89 | // Pseudocode |
| 90 | for port in serialport::available_ports()? { |
| 91 | match port.port_type { |
| 92 | SerialPortType::UsbPort(info) => { |
| 93 | // Filter: known POS vendor IDs optional |
| 94 | // Include all USB-serial for user selection |
| 95 | } |
| 96 | _ => {} |
| 97 | } |
| 98 | } |
| 99 | ``` |
| 100 | |
| 101 | **Linux:** User must be in `dialout` group. Show actionable error if permission denied. |
| 102 | |
| 103 | **Windows:** COM ports appear after driver install (usually automatic for CDC). |
| 104 | |
| 105 | ### USB printer class (v1) |
| 106 | |
| 107 | - **Linux:** `nusb` — find interface class 7 (printer), bulk OUT endpoint |
| 108 | - **Windows:** `escpos` `usbprint` feature — open via `\\.\USBPRINT\...` without replacing system driver |
| 109 | |
| 110 | Filter candidates by: |
| 111 | |
| 112 | - Interface class 7 |
| 113 | - Optional known VID list (Epson `0x04b8`, Star, Bixolon, etc.) |
| 114 | |
| 115 | ### Bluetooth SPP (v1.1) |
| 116 | |
| 117 | - **Windows:** Enumerate COM ports associated with paired Bluetooth devices |
| 118 | - **Linux:** `/dev/rfcomm*` or bind via BlueZ; may require `bluetooth` group |
| 119 | |
| 120 | Discovery is harder than USB; show paired devices and let user refresh after OS pairing. |
| 121 | |
| 122 | --- |
| 123 | |
| 124 | ## Printer picker UI |
| 125 | |
| 126 | ``` |
| 127 | ┌─────────────────────────────────────────┐ |
| 128 | │ Select printer │ |
| 129 | ├─────────────────────────────────────────┤ |
| 130 | │ ○ COM3 — USB Serial (VID:04b8 PID:0e15)│ |
| 131 | │ ○ /dev/ttyUSB0 — CH340 │ |
| 132 | │ ○ \\.\USBPRINT\epson-tm-t20 │ |
| 133 | │ │ |
| 134 | │ [ Refresh ] [ Print ] │ |
| 135 | └─────────────────────────────────────────┘ |
| 136 | ``` |
| 137 | |
| 138 | Each `PrinterDevice` has: |
| 139 | |
| 140 | | Field | Example | |
| 141 | |-------|---------| |
| 142 | | `id` | `serial:COM3` or `usb:04b8:0e15:iface0` | |
| 143 | | `display_name` | `Epson TM-T20 (COM3)` | |
| 144 | | `transport` | `Serial { port: "COM3", baud: 9600 }` | |
| 145 | | `last_used` | timestamp for default selection | |
| 146 | |
| 147 | **Default baud:** 9600 or 115200 — probe common rates or expose advanced setting if open fails. |
| 148 | |
| 149 | --- |
| 150 | |
| 151 | ## Print pipeline |
| 152 | |
| 153 | ``` |
| 154 | Document body (DSL) |
| 155 | │ |
| 156 | ▼ |
| 157 | Parse → AST |
| 158 | │ |
| 159 | ▼ |
| 160 | Collect parameters (UI dialog) |
| 161 | │ |
| 162 | ▼ |
| 163 | Substitute params |
| 164 | │ |
| 165 | ▼ |
| 166 | ESC/POS encoder (escpos crate) |
| 167 | │ |
| 168 | ▼ |
| 169 | Transport.write(all bytes) |
| 170 | │ |
| 171 | ▼ |
| 172 | Optional: read status (paper out, cover open) |
| 173 | ``` |
| 174 | |
| 175 | ### Error handling |
| 176 | |
| 177 | | Error | User message | |
| 178 | |-------|--------------| |
| 179 | | Port busy | “Printer in use by another application” | |
| 180 | | Permission denied | “Add user to dialout group” (Linux) | |
| 181 | | Write timeout | “Printer not responding — check power and cable” | |
| 182 | | Paper out (if status read) | “Paper out” | |
| 183 | |
| 184 | --- |
| 185 | |
| 186 | ## Parameter integration at print |
| 187 | |
| 188 | 1. `collect_parameters(body)` → `["DocumentNumber", "GrandTotal", ...]` |
| 189 | 2. Modal collects values; same name used once |
| 190 | 3. Store in `last_print_params` for next run |
| 191 | 4. `substitute(body, params)` then encode |
| 192 | |
| 193 | Barcode/QR validation: |
| 194 | |
| 195 | - EAN13 must be 12–13 digits after substitution |
| 196 | - Show validation errors before opening printer |
| 197 | |
| 198 | --- |
| 199 | |
| 200 | ## Images on printer |
| 201 | |
| 202 | 1. Load image from path (or fail if param path invalid) |
| 203 | 2. Convert to grayscale → threshold/dither |
| 204 | 3. Scale to target width (dots), respecting `page_width_mm` |
| 205 | 4. Emit GS v 0 raster command |
| 206 | |
| 207 | Large images slow printing; warn if > 50% of paper width × tall. |
| 208 | |
| 209 | --- |
| 210 | |
| 211 | ## Preview width vs print width |
| 212 | |
| 213 | | Setting | Preview | Print | |
| 214 | |---------|---------|-------| |
| 215 | | `autoscale` | Scale preview to panel width | Always full paper width | |
| 216 | | `fixed` | Render at exact mm width | Full paper width | |
| 217 | |
| 218 | Print always uses physical paper width from metadata; preview is a visual aid. |
| 219 | |
| 220 | --- |
| 221 | |
| 222 | ## Security considerations |
| 223 | |
| 224 | - **Raw USB access:** only write to user-selected device; no automatic writes |
| 225 | - **Path traversal:** image paths must resolve under `.pos` directory or explicit absolute paths user provided |
| 226 | - **Bluetooth:** only paired devices user selects |
| 227 | |
| 228 | --- |
| 229 | |
| 230 | ## Testing without hardware |
| 231 | |
| 232 | | Method | Use | |
| 233 | |--------|-----| |
| 234 | | `FileTransport` | Write `.bin` ESC/POS to disk for hex inspection | |
| 235 | | ESC/POS emulator | [escpos-printer-emulator](https://github.com) / serial port loopback | |
| 236 | | Snapshot tests | Compare generated bytes to golden files | |
| 237 | |
| 238 | --- |
| 239 | |
| 240 | ## Dependencies (Rust) |
| 241 | |
| 242 | ```toml |
| 243 | escpos = { version = "...", features = ["barcodes", "codes_2d", "graphics", "serial_port", "native_usb", "usbprint"] } |
| 244 | serialport = "4" |
| 245 | nusb = "0.2" # optional USB class |
| 246 | image = "0.25" |
| 247 | ``` |
| 248 | |
| 249 | Platform-specific features enabled per target in `build.rs` or Cargo features. |
| 250 | |
| 251 | --- |
| 252 | |
| 253 | ## Open questions (resolve during implementation) |
| 254 | |
| 255 | 1. **Baud rate autodetect** — try 9600, 19200, 115200 on failure? |
| 256 | 2. **Status polling** — DLE EOT real-time status vs fire-and-forget? |
| 257 | 3. **Concurrent prints** — mutex per printer ID |
| 258 | 4. **Network printers** — add TCP 9100 in v2? |