@slastra/tsplib 0.0.0-stage → 0.2.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 +89 -0
- package/LICENSE +21 -0
- package/README.md +91 -2
- package/dist/flow.d.ts +47 -0
- package/dist/flow.d.ts.map +1 -0
- package/dist/flow.js +52 -0
- package/dist/flow.js.map +1 -0
- package/dist/index.d.ts +13 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +13 -0
- package/dist/index.js.map +1 -0
- package/dist/raster.d.ts +32 -0
- package/dist/raster.d.ts.map +1 -0
- package/dist/raster.js +34 -0
- package/dist/raster.js.map +1 -0
- package/dist/transport.d.ts +34 -0
- package/dist/transport.d.ts.map +1 -0
- package/dist/transport.js +31 -0
- package/dist/transport.js.map +1 -0
- package/dist/tspl.d.ts +62 -0
- package/dist/tspl.d.ts.map +1 -0
- package/dist/tspl.js +87 -0
- package/dist/tspl.js.map +1 -0
- package/dist/web-bluetooth.d.ts +54 -0
- package/dist/web-bluetooth.d.ts.map +1 -0
- package/dist/web-bluetooth.js +121 -0
- package/dist/web-bluetooth.js.map +1 -0
- package/package.json +67 -5
- package/src/flow.ts +73 -0
- package/src/index.ts +30 -0
- package/src/raster.ts +49 -0
- package/src/transport.ts +57 -0
- package/src/tspl.ts +137 -0
- package/src/web-bluetooth.ts +171 -0
package/src/tspl.ts
ADDED
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
import type { RasterRow } from './raster.js';
|
|
2
|
+
|
|
3
|
+
/** Dots per millimetre at 203 dpi, the resolution of every printer verified here. */
|
|
4
|
+
export const DOTS_PER_MM = 8;
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* How the printer finds the start of each label.
|
|
8
|
+
*
|
|
9
|
+
* - `gap`: die-cut labels on a liner, found by the see-through gap between them.
|
|
10
|
+
* - `mark`: continuous stock with a black mark printed on the back.
|
|
11
|
+
* - `continuous`: no marks at all; the label is exactly as long as `heightMm`.
|
|
12
|
+
*/
|
|
13
|
+
export type MediaType = 'gap' | 'mark' | 'continuous';
|
|
14
|
+
|
|
15
|
+
export interface LabelOptions {
|
|
16
|
+
/** Label width across the head. TSPL clips anything drawn past it. */
|
|
17
|
+
widthMm: number;
|
|
18
|
+
/** Label length along the feed. */
|
|
19
|
+
heightMm: number;
|
|
20
|
+
media?: MediaType;
|
|
21
|
+
/** Gap or mark length. Ignored for continuous stock. */
|
|
22
|
+
gapMm?: number;
|
|
23
|
+
/** Burn darkness, 0–15. */
|
|
24
|
+
density?: number;
|
|
25
|
+
/** Copies of this label. They cost nothing extra on the wire. */
|
|
26
|
+
copies?: number;
|
|
27
|
+
/**
|
|
28
|
+
* TSPL `DIRECTION`: 0 prints the raster as drawn with its top leaving the
|
|
29
|
+
* printer first, 1 turns it half a turn. Not a quarter turn: rotating a
|
|
30
|
+
* design to fit the stock is the caller's job.
|
|
31
|
+
*/
|
|
32
|
+
direction?: 0 | 1;
|
|
33
|
+
/** Where the raster's top-left corner lands on the label, in dots. */
|
|
34
|
+
x?: number;
|
|
35
|
+
y?: number;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export const DEFAULT_DENSITY = 8;
|
|
39
|
+
export const DEFAULT_GAP_MM = 3;
|
|
40
|
+
|
|
41
|
+
const enc = new TextEncoder();
|
|
42
|
+
|
|
43
|
+
/** TSPL takes decimals but chokes on exponents; two places is finer than a dot. */
|
|
44
|
+
function mm(n: number): string {
|
|
45
|
+
return `${Math.round(n * 100) / 100} mm`;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function int(name: string, n: number, min: number, max: number): number {
|
|
49
|
+
if (!Number.isInteger(n) || n < min || n > max) {
|
|
50
|
+
throw new RangeError(`${name} must be an integer from ${min} to ${max}, got ${n}`);
|
|
51
|
+
}
|
|
52
|
+
return n;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Pack rows of dots into TSPL `BITMAP` data: MSB first, rows padded to whole
|
|
57
|
+
* bytes, and **1 is white**. That last part is the inverse of the row
|
|
58
|
+
* convention above and of most raster formats, so it is the bug to expect:
|
|
59
|
+
* get it backwards and the label comes out a solid black slab with the design
|
|
60
|
+
* cut out of it. Padding is white for the same reason.
|
|
61
|
+
*
|
|
62
|
+
* Every row must be the same width. A ragged row would not hang the printer
|
|
63
|
+
* the way it does under YPL, but it would shear everything below it sideways,
|
|
64
|
+
* so it is refused rather than sent.
|
|
65
|
+
*/
|
|
66
|
+
export function packBitmap(rows: RasterRow[]): { widthBytes: number; data: Uint8Array } {
|
|
67
|
+
const width = rows[0]?.length ?? 0;
|
|
68
|
+
const widthBytes = Math.ceil(width / 8);
|
|
69
|
+
const data = new Uint8Array(widthBytes * rows.length).fill(0xff);
|
|
70
|
+
rows.forEach((row, y) => {
|
|
71
|
+
if (row.length !== width) {
|
|
72
|
+
throw new RangeError(`row ${y} is ${row.length} dots wide, expected ${width}`);
|
|
73
|
+
}
|
|
74
|
+
const base = y * widthBytes;
|
|
75
|
+
for (let x = 0; x < width; x++) {
|
|
76
|
+
if (row[x]) data[base + (x >> 3)] &= ~(0x80 >> (x & 7));
|
|
77
|
+
}
|
|
78
|
+
});
|
|
79
|
+
return { widthBytes, data };
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
function concat(parts: Uint8Array[]): Uint8Array {
|
|
83
|
+
const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));
|
|
84
|
+
let at = 0;
|
|
85
|
+
for (const p of parts) {
|
|
86
|
+
out.set(p, at);
|
|
87
|
+
at += p.length;
|
|
88
|
+
}
|
|
89
|
+
return out;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* One complete TSPL job for a single raster label: page setup, the bitmap,
|
|
94
|
+
* and the print command. The whole thing is self-contained, so a batch is
|
|
95
|
+
* just these laid end to end and a dropped job never leaves state behind for
|
|
96
|
+
* the next one.
|
|
97
|
+
*
|
|
98
|
+
* Only `BITMAP` draws. The printer's own fonts and barcode symbologies are
|
|
99
|
+
* deliberately unused: a host-side raster is the only way the preview can be
|
|
100
|
+
* trusted to match the paper.
|
|
101
|
+
*/
|
|
102
|
+
export function buildLabel(rows: RasterRow[], options: LabelOptions): Uint8Array {
|
|
103
|
+
const {
|
|
104
|
+
widthMm,
|
|
105
|
+
heightMm,
|
|
106
|
+
media = 'gap',
|
|
107
|
+
gapMm = DEFAULT_GAP_MM,
|
|
108
|
+
density = DEFAULT_DENSITY,
|
|
109
|
+
copies = 1,
|
|
110
|
+
direction = 0,
|
|
111
|
+
x = 0,
|
|
112
|
+
y = 0
|
|
113
|
+
} = options;
|
|
114
|
+
if (!(widthMm > 0) || !(heightMm > 0)) {
|
|
115
|
+
throw new RangeError(`label size must be positive, got ${widthMm} x ${heightMm} mm`);
|
|
116
|
+
}
|
|
117
|
+
if (rows.length === 0 || rows[0].length === 0) throw new RangeError('raster is empty');
|
|
118
|
+
int('density', density, 0, 15);
|
|
119
|
+
int('copies', copies, 1, 65535);
|
|
120
|
+
int('x', x, 0, 65535);
|
|
121
|
+
int('y', y, 0, 65535);
|
|
122
|
+
|
|
123
|
+
const gap =
|
|
124
|
+
media === 'mark'
|
|
125
|
+
? `BLINE ${mm(gapMm)}, 0 mm`
|
|
126
|
+
: `GAP ${media === 'continuous' ? '0 mm' : mm(gapMm)}, 0 mm`;
|
|
127
|
+
const { widthBytes, data } = packBitmap(rows);
|
|
128
|
+
const head = [
|
|
129
|
+
`SIZE ${mm(widthMm)}, ${mm(heightMm)}`,
|
|
130
|
+
gap,
|
|
131
|
+
`DIRECTION ${direction}`,
|
|
132
|
+
`DENSITY ${density}`,
|
|
133
|
+
'CLS',
|
|
134
|
+
`BITMAP ${x},${y},${widthBytes},${rows.length},0,`
|
|
135
|
+
].join('\r\n');
|
|
136
|
+
return concat([enc.encode(head), data, enc.encode(`\r\nPRINT 1,${copies}\r\n`)]);
|
|
137
|
+
}
|
|
@@ -0,0 +1,171 @@
|
|
|
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
|
+
/**
|
|
33
|
+
* Whether to meter writes by the credits on the flow channel. The Y43BT
|
|
34
|
+
* returns one credit per write; the Core Innovations CTP800BD grants ten
|
|
35
|
+
* on subscribing and never returns another, so metering it stalls on the
|
|
36
|
+
* eleventh write. With `false` the writes go out back to back, which that
|
|
37
|
+
* printer takes without loss, but a jammed or empty printer then no longer
|
|
38
|
+
* fails the send: there is no fault signal left.
|
|
39
|
+
*/
|
|
40
|
+
credits?: boolean;
|
|
41
|
+
/** Fires if the printer drops the GATT link. */
|
|
42
|
+
onDisconnect?: () => void;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** A connected printer. Extends {@link Link}, so it drives `printJob` directly. */
|
|
46
|
+
export interface BluetoothLink extends Link {
|
|
47
|
+
readonly deviceName: string;
|
|
48
|
+
/** The write size currently in use, in bytes. */
|
|
49
|
+
readonly chunkSize: number;
|
|
50
|
+
disconnect(): void;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** Whether this browser exposes Web Bluetooth at all (Chromium only). */
|
|
54
|
+
export function hasBluetooth(): boolean {
|
|
55
|
+
return typeof navigator !== 'undefined' && 'bluetooth' in navigator;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** Web Bluetooth is unavailable on insecure origins, localhost excepted. */
|
|
59
|
+
export function isSecureContext(): boolean {
|
|
60
|
+
return typeof window !== 'undefined' && window.isSecureContext;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** Both conditions the browser must meet. */
|
|
64
|
+
export function isSupported(): boolean {
|
|
65
|
+
return hasBluetooth() && isSecureContext();
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* Connect to a printer over Web Bluetooth.
|
|
70
|
+
*
|
|
71
|
+
* Discovery matches on device NAME, never on service UUID: a service-UUID
|
|
72
|
+
* filter makes Chrome push a `SetDiscoveryFilter` UUID list to BlueZ, which
|
|
73
|
+
* segfaults `bluetoothd` 5.87 on desktop Linux. `getDevices()` is tried first
|
|
74
|
+
* so an already-permitted printer reconnects with no chooser at all.
|
|
75
|
+
*
|
|
76
|
+
* Must be called from a user gesture, per the Web Bluetooth spec.
|
|
77
|
+
*/
|
|
78
|
+
export async function connect(options: ConnectOptions = {}): Promise<BluetoothLink> {
|
|
79
|
+
const {
|
|
80
|
+
namePrefix = 'Y43BT',
|
|
81
|
+
maxChunk = 240,
|
|
82
|
+
creditTimeoutMs = 10000,
|
|
83
|
+
credits = true,
|
|
84
|
+
onDisconnect
|
|
85
|
+
} = options;
|
|
86
|
+
|
|
87
|
+
const device = await pickDevice(namePrefix);
|
|
88
|
+
if (!device.gatt) throw new Error('device has no GATT server');
|
|
89
|
+
device.addEventListener('gattserverdisconnected', () => onDisconnect?.());
|
|
90
|
+
|
|
91
|
+
const service = await (await device.gatt.connect()).getPrimaryService(SERVICE);
|
|
92
|
+
const writeChar = await service.getCharacteristic(WRITE_UUID);
|
|
93
|
+
const flowChar = await service.getCharacteristic(FLOW_UUID);
|
|
94
|
+
|
|
95
|
+
const gate = new CreditGate();
|
|
96
|
+
let chunk = SAFE_CHUNK;
|
|
97
|
+
let shrunk = false;
|
|
98
|
+
|
|
99
|
+
// The listener goes on before notifications start: the opening credit
|
|
100
|
+
// grant arrives the moment the subscription does, and missing it would
|
|
101
|
+
// leave the link waiting for credits the printer thinks it already gave.
|
|
102
|
+
flowChar.addEventListener('characteristicvaluechanged', (e) => {
|
|
103
|
+
const value = (e.target as BluetoothRemoteGATTCharacteristic).value;
|
|
104
|
+
if (!value) return;
|
|
105
|
+
const msg = parseFlow(new Uint8Array(value.buffer, value.byteOffset, value.byteLength));
|
|
106
|
+
if (msg.kind === 'credit') gate.grant(msg.count);
|
|
107
|
+
else if (msg.kind === 'mtu' && !shrunk)
|
|
108
|
+
chunk = Math.max(SAFE_CHUNK, Math.min(maxChunk, msg.bytes));
|
|
109
|
+
});
|
|
110
|
+
await flowChar.startNotifications();
|
|
111
|
+
|
|
112
|
+
// One job at a time: two interleaved sends would splice two labels' bytes
|
|
113
|
+
// together, which TSPL cannot recover from.
|
|
114
|
+
let queue: Promise<void> = Promise.resolve();
|
|
115
|
+
|
|
116
|
+
async function sendNow(bytes: Uint8Array) {
|
|
117
|
+
let at = 0;
|
|
118
|
+
while (at < bytes.length) {
|
|
119
|
+
if (credits) await gate.take(creditTimeoutMs);
|
|
120
|
+
const size = chunk;
|
|
121
|
+
try {
|
|
122
|
+
await writeChar.writeValueWithoutResponse(
|
|
123
|
+
bytes.slice(at, at + size) as Uint8Array<ArrayBuffer>
|
|
124
|
+
);
|
|
125
|
+
} catch (err) {
|
|
126
|
+
// Nothing went out, so the credit is still ours. An oversized write
|
|
127
|
+
// is the one failure worth retrying, smaller; anything else is real.
|
|
128
|
+
if (credits) gate.grant(1);
|
|
129
|
+
if (size <= SAFE_CHUNK) throw err;
|
|
130
|
+
chunk = SAFE_CHUNK;
|
|
131
|
+
shrunk = true;
|
|
132
|
+
continue;
|
|
133
|
+
}
|
|
134
|
+
at += size;
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
return {
|
|
139
|
+
deviceName: device.name ?? namePrefix,
|
|
140
|
+
get chunkSize() {
|
|
141
|
+
return chunk;
|
|
142
|
+
},
|
|
143
|
+
send(bytes) {
|
|
144
|
+
const run = queue.then(() => sendNow(bytes));
|
|
145
|
+
queue = run.catch(() => {});
|
|
146
|
+
return run;
|
|
147
|
+
},
|
|
148
|
+
disconnect() {
|
|
149
|
+
device.gatt?.disconnect();
|
|
150
|
+
}
|
|
151
|
+
};
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
async function pickDevice(namePrefix: string): Promise<BluetoothDevice> {
|
|
155
|
+
if (navigator.bluetooth.getDevices) {
|
|
156
|
+
try {
|
|
157
|
+
const known = await navigator.bluetooth.getDevices();
|
|
158
|
+
const matches = known.filter((d) => (d.name ?? '').startsWith(namePrefix));
|
|
159
|
+
// a dual-mode printer can leave both of its names permitted; the LE one
|
|
160
|
+
// is the one with the GATT services
|
|
161
|
+
const hit = matches.find((d) => d.name?.endsWith('_LE')) ?? matches[0];
|
|
162
|
+
if (hit) return hit;
|
|
163
|
+
} catch {
|
|
164
|
+
// permissions backend unavailable: fall through to a chooser
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
return navigator.bluetooth.requestDevice({
|
|
168
|
+
filters: [{ namePrefix }],
|
|
169
|
+
optionalServices: [SERVICE]
|
|
170
|
+
});
|
|
171
|
+
}
|