@slastra/tsplib 0.0.0-stage → 0.1.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.
@@ -0,0 +1,156 @@
1
+ import { CreditGate, parseFlow } from './flow.js';
2
+ import type { Link } from './transport.js';
3
+
4
+ /**
5
+ * The module advertises `0x18f0` (write `2af1`), the service most cheap BLE
6
+ * printers carry TSPL on. On the Y43BT that one accepts writes and does
7
+ * nothing with them. The printer is on `ff00`.
8
+ */
9
+ const SERVICE = 0xff00;
10
+ const WRITE_UUID = 0xff02;
11
+ const FLOW_UUID = 0xff03;
12
+
13
+ /** The 23-byte default ATT MTU, less the 3-byte write header. Always safe. */
14
+ const SAFE_CHUNK = 20;
15
+
16
+ export interface ConnectOptions {
17
+ /**
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.
21
+ */
22
+ namePrefix?: string;
23
+ /**
24
+ * 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.
28
+ */
29
+ maxChunk?: number;
30
+ /** How long to wait for the printer to return a credit before giving up. */
31
+ creditTimeoutMs?: number;
32
+ /** Fires if the printer drops the GATT link. */
33
+ onDisconnect?: () => void;
34
+ }
35
+
36
+ /** A connected printer. Extends {@link Link}, so it drives `printJob` directly. */
37
+ export interface BluetoothLink extends Link {
38
+ readonly deviceName: string;
39
+ /** The write size currently in use, in bytes. */
40
+ readonly chunkSize: number;
41
+ disconnect(): void;
42
+ }
43
+
44
+ /** Whether this browser exposes Web Bluetooth at all (Chromium only). */
45
+ export function hasBluetooth(): boolean {
46
+ return typeof navigator !== 'undefined' && 'bluetooth' in navigator;
47
+ }
48
+
49
+ /** Web Bluetooth is unavailable on insecure origins, localhost excepted. */
50
+ export function isSecureContext(): boolean {
51
+ return typeof window !== 'undefined' && window.isSecureContext;
52
+ }
53
+
54
+ /** Both conditions the browser must meet. */
55
+ export function isSupported(): boolean {
56
+ return hasBluetooth() && isSecureContext();
57
+ }
58
+
59
+ /**
60
+ * Connect to a printer over Web Bluetooth.
61
+ *
62
+ * Discovery matches on device NAME, never on service UUID: a service-UUID
63
+ * filter makes Chrome push a `SetDiscoveryFilter` UUID list to BlueZ, which
64
+ * segfaults `bluetoothd` 5.87 on desktop Linux. `getDevices()` is tried first
65
+ * so an already-permitted printer reconnects with no chooser at all.
66
+ *
67
+ * Must be called from a user gesture, per the Web Bluetooth spec.
68
+ */
69
+ export async function connect(options: ConnectOptions = {}): Promise<BluetoothLink> {
70
+ const { namePrefix = 'Y43BT', maxChunk = 240, creditTimeoutMs = 10000, onDisconnect } = options;
71
+
72
+ const device = await pickDevice(namePrefix);
73
+ if (!device.gatt) throw new Error('device has no GATT server');
74
+ device.addEventListener('gattserverdisconnected', () => onDisconnect?.());
75
+
76
+ const service = await (await device.gatt.connect()).getPrimaryService(SERVICE);
77
+ const writeChar = await service.getCharacteristic(WRITE_UUID);
78
+ const flowChar = await service.getCharacteristic(FLOW_UUID);
79
+
80
+ const gate = new CreditGate();
81
+ let chunk = SAFE_CHUNK;
82
+ let shrunk = false;
83
+
84
+ // The listener goes on before notifications start: the opening credit
85
+ // grant arrives the moment the subscription does, and missing it would
86
+ // leave the link waiting for credits the printer thinks it already gave.
87
+ flowChar.addEventListener('characteristicvaluechanged', (e) => {
88
+ const value = (e.target as BluetoothRemoteGATTCharacteristic).value;
89
+ if (!value) return;
90
+ const msg = parseFlow(new Uint8Array(value.buffer, value.byteOffset, value.byteLength));
91
+ if (msg.kind === 'credit') gate.grant(msg.count);
92
+ else if (msg.kind === 'mtu' && !shrunk)
93
+ chunk = Math.max(SAFE_CHUNK, Math.min(maxChunk, msg.bytes));
94
+ });
95
+ await flowChar.startNotifications();
96
+
97
+ // One job at a time: two interleaved sends would splice two labels' bytes
98
+ // together, which TSPL cannot recover from.
99
+ let queue: Promise<void> = Promise.resolve();
100
+
101
+ async function sendNow(bytes: Uint8Array) {
102
+ let at = 0;
103
+ while (at < bytes.length) {
104
+ await gate.take(creditTimeoutMs);
105
+ const size = chunk;
106
+ try {
107
+ await writeChar.writeValueWithoutResponse(
108
+ bytes.slice(at, at + size) as Uint8Array<ArrayBuffer>
109
+ );
110
+ } catch (err) {
111
+ // Nothing went out, so the credit is still ours. An oversized write
112
+ // is the one failure worth retrying, smaller; anything else is real.
113
+ gate.grant(1);
114
+ if (size <= SAFE_CHUNK) throw err;
115
+ chunk = SAFE_CHUNK;
116
+ shrunk = true;
117
+ continue;
118
+ }
119
+ at += size;
120
+ }
121
+ }
122
+
123
+ return {
124
+ deviceName: device.name ?? namePrefix,
125
+ get chunkSize() {
126
+ return chunk;
127
+ },
128
+ send(bytes) {
129
+ const run = queue.then(() => sendNow(bytes));
130
+ queue = run.catch(() => {});
131
+ return run;
132
+ },
133
+ disconnect() {
134
+ device.gatt?.disconnect();
135
+ }
136
+ };
137
+ }
138
+
139
+ async function pickDevice(namePrefix: string): Promise<BluetoothDevice> {
140
+ if (navigator.bluetooth.getDevices) {
141
+ try {
142
+ const known = await navigator.bluetooth.getDevices();
143
+ const matches = known.filter((d) => (d.name ?? '').startsWith(namePrefix));
144
+ // a dual-mode printer can leave both of its names permitted; the LE one
145
+ // is the one with the GATT services
146
+ const hit = matches.find((d) => d.name?.endsWith('_LE')) ?? matches[0];
147
+ if (hit) return hit;
148
+ } catch {
149
+ // permissions backend unavailable: fall through to a chooser
150
+ }
151
+ }
152
+ return navigator.bluetooth.requestDevice({
153
+ filters: [{ namePrefix }],
154
+ optionalServices: [SERVICE]
155
+ });
156
+ }