# 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

```rust
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:

```rust
// 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:** `escpos` `usbprint` feature — 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 require `bluetooth` group

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 | Print |
|---------|---------|-------|
| `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 `.pos` directory 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](https://github.com) / serial port loopback |
| Snapshot tests | Compare generated bytes to golden files |

---

## Dependencies (Rust)

```toml
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?
