webserial-core 1.2.0 → 2.0.0-dev.1

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.
Files changed (43) hide show
  1. package/{LICENSE → LICENSE.md} +1 -1
  2. package/README.md +142 -287
  3. package/dist/adapters/web-bluetooth/WebBluetoothProvider.d.ts +19 -0
  4. package/dist/adapters/web-bluetooth/index.d.ts +6 -0
  5. package/dist/adapters/web-usb/WebUsbProvider.d.ts +127 -0
  6. package/dist/adapters/web-usb/index.d.ts +6 -0
  7. package/dist/adapters/websocket/WebSocketProvider.d.ts +20 -0
  8. package/dist/adapters/websocket/index.d.ts +6 -0
  9. package/dist/core/AbstractSerialDevice.d.ts +108 -0
  10. package/dist/core/SerialEventEmitter.d.ts +37 -0
  11. package/dist/core/SerialRegistry.d.ts +53 -0
  12. package/dist/errors/index.d.ts +40 -0
  13. package/dist/index.d.ts +10 -0
  14. package/dist/parsers/DelimiterParser.d.ts +22 -0
  15. package/dist/parsers/FixedLengthParser.d.ts +23 -0
  16. package/dist/parsers/RawParser.d.ts +22 -0
  17. package/dist/parsers/index.d.ts +7 -0
  18. package/dist/queue/CommandQueue.d.ts +98 -0
  19. package/dist/types/index.d.ts +124 -0
  20. package/dist/webserial-core.cjs +1 -0
  21. package/dist/webserial-core.mjs +853 -0
  22. package/dist/webserial-core.umd.js +1 -0
  23. package/package.json +62 -68
  24. package/dist/types/Core.d.ts +0 -268
  25. package/dist/types/Core.d.ts.map +0 -1
  26. package/dist/types/Devices.d.ts +0 -62
  27. package/dist/types/Devices.d.ts.map +0 -1
  28. package/dist/types/Dispatcher.d.ts +0 -98
  29. package/dist/types/Dispatcher.d.ts.map +0 -1
  30. package/dist/types/SerialError.d.ts +0 -61
  31. package/dist/types/SerialError.d.ts.map +0 -1
  32. package/dist/types/SerialEvent.d.ts +0 -4
  33. package/dist/types/SerialEvent.d.ts.map +0 -1
  34. package/dist/types/Socket.d.ts +0 -29
  35. package/dist/types/Socket.d.ts.map +0 -1
  36. package/dist/types/main.d.ts +0 -15
  37. package/dist/types/main.d.ts.map +0 -1
  38. package/dist/types/utils.d.ts +0 -3
  39. package/dist/types/utils.d.ts.map +0 -1
  40. package/dist/webserial-core.js +0 -1236
  41. package/dist/webserial-core.js.map +0 -1
  42. package/dist/webserial-core.umd.cjs +0 -5
  43. package/dist/webserial-core.umd.cjs.map +0 -1
@@ -1,1236 +0,0 @@
1
- import { io as b } from "socket.io-client";
2
- class g extends CustomEvent {
3
- constructor(e, t) {
4
- super(e, t);
5
- }
6
- }
7
- class y extends EventTarget {
8
- __listeners__ = {
9
- debug: !1
10
- };
11
- __debug__ = !1;
12
- __listenersCallbacks__ = [];
13
- /**
14
- * Dispatches an event with the specified type and data
15
- * @param type - The event type to dispatch
16
- * @param data - Optional data to attach to the event
17
- * @example
18
- * ```typescript
19
- * dispatcher.dispatch('connected', { port: 'COM3' });
20
- * ```
21
- */
22
- dispatch(e, t = null) {
23
- const n = new g(e, { detail: t });
24
- this.dispatchEvent(n), this.__debug__ && this.dispatchEvent(new g("debug", { detail: { type: e, data: t } }));
25
- }
26
- /**
27
- * Dispatches an event asynchronously after a specified delay
28
- * @param type - The event type to dispatch
29
- * @param data - Optional data to attach to the event
30
- * @param ms - Delay in milliseconds (default: 100)
31
- * @example
32
- * ```typescript
33
- * dispatcher.dispatchAsync('timeout', { reason: 'no response' }, 500);
34
- * ```
35
- */
36
- dispatchAsync(e, t = null, n = 100) {
37
- const i = this;
38
- setTimeout(() => {
39
- i.dispatch(e, t);
40
- }, n);
41
- }
42
- /**
43
- * Registers an event listener for the specified event type
44
- * @param type - The event type to listen to
45
- * @param callback - The callback function to execute when the event is triggered
46
- * @example
47
- * ```typescript
48
- * dispatcher.on('connected', (event) => {
49
- * console.log('Device connected', event.detail);
50
- * });
51
- * ```
52
- */
53
- on(e, t) {
54
- typeof this.__listeners__[e] < "u" && !this.__listeners__[e] && (this.__listeners__[e] = !0), this.__listenersCallbacks__.push({ key: e, callback: t }), this.addEventListener(e, t);
55
- }
56
- /**
57
- * Removes an event listener for the specified event type
58
- * @param type - The event type to stop listening to
59
- * @param callback - The callback function to remove
60
- * @example
61
- * ```typescript
62
- * const handler = (event) => console.log(event.detail);
63
- * dispatcher.on('data', handler);
64
- * dispatcher.off('data', handler);
65
- * ```
66
- */
67
- off(e, t) {
68
- this.__listenersCallbacks__ = this.__listenersCallbacks__.filter((n) => !(n.key === e && n.callback === t)), this.removeEventListener(e, t);
69
- }
70
- /**
71
- * Registers an available listener type for tracking
72
- * @param type - The event type to register
73
- * @internal
74
- */
75
- serialRegisterAvailableListener(e) {
76
- this.__listeners__[e] || (this.__listeners__[e] = !1);
77
- }
78
- /**
79
- * Gets the list of all available listeners and their state
80
- * @returns Array of listener objects with type and listening status
81
- * @example
82
- * ```typescript
83
- * const listeners = dispatcher.availableListeners;
84
- * console.log(listeners); // [{ type: 'connected', listening: true }, ...]
85
- * ```
86
- */
87
- get availableListeners() {
88
- return Object.keys(this.__listeners__).sort().map((t) => ({
89
- type: t,
90
- listening: this.__listeners__[t]
91
- }));
92
- }
93
- /**
94
- * Removes all event listeners except internal ones (like queue listeners)
95
- * Resets all listener states to false
96
- * @example
97
- * ```typescript
98
- * dispatcher.removeAllListeners();
99
- * ```
100
- */
101
- removeAllListeners() {
102
- for (const e of this.__listenersCallbacks__)
103
- ["internal:queue"].includes(e.key) || (this.__listenersCallbacks__ = this.__listenersCallbacks__.filter((t) => !(t.key === e.key && t.callback === e.callback)), this.removeEventListener(e.key, e.callback));
104
- for (const e of Object.keys(this.__listeners__))
105
- this.__listeners__[e] = !1;
106
- }
107
- }
108
- class s extends y {
109
- static instance;
110
- static devices = {};
111
- constructor() {
112
- super(), ["change"].forEach((t) => {
113
- this.serialRegisterAvailableListener(t);
114
- });
115
- }
116
- static $dispatchChange(e = null) {
117
- e && e.$checkAndDispatchConnection(), s.instance.dispatch("change", { devices: s.devices, dispatcher: e });
118
- }
119
- static typeError(e) {
120
- const t = new Error();
121
- throw t.message = `Type ${e} is not supported`, t.name = "DeviceTypeError", t;
122
- }
123
- /**
124
- * Registers a new device type in the registry
125
- * @param type - The type name of the device (e.g., 'arduino', 'esp32')
126
- * @internal
127
- */
128
- static registerType(e) {
129
- typeof s.devices[e] > "u" && (s.devices = { ...s.devices, [e]: {} });
130
- }
131
- /**
132
- * Adds a device to the registry
133
- * @param device - The Core device instance to add
134
- * @returns The index of the device in its type registry
135
- * @throws {Error} If device with the same ID already exists
136
- * @example
137
- * ```typescript
138
- * const arduino = new Arduino();
139
- * Devices.add(arduino);
140
- * ```
141
- */
142
- static add(e) {
143
- const t = e.typeDevice;
144
- typeof s.devices[t] > "u" && s.registerType(t);
145
- const n = e.uuid;
146
- if (typeof s.devices[t] > "u" && s.typeError(t), s.devices[t][n])
147
- throw new Error(`Device with id ${n} already exists`);
148
- return s.devices[t][n] = e, s.$dispatchChange(e), Object.keys(s.devices[t]).indexOf(n);
149
- }
150
- /**
151
- * Gets a specific device by type and UUID
152
- * @param type - The device type
153
- * @param id - The device UUID
154
- * @returns The device instance
155
- * @throws {Error} If the device type is not supported
156
- * @example
157
- * ```typescript
158
- * const device = Devices.get('arduino', 'uuid-123');
159
- * ```
160
- */
161
- static get(e, t) {
162
- return typeof s.devices[e] > "u" && s.registerType(e), typeof s.devices[e] > "u" && s.typeError(e), s.devices[e][t];
163
- }
164
- static getAll(e = null) {
165
- return e === null ? s.devices : (typeof s.devices[e] > "u" && s.typeError(e), s.devices[e]);
166
- }
167
- static getList() {
168
- return Object.values(s.devices).map((t) => Object.values(t)).flat();
169
- }
170
- static getByNumber(e, t) {
171
- return typeof s.devices[e] > "u" && s.typeError(e), Object.values(s.devices[e]).find((i) => i.deviceNumber === t) ?? null;
172
- }
173
- static getCustom(e, t = 1) {
174
- return typeof s.devices[e] > "u" && s.typeError(e), Object.values(s.devices[e]).find((i) => i.deviceNumber === t) ?? null;
175
- }
176
- static async connectToAll() {
177
- const e = s.getList();
178
- for (const t of e)
179
- t.isConnected || await t.connect().catch(console.warn);
180
- return Promise.resolve(s.areAllConnected());
181
- }
182
- static async disconnectAll() {
183
- const e = s.getList();
184
- for (const t of e)
185
- t.isDisconnected || await t.disconnect().catch(console.warn);
186
- return Promise.resolve(s.areAllDisconnected());
187
- }
188
- static async areAllConnected() {
189
- const e = s.getList();
190
- for (const t of e)
191
- if (!t.isConnected) return Promise.resolve(!1);
192
- return Promise.resolve(!0);
193
- }
194
- static async areAllDisconnected() {
195
- const e = s.getList();
196
- for (const t of e)
197
- if (!t.isDisconnected) return Promise.resolve(!1);
198
- return Promise.resolve(!0);
199
- }
200
- static async getAllConnected() {
201
- const e = s.getList();
202
- return Promise.resolve(e.filter((t) => t.isConnected));
203
- }
204
- static async getAllDisconnected() {
205
- const e = s.getList();
206
- return Promise.resolve(e.filter((t) => t.isDisconnected));
207
- }
208
- }
209
- s.instance || (s.instance = new s());
210
- function m(a = 100) {
211
- return new Promise(
212
- (e) => setTimeout(() => e(), a)
213
- );
214
- }
215
- class C {
216
- #i = "http://localhost:3001";
217
- #t = {
218
- transports: ["websocket"]
219
- };
220
- #e = null;
221
- #s = !1;
222
- #a = !1;
223
- #n;
224
- constructor(e, t) {
225
- e && (this.#i = e), t && (this.#t = { ...this.#t, ...t }), this.#n = {
226
- onResponse: this.onResponse.bind(this),
227
- onDisconnect: () => {
228
- this.#s = !1, window.dispatchEvent(new Event("serial:socket:disconnected"));
229
- },
230
- onConnect: () => {
231
- this.#s = !0, window.dispatchEvent(new Event("serial:socket:connected"));
232
- },
233
- onConnectError: (n) => {
234
- console.debug("Socket connection error", n), this.#s = !1, window.dispatchEvent(new Event("serial:socket:disconnected"));
235
- }
236
- };
237
- }
238
- set uri(e) {
239
- const t = new URL(e);
240
- if (!["http:", "https:", "ws:", "wss:"].includes(t.protocol))
241
- throw new Error("URI must start with http://, https://, ws://, or wss://");
242
- this.#i = e;
243
- }
244
- get uri() {
245
- return this.#i;
246
- }
247
- set options(e) {
248
- if (typeof e != "object")
249
- throw new Error("Options must be an object");
250
- this.#t = e;
251
- }
252
- get options() {
253
- return this.#t;
254
- }
255
- get socketId() {
256
- return this.#e && this.#e.id ? this.#e.id : null;
257
- }
258
- configure(e, t) {
259
- if (this.#a)
260
- throw new Error("Cannot configure socket after it has been initialized. Call configure() before prepare().");
261
- e && (this.uri = e), t && (this.#t = { ...this.#t, ...t });
262
- }
263
- disconnect() {
264
- this.#e && (this.#e.off("response", this.#n.onResponse), this.#e.off("disconnect", this.#n.onDisconnect), this.#e.off("connect", this.#n.onConnect), this.#e.off("connect_error", this.#n.onConnectError), this.#e.disconnect(), this.#e = null, this.#a = !1), this.#s = !1;
265
- }
266
- prepare() {
267
- this.#s || this.#a || (this.#e = b(this.#i, this.#t), this.#a = !0, this.#e.on("disconnect", this.#n.onDisconnect), this.#e.on("response", this.#n.onResponse), this.#e.on("connect", this.#n.onConnect), this.#e.on("connect_error", this.#n.onConnectError));
268
- }
269
- connectDevice(e) {
270
- if (!this.#e)
271
- throw new Error("Socket not connected. Call prepare() first.");
272
- this.#e.emit("connectDevice", { config: e });
273
- }
274
- disconnectDevice(e) {
275
- if (!this.#e)
276
- throw new Error("Socket not connected. Call prepare() first.");
277
- this.#e.emit("disconnectDevice", { config: e });
278
- }
279
- disconnectAllDevices() {
280
- if (!this.#e)
281
- throw new Error("Socket not connected. Call prepare() first.");
282
- this.#e.emit("disconnectAll");
283
- }
284
- write(e) {
285
- if (!this.#e)
286
- throw new Error("Socket not connected. Call prepare() first.");
287
- this.#e.emit("cmd", e);
288
- }
289
- onResponse(e) {
290
- let t = s.get(e.name, e.uuid);
291
- t || (t = s.getByNumber(e.name, e.deviceNumber)), t && t.socketResponse(e);
292
- }
293
- isConnected() {
294
- return this.#s;
295
- }
296
- isDisconnected() {
297
- return !this.#s;
298
- }
299
- }
300
- const c = new C(), f = {
301
- baudRate: 9600,
302
- dataBits: 8,
303
- stopBits: 1,
304
- parity: "none",
305
- bufferSize: 32768,
306
- flowControl: "none"
307
- };
308
- class T extends y {
309
- __internal__ = {
310
- bypassSerialBytesConnection: !1,
311
- auto_response: !1,
312
- device_number: 1,
313
- aux_port_connector: 0,
314
- last_error: {
315
- message: null,
316
- action: null,
317
- code: null,
318
- no_code: 0
319
- },
320
- serial: {
321
- transformStream: !1,
322
- socket: !1,
323
- portInfo: {
324
- path: null,
325
- vendorId: null,
326
- productId: null,
327
- parser: {
328
- name: "inter-byte-timeout",
329
- interval: 50
330
- }
331
- },
332
- aux_connecting: "idle",
333
- connecting: !1,
334
- connected: !1,
335
- port: null,
336
- last_action: null,
337
- response: {
338
- length: null,
339
- buffer: new Uint8Array([]),
340
- as: "uint8",
341
- replacer: /[\n\r]+/g,
342
- limiter: null,
343
- prefixLimiter: !1,
344
- sufixLimiter: !0,
345
- delimited: !1
346
- },
347
- reader: null,
348
- input_done: null,
349
- output_done: null,
350
- input_stream: null,
351
- output_stream: null,
352
- keep_reading: !0,
353
- time_until_send_bytes: void 0,
354
- delay_first_connection: 200,
355
- bytes_connection: null,
356
- filters: [],
357
- config_port: f,
358
- queue: [],
359
- running_queue: !1,
360
- auto_response: null,
361
- free_timeout_ms: 50,
362
- // In previous versions 400 was used
363
- useRTSCTS: !1
364
- // Use RTS/CTS flow control
365
- },
366
- device: {
367
- type: "unknown",
368
- id: window.crypto.randomUUID(),
369
- listen_on_port: null
370
- },
371
- time: {
372
- response_connection: 500,
373
- response_engines: 2e3,
374
- response_general: 2e3
375
- },
376
- timeout: {
377
- until_response: 0
378
- },
379
- interval: {
380
- reconnection: 0
381
- }
382
- };
383
- #i = null;
384
- constructor({
385
- filters: e = null,
386
- config_port: t = f,
387
- no_device: n = 1,
388
- device_listen_on_channel: i = 1,
389
- bypassSerialBytesConnection: o = !1,
390
- socket: r = !1,
391
- transformStream: h = !1
392
- } = {
393
- filters: null,
394
- config_port: f,
395
- no_device: 1,
396
- device_listen_on_channel: 1,
397
- bypassSerialBytesConnection: !1,
398
- socket: !1,
399
- transformStream: !1
400
- }) {
401
- if (super(), !("serial" in navigator))
402
- throw new Error("Web Serial not supported");
403
- e && (this.serialFilters = e), t && (this.serialConfigPort = t), o && (this.__internal__.bypassSerialBytesConnection = o), n && this.#C(n), i && ["number", "string"].includes(typeof i) && (this.listenOnChannel = i), this.__internal__.serial.socket = r, this.__internal__.serial.transformStream = h, this.#m(), this.#y();
404
- }
405
- set listenOnChannel(e) {
406
- if (typeof e == "string" && (e = parseInt(e)), isNaN(e) || e < 1 || e > 255)
407
- throw new Error("Invalid port number");
408
- this.__internal__.device.listen_on_port = e, !this.__internal__.bypassSerialBytesConnection && (this.__internal__.serial.bytes_connection = this.serialSetConnectionConstant(e));
409
- }
410
- get lastAction() {
411
- return this.__internal__.serial.last_action;
412
- }
413
- get listenOnChannel() {
414
- return this.__internal__.device.listen_on_port ?? 1;
415
- }
416
- set serialFilters(e) {
417
- if (this.isConnected) throw new Error("Cannot change serial filters while connected");
418
- this.__internal__.serial.filters = e;
419
- }
420
- get serialFilters() {
421
- return this.__internal__.serial.filters;
422
- }
423
- set serialConfigPort(e) {
424
- if (this.isConnected) throw new Error("Cannot change serial filters while connected");
425
- this.__internal__.serial.config_port = e;
426
- }
427
- get serialConfigPort() {
428
- return this.__internal__.serial.config_port;
429
- }
430
- get useRTSCTS() {
431
- return this.__internal__.serial.useRTSCTS;
432
- }
433
- set useRTSCTS(e) {
434
- this.__internal__.serial.useRTSCTS = e;
435
- }
436
- get isConnected() {
437
- const e = this.__internal__.serial.connected, t = this.#t(this.__internal__.serial.port);
438
- return e && !t && this.#e({ error: "Port is closed, not readable or writable." }), this.__internal__.serial.connected = t, this.__internal__.serial.connected;
439
- }
440
- get isConnecting() {
441
- return this.__internal__.serial.connecting;
442
- }
443
- get isDisconnected() {
444
- const e = this.__internal__.serial.connected, t = this.#t(this.__internal__.serial.port);
445
- return !e && t && (this.dispatch("serial:connected"), this.#o(!1), s.$dispatchChange(this)), this.__internal__.serial.connected = t, !this.__internal__.serial.connected;
446
- }
447
- get deviceNumber() {
448
- return this.__internal__.device_number;
449
- }
450
- get uuid() {
451
- return this.__internal__.device.id;
452
- }
453
- get typeDevice() {
454
- return this.__internal__.device.type;
455
- }
456
- get queue() {
457
- return this.__internal__.serial.queue;
458
- }
459
- get responseDelimited() {
460
- return this.__internal__.serial.response.delimited;
461
- }
462
- set responseDelimited(e) {
463
- if (typeof e != "boolean")
464
- throw new Error("responseDelimited must be a boolean");
465
- this.__internal__.serial.response.delimited = e;
466
- }
467
- get responsePrefixLimited() {
468
- return this.__internal__.serial.response.prefixLimiter;
469
- }
470
- set responsePrefixLimited(e) {
471
- if (typeof e != "boolean")
472
- throw new Error("responsePrefixLimited must be a boolean");
473
- this.__internal__.serial.response.prefixLimiter = e;
474
- }
475
- get responseSufixLimited() {
476
- return this.__internal__.serial.response.sufixLimiter;
477
- }
478
- set responseSufixLimited(e) {
479
- if (typeof e != "boolean")
480
- throw new Error("responseSufixLimited must be a boolean");
481
- this.__internal__.serial.response.sufixLimiter = e;
482
- }
483
- get responseLimiter() {
484
- return this.__internal__.serial.response.limiter;
485
- }
486
- set responseLimiter(e) {
487
- if (typeof e != "string" && !(e instanceof RegExp))
488
- throw new Error("responseLimiter must be a string or a RegExp");
489
- this.__internal__.serial.response.limiter = e;
490
- }
491
- get fixedBytesMessage() {
492
- return this.__internal__.serial.response.length;
493
- }
494
- set fixedBytesMessage(e) {
495
- if (e !== null && (typeof e != "number" || e < 1))
496
- throw new Error("Invalid length for fixed bytes message");
497
- this.__internal__.serial.response.length = e;
498
- }
499
- get timeoutBeforeResponseBytes() {
500
- return this.__internal__.serial.free_timeout_ms || 50;
501
- }
502
- set timeoutBeforeResponseBytes(e) {
503
- if (e !== void 0 && (typeof e != "number" || e < 1))
504
- throw new Error("Invalid timeout for response bytes");
505
- this.__internal__.serial.free_timeout_ms = e ?? 50;
506
- }
507
- get bypassSerialBytesConnection() {
508
- return this.__internal__.bypassSerialBytesConnection;
509
- }
510
- set bypassSerialBytesConnection(e) {
511
- if (typeof e != "boolean")
512
- throw new Error("bypassSerialBytesConnection must be a boolean");
513
- this.__internal__.bypassSerialBytesConnection = e;
514
- }
515
- get useSocket() {
516
- return this.__internal__.serial.socket;
517
- }
518
- get connectionBytes() {
519
- const e = this.__internal__.serial.bytes_connection;
520
- return e instanceof Uint8Array ? e : typeof e == "string" ? this.stringArrayToUint8Array(this.parseStringToBytes(e, "")) : Array.isArray(e) && typeof e[0] == "string" ? this.stringArrayToUint8Array(e) : Array.isArray(e) && typeof e[0] == "number" ? new Uint8Array(e) : new Uint8Array([]);
521
- }
522
- set portPath(e) {
523
- if (this.isConnected) throw new Error("Cannot change port path while connected");
524
- if (typeof e != "string" && e !== null)
525
- throw new TypeError("vendorId must be string or null");
526
- this.__internal__.serial.portInfo.path = e;
527
- }
528
- get portPath() {
529
- return this.__internal__.serial.portInfo.path;
530
- }
531
- set portVendorId(e) {
532
- if (this.isConnected) throw new Error("Cannot change port vendorId while connected");
533
- if (typeof e == "number" && typeof e != "string" && e !== null)
534
- throw new TypeError("vendorId must be a number, string or null");
535
- this.__internal__.serial.portInfo.vendorId = e;
536
- }
537
- get portVendorId() {
538
- return this.__internal__.serial.portInfo.vendorId;
539
- }
540
- set portProductId(e) {
541
- if (this.isConnected) throw new Error("Cannot change port productId while connected");
542
- if (typeof e == "number" && typeof e != "string" && e !== null)
543
- throw new TypeError("productId must be a number, string or null");
544
- this.__internal__.serial.portInfo.productId = e;
545
- }
546
- get portProductId() {
547
- return this.__internal__.serial.portInfo.productId;
548
- }
549
- set socketPortParser(e) {
550
- if (["byte-length", "inter-byte-timeout"].includes(e))
551
- throw new TypeError("socketPortParser must be a string, either 'byte-length' or 'inter-byte-timeout'");
552
- this.__internal__.serial.portInfo.parser.name = e;
553
- }
554
- get socketPortParser() {
555
- return this.__internal__.serial.portInfo.parser.name;
556
- }
557
- set socketPortParserInterval(e) {
558
- if (typeof e != "number" || e < 1)
559
- throw new TypeError("Interval must be a positive number");
560
- this.__internal__.serial.portInfo.parser.interval = e;
561
- }
562
- get socketPortParserInterval() {
563
- return this.__internal__.serial.portInfo.parser.interval || 50;
564
- }
565
- set socketPortParserLength(e) {
566
- if (typeof e != "number" || e < 1)
567
- throw new TypeError("Length must be a positive number or null");
568
- this.__internal__.serial.portInfo.parser.length = e;
569
- }
570
- get socketPortParserLength() {
571
- return this.__internal__.serial.portInfo.parser.length || 14;
572
- }
573
- get parserForSocket() {
574
- return this.socketPortParser === "byte-length" ? {
575
- name: this.socketPortParser,
576
- length: this.socketPortParserLength
577
- } : {
578
- name: this.socketPortParser,
579
- interval: this.socketPortParserInterval
580
- };
581
- }
582
- get configDeviceSocket() {
583
- return {
584
- uuid: this.uuid,
585
- name: this.typeDevice,
586
- deviceNumber: this.deviceNumber,
587
- connectionBytes: Array.from(this.connectionBytes),
588
- config: {
589
- baudRate: this.__internal__.serial.config_port.baudRate,
590
- dataBits: this.__internal__.serial.config_port.dataBits,
591
- stopBits: this.__internal__.serial.config_port.stopBits,
592
- parity: this.__internal__.serial.config_port.parity,
593
- bufferSize: this.__internal__.serial.config_port.bufferSize,
594
- flowControl: this.__internal__.serial.config_port.flowControl
595
- },
596
- info: {
597
- vendorId: this.portVendorId,
598
- // vendor ID or null for auto-detect
599
- productId: this.portProductId,
600
- // product ID or null for auto-detect
601
- portName: this.portPath
602
- // COM3, /dev/ttyUSB0, etc. null for auto-detect
603
- },
604
- response: {
605
- automatic: this.__internal__.auto_response,
606
- // true to auto-respond to commands this only for devices that doesn't respond nothing
607
- autoResponse: this.__internal__.serial.auto_response,
608
- // null or data to respond automatically, ie. [0x02, 0x06, 0xdd, 0xdd, 0xf0, 0xcf, 0x03] for relay
609
- parser: this.parserForSocket,
610
- timeout: {
611
- general: this.__internal__.time.response_general,
612
- engines: this.__internal__.time.response_engines,
613
- connection: this.__internal__.time.response_connection
614
- }
615
- }
616
- };
617
- }
618
- #t(e) {
619
- return this.useSocket ? this.__internal__.serial.connected && c.isConnected() : !!(e && e.readable && e.writable);
620
- }
621
- async timeout(e, t) {
622
- 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", {}), s.$dispatchChange(this)) : t === "connection:start" && (await this.serialDisconnect(), this.__internal__.serial.connected = !1, this.__internal__.aux_port_connector += 1, s.$dispatchChange(this), await this.serialConnect()), this.__internal__.serial.queue.length > 0 && this.dispatch("internal:queue", {}), this.dispatch("serial:timeout", {
623
- ...this.__internal__.last_error,
624
- bytes: e,
625
- action: t
626
- });
627
- }
628
- async disconnect(e = null) {
629
- await this.serialDisconnect(), this.#e(e);
630
- }
631
- #e(e = null) {
632
- this.__internal__.serial.connected = !1, this.__internal__.aux_port_connector = 0, this.dispatch("serial:disconnected", e), s.$dispatchChange(this);
633
- }
634
- #s(e) {
635
- this.__internal__.serial.aux_connecting = e.detail.active ? "connecting" : "finished";
636
- }
637
- socketResponse(e) {
638
- const t = this.__internal__.serial.connected;
639
- if (e.type === "disconnect" || e.type === "error" && e.data === "DISCONNECTED" ? this.__internal__.serial.connected = !1 : e.type === "success" && (this.__internal__.serial.connected = !0), s.$dispatchChange(this), !t && this.__internal__.serial.connected && (this.dispatch("serial:connected"), this.#o(!1)), e.type === "success")
640
- this.#r(new Uint8Array(e.data));
641
- else if (e.type === "error") {
642
- const n = new Error("The port is closed or is not readable/writable");
643
- this.serialErrors(n);
644
- } else e.type === "timeout" && this.timeout(e.data.bytes ?? [], this.lastAction || "unknown");
645
- this.__internal__.serial.last_action = null;
646
- }
647
- async connect() {
648
- return this.isConnected ? !0 : (this.__internal__.serial.aux_connecting = "idle", new Promise((e, t) => {
649
- this.#i || (this.#i = this.#s.bind(this)), this.on("internal:connecting", this.#i);
650
- const n = setInterval(() => {
651
- this.__internal__.serial.aux_connecting === "finished" ? (clearInterval(n), this.__internal__.serial.aux_connecting = "idle", this.#i !== null && this.off("internal:connecting", this.#i), this.isConnected ? e(!0) : t(`${this.typeDevice} device ${this.deviceNumber} not connected`)) : this.__internal__.serial.aux_connecting === "connecting" && (this.__internal__.serial.aux_connecting = "idle", this.dispatch("internal:connecting", { active: !0 }), this.dispatch("serial:connecting", { active: !0 }));
652
- }, 100);
653
- this.serialConnect();
654
- }));
655
- }
656
- async serialDisconnect() {
657
- try {
658
- if (this.useSocket)
659
- c.isConnected() && c.disconnectDevice(this.configDeviceSocket);
660
- else {
661
- const e = this.__internal__.serial.reader, t = this.__internal__.serial.output_stream;
662
- e && (await e.cancel().catch((i) => this.serialErrors(i)), 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();
663
- }
664
- } catch (e) {
665
- this.serialErrors(e);
666
- } finally {
667
- 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, s.$dispatchChange(this);
668
- }
669
- }
670
- async #a(e) {
671
- if (c.isDisconnected())
672
- throw this.#e({ error: "Socket is disconnected." }), new Error("The socket is disconnected");
673
- if (this.isDisconnected)
674
- throw this.#e({ error: "Port is closed, not readable or writable." }), new Error("The port is closed or is not readable/writable");
675
- const t = this.validateBytes(e);
676
- c.write({ config: this.configDeviceSocket, bytes: Array.from(t) });
677
- }
678
- async #n(e) {
679
- if (this.useSocket) {
680
- await this.#a(e);
681
- return;
682
- }
683
- const t = this.__internal__.serial.port;
684
- if (!t || t && (!t.readable || !t.writable))
685
- throw this.#e({ error: "Port is closed, not readable or writable." }), new Error("The port is closed or is not readable/writable");
686
- const n = this.validateBytes(e);
687
- if (this.useRTSCTS && await this.#l(t, 5e3), t.writable === null) return;
688
- const i = t.writable.getWriter();
689
- await i.write(n), i.releaseLock();
690
- }
691
- async #l(e, t = 5e3) {
692
- const n = Date.now();
693
- for (; ; ) {
694
- if (Date.now() - n > t)
695
- throw new Error("Timeout waiting for clearToSend signal");
696
- const { clearToSend: i } = await e.getSignals();
697
- if (i) return;
698
- await m(100);
699
- }
700
- }
701
- #r(e = new Uint8Array([]), t = !1) {
702
- if (e && e.length > 0) {
703
- const n = this.__internal__.serial.connected;
704
- if (this.__internal__.serial.connected = this.#t(this.__internal__.serial.port), s.$dispatchChange(this), !n && this.__internal__.serial.connected && (this.dispatch("serial:connected"), this.#o(!1)), 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), this.__internal__.serial.response.as === "hex")
705
- t ? this.serialCorruptMessage(this.parseUint8ToHex(e)) : this.serialMessage(this.parseUint8ToHex(e));
706
- else if (this.__internal__.serial.response.as === "uint8")
707
- t ? this.serialCorruptMessage(e) : this.serialMessage(e);
708
- else if (this.__internal__.serial.response.as === "string") {
709
- const i = this.parseUint8ArrayToString(e);
710
- if (this.__internal__.serial.response.limiter !== null) {
711
- const o = i.split(this.__internal__.serial.response.limiter);
712
- for (const r in o)
713
- o[r] && (t ? this.serialCorruptMessage(o[r]) : this.serialMessage(o[r]));
714
- } else
715
- t ? this.serialCorruptMessage(i) : this.serialMessage(i);
716
- } else {
717
- const i = this.stringToArrayBuffer(this.parseUint8ArrayToString(e));
718
- t ? this.serialCorruptMessage(i) : this.serialMessage(i);
719
- }
720
- }
721
- if (this.__internal__.serial.queue.length === 0) {
722
- this.__internal__.serial.running_queue = !1;
723
- return;
724
- }
725
- this.dispatch("internal:queue", {});
726
- }
727
- getResponseAsArrayBuffer() {
728
- this.__internal__.serial.response.as = "arraybuffer";
729
- }
730
- getResponseAsArrayHex() {
731
- this.__internal__.serial.response.as = "hex";
732
- }
733
- getResponseAsUint8Array() {
734
- this.__internal__.serial.response.as = "uint8";
735
- }
736
- getResponseAsString() {
737
- this.__internal__.serial.response.as = "string";
738
- }
739
- async #_() {
740
- const e = this.serialFilters, t = await navigator.serial.getPorts({ filters: e });
741
- return e.length === 0 ? t : t.filter((i) => {
742
- const o = i.getInfo();
743
- return e.some((r) => o.usbProductId === r.usbProductId && o.usbVendorId === r.usbVendorId);
744
- }).filter((i) => !this.#t(i));
745
- }
746
- async serialPortsSaved(e) {
747
- const t = this.serialFilters;
748
- if (this.__internal__.aux_port_connector < e.length) {
749
- const n = this.__internal__.aux_port_connector;
750
- this.__internal__.serial.port = e[n];
751
- } else
752
- this.__internal__.aux_port_connector = 0, this.__internal__.serial.port = await navigator.serial.requestPort({
753
- filters: t
754
- });
755
- if (!this.__internal__.serial.port)
756
- throw new Error("Select another port please");
757
- }
758
- serialErrors(e) {
759
- const t = e.toString().toLowerCase();
760
- switch (!0) {
761
- case t.includes("must be handling a user gesture to show a permission request"):
762
- case t.includes("the port is closed."):
763
- case t.includes("the port is closed or is not writable"):
764
- case t.includes("the port is closed or is not readable"):
765
- case t.includes("the port is closed or is not readable/writable"):
766
- case t.includes("select another port please"):
767
- case t.includes("no port selected by the user"):
768
- case t.includes(
769
- "this readable stream reader has been released and cannot be used to cancel its previous owner stream"
770
- ):
771
- this.dispatch("serial:need-permission", {}), s.$dispatchChange(this);
772
- break;
773
- case t.includes("the port is already open."):
774
- case t.includes("failed to open serial port"):
775
- this.serialDisconnect().then(async () => {
776
- this.__internal__.aux_port_connector += 1, await this.serialConnect();
777
- });
778
- break;
779
- case t.includes("cannot read properties of undefined (reading 'writable')"):
780
- case t.includes("cannot read properties of null (reading 'writable')"):
781
- case t.includes("cannot read property 'writable' of null"):
782
- case t.includes("cannot read property 'writable' of undefined"):
783
- this.serialDisconnect().then(async () => {
784
- await this.serialConnect();
785
- });
786
- break;
787
- case t.includes("'close' on 'serialport': a call to close() is already in progress."):
788
- break;
789
- case t.includes("failed to execute 'open' on 'serialport': a call to open() is already in progress."):
790
- break;
791
- case t.includes("the port is already closed."):
792
- break;
793
- case t.includes("the device has been lost"):
794
- this.dispatch("serial:lost", {}), s.$dispatchChange(this);
795
- break;
796
- case t.includes("navigator.serial is undefined"):
797
- this.dispatch("serial:unsupported", {});
798
- break;
799
- default:
800
- console.error(e);
801
- break;
802
- }
803
- this.dispatch("serial:error", e);
804
- }
805
- #c(e) {
806
- if (e) {
807
- const t = this.__internal__.serial.response.buffer, n = new Uint8Array(t.length + e.byteLength);
808
- n.set(t, 0), n.set(new Uint8Array(e), t.length), this.__internal__.serial.response.buffer = n;
809
- }
810
- }
811
- async #h() {
812
- 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.response.buffer && this.#r(this.__internal__.serial.response.buffer), this.__internal__.serial.response.buffer = new Uint8Array(0);
813
- }
814
- async #u() {
815
- 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(() => {
816
- this.__internal__.serial.response.buffer && this.#r(this.__internal__.serial.response.buffer), this.__internal__.serial.response.buffer = new Uint8Array(0);
817
- }, this.__internal__.serial.free_timeout_ms || 50);
818
- }
819
- async #d() {
820
- const e = this.__internal__.serial.response.length;
821
- let t = this.__internal__.serial.response.buffer;
822
- if (this.__internal__.serial.time_until_send_bytes && (clearTimeout(this.__internal__.serial.time_until_send_bytes), this.__internal__.serial.time_until_send_bytes = 0), !(e === null || !t || t.length === 0)) {
823
- for (; t.length >= e; ) {
824
- const n = t.slice(0, e);
825
- this.#r(n), t = t.slice(e);
826
- }
827
- this.__internal__.serial.response.buffer = t, t.length > 0 && (this.__internal__.serial.time_until_send_bytes = setTimeout(() => {
828
- this.#r(this.__internal__.serial.response.buffer, !0);
829
- }, this.__internal__.serial.free_timeout_ms || 50));
830
- }
831
- }
832
- async #f() {
833
- const {
834
- limiter: e,
835
- prefixLimiter: t = !1,
836
- sufixLimiter: n = !0
837
- } = this.__internal__.serial.response;
838
- if (!e)
839
- throw new Error("No limiter defined for delimited serial response");
840
- const i = this.__internal__.serial.response.buffer;
841
- if (!e || !i || i.length === 0) return;
842
- this.__internal__.serial.time_until_send_bytes && (clearTimeout(this.__internal__.serial.time_until_send_bytes), this.__internal__.serial.time_until_send_bytes = 0);
843
- let r = new TextDecoder().decode(i);
844
- const h = [];
845
- if (typeof e == "string") {
846
- let l;
847
- if (t && n)
848
- l = new RegExp(`${e}([^${e}]+)${e}`, "g");
849
- else if (t)
850
- l = new RegExp(`${e}([^${e}]*)`, "g");
851
- else if (n)
852
- l = new RegExp(`([^${e}]+)${e}`, "g");
853
- else
854
- return;
855
- let u, _ = 0;
856
- for (; (u = l.exec(r)) !== null; )
857
- h.push(new TextEncoder().encode(u[1])), _ = l.lastIndex;
858
- r = r.slice(_);
859
- } else if (e instanceof RegExp) {
860
- let l, u = 0;
861
- if (t && n) {
862
- const _ = new RegExp(`${e.source}(.*?)${e.source}`, "g");
863
- for (; (l = _.exec(r)) !== null; )
864
- h.push(new TextEncoder().encode(l[1])), u = _.lastIndex;
865
- } else if (n)
866
- for (; (l = e.exec(r)) !== null; ) {
867
- const _ = l.index, d = r.slice(u, _);
868
- h.push(new TextEncoder().encode(d)), u = e.lastIndex;
869
- }
870
- else if (t) {
871
- const _ = r.split(e);
872
- _.shift();
873
- for (const d of _)
874
- h.push(new TextEncoder().encode(d));
875
- r = "";
876
- }
877
- r = r.slice(u);
878
- }
879
- for (const l of h)
880
- this.#r(l);
881
- const p = new TextEncoder().encode(r);
882
- this.__internal__.serial.response.buffer = p, p.length > 0 && (this.__internal__.serial.time_until_send_bytes = setTimeout(() => {
883
- this.#r(this.__internal__.serial.response.buffer, !0), this.__internal__.serial.response.buffer = new Uint8Array(0);
884
- }, this.__internal__.serial.free_timeout_ms ?? 50));
885
- }
886
- async #p() {
887
- const e = this.__internal__.serial.port;
888
- if (!e || !e.readable) throw new Error("Port is not readable");
889
- const t = this.__internal__.serial.transformStream ? this.__internal__.serial.transformStream : null, n = t ? e.readable.pipeThrough(t).getReader() : e.readable.getReader();
890
- this.__internal__.serial.reader = n;
891
- try {
892
- for (; this.__internal__.serial.keep_reading; ) {
893
- const { value: i, done: o } = await n.read();
894
- if (o) break;
895
- this.#c(i), this.__internal__.serial.transformStream ? await this.#h() : this.__internal__.serial.response.delimited ? await this.#f() : this.__internal__.serial.response.length === null ? await this.#u() : await this.#d();
896
- }
897
- } catch (i) {
898
- this.serialErrors(i);
899
- } finally {
900
- n.releaseLock(), this.__internal__.serial.keep_reading = !0, this.__internal__.serial.port && await this.__internal__.serial.port.close();
901
- }
902
- }
903
- #o(e) {
904
- e !== this.__internal__.serial.connecting && (this.__internal__.serial.connecting = e, this.dispatch("serial:connecting", { active: e }), this.dispatch("internal:connecting", { active: e }));
905
- }
906
- async serialConnect() {
907
- try {
908
- if (this.#o(!0), this.useSocket) {
909
- if (c.prepare(), this.__internal__.serial.last_action = "connect", this.__internal__.timeout.until_response = setTimeout(async () => {
910
- await this.timeout(this.__internal__.serial.bytes_connection ?? [], "connection:start");
911
- }, this.__internal__.time.response_connection), c.isDisconnected())
912
- return;
913
- c.connectDevice(this.configDeviceSocket), this.dispatch("serial:sent", {
914
- action: "connect",
915
- bytes: this.__internal__.serial.bytes_connection
916
- });
917
- } else {
918
- const e = await this.#_();
919
- if (e.length > 0)
920
- await this.serialPortsSaved(e);
921
- else {
922
- const i = this.serialFilters;
923
- this.__internal__.serial.port = await navigator.serial.requestPort({
924
- filters: i
925
- });
926
- }
927
- const t = this.__internal__.serial.port;
928
- if (!t)
929
- throw new Error("No port selected by the user");
930
- await t.open(this.serialConfigPort);
931
- const n = this;
932
- t.onconnect = (i) => {
933
- n.dispatch("serial:connected", i), n.#o(!1), s.$dispatchChange(this), n.__internal__.serial.queue.length > 0 ? n.dispatch("internal:queue", {}) : n.__internal__.serial.running_queue = !1;
934
- }, t.ondisconnect = async () => {
935
- await n.disconnect();
936
- }, await m(this.__internal__.serial.delay_first_connection), this.__internal__.timeout.until_response = setTimeout(async () => {
937
- await n.timeout(n.__internal__.serial.bytes_connection ?? [], "connection:start");
938
- }, this.__internal__.time.response_connection), this.__internal__.serial.last_action = "connect", await this.#n(this.__internal__.serial.bytes_connection ?? []), this.dispatch("serial:sent", {
939
- action: "connect",
940
- bytes: this.__internal__.serial.bytes_connection
941
- }), this.__internal__.auto_response && this.#r(this.__internal__.serial.auto_response), await this.#p();
942
- }
943
- } catch (e) {
944
- this.#o(!1), this.serialErrors(e);
945
- }
946
- }
947
- async #g() {
948
- return typeof window > "u" ? !1 : "serial" in navigator && "forget" in SerialPort.prototype && this.__internal__.serial.port ? (await this.__internal__.serial.port.forget(), !0) : !1;
949
- }
950
- async serialForget() {
951
- return await this.#g();
952
- }
953
- decToHex(e) {
954
- return typeof e == "string" && (e = parseInt(e, 10)), e.toString(16);
955
- }
956
- hexToDec(e) {
957
- return parseInt(e, 16);
958
- }
959
- hexMaker(e = "00", t = 2) {
960
- return e.toString().padStart(t, "0").toLowerCase();
961
- }
962
- add0x(e) {
963
- const t = [];
964
- return e.forEach((n, i) => {
965
- t[i] = "0x" + n;
966
- }), t;
967
- }
968
- bytesToHex(e) {
969
- return this.add0x(Array.from(e, (t) => this.hexMaker(t)));
970
- }
971
- #m() {
972
- [
973
- "serial:connected",
974
- "serial:connecting",
975
- "serial:reconnect",
976
- "serial:timeout",
977
- "serial:disconnected",
978
- "serial:sent",
979
- "serial:soft-reload",
980
- "serial:message",
981
- "serial:corrupt-message",
982
- "unknown",
983
- "serial:need-permission",
984
- "serial:lost",
985
- "serial:unsupported",
986
- "serial:error",
987
- "debug"
988
- ].forEach((t) => {
989
- this.serialRegisterAvailableListener(t);
990
- });
991
- }
992
- #y() {
993
- const e = this;
994
- this.on("internal:queue", async () => {
995
- await e.#b();
996
- });
997
- const t = () => {
998
- e.isConnected && e.#e({ error: "Socket disconnected." });
999
- }, n = () => {
1000
- e.isDisconnected && !e.isConnecting && e.serialConnect().catch(() => {
1001
- });
1002
- };
1003
- this.useSocket && (window.addEventListener("serial:socket:disconnected", t), window.addEventListener("serial:socket:connected", n)), this.#w();
1004
- }
1005
- #w() {
1006
- const e = this;
1007
- navigator.serial.addEventListener("connect", async () => {
1008
- e.isDisconnected && await e.serialConnect().catch(() => {
1009
- });
1010
- });
1011
- }
1012
- async #b() {
1013
- if (this.useSocket && c.isDisconnected())
1014
- return;
1015
- if (!this.#t(this.__internal__.serial.port)) {
1016
- this.#e({ error: "Port is closed, not readable or writable." }), await this.serialConnect();
1017
- return;
1018
- }
1019
- if (this.__internal__.timeout.until_response) return;
1020
- if (this.__internal__.serial.queue.length === 0) {
1021
- this.__internal__.serial.running_queue = !1;
1022
- return;
1023
- }
1024
- this.__internal__.serial.running_queue = !0;
1025
- const e = this.__internal__.serial.queue[0];
1026
- let t = this.__internal__.time.response_general;
1027
- if (e.action === "connect" && (t = this.__internal__.time.response_connection), this.__internal__.timeout.until_response = setTimeout(async () => {
1028
- await this.timeout(e.bytes, e.action);
1029
- }, t), this.__internal__.serial.last_action = e.action ?? "unknown", await this.#n(e.bytes), this.dispatch("serial:sent", {
1030
- action: e.action,
1031
- bytes: e.bytes
1032
- }), this.__internal__.auto_response) {
1033
- let i = new Uint8Array(0);
1034
- try {
1035
- i = this.validateBytes(this.__internal__.serial.auto_response);
1036
- } catch (o) {
1037
- this.serialErrors(o);
1038
- }
1039
- this.#r(i);
1040
- }
1041
- const n = [...this.__internal__.serial.queue];
1042
- this.__internal__.serial.queue = n.splice(1), this.__internal__.serial.queue.length > 0 && (this.__internal__.serial.running_queue = !0);
1043
- }
1044
- validateBytes(e) {
1045
- let t = new Uint8Array(0);
1046
- if (e instanceof Uint8Array)
1047
- t = e;
1048
- else if (typeof e == "string")
1049
- t = this.parseStringToTextEncoder(e);
1050
- else if (Array.isArray(e) && typeof e[0] == "string")
1051
- t = this.stringArrayToUint8Array(e);
1052
- else if (Array.isArray(e) && typeof e[0] == "number")
1053
- t = new Uint8Array(e);
1054
- else
1055
- throw new Error("Invalid data type");
1056
- return t;
1057
- }
1058
- async appendToQueue(e, t) {
1059
- const n = this.validateBytes(e);
1060
- if (["connect", "connection:start"].includes(t)) {
1061
- if (this.__internal__.serial.connected) return;
1062
- await this.serialConnect();
1063
- return;
1064
- }
1065
- this.__internal__.serial.queue.push({ bytes: n, action: t }), this.dispatch("internal:queue", {});
1066
- }
1067
- #C(e = 1) {
1068
- this.__internal__.device_number = e, !this.__internal__.bypassSerialBytesConnection && (this.__internal__.serial.bytes_connection = this.serialSetConnectionConstant(e));
1069
- }
1070
- serialSetConnectionConstant(e = 1) {
1071
- if (this.__internal__.bypassSerialBytesConnection) return this.__internal__.serial.bytes_connection;
1072
- throw new Error(`Method not implemented 'serialSetConnectionConstant' to listen on channel ${e}`);
1073
- }
1074
- serialMessage(e) {
1075
- throw console.log(e), this.dispatch("serial:message", { code: e }), new Error("Method not implemented 'serialMessage'");
1076
- }
1077
- serialCorruptMessage(e) {
1078
- throw console.log(e), this.dispatch("serial:corrupt-message", { code: e }), new Error("Method not implemented 'serialCorruptMessage'");
1079
- }
1080
- #E() {
1081
- this.__internal__.last_error = {
1082
- message: null,
1083
- action: null,
1084
- code: null,
1085
- no_code: 0
1086
- };
1087
- }
1088
- clearSerialQueue() {
1089
- this.__internal__.serial.queue = [];
1090
- }
1091
- sumHex(e) {
1092
- let t = 0;
1093
- return e.forEach((n) => {
1094
- t += parseInt(n, 16);
1095
- }), t.toString(16);
1096
- }
1097
- toString() {
1098
- return JSON.stringify({
1099
- __class: this.typeDevice,
1100
- device_number: this.deviceNumber,
1101
- uuid: this.uuid,
1102
- connected: this.isConnected,
1103
- connection: this.__internal__.serial.bytes_connection
1104
- });
1105
- }
1106
- softReload() {
1107
- this.#E(), this.dispatch("serial:soft-reload", {});
1108
- }
1109
- async sendConnect() {
1110
- if (!this.__internal__.serial.bytes_connection)
1111
- throw new Error("No connection bytes defined");
1112
- await this.appendToQueue(this.__internal__.serial.bytes_connection, "connect");
1113
- }
1114
- async sendCustomCode({ code: e = [] } = { code: [] }) {
1115
- if (!e)
1116
- throw new Error("No data to send");
1117
- this.__internal__.bypassSerialBytesConnection && (this.__internal__.serial.bytes_connection = this.validateBytes(e)), await this.appendToQueue(e, "custom");
1118
- }
1119
- stringToArrayHex(e) {
1120
- return Array.from(e).map((t) => t.charCodeAt(0).toString(16));
1121
- }
1122
- stringToArrayBuffer(e, t = `
1123
- `) {
1124
- return this.parseStringToTextEncoder(e, t).buffer;
1125
- }
1126
- parseStringToTextEncoder(e = "", t = `
1127
- `) {
1128
- const n = new TextEncoder();
1129
- return e += t, n.encode(e);
1130
- }
1131
- parseStringToBytes(e = "", t = `
1132
- `) {
1133
- const n = this.parseStringToTextEncoder(e, t);
1134
- return Array.from(n).map((i) => i.toString(16));
1135
- }
1136
- parseUint8ToHex(e) {
1137
- return Array.from(e).map((t) => t.toString(16).padStart(2, "0").toLowerCase());
1138
- }
1139
- parseHexToUint8(e) {
1140
- return new Uint8Array(e.map((t) => parseInt(t, 16)));
1141
- }
1142
- stringArrayToUint8Array(e) {
1143
- const t = [];
1144
- return typeof e == "string" ? this.parseStringToTextEncoder(e).buffer : (e.forEach((n) => {
1145
- const i = n.replace("0x", "");
1146
- t.push(parseInt(i, 16));
1147
- }), new Uint8Array(t));
1148
- }
1149
- parseUint8ArrayToString(e) {
1150
- let t = new Uint8Array(0);
1151
- e instanceof Uint8Array ? t = e : t = this.stringArrayToUint8Array(e), e = this.parseUint8ToHex(t);
1152
- const n = e.map((i) => parseInt(i, 16));
1153
- return this.__internal__.serial.response.replacer ? String.fromCharCode(...n).replace(this.__internal__.serial.response.replacer, "") : String.fromCharCode(...n);
1154
- }
1155
- hexToAscii(e) {
1156
- const t = e.toString();
1157
- let n = "";
1158
- for (let i = 0; i < t.length; i += 2)
1159
- n += String.fromCharCode(parseInt(t.substring(i, 2), 16));
1160
- return n;
1161
- }
1162
- asciiToHex(e) {
1163
- const t = [];
1164
- for (let n = 0, i = e.length; n < i; n++) {
1165
- const o = Number(e.charCodeAt(n)).toString(16);
1166
- t.push(o);
1167
- }
1168
- return t.join("");
1169
- }
1170
- $checkAndDispatchConnection() {
1171
- return this.isConnected;
1172
- }
1173
- }
1174
- var E = /* @__PURE__ */ ((a) => (a.CONNECTION_FAILED = "CONNECTION_FAILED", a.DISCONNECTION_FAILED = "DISCONNECTION_FAILED", a.WRITE_FAILED = "WRITE_FAILED", a.READ_FAILED = "READ_FAILED", a.TIMEOUT = "TIMEOUT", a.PORT_NOT_FOUND = "PORT_NOT_FOUND", a.PERMISSION_DENIED = "PERMISSION_DENIED", a.DEVICE_NOT_SUPPORTED = "DEVICE_NOT_SUPPORTED", a.INVALID_CONFIGURATION = "INVALID_CONFIGURATION", a.SOCKET_ERROR = "SOCKET_ERROR", a.UNKNOWN_ERROR = "UNKNOWN_ERROR", a))(E || {});
1175
- class w extends Error {
1176
- /**
1177
- * Error code identifying the type of error
1178
- */
1179
- code;
1180
- /**
1181
- * Additional context about the error
1182
- */
1183
- context;
1184
- /**
1185
- * Timestamp when the error occurred
1186
- */
1187
- timestamp;
1188
- /**
1189
- * Creates a new SerialError
1190
- * @param message - Human-readable error message
1191
- * @param code - Error code from SerialErrorCode enum
1192
- * @param context - Additional context information
1193
- * @example
1194
- * ```typescript
1195
- * throw new SerialError(
1196
- * 'Failed to connect to device',
1197
- * SerialErrorCode.CONNECTION_FAILED,
1198
- * { port: 'COM3', baudRate: 9600 }
1199
- * );
1200
- * ```
1201
- */
1202
- constructor(e, t = "UNKNOWN_ERROR", n) {
1203
- super(e), this.name = "SerialError", this.code = t, this.context = n, this.timestamp = /* @__PURE__ */ new Date(), Error.captureStackTrace && Error.captureStackTrace(this, w);
1204
- }
1205
- /**
1206
- * Returns a JSON representation of the error
1207
- * @returns Serialized error object
1208
- */
1209
- toJSON() {
1210
- return {
1211
- name: this.name,
1212
- message: this.message,
1213
- code: this.code,
1214
- context: this.context,
1215
- timestamp: this.timestamp.toISOString(),
1216
- stack: this.stack
1217
- };
1218
- }
1219
- /**
1220
- * Returns a formatted string representation of the error
1221
- * @returns Formatted error string
1222
- */
1223
- toString() {
1224
- const e = this.context ? ` | Context: ${JSON.stringify(this.context)}` : "";
1225
- return `${this.name} [${this.code}]: ${this.message}${e}`;
1226
- }
1227
- }
1228
- export {
1229
- T as Core,
1230
- s as Devices,
1231
- y as Dispatcher,
1232
- w as SerialError,
1233
- E as SerialErrorCode,
1234
- c as Socket
1235
- };
1236
- //# sourceMappingURL=webserial-core.js.map