@loksly/usb-ly 0.0.0-stage → 0.2.2

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Loksly
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,31 @@
1
- # Temporary Holding Version
1
+ # @loksly/usb-ly
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A Node.js driver for the Thermalright **LY** USB LCD panels (Trofeo Vision
4
+ 9.16 and siblings, USB `0416:5408` / `0416:5409`), over libusb. No Python, no
5
+ `trcc`.
6
+
7
+ ```js
8
+ import { LyPanel } from '@loksly/usb-ly';
9
+
10
+ const panel = await LyPanel.open({ serial: '202592047DAE' }); // or no serial: the first one
11
+ console.log(panel.info); // { pm: 65, sub: 5, model: { width: 1920, height: 462, rotate: 180 }, … }
12
+ const kept = await panel.send(jpegBuffer); // false: the panel dropped it (too big)
13
+ await panel.close();
14
+ ```
15
+
16
+ - **A frame is never silently lost.** `send` reads the panel's ACK: byte 8 is
17
+ 1 when it kept the frame and 2 when it dropped it (the limit is 511 871
18
+ bytes). Without that, the write succeeds and the screen keeps the old picture.
19
+ - **Resend an unchanged frame every second or so**: the firmware shows the
20
+ factory logo again after 2–3 s without one. That is the caller's job
21
+ (Kiosko's `usb` driver does it).
22
+ - **A serial that is not found is an error**, never "another panel".
23
+ - `protocol.ts` is pure (no I/O) and its output is byte-identical to
24
+ thermalright-trcc-linux 9.12 (the tests compare against vectors generated by
25
+ `trcc` itself); `transport.ts` is the only part that touches libusb.
26
+
27
+ `usb` is an optional dependency: on Windows the panel needs the WinUSB driver,
28
+ on Linux a udev rule. See [docs/usb.md](../../docs/usb.md).
29
+
30
+ Not covered: other Thermalright protocols (SCSI, HID, 320×240), LED control.
31
+ MIT.
@@ -0,0 +1,3 @@
1
+ export * from './protocol.ts';
2
+ export * from './transport.ts';
3
+ export * from './panel.ts';
package/dist/index.js ADDED
@@ -0,0 +1,3 @@
1
+ export * from "./protocol.js";
2
+ export * from "./transport.js";
3
+ export * from "./panel.js";
@@ -0,0 +1,32 @@
1
+ import { type Handshake, type PanelModel } from './protocol.ts';
2
+ import { type OpenOptions, type Transport } from './transport.ts';
3
+ export interface PanelInfo extends Handshake {
4
+ pid: number;
5
+ serial?: string;
6
+ /** Where it is plugged (`bus-address`). */
7
+ location?: string;
8
+ /** What trcc knows about this model, if anything. */
9
+ model?: PanelModel;
10
+ }
11
+ /** One connected panel: say hello once, then `send` JPEG frames. Sends never overlap. */
12
+ export declare class LyPanel {
13
+ private queue;
14
+ info: PanelInfo | null;
15
+ private readonly transport;
16
+ readonly pid: number;
17
+ private readonly meta;
18
+ constructor(transport: Transport, pid: number, meta?: {
19
+ serial?: string;
20
+ location?: string;
21
+ });
22
+ /** Opens the first (or `serial`) panel and handshakes. */
23
+ static open(o?: OpenOptions): Promise<LyPanel>;
24
+ connect(): Promise<PanelInfo>;
25
+ /**
26
+ * Writes one JPEG. Resolves `true` if the panel kept it, `false` if it
27
+ * dropped it (too big: see MAX_FRAME_BYTES). Rejects on a bus error: the
28
+ * caller reconnects.
29
+ */
30
+ send(jpeg: Buffer): Promise<boolean>;
31
+ close(): Promise<void>;
32
+ }
package/dist/panel.js ADDED
@@ -0,0 +1,53 @@
1
+ import { ACK_TIMEOUT_MS, HANDSHAKE_TIMEOUT_MS, REPLY_SIZE, WRITE_TIMEOUT_MS, frameWrites, handshakeRequest, isAccepted, modelFor, parseHandshake, prepareFrame, } from "./protocol.js";
2
+ import { openTransport } from "./transport.js";
3
+ /** One connected panel: say hello once, then `send` JPEG frames. Sends never overlap. */
4
+ export class LyPanel {
5
+ queue = Promise.resolve();
6
+ info = null;
7
+ transport;
8
+ pid;
9
+ meta;
10
+ constructor(transport, pid, meta = {}) {
11
+ this.transport = transport;
12
+ this.pid = pid;
13
+ this.meta = meta;
14
+ }
15
+ /** Opens the first (or `serial`) panel and handshakes. */
16
+ static async open(o = {}) {
17
+ const { transport, pid, serial, location } = await openTransport(o);
18
+ const panel = new LyPanel(transport, pid, { ...(serial ? { serial } : {}), location });
19
+ try {
20
+ await panel.connect();
21
+ }
22
+ catch (err) {
23
+ await transport.close();
24
+ throw err;
25
+ }
26
+ return panel;
27
+ }
28
+ async connect() {
29
+ await this.transport.write(handshakeRequest(), HANDSHAKE_TIMEOUT_MS);
30
+ const hs = parseHandshake(await this.transport.read(REPLY_SIZE, HANDSHAKE_TIMEOUT_MS), this.pid);
31
+ const model = modelFor(hs.pm, hs.sub);
32
+ this.info = { ...hs, pid: this.pid, ...this.meta, ...(model ? { model } : {}) };
33
+ return this.info;
34
+ }
35
+ /**
36
+ * Writes one JPEG. Resolves `true` if the panel kept it, `false` if it
37
+ * dropped it (too big: see MAX_FRAME_BYTES). Rejects on a bus error: the
38
+ * caller reconnects.
39
+ */
40
+ send(jpeg) {
41
+ const run = async () => {
42
+ for (const part of frameWrites(prepareFrame(jpeg, this.pid), this.pid))
43
+ await this.transport.write(part, WRITE_TIMEOUT_MS);
44
+ return isAccepted(await this.transport.read(REPLY_SIZE, ACK_TIMEOUT_MS));
45
+ };
46
+ const next = this.queue.then(run, run);
47
+ this.queue = next.catch(() => undefined);
48
+ return next;
49
+ }
50
+ close() {
51
+ return this.transport.close();
52
+ }
53
+ }
@@ -0,0 +1,72 @@
1
+ /**
2
+ * The wire protocol of the LY family of Thermalright USB LCD panels
3
+ * (Trofeo Vision 9.16 and siblings), VID 0x0416:
4
+ *
5
+ * PID 0x5408 "LY" chunk header byte 8 = 1, chunk count padded to a multiple of 4
6
+ * PID 0x5409 "LY1" chunk header byte 8 = 2, no padding
7
+ *
8
+ * Handshake: write 2048 bytes (a 16-byte header and zeros), read 512; the
9
+ * reply starts `03 FF` and has byte 8 = 1. PM and SUB, two bytes that say
10
+ * which model it is, come from bytes 20 and 22.
11
+ *
12
+ * Frame: the JPEG goes in 512-byte chunks (a 16-byte header and 496 bytes of
13
+ * data), written to the bulk OUT endpoint in 4096-byte USB transfers, then a
14
+ * 512-byte ACK is read whose **byte 8 says whether the panel kept the frame**
15
+ * (1) or dropped it (2). A dropped frame is silent otherwise: the write
16
+ * succeeds and the screen keeps the previous picture.
17
+ *
18
+ * All of it is read from the USBLCDNEW protocol as implemented by
19
+ * thermalright-trcc-linux (`trcc/adapters/device/ly_lcd.py`, 9.12); the
20
+ * golden vectors in the tests are produced by that implementation.
21
+ */
22
+ export declare const VENDOR_ID = 1046;
23
+ export declare const PID_LY = 21512;
24
+ export declare const PID_LY1 = 21513;
25
+ export declare const PRODUCT_IDS: readonly number[];
26
+ /** Bulk OUT and IN endpoints, used when the device's descriptors don't say otherwise. */
27
+ export declare const EP_OUT = 1;
28
+ export declare const EP_IN = 129;
29
+ export declare const CHUNK_SIZE = 512;
30
+ export declare const CHUNK_HEADER_SIZE = 16;
31
+ export declare const CHUNK_DATA_SIZE = 496;
32
+ export declare const USB_WRITE_SIZE = 4096;
33
+ export declare const REPLY_SIZE = 512;
34
+ export declare const HANDSHAKE_TIMEOUT_MS = 1000;
35
+ export declare const WRITE_TIMEOUT_MS = 5000;
36
+ export declare const ACK_TIMEOUT_MS = 1000;
37
+ /**
38
+ * The largest JPEG the firmware keeps, measured on a Trofeo Vision: 1032
39
+ * chunks of 496 bytes. One byte more and the panel drops the frame with a
40
+ * normal-looking ACK (byte 8 = 2). trcc's own ceiling, 512 KiB, is above it.
41
+ */
42
+ export declare const MAX_FRAME_BYTES = 511871;
43
+ export type Variant = 'ly' | 'ly1';
44
+ export declare function variantOf(pid: number): Variant;
45
+ /** The bytes the host sends to say hello. */
46
+ export declare function handshakeRequest(): Buffer;
47
+ export interface Handshake {
48
+ /** The model byte (`64 + resp[20]` on LY; `49 + resp[20]` on LY1). */
49
+ pm: number;
50
+ /** The sub-model byte (`resp[22] + 1` on LY; `resp[22]` on LY1). */
51
+ sub: number;
52
+ /** The first bytes of the reply, for reports. */
53
+ raw: Buffer;
54
+ }
55
+ export declare class UnrecognisedReply extends Error {
56
+ name: string;
57
+ }
58
+ export declare function parseHandshake(resp: Buffer, pid: number): Handshake;
59
+ /** Resolution and mount angle the firmware asks for, for the models trcc knows. */
60
+ export interface PanelModel {
61
+ width: number;
62
+ height: number;
63
+ /** Degrees the picture must be turned before encoding (0, 90, 180). Kiosko's `rotate`. */
64
+ rotate: number;
65
+ }
66
+ export declare function modelFor(pm: number, sub: number): PanelModel | undefined;
67
+ /** The exact bytes that go on the bus for a JPEG: chunk headers included, padded. */
68
+ export declare function prepareFrame(payload: Buffer, pid: number): Buffer;
69
+ /** The USB transfers a prepared frame is written in: 4096 bytes, and a shorter last one. */
70
+ export declare function frameWrites(frame: Buffer, pid: number): Buffer[];
71
+ /** Did the panel keep the frame? A short or odd ACK is taken as good (it may be another firmware). */
72
+ export declare function isAccepted(ack: Buffer): boolean;
@@ -0,0 +1,123 @@
1
+ /**
2
+ * The wire protocol of the LY family of Thermalright USB LCD panels
3
+ * (Trofeo Vision 9.16 and siblings), VID 0x0416:
4
+ *
5
+ * PID 0x5408 "LY" chunk header byte 8 = 1, chunk count padded to a multiple of 4
6
+ * PID 0x5409 "LY1" chunk header byte 8 = 2, no padding
7
+ *
8
+ * Handshake: write 2048 bytes (a 16-byte header and zeros), read 512; the
9
+ * reply starts `03 FF` and has byte 8 = 1. PM and SUB, two bytes that say
10
+ * which model it is, come from bytes 20 and 22.
11
+ *
12
+ * Frame: the JPEG goes in 512-byte chunks (a 16-byte header and 496 bytes of
13
+ * data), written to the bulk OUT endpoint in 4096-byte USB transfers, then a
14
+ * 512-byte ACK is read whose **byte 8 says whether the panel kept the frame**
15
+ * (1) or dropped it (2). A dropped frame is silent otherwise: the write
16
+ * succeeds and the screen keeps the previous picture.
17
+ *
18
+ * All of it is read from the USBLCDNEW protocol as implemented by
19
+ * thermalright-trcc-linux (`trcc/adapters/device/ly_lcd.py`, 9.12); the
20
+ * golden vectors in the tests are produced by that implementation.
21
+ */
22
+ export const VENDOR_ID = 0x0416;
23
+ export const PID_LY = 0x5408;
24
+ export const PID_LY1 = 0x5409;
25
+ export const PRODUCT_IDS = [PID_LY, PID_LY1];
26
+ /** Bulk OUT and IN endpoints, used when the device's descriptors don't say otherwise. */
27
+ export const EP_OUT = 0x01;
28
+ export const EP_IN = 0x81;
29
+ export const CHUNK_SIZE = 512;
30
+ export const CHUNK_HEADER_SIZE = 16;
31
+ export const CHUNK_DATA_SIZE = 496;
32
+ export const USB_WRITE_SIZE = 4096;
33
+ export const REPLY_SIZE = 512;
34
+ export const HANDSHAKE_TIMEOUT_MS = 1000;
35
+ export const WRITE_TIMEOUT_MS = 5000;
36
+ export const ACK_TIMEOUT_MS = 1000;
37
+ /**
38
+ * The largest JPEG the firmware keeps, measured on a Trofeo Vision: 1032
39
+ * chunks of 496 bytes. One byte more and the panel drops the frame with a
40
+ * normal-looking ACK (byte 8 = 2). trcc's own ceiling, 512 KiB, is above it.
41
+ */
42
+ export const MAX_FRAME_BYTES = 511_871;
43
+ export function variantOf(pid) {
44
+ return pid === PID_LY1 ? 'ly1' : 'ly';
45
+ }
46
+ /** The bytes the host sends to say hello. */
47
+ export function handshakeRequest() {
48
+ const b = Buffer.alloc(2048);
49
+ b[0] = 0x02;
50
+ b[1] = 0xff;
51
+ b[8] = 0x01;
52
+ return b;
53
+ }
54
+ export class UnrecognisedReply extends Error {
55
+ name = 'UnrecognisedReply';
56
+ }
57
+ export function parseHandshake(resp, pid) {
58
+ if (resp.length < 37 || resp[0] !== 3 || resp[1] !== 0xff || resp[8] !== 1) {
59
+ const at = (i) => (resp.length > i ? String(resp[i]) : 'N/A');
60
+ throw new UnrecognisedReply(`handshake validation failed (length ${resp.length}, [0]=${at(0)}, [1]=${at(1)}, [8]=${at(8)})`);
61
+ }
62
+ const raw = resp.subarray(0, Math.min(resp.length, 64));
63
+ if (variantOf(pid) === 'ly') {
64
+ // trcc clamps 0..3 to 1.
65
+ const r = resp[20] <= 3 ? 1 : resp[20];
66
+ return { pm: 64 + r, sub: (resp[22] ?? 0) + 1, raw };
67
+ }
68
+ return { pm: 49 + resp[20], sub: resp[22] ?? 0, raw };
69
+ }
70
+ /**
71
+ * From trcc 9.12 `bulk_profile(pm, sub)` + `wire_angle`. Only the models it
72
+ * knows; anything else is `undefined` and the caller uses its own config.
73
+ */
74
+ const ANGLES_1920 = [180, 180, 0, 0, 0, 180, 180, 180, 180];
75
+ const MODELS = {
76
+ 64: { width: 1600, height: 720, angles: [180, 180, 180, 0, 180, 180, 180, 180, 180] },
77
+ 65: { width: 1920, height: 462, angles: ANGLES_1920 },
78
+ 66: { width: 1920, height: 462, angles: ANGLES_1920 },
79
+ 68: { width: 1280, height: 480, angles: [0, 0, 90, 0, 0, 0, 0, 0, 0] },
80
+ 69: { width: 1920, height: 440, angles: ANGLES_1920 },
81
+ };
82
+ export function modelFor(pm, sub) {
83
+ const m = MODELS[pm] ?? (pm >= 67 && pm <= 80 ? { width: 480, height: 480, angles: Array(9).fill(0) } : undefined);
84
+ const rotate = m?.angles[sub];
85
+ return m && rotate !== undefined ? { width: m.width, height: m.height, rotate } : undefined;
86
+ }
87
+ /** The exact bytes that go on the bus for a JPEG: chunk headers included, padded. */
88
+ export function prepareFrame(payload, pid) {
89
+ const total = payload.length;
90
+ const n = Math.floor(total / CHUNK_DATA_SIZE) + 1;
91
+ const lastLen = total % CHUNK_DATA_SIZE;
92
+ const cmd = variantOf(pid) === 'ly' ? 1 : 2;
93
+ const padTo = variantOf(pid) === 'ly' ? 4 : 1;
94
+ const padded = Math.ceil(n / padTo) * padTo;
95
+ const out = Buffer.alloc(padded * CHUNK_SIZE);
96
+ for (let i = 0; i < n; i++) {
97
+ const o = i * CHUNK_SIZE;
98
+ const len = i === n - 1 ? lastLen : CHUNK_DATA_SIZE;
99
+ out[o] = 0x01;
100
+ out[o + 1] = 0xff;
101
+ out.writeUInt32LE(total, o + 2);
102
+ out.writeUInt16LE(len, o + 6);
103
+ out[o + 8] = cmd;
104
+ out.writeUInt16LE(n, o + 9);
105
+ out.writeUInt16LE(i, o + 11);
106
+ payload.copy(out, o + CHUNK_HEADER_SIZE, i * CHUNK_DATA_SIZE, i * CHUNK_DATA_SIZE + len);
107
+ }
108
+ return out;
109
+ }
110
+ /** The USB transfers a prepared frame is written in: 4096 bytes, and a shorter last one. */
111
+ export function frameWrites(frame, pid) {
112
+ const out = [];
113
+ for (let pos = 0; pos < frame.length; pos += USB_WRITE_SIZE) {
114
+ const remaining = frame.length - pos;
115
+ const size = remaining >= USB_WRITE_SIZE ? USB_WRITE_SIZE : variantOf(pid) === 'ly' ? Math.min(2048, remaining) : remaining;
116
+ out.push(frame.subarray(pos, pos + size));
117
+ }
118
+ return out;
119
+ }
120
+ /** Did the panel keep the frame? A short or odd ACK is taken as good (it may be another firmware). */
121
+ export function isAccepted(ack) {
122
+ return ack.length < 9 || ack[8] === 1;
123
+ }
@@ -0,0 +1,62 @@
1
+ /**
2
+ * The USB side: one panel opened by VID/PID (and USB serial number), through
3
+ * libusb (the `usb` npm package, an optional dependency with prebuilt
4
+ * binaries for Linux, macOS and Windows).
5
+ *
6
+ * Windows needs the **WinUSB** driver on the device (Zadig, or an INF), or
7
+ * libusb answers LIBUSB_ERROR_NOT_SUPPORTED when opening it; `usb.useUsbDkBackend()`
8
+ * is the alternative with UsbDK. Linux needs a udev rule giving your user
9
+ * access to 0416:5408.
10
+ */
11
+ import type { Device } from 'usb';
12
+ /** What the panel code needs from a USB pipe; fakes implement this in tests. */
13
+ export interface Transport {
14
+ write(data: Buffer, timeoutMs: number): Promise<void>;
15
+ read(length: number, timeoutMs: number): Promise<Buffer>;
16
+ close(): Promise<void>;
17
+ }
18
+ /** The part of the `usb` module that is used; tests pass a fake. */
19
+ export interface UsbModule {
20
+ getDeviceList(): Device[];
21
+ }
22
+ export declare class PanelNotFound extends Error {
23
+ name: string;
24
+ }
25
+ export declare class UsbUnavailable extends Error {
26
+ name: string;
27
+ }
28
+ /** Loads libusb on demand, so a missing or broken native module never breaks anything that doesn't use USB. */
29
+ export declare function loadUsb(): Promise<UsbModule>;
30
+ export interface FoundPanel {
31
+ pid: number;
32
+ /** USB serial number; undefined if the panel has none or it couldn't be read. */
33
+ serial?: string;
34
+ /** Where it is plugged: `bus-address`; changes when it is moved. */
35
+ location: string;
36
+ /** Why the serial could not be read (a driver, permissions). */
37
+ error?: string;
38
+ device: Device;
39
+ }
40
+ /** Every LY panel libusb sees, with its serial number. Opens each only to read it. */
41
+ export declare function findPanels(usb: UsbModule, filter?: {
42
+ pid?: number;
43
+ }): Promise<FoundPanel[]>;
44
+ export interface OpenOptions {
45
+ /**
46
+ * USB serial number of the panel to use. With several identical panels this
47
+ * is the only thing that tells them apart, and **a serial that is not found
48
+ * is an error, never "the first one"**: taking a twin another process holds
49
+ * would leave it blank. Without it, the first panel is used.
50
+ */
51
+ serial?: string;
52
+ pid?: number;
53
+ usb?: UsbModule;
54
+ os?: NodeJS.Platform;
55
+ }
56
+ /** Opens one panel. Throws PanelNotFound if it isn't there. */
57
+ export declare function openTransport(o?: OpenOptions): Promise<{
58
+ transport: Transport;
59
+ pid: number;
60
+ serial?: string;
61
+ location: string;
62
+ }>;
@@ -0,0 +1,144 @@
1
+ import { ACK_TIMEOUT_MS, PRODUCT_IDS, VENDOR_ID } from "./protocol.js";
2
+ export class PanelNotFound extends Error {
3
+ name = 'PanelNotFound';
4
+ }
5
+ export class UsbUnavailable extends Error {
6
+ name = 'UsbUnavailable';
7
+ }
8
+ /** Loads libusb on demand, so a missing or broken native module never breaks anything that doesn't use USB. */
9
+ export async function loadUsb() {
10
+ try {
11
+ const m = (await import('usb'));
12
+ const mod = m.getDeviceList ? m : m.default?.getDeviceList ? m.default : m.usb;
13
+ if (!mod?.getDeviceList)
14
+ throw new Error('the usb module has no getDeviceList');
15
+ return mod;
16
+ }
17
+ catch (err) {
18
+ throw new UsbUnavailable(`cannot load the "usb" package (libusb): ${err instanceof Error ? err.message : String(err)}. Install it with: npm install usb`);
19
+ }
20
+ }
21
+ const call = (fn) => new Promise((resolve, reject) => fn((err, value) => (err ? reject(err) : resolve(value))));
22
+ async function serialOf(device) {
23
+ const index = device.deviceDescriptor.iSerialNumber;
24
+ if (!index)
25
+ return undefined;
26
+ const value = await call((cb) => device.getStringDescriptor(index, (e, v) => cb(e ?? null, v)));
27
+ return value?.trim() || undefined;
28
+ }
29
+ /** Every LY panel libusb sees, with its serial number. Opens each only to read it. */
30
+ export async function findPanels(usb, filter = {}) {
31
+ const out = [];
32
+ for (const device of usb.getDeviceList()) {
33
+ const d = device.deviceDescriptor;
34
+ if (d.idVendor !== VENDOR_ID || !PRODUCT_IDS.includes(d.idProduct) || (filter.pid && d.idProduct !== filter.pid))
35
+ continue;
36
+ const found = { pid: d.idProduct, location: `${device.busNumber}-${device.deviceAddress}`, device };
37
+ try {
38
+ device.open();
39
+ try {
40
+ const serial = await serialOf(device);
41
+ if (serial)
42
+ found.serial = serial;
43
+ }
44
+ finally {
45
+ device.close();
46
+ }
47
+ }
48
+ catch (err) {
49
+ found.error = err instanceof Error ? err.message : String(err);
50
+ }
51
+ out.push(found);
52
+ }
53
+ return out;
54
+ }
55
+ class UsbTransport {
56
+ detached = false;
57
+ device;
58
+ iface;
59
+ out;
60
+ inp;
61
+ constructor(device, iface, out, inp) {
62
+ this.device = device;
63
+ this.iface = iface;
64
+ this.out = out;
65
+ this.inp = inp;
66
+ }
67
+ static async open(found, os = process.platform) {
68
+ const { device } = found;
69
+ device.open();
70
+ let iface;
71
+ let detached = false;
72
+ try {
73
+ // The kernel may have bound a driver (usbhid, usb-storage…) to the interface.
74
+ if (device.configDescriptor?.bConfigurationValue !== 1)
75
+ await call((cb) => device.setConfiguration(1, (e) => cb(e ?? null)));
76
+ iface = device.interface(0);
77
+ if (os === 'linux' && iface.isKernelDriverActive()) {
78
+ iface.detachKernelDriver();
79
+ detached = true;
80
+ }
81
+ iface.claim();
82
+ const eps = iface.endpoints;
83
+ const out = eps.find((e) => e.direction === 'out');
84
+ const inp = eps.find((e) => e.direction === 'in');
85
+ if (!out || !inp)
86
+ throw new Error('the panel has no bulk IN/OUT endpoints on interface 0');
87
+ const t = new UsbTransport(device, iface, out, inp);
88
+ t.detached = detached;
89
+ return t;
90
+ }
91
+ catch (err) {
92
+ try {
93
+ if (iface && detached)
94
+ iface.attachKernelDriver();
95
+ }
96
+ catch {
97
+ /* nothing to give back */
98
+ }
99
+ device.close();
100
+ throw err;
101
+ }
102
+ }
103
+ async write(data, timeoutMs) {
104
+ this.out.timeout = timeoutMs;
105
+ await call((cb) => this.out.transfer(data, (e, n) => cb(e ?? null, n)));
106
+ }
107
+ async read(length, timeoutMs = ACK_TIMEOUT_MS) {
108
+ this.inp.timeout = timeoutMs;
109
+ return call((cb) => this.inp.transfer(length, (e, d) => cb(e ?? null, d)));
110
+ }
111
+ async close() {
112
+ try {
113
+ await call((cb) => this.iface.release(true, (e) => cb(e ?? null)));
114
+ }
115
+ catch {
116
+ /* already gone */
117
+ }
118
+ try {
119
+ if (this.detached)
120
+ this.iface.attachKernelDriver();
121
+ }
122
+ catch {
123
+ /* the kernel gives it back on replug */
124
+ }
125
+ try {
126
+ this.device.close();
127
+ }
128
+ catch {
129
+ /* unplugged */
130
+ }
131
+ }
132
+ }
133
+ /** Opens one panel. Throws PanelNotFound if it isn't there. */
134
+ export async function openTransport(o = {}) {
135
+ const usb = o.usb ?? (await loadUsb());
136
+ const all = await findPanels(usb, o.pid ? { pid: o.pid } : {});
137
+ const found = o.serial ? all.find((p) => p.serial === o.serial) : all[0];
138
+ if (!found) {
139
+ const seen = all.map((p) => p.serial ?? `(${p.error ?? 'no serial'}) at ${p.location}`).join(', ');
140
+ throw new PanelNotFound(o.serial ? `no panel with serial ${o.serial}${all.length ? ` (found: ${seen})` : ' (none plugged in)'}` : 'no LY panel found');
141
+ }
142
+ const transport = await UsbTransport.open(found, o.os);
143
+ return { transport, pid: found.pid, ...(found.serial ? { serial: found.serial } : {}), location: found.location };
144
+ }
package/package.json CHANGED
@@ -1,6 +1,32 @@
1
1
  {
2
2
  "name": "@loksly/usb-ly",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.2",
4
+ "description": "Node driver for the Thermalright LY USB LCD panels (Trofeo Vision 9.16 and siblings): talks USB from Node, no Python or trcc needed.",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "author": "Loksly",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/kiosko-lcd/kiosko.git",
11
+ "directory": "packages/usb-ly"
12
+ },
13
+ "keywords": ["thermalright", "lcd", "usb", "trofeo-vision", "ly"],
14
+ "exports": {
15
+ ".": {
16
+ "source": "./src/index.ts",
17
+ "types": "./dist/index.d.ts",
18
+ "default": "./dist/index.js"
19
+ }
20
+ },
21
+ "files": ["dist", "src", "!src/**/*.test.ts", "!src/golden.json", "README.md", "LICENSE"],
22
+ "engines": { "node": ">=20" },
23
+ "optionalDependencies": {
24
+ "usb": "^2.15.0"
25
+ },
26
+ "scripts": {
27
+ "build": "tsc -p tsconfig.json",
28
+ "prepublishOnly": "npm run build",
29
+ "test": "node --conditions=source --test 'src/**/*.test.ts'",
30
+ "check": "tsc -p tsconfig.json --noEmit"
31
+ }
32
+ }
package/src/index.ts ADDED
@@ -0,0 +1,3 @@
1
+ export * from './protocol.ts';
2
+ export * from './transport.ts';
3
+ export * from './panel.ts';
package/src/panel.ts ADDED
@@ -0,0 +1,80 @@
1
+ import {
2
+ ACK_TIMEOUT_MS,
3
+ HANDSHAKE_TIMEOUT_MS,
4
+ REPLY_SIZE,
5
+ WRITE_TIMEOUT_MS,
6
+ frameWrites,
7
+ handshakeRequest,
8
+ isAccepted,
9
+ modelFor,
10
+ parseHandshake,
11
+ prepareFrame,
12
+ type Handshake,
13
+ type PanelModel,
14
+ } from './protocol.ts';
15
+ import { openTransport, type OpenOptions, type Transport } from './transport.ts';
16
+
17
+ export interface PanelInfo extends Handshake {
18
+ pid: number;
19
+ serial?: string;
20
+ /** Where it is plugged (`bus-address`). */
21
+ location?: string;
22
+ /** What trcc knows about this model, if anything. */
23
+ model?: PanelModel;
24
+ }
25
+
26
+ /** One connected panel: say hello once, then `send` JPEG frames. Sends never overlap. */
27
+ export class LyPanel {
28
+ private queue: Promise<unknown> = Promise.resolve();
29
+ info: PanelInfo | null = null;
30
+
31
+ private readonly transport: Transport;
32
+ readonly pid: number;
33
+ private readonly meta: { serial?: string; location?: string };
34
+
35
+ constructor(transport: Transport, pid: number, meta: { serial?: string; location?: string } = {}) {
36
+ this.transport = transport;
37
+ this.pid = pid;
38
+ this.meta = meta;
39
+ }
40
+
41
+ /** Opens the first (or `serial`) panel and handshakes. */
42
+ static async open(o: OpenOptions = {}): Promise<LyPanel> {
43
+ const { transport, pid, serial, location } = await openTransport(o);
44
+ const panel = new LyPanel(transport, pid, { ...(serial ? { serial } : {}), location });
45
+ try {
46
+ await panel.connect();
47
+ } catch (err) {
48
+ await transport.close();
49
+ throw err;
50
+ }
51
+ return panel;
52
+ }
53
+
54
+ async connect(): Promise<PanelInfo> {
55
+ await this.transport.write(handshakeRequest(), HANDSHAKE_TIMEOUT_MS);
56
+ const hs = parseHandshake(await this.transport.read(REPLY_SIZE, HANDSHAKE_TIMEOUT_MS), this.pid);
57
+ const model = modelFor(hs.pm, hs.sub);
58
+ this.info = { ...hs, pid: this.pid, ...this.meta, ...(model ? { model } : {}) };
59
+ return this.info;
60
+ }
61
+
62
+ /**
63
+ * Writes one JPEG. Resolves `true` if the panel kept it, `false` if it
64
+ * dropped it (too big: see MAX_FRAME_BYTES). Rejects on a bus error: the
65
+ * caller reconnects.
66
+ */
67
+ send(jpeg: Buffer): Promise<boolean> {
68
+ const run = async () => {
69
+ for (const part of frameWrites(prepareFrame(jpeg, this.pid), this.pid)) await this.transport.write(part, WRITE_TIMEOUT_MS);
70
+ return isAccepted(await this.transport.read(REPLY_SIZE, ACK_TIMEOUT_MS));
71
+ };
72
+ const next = this.queue.then(run, run);
73
+ this.queue = next.catch(() => undefined);
74
+ return next;
75
+ }
76
+
77
+ close(): Promise<void> {
78
+ return this.transport.close();
79
+ }
80
+ }
@@ -0,0 +1,156 @@
1
+ /**
2
+ * The wire protocol of the LY family of Thermalright USB LCD panels
3
+ * (Trofeo Vision 9.16 and siblings), VID 0x0416:
4
+ *
5
+ * PID 0x5408 "LY" chunk header byte 8 = 1, chunk count padded to a multiple of 4
6
+ * PID 0x5409 "LY1" chunk header byte 8 = 2, no padding
7
+ *
8
+ * Handshake: write 2048 bytes (a 16-byte header and zeros), read 512; the
9
+ * reply starts `03 FF` and has byte 8 = 1. PM and SUB, two bytes that say
10
+ * which model it is, come from bytes 20 and 22.
11
+ *
12
+ * Frame: the JPEG goes in 512-byte chunks (a 16-byte header and 496 bytes of
13
+ * data), written to the bulk OUT endpoint in 4096-byte USB transfers, then a
14
+ * 512-byte ACK is read whose **byte 8 says whether the panel kept the frame**
15
+ * (1) or dropped it (2). A dropped frame is silent otherwise: the write
16
+ * succeeds and the screen keeps the previous picture.
17
+ *
18
+ * All of it is read from the USBLCDNEW protocol as implemented by
19
+ * thermalright-trcc-linux (`trcc/adapters/device/ly_lcd.py`, 9.12); the
20
+ * golden vectors in the tests are produced by that implementation.
21
+ */
22
+
23
+ export const VENDOR_ID = 0x0416;
24
+ export const PID_LY = 0x5408;
25
+ export const PID_LY1 = 0x5409;
26
+ export const PRODUCT_IDS: readonly number[] = [PID_LY, PID_LY1];
27
+
28
+ /** Bulk OUT and IN endpoints, used when the device's descriptors don't say otherwise. */
29
+ export const EP_OUT = 0x01;
30
+ export const EP_IN = 0x81;
31
+
32
+ export const CHUNK_SIZE = 512;
33
+ export const CHUNK_HEADER_SIZE = 16;
34
+ export const CHUNK_DATA_SIZE = 496;
35
+ export const USB_WRITE_SIZE = 4096;
36
+ export const REPLY_SIZE = 512;
37
+
38
+ export const HANDSHAKE_TIMEOUT_MS = 1000;
39
+ export const WRITE_TIMEOUT_MS = 5000;
40
+ export const ACK_TIMEOUT_MS = 1000;
41
+
42
+ /**
43
+ * The largest JPEG the firmware keeps, measured on a Trofeo Vision: 1032
44
+ * chunks of 496 bytes. One byte more and the panel drops the frame with a
45
+ * normal-looking ACK (byte 8 = 2). trcc's own ceiling, 512 KiB, is above it.
46
+ */
47
+ export const MAX_FRAME_BYTES = 511_871;
48
+
49
+ export type Variant = 'ly' | 'ly1';
50
+
51
+ export function variantOf(pid: number): Variant {
52
+ return pid === PID_LY1 ? 'ly1' : 'ly';
53
+ }
54
+
55
+ /** The bytes the host sends to say hello. */
56
+ export function handshakeRequest(): Buffer {
57
+ const b = Buffer.alloc(2048);
58
+ b[0] = 0x02;
59
+ b[1] = 0xff;
60
+ b[8] = 0x01;
61
+ return b;
62
+ }
63
+
64
+ export interface Handshake {
65
+ /** The model byte (`64 + resp[20]` on LY; `49 + resp[20]` on LY1). */
66
+ pm: number;
67
+ /** The sub-model byte (`resp[22] + 1` on LY; `resp[22]` on LY1). */
68
+ sub: number;
69
+ /** The first bytes of the reply, for reports. */
70
+ raw: Buffer;
71
+ }
72
+
73
+ export class UnrecognisedReply extends Error {
74
+ override name = 'UnrecognisedReply';
75
+ }
76
+
77
+ export function parseHandshake(resp: Buffer, pid: number): Handshake {
78
+ if (resp.length < 37 || resp[0] !== 3 || resp[1] !== 0xff || resp[8] !== 1) {
79
+ const at = (i: number) => (resp.length > i ? String(resp[i]) : 'N/A');
80
+ throw new UnrecognisedReply(`handshake validation failed (length ${resp.length}, [0]=${at(0)}, [1]=${at(1)}, [8]=${at(8)})`);
81
+ }
82
+ const raw = resp.subarray(0, Math.min(resp.length, 64));
83
+ if (variantOf(pid) === 'ly') {
84
+ // trcc clamps 0..3 to 1.
85
+ const r = resp[20]! <= 3 ? 1 : resp[20]!;
86
+ return { pm: 64 + r, sub: (resp[22] ?? 0) + 1, raw };
87
+ }
88
+ return { pm: 49 + resp[20]!, sub: resp[22] ?? 0, raw };
89
+ }
90
+
91
+ /** Resolution and mount angle the firmware asks for, for the models trcc knows. */
92
+ export interface PanelModel {
93
+ width: number;
94
+ height: number;
95
+ /** Degrees the picture must be turned before encoding (0, 90, 180). Kiosko's `rotate`. */
96
+ rotate: number;
97
+ }
98
+
99
+ /**
100
+ * From trcc 9.12 `bulk_profile(pm, sub)` + `wire_angle`. Only the models it
101
+ * knows; anything else is `undefined` and the caller uses its own config.
102
+ */
103
+ const ANGLES_1920 = [180, 180, 0, 0, 0, 180, 180, 180, 180];
104
+ const MODELS: Record<number, { width: number; height: number; angles: number[] }> = {
105
+ 64: { width: 1600, height: 720, angles: [180, 180, 180, 0, 180, 180, 180, 180, 180] },
106
+ 65: { width: 1920, height: 462, angles: ANGLES_1920 },
107
+ 66: { width: 1920, height: 462, angles: ANGLES_1920 },
108
+ 68: { width: 1280, height: 480, angles: [0, 0, 90, 0, 0, 0, 0, 0, 0] },
109
+ 69: { width: 1920, height: 440, angles: ANGLES_1920 },
110
+ };
111
+
112
+ export function modelFor(pm: number, sub: number): PanelModel | undefined {
113
+ const m = MODELS[pm] ?? (pm >= 67 && pm <= 80 ? { width: 480, height: 480, angles: Array<number>(9).fill(0) } : undefined);
114
+ const rotate = m?.angles[sub];
115
+ return m && rotate !== undefined ? { width: m.width, height: m.height, rotate } : undefined;
116
+ }
117
+
118
+ /** The exact bytes that go on the bus for a JPEG: chunk headers included, padded. */
119
+ export function prepareFrame(payload: Buffer, pid: number): Buffer {
120
+ const total = payload.length;
121
+ const n = Math.floor(total / CHUNK_DATA_SIZE) + 1;
122
+ const lastLen = total % CHUNK_DATA_SIZE;
123
+ const cmd = variantOf(pid) === 'ly' ? 1 : 2;
124
+ const padTo = variantOf(pid) === 'ly' ? 4 : 1;
125
+ const padded = Math.ceil(n / padTo) * padTo;
126
+ const out = Buffer.alloc(padded * CHUNK_SIZE);
127
+ for (let i = 0; i < n; i++) {
128
+ const o = i * CHUNK_SIZE;
129
+ const len = i === n - 1 ? lastLen : CHUNK_DATA_SIZE;
130
+ out[o] = 0x01;
131
+ out[o + 1] = 0xff;
132
+ out.writeUInt32LE(total, o + 2);
133
+ out.writeUInt16LE(len, o + 6);
134
+ out[o + 8] = cmd;
135
+ out.writeUInt16LE(n, o + 9);
136
+ out.writeUInt16LE(i, o + 11);
137
+ payload.copy(out, o + CHUNK_HEADER_SIZE, i * CHUNK_DATA_SIZE, i * CHUNK_DATA_SIZE + len);
138
+ }
139
+ return out;
140
+ }
141
+
142
+ /** The USB transfers a prepared frame is written in: 4096 bytes, and a shorter last one. */
143
+ export function frameWrites(frame: Buffer, pid: number): Buffer[] {
144
+ const out: Buffer[] = [];
145
+ for (let pos = 0; pos < frame.length; pos += USB_WRITE_SIZE) {
146
+ const remaining = frame.length - pos;
147
+ const size = remaining >= USB_WRITE_SIZE ? USB_WRITE_SIZE : variantOf(pid) === 'ly' ? Math.min(2048, remaining) : remaining;
148
+ out.push(frame.subarray(pos, pos + size));
149
+ }
150
+ return out;
151
+ }
152
+
153
+ /** Did the panel keep the frame? A short or odd ACK is taken as good (it may be another firmware). */
154
+ export function isAccepted(ack: Buffer): boolean {
155
+ return ack.length < 9 || ack[8] === 1;
156
+ }
@@ -0,0 +1,189 @@
1
+ /**
2
+ * The USB side: one panel opened by VID/PID (and USB serial number), through
3
+ * libusb (the `usb` npm package, an optional dependency with prebuilt
4
+ * binaries for Linux, macOS and Windows).
5
+ *
6
+ * Windows needs the **WinUSB** driver on the device (Zadig, or an INF), or
7
+ * libusb answers LIBUSB_ERROR_NOT_SUPPORTED when opening it; `usb.useUsbDkBackend()`
8
+ * is the alternative with UsbDK. Linux needs a udev rule giving your user
9
+ * access to 0416:5408.
10
+ */
11
+ import type { Device, InEndpoint, Interface, OutEndpoint } from 'usb';
12
+ import { ACK_TIMEOUT_MS, PRODUCT_IDS, VENDOR_ID } from './protocol.ts';
13
+
14
+ /** What the panel code needs from a USB pipe; fakes implement this in tests. */
15
+ export interface Transport {
16
+ write(data: Buffer, timeoutMs: number): Promise<void>;
17
+ read(length: number, timeoutMs: number): Promise<Buffer>;
18
+ close(): Promise<void>;
19
+ }
20
+
21
+ /** The part of the `usb` module that is used; tests pass a fake. */
22
+ export interface UsbModule {
23
+ getDeviceList(): Device[];
24
+ }
25
+
26
+ export class PanelNotFound extends Error {
27
+ override name = 'PanelNotFound';
28
+ }
29
+
30
+ export class UsbUnavailable extends Error {
31
+ override name = 'UsbUnavailable';
32
+ }
33
+
34
+ /** Loads libusb on demand, so a missing or broken native module never breaks anything that doesn't use USB. */
35
+ export async function loadUsb(): Promise<UsbModule> {
36
+ try {
37
+ const m = (await import('usb')) as unknown as { usb?: UsbModule; getDeviceList?: () => Device[]; default?: { getDeviceList?: () => Device[] } };
38
+ const mod = m.getDeviceList ? (m as unknown as UsbModule) : m.default?.getDeviceList ? (m.default as unknown as UsbModule) : m.usb;
39
+ if (!mod?.getDeviceList) throw new Error('the usb module has no getDeviceList');
40
+ return mod;
41
+ } catch (err) {
42
+ throw new UsbUnavailable(`cannot load the "usb" package (libusb): ${err instanceof Error ? err.message : String(err)}. Install it with: npm install usb`);
43
+ }
44
+ }
45
+
46
+ const call = <T>(fn: (cb: (err?: Error | null, value?: T) => void) => void): Promise<T> =>
47
+ new Promise((resolve, reject) => fn((err, value) => (err ? reject(err) : resolve(value as T))));
48
+
49
+ async function serialOf(device: Device): Promise<string | undefined> {
50
+ const index = device.deviceDescriptor.iSerialNumber;
51
+ if (!index) return undefined;
52
+ const value = await call<string | undefined>((cb) => device.getStringDescriptor(index, (e, v) => cb(e ?? null, v)));
53
+ return value?.trim() || undefined;
54
+ }
55
+
56
+ export interface FoundPanel {
57
+ pid: number;
58
+ /** USB serial number; undefined if the panel has none or it couldn't be read. */
59
+ serial?: string;
60
+ /** Where it is plugged: `bus-address`; changes when it is moved. */
61
+ location: string;
62
+ /** Why the serial could not be read (a driver, permissions). */
63
+ error?: string;
64
+ device: Device;
65
+ }
66
+
67
+ /** Every LY panel libusb sees, with its serial number. Opens each only to read it. */
68
+ export async function findPanels(usb: UsbModule, filter: { pid?: number } = {}): Promise<FoundPanel[]> {
69
+ const out: FoundPanel[] = [];
70
+ for (const device of usb.getDeviceList()) {
71
+ const d = device.deviceDescriptor;
72
+ if (d.idVendor !== VENDOR_ID || !PRODUCT_IDS.includes(d.idProduct) || (filter.pid && d.idProduct !== filter.pid)) continue;
73
+ const found: FoundPanel = { pid: d.idProduct, location: `${device.busNumber}-${device.deviceAddress}`, device };
74
+ try {
75
+ device.open();
76
+ try {
77
+ const serial = await serialOf(device);
78
+ if (serial) found.serial = serial;
79
+ } finally {
80
+ device.close();
81
+ }
82
+ } catch (err) {
83
+ found.error = err instanceof Error ? err.message : String(err);
84
+ }
85
+ out.push(found);
86
+ }
87
+ return out;
88
+ }
89
+
90
+ class UsbTransport implements Transport {
91
+ private detached = false;
92
+ private readonly device: Device;
93
+ private readonly iface: Interface;
94
+ private readonly out: OutEndpoint;
95
+ private readonly inp: InEndpoint;
96
+
97
+ constructor(device: Device, iface: Interface, out: OutEndpoint, inp: InEndpoint) {
98
+ this.device = device;
99
+ this.iface = iface;
100
+ this.out = out;
101
+ this.inp = inp;
102
+ }
103
+
104
+ static async open(found: FoundPanel, os: NodeJS.Platform = process.platform): Promise<UsbTransport> {
105
+ const { device } = found;
106
+ device.open();
107
+ let iface: Interface | undefined;
108
+ let detached = false;
109
+ try {
110
+ // The kernel may have bound a driver (usbhid, usb-storage…) to the interface.
111
+ if (device.configDescriptor?.bConfigurationValue !== 1) await call<void>((cb) => device.setConfiguration(1, (e) => cb(e ?? null)));
112
+ iface = device.interface(0);
113
+ if (os === 'linux' && iface.isKernelDriverActive()) {
114
+ iface.detachKernelDriver();
115
+ detached = true;
116
+ }
117
+ iface.claim();
118
+ const eps = iface.endpoints;
119
+ const out = eps.find((e) => e.direction === 'out') as OutEndpoint | undefined;
120
+ const inp = eps.find((e) => e.direction === 'in') as InEndpoint | undefined;
121
+ if (!out || !inp) throw new Error('the panel has no bulk IN/OUT endpoints on interface 0');
122
+ const t = new UsbTransport(device, iface, out, inp);
123
+ t.detached = detached;
124
+ return t;
125
+ } catch (err) {
126
+ try {
127
+ if (iface && detached) iface.attachKernelDriver();
128
+ } catch {
129
+ /* nothing to give back */
130
+ }
131
+ device.close();
132
+ throw err;
133
+ }
134
+ }
135
+
136
+ async write(data: Buffer, timeoutMs: number): Promise<void> {
137
+ this.out.timeout = timeoutMs;
138
+ await call<number>((cb) => this.out.transfer(data, (e, n) => cb(e ?? null, n)));
139
+ }
140
+
141
+ async read(length: number, timeoutMs = ACK_TIMEOUT_MS): Promise<Buffer> {
142
+ this.inp.timeout = timeoutMs;
143
+ return call<Buffer>((cb) => this.inp.transfer(length, (e, d) => cb(e ?? null, d)));
144
+ }
145
+
146
+ async close(): Promise<void> {
147
+ try {
148
+ await call<void>((cb) => this.iface.release(true, (e) => cb(e ?? null)));
149
+ } catch {
150
+ /* already gone */
151
+ }
152
+ try {
153
+ if (this.detached) this.iface.attachKernelDriver();
154
+ } catch {
155
+ /* the kernel gives it back on replug */
156
+ }
157
+ try {
158
+ this.device.close();
159
+ } catch {
160
+ /* unplugged */
161
+ }
162
+ }
163
+ }
164
+
165
+ export interface OpenOptions {
166
+ /**
167
+ * USB serial number of the panel to use. With several identical panels this
168
+ * is the only thing that tells them apart, and **a serial that is not found
169
+ * is an error, never "the first one"**: taking a twin another process holds
170
+ * would leave it blank. Without it, the first panel is used.
171
+ */
172
+ serial?: string;
173
+ pid?: number;
174
+ usb?: UsbModule;
175
+ os?: NodeJS.Platform;
176
+ }
177
+
178
+ /** Opens one panel. Throws PanelNotFound if it isn't there. */
179
+ export async function openTransport(o: OpenOptions = {}): Promise<{ transport: Transport; pid: number; serial?: string; location: string }> {
180
+ const usb = o.usb ?? (await loadUsb());
181
+ const all = await findPanels(usb, o.pid ? { pid: o.pid } : {});
182
+ const found = o.serial ? all.find((p) => p.serial === o.serial) : all[0];
183
+ if (!found) {
184
+ const seen = all.map((p) => p.serial ?? `(${p.error ?? 'no serial'}) at ${p.location}`).join(', ');
185
+ throw new PanelNotFound(o.serial ? `no panel with serial ${o.serial}${all.length ? ` (found: ${seen})` : ' (none plugged in)'}` : 'no LY panel found');
186
+ }
187
+ const transport = await UsbTransport.open(found, o.os);
188
+ return { transport, pid: found.pid, ...(found.serial ? { serial: found.serial } : {}), location: found.location };
189
+ }