@myshkouski/web-serial-polyfill 1.0.16

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 ADDED
@@ -0,0 +1,603 @@
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
+ 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,
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
+ * a function that opens the device and claims all interfaces needed to
282
+ * control and communicate to and from the serial device
283
+ * @param {SerialOptions} options Object containing serial options
284
+ * @return {Promise<void>} A promise that will resolve when device is ready
285
+ * for communication
286
+ */
287
+ public async open(options: SerialOptions): Promise<void> {
288
+ this.serialOptions_ = options;
289
+ this.validateOptions();
290
+
291
+ try {
292
+ await this.device_.open();
293
+ if (this.device_.configuration === null) {
294
+ await this.device_.selectConfiguration(1);
295
+ }
296
+
297
+ await this.device_.claimInterface(this.controlInterface_.interfaceNumber);
298
+ if (this.controlInterface_ !== this.transferInterface_) {
299
+ await this.device_.claimInterface(
300
+ this.transferInterface_.interfaceNumber);
301
+ }
302
+
303
+ await this.setLineCoding();
304
+ await this.setSignals({dataTerminalReady: true});
305
+ } catch (error) {
306
+ if (this.device_.opened) {
307
+ await this.device_.close();
308
+ }
309
+ throw new Error('Error setting up device: ' + error.toString());
310
+ }
311
+ }
312
+
313
+ /**
314
+ * Closes the port.
315
+ *
316
+ * @return {Promise<void>} A promise that will resolve when the port is
317
+ * closed.
318
+ */
319
+ public async close(): Promise<void> {
320
+ const promises = [];
321
+ if (this.readable_) {
322
+ promises.push(this.readable_.cancel());
323
+ }
324
+ if (this.writable_) {
325
+ promises.push(this.writable_.abort());
326
+ }
327
+ await Promise.all(promises);
328
+ this.readable_ = null;
329
+ this.writable_ = null;
330
+ if (this.device_.opened) {
331
+ await this.setSignals({dataTerminalReady: false, requestToSend: false});
332
+ if (this.transferInterface_.claimed) {
333
+ await this.device_.releaseInterface(this.transferInterface_.interfaceNumber);
334
+ }
335
+ await this.device_.close();
336
+ }
337
+ }
338
+
339
+ /**
340
+ * Forgets the port.
341
+ *
342
+ * @return {Promise<void>} A promise that will resolve when the port is
343
+ * forgotten.
344
+ */
345
+ public async forget(): Promise<void> {
346
+ return this.device_.forget();
347
+ }
348
+
349
+ /**
350
+ * A function that returns properties of the device.
351
+ * @return {SerialPortInfo} Device properties.
352
+ */
353
+ public getInfo(): SerialPortInfo {
354
+ return {
355
+ usbVendorId: this.device_.vendorId,
356
+ usbProductId: this.device_.productId,
357
+ };
358
+ }
359
+
360
+ /**
361
+ * A function used to change the serial settings of the device
362
+ * @param {object} options the object which carries serial settings data
363
+ * @return {Promise<void>} A promise that will resolve when the options are
364
+ * set
365
+ */
366
+ public reconfigure(options: SerialOptions): Promise<void> {
367
+ this.serialOptions_ = {...this.serialOptions_, ...options};
368
+ this.validateOptions();
369
+ return this.setLineCoding();
370
+ }
371
+
372
+ /**
373
+ * Sets control signal state for the port.
374
+ * @param {SerialOutputSignals} signals The signals to enable or disable.
375
+ * @return {Promise<void>} a promise that is resolved when the signal state
376
+ * has been changed.
377
+ */
378
+ public async setSignals(signals: SerialOutputSignals): Promise<void> {
379
+ this.outputSignals_ = {...this.outputSignals_, ...signals};
380
+
381
+ if (signals.dataTerminalReady !== undefined ||
382
+ signals.requestToSend !== undefined) {
383
+ // The Set_Control_Line_State command expects a bitmap containing the
384
+ // values of all output signals that should be enabled or disabled.
385
+ //
386
+ // Ref: USB CDC specification version 1.1 §6.2.14.
387
+ const value = (this.outputSignals_.dataTerminalReady ? 1 << 0 : 0) |
388
+ (this.outputSignals_.requestToSend ? 1 << 1 : 0);
389
+
390
+ await this.device_.controlTransferOut({
391
+ 'requestType': 'class',
392
+ 'recipient': 'interface',
393
+ 'request': kSetControlLineState,
394
+ 'value': value,
395
+ 'index': this.controlInterface_.interfaceNumber,
396
+ });
397
+ }
398
+
399
+ if (signals.break !== undefined) {
400
+ // The SendBreak command expects to be given a duration for how long the
401
+ // break signal should be asserted. Passing 0xFFFF enables the signal
402
+ // until 0x0000 is send.
403
+ //
404
+ // Ref: USB CDC specification version 1.1 §6.2.15.
405
+ const value = this.outputSignals_.break ? 0xFFFF : 0x0000;
406
+
407
+ await this.device_.controlTransferOut({
408
+ 'requestType': 'class',
409
+ 'recipient': 'interface',
410
+ 'request': kSendBreak,
411
+ 'value': value,
412
+ 'index': this.controlInterface_.interfaceNumber,
413
+ });
414
+ }
415
+ }
416
+
417
+ /**
418
+ * Checks the serial options for validity and throws an error if it is
419
+ * not valid
420
+ */
421
+ private validateOptions(): void {
422
+ if (!this.isValidBaudRate(this.serialOptions_.baudRate)) {
423
+ throw new RangeError('invalid Baud Rate ' + this.serialOptions_.baudRate);
424
+ }
425
+
426
+ if (!this.isValidDataBits(this.serialOptions_.dataBits)) {
427
+ throw new RangeError('invalid dataBits ' + this.serialOptions_.dataBits);
428
+ }
429
+
430
+ if (!this.isValidStopBits(this.serialOptions_.stopBits)) {
431
+ throw new RangeError('invalid stopBits ' + this.serialOptions_.stopBits);
432
+ }
433
+
434
+ if (!this.isValidParity(this.serialOptions_.parity)) {
435
+ throw new RangeError('invalid parity ' + this.serialOptions_.parity);
436
+ }
437
+ }
438
+
439
+ /**
440
+ * Checks the baud rate for validity
441
+ * @param {number} baudRate the baud rate to check
442
+ * @return {boolean} A boolean that reflects whether the baud rate is valid
443
+ */
444
+ private isValidBaudRate(baudRate: number): boolean {
445
+ return baudRate % 1 === 0;
446
+ }
447
+
448
+ /**
449
+ * Checks the data bits for validity
450
+ * @param {number} dataBits the data bits to check
451
+ * @return {boolean} A boolean that reflects whether the data bits setting is
452
+ * valid
453
+ */
454
+ private isValidDataBits(dataBits: number | undefined): boolean {
455
+ if (typeof dataBits === 'undefined') {
456
+ return true;
457
+ }
458
+ return kAcceptableDataBits.includes(dataBits);
459
+ }
460
+
461
+ /**
462
+ * Checks the stop bits for validity
463
+ * @param {number} stopBits the stop bits to check
464
+ * @return {boolean} A boolean that reflects whether the stop bits setting is
465
+ * valid
466
+ */
467
+ private isValidStopBits(stopBits: number | undefined): boolean {
468
+ if (typeof stopBits === 'undefined') {
469
+ return true;
470
+ }
471
+ return kAcceptableStopBits.includes(stopBits);
472
+ }
473
+
474
+ /**
475
+ * Checks the parity for validity
476
+ * @param {string} parity the parity to check
477
+ * @return {boolean} A boolean that reflects whether the parity is valid
478
+ */
479
+ private isValidParity(parity: ParityType | undefined): boolean {
480
+ if (typeof parity === 'undefined') {
481
+ return true;
482
+ }
483
+ return kAcceptableParity.includes(parity);
484
+ }
485
+
486
+ /**
487
+ * sends the options alog the control interface to set them on the device
488
+ * @return {Promise} a promise that will resolve when the options are set
489
+ */
490
+ private async setLineCoding(): Promise<void> {
491
+ // Ref: USB CDC specification version 1.1 §6.2.12.
492
+ const buffer = new ArrayBuffer(7);
493
+ const view = new DataView(buffer);
494
+ view.setUint32(0, this.serialOptions_.baudRate, true);
495
+ view.setUint8(
496
+ 4, kStopBitsIndexMapping.indexOf(
497
+ this.serialOptions_.stopBits ?? kDefaultStopBits));
498
+ view.setUint8(
499
+ 5, kParityIndexMapping.indexOf(
500
+ this.serialOptions_.parity ?? kDefaultParity));
501
+ view.setUint8(6, this.serialOptions_.dataBits ?? kDefaultDataBits);
502
+
503
+ const result = await this.device_.controlTransferOut({
504
+ 'requestType': 'class',
505
+ 'recipient': 'interface',
506
+ 'request': kSetLineCoding,
507
+ 'value': 0x00,
508
+ 'index': this.controlInterface_.interfaceNumber,
509
+ }, buffer);
510
+ if (result.status != 'ok') {
511
+ throw new DOMException('NetworkError', 'Failed to set line coding.');
512
+ }
513
+ }
514
+ }
515
+
516
+ /** generic implementation of navigator.serial object */
517
+ export abstract class BaseSerial<T extends SerialPort> {
518
+ /**
519
+ * @param {USB} usb Instance of navigator.usb object
520
+ */
521
+ constructor(
522
+ protected readonly usb: USB,
523
+ ) { }
524
+
525
+ protected abstract createPort(device: USBDevice,
526
+ options?: SerialPolyfillOptions): T
527
+
528
+ /**
529
+ * Requests permission to access a new port.
530
+ *
531
+ * @param {SerialPortRequestOptions} options
532
+ * @param {SerialPolyfillOptions} polyfillOptions
533
+ * @return {Promise<SerialPort>}
534
+ */
535
+ async requestPort(
536
+ options?: SerialPortRequestOptions,
537
+ polyfillOptions?: SerialPolyfillOptions): Promise<T> {
538
+ polyfillOptions = {...kDefaultPolyfillOptions, ...polyfillOptions};
539
+
540
+ const usbFilters: USBDeviceFilter[] = [];
541
+ if (options && options.filters) {
542
+ for (const filter of options.filters) {
543
+ const usbFilter: USBDeviceFilter = {
544
+ classCode: polyfillOptions.usbControlInterfaceClass,
545
+ };
546
+ if (filter.usbVendorId !== undefined) {
547
+ usbFilter.vendorId = filter.usbVendorId;
548
+ }
549
+ if (filter.usbProductId !== undefined) {
550
+ usbFilter.productId = filter.usbProductId;
551
+ }
552
+ usbFilters.push(usbFilter);
553
+ }
554
+ }
555
+
556
+ if (usbFilters.length === 0) {
557
+ usbFilters.push({
558
+ classCode: polyfillOptions.usbControlInterfaceClass,
559
+ });
560
+ }
561
+
562
+ const device = await this.usb.requestDevice({'filters': usbFilters});
563
+ const port = this.createPort(device, polyfillOptions);
564
+ return port;
565
+ }
566
+
567
+ /**
568
+ * Get the set of currently available ports.
569
+ *
570
+ * @param {SerialPolyfillOptions} polyfillOptions Polyfill configuration that
571
+ * should be applied to these ports.
572
+ * @return {Promise<SerialPort[]>} a promise that is resolved with a list of
573
+ * ports.
574
+ */
575
+ async getPorts(polyfillOptions?: SerialPolyfillOptions): Promise<T[]> {
576
+ polyfillOptions = {...kDefaultPolyfillOptions, ...polyfillOptions};
577
+
578
+ const devices = await this.usb.getDevices();
579
+ const ports: T[] = [];
580
+ devices.forEach((device) => {
581
+ try {
582
+ const port = this.createPort(device, polyfillOptions);
583
+ ports.push(port);
584
+ } catch (e) {
585
+ // Skip unrecognized port.
586
+ }
587
+ });
588
+ return ports;
589
+ }
590
+ }
591
+
592
+ /** default implementation of the global navigator.serial object */
593
+ export class Serial extends BaseSerial<SerialPort> {
594
+ /**
595
+ * @param {USBDevice} device
596
+ * @param {SerialPolyfillOptions} options
597
+ * @return {SerialPort} Default serial port implementation
598
+ */
599
+ protected createPort(device: USBDevice,
600
+ options?: SerialPolyfillOptions): SerialPort {
601
+ return new SerialPort(device, options);
602
+ }
603
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,12 @@
1
+ {
2
+ "compilerOptions": {
3
+ "module": "es2015",
4
+ "lib": ["es2017"],
5
+ "outDir": "./dist/",
6
+ "sourceMap": true,
7
+ "noImplicitAny": true,
8
+ "strictNullChecks": true,
9
+ "target": "es2017",
10
+ "declaration": true
11
+ }
12
+ }