@myshkouski/web-serial-polyfill 2.0.3 → 2.0.4

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/serial.ts CHANGED
@@ -1,644 +1,641 @@
1
- /*
2
- * Copyright 2019 Google LLC
3
- *
4
- * Licensed under the Apache License, Version 2.0 (the
5
- * "License"); you may not use this file except in
6
- * compliance with the License. You may obtain a copy of
7
- * the License at
8
- *
9
- * https://www.apache.org/licenses/LICENSE-2.0
10
- *
11
- * Unless required by applicable law or agreed to in
12
- * writing, software distributed under the License is
13
- * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
14
- * OR CONDITIONS OF ANY KIND, either express or implied.
15
- * See the License for the specific language governing
16
- * permissions and limitations under the License.
17
- */
18
- 'use strict';
19
-
20
- export enum SerialPolyfillProtocol {
21
- UsbCdcAcm, // eslint-disable-line no-unused-vars
22
- }
23
-
24
- export interface SerialPolyfillOptions {
25
- protocol?: SerialPolyfillProtocol;
26
- usbControlInterfaceClass?: number;
27
- usbTransferInterfaceClass?: number;
28
- }
29
-
30
- const kSetLineCoding = 0x20;
31
- const kSetControlLineState = 0x22;
32
- const kSendBreak = 0x23;
33
-
34
- const kDefaultBufferSize = 255;
35
- const kDefaultDataBits = 8;
36
- const kDefaultParity = 'none';
37
- const kDefaultStopBits = 1;
38
-
39
- const kAcceptableDataBits = [16, 8, 7, 6, 5];
40
- const kAcceptableStopBits = [1, 2];
41
- const kAcceptableParity = ['none', 'even', 'odd'];
42
-
43
- const kParityIndexMapping: ParityType[] =
44
- ['none', 'odd', 'even'];
45
- const kStopBitsIndexMapping = [1, 1.5, 2];
46
-
47
- const kDefaultPolyfillOptions = {
48
- protocol: SerialPolyfillProtocol.UsbCdcAcm,
49
- usbControlInterfaceClass: 2,
50
- usbTransferInterfaceClass: 10,
51
- };
52
-
53
- /**
54
- * Utility function to get the interface implementing a desired class.
55
- * @param {USBDevice} device The USB device.
56
- * @param {number} classCode The desired interface class.
57
- * @return {USBInterface} The first interface found that implements the desired
58
- * class.
59
- * @throws TypeError if no interface is found.
60
- */
61
- function findInterface(device: USBDevice, classCode: number): USBInterface {
62
- const configuration = device.configurations[0];
63
- for (const iface of configuration.interfaces) {
64
- const alternate = iface.alternates[0];
65
- if (alternate.interfaceClass === classCode) {
66
- return iface;
67
- }
68
- }
69
- throw new TypeError(`Unable to find interface with class ${classCode}.`);
70
- }
71
-
72
- /**
73
- * Utility function to get an endpoint with a particular direction.
74
- * @param {USBInterface} iface The interface to search.
75
- * @param {USBDirection} direction The desired transfer direction.
76
- * @return {USBEndpoint} The first endpoint with the desired transfer direction.
77
- * @throws TypeError if no endpoint is found.
78
- */
79
- function findEndpoint(iface: USBInterface, direction: USBDirection):
80
- USBEndpoint {
81
- const alternate = iface.alternates[0];
82
- for (const endpoint of alternate.endpoints) {
83
- if (endpoint.direction == direction) {
84
- return endpoint;
85
- }
86
- }
87
- throw new TypeError(`Interface ${iface.interfaceNumber} does not have an ` +
88
- `${direction} endpoint.`);
89
- }
90
-
91
- /**
92
- * Implementation of the underlying source API[1] which reads data from a USB
93
- * endpoint. This can be used to construct a ReadableStream.
94
- *
95
- * [1]: https://streams.spec.whatwg.org/#underlying-source-api
96
- */
97
- class UsbEndpointUnderlyingSource implements UnderlyingByteSource {
98
- private device_: USBDevice;
99
- private endpoint_: USBEndpoint;
100
- private onError_: () => void;
101
-
102
- type: 'bytes';
103
-
104
- /**
105
- * Constructs a new UnderlyingSource that will pull data from the specified
106
- * endpoint on the given USB device.
107
- *
108
- * @param {USBDevice} device
109
- * @param {USBEndpoint} endpoint
110
- * @param {function} onError function to be called on error
111
- */
112
- constructor(device: USBDevice, endpoint: USBEndpoint, onError: () => void) {
113
- this.type = 'bytes';
114
- this.device_ = device;
115
- this.endpoint_ = endpoint;
116
- this.onError_ = onError;
117
- }
118
-
119
- /**
120
- * Reads a chunk of data from the device.
121
- *
122
- * @param {ReadableByteStreamController} controller
123
- */
124
- async pull(controller: ReadableByteStreamController): Promise<void> {
125
- let chunkSize;
126
- if (controller.desiredSize) {
127
- const d = controller.desiredSize / this.endpoint_.packetSize;
128
- chunkSize = Math.ceil(d) * this.endpoint_.packetSize;
129
- } else {
130
- chunkSize = this.endpoint_.packetSize;
131
- }
132
-
133
- try {
134
- const result = await this.device_.transferIn(
135
- this.endpoint_.endpointNumber, chunkSize);
136
- if (result.status != 'ok') {
137
- controller.error(`USB error: ${result.status}`);
138
- this.onError_();
139
- }
140
- if (result.data?.buffer) {
141
- const chunk = new Uint8Array(
142
- toArrayBuffer(result.data.buffer), result.data.byteOffset,
143
- result.data.byteLength);
144
- controller.enqueue(chunk);
145
- }
146
- } catch (error) {
147
- controller.error(error.toString());
148
- this.onError_();
149
- }
150
- }
151
- }
152
-
153
- /**
154
- * Implementation of the underlying sink API[2] which writes data to a USB
155
- * endpoint. This can be used to construct a WritableStream.
156
- *
157
- * [2]: https://streams.spec.whatwg.org/#underlying-sink-api
158
- */
159
- class UsbEndpointUnderlyingSink implements UnderlyingSink<Uint8Array> {
160
- private device_: USBDevice;
161
- private endpoint_: USBEndpoint;
162
- private onError_: () => void;
163
-
164
- /**
165
- * Constructs a new UnderlyingSink that will write data to the specified
166
- * endpoint on the given USB device.
167
- *
168
- * @param {USBDevice} device
169
- * @param {USBEndpoint} endpoint
170
- * @param {function} onError function to be called on error
171
- */
172
- constructor(device: USBDevice, endpoint: USBEndpoint, onError: () => void) {
173
- this.device_ = device;
174
- this.endpoint_ = endpoint;
175
- this.onError_ = onError;
176
- }
177
-
178
- /**
179
- * Writes a chunk to the device.
180
- *
181
- * @param {Uint8Array} chunk
182
- * @param {WritableStreamDefaultController} controller
183
- */
184
- async write(
185
- chunk: Uint8Array<ArrayBuffer>,
186
- controller: WritableStreamDefaultController): Promise<void> {
187
- try {
188
- const result =
189
- await this.device_.transferOut(this.endpoint_.endpointNumber, chunk);
190
- if (result.status != 'ok') {
191
- controller.error(result.status);
192
- this.onError_();
193
- }
194
- } catch (error) {
195
- controller.error(error.toString());
196
- this.onError_();
197
- }
198
- }
199
- }
200
-
201
- /** a class used to control serial devices over WebUSB */
202
- export class SerialPort {
203
- private polyfillOptions_: SerialPolyfillOptions;
204
- private device_: USBDevice;
205
- private controlInterface_: USBInterface;
206
- private transferInterface_: USBInterface;
207
- private inEndpoint_: USBEndpoint;
208
- private outEndpoint_: USBEndpoint;
209
-
210
- private serialOptions_: SerialOptions;
211
- private readable_: ReadableStream<Uint8Array> | null;
212
- private writable_: WritableStream<Uint8Array> | null;
213
- private outputSignals_: SerialOutputSignals;
214
-
215
- /**
216
- * constructor taking a WebUSB device that creates a SerialPort instance.
217
- * @param {USBDevice} device A device acquired from the WebUSB API
218
- * @param {SerialPolyfillOptions} polyfillOptions Optional options to
219
- * configure the polyfill.
220
- */
221
- public constructor(
222
- device: USBDevice,
223
- polyfillOptions?: SerialPolyfillOptions) {
224
- this.polyfillOptions_ = {...kDefaultPolyfillOptions, ...polyfillOptions};
225
- this.outputSignals_ = {
226
- dataTerminalReady: false,
227
- requestToSend: false,
228
- break: false,
229
- };
230
-
231
- this.device_ = device;
232
- this.controlInterface_ = findInterface(
233
- this.device_,
234
- this.polyfillOptions_.usbControlInterfaceClass as number);
235
- this.transferInterface_ = findInterface(
236
- this.device_,
237
- this.polyfillOptions_.usbTransferInterfaceClass as number);
238
- this.inEndpoint_ = findEndpoint(this.transferInterface_, 'in');
239
- this.outEndpoint_ = findEndpoint(this.transferInterface_, 'out');
240
- }
241
-
242
- /**
243
- * Getter for the readable attribute. Constructs a new ReadableStream as
244
- * necessary.
245
- * @return {ReadableStream} the current readable stream
246
- */
247
- public get readable(): ReadableStream<Uint8Array> | null {
248
- if (!this.readable_ && this.device_.opened) {
249
- this.readable_ = new ReadableStream<Uint8Array>(
250
- new UsbEndpointUnderlyingSource(
251
- this.device_, this.inEndpoint_, () => {
252
- this.readable_ = null;
253
- }),
254
- {
255
- highWaterMark: this.serialOptions_.bufferSize ?? kDefaultBufferSize,
256
- });
257
- }
258
- return this.readable_;
259
- }
260
-
261
- /**
262
- * Getter for the writable attribute. Constructs a new WritableStream as
263
- * necessary.
264
- * @return {WritableStream} the current writable stream
265
- */
266
- public get writable(): WritableStream<Uint8Array> | null {
267
- if (!this.writable_ && this.device_.opened) {
268
- this.writable_ = new WritableStream(
269
- new UsbEndpointUnderlyingSink(
270
- this.device_, this.outEndpoint_, () => {
271
- this.writable_ = null;
272
- }),
273
- new ByteLengthQueuingStrategy({
274
- highWaterMark: this.serialOptions_.bufferSize ?? kDefaultBufferSize,
275
- }));
276
- }
277
- return this.writable_;
278
- }
279
-
280
- /**
281
- * Release transfer and control interfaces.
282
- * Used before closing device.
283
- */
284
- private async releaseInterfaces_(): Promise<void> {
285
- if (this.transferInterface_.claimed) {
286
- await this.device_.releaseInterface(
287
- this.transferInterface_.interfaceNumber
288
- );
289
- }
290
- if (this.controlInterface_.claimed) {
291
- await this.device_.releaseInterface(
292
- this.controlInterface_.interfaceNumber);
293
- }
294
- }
295
-
296
- /**
297
- * a function that opens the device and claims all interfaces needed to
298
- * control and communicate to and from the serial device
299
- * @param {SerialOptions} options Object containing serial options
300
- * @return {Promise<void>} A promise that will resolve when device is ready
301
- * for communication
302
- */
303
- public async open(options: SerialOptions): Promise<void> {
304
- this.serialOptions_ = options;
305
- this.validateOptions();
306
-
307
- try {
308
- await this.device_.open();
309
- if (this.device_.configuration === null) {
310
- await this.device_.selectConfiguration(1);
311
- }
312
-
313
- await this.device_.claimInterface(this.controlInterface_.interfaceNumber);
314
- if (this.controlInterface_ !== this.transferInterface_) {
315
- await this.device_.claimInterface(
316
- this.transferInterface_.interfaceNumber);
317
- }
318
-
319
- await this.setLineCoding();
320
- await this.setSignals({dataTerminalReady: true});
321
- } catch (error) {
322
- if (this.device_.opened) {
323
- await this.releaseInterfaces_();
324
- await this.device_.close();
325
- }
326
- throw new Error('Error setting up device: ' + error.toString());
327
- }
328
- }
329
-
330
- /**
331
- * Closes the port.
332
- *
333
- * @return {Promise<void>} A promise that will resolve when the port is
334
- * closed.
335
- */
336
- public async close(): Promise<void> {
337
- const promises = [];
338
- if (this.readable_) {
339
- promises.push(this.readable_.cancel());
340
- }
341
- if (this.writable_) {
342
- promises.push(this.writable_.abort());
343
- }
344
- await Promise.all(promises);
345
- this.readable_ = null;
346
- this.writable_ = null;
347
- if (this.device_.opened) {
348
- await this.setSignals({dataTerminalReady: false, requestToSend: false});
349
- await this.releaseInterfaces_();
350
- await this.device_.close();
351
- }
352
- }
353
-
354
- /**
355
- * Forgets the port.
356
- *
357
- * @return {Promise<void>} A promise that will resolve when the port is
358
- * forgotten.
359
- */
360
- public async forget(): Promise<void> {
361
- return this.device_.forget();
362
- }
363
-
364
- /**
365
- * A function that returns properties of the device.
366
- * @return {SerialPortInfo} Device properties.
367
- */
368
- public getInfo(): SerialPortInfo {
369
- return {
370
- usbVendorId: this.device_.vendorId,
371
- usbProductId: this.device_.productId,
372
- };
373
- }
374
-
375
- /**
376
- * A function used to change the serial settings of the device
377
- * @param {object} options the object which carries serial settings data
378
- * @return {Promise<void>} A promise that will resolve when the options are
379
- * set
380
- */
381
- public reconfigure(options: SerialOptions): Promise<void> {
382
- this.serialOptions_ = {...this.serialOptions_, ...options};
383
- this.validateOptions();
384
- return this.setLineCoding();
385
- }
386
-
387
- /**
388
- * Sets control signal state for the port.
389
- * @param {SerialOutputSignals} signals The signals to enable or disable.
390
- * @return {Promise<void>} a promise that is resolved when the signal state
391
- * has been changed.
392
- */
393
- public async setSignals(signals: SerialOutputSignals): Promise<void> {
394
- this.outputSignals_ = {...this.outputSignals_, ...signals};
395
-
396
- if (signals.dataTerminalReady !== undefined ||
397
- signals.requestToSend !== undefined) {
398
- // The Set_Control_Line_State command expects a bitmap containing the
399
- // values of all output signals that should be enabled or disabled.
400
- //
401
- // Ref: USB CDC specification version 1.1 §6.2.14.
402
- const value = (this.outputSignals_.dataTerminalReady ? 1 << 0 : 0) |
403
- (this.outputSignals_.requestToSend ? 1 << 1 : 0);
404
-
405
- await this.device_.controlTransferOut({
406
- 'requestType': 'class',
407
- 'recipient': 'interface',
408
- 'request': kSetControlLineState,
409
- 'value': value,
410
- 'index': this.controlInterface_.interfaceNumber,
411
- });
412
- }
413
-
414
- if (signals.break !== undefined) {
415
- // The SendBreak command expects to be given a duration for how long the
416
- // break signal should be asserted. Passing 0xFFFF enables the signal
417
- // until 0x0000 is send.
418
- //
419
- // Ref: USB CDC specification version 1.1 §6.2.15.
420
- const value = this.outputSignals_.break ? 0xFFFF : 0x0000;
421
-
422
- await this.device_.controlTransferOut({
423
- 'requestType': 'class',
424
- 'recipient': 'interface',
425
- 'request': kSendBreak,
426
- 'value': value,
427
- 'index': this.controlInterface_.interfaceNumber,
428
- });
429
- }
430
- }
431
-
432
- /**
433
- * Checks the serial options for validity and throws an error if it is
434
- * not valid
435
- */
436
- private validateOptions(): void {
437
- if (!this.isValidBaudRate(this.serialOptions_.baudRate)) {
438
- throw new RangeError('invalid Baud Rate ' + this.serialOptions_.baudRate);
439
- }
440
-
441
- if (!this.isValidDataBits(this.serialOptions_.dataBits)) {
442
- throw new RangeError('invalid dataBits ' + this.serialOptions_.dataBits);
443
- }
444
-
445
- if (!this.isValidStopBits(this.serialOptions_.stopBits)) {
446
- throw new RangeError('invalid stopBits ' + this.serialOptions_.stopBits);
447
- }
448
-
449
- if (!this.isValidParity(this.serialOptions_.parity)) {
450
- throw new RangeError('invalid parity ' + this.serialOptions_.parity);
451
- }
452
- }
453
-
454
- /**
455
- * Checks the baud rate for validity
456
- * @param {number} baudRate the baud rate to check
457
- * @return {boolean} A boolean that reflects whether the baud rate is valid
458
- */
459
- private isValidBaudRate(baudRate: number): boolean {
460
- return baudRate % 1 === 0;
461
- }
462
-
463
- /**
464
- * Checks the data bits for validity
465
- * @param {number} dataBits the data bits to check
466
- * @return {boolean} A boolean that reflects whether the data bits setting is
467
- * valid
468
- */
469
- private isValidDataBits(dataBits: number | undefined): boolean {
470
- if (typeof dataBits === 'undefined') {
471
- return true;
472
- }
473
- return kAcceptableDataBits.includes(dataBits);
474
- }
475
-
476
- /**
477
- * Checks the stop bits for validity
478
- * @param {number} stopBits the stop bits to check
479
- * @return {boolean} A boolean that reflects whether the stop bits setting is
480
- * valid
481
- */
482
- private isValidStopBits(stopBits: number | undefined): boolean {
483
- if (typeof stopBits === 'undefined') {
484
- return true;
485
- }
486
- return kAcceptableStopBits.includes(stopBits);
487
- }
488
-
489
- /**
490
- * Checks the parity for validity
491
- * @param {string} parity the parity to check
492
- * @return {boolean} A boolean that reflects whether the parity is valid
493
- */
494
- private isValidParity(parity: ParityType | undefined): boolean {
495
- if (typeof parity === 'undefined') {
496
- return true;
497
- }
498
- return kAcceptableParity.includes(parity);
499
- }
500
-
501
- /**
502
- * sends the options alog the control interface to set them on the device
503
- * @return {Promise} a promise that will resolve when the options are set
504
- */
505
- private async setLineCoding(): Promise<void> {
506
- // Ref: USB CDC specification version 1.1 §6.2.12.
507
- const buffer = new ArrayBuffer(7);
508
- const view = new DataView(buffer);
509
- view.setUint32(0, this.serialOptions_.baudRate, true);
510
- view.setUint8(
511
- 4, kStopBitsIndexMapping.indexOf(
512
- this.serialOptions_.stopBits ?? kDefaultStopBits));
513
- view.setUint8(
514
- 5, kParityIndexMapping.indexOf(
515
- this.serialOptions_.parity ?? kDefaultParity));
516
- view.setUint8(6, this.serialOptions_.dataBits ?? kDefaultDataBits);
517
-
518
- const result = await this.device_.controlTransferOut({
519
- 'requestType': 'class',
520
- 'recipient': 'interface',
521
- 'request': kSetLineCoding,
522
- 'value': 0x00,
523
- 'index': this.controlInterface_.interfaceNumber,
524
- }, buffer);
525
- if (result.status != 'ok') {
526
- throw new DOMException('NetworkError', 'Failed to set line coding.');
527
- }
528
- }
529
- }
530
-
531
- /** generic implementation of navigator.serial object */
532
- export abstract class BaseSerial<T extends SerialPort> {
533
- /**
534
- * @param {USB} usb Instance of navigator.usb object
535
- */
536
- constructor(
537
- protected readonly usb: USB,
538
- ) { }
539
-
540
- protected abstract createPort(device: USBDevice,
541
- options?: SerialPolyfillOptions): T
542
-
543
- /**
544
- * Requests permission to access a new port.
545
- *
546
- * @param {SerialPortRequestOptions} options
547
- * @param {SerialPolyfillOptions} polyfillOptions
548
- * @return {Promise<SerialPort>}
549
- */
550
- async requestPort(
551
- options?: SerialPortRequestOptions,
552
- polyfillOptions?: SerialPolyfillOptions): Promise<T> {
553
- polyfillOptions = {...kDefaultPolyfillOptions, ...polyfillOptions};
554
-
555
- const usbFilters: USBDeviceFilter[] = [];
556
- if (options && options.filters) {
557
- for (const filter of options.filters) {
558
- const usbFilter: USBDeviceFilter = {
559
- classCode: polyfillOptions.usbControlInterfaceClass,
560
- };
561
- if (filter.usbVendorId !== undefined) {
562
- usbFilter.vendorId = filter.usbVendorId;
563
- }
564
- if (filter.usbProductId !== undefined) {
565
- usbFilter.productId = filter.usbProductId;
566
- }
567
- usbFilters.push(usbFilter);
568
- }
569
- }
570
-
571
- if (usbFilters.length === 0) {
572
- usbFilters.push({
573
- classCode: polyfillOptions.usbControlInterfaceClass,
574
- });
575
- }
576
-
577
- const device = await this.usb.requestDevice({'filters': usbFilters});
578
- const port = this.createPort(device, polyfillOptions);
579
- return port;
580
- }
581
-
582
- /**
583
- * Get the set of currently available ports.
584
- *
585
- * @param {SerialPolyfillOptions} polyfillOptions Polyfill configuration that
586
- * should be applied to these ports.
587
- * @return {Promise<SerialPort[]>} a promise that is resolved with a list of
588
- * ports.
589
- */
590
- async getPorts(polyfillOptions?: SerialPolyfillOptions): Promise<T[]> {
591
- polyfillOptions = {...kDefaultPolyfillOptions, ...polyfillOptions};
592
-
593
- const devices = await this.usb.getDevices();
594
- const ports: T[] = [];
595
- devices.forEach((device) => {
596
- try {
597
- const port = this.createPort(device, polyfillOptions);
598
- ports.push(port);
599
- } catch (e) {
600
- // Skip unrecognized port.
601
- }
602
- });
603
- return ports;
604
- }
605
- }
606
-
607
- /** default implementation of the global navigator.serial object */
608
- export class Serial extends BaseSerial<SerialPort> {
609
- /**
610
- * @param {USBDevice} device
611
- * @param {SerialPolyfillOptions} options
612
- * @return {SerialPort} Default serial port implementation
613
- */
614
- protected createPort(device: USBDevice,
615
- options?: SerialPolyfillOptions): SerialPort {
616
- return new SerialPort(device, options);
617
- }
618
- }
619
-
620
- /**
621
- * Converts ArrayBufferLike to ArrayBuffer.
622
- *
623
- * @param {buffer} buffer
624
- * @return {ArrayBuffer} original ArrayBuffer
625
- * or new ArrayBuffer with contents of SharedArrayBuffer
626
- */
627
- function toArrayBuffer(buffer: ArrayBufferLike) {
628
- if (buffer instanceof ArrayBuffer) {
629
- // Return buffer when it's already an ArrayBuffer
630
- return buffer;
631
- }
632
-
633
- // Create a new ArrayBuffer with the same byte length
634
- const arrayBuffer = new ArrayBuffer(buffer.byteLength);
635
-
636
- // Create views for both buffers
637
- const sharedArrayBufferView = new Uint8Array(buffer);
638
- const arrayBufferView = new Uint8Array(arrayBuffer);
639
-
640
- // Copy the contents
641
- arrayBufferView.set(sharedArrayBufferView);
642
-
643
- return arrayBuffer;
644
- }
1
+ /*
2
+ * Copyright 2019 Google LLC
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the
5
+ * "License"); you may not use this file except in
6
+ * compliance with the License. You may obtain a copy of
7
+ * the License at
8
+ *
9
+ * https://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in
12
+ * writing, software distributed under the License is
13
+ * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
14
+ * OR CONDITIONS OF ANY KIND, either express or implied.
15
+ * See the License for the specific language governing
16
+ * permissions and limitations under the License.
17
+ */
18
+ 'use strict';
19
+
20
+ export enum SerialPolyfillProtocol {
21
+ UsbCdcAcm, // eslint-disable-line no-unused-vars
22
+ }
23
+
24
+ export interface SerialPolyfillOptions {
25
+ protocol?: SerialPolyfillProtocol;
26
+ usbControlInterfaceClass?: number;
27
+ usbTransferInterfaceClass?: number;
28
+ }
29
+
30
+ const kSetLineCoding = 0x20;
31
+ const kSetControlLineState = 0x22;
32
+ const kSendBreak = 0x23;
33
+
34
+ const kDefaultBufferSize = 255;
35
+ const kDefaultDataBits = 8;
36
+ const kDefaultParity = 'none';
37
+ const kDefaultStopBits = 1;
38
+
39
+ const kAcceptableDataBits = [16, 8, 7, 6, 5];
40
+ const kAcceptableStopBits = [1, 2];
41
+ const kAcceptableParity = ['none', 'even', 'odd'];
42
+
43
+ const kParityIndexMapping: ParityType[] =
44
+ ['none', 'odd', 'even'];
45
+ const kStopBitsIndexMapping = [1, 1.5, 2];
46
+
47
+ const kDefaultPolyfillOptions = {
48
+ protocol: SerialPolyfillProtocol.UsbCdcAcm,
49
+ usbControlInterfaceClass: 2,
50
+ usbTransferInterfaceClass: 10,
51
+ };
52
+
53
+ /**
54
+ * Utility function to get the interface implementing a desired class.
55
+ * @param {USBDevice} device The USB device.
56
+ * @param {number} classCode The desired interface class.
57
+ * @return {USBInterface} The first interface found that implements the desired
58
+ * class.
59
+ * @throws TypeError if no interface is found.
60
+ */
61
+ function findInterface(device: USBDevice, classCode: number): USBInterface {
62
+ const configuration = device.configurations[0];
63
+ for (const iface of configuration.interfaces) {
64
+ const alternate = iface.alternates[0];
65
+ if (alternate.interfaceClass === classCode) {
66
+ return iface;
67
+ }
68
+ }
69
+ throw new TypeError(`Unable to find interface with class ${classCode}.`);
70
+ }
71
+
72
+ /**
73
+ * Utility function to get an endpoint with a particular direction.
74
+ * @param {USBInterface} iface The interface to search.
75
+ * @param {USBDirection} direction The desired transfer direction.
76
+ * @return {USBEndpoint} The first endpoint with the desired transfer direction.
77
+ * @throws TypeError if no endpoint is found.
78
+ */
79
+ function findEndpoint(iface: USBInterface, direction: USBDirection):
80
+ USBEndpoint {
81
+ const alternate = iface.alternates[0];
82
+ for (const endpoint of alternate.endpoints) {
83
+ if (endpoint.direction == direction) {
84
+ return endpoint;
85
+ }
86
+ }
87
+ throw new TypeError(`Interface ${iface.interfaceNumber} does not have an ` +
88
+ `${direction} endpoint.`);
89
+ }
90
+
91
+ /**
92
+ * Implementation of the underlying source API[1] which reads data from a USB
93
+ * endpoint. This can be used to construct a ReadableStream.
94
+ *
95
+ * [1]: https://streams.spec.whatwg.org/#underlying-source-api
96
+ */
97
+ class UsbEndpointUnderlyingSource implements UnderlyingByteSource {
98
+ private device_: USBDevice;
99
+ private endpoint_: USBEndpoint;
100
+ private onError_: () => void;
101
+
102
+ type: 'bytes';
103
+
104
+ /**
105
+ * Constructs a new UnderlyingSource that will pull data from the specified
106
+ * endpoint on the given USB device.
107
+ *
108
+ * @param {USBDevice} device
109
+ * @param {USBEndpoint} endpoint
110
+ * @param {function} onError function to be called on error
111
+ */
112
+ constructor(device: USBDevice, endpoint: USBEndpoint, onError: () => void) {
113
+ this.type = 'bytes';
114
+ this.device_ = device;
115
+ this.endpoint_ = endpoint;
116
+ this.onError_ = onError;
117
+ }
118
+
119
+ /**
120
+ * Reads a chunk of data from the device.
121
+ *
122
+ * @param {ReadableByteStreamController} controller
123
+ */
124
+ async pull(controller: ReadableByteStreamController): Promise<void> {
125
+ let chunkSize;
126
+ if (controller.desiredSize) {
127
+ const d = controller.desiredSize / this.endpoint_.packetSize;
128
+ chunkSize = Math.ceil(d) * this.endpoint_.packetSize;
129
+ } else {
130
+ chunkSize = this.endpoint_.packetSize;
131
+ }
132
+
133
+ try {
134
+ const result = await this.device_.transferIn(
135
+ this.endpoint_.endpointNumber, chunkSize);
136
+ if (result.status != 'ok') {
137
+ controller.error(`USB error: ${result.status}`);
138
+ this.onError_();
139
+ }
140
+ if (result.data?.buffer) {
141
+ const chunk = new Uint8Array(
142
+ toArrayBuffer(result.data.buffer), result.data.byteOffset,
143
+ result.data.byteLength);
144
+ controller.enqueue(chunk);
145
+ }
146
+ } catch (error) {
147
+ controller.error(error.toString());
148
+ this.onError_();
149
+ }
150
+ }
151
+ }
152
+
153
+ /**
154
+ * Implementation of the underlying sink API[2] which writes data to a USB
155
+ * endpoint. This can be used to construct a WritableStream.
156
+ *
157
+ * [2]: https://streams.spec.whatwg.org/#underlying-sink-api
158
+ */
159
+ class UsbEndpointUnderlyingSink implements UnderlyingSink<Uint8Array> {
160
+ private device_: USBDevice;
161
+ private endpoint_: USBEndpoint;
162
+ private onError_: () => void;
163
+
164
+ /**
165
+ * Constructs a new UnderlyingSink that will write data to the specified
166
+ * endpoint on the given USB device.
167
+ *
168
+ * @param {USBDevice} device
169
+ * @param {USBEndpoint} endpoint
170
+ * @param {function} onError function to be called on error
171
+ */
172
+ constructor(device: USBDevice, endpoint: USBEndpoint, onError: () => void) {
173
+ this.device_ = device;
174
+ this.endpoint_ = endpoint;
175
+ this.onError_ = onError;
176
+ }
177
+
178
+ /**
179
+ * Writes a chunk to the device.
180
+ *
181
+ * @param {Uint8Array} chunk
182
+ * @param {WritableStreamDefaultController} controller
183
+ */
184
+ async write(
185
+ chunk: Uint8Array<ArrayBuffer>,
186
+ controller: WritableStreamDefaultController): Promise<void> {
187
+ try {
188
+ const result =
189
+ await this.device_.transferOut(this.endpoint_.endpointNumber, chunk);
190
+ if (result.status != 'ok') {
191
+ controller.error(result.status);
192
+ this.onError_();
193
+ }
194
+ } catch (error) {
195
+ controller.error(error.toString());
196
+ this.onError_();
197
+ }
198
+ }
199
+ }
200
+
201
+ /** a class used to control serial devices over WebUSB */
202
+ export class SerialPort {
203
+ private polyfillOptions_: SerialPolyfillOptions;
204
+ private device_: USBDevice;
205
+ private controlInterface_: USBInterface;
206
+ private transferInterface_: USBInterface;
207
+ private inEndpoint_: USBEndpoint;
208
+ private outEndpoint_: USBEndpoint;
209
+
210
+ private serialOptions_: SerialOptions;
211
+ private readable_: ReadableStream<Uint8Array> | null;
212
+ private writable_: WritableStream<Uint8Array> | null;
213
+ private outputSignals_: SerialOutputSignals;
214
+
215
+ /**
216
+ * constructor taking a WebUSB device that creates a SerialPort instance.
217
+ * @param {USBDevice} device A device acquired from the WebUSB API
218
+ * @param {SerialPolyfillOptions} polyfillOptions Optional options to
219
+ * configure the polyfill.
220
+ */
221
+ public constructor(
222
+ device: USBDevice,
223
+ polyfillOptions?: SerialPolyfillOptions) {
224
+ this.polyfillOptions_ = {...kDefaultPolyfillOptions, ...polyfillOptions};
225
+ this.outputSignals_ = {
226
+ dataTerminalReady: false,
227
+ requestToSend: false,
228
+ break: false,
229
+ };
230
+
231
+ this.device_ = device;
232
+ this.controlInterface_ = findInterface(
233
+ this.device_,
234
+ this.polyfillOptions_.usbControlInterfaceClass as number);
235
+ this.transferInterface_ = findInterface(
236
+ this.device_,
237
+ this.polyfillOptions_.usbTransferInterfaceClass as number);
238
+ this.inEndpoint_ = findEndpoint(this.transferInterface_, 'in');
239
+ this.outEndpoint_ = findEndpoint(this.transferInterface_, 'out');
240
+ }
241
+
242
+ /**
243
+ * Getter for the readable attribute. Constructs a new ReadableStream as
244
+ * necessary.
245
+ * @return {ReadableStream} the current readable stream
246
+ */
247
+ public get readable(): ReadableStream<Uint8Array> | null {
248
+ if (!this.readable_ && this.device_.opened) {
249
+ this.readable_ = new ReadableStream<Uint8Array>(
250
+ new UsbEndpointUnderlyingSource(
251
+ this.device_, this.inEndpoint_, () => {
252
+ this.readable_ = null;
253
+ }),
254
+ {
255
+ highWaterMark: this.serialOptions_.bufferSize ?? kDefaultBufferSize,
256
+ });
257
+ }
258
+ return this.readable_;
259
+ }
260
+
261
+ /**
262
+ * Getter for the writable attribute. Constructs a new WritableStream as
263
+ * necessary.
264
+ * @return {WritableStream} the current writable stream
265
+ */
266
+ public get writable(): WritableStream<Uint8Array> | null {
267
+ if (!this.writable_ && this.device_.opened) {
268
+ this.writable_ = new WritableStream(
269
+ new UsbEndpointUnderlyingSink(
270
+ this.device_, this.outEndpoint_, () => {
271
+ this.writable_ = null;
272
+ }),
273
+ new ByteLengthQueuingStrategy({
274
+ highWaterMark: this.serialOptions_.bufferSize ?? kDefaultBufferSize,
275
+ }));
276
+ }
277
+ return this.writable_;
278
+ }
279
+
280
+ /**
281
+ * Release transfer and control interfaces.
282
+ * Used before closing device.
283
+ */
284
+ private async releaseInterfaces_(): Promise<void> {
285
+ await this.device_.releaseInterface(
286
+ this.transferInterface_.interfaceNumber
287
+ );
288
+ await this.device_.releaseInterface(
289
+ this.controlInterface_.interfaceNumber
290
+ );
291
+ }
292
+
293
+ /**
294
+ * a function that opens the device and claims all interfaces needed to
295
+ * control and communicate to and from the serial device
296
+ * @param {SerialOptions} options Object containing serial options
297
+ * @return {Promise<void>} A promise that will resolve when device is ready
298
+ * for communication
299
+ */
300
+ public async open(options: SerialOptions): Promise<void> {
301
+ this.serialOptions_ = options;
302
+ this.validateOptions();
303
+
304
+ try {
305
+ await this.device_.open();
306
+ if (this.device_.configuration === null) {
307
+ await this.device_.selectConfiguration(1);
308
+ }
309
+
310
+ await this.device_.claimInterface(this.controlInterface_.interfaceNumber);
311
+ if (this.controlInterface_ !== this.transferInterface_) {
312
+ await this.device_.claimInterface(
313
+ this.transferInterface_.interfaceNumber);
314
+ }
315
+
316
+ await this.setLineCoding();
317
+ await this.setSignals({dataTerminalReady: true});
318
+ } catch (error) {
319
+ if (this.device_.opened) {
320
+ await this.releaseInterfaces_();
321
+ await this.device_.close();
322
+ }
323
+ throw new Error('Error setting up device: ' + error.toString());
324
+ }
325
+ }
326
+
327
+ /**
328
+ * Closes the port.
329
+ *
330
+ * @return {Promise<void>} A promise that will resolve when the port is
331
+ * closed.
332
+ */
333
+ public async close(): Promise<void> {
334
+ const promises = [];
335
+ if (this.readable_) {
336
+ promises.push(this.readable_.cancel());
337
+ }
338
+ if (this.writable_) {
339
+ promises.push(this.writable_.abort());
340
+ }
341
+ await Promise.all(promises);
342
+ this.readable_ = null;
343
+ this.writable_ = null;
344
+ if (this.device_.opened) {
345
+ await this.setSignals({dataTerminalReady: false, requestToSend: false});
346
+ await this.releaseInterfaces_();
347
+ await this.device_.close();
348
+ }
349
+ }
350
+
351
+ /**
352
+ * Forgets the port.
353
+ *
354
+ * @return {Promise<void>} A promise that will resolve when the port is
355
+ * forgotten.
356
+ */
357
+ public async forget(): Promise<void> {
358
+ return this.device_.forget();
359
+ }
360
+
361
+ /**
362
+ * A function that returns properties of the device.
363
+ * @return {SerialPortInfo} Device properties.
364
+ */
365
+ public getInfo(): SerialPortInfo {
366
+ return {
367
+ usbVendorId: this.device_.vendorId,
368
+ usbProductId: this.device_.productId,
369
+ };
370
+ }
371
+
372
+ /**
373
+ * A function used to change the serial settings of the device
374
+ * @param {object} options the object which carries serial settings data
375
+ * @return {Promise<void>} A promise that will resolve when the options are
376
+ * set
377
+ */
378
+ public reconfigure(options: SerialOptions): Promise<void> {
379
+ this.serialOptions_ = {...this.serialOptions_, ...options};
380
+ this.validateOptions();
381
+ return this.setLineCoding();
382
+ }
383
+
384
+ /**
385
+ * Sets control signal state for the port.
386
+ * @param {SerialOutputSignals} signals The signals to enable or disable.
387
+ * @return {Promise<void>} a promise that is resolved when the signal state
388
+ * has been changed.
389
+ */
390
+ public async setSignals(signals: SerialOutputSignals): Promise<void> {
391
+ this.outputSignals_ = {...this.outputSignals_, ...signals};
392
+
393
+ if (signals.dataTerminalReady !== undefined ||
394
+ signals.requestToSend !== undefined) {
395
+ // The Set_Control_Line_State command expects a bitmap containing the
396
+ // values of all output signals that should be enabled or disabled.
397
+ //
398
+ // Ref: USB CDC specification version 1.1 §6.2.14.
399
+ const value = (this.outputSignals_.dataTerminalReady ? 1 << 0 : 0) |
400
+ (this.outputSignals_.requestToSend ? 1 << 1 : 0);
401
+
402
+ await this.device_.controlTransferOut({
403
+ 'requestType': 'class',
404
+ 'recipient': 'interface',
405
+ 'request': kSetControlLineState,
406
+ 'value': value,
407
+ 'index': this.controlInterface_.interfaceNumber,
408
+ });
409
+ }
410
+
411
+ if (signals.break !== undefined) {
412
+ // The SendBreak command expects to be given a duration for how long the
413
+ // break signal should be asserted. Passing 0xFFFF enables the signal
414
+ // until 0x0000 is send.
415
+ //
416
+ // Ref: USB CDC specification version 1.1 §6.2.15.
417
+ const value = this.outputSignals_.break ? 0xFFFF : 0x0000;
418
+
419
+ await this.device_.controlTransferOut({
420
+ 'requestType': 'class',
421
+ 'recipient': 'interface',
422
+ 'request': kSendBreak,
423
+ 'value': value,
424
+ 'index': this.controlInterface_.interfaceNumber,
425
+ });
426
+ }
427
+ }
428
+
429
+ /**
430
+ * Checks the serial options for validity and throws an error if it is
431
+ * not valid
432
+ */
433
+ private validateOptions(): void {
434
+ if (!this.isValidBaudRate(this.serialOptions_.baudRate)) {
435
+ throw new RangeError('invalid Baud Rate ' + this.serialOptions_.baudRate);
436
+ }
437
+
438
+ if (!this.isValidDataBits(this.serialOptions_.dataBits)) {
439
+ throw new RangeError('invalid dataBits ' + this.serialOptions_.dataBits);
440
+ }
441
+
442
+ if (!this.isValidStopBits(this.serialOptions_.stopBits)) {
443
+ throw new RangeError('invalid stopBits ' + this.serialOptions_.stopBits);
444
+ }
445
+
446
+ if (!this.isValidParity(this.serialOptions_.parity)) {
447
+ throw new RangeError('invalid parity ' + this.serialOptions_.parity);
448
+ }
449
+ }
450
+
451
+ /**
452
+ * Checks the baud rate for validity
453
+ * @param {number} baudRate the baud rate to check
454
+ * @return {boolean} A boolean that reflects whether the baud rate is valid
455
+ */
456
+ private isValidBaudRate(baudRate: number): boolean {
457
+ return baudRate % 1 === 0;
458
+ }
459
+
460
+ /**
461
+ * Checks the data bits for validity
462
+ * @param {number} dataBits the data bits to check
463
+ * @return {boolean} A boolean that reflects whether the data bits setting is
464
+ * valid
465
+ */
466
+ private isValidDataBits(dataBits: number | undefined): boolean {
467
+ if (typeof dataBits === 'undefined') {
468
+ return true;
469
+ }
470
+ return kAcceptableDataBits.includes(dataBits);
471
+ }
472
+
473
+ /**
474
+ * Checks the stop bits for validity
475
+ * @param {number} stopBits the stop bits to check
476
+ * @return {boolean} A boolean that reflects whether the stop bits setting is
477
+ * valid
478
+ */
479
+ private isValidStopBits(stopBits: number | undefined): boolean {
480
+ if (typeof stopBits === 'undefined') {
481
+ return true;
482
+ }
483
+ return kAcceptableStopBits.includes(stopBits);
484
+ }
485
+
486
+ /**
487
+ * Checks the parity for validity
488
+ * @param {string} parity the parity to check
489
+ * @return {boolean} A boolean that reflects whether the parity is valid
490
+ */
491
+ private isValidParity(parity: ParityType | undefined): boolean {
492
+ if (typeof parity === 'undefined') {
493
+ return true;
494
+ }
495
+ return kAcceptableParity.includes(parity);
496
+ }
497
+
498
+ /**
499
+ * sends the options alog the control interface to set them on the device
500
+ * @return {Promise} a promise that will resolve when the options are set
501
+ */
502
+ private async setLineCoding(): Promise<void> {
503
+ // Ref: USB CDC specification version 1.1 §6.2.12.
504
+ const buffer = new ArrayBuffer(7);
505
+ const view = new DataView(buffer);
506
+ view.setUint32(0, this.serialOptions_.baudRate, true);
507
+ view.setUint8(
508
+ 4, kStopBitsIndexMapping.indexOf(
509
+ this.serialOptions_.stopBits ?? kDefaultStopBits));
510
+ view.setUint8(
511
+ 5, kParityIndexMapping.indexOf(
512
+ this.serialOptions_.parity ?? kDefaultParity));
513
+ view.setUint8(6, this.serialOptions_.dataBits ?? kDefaultDataBits);
514
+
515
+ const result = await this.device_.controlTransferOut({
516
+ 'requestType': 'class',
517
+ 'recipient': 'interface',
518
+ 'request': kSetLineCoding,
519
+ 'value': 0x00,
520
+ 'index': this.controlInterface_.interfaceNumber,
521
+ }, buffer);
522
+ if (result.status != 'ok') {
523
+ throw new DOMException('NetworkError', 'Failed to set line coding.');
524
+ }
525
+ }
526
+ }
527
+
528
+ /** generic implementation of navigator.serial object */
529
+ export abstract class BaseSerial<T extends SerialPort> {
530
+ /**
531
+ * @param {USB} usb Instance of navigator.usb object
532
+ */
533
+ constructor(
534
+ protected readonly usb: USB,
535
+ ) { }
536
+
537
+ protected abstract createPort(device: USBDevice,
538
+ options?: SerialPolyfillOptions): T
539
+
540
+ /**
541
+ * Requests permission to access a new port.
542
+ *
543
+ * @param {SerialPortRequestOptions} options
544
+ * @param {SerialPolyfillOptions} polyfillOptions
545
+ * @return {Promise<SerialPort>}
546
+ */
547
+ async requestPort(
548
+ options?: SerialPortRequestOptions,
549
+ polyfillOptions?: SerialPolyfillOptions): Promise<T> {
550
+ polyfillOptions = {...kDefaultPolyfillOptions, ...polyfillOptions};
551
+
552
+ const usbFilters: USBDeviceFilter[] = [];
553
+ if (options && options.filters) {
554
+ for (const filter of options.filters) {
555
+ const usbFilter: USBDeviceFilter = {
556
+ classCode: polyfillOptions.usbControlInterfaceClass,
557
+ };
558
+ if (filter.usbVendorId !== undefined) {
559
+ usbFilter.vendorId = filter.usbVendorId;
560
+ }
561
+ if (filter.usbProductId !== undefined) {
562
+ usbFilter.productId = filter.usbProductId;
563
+ }
564
+ usbFilters.push(usbFilter);
565
+ }
566
+ }
567
+
568
+ if (usbFilters.length === 0) {
569
+ usbFilters.push({
570
+ classCode: polyfillOptions.usbControlInterfaceClass,
571
+ });
572
+ }
573
+
574
+ const device = await this.usb.requestDevice({'filters': usbFilters});
575
+ const port = this.createPort(device, polyfillOptions);
576
+ return port;
577
+ }
578
+
579
+ /**
580
+ * Get the set of currently available ports.
581
+ *
582
+ * @param {SerialPolyfillOptions} polyfillOptions Polyfill configuration that
583
+ * should be applied to these ports.
584
+ * @return {Promise<SerialPort[]>} a promise that is resolved with a list of
585
+ * ports.
586
+ */
587
+ async getPorts(polyfillOptions?: SerialPolyfillOptions): Promise<T[]> {
588
+ polyfillOptions = {...kDefaultPolyfillOptions, ...polyfillOptions};
589
+
590
+ const devices = await this.usb.getDevices();
591
+ const ports: T[] = [];
592
+ devices.forEach((device) => {
593
+ try {
594
+ const port = this.createPort(device, polyfillOptions);
595
+ ports.push(port);
596
+ } catch (e) {
597
+ // Skip unrecognized port.
598
+ }
599
+ });
600
+ return ports;
601
+ }
602
+ }
603
+
604
+ /** default implementation of the global navigator.serial object */
605
+ export class Serial extends BaseSerial<SerialPort> {
606
+ /**
607
+ * @param {USBDevice} device
608
+ * @param {SerialPolyfillOptions} options
609
+ * @return {SerialPort} Default serial port implementation
610
+ */
611
+ protected createPort(device: USBDevice,
612
+ options?: SerialPolyfillOptions): SerialPort {
613
+ return new SerialPort(device, options);
614
+ }
615
+ }
616
+
617
+ /**
618
+ * Converts ArrayBufferLike to ArrayBuffer.
619
+ *
620
+ * @param {buffer} buffer
621
+ * @return {ArrayBuffer} original ArrayBuffer
622
+ * or new ArrayBuffer with contents of SharedArrayBuffer
623
+ */
624
+ function toArrayBuffer(buffer: ArrayBufferLike) {
625
+ if (buffer instanceof ArrayBuffer) {
626
+ // Return buffer when it's already an ArrayBuffer
627
+ return buffer;
628
+ }
629
+
630
+ // Create a new ArrayBuffer with the same byte length
631
+ const arrayBuffer = new ArrayBuffer(buffer.byteLength);
632
+
633
+ // Create views for both buffers
634
+ const sharedArrayBufferView = new Uint8Array(buffer);
635
+ const arrayBufferView = new Uint8Array(arrayBuffer);
636
+
637
+ // Copy the contents
638
+ arrayBufferView.set(sharedArrayBufferView);
639
+
640
+ return arrayBuffer;
641
+ }