webserial-core 1.0.4 → 1.0.5
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 +88 -81
- package/dist/webserial-core.umd.cjs +2 -2
- package/package.json +3 -3
package/dist/webserial-core.js
CHANGED
|
@@ -1,54 +1,54 @@
|
|
|
1
|
-
var
|
|
2
|
-
var
|
|
1
|
+
var O = Object.defineProperty;
|
|
2
|
+
var v = (s) => {
|
|
3
3
|
throw TypeError(s);
|
|
4
4
|
};
|
|
5
|
-
var
|
|
6
|
-
var
|
|
7
|
-
var
|
|
8
|
-
var l = (s, i, e) => (
|
|
5
|
+
var H = (s, i, e) => i in s ? O(s, i, { enumerable: !0, configurable: !0, writable: !0, value: e }) : s[i] = e;
|
|
6
|
+
var p = (s, i, e) => H(s, typeof i != "symbol" ? i + "" : i, e), j = (s, i, e) => i.has(s) || v("Cannot " + e);
|
|
7
|
+
var C = (s, i, e) => i.has(s) ? v("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) => (j(s, i, "access private method"), e);
|
|
9
9
|
const _ = [];
|
|
10
10
|
for (let s = 0; s < 256; ++s)
|
|
11
11
|
_.push((s + 256).toString(16).slice(1));
|
|
12
|
-
function
|
|
12
|
+
function B(s, i = 0) {
|
|
13
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
|
|
16
|
-
const
|
|
17
|
-
function
|
|
18
|
-
if (!
|
|
15
|
+
let b;
|
|
16
|
+
const F = new Uint8Array(16);
|
|
17
|
+
function V() {
|
|
18
|
+
if (!b) {
|
|
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
|
+
b = crypto.getRandomValues.bind(crypto);
|
|
22
22
|
}
|
|
23
|
-
return
|
|
23
|
+
return b(F);
|
|
24
24
|
}
|
|
25
|
-
const
|
|
26
|
-
function
|
|
25
|
+
const W = typeof crypto < "u" && crypto.randomUUID && crypto.randomUUID.bind(crypto), x = { randomUUID: W };
|
|
26
|
+
function Q(s, i, e) {
|
|
27
27
|
var n;
|
|
28
|
-
if (
|
|
29
|
-
return
|
|
28
|
+
if (x.randomUUID && !s)
|
|
29
|
+
return x.randomUUID();
|
|
30
30
|
s = s || {};
|
|
31
|
-
const t = s.random ?? ((n = s.rng) == null ? void 0 : n.call(s)) ??
|
|
31
|
+
const t = s.random ?? ((n = s.rng) == null ? void 0 : n.call(s)) ?? V();
|
|
32
32
|
if (t.length < 16)
|
|
33
33
|
throw new Error("Random bytes length must be >= 16");
|
|
34
|
-
return t[6] = t[6] & 15 | 64, t[8] = t[8] & 63 | 128,
|
|
34
|
+
return t[6] = t[6] & 15 | 64, t[8] = t[8] & 63 | 128, B(t);
|
|
35
35
|
}
|
|
36
|
-
class
|
|
36
|
+
class S extends CustomEvent {
|
|
37
37
|
constructor(i, e) {
|
|
38
38
|
super(i, e);
|
|
39
39
|
}
|
|
40
40
|
}
|
|
41
|
-
class
|
|
41
|
+
class E extends EventTarget {
|
|
42
42
|
constructor() {
|
|
43
43
|
super(...arguments);
|
|
44
|
-
|
|
44
|
+
p(this, "__listeners__", {
|
|
45
45
|
debug: !1
|
|
46
46
|
});
|
|
47
|
-
|
|
47
|
+
p(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 S(e, { detail: t });
|
|
51
|
+
this.dispatchEvent(n), this.__debug__ && this.dispatchEvent(new S("debug", { detail: { type: e, data: t } }));
|
|
52
52
|
}
|
|
53
53
|
dispatchAsync(e, t = null, n = 100) {
|
|
54
54
|
const a = this;
|
|
@@ -72,7 +72,7 @@ class A extends EventTarget {
|
|
|
72
72
|
}));
|
|
73
73
|
}
|
|
74
74
|
}
|
|
75
|
-
const o = class o extends
|
|
75
|
+
const o = class o extends E {
|
|
76
76
|
constructor() {
|
|
77
77
|
super(), ["change"].forEach((e) => {
|
|
78
78
|
this.serialRegisterAvailableListener(e);
|
|
@@ -112,18 +112,18 @@ const o = class o extends A {
|
|
|
112
112
|
return typeof o.devices[i] > "u" && o.typeError(i), Object.values(o.devices[i]).find((n) => n.deviceNumber === e) ?? null;
|
|
113
113
|
}
|
|
114
114
|
};
|
|
115
|
-
|
|
115
|
+
p(o, "instance"), p(o, "devices", {});
|
|
116
116
|
let c = o;
|
|
117
117
|
c.instance || (c.instance = new c());
|
|
118
|
-
function
|
|
118
|
+
function A(s = 100) {
|
|
119
119
|
return new Promise(
|
|
120
120
|
(i) => setTimeout(() => i(), s)
|
|
121
121
|
);
|
|
122
122
|
}
|
|
123
|
-
function
|
|
123
|
+
function z() {
|
|
124
124
|
return "serial" in navigator;
|
|
125
125
|
}
|
|
126
|
-
const
|
|
126
|
+
const y = {
|
|
127
127
|
baudRate: 9600,
|
|
128
128
|
dataBits: 8,
|
|
129
129
|
stopBits: 1,
|
|
@@ -131,22 +131,22 @@ const b = {
|
|
|
131
131
|
bufferSize: 32768,
|
|
132
132
|
flowControl: "none"
|
|
133
133
|
};
|
|
134
|
-
var r,
|
|
135
|
-
class
|
|
134
|
+
var r, f, g, w, u, T, U, k, D, L, P, I, $, q, R, M, N;
|
|
135
|
+
class J extends E {
|
|
136
136
|
constructor({
|
|
137
137
|
filters: e = null,
|
|
138
|
-
config_port: t =
|
|
138
|
+
config_port: t = y,
|
|
139
139
|
no_device: n = 1,
|
|
140
140
|
device_listen_on_channel: a = 1
|
|
141
141
|
} = {
|
|
142
142
|
filters: null,
|
|
143
|
-
config_port:
|
|
143
|
+
config_port: y,
|
|
144
144
|
no_device: 1,
|
|
145
145
|
device_listen_on_channel: 1
|
|
146
146
|
}) {
|
|
147
147
|
super();
|
|
148
|
-
|
|
149
|
-
|
|
148
|
+
C(this, r);
|
|
149
|
+
p(this, "__internal__", {
|
|
150
150
|
auto_response: !1,
|
|
151
151
|
device_number: 1,
|
|
152
152
|
aux_port_connector: 0,
|
|
@@ -163,7 +163,9 @@ class G extends A {
|
|
|
163
163
|
response: {
|
|
164
164
|
length: null,
|
|
165
165
|
buffer: new Uint8Array([]),
|
|
166
|
-
as: "hex"
|
|
166
|
+
as: "hex",
|
|
167
|
+
replacer: /[\n\r]+/g,
|
|
168
|
+
limiter: null
|
|
167
169
|
},
|
|
168
170
|
reader: null,
|
|
169
171
|
input_done: null,
|
|
@@ -175,13 +177,13 @@ class G extends A {
|
|
|
175
177
|
delay_first_connection: 200,
|
|
176
178
|
bytes_connection: null,
|
|
177
179
|
filters: [],
|
|
178
|
-
config_port:
|
|
180
|
+
config_port: y,
|
|
179
181
|
queue: [],
|
|
180
182
|
auto_response: ["DD", "DD"]
|
|
181
183
|
},
|
|
182
184
|
device: {
|
|
183
185
|
type: "unknown",
|
|
184
|
-
id:
|
|
186
|
+
id: Q(),
|
|
185
187
|
listen_on_port: null
|
|
186
188
|
},
|
|
187
189
|
time: {
|
|
@@ -197,7 +199,7 @@ class G extends A {
|
|
|
197
199
|
});
|
|
198
200
|
if (!("serial" in navigator))
|
|
199
201
|
throw new Error("Web Serial not supported");
|
|
200
|
-
e && (this.serialFilters = e), t && (this.serialConfigPort = t), n && l(this, r,
|
|
202
|
+
e && (this.serialFilters = e), t && (this.serialConfigPort = t), n && l(this, r, M).call(this, n), a && ["number", "string"].includes(typeof a) && (this.listenOnChannel = a), l(this, r, I).call(this), l(this, r, $).call(this);
|
|
201
203
|
}
|
|
202
204
|
set listenOnChannel(e) {
|
|
203
205
|
if (typeof e == "string" && (e = parseInt(e)), isNaN(e) || e < 1 || e > 255)
|
|
@@ -223,11 +225,11 @@ class G extends A {
|
|
|
223
225
|
return this.__internal__.serial.config_port;
|
|
224
226
|
}
|
|
225
227
|
get isConnected() {
|
|
226
|
-
const e = this.__internal__.serial.connected, t = l(this, r,
|
|
227
|
-
return e && !t && l(this, r,
|
|
228
|
+
const e = this.__internal__.serial.connected, t = l(this, r, f).call(this, this.__internal__.serial.port);
|
|
229
|
+
return e && !t && l(this, r, g).call(this, { error: "Port is closed, not readable or writable." }), this.__internal__.serial.connected = t, this.__internal__.serial.connected;
|
|
228
230
|
}
|
|
229
231
|
get isDisconnected() {
|
|
230
|
-
const e = this.__internal__.serial.connected, t = l(this, r,
|
|
232
|
+
const e = this.__internal__.serial.connected, t = l(this, r, f).call(this, this.__internal__.serial.port);
|
|
231
233
|
return !e && t && (this.dispatch("serial:connected"), c.$dispatchChange(this)), this.__internal__.serial.connected = t, !this.__internal__.serial.connected;
|
|
232
234
|
}
|
|
233
235
|
get deviceNumber() {
|
|
@@ -250,12 +252,12 @@ class G extends A {
|
|
|
250
252
|
});
|
|
251
253
|
}
|
|
252
254
|
async disconnect(e = null) {
|
|
253
|
-
await this.serialDisconnect(), l(this, r,
|
|
255
|
+
await this.serialDisconnect(), l(this, r, g).call(this, e);
|
|
254
256
|
}
|
|
255
257
|
async connect() {
|
|
256
258
|
return new Promise((e, t) => {
|
|
257
|
-
|
|
258
|
-
await
|
|
259
|
+
z() || t("Web Serial not supported"), setTimeout(async () => {
|
|
260
|
+
await A(499), await this.serialConnect(), this.isConnected ? e(`${this.typeDevice} device ${this.deviceNumber} connected`) : t(`${this.typeDevice} device ${this.deviceNumber} not connected`);
|
|
259
261
|
}, 1);
|
|
260
262
|
});
|
|
261
263
|
}
|
|
@@ -343,7 +345,7 @@ class G extends A {
|
|
|
343
345
|
async serialConnect() {
|
|
344
346
|
try {
|
|
345
347
|
this.dispatch("serial:connecting", {});
|
|
346
|
-
const e = await l(this, r,
|
|
348
|
+
const e = await l(this, r, T).call(this);
|
|
347
349
|
if (e.length > 0)
|
|
348
350
|
await this.serialPortsSaved(e);
|
|
349
351
|
else {
|
|
@@ -361,18 +363,18 @@ class G extends A {
|
|
|
361
363
|
console.log(a), n.dispatch("serial:connected", a), c.$dispatchChange(this), n.__internal__.serial.queue.length > 0 && n.dispatch("internal:queue", {});
|
|
362
364
|
}, t.ondisconnect = async () => {
|
|
363
365
|
await n.disconnect();
|
|
364
|
-
}, await
|
|
366
|
+
}, await A(this.__internal__.serial.delay_first_connection), this.__internal__.timeout.until_response = setTimeout(async () => {
|
|
365
367
|
await n.timeout(n.__internal__.serial.bytes_connection ?? [], "connection:start");
|
|
366
|
-
}, this.__internal__.time.response_connection), this.__internal__.serial.last_action = "connect", await l(this, r,
|
|
368
|
+
}, this.__internal__.time.response_connection), this.__internal__.serial.last_action = "connect", await l(this, r, w).call(this, this.__internal__.serial.bytes_connection ?? []), this.dispatch("serial:sent", {
|
|
367
369
|
action: "connect",
|
|
368
370
|
bytes: this.__internal__.serial.bytes_connection
|
|
369
|
-
}), this.__internal__.auto_response && l(this, r, u).call(this, this.__internal__.serial.auto_response, null), await l(this, r,
|
|
371
|
+
}), this.__internal__.auto_response && l(this, r, u).call(this, this.__internal__.serial.auto_response, null), await l(this, r, L).call(this);
|
|
370
372
|
} catch (e) {
|
|
371
373
|
this.serialErrors(e);
|
|
372
374
|
}
|
|
373
375
|
}
|
|
374
376
|
async serialForget() {
|
|
375
|
-
return await l(this, r,
|
|
377
|
+
return await l(this, r, P).call(this);
|
|
376
378
|
}
|
|
377
379
|
decToHex(e) {
|
|
378
380
|
return typeof e == "string" && (e = parseInt(e, 10)), e.toString(16);
|
|
@@ -429,7 +431,7 @@ class G extends A {
|
|
|
429
431
|
});
|
|
430
432
|
}
|
|
431
433
|
softReload() {
|
|
432
|
-
l(this, r,
|
|
434
|
+
l(this, r, N).call(this), this.dispatch("serial:soft-reload", {});
|
|
433
435
|
}
|
|
434
436
|
async sendConnect() {
|
|
435
437
|
if (!this.__internal__.serial.bytes_connection)
|
|
@@ -476,7 +478,7 @@ class G extends A {
|
|
|
476
478
|
const t = this.stringArrayToUint8Array(e);
|
|
477
479
|
e = this.parseUint8ToHex(t);
|
|
478
480
|
const n = e.map((a) => parseInt(a, 16));
|
|
479
|
-
return String.fromCharCode(...n).replace(
|
|
481
|
+
return this.__internal__.serial.response.replacer ? String.fromCharCode(...n).replace(this.__internal__.serial.response.replacer, "") : String.fromCharCode(...n);
|
|
480
482
|
}
|
|
481
483
|
hexToAscii(e) {
|
|
482
484
|
const t = e.toString();
|
|
@@ -497,14 +499,14 @@ class G extends A {
|
|
|
497
499
|
return this.isConnected;
|
|
498
500
|
}
|
|
499
501
|
}
|
|
500
|
-
r = new WeakSet(),
|
|
502
|
+
r = new WeakSet(), f = function(e) {
|
|
501
503
|
return !!(e && e.readable && e.writable);
|
|
502
|
-
},
|
|
504
|
+
}, g = function(e = null) {
|
|
503
505
|
this.__internal__.serial.connected = !1, this.__internal__.aux_port_connector = 0, this.dispatch("serial:disconnected", e), c.$dispatchChange(this);
|
|
504
|
-
},
|
|
506
|
+
}, w = async function(e) {
|
|
505
507
|
const t = this.__internal__.serial.port;
|
|
506
508
|
if (!t || t && (!t.readable || !t.writable))
|
|
507
|
-
throw l(this, r,
|
|
509
|
+
throw l(this, r, g).call(this, { error: "Port is closed, not readable or writable." }), new Error("The port is closed or is not readable/writable");
|
|
508
510
|
const n = this.stringArrayToUint8Array(e);
|
|
509
511
|
if (t.writable === null) return;
|
|
510
512
|
const a = t.writable.getWriter();
|
|
@@ -512,7 +514,7 @@ r = new WeakSet(), p = function(e) {
|
|
|
512
514
|
}, u = function(e = [], t = null) {
|
|
513
515
|
if (e && e.length > 0) {
|
|
514
516
|
const n = this.__internal__.serial.connected;
|
|
515
|
-
this.__internal__.serial.connected = l(this, r,
|
|
517
|
+
this.__internal__.serial.connected = l(this, r, f).call(this, this.__internal__.serial.port), c.$dispatchChange(this), !n && this.__internal__.serial.connected && this.dispatch("serial:connected"), 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
518
|
const a = [];
|
|
517
519
|
for (const h in e)
|
|
518
520
|
a.push(e[h].toString().padStart(2, "0").toLowerCase());
|
|
@@ -521,7 +523,12 @@ r = new WeakSet(), p = function(e) {
|
|
|
521
523
|
else if (this.__internal__.serial.response.as === "uint8")
|
|
522
524
|
this.serialMessage(this.parseHexToUint8(this.add0x(a)));
|
|
523
525
|
else if (this.__internal__.serial.response.as === "string")
|
|
524
|
-
|
|
526
|
+
if (this.__internal__.serial.response.limiter !== null) {
|
|
527
|
+
const d = this.parseUint8ArrayToString(this.add0x(a)).split(this.__internal__.serial.response.limiter);
|
|
528
|
+
for (const m in d)
|
|
529
|
+
d[m] && this.serialMessage(d[m]);
|
|
530
|
+
} else
|
|
531
|
+
this.serialMessage(this.parseUint8ArrayToString(this.add0x(a)));
|
|
525
532
|
else {
|
|
526
533
|
const h = this.stringToArrayBuffer(
|
|
527
534
|
this.parseUint8ArrayToString(this.add0x(a))
|
|
@@ -531,25 +538,25 @@ r = new WeakSet(), p = function(e) {
|
|
|
531
538
|
} else
|
|
532
539
|
this.serialCorruptMessage(e, t);
|
|
533
540
|
this.__internal__.serial.queue.length !== 0 && this.dispatch("internal:queue", {});
|
|
534
|
-
},
|
|
541
|
+
}, T = async function() {
|
|
535
542
|
const e = this.serialFilters, t = await navigator.serial.getPorts({ filters: e });
|
|
536
543
|
return e.length === 0 ? t : t.filter((a) => {
|
|
537
544
|
const h = a.getInfo();
|
|
538
|
-
return e.some((
|
|
539
|
-
}).filter((a) => !l(this, r,
|
|
540
|
-
},
|
|
545
|
+
return e.some((d) => h.usbProductId === d.usbProductId && h.usbVendorId === d.usbVendorId);
|
|
546
|
+
}).filter((a) => !l(this, r, f).call(this, a));
|
|
547
|
+
}, U = function(e) {
|
|
541
548
|
if (e) {
|
|
542
549
|
const t = this.__internal__.serial.response.buffer, n = new Uint8Array(t.length + e.byteLength);
|
|
543
550
|
n.set(t, 0), n.set(new Uint8Array(e), t.length), this.__internal__.serial.response.buffer = n;
|
|
544
551
|
}
|
|
545
|
-
},
|
|
552
|
+
}, k = async function() {
|
|
546
553
|
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(() => {
|
|
547
554
|
const e = [];
|
|
548
555
|
for (const t in this.__internal__.serial.response.buffer)
|
|
549
556
|
e.push(this.__internal__.serial.response.buffer[t].toString(16));
|
|
550
557
|
this.__internal__.serial.response.buffer && l(this, r, u).call(this, e), this.__internal__.serial.response.buffer = new Uint8Array(0);
|
|
551
558
|
}, 400);
|
|
552
|
-
},
|
|
559
|
+
}, D = async function() {
|
|
553
560
|
if (this.__internal__.serial.response.length !== null) {
|
|
554
561
|
if (this.__internal__.serial.response.length === this.__internal__.serial.response.buffer.length) {
|
|
555
562
|
const e = [];
|
|
@@ -581,7 +588,7 @@ r = new WeakSet(), p = function(e) {
|
|
|
581
588
|
}
|
|
582
589
|
}
|
|
583
590
|
}
|
|
584
|
-
},
|
|
591
|
+
}, L = async function() {
|
|
585
592
|
const e = this.__internal__.serial.port;
|
|
586
593
|
if (!e || !e.readable) throw new Error("Port is not readable");
|
|
587
594
|
for (; e.readable && this.__internal__.serial.keep_reading; ) {
|
|
@@ -595,7 +602,7 @@ r = new WeakSet(), p = function(e) {
|
|
|
595
602
|
t.releaseLock(), this.__internal__.serial.keep_reading = !1, n = !1;
|
|
596
603
|
break;
|
|
597
604
|
}
|
|
598
|
-
l(this, r,
|
|
605
|
+
l(this, r, U).call(this, a), this.__internal__.serial.response.length === null ? await l(this, r, k).call(this) : await l(this, r, D).call(this);
|
|
599
606
|
}
|
|
600
607
|
} catch (n) {
|
|
601
608
|
this.serialErrors(n);
|
|
@@ -604,9 +611,9 @@ r = new WeakSet(), p = function(e) {
|
|
|
604
611
|
}
|
|
605
612
|
}
|
|
606
613
|
this.__internal__.serial.keep_reading = !0, this.__internal__.serial.port && await this.__internal__.serial.port.close();
|
|
607
|
-
},
|
|
614
|
+
}, P = async function() {
|
|
608
615
|
return typeof window > "u" ? !1 : "serial" in navigator && "forget" in SerialPort.prototype && this.__internal__.serial.port ? (await this.__internal__.serial.port.forget(), !0) : !1;
|
|
609
|
-
},
|
|
616
|
+
}, I = function() {
|
|
610
617
|
[
|
|
611
618
|
"serial:connected",
|
|
612
619
|
"serial:connecting",
|
|
@@ -625,21 +632,21 @@ r = new WeakSet(), p = function(e) {
|
|
|
625
632
|
].forEach((t) => {
|
|
626
633
|
this.serialRegisterAvailableListener(t);
|
|
627
634
|
});
|
|
628
|
-
},
|
|
635
|
+
}, $ = function() {
|
|
629
636
|
const e = this;
|
|
630
637
|
this.on("internal:queue", async () => {
|
|
631
638
|
var t;
|
|
632
|
-
await l(t = e, r,
|
|
633
|
-
}), l(this, r,
|
|
634
|
-
},
|
|
639
|
+
await l(t = e, r, R).call(t);
|
|
640
|
+
}), l(this, r, q).call(this);
|
|
641
|
+
}, q = function() {
|
|
635
642
|
const e = this;
|
|
636
643
|
navigator.serial.addEventListener("connect", async () => {
|
|
637
644
|
e.isDisconnected && await e.serialConnect().catch(() => {
|
|
638
645
|
});
|
|
639
646
|
});
|
|
640
|
-
},
|
|
641
|
-
if (!l(this, r,
|
|
642
|
-
l(this, r,
|
|
647
|
+
}, R = async function() {
|
|
648
|
+
if (!l(this, r, f).call(this, this.__internal__.serial.port)) {
|
|
649
|
+
l(this, r, g).call(this, { error: "Port is closed, not readable or writable." }), await this.serialConnect();
|
|
643
650
|
return;
|
|
644
651
|
}
|
|
645
652
|
if (this.__internal__.timeout.until_response || this.__internal__.serial.queue.length === 0) return;
|
|
@@ -647,15 +654,15 @@ r = new WeakSet(), p = function(e) {
|
|
|
647
654
|
let t = this.__internal__.time.response_general;
|
|
648
655
|
e.action === "connect" && (t = this.__internal__.time.response_connection), this.__internal__.timeout.until_response = setTimeout(async () => {
|
|
649
656
|
await this.timeout(e.bytes, e.action);
|
|
650
|
-
}, t), this.__internal__.serial.last_action = e.action ?? "unknown", await l(this, r,
|
|
657
|
+
}, t), this.__internal__.serial.last_action = e.action ?? "unknown", await l(this, r, w).call(this, e.bytes), this.dispatch("serial:sent", {
|
|
651
658
|
action: e.action,
|
|
652
659
|
bytes: e.bytes
|
|
653
660
|
}), this.__internal__.auto_response && l(this, r, u).call(this, this.__internal__.serial.auto_response, null);
|
|
654
661
|
const n = [...this.__internal__.serial.queue];
|
|
655
662
|
this.__internal__.serial.queue = n.splice(1);
|
|
656
|
-
},
|
|
663
|
+
}, M = function(e = 1) {
|
|
657
664
|
this.__internal__.device_number = e, this.__internal__.serial.bytes_connection = this.serialSetConnectionConstant(e);
|
|
658
|
-
},
|
|
665
|
+
}, N = function() {
|
|
659
666
|
this.__internal__.last_error = {
|
|
660
667
|
message: null,
|
|
661
668
|
action: null,
|
|
@@ -664,7 +671,7 @@ r = new WeakSet(), p = function(e) {
|
|
|
664
671
|
};
|
|
665
672
|
};
|
|
666
673
|
export {
|
|
667
|
-
|
|
674
|
+
J as Core,
|
|
668
675
|
c as Devices,
|
|
669
|
-
|
|
676
|
+
E as Dispatcher
|
|
670
677
|
};
|
|
@@ -1,4 +1,4 @@
|
|
|
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,u)=>a in c?V(c,a,{enumerable:!0,configurable:!0,writable:!0,value:u}):c[a]=u;var f=(c,a,u)=>Q(c,typeof a!="symbol"?a+"":a,u),z=(c,a,u)=>a.has(c)||T("Cannot "+u);var E=(c,a,u)=>a.has(c)?T("Cannot add the same private member more than once"):a instanceof WeakSet?a.add(c):a.set(c,u);var _=(c,a,u)=>(z(c,a,"access private method"),u);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 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 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,u(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 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 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,$).call(this),_(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(){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"),h.$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",{}),h.$dispatchChange(this)):t==="connection:start"&&(await this.serialDisconnect(),this.__internal__.serial.connected=!1,this.__internal__.aux_port_connector+=1,h.$dispatchChange(this),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,h.$dispatchChange(this)}}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",{}),h.$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",{}),h.$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),h.$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=`
|
|
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 Q=Object.defineProperty;var E=c=>{throw TypeError(c)};var z=(c,a,u)=>a in c?Q(c,a,{enumerable:!0,configurable:!0,writable:!0,value:u}):c[a]=u;var g=(c,a,u)=>z(c,typeof a!="symbol"?a+"":a,u),G=(c,a,u)=>a.has(c)||E("Cannot "+u);var U=(c,a,u)=>a.has(c)?E("Cannot add the same private member more than once"):a instanceof WeakSet?a.add(c):a.set(c,u);var _=(c,a,u)=>(G(c,a,"access private method"),u);var s,b,y,C,p,k,D,L,P,I,$,q,M,R,N,O,H;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 m;const j=new Uint8Array(16);function B(){if(!m){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");m=crypto.getRandomValues.bind(crypto)}return m(j)}const x={randomUUID:typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function F(o,i,e){var n;if(x.randomUUID&&!o)return x.randomUUID();o=o||{};const t=o.random??((n=o.rng)==null?void 0:n.call(o))??B();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 S extends CustomEvent{constructor(i,e){super(i,e)}}class w extends EventTarget{constructor(){super(...arguments);g(this,"__listeners__",{debug:!1});g(this,"__debug__",!1)}dispatch(e,t=null){const n=new S(e,{detail:t});this.dispatchEvent(n),this.__debug__&&this.dispatchEvent(new S("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}};g(l,"instance"),g(l,"devices",{});let h=l;h.instance||(h.instance=new h);function A(o=100){return new Promise(i=>setTimeout(()=>i(),o))}function W(){return"serial"in navigator}const v={baudRate:9600,dataBits:8,stopBits:1,parity:"none",bufferSize:32768,flowControl:"none"};class V extends w{constructor({filters:e=null,config_port:t=v,no_device:n=1,device_listen_on_channel:r=1}={filters:null,config_port:v,no_device:1,device_listen_on_channel:1}){super();U(this,s);g(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",replacer:/[\n\r]+/g,limiter:null},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:v,queue:[],auto_response:["DD","DD"]},device:{type:"unknown",id:F(),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,O).call(this,n),r&&["number","string"].includes(typeof r)&&(this.listenOnChannel=r),_(this,s,q).call(this),_(this,s,M).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,b).call(this,this.__internal__.serial.port);return e&&!t&&_(this,s,y).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,b).call(this,this.__internal__.serial.port);return!e&&t&&(this.dispatch("serial:connected"),h.$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",{}),h.$dispatchChange(this)):t==="connection:start"&&(await this.serialDisconnect(),this.__internal__.serial.connected=!1,this.__internal__.aux_port_connector+=1,h.$dispatchChange(this),await this.serialConnect()),this.dispatch("serial:timeout",{...this.__internal__.last_error,bytes:e,action:t})}async disconnect(e=null){await this.serialDisconnect(),_(this,s,y).call(this,e)}async connect(){return new Promise((e,t)=>{W()||t("Web Serial not supported"),setTimeout(async()=>{await A(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,h.$dispatchChange(this)}}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",{}),h.$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",{}),h.$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,k).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),h.$dispatchChange(this),n.__internal__.serial.queue.length>0&&n.dispatch("internal:queue",{})},t.ondisconnect=async()=>{await n.disconnect()},await A(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,C).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,I).call(this)}catch(e){this.serialErrors(e)}}async serialForget(){return await _(this,s,$).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,H).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(
|
|
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 this.__internal__.serial.response.replacer?String.fromCharCode(...n).replace(this.__internal__.serial.response.replacer,""):String.fromCharCode(...n)}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,b=function(e){return!!(e&&e.readable&&e.writable)},y=function(e=null){this.__internal__.serial.connected=!1,this.__internal__.aux_port_connector=0,this.dispatch("serial:disconnected",e),h.$dispatchChange(this)},C=async function(e){const t=this.__internal__.serial.port;if(!t||t&&(!t.readable||!t.writable))throw _(this,s,y).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,b).call(this,this.__internal__.serial.port),h.$dispatchChange(this),!n&&this.__internal__.serial.connected&&this.dispatch("serial:connected"),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")if(this.__internal__.serial.response.limiter!==null){const f=this.parseUint8ArrayToString(this.add0x(r)).split(this.__internal__.serial.response.limiter);for(const T in f)f[T]&&this.serialMessage(f[T])}else 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",{})},k=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(f=>d.usbProductId===f.usbProductId&&d.usbVendorId===f.usbVendorId)}).filter(r=>!_(this,s,b).call(this,r))},D=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}},L=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)},P=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)}}}}},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:d}=await t.read();if(d){t.releaseLock(),this.__internal__.serial.keep_reading=!1,n=!1;break}_(this,s,D).call(this,r),this.__internal__.serial.response.length===null?await _(this,s,L).call(this):await _(this,s,P).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()},$=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)})},M=function(){const e=this;this.on("internal:queue",async()=>{var t;await _(t=e,s,N).call(t)}),_(this,s,R).call(this)},R=function(){const e=this;navigator.serial.addEventListener("connect",async()=>{e.isDisconnected&&await e.serialConnect().catch(()=>{})})},N=async function(){if(!_(this,s,b).call(this,this.__internal__.serial.port)){_(this,s,y).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,C).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)},O=function(e=1){this.__internal__.device_number=e,this.__internal__.serial.bytes_connection=this.serialSetConnectionConstant(e)},H=function(){this.__internal__.last_error={message:null,action:null,code:null,no_code:0}},c.Core=V,c.Devices=h,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.5",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
7
7
|
"author": "danidoble",
|
|
@@ -47,9 +47,9 @@
|
|
|
47
47
|
"puppeteer": "^24.4.0",
|
|
48
48
|
"semantic-release": "^24.2.3",
|
|
49
49
|
"typescript": "~5.7.3",
|
|
50
|
-
"typescript-eslint": "^8.26.
|
|
50
|
+
"typescript-eslint": "^8.26.1",
|
|
51
51
|
"uuid": "^11.1.0",
|
|
52
|
-
"vite": "^6.2.
|
|
52
|
+
"vite": "^6.2.2"
|
|
53
53
|
},
|
|
54
54
|
"publishConfig": {
|
|
55
55
|
"access": "public"
|