webserial-core 1.0.0 → 1.0.2
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 +85 -83
- package/dist/webserial-core.umd.cjs +2 -2
- package/package.json +1 -1
package/dist/webserial-core.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
var N = Object.defineProperty;
|
|
2
|
-
var
|
|
2
|
+
var w = (r) => {
|
|
3
3
|
throw TypeError(r);
|
|
4
4
|
};
|
|
5
5
|
var O = (r, i, e) => i in r ? N(r, i, { enumerable: !0, configurable: !0, writable: !0, value: e }) : r[i] = e;
|
|
6
|
-
var
|
|
7
|
-
var m = (r, i, e) => i.has(r) ?
|
|
6
|
+
var d = (r, i, e) => O(r, typeof i != "symbol" ? i + "" : i, e), H = (r, i, e) => i.has(r) || w("Cannot " + e);
|
|
7
|
+
var m = (r, i, e) => i.has(r) ? w("Cannot add the same private member more than once") : i instanceof WeakSet ? i.add(r) : i.set(r, e);
|
|
8
8
|
var l = (r, i, e) => (H(r, i, "access private method"), e);
|
|
9
9
|
const _ = [];
|
|
10
10
|
for (let r = 0; r < 256; ++r)
|
|
@@ -22,33 +22,33 @@ function F() {
|
|
|
22
22
|
}
|
|
23
23
|
return p(B);
|
|
24
24
|
}
|
|
25
|
-
const $ = typeof crypto < "u" && crypto.randomUUID && crypto.randomUUID.bind(crypto),
|
|
25
|
+
const $ = typeof crypto < "u" && crypto.randomUUID && crypto.randomUUID.bind(crypto), v = { randomUUID: $ };
|
|
26
26
|
function V(r, i, e) {
|
|
27
27
|
var n;
|
|
28
|
-
if (
|
|
29
|
-
return
|
|
28
|
+
if (v.randomUUID && !r)
|
|
29
|
+
return v.randomUUID();
|
|
30
30
|
r = r || {};
|
|
31
31
|
const t = r.random ?? ((n = r.rng) == null ? void 0 : n.call(r)) ?? 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);
|
|
35
35
|
}
|
|
36
|
-
class
|
|
36
|
+
class x extends CustomEvent {
|
|
37
37
|
constructor(i, e) {
|
|
38
38
|
super(i, e);
|
|
39
39
|
}
|
|
40
40
|
}
|
|
41
|
-
class
|
|
41
|
+
class C extends EventTarget {
|
|
42
42
|
constructor() {
|
|
43
43
|
super(...arguments);
|
|
44
|
-
|
|
44
|
+
d(this, "__listeners__", {
|
|
45
45
|
debug: !1
|
|
46
46
|
});
|
|
47
|
-
|
|
47
|
+
d(this, "__debug__", !1);
|
|
48
48
|
}
|
|
49
49
|
dispatch(e, t = null) {
|
|
50
|
-
const n = new
|
|
51
|
-
this.dispatchEvent(n), this.__debug__ && this.dispatchEvent(new
|
|
50
|
+
const n = new x(e, { detail: t });
|
|
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
54
|
const s = this;
|
|
@@ -72,12 +72,47 @@ class S extends EventTarget {
|
|
|
72
72
|
}));
|
|
73
73
|
}
|
|
74
74
|
}
|
|
75
|
-
|
|
75
|
+
const o = class o extends C {
|
|
76
|
+
static typeError(i) {
|
|
77
|
+
const e = new Error();
|
|
78
|
+
throw e.message = `Type ${i} is not supported`, e.name = "DeviceTypeError", e;
|
|
79
|
+
}
|
|
80
|
+
static registerType(i) {
|
|
81
|
+
typeof o.devices[i] > "u" && (o.devices[i] = {});
|
|
82
|
+
}
|
|
83
|
+
static add(i) {
|
|
84
|
+
const e = i.typeDevice;
|
|
85
|
+
typeof o.devices[e] > "u" && (o.devices[e] = {});
|
|
86
|
+
const t = i.uuid;
|
|
87
|
+
if (typeof o.devices[e] > "u" && o.typeError(e), this.instance.dispatch("change", o.devices), o.devices[e][t])
|
|
88
|
+
throw new Error(`Device with id ${t} already exists`);
|
|
89
|
+
return o.devices[e][t] = i, this.instance.dispatch("change", o.devices), Object.keys(o.devices[e]).indexOf(t);
|
|
90
|
+
}
|
|
91
|
+
static get(i, e) {
|
|
92
|
+
return typeof o.devices[i] > "u" && (o.devices[i] = {}), typeof o.devices[i] > "u" && o.typeError(i), o.devices[i][e];
|
|
93
|
+
}
|
|
94
|
+
static getAll(i = null) {
|
|
95
|
+
return i === null ? o.devices : (typeof o.devices[i] > "u" && o.typeError(i), o.devices[i]);
|
|
96
|
+
}
|
|
97
|
+
static getList() {
|
|
98
|
+
return Object.values(o.devices).map((e) => Object.values(e)).flat();
|
|
99
|
+
}
|
|
100
|
+
static getByNumber(i, e) {
|
|
101
|
+
return typeof o.devices[i] > "u" && o.typeError(i), Object.values(o.devices[i]).find((n) => n.deviceNumber === e) ?? null;
|
|
102
|
+
}
|
|
103
|
+
static getCustom(i, e = 1) {
|
|
104
|
+
return typeof o.devices[i] > "u" && o.typeError(i), Object.values(o.devices[i]).find((n) => n.deviceNumber === e) ?? null;
|
|
105
|
+
}
|
|
106
|
+
};
|
|
107
|
+
d(o, "instance"), d(o, "devices", {});
|
|
108
|
+
let c = o;
|
|
109
|
+
c.instance || (c.instance = new c());
|
|
110
|
+
function S(r = 100) {
|
|
76
111
|
return new Promise(
|
|
77
112
|
(i) => setTimeout(() => i(), r)
|
|
78
113
|
);
|
|
79
114
|
}
|
|
80
|
-
function
|
|
115
|
+
function W() {
|
|
81
116
|
return "serial" in navigator;
|
|
82
117
|
}
|
|
83
118
|
const f = {
|
|
@@ -88,8 +123,8 @@ const f = {
|
|
|
88
123
|
bufferSize: 32768,
|
|
89
124
|
flowControl: "none"
|
|
90
125
|
};
|
|
91
|
-
var a,
|
|
92
|
-
class z extends
|
|
126
|
+
var a, g, y, h, E, A, T, U, k, D, I, L, P, q, R, M;
|
|
127
|
+
class z extends C {
|
|
93
128
|
constructor({
|
|
94
129
|
filters: e = null,
|
|
95
130
|
config_port: t = f,
|
|
@@ -103,7 +138,7 @@ class z extends S {
|
|
|
103
138
|
}) {
|
|
104
139
|
super();
|
|
105
140
|
m(this, a);
|
|
106
|
-
|
|
141
|
+
d(this, "__internal__", {
|
|
107
142
|
auto_response: !1,
|
|
108
143
|
device_number: 1,
|
|
109
144
|
aux_port_connector: 0,
|
|
@@ -151,6 +186,8 @@ class z extends S {
|
|
|
151
186
|
reconnection: 0
|
|
152
187
|
}
|
|
153
188
|
});
|
|
189
|
+
if (!("serial" in navigator))
|
|
190
|
+
throw new Error("Web Serial not supported");
|
|
154
191
|
e && (this.serialFilters = e), t && (this.serialConfigPort = t), n && l(this, a, R).call(this, n), s && ["number", "string"].includes(typeof s) && (this.listenOnChannel = s), l(this, a, I).call(this), l(this, a, L).call(this);
|
|
155
192
|
}
|
|
156
193
|
set listenOnChannel(e) {
|
|
@@ -202,12 +239,12 @@ class z extends S {
|
|
|
202
239
|
});
|
|
203
240
|
}
|
|
204
241
|
async disconnect(e = null) {
|
|
205
|
-
await this.serialDisconnect(), this.__internal__.serial.connected = !1, this.__internal__.aux_port_connector = 0, this.dispatch("serial:disconnected", e);
|
|
242
|
+
await this.serialDisconnect(), this.__internal__.serial.connected = !1, this.__internal__.aux_port_connector = 0, this.dispatch("serial:disconnected", e), c.instance.dispatch("change");
|
|
206
243
|
}
|
|
207
244
|
async connect() {
|
|
208
245
|
return new Promise((e, t) => {
|
|
209
|
-
|
|
210
|
-
await
|
|
246
|
+
W() || t("Web Serial not supported"), setTimeout(async () => {
|
|
247
|
+
await S(499), await this.serialConnect(), this.isConnected ? e(`${this.typeDevice} device ${this.deviceNumber} connected`) : t(`${this.typeDevice} device ${this.deviceNumber} not connected`);
|
|
211
248
|
}, 1);
|
|
212
249
|
});
|
|
213
250
|
}
|
|
@@ -256,7 +293,7 @@ class z extends S {
|
|
|
256
293
|
case t.includes(
|
|
257
294
|
"this readable stream reader has been released and cannot be used to cancel its previous owner stream"
|
|
258
295
|
):
|
|
259
|
-
this.dispatch("serial:need-permission", {});
|
|
296
|
+
this.dispatch("serial:need-permission", {}), c.instance.dispatch("change");
|
|
260
297
|
break;
|
|
261
298
|
case t.includes("the port is already open."):
|
|
262
299
|
case t.includes("failed to open serial port"):
|
|
@@ -279,7 +316,7 @@ class z extends S {
|
|
|
279
316
|
case t.includes("the port is already closed."):
|
|
280
317
|
break;
|
|
281
318
|
case t.includes("the device has been lost"):
|
|
282
|
-
this.dispatch("serial:lost", {});
|
|
319
|
+
this.dispatch("serial:lost", {}), c.instance.dispatch("change");
|
|
283
320
|
break;
|
|
284
321
|
case t.includes("navigator.serial is undefined"):
|
|
285
322
|
this.dispatch("serial:unsupported", {});
|
|
@@ -293,7 +330,7 @@ class z extends S {
|
|
|
293
330
|
async serialConnect() {
|
|
294
331
|
try {
|
|
295
332
|
this.dispatch("serial:connecting", {});
|
|
296
|
-
const e = await l(this, a,
|
|
333
|
+
const e = await l(this, a, E).call(this);
|
|
297
334
|
if (e.length > 0)
|
|
298
335
|
await this.serialPortsSaved(e);
|
|
299
336
|
else {
|
|
@@ -308,15 +345,15 @@ class z extends S {
|
|
|
308
345
|
await t.open(this.serialConfigPort);
|
|
309
346
|
const n = this;
|
|
310
347
|
t.onconnect = (s) => {
|
|
311
|
-
n.dispatch("serial:connected", s), n.__internal__.serial.queue.length > 0 && n.dispatch("internal:queue", {});
|
|
348
|
+
n.dispatch("serial:connected", s), c.instance.dispatch("change"), n.__internal__.serial.queue.length > 0 && n.dispatch("internal:queue", {});
|
|
312
349
|
}, t.ondisconnect = async () => {
|
|
313
350
|
await n.disconnect();
|
|
314
|
-
}, await
|
|
351
|
+
}, await S(this.__internal__.serial.delay_first_connection), this.__internal__.timeout.until_response = setTimeout(async () => {
|
|
315
352
|
await n.timeout(n.__internal__.serial.bytes_connection ?? [], "connection:start");
|
|
316
|
-
}, this.__internal__.time.response_connection), this.__internal__.serial.last_action = "connect", await l(this, a,
|
|
353
|
+
}, this.__internal__.time.response_connection), this.__internal__.serial.last_action = "connect", await l(this, a, y).call(this, this.__internal__.serial.bytes_connection ?? []), this.dispatch("serial:sent", {
|
|
317
354
|
action: "connect",
|
|
318
355
|
bytes: this.__internal__.serial.bytes_connection
|
|
319
|
-
}), this.__internal__.auto_response && l(this, a,
|
|
356
|
+
}), this.__internal__.auto_response && l(this, a, h).call(this, ["DD", "DD"], null), await l(this, a, k).call(this);
|
|
320
357
|
} catch (e) {
|
|
321
358
|
this.serialErrors(e);
|
|
322
359
|
}
|
|
@@ -444,17 +481,17 @@ class z extends S {
|
|
|
444
481
|
return t.join("");
|
|
445
482
|
}
|
|
446
483
|
}
|
|
447
|
-
a = new WeakSet(),
|
|
448
|
-
return !!(e.readable && e.writable);
|
|
449
|
-
},
|
|
484
|
+
a = new WeakSet(), g = function(e) {
|
|
485
|
+
return !!(e && e.readable && e.writable);
|
|
486
|
+
}, y = async function(e) {
|
|
450
487
|
const t = this.__internal__.serial.port;
|
|
451
|
-
if (!t || !t.writable)
|
|
488
|
+
if (!t || !t.readable || !t.writable)
|
|
452
489
|
throw new Error("The port is closed or is not writable");
|
|
453
490
|
const n = this.stringArrayToUint8Array(e), s = t.writable.getWriter();
|
|
454
491
|
await s.write(n), s.releaseLock();
|
|
455
|
-
},
|
|
492
|
+
}, h = function(e = [], t = null) {
|
|
456
493
|
if (e && e.length > 0) {
|
|
457
|
-
this.__internal__.serial.connected || this.dispatch("serial:connected"), this.__internal__.serial.connected = !0, 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);
|
|
494
|
+
this.__internal__.serial.connected || (this.dispatch("serial:connected"), c.instance.dispatch("change")), this.__internal__.serial.connected = !0, 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);
|
|
458
495
|
const n = [];
|
|
459
496
|
for (const s in e)
|
|
460
497
|
n.push(e[s].toString().padStart(2, "0").toLowerCase());
|
|
@@ -473,13 +510,13 @@ a = new WeakSet(), C = function(e) {
|
|
|
473
510
|
} else
|
|
474
511
|
this.serialCorruptMessage(e, t);
|
|
475
512
|
this.__internal__.serial.queue.length !== 0 && this.dispatch("internal:queue", {});
|
|
476
|
-
},
|
|
513
|
+
}, E = async function() {
|
|
477
514
|
const e = this.serialFilters, t = await navigator.serial.getPorts({ filters: e });
|
|
478
515
|
return e.length === 0 ? t : t.filter((s) => {
|
|
479
516
|
const u = s.getInfo();
|
|
480
|
-
return e.some((
|
|
481
|
-
}).filter((s) => !l(this, a,
|
|
482
|
-
},
|
|
517
|
+
return e.some((b) => u.usbProductId === b.usbProductId && u.usbVendorId === b.usbVendorId);
|
|
518
|
+
}).filter((s) => !l(this, a, g).call(this, s));
|
|
519
|
+
}, A = function(e) {
|
|
483
520
|
if (e) {
|
|
484
521
|
const t = this.__internal__.serial.response.buffer, n = new Uint8Array(t.length + e.byteLength);
|
|
485
522
|
n.set(t, 0), n.set(new Uint8Array(e), t.length), this.__internal__.serial.response.buffer = n;
|
|
@@ -489,7 +526,7 @@ a = new WeakSet(), C = function(e) {
|
|
|
489
526
|
const e = [];
|
|
490
527
|
for (const t in this.__internal__.serial.response.buffer)
|
|
491
528
|
e.push(this.__internal__.serial.response.buffer[t].toString(16));
|
|
492
|
-
this.__internal__.serial.response.buffer && l(this, a,
|
|
529
|
+
this.__internal__.serial.response.buffer && l(this, a, h).call(this, e), this.__internal__.serial.response.buffer = new Uint8Array(0);
|
|
493
530
|
}, 400);
|
|
494
531
|
}, U = async function() {
|
|
495
532
|
if (this.__internal__.serial.response.length !== null) {
|
|
@@ -497,7 +534,7 @@ a = new WeakSet(), C = function(e) {
|
|
|
497
534
|
const e = [];
|
|
498
535
|
for (const t in this.__internal__.serial.response.buffer)
|
|
499
536
|
e.push(this.__internal__.serial.response.buffer[t].toString(16));
|
|
500
|
-
l(this, a,
|
|
537
|
+
l(this, a, h).call(this, e), this.__internal__.serial.response.buffer = new Uint8Array(0);
|
|
501
538
|
} else if (this.__internal__.serial.response.length < this.__internal__.serial.response.buffer.length) {
|
|
502
539
|
let e = new Uint8Array(0);
|
|
503
540
|
for (let n = 0; n < this.__internal__.serial.response.length; n++)
|
|
@@ -506,7 +543,7 @@ a = new WeakSet(), C = function(e) {
|
|
|
506
543
|
const n = [];
|
|
507
544
|
for (const s in e)
|
|
508
545
|
n.push(e[s].toString(16));
|
|
509
|
-
l(this, a,
|
|
546
|
+
l(this, a, h).call(this, n), this.__internal__.serial.response.buffer = new Uint8Array(0);
|
|
510
547
|
return;
|
|
511
548
|
}
|
|
512
549
|
e = new Uint8Array(0);
|
|
@@ -518,7 +555,7 @@ a = new WeakSet(), C = function(e) {
|
|
|
518
555
|
const n = [];
|
|
519
556
|
for (const s in e)
|
|
520
557
|
n.push(e[s].toString(16));
|
|
521
|
-
l(this, a,
|
|
558
|
+
l(this, a, h).call(this, n), this.__internal__.serial.response.buffer = new Uint8Array(0);
|
|
522
559
|
}
|
|
523
560
|
}
|
|
524
561
|
}
|
|
@@ -537,7 +574,7 @@ a = new WeakSet(), C = function(e) {
|
|
|
537
574
|
t.releaseLock(), this.__internal__.serial.keep_reading = !1, n = !1;
|
|
538
575
|
break;
|
|
539
576
|
}
|
|
540
|
-
l(this, a,
|
|
577
|
+
l(this, a, A).call(this, s), this.__internal__.serial.response.length === null ? await l(this, a, T).call(this) : await l(this, a, U).call(this);
|
|
541
578
|
}
|
|
542
579
|
} catch (n) {
|
|
543
580
|
this.serialErrors(n);
|
|
@@ -580,8 +617,8 @@ a = new WeakSet(), C = function(e) {
|
|
|
580
617
|
});
|
|
581
618
|
});
|
|
582
619
|
}, q = async function() {
|
|
583
|
-
if (!this.__internal__.serial.
|
|
584
|
-
await this.serialConnect();
|
|
620
|
+
if (!l(this, a, g).call(this, this.__internal__.serial.port)) {
|
|
621
|
+
this.__internal__.serial.connected = !1, this.__internal__.aux_port_connector = 0, this.dispatch("serial:disconnected", { error: "Port is closed, not readable or writable." }), c.instance.dispatch("change"), await this.serialConnect();
|
|
585
622
|
return;
|
|
586
623
|
}
|
|
587
624
|
if (this.__internal__.timeout.until_response || this.__internal__.serial.queue.length === 0) return;
|
|
@@ -589,10 +626,10 @@ a = new WeakSet(), C = function(e) {
|
|
|
589
626
|
let t = this.__internal__.time.response_general;
|
|
590
627
|
e.action === "connect" && (t = this.__internal__.time.response_connection), this.__internal__.timeout.until_response = setTimeout(async () => {
|
|
591
628
|
await this.timeout(e.bytes, e.action);
|
|
592
|
-
}, t), this.__internal__.serial.last_action = e.action ?? "unknown", await l(this, a,
|
|
629
|
+
}, t), this.__internal__.serial.last_action = e.action ?? "unknown", await l(this, a, y).call(this, e.bytes), this.dispatch("serial:sent", {
|
|
593
630
|
action: e.action,
|
|
594
631
|
bytes: e.bytes
|
|
595
|
-
}), this.__internal__.auto_response && l(this, a,
|
|
632
|
+
}), this.__internal__.auto_response && l(this, a, h).call(this, ["DD", "DD"], null);
|
|
596
633
|
const n = [...this.__internal__.serial.queue];
|
|
597
634
|
this.__internal__.serial.queue = n.splice(1);
|
|
598
635
|
}, R = function(e = 1) {
|
|
@@ -605,43 +642,8 @@ a = new WeakSet(), C = function(e) {
|
|
|
605
642
|
no_code: 0
|
|
606
643
|
};
|
|
607
644
|
};
|
|
608
|
-
const o = class o extends S {
|
|
609
|
-
static typeError(i) {
|
|
610
|
-
const e = new Error();
|
|
611
|
-
throw e.message = `Type ${i} is not supported`, e.name = "DeviceTypeError", e;
|
|
612
|
-
}
|
|
613
|
-
static registerType(i) {
|
|
614
|
-
typeof o.devices[i] > "u" && (o.devices[i] = {});
|
|
615
|
-
}
|
|
616
|
-
static add(i) {
|
|
617
|
-
const e = i.typeDevice;
|
|
618
|
-
typeof o.devices[e] > "u" && (o.devices[e] = {});
|
|
619
|
-
const t = i.uuid;
|
|
620
|
-
if (typeof o.devices[e] > "u" && o.typeError(e), this.instance.dispatch("change", o.devices), o.devices[e][t])
|
|
621
|
-
throw new Error(`Device with id ${t} already exists`);
|
|
622
|
-
return o.devices[e][t] = i, this.instance.dispatch("change", o.devices), Object.keys(o.devices[e]).indexOf(t);
|
|
623
|
-
}
|
|
624
|
-
static get(i, e) {
|
|
625
|
-
return typeof o.devices[i] > "u" && (o.devices[i] = {}), typeof o.devices[i] > "u" && o.typeError(i), o.devices[i][e];
|
|
626
|
-
}
|
|
627
|
-
static getAll(i = null) {
|
|
628
|
-
return i === null ? o.devices : (typeof o.devices[i] > "u" && o.typeError(i), o.devices[i]);
|
|
629
|
-
}
|
|
630
|
-
static getList() {
|
|
631
|
-
return Object.values(o.devices).map((e) => Object.values(e)).flat();
|
|
632
|
-
}
|
|
633
|
-
static getByNumber(i, e) {
|
|
634
|
-
return typeof o.devices[i] > "u" && o.typeError(i), Object.values(o.devices[i]).find((n) => n.deviceNumber === e) ?? null;
|
|
635
|
-
}
|
|
636
|
-
static getCustom(i, e = 1) {
|
|
637
|
-
return typeof o.devices[i] > "u" && o.typeError(i), Object.values(o.devices[i]).find((n) => n.deviceNumber === e) ?? null;
|
|
638
|
-
}
|
|
639
|
-
};
|
|
640
|
-
h(o, "instance"), h(o, "devices", {});
|
|
641
|
-
let d = o;
|
|
642
|
-
d.instance || (d.instance = new d());
|
|
643
645
|
export {
|
|
644
646
|
z as Core,
|
|
645
|
-
|
|
646
|
-
|
|
647
|
+
c as Devices,
|
|
648
|
+
C as Dispatcher
|
|
647
649
|
};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
(function(_,s){typeof exports=="object"&&typeof module<"u"?s(exports):typeof define=="function"&&define.amd?define(["exports"],s):(_=typeof globalThis<"u"?globalThis:_||self,s(_.WebSerialCore={}))})(this,function(_){"use strict";var V=Object.defineProperty;var C=_=>{throw TypeError(_)};var W=(_,s,u)=>s in _?V(_,s,{enumerable:!0,configurable:!0,writable:!0,value:u}):_[s]=u;var f=(_,s,u)=>W(_,typeof s!="symbol"?s+"":s,u),Q=(_,s,u)=>s.has(_)||C("Cannot "+u);var T=(_,s,u)=>s.has(_)?C("Cannot add the same private member more than once"):s instanceof WeakSet?s.add(_):s.set(_,u);var c=(_,s,u)=>(Q(_,s,"access private method"),u);var a,A,m,h,E,U,D,k,I,L,P,q,M,R,N,O;const s=[];for(let o=0;o<256;++o)s.push((o+256).toString(16).slice(1));function u(o,i=0){return(s[o[i+0]]+s[o[i+1]]+s[o[i+2]]+s[o[i+3]]+"-"+s[o[i+4]]+s[o[i+5]]+"-"+s[o[i+6]]+s[o[i+7]]+"-"+s[o[i+8]]+s[o[i+9]]+"-"+s[o[i+10]]+s[o[i+11]]+s[o[i+12]]+s[o[i+13]]+s[o[i+14]]+s[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 w={randomUUID:typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function B(o,i,e){var n;if(w.randomUUID&&!o)return w.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 v 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 v(e,{detail:t});this.dispatchEvent(n),this.__debug__&&this.dispatchEvent(new v("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]}))}}function x(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 $ 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();T(this,a);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}});e&&(this.serialFilters=e),t&&(this.serialConfigPort=t),n&&c(this,a,N).call(this,n),r&&["number","string"].includes(typeof r)&&(this.listenOnChannel=r),c(this,a,P).call(this),c(this,a,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)}async connect(){return new Promise((e,t)=>{F()||t("Web Serial not supported"),setTimeout(async()=>{await x(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",{});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",{});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,a,E).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),n.__internal__.serial.queue.length>0&&n.dispatch("internal:queue",{})},t.ondisconnect=async()=>{await n.disconnect()},await x(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,a,m).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,a,h).call(this,["DD","DD"],null),await c(this,a,I).call(this)}catch(e){this.serialErrors(e)}}async serialForget(){return await c(this,a,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,a,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(_,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=`
|
|
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 p=Number(e.charCodeAt(n)).toString(16);t.push(p)}return t.join("")}}
|
|
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 p=Number(e.charCodeAt(n)).toString(16);t.push(p)}return t.join("")}}s=new WeakSet,m=function(e){return!!(e&&e.readable&&e.writable)},w=async function(e){const t=this.__internal__.serial.port;if(!t||!t.readable||!t.writable)throw new Error("The port is closed or is not writable");const n=this.stringArrayToUint8Array(e),r=t.writable.getWriter();await r.write(n),r.releaseLock()},d=function(e=[],t=null){if(e&&e.length>0){this.__internal__.serial.connected||(this.dispatch("serial:connected"),h.instance.dispatch("change")),this.__internal__.serial.connected=!0,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 n=[];for(const r in e)n.push(e[r].toString().padStart(2,"0").toLowerCase());if(this.__internal__.serial.response.as==="hex")this.serialMessage(n);else if(this.__internal__.serial.response.as==="uint8")this.serialMessage(this.parseHexToUint8(this.add0x(n)));else if(this.__internal__.serial.response.as==="string")this.serialMessage(this.parseUint8ArrayToString(this.add0x(n)));else{const r=this.stringToArrayBuffer(this.parseUint8ArrayToString(this.add0x(n)));this.serialMessage(r)}}else this.serialCorruptMessage(e,t);this.__internal__.serial.queue.length!==0&&this.dispatch("internal:queue",{})},A=async function(){const e=this.serialFilters,t=await navigator.serial.getPorts({filters:e});return e.length===0?t:t.filter(r=>{const p=r.getInfo();return e.some(C=>p.usbProductId===C.usbProductId&&p.usbVendorId===C.usbVendorId)}).filter(r=>!c(this,s,m).call(this,r))},U=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&&c(this,s,d).call(this,e),this.__internal__.serial.response.buffer=new Uint8Array(0)},400)},k=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));c(this,s,d).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));c(this,s,d).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));c(this,s,d).call(this,n),this.__internal__.serial.response.buffer=new Uint8Array(0)}}}}},I=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:p}=await t.read();if(p){t.releaseLock(),this.__internal__.serial.keep_reading=!1,n=!1;break}c(this,s,U).call(this,r),this.__internal__.serial.response.length===null?await c(this,s,D).call(this):await c(this,s,k).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()},L=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},P=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)})},q=function(){const e=this;this.on("internal:queue",async()=>{var t;await c(t=e,s,R).call(t)}),c(this,s,M).call(this)},M=function(){const e=this;navigator.serial.addEventListener("connect",async()=>{e.isDisconnected&&await e.serialConnect().catch(()=>{})})},R=async function(){if(!c(this,s,m).call(this,this.__internal__.serial.port)){this.__internal__.serial.connected=!1,this.__internal__.aux_port_connector=0,this.dispatch("serial:disconnected",{error:"Port is closed, not readable or writable."}),h.instance.dispatch("change"),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 c(this,s,w).call(this,e.bytes),this.dispatch("serial:sent",{action:e.action,bytes:e.bytes}),this.__internal__.auto_response&&c(this,s,d).call(this,["DD","DD"],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}},_.Core=W,_.Devices=h,_.Dispatcher=y,Object.defineProperty(_,Symbol.toStringTag,{value:"Module"})});
|