BlueGit

timfa posprint

Files

posprint / docs / PRINTING.md

PRINTING.md

PRINTING.md 6.1 KiB Download Raw

Printing subsystem

Raw ESC/POS output to POS thermal printers via USB printer-class, Windows spooler (Windows), USB-serial, or LAN TCP 9100 (optional).

---

Goals

1. Discover printers (USB-direct, Windows spooler, serial ports, optional LAN TCP 9100) 2. Let the user pick a target in the print dialog 3. Generate ESC/POS bytes from the AST (after parameter substitution) 4. Write bytes to the chosen transport (serial baud is probed; LAN uses TCP)

---

Protocol: ESC/POS

Target Epson ESC/POS compatible printers (58 mm / 80 mm thermal).

Implemented commands

FeatureESC/POSSource
InitializeESC @escpos.rs
Code pageESC t 0 (CP437)Always CP437 today; metadata field reserved
BoldESC EHeadings level 2 only
Double sizeGS !Heading level 1
AlignmentESC aParagraphs, images, barcodes, QR
Line feedLF (text lines), ESC d (@feed / blank lines)Text ends with LF; blank/@feed use ESC d
Raster flushLF after GS v 0Ensures spacing after images/barcodes/QR rasters
List bullet* top-level, - nested- item / - nested; hanging wrap
Inline checkboxASCII [ ] / [x][] / [x] / $[Name] — same font as text
Partial cutGS V 66 0@cut in template only
BarcodeGS H, GS h, GS w, GS kNative: HRI off by default (GS H 0); show_text=true → GS H 2. Raster via GS v 0
QR CodeGS ( kModel 2; or raster GS v 0
Raster imageGS v 0@image / raster barcode / raster QR

Encoder: EscPosEncoder in src/escpos.rs — not the escpos crates.io package.

---

Transport (implemented)

Print button
     │
     ▼
substitute_document()
     │
     ▼
EscPosEncoder::encode_document()
     │
     ▼
open_printer(target)   # USB-direct | Win spooler | serial | network TCP
     │
     ▼
print_bytes() → write_all + flush

PrinterTransport trait

pub trait PrinterTransport {
    fn write_all(&mut self, data: &[u8]) -> io::Result<()>;
    fn flush(&mut self) -> io::Result<()>;
}
TypeRole
USB-direct (rusb)USB printer-class bulk OUT (usb_direct.rs)
Windows spoolerRaw jobs via Win32 spooler (win_spool.rs, Windows only)
SerialTransportUSB-serial / CDC ports via serialport
NetworkTransportRaw ESC/POS over TCP (default port 9100, network.rs) — not CUPS/IPP
MockTransportTests — records bytes in written vec

Discovery

list_local_printers() returns, in order:

1. USB printer-class devices (usb_direct) 2. Windows spooler queues (Windows) 3. USB-serial ports only (SerialPortType::UsbPort — skips empty PCI/ttyS* ports common on Linux)

When LAN printers are enabled in Settings (lan_printers_enabled, default off), the print dialog additionally:

1. Validates the durable LAN cache (lan_printer_cache in config) with short TCP probes and shows hits immediately with local devices 2. Scans local IPv4 subnets for open TCP 9100 in the background, merges results, and updates the cache

Serial baud rates

SerialTransport::open tries, in order:

115200, 9600, 19200, 38400, 57600, 4800

PrinterDevice

FieldExample
idserial:COM3, usb:04b8:0e15:…, spool:POS-58, net:192.168.1.50:9100
display_nameHuman-readable label
targetSerial / UsbDirect / WinSpooler / Network

---

Print dialog (UI)

  • One field per unique ${Parameter}.
  • Printer list: USB printer-class, Windows spooler (Windows), connected USB-serial devices, and (if enabled) LAN TCP 9100 printers (Refresh button). Empty motherboard serial ports are omitted; use manual entry for those.
  • Print sits next to Refresh; close the dialog with the window ✕.
  • The printer list uses a fixed-height scroll area so long lists stay usable.
  • Optional manual serial port / queue name / LAN host or host:9100.
  • While open, the main Design UI is disabled (including editor autocomplete).
  • Errors shown inline (parse, open, write, barcode validation).

---

Print pipeline

Document body (DSL)
        │
        ▼
   parse() → Document
        │
        ▼
 collect_parameters() → UI dialog / CLI --set
     │  (${Name} text fields, $[Name] checkboxes)
        │
        ▼
 substitute_document()
        │
        ▼
 EscPosEncoder (in-tree)
        │
        ▼
 open_printer → write_all

Error handling

ConditionBehaviour
Parse errorBlock print; show in toolbar
Open failureMessage in dialog / CLI
Write failureMessage in dialog / CLI
Invalid barcode dataError before write
Linux serial permissionJoin dialout group

Status polling (paper out, cover open) is not implemented.

---

Images and rasters

1. If the path is http:// or https://, download (timeout + size limit, process cache); otherwise resolve relative to the .pos file (or absolute). 2. Decode with image, convert to luma, scale to printable width (chars_per_line × 12 dots). 3. Threshold to 1-bit; emit GS v 0 (1D 76 30 00 + width/height LE + bitmap). 4. Append LF after the raster so following content (including blank-line feeds) advances correctly.

Preview draws the same bitmaps on the canvas (scaled for screen).

posprint:// print links embed the .pos JSON in the URL; use remote @image https://… for logos. See POSPRINT-URL.md.

---

Testing without hardware

MethodLocation
MockTransportprint/mod.rs tests
ESC/POS byte checksescpos.rs tests
cargo test~100 unit tests; no printer required

---

Dependencies

serialport = "4"
rusb = "0.9"
image = { features = ["png", "jpeg", "gif", "bmp"] }

On Windows, spooler access uses Win32 APIs (winreg / system libs as needed). No escpos or nusb crates.

---

Planned (not implemented)

FeatureNotes
Bluetooth SPPAfter OS pairing; evaluate already-connected devices only
Printer status readDLE EOT
Source
1# Printing subsystem
2
3Raw ESC/POS output to POS thermal printers via **USB printer-class**, **Windows spooler** (Windows), **USB-serial**, or **LAN TCP 9100** (optional).
4
5---
6
7## Goals
8
91. Discover printers (USB-direct, Windows spooler, serial ports, optional LAN TCP 9100)
102. Let the user pick a target in the print dialog
113. Generate ESC/POS bytes from the AST (after parameter substitution)
124. Write bytes to the chosen transport (serial baud is probed; LAN uses TCP)
13
14---
15
16## Protocol: ESC/POS
17
18Target **Epson ESC/POS** compatible printers (58 mm / 80 mm thermal).
19
20### Implemented commands
21
22| Feature | ESC/POS | Source |
23|---------|---------|--------|
24| Initialize | ESC @ | `escpos.rs` |
25| Code page | ESC t 0 (CP437) | Always CP437 today; metadata field reserved |
26| Bold | ESC E | Headings level 2 only |
27| Double size | GS ! | Heading level 1 |
28| Alignment | ESC a | Paragraphs, images, barcodes, QR |
29| Line feed | LF (text lines), ESC d (`@feed` / blank lines) | Text ends with LF; blank/`@feed` use ESC d |
30| Raster flush | LF after GS v 0 | Ensures spacing after images/barcodes/QR rasters |
31| List bullet | `*` top-level, `-` nested | `- item` / ` - nested`; hanging wrap |
32| Inline checkbox | ASCII `[ ]` / `[x]` | `[]` / `[x]` / `$[Name]` — same font as text |
33| Partial cut | GS V 66 0 | `@cut` in template only |
34| Barcode | GS H, GS h, GS w, GS k | Native: HRI off by default (`GS H 0`); `show_text=true` → `GS H 2`. Raster via GS v 0 |
35| QR Code | GS ( k | Model 2; or raster GS v 0 |
36| Raster image | GS v 0 | `@image` / raster barcode / raster QR |
37
38Encoder: `EscPosEncoder` in `src/escpos.rs` — **not** the `escpos` crates.io package.
39
40---
41
42## Transport (implemented)
43
44```
45Print button
46 │
47 ▼
48substitute_document()
49 │
50 ▼
51EscPosEncoder::encode_document()
52 │
53 ▼
54open_printer(target) # USB-direct | Win spooler | serial | network TCP
55 │
56 ▼
57print_bytes() → write_all + flush
58```
59
60### `PrinterTransport` trait
61
62```rust
63pub trait PrinterTransport {
64 fn write_all(&mut self, data: &[u8]) -> io::Result<()>;
65 fn flush(&mut self) -> io::Result<()>;
66}
67```
68
69| Type | Role |
70|------|------|
71| USB-direct (`rusb`) | USB printer-class bulk OUT (`usb_direct.rs`) |
72| Windows spooler | Raw jobs via Win32 spooler (`win_spool.rs`, Windows only) |
73| `SerialTransport` | USB-serial / CDC ports via `serialport` |
74| `NetworkTransport` | Raw ESC/POS over TCP (default port **9100**, `network.rs`) — not CUPS/IPP |
75| `MockTransport` | Tests — records bytes in `written` vec |
76
77### Discovery
78
79`list_local_printers()` returns, in order:
80
811. USB printer-class devices (`usb_direct`)
822. Windows spooler queues (Windows)
833. USB-serial ports only (`SerialPortType::UsbPort` — skips empty PCI/`ttyS*` ports common on Linux)
84
85When **LAN printers** are enabled in Settings (`lan_printers_enabled`, default **off**), the print dialog additionally:
86
871. Validates the durable **LAN cache** (`lan_printer_cache` in config) with short TCP probes and shows hits immediately with local devices
882. Scans local IPv4 subnets for open TCP **9100** in the background, merges results, and updates the cache
89
90### Serial baud rates
91
92`SerialTransport::open` tries, in order:
93
94`115200`, `9600`, `19200`, `38400`, `57600`, `4800`
95
96### `PrinterDevice`
97
98| Field | Example |
99|-------|---------|
100| `id` | `serial:COM3`, `usb:04b8:0e15:…`, `spool:POS-58`, `net:192.168.1.50:9100` |
101| `display_name` | Human-readable label |
102| `target` | `Serial` / `UsbDirect` / `WinSpooler` / `Network` |
103
104---
105
106## Print dialog (UI)
107
108- One field per unique `${Parameter}`.
109- Printer list: USB printer-class, Windows spooler (Windows), connected USB-serial devices, and (if enabled) LAN TCP 9100 printers (Refresh button). Empty motherboard serial ports are omitted; use manual entry for those.
110- **Print** sits next to **Refresh**; close the dialog with the window ✕.
111- The printer list uses a fixed-height scroll area so long lists stay usable.
112- Optional manual serial port / queue name / LAN `host` or `host:9100`.
113- While open, the main Design UI is disabled (including editor autocomplete).
114- Errors shown inline (parse, open, write, barcode validation).
115
116---
117
118## Print pipeline
119
120```
121Document body (DSL)
122 │
123 ▼
124 parse() → Document
125 │
126 ▼
127 collect_parameters() → UI dialog / CLI --set
128 │ (${Name} text fields, $[Name] checkboxes)
129 │
130 ▼
131 substitute_document()
132 │
133 ▼
134 EscPosEncoder (in-tree)
135 │
136 ▼
137 open_printer → write_all
138```
139
140### Error handling
141
142| Condition | Behaviour |
143|-----------|-----------|
144| Parse error | Block print; show in toolbar |
145| Open failure | Message in dialog / CLI |
146| Write failure | Message in dialog / CLI |
147| Invalid barcode data | Error before write |
148| Linux serial permission | Join `dialout` group |
149
150Status polling (paper out, cover open) is **not** implemented.
151
152---
153
154## Images and rasters
155
1561. If the path is `http://` or `https://`, download (timeout + size limit, process cache); otherwise resolve relative to the `.pos` file (or absolute).
1572. Decode with `image`, convert to luma, scale to printable width (`chars_per_line × 12` dots).
1583. Threshold to 1-bit; emit `GS v 0` (`1D 76 30 00` + width/height LE + bitmap).
1594. Append **LF** after the raster so following content (including blank-line feeds) advances correctly.
160
161Preview draws the same bitmaps on the canvas (scaled for screen).
162
163`posprint://` print links embed the `.pos` JSON in the URL; use remote `@image https://…` for logos. See [POSPRINT-URL.md](POSPRINT-URL.md).
164
165---
166
167## Testing without hardware
168
169| Method | Location |
170|--------|----------|
171| `MockTransport` | `print/mod.rs` tests |
172| ESC/POS byte checks | `escpos.rs` tests |
173| `cargo test` | ~100 unit tests; no printer required |
174
175---
176
177## Dependencies
178
179```toml
180serialport = "4"
181rusb = "0.9"
182image = { features = ["png", "jpeg", "gif", "bmp"] }
183```
184
185On Windows, spooler access uses Win32 APIs (`winreg` / system libs as needed). No `escpos` or `nusb` crates.
186
187---
188
189## Planned (not implemented)
190
191| Feature | Notes |
192|---------|-------|
193| Bluetooth SPP | After OS pairing; evaluate already-connected devices only |
194| Printer status read | DLE EOT |