@slastra/tsplib 0.2.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/FINDINGS.md CHANGED
@@ -1,4 +1,4 @@
1
- # Findings: Labeer Y43BT and Core Innovations CTP800BD over BLE
1
+ # Findings: Labeer Y43BT, Core Innovations CTP800BD and POLONO PM220S over BLE
2
2
 
3
3
  How the Y43BT's BLE interface was mapped, on 2026-11-03, with a Labeer Y43BT on the bench and [bleak](https://github.com/hbldh/bleak) on Linux (BlueZ). Every claim below was checked on paper or on the wire.
4
4
 
@@ -56,6 +56,8 @@ A 112 mm ruler printed under that `SIZE` stopped right after its 101 mm tick. Th
56
56
 
57
57
  4 × 6 in gap stock prints cleanly. 2 × 1 in stock first printed the start of a label and then jammed, twice, on adhesive left in the paper path. Once that was cleaned out it printed without issue from printrow, placed correctly with the raster at `x = 0`, so the printer positions a narrow label from `SIZE` itself.
58
58
 
59
+ On 2 × 1 in stock the Y43BT prints about 2 mm low, every label alike; a CTP800BD prints the same job where it's drawn. TSPL's `SHIFT -16` made no difference on the Y43BT, so it seems to ignore `SHIFT`; moving the raster up 16 rows inside the label fixes it.
60
+
59
61
  ## Still open
60
62
 
61
63
  - The true head width, which needs a `SIZE` wider than 4 in.
@@ -87,3 +89,51 @@ After that it never sent anything else on `ff03`: no credit back after any write
87
89
  The printer runs classic and LE on the same public address, and its advertising flags (`0x02`) do not mark BR/EDR as unsupported. For a device like that, BlueZ's `Device1.Connect` picks BR/EDR: a classic bond always wins, and otherwise the "last seen" tie between the two bearers breaks toward classic. A `btmon` capture of Chrome's `gatt.connect()` shows HCI `Create Connection` (the BR/EDR page, `0x01|0x0005`), then SDP on PSM 1, then a disconnect about five seconds later, because there is no GATT over classic. Chrome reports `NetworkError: Unknown error when connecting to the device`.
88
90
 
89
91
  BlueZ 5.87 has a per-device `PreferredBearer` property, but only with `Experimental = true` in `/etc/bluetooth/main.conf`. With that on and the property set to `le` (and `Trusted` set to true), Chrome connected over LE and printed. A classic pairing from the desktop's Bluetooth settings also forces BR/EDR, so the printer should not be paired there.
92
+
93
+ ## POLONO PM220S
94
+
95
+ Probed on 2026-11-28 with bleak on Linux, through BlueZ. A 2 in battery label printer, 203 dpi, sold with POLONO's own rolls, each of which carries an RFID tag.
96
+
97
+ ### The same layout, minus the flow channel
98
+
99
+ It advertises as plain `PM220S`, with no per-unit suffix, on a public address shared by classic and LE, and its advertising flags are `0x02` again. So it needs the same `PreferredBearer = le` as the CTP800BD above. `Trusted` matters more than it looks: BlueZ recycles an untrusted device's entry between scans, and the bearer setting goes with it.
100
+
101
+ | Service | Characteristics | What it turned out to be |
102
+ | ----------------- | ------------------------------------------------- | --------------------------------------------------- |
103
+ | `ff00` | `ff02` write, `ff01` read + notify, `ff03` notify | **The printer.** TSPL on `ff02`, replies on `ff01`. |
104
+ | `18f0` | `2af1` write, `2af0` notify | Not tried: `ff02` worked first. |
105
+ | `e7810a71-…` | `bef8d6c9-…` write | Not tried. |
106
+ | `49535343-fe7d-…` | ISSC transparent UART | Not tried. |
107
+
108
+ `ff03` never notified anything: no credit grant and no write size on subscribing, and nothing during or after a job. BlueZ negotiated an ATT MTU of 517.
109
+
110
+ ### It answers
111
+
112
+ Every reply comes as a notification on `ff01`.
113
+
114
+ | Sent | Reply | Meaning |
115
+ | ----------------------- | ---------------------------------------------- | ---------------------------------------- |
116
+ | `ESC !?` | `00` | TSPL status byte: ready |
117
+ | `ESC !?` during a print | `20` | printing |
118
+ | `CONFIG?\r\n` | `"CONFIG " 00 cb 00 00 03 00 01 1d 02 01 \r\n` | 203 dpi, hardware 0.3.0, firmware 1.29.2 |
119
+ | `BATTERY?\r\n` | `"BATTERY " 80 00 \r\n` | 80 % (BCD), not charging |
120
+
121
+ `CONFIG?` and `BATTERY?` are the vendor app's own queries, and the layouts are the ones [olofj/p31s](https://github.com/olofj/p31s) documents for the P31S. `GETCHUNKSIZE`, `GETPRINTEDCOUNT` and `~!T` got no reply. Queries sent while a job is still arriving are answered once it has all arrived, not dropped.
122
+
123
+ Only the two status values above have been seen. The lid and paper bits are TSPL's documented ones and have not been provoked.
124
+
125
+ ### Printing
126
+
127
+ A 384 × 240 raster from `buildLabel` (`SIZE 48 mm, 30 mm`, `GAP 3 mm`, `DENSITY 8`, 11,617 bytes) with an edge border, rulers, text, a solid block, a 1-dot checkerboard and 1-dot lines went out as back-to-back 180-byte writes with no gating. It printed clean, dark and centered on a 50 × 30 mm label, so the 48 mm head sits in the middle of 50 mm stock. The transfer took about 3.6 s on the air, longer than the print itself. The same printer then printed from Chrome on Linux through [printrow](https://printrow.lastra.us), over Web Bluetooth.
128
+
129
+ No handshake was needed. The vendor app's config for this model sets `isEncrypt` and `rfidProtocol`, but a plain TSPL job on a fresh connection prints.
130
+
131
+ ### Rolls without a tag
132
+
133
+ The NIIMBOT B1 burns untagged stock at near-zero density, so this was the thing to rule out. A generic roll with no RFID tag printed from printrow as dark as POLONO's own. The printer was then switched off and on with that roll still loaded, so that nothing read from the tagged roll could carry over, and it printed the same again. Whatever the tag is for, the firmware (1.29.2) does not need it to print.
134
+
135
+ ### Still open
136
+
137
+ - The fault bits of the status byte: lid open, out of paper.
138
+ - Black-mark and continuous stock.
139
+ - `BITMAP` mode 3 (QuickLZ), which the vendor app uses on this model and which would shorten the transfer.
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # tsplib
2
2
 
3
- TypeScript library for TSPL raster label printing over BLE, for printers that meter writes with a credit channel.
3
+ TypeScript library for TSPL raster label printing over BLE, for printers that carry TSPL on an undocumented GATT channel, credit-metered or not.
4
4
 
5
5
  [![npm](https://img.shields.io/npm/v/@slastra/tsplib)](https://www.npmjs.com/package/@slastra/tsplib)
6
6
  [![license](https://img.shields.io/npm/l/@slastra/tsplib)](./LICENSE)
@@ -17,13 +17,17 @@ The module advertises twice, as `Y43BT-XXXX` (classic Bluetooth) and `Y43BT-XXXX
17
17
 
18
18
  The head prints at least the full 4 in (101.6 mm); its true width has not been measured past that. A narrow label needs no `x` offset: the printer places it under the head from `SIZE` alone.
19
19
 
20
- Also verified on a **Core Innovations CTP800BD**, the same module family under the name `Shipping Printer-XXXX`, on 4 × 6 in gap stock with a full-width 124 KB raster. Two things differ. It grants ten credits on subscribing and never returns another, so it has to be driven with `credits: false`. And it runs classic and LE on one public address, which on Linux makes BlueZ connect over classic and fail; [FINDINGS.md](./FINDINGS.md#core-innovations-ctp800bd) has the BlueZ setting that fixes it.
20
+ Also verified on a **Core Innovations CTP800BD**, the same module family under the name `Shipping Printer-XXXX`, on 4 × 6 in gap stock with a full-width 124 KB raster. Two things differ. It grants ten credits on subscribing and never returns another, so it is driven without credits. And it runs classic and LE on one public address, which on Linux makes BlueZ connect over classic and fail; [FINDINGS.md](./FINDINGS.md#core-innovations-ctp800bd) has the BlueZ setting that fixes it.
21
+
22
+ Also verified on a **POLONO PM220S**, a 2 in battery label printer with a 384-dot (48 mm) head, on POLONO's own 50 × 30 mm roll. It has the same `ff00` layout but a different personality: the flow channel says nothing at all, so it is driven without credits at a fixed 180-byte write, and it is the first printer here that answers. `link.readStatus()` returns the TSPL status byte and `link.readConfig()` its firmware and hardware versions. It shares the CTP800BD's one-address dual-mode habit, so Linux needs the same BlueZ setting. POLONO's rolls carry an RFID tag, but the printer does not insist on one: a generic roll with no tag prints just as dark, also after a power cycle. [FINDINGS.md](./FINDINGS.md#polono-pm220s) has the rest.
23
+
24
+ All three are in the exported `PRINTERS` table, so a bare `connect()` offers any of them in Chrome's chooser and picks the credit mode from the name it gets back. `link.printer` says which it was. To insist on one:
21
25
 
22
26
  ```ts
23
27
  const link = await connect({ namePrefix: 'Shipping Printer', credits: false });
24
28
  ```
25
29
 
26
- **How to tell if your printer is this one.** Connect over BLE and look for service `ff00` with characteristics `ff02` (write) and `ff03` (notify). If subscribing to `ff03` immediately notifies a credit grant (`01 nn`) and a write limit (`02 lo hi`), it is this module, whatever the case says. If the credits never come back after writes, use `credits: false`.
30
+ **How to tell if your printer is this one.** Connect over BLE and look for service `ff00` with characteristics `ff02` (write) and `ff03` (notify). If subscribing to `ff03` immediately notifies a credit grant (`01 nn`) and a write limit (`02 lo hi`), it is this module, whatever the case says. If the credits never come back after writes, or none are granted at all, use `credits: false`.
27
31
 
28
32
  ## Install
29
33
 
@@ -61,7 +65,20 @@ await printJob(link, [async () => job], { onProgress: (done, total) => console.l
61
65
  | `direction` | `0` | TSPL `DIRECTION`: `1` turns the label half a turn. |
62
66
  | `x`, `y` | `0` | Where the raster's top-left lands, in dots. |
63
67
 
64
- `connect` options are `namePrefix` (default `'Y43BT'`), `maxChunk` (240), `creditTimeoutMs` (10000), `credits` (`true`; `false` sends without waiting for credits, for printers that never return them) and `onDisconnect`.
68
+ `connect` options are `namePrefix` (default: every printer in `PRINTERS`), `maxChunk` (240), `creditTimeoutMs` (10000), `replyTimeoutMs` (2000), `credits` (default: the picked printer's entry in `PRINTERS`, else `true`; `false` sends without waiting for credits, for printers that never return them) and `onDisconnect`. The link reports `printer` (the `PRINTERS` entry, or `null`) and `credits`.
69
+
70
+ On a printer that answers queries, the link also reads its state:
71
+
72
+ ```ts
73
+ import { describeStatus, isFault } from '@slastra/tsplib';
74
+
75
+ const status = await link.readStatus(); // the TSPL status byte, or null
76
+ if (status !== null && isFault(status)) console.warn(describeStatus(status)); // "out of paper"
77
+
78
+ const config = await link.readConfig(); // { dpi: 203, hardware: '0.3.0', firmware: '1.29.2' }, or null
79
+ ```
80
+
81
+ Both resolve to `null` on a printer that answers nothing, and when the answer does not come in time. A query waits behind any job already being sent.
65
82
 
66
83
  Any transport with a `send(bytes)` that resolves once the bytes are accepted can drive `printJob`, so a USB `/dev/usb/lpN` writer works as well as Bluetooth.
67
84
 
@@ -70,22 +87,22 @@ Any transport with a `send(bytes)` that resolves once the bytes are accepted can
70
87
  - **Only `BITMAP` draws.** The printer's own fonts and barcodes are left unused, so the design is rendered host-side and the preview can be trusted to match the paper.
71
88
  - **In TSPL bitmaps, 1 is white.** That is the inverse of most raster formats, and getting it backwards prints a solid black slab with the design cut out of it. Padding bits are white for the same reason.
72
89
  - **Credits are the backpressure.** Every GATT write costs one credit and earns one back, so writes go out exactly as fast as the printer takes them, with no pacing timer to tune.
73
- - **The write size follows the printer.** It announces its limit (244 bytes) on the flow channel. If the browser's link never negotiated an MTU that big, the first large write fails, its credit is refunded, and the link drops to 20-byte writes for good.
90
+ - **The write size follows the printer.** It announces its limit (244 bytes) on the flow channel. If the browser's link never negotiated an MTU that big, the first large write fails, its credit is refunded, and the link drops to 20-byte writes for good. The PM220S announces nothing, so its size comes from the `PRINTERS` table.
74
91
  - **Cancelling stops between labels, never inside one.** A half-sent `BITMAP` leaves the printer reading the next job's commands as image data.
75
- - **There is no status.** Neither printer answered any of TSPL's or ESC/POS's status queries on any channel. A credit that never comes back (10 s by default) is the only fault signal, and it fails the send rather than hanging it. With `credits: false` there is no fault signal at all.
92
+ - **Status is the exception.** The Y43BT and CTP800BD answered none of TSPL's or ESC/POS's status queries on any channel. For them a credit that never comes back (10 s by default) is the only fault signal, and it fails the send rather than hanging it; with `credits: false` there is none at all. The PM220S answers `ESC !?` on `ff01`, so its state can be read before and after a job.
76
93
 
77
94
  ## Development
78
95
 
79
96
  ```bash
80
97
  bun install
81
- bun test test # job bytes, bitmap packing, credit gate, print loop, BLE transport against a fake printer
98
+ bun test test # job bytes, bitmap packing, credit gate, status parsing, print loop, BLE transport against a fake printer
82
99
  bun run check # tsc
83
100
  bun run build # emits dist/
84
101
  ```
85
102
 
86
103
  ## Credits
87
104
 
88
- The Labeer protocol findings are original work from probing the hardware directly; see [FINDINGS.md](./FINDINGS.md). TSPL is TSC's printer language, documented in its public programming manual.
105
+ The Labeer, Core Innovations and POLONO findings are original work from probing the hardware directly; see [FINDINGS.md](./FINDINGS.md). The PM220S's `CONFIG?` and `BATTERY?` layouts follow [olofj/p31s](https://github.com/olofj/p31s)'s notes on its sibling, the P31S. TSPL is TSC's printer language, documented in its public programming manual.
89
106
 
90
107
  ## License
91
108
 
package/dist/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  /**
2
- * tsplib — TSPL raster label printing, for printers that hide TSPL behind a
3
- * credit-metered BLE channel.
2
+ * tsplib — TSPL raster label printing, for printers that hide TSPL behind an
3
+ * undocumented BLE channel, credit-metered or not.
4
4
  *
5
5
  * This entry point is pure: no DOM, no Node APIs, no dependencies. The Web
6
6
  * Bluetooth transport lives behind `tsplib/web-bluetooth` so importing the job
@@ -10,4 +10,6 @@ export { DOTS_PER_MM, DEFAULT_DENSITY, DEFAULT_GAP_MM, packBitmap, buildLabel, t
10
10
  export { THRESHOLD, lumaOverWhite, imageDataToRows, type RasterRow, type PixelSource } from './raster.js';
11
11
  export { parseFlow, CreditGate, type FlowMessage } from './flow.js';
12
12
  export { printJob, type Link, type PrintJobOptions } from './transport.js';
13
+ export { STATUS_QUERY, CONFIG_QUERY, Status, isFault, describeStatus, parseConfig, type PrinterConfig } from './status.js';
14
+ export { PRINTERS, knownPrinter, type KnownPrinter } from './printers.js';
13
15
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,OAAO,EACN,WAAW,EACX,eAAe,EACf,cAAc,EACd,UAAU,EACV,UAAU,EACV,KAAK,SAAS,EACd,KAAK,YAAY,EACjB,MAAM,WAAW,CAAC;AAEnB,OAAO,EACN,SAAS,EACT,aAAa,EACb,eAAe,EACf,KAAK,SAAS,EACd,KAAK,WAAW,EAChB,MAAM,aAAa,CAAC;AAErB,OAAO,EAAE,SAAS,EAAE,UAAU,EAAE,KAAK,WAAW,EAAE,MAAM,WAAW,CAAC;AAEpE,OAAO,EAAE,QAAQ,EAAE,KAAK,IAAI,EAAE,KAAK,eAAe,EAAE,MAAM,gBAAgB,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,OAAO,EACN,WAAW,EACX,eAAe,EACf,cAAc,EACd,UAAU,EACV,UAAU,EACV,KAAK,SAAS,EACd,KAAK,YAAY,EACjB,MAAM,WAAW,CAAC;AAEnB,OAAO,EACN,SAAS,EACT,aAAa,EACb,eAAe,EACf,KAAK,SAAS,EACd,KAAK,WAAW,EAChB,MAAM,aAAa,CAAC;AAErB,OAAO,EAAE,SAAS,EAAE,UAAU,EAAE,KAAK,WAAW,EAAE,MAAM,WAAW,CAAC;AAEpE,OAAO,EAAE,QAAQ,EAAE,KAAK,IAAI,EAAE,KAAK,eAAe,EAAE,MAAM,gBAAgB,CAAC;AAE3E,OAAO,EACN,YAAY,EACZ,YAAY,EACZ,MAAM,EACN,OAAO,EACP,cAAc,EACd,WAAW,EACX,KAAK,aAAa,EAClB,MAAM,aAAa,CAAC;AAErB,OAAO,EAAE,QAAQ,EAAE,YAAY,EAAE,KAAK,YAAY,EAAE,MAAM,eAAe,CAAC"}
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  /**
2
- * tsplib — TSPL raster label printing, for printers that hide TSPL behind a
3
- * credit-metered BLE channel.
2
+ * tsplib — TSPL raster label printing, for printers that hide TSPL behind an
3
+ * undocumented BLE channel, credit-metered or not.
4
4
  *
5
5
  * This entry point is pure: no DOM, no Node APIs, no dependencies. The Web
6
6
  * Bluetooth transport lives behind `tsplib/web-bluetooth` so importing the job
@@ -10,4 +10,6 @@ export { DOTS_PER_MM, DEFAULT_DENSITY, DEFAULT_GAP_MM, packBitmap, buildLabel }
10
10
  export { THRESHOLD, lumaOverWhite, imageDataToRows } from './raster.js';
11
11
  export { parseFlow, CreditGate } from './flow.js';
12
12
  export { printJob } from './transport.js';
13
+ export { STATUS_QUERY, CONFIG_QUERY, Status, isFault, describeStatus, parseConfig } from './status.js';
14
+ export { PRINTERS, knownPrinter } from './printers.js';
13
15
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,OAAO,EACN,WAAW,EACX,eAAe,EACf,cAAc,EACd,UAAU,EACV,UAAU,EAGV,MAAM,WAAW,CAAC;AAEnB,OAAO,EACN,SAAS,EACT,aAAa,EACb,eAAe,EAGf,MAAM,aAAa,CAAC;AAErB,OAAO,EAAE,SAAS,EAAE,UAAU,EAAoB,MAAM,WAAW,CAAC;AAEpE,OAAO,EAAE,QAAQ,EAAmC,MAAM,gBAAgB,CAAC"}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,OAAO,EACN,WAAW,EACX,eAAe,EACf,cAAc,EACd,UAAU,EACV,UAAU,EAGV,MAAM,WAAW,CAAC;AAEnB,OAAO,EACN,SAAS,EACT,aAAa,EACb,eAAe,EAGf,MAAM,aAAa,CAAC;AAErB,OAAO,EAAE,SAAS,EAAE,UAAU,EAAoB,MAAM,WAAW,CAAC;AAEpE,OAAO,EAAE,QAAQ,EAAmC,MAAM,gBAAgB,CAAC;AAE3E,OAAO,EACN,YAAY,EACZ,YAAY,EACZ,MAAM,EACN,OAAO,EACP,cAAc,EACd,WAAW,EAEX,MAAM,aAAa,CAAC;AAErB,OAAO,EAAE,QAAQ,EAAE,YAAY,EAAqB,MAAM,eAAe,CAAC"}
@@ -0,0 +1,32 @@
1
+ /** A printer this library has been verified on, by what its BLE side advertises. */
2
+ export interface KnownPrinter {
3
+ /** What it is sold as. */
4
+ readonly name: string;
5
+ /** Its BLE advertised name, up to the per-unit suffix. */
6
+ readonly namePrefix: string;
7
+ /**
8
+ * Whether it hands a write credit back for every write. A printer that does
9
+ * is metered by them; one that does not has to be sent to back to back.
10
+ */
11
+ readonly credits: boolean;
12
+ /**
13
+ * Whether it answers queries on `ff01`: the TSPL status byte (`ESC !?`)
14
+ * and `CONFIG?`. Most of this module family answers nothing at all.
15
+ */
16
+ readonly status: boolean;
17
+ /**
18
+ * The write size to use on a printer that never announces one on the flow
19
+ * channel. Without it such a link stays at 20-byte writes.
20
+ */
21
+ readonly chunkBytes?: number;
22
+ }
23
+ /**
24
+ * Every printer verified so far. They share one GATT layout (TSPL on `ff00`,
25
+ * flow on `ff03`) and differ in name, in whether credits come back, and in
26
+ * whether anything answers a query.
27
+ * See FINDINGS.md for each.
28
+ */
29
+ export declare const PRINTERS: readonly KnownPrinter[];
30
+ /** The known printer a BLE device name belongs to, if any. */
31
+ export declare function knownPrinter(deviceName: string): KnownPrinter | undefined;
32
+ //# sourceMappingURL=printers.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"printers.d.ts","sourceRoot":"","sources":["../src/printers.ts"],"names":[],"mappings":"AAAA,oFAAoF;AACpF,MAAM,WAAW,YAAY;IAC5B,0BAA0B;IAC1B,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,0DAA0D;IAC1D,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;IAC5B;;;OAGG;IACH,QAAQ,CAAC,OAAO,EAAE,OAAO,CAAC;IAC1B;;;OAGG;IACH,QAAQ,CAAC,MAAM,EAAE,OAAO,CAAC;IACzB;;;OAGG;IACH,QAAQ,CAAC,UAAU,CAAC,EAAE,MAAM,CAAC;CAC7B;AAED;;;;;GAKG;AACH,eAAO,MAAM,QAAQ,EAAE,SAAS,YAAY,EAa3C,CAAC;AAEF,8DAA8D;AAC9D,wBAAgB,YAAY,CAAC,UAAU,EAAE,MAAM,GAAG,YAAY,GAAG,SAAS,CAEzE"}
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Every printer verified so far. They share one GATT layout (TSPL on `ff00`,
3
+ * flow on `ff03`) and differ in name, in whether credits come back, and in
4
+ * whether anything answers a query.
5
+ * See FINDINGS.md for each.
6
+ */
7
+ export const PRINTERS = [
8
+ // advertises `Y43BT-XXXX` (classic) and `Y43BT-XXXX_LE`; only `_LE` has GATT
9
+ { name: 'Labeer Y43BT', namePrefix: 'Y43BT', credits: true, status: false },
10
+ // grants ten credits on subscribing and never returns another
11
+ {
12
+ name: 'Core Innovations CTP800BD',
13
+ namePrefix: 'Shipping Printer',
14
+ credits: false,
15
+ status: false
16
+ },
17
+ // `ff03` stays silent: no credits and no write size, so both are set here.
18
+ // 180 bytes fits the smallest MTU a desktop or phone negotiates with it.
19
+ { name: 'POLONO PM220S', namePrefix: 'PM220S', credits: false, status: true, chunkBytes: 180 }
20
+ ];
21
+ /** The known printer a BLE device name belongs to, if any. */
22
+ export function knownPrinter(deviceName) {
23
+ return PRINTERS.find((p) => deviceName.startsWith(p.namePrefix));
24
+ }
25
+ //# sourceMappingURL=printers.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"printers.js","sourceRoot":"","sources":["../src/printers.ts"],"names":[],"mappings":"AAuBA;;;;;GAKG;AACH,MAAM,CAAC,MAAM,QAAQ,GAA4B;IAChD,6EAA6E;IAC7E,EAAE,IAAI,EAAE,cAAc,EAAE,UAAU,EAAE,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE;IAC3E,8DAA8D;IAC9D;QACC,IAAI,EAAE,2BAA2B;QACjC,UAAU,EAAE,kBAAkB;QAC9B,OAAO,EAAE,KAAK;QACd,MAAM,EAAE,KAAK;KACb;IACD,2EAA2E;IAC3E,yEAAyE;IACzE,EAAE,IAAI,EAAE,eAAe,EAAE,UAAU,EAAE,QAAQ,EAAE,OAAO,EAAE,KAAK,EAAE,MAAM,EAAE,IAAI,EAAE,UAAU,EAAE,GAAG,EAAE;CAC9F,CAAC;AAEF,8DAA8D;AAC9D,MAAM,UAAU,YAAY,CAAC,UAAkB;IAC9C,OAAO,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,UAAU,CAAC,UAAU,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC;AAClE,CAAC"}
@@ -0,0 +1,49 @@
1
+ /**
2
+ * What a printer says about itself, on the ones that say anything.
3
+ *
4
+ * The POLONO PM220S answers on `ff01`, the notify characteristic the Y43BT
5
+ * and CTP800BD leave silent. Two queries are used here: TSPL's own status
6
+ * byte, and the vendor's `CONFIG?`.
7
+ */
8
+ /** TSPL's status query. It is three bytes with no line ending. */
9
+ export declare const STATUS_QUERY: Uint8Array<ArrayBuffer>;
10
+ /** The vendor's version query, a text line like any TSPL command. */
11
+ export declare const CONFIG_QUERY: Uint8Array<ArrayBuffer>;
12
+ /**
13
+ * The bits of the TSPL status byte, as TSC documents them. On the PM220S only
14
+ * `0x00` (ready) and `0x20` (printing) have been seen on the wire; the fault
15
+ * bits are the standard's, not yet provoked on hardware.
16
+ */
17
+ export declare const Status: {
18
+ readonly HeadOpen: 1;
19
+ readonly PaperJam: 2;
20
+ readonly OutOfPaper: 4;
21
+ readonly OutOfRibbon: 8;
22
+ readonly Paused: 16;
23
+ readonly Printing: 32;
24
+ readonly OtherError: 128;
25
+ };
26
+ /** Whether the status byte reports a fault. Printing and paused are not faults. */
27
+ export declare function isFault(status: number): boolean;
28
+ /** The status byte in words: "ready", "printing", "lid open, out of paper". */
29
+ export declare function describeStatus(status: number): string;
30
+ /** The answer to `CONFIG?`. */
31
+ export interface PrinterConfig {
32
+ /** Dots per inch. */
33
+ dpi: number;
34
+ /** Hardware revision, "0.3.0" style. */
35
+ hardware: string;
36
+ /** Firmware version, "1.29.2" style. */
37
+ firmware: string;
38
+ }
39
+ /**
40
+ * Parse a `CONFIG?` reply, or return null for anything else:
41
+ *
42
+ * "CONFIG " 00 cb 00 | 00 03 00 | 01 1d 02 | 01 | \r\n
43
+ * ^203 dpi ^hw 0.3.0 ^fw 1.29.2 ^settings
44
+ *
45
+ * The layout is the one documented for the sibling P31S, and a PM220S reply
46
+ * fits it byte for byte.
47
+ */
48
+ export declare function parseConfig(raw: Uint8Array): PrinterConfig | null;
49
+ //# sourceMappingURL=status.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"status.d.ts","sourceRoot":"","sources":["../src/status.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,kEAAkE;AAClE,eAAO,MAAM,YAAY,yBAAkC,CAAC;AAE5D,qEAAqE;AACrE,eAAO,MAAM,YAAY,yBAA0C,CAAC;AAEpE;;;;GAIG;AACH,eAAO,MAAM,MAAM;;;;;;;;CAQT,CAAC;AAYX,mFAAmF;AACnF,wBAAgB,OAAO,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAE/C;AAED,+EAA+E;AAC/E,wBAAgB,cAAc,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,CAIrD;AAED,+BAA+B;AAC/B,MAAM,WAAW,aAAa;IAC7B,qBAAqB;IACrB,GAAG,EAAE,MAAM,CAAC;IACZ,wCAAwC;IACxC,QAAQ,EAAE,MAAM,CAAC;IACjB,wCAAwC;IACxC,QAAQ,EAAE,MAAM,CAAC;CACjB;AAID;;;;;;;;GAQG;AACH,wBAAgB,WAAW,CAAC,GAAG,EAAE,UAAU,GAAG,aAAa,GAAG,IAAI,CAOjE"}
package/dist/status.js ADDED
@@ -0,0 +1,66 @@
1
+ /**
2
+ * What a printer says about itself, on the ones that say anything.
3
+ *
4
+ * The POLONO PM220S answers on `ff01`, the notify characteristic the Y43BT
5
+ * and CTP800BD leave silent. Two queries are used here: TSPL's own status
6
+ * byte, and the vendor's `CONFIG?`.
7
+ */
8
+ /** TSPL's status query. It is three bytes with no line ending. */
9
+ export const STATUS_QUERY = Uint8Array.of(0x1b, 0x21, 0x3f);
10
+ /** The vendor's version query, a text line like any TSPL command. */
11
+ export const CONFIG_QUERY = new TextEncoder().encode('CONFIG?\r\n');
12
+ /**
13
+ * The bits of the TSPL status byte, as TSC documents them. On the PM220S only
14
+ * `0x00` (ready) and `0x20` (printing) have been seen on the wire; the fault
15
+ * bits are the standard's, not yet provoked on hardware.
16
+ */
17
+ export const Status = {
18
+ HeadOpen: 0x01,
19
+ PaperJam: 0x02,
20
+ OutOfPaper: 0x04,
21
+ OutOfRibbon: 0x08,
22
+ Paused: 0x10,
23
+ Printing: 0x20,
24
+ OtherError: 0x80
25
+ };
26
+ const NAMES = [
27
+ [Status.HeadOpen, 'lid open'],
28
+ [Status.PaperJam, 'paper jam'],
29
+ [Status.OutOfPaper, 'out of paper'],
30
+ [Status.OutOfRibbon, 'out of ribbon'],
31
+ [Status.Paused, 'paused'],
32
+ [Status.Printing, 'printing'],
33
+ [Status.OtherError, 'error']
34
+ ];
35
+ /** Whether the status byte reports a fault. Printing and paused are not faults. */
36
+ export function isFault(status) {
37
+ return (status & ~(Status.Printing | Status.Paused)) !== 0;
38
+ }
39
+ /** The status byte in words: "ready", "printing", "lid open, out of paper". */
40
+ export function describeStatus(status) {
41
+ if (status === 0)
42
+ return 'ready';
43
+ const said = NAMES.filter(([bit]) => status & bit).map(([, name]) => name);
44
+ return said.length ? said.join(', ') : `status 0x${status.toString(16).padStart(2, '0')}`;
45
+ }
46
+ const CONFIG_HEADER = 'CONFIG ';
47
+ /**
48
+ * Parse a `CONFIG?` reply, or return null for anything else:
49
+ *
50
+ * "CONFIG " 00 cb 00 | 00 03 00 | 01 1d 02 | 01 | \r\n
51
+ * ^203 dpi ^hw 0.3.0 ^fw 1.29.2 ^settings
52
+ *
53
+ * The layout is the one documented for the sibling P31S, and a PM220S reply
54
+ * fits it byte for byte.
55
+ */
56
+ export function parseConfig(raw) {
57
+ if (raw.length < 16)
58
+ return null;
59
+ for (let i = 0; i < CONFIG_HEADER.length; i++) {
60
+ if (raw[i] !== CONFIG_HEADER.charCodeAt(i))
61
+ return null;
62
+ }
63
+ const version = (at) => `${raw[at]}.${raw[at + 1]}.${raw[at + 2]}`;
64
+ return { dpi: raw[8], hardware: version(10), firmware: version(13) };
65
+ }
66
+ //# sourceMappingURL=status.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"status.js","sourceRoot":"","sources":["../src/status.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,kEAAkE;AAClE,MAAM,CAAC,MAAM,YAAY,GAA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AAC,EAAE,EAAE,CAAC,IAAI,CAAC,CAAC;IAC3E,OAAO,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,YAAY,MAAM,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,QAAQ,CAAC,CAAC,EAAE,GAAG,CAAC,EAAE,CAAC;AAC3F,CAAC;AAYD,MAAM,aAAa,GAAG,SAAS,CAAC;AAEhC;;;;;;;;GAQG;AACH,MAAM,UAAU,WAAW,CAAC,GAAe;IAC1C,IAAI,GAAG,CAAC,MAAM,GAAG,EAAE;QAAE,OAAO,IAAI,CAAC;IACjC,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,aAAa,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE,CAAC;QAC/C,IAAI,GAAG,CAAC,CAAC,CAAC,KAAK,aAAa,CAAC,UAAU,CAAC,CAAC,CAAC;YAAE,OAAO,IAAI,CAAC;IACzD,CAAC;IACD,MAAM,OAAO,GAAG,CAAC,EAAU,EAAE,EAAE,CAAC,GAAG,GAAG,CAAC,EAAE,CAAC,IAAI,GAAG,CAAC,EAAE,GAAG,CAAC,CAAC,IAAI,GAAG,CAAC,EAAE,GAAG,CAAC,CAAC,EAAE,CAAC;IAC3E,OAAO,EAAE,GAAG,EAAE,GAAG,CAAC,CAAC,CAAC,EAAE,QAAQ,EAAE,OAAO,CAAC,EAAE,CAAC,EAAE,QAAQ,EAAE,OAAO,CAAC,EAAE,CAAC,EAAE,CAAC;AACtE,CAAC"}
@@ -4,9 +4,10 @@
4
4
  * TSPL itself is transport-agnostic, so a USB `/dev/usb/lpN` writer or a
5
5
  * classic SPP socket drives `printJob` just as well.
6
6
  *
7
- * There is no status read. The Y43BT answered none of TSPL's (`~!T`, `ESC !?`)
8
- * or ESC/POS's status queries on any of its channels, so the link's own flow
9
- * control is the only fault signal there is.
7
+ * There is no status read at this level. Most of these printers answer none of
8
+ * TSPL's (`~!T`, `ESC !?`) or ESC/POS's status queries, so the link's own flow
9
+ * control is the only fault signal they have. The Web Bluetooth link adds
10
+ * `readStatus` for the one that does answer.
10
11
  */
11
12
  export interface Link {
12
13
  send(bytes: Uint8Array): Promise<void>;
@@ -1 +1 @@
1
- {"version":3,"file":"transport.d.ts","sourceRoot":"","sources":["../src/transport.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AACH,MAAM,WAAW,IAAI;IACpB,IAAI,CAAC,KAAK,EAAE,UAAU,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;CACvC;AAED,MAAM,WAAW,eAAe;IAC/B,8DAA8D;IAC9D,UAAU,CAAC,EAAE,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,KAAK,IAAI,CAAC;IACnD;;;;OAIG;IACH,MAAM,CAAC,EAAE,WAAW,CAAC;CACrB;AAED;;;;;;;;GAQG;AACH,wBAAsB,QAAQ,CAC7B,IAAI,EAAE,IAAI,EACV,MAAM,EAAE,CAAC,MAAM,OAAO,CAAC,UAAU,CAAC,CAAC,EAAE,EACrC,EAAE,UAAU,EAAE,MAAM,EAAE,GAAE,eAAoB,GAC1C,OAAO,CAAC,MAAM,CAAC,CAkBjB"}
1
+ {"version":3,"file":"transport.d.ts","sourceRoot":"","sources":["../src/transport.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AACH,MAAM,WAAW,IAAI;IACpB,IAAI,CAAC,KAAK,EAAE,UAAU,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;CACvC;AAED,MAAM,WAAW,eAAe;IAC/B,8DAA8D;IAC9D,UAAU,CAAC,EAAE,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,KAAK,IAAI,CAAC;IACnD;;;;OAIG;IACH,MAAM,CAAC,EAAE,WAAW,CAAC;CACrB;AAED;;;;;;;;GAQG;AACH,wBAAsB,QAAQ,CAC7B,IAAI,EAAE,IAAI,EACV,MAAM,EAAE,CAAC,MAAM,OAAO,CAAC,UAAU,CAAC,CAAC,EAAE,EACrC,EAAE,UAAU,EAAE,MAAM,EAAE,GAAE,eAAoB,GAC1C,OAAO,CAAC,MAAM,CAAC,CAkBjB"}
@@ -1 +1 @@
1
- {"version":3,"file":"transport.js","sourceRoot":"","sources":["../src/transport.ts"],"names":[],"mappings":"AAyBA;;;;;;;;GAQG;AACH,MAAM,CAAC,KAAK,UAAU,QAAQ,CAC7B,IAAU,EACV,MAAqC,EACrC,EAAE,UAAU,EAAE,MAAM,KAAsB,EAAE;IAE5C,IAAI,IAAI,GAAG,CAAC,CAAC;IACb,IAAI,IAAI,GAAoC,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC;IAC1D,IAAI,CAAC;QACJ,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,MAAM,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE,CAAC;YACxC,IAAI,MAAM,EAAE,OAAO;gBAAE,MAAM;YAC3B,MAAM,GAAG,GAAG,MAAM,IAAK,CAAC;YACxB,IAAI,GAAG,MAAM,CAAC,CAAC,GAAG,CAAC,CAAC,EAAE,EAAE,CAAC;YACzB,MAAM,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;YACrB,IAAI,GAAG,CAAC,GAAG,CAAC,CAAC;YACb,UAAU,EAAE,CAAC,IAAI,EAAE,MAAM,CAAC,MAAM,CAAC,CAAC;QACnC,CAAC;IACF,CAAC;YAAS,CAAC;QACV,mEAAmE;QACnE,kEAAkE;QAClE,IAAI,EAAE,KAAK,CAAC,GAAG,EAAE,GAAE,CAAC,CAAC,CAAC;IACvB,CAAC;IACD,OAAO,IAAI,CAAC;AACb,CAAC"}
1
+ {"version":3,"file":"transport.js","sourceRoot":"","sources":["../src/transport.ts"],"names":[],"mappings":"AA0BA;;;;;;;;GAQG;AACH,MAAM,CAAC,KAAK,UAAU,QAAQ,CAC7B,IAAU,EACV,MAAqC,EACrC,EAAE,UAAU,EAAE,MAAM,KAAsB,EAAE;IAE5C,IAAI,IAAI,GAAG,CAAC,CAAC;IACb,IAAI,IAAI,GAAoC,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC;IAC1D,IAAI,CAAC;QACJ,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,MAAM,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE,CAAC;YACxC,IAAI,MAAM,EAAE,OAAO;gBAAE,MAAM;YAC3B,MAAM,GAAG,GAAG,MAAM,IAAK,CAAC;YACxB,IAAI,GAAG,MAAM,CAAC,CAAC,GAAG,CAAC,CAAC,EAAE,EAAE,CAAC;YACzB,MAAM,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;YACrB,IAAI,GAAG,CAAC,GAAG,CAAC,CAAC;YACb,UAAU,EAAE,CAAC,IAAI,EAAE,MAAM,CAAC,MAAM,CAAC,CAAC;QACnC,CAAC;IACF,CAAC;YAAS,CAAC;QACV,mEAAmE;QACnE,kEAAkE;QAClE,IAAI,EAAE,KAAK,CAAC,GAAG,EAAE,GAAE,CAAC,CAAC,CAAC;IACvB,CAAC;IACD,OAAO,IAAI,CAAC;AACb,CAAC"}
@@ -1,20 +1,29 @@
1
+ import { PRINTERS, knownPrinter, type KnownPrinter } from './printers.js';
2
+ import { type PrinterConfig } from './status.js';
1
3
  import type { Link } from './transport.js';
4
+ export { PRINTERS, knownPrinter, type KnownPrinter };
2
5
  export interface ConnectOptions {
3
6
  /**
4
- * Device name prefix to match. The module advertises twice, `Y43BT-XXXX`
5
- * over classic Bluetooth and `Y43BT-XXXX_LE` over BLE; pick the `_LE` one
6
- * in the chooser, since that is the one with the GATT services.
7
+ * Device name prefix to match. Left out, the chooser offers every printer in
8
+ * {@link PRINTERS}, so one Connect reaches whichever is switched on.
9
+ *
10
+ * The Y43BT advertises twice, `Y43BT-XXXX` over classic Bluetooth and
11
+ * `Y43BT-XXXX_LE` over BLE; the `_LE` one is the one with the GATT services.
7
12
  */
8
13
  namePrefix?: string;
9
14
  /**
10
15
  * Largest GATT write to attempt. The printer announces its own limit on
11
- * the flow channel (244 on the Y43BT) and the smaller of the two wins. If
12
- * the browser's link turns out not to have negotiated a big enough MTU, the
13
- * first oversized write fails and the link drops to 20 bytes for good.
16
+ * the flow channel (244 on the Y43BT) and the smaller of the two wins. A
17
+ * printer that announces none, like the PM220S, uses the size in its
18
+ * {@link PRINTERS} entry instead. If the browser's link turns out not to
19
+ * have negotiated a big enough MTU, the first oversized write fails and the
20
+ * link drops to 20 bytes for good.
14
21
  */
15
22
  maxChunk?: number;
16
23
  /** How long to wait for the printer to return a credit before giving up. */
17
24
  creditTimeoutMs?: number;
25
+ /** How long to wait for the answer to a status or config query. */
26
+ replyTimeoutMs?: number;
18
27
  /**
19
28
  * Whether to meter writes by the credits on the flow channel. The Y43BT
20
29
  * returns one credit per write; the Core Innovations CTP800BD grants ten
@@ -22,6 +31,9 @@ export interface ConnectOptions {
22
31
  * eleventh write. With `false` the writes go out back to back, which that
23
32
  * printer takes without loss, but a jammed or empty printer then no longer
24
33
  * fails the send: there is no fault signal left.
34
+ *
35
+ * Left out, it follows the picked printer's entry in {@link PRINTERS}, and
36
+ * is `true` for a printer not in it.
25
37
  */
26
38
  credits?: boolean;
27
39
  /** Fires if the printer drops the GATT link. */
@@ -30,8 +42,21 @@ export interface ConnectOptions {
30
42
  /** A connected printer. Extends {@link Link}, so it drives `printJob` directly. */
31
43
  export interface BluetoothLink extends Link {
32
44
  readonly deviceName: string;
45
+ /** The known printer the device turned out to be, or null for any other. */
46
+ readonly printer: KnownPrinter | null;
47
+ /** Whether writes are metered by credits on this link. */
48
+ readonly credits: boolean;
33
49
  /** The write size currently in use, in bytes. */
34
50
  readonly chunkSize: number;
51
+ /**
52
+ * The TSPL status byte (`ESC !?`), for `describeStatus` and `isFault`. Null
53
+ * on a printer that answers no queries, and when this one does not answer
54
+ * in time. The query waits its turn behind any job already being sent, so
55
+ * it can never land in the middle of a label's bitmap.
56
+ */
57
+ readStatus(): Promise<number | null>;
58
+ /** Resolution and versions from `CONFIG?`. Null as for `readStatus`. */
59
+ readConfig(): Promise<PrinterConfig | null>;
35
60
  disconnect(): void;
36
61
  }
37
62
  /** Whether this browser exposes Web Bluetooth at all (Chromium only). */
@@ -1 +1 @@
1
- {"version":3,"file":"web-bluetooth.d.ts","sourceRoot":"","sources":["../src/web-bluetooth.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,gBAAgB,CAAC;AAc3C,MAAM,WAAW,cAAc;IAC9B;;;;OAIG;IACH,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB;;;;;OAKG;IACH,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,4EAA4E;IAC5E,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB;;;;;;;OAOG;IACH,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,gDAAgD;IAChD,YAAY,CAAC,EAAE,MAAM,IAAI,CAAC;CAC1B;AAED,mFAAmF;AACnF,MAAM,WAAW,aAAc,SAAQ,IAAI;IAC1C,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;IAC5B,iDAAiD;IACjD,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,UAAU,IAAI,IAAI,CAAC;CACnB;AAED,yEAAyE;AACzE,wBAAgB,YAAY,IAAI,OAAO,CAEtC;AAED,4EAA4E;AAC5E,wBAAgB,eAAe,IAAI,OAAO,CAEzC;AAED,6CAA6C;AAC7C,wBAAgB,WAAW,IAAI,OAAO,CAErC;AAED;;;;;;;;;GASG;AACH,wBAAsB,OAAO,CAAC,OAAO,GAAE,cAAmB,GAAG,OAAO,CAAC,aAAa,CAAC,CA0ElF"}
1
+ {"version":3,"file":"web-bluetooth.d.ts","sourceRoot":"","sources":["../src/web-bluetooth.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,QAAQ,EAAE,YAAY,EAAE,KAAK,YAAY,EAAE,MAAM,eAAe,CAAC;A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cAAmB,GAAG,OAAO,CAAC,aAAa,CAAC,CA+HlF"}
@@ -1,4 +1,7 @@
1
1
  import { CreditGate, parseFlow } from './flow.js';
2
+ import { PRINTERS, knownPrinter } from './printers.js';
3
+ import { CONFIG_QUERY, STATUS_QUERY, parseConfig } from './status.js';
4
+ export { PRINTERS, knownPrinter };
2
5
  /**
3
6
  * The module advertises `0x18f0` (write `2af1`), the service most cheap BLE
4
7
  * printers carry TSPL on. On the Y43BT that one accepts writes and does
@@ -7,6 +10,8 @@ import { CreditGate, parseFlow } from './flow.js';
7
10
  const SERVICE = 0xff00;
8
11
  const WRITE_UUID = 0xff02;
9
12
  const FLOW_UUID = 0xff03;
13
+ /** Where a printer that answers queries answers them. */
14
+ const REPLY_UUID = 0xff01;
10
15
  /** The 23-byte default ATT MTU, less the 3-byte write header. Always safe. */
11
16
  const SAFE_CHUNK = 20;
12
17
  /** Whether this browser exposes Web Bluetooth at all (Chromium only). */
@@ -32,8 +37,11 @@ export function isSupported() {
32
37
  * Must be called from a user gesture, per the Web Bluetooth spec.
33
38
  */
34
39
  export async function connect(options = {}) {
35
- const { namePrefix = 'Y43BT', maxChunk = 240, creditTimeoutMs = 10000, credits = true, onDisconnect } = options;
36
- const device = await pickDevice(namePrefix);
40
+ const { namePrefix, maxChunk = 240, creditTimeoutMs = 10000, replyTimeoutMs = 2000, onDisconnect } = options;
41
+ const prefixes = namePrefix === undefined ? PRINTERS.map((p) => p.namePrefix) : [namePrefix];
42
+ const device = await pickDevice(prefixes);
43
+ const printer = knownPrinter(device.name ?? '') ?? null;
44
+ const credits = options.credits ?? printer?.credits ?? true;
37
45
  if (!device.gatt)
38
46
  throw new Error('device has no GATT server');
39
47
  device.addEventListener('gattserverdisconnected', () => onDisconnect?.());
@@ -41,7 +49,7 @@ export async function connect(options = {}) {
41
49
  const writeChar = await service.getCharacteristic(WRITE_UUID);
42
50
  const flowChar = await service.getCharacteristic(FLOW_UUID);
43
51
  const gate = new CreditGate();
44
- let chunk = SAFE_CHUNK;
52
+ let chunk = printer?.chunkBytes ? Math.min(maxChunk, printer.chunkBytes) : SAFE_CHUNK;
45
53
  let shrunk = false;
46
54
  // The listener goes on before notifications start: the opening credit
47
55
  // grant arrives the moment the subscription does, and missing it would
@@ -57,6 +65,19 @@ export async function connect(options = {}) {
57
65
  chunk = Math.max(SAFE_CHUNK, Math.min(maxChunk, msg.bytes));
58
66
  });
59
67
  await flowChar.startNotifications();
68
+ // Replies are matched to whoever is waiting for one. With nobody waiting
69
+ // they are dropped: the printer says nothing unasked.
70
+ let onReply = null;
71
+ let replyChar = null;
72
+ if (printer?.status) {
73
+ replyChar = await service.getCharacteristic(REPLY_UUID);
74
+ replyChar.addEventListener('characteristicvaluechanged', (e) => {
75
+ const value = e.target.value;
76
+ if (value)
77
+ onReply?.(new Uint8Array(value.buffer, value.byteOffset, value.byteLength));
78
+ });
79
+ await replyChar.startNotifications();
80
+ }
60
81
  // One job at a time: two interleaved sends would splice two labels' bytes
61
82
  // together, which TSPL cannot recover from.
62
83
  let queue = Promise.resolve();
@@ -83,8 +104,41 @@ export async function connect(options = {}) {
83
104
  at += size;
84
105
  }
85
106
  }
107
+ /**
108
+ * Send a query and wait for the first reply `accept` recognizes. It runs
109
+ * on the same queue as `send`, so it goes out between jobs, never inside
110
+ * one, and two queries cannot take each other's answers.
111
+ */
112
+ function ask(query, accept) {
113
+ if (!replyChar)
114
+ return Promise.resolve(null);
115
+ const run = queue.then(async () => {
116
+ let timer;
117
+ try {
118
+ const reply = new Promise((resolve) => {
119
+ onReply = (bytes) => {
120
+ const hit = accept(bytes);
121
+ if (hit !== null)
122
+ resolve(hit);
123
+ };
124
+ timer = setTimeout(() => resolve(null), replyTimeoutMs);
125
+ });
126
+ await sendNow(query);
127
+ return await reply;
128
+ }
129
+ finally {
130
+ clearTimeout(timer);
131
+ onReply = null;
132
+ }
133
+ });
134
+ queue = run.then(() => { }, () => { });
135
+ // a query that could not be sent is an unanswered one, not a failed job
136
+ return run.catch(() => null);
137
+ }
86
138
  return {
87
- deviceName: device.name ?? namePrefix,
139
+ deviceName: device.name ?? prefixes[0],
140
+ printer,
141
+ credits,
88
142
  get chunkSize() {
89
143
  return chunk;
90
144
  },
@@ -93,16 +147,23 @@ export async function connect(options = {}) {
93
147
  queue = run.catch(() => { });
94
148
  return run;
95
149
  },
150
+ // the status reply is the one byte; anything longer is some other answer
151
+ readStatus: () => ask(STATUS_QUERY, (bytes) => (bytes.length === 1 ? bytes[0] : null)),
152
+ readConfig: () => ask(CONFIG_QUERY, parseConfig),
96
153
  disconnect() {
97
154
  device.gatt?.disconnect();
98
155
  }
99
156
  };
100
157
  }
101
- async function pickDevice(namePrefix) {
158
+ async function pickDevice(prefixes) {
159
+ const matching = (name = '') => prefixes.some((prefix) => name.startsWith(prefix));
102
160
  if (navigator.bluetooth.getDevices) {
103
161
  try {
162
+ // With more than one printer permitted, this takes the first, whether
163
+ // it is switched on or not. A caller that sees the connect fail can
164
+ // forget() it, and the next connect opens the chooser.
104
165
  const known = await navigator.bluetooth.getDevices();
105
- const matches = known.filter((d) => (d.name ?? '').startsWith(namePrefix));
166
+ const matches = known.filter((d) => matching(d.name));
106
167
  // a dual-mode printer can leave both of its names permitted; the LE one
107
168
  // is the one with the GATT services
108
169
  const hit = matches.find((d) => d.name?.endsWith('_LE')) ?? matches[0];
@@ -114,7 +175,7 @@ async function pickDevice(namePrefix) {
114
175
  }
115
176
  }
116
177
  return navigator.bluetooth.requestDevice({
117
- filters: [{ namePrefix }],
178
+ filters: prefixes.map((namePrefix) => ({ namePrefix })),
118
179
  optionalServices: [SERVICE]
119
180
  });
120
181
  }
@@ -1 +1 @@
1
- {"version":3,"file":"web-bluetooth.js","sourceRoot":"","sources":["../src/web-bluetooth.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,MAAM,WAAW,CAAC;AAGlD;;;;GAIG;AACH,MAAM,OAAO,GAAG,MAAM,CAAC;AACvB,MAAM,UAAU,GAAG,MAAM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CAAC,CAAC,UAAU,EAAE,EAAE,CAAC,CAAC,EAAE,UAAU,EAAE,CAAC,CAAC;QACvD,gBAAgB,EAAE,CAAC,OAAO,CAAC;KAC3B,CAAC,CAAC;AACJ,CAAC"}
package/package.json CHANGED
@@ -1,13 +1,15 @@
1
1
  {
2
2
  "name": "@slastra/tsplib",
3
- "version": "0.2.0",
4
- "description": "TSPL raster label printing over BLE for printers that hide TSPL behind a credit-metered GATT channel (Labeer Y43BT, Core Innovations CTP800BD, and their white-label siblings). Job builder, 1-bit raster, and a Web Bluetooth transport.",
3
+ "version": "0.4.0",
4
+ "description": "TSPL raster label printing over BLE for printers that hide TSPL behind an undocumented GATT channel (Labeer Y43BT, Core Innovations CTP800BD, POLONO PM220S, and their white-label siblings). Job builder, 1-bit raster, status read, and a Web Bluetooth transport.",
5
5
  "keywords": [
6
6
  "tspl",
7
7
  "labeer",
8
8
  "y43bt",
9
9
  "ctp800bd",
10
10
  "core-innovations",
11
+ "polono",
12
+ "pm220s",
11
13
  "thermal-printer",
12
14
  "label-printer",
13
15
  "shipping-label",
package/src/index.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  /**
2
- * tsplib — TSPL raster label printing, for printers that hide TSPL behind a
3
- * credit-metered BLE channel.
2
+ * tsplib — TSPL raster label printing, for printers that hide TSPL behind an
3
+ * undocumented BLE channel, credit-metered or not.
4
4
  *
5
5
  * This entry point is pure: no DOM, no Node APIs, no dependencies. The Web
6
6
  * Bluetooth transport lives behind `tsplib/web-bluetooth` so importing the job
@@ -28,3 +28,15 @@ export {
28
28
  export { parseFlow, CreditGate, type FlowMessage } from './flow.js';
29
29
 
30
30
  export { printJob, type Link, type PrintJobOptions } from './transport.js';
31
+
32
+ export {
33
+ STATUS_QUERY,
34
+ CONFIG_QUERY,
35
+ Status,
36
+ isFault,
37
+ describeStatus,
38
+ parseConfig,
39
+ type PrinterConfig
40
+ } from './status.js';
41
+
42
+ export { PRINTERS, knownPrinter, type KnownPrinter } from './printers.js';
@@ -0,0 +1,48 @@
1
+ /** A printer this library has been verified on, by what its BLE side advertises. */
2
+ export interface KnownPrinter {
3
+ /** What it is sold as. */
4
+ readonly name: string;
5
+ /** Its BLE advertised name, up to the per-unit suffix. */
6
+ readonly namePrefix: string;
7
+ /**
8
+ * Whether it hands a write credit back for every write. A printer that does
9
+ * is metered by them; one that does not has to be sent to back to back.
10
+ */
11
+ readonly credits: boolean;
12
+ /**
13
+ * Whether it answers queries on `ff01`: the TSPL status byte (`ESC !?`)
14
+ * and `CONFIG?`. Most of this module family answers nothing at all.
15
+ */
16
+ readonly status: boolean;
17
+ /**
18
+ * The write size to use on a printer that never announces one on the flow
19
+ * channel. Without it such a link stays at 20-byte writes.
20
+ */
21
+ readonly chunkBytes?: number;
22
+ }
23
+
24
+ /**
25
+ * Every printer verified so far. They share one GATT layout (TSPL on `ff00`,
26
+ * flow on `ff03`) and differ in name, in whether credits come back, and in
27
+ * whether anything answers a query.
28
+ * See FINDINGS.md for each.
29
+ */
30
+ export const PRINTERS: readonly KnownPrinter[] = [
31
+ // advertises `Y43BT-XXXX` (classic) and `Y43BT-XXXX_LE`; only `_LE` has GATT
32
+ { name: 'Labeer Y43BT', namePrefix: 'Y43BT', credits: true, status: false },
33
+ // grants ten credits on subscribing and never returns another
34
+ {
35
+ name: 'Core Innovations CTP800BD',
36
+ namePrefix: 'Shipping Printer',
37
+ credits: false,
38
+ status: false
39
+ },
40
+ // `ff03` stays silent: no credits and no write size, so both are set here.
41
+ // 180 bytes fits the smallest MTU a desktop or phone negotiates with it.
42
+ { name: 'POLONO PM220S', namePrefix: 'PM220S', credits: false, status: true, chunkBytes: 180 }
43
+ ];
44
+
45
+ /** The known printer a BLE device name belongs to, if any. */
46
+ export function knownPrinter(deviceName: string): KnownPrinter | undefined {
47
+ return PRINTERS.find((p) => deviceName.startsWith(p.namePrefix));
48
+ }
package/src/status.ts ADDED
@@ -0,0 +1,80 @@
1
+ /**
2
+ * What a printer says about itself, on the ones that say anything.
3
+ *
4
+ * The POLONO PM220S answers on `ff01`, the notify characteristic the Y43BT
5
+ * and CTP800BD leave silent. Two queries are used here: TSPL's own status
6
+ * byte, and the vendor's `CONFIG?`.
7
+ */
8
+
9
+ /** TSPL's status query. It is three bytes with no line ending. */
10
+ export const STATUS_QUERY = Uint8Array.of(0x1b, 0x21, 0x3f);
11
+
12
+ /** The vendor's version query, a text line like any TSPL command. */
13
+ export const CONFIG_QUERY = new TextEncoder().encode('CONFIG?\r\n');
14
+
15
+ /**
16
+ * The bits of the TSPL status byte, as TSC documents them. On the PM220S only
17
+ * `0x00` (ready) and `0x20` (printing) have been seen on the wire; the fault
18
+ * bits are the standard's, not yet provoked on hardware.
19
+ */
20
+ export const Status = {
21
+ HeadOpen: 0x01,
22
+ PaperJam: 0x02,
23
+ OutOfPaper: 0x04,
24
+ OutOfRibbon: 0x08,
25
+ Paused: 0x10,
26
+ Printing: 0x20,
27
+ OtherError: 0x80
28
+ } as const;
29
+
30
+ const NAMES: [number, string][] = [
31
+ [Status.HeadOpen, 'lid open'],
32
+ [Status.PaperJam, 'paper jam'],
33
+ [Status.OutOfPaper, 'out of paper'],
34
+ [Status.OutOfRibbon, 'out of ribbon'],
35
+ [Status.Paused, 'paused'],
36
+ [Status.Printing, 'printing'],
37
+ [Status.OtherError, 'error']
38
+ ];
39
+
40
+ /** Whether the status byte reports a fault. Printing and paused are not faults. */
41
+ export function isFault(status: number): boolean {
42
+ return (status & ~(Status.Printing | Status.Paused)) !== 0;
43
+ }
44
+
45
+ /** The status byte in words: "ready", "printing", "lid open, out of paper". */
46
+ export function describeStatus(status: number): string {
47
+ if (status === 0) return 'ready';
48
+ const said = NAMES.filter(([bit]) => status & bit).map(([, name]) => name);
49
+ return said.length ? said.join(', ') : `status 0x${status.toString(16).padStart(2, '0')}`;
50
+ }
51
+
52
+ /** The answer to `CONFIG?`. */
53
+ export interface PrinterConfig {
54
+ /** Dots per inch. */
55
+ dpi: number;
56
+ /** Hardware revision, "0.3.0" style. */
57
+ hardware: string;
58
+ /** Firmware version, "1.29.2" style. */
59
+ firmware: string;
60
+ }
61
+
62
+ const CONFIG_HEADER = 'CONFIG ';
63
+
64
+ /**
65
+ * Parse a `CONFIG?` reply, or return null for anything else:
66
+ *
67
+ * "CONFIG " 00 cb 00 | 00 03 00 | 01 1d 02 | 01 | \r\n
68
+ * ^203 dpi ^hw 0.3.0 ^fw 1.29.2 ^settings
69
+ *
70
+ * The layout is the one documented for the sibling P31S, and a PM220S reply
71
+ * fits it byte for byte.
72
+ */
73
+ export function parseConfig(raw: Uint8Array): PrinterConfig | null {
74
+ if (raw.length < 16) return null;
75
+ for (let i = 0; i < CONFIG_HEADER.length; i++) {
76
+ if (raw[i] !== CONFIG_HEADER.charCodeAt(i)) return null;
77
+ }
78
+ const version = (at: number) => `${raw[at]}.${raw[at + 1]}.${raw[at + 2]}`;
79
+ return { dpi: raw[8], hardware: version(10), firmware: version(13) };
80
+ }
package/src/transport.ts CHANGED
@@ -4,9 +4,10 @@
4
4
  * TSPL itself is transport-agnostic, so a USB `/dev/usb/lpN` writer or a
5
5
  * classic SPP socket drives `printJob` just as well.
6
6
  *
7
- * There is no status read. The Y43BT answered none of TSPL's (`~!T`, `ESC !?`)
8
- * or ESC/POS's status queries on any of its channels, so the link's own flow
9
- * control is the only fault signal there is.
7
+ * There is no status read at this level. Most of these printers answer none of
8
+ * TSPL's (`~!T`, `ESC !?`) or ESC/POS's status queries, so the link's own flow
9
+ * control is the only fault signal they have. The Web Bluetooth link adds
10
+ * `readStatus` for the one that does answer.
10
11
  */
11
12
  export interface Link {
12
13
  send(bytes: Uint8Array): Promise<void>;
@@ -1,6 +1,10 @@
1
1
  import { CreditGate, parseFlow } from './flow.js';
2
+ import { PRINTERS, knownPrinter, type KnownPrinter } from './printers.js';
3
+ import { CONFIG_QUERY, STATUS_QUERY, parseConfig, type PrinterConfig } from './status.js';
2
4
  import type { Link } from './transport.js';
3
5
 
6
+ export { PRINTERS, knownPrinter, type KnownPrinter };
7
+
4
8
  /**
5
9
  * The module advertises `0x18f0` (write `2af1`), the service most cheap BLE
6
10
  * printers carry TSPL on. On the Y43BT that one accepts writes and does
@@ -9,26 +13,34 @@ import type { Link } from './transport.js';
9
13
  const SERVICE = 0xff00;
10
14
  const WRITE_UUID = 0xff02;
11
15
  const FLOW_UUID = 0xff03;
16
+ /** Where a printer that answers queries answers them. */
17
+ const REPLY_UUID = 0xff01;
12
18
 
13
19
  /** The 23-byte default ATT MTU, less the 3-byte write header. Always safe. */
14
20
  const SAFE_CHUNK = 20;
15
21
 
16
22
  export interface ConnectOptions {
17
23
  /**
18
- * Device name prefix to match. The module advertises twice, `Y43BT-XXXX`
19
- * over classic Bluetooth and `Y43BT-XXXX_LE` over BLE; pick the `_LE` one
20
- * in the chooser, since that is the one with the GATT services.
24
+ * Device name prefix to match. Left out, the chooser offers every printer in
25
+ * {@link PRINTERS}, so one Connect reaches whichever is switched on.
26
+ *
27
+ * The Y43BT advertises twice, `Y43BT-XXXX` over classic Bluetooth and
28
+ * `Y43BT-XXXX_LE` over BLE; the `_LE` one is the one with the GATT services.
21
29
  */
22
30
  namePrefix?: string;
23
31
  /**
24
32
  * Largest GATT write to attempt. The printer announces its own limit on
25
- * the flow channel (244 on the Y43BT) and the smaller of the two wins. If
26
- * the browser's link turns out not to have negotiated a big enough MTU, the
27
- * first oversized write fails and the link drops to 20 bytes for good.
33
+ * the flow channel (244 on the Y43BT) and the smaller of the two wins. A
34
+ * printer that announces none, like the PM220S, uses the size in its
35
+ * {@link PRINTERS} entry instead. If the browser's link turns out not to
36
+ * have negotiated a big enough MTU, the first oversized write fails and the
37
+ * link drops to 20 bytes for good.
28
38
  */
29
39
  maxChunk?: number;
30
40
  /** How long to wait for the printer to return a credit before giving up. */
31
41
  creditTimeoutMs?: number;
42
+ /** How long to wait for the answer to a status or config query. */
43
+ replyTimeoutMs?: number;
32
44
  /**
33
45
  * Whether to meter writes by the credits on the flow channel. The Y43BT
34
46
  * returns one credit per write; the Core Innovations CTP800BD grants ten
@@ -36,6 +48,9 @@ export interface ConnectOptions {
36
48
  * eleventh write. With `false` the writes go out back to back, which that
37
49
  * printer takes without loss, but a jammed or empty printer then no longer
38
50
  * fails the send: there is no fault signal left.
51
+ *
52
+ * Left out, it follows the picked printer's entry in {@link PRINTERS}, and
53
+ * is `true` for a printer not in it.
39
54
  */
40
55
  credits?: boolean;
41
56
  /** Fires if the printer drops the GATT link. */
@@ -45,8 +60,21 @@ export interface ConnectOptions {
45
60
  /** A connected printer. Extends {@link Link}, so it drives `printJob` directly. */
46
61
  export interface BluetoothLink extends Link {
47
62
  readonly deviceName: string;
63
+ /** The known printer the device turned out to be, or null for any other. */
64
+ readonly printer: KnownPrinter | null;
65
+ /** Whether writes are metered by credits on this link. */
66
+ readonly credits: boolean;
48
67
  /** The write size currently in use, in bytes. */
49
68
  readonly chunkSize: number;
69
+ /**
70
+ * The TSPL status byte (`ESC !?`), for `describeStatus` and `isFault`. Null
71
+ * on a printer that answers no queries, and when this one does not answer
72
+ * in time. The query waits its turn behind any job already being sent, so
73
+ * it can never land in the middle of a label's bitmap.
74
+ */
75
+ readStatus(): Promise<number | null>;
76
+ /** Resolution and versions from `CONFIG?`. Null as for `readStatus`. */
77
+ readConfig(): Promise<PrinterConfig | null>;
50
78
  disconnect(): void;
51
79
  }
52
80
 
@@ -77,14 +105,17 @@ export function isSupported(): boolean {
77
105
  */
78
106
  export async function connect(options: ConnectOptions = {}): Promise<BluetoothLink> {
79
107
  const {
80
- namePrefix = 'Y43BT',
108
+ namePrefix,
81
109
  maxChunk = 240,
82
110
  creditTimeoutMs = 10000,
83
- credits = true,
111
+ replyTimeoutMs = 2000,
84
112
  onDisconnect
85
113
  } = options;
114
+ const prefixes = namePrefix === undefined ? PRINTERS.map((p) => p.namePrefix) : [namePrefix];
86
115
 
87
- const device = await pickDevice(namePrefix);
116
+ const device = await pickDevice(prefixes);
117
+ const printer = knownPrinter(device.name ?? '') ?? null;
118
+ const credits = options.credits ?? printer?.credits ?? true;
88
119
  if (!device.gatt) throw new Error('device has no GATT server');
89
120
  device.addEventListener('gattserverdisconnected', () => onDisconnect?.());
90
121
 
@@ -93,7 +124,7 @@ export async function connect(options: ConnectOptions = {}): Promise<BluetoothLi
93
124
  const flowChar = await service.getCharacteristic(FLOW_UUID);
94
125
 
95
126
  const gate = new CreditGate();
96
- let chunk = SAFE_CHUNK;
127
+ let chunk = printer?.chunkBytes ? Math.min(maxChunk, printer.chunkBytes) : SAFE_CHUNK;
97
128
  let shrunk = false;
98
129
 
99
130
  // The listener goes on before notifications start: the opening credit
@@ -109,6 +140,19 @@ export async function connect(options: ConnectOptions = {}): Promise<BluetoothLi
109
140
  });
110
141
  await flowChar.startNotifications();
111
142
 
143
+ // Replies are matched to whoever is waiting for one. With nobody waiting
144
+ // they are dropped: the printer says nothing unasked.
145
+ let onReply: ((bytes: Uint8Array) => void) | null = null;
146
+ let replyChar: BluetoothRemoteGATTCharacteristic | null = null;
147
+ if (printer?.status) {
148
+ replyChar = await service.getCharacteristic(REPLY_UUID);
149
+ replyChar.addEventListener('characteristicvaluechanged', (e) => {
150
+ const value = (e.target as BluetoothRemoteGATTCharacteristic).value;
151
+ if (value) onReply?.(new Uint8Array(value.buffer, value.byteOffset, value.byteLength));
152
+ });
153
+ await replyChar.startNotifications();
154
+ }
155
+
112
156
  // One job at a time: two interleaved sends would splice two labels' bytes
113
157
  // together, which TSPL cannot recover from.
114
158
  let queue: Promise<void> = Promise.resolve();
@@ -135,8 +179,42 @@ export async function connect(options: ConnectOptions = {}): Promise<BluetoothLi
135
179
  }
136
180
  }
137
181
 
182
+ /**
183
+ * Send a query and wait for the first reply `accept` recognizes. It runs
184
+ * on the same queue as `send`, so it goes out between jobs, never inside
185
+ * one, and two queries cannot take each other's answers.
186
+ */
187
+ function ask<T>(query: Uint8Array, accept: (bytes: Uint8Array) => T | null): Promise<T | null> {
188
+ if (!replyChar) return Promise.resolve(null);
189
+ const run = queue.then(async () => {
190
+ let timer: ReturnType<typeof setTimeout> | undefined;
191
+ try {
192
+ const reply = new Promise<T | null>((resolve) => {
193
+ onReply = (bytes) => {
194
+ const hit = accept(bytes);
195
+ if (hit !== null) resolve(hit);
196
+ };
197
+ timer = setTimeout(() => resolve(null), replyTimeoutMs);
198
+ });
199
+ await sendNow(query);
200
+ return await reply;
201
+ } finally {
202
+ clearTimeout(timer);
203
+ onReply = null;
204
+ }
205
+ });
206
+ queue = run.then(
207
+ () => {},
208
+ () => {}
209
+ );
210
+ // a query that could not be sent is an unanswered one, not a failed job
211
+ return run.catch(() => null);
212
+ }
213
+
138
214
  return {
139
- deviceName: device.name ?? namePrefix,
215
+ deviceName: device.name ?? prefixes[0],
216
+ printer,
217
+ credits,
140
218
  get chunkSize() {
141
219
  return chunk;
142
220
  },
@@ -145,17 +223,24 @@ export async function connect(options: ConnectOptions = {}): Promise<BluetoothLi
145
223
  queue = run.catch(() => {});
146
224
  return run;
147
225
  },
226
+ // the status reply is the one byte; anything longer is some other answer
227
+ readStatus: () => ask(STATUS_QUERY, (bytes) => (bytes.length === 1 ? bytes[0] : null)),
228
+ readConfig: () => ask(CONFIG_QUERY, parseConfig),
148
229
  disconnect() {
149
230
  device.gatt?.disconnect();
150
231
  }
151
232
  };
152
233
  }
153
234
 
154
- async function pickDevice(namePrefix: string): Promise<BluetoothDevice> {
235
+ async function pickDevice(prefixes: string[]): Promise<BluetoothDevice> {
236
+ const matching = (name = '') => prefixes.some((prefix) => name.startsWith(prefix));
155
237
  if (navigator.bluetooth.getDevices) {
156
238
  try {
239
+ // With more than one printer permitted, this takes the first, whether
240
+ // it is switched on or not. A caller that sees the connect fail can
241
+ // forget() it, and the next connect opens the chooser.
157
242
  const known = await navigator.bluetooth.getDevices();
158
- const matches = known.filter((d) => (d.name ?? '').startsWith(namePrefix));
243
+ const matches = known.filter((d) => matching(d.name));
159
244
  // a dual-mode printer can leave both of its names permitted; the LE one
160
245
  // is the one with the GATT services
161
246
  const hit = matches.find((d) => d.name?.endsWith('_LE')) ?? matches[0];
@@ -165,7 +250,7 @@ async function pickDevice(namePrefix: string): Promise<BluetoothDevice> {
165
250
  }
166
251
  }
167
252
  return navigator.bluetooth.requestDevice({
168
- filters: [{ namePrefix }],
253
+ filters: prefixes.map((namePrefix) => ({ namePrefix })),
169
254
  optionalServices: [SERVICE]
170
255
  });
171
256
  }