-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathusblib.js
More file actions
156 lines (146 loc) · 4.38 KB
/
usblib.js
File metadata and controls
156 lines (146 loc) · 4.38 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
import * as constants from "./constants";
import { concatUint8Array, sleep } from "./utils";
export class usbClass {
constructor() {
/** @type {USBDevice|null} */
this.device = null;
/** @type {USBEndpoint|null} */
this.epIn = null;
/** @type {USBEndpoint|null} */
this.epOut = null;
this.maxSize = 512;
}
get connected() {
return this.device?.opened && this.device.configurations[0].interfaces[0].claimed;
}
/**
* @param {USBDevice} device
* @returns {{ epIn: USBEndpoint, epOut: USBEndpoint }}
*/
#validateDevice(device) {
const ife = device.configurations[0].interfaces[0].alternates[0];
if (ife.endpoints.length !== 2) {
throw "USB - Attempted to connect to null device";
}
let epIn = null, epOut = null;
for (const endpoint of ife.endpoints) {
if (endpoint.type !== "bulk") {
throw "USB - Interface endpoint is not bulk";
}
if (endpoint.direction === "in") {
if (epIn) {
throw "USB - Interface has multiple IN endpoints";
}
epIn = endpoint;
} else if (endpoint.direction === "out") {
if (epOut) {
throw "USB - Interface has multiple OUT endpoints";
}
epOut = endpoint;
}
}
console.debug("[usblib] endpoints: in =", epIn, ", out =", epOut);
this.epIn = epIn;
this.epOut = epOut;
this.maxSize = this.epIn.packetSize;
}
/**
* @param {USBDevice} device
* @returns {Promise<void>}
* @private
*/
async #connectDevice(device) {
this.device = device;
this.#validateDevice(device);
try {
await device.open();
await device.selectConfiguration(1);
await device.claimInterface(0);
} catch (error) {
try {
await device.reset();
await device.forget();
await device.close();
} catch {
// ignore cleanup errors
}
throw new Error("Error while connecting to device", { cause: error });
}
}
async connect() {
if (!("usb" in navigator)) {
throw new Error("Browser missing WebUSB support");
}
const device = await navigator.usb.requestDevice({
filters: [{
vendorId: constants.VENDOR_ID,
productId: constants.PRODUCT_ID,
classCode: constants.QDL_CLASS_CODE,
}],
});
console.debug("[usblib] Using USB device:", device);
// TODO: is this event listener required?
navigator.usb.addEventListener("connect", async (event) => {
console.debug("[usblib] USB device connected:", event.device);
await this.#connectDevice(event.device);
});
await this.#connectDevice(device);
}
async #read() {
const result = await this.device?.transferIn(this.epIn?.endpointNumber, this.maxSize);
return new Uint8Array(result.data?.buffer);
}
/**
* @param {number} [length=0]
* @returns {Promise<Uint8Array>}
*/
async read(length = 0) {
console.debug("[usblib] read", { length });
let result;
if (length) {
/** @type {Uint8Array[]} */
const chunks = [];
let received = 0;
do {
const chunk = await this.#read();
if (chunk.byteLength) {
chunks.push(chunk);
received += chunk.byteLength;
} else {
console.warn(" read empty");
break;
}
} while (received < length);
result = concatUint8Array(chunks);
} else {
result = await this.#read();
}
console.debug(" result:", result.toHexString());
return result;
}
/**
* @param {Uint8Array} data
* @param {boolean} [wait=true]
* @returns {Promise<void>}
*/
async write(data, wait = true) {
console.debug("[usblib] write", data.toHexString());
if (data.byteLength === 0) {
try {
await this.device?.transferOut(this.epOut?.endpointNumber, data);
} catch {
await this.device?.transferOut(this.epOut?.endpointNumber, data);
}
return;
}
let offset = 0;
do {
const chunk = data.slice(offset, offset + constants.BULK_TRANSFER_SIZE);
offset += chunk.byteLength;
const promise = this.device?.transferOut(this.epOut?.endpointNumber, chunk);
// this is a hack, webusb doesn't have timed out catching
// this only happens in sahara.configure(). The loader receive the packet but doesn't respond back (same as edl repo).
await (wait ? promise : sleep(80));
} while (offset < data.byteLength);
}
}