webserial-core 1.0.2 → 1.0.3
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/dist/webserial-core.js +136 -115
- package/dist/webserial-core.umd.cjs +2 -2
- package/package.json +4 -4
package/dist/webserial-core.js
CHANGED
|
@@ -1,34 +1,34 @@
|
|
|
1
1
|
var N = Object.defineProperty;
|
|
2
|
-
var
|
|
3
|
-
throw TypeError(
|
|
2
|
+
var m = (s) => {
|
|
3
|
+
throw TypeError(s);
|
|
4
4
|
};
|
|
5
|
-
var O = (
|
|
6
|
-
var d = (
|
|
7
|
-
var
|
|
8
|
-
var l = (
|
|
5
|
+
var O = (s, i, e) => i in s ? N(s, i, { enumerable: !0, configurable: !0, writable: !0, value: e }) : s[i] = e;
|
|
6
|
+
var d = (s, i, e) => O(s, typeof i != "symbol" ? i + "" : i, e), H = (s, i, e) => i.has(s) || m("Cannot " + e);
|
|
7
|
+
var v = (s, i, e) => i.has(s) ? m("Cannot add the same private member more than once") : i instanceof WeakSet ? i.add(s) : i.set(s, e);
|
|
8
|
+
var l = (s, i, e) => (H(s, i, "access private method"), e);
|
|
9
9
|
const _ = [];
|
|
10
|
-
for (let
|
|
11
|
-
_.push((
|
|
12
|
-
function j(
|
|
13
|
-
return (_[
|
|
10
|
+
for (let s = 0; s < 256; ++s)
|
|
11
|
+
_.push((s + 256).toString(16).slice(1));
|
|
12
|
+
function j(s, i = 0) {
|
|
13
|
+
return (_[s[i + 0]] + _[s[i + 1]] + _[s[i + 2]] + _[s[i + 3]] + "-" + _[s[i + 4]] + _[s[i + 5]] + "-" + _[s[i + 6]] + _[s[i + 7]] + "-" + _[s[i + 8]] + _[s[i + 9]] + "-" + _[s[i + 10]] + _[s[i + 11]] + _[s[i + 12]] + _[s[i + 13]] + _[s[i + 14]] + _[s[i + 15]]).toLowerCase();
|
|
14
14
|
}
|
|
15
|
-
let
|
|
15
|
+
let g;
|
|
16
16
|
const B = new Uint8Array(16);
|
|
17
17
|
function F() {
|
|
18
|
-
if (!
|
|
18
|
+
if (!g) {
|
|
19
19
|
if (typeof crypto > "u" || !crypto.getRandomValues)
|
|
20
20
|
throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");
|
|
21
|
-
|
|
21
|
+
g = crypto.getRandomValues.bind(crypto);
|
|
22
22
|
}
|
|
23
|
-
return
|
|
23
|
+
return g(B);
|
|
24
24
|
}
|
|
25
|
-
const
|
|
26
|
-
function
|
|
25
|
+
const V = typeof crypto < "u" && crypto.randomUUID && crypto.randomUUID.bind(crypto), C = { randomUUID: V };
|
|
26
|
+
function W(s, i, e) {
|
|
27
27
|
var n;
|
|
28
|
-
if (
|
|
29
|
-
return
|
|
30
|
-
|
|
31
|
-
const t =
|
|
28
|
+
if (C.randomUUID && !s)
|
|
29
|
+
return C.randomUUID();
|
|
30
|
+
s = s || {};
|
|
31
|
+
const t = s.random ?? ((n = s.rng) == null ? void 0 : n.call(s)) ?? F();
|
|
32
32
|
if (t.length < 16)
|
|
33
33
|
throw new Error("Random bytes length must be >= 16");
|
|
34
34
|
return t[6] = t[6] & 15 | 64, t[8] = t[8] & 63 | 128, j(t);
|
|
@@ -38,7 +38,7 @@ class x extends CustomEvent {
|
|
|
38
38
|
super(i, e);
|
|
39
39
|
}
|
|
40
40
|
}
|
|
41
|
-
class
|
|
41
|
+
class A extends EventTarget {
|
|
42
42
|
constructor() {
|
|
43
43
|
super(...arguments);
|
|
44
44
|
d(this, "__listeners__", {
|
|
@@ -51,9 +51,9 @@ class C extends EventTarget {
|
|
|
51
51
|
this.dispatchEvent(n), this.__debug__ && this.dispatchEvent(new x("debug", { detail: { type: e, data: t } }));
|
|
52
52
|
}
|
|
53
53
|
dispatchAsync(e, t = null, n = 100) {
|
|
54
|
-
const
|
|
54
|
+
const a = this;
|
|
55
55
|
setTimeout(() => {
|
|
56
|
-
|
|
56
|
+
a.dispatch(e, t);
|
|
57
57
|
}, n);
|
|
58
58
|
}
|
|
59
59
|
on(e, t) {
|
|
@@ -72,7 +72,15 @@ class C extends EventTarget {
|
|
|
72
72
|
}));
|
|
73
73
|
}
|
|
74
74
|
}
|
|
75
|
-
const o = class o extends
|
|
75
|
+
const o = class o extends A {
|
|
76
|
+
constructor() {
|
|
77
|
+
super(), ["change"].forEach((e) => {
|
|
78
|
+
this.serialRegisterAvailableListener(e);
|
|
79
|
+
});
|
|
80
|
+
}
|
|
81
|
+
static $dispatchChange(i = null) {
|
|
82
|
+
i && i.$checkAndDispatchConnection(), o.instance.dispatch("change", { devices: o.devices, dispatcher: i });
|
|
83
|
+
}
|
|
76
84
|
static typeError(i) {
|
|
77
85
|
const e = new Error();
|
|
78
86
|
throw e.message = `Type ${i} is not supported`, e.name = "DeviceTypeError", e;
|
|
@@ -84,9 +92,9 @@ const o = class o extends C {
|
|
|
84
92
|
const e = i.typeDevice;
|
|
85
93
|
typeof o.devices[e] > "u" && (o.devices[e] = {});
|
|
86
94
|
const t = i.uuid;
|
|
87
|
-
if (typeof o.devices[e] > "u" && o.typeError(e),
|
|
95
|
+
if (typeof o.devices[e] > "u" && o.typeError(e), o.devices[e][t])
|
|
88
96
|
throw new Error(`Device with id ${t} already exists`);
|
|
89
|
-
return o.devices[e][t] = i,
|
|
97
|
+
return o.devices[e][t] = i, o.$dispatchChange(i), Object.keys(o.devices[e]).indexOf(t);
|
|
90
98
|
}
|
|
91
99
|
static get(i, e) {
|
|
92
100
|
return typeof o.devices[i] > "u" && (o.devices[i] = {}), typeof o.devices[i] > "u" && o.typeError(i), o.devices[i][e];
|
|
@@ -107,15 +115,15 @@ const o = class o extends C {
|
|
|
107
115
|
d(o, "instance"), d(o, "devices", {});
|
|
108
116
|
let c = o;
|
|
109
117
|
c.instance || (c.instance = new c());
|
|
110
|
-
function S(
|
|
118
|
+
function S(s = 100) {
|
|
111
119
|
return new Promise(
|
|
112
|
-
(i) => setTimeout(() => i(),
|
|
120
|
+
(i) => setTimeout(() => i(), s)
|
|
113
121
|
);
|
|
114
122
|
}
|
|
115
|
-
function
|
|
123
|
+
function Q() {
|
|
116
124
|
return "serial" in navigator;
|
|
117
125
|
}
|
|
118
|
-
const
|
|
126
|
+
const b = {
|
|
119
127
|
baudRate: 9600,
|
|
120
128
|
dataBits: 8,
|
|
121
129
|
stopBits: 1,
|
|
@@ -123,21 +131,21 @@ const f = {
|
|
|
123
131
|
bufferSize: 32768,
|
|
124
132
|
flowControl: "none"
|
|
125
133
|
};
|
|
126
|
-
var
|
|
127
|
-
class
|
|
134
|
+
var r, p, f, y, u, E, T, U, k, D, L, P, I, q, $, R, M;
|
|
135
|
+
class G extends A {
|
|
128
136
|
constructor({
|
|
129
137
|
filters: e = null,
|
|
130
|
-
config_port: t =
|
|
138
|
+
config_port: t = b,
|
|
131
139
|
no_device: n = 1,
|
|
132
|
-
device_listen_on_channel:
|
|
140
|
+
device_listen_on_channel: a = 1
|
|
133
141
|
} = {
|
|
134
142
|
filters: null,
|
|
135
|
-
config_port:
|
|
143
|
+
config_port: b,
|
|
136
144
|
no_device: 1,
|
|
137
145
|
device_listen_on_channel: 1
|
|
138
146
|
}) {
|
|
139
147
|
super();
|
|
140
|
-
|
|
148
|
+
v(this, r);
|
|
141
149
|
d(this, "__internal__", {
|
|
142
150
|
auto_response: !1,
|
|
143
151
|
device_number: 1,
|
|
@@ -167,12 +175,13 @@ class z extends C {
|
|
|
167
175
|
delay_first_connection: 200,
|
|
168
176
|
bytes_connection: null,
|
|
169
177
|
filters: [],
|
|
170
|
-
config_port:
|
|
171
|
-
queue: []
|
|
178
|
+
config_port: b,
|
|
179
|
+
queue: [],
|
|
180
|
+
auto_response: ["DD", "DD"]
|
|
172
181
|
},
|
|
173
182
|
device: {
|
|
174
183
|
type: "unknown",
|
|
175
|
-
id:
|
|
184
|
+
id: W(),
|
|
176
185
|
listen_on_port: null
|
|
177
186
|
},
|
|
178
187
|
time: {
|
|
@@ -188,7 +197,7 @@ class z extends C {
|
|
|
188
197
|
});
|
|
189
198
|
if (!("serial" in navigator))
|
|
190
199
|
throw new Error("Web Serial not supported");
|
|
191
|
-
e && (this.serialFilters = e), t && (this.serialConfigPort = t), n && l(this,
|
|
200
|
+
e && (this.serialFilters = e), t && (this.serialConfigPort = t), n && l(this, r, R).call(this, n), a && ["number", "string"].includes(typeof a) && (this.listenOnChannel = a), l(this, r, P).call(this), l(this, r, I).call(this);
|
|
192
201
|
}
|
|
193
202
|
set listenOnChannel(e) {
|
|
194
203
|
if (typeof e == "string" && (e = parseInt(e)), isNaN(e) || e < 1 || e > 255)
|
|
@@ -214,10 +223,12 @@ class z extends C {
|
|
|
214
223
|
return this.__internal__.serial.config_port;
|
|
215
224
|
}
|
|
216
225
|
get isConnected() {
|
|
217
|
-
|
|
226
|
+
const e = this.__internal__.serial.connected, t = l(this, r, p).call(this, this.__internal__.serial.port);
|
|
227
|
+
return e && !t && l(this, r, f).call(this, { error: "Port is closed, not readable or writable." }), this.__internal__.serial.connected = t, this.__internal__.serial.connected;
|
|
218
228
|
}
|
|
219
229
|
get isDisconnected() {
|
|
220
|
-
|
|
230
|
+
const e = this.__internal__.serial.connected, t = l(this, r, p).call(this, this.__internal__.serial.port);
|
|
231
|
+
return !e && t && (this.dispatch("serial:connected"), c.$dispatchChange(this)), this.__internal__.serial.connected = t, !this.__internal__.serial.connected;
|
|
221
232
|
}
|
|
222
233
|
get deviceNumber() {
|
|
223
234
|
return this.__internal__.device_number;
|
|
@@ -239,11 +250,11 @@ class z extends C {
|
|
|
239
250
|
});
|
|
240
251
|
}
|
|
241
252
|
async disconnect(e = null) {
|
|
242
|
-
await this.serialDisconnect(), this
|
|
253
|
+
await this.serialDisconnect(), l(this, r, f).call(this, e);
|
|
243
254
|
}
|
|
244
255
|
async connect() {
|
|
245
256
|
return new Promise((e, t) => {
|
|
246
|
-
|
|
257
|
+
Q() || t("Web Serial not supported"), setTimeout(async () => {
|
|
247
258
|
await S(499), await this.serialConnect(), this.isConnected ? e(`${this.typeDevice} device ${this.deviceNumber} connected`) : t(`${this.typeDevice} device ${this.deviceNumber} not connected`);
|
|
248
259
|
}, 1);
|
|
249
260
|
});
|
|
@@ -251,7 +262,7 @@ class z extends C {
|
|
|
251
262
|
async serialDisconnect() {
|
|
252
263
|
try {
|
|
253
264
|
const e = this.__internal__.serial.reader, t = this.__internal__.serial.output_stream;
|
|
254
|
-
e && (await e.cancel().catch((
|
|
265
|
+
e && (await e.cancel().catch((a) => this.serialErrors(a)), await this.__internal__.serial.input_done), t && (await t.getWriter().close(), await this.__internal__.serial.output_done), this.__internal__.serial.connected && this.__internal__.serial && this.__internal__.serial.port && await this.__internal__.serial.port.close();
|
|
255
266
|
} catch (e) {
|
|
256
267
|
this.serialErrors(e);
|
|
257
268
|
} finally {
|
|
@@ -288,12 +299,14 @@ class z extends C {
|
|
|
288
299
|
case t.includes("must be handling a user gesture to show a permission request"):
|
|
289
300
|
case t.includes("the port is closed."):
|
|
290
301
|
case t.includes("the port is closed or is not writable"):
|
|
302
|
+
case t.includes("the port is closed or is not readable"):
|
|
303
|
+
case t.includes("the port is closed or is not readable/writable"):
|
|
291
304
|
case t.includes("select another port please"):
|
|
292
305
|
case t.includes("no port selected by the user"):
|
|
293
306
|
case t.includes(
|
|
294
307
|
"this readable stream reader has been released and cannot be used to cancel its previous owner stream"
|
|
295
308
|
):
|
|
296
|
-
this.dispatch("serial:need-permission", {}), c
|
|
309
|
+
this.dispatch("serial:need-permission", {}), c.$dispatchChange(this);
|
|
297
310
|
break;
|
|
298
311
|
case t.includes("the port is already open."):
|
|
299
312
|
case t.includes("failed to open serial port"):
|
|
@@ -316,7 +329,7 @@ class z extends C {
|
|
|
316
329
|
case t.includes("the port is already closed."):
|
|
317
330
|
break;
|
|
318
331
|
case t.includes("the device has been lost"):
|
|
319
|
-
this.dispatch("serial:lost", {}), c
|
|
332
|
+
this.dispatch("serial:lost", {}), c.$dispatchChange(this);
|
|
320
333
|
break;
|
|
321
334
|
case t.includes("navigator.serial is undefined"):
|
|
322
335
|
this.dispatch("serial:unsupported", {});
|
|
@@ -330,13 +343,13 @@ class z extends C {
|
|
|
330
343
|
async serialConnect() {
|
|
331
344
|
try {
|
|
332
345
|
this.dispatch("serial:connecting", {});
|
|
333
|
-
const e = await l(this,
|
|
346
|
+
const e = await l(this, r, E).call(this);
|
|
334
347
|
if (e.length > 0)
|
|
335
348
|
await this.serialPortsSaved(e);
|
|
336
349
|
else {
|
|
337
|
-
const
|
|
350
|
+
const a = this.serialFilters;
|
|
338
351
|
this.__internal__.serial.port = await navigator.serial.requestPort({
|
|
339
|
-
filters:
|
|
352
|
+
filters: a
|
|
340
353
|
});
|
|
341
354
|
}
|
|
342
355
|
const t = this.__internal__.serial.port;
|
|
@@ -344,22 +357,22 @@ class z extends C {
|
|
|
344
357
|
throw new Error("No port selected by the user");
|
|
345
358
|
await t.open(this.serialConfigPort);
|
|
346
359
|
const n = this;
|
|
347
|
-
t.onconnect = (
|
|
348
|
-
n.dispatch("serial:connected",
|
|
360
|
+
t.onconnect = (a) => {
|
|
361
|
+
console.log(a), n.dispatch("serial:connected", a), c.$dispatchChange(this), n.__internal__.serial.queue.length > 0 && n.dispatch("internal:queue", {});
|
|
349
362
|
}, t.ondisconnect = async () => {
|
|
350
363
|
await n.disconnect();
|
|
351
364
|
}, await S(this.__internal__.serial.delay_first_connection), this.__internal__.timeout.until_response = setTimeout(async () => {
|
|
352
365
|
await n.timeout(n.__internal__.serial.bytes_connection ?? [], "connection:start");
|
|
353
|
-
}, this.__internal__.time.response_connection), this.__internal__.serial.last_action = "connect", await l(this,
|
|
366
|
+
}, this.__internal__.time.response_connection), this.__internal__.serial.last_action = "connect", await l(this, r, y).call(this, this.__internal__.serial.bytes_connection ?? []), this.dispatch("serial:sent", {
|
|
354
367
|
action: "connect",
|
|
355
368
|
bytes: this.__internal__.serial.bytes_connection
|
|
356
|
-
}), this.__internal__.auto_response && l(this,
|
|
369
|
+
}), this.__internal__.auto_response && l(this, r, u).call(this, this.__internal__.serial.auto_response, null), await l(this, r, D).call(this);
|
|
357
370
|
} catch (e) {
|
|
358
371
|
this.serialErrors(e);
|
|
359
372
|
}
|
|
360
373
|
}
|
|
361
374
|
async serialForget() {
|
|
362
|
-
return await l(this,
|
|
375
|
+
return await l(this, r, L).call(this);
|
|
363
376
|
}
|
|
364
377
|
decToHex(e) {
|
|
365
378
|
return typeof e == "string" && (e = parseInt(e, 10)), e.toString(16);
|
|
@@ -372,8 +385,8 @@ class z extends C {
|
|
|
372
385
|
}
|
|
373
386
|
add0x(e) {
|
|
374
387
|
const t = [];
|
|
375
|
-
return e.forEach((n,
|
|
376
|
-
t[
|
|
388
|
+
return e.forEach((n, a) => {
|
|
389
|
+
t[a] = "0x" + n;
|
|
377
390
|
}), t;
|
|
378
391
|
}
|
|
379
392
|
bytesToHex(e) {
|
|
@@ -416,7 +429,7 @@ class z extends C {
|
|
|
416
429
|
});
|
|
417
430
|
}
|
|
418
431
|
softReload() {
|
|
419
|
-
l(this,
|
|
432
|
+
l(this, r, M).call(this), this.dispatch("serial:soft-reload", {});
|
|
420
433
|
}
|
|
421
434
|
async sendConnect() {
|
|
422
435
|
if (!this.__internal__.serial.bytes_connection)
|
|
@@ -444,7 +457,7 @@ class z extends C {
|
|
|
444
457
|
parseStringToBytes(e = "", t = `
|
|
445
458
|
`) {
|
|
446
459
|
const n = this.parseStringToTextEncoder(e, t);
|
|
447
|
-
return Array.from(n).map((
|
|
460
|
+
return Array.from(n).map((a) => a.toString(16));
|
|
448
461
|
}
|
|
449
462
|
parseUint8ToHex(e) {
|
|
450
463
|
return Array.from(e).map((t) => t.toString(16));
|
|
@@ -455,95 +468,103 @@ class z extends C {
|
|
|
455
468
|
stringArrayToUint8Array(e) {
|
|
456
469
|
const t = [];
|
|
457
470
|
return e.forEach((n) => {
|
|
458
|
-
const
|
|
459
|
-
t.push(parseInt(
|
|
471
|
+
const a = n.replace("0x", "");
|
|
472
|
+
t.push(parseInt(a, 16));
|
|
460
473
|
}), new Uint8Array(t);
|
|
461
474
|
}
|
|
462
475
|
parseUint8ArrayToString(e) {
|
|
463
476
|
const t = this.stringArrayToUint8Array(e);
|
|
464
477
|
e = this.parseUint8ToHex(t);
|
|
465
|
-
const n = e.map((
|
|
478
|
+
const n = e.map((a) => parseInt(a, 16));
|
|
466
479
|
return String.fromCharCode(...n).replace(/[\n\r]+/g, "");
|
|
467
480
|
}
|
|
468
481
|
hexToAscii(e) {
|
|
469
482
|
const t = e.toString();
|
|
470
483
|
let n = "";
|
|
471
|
-
for (let
|
|
472
|
-
n += String.fromCharCode(parseInt(t.substring(
|
|
484
|
+
for (let a = 0; a < t.length; a += 2)
|
|
485
|
+
n += String.fromCharCode(parseInt(t.substring(a, 2), 16));
|
|
473
486
|
return n;
|
|
474
487
|
}
|
|
475
488
|
asciiToHex(e) {
|
|
476
489
|
const t = [];
|
|
477
|
-
for (let n = 0,
|
|
478
|
-
const
|
|
479
|
-
t.push(
|
|
490
|
+
for (let n = 0, a = e.length; n < a; n++) {
|
|
491
|
+
const h = Number(e.charCodeAt(n)).toString(16);
|
|
492
|
+
t.push(h);
|
|
480
493
|
}
|
|
481
494
|
return t.join("");
|
|
482
495
|
}
|
|
496
|
+
$checkAndDispatchConnection() {
|
|
497
|
+
return this.isConnected;
|
|
498
|
+
}
|
|
483
499
|
}
|
|
484
|
-
|
|
500
|
+
r = new WeakSet(), p = function(e) {
|
|
485
501
|
return !!(e && e.readable && e.writable);
|
|
502
|
+
}, f = function(e = null) {
|
|
503
|
+
this.__internal__.serial.connected = !1, this.__internal__.aux_port_connector = 0, this.dispatch("serial:disconnected", e), c.$dispatchChange(this);
|
|
486
504
|
}, y = async function(e) {
|
|
487
505
|
const t = this.__internal__.serial.port;
|
|
488
|
-
if (!t || !t.readable || !t.writable)
|
|
489
|
-
throw new Error("The port is closed or is not writable");
|
|
490
|
-
const n = this.stringArrayToUint8Array(e)
|
|
491
|
-
|
|
492
|
-
|
|
506
|
+
if (!t || t && (!t.readable || !t.writable))
|
|
507
|
+
throw l(this, r, f).call(this, { error: "Port is closed, not readable or writable." }), new Error("The port is closed or is not readable/writable");
|
|
508
|
+
const n = this.stringArrayToUint8Array(e);
|
|
509
|
+
if (t.writable === null) return;
|
|
510
|
+
const a = t.writable.getWriter();
|
|
511
|
+
await a.write(n), a.releaseLock();
|
|
512
|
+
}, u = function(e = [], t = null) {
|
|
493
513
|
if (e && e.length > 0) {
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
514
|
+
const n = this.__internal__.serial.connected;
|
|
515
|
+
this.__internal__.serial.connected = l(this, r, p).call(this, this.__internal__.serial.port), !n && this.__internal__.serial.connected && (this.dispatch("serial:connected"), c.$dispatchChange(this)), this.__internal__.interval.reconnection && (clearInterval(this.__internal__.interval.reconnection), this.__internal__.interval.reconnection = 0), this.__internal__.timeout.until_response && (clearTimeout(this.__internal__.timeout.until_response), this.__internal__.timeout.until_response = 0);
|
|
516
|
+
const a = [];
|
|
517
|
+
for (const h in e)
|
|
518
|
+
a.push(e[h].toString().padStart(2, "0").toLowerCase());
|
|
498
519
|
if (this.__internal__.serial.response.as === "hex")
|
|
499
|
-
this.serialMessage(
|
|
520
|
+
this.serialMessage(a);
|
|
500
521
|
else if (this.__internal__.serial.response.as === "uint8")
|
|
501
|
-
this.serialMessage(this.parseHexToUint8(this.add0x(
|
|
522
|
+
this.serialMessage(this.parseHexToUint8(this.add0x(a)));
|
|
502
523
|
else if (this.__internal__.serial.response.as === "string")
|
|
503
|
-
this.serialMessage(this.parseUint8ArrayToString(this.add0x(
|
|
524
|
+
this.serialMessage(this.parseUint8ArrayToString(this.add0x(a)));
|
|
504
525
|
else {
|
|
505
|
-
const
|
|
506
|
-
this.parseUint8ArrayToString(this.add0x(
|
|
526
|
+
const h = this.stringToArrayBuffer(
|
|
527
|
+
this.parseUint8ArrayToString(this.add0x(a))
|
|
507
528
|
);
|
|
508
|
-
this.serialMessage(
|
|
529
|
+
this.serialMessage(h);
|
|
509
530
|
}
|
|
510
531
|
} else
|
|
511
532
|
this.serialCorruptMessage(e, t);
|
|
512
533
|
this.__internal__.serial.queue.length !== 0 && this.dispatch("internal:queue", {});
|
|
513
534
|
}, E = async function() {
|
|
514
535
|
const e = this.serialFilters, t = await navigator.serial.getPorts({ filters: e });
|
|
515
|
-
return e.length === 0 ? t : t.filter((
|
|
516
|
-
const
|
|
517
|
-
return e.some((
|
|
518
|
-
}).filter((
|
|
519
|
-
},
|
|
536
|
+
return e.length === 0 ? t : t.filter((a) => {
|
|
537
|
+
const h = a.getInfo();
|
|
538
|
+
return e.some((w) => h.usbProductId === w.usbProductId && h.usbVendorId === w.usbVendorId);
|
|
539
|
+
}).filter((a) => !l(this, r, p).call(this, a));
|
|
540
|
+
}, T = function(e) {
|
|
520
541
|
if (e) {
|
|
521
542
|
const t = this.__internal__.serial.response.buffer, n = new Uint8Array(t.length + e.byteLength);
|
|
522
543
|
n.set(t, 0), n.set(new Uint8Array(e), t.length), this.__internal__.serial.response.buffer = n;
|
|
523
544
|
}
|
|
524
|
-
},
|
|
545
|
+
}, U = async function() {
|
|
525
546
|
this.__internal__.serial.time_until_send_bytes && (clearTimeout(this.__internal__.serial.time_until_send_bytes), this.__internal__.serial.time_until_send_bytes = 0), this.__internal__.serial.time_until_send_bytes = setTimeout(() => {
|
|
526
547
|
const e = [];
|
|
527
548
|
for (const t in this.__internal__.serial.response.buffer)
|
|
528
549
|
e.push(this.__internal__.serial.response.buffer[t].toString(16));
|
|
529
|
-
this.__internal__.serial.response.buffer && l(this,
|
|
550
|
+
this.__internal__.serial.response.buffer && l(this, r, u).call(this, e), this.__internal__.serial.response.buffer = new Uint8Array(0);
|
|
530
551
|
}, 400);
|
|
531
|
-
},
|
|
552
|
+
}, k = async function() {
|
|
532
553
|
if (this.__internal__.serial.response.length !== null) {
|
|
533
554
|
if (this.__internal__.serial.response.length === this.__internal__.serial.response.buffer.length) {
|
|
534
555
|
const e = [];
|
|
535
556
|
for (const t in this.__internal__.serial.response.buffer)
|
|
536
557
|
e.push(this.__internal__.serial.response.buffer[t].toString(16));
|
|
537
|
-
l(this,
|
|
558
|
+
l(this, r, u).call(this, e), this.__internal__.serial.response.buffer = new Uint8Array(0);
|
|
538
559
|
} else if (this.__internal__.serial.response.length < this.__internal__.serial.response.buffer.length) {
|
|
539
560
|
let e = new Uint8Array(0);
|
|
540
561
|
for (let n = 0; n < this.__internal__.serial.response.length; n++)
|
|
541
562
|
e[n] = this.__internal__.serial.response.buffer[n];
|
|
542
563
|
if (e.length === this.__internal__.serial.response.length) {
|
|
543
564
|
const n = [];
|
|
544
|
-
for (const
|
|
545
|
-
n.push(e[
|
|
546
|
-
l(this,
|
|
565
|
+
for (const a in e)
|
|
566
|
+
n.push(e[a].toString(16));
|
|
567
|
+
l(this, r, u).call(this, n), this.__internal__.serial.response.buffer = new Uint8Array(0);
|
|
547
568
|
return;
|
|
548
569
|
}
|
|
549
570
|
e = new Uint8Array(0);
|
|
@@ -553,14 +574,14 @@ a = new WeakSet(), g = function(e) {
|
|
|
553
574
|
e[n - this.__internal__.serial.response.length] = this.__internal__.serial.response.buffer[n];
|
|
554
575
|
if (e.length === this.__internal__.serial.response.length) {
|
|
555
576
|
const n = [];
|
|
556
|
-
for (const
|
|
557
|
-
n.push(e[
|
|
558
|
-
l(this,
|
|
577
|
+
for (const a in e)
|
|
578
|
+
n.push(e[a].toString(16));
|
|
579
|
+
l(this, r, u).call(this, n), this.__internal__.serial.response.buffer = new Uint8Array(0);
|
|
559
580
|
}
|
|
560
581
|
}
|
|
561
582
|
}
|
|
562
583
|
}
|
|
563
|
-
},
|
|
584
|
+
}, D = async function() {
|
|
564
585
|
const e = this.__internal__.serial.port;
|
|
565
586
|
if (!e || !e.readable) throw new Error("Port is not readable");
|
|
566
587
|
for (; e.readable && this.__internal__.serial.keep_reading; ) {
|
|
@@ -569,12 +590,12 @@ a = new WeakSet(), g = function(e) {
|
|
|
569
590
|
try {
|
|
570
591
|
let n = !0;
|
|
571
592
|
for (; n; ) {
|
|
572
|
-
const { value:
|
|
573
|
-
if (
|
|
593
|
+
const { value: a, done: h } = await t.read();
|
|
594
|
+
if (h) {
|
|
574
595
|
t.releaseLock(), this.__internal__.serial.keep_reading = !1, n = !1;
|
|
575
596
|
break;
|
|
576
597
|
}
|
|
577
|
-
l(this,
|
|
598
|
+
l(this, r, T).call(this, a), this.__internal__.serial.response.length === null ? await l(this, r, U).call(this) : await l(this, r, k).call(this);
|
|
578
599
|
}
|
|
579
600
|
} catch (n) {
|
|
580
601
|
this.serialErrors(n);
|
|
@@ -583,9 +604,9 @@ a = new WeakSet(), g = function(e) {
|
|
|
583
604
|
}
|
|
584
605
|
}
|
|
585
606
|
this.__internal__.serial.keep_reading = !0, this.__internal__.serial.port && await this.__internal__.serial.port.close();
|
|
586
|
-
},
|
|
607
|
+
}, L = async function() {
|
|
587
608
|
return typeof window > "u" ? !1 : "serial" in navigator && "forget" in SerialPort.prototype && this.__internal__.serial.port ? (await this.__internal__.serial.port.forget(), !0) : !1;
|
|
588
|
-
},
|
|
609
|
+
}, P = function() {
|
|
589
610
|
[
|
|
590
611
|
"serial:connected",
|
|
591
612
|
"serial:connecting",
|
|
@@ -604,21 +625,21 @@ a = new WeakSet(), g = function(e) {
|
|
|
604
625
|
].forEach((t) => {
|
|
605
626
|
this.serialRegisterAvailableListener(t);
|
|
606
627
|
});
|
|
607
|
-
},
|
|
628
|
+
}, I = function() {
|
|
608
629
|
const e = this;
|
|
609
630
|
this.on("internal:queue", async () => {
|
|
610
631
|
var t;
|
|
611
|
-
await l(t = e,
|
|
612
|
-
}), l(this,
|
|
613
|
-
},
|
|
632
|
+
await l(t = e, r, $).call(t);
|
|
633
|
+
}), l(this, r, q).call(this);
|
|
634
|
+
}, q = function() {
|
|
614
635
|
const e = this;
|
|
615
636
|
navigator.serial.addEventListener("connect", async () => {
|
|
616
637
|
e.isDisconnected && await e.serialConnect().catch(() => {
|
|
617
638
|
});
|
|
618
639
|
});
|
|
619
|
-
},
|
|
620
|
-
if (!l(this,
|
|
621
|
-
this
|
|
640
|
+
}, $ = async function() {
|
|
641
|
+
if (!l(this, r, p).call(this, this.__internal__.serial.port)) {
|
|
642
|
+
l(this, r, f).call(this, { error: "Port is closed, not readable or writable." }), await this.serialConnect();
|
|
622
643
|
return;
|
|
623
644
|
}
|
|
624
645
|
if (this.__internal__.timeout.until_response || this.__internal__.serial.queue.length === 0) return;
|
|
@@ -626,10 +647,10 @@ a = new WeakSet(), g = function(e) {
|
|
|
626
647
|
let t = this.__internal__.time.response_general;
|
|
627
648
|
e.action === "connect" && (t = this.__internal__.time.response_connection), this.__internal__.timeout.until_response = setTimeout(async () => {
|
|
628
649
|
await this.timeout(e.bytes, e.action);
|
|
629
|
-
}, t), this.__internal__.serial.last_action = e.action ?? "unknown", await l(this,
|
|
650
|
+
}, t), this.__internal__.serial.last_action = e.action ?? "unknown", await l(this, r, y).call(this, e.bytes), this.dispatch("serial:sent", {
|
|
630
651
|
action: e.action,
|
|
631
652
|
bytes: e.bytes
|
|
632
|
-
}), this.__internal__.auto_response && l(this,
|
|
653
|
+
}), this.__internal__.auto_response && l(this, r, u).call(this, this.__internal__.serial.auto_response, null);
|
|
633
654
|
const n = [...this.__internal__.serial.queue];
|
|
634
655
|
this.__internal__.serial.queue = n.splice(1);
|
|
635
656
|
}, R = function(e = 1) {
|
|
@@ -643,7 +664,7 @@ a = new WeakSet(), g = function(e) {
|
|
|
643
664
|
};
|
|
644
665
|
};
|
|
645
666
|
export {
|
|
646
|
-
|
|
667
|
+
G as Core,
|
|
647
668
|
c as Devices,
|
|
648
|
-
|
|
669
|
+
A as Dispatcher
|
|
649
670
|
};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
(function(_,a){typeof exports=="object"&&typeof module<"u"?a(exports):typeof define=="function"&&define.amd?define(["exports"],a):(_=typeof globalThis<"u"?globalThis:_||self,a(_.WebSerialCore={}))})(this,function(_){"use strict";var $=Object.defineProperty;var T=_=>{throw TypeError(_)};var V=(_,a,u)=>a in _?$(_,a,{enumerable:!0,configurable:!0,writable:!0,value:u}):_[a]=u;var f=(_,a,u)=>V(_,typeof a!="symbol"?a+"":a,u),Q=(_,a,u)=>a.has(_)||T("Cannot "+u);var E=(_,a,u)=>a.has(_)?T("Cannot add the same private member more than once"):a instanceof WeakSet?a.add(_):a.set(_,u);var c=(_,a,u)=>(Q(_,a,"access private method"),u);var s,m,w,d,A,U,D,k,I,L,P,q,M,R,N,O;const a=[];for(let o=0;o<256;++o)a.push((o+256).toString(16).slice(1));function u(o,i=0){return(a[o[i+0]]+a[o[i+1]]+a[o[i+2]]+a[o[i+3]]+"-"+a[o[i+4]]+a[o[i+5]]+"-"+a[o[i+6]]+a[o[i+7]]+"-"+a[o[i+8]]+a[o[i+9]]+"-"+a[o[i+10]]+a[o[i+11]]+a[o[i+12]]+a[o[i+13]]+a[o[i+14]]+a[o[i+15]]).toLowerCase()}let g;const H=new Uint8Array(16);function j(){if(!g){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");g=crypto.getRandomValues.bind(crypto)}return g(H)}const v={randomUUID:typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function B(o,i,e){var n;if(v.randomUUID&&!o)return v.randomUUID();o=o||{};const t=o.random??((n=o.rng)==null?void 0:n.call(o))??j();if(t.length<16)throw new Error("Random bytes length must be >= 16");return t[6]=t[6]&15|64,t[8]=t[8]&63|128,u(t)}class x extends CustomEvent{constructor(i,e){super(i,e)}}class y extends EventTarget{constructor(){super(...arguments);f(this,"__listeners__",{debug:!1});f(this,"__debug__",!1)}dispatch(e,t=null){const n=new x(e,{detail:t});this.dispatchEvent(n),this.__debug__&&this.dispatchEvent(new x("debug",{detail:{type:e,data:t}}))}dispatchAsync(e,t=null,n=100){const r=this;setTimeout(()=>{r.dispatch(e,t)},n)}on(e,t){typeof this.__listeners__[e]<"u"&&!this.__listeners__[e]&&(this.__listeners__[e]=!0),this.addEventListener(e,t)}off(e,t){this.removeEventListener(e,t)}serialRegisterAvailableListener(e){this.__listeners__[e]||(this.__listeners__[e]=!1)}get availableListeners(){return Object.keys(this.__listeners__).sort().map(t=>({type:t,listening:this.__listeners__[t]}))}}const l=class l extends y{static typeError(i){const e=new Error;throw e.message=`Type ${i} is not supported`,e.name="DeviceTypeError",e}static registerType(i){typeof l.devices[i]>"u"&&(l.devices[i]={})}static add(i){const e=i.typeDevice;typeof l.devices[e]>"u"&&(l.devices[e]={});const t=i.uuid;if(typeof l.devices[e]>"u"&&l.typeError(e),this.instance.dispatch("change",l.devices),l.devices[e][t])throw new Error(`Device with id ${t} already exists`);return l.devices[e][t]=i,this.instance.dispatch("change",l.devices),Object.keys(l.devices[e]).indexOf(t)}static get(i,e){return typeof l.devices[i]>"u"&&(l.devices[i]={}),typeof l.devices[i]>"u"&&l.typeError(i),l.devices[i][e]}static getAll(i=null){return i===null?l.devices:(typeof l.devices[i]>"u"&&l.typeError(i),l.devices[i])}static getList(){return Object.values(l.devices).map(e=>Object.values(e)).flat()}static getByNumber(i,e){return typeof l.devices[i]>"u"&&l.typeError(i),Object.values(l.devices[i]).find(n=>n.deviceNumber===e)??null}static getCustom(i,e=1){return typeof l.devices[i]>"u"&&l.typeError(i),Object.values(l.devices[i]).find(n=>n.deviceNumber===e)??null}};f(l,"instance"),f(l,"devices",{});let h=l;h.instance||(h.instance=new h);function S(o=100){return new Promise(i=>setTimeout(()=>i(),o))}function F(){return"serial"in navigator}const b={baudRate:9600,dataBits:8,stopBits:1,parity:"none",bufferSize:32768,flowControl:"none"};class W extends y{constructor({filters:e=null,config_port:t=b,no_device:n=1,device_listen_on_channel:r=1}={filters:null,config_port:b,no_device:1,device_listen_on_channel:1}){super();E(this,s);f(this,"__internal__",{auto_response:!1,device_number:1,aux_port_connector:0,last_error:{message:null,action:null,code:null,no_code:0},serial:{connected:!1,port:null,last_action:null,response:{length:null,buffer:new Uint8Array([]),as:"hex"},reader:null,input_done:null,output_done:null,input_stream:null,output_stream:null,keep_reading:!0,time_until_send_bytes:void 0,delay_first_connection:200,bytes_connection:null,filters:[],config_port:b,queue:[]},device:{type:"unknown",id:B(),listen_on_port:null},time:{response_connection:500,response_general:2e3},timeout:{until_response:0},interval:{reconnection:0}});if(!("serial"in navigator))throw new Error("Web Serial not supported");e&&(this.serialFilters=e),t&&(this.serialConfigPort=t),n&&c(this,s,N).call(this,n),r&&["number","string"].includes(typeof r)&&(this.listenOnChannel=r),c(this,s,P).call(this),c(this,s,q).call(this)}set listenOnChannel(e){if(typeof e=="string"&&(e=parseInt(e)),isNaN(e)||e<1||e>255)throw new Error("Invalid port number");this.__internal__.device.listen_on_port=e,this.__internal__.serial.bytes_connection=this.serialSetConnectionConstant(e)}get lastAction(){return this.__internal__.serial.last_action}get listenOnChannel(){return this.__internal__.device.listen_on_port??1}set serialFilters(e){this.__internal__.serial.filters=e}get serialFilters(){return this.__internal__.serial.filters}set serialConfigPort(e){this.__internal__.serial.config_port=e}get serialConfigPort(){return this.__internal__.serial.config_port}get isConnected(){return this.__internal__.serial.connected}get isDisconnected(){return!this.__internal__.serial.connected}get deviceNumber(){return this.__internal__.device_number}get uuid(){return this.__internal__.device.id}get typeDevice(){return this.__internal__.device.type}get queue(){return this.__internal__.serial.queue}async timeout(e,t){this.__internal__.last_error.message="Operation response timed out.",this.__internal__.last_error.action=t,this.__internal__.last_error.code=e,this.__internal__.timeout.until_response&&(clearTimeout(this.__internal__.timeout.until_response),this.__internal__.timeout.until_response=0),t==="connect"?(this.__internal__.serial.connected=!1,this.dispatch("serial:reconnect",{})):t==="connection:start"&&(await this.serialDisconnect(),this.__internal__.serial.connected=!1,this.__internal__.aux_port_connector+=1,await this.serialConnect()),this.dispatch("serial:timeout",{...this.__internal__.last_error,bytes:e,action:t})}async disconnect(e=null){await this.serialDisconnect(),this.__internal__.serial.connected=!1,this.__internal__.aux_port_connector=0,this.dispatch("serial:disconnected",e),h.instance.dispatch("change")}async connect(){return new Promise((e,t)=>{F()||t("Web Serial not supported"),setTimeout(async()=>{await S(499),await this.serialConnect(),this.isConnected?e(`${this.typeDevice} device ${this.deviceNumber} connected`):t(`${this.typeDevice} device ${this.deviceNumber} not connected`)},1)})}async serialDisconnect(){try{const e=this.__internal__.serial.reader,t=this.__internal__.serial.output_stream;e&&(await e.cancel().catch(r=>this.serialErrors(r)),await this.__internal__.serial.input_done),t&&(await t.getWriter().close(),await this.__internal__.serial.output_done),this.__internal__.serial.connected&&this.__internal__.serial&&this.__internal__.serial.port&&await this.__internal__.serial.port.close()}catch(e){this.serialErrors(e)}finally{this.__internal__.serial.reader=null,this.__internal__.serial.input_done=null,this.__internal__.serial.output_stream=null,this.__internal__.serial.output_done=null,this.__internal__.serial.connected=!1,this.__internal__.serial.port=null}}getResponseAsArrayBuffer(){this.__internal__.serial.response.as="arraybuffer"}getResponseAsArrayHex(){this.__internal__.serial.response.as="hex"}getResponseAsUint8Array(){this.__internal__.serial.response.as="uint8"}getResponseAsString(){this.__internal__.serial.response.as="string"}async serialPortsSaved(e){const t=this.serialFilters;if(this.__internal__.aux_port_connector<e.length){const n=this.__internal__.aux_port_connector;this.__internal__.serial.port=e[n]}else this.__internal__.aux_port_connector=0,this.__internal__.serial.port=await navigator.serial.requestPort({filters:t});if(!this.__internal__.serial.port)throw new Error("Select another port please")}serialErrors(e){const t=e.toString().toLowerCase();switch(!0){case t.includes("must be handling a user gesture to show a permission request"):case t.includes("the port is closed."):case t.includes("the port is closed or is not writable"):case t.includes("select another port please"):case t.includes("no port selected by the user"):case t.includes("this readable stream reader has been released and cannot be used to cancel its previous owner stream"):this.dispatch("serial:need-permission",{}),h.instance.dispatch("change");break;case t.includes("the port is already open."):case t.includes("failed to open serial port"):this.serialDisconnect().then(async()=>{this.__internal__.aux_port_connector+=1,await this.serialConnect()});break;case t.includes("cannot read properties of undefined (reading 'writable')"):case t.includes("cannot read properties of null (reading 'writable')"):case t.includes("cannot read property 'writable' of null"):case t.includes("cannot read property 'writable' of undefined"):this.serialDisconnect().then(async()=>{await this.serialConnect()});break;case t.includes("'close' on 'serialport': a call to close() is already in progress."):break;case t.includes("failed to execute 'open' on 'serialport': a call to open() is already in progress."):break;case t.includes("the port is already closed."):break;case t.includes("the device has been lost"):this.dispatch("serial:lost",{}),h.instance.dispatch("change");break;case t.includes("navigator.serial is undefined"):this.dispatch("serial:unsupported",{});break;default:console.error(e);break}this.dispatch("serial:error",e)}async serialConnect(){try{this.dispatch("serial:connecting",{});const e=await c(this,s,A).call(this);if(e.length>0)await this.serialPortsSaved(e);else{const r=this.serialFilters;this.__internal__.serial.port=await navigator.serial.requestPort({filters:r})}const t=this.__internal__.serial.port;if(!t)throw new Error("No port selected by the user");await t.open(this.serialConfigPort);const n=this;t.onconnect=r=>{n.dispatch("serial:connected",r),h.instance.dispatch("change"),n.__internal__.serial.queue.length>0&&n.dispatch("internal:queue",{})},t.ondisconnect=async()=>{await n.disconnect()},await S(this.__internal__.serial.delay_first_connection),this.__internal__.timeout.until_response=setTimeout(async()=>{await n.timeout(n.__internal__.serial.bytes_connection??[],"connection:start")},this.__internal__.time.response_connection),this.__internal__.serial.last_action="connect",await c(this,s,w).call(this,this.__internal__.serial.bytes_connection??[]),this.dispatch("serial:sent",{action:"connect",bytes:this.__internal__.serial.bytes_connection}),this.__internal__.auto_response&&c(this,s,d).call(this,["DD","DD"],null),await c(this,s,I).call(this)}catch(e){this.serialErrors(e)}}async serialForget(){return await c(this,s,L).call(this)}decToHex(e){return typeof e=="string"&&(e=parseInt(e,10)),e.toString(16)}hexToDec(e){return parseInt(e,16)}hexMaker(e="00",t=2){return e.toString().padStart(t,"0").toLowerCase()}add0x(e){const t=[];return e.forEach((n,r)=>{t[r]="0x"+n}),t}bytesToHex(e){return this.add0x(Array.from(e,t=>this.hexMaker(t)))}async appendToQueue(e,t){const n=this.bytesToHex(e);if(["connect","connection:start"].includes(t)){if(this.__internal__.serial.connected)return;await this.serialConnect();return}this.__internal__.serial.queue.push({bytes:n,action:t}),this.dispatch("internal:queue",{})}serialSetConnectionConstant(e=1){throw new Error(`Method not implemented 'serialSetConnectionConstant' to listen on channel ${e}`)}serialMessage(e){throw console.log(e),new Error("Method not implemented 'serialMessage'")}serialCorruptMessage(e,t){throw console.log(e,t),new Error("Method not implemented 'serialCorruptMessage'")}clearSerialQueue(){this.__internal__.serial.queue=[]}sumHex(e){let t=0;return e.forEach(n=>{t+=parseInt(n,16)}),t.toString(16)}toString(){return JSON.stringify({__class:this.typeDevice,device_number:this.deviceNumber,uuid:this.uuid,connected:this.isConnected,connection:this.__internal__.serial.bytes_connection})}softReload(){c(this,s,O).call(this),this.dispatch("serial:soft-reload",{})}async sendConnect(){if(!this.__internal__.serial.bytes_connection)throw new Error("No connection bytes defined");await this.appendToQueue(this.__internal__.serial.bytes_connection,"connect")}async sendCustomCode({code:e=[]}={code:[]}){if(e===null||e.length===0)throw new Error("No data to send");await this.appendToQueue(e,"custom")}stringToArrayHex(e){return Array.from(e).map(t=>t.charCodeAt(0).toString(16))}stringToArrayBuffer(e,t=`
|
|
1
|
+
(function(c,a){typeof exports=="object"&&typeof module<"u"?a(exports):typeof define=="function"&&define.amd?define(["exports"],a):(c=typeof globalThis<"u"?globalThis:c||self,a(c.WebSerialCore={}))})(this,function(c){"use strict";var V=Object.defineProperty;var T=c=>{throw TypeError(c)};var Q=(c,a,h)=>a in c?V(c,a,{enumerable:!0,configurable:!0,writable:!0,value:h}):c[a]=h;var f=(c,a,h)=>Q(c,typeof a!="symbol"?a+"":a,h),z=(c,a,h)=>a.has(c)||T("Cannot "+h);var E=(c,a,h)=>a.has(c)?T("Cannot add the same private member more than once"):a instanceof WeakSet?a.add(c):a.set(c,h);var _=(c,a,h)=>(z(c,a,"access private method"),h);var s,g,b,v,p,U,k,D,L,P,I,q,$,R,M,N,O;const a=[];for(let o=0;o<256;++o)a.push((o+256).toString(16).slice(1));function h(o,i=0){return(a[o[i+0]]+a[o[i+1]]+a[o[i+2]]+a[o[i+3]]+"-"+a[o[i+4]]+a[o[i+5]]+"-"+a[o[i+6]]+a[o[i+7]]+"-"+a[o[i+8]]+a[o[i+9]]+"-"+a[o[i+10]]+a[o[i+11]]+a[o[i+12]]+a[o[i+13]]+a[o[i+14]]+a[o[i+15]]).toLowerCase()}let y;const H=new Uint8Array(16);function j(){if(!y){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");y=crypto.getRandomValues.bind(crypto)}return y(H)}const C={randomUUID:typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function B(o,i,e){var n;if(C.randomUUID&&!o)return C.randomUUID();o=o||{};const t=o.random??((n=o.rng)==null?void 0:n.call(o))??j();if(t.length<16)throw new Error("Random bytes length must be >= 16");return t[6]=t[6]&15|64,t[8]=t[8]&63|128,h(t)}class x extends CustomEvent{constructor(i,e){super(i,e)}}class w extends EventTarget{constructor(){super(...arguments);f(this,"__listeners__",{debug:!1});f(this,"__debug__",!1)}dispatch(e,t=null){const n=new x(e,{detail:t});this.dispatchEvent(n),this.__debug__&&this.dispatchEvent(new x("debug",{detail:{type:e,data:t}}))}dispatchAsync(e,t=null,n=100){const r=this;setTimeout(()=>{r.dispatch(e,t)},n)}on(e,t){typeof this.__listeners__[e]<"u"&&!this.__listeners__[e]&&(this.__listeners__[e]=!0),this.addEventListener(e,t)}off(e,t){this.removeEventListener(e,t)}serialRegisterAvailableListener(e){this.__listeners__[e]||(this.__listeners__[e]=!1)}get availableListeners(){return Object.keys(this.__listeners__).sort().map(t=>({type:t,listening:this.__listeners__[t]}))}}const l=class l extends w{constructor(){super(),["change"].forEach(e=>{this.serialRegisterAvailableListener(e)})}static $dispatchChange(i=null){i&&i.$checkAndDispatchConnection(),l.instance.dispatch("change",{devices:l.devices,dispatcher:i})}static typeError(i){const e=new Error;throw e.message=`Type ${i} is not supported`,e.name="DeviceTypeError",e}static registerType(i){typeof l.devices[i]>"u"&&(l.devices[i]={})}static add(i){const e=i.typeDevice;typeof l.devices[e]>"u"&&(l.devices[e]={});const t=i.uuid;if(typeof l.devices[e]>"u"&&l.typeError(e),l.devices[e][t])throw new Error(`Device with id ${t} already exists`);return l.devices[e][t]=i,l.$dispatchChange(i),Object.keys(l.devices[e]).indexOf(t)}static get(i,e){return typeof l.devices[i]>"u"&&(l.devices[i]={}),typeof l.devices[i]>"u"&&l.typeError(i),l.devices[i][e]}static getAll(i=null){return i===null?l.devices:(typeof l.devices[i]>"u"&&l.typeError(i),l.devices[i])}static getList(){return Object.values(l.devices).map(e=>Object.values(e)).flat()}static getByNumber(i,e){return typeof l.devices[i]>"u"&&l.typeError(i),Object.values(l.devices[i]).find(n=>n.deviceNumber===e)??null}static getCustom(i,e=1){return typeof l.devices[i]>"u"&&l.typeError(i),Object.values(l.devices[i]).find(n=>n.deviceNumber===e)??null}};f(l,"instance"),f(l,"devices",{});let u=l;u.instance||(u.instance=new u);function S(o=100){return new Promise(i=>setTimeout(()=>i(),o))}function F(){return"serial"in navigator}const m={baudRate:9600,dataBits:8,stopBits:1,parity:"none",bufferSize:32768,flowControl:"none"};class W extends w{constructor({filters:e=null,config_port:t=m,no_device:n=1,device_listen_on_channel:r=1}={filters:null,config_port:m,no_device:1,device_listen_on_channel:1}){super();E(this,s);f(this,"__internal__",{auto_response:!1,device_number:1,aux_port_connector:0,last_error:{message:null,action:null,code:null,no_code:0},serial:{connected:!1,port:null,last_action:null,response:{length:null,buffer:new Uint8Array([]),as:"hex"},reader:null,input_done:null,output_done:null,input_stream:null,output_stream:null,keep_reading:!0,time_until_send_bytes:void 0,delay_first_connection:200,bytes_connection:null,filters:[],config_port:m,queue:[],auto_response:["DD","DD"]},device:{type:"unknown",id:B(),listen_on_port:null},time:{response_connection:500,response_general:2e3},timeout:{until_response:0},interval:{reconnection:0}});if(!("serial"in navigator))throw new Error("Web Serial not supported");e&&(this.serialFilters=e),t&&(this.serialConfigPort=t),n&&_(this,s,N).call(this,n),r&&["number","string"].includes(typeof r)&&(this.listenOnChannel=r),_(this,s,q).call(this),_(this,s,$).call(this)}set listenOnChannel(e){if(typeof e=="string"&&(e=parseInt(e)),isNaN(e)||e<1||e>255)throw new Error("Invalid port number");this.__internal__.device.listen_on_port=e,this.__internal__.serial.bytes_connection=this.serialSetConnectionConstant(e)}get lastAction(){return this.__internal__.serial.last_action}get listenOnChannel(){return this.__internal__.device.listen_on_port??1}set serialFilters(e){this.__internal__.serial.filters=e}get serialFilters(){return this.__internal__.serial.filters}set serialConfigPort(e){this.__internal__.serial.config_port=e}get serialConfigPort(){return this.__internal__.serial.config_port}get isConnected(){const e=this.__internal__.serial.connected,t=_(this,s,g).call(this,this.__internal__.serial.port);return e&&!t&&_(this,s,b).call(this,{error:"Port is closed, not readable or writable."}),this.__internal__.serial.connected=t,this.__internal__.serial.connected}get isDisconnected(){const e=this.__internal__.serial.connected,t=_(this,s,g).call(this,this.__internal__.serial.port);return!e&&t&&(this.dispatch("serial:connected"),u.$dispatchChange(this)),this.__internal__.serial.connected=t,!this.__internal__.serial.connected}get deviceNumber(){return this.__internal__.device_number}get uuid(){return this.__internal__.device.id}get typeDevice(){return this.__internal__.device.type}get queue(){return this.__internal__.serial.queue}async timeout(e,t){this.__internal__.last_error.message="Operation response timed out.",this.__internal__.last_error.action=t,this.__internal__.last_error.code=e,this.__internal__.timeout.until_response&&(clearTimeout(this.__internal__.timeout.until_response),this.__internal__.timeout.until_response=0),t==="connect"?(this.__internal__.serial.connected=!1,this.dispatch("serial:reconnect",{})):t==="connection:start"&&(await this.serialDisconnect(),this.__internal__.serial.connected=!1,this.__internal__.aux_port_connector+=1,await this.serialConnect()),this.dispatch("serial:timeout",{...this.__internal__.last_error,bytes:e,action:t})}async disconnect(e=null){await this.serialDisconnect(),_(this,s,b).call(this,e)}async connect(){return new Promise((e,t)=>{F()||t("Web Serial not supported"),setTimeout(async()=>{await S(499),await this.serialConnect(),this.isConnected?e(`${this.typeDevice} device ${this.deviceNumber} connected`):t(`${this.typeDevice} device ${this.deviceNumber} not connected`)},1)})}async serialDisconnect(){try{const e=this.__internal__.serial.reader,t=this.__internal__.serial.output_stream;e&&(await e.cancel().catch(r=>this.serialErrors(r)),await this.__internal__.serial.input_done),t&&(await t.getWriter().close(),await this.__internal__.serial.output_done),this.__internal__.serial.connected&&this.__internal__.serial&&this.__internal__.serial.port&&await this.__internal__.serial.port.close()}catch(e){this.serialErrors(e)}finally{this.__internal__.serial.reader=null,this.__internal__.serial.input_done=null,this.__internal__.serial.output_stream=null,this.__internal__.serial.output_done=null,this.__internal__.serial.connected=!1,this.__internal__.serial.port=null}}getResponseAsArrayBuffer(){this.__internal__.serial.response.as="arraybuffer"}getResponseAsArrayHex(){this.__internal__.serial.response.as="hex"}getResponseAsUint8Array(){this.__internal__.serial.response.as="uint8"}getResponseAsString(){this.__internal__.serial.response.as="string"}async serialPortsSaved(e){const t=this.serialFilters;if(this.__internal__.aux_port_connector<e.length){const n=this.__internal__.aux_port_connector;this.__internal__.serial.port=e[n]}else this.__internal__.aux_port_connector=0,this.__internal__.serial.port=await navigator.serial.requestPort({filters:t});if(!this.__internal__.serial.port)throw new Error("Select another port please")}serialErrors(e){const t=e.toString().toLowerCase();switch(!0){case t.includes("must be handling a user gesture to show a permission request"):case t.includes("the port is closed."):case t.includes("the port is closed or is not writable"):case t.includes("the port is closed or is not readable"):case t.includes("the port is closed or is not readable/writable"):case t.includes("select another port please"):case t.includes("no port selected by the user"):case t.includes("this readable stream reader has been released and cannot be used to cancel its previous owner stream"):this.dispatch("serial:need-permission",{}),u.$dispatchChange(this);break;case t.includes("the port is already open."):case t.includes("failed to open serial port"):this.serialDisconnect().then(async()=>{this.__internal__.aux_port_connector+=1,await this.serialConnect()});break;case t.includes("cannot read properties of undefined (reading 'writable')"):case t.includes("cannot read properties of null (reading 'writable')"):case t.includes("cannot read property 'writable' of null"):case t.includes("cannot read property 'writable' of undefined"):this.serialDisconnect().then(async()=>{await this.serialConnect()});break;case t.includes("'close' on 'serialport': a call to close() is already in progress."):break;case t.includes("failed to execute 'open' on 'serialport': a call to open() is already in progress."):break;case t.includes("the port is already closed."):break;case t.includes("the device has been lost"):this.dispatch("serial:lost",{}),u.$dispatchChange(this);break;case t.includes("navigator.serial is undefined"):this.dispatch("serial:unsupported",{});break;default:console.error(e);break}this.dispatch("serial:error",e)}async serialConnect(){try{this.dispatch("serial:connecting",{});const e=await _(this,s,U).call(this);if(e.length>0)await this.serialPortsSaved(e);else{const r=this.serialFilters;this.__internal__.serial.port=await navigator.serial.requestPort({filters:r})}const t=this.__internal__.serial.port;if(!t)throw new Error("No port selected by the user");await t.open(this.serialConfigPort);const n=this;t.onconnect=r=>{console.log(r),n.dispatch("serial:connected",r),u.$dispatchChange(this),n.__internal__.serial.queue.length>0&&n.dispatch("internal:queue",{})},t.ondisconnect=async()=>{await n.disconnect()},await S(this.__internal__.serial.delay_first_connection),this.__internal__.timeout.until_response=setTimeout(async()=>{await n.timeout(n.__internal__.serial.bytes_connection??[],"connection:start")},this.__internal__.time.response_connection),this.__internal__.serial.last_action="connect",await _(this,s,v).call(this,this.__internal__.serial.bytes_connection??[]),this.dispatch("serial:sent",{action:"connect",bytes:this.__internal__.serial.bytes_connection}),this.__internal__.auto_response&&_(this,s,p).call(this,this.__internal__.serial.auto_response,null),await _(this,s,P).call(this)}catch(e){this.serialErrors(e)}}async serialForget(){return await _(this,s,I).call(this)}decToHex(e){return typeof e=="string"&&(e=parseInt(e,10)),e.toString(16)}hexToDec(e){return parseInt(e,16)}hexMaker(e="00",t=2){return e.toString().padStart(t,"0").toLowerCase()}add0x(e){const t=[];return e.forEach((n,r)=>{t[r]="0x"+n}),t}bytesToHex(e){return this.add0x(Array.from(e,t=>this.hexMaker(t)))}async appendToQueue(e,t){const n=this.bytesToHex(e);if(["connect","connection:start"].includes(t)){if(this.__internal__.serial.connected)return;await this.serialConnect();return}this.__internal__.serial.queue.push({bytes:n,action:t}),this.dispatch("internal:queue",{})}serialSetConnectionConstant(e=1){throw new Error(`Method not implemented 'serialSetConnectionConstant' to listen on channel ${e}`)}serialMessage(e){throw console.log(e),new Error("Method not implemented 'serialMessage'")}serialCorruptMessage(e,t){throw console.log(e,t),new Error("Method not implemented 'serialCorruptMessage'")}clearSerialQueue(){this.__internal__.serial.queue=[]}sumHex(e){let t=0;return e.forEach(n=>{t+=parseInt(n,16)}),t.toString(16)}toString(){return JSON.stringify({__class:this.typeDevice,device_number:this.deviceNumber,uuid:this.uuid,connected:this.isConnected,connection:this.__internal__.serial.bytes_connection})}softReload(){_(this,s,O).call(this),this.dispatch("serial:soft-reload",{})}async sendConnect(){if(!this.__internal__.serial.bytes_connection)throw new Error("No connection bytes defined");await this.appendToQueue(this.__internal__.serial.bytes_connection,"connect")}async sendCustomCode({code:e=[]}={code:[]}){if(e===null||e.length===0)throw new Error("No data to send");await this.appendToQueue(e,"custom")}stringToArrayHex(e){return Array.from(e).map(t=>t.charCodeAt(0).toString(16))}stringToArrayBuffer(e,t=`
|
|
2
2
|
`){return this.parseStringToTextEncoder(e,t).buffer}parseStringToTextEncoder(e="",t=`
|
|
3
3
|
`){const n=new TextEncoder;return e+=t,n.encode(e)}parseStringToBytes(e="",t=`
|
|
4
|
-
`){const n=this.parseStringToTextEncoder(e,t);return Array.from(n).map(r=>r.toString(16))}parseUint8ToHex(e){return Array.from(e).map(t=>t.toString(16))}parseHexToUint8(e){return new Uint8Array(e.map(t=>parseInt(t,16)))}stringArrayToUint8Array(e){const t=[];return e.forEach(n=>{const r=n.replace("0x","");t.push(parseInt(r,16))}),new Uint8Array(t)}parseUint8ArrayToString(e){const t=this.stringArrayToUint8Array(e);e=this.parseUint8ToHex(t);const n=e.map(r=>parseInt(r,16));return String.fromCharCode(...n).replace(/[\n\r]+/g,"")}hexToAscii(e){const t=e.toString();let n="";for(let r=0;r<t.length;r+=2)n+=String.fromCharCode(parseInt(t.substring(r,2),16));return n}asciiToHex(e){const t=[];for(let n=0,r=e.length;n<r;n++){const
|
|
4
|
+
`){const n=this.parseStringToTextEncoder(e,t);return Array.from(n).map(r=>r.toString(16))}parseUint8ToHex(e){return Array.from(e).map(t=>t.toString(16))}parseHexToUint8(e){return new Uint8Array(e.map(t=>parseInt(t,16)))}stringArrayToUint8Array(e){const t=[];return e.forEach(n=>{const r=n.replace("0x","");t.push(parseInt(r,16))}),new Uint8Array(t)}parseUint8ArrayToString(e){const t=this.stringArrayToUint8Array(e);e=this.parseUint8ToHex(t);const n=e.map(r=>parseInt(r,16));return String.fromCharCode(...n).replace(/[\n\r]+/g,"")}hexToAscii(e){const t=e.toString();let n="";for(let r=0;r<t.length;r+=2)n+=String.fromCharCode(parseInt(t.substring(r,2),16));return n}asciiToHex(e){const t=[];for(let n=0,r=e.length;n<r;n++){const d=Number(e.charCodeAt(n)).toString(16);t.push(d)}return t.join("")}$checkAndDispatchConnection(){return this.isConnected}}s=new WeakSet,g=function(e){return!!(e&&e.readable&&e.writable)},b=function(e=null){this.__internal__.serial.connected=!1,this.__internal__.aux_port_connector=0,this.dispatch("serial:disconnected",e),u.$dispatchChange(this)},v=async function(e){const t=this.__internal__.serial.port;if(!t||t&&(!t.readable||!t.writable))throw _(this,s,b).call(this,{error:"Port is closed, not readable or writable."}),new Error("The port is closed or is not readable/writable");const n=this.stringArrayToUint8Array(e);if(t.writable===null)return;const r=t.writable.getWriter();await r.write(n),r.releaseLock()},p=function(e=[],t=null){if(e&&e.length>0){const n=this.__internal__.serial.connected;this.__internal__.serial.connected=_(this,s,g).call(this,this.__internal__.serial.port),!n&&this.__internal__.serial.connected&&(this.dispatch("serial:connected"),u.$dispatchChange(this)),this.__internal__.interval.reconnection&&(clearInterval(this.__internal__.interval.reconnection),this.__internal__.interval.reconnection=0),this.__internal__.timeout.until_response&&(clearTimeout(this.__internal__.timeout.until_response),this.__internal__.timeout.until_response=0);const r=[];for(const d in e)r.push(e[d].toString().padStart(2,"0").toLowerCase());if(this.__internal__.serial.response.as==="hex")this.serialMessage(r);else if(this.__internal__.serial.response.as==="uint8")this.serialMessage(this.parseHexToUint8(this.add0x(r)));else if(this.__internal__.serial.response.as==="string")this.serialMessage(this.parseUint8ArrayToString(this.add0x(r)));else{const d=this.stringToArrayBuffer(this.parseUint8ArrayToString(this.add0x(r)));this.serialMessage(d)}}else this.serialCorruptMessage(e,t);this.__internal__.serial.queue.length!==0&&this.dispatch("internal:queue",{})},U=async function(){const e=this.serialFilters,t=await navigator.serial.getPorts({filters:e});return e.length===0?t:t.filter(r=>{const d=r.getInfo();return e.some(A=>d.usbProductId===A.usbProductId&&d.usbVendorId===A.usbVendorId)}).filter(r=>!_(this,s,g).call(this,r))},k=function(e){if(e){const t=this.__internal__.serial.response.buffer,n=new Uint8Array(t.length+e.byteLength);n.set(t,0),n.set(new Uint8Array(e),t.length),this.__internal__.serial.response.buffer=n}},D=async function(){this.__internal__.serial.time_until_send_bytes&&(clearTimeout(this.__internal__.serial.time_until_send_bytes),this.__internal__.serial.time_until_send_bytes=0),this.__internal__.serial.time_until_send_bytes=setTimeout(()=>{const e=[];for(const t in this.__internal__.serial.response.buffer)e.push(this.__internal__.serial.response.buffer[t].toString(16));this.__internal__.serial.response.buffer&&_(this,s,p).call(this,e),this.__internal__.serial.response.buffer=new Uint8Array(0)},400)},L=async function(){if(this.__internal__.serial.response.length!==null){if(this.__internal__.serial.response.length===this.__internal__.serial.response.buffer.length){const e=[];for(const t in this.__internal__.serial.response.buffer)e.push(this.__internal__.serial.response.buffer[t].toString(16));_(this,s,p).call(this,e),this.__internal__.serial.response.buffer=new Uint8Array(0)}else if(this.__internal__.serial.response.length<this.__internal__.serial.response.buffer.length){let e=new Uint8Array(0);for(let n=0;n<this.__internal__.serial.response.length;n++)e[n]=this.__internal__.serial.response.buffer[n];if(e.length===this.__internal__.serial.response.length){const n=[];for(const r in e)n.push(e[r].toString(16));_(this,s,p).call(this,n),this.__internal__.serial.response.buffer=new Uint8Array(0);return}e=new Uint8Array(0);const t=this.__internal__.serial.response.length*2;if(this.__internal__.serial.response.buffer.length===t){for(let n=14;n<t;n++)e[n-this.__internal__.serial.response.length]=this.__internal__.serial.response.buffer[n];if(e.length===this.__internal__.serial.response.length){const n=[];for(const r in e)n.push(e[r].toString(16));_(this,s,p).call(this,n),this.__internal__.serial.response.buffer=new Uint8Array(0)}}}}},P=async function(){const e=this.__internal__.serial.port;if(!e||!e.readable)throw new Error("Port is not readable");for(;e.readable&&this.__internal__.serial.keep_reading;){const t=e.readable.getReader();this.__internal__.serial.reader=t;try{let n=!0;for(;n;){const{value:r,done:d}=await t.read();if(d){t.releaseLock(),this.__internal__.serial.keep_reading=!1,n=!1;break}_(this,s,k).call(this,r),this.__internal__.serial.response.length===null?await _(this,s,D).call(this):await _(this,s,L).call(this)}}catch(n){this.serialErrors(n)}finally{t.releaseLock()}}this.__internal__.serial.keep_reading=!0,this.__internal__.serial.port&&await this.__internal__.serial.port.close()},I=async function(){return typeof window>"u"?!1:"serial"in navigator&&"forget"in SerialPort.prototype&&this.__internal__.serial.port?(await this.__internal__.serial.port.forget(),!0):!1},q=function(){["serial:connected","serial:connecting","serial:reconnect","serial:timeout","serial:disconnected","serial:sent","serial:soft-reload","serial:message","unknown","serial:need-permission","serial:lost","serial:unsupported","serial:error","debug"].forEach(t=>{this.serialRegisterAvailableListener(t)})},$=function(){const e=this;this.on("internal:queue",async()=>{var t;await _(t=e,s,M).call(t)}),_(this,s,R).call(this)},R=function(){const e=this;navigator.serial.addEventListener("connect",async()=>{e.isDisconnected&&await e.serialConnect().catch(()=>{})})},M=async function(){if(!_(this,s,g).call(this,this.__internal__.serial.port)){_(this,s,b).call(this,{error:"Port is closed, not readable or writable."}),await this.serialConnect();return}if(this.__internal__.timeout.until_response||this.__internal__.serial.queue.length===0)return;const e=this.__internal__.serial.queue[0];let t=this.__internal__.time.response_general;e.action==="connect"&&(t=this.__internal__.time.response_connection),this.__internal__.timeout.until_response=setTimeout(async()=>{await this.timeout(e.bytes,e.action)},t),this.__internal__.serial.last_action=e.action??"unknown",await _(this,s,v).call(this,e.bytes),this.dispatch("serial:sent",{action:e.action,bytes:e.bytes}),this.__internal__.auto_response&&_(this,s,p).call(this,this.__internal__.serial.auto_response,null);const n=[...this.__internal__.serial.queue];this.__internal__.serial.queue=n.splice(1)},N=function(e=1){this.__internal__.device_number=e,this.__internal__.serial.bytes_connection=this.serialSetConnectionConstant(e)},O=function(){this.__internal__.last_error={message:null,action:null,code:null,no_code:0}},c.Core=W,c.Devices=u,c.Dispatcher=w,Object.defineProperty(c,Symbol.toStringTag,{value:"Module"})});
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "webserial-core",
|
|
3
3
|
"description": "Webserial Core to easy connections with serial devices",
|
|
4
|
-
"version": "1.0.
|
|
4
|
+
"version": "1.0.3",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
7
7
|
"author": "danidoble",
|
|
@@ -39,9 +39,9 @@
|
|
|
39
39
|
"format": "prettier --write ./lib/**/*.ts"
|
|
40
40
|
},
|
|
41
41
|
"devDependencies": {
|
|
42
|
-
"@eslint/js": "^9.
|
|
42
|
+
"@eslint/js": "^9.22.0",
|
|
43
43
|
"@types/w3c-web-serial": "^1.0.8",
|
|
44
|
-
"eslint": "^9.
|
|
44
|
+
"eslint": "^9.22.0",
|
|
45
45
|
"globals": "^15.15.0",
|
|
46
46
|
"prettier": "3.4.2",
|
|
47
47
|
"puppeteer": "^24.4.0",
|
|
@@ -49,7 +49,7 @@
|
|
|
49
49
|
"typescript": "~5.7.3",
|
|
50
50
|
"typescript-eslint": "^8.26.0",
|
|
51
51
|
"uuid": "^11.1.0",
|
|
52
|
-
"vite": "^6.2.
|
|
52
|
+
"vite": "^6.2.1"
|
|
53
53
|
},
|
|
54
54
|
"publishConfig": {
|
|
55
55
|
"access": "public"
|