@potatosalad775/eqcaps-device-bridge 0.4.2 → 0.5.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.
Files changed (40) hide show
  1. package/README.md +106 -14
  2. package/dist/browser/webhid.d.ts +2 -2
  3. package/dist/browser/webhid.d.ts.map +1 -1
  4. package/dist/browser/webhid.js +23 -15
  5. package/dist/browser/webhid.js.map +1 -1
  6. package/dist/device.d.ts +49 -6
  7. package/dist/device.d.ts.map +1 -1
  8. package/dist/device.js +92 -18
  9. package/dist/device.js.map +1 -1
  10. package/dist/handler.d.ts +92 -4
  11. package/dist/handler.d.ts.map +1 -1
  12. package/dist/handler.js.map +1 -1
  13. package/dist/handlers/index.d.ts +3 -1
  14. package/dist/handlers/index.d.ts.map +1 -1
  15. package/dist/handlers/index.js +4 -0
  16. package/dist/handlers/index.js.map +1 -1
  17. package/dist/handlers/qudelix-usb-hid.d.ts +20 -13
  18. package/dist/handlers/qudelix-usb-hid.d.ts.map +1 -1
  19. package/dist/handlers/qudelix-usb-hid.js +234 -91
  20. package/dist/handlers/qudelix-usb-hid.js.map +1 -1
  21. package/dist/handlers/qudelix-v2-usb-hid.d.ts +31 -0
  22. package/dist/handlers/qudelix-v2-usb-hid.d.ts.map +1 -0
  23. package/dist/handlers/qudelix-v2-usb-hid.js +276 -0
  24. package/dist/handlers/qudelix-v2-usb-hid.js.map +1 -0
  25. package/dist/handlers/qudelix.d.ts +222 -0
  26. package/dist/handlers/qudelix.d.ts.map +1 -0
  27. package/dist/handlers/qudelix.js +646 -0
  28. package/dist/handlers/qudelix.js.map +1 -0
  29. package/dist/handlers/topping-usb-hid.d.ts +59 -0
  30. package/dist/handlers/topping-usb-hid.d.ts.map +1 -0
  31. package/dist/handlers/topping-usb-hid.js +892 -0
  32. package/dist/handlers/topping-usb-hid.js.map +1 -0
  33. package/dist/index.d.ts +2 -2
  34. package/dist/index.d.ts.map +1 -1
  35. package/dist/index.js.map +1 -1
  36. package/dist/protocols.d.ts +9 -0
  37. package/dist/protocols.d.ts.map +1 -1
  38. package/dist/protocols.js +82 -33
  39. package/dist/protocols.js.map +1 -1
  40. package/package.json +2 -2
@@ -0,0 +1,646 @@
1
+ // What the two Qudelix handlers share, as Qudelix's app for Chrome (version 4.0.3.1) drives the
2
+ // devices over USB HID: the framing, the session that opens a device, the models and their EQ
3
+ // groups, the stored-preset layouts and the filter codes. The 5K and T71 speak the first protocol
4
+ // (`qudelix-usb-hid`), the 5K Plus the second (`qudelix-v2-usb-hid`). A device says which, and
5
+ // which model it is, in its answer to the opening request; the USB ids only pick the framing.
6
+ //
7
+ // Framing, by USB vendor id, on the vendor collection (usage page 0xFF00). A packet is
8
+ // [command u16 BE, data…] and n its length:
9
+ // 0x0a12: out on report 8, or 7 when the descriptor has no report 8: [n + 1, 0x80, packet…];
10
+ // in on reports 2 and 9: [n, packet…].
11
+ // 0x1fc9: out on report 2: [0x00, n u16 BE, packet…]; in on report 1: [x, n u16 BE, packet…].
12
+ // Out reports are zero-padded to their size in the descriptor, and a packet that doesn't fit isn't
13
+ // sent. No checksums, no sequence numbers, no waits between packets.
14
+ //
15
+ // Session: input is dropped until 20 ms pass without any; then the opening request 0x0100
16
+ // [0x20, 0x00, 0x04], answered within 5 s by 0x0101 [device id u16 BE, 3 = ready, firmware, …]
17
+ // on the first protocol (other states are waited past) or 0x9000 on the second (elements 1, the
18
+ // device id, and 2, the protocol version [major, minor, revision, packet size]). Device ids: 1 the
19
+ // 5K, 2 the 5K Plus, 0x100 the T71.
20
+ //
21
+ // Second protocol: a packet is [command u16 BE, header, slice of the message], the header the
22
+ // fragment id (0–31, from 0 in each message) with 0x80 on the last fragment. A message is
23
+ // elements [id, size in 4-byte words, data padded to that size], at most 1022 bytes. The sender
24
+ // waits for an ack 0x9001 [fragment id, 0 = ok] after every fragment but the last.
25
+ //
26
+ // Groups: each model has a user EQ (0) and a speaker (headphone) EQ (1), each with its own bands,
27
+ // pre-gain, switch, headroom and presets; the 5K and 5K Plus have a single-EQ mode where one
28
+ // all-band EQ (2) replaces both. Preset indexes: 0–21 the built-in curves, 22 on the custom
29
+ // presets, 255 an edited EQ. A profile's slot ids are these indexes.
30
+ import { be16, grid, I16, readU16be, U16 } from "../bytes.js";
31
+ import { BridgeError } from "../errors.js";
32
+ import { decimals, hidFrame, sendFrame, typeCodes } from "../io.js";
33
+ import { after } from "../platform.js";
34
+ const lengthFirst = (d) => {
35
+ const n = readU16be(d, 1);
36
+ return n > d.length - 3 ? new Uint8Array(0) : d.subarray(3, 3 + n);
37
+ };
38
+ const STACKS = {
39
+ 0x0a12: {
40
+ outputs: [8, 7],
41
+ inputs: [2, 9],
42
+ wrap: (p) => [p.length + 1, 0x80, ...p],
43
+ unwrapIn: (d) => d.subarray(1, Math.min(d.length, (d[0] ?? 0) + 1)),
44
+ unwrapOut: (d) => d.subarray(2, Math.min(d.length, (d[0] ?? 0) + 1))
45
+ },
46
+ 0x1fc9: {
47
+ outputs: [2],
48
+ inputs: [1],
49
+ wrap: (p) => [0, ...be16(p.length), ...p],
50
+ unwrapIn: lengthFirst,
51
+ unwrapOut: lengthFirst
52
+ }
53
+ };
54
+ /** What a codec assumes without a device: a 0x0a12 device's report 8, 63 bytes on a 5K. */
55
+ export const OFFLINE_LINK = { vendorId: 0x0a12, reportId: 8, reportSize: 63 };
56
+ function stackOf(vendorId) {
57
+ const stack = STACKS[vendorId];
58
+ if (!stack) {
59
+ throw new BridgeError('unsupported', `Qudelix: no framing for vendor id 0x${vendorId.toString(16).padStart(4, '0')}`);
60
+ }
61
+ return stack;
62
+ }
63
+ /** The transport's link. The audio interface, which has no vendor collection, is refused. */
64
+ export function linkOf(t) {
65
+ const stack = stackOf(t.vendorId);
66
+ const vendor = (cs) => cs.flatMap((c) => [...(c.usagePage === 0xff00 ? [c] : []), ...vendor(c.children)]);
67
+ const collections = vendor(t.collections);
68
+ if (!collections.length) {
69
+ throw new BridgeError('transport', 'Qudelix: this is the audio interface; connect the control interface (usage page 0xFF00)');
70
+ }
71
+ const reports = collections.flatMap((c) => c.outputReports);
72
+ for (const reportId of stack.outputs) {
73
+ const size = reports.find((r) => r.reportId === reportId)?.size;
74
+ if (size)
75
+ return { vendorId: t.vendorId, reportId, reportSize: size };
76
+ }
77
+ throw new BridgeError('unsupported', `Qudelix: the control interface declares no output report ${stack.outputs.join(' or ')}`);
78
+ }
79
+ /** `packet` as an output report of `link`, zero-padded to its size. */
80
+ export function hidOut(link, packet) {
81
+ const bytes = stackOf(link.vendorId).wrap(packet);
82
+ if (bytes.length > link.reportSize) {
83
+ throw new BridgeError('unsupported', `Qudelix: a ${packet.length}-byte packet doesn't fit report ${link.reportId} (${link.reportSize} bytes)`);
84
+ }
85
+ const data = new Uint8Array(link.reportSize);
86
+ data.set(bytes);
87
+ return hidFrame(link.reportId, data);
88
+ }
89
+ /** The packet an output report of `link` carries. */
90
+ export const sentPacket = (link, frame) => stackOf(link.vendorId).unwrapOut(frame.data);
91
+ /** A packet: the command, big-endian, and its data. */
92
+ export const packet = (command, data = []) => [
93
+ ...be16(command),
94
+ ...data
95
+ ];
96
+ export function readBits(bytes, at, width, signed = false) {
97
+ let value = 0;
98
+ for (let i = 0; i < width; i++) {
99
+ const bit = at + i;
100
+ if (((bytes[bit >> 3] ?? 0) >> (bit & 7)) & 1)
101
+ value += 2 ** i;
102
+ }
103
+ return signed && value >= 2 ** (width - 1) ? value - 2 ** width : value;
104
+ }
105
+ export function writeBits(bytes, at, width, value) {
106
+ const raw = value < 0 ? value + 2 ** width : value;
107
+ for (let i = 0; i < width; i++) {
108
+ const bit = at + i;
109
+ const mask = 1 << (bit & 7);
110
+ const byte = bytes[bit >> 3] ?? 0;
111
+ bytes[bit >> 3] = Math.floor(raw / 2 ** i) % 2 ? byte | mask : byte & ~mask;
112
+ }
113
+ }
114
+ export function struct(...fields) {
115
+ const named = new Map();
116
+ let bits = 0;
117
+ for (const [name, width, signed] of fields) {
118
+ if (name)
119
+ named.set(name, { at: bits, bits: width, signed: signed === 'signed' });
120
+ bits += width;
121
+ }
122
+ return {
123
+ bits,
124
+ has: (name) => named.has(name),
125
+ read(bytes, at = 0) {
126
+ const out = {};
127
+ for (const [name, f] of named)
128
+ out[name] = readBits(bytes, at + f.at, f.bits, f.signed);
129
+ return out;
130
+ },
131
+ write(bytes, values, at = 0) {
132
+ for (const [name, value] of Object.entries(values)) {
133
+ const f = named.get(name);
134
+ if (f && value !== undefined)
135
+ writeBits(bytes, at + f.at, f.bits, value);
136
+ }
137
+ }
138
+ };
139
+ }
140
+ /** A copy of `bytes` with some fields of `layout` changed. */
141
+ export function withFields(bytes, layout, values) {
142
+ const out = bytes.slice();
143
+ layout.write(out, values);
144
+ return out;
145
+ }
146
+ const user = (bands, customs, freqs, channels = [1]) => ({
147
+ id: 0,
148
+ name: 'user EQ',
149
+ bands,
150
+ channels,
151
+ stereo: false,
152
+ graphic: true,
153
+ customs,
154
+ freqs
155
+ });
156
+ const speaker = (bands, freqs) => ({
157
+ id: 1,
158
+ name: 'speaker EQ',
159
+ bands,
160
+ channels: [2],
161
+ stereo: true,
162
+ graphic: false,
163
+ customs: 20,
164
+ freqs
165
+ });
166
+ const allBand = (bands) => ({
167
+ id: 2,
168
+ name: `${bands}-band EQ`,
169
+ bands,
170
+ channels: [1],
171
+ stereo: false,
172
+ graphic: true,
173
+ customs: 20,
174
+ freqs: bands
175
+ });
176
+ export const FIVE_K = 1;
177
+ export const FIVE_K_PLUS = 2;
178
+ export const T71 = 0x100;
179
+ /** By device id. */
180
+ export const QUDELIX_MODELS = {
181
+ [FIVE_K]: {
182
+ name: '5K',
183
+ protocol: 1,
184
+ // The 5K stores 20 frequencies whatever the group: two rows of 10, or one of 20.
185
+ usr: user(10, 20, 20),
186
+ spk: speaker(10, 20),
187
+ all: allBand(20),
188
+ preset: {
189
+ head: struct(['type', 1], ['impedance', 14], ['sensitivity', 11], ['xfeed', 6]),
190
+ preGains: 2,
191
+ band: struct(['filter', 4], ['gain', 10, 'signed'], ['q', 14], ['', 4])
192
+ },
193
+ groupConfig: struct(['headroom', 8, 'signed'], ['preset', 8], ['enable', 1], ['autoHeadroom', 1], ['', 14])
194
+ },
195
+ [T71]: {
196
+ name: 'T71',
197
+ protocol: 1,
198
+ usr: user(10, 10, 0, [1, 5]),
199
+ spk: speaker(10, 0),
200
+ preset: {
201
+ head: struct(['channels', 8], ['bands', 8], ['muteMask', 8], ['xfeedFront', 7], ['type', 1], ['xfeedBack', 7], ['impedance', 14], ['sensitivity', 11]),
202
+ preGains: 8,
203
+ band: struct(['filter', 4], ['gain', 10, 'signed'], ['freq', 15], ['q', 14], ['', 5])
204
+ },
205
+ groupConfig: struct(['version', 4], ['headroom', 8, 'signed'], ['preset', 8], ['enable', 1], ['invertMask', 8], ['', 3])
206
+ },
207
+ [FIVE_K_PLUS]: {
208
+ name: '5K Plus',
209
+ protocol: 2,
210
+ usr: user(10, 20, 10),
211
+ spk: speaker(20, 40),
212
+ all: allBand(30),
213
+ preset: {
214
+ head: struct(['type', 1], ['impedance', 14], ['sensitivity', 11], ['xfeed', 6], ['xspace', 6], ['geqMode', 3], ['', 23], ['', 32]),
215
+ preGains: 2,
216
+ band: struct(['filter', 4], ['gain', 10, 'signed'], ['q', 16], ['', 2])
217
+ },
218
+ groupConfig: struct(['version', 4], ['enable', 1], ['', 11], ['headroom', 8, 'signed'], ['preset', 8])
219
+ }
220
+ };
221
+ /**
222
+ * The EQ `name` drives in the device's mode: the user EQ is the all-band EQ in single-EQ mode,
223
+ * which has no speaker EQ.
224
+ */
225
+ export function groupOf(model, name, single) {
226
+ if (!single)
227
+ return model[name];
228
+ if (name === 'usr' && model.all)
229
+ return model.all;
230
+ throw new BridgeError('unsupported', `Qudelix ${model.name}: the device is in single-EQ mode (one ${model.all?.bands ?? 0}-band EQ), which has no speaker EQ`);
231
+ }
232
+ /** Refuses a channel count the bridge doesn't drive. */
233
+ function checkChannels(group, channels) {
234
+ if (group.channels.includes(channels))
235
+ return;
236
+ throw new BridgeError('unsupported', group.stereo
237
+ ? `Qudelix: the speaker EQ has ${channels} channels, which the app treats as drivers; the bridge writes one left and right pair`
238
+ : `Qudelix: the ${group.name} has ${channels} channels; the bridge drives ${group.channels.join(' or ')}`);
239
+ }
240
+ const LEFT = 1;
241
+ const RIGHT = 2;
242
+ /**
243
+ * A push's writes, one per channel mask. A left and right pair gets one write for both, or with
244
+ * `right` one each (`right.preamp` left out is `preamp`); any other group one per channel, all
245
+ * alike. Refuses a channel count the bridge doesn't drive, more bands than the group has, and
246
+ * `right` on a group that isn't a pair.
247
+ */
248
+ export function channelWrites(group, channels, { filters, preamp, right }) {
249
+ checkChannels(group, channels);
250
+ if (right !== undefined && !group.stereo) {
251
+ throw new BridgeError('invalid-request', `Qudelix: the ${group.name} has no left and right to write apart`);
252
+ }
253
+ const writes = right
254
+ ? [
255
+ { mask: LEFT, filters, preamp },
256
+ { mask: RIGHT, filters: right.filters, preamp: right.preamp ?? preamp }
257
+ ]
258
+ : group.stereo
259
+ ? [{ mask: LEFT | RIGHT, filters, preamp }]
260
+ : Array.from({ length: channels }, (_, i) => ({ mask: 1 << i, filters, preamp }));
261
+ for (const w of writes) {
262
+ if (w.filters.length > group.bands) {
263
+ throw new BridgeError('invalid-request', `Qudelix: the ${group.name} has ${group.bands} bands, not ${w.filters.length}`);
264
+ }
265
+ }
266
+ return writes;
267
+ }
268
+ /** The band writes of `writes`, in the order they are sent: band by band, each mask in turn. */
269
+ export function bandWrites(writes) {
270
+ const out = [];
271
+ const bands = Math.max(...writes.map((w) => w.filters.length));
272
+ for (let band = 0; band < bands; band++) {
273
+ for (const { mask, filters } of writes) {
274
+ const filter = filters[band];
275
+ if (filter)
276
+ out.push({ mask, band, filter });
277
+ }
278
+ }
279
+ return out;
280
+ }
281
+ /** The channels a write's mask names, as `held` keeps them. */
282
+ export function maskedChannels(held, mask) {
283
+ return [...Array(8).keys()]
284
+ .filter((ch) => mask & (1 << ch))
285
+ .map((ch) => (held[ch] ??= { filters: [] }));
286
+ }
287
+ const sameFilter = (a, b) => a === b ||
288
+ (!!a && !!b && a.type === b.type && a.freq === b.freq && a.gain === b.gain && a.q === b.q);
289
+ /** The same pre-gain, and the same filter in every band, a band never written included. */
290
+ const sameChannel = (a, b) => a.preamp === b.preamp &&
291
+ a.filters.length === b.filters.length &&
292
+ [...a.filters.keys()].every((i) => sameFilter(a.filters[i], b.filters[i]));
293
+ /**
294
+ * What a decode returns of `held`: the first channel's, and a pair's right channel where it
295
+ * differs from the left. A frame for left and right together (mask 3) writes them alike.
296
+ */
297
+ export function writtenState(group, held) {
298
+ const [left = { filters: [] }, right] = held;
299
+ return group.stereo && right && !sameChannel(left, right) ? { ...left, right } : left;
300
+ }
301
+ // --- Presets and filters ----------------------------------------------------------------------------
302
+ export const CUSTOM = 22;
303
+ export const EDITED = 255;
304
+ export const PARAMETRIC = 1;
305
+ /** Which custom preset, from 0, the preset index `slot` is; a built-in or one past the group's is refused. */
306
+ export function customOf(group, slot) {
307
+ const n = slot - CUSTOM;
308
+ if (!Number.isInteger(slot) || n < 0 || n >= group.customs) {
309
+ throw new BridgeError('invalid-request', `Qudelix: the ${group.name} saves to presets ${CUSTOM}–${CUSTOM + group.customs - 1}, not ${slot}`);
310
+ }
311
+ return n;
312
+ }
313
+ /** Filter codes. 0 is a band switched off (bypass), which reads as no filter. */
314
+ export const QUDELIX_TYPES = typeCodes('qudelix', { LPQ: 1, HPQ: 2, LSC: 3, HSC: 4, PK: 5 });
315
+ const BYPASS = 0;
316
+ /** The band write's fields: freq u16 Hz, gain s16 ×10, q u16 ×1024; pre-gain s16 ×10. */
317
+ export const QUDELIX_WIRE = {
318
+ freq: grid(1, U16),
319
+ q: { ...grid(1024, U16), min: 1 / 1024 },
320
+ gain: grid(10, I16),
321
+ preamp: grid(10, I16)
322
+ };
323
+ export function filterOf(b) {
324
+ if (b.filter === BYPASS)
325
+ return null;
326
+ return {
327
+ type: QUDELIX_TYPES.decode(b.filter),
328
+ freq: b.freq,
329
+ gain: decimals(b.gain / 10, 1),
330
+ q: b.q / 1024
331
+ };
332
+ }
333
+ export function presetSize(model, group, channels) {
334
+ const { head, preGains, band } = model.preset;
335
+ return (head.bits + 16 * (preGains + group.freqs) + channels * group.bands * band.bits) / 8;
336
+ }
337
+ /** Decodes a stored preset of `group`. A channel count the bridge doesn't drive is `unsupported`. */
338
+ export function readPreset(model, group, bytes) {
339
+ const { head, preGains, band } = model.preset;
340
+ const h = head.read(bytes);
341
+ const channels = h.channels ?? group.channels[0];
342
+ const size = presetSize(model, group, channels);
343
+ if ((h.bands ?? group.bands) !== group.bands || bytes.length !== size) {
344
+ throw new BridgeError('bad-response', `Qudelix ${model.name}: a ${bytes.length}-byte ${group.name} preset, not the ${size} its layout gives`);
345
+ }
346
+ checkChannels(group, channels);
347
+ const gainsAt = head.bits;
348
+ const freqsAt = gainsAt + 16 * preGains;
349
+ const bandsAt = freqsAt + 16 * group.freqs;
350
+ return Array.from({ length: channels }, (_, ch) => ({
351
+ preGain: readBits(bytes, gainsAt + 16 * ch, 16, true),
352
+ bands: Array.from({ length: group.bands }, (_, i) => {
353
+ const at = ch * group.bands + i;
354
+ const r = band.read(bytes, bandsAt + at * band.bits);
355
+ return {
356
+ filter: r.filter ?? 0,
357
+ gain: r.gain ?? 0,
358
+ q: r.q ?? 0,
359
+ freq: group.freqs ? readBits(bytes, freqsAt + 16 * at, 16) : (r.freq ?? 0)
360
+ };
361
+ })
362
+ }));
363
+ }
364
+ const sameBand = (a, b) => a.filter === b.filter && a.freq === b.freq && a.gain === b.gain && a.q === b.q;
365
+ /**
366
+ * What a pull returns: the first channel, and a left and right pair's right channel as `right`,
367
+ * equal or not. Another channel of a group that isn't a pair (the T71's five-channel user EQ) that
368
+ * differs from the first is reported through `log`, since a profile has one set of filters.
369
+ */
370
+ export function pullResult(log, model, group, preset, index) {
371
+ const channel = ({ preGain, bands }) => ({
372
+ filters: bands.map(filterOf),
373
+ preamp: decimals(preGain / 10, 1)
374
+ });
375
+ const [first, ...others] = preset;
376
+ if (!group.stereo) {
377
+ others.forEach((other, i) => {
378
+ if (other.preGain !== first.preGain ||
379
+ other.bands.some((b, k) => !sameBand(b, first.bands[k]))) {
380
+ log(`Qudelix ${model.name}: the ${group.name}'s channel ${i + 1} differs from channel 0, which is what the pull returns`);
381
+ }
382
+ });
383
+ }
384
+ return {
385
+ ...channel(first),
386
+ ...(group.stereo ? { right: channel(others[0]) } : {}),
387
+ ...(index === EDITED ? {} : { slot: index })
388
+ };
389
+ }
390
+ // --- Second-protocol messages -------------------------------------------------------------------
391
+ export const INIT_RSP = 0x9000;
392
+ export const ACK = 0x9001;
393
+ export const REQ = 0x9002;
394
+ export const RSP = 0x9003;
395
+ export const SET = 0x9004;
396
+ export const NOTI = 0x9005;
397
+ export const ACTION = 0x9006;
398
+ const MAX_MESSAGE = 1022;
399
+ /** The elements of a message; null when one runs past its end. */
400
+ export function elementsOf(payload) {
401
+ const out = [];
402
+ for (let at = 0; at < payload.length;) {
403
+ const size = (payload[at + 1] ?? 0) * 4;
404
+ if (at + 2 > payload.length || at + 2 + size > payload.length)
405
+ return null;
406
+ out.push({ id: payload[at], data: payload.subarray(at + 2, at + 2 + size) });
407
+ at += 2 + size;
408
+ }
409
+ return out;
410
+ }
411
+ /** One element's bytes, its data zero-padded to whole words. */
412
+ export function elementBytes(id, data) {
413
+ const words = Math.ceil(data.length / 4);
414
+ return [id, words, ...Array.from(data), ...new Array(words * 4 - data.length).fill(0)];
415
+ }
416
+ /**
417
+ * Second-protocol packets back into messages, as the app reassembles them: one message at a time,
418
+ * and a fragment out of order, repeated or of another command drops it.
419
+ */
420
+ export class Reassembly {
421
+ #command = -1;
422
+ #last = -1;
423
+ #parts = new Map();
424
+ #size = 0;
425
+ #reset() {
426
+ this.#command = -1;
427
+ this.#last = -1;
428
+ this.#parts.clear();
429
+ this.#size = 0;
430
+ return undefined;
431
+ }
432
+ /** One packet's [header, slice…]; the message once its fragments are all in. */
433
+ push(command, body) {
434
+ const header = body[0];
435
+ if (header === undefined || header & 0x60)
436
+ return this.#reset();
437
+ const id = header & 0x1f;
438
+ const data = body.slice(1);
439
+ if (this.#command < 0)
440
+ this.#command = command;
441
+ else if (this.#command !== command)
442
+ return this.#reset();
443
+ if (this.#parts.has(id) || (this.#last >= 0 && id > this.#last))
444
+ return this.#reset();
445
+ if (header & 0x80) {
446
+ if (this.#last >= 0 || [...this.#parts.keys()].some((k) => k > id))
447
+ return this.#reset();
448
+ this.#last = id;
449
+ }
450
+ if (this.#size + data.length > MAX_MESSAGE)
451
+ return this.#reset();
452
+ this.#parts.set(id, data);
453
+ this.#size += data.length;
454
+ if (this.#last < 0)
455
+ return undefined;
456
+ const out = new Uint8Array(this.#size);
457
+ let at = 0;
458
+ for (let i = 0; i <= this.#last; i++) {
459
+ const part = this.#parts.get(i);
460
+ if (!part)
461
+ return undefined;
462
+ out.set(part, at);
463
+ at += part.length;
464
+ }
465
+ this.#reset();
466
+ return out;
467
+ }
468
+ }
469
+ const OPEN_REQUEST = packet(0x0100, [0x20, 0x00, 0x04]);
470
+ const INIT_DATA = 0x0101;
471
+ const READY = 3;
472
+ const QUIET_MS = 20;
473
+ const OPEN_TIMEOUT = 5000;
474
+ const FIRMWARE = struct(['major', 6], ['minor', 6], ['revision', 4]);
475
+ const DEVICE_ID = 1;
476
+ const PROTOCOL = 2;
477
+ const isSecond = (command) => command >= INIT_RSP && command <= ACTION;
478
+ const opening = (m) => {
479
+ if (m.command === INIT_DATA)
480
+ return m.payload[2] === READY;
481
+ const ids = m.command === INIT_RSP ? elementsOf(m.payload)?.map((e) => e.id) : undefined;
482
+ return !!ids && ids.includes(DEVICE_ID) && ids.includes(PROTOCOL);
483
+ };
484
+ /** A transport's open session: one input listener, which reassembles and dispatches messages. */
485
+ export class QudelixSession {
486
+ transport;
487
+ link;
488
+ device = { id: 0, model: undefined, firmware: null, packetSize: 0 };
489
+ /** The second protocol's elements, latest first: the opening answer, answers, notifications. */
490
+ elements = new Map();
491
+ #waiters = new Set();
492
+ #reassembly = new Reassembly();
493
+ #heard = 0;
494
+ #draining = true;
495
+ #open = false;
496
+ #unsubscribe;
497
+ constructor(transport, link) {
498
+ this.transport = transport;
499
+ this.link = link;
500
+ const stack = stackOf(link.vendorId);
501
+ this.#unsubscribe = transport.onInputReport((reportId, data) => {
502
+ this.#heard++;
503
+ if (this.#draining || !stack.inputs.includes(reportId))
504
+ return;
505
+ const p = stack.unwrapIn(data);
506
+ if (p.length < 2)
507
+ return;
508
+ const command = readU16be(p, 0);
509
+ const payload = isSecond(command)
510
+ ? this.#reassembly.push(command, p.subarray(2))
511
+ : p.slice(2);
512
+ if (payload)
513
+ this.#dispatch({ command, payload });
514
+ });
515
+ }
516
+ #dispatch(m) {
517
+ if (this.#open && (m.command === RSP || m.command === NOTI))
518
+ this.#keep(m.payload);
519
+ for (const waiter of [...this.#waiters])
520
+ waiter(m);
521
+ }
522
+ #keep(payload) {
523
+ for (const e of elementsOf(payload) ?? [])
524
+ this.elements.set(e.id, e.data.slice());
525
+ }
526
+ /** Waits until 20 ms pass without input, as the app does before it opens a device. */
527
+ async drain(sleep) {
528
+ for (let waited = 0;; waited += QUIET_MS) {
529
+ const heard = this.#heard;
530
+ await sleep(QUIET_MS);
531
+ if (this.#heard === heard)
532
+ break;
533
+ if (waited >= OPEN_TIMEOUT) {
534
+ throw new BridgeError('timeout', 'Qudelix: the device never went quiet long enough to open');
535
+ }
536
+ }
537
+ this.#draining = false;
538
+ }
539
+ /** The device the opening answer describes. */
540
+ opened(m) {
541
+ const p = m.payload;
542
+ if (m.command === INIT_DATA) {
543
+ const id = readU16be(p, 0);
544
+ const { major, minor, revision } = FIRMWARE.read(p, 24);
545
+ this.device = {
546
+ id,
547
+ model: QUDELIX_MODELS[id],
548
+ firmware: [major, minor, revision],
549
+ packetSize: 0
550
+ };
551
+ }
552
+ else {
553
+ const elements = new Map(elementsOf(p).map((e) => [e.id, e.data]));
554
+ const [major = 0, minor = 0, revision = 0, size = 0] = elements.get(PROTOCOL);
555
+ if (major !== 2) {
556
+ throw new BridgeError('unsupported', `Qudelix: the device speaks protocol ${major}.${minor}.${revision}; the app and this bridge speak 2.x`);
557
+ }
558
+ const id = readBits(elements.get(DEVICE_ID), 0, 16);
559
+ this.device = {
560
+ id,
561
+ model: QUDELIX_MODELS[id],
562
+ firmware: null,
563
+ packetSize: Math.min(Math.max(size, 40), 120)
564
+ };
565
+ this.#keep(p);
566
+ }
567
+ this.#open = true;
568
+ }
569
+ /** The first message `match` accepts within `timeoutMs`. Call it before sending the request. */
570
+ expect(match, timeoutMs, what) {
571
+ return new Promise((resolve, reject) => {
572
+ const waiter = (m) => {
573
+ if (!match(m))
574
+ return;
575
+ cancel();
576
+ this.#waiters.delete(waiter);
577
+ resolve(m);
578
+ };
579
+ const cancel = after(timeoutMs, () => {
580
+ this.#waiters.delete(waiter);
581
+ reject(new BridgeError('timeout', `Qudelix: no answer to ${what} within ${timeoutMs} ms`));
582
+ });
583
+ this.#waiters.add(waiter);
584
+ });
585
+ }
586
+ /** Sends `packet` and waits for the answer `match` accepts. */
587
+ async ask(data, match, timeoutMs, what) {
588
+ const answer = this.expect(match, timeoutMs, what);
589
+ // Keeps a send failure from leaving the wait's rejection unhandled.
590
+ answer.catch(() => { });
591
+ await this.send(data);
592
+ return answer;
593
+ }
594
+ send(data) {
595
+ return sendFrame(this.transport, hidOut(this.link, data));
596
+ }
597
+ close() {
598
+ this.#unsubscribe();
599
+ }
600
+ }
601
+ const sessions = new WeakMap();
602
+ async function openSession(ctx) {
603
+ const session = new QudelixSession(ctx.transport, linkOf(ctx.transport));
604
+ try {
605
+ await session.drain(ctx.sleep);
606
+ session.opened(await session.ask(OPEN_REQUEST, opening, OPEN_TIMEOUT, 'the opening request'));
607
+ return session;
608
+ }
609
+ catch (error) {
610
+ session.close();
611
+ throw error;
612
+ }
613
+ }
614
+ /**
615
+ * The transport's session, opened on first use. One that fails to open is forgotten, so the next
616
+ * operation opens it again.
617
+ */
618
+ export function qudelixSession(ctx) {
619
+ const t = ctx.transport;
620
+ const known = sessions.get(t);
621
+ if (known)
622
+ return known;
623
+ const opening = openSession(ctx);
624
+ sessions.set(t, opening);
625
+ opening.catch(() => {
626
+ if (sessions.get(t) === opening)
627
+ sessions.delete(t);
628
+ });
629
+ return opening;
630
+ }
631
+ /** Closes and forgets a session, as the app reconnects after a failed transfer. */
632
+ export function dropSession(session) {
633
+ session.close();
634
+ sessions.delete(session.transport);
635
+ }
636
+ /** Refuses a device the handler doesn't drive, naming the handler that does. */
637
+ export function modelFor(session, protocol) {
638
+ const { id, model } = session.device;
639
+ if (model?.protocol === protocol)
640
+ return model;
641
+ const hex = `0x${id.toString(16).padStart(4, '0')}`;
642
+ throw new BridgeError('unsupported', model
643
+ ? `Qudelix: this is a ${model.name}, which speaks the ${model.protocol === 1 ? 'first protocol (qudelix-usb-hid)' : 'second protocol (qudelix-v2-usb-hid)'}`
644
+ : `Qudelix: device id ${hex} is no model this bridge knows`);
645
+ }
646
+ //# sourceMappingURL=qudelix.js.map