BlueGit

timfa posprint

feat: include paired Classic Bluetooth SPP printers in discovery

After OS pairing, Bluetooth SPP serial ports (Windows COM, Linux rfcomm)
show up in Refresh and `posprint list`. Printing still uses SerialTransport.
BLE remains out of scope; empty PCI/ttyS ports stay hidden.

Co-authored-by: tim <tim@timfalken.com>

timfa project_84475926_bot_3b4fb417c41b9b24a7422b6452f025d2 · pushed by timfa

Authored 2026-09-19 · 8 weeks ago

Hash
8b514b7fb40ecd37435a474221326e94774ecb7e
Parent
0b46f1f6
12 files changed +214 −63
.cursor/rules/architecture.mdc +2 −2
@@ -10,7 +10,7 @@ alwaysApply: true
10 10
11 11 - **Rust only** — no TypeScript/JavaScript frontend.
12 12 - **egui / eframe** for UI (`src/app.rs`, `src/main.rs`).
13 - **Printing:** USB printer-class (`rusb`), Windows spooler (Windows), and USB-serial (`serialport`) via `src/print/`.
13 - **Printing:** USB printer-class (`rusb`), Windows spooler (Windows), USB-serial, and OS-paired Classic Bluetooth SPP (`serialport`) via `src/print/`.
14 14
15 15 ## Module responsibilities
16 16
@@ -42,4 +42,4 @@ Do **not** add `escpos`, `nusb`, `tauri`, or a JS toolchain without a deliberate
42 42
43 43 ## Planned features (not in codebase yet)
44 44
45 Bluetooth, network TCP 9100, persisted recent files/parameters, syntax highlighting. Document these only under "Planned" sections — do not implement stubs without a task.
45 BLE, network TCP 9100, persisted recent files/parameters, syntax highlighting. Document these only under "Planned" sections — do not implement stubs without a task. Classic Bluetooth SPP after OS pairing is implemented (no BLE/GATT).
@@ -10,7 +10,7 @@ alwaysApply: true
10
10
11- **Rust only** — no TypeScript/JavaScript frontend.
11- **Rust only** — no TypeScript/JavaScript frontend.
12- **egui / eframe** for UI (`src/app.rs`, `src/main.rs`).
12- **egui / eframe** for UI (`src/app.rs`, `src/main.rs`).
13- **Printing:** USB printer-class (`rusb`), Windows spooler (Windows), and USB-serial (`serialport`) via `src/print/`.
13- **Printing:** USB printer-class (`rusb`), Windows spooler (Windows), USB-serial, and OS-paired Classic Bluetooth SPP (`serialport`) via `src/print/`.
14
14
15## Module responsibilities
15## Module responsibilities
16
16
@@ -42,4 +42,4 @@ Do **not** add `escpos`, `nusb`, `tauri`, or a JS toolchain without a deliberate
42
42
43## Planned features (not in codebase yet)
43## Planned features (not in codebase yet)
44
44
45Bluetooth, network TCP 9100, persisted recent files/parameters, syntax highlighting. Document these only under "Planned" sections — do not implement stubs without a task.
45BLE, network TCP 9100, persisted recent files/parameters, syntax highlighting. Document these only under "Planned" sections — do not implement stubs without a task. Classic Bluetooth SPP after OS pairing is implemented (no BLE/GATT).
.cursor/rules/development.mdc +1 −1
@@ -11,7 +11,7 @@ alwaysApply: true
11 11 - Single language: **Rust** with **egui** (eframe) for the UI.
12 12 - Prefer std library and in-house code. Add a crate only when reimplementing would be unreasonable (e.g. `serialport`, `serde`, `image`, UI framework).
13 13 - ESC/POS encoding lives in `src/escpos.rs` — do not add the `escpos` crates.io package.
14 - Printing: USB printer-class (`rusb`), Windows spooler, and USB-serial (`serialport`). Do not add Bluetooth or network printing until explicitly requested.
14 - Printing: USB printer-class (`rusb`), Windows spooler, USB-serial, and OS-paired Classic Bluetooth SPP (`serialport`). Do not add BLE or network printing until explicitly requested.
15 15
16 16 ## Testing
17 17
@@ -11,7 +11,7 @@ alwaysApply: true
11- Single language: **Rust** with **egui** (eframe) for the UI.
11- Single language: **Rust** with **egui** (eframe) for the UI.
12- Prefer std library and in-house code. Add a crate only when reimplementing would be unreasonable (e.g. `serialport`, `serde`, `image`, UI framework).
12- Prefer std library and in-house code. Add a crate only when reimplementing would be unreasonable (e.g. `serialport`, `serde`, `image`, UI framework).
13- ESC/POS encoding lives in `src/escpos.rs` — do not add the `escpos` crates.io package.
13- ESC/POS encoding lives in `src/escpos.rs` — do not add the `escpos` crates.io package.
14- Printing: USB printer-class (`rusb`), Windows spooler, and USB-serial (`serialport`). Do not add Bluetooth or network printing until explicitly requested.
14- Printing: USB printer-class (`rusb`), Windows spooler, USB-serial, and OS-paired Classic Bluetooth SPP (`serialport`). Do not add BLE or network printing until explicitly requested.
15
15
16## Testing
16## Testing
17
17
README.md +7 −4
@@ -1,6 +1,6 @@
1 1 # posprint
2 2
3 Cross-platform designer for POS (point-of-sale) receipt documents. Edit templates in a markdown-like syntax, preview output live, substitute runtime parameters, and print via raw ESC/POS (USB printer-class, Windows spooler, or USB-serial).
3 Cross-platform designer for POS (point-of-sale) receipt documents. Edit templates in a markdown-like syntax, preview output live, substitute runtime parameters, and print via raw ESC/POS (USB printer-class, Windows spooler, USB-serial, or Classic Bluetooth SPP after OS pairing).
4 4
5 5 **Target platforms:** Windows and Linux (x64).
6 6
@@ -24,10 +24,13 @@ cargo build --release
24 24 ### Command-line printing
25 25
26 26 ```bash
27 # Windows (serial or spooler queue name)
27 # List discovered printers (USB, spooler, serial, paired Bluetooth SPP)
28 posprint list
29
30 # Windows (serial, Bluetooth COM after pairing, or spooler queue name)
28 31 posprint print receipt.pos -p COM3 --set StoreName="Shop" --set DocumentNumber=42
29 32
30 # Linux
33 # Linux (USB-serial or RFCOMM after pairing)
31 34 posprint print receipt.pos -p /dev/ttyUSB0 --set StoreName="Shop" --set DocumentNumber=42
32 35
33 36 # Embedded CLI help for this OS
@@ -56,7 +59,7 @@ Tag a version (e.g. `0.4.0`) to trigger release builds. If AUR publishing is con
56 59 - Parameter tokens: `${Name}` (text) and `$[Name]` (bool checkbox) via print dialog and CLI `--set`
57 60 - Inline ASCII checkboxes (`[]` / `[ ]` / `[x]`) — CP437-safe on thermal printers
58 61 - Nested bullet lists, headings, `@date` / `@time`, barcodes, QR, images
59 - Print via USB-direct, Windows spooler, or serial (baud probed)
62 - Print via USB-direct, Windows spooler, USB-serial, or paired Classic Bluetooth SPP (baud probed; BLE not supported)
60 63 - In-app **Help** tab (from [docs/HELP.md](docs/HELP.md))
61 64
62 65 ## Documentation
@@ -1,6 +1,6 @@
1# posprint
1# posprint
2
2
3Cross-platform designer for POS (point-of-sale) receipt documents. Edit templates in a markdown-like syntax, preview output live, substitute runtime parameters, and print via raw ESC/POS (USB printer-class, Windows spooler, or USB-serial).
3Cross-platform designer for POS (point-of-sale) receipt documents. Edit templates in a markdown-like syntax, preview output live, substitute runtime parameters, and print via raw ESC/POS (USB printer-class, Windows spooler, USB-serial, or Classic Bluetooth SPP after OS pairing).
4
4
5**Target platforms:** Windows and Linux (x64).
5**Target platforms:** Windows and Linux (x64).
6
6
@@ -24,10 +24,13 @@ cargo build --release
24### Command-line printing
24### Command-line printing
25
25
26```bash
26```bash
27# Windows (serial or spooler queue name)
27# List discovered printers (USB, spooler, serial, paired Bluetooth SPP)
28posprint list
29
30# Windows (serial, Bluetooth COM after pairing, or spooler queue name)
28posprint print receipt.pos -p COM3 --set StoreName="Shop" --set DocumentNumber=42
31posprint print receipt.pos -p COM3 --set StoreName="Shop" --set DocumentNumber=42
29
32
30# Linux
33# Linux (USB-serial or RFCOMM after pairing)
31posprint print receipt.pos -p /dev/ttyUSB0 --set StoreName="Shop" --set DocumentNumber=42
34posprint print receipt.pos -p /dev/ttyUSB0 --set StoreName="Shop" --set DocumentNumber=42
32
35
33# Embedded CLI help for this OS
36# Embedded CLI help for this OS
@@ -56,7 +59,7 @@ Tag a version (e.g. `0.4.0`) to trigger release builds. If AUR publishing is con
56- Parameter tokens: `${Name}` (text) and `$[Name]` (bool checkbox) via print dialog and CLI `--set`
59- Parameter tokens: `${Name}` (text) and `$[Name]` (bool checkbox) via print dialog and CLI `--set`
57- Inline ASCII checkboxes (`[]` / `[ ]` / `[x]`) — CP437-safe on thermal printers
60- Inline ASCII checkboxes (`[]` / `[ ]` / `[x]`) — CP437-safe on thermal printers
58- Nested bullet lists, headings, `@date` / `@time`, barcodes, QR, images
61- Nested bullet lists, headings, `@date` / `@time`, barcodes, QR, images
59- Print via USB-direct, Windows spooler, or serial (baud probed)
62- Print via USB-direct, Windows spooler, USB-serial, or paired Classic Bluetooth SPP (baud probed; BLE not supported)
60- In-app **Help** tab (from [docs/HELP.md](docs/HELP.md))
63- In-app **Help** tab (from [docs/HELP.md](docs/HELP.md))
61
64
62## Documentation
65## Documentation
docs/ARCHITECTURE.md +2 −2
@@ -9,7 +9,7 @@ posprint is a **single Rust binary** using **egui** (eframe). No separate fronte
9 9 │ posprint (Rust + egui) │
10 10 │ - Design / Help / Settings │
11 11 │ - DSL parse → AST → preview + ESC/POS │
12 │ - USB-direct / Win spooler / serial printing │
12 │ - USB-direct / Win spooler / serial / BT SPP │
13 13 │ - `.pos` JSON load/save (serde) │
14 14 └──────────────────────────────────────────────────┘
15 15 ```
@@ -100,7 +100,7 @@ While the print dialog is open, the main UI is disabled and editor autocomplete
100 100 ### Print
101 101
102 102 1. **Print** → parse → `collect_parameter_names`.
103 2. Dialog: text field per `${Name}`, checkbox per `$[Name]`; `list_printers()` for USB / spooler / serial.
103 2. Dialog: text field per `${Name}`, checkbox per `$[Name]`; `list_printers()` for USB / spooler / USB-serial / paired Bluetooth SPP.
104 104 3. `substitute_document` → `EscPosEncoder` → `open_printer` → `print_bytes`.
105 105 4. Serial baud is probed (`115200` first, then `9600`, …).
106 106
@@ -9,7 +9,7 @@ posprint is a **single Rust binary** using **egui** (eframe). No separate fronte
9│ posprint (Rust + egui) │
9│ posprint (Rust + egui) │
10│ - Design / Help / Settings │
10│ - Design / Help / Settings │
11│ - DSL parse → AST → preview + ESC/POS │
11│ - DSL parse → AST → preview + ESC/POS │
12│ - USB-direct / Win spooler / serial printing │
12│ - USB-direct / Win spooler / serial / BT SPP │
13│ - `.pos` JSON load/save (serde) │
13│ - `.pos` JSON load/save (serde) │
14└──────────────────────────────────────────────────┘
14└──────────────────────────────────────────────────┘
15```
15```
@@ -100,7 +100,7 @@ While the print dialog is open, the main UI is disabled and editor autocomplete
100### Print
100### Print
101
101
1021. **Print** → parse → `collect_parameter_names`.
1021. **Print** → parse → `collect_parameter_names`.
1032. Dialog: text field per `${Name}`, checkbox per `$[Name]`; `list_printers()` for USB / spooler / serial.
1032. Dialog: text field per `${Name}`, checkbox per `$[Name]`; `list_printers()` for USB / spooler / USB-serial / paired Bluetooth SPP.
1043. `substitute_document` → `EscPosEncoder` → `open_printer` → `print_bytes`.
1043. `substitute_document` → `EscPosEncoder` → `open_printer` → `print_bytes`.
1054. Serial baud is probed (`115200` first, then `9600`, …).
1054. Serial baud is probed (`115200` first, then `9600`, …).
106
106
docs/DSL-SPEC.md +2 −1
@@ -311,7 +311,8 @@ Full command details: [PRINTING.md](PRINTING.md).
311 311
312 312 - `@table` for columnar line items
313 313 - Numbered lists
314 - Bluetooth / network printer transports
314 - Network TCP 9100 printer transport
315 - BLE (GATT) printer transport (Classic Bluetooth SPP is implemented)
315 316 - Syntax highlighting in the editor
316 317
317 318 ---
@@ -311,7 +311,8 @@ Full command details: [PRINTING.md](PRINTING.md).
311
311
312- `@table` for columnar line items
312- `@table` for columnar line items
313- Numbered lists
313- Numbered lists
314- Bluetooth / network printer transports
314- Network TCP 9100 printer transport
315- BLE (GATT) printer transport (Classic Bluetooth SPP is implemented)
315- Syntax highlighting in the editor
316- Syntax highlighting in the editor
316
317
317---
318---
docs/HELP-CLI-LINUX.md +8 −3
@@ -7,6 +7,7 @@ Run `posprint cli-help` to print this section from the binary (no GUI required).
7 7 ## Syntax
8 8
9 9 ```bash
10 posprint list
10 11 posprint print <file.pos> --printer <DEVICE> --set Name=Value [--set Other=Value ...]
11 12 posprint link <file.pos>
12 13 ```
@@ -14,13 +15,16 @@ posprint link <file.pos>
14 15 Short form:
15 16
16 17 ```bash
18 posprint list
17 19 posprint print receipt.pos -p /dev/ttyUSB0 --set StoreName="My Shop" --set DocumentNumber=1001
20 posprint print receipt.pos -p /dev/rfcomm0 --set StoreName="My Shop" --set DocumentNumber=1001
18 21 posprint link receipt.pos
19 22 ```
20 23
21 24 ## Rules
22 25
23 - **`--printer` / `-p`** (required): serial device path (e.g. `/dev/ttyUSB0`, `/dev/ttyACM0`), or another printer id accepted by discovery.
26 - **`posprint list`**: print discovered printers (USB, USB-serial, paired Classic Bluetooth SPP). Use the device path from the list as `-p`.
27 - **`--printer` / `-p`** (required): serial device path (e.g. `/dev/ttyUSB0`, `/dev/ttyACM0`, `/dev/rfcomm0` after OS pairing), or another printer id accepted by discovery.
24 28 - **`--set NAME=VALUE`** (required for every parameter): one flag per `${Name}` or `$[Name]` in the template.
25 29 - Checkbox params (`$[Name]`): use `true`/`false` (also `1`/`0`, `yes`/`no`).
26 30 - If any text `${Name}` is missing or empty, or a `$[Name]` is omitted / not a boolean, the command **fails**.
@@ -50,10 +54,11 @@ posprint print ~/receipts/sale.pos -p /dev/ttyUSB0 \
50 54 ## Printer device
51 55
52 56 ```bash
53 ls -l /dev/ttyUSB* /dev/ttyACM* 2>/dev/null
57 posprint list
58 ls -l /dev/ttyUSB* /dev/ttyACM* /dev/rfcomm* 2>/dev/null
54 59 ```
55 60
56 Use the device node shown when the printer is connected.
61 Use the device node shown when the printer is connected. Pair a Classic Bluetooth SPP printer in the OS first; BLE is not supported.
57 62
58 63 ## Exit codes
59 64
@@ -7,6 +7,7 @@ Run `posprint cli-help` to print this section from the binary (no GUI required).
7## Syntax
7## Syntax
8
8
9```bash
9```bash
10posprint list
10posprint print <file.pos> --printer <DEVICE> --set Name=Value [--set Other=Value ...]
11posprint print <file.pos> --printer <DEVICE> --set Name=Value [--set Other=Value ...]
11posprint link <file.pos>
12posprint link <file.pos>
12```
13```
@@ -14,13 +15,16 @@ posprint link <file.pos>
14Short form:
15Short form:
15
16
16```bash
17```bash
18posprint list
17posprint print receipt.pos -p /dev/ttyUSB0 --set StoreName="My Shop" --set DocumentNumber=1001
19posprint print receipt.pos -p /dev/ttyUSB0 --set StoreName="My Shop" --set DocumentNumber=1001
20posprint print receipt.pos -p /dev/rfcomm0 --set StoreName="My Shop" --set DocumentNumber=1001
18posprint link receipt.pos
21posprint link receipt.pos
19```
22```
20
23
21## Rules
24## Rules
22
25
23- **`--printer` / `-p`** (required): serial device path (e.g. `/dev/ttyUSB0`, `/dev/ttyACM0`), or another printer id accepted by discovery.
26- **`posprint list`**: print discovered printers (USB, USB-serial, paired Classic Bluetooth SPP). Use the device path from the list as `-p`.
27- **`--printer` / `-p`** (required): serial device path (e.g. `/dev/ttyUSB0`, `/dev/ttyACM0`, `/dev/rfcomm0` after OS pairing), or another printer id accepted by discovery.
24- **`--set NAME=VALUE`** (required for every parameter): one flag per `${Name}` or `$[Name]` in the template.
28- **`--set NAME=VALUE`** (required for every parameter): one flag per `${Name}` or `$[Name]` in the template.
25- Checkbox params (`$[Name]`): use `true`/`false` (also `1`/`0`, `yes`/`no`).
29- Checkbox params (`$[Name]`): use `true`/`false` (also `1`/`0`, `yes`/`no`).
26- If any text `${Name}` is missing or empty, or a `$[Name]` is omitted / not a boolean, the command **fails**.
30- If any text `${Name}` is missing or empty, or a `$[Name]` is omitted / not a boolean, the command **fails**.
@@ -50,10 +54,11 @@ posprint print ~/receipts/sale.pos -p /dev/ttyUSB0 \
50## Printer device
54## Printer device
51
55
52```bash
56```bash
53ls -l /dev/ttyUSB* /dev/ttyACM* 2>/dev/null
57posprint list
58ls -l /dev/ttyUSB* /dev/ttyACM* /dev/rfcomm* 2>/dev/null
54```
59```
55
60
56Use the device node shown when the printer is connected.
61Use the device node shown when the printer is connected. Pair a Classic Bluetooth SPP printer in the OS first; BLE is not supported.
57
62
58## Exit codes
63## Exit codes
59
64
docs/HELP-CLI-WINDOWS.md +5 −1
@@ -7,6 +7,7 @@ Run `posprint cli-help` to print this section from the binary (no GUI required).
7 7 ## Syntax
8 8
9 9 ```powershell
10 posprint list
10 11 posprint print <file.pos> --printer <PORT> --set Name=Value [--set Other=Value ...]
11 12 posprint link <file.pos>
12 13 ```
@@ -14,13 +15,15 @@ posprint link <file.pos>
14 15 Short form:
15 16
16 17 ```powershell
18 posprint list
17 19 posprint print receipt.pos -p COM3 --set StoreName="My Shop" --set DocumentNumber=1001
18 20 posprint link receipt.pos
19 21 ```
20 22
21 23 ## Rules
22 24
23 - **`--printer` / `-p`** (required): serial port (`COM3`), or a Windows printer queue name for spooler printing.
25 - **`posprint list`**: print discovered printers (USB, spooler, USB-serial, paired Classic Bluetooth SPP).
26 - **`--printer` / `-p`** (required): serial port (`COM3`, including a Bluetooth SPP COM after OS pairing), or a Windows printer queue name for spooler printing.
24 27 - **`--set NAME=VALUE`** (required for every parameter): one flag per `${Name}` or `$[Name]` in the template.
25 28 - Checkbox params (`$[Name]`): use `true`/`false` (also `1`/`0`, `yes`/`no`).
26 29 - If any text `${Name}` is missing or empty, or a `$[Name]` is omitted / not a boolean, the command **fails**.
@@ -42,6 +45,7 @@ posprint print C:\receipts\sale.pos -p COM3 `
42 45 ## Printer target
43 46
44 47 - Serial: **Device Manager → Ports (COM & LPT)** for the COM port; install the USB-serial driver if needed.
48 - Bluetooth SPP: pair the printer in Windows first, then use the virtual COM port (`posprint list` labels it Bluetooth). BLE is not supported.
45 49 - Spooler: use the Windows printer queue name as `-p` (same name as in Settings → Printers).
46 50 - Close other programs using the same COM port before printing.
47 51
@@ -7,6 +7,7 @@ Run `posprint cli-help` to print this section from the binary (no GUI required).
7## Syntax
7## Syntax
8
8
9```powershell
9```powershell
10posprint list
10posprint print <file.pos> --printer <PORT> --set Name=Value [--set Other=Value ...]
11posprint print <file.pos> --printer <PORT> --set Name=Value [--set Other=Value ...]
11posprint link <file.pos>
12posprint link <file.pos>
12```
13```
@@ -14,13 +15,15 @@ posprint link <file.pos>
14Short form:
15Short form:
15
16
16```powershell
17```powershell
18posprint list
17posprint print receipt.pos -p COM3 --set StoreName="My Shop" --set DocumentNumber=1001
19posprint print receipt.pos -p COM3 --set StoreName="My Shop" --set DocumentNumber=1001
18posprint link receipt.pos
20posprint link receipt.pos
19```
21```
20
22
21## Rules
23## Rules
22
24
23- **`--printer` / `-p`** (required): serial port (`COM3`), or a Windows printer queue name for spooler printing.
25- **`posprint list`**: print discovered printers (USB, spooler, USB-serial, paired Classic Bluetooth SPP).
26- **`--printer` / `-p`** (required): serial port (`COM3`, including a Bluetooth SPP COM after OS pairing), or a Windows printer queue name for spooler printing.
24- **`--set NAME=VALUE`** (required for every parameter): one flag per `${Name}` or `$[Name]` in the template.
27- **`--set NAME=VALUE`** (required for every parameter): one flag per `${Name}` or `$[Name]` in the template.
25- Checkbox params (`$[Name]`): use `true`/`false` (also `1`/`0`, `yes`/`no`).
28- Checkbox params (`$[Name]`): use `true`/`false` (also `1`/`0`, `yes`/`no`).
26- If any text `${Name}` is missing or empty, or a `$[Name]` is omitted / not a boolean, the command **fails**.
29- If any text `${Name}` is missing or empty, or a `$[Name]` is omitted / not a boolean, the command **fails**.
@@ -42,6 +45,7 @@ posprint print C:\receipts\sale.pos -p COM3 `
42## Printer target
45## Printer target
43
46
44- Serial: **Device Manager → Ports (COM & LPT)** for the COM port; install the USB-serial driver if needed.
47- Serial: **Device Manager → Ports (COM & LPT)** for the COM port; install the USB-serial driver if needed.
48- Bluetooth SPP: pair the printer in Windows first, then use the virtual COM port (`posprint list` labels it Bluetooth). BLE is not supported.
45- Spooler: use the Windows printer queue name as `-p` (same name as in Settings → Printers).
49- Spooler: use the Windows printer queue name as `-p` (same name as in Settings → Printers).
46- Close other programs using the same COM port before printing.
50- Close other programs using the same COM port before printing.
47
51
docs/HELP.md +5 −2
@@ -288,10 +288,13 @@ Printers may appear as:
288 288 - **USB printer-class** devices (direct bulk OUT)
289 289 - **Windows spooler** queues (Windows)
290 290 - **USB-serial** ports with a device attached (`COMx`, `/dev/ttyUSB0`, `/dev/ttyACM0`, …)
291 - **Classic Bluetooth SPP** after you pair the printer in the OS (`COMx` on Windows, often `/dev/rfcomm0` on Linux). Listed with a **Bluetooth** label.
291 292
292 293 Empty motherboard serial ports (common on Linux as `/dev/ttyS*`) are hidden. Use **Enter port or queue manually** if you need one of those.
293 294
294 **Linux serial:** join the `dialout` group.
295 Bluetooth Low Energy (BLE) printers are not supported. Pair Classic Bluetooth SPP in Windows or your Linux Bluetooth settings first; Posprint does not pair devices itself.
296
297 **Linux serial / RFCOMM:** join the `dialout` group.
295 298
296 299 ---
297 300
@@ -303,7 +306,7 @@ posprint link receipt.pos
303 306 posprint cli-help
304 307 ```
305 308
306 `-p` accepts a serial port name, USB device label from discovery, or (on Windows) a spooler queue name. See platform CLI help via `posprint cli-help`.
309 `posprint list` prints discovered printers. `-p` accepts a serial port name (including a paired Bluetooth COM/`rfcomm` node), USB device label from discovery, or (on Windows) a spooler queue name. See platform CLI help via `posprint cli-help`.
307 310
308 311 `posprint link` prints a `posprint://` deep link for the file (see [POSPRINT-URL.md](POSPRINT-URL.md)).
309 312
@@ -288,10 +288,13 @@ Printers may appear as:
288- **USB printer-class** devices (direct bulk OUT)
288- **USB printer-class** devices (direct bulk OUT)
289- **Windows spooler** queues (Windows)
289- **Windows spooler** queues (Windows)
290- **USB-serial** ports with a device attached (`COMx`, `/dev/ttyUSB0`, `/dev/ttyACM0`, …)
290- **USB-serial** ports with a device attached (`COMx`, `/dev/ttyUSB0`, `/dev/ttyACM0`, …)
291- **Classic Bluetooth SPP** after you pair the printer in the OS (`COMx` on Windows, often `/dev/rfcomm0` on Linux). Listed with a **Bluetooth** label.
291
292
292Empty motherboard serial ports (common on Linux as `/dev/ttyS*`) are hidden. Use **Enter port or queue manually** if you need one of those.
293Empty motherboard serial ports (common on Linux as `/dev/ttyS*`) are hidden. Use **Enter port or queue manually** if you need one of those.
293
294
294**Linux serial:** join the `dialout` group.
295Bluetooth Low Energy (BLE) printers are not supported. Pair Classic Bluetooth SPP in Windows or your Linux Bluetooth settings first; Posprint does not pair devices itself.
296
297**Linux serial / RFCOMM:** join the `dialout` group.
295
298
296---
299---
297
300
@@ -303,7 +306,7 @@ posprint link receipt.pos
303posprint cli-help
306posprint cli-help
304```
307```
305
308
306`-p` accepts a serial port name, USB device label from discovery, or (on Windows) a spooler queue name. See platform CLI help via `posprint cli-help`.
309`posprint list` prints discovered printers. `-p` accepts a serial port name (including a paired Bluetooth COM/`rfcomm` node), USB device label from discovery, or (on Windows) a spooler queue name. See platform CLI help via `posprint cli-help`.
307
310
308`posprint link` prints a `posprint://` deep link for the file (see [POSPRINT-URL.md](POSPRINT-URL.md)).
311`posprint link` prints a `posprint://` deep link for the file (see [POSPRINT-URL.md](POSPRINT-URL.md)).
309
312
docs/PRINTING.md +21 −8
@@ -1,12 +1,12 @@
1 1 # Printing subsystem
2 2
3 Raw ESC/POS output to POS thermal printers via **USB printer-class**, **Windows spooler** (Windows), or **USB-serial**.
3 Raw ESC/POS output to POS thermal printers via **USB printer-class**, **Windows spooler** (Windows), **USB-serial**, or **Classic Bluetooth SPP** after OS pairing.
4 4
5 5 ---
6 6
7 7 ## Goals
8 8
9 1. Discover printers (USB-direct, Windows spooler, serial ports)
9 1. Discover printers (USB-direct, Windows spooler, USB-serial, paired Bluetooth SPP)
10 10 2. Let the user pick a target in the print dialog
11 11 3. Generate ESC/POS bytes from the AST (after parameter substitution)
12 12 4. Write bytes to the chosen transport (serial baud is probed)
@@ -70,7 +70,7 @@ pub trait PrinterTransport {
70 70 |------|------|
71 71 | USB-direct (`rusb`) | USB printer-class bulk OUT (`usb_direct.rs`) |
72 72 | Windows spooler | Raw jobs via Win32 spooler (`win_spool.rs`, Windows only) |
73 | `SerialTransport` | USB-serial / CDC ports via `serialport` |
73 | `SerialTransport` | USB-serial / CDC and paired Classic Bluetooth SPP via `serialport` |
74 74 | `MockTransport` | Tests — records bytes in `written` vec |
75 75
76 76 ### Discovery
@@ -79,7 +79,7 @@ pub trait PrinterTransport {
79 79
80 80 1. USB printer-class devices (`usb_direct`)
81 81 2. Windows spooler queues (Windows)
82 3. USB-serial ports only (`SerialPortType::UsbPort` — skips empty PCI/`ttyS*` ports common on Linux)
82 3. USB-serial (`SerialPortType::UsbPort`) and OS-paired Classic Bluetooth SPP (`BluetoothPort`, plus Linux `/dev/rfcomm*`). Empty PCI/`ttyS*` ports are skipped. BLE is not scanned.
83 83
84 84 ### Serial baud rates
85 85
@@ -91,8 +91,8 @@ pub trait PrinterTransport {
91 91
92 92 | Field | Example |
93 93 |-------|---------|
94 | `id` | `serial:COM3`, `usb:04b8:0e15:…`, `spool:POS-58` |
95 | `display_name` | Human-readable label |
94 | `id` | `serial:COM3`, `serial:COM5`, `usb:04b8:0e15:…`, `spool:POS-58` |
95 | `display_name` | Human-readable label (`COM5 — Bluetooth` for paired SPP) |
96 96 | `target` | `Serial` / `UsbDirect` / `WinSpooler` |
97 97
98 98 ---
@@ -100,7 +100,7 @@ pub trait PrinterTransport {
100 100 ## Print dialog (UI)
101 101
102 102 - One field per unique `${Parameter}`.
103 - Printer list: USB printer-class, Windows spooler (Windows), and connected USB-serial devices (Refresh button). Empty motherboard serial ports are omitted; use manual entry for those.
103 - Printer list: USB printer-class, Windows spooler (Windows), USB-serial, and paired Classic Bluetooth SPP serial ports (Refresh button). Empty motherboard serial ports are omitted; use manual entry for those. BLE is out of scope.
104 104 - **Print** sits next to **Refresh**; close the dialog with the window ✕.
105 105 - The printer list uses a fixed-height scroll area so long lists stay usable.
106 106 - Optional manual serial port / queue name.
@@ -180,10 +180,23 @@ On Windows, spooler access uses Win32 APIs (`winreg` / system libs as needed). N
180 180
181 181 ---
182 182
183 ### Classic Bluetooth SPP (implemented)
184
185 Pair the printer in the OS first. Posprint does not scan, pair, or talk BLE/GATT.
186
187 | Platform | After pairing | Discovery |
188 |----------|---------------|-----------|
189 | Windows | Bluetooth SPP virtual COM (`COMx`) | `SerialPortType::BluetoothPort` |
190 | Linux | RFCOMM node (often `/dev/rfcomm0`) | `BluetoothPort`, or `/dev/rfcomm*` if typed Unknown |
191
192 Printing reuses `SerialTransport` (same baud probe as USB-serial). Manual port entry still works (`COM5`, `/dev/rfcomm0`).
193
194 ---
195
183 196 ## Planned (not implemented)
184 197
185 198 | Feature | Notes |
186 199 |---------|-------|
187 | Bluetooth SPP | After OS pairing |
200 | BLE (GATT) | Out of scope — Classic SPP only |
188 201 | Network TCP 9100 | Future |
189 202 | Printer status read | DLE EOT |
@@ -1,12 +1,12 @@
1# Printing subsystem
1# Printing subsystem
2
2
3Raw ESC/POS output to POS thermal printers via **USB printer-class**, **Windows spooler** (Windows), or **USB-serial**.
3Raw ESC/POS output to POS thermal printers via **USB printer-class**, **Windows spooler** (Windows), **USB-serial**, or **Classic Bluetooth SPP** after OS pairing.
4
4
5---
5---
6
6
7## Goals
7## Goals
8
8
91. Discover printers (USB-direct, Windows spooler, serial ports)
91. Discover printers (USB-direct, Windows spooler, USB-serial, paired Bluetooth SPP)
102. Let the user pick a target in the print dialog
102. Let the user pick a target in the print dialog
113. Generate ESC/POS bytes from the AST (after parameter substitution)
113. Generate ESC/POS bytes from the AST (after parameter substitution)
124. Write bytes to the chosen transport (serial baud is probed)
124. Write bytes to the chosen transport (serial baud is probed)
@@ -70,7 +70,7 @@ pub trait PrinterTransport {
70|------|------|
70|------|------|
71| USB-direct (`rusb`) | USB printer-class bulk OUT (`usb_direct.rs`) |
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) |
72| Windows spooler | Raw jobs via Win32 spooler (`win_spool.rs`, Windows only) |
73| `SerialTransport` | USB-serial / CDC ports via `serialport` |
73| `SerialTransport` | USB-serial / CDC and paired Classic Bluetooth SPP via `serialport` |
74| `MockTransport` | Tests — records bytes in `written` vec |
74| `MockTransport` | Tests — records bytes in `written` vec |
75
75
76### Discovery
76### Discovery
@@ -79,7 +79,7 @@ pub trait PrinterTransport {
79
79
801. USB printer-class devices (`usb_direct`)
801. USB printer-class devices (`usb_direct`)
812. Windows spooler queues (Windows)
812. Windows spooler queues (Windows)
823. USB-serial ports only (`SerialPortType::UsbPort` — skips empty PCI/`ttyS*` ports common on Linux)
823. USB-serial (`SerialPortType::UsbPort`) and OS-paired Classic Bluetooth SPP (`BluetoothPort`, plus Linux `/dev/rfcomm*`). Empty PCI/`ttyS*` ports are skipped. BLE is not scanned.
83
83
84### Serial baud rates
84### Serial baud rates
85
85
@@ -91,8 +91,8 @@ pub trait PrinterTransport {
91
91
92| Field | Example |
92| Field | Example |
93|-------|---------|
93|-------|---------|
94| `id` | `serial:COM3`, `usb:04b8:0e15:…`, `spool:POS-58` |
94| `id` | `serial:COM3`, `serial:COM5`, `usb:04b8:0e15:…`, `spool:POS-58` |
95| `display_name` | Human-readable label |
95| `display_name` | Human-readable label (`COM5 — Bluetooth` for paired SPP) |
96| `target` | `Serial` / `UsbDirect` / `WinSpooler` |
96| `target` | `Serial` / `UsbDirect` / `WinSpooler` |
97
97
98---
98---
@@ -100,7 +100,7 @@ pub trait PrinterTransport {
100## Print dialog (UI)
100## Print dialog (UI)
101
101
102- One field per unique `${Parameter}`.
102- One field per unique `${Parameter}`.
103- Printer list: USB printer-class, Windows spooler (Windows), and connected USB-serial devices (Refresh button). Empty motherboard serial ports are omitted; use manual entry for those.
103- Printer list: USB printer-class, Windows spooler (Windows), USB-serial, and paired Classic Bluetooth SPP serial ports (Refresh button). Empty motherboard serial ports are omitted; use manual entry for those. BLE is out of scope.
104- **Print** sits next to **Refresh**; close the dialog with the window ✕.
104- **Print** sits next to **Refresh**; close the dialog with the window ✕.
105- The printer list uses a fixed-height scroll area so long lists stay usable.
105- The printer list uses a fixed-height scroll area so long lists stay usable.
106- Optional manual serial port / queue name.
106- Optional manual serial port / queue name.
@@ -180,10 +180,23 @@ On Windows, spooler access uses Win32 APIs (`winreg` / system libs as needed). N
180
180
181---
181---
182
182
183### Classic Bluetooth SPP (implemented)
184
185Pair the printer in the OS first. Posprint does not scan, pair, or talk BLE/GATT.
186
187| Platform | After pairing | Discovery |
188|----------|---------------|-----------|
189| Windows | Bluetooth SPP virtual COM (`COMx`) | `SerialPortType::BluetoothPort` |
190| Linux | RFCOMM node (often `/dev/rfcomm0`) | `BluetoothPort`, or `/dev/rfcomm*` if typed Unknown |
191
192Printing reuses `SerialTransport` (same baud probe as USB-serial). Manual port entry still works (`COM5`, `/dev/rfcomm0`).
193
194---
195
183## Planned (not implemented)
196## Planned (not implemented)
184
197
185| Feature | Notes |
198| Feature | Notes |
186|---------|-------|
199|---------|-------|
187| Bluetooth SPP | After OS pairing |
200| BLE (GATT) | Out of scope — Classic SPP only |
188| Network TCP 9100 | Future |
201| Network TCP 9100 | Future |
189| Printer status read | DLE EOT |
202| Printer status read | DLE EOT |
src/cli.rs +30 −2
@@ -31,11 +31,13 @@ pub enum Commands {
31 31 /// Show command-line printing help (also in the GUI Help tab)
32 32 #[command(name = "cli-help")]
33 33 CliHelp,
34 /// Print a .pos file to a USB-serial printer (all parameters required)
34 /// List discovered printers (USB, spooler, USB-serial, paired Bluetooth SPP)
35 List,
36 /// Print a .pos file to a printer (all parameters required)
35 37 Print {
36 38 /// Path to the `.pos` template file
37 39 file: PathBuf,
38 /// Serial port (e.g. COM3 on Windows, /dev/ttyUSB0 on Linux)
40 /// Printer: serial/COM, /dev/rfcomm*, USB id from `list`, or Windows queue
39 41 #[arg(short, long)]
40 42 printer: String,
41 43 /// Template parameter as NAME=VALUE (repeat for each `${Name}` / `$[Name]`;
@@ -56,6 +58,13 @@ pub fn run(cli: Cli) -> i32 {
56 58 println!("{}", crate::HELP_CLI_MARKDOWN);
57 59 0
58 60 }
61 Some(Commands::List) => match run_list() {
62 Ok(()) => 0,
63 Err(e) => {
64 eprintln!("{e}");
65 1
66 }
67 },
59 68 Some(Commands::Print { file, printer, set }) => match run_print(&file, &printer, &set) {
60 69 Ok(()) => 0,
61 70 Err(e) => {
@@ -79,6 +88,18 @@ pub fn run(cli: Cli) -> i32 {
79 88 }
80 89 }
81 90
91 fn run_list() -> Result<(), String> {
92 let printers = crate::print::list_printers().map_err(|e| format!("{e:?}"))?;
93 if printers.is_empty() {
94 println!("No printers found.");
95 return Ok(());
96 }
97 for printer in printers {
98 println!("{}\t{}", printer.id, printer.display_name);
99 }
100 Ok(())
101 }
102
82 103 fn run_print(file: &PathBuf, printer: &str, set: &[String]) -> Result<(), String> {
83 104 let params = parse_params(set)?;
84 105 pipeline::print_pos_file(file, printer, &params).map_err(|e| e.to_string())
@@ -146,4 +167,11 @@ mod tests {
146 167 0
147 168 );
148 169 }
170
171 #[test]
172 fn accepts_list_subcommand() {
173 use clap::Parser;
174 let cli = Cli::parse_from(["posprint", "list"]);
175 assert!(matches!(cli.command, Some(Commands::List)));
176 }
149 177 }
@@ -31,11 +31,13 @@ pub enum Commands {
31 /// Show command-line printing help (also in the GUI Help tab)
31 /// Show command-line printing help (also in the GUI Help tab)
32 #[command(name = "cli-help")]
32 #[command(name = "cli-help")]
33 CliHelp,
33 CliHelp,
34 /// Print a .pos file to a USB-serial printer (all parameters required)
34 /// List discovered printers (USB, spooler, USB-serial, paired Bluetooth SPP)
35 List,
36 /// Print a .pos file to a printer (all parameters required)
35 Print {
37 Print {
36 /// Path to the `.pos` template file
38 /// Path to the `.pos` template file
37 file: PathBuf,
39 file: PathBuf,
38 /// Serial port (e.g. COM3 on Windows, /dev/ttyUSB0 on Linux)
40 /// Printer: serial/COM, /dev/rfcomm*, USB id from `list`, or Windows queue
39 #[arg(short, long)]
41 #[arg(short, long)]
40 printer: String,
42 printer: String,
41 /// Template parameter as NAME=VALUE (repeat for each `${Name}` / `$[Name]`;
43 /// Template parameter as NAME=VALUE (repeat for each `${Name}` / `$[Name]`;
@@ -56,6 +58,13 @@ pub fn run(cli: Cli) -> i32 {
56 println!("{}", crate::HELP_CLI_MARKDOWN);
58 println!("{}", crate::HELP_CLI_MARKDOWN);
57 0
59 0
58 }
60 }
61 Some(Commands::List) => match run_list() {
62 Ok(()) => 0,
63 Err(e) => {
64 eprintln!("{e}");
65 1
66 }
67 },
59 Some(Commands::Print { file, printer, set }) => match run_print(&file, &printer, &set) {
68 Some(Commands::Print { file, printer, set }) => match run_print(&file, &printer, &set) {
60 Ok(()) => 0,
69 Ok(()) => 0,
61 Err(e) => {
70 Err(e) => {
@@ -79,6 +88,18 @@ pub fn run(cli: Cli) -> i32 {
79 }
88 }
80}
89}
81
90
91fn run_list() -> Result<(), String> {
92 let printers = crate::print::list_printers().map_err(|e| format!("{e:?}"))?;
93 if printers.is_empty() {
94 println!("No printers found.");
95 return Ok(());
96 }
97 for printer in printers {
98 println!("{}\t{}", printer.id, printer.display_name);
99 }
100 Ok(())
101}
102
82fn run_print(file: &PathBuf, printer: &str, set: &[String]) -> Result<(), String> {
103fn run_print(file: &PathBuf, printer: &str, set: &[String]) -> Result<(), String> {
83 let params = parse_params(set)?;
104 let params = parse_params(set)?;
84 pipeline::print_pos_file(file, printer, &params).map_err(|e| e.to_string())
105 pipeline::print_pos_file(file, printer, &params).map_err(|e| e.to_string())
@@ -146,4 +167,11 @@ mod tests {
146 0
167 0
147 );
168 );
148 }
169 }
170
171 #[test]
172 fn accepts_list_subcommand() {
173 use clap::Parser;
174 let cli = Cli::parse_from(["posprint", "list"]);
175 assert!(matches!(cli.command, Some(Commands::List)));
176 }
149}
177}
src/print/mod.rs +126 −34
@@ -1,7 +1,7 @@
1 1 use std::io::{self, Write};
2 2 use std::time::Duration;
3 3
4 use serialport::SerialPortType;
4 use serialport::{SerialPortInfo, SerialPortType};
5 5
6 6 mod usb_direct;
7 7 #[cfg(windows)]
@@ -81,7 +81,8 @@ impl PrinterTransport for SerialTransport {
81 81 }
82 82 }
83 83
84 /// List POS printers: USB printer-class devices, Windows spooler queues, then serial ports.
84 /// List POS printers: USB printer-class, Windows spooler, then USB-serial and
85 /// OS-paired Classic Bluetooth SPP ports.
85 86 pub fn list_printers() -> Result<Vec<PrinterDevice>, PrintError> {
86 87 let mut devices = usb_direct::list_usb_printer_devices();
87 88
@@ -99,37 +100,70 @@ pub fn list_usb_serial_printers() -> Result<Vec<PrinterDevice>, serialport::Erro
99 100 fn list_serial_devices() -> Result<Vec<PrinterDevice>, serialport::Error> {
100 101 let mut devices = Vec::new();
101 102 for port in serialport::available_ports()? {
102 // Only USB-attached serial devices: Linux often lists dozens of empty
103 // /dev/ttyS* (PCI/Unknown) that are not connected to anything.
104 let SerialPortType::UsbPort(info) = &port.port_type else {
105 continue;
106 };
107 let product = info
108 .product
109 .as_deref()
110 .or(info.serial_number.as_deref())
111 .unwrap_or("USB device");
112 let label = format!(
113 "{} — {product} (serial {}:{})",
114 port.port_name,
115 fmt_vid_pid(info.vid),
116 fmt_vid_pid(info.pid)
117 );
118 devices.push(PrinterDevice {
119 id: format!("serial:{}", port.port_name),
120 display_name: label,
121 target: PrinterTarget::Serial(port.port_name.clone()),
122 });
103 if let Some(device) = serial_device_from_port(&port) {
104 devices.push(device);
105 }
123 106 }
124 107 devices.sort_by(|a, b| a.display_name.cmp(&b.display_name));
125 108 Ok(devices)
126 109 }
127 110
111 /// USB-serial or OS-paired Classic Bluetooth SPP. Skips empty PCI/`ttyS*` noise.
112 pub fn is_serial_printer_candidate(port_type: &SerialPortType) -> bool {
113 is_usb_serial_candidate(port_type) || is_bluetooth_serial_candidate(port_type)
114 }
115
128 116 /// True when a serial port type is a connected USB device (possible POS printer).
129 117 pub fn is_usb_serial_candidate(port_type: &SerialPortType) -> bool {
130 118 matches!(port_type, SerialPortType::UsbPort(_))
131 119 }
132 120
121 /// True when `serialport` reports a Classic Bluetooth SPP / RFCOMM port.
122 pub fn is_bluetooth_serial_candidate(port_type: &SerialPortType) -> bool {
123 matches!(port_type, SerialPortType::BluetoothPort)
124 }
125
126 /// Linux RFCOMM node (`/dev/rfcomm0`) even if enumeration typed it as Unknown.
127 fn is_rfcomm_device_name(port_name: &str) -> bool {
128 let base = port_name.rsplit(['/', '\\']).next().unwrap_or(port_name);
129 base.len() >= 6 && base[..6].eq_ignore_ascii_case("rfcomm")
130 }
131
132 /// Map an enumerated serial port to a printer entry, or skip PCI/`ttyS*` noise.
133 pub fn serial_device_from_port(port: &SerialPortInfo) -> Option<PrinterDevice> {
134 if !is_serial_printer_candidate(&port.port_type) && !is_rfcomm_device_name(&port.port_name) {
135 return None;
136 }
137 Some(PrinterDevice {
138 id: format!("serial:{}", port.port_name),
139 display_name: serial_port_display_name(port),
140 target: PrinterTarget::Serial(port.port_name.clone()),
141 })
142 }
143
144 fn serial_port_display_name(port: &SerialPortInfo) -> String {
145 match &port.port_type {
146 SerialPortType::UsbPort(info) => {
147 let product = info
148 .product
149 .as_deref()
150 .or(info.serial_number.as_deref())
151 .unwrap_or("USB device");
152 format!(
153 "{} — {product} (serial {}:{})",
154 port.port_name,
155 fmt_vid_pid(info.vid),
156 fmt_vid_pid(info.pid)
157 )
158 }
159 SerialPortType::BluetoothPort => format!("{} — Bluetooth", port.port_name),
160 _ if is_rfcomm_device_name(&port.port_name) => {
161 format!("{} — Bluetooth", port.port_name)
162 }
163 _ => format!("{} — serial", port.port_name),
164 }
165 }
166
133 167 pub fn open_printer(target: &PrinterTarget) -> Result<Box<dyn PrinterTransport>, PrintError> {
134 168 match target {
135 169 PrinterTarget::Serial(port) => Ok(Box::new(SerialTransport::open(port)?)),
@@ -257,7 +291,7 @@ impl PrinterTransport for MockTransport {
257 291 #[cfg(test)]
258 292 mod tests {
259 293 use super::*;
260 use serialport::UsbPortInfo;
294 use serialport::{SerialPortInfo, UsbPortInfo};
261 295
262 296 #[test]
263 297 fn mock_transport_records_bytes() {
@@ -272,23 +306,81 @@ mod tests {
272 306 assert!(list.is_ok());
273 307 }
274 308
309 fn sample_usb_port_type() -> SerialPortType {
310 SerialPortType::UsbPort(UsbPortInfo {
311 vid: 0x0416,
312 pid: 0x5011,
313 serial_number: None,
314 manufacturer: None,
315 product: Some("POS-58".into()),
316 })
317 }
318
275 319 #[test]
276 fn non_usb_serial_ports_are_not_candidates() {
277 assert!(!is_usb_serial_candidate(&SerialPortType::PciPort));
320 fn pci_and_unknown_serial_ports_are_not_candidates() {
321 assert!(!is_serial_printer_candidate(&SerialPortType::PciPort));
322 assert!(!is_serial_printer_candidate(&SerialPortType::Unknown));
278 323 assert!(!is_usb_serial_candidate(&SerialPortType::BluetoothPort));
324 assert!(!is_usb_serial_candidate(&SerialPortType::PciPort));
279 325 assert!(!is_usb_serial_candidate(&SerialPortType::Unknown));
280 326 }
281 327
282 328 #[test]
283 fn usb_serial_port_is_candidate() {
284 let usb = SerialPortType::UsbPort(UsbPortInfo {
285 vid: 0x0416,
286 pid: 0x5011,
287 serial_number: None,
288 manufacturer: None,
289 product: Some("POS-58".into()),
290 });
329 fn usb_and_bluetooth_serial_ports_are_candidates() {
330 let usb = sample_usb_port_type();
291 331 assert!(is_usb_serial_candidate(&usb));
332 assert!(is_serial_printer_candidate(&usb));
333 assert!(is_bluetooth_serial_candidate(&SerialPortType::BluetoothPort));
334 assert!(is_serial_printer_candidate(&SerialPortType::BluetoothPort));
335 }
336
337 #[test]
338 fn bluetooth_serial_device_is_labeled() {
339 let port = SerialPortInfo {
340 port_name: "COM5".into(),
341 port_type: SerialPortType::BluetoothPort,
342 };
343 let device = serial_device_from_port(&port).expect("bluetooth candidate");
344 assert_eq!(device.id, "serial:COM5");
345 assert_eq!(device.display_name, "COM5 — Bluetooth");
346 assert_eq!(device.target, PrinterTarget::Serial("COM5".into()));
347 }
348
349 #[test]
350 fn linux_rfcomm_is_listed_even_if_type_unknown() {
351 let port = SerialPortInfo {
352 port_name: "/dev/rfcomm0".into(),
353 port_type: SerialPortType::Unknown,
354 };
355 let device = serial_device_from_port(&port).expect("rfcomm candidate");
356 assert_eq!(device.display_name, "/dev/rfcomm0 — Bluetooth");
357 assert_eq!(device.target, PrinterTarget::Serial("/dev/rfcomm0".into()));
358 }
359
360 #[test]
361 fn empty_pci_ttys_ports_are_not_listed() {
362 let pci = SerialPortInfo {
363 port_name: "/dev/ttyS0".into(),
364 port_type: SerialPortType::PciPort,
365 };
366 assert!(serial_device_from_port(&pci).is_none());
367 let unknown = SerialPortInfo {
368 port_name: "/dev/ttyS1".into(),
369 port_type: SerialPortType::Unknown,
370 };
371 assert!(serial_device_from_port(&unknown).is_none());
372 }
373
374 #[test]
375 fn usb_serial_device_keeps_vid_pid_label() {
376 let port = SerialPortInfo {
377 port_name: "/dev/ttyUSB0".into(),
378 port_type: sample_usb_port_type(),
379 };
380 let device = serial_device_from_port(&port).expect("usb candidate");
381 assert!(device.display_name.contains("POS-58"));
382 assert!(device.display_name.contains("0416:5011"));
383 assert!(!device.display_name.contains("Bluetooth"));
292 384 }
293 385
294 386 #[test]
@@ -1,7 +1,7 @@
1use std::io::{self, Write};
1use std::io::{self, Write};
2use std::time::Duration;
2use std::time::Duration;
3
3
4use serialport::SerialPortType;
4use serialport::{SerialPortInfo, SerialPortType};
5
5
6mod usb_direct;
6mod usb_direct;
7#[cfg(windows)]
7#[cfg(windows)]
@@ -81,7 +81,8 @@ impl PrinterTransport for SerialTransport {
81 }
81 }
82}
82}
83
83
84/// List POS printers: USB printer-class devices, Windows spooler queues, then serial ports.
84/// List POS printers: USB printer-class, Windows spooler, then USB-serial and
85/// OS-paired Classic Bluetooth SPP ports.
85pub fn list_printers() -> Result<Vec<PrinterDevice>, PrintError> {
86pub fn list_printers() -> Result<Vec<PrinterDevice>, PrintError> {
86 let mut devices = usb_direct::list_usb_printer_devices();
87 let mut devices = usb_direct::list_usb_printer_devices();
87
88
@@ -99,37 +100,70 @@ pub fn list_usb_serial_printers() -> Result<Vec<PrinterDevice>, serialport::Erro
99fn list_serial_devices() -> Result<Vec<PrinterDevice>, serialport::Error> {
100fn list_serial_devices() -> Result<Vec<PrinterDevice>, serialport::Error> {
100 let mut devices = Vec::new();
101 let mut devices = Vec::new();
101 for port in serialport::available_ports()? {
102 for port in serialport::available_ports()? {
102 // Only USB-attached serial devices: Linux often lists dozens of empty
103 if let Some(device) = serial_device_from_port(&port) {
103 // /dev/ttyS* (PCI/Unknown) that are not connected to anything.
104 devices.push(device);
104 let SerialPortType::UsbPort(info) = &port.port_type else {
105 }
105 continue;
106 };
107 let product = info
108 .product
109 .as_deref()
110 .or(info.serial_number.as_deref())
111 .unwrap_or("USB device");
112 let label = format!(
113 "{} — {product} (serial {}:{})",
114 port.port_name,
115 fmt_vid_pid(info.vid),
116 fmt_vid_pid(info.pid)
117 );
118 devices.push(PrinterDevice {
119 id: format!("serial:{}", port.port_name),
120 display_name: label,
121 target: PrinterTarget::Serial(port.port_name.clone()),
122 });
123 }
106 }
124 devices.sort_by(|a, b| a.display_name.cmp(&b.display_name));
107 devices.sort_by(|a, b| a.display_name.cmp(&b.display_name));
125 Ok(devices)
108 Ok(devices)
126}
109}
127
110
111/// USB-serial or OS-paired Classic Bluetooth SPP. Skips empty PCI/`ttyS*` noise.
112pub fn is_serial_printer_candidate(port_type: &SerialPortType) -> bool {
113 is_usb_serial_candidate(port_type) || is_bluetooth_serial_candidate(port_type)
114}
115
128/// True when a serial port type is a connected USB device (possible POS printer).
116/// True when a serial port type is a connected USB device (possible POS printer).
129pub fn is_usb_serial_candidate(port_type: &SerialPortType) -> bool {
117pub fn is_usb_serial_candidate(port_type: &SerialPortType) -> bool {
130 matches!(port_type, SerialPortType::UsbPort(_))
118 matches!(port_type, SerialPortType::UsbPort(_))
131}
119}
132
120
121/// True when `serialport` reports a Classic Bluetooth SPP / RFCOMM port.
122pub fn is_bluetooth_serial_candidate(port_type: &SerialPortType) -> bool {
123 matches!(port_type, SerialPortType::BluetoothPort)
124}
125
126/// Linux RFCOMM node (`/dev/rfcomm0`) even if enumeration typed it as Unknown.
127fn is_rfcomm_device_name(port_name: &str) -> bool {
128 let base = port_name.rsplit(['/', '\\']).next().unwrap_or(port_name);
129 base.len() >= 6 && base[..6].eq_ignore_ascii_case("rfcomm")
130}
131
132/// Map an enumerated serial port to a printer entry, or skip PCI/`ttyS*` noise.
133pub fn serial_device_from_port(port: &SerialPortInfo) -> Option<PrinterDevice> {
134 if !is_serial_printer_candidate(&port.port_type) && !is_rfcomm_device_name(&port.port_name) {
135 return None;
136 }
137 Some(PrinterDevice {
138 id: format!("serial:{}", port.port_name),
139 display_name: serial_port_display_name(port),
140 target: PrinterTarget::Serial(port.port_name.clone()),
141 })
142}
143
144fn serial_port_display_name(port: &SerialPortInfo) -> String {
145 match &port.port_type {
146 SerialPortType::UsbPort(info) => {
147 let product = info
148 .product
149 .as_deref()
150 .or(info.serial_number.as_deref())
151 .unwrap_or("USB device");
152 format!(
153 "{} — {product} (serial {}:{})",
154 port.port_name,
155 fmt_vid_pid(info.vid),
156 fmt_vid_pid(info.pid)
157 )
158 }
159 SerialPortType::BluetoothPort => format!("{} — Bluetooth", port.port_name),
160 _ if is_rfcomm_device_name(&port.port_name) => {
161 format!("{} — Bluetooth", port.port_name)
162 }
163 _ => format!("{} — serial", port.port_name),
164 }
165}
166
133pub fn open_printer(target: &PrinterTarget) -> Result<Box<dyn PrinterTransport>, PrintError> {
167pub fn open_printer(target: &PrinterTarget) -> Result<Box<dyn PrinterTransport>, PrintError> {
134 match target {
168 match target {
135 PrinterTarget::Serial(port) => Ok(Box::new(SerialTransport::open(port)?)),
169 PrinterTarget::Serial(port) => Ok(Box::new(SerialTransport::open(port)?)),
@@ -257,7 +291,7 @@ impl PrinterTransport for MockTransport {
257#[cfg(test)]
291#[cfg(test)]
258mod tests {
292mod tests {
259 use super::*;
293 use super::*;
260 use serialport::UsbPortInfo;
294 use serialport::{SerialPortInfo, UsbPortInfo};
261
295
262 #[test]
296 #[test]
263 fn mock_transport_records_bytes() {
297 fn mock_transport_records_bytes() {
@@ -272,23 +306,81 @@ mod tests {
272 assert!(list.is_ok());
306 assert!(list.is_ok());
273 }
307 }
274
308
309 fn sample_usb_port_type() -> SerialPortType {
310 SerialPortType::UsbPort(UsbPortInfo {
311 vid: 0x0416,
312 pid: 0x5011,
313 serial_number: None,
314 manufacturer: None,
315 product: Some("POS-58".into()),
316 })
317 }
318
275 #[test]
319 #[test]
276 fn non_usb_serial_ports_are_not_candidates() {
320 fn pci_and_unknown_serial_ports_are_not_candidates() {
277 assert!(!is_usb_serial_candidate(&SerialPortType::PciPort));
321 assert!(!is_serial_printer_candidate(&SerialPortType::PciPort));
322 assert!(!is_serial_printer_candidate(&SerialPortType::Unknown));
278 assert!(!is_usb_serial_candidate(&SerialPortType::BluetoothPort));
323 assert!(!is_usb_serial_candidate(&SerialPortType::BluetoothPort));
324 assert!(!is_usb_serial_candidate(&SerialPortType::PciPort));
279 assert!(!is_usb_serial_candidate(&SerialPortType::Unknown));
325 assert!(!is_usb_serial_candidate(&SerialPortType::Unknown));
280 }
326 }
281
327
282 #[test]
328 #[test]
283 fn usb_serial_port_is_candidate() {
329 fn usb_and_bluetooth_serial_ports_are_candidates() {
284 let usb = SerialPortType::UsbPort(UsbPortInfo {
330 let usb = sample_usb_port_type();
285 vid: 0x0416,
286 pid: 0x5011,
287 serial_number: None,
288 manufacturer: None,
289 product: Some("POS-58".into()),
290 });
291 assert!(is_usb_serial_candidate(&usb));
331 assert!(is_usb_serial_candidate(&usb));
332 assert!(is_serial_printer_candidate(&usb));
333 assert!(is_bluetooth_serial_candidate(&SerialPortType::BluetoothPort));
334 assert!(is_serial_printer_candidate(&SerialPortType::BluetoothPort));
335 }
336
337 #[test]
338 fn bluetooth_serial_device_is_labeled() {
339 let port = SerialPortInfo {
340 port_name: "COM5".into(),
341 port_type: SerialPortType::BluetoothPort,
342 };
343 let device = serial_device_from_port(&port).expect("bluetooth candidate");
344 assert_eq!(device.id, "serial:COM5");
345 assert_eq!(device.display_name, "COM5 — Bluetooth");
346 assert_eq!(device.target, PrinterTarget::Serial("COM5".into()));
347 }
348
349 #[test]
350 fn linux_rfcomm_is_listed_even_if_type_unknown() {
351 let port = SerialPortInfo {
352 port_name: "/dev/rfcomm0".into(),
353 port_type: SerialPortType::Unknown,
354 };
355 let device = serial_device_from_port(&port).expect("rfcomm candidate");
356 assert_eq!(device.display_name, "/dev/rfcomm0 — Bluetooth");
357 assert_eq!(device.target, PrinterTarget::Serial("/dev/rfcomm0".into()));
358 }
359
360 #[test]
361 fn empty_pci_ttys_ports_are_not_listed() {
362 let pci = SerialPortInfo {
363 port_name: "/dev/ttyS0".into(),
364 port_type: SerialPortType::PciPort,
365 };
366 assert!(serial_device_from_port(&pci).is_none());
367 let unknown = SerialPortInfo {
368 port_name: "/dev/ttyS1".into(),
369 port_type: SerialPortType::Unknown,
370 };
371 assert!(serial_device_from_port(&unknown).is_none());
372 }
373
374 #[test]
375 fn usb_serial_device_keeps_vid_pid_label() {
376 let port = SerialPortInfo {
377 port_name: "/dev/ttyUSB0".into(),
378 port_type: sample_usb_port_type(),
379 };
380 let device = serial_device_from_port(&port).expect("usb candidate");
381 assert!(device.display_name.contains("POS-58"));
382 assert!(device.display_name.contains("0416:5011"));
383 assert!(!device.display_name.contains("Bluetooth"));
292 }
384 }
293
385
294 #[test]
386 #[test]
src/print_dialog.rs +5 −3
@@ -320,12 +320,14 @@ impl PrintDialog {
320 320 ui.label("Port / queue:");
321 321 ui.text_edit_singleline(&mut self.manual_port);
322 322 });
323 ui.label("Examples: COM3, printer queue name (Windows), /dev/ttyUSB0 (Linux)");
323 ui.label(
324 "Examples: COM3, Bluetooth COM after pairing, printer queue (Windows), /dev/ttyUSB0 or /dev/rfcomm0 (Linux)",
325 );
324 326 } else if self.printers_loading && self.printers.is_empty() {
325 ui.label("Searching for USB, spooler, and serial printers…");
327 ui.label("Searching for USB, spooler, serial, and paired Bluetooth printers…");
326 328 } else if self.printers.is_empty() {
327 329 ui.label(
328 "No printers found. Connect a USB POS printer, refresh, or enter a port/queue manually.",
330 "No printers found. Connect a USB POS printer, pair a Classic Bluetooth SPP printer in the OS, refresh, or enter a port/queue manually.",
329 331 );
330 332 } else {
331 333 // Fixed height so wheel scrolling works; avoid nesting inside another ScrollArea.
@@ -320,12 +320,14 @@ impl PrintDialog {
320 ui.label("Port / queue:");
320 ui.label("Port / queue:");
321 ui.text_edit_singleline(&mut self.manual_port);
321 ui.text_edit_singleline(&mut self.manual_port);
322 });
322 });
323 ui.label("Examples: COM3, printer queue name (Windows), /dev/ttyUSB0 (Linux)");
323 ui.label(
324 "Examples: COM3, Bluetooth COM after pairing, printer queue (Windows), /dev/ttyUSB0 or /dev/rfcomm0 (Linux)",
325 );
324 } else if self.printers_loading && self.printers.is_empty() {
326 } else if self.printers_loading && self.printers.is_empty() {
325 ui.label("Searching for USB, spooler, and serial printers…");
327 ui.label("Searching for USB, spooler, serial, and paired Bluetooth printers…");
326 } else if self.printers.is_empty() {
328 } else if self.printers.is_empty() {
327 ui.label(
329 ui.label(
328 "No printers found. Connect a USB POS printer, refresh, or enter a port/queue manually.",
330 "No printers found. Connect a USB POS printer, pair a Classic Bluetooth SPP printer in the OS, refresh, or enter a port/queue manually.",
329 );
331 );
330 } else {
332 } else {
331 // Fixed height so wheel scrolling works; avoid nesting inside another ScrollArea.
333 // Fixed height so wheel scrolling works; avoid nesting inside another ScrollArea.