-
Notifications
You must be signed in to change notification settings - Fork 100
/
webserial.ts
418 lines (384 loc) · 12.2 KB
/
webserial.ts
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
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
/* global SerialPort, ParityType, FlowControlType */
/**
* Options for device serialPort.
* @interface SerialOptions
*
* Note: According to the documentation of the Web Serial API, 'baudRate' is a
* 'required' field as part of serial options. However, we are currently
* maintaining 'baudRate' as a separate parameter outside the options
* dictionary, and it is effectively used in the code. For now, we are
* keeping it optional in the dictionary to avoid conflicts.
*/
export interface SerialOptions {
/**
* A positive, non-zero value indicating the baud rate at which serial communication should be established.
* @type {number | undefined}
*/
baudRate?: number | undefined;
/**
* The number of data bits per frame. Either 7 or 8.
* @type {number | undefined}
*/
dataBits?: number | undefined;
/**
* The number of stop bits at the end of a frame. Either 1 or 2.
* @type {number | undefined}
*/
stopBits?: number | undefined;
/**
* The parity mode: none, even or odd
* @type {ParityType | undefined}
*/
parity?: ParityType | undefined;
/**
* A positive, non-zero value indicating the size of the read and write buffers that should be created.
* @type {number | undefined}
*/
bufferSize?: number | undefined;
/**
* The flow control mode: none or hardware.
* @type {FlowControlType | undefined}
*/
flowControl?: FlowControlType | undefined;
}
/**
* Wrapper class around Webserial API to communicate with the serial device.
* @param {typeof import("w3c-web-serial").SerialPort} device - Requested device prompted by the browser.
*
* ```
* const port = await navigator.serial.requestPort();
* ```
*/
class Transport {
public slipReaderEnabled = false;
public leftOver = new Uint8Array(0);
public baudrate = 0;
private traceLog = "";
private lastTraceTime = Date.now();
private reader: ReadableStreamDefaultReader<Uint8Array> | undefined;
constructor(public device: SerialPort, public tracing = false, enableSlipReader = true) {
this.slipReaderEnabled = enableSlipReader;
}
/**
* Request the serial device vendor ID and Product ID as string.
* @returns {string} Return the device VendorID and ProductID from SerialPortInfo as formatted string.
*/
getInfo(): string {
const info = this.device.getInfo();
return info.usbVendorId && info.usbProductId
? `WebSerial VendorID 0x${info.usbVendorId.toString(16)} ProductID 0x${info.usbProductId.toString(16)}`
: "";
}
/**
* Request the serial device product id from SerialPortInfo.
* @returns {number | undefined} Return the product ID.
*/
getPid(): number | undefined {
return this.device.getInfo().usbProductId;
}
/**
* Format received or sent data for tracing output.
* @param {string} message Message to format as trace line.
*/
trace(message: string) {
const delta = Date.now() - this.lastTraceTime;
const prefix = `TRACE ${delta.toFixed(3)}`;
const traceMessage = `${prefix} ${message}`;
console.log(traceMessage);
this.traceLog += traceMessage + "\n";
}
async returnTrace() {
try {
await navigator.clipboard.writeText(this.traceLog);
console.log("Text copied to clipboard!");
} catch (err) {
console.error("Failed to copy text:", err);
}
}
hexify(s: Uint8Array) {
return Array.from(s)
.map((byte) => byte.toString(16).padStart(2, "0"))
.join("")
.padEnd(16, " ");
}
hexConvert(uint8Array: Uint8Array, autoSplit = true) {
if (autoSplit && uint8Array.length > 16) {
let result = "";
let s = uint8Array;
while (s.length > 0) {
const line = s.slice(0, 16);
const asciiLine = String.fromCharCode(...line)
.split("")
.map((c) => (c === " " || (c >= " " && c <= "~" && c !== " ") ? c : "."))
.join("");
s = s.slice(16);
result += `\n ${this.hexify(line.slice(0, 8))} ${this.hexify(line.slice(8))} | ${asciiLine}`;
}
return result;
} else {
return this.hexify(uint8Array);
}
}
/**
* Format data packet using the Serial Line Internet Protocol (SLIP).
* @param {Uint8Array} data Binary unsigned 8 bit array data to format.
* @returns {Uint8Array} Formatted unsigned 8 bit data array.
*/
slipWriter(data: Uint8Array) {
const outData = [];
outData.push(0xc0);
for (let i = 0; i < data.length; i++) {
if (data[i] === 0xdb) {
outData.push(0xdb, 0xdd);
} else if (data[i] === 0xc0) {
outData.push(0xdb, 0xdc);
} else {
outData.push(data[i]);
}
}
outData.push(0xc0);
return new Uint8Array(outData);
}
/**
* Write binary data to device using the WebSerial device writable stream.
* @param {Uint8Array} data 8 bit unsigned data array to write to device.
*/
async write(data: Uint8Array) {
const outData = this.slipWriter(data);
if (this.device.writable) {
const writer = this.device.writable.getWriter();
if (this.tracing) {
console.log("Write bytes");
this.trace(`Write ${outData.length} bytes: ${this.hexConvert(outData)}`);
}
await writer.write(outData);
writer.releaseLock();
}
}
/**
* Concatenate buffer2 to buffer1 and return the resulting ArrayBuffer.
* @param {ArrayBuffer} buffer1 First buffer to concatenate.
* @param {ArrayBuffer} buffer2 Second buffer to concatenate.
* @returns {ArrayBuffer} Result Array buffer.
*/
_appendBuffer(buffer1: ArrayBuffer, buffer2: ArrayBuffer) {
const tmp = new Uint8Array(buffer1.byteLength + buffer2.byteLength);
tmp.set(new Uint8Array(buffer1), 0);
tmp.set(new Uint8Array(buffer2), buffer1.byteLength);
return tmp.buffer;
}
/**
* Take a data array and return the first well formed packet after
* replacing the escape sequence. Reads at least 8 bytes.
* @param {Uint8Array} data Unsigned 8 bit array from the device read stream.
* @returns {Uint8Array} Formatted packet using SLIP escape sequences.
*/
slipReader(data: Uint8Array) {
let i = 0;
let dataStart = 0,
dataEnd = 0;
let state = "init";
while (i < data.length) {
if (state === "init" && data[i] == 0xc0) {
dataStart = i + 1;
state = "valid_data";
i++;
continue;
}
if (state === "valid_data" && data[i] == 0xc0) {
dataEnd = i - 1;
state = "packet_complete";
break;
}
i++;
}
if (state !== "packet_complete") {
this.leftOver = data;
return new Uint8Array(0);
}
this.leftOver = data.slice(dataEnd + 2);
const tempPkt = new Uint8Array(dataEnd - dataStart + 1);
let j = 0;
for (i = dataStart; i <= dataEnd; i++, j++) {
if (data[i] === 0xdb && data[i + 1] === 0xdc) {
tempPkt[j] = 0xc0;
i++;
continue;
}
if (data[i] === 0xdb && data[i + 1] === 0xdd) {
tempPkt[j] = 0xdb;
i++;
continue;
}
tempPkt[j] = data[i];
}
const packet = tempPkt.slice(0, j); /* Remove unused bytes due to escape seq */
return packet;
}
/**
* Read from serial device using the device ReadableStream.
* @param {number} timeout Read timeout number
* @param {number} minData Minimum packet array length
* @returns {Uint8Array} 8 bit unsigned data array read from device.
*/
async read(timeout = 0, minData = 12) {
let t;
let packet = this.leftOver;
this.leftOver = new Uint8Array(0);
if (this.slipReaderEnabled) {
const valFinal = this.slipReader(packet);
if (valFinal.length > 0) {
return valFinal;
}
packet = this.leftOver;
this.leftOver = new Uint8Array(0);
}
if (this.device.readable == null) {
return this.leftOver;
}
this.reader = this.device.readable.getReader();
try {
if (timeout > 0) {
t = setTimeout(() => {
if (this.reader) {
this.reader.cancel();
}
}, timeout);
}
do {
const { value, done } = await this.reader.read();
if (done) {
this.leftOver = packet;
throw new Error("Timeout");
}
const p = new Uint8Array(this._appendBuffer(packet.buffer, value.buffer));
packet = p;
} while (packet.length < minData);
} finally {
if (timeout > 0) {
clearTimeout(t);
}
this.reader.releaseLock();
}
if (this.tracing) {
console.log("Read bytes");
this.trace(`Read ${packet.length} bytes: ${this.hexConvert(packet)}`);
}
if (this.slipReaderEnabled) {
const slipReaderResult = this.slipReader(packet);
if (this.tracing) {
console.log("Slip reader results");
this.trace(`Read ${slipReaderResult.length} bytes: ${this.hexConvert(slipReaderResult)}`);
}
return slipReaderResult;
}
return packet;
}
/**
* Read from serial device without slip formatting.
* @param {number} timeout Read timeout in milliseconds (ms)
* @returns {Uint8Array} 8 bit unsigned data array read from device.
*/
async rawRead(timeout = 0) {
if (this.leftOver.length != 0) {
const p = this.leftOver;
this.leftOver = new Uint8Array(0);
return p;
}
if (!this.device.readable) {
return this.leftOver;
}
this.reader = this.device.readable.getReader();
let t;
try {
if (timeout > 0) {
t = setTimeout(() => {
if (this.reader) {
this.reader.cancel();
}
}, timeout);
}
const { value, done } = await this.reader.read();
if (done) {
return value;
}
if (this.tracing) {
console.log("Raw Read bytes");
this.trace(`Read ${value.length} bytes: ${this.hexConvert(value)}`);
}
return value;
} finally {
if (timeout > 0) {
clearTimeout(t);
}
this.reader.releaseLock();
}
}
_DTR_state = false;
/**
* Send the RequestToSend (RTS) signal to given state
* # True for EN=LOW, chip in reset and False EN=HIGH, chip out of reset
* @param {boolean} state Boolean state to set the signal
*/
async setRTS(state: boolean) {
await this.device.setSignals({ requestToSend: state });
// # Work-around for adapters on Windows using the usbser.sys driver:
// # generate a dummy change to DTR so that the set-control-line-state
// # request is sent with the updated RTS state and the same DTR state
// Referenced to esptool.py
await this.setDTR(this._DTR_state);
}
/**
* Send the dataTerminalReady (DTS) signal to given state
* # True for IO0=LOW, chip in reset and False IO0=HIGH
* @param {boolean} state Boolean state to set the signal
*/
async setDTR(state: boolean) {
this._DTR_state = state;
await this.device.setSignals({ dataTerminalReady: state });
}
/**
* Connect to serial device using the Webserial open method.
* @param {number} baud Number baud rate for serial connection.
* @param {typeof import("w3c-web-serial").SerialOptions} serialOptions Serial Options for WebUSB SerialPort class.
*/
async connect(baud = 115200, serialOptions: SerialOptions = {}) {
await this.device.open({
baudRate: baud,
dataBits: serialOptions?.dataBits,
stopBits: serialOptions?.stopBits,
bufferSize: serialOptions?.bufferSize,
parity: serialOptions?.parity,
flowControl: serialOptions?.flowControl,
});
this.baudrate = baud;
this.leftOver = new Uint8Array(0);
}
async sleep(ms: number) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
/**
* Wait for a given timeout ms for serial device unlock.
* @param {number} timeout Timeout time in milliseconds (ms) to sleep
*/
async waitForUnlock(timeout: number) {
while (
(this.device.readable && this.device.readable.locked) ||
(this.device.writable && this.device.writable.locked)
) {
await this.sleep(timeout);
}
}
/**
* Disconnect from serial device by running SerialPort.close() after streams unlock.
*/
async disconnect() {
if (this.device.readable?.locked) {
await this.reader?.cancel();
}
await this.waitForUnlock(400);
this.reader = undefined;
await this.device.close();
}
}
export { Transport };