webserial-core 1.0.0 → 1.0.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.
- package/dist/webserial-core.js +14 -12
- package/dist/webserial-core.umd.cjs +2 -2
- package/package.json +1 -1
package/dist/webserial-core.js
CHANGED
|
@@ -4,7 +4,7 @@ var b = (r) => {
|
|
|
4
4
|
};
|
|
5
5
|
var O = (r, i, e) => i in r ? N(r, i, { enumerable: !0, configurable: !0, writable: !0, value: e }) : r[i] = e;
|
|
6
6
|
var h = (r, i, e) => O(r, typeof i != "symbol" ? i + "" : i, e), H = (r, i, e) => i.has(r) || b("Cannot " + e);
|
|
7
|
-
var
|
|
7
|
+
var w = (r, i, e) => i.has(r) ? b("Cannot add the same private member more than once") : i instanceof WeakSet ? i.add(r) : i.set(r, e);
|
|
8
8
|
var l = (r, i, e) => (H(r, i, "access private method"), e);
|
|
9
9
|
const _ = [];
|
|
10
10
|
for (let r = 0; r < 256; ++r)
|
|
@@ -22,11 +22,11 @@ function F() {
|
|
|
22
22
|
}
|
|
23
23
|
return p(B);
|
|
24
24
|
}
|
|
25
|
-
const $ = typeof crypto < "u" && crypto.randomUUID && crypto.randomUUID.bind(crypto),
|
|
25
|
+
const $ = typeof crypto < "u" && crypto.randomUUID && crypto.randomUUID.bind(crypto), m = { randomUUID: $ };
|
|
26
26
|
function V(r, i, e) {
|
|
27
27
|
var n;
|
|
28
|
-
if (
|
|
29
|
-
return
|
|
28
|
+
if (m.randomUUID && !r)
|
|
29
|
+
return m.randomUUID();
|
|
30
30
|
r = r || {};
|
|
31
31
|
const t = r.random ?? ((n = r.rng) == null ? void 0 : n.call(r)) ?? F();
|
|
32
32
|
if (t.length < 16)
|
|
@@ -77,7 +77,7 @@ function x(r = 100) {
|
|
|
77
77
|
(i) => setTimeout(() => i(), r)
|
|
78
78
|
);
|
|
79
79
|
}
|
|
80
|
-
function
|
|
80
|
+
function W() {
|
|
81
81
|
return "serial" in navigator;
|
|
82
82
|
}
|
|
83
83
|
const f = {
|
|
@@ -88,7 +88,7 @@ const f = {
|
|
|
88
88
|
bufferSize: 32768,
|
|
89
89
|
flowControl: "none"
|
|
90
90
|
};
|
|
91
|
-
var a, C, g, c,
|
|
91
|
+
var a, C, g, c, E, A, T, U, k, D, I, L, P, q, R, M;
|
|
92
92
|
class z extends S {
|
|
93
93
|
constructor({
|
|
94
94
|
filters: e = null,
|
|
@@ -102,7 +102,7 @@ class z extends S {
|
|
|
102
102
|
device_listen_on_channel: 1
|
|
103
103
|
}) {
|
|
104
104
|
super();
|
|
105
|
-
|
|
105
|
+
w(this, a);
|
|
106
106
|
h(this, "__internal__", {
|
|
107
107
|
auto_response: !1,
|
|
108
108
|
device_number: 1,
|
|
@@ -151,6 +151,8 @@ class z extends S {
|
|
|
151
151
|
reconnection: 0
|
|
152
152
|
}
|
|
153
153
|
});
|
|
154
|
+
if (!("serial" in navigator))
|
|
155
|
+
throw new Error("Web Serial not supported");
|
|
154
156
|
e && (this.serialFilters = e), t && (this.serialConfigPort = t), n && l(this, a, R).call(this, n), s && ["number", "string"].includes(typeof s) && (this.listenOnChannel = s), l(this, a, I).call(this), l(this, a, L).call(this);
|
|
155
157
|
}
|
|
156
158
|
set listenOnChannel(e) {
|
|
@@ -206,7 +208,7 @@ class z extends S {
|
|
|
206
208
|
}
|
|
207
209
|
async connect() {
|
|
208
210
|
return new Promise((e, t) => {
|
|
209
|
-
|
|
211
|
+
W() || t("Web Serial not supported"), setTimeout(async () => {
|
|
210
212
|
await x(499), await this.serialConnect(), this.isConnected ? e(`${this.typeDevice} device ${this.deviceNumber} connected`) : t(`${this.typeDevice} device ${this.deviceNumber} not connected`);
|
|
211
213
|
}, 1);
|
|
212
214
|
});
|
|
@@ -293,7 +295,7 @@ class z extends S {
|
|
|
293
295
|
async serialConnect() {
|
|
294
296
|
try {
|
|
295
297
|
this.dispatch("serial:connecting", {});
|
|
296
|
-
const e = await l(this, a,
|
|
298
|
+
const e = await l(this, a, E).call(this);
|
|
297
299
|
if (e.length > 0)
|
|
298
300
|
await this.serialPortsSaved(e);
|
|
299
301
|
else {
|
|
@@ -473,13 +475,13 @@ a = new WeakSet(), C = function(e) {
|
|
|
473
475
|
} else
|
|
474
476
|
this.serialCorruptMessage(e, t);
|
|
475
477
|
this.__internal__.serial.queue.length !== 0 && this.dispatch("internal:queue", {});
|
|
476
|
-
},
|
|
478
|
+
}, E = async function() {
|
|
477
479
|
const e = this.serialFilters, t = await navigator.serial.getPorts({ filters: e });
|
|
478
480
|
return e.length === 0 ? t : t.filter((s) => {
|
|
479
481
|
const u = s.getInfo();
|
|
480
482
|
return e.some((y) => u.usbProductId === y.usbProductId && u.usbVendorId === y.usbVendorId);
|
|
481
483
|
}).filter((s) => !l(this, a, C).call(this, s));
|
|
482
|
-
},
|
|
484
|
+
}, A = function(e) {
|
|
483
485
|
if (e) {
|
|
484
486
|
const t = this.__internal__.serial.response.buffer, n = new Uint8Array(t.length + e.byteLength);
|
|
485
487
|
n.set(t, 0), n.set(new Uint8Array(e), t.length), this.__internal__.serial.response.buffer = n;
|
|
@@ -537,7 +539,7 @@ a = new WeakSet(), C = function(e) {
|
|
|
537
539
|
t.releaseLock(), this.__internal__.serial.keep_reading = !1, n = !1;
|
|
538
540
|
break;
|
|
539
541
|
}
|
|
540
|
-
l(this, a,
|
|
542
|
+
l(this, a, A).call(this, s), this.__internal__.serial.response.length === null ? await l(this, a, T).call(this) : await l(this, a, U).call(this);
|
|
541
543
|
}
|
|
542
544
|
} catch (n) {
|
|
543
545
|
this.serialErrors(n);
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
(function(_,s){typeof exports=="object"&&typeof module<"u"?s(exports):typeof define=="function"&&define.amd?define(["exports"],s):(_=typeof globalThis<"u"?globalThis:_||self,s(_.WebSerialCore={}))})(this,function(_){"use strict";var V=Object.defineProperty;var C=_=>{throw TypeError(_)};var W=(_,s,u)=>s in _?V(_,s,{enumerable:!0,configurable:!0,writable:!0,value:u}):_[s]=u;var f=(_,s,u)=>W(_,typeof s!="symbol"?s+"":s,u),Q=(_,s,u)=>s.has(_)||C("Cannot "+u);var T=(_,s,u)=>s.has(_)?C("Cannot add the same private member more than once"):s instanceof WeakSet?s.add(_):s.set(_,u);var c=(_,s,u)=>(Q(_,s,"access private method"),u);var a,A,m,h,E,U,D,k,I,L,P,q,M,R,N,O;const s=[];for(let o=0;o<256;++o)s.push((o+256).toString(16).slice(1));function u(o,i=0){return(s[o[i+0]]+s[o[i+1]]+s[o[i+2]]+s[o[i+3]]+"-"+s[o[i+4]]+s[o[i+5]]+"-"+s[o[i+6]]+s[o[i+7]]+"-"+s[o[i+8]]+s[o[i+9]]+"-"+s[o[i+10]]+s[o[i+11]]+s[o[i+12]]+s[o[i+13]]+s[o[i+14]]+s[o[i+15]]).toLowerCase()}let g;const H=new Uint8Array(16);function j(){if(!g){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");g=crypto.getRandomValues.bind(crypto)}return g(H)}const w={randomUUID:typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function B(o,i,e){var n;if(w.randomUUID&&!o)return w.randomUUID();o=o||{};const t=o.random??((n=o.rng)==null?void 0:n.call(o))??j();if(t.length<16)throw new Error("Random bytes length must be >= 16");return t[6]=t[6]&15|64,t[8]=t[8]&63|128,u(t)}class v extends CustomEvent{constructor(i,e){super(i,e)}}class y extends EventTarget{constructor(){super(...arguments);f(this,"__listeners__",{debug:!1});f(this,"__debug__",!1)}dispatch(e,t=null){const n=new v(e,{detail:t});this.dispatchEvent(n),this.__debug__&&this.dispatchEvent(new v("debug",{detail:{type:e,data:t}}))}dispatchAsync(e,t=null,n=100){const r=this;setTimeout(()=>{r.dispatch(e,t)},n)}on(e,t){typeof this.__listeners__[e]<"u"&&!this.__listeners__[e]&&(this.__listeners__[e]=!0),this.addEventListener(e,t)}off(e,t){this.removeEventListener(e,t)}serialRegisterAvailableListener(e){this.__listeners__[e]||(this.__listeners__[e]=!1)}get availableListeners(){return Object.keys(this.__listeners__).sort().map(t=>({type:t,listening:this.__listeners__[t]}))}}function x(o=100){return new Promise(i=>setTimeout(()=>i(),o))}function F(){return"serial"in navigator}const b={baudRate:9600,dataBits:8,stopBits:1,parity:"none",bufferSize:32768,flowControl:"none"};class $ extends y{constructor({filters:e=null,config_port:t=b,no_device:n=1,device_listen_on_channel:r=1}={filters:null,config_port:b,no_device:1,device_listen_on_channel:1}){super();T(this,a);f(this,"__internal__",{auto_response:!1,device_number:1,aux_port_connector:0,last_error:{message:null,action:null,code:null,no_code:0},serial:{connected:!1,port:null,last_action:null,response:{length:null,buffer:new Uint8Array([]),as:"hex"},reader:null,input_done:null,output_done:null,input_stream:null,output_stream:null,keep_reading:!0,time_until_send_bytes:void 0,delay_first_connection:200,bytes_connection:null,filters:[],config_port:b,queue:[]},device:{type:"unknown",id:B(),listen_on_port:null},time:{response_connection:500,response_general:2e3},timeout:{until_response:0},interval:{reconnection:0}});e&&(this.serialFilters=e),t&&(this.serialConfigPort=t),n&&c(this,a,N).call(this,n),r&&["number","string"].includes(typeof r)&&(this.listenOnChannel=r),c(this,a,P).call(this),c(this,a,q).call(this)}set listenOnChannel(e){if(typeof e=="string"&&(e=parseInt(e)),isNaN(e)||e<1||e>255)throw new Error("Invalid port number");this.__internal__.device.listen_on_port=e,this.__internal__.serial.bytes_connection=this.serialSetConnectionConstant(e)}get lastAction(){return this.__internal__.serial.last_action}get listenOnChannel(){return this.__internal__.device.listen_on_port??1}set serialFilters(e){this.__internal__.serial.filters=e}get serialFilters(){return this.__internal__.serial.filters}set serialConfigPort(e){this.__internal__.serial.config_port=e}get serialConfigPort(){return this.__internal__.serial.config_port}get isConnected(){return this.__internal__.serial.connected}get isDisconnected(){return!this.__internal__.serial.connected}get deviceNumber(){return this.__internal__.device_number}get uuid(){return this.__internal__.device.id}get typeDevice(){return this.__internal__.device.type}get queue(){return this.__internal__.serial.queue}async timeout(e,t){this.__internal__.last_error.message="Operation response timed out.",this.__internal__.last_error.action=t,this.__internal__.last_error.code=e,this.__internal__.timeout.until_response&&(clearTimeout(this.__internal__.timeout.until_response),this.__internal__.timeout.until_response=0),t==="connect"?(this.__internal__.serial.connected=!1,this.dispatch("serial:reconnect",{})):t==="connection:start"&&(await this.serialDisconnect(),this.__internal__.serial.connected=!1,this.__internal__.aux_port_connector+=1,await this.serialConnect()),this.dispatch("serial:timeout",{...this.__internal__.last_error,bytes:e,action:t})}async disconnect(e=null){await this.serialDisconnect(),this.__internal__.serial.connected=!1,this.__internal__.aux_port_connector=0,this.dispatch("serial:disconnected",e)}async connect(){return new Promise((e,t)=>{F()||t("Web Serial not supported"),setTimeout(async()=>{await x(499),await this.serialConnect(),this.isConnected?e(`${this.typeDevice} device ${this.deviceNumber} connected`):t(`${this.typeDevice} device ${this.deviceNumber} not connected`)},1)})}async serialDisconnect(){try{const e=this.__internal__.serial.reader,t=this.__internal__.serial.output_stream;e&&(await e.cancel().catch(r=>this.serialErrors(r)),await this.__internal__.serial.input_done),t&&(await t.getWriter().close(),await this.__internal__.serial.output_done),this.__internal__.serial.connected&&this.__internal__.serial&&this.__internal__.serial.port&&await this.__internal__.serial.port.close()}catch(e){this.serialErrors(e)}finally{this.__internal__.serial.reader=null,this.__internal__.serial.input_done=null,this.__internal__.serial.output_stream=null,this.__internal__.serial.output_done=null,this.__internal__.serial.connected=!1,this.__internal__.serial.port=null}}getResponseAsArrayBuffer(){this.__internal__.serial.response.as="arraybuffer"}getResponseAsArrayHex(){this.__internal__.serial.response.as="hex"}getResponseAsUint8Array(){this.__internal__.serial.response.as="uint8"}getResponseAsString(){this.__internal__.serial.response.as="string"}async serialPortsSaved(e){const t=this.serialFilters;if(this.__internal__.aux_port_connector<e.length){const n=this.__internal__.aux_port_connector;this.__internal__.serial.port=e[n]}else this.__internal__.aux_port_connector=0,this.__internal__.serial.port=await navigator.serial.requestPort({filters:t});if(!this.__internal__.serial.port)throw new Error("Select another port please")}serialErrors(e){const t=e.toString().toLowerCase();switch(!0){case t.includes("must be handling a user gesture to show a permission request"):case t.includes("the port is closed."):case t.includes("the port is closed or is not writable"):case t.includes("select another port please"):case t.includes("no port selected by the user"):case t.includes("this readable stream reader has been released and cannot be used to cancel its previous owner stream"):this.dispatch("serial:need-permission",{});break;case t.includes("the port is already open."):case t.includes("failed to open serial port"):this.serialDisconnect().then(async()=>{this.__internal__.aux_port_connector+=1,await this.serialConnect()});break;case t.includes("cannot read properties of undefined (reading 'writable')"):case t.includes("cannot read properties of null (reading 'writable')"):case t.includes("cannot read property 'writable' of null"):case t.includes("cannot read property 'writable' of undefined"):this.serialDisconnect().then(async()=>{await this.serialConnect()});break;case t.includes("'close' on 'serialport': a call to close() is already in progress."):break;case t.includes("failed to execute 'open' on 'serialport': a call to open() is already in progress."):break;case t.includes("the port is already closed."):break;case t.includes("the device has been lost"):this.dispatch("serial:lost",{});break;case t.includes("navigator.serial is undefined"):this.dispatch("serial:unsupported",{});break;default:console.error(e);break}this.dispatch("serial:error",e)}async serialConnect(){try{this.dispatch("serial:connecting",{});const e=await c(this,a,E).call(this);if(e.length>0)await this.serialPortsSaved(e);else{const r=this.serialFilters;this.__internal__.serial.port=await navigator.serial.requestPort({filters:r})}const t=this.__internal__.serial.port;if(!t)throw new Error("No port selected by the user");await t.open(this.serialConfigPort);const n=this;t.onconnect=r=>{n.dispatch("serial:connected",r),n.__internal__.serial.queue.length>0&&n.dispatch("internal:queue",{})},t.ondisconnect=async()=>{await n.disconnect()},await x(this.__internal__.serial.delay_first_connection),this.__internal__.timeout.until_response=setTimeout(async()=>{await n.timeout(n.__internal__.serial.bytes_connection??[],"connection:start")},this.__internal__.time.response_connection),this.__internal__.serial.last_action="connect",await c(this,a,m).call(this,this.__internal__.serial.bytes_connection??[]),this.dispatch("serial:sent",{action:"connect",bytes:this.__internal__.serial.bytes_connection}),this.__internal__.auto_response&&c(this,a,h).call(this,["DD","DD"],null),await c(this,a,I).call(this)}catch(e){this.serialErrors(e)}}async serialForget(){return await c(this,a,L).call(this)}decToHex(e){return typeof e=="string"&&(e=parseInt(e,10)),e.toString(16)}hexToDec(e){return parseInt(e,16)}hexMaker(e="00",t=2){return e.toString().padStart(t,"0").toLowerCase()}add0x(e){const t=[];return e.forEach((n,r)=>{t[r]="0x"+n}),t}bytesToHex(e){return this.add0x(Array.from(e,t=>this.hexMaker(t)))}async appendToQueue(e,t){const n=this.bytesToHex(e);if(["connect","connection:start"].includes(t)){if(this.__internal__.serial.connected)return;await this.serialConnect();return}this.__internal__.serial.queue.push({bytes:n,action:t}),this.dispatch("internal:queue",{})}serialSetConnectionConstant(e=1){throw new Error(`Method not implemented 'serialSetConnectionConstant' to listen on channel ${e}`)}serialMessage(e){throw console.log(e),new Error("Method not implemented 'serialMessage'")}serialCorruptMessage(e,t){throw console.log(e,t),new Error("Method not implemented 'serialCorruptMessage'")}clearSerialQueue(){this.__internal__.serial.queue=[]}sumHex(e){let t=0;return e.forEach(n=>{t+=parseInt(n,16)}),t.toString(16)}toString(){return JSON.stringify({__class:this.typeDevice,device_number:this.deviceNumber,uuid:this.uuid,connected:this.isConnected,connection:this.__internal__.serial.bytes_connection})}softReload(){c(this,a,O).call(this),this.dispatch("serial:soft-reload",{})}async sendConnect(){if(!this.__internal__.serial.bytes_connection)throw new Error("No connection bytes defined");await this.appendToQueue(this.__internal__.serial.bytes_connection,"connect")}async sendCustomCode({code:e=[]}={code:[]}){if(e===null||e.length===0)throw new Error("No data to send");await this.appendToQueue(e,"custom")}stringToArrayHex(e){return Array.from(e).map(t=>t.charCodeAt(0).toString(16))}stringToArrayBuffer(e,t=`
|
|
1
|
+
(function(_,s){typeof exports=="object"&&typeof module<"u"?s(exports):typeof define=="function"&&define.amd?define(["exports"],s):(_=typeof globalThis<"u"?globalThis:_||self,s(_.WebSerialCore={}))})(this,function(_){"use strict";var $=Object.defineProperty;var C=_=>{throw TypeError(_)};var V=(_,s,u)=>s in _?$(_,s,{enumerable:!0,configurable:!0,writable:!0,value:u}):_[s]=u;var f=(_,s,u)=>V(_,typeof s!="symbol"?s+"":s,u),Q=(_,s,u)=>s.has(_)||C("Cannot "+u);var T=(_,s,u)=>s.has(_)?C("Cannot add the same private member more than once"):s instanceof WeakSet?s.add(_):s.set(_,u);var c=(_,s,u)=>(Q(_,s,"access private method"),u);var a,E,m,h,A,U,D,k,I,L,P,q,M,R,N,O;const s=[];for(let o=0;o<256;++o)s.push((o+256).toString(16).slice(1));function u(o,i=0){return(s[o[i+0]]+s[o[i+1]]+s[o[i+2]]+s[o[i+3]]+"-"+s[o[i+4]]+s[o[i+5]]+"-"+s[o[i+6]]+s[o[i+7]]+"-"+s[o[i+8]]+s[o[i+9]]+"-"+s[o[i+10]]+s[o[i+11]]+s[o[i+12]]+s[o[i+13]]+s[o[i+14]]+s[o[i+15]]).toLowerCase()}let g;const H=new Uint8Array(16);function j(){if(!g){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");g=crypto.getRandomValues.bind(crypto)}return g(H)}const w={randomUUID:typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function B(o,i,e){var n;if(w.randomUUID&&!o)return w.randomUUID();o=o||{};const t=o.random??((n=o.rng)==null?void 0:n.call(o))??j();if(t.length<16)throw new Error("Random bytes length must be >= 16");return t[6]=t[6]&15|64,t[8]=t[8]&63|128,u(t)}class v extends CustomEvent{constructor(i,e){super(i,e)}}class y extends EventTarget{constructor(){super(...arguments);f(this,"__listeners__",{debug:!1});f(this,"__debug__",!1)}dispatch(e,t=null){const n=new v(e,{detail:t});this.dispatchEvent(n),this.__debug__&&this.dispatchEvent(new v("debug",{detail:{type:e,data:t}}))}dispatchAsync(e,t=null,n=100){const r=this;setTimeout(()=>{r.dispatch(e,t)},n)}on(e,t){typeof this.__listeners__[e]<"u"&&!this.__listeners__[e]&&(this.__listeners__[e]=!0),this.addEventListener(e,t)}off(e,t){this.removeEventListener(e,t)}serialRegisterAvailableListener(e){this.__listeners__[e]||(this.__listeners__[e]=!1)}get availableListeners(){return Object.keys(this.__listeners__).sort().map(t=>({type:t,listening:this.__listeners__[t]}))}}function x(o=100){return new Promise(i=>setTimeout(()=>i(),o))}function F(){return"serial"in navigator}const b={baudRate:9600,dataBits:8,stopBits:1,parity:"none",bufferSize:32768,flowControl:"none"};class W extends y{constructor({filters:e=null,config_port:t=b,no_device:n=1,device_listen_on_channel:r=1}={filters:null,config_port:b,no_device:1,device_listen_on_channel:1}){super();T(this,a);f(this,"__internal__",{auto_response:!1,device_number:1,aux_port_connector:0,last_error:{message:null,action:null,code:null,no_code:0},serial:{connected:!1,port:null,last_action:null,response:{length:null,buffer:new Uint8Array([]),as:"hex"},reader:null,input_done:null,output_done:null,input_stream:null,output_stream:null,keep_reading:!0,time_until_send_bytes:void 0,delay_first_connection:200,bytes_connection:null,filters:[],config_port:b,queue:[]},device:{type:"unknown",id:B(),listen_on_port:null},time:{response_connection:500,response_general:2e3},timeout:{until_response:0},interval:{reconnection:0}});if(!("serial"in navigator))throw new Error("Web Serial not supported");e&&(this.serialFilters=e),t&&(this.serialConfigPort=t),n&&c(this,a,N).call(this,n),r&&["number","string"].includes(typeof r)&&(this.listenOnChannel=r),c(this,a,P).call(this),c(this,a,q).call(this)}set listenOnChannel(e){if(typeof e=="string"&&(e=parseInt(e)),isNaN(e)||e<1||e>255)throw new Error("Invalid port number");this.__internal__.device.listen_on_port=e,this.__internal__.serial.bytes_connection=this.serialSetConnectionConstant(e)}get lastAction(){return this.__internal__.serial.last_action}get listenOnChannel(){return this.__internal__.device.listen_on_port??1}set serialFilters(e){this.__internal__.serial.filters=e}get serialFilters(){return this.__internal__.serial.filters}set serialConfigPort(e){this.__internal__.serial.config_port=e}get serialConfigPort(){return this.__internal__.serial.config_port}get isConnected(){return this.__internal__.serial.connected}get isDisconnected(){return!this.__internal__.serial.connected}get deviceNumber(){return this.__internal__.device_number}get uuid(){return this.__internal__.device.id}get typeDevice(){return this.__internal__.device.type}get queue(){return this.__internal__.serial.queue}async timeout(e,t){this.__internal__.last_error.message="Operation response timed out.",this.__internal__.last_error.action=t,this.__internal__.last_error.code=e,this.__internal__.timeout.until_response&&(clearTimeout(this.__internal__.timeout.until_response),this.__internal__.timeout.until_response=0),t==="connect"?(this.__internal__.serial.connected=!1,this.dispatch("serial:reconnect",{})):t==="connection:start"&&(await this.serialDisconnect(),this.__internal__.serial.connected=!1,this.__internal__.aux_port_connector+=1,await this.serialConnect()),this.dispatch("serial:timeout",{...this.__internal__.last_error,bytes:e,action:t})}async disconnect(e=null){await this.serialDisconnect(),this.__internal__.serial.connected=!1,this.__internal__.aux_port_connector=0,this.dispatch("serial:disconnected",e)}async connect(){return new Promise((e,t)=>{F()||t("Web Serial not supported"),setTimeout(async()=>{await x(499),await this.serialConnect(),this.isConnected?e(`${this.typeDevice} device ${this.deviceNumber} connected`):t(`${this.typeDevice} device ${this.deviceNumber} not connected`)},1)})}async serialDisconnect(){try{const e=this.__internal__.serial.reader,t=this.__internal__.serial.output_stream;e&&(await e.cancel().catch(r=>this.serialErrors(r)),await this.__internal__.serial.input_done),t&&(await t.getWriter().close(),await this.__internal__.serial.output_done),this.__internal__.serial.connected&&this.__internal__.serial&&this.__internal__.serial.port&&await this.__internal__.serial.port.close()}catch(e){this.serialErrors(e)}finally{this.__internal__.serial.reader=null,this.__internal__.serial.input_done=null,this.__internal__.serial.output_stream=null,this.__internal__.serial.output_done=null,this.__internal__.serial.connected=!1,this.__internal__.serial.port=null}}getResponseAsArrayBuffer(){this.__internal__.serial.response.as="arraybuffer"}getResponseAsArrayHex(){this.__internal__.serial.response.as="hex"}getResponseAsUint8Array(){this.__internal__.serial.response.as="uint8"}getResponseAsString(){this.__internal__.serial.response.as="string"}async serialPortsSaved(e){const t=this.serialFilters;if(this.__internal__.aux_port_connector<e.length){const n=this.__internal__.aux_port_connector;this.__internal__.serial.port=e[n]}else this.__internal__.aux_port_connector=0,this.__internal__.serial.port=await navigator.serial.requestPort({filters:t});if(!this.__internal__.serial.port)throw new Error("Select another port please")}serialErrors(e){const t=e.toString().toLowerCase();switch(!0){case t.includes("must be handling a user gesture to show a permission request"):case t.includes("the port is closed."):case t.includes("the port is closed or is not writable"):case t.includes("select another port please"):case t.includes("no port selected by the user"):case t.includes("this readable stream reader has been released and cannot be used to cancel its previous owner stream"):this.dispatch("serial:need-permission",{});break;case t.includes("the port is already open."):case t.includes("failed to open serial port"):this.serialDisconnect().then(async()=>{this.__internal__.aux_port_connector+=1,await this.serialConnect()});break;case t.includes("cannot read properties of undefined (reading 'writable')"):case t.includes("cannot read properties of null (reading 'writable')"):case t.includes("cannot read property 'writable' of null"):case t.includes("cannot read property 'writable' of undefined"):this.serialDisconnect().then(async()=>{await this.serialConnect()});break;case t.includes("'close' on 'serialport': a call to close() is already in progress."):break;case t.includes("failed to execute 'open' on 'serialport': a call to open() is already in progress."):break;case t.includes("the port is already closed."):break;case t.includes("the device has been lost"):this.dispatch("serial:lost",{});break;case t.includes("navigator.serial is undefined"):this.dispatch("serial:unsupported",{});break;default:console.error(e);break}this.dispatch("serial:error",e)}async serialConnect(){try{this.dispatch("serial:connecting",{});const e=await c(this,a,A).call(this);if(e.length>0)await this.serialPortsSaved(e);else{const r=this.serialFilters;this.__internal__.serial.port=await navigator.serial.requestPort({filters:r})}const t=this.__internal__.serial.port;if(!t)throw new Error("No port selected by the user");await t.open(this.serialConfigPort);const n=this;t.onconnect=r=>{n.dispatch("serial:connected",r),n.__internal__.serial.queue.length>0&&n.dispatch("internal:queue",{})},t.ondisconnect=async()=>{await n.disconnect()},await x(this.__internal__.serial.delay_first_connection),this.__internal__.timeout.until_response=setTimeout(async()=>{await n.timeout(n.__internal__.serial.bytes_connection??[],"connection:start")},this.__internal__.time.response_connection),this.__internal__.serial.last_action="connect",await c(this,a,m).call(this,this.__internal__.serial.bytes_connection??[]),this.dispatch("serial:sent",{action:"connect",bytes:this.__internal__.serial.bytes_connection}),this.__internal__.auto_response&&c(this,a,h).call(this,["DD","DD"],null),await c(this,a,I).call(this)}catch(e){this.serialErrors(e)}}async serialForget(){return await c(this,a,L).call(this)}decToHex(e){return typeof e=="string"&&(e=parseInt(e,10)),e.toString(16)}hexToDec(e){return parseInt(e,16)}hexMaker(e="00",t=2){return e.toString().padStart(t,"0").toLowerCase()}add0x(e){const t=[];return e.forEach((n,r)=>{t[r]="0x"+n}),t}bytesToHex(e){return this.add0x(Array.from(e,t=>this.hexMaker(t)))}async appendToQueue(e,t){const n=this.bytesToHex(e);if(["connect","connection:start"].includes(t)){if(this.__internal__.serial.connected)return;await this.serialConnect();return}this.__internal__.serial.queue.push({bytes:n,action:t}),this.dispatch("internal:queue",{})}serialSetConnectionConstant(e=1){throw new Error(`Method not implemented 'serialSetConnectionConstant' to listen on channel ${e}`)}serialMessage(e){throw console.log(e),new Error("Method not implemented 'serialMessage'")}serialCorruptMessage(e,t){throw console.log(e,t),new Error("Method not implemented 'serialCorruptMessage'")}clearSerialQueue(){this.__internal__.serial.queue=[]}sumHex(e){let t=0;return e.forEach(n=>{t+=parseInt(n,16)}),t.toString(16)}toString(){return JSON.stringify({__class:this.typeDevice,device_number:this.deviceNumber,uuid:this.uuid,connected:this.isConnected,connection:this.__internal__.serial.bytes_connection})}softReload(){c(this,a,O).call(this),this.dispatch("serial:soft-reload",{})}async sendConnect(){if(!this.__internal__.serial.bytes_connection)throw new Error("No connection bytes defined");await this.appendToQueue(this.__internal__.serial.bytes_connection,"connect")}async sendCustomCode({code:e=[]}={code:[]}){if(e===null||e.length===0)throw new Error("No data to send");await this.appendToQueue(e,"custom")}stringToArrayHex(e){return Array.from(e).map(t=>t.charCodeAt(0).toString(16))}stringToArrayBuffer(e,t=`
|
|
2
2
|
`){return this.parseStringToTextEncoder(e,t).buffer}parseStringToTextEncoder(e="",t=`
|
|
3
3
|
`){const n=new TextEncoder;return e+=t,n.encode(e)}parseStringToBytes(e="",t=`
|
|
4
|
-
`){const n=this.parseStringToTextEncoder(e,t);return Array.from(n).map(r=>r.toString(16))}parseUint8ToHex(e){return Array.from(e).map(t=>t.toString(16))}parseHexToUint8(e){return new Uint8Array(e.map(t=>parseInt(t,16)))}stringArrayToUint8Array(e){const t=[];return e.forEach(n=>{const r=n.replace("0x","");t.push(parseInt(r,16))}),new Uint8Array(t)}parseUint8ArrayToString(e){const t=this.stringArrayToUint8Array(e);e=this.parseUint8ToHex(t);const n=e.map(r=>parseInt(r,16));return String.fromCharCode(...n).replace(/[\n\r]+/g,"")}hexToAscii(e){const t=e.toString();let n="";for(let r=0;r<t.length;r+=2)n+=String.fromCharCode(parseInt(t.substring(r,2),16));return n}asciiToHex(e){const t=[];for(let n=0,r=e.length;n<r;n++){const p=Number(e.charCodeAt(n)).toString(16);t.push(p)}return t.join("")}}a=new WeakSet,
|
|
4
|
+
`){const n=this.parseStringToTextEncoder(e,t);return Array.from(n).map(r=>r.toString(16))}parseUint8ToHex(e){return Array.from(e).map(t=>t.toString(16))}parseHexToUint8(e){return new Uint8Array(e.map(t=>parseInt(t,16)))}stringArrayToUint8Array(e){const t=[];return e.forEach(n=>{const r=n.replace("0x","");t.push(parseInt(r,16))}),new Uint8Array(t)}parseUint8ArrayToString(e){const t=this.stringArrayToUint8Array(e);e=this.parseUint8ToHex(t);const n=e.map(r=>parseInt(r,16));return String.fromCharCode(...n).replace(/[\n\r]+/g,"")}hexToAscii(e){const t=e.toString();let n="";for(let r=0;r<t.length;r+=2)n+=String.fromCharCode(parseInt(t.substring(r,2),16));return n}asciiToHex(e){const t=[];for(let n=0,r=e.length;n<r;n++){const p=Number(e.charCodeAt(n)).toString(16);t.push(p)}return t.join("")}}a=new WeakSet,E=function(e){return!!(e.readable&&e.writable)},m=async function(e){const t=this.__internal__.serial.port;if(!t||!t.writable)throw new Error("The port is closed or is not writable");const n=this.stringArrayToUint8Array(e),r=t.writable.getWriter();await r.write(n),r.releaseLock()},h=function(e=[],t=null){if(e&&e.length>0){this.__internal__.serial.connected||this.dispatch("serial:connected"),this.__internal__.serial.connected=!0,this.__internal__.interval.reconnection&&(clearInterval(this.__internal__.interval.reconnection),this.__internal__.interval.reconnection=0),this.__internal__.timeout.until_response&&(clearTimeout(this.__internal__.timeout.until_response),this.__internal__.timeout.until_response=0);const n=[];for(const r in e)n.push(e[r].toString().padStart(2,"0").toLowerCase());if(this.__internal__.serial.response.as==="hex")this.serialMessage(n);else if(this.__internal__.serial.response.as==="uint8")this.serialMessage(this.parseHexToUint8(this.add0x(n)));else if(this.__internal__.serial.response.as==="string")this.serialMessage(this.parseUint8ArrayToString(this.add0x(n)));else{const r=this.stringToArrayBuffer(this.parseUint8ArrayToString(this.add0x(n)));this.serialMessage(r)}}else this.serialCorruptMessage(e,t);this.__internal__.serial.queue.length!==0&&this.dispatch("internal:queue",{})},A=async function(){const e=this.serialFilters,t=await navigator.serial.getPorts({filters:e});return e.length===0?t:t.filter(r=>{const p=r.getInfo();return e.some(S=>p.usbProductId===S.usbProductId&&p.usbVendorId===S.usbVendorId)}).filter(r=>!c(this,a,E).call(this,r))},U=function(e){if(e){const t=this.__internal__.serial.response.buffer,n=new Uint8Array(t.length+e.byteLength);n.set(t,0),n.set(new Uint8Array(e),t.length),this.__internal__.serial.response.buffer=n}},D=async function(){this.__internal__.serial.time_until_send_bytes&&(clearTimeout(this.__internal__.serial.time_until_send_bytes),this.__internal__.serial.time_until_send_bytes=0),this.__internal__.serial.time_until_send_bytes=setTimeout(()=>{const e=[];for(const t in this.__internal__.serial.response.buffer)e.push(this.__internal__.serial.response.buffer[t].toString(16));this.__internal__.serial.response.buffer&&c(this,a,h).call(this,e),this.__internal__.serial.response.buffer=new Uint8Array(0)},400)},k=async function(){if(this.__internal__.serial.response.length!==null){if(this.__internal__.serial.response.length===this.__internal__.serial.response.buffer.length){const e=[];for(const t in this.__internal__.serial.response.buffer)e.push(this.__internal__.serial.response.buffer[t].toString(16));c(this,a,h).call(this,e),this.__internal__.serial.response.buffer=new Uint8Array(0)}else if(this.__internal__.serial.response.length<this.__internal__.serial.response.buffer.length){let e=new Uint8Array(0);for(let n=0;n<this.__internal__.serial.response.length;n++)e[n]=this.__internal__.serial.response.buffer[n];if(e.length===this.__internal__.serial.response.length){const n=[];for(const r in e)n.push(e[r].toString(16));c(this,a,h).call(this,n),this.__internal__.serial.response.buffer=new Uint8Array(0);return}e=new Uint8Array(0);const t=this.__internal__.serial.response.length*2;if(this.__internal__.serial.response.buffer.length===t){for(let n=14;n<t;n++)e[n-this.__internal__.serial.response.length]=this.__internal__.serial.response.buffer[n];if(e.length===this.__internal__.serial.response.length){const n=[];for(const r in e)n.push(e[r].toString(16));c(this,a,h).call(this,n),this.__internal__.serial.response.buffer=new Uint8Array(0)}}}}},I=async function(){const e=this.__internal__.serial.port;if(!e||!e.readable)throw new Error("Port is not readable");for(;e.readable&&this.__internal__.serial.keep_reading;){const t=e.readable.getReader();this.__internal__.serial.reader=t;try{let n=!0;for(;n;){const{value:r,done:p}=await t.read();if(p){t.releaseLock(),this.__internal__.serial.keep_reading=!1,n=!1;break}c(this,a,U).call(this,r),this.__internal__.serial.response.length===null?await c(this,a,D).call(this):await c(this,a,k).call(this)}}catch(n){this.serialErrors(n)}finally{t.releaseLock()}}this.__internal__.serial.keep_reading=!0,this.__internal__.serial.port&&await this.__internal__.serial.port.close()},L=async function(){return typeof window>"u"?!1:"serial"in navigator&&"forget"in SerialPort.prototype&&this.__internal__.serial.port?(await this.__internal__.serial.port.forget(),!0):!1},P=function(){["serial:connected","serial:connecting","serial:reconnect","serial:timeout","serial:disconnected","serial:sent","serial:soft-reload","serial:message","unknown","serial:need-permission","serial:lost","serial:unsupported","serial:error","debug"].forEach(t=>{this.serialRegisterAvailableListener(t)})},q=function(){const e=this;this.on("internal:queue",async()=>{var t;await c(t=e,a,R).call(t)}),c(this,a,M).call(this)},M=function(){const e=this;navigator.serial.addEventListener("connect",async()=>{e.isDisconnected&&await e.serialConnect().catch(()=>{})})},R=async function(){if(!this.__internal__.serial.connected){await this.serialConnect();return}if(this.__internal__.timeout.until_response||this.__internal__.serial.queue.length===0)return;const e=this.__internal__.serial.queue[0];let t=this.__internal__.time.response_general;e.action==="connect"&&(t=this.__internal__.time.response_connection),this.__internal__.timeout.until_response=setTimeout(async()=>{await this.timeout(e.bytes,e.action)},t),this.__internal__.serial.last_action=e.action??"unknown",await c(this,a,m).call(this,e.bytes),this.dispatch("serial:sent",{action:e.action,bytes:e.bytes}),this.__internal__.auto_response&&c(this,a,h).call(this,["DD","DD"],null);const n=[...this.__internal__.serial.queue];this.__internal__.serial.queue=n.splice(1)},N=function(e=1){this.__internal__.device_number=e,this.__internal__.serial.bytes_connection=this.serialSetConnectionConstant(e)},O=function(){this.__internal__.last_error={message:null,action:null,code:null,no_code:0}};const l=class l extends y{static typeError(i){const e=new Error;throw e.message=`Type ${i} is not supported`,e.name="DeviceTypeError",e}static registerType(i){typeof l.devices[i]>"u"&&(l.devices[i]={})}static add(i){const e=i.typeDevice;typeof l.devices[e]>"u"&&(l.devices[e]={});const t=i.uuid;if(typeof l.devices[e]>"u"&&l.typeError(e),this.instance.dispatch("change",l.devices),l.devices[e][t])throw new Error(`Device with id ${t} already exists`);return l.devices[e][t]=i,this.instance.dispatch("change",l.devices),Object.keys(l.devices[e]).indexOf(t)}static get(i,e){return typeof l.devices[i]>"u"&&(l.devices[i]={}),typeof l.devices[i]>"u"&&l.typeError(i),l.devices[i][e]}static getAll(i=null){return i===null?l.devices:(typeof l.devices[i]>"u"&&l.typeError(i),l.devices[i])}static getList(){return Object.values(l.devices).map(e=>Object.values(e)).flat()}static getByNumber(i,e){return typeof l.devices[i]>"u"&&l.typeError(i),Object.values(l.devices[i]).find(n=>n.deviceNumber===e)??null}static getCustom(i,e=1){return typeof l.devices[i]>"u"&&l.typeError(i),Object.values(l.devices[i]).find(n=>n.deviceNumber===e)??null}};f(l,"instance"),f(l,"devices",{});let d=l;d.instance||(d.instance=new d),_.Core=W,_.Devices=d,_.Dispatcher=y,Object.defineProperty(_,Symbol.toStringTag,{value:"Module"})});
|