brilliantsole 0.0.28 → 0.0.29
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/build/brilliantsole.cjs +656 -158
- package/build/brilliantsole.cjs.map +1 -1
- package/build/brilliantsole.js +656 -158
- package/build/brilliantsole.js.map +1 -1
- package/build/brilliantsole.ls.js +656 -158
- package/build/brilliantsole.ls.js.map +1 -1
- package/build/brilliantsole.min.js +1 -1
- package/build/brilliantsole.min.js.map +1 -1
- package/build/brilliantsole.module.d.ts +75 -15
- package/build/brilliantsole.module.js +654 -159
- package/build/brilliantsole.module.js.map +1 -1
- package/build/brilliantsole.module.min.d.ts +75 -15
- package/build/brilliantsole.module.min.js +1 -1
- package/build/brilliantsole.module.min.js.map +1 -1
- package/build/brilliantsole.node.module.d.ts +75 -15
- package/build/brilliantsole.node.module.js +654 -159
- package/build/brilliantsole.node.module.js.map +1 -1
- package/build/dts/BS.d.ts +1 -0
- package/build/dts/Device.d.ts +25 -7
- package/build/dts/MicrophoneManager.d.ts +88 -0
- package/build/dts/connection/BaseConnectionManager.d.ts +2 -2
- package/build/dts/devicePair/DevicePair.d.ts +5 -5
- package/build/dts/sensor/SensorDataManager.d.ts +3 -3
- package/build/dts/utils/AudioUtils.d.ts +2 -0
- package/build/index.d.ts +75 -15
- package/build/index.node.d.ts +75 -15
- package/examples/basic/index.html +108 -53
- package/examples/basic/script.js +248 -21
- package/examples/camera/barcode-detector.js +109 -0
- package/examples/camera/depth-estimation.js +71 -0
- package/examples/camera/face-detector.js +119 -0
- package/examples/camera/face-landmark.js +111 -0
- package/examples/camera/gesture-recognition.js +97 -0
- package/examples/camera/hand-landmark.js +74 -0
- package/examples/camera/image-segmentation.js +98 -0
- package/examples/camera/image-to-text.js +43 -0
- package/examples/camera/image-upscale.js +75 -0
- package/examples/camera/index.html +129 -0
- package/examples/camera/object-detection.js +98 -0
- package/examples/camera/pose-landmark.js +60 -0
- package/examples/camera/script.js +316 -0
- package/examples/camera/utils.js +165 -0
- package/examples/camera/yolo-tiny.js +54 -0
- package/examples/camera/yolo.js +119 -0
- package/examples/edge-impulse/script.js +23 -5
- package/examples/glasses-gestures/README.md +11 -0
- package/examples/glasses-gestures/edge-impulse-standalone.js +7228 -0
- package/examples/glasses-gestures/edge-impulse-standalone.wasm +0 -0
- package/examples/glasses-gestures/index.html +69 -0
- package/examples/glasses-gestures/run-impulse.js +135 -0
- package/examples/glasses-gestures/script.js +226 -0
- package/examples/microphone/gender.js +54 -0
- package/examples/microphone/index.html +102 -0
- package/examples/microphone/script.js +394 -0
- package/examples/microphone/utils.js +45 -0
- package/examples/microphone/whisper-realtime.js +166 -0
- package/examples/microphone/whisper.js +132 -0
- package/examples/ukaton-firmware-update/merged-firmware.bin +0 -0
- package/examples/webxr-3/components/bs-camera.js +65 -0
- package/examples/webxr-3/index.html +134 -0
- package/examples/webxr-3/script.js +432 -0
- package/package.json +1 -1
- package/src/BS.ts +9 -0
- package/src/CameraManager.ts +4 -6
- package/src/Device.ts +110 -0
- package/src/MicrophoneManager.ts +599 -0
- package/src/connection/BaseConnectionManager.ts +2 -0
- package/src/sensor/SensorDataManager.ts +5 -0
- package/src/utils/AudioUtils.ts +65 -0
|
@@ -2,5 +2,5 @@
|
|
|
2
2
|
* @copyright Zack Qattan 2024
|
|
3
3
|
* @license MIT
|
|
4
4
|
*/
|
|
5
|
-
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).BS={})}(this,(function(e){"use strict";function t(e,t,s,i){if("a"===s&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===s?i:"a"===s?i.call(e):i?i.value:t.get(e)}function s(e,t,s,i,n){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?n.call(e,s):n?n.value=s:t.set(e,s),s}"function"==typeof SuppressedError&&SuppressedError;const i=!1,n="undefined"!=typeof window&&void 0!==window?.document,a="undefined"!=typeof process&&null!=process?.versions?.node,r=n&&navigator.userAgent||"";let o=!1;n?o=Boolean(navigator.bluetooth):a&&(o=!0);const c=n&&/Bluefy/i.test(r),h=n&&/WebBLE/i.test(r),l=n&&/Android/i.test(r),f=n&&/Safari/i.test(r)&&!/Chrome/i.test(r),g=n&&/iPad|iPhone|iPod/i.test(r),u=n&&/Macintosh/i.test(r),d=!n&&!a&&"undefined"!=typeof global&&"undefined"!=typeof Studio;var m,p,v,w,y=Object.freeze({__proto__:null,isAndroid:l,get isBluetoothSupported(){return o},isIOS:g,isInBluefy:c,isInBrowser:n,isInDev:i,isInLensStudio:d,isInNode:a,isInProduction:!0,isInWebBLE:h,isMac:u,isSafari:f});if(d){const e=function(...e){Studio.log(e.map((e=>new String(e))).join(","))};(w={}).log=e,w.warn=e.bind(w,"WARNING"),w.error=e.bind(w,"ERROR")}else w=console;function b(e){return(...t)=>{if(a){const s=function(){const e=(new Error).stack;if(!e)return"";const t=e.split("\n"),s=t[3]||t[2],i=s.match(/at (.*?) \(/)||s.match(/at (.*)/);return i?`[${i[1].trim()}]`:""}();e(s,...t)}else e(...t)}}if(!w.assert){const e=(e,...t)=>{e||w.warn(...t)};w.assert=e}if(!w.table){const e=(...e)=>{w.log(...e)};w.table=e}function S(){}const C=a?b(w.log.bind(w)):w.log.bind(w),E=a?b(w.warn.bind(w)):w.warn.bind(w),M=a?b(w.error.bind(w)):w.error.bind(w),k=a?b(w.table.bind(w)):w.table.bind(w),D=w.assert.bind(w);class T{constructor(e){if(v.set(this,{log:i,warn:i,assert:!0,error:!0,table:!0}),t(m,m,"f",p)[e])throw new Error(`"${e}" console already exists`);t(m,m,"f",p)[e]=this}setLevelFlags(e){Object.assign(t(this,v,"f"),e)}static setLevelFlagsForType(e,s){if(!t(this,m,"f",p)[e])throw new Error(`no console found with type "${e}"`);t(this,m,"f",p)[e].setLevelFlags(s)}static setAllLevelFlags(e){for(const s in t(this,m,"f",p))t(this,m,"f",p)[s].setLevelFlags(e)}static create(e,s){return t(this,m,"f",p)[e]||new m(e)}get log(){return t(this,v,"f").log?C:S}get warn(){return t(this,v,"f").warn?E:S}get error(){return t(this,v,"f").error?M:S}get assert(){return t(this,v,"f").assert?D:S}get table(){return t(this,v,"f").table?k:S}assertWithError(e,t){if(!Boolean(e))throw new Error(t)}assertTypeWithError(e,t){this.assertWithError(typeof e==t,`value ${e} of type "${typeof e}" not of type "${t}"`)}assertEnumWithError(e,t){this.assertWithError(t.includes(e),`invalid enum "${e}"`)}assertRangeWithError(e,t,s,i){this.assertWithError(t>=s&&t<=i,`${e} ${t} must be within ${s}-${i}`)}}function W(e,t){return T.create(e,t)}m=T,v=new WeakMap,p={value:{}};const I=W("EventDispatcher",{log:!1});class _{constructor(e,t){this.target=e,this.validEventTypes=t,this.listeners={},this.addEventListener=this.addEventListener.bind(this),this.removeEventListener=this.removeEventListener.bind(this),this.removeEventListeners=this.removeEventListeners.bind(this),this.removeAllEventListeners=this.removeAllEventListeners.bind(this),this.dispatchEvent=this.dispatchEvent.bind(this),this.waitForEvent=this.waitForEvent.bind(this)}isValidEventType(e){return this.validEventTypes.includes(e)}updateEventListeners(e){this.listeners[e]&&(this.listeners[e]=this.listeners[e].filter((t=>(t.shouldRemove&&I.log(`removing "${e}" eventListener`,t),!t.shouldRemove))))}addEventListener(e,t,s={once:!1}){if(!this.isValidEventType(e))throw new Error(`Invalid event type: ${e}`);this.listeners[e]||(this.listeners[e]=[],I.log(`creating "${e}" listeners array`,this.listeners[e]));this.listeners[e].find((e=>e.listener==t&&e.once==s.once))?I.log("already added listener"):(I.log(`adding "${e}" listener`,t,s),this.listeners[e].push({listener:t,once:s.once}),I.log(`currently have ${this.listeners[e].length} "${e}" listeners`))}removeEventListener(e,t){if(!this.isValidEventType(e))throw new Error(`Invalid event type: ${e}`);this.listeners[e]&&(I.log(`removing "${e}" listener...`,t),this.listeners[e].forEach((s=>{s.listener===t&&(I.log(`flagging "${e}" listener`,t),s.shouldRemove=!0)})),this.updateEventListeners(e))}removeEventListeners(e){if(!this.isValidEventType(e))throw new Error(`Invalid event type: ${e}`);this.listeners[e]&&(I.log(`removing "${e}" listeners...`),this.listeners[e]=[])}removeAllEventListeners(){I.log("removing listeners..."),this.listeners={}}dispatchEvent(e,t){if(!this.isValidEventType(e))throw new Error(`Invalid event type: ${e}`);this.listeners[e]&&(this.listeners[e].forEach((s=>{s.shouldRemove||(I.log(`dispatching "${e}" listener`,s),s.listener({type:e,target:this.target,message:t}),s.once&&(I.log(`flagging "${e}" listener`,s),s.shouldRemove=!0))})),this.updateEventListeners(e))}waitForEvent(e){return new Promise((t=>{this.addEventListener(e,(e=>{t(e)}),{once:!0})}))}}var L,U,F;const A=W("Timer",{log:!1});class R{get callback(){return t(this,L,"f")}set callback(e){A.assertTypeWithError(e,"function"),A.log({newCallback:e}),s(this,L,e,"f"),this.isRunning&&this.restart()}get interval(){return t(this,U,"f")}set interval(e){A.assertTypeWithError(e,"number"),A.assertWithError(e>0,"interval must be above 0"),A.log({newInterval:e}),s(this,U,e,"f"),this.isRunning&&this.restart()}constructor(e,t){L.set(this,void 0),U.set(this,void 0),F.set(this,void 0),this.interval=t,this.callback=e}get isRunning(){return null!=t(this,F,"f")}start(e=!1){this.isRunning?A.log("interval already running"):(A.log(`starting interval every ${t(this,U,"f")}ms`),s(this,F,setInterval(t(this,L,"f"),t(this,U,"f")),"f"),e&&t(this,L,"f").call(this))}stop(){this.isRunning?(A.log("stopping interval"),clearInterval(t(this,F,"f")),s(this,F,void 0,"f")):A.log("interval already not running")}restart(e=!1){this.stop(),this.start(e)}}function x(e){for(let t=0;t<8;++t)e=(1&e?0:3988292384)^e>>>1;return 4278190080^e}L=new WeakMap,U=new WeakMap,F=new WeakMap,W("checksum",{log:!1});const $=new Uint32Array(256);for(let e=0;e<256;++e)$[e]=x(e);function O(e){let t=new Uint8Array(e),s=0;for(let e=0;e<t.byteLength;++e){const i=255&s,n=t[e];s=($[i^n]^s>>>8)>>>0}return s}var B,P;B="undefined"==typeof TextEncoder?class{encode(e){const t=Array.from(e).map((e=>e.charCodeAt(0)));return Uint8Array.from(t)}}:TextEncoder,P="undefined"==typeof TextDecoder?class{decode(e){return Array.from(new Uint8Array(e)).map((e=>String.fromCharCode(e))).join("")}}:TextDecoder;const N=new B,V=new P,q=W("ArrayBufferUtils",{log:!1});function z(...e){const t=(e=(e=(e=e.filter((e=>null!=e||null!=e))).map((e=>{if("number"==typeof e){const t=e;return Uint8Array.from([Math.floor(t)])}if("boolean"==typeof e){const t=e;return Uint8Array.from([t?1:0])}if("string"==typeof e){return j(e)}if(e instanceof Array){return z(...e)}if(e instanceof ArrayBuffer)return e;if("buffer"in e&&e.buffer instanceof ArrayBuffer){return e.buffer}if(e instanceof DataView){return e.buffer}if("object"==typeof e){return function(e){return j(JSON.stringify(e))}(e)}return e}))).filter((e=>e&&"byteLength"in e))).reduce(((e,t)=>e+t.byteLength),0),s=new Uint8Array(t);let i=0;return e.forEach((e=>{s.set(new Uint8Array(e),i),i+=e.byteLength})),s.buffer}function j(e){const t=N.encode(e);return z(t.byteLength,t)}function G(e,t,s){let i;return null!=s&&(i=e.byteOffset+t+s),q.log({dataView:e,begin:t,end:i,length:s}),new DataView(e.buffer.slice(e.byteOffset+t,i))}async function H(e){let t;if(e instanceof Array)t=Uint8Array.from(e);else if(e instanceof DataView)t=e.buffer;else if("string"==typeof e||e instanceof URL){const s=await fetch(e);t=await s.arrayBuffer()}else if(e instanceof File)t=await e.arrayBuffer();else{if(!(e instanceof ArrayBuffer))throw{error:"invalid file type",file:e};t=e}return t}function J(e,{include:t,exclude:s}={}){const i=e=>{const i=t=>"string"==typeof t?e===t:t.test(e);return t?t.some(i):!s||!s.some(i)};for(const[t,s]of(e=>{const t=new Set;do{for(const s of Reflect.ownKeys(e))t.add([e,s])}while((e=Reflect.getPrototypeOf(e))&&e!==Object.prototype);return t})(e.constructor.prototype)){if("constructor"===s||!i(s))continue;const n=Reflect.getOwnPropertyDescriptor(t,s);n&&"function"==typeof n.value&&(e[s]=e[s].bind(e))}return e}var K,Q,Z,X,Y,ee,te,se,ie,ne,ae,re,oe,ce,he,le,fe,ge,ue,de,me,pe,ve,we,ye,be,Se,Ce,Ee,Me,ke,De,Te,We,Ie,_e,Le,Ue,Fe,Ae,Re;const xe=W("FileTransferManager",{log:!1}),$e=["getFileTypes","maxFileLength","getFileType","setFileType","getFileLength","setFileLength","getFileChecksum","setFileChecksum","setFileTransferCommand","fileTransferStatus","getFileBlock","setFileBlock","fileBytesTransferred"],Oe=["tflite","wifiServerCert","wifiServerKey"],Be=["idle","sending","receiving"],Pe=["startSend","startReceive","cancel"],Ne=[...$e,"fileTransferProgress","fileTransferComplete","fileReceived"],Ve=["maxFileLength","getFileLength","getFileChecksum","getFileType","fileTransferStatus"];class qe{constructor(){K.add(this),se.set(this,[]),ae.set(this,Q.MaxLength),he.set(this,void 0),ue.set(this,0),ve.set(this,0),Ce.set(this,"idle"),Te.set(this,[]),Ie.set(this,void 0),_e.set(this,0),Ae.set(this,!1),Re.set(this,!1),J(this)}get addEventListener(){return this.eventDispatcher.addEventListener}get removeEventListener(){return this.eventDispatcher.removeEventListener}get waitForEvent(){return this.eventDispatcher.waitForEvent}get fileTypes(){return t(this,se,"f")}static get MaxLength(){return t(this,Q,"f",ne)}get maxLength(){return t(this,ae,"f")}get type(){return t(this,he,"f")}get length(){return t(this,ue,"f")}get checksum(){return t(this,ve,"f")}get status(){return t(this,Ce,"f")}parseMessage(e,s){switch(xe.log({messageType:e}),e){case"getFileTypes":t(this,K,"m",ie).call(this,s);break;case"maxFileLength":t(this,K,"m",re).call(this,s);break;case"getFileType":case"setFileType":t(this,K,"m",le).call(this,s);break;case"getFileLength":case"setFileLength":t(this,K,"m",de).call(this,s);break;case"getFileChecksum":case"setFileChecksum":t(this,K,"m",we).call(this,s);break;case"fileTransferStatus":t(this,K,"m",Ee).call(this,s);break;case"getFileBlock":t(this,K,"m",We).call(this,s);break;case"fileBytesTransferred":t(this,K,"m",Fe).call(this,s);break;default:throw Error(`uncaught messageType ${e}`)}}async send(e,s){t(this,K,"m",ke).call(this),t(this,K,"m",X).call(this,e);const i=await H(s),n=i.byteLength,a=O(i);if(e!=this.type)xe.log("different fileTypes - sending");else if(n!=this.length)xe.log("different fileLengths - sending");else{if(a==this.checksum)return xe.log("already sent file"),!1;xe.log("different fileChecksums - sending")}const r=[];return r.push(t(this,K,"m",ge).call(this,e,!1)),r.push(t(this,K,"m",pe).call(this,n,!1)),r.push(t(this,K,"m",be).call(this,a,!1)),r.push(t(this,K,"m",Se).call(this,"startSend",!1)),this.sendMessage(),await Promise.all(r),await t(this,K,"m",Le).call(this,i),!0}async receive(e){t(this,K,"m",ke).call(this),t(this,K,"m",X).call(this,e),await t(this,K,"m",ge).call(this,e),await t(this,K,"m",Se).call(this,"startReceive")}async cancel(){t(this,K,"m",De).call(this),xe.log("cancelling file transfer..."),s(this,Ae,!0,"f"),await t(this,K,"m",Se).call(this,"cancel")}get isServerSide(){return t(this,Re,"f")}set isServerSide(e){t(this,Re,"f")!=e?(xe.log({newIsServerSide:e}),s(this,Re,e,"f")):xe.log("redundant isServerSide assignment")}requestRequiredInformation(){xe.log("requesting required fileTransfer information");const e=Ve.map((e=>({type:e})));this.sendMessage(e,!1)}}Q=qe,se=new WeakMap,ae=new WeakMap,he=new WeakMap,ue=new WeakMap,ve=new WeakMap,Ce=new WeakMap,Te=new WeakMap,Ie=new WeakMap,_e=new WeakMap,Ae=new WeakMap,Re=new WeakMap,K=new WeakSet,Z=function(){return this.eventDispatcher.dispatchEvent},X=function(e){xe.assertEnumWithError(e,Oe)},Y=function(e){xe.assertWithError(e in Oe,`invalid typeEnum ${e}`)},ee=function(e){xe.assertWithError(e in Be,`invalid statusEnum ${e}`)},te=function(e){xe.assertEnumWithError(e,Pe)},ie=function(e){const i=Array.from(new Uint8Array(e.buffer)).map((e=>Oe[e])).filter(Boolean);s(this,se,i,"f"),xe.log("fileTypes",i),t(this,K,"a",Z).call(this,"getFileTypes",{fileTypes:t(this,se,"f")})},re=function(e){xe.log("parseFileMaxLength",e);const s=e.getUint32(0,!0);xe.log(`maxLength: ${s/1024}kB`),t(this,K,"m",oe).call(this,s)},oe=function(e){xe.log({maxLength:e}),s(this,ae,e,"f"),t(this,K,"a",Z).call(this,"maxFileLength",{maxFileLength:e})},ce=function(e){xe.assertWithError(e<=this.maxLength,`file length ${e}kB too large - must be ${this.maxLength}kB or less`)},le=function(e){xe.log("parseFileType",e);const s=e.getUint8(0);t(this,K,"m",Y).call(this,s);const i=Oe[s];t(this,K,"m",fe).call(this,i)},fe=function(e){xe.log({fileTransferType:e}),s(this,he,e,"f"),t(this,K,"a",Z).call(this,"getFileType",{fileType:e})},ge=async function(e,s){if(t(this,K,"m",X).call(this,e),this.type==e)return void xe.log(`redundant type assignment ${e}`);const i=this.waitForEvent("getFileType"),n=Oe.indexOf(e);this.sendMessage([{type:"setFileType",data:Uint8Array.from([n]).buffer}],s),await i},de=function(e){xe.log("parseFileLength",e);const s=e.getUint32(0,!0);t(this,K,"m",me).call(this,s)},me=function(e){xe.log(`length: ${e/1024}kB`),s(this,ue,e,"f"),t(this,K,"a",Z).call(this,"getFileLength",{fileLength:e})},pe=async function(e,s){if(xe.assertTypeWithError(e,"number"),t(this,K,"m",ce).call(this,e),this.length==e)return void xe.log(`redundant length assignment ${e}`);const i=this.waitForEvent("getFileLength"),n=new DataView(new ArrayBuffer(4));n.setUint32(0,e,!0),this.sendMessage([{type:"setFileLength",data:n.buffer}],s),await i},we=function(e){xe.log("checksum",e);const s=e.getUint32(0,!0);t(this,K,"m",ye).call(this,s)},ye=function(e){xe.log({checksum:e}),s(this,ve,e,"f"),t(this,K,"a",Z).call(this,"getFileChecksum",{fileChecksum:e})},be=async function(e,t){if(xe.assertTypeWithError(e,"number"),this.checksum==e)return void xe.log(`redundant checksum assignment ${e}`);const s=this.waitForEvent("getFileChecksum"),i=new DataView(new ArrayBuffer(4));i.setUint32(0,e,!0),this.sendMessage([{type:"setFileChecksum",data:i.buffer}],t),await s},Se=async function(e,s){t(this,K,"m",te).call(this,e);const i=this.waitForEvent("fileTransferStatus");xe.log(`setting command ${e}`);const n=Pe.indexOf(e);this.sendMessage([{type:"setFileTransferCommand",data:Uint8Array.from([n]).buffer}],s),await i},Ee=function(e){xe.log("parseFileStatus",e);const s=e.getUint8(0);t(this,K,"m",ee).call(this,s);const i=Be[s];t(this,K,"m",Me).call(this,i)},Me=function(e){xe.log({status:e}),s(this,Ce,e,"f"),t(this,K,"a",Z).call(this,"fileTransferStatus",{fileTransferStatus:e}),t(this,Te,"f").length=0,s(this,Ae,!1,"f")},ke=function(){xe.assertWithError("idle"==t(this,Ce,"f"),"status is not idle")},De=function(){xe.assertWithError("idle"!=t(this,Ce,"f"),"status is idle")},We=async function(e){xe.log("parseFileBlock",e),t(this,Te,"f").push(e.buffer);const s=t(this,Te,"f").reduce(((e,t)=>e+t.byteLength),0),i=s/t(this,ue,"f");if(xe.log(`received ${s} of ${t(this,ue,"f")} bytes (${100*i}%)`),t(this,K,"a",Z).call(this,"fileTransferProgress",{progress:i}),s!=t(this,ue,"f")){const e=new DataView(new ArrayBuffer(4));if(e.setUint32(0,s,!0),this.isServerSide)return;return void await this.sendMessage([{type:"fileBytesTransferred",data:e.buffer}])}xe.log("file transfer complete");let n,a=(new Date).toLocaleString();switch(this.type){case"tflite":a+=".tflite";break;case"wifiServerCert":a+="_server.crt";break;case"wifiServerKey":a+="_server.key"}n="undefined"!=typeof File?new File(t(this,Te,"f"),a):new Blob(t(this,Te,"f"));const r=O(await n.arrayBuffer());xe.log({checksum:r}),r==t(this,ve,"f")?(xe.log("received file",n),t(this,K,"a",Z).call(this,"getFileBlock",{fileTransferBlock:e}),t(this,K,"a",Z).call(this,"fileTransferComplete",{direction:"receiving"}),t(this,K,"a",Z).call(this,"fileReceived",{file:n})):xe.error(`wrong checksum - expected ${t(this,ve,"f")}, got ${r}`)},Le=async function(e){return s(this,Ie,e,"f"),s(this,_e,0,"f"),t(this,K,"m",Ue).call(this)},Ue=async function(){if("sending"!=this.status)return;if(t(this,Ae,"f"))return void xe.error("not sending block - busy cancelling");if(!t(this,Ie,"f"))return void(this.isServerSide||xe.error("no buffer defined"));const e=t(this,Ie,"f");let i=t(this,_e,"f");const n=e.slice(i,i+(this.mtu-3-3));xe.log("slicedBuffer",n);const a=1-(e.byteLength-i)/e.byteLength;xe.log(`sending bytes ${i}-${i+n.byteLength} of ${e.byteLength} bytes (${100*a}%)`),t(this,K,"a",Z).call(this,"fileTransferProgress",{progress:a}),0==n.byteLength?(xe.log("finished sending buffer"),t(this,K,"a",Z).call(this,"fileTransferComplete",{direction:"sending"})):(await this.sendMessage([{type:"setFileBlock",data:n}]),s(this,_e,i+n.byteLength,"f"))},Fe=async function(e){xe.log("parseBytesTransferred",e);const s=e.getUint32(0,!0);if(xe.log({bytesTransferred:s}),"sending"==this.status)return this.isServerSide||t(this,_e,"f")==s?void t(this,K,"m",Ue).call(this):(xe.error(`bytesTransferred are not equal - got ${s}, expected ${t(this,_e,"f")}`),void this.cancel());xe.error("not currently sending file")},ne={value:0};const ze=W("MathUtils",{log:!1});const je=65536;function Ge(e,t){const s=Date.now();var i;let n=(i=s)-i%je+e.getUint16(t,!0);return Math.abs(s-n)>6e4&&(ze.log("correcting timestamp delta"),n+=je*Math.sign(s-n)),n}var He,Je,Ke;const Qe={min:1/0,max:-1/0,span:0};class Ze{constructor(){He.add(this),Je.set(this,Object.assign({},Qe))}get min(){return t(this,Je,"f").min}get max(){return t(this,Je,"f").max}set min(e){t(this,Je,"f").min=e,t(this,Je,"f").max=Math.max(e,t(this,Je,"f").max),t(this,He,"m",Ke).call(this)}set max(e){t(this,Je,"f").max=e,t(this,Je,"f").min=Math.min(e,t(this,Je,"f").min),t(this,He,"m",Ke).call(this)}reset(){Object.assign(t(this,Je,"f"),Qe)}update(e){t(this,Je,"f").min=Math.min(e,t(this,Je,"f").min),t(this,Je,"f").max=Math.max(e,t(this,Je,"f").max),t(this,He,"m",Ke).call(this)}getNormalization(e,s){let i=function(e,t,s,i){return null==i&&(i=s-t),(e-t)/i}(e,t(this,Je,"f").min,t(this,Je,"f").max,t(this,Je,"f").span);return s&&(i*=t(this,Je,"f").span),i||0}updateAndGetNormalization(e,t){return this.update(e),this.getNormalization(e,t)}}var Xe,Ye,et,tt,st;Je=new WeakMap,He=new WeakSet,Ke=function(){t(this,Je,"f").span=t(this,Je,"f").max-t(this,Je,"f").min};class it{constructor(){Xe.set(this,{x:new Ze,y:new Ze})}reset(){t(this,Xe,"f").x.reset(),t(this,Xe,"f").y.reset()}update(e){t(this,Xe,"f").x.update(e.x),t(this,Xe,"f").y.update(e.y)}getNormalization(e,s){return{x:t(this,Xe,"f").x.getNormalization(e.x,s),y:t(this,Xe,"f").y.getNormalization(e.y,s)}}updateAndGetNormalization(e,t){return this.update(e),this.getNormalization(e,t)}}Xe=new WeakMap;const nt=W("PressureDataManager",{log:!1}),at=["pressure"],rt=at;class ot{constructor(){Ye.set(this,[]),et.set(this,void 0),tt.set(this,new Ze),st.set(this,new it)}get positions(){return t(this,Ye,"f")}get numberOfSensors(){return this.positions.length}parsePositions(e){const t=[];for(let s=0,i=0;i<e.byteLength;s++,i+=2)t.push({x:e.getUint8(i)/256,y:e.getUint8(i+1)/256});var i,n;nt.log({positions:t}),s(this,Ye,t,"f"),s(this,et,(i=this.numberOfSensors,n=()=>new Ze,new Array(i).fill(1).map(((e,t)=>{if("function"==typeof n)return n(t);{const e=n;return Object.assign({},e)}}))),"f"),this.resetRange()}resetRange(){t(this,et,"f")?.forEach((e=>e.reset())),t(this,st,"f").reset(),t(this,tt,"f").reset()}parseData(e,s){const i={sensors:[],scaledSum:0,normalizedSum:0};for(let n=0,a=0;a<e.byteLength;n++,a+=2){const r=e.getUint16(a,!0);let o=r*s/this.numberOfSensors;const c=t(this,et,"f")[n].updateAndGetNormalization(o,!1),h=this.positions[n];i.sensors[n]={rawValue:r,scaledValue:o,normalizedValue:c,position:h,weightedValue:0},i.scaledSum+=o}return i.normalizedSum=t(this,tt,"f").updateAndGetNormalization(i.scaledSum,!1),i.scaledSum>0&&(i.center={x:0,y:0},i.sensors.forEach((e=>{e.weightedValue=e.scaledValue/i.scaledSum,i.center.x+=e.position.x*e.weightedValue,i.center.y+=e.position.y*e.weightedValue})),i.normalizedCenter=t(this,st,"f").updateAndGetNormalization(i.center,!1)),nt.log({pressure:i}),i}}Ye=new WeakMap,et=new WeakMap,tt=new WeakMap,st=new WeakMap;const ct=W("MotionSensorDataManager",{log:!1}),ht=["still","walking","running","bicycle","vehicle","tilting"],lt=["portraitUpright","landscapeLeft","portraitUpsideDown","landscapeRight","unknown"];class ft{parseVector3(e,t){let[s,i,n]=[e.getInt16(0,!0),e.getInt16(2,!0),e.getInt16(4,!0)].map((e=>e*t));const a={x:s,y:i,z:n};return ct.log({vector:a}),a}parseQuaternion(e,t){let[s,i,n,a]=[e.getInt16(0,!0),e.getInt16(2,!0),e.getInt16(4,!0),e.getInt16(6,!0)].map((e=>e*t));const r={x:s,y:i,z:n,w:a};return ct.log({quaternion:r}),r}parseEuler(e,t){let[s,i,n]=[e.getInt16(0,!0),e.getInt16(2,!0),e.getInt16(4,!0)].map((e=>e*t));i*=-1,s*=-1,s<0&&(s+=360);const a={heading:s,pitch:i,roll:n};return ct.log({euler:a}),a}parseStepCounter(e){ct.log("parseStepCounter",e);const t=e.getUint32(0,!0);return ct.log({stepCount:t}),t}parseActivity(e){ct.log("parseActivity",e);const t={},s=e.getUint8(0);return ct.log("activityBitfield",s.toString(2)),ht.forEach(((e,i)=>{t[e]=Boolean(s&1<<i)})),ct.log("activity",t),t}parseDeviceOrientation(e){ct.log("parseDeviceOrientation",e);const t=e.getUint8(0),s=lt[t];return ct.assertWithError(s,"undefined deviceOrientation"),ct.log({deviceOrientation:s}),s}}var gt,ut;const dt=["barometer"],mt=dt,pt=W("BarometerSensorDataManager",{log:!1});class vt{constructor(){gt.add(this)}parseData(e,s){const i=e.getUint32(0,!0)*s,n=t(this,gt,"m",ut).call(this,i);return pt.log({pressure:i,altitude:n}),{pressure:i}}}gt=new WeakSet,ut=function(e){const t=.0065;return 288.15/t*(1-Math.pow(e/101325,.19026643566373183))};const wt=W("ParseUtils",{log:!1});function yt(e,t=0){const s=e.getUint8(t++);return{string:V.decode(e.buffer.slice(e.byteOffset+t,e.byteOffset+t+s)),byteOffset:t+=s}}function bt(e,t,s,i,n=!1){let a=0;for(;a<e.byteLength;){const r=e.getUint8(a++);wt.assertWithError(r in t,`invalid messageTypeEnum ${r}`);const o=t[r];let c;n?(c=e.getUint16(a,!0),a+=2):c=e.getUint8(a++),wt.log({messageTypeEnum:r,messageType:o,messageLength:c,dataView:e,byteOffset:a});const h=G(e,a,c);wt.log({_dataView:h}),s(o,h,i),a+=c}}var St,Ct,Et,Mt,kt,Dt,Tt,Wt,It,_t,Lt,Ut,Ft,At,Rt,xt,$t,Ot,Bt,Pt,Nt,Vt,qt,zt,jt,Gt,Ht,Jt,Kt;const Qt=W("CameraManager",{log:!1}),Zt=["focus","takePicture","stop","sleep","wake"],Xt=["idle","focusing","takingPicture","asleep"],Yt=["headerSize","header","imageSize","image","footerSize","footer"],es=["resolution","qualityFactor","shutter","gain","redGain","greenGain","blueGain"],ts=["cameraStatus","cameraCommand","getCameraConfiguration","setCameraConfiguration","cameraData"],ss=["getCameraConfiguration","cameraStatus"],is=[...ts,"cameraImageProgress","cameraImage"];class ns{constructor(){St.add(this),Mt.set(this,void 0),Ut.set(this,0),Ft.set(this,void 0),At.set(this,0),Rt.set(this,0),xt.set(this,void 0),$t.set(this,0),Ot.set(this,0),Bt.set(this,void 0),Pt.set(this,0),Nt.set(this,!1),qt.set(this,{}),zt.set(this,void 0),jt.set(this,{resolution:{min:100,max:720},qualityFactor:{min:15,max:60},shutter:{min:4,max:16383},gain:{min:1,max:248},redGain:{min:0,max:1023},greenGain:{min:0,max:1023},blueGain:{min:0,max:1023}}),J(this)}get waitForEvent(){return this.eventDispatcher.waitForEvent}requestRequiredInformation(){Qt.log("requesting required camera information");const e=ss.map((e=>({type:e})));this.sendMessage(e,!1)}get cameraStatus(){return t(this,Mt,"f")}async focus(){t(this,St,"m",It).call(this),await t(this,St,"m",Tt).call(this,"focus")}async takePicture(){t(this,St,"m",It).call(this),await t(this,St,"m",Tt).call(this,"takePicture")}async stop(){t(this,St,"m",It).call(this),await t(this,St,"m",Tt).call(this,"stop")}async sleep(){t(this,St,"m",It).call(this),await t(this,St,"m",Tt).call(this,"sleep")}async wake(){t(this,St,"m",Wt).call(this),await t(this,St,"m",Tt).call(this,"wake")}get cameraConfiguration(){return t(this,qt,"f")}get availableCameraConfigurationTypes(){return t(this,zt,"f")}get cameraConfigurationRanges(){return t(this,jt,"f")}async setCameraConfiguration(e){if(Qt.log({newCameraConfiguration:e}),t(this,St,"m",Ht).call(this,e))return void Qt.log("redundant camera configuration");const s=t(this,St,"m",Kt).call(this,e);Qt.log({setCameraConfigurationData:s});const i=this.waitForEvent("getCameraConfiguration");this.sendMessage([{type:"setCameraConfiguration",data:s.buffer}]),await i}static AssertValidCameraConfigurationType(e){Qt.assertEnumWithError(e,es)}static AssertValidCameraConfigurationTypeEnum(e){Qt.assertTypeWithError(e,"number"),Qt.assertWithError(e in es,`invalid cameraConfigurationTypeEnum ${e}`)}parseMessage(e,s){switch(Qt.log({messageType:e,dataView:s}),e){case"cameraStatus":t(this,St,"m",kt).call(this,s);break;case"getCameraConfiguration":case"setCameraConfiguration":t(this,St,"m",Gt).call(this,s);break;case"cameraData":t(this,St,"m",_t).call(this,s);break;default:throw Error(`uncaught messageType ${e}`)}}clear(){s(this,Mt,void 0,"f"),s(this,At,0,"f"),s(this,$t,0,"f"),s(this,Pt,0,"f")}}var as;Ct=ns,Mt=new WeakMap,Ut=new WeakMap,Ft=new WeakMap,At=new WeakMap,Rt=new WeakMap,xt=new WeakMap,$t=new WeakMap,Ot=new WeakMap,Bt=new WeakMap,Pt=new WeakMap,Nt=new WeakMap,qt=new WeakMap,zt=new WeakMap,jt=new WeakMap,St=new WeakSet,Et=function(){return this.eventDispatcher.dispatchEvent},kt=function(e){const s=e.getUint8(0),i=Xt[s];t(this,St,"m",Dt).call(this,i)},Dt=function(e){if(Qt.assertEnumWithError(e,Xt),e==t(this,Mt,"f"))return void Qt.log(`redundant cameraStatus ${e}`);const i=t(this,Mt,"f");s(this,Mt,e,"f"),Qt.log(`updated cameraStatus to "${this.cameraStatus}"`),t(this,St,"a",Et).call(this,"cameraStatus",{cameraStatus:this.cameraStatus,previousCameraStatus:i}),"takingPicture"!=t(this,Mt,"f")&&t(this,$t,"f")>0&&!t(this,Nt,"f")&&t(this,St,"m",Vt).call(this)},Tt=async function(e,t){Qt.assertEnumWithError(e,Zt),Qt.log(`sending camera command "${e}"`);const s=this.waitForEvent("cameraStatus");Qt.log(`setting command "${e}"`);const i=Zt.indexOf(e);this.sendMessage([{type:"cameraCommand",data:Uint8Array.from([i]).buffer}],t),await s},Wt=function(){Qt.assertWithError("asleep"==t(this,Mt,"f"),`camera is not asleep - currently ${t(this,Mt,"f")}`)},It=function(){Qt.assertWithError("asleep"!=t(this,Mt,"f"),`camera is not awake - currently ${t(this,Mt,"f")}`)},_t=function(e){Qt.log("parsing camera data",e),bt(e,Yt,t(this,St,"m",Lt).bind(this),null,!0)},Lt=function(e,i){switch(Qt.log({cameraDataType:e,dataView:i}),e){case"headerSize":s(this,Ut,i.getUint16(0,!0),"f"),Qt.log({headerSize:t(this,Ut,"f")}),s(this,Ft,void 0,"f"),t(this,At,"f");break;case"header":s(this,Ft,z(t(this,Ft,"f"),i),"f"),Qt.log({headerData:t(this,Ft,"f")}),s(this,At,t(this,Ft,"f")?.byteLength/t(this,Ut,"f"),"f"),Qt.log({headerProgress:t(this,At,"f")}),t(this,St,"a",Et).call(this,"cameraImageProgress",{progress:t(this,At,"f"),type:"header"}),1==t(this,At,"f")&&Qt.log("finished getting header data");break;case"imageSize":s(this,Rt,i.getUint16(0,!0),"f"),Qt.log({imageSize:t(this,Rt,"f")}),s(this,xt,void 0,"f"),t(this,$t,"f"),s(this,Nt,!1,"f");break;case"image":s(this,xt,z(t(this,xt,"f"),i),"f"),Qt.log({imageData:t(this,xt,"f")}),s(this,$t,t(this,xt,"f")?.byteLength/t(this,Rt,"f"),"f"),Qt.log({imageProgress:t(this,$t,"f")}),1==t(this,$t,"f")&&(Qt.log("finished getting image data"),1==t(this,At,"f")&&t(this,St,"m",Vt).call(this)),t(this,St,"a",Et).call(this,"cameraImageProgress",{progress:t(this,$t,"f"),type:"image"});break;case"footerSize":s(this,Ot,i.getUint16(0,!0),"f"),Qt.log({footerSize:t(this,Ot,"f")}),s(this,Bt,void 0,"f"),t(this,Pt,"f");break;case"footer":s(this,Bt,z(t(this,Bt,"f"),i),"f"),Qt.log({footerData:t(this,Bt,"f")}),s(this,Pt,t(this,Bt,"f")?.byteLength/t(this,Ot,"f"),"f"),Qt.log({footerProgress:t(this,Pt,"f")}),t(this,St,"a",Et).call(this,"cameraImageProgress",{progress:t(this,Pt,"f"),type:"footer"}),1==t(this,Pt,"f")&&(Qt.log("finished getting footer data"),1==t(this,$t,"f")&&t(this,St,"m",Vt).call(this))}},Vt=function(){Qt.log("building image...");const e=z(t(this,Ft,"f"),t(this,xt,"f"),t(this,Bt,"f"));Qt.log({imageData:e});let i=new Blob([e],{type:"image/jpeg"});Qt.log("created blob",i);const n=URL.createObjectURL(i);Qt.log("created url",n),t(this,St,"a",Et).call(this,"cameraImage",{url:n,blob:i}),s(this,Nt,!0,"f")},Gt=function(e){const i={};let n=0;for(;n<e.byteLength;){const t=e.getUint8(n++),s=es[t];Qt.assertWithError(s,`invalid cameraConfigurationTypeIndex ${t}`),i[s]=e.getUint16(n,!0),n+=2}Qt.log({parsedCameraConfiguration:i}),s(this,zt,Object.keys(i),"f"),s(this,qt,i,"f"),t(this,St,"a",Et).call(this,"getCameraConfiguration",{cameraConfiguration:t(this,qt,"f")})},Ht=function(e){return Object.keys(e).every((t=>this.cameraConfiguration[t]==e[t]))},Jt=function(e){Qt.assertWithError(t(this,zt,"f"),"must get initial cameraConfiguration");const s=t(this,zt,"f")?.includes(e);return Qt.assertWithError(s,`unavailable camera configuration type "${e}"`),s},Kt=function(e){let s=Object.keys(e);s=s.filter((e=>t(this,St,"m",Jt).call(this,e)));const i=new DataView(new ArrayBuffer(3*s.length));return s.forEach(((t,s)=>{Ct.AssertValidCameraConfigurationType(t);const n=es.indexOf(t);i.setUint8(3*s,n);const a=e[t];i.setUint16(3*s+1,a,!0)})),Qt.log({sensorConfigurationData:i}),i};const rs=W("SensorDataManager",{log:!1}),os=[...at,"acceleration","gravity","linearAcceleration","gyroscope","magnetometer","gameRotation","rotation","orientation","activity","stepCounter","stepDetector","deviceOrientation","tapDetector",...dt,"camera"],cs=[...rt,"acceleration","gravity","linearAcceleration","gyroscope","magnetometer","gameRotation","rotation","orientation",...mt],hs=["getPressurePositions","getSensorScalars","sensorData"],ls=["getPressurePositions"],fs=[...hs,...os];class gs{constructor(){this.pressureSensorDataManager=new ot,this.motionSensorDataManager=new ft,this.barometerSensorDataManager=new vt,as.set(this,new Map)}static AssertValidSensorType(e){rs.assertEnumWithError(e,os)}static AssertValidSensorTypeEnum(e){rs.assertTypeWithError(e,"number"),rs.assertWithError(e in os,`invalid sensorTypeEnum ${e}`)}get dispatchEvent(){return this.eventDispatcher.dispatchEvent}parseMessage(e,t){switch(rs.log({messageType:e}),e){case"getSensorScalars":this.parseScalars(t);break;case"getPressurePositions":this.pressureSensorDataManager.parsePositions(t);break;case"sensorData":this.parseData(t);break;default:throw Error(`uncaught messageType ${e}`)}}parseScalars(e){for(let s=0;s<e.byteLength;s+=5){const i=e.getUint8(s),n=os[i];if(!n){rs.warn(`unknown sensorType index ${i}`);continue}const a=e.getFloat32(s+1,!0);rs.log({sensorType:n,sensorScalar:a}),t(this,as,"f").set(n,a)}}parseData(e){rs.log("sensorData",Array.from(new Uint8Array(e.buffer)));let t=0;const s=Ge(e,t);t+=2;bt(new DataView(e.buffer,t),os,this.parseDataCallback.bind(this),{timestamp:s})}parseDataCallback(e,s,{timestamp:i}){const n=t(this,as,"f").get(e)||1;let a=null;switch(e){case"pressure":a=this.pressureSensorDataManager.parseData(s,n);break;case"acceleration":case"gravity":case"linearAcceleration":case"gyroscope":case"magnetometer":a=this.motionSensorDataManager.parseVector3(s,n);break;case"gameRotation":case"rotation":a=this.motionSensorDataManager.parseQuaternion(s,n);break;case"orientation":a=this.motionSensorDataManager.parseEuler(s,n);break;case"stepCounter":a=this.motionSensorDataManager.parseStepCounter(s);break;case"stepDetector":case"tapDetector":a={};break;case"activity":a=this.motionSensorDataManager.parseActivity(s);break;case"deviceOrientation":a=this.motionSensorDataManager.parseDeviceOrientation(s);break;case"barometer":a=this.barometerSensorDataManager.parseData(s,n);break;case"camera":return;default:rs.error(`uncaught sensorType "${e}"`)}rs.assertWithError(null!=a,`no sensorData defined for sensorType "${e}"`),rs.log({sensorType:e,sensorData:a}),this.dispatchEvent(e,{sensorType:e,[e]:a,timestamp:i}),this.dispatchEvent("sensorData",{sensorType:e,[e]:a,timestamp:i})}}var us,ds,ms,ps,vs,ws,ys,bs,Ss,Cs,Es,Ms,ks;as=new WeakMap;const Ds=W("SensorConfigurationManager",{log:!1}),Ts=["getSensorConfiguration","setSensorConfiguration"],Ws=Ts;class Is{constructor(){us.add(this),ps.set(this,void 0),ws.set(this,{}),J(this)}get addEventListener(){return this.eventDispatcher.addEventListener}get waitForEvent(){return this.eventDispatcher.waitForEvent}get configuration(){return t(this,ws,"f")}async setConfiguration(e,s){if(s&&(e=Object.assign({...this.zeroSensorConfiguration},e)),Ds.log({newSensorConfiguration:e}),t(this,us,"m",bs).call(this,e))return void Ds.log("redundant sensor configuration");const i=t(this,us,"m",Ms).call(this,e);Ds.log({setSensorConfigurationData:i});const n=this.waitForEvent("getSensorConfiguration");this.sendMessage([{type:"setSensorConfiguration",data:i.buffer}]),await n}static get ZeroSensorConfiguration(){return t(this,ds,"f",ks)}get zeroSensorConfiguration(){const e={};return t(this,ps,"f").forEach((t=>{e[t]=0})),e}async clearSensorConfiguration(){return this.setConfiguration(this.zeroSensorConfiguration)}parseMessage(e,s){switch(Ds.log({messageType:e}),e){case"getSensorConfiguration":case"setSensorConfiguration":const i=t(this,us,"m",Ss).call(this,s);t(this,us,"m",ys).call(this,i);break;default:throw Error(`uncaught messageType ${e}`)}}}var _s,Ls,Us,Fs,As,Rs,xs,$s,Os,Bs,Ps,Ns,Vs,qs,zs,js,Gs,Hs,Js,Ks,Qs,Zs,Xs,Ys,ei,ti,si,ii,ni,ai,ri;ds=Is,ps=new WeakMap,ws=new WeakMap,us=new WeakSet,ms=function(){return this.eventDispatcher.dispatchEvent},vs=function(e){Ds.assertWithError(t(this,ps,"f"),"must get initial sensorConfiguration");const s=t(this,ps,"f")?.includes(e);return Ds.log(s,`unavailable sensor type "${e}"`),s},ys=function(e){s(this,ws,e,"f"),Ds.log({updatedConfiguration:t(this,ws,"f")}),t(this,us,"a",ms).call(this,"getSensorConfiguration",{sensorConfiguration:this.configuration})},bs=function(e){return Object.keys(e).every((t=>this.configuration[t]==e[t]))},Ss=function(e){const t={};for(let s=0;s<e.byteLength;s+=3){const i=e.getUint8(s),n=os[i],a=e.getUint16(s+1,!0);Ds.log({sensorType:n,sensorRate:a}),n?t[n]=a:Ds.warn(`unknown sensorType index ${i}`)}return Ds.log({parsedSensorConfiguration:t}),s(this,ps,Object.keys(t),"f"),t},Cs=function(e){Ds.assertTypeWithError(e,"number"),Ds.assertWithError(e>=0,`sensorRate must be 0 or greater (got ${e})`),Ds.assertWithError(e<65535,`sensorRate must be 0 or greater (got ${e})`),Ds.assertWithError(e%5==0,"sensorRate must be multiple of 5")},Es=function(e){t(ds,ds,"m",Cs).call(ds,e)},Ms=function(e){let s=Object.keys(e);s=s.filter((e=>t(this,us,"m",vs).call(this,e)));const i=new DataView(new ArrayBuffer(3*s.length));return s.forEach(((s,n)=>{gs.AssertValidSensorType(s);const a=os.indexOf(s);i.setUint8(3*n,a);const r=e[s];t(this,us,"m",Es).call(this,r),i.setUint16(3*n+1,r,!0)})),Ds.log({sensorConfigurationData:i}),i},ks={value:{}},os.forEach((e=>{t(ds,ds,"f",ks)[e]=0}));const oi=W("TfliteManager",{log:!1}),ci=["getTfliteName","setTfliteName","getTfliteTask","setTfliteTask","getTfliteSampleRate","setTfliteSampleRate","getTfliteSensorTypes","setTfliteSensorTypes","tfliteIsReady","getTfliteCaptureDelay","setTfliteCaptureDelay","getTfliteThreshold","setTfliteThreshold","getTfliteInferencingEnabled","setTfliteInferencingEnabled","tfliteInference"],hi=ci,li=["getTfliteName","getTfliteTask","getTfliteSampleRate","getTfliteSensorTypes","tfliteIsReady","getTfliteCaptureDelay","getTfliteThreshold","getTfliteInferencingEnabled"],fi=["classification","regression"],gi=["pressure","linearAcceleration","gyroscope","magnetometer"];class ui{constructor(){_s.add(this),As.set(this,void 0),$s.set(this,void 0),Ps.set(this,void 0),qs.set(this,[]),Gs.set(this,void 0),Qs.set(this,void 0),Ys.set(this,void 0),si.set(this,void 0),ri.set(this,void 0),J(this)}get addEventListenter(){return this.eventDispatcher.addEventListener}get removeEventListener(){return this.eventDispatcher.removeEventListener}get waitForEvent(){return this.eventDispatcher.waitForEvent}get name(){return t(this,As,"f")}async setName(e,t){if(oi.assertTypeWithError(e,"string"),this.name==e)return void oi.log(`redundant name assignment ${e}`);const s=this.waitForEvent("getTfliteName"),i=N.encode(e);this.sendMessage([{type:"setTfliteName",data:i.buffer}],t),await s}get task(){return t(this,$s,"f")}async setTask(e,s){if(t(this,_s,"m",Ls).call(this,e),this.task==e)return void oi.log(`redundant task assignment ${e}`);const i=this.waitForEvent("getTfliteTask"),n=fi.indexOf(e);this.sendMessage([{type:"setTfliteTask",data:Uint8Array.from([n]).buffer}],s),await i}get sampleRate(){return t(this,Ps,"f")}async setSampleRate(e,s){if(oi.assertTypeWithError(e,"number"),e-=e%5,oi.assertWithError(e>=5,`sampleRate must be multiple of 5 greater than 0 (got ${e})`),t(this,Ps,"f")==e)return void oi.log(`redundant sampleRate assignment ${e}`);const i=this.waitForEvent("getTfliteSampleRate"),n=new DataView(new ArrayBuffer(2));n.setUint16(0,e,!0),this.sendMessage([{type:"setTfliteSampleRate",data:n.buffer}],s),await i}static AssertValidSensorType(e){gs.AssertValidSensorType(e);const t=e;oi.assertWithError(gi.includes(t),`invalid tflite sensorType "${e}"`)}get sensorTypes(){return t(this,qs,"f").slice()}async setSensorTypes(e,t){e.forEach((e=>{ui.AssertValidSensorType(e)}));const s=this.waitForEvent("getTfliteSensorTypes");var i;const n=(e=(i=e).filter(((e,t)=>i.indexOf(e)==t))).map((e=>os.indexOf(e))).sort();oi.log(e,n),this.sendMessage([{type:"setTfliteSensorTypes",data:Uint8Array.from(n).buffer}],t),await s}get isReady(){return t(this,Gs,"f")}get captureDelay(){return t(this,Qs,"f")}async setCaptureDelay(e,s){if(oi.assertTypeWithError(e,"number"),t(this,Qs,"f")==e)return void oi.log(`redundant captureDelay assignment ${e}`);const i=this.waitForEvent("getTfliteCaptureDelay"),n=new DataView(new ArrayBuffer(2));n.setUint16(0,e,!0),this.sendMessage([{type:"setTfliteCaptureDelay",data:n.buffer}],s),await i}get threshold(){return t(this,Ys,"f")}async setThreshold(e,s){if(oi.assertTypeWithError(e,"number"),oi.assertWithError(e>=0,`threshold must be positive (got ${e})`),t(this,Ys,"f")==e)return void oi.log(`redundant threshold assignment ${e}`);const i=this.waitForEvent("getTfliteThreshold"),n=new DataView(new ArrayBuffer(4));n.setFloat32(0,e,!0),this.sendMessage([{type:"setTfliteThreshold",data:n.buffer}],s),await i}get inferencingEnabled(){return t(this,si,"f")}async setInferencingEnabled(e,s=!0){if(oi.assertTypeWithError(e,"boolean"),!e&&!this.isReady)return;if(t(this,_s,"m",Ks).call(this),t(this,si,"f")==e)return void oi.log(`redundant inferencingEnabled assignment ${e}`);const i=this.waitForEvent("getTfliteInferencingEnabled");this.sendMessage([{type:"setTfliteInferencingEnabled",data:Uint8Array.from([Number(e)]).buffer}],s),await i}async toggleInferencingEnabled(){return this.setInferencingEnabled(!this.inferencingEnabled)}async enableInferencing(){this.inferencingEnabled||this.setInferencingEnabled(!0)}async disableInferencing(){this.inferencingEnabled&&this.setInferencingEnabled(!1)}parseMessage(e,s){switch(oi.log({messageType:e}),e){case"getTfliteName":case"setTfliteName":t(this,_s,"m",Rs).call(this,s);break;case"getTfliteTask":case"setTfliteTask":t(this,_s,"m",Os).call(this,s);break;case"getTfliteSampleRate":case"setTfliteSampleRate":t(this,_s,"m",Ns).call(this,s);break;case"getTfliteSensorTypes":case"setTfliteSensorTypes":t(this,_s,"m",zs).call(this,s);break;case"tfliteIsReady":t(this,_s,"m",Hs).call(this,s);break;case"getTfliteCaptureDelay":case"setTfliteCaptureDelay":t(this,_s,"m",Zs).call(this,s);break;case"getTfliteThreshold":case"setTfliteThreshold":t(this,_s,"m",ei).call(this,s);break;case"getTfliteInferencingEnabled":case"setTfliteInferencingEnabled":t(this,_s,"m",ii).call(this,s);break;case"tfliteInference":t(this,_s,"m",ai).call(this,s);break;default:throw Error(`uncaught messageType ${e}`)}}get configuration(){return t(this,ri,"f")}sendConfiguration(e,i){if(e==t(this,ri,"f"))return void oi.log("redundant tflite configuration assignment");if(s(this,ri,e,"f"),oi.log("assigned new tflite configuration",this.configuration),!this.configuration)return;const{name:n,task:a,captureDelay:r,sampleRate:o,threshold:c,sensorTypes:h}=this.configuration;this.setName(n,!1),this.setTask(a,!1),null!=r&&this.setCaptureDelay(r,!1),this.setSampleRate(o,!1),null!=c&&this.setThreshold(c,!1),this.setSensorTypes(h,i)}clear(){s(this,ri,void 0,"f"),s(this,si,!1,"f"),s(this,qs,[],"f"),s(this,Ps,0,"f"),s(this,Gs,!1,"f")}requestRequiredInformation(){oi.log("requesting required tflite information");const e=li.map((e=>({type:e})));this.sendMessage(e,!1)}}var di,mi,pi,vi,wi;As=new WeakMap,$s=new WeakMap,Ps=new WeakMap,qs=new WeakMap,Gs=new WeakMap,Qs=new WeakMap,Ys=new WeakMap,si=new WeakMap,ri=new WeakMap,_s=new WeakSet,Ls=function(e){oi.assertEnumWithError(e,fi)},Us=function(e){oi.assertWithError(e in fi,`invalid taskEnum ${e}`)},Fs=function(){return this.eventDispatcher.dispatchEvent},Rs=function(e){oi.log("parseName",e);const s=V.decode(e.buffer);t(this,_s,"m",xs).call(this,s)},xs=function(e){oi.log({name:e}),s(this,As,e,"f"),t(this,_s,"a",Fs).call(this,"getTfliteName",{tfliteName:e})},Os=function(e){oi.log("parseTask",e);const s=e.getUint8(0);t(this,_s,"m",Us).call(this,s);const i=fi[s];t(this,_s,"m",Bs).call(this,i)},Bs=function(e){oi.log({task:e}),s(this,$s,e,"f"),t(this,_s,"a",Fs).call(this,"getTfliteTask",{tfliteTask:e})},Ns=function(e){oi.log("parseSampleRate",e);const s=e.getUint16(0,!0);t(this,_s,"m",Vs).call(this,s)},Vs=function(e){oi.log({sampleRate:e}),s(this,Ps,e,"f"),t(this,_s,"a",Fs).call(this,"getTfliteSampleRate",{tfliteSampleRate:e})},zs=function(e){oi.log("parseSensorTypes",e);const s=[];for(let t=0;t<e.byteLength;t++){const i=e.getUint8(t),n=os[i];n?gi.includes(n)?s.push(n):oi.error(`invalid tfliteSensorType ${n}`):oi.error(`invalid sensorTypeEnum ${i}`)}t(this,_s,"m",js).call(this,s)},js=function(e){oi.log({sensorTypes:e}),s(this,qs,e,"f"),t(this,_s,"a",Fs).call(this,"getTfliteSensorTypes",{tfliteSensorTypes:e})},Hs=function(e){oi.log("parseIsReady",e);const s=Boolean(e.getUint8(0));t(this,_s,"m",Js).call(this,s)},Js=function(e){oi.log({isReady:e}),s(this,Gs,e,"f"),t(this,_s,"a",Fs).call(this,"tfliteIsReady",{tfliteIsReady:e})},Ks=function(){oi.assertWithError(this.isReady,"tflite is not ready")},Zs=function(e){oi.log("parseCaptureDelay",e);const s=e.getUint16(0,!0);t(this,_s,"m",Xs).call(this,s)},Xs=function(e){oi.log({captureDelay:e}),s(this,Qs,e,"f"),t(this,_s,"a",Fs).call(this,"getTfliteCaptureDelay",{tfliteCaptureDelay:e})},ei=function(e){oi.log("parseThreshold",e);const s=e.getFloat32(0,!0);t(this,_s,"m",ti).call(this,s)},ti=function(e){oi.log({threshold:e}),s(this,Ys,e,"f"),t(this,_s,"a",Fs).call(this,"getTfliteThreshold",{tfliteThreshold:e})},ii=function(e){oi.log("parseInferencingEnabled",e);const s=Boolean(e.getUint8(0));t(this,_s,"m",ni).call(this,s)},ni=function(e){oi.log({inferencingEnabled:e}),s(this,si,e,"f"),t(this,_s,"a",Fs).call(this,"getTfliteInferencingEnabled",{tfliteInferencingEnabled:e})},ai=function(e){oi.log("parseInference",e);const s=Ge(e,0);oi.log({timestamp:s});const i=[];for(let t=0,s=2;s<e.byteLength;t++,s+=4){const t=e.getFloat32(s,!0);i.push(t)}oi.log("values",i);const n={timestamp:s,values:i};if("classification"==this.task){let e=0,s=0;if(i.forEach(((t,i)=>{t>e&&(e=t,s=i)})),oi.log({maxIndex:s,maxValue:e}),n.maxIndex=s,n.maxValue=e,t(this,ri,"f")?.classes){const{classes:e}=t(this,ri,"f");n.maxClass=e[s],n.classValues={},i.forEach(((t,s)=>{const i=e[s];n.classValues[i]=t}))}}t(this,_s,"a",Fs).call(this,"tfliteInference",{tfliteInference:n})};const yi=W("DeviceInformationManager",{log:!1}),bi=["manufacturerName","modelNumber","hardwareRevision","firmwareRevision","softwareRevision","pnpId","serialNumber"],Si=[...bi,"deviceInformation"];class Ci{constructor(){di.add(this),pi.set(this,{})}get information(){return t(this,pi,"f")}clear(){s(this,pi,{},"f")}parseMessage(e,s){switch(yi.log({messageType:e}),e){case"manufacturerName":const i=V.decode(s.buffer);yi.log({manufacturerName:i}),t(this,di,"m",wi).call(this,{manufacturerName:i});break;case"modelNumber":const n=V.decode(s.buffer);yi.log({modelNumber:n}),t(this,di,"m",wi).call(this,{modelNumber:n});break;case"softwareRevision":const a=V.decode(s.buffer);yi.log({softwareRevision:a}),t(this,di,"m",wi).call(this,{softwareRevision:a});break;case"hardwareRevision":const r=V.decode(s.buffer);yi.log({hardwareRevision:r}),t(this,di,"m",wi).call(this,{hardwareRevision:r});break;case"firmwareRevision":const o=V.decode(s.buffer);yi.log({firmwareRevision:o}),t(this,di,"m",wi).call(this,{firmwareRevision:o});break;case"pnpId":const c={source:1===s.getUint8(0)?"Bluetooth":"USB",productId:s.getUint16(3,!0),productVersion:s.getUint16(5,!0),vendorId:0};"Bluetooth"==c.source&&(c.vendorId=s.getUint16(1,!0)),yi.log({pnpId:c}),t(this,di,"m",wi).call(this,{pnpId:c});break;case"serialNumber":const h=V.decode(s.buffer);yi.log({serialNumber:h});break;default:throw Error(`uncaught messageType ${e}`)}}}var Ei,Mi,ki,Di,Ti,Wi,Ii,_i,Li,Ui,Fi,Ai,Ri,xi,$i,Oi,Bi,Pi;pi=new WeakMap,di=new WeakSet,mi=function(){return this.eventDispatcher.dispatchEvent},vi=function(){return bi.filter((e=>"serialNumber"!=e)).every((e=>e in t(this,pi,"f")))},wi=function(e){yi.log({partialDeviceInformation:e});Object.keys(e).forEach((s=>{t(this,di,"a",mi).call(this,s,{[s]:e[s]})})),Object.assign(t(this,pi,"f"),e),yi.log({deviceInformation:t(this,pi,"f")}),t(this,di,"a",vi)&&(yi.log("completed deviceInformation"),t(this,di,"a",mi).call(this,"deviceInformation",{deviceInformation:this.information}))};const Ni=W("InformationManager",{log:!1}),Vi=["leftInsole","rightInsole","leftGlove","rightGlove","glasses","generic"],qi=["left","right"],zi=["isCharging","getBatteryCurrent","getMtu","getId","getName","setName","getType","setType","getCurrentTime","setCurrentTime"],ji=zi;class Gi{constructor(){Ei.add(this),ki.set(this,!1),Ti.set(this,void 0),Ii.set(this,void 0),Li.set(this,""),Ui.set(this,void 0),xi.set(this,0),Oi.set(this,!1),J(this)}get waitForEvent(){return this.eventDispatcher.waitForEvent}get isCharging(){return t(this,ki,"f")}get batteryCurrent(){return t(this,Ti,"f")}async getBatteryCurrent(){Ni.log("getting battery current...");const e=this.waitForEvent("getBatteryCurrent");this.sendMessage([{type:"getBatteryCurrent"}]),await e}get id(){return t(this,Ii,"f")}get name(){return t(this,Li,"f")}updateName(e){Ni.assertTypeWithError(e,"string"),s(this,Li,e,"f"),Ni.log({updatedName:t(this,Li,"f")}),t(this,Ei,"a",Mi).call(this,"getName",{name:t(this,Li,"f")})}async setName(e){Ni.assertTypeWithError(e,"string"),Ni.assertRangeWithError("newName",e.length,2,30);const t=N.encode(e);Ni.log({setNameData:t});const s=this.waitForEvent("getName");this.sendMessage([{type:"setName",data:t.buffer}]),await s}get type(){return t(this,Ui,"f")}get typeEnum(){return Vi.indexOf(this.type)}updateType(e){t(this,Ei,"m",Fi).call(this,e),e!=this.type?(s(this,Ui,e,"f"),Ni.log({updatedType:t(this,Ui,"f")}),t(this,Ei,"a",Mi).call(this,"getType",{type:t(this,Ui,"f")})):Ni.log("redundant type assignment")}async setType(e){t(this,Ei,"m",Fi).call(this,e);const s=Vi.indexOf(e);t(this,Ei,"m",Ri).call(this,s)}get isInsole(){switch(this.type){case"leftInsole":case"rightInsole":return!0;default:return!1}}get isGlove(){switch(this.type){case"leftGlove":case"rightGlove":return!0;default:return!1}}get side(){switch(this.type){case"leftInsole":case"leftGlove":default:return"left";case"rightInsole":case"rightGlove":return"right"}}get mtu(){return t(this,xi,"f")}get isCurrentTimeSet(){return t(this,Oi,"f")}parseMessage(e,s){switch(Ni.log({messageType:e}),e){case"isCharging":const i=Boolean(s.getUint8(0));Ni.log({isCharging:i}),t(this,Ei,"m",Di).call(this,i);break;case"getBatteryCurrent":const n=s.getFloat32(0,!0);Ni.log({batteryCurrent:n}),t(this,Ei,"m",Wi).call(this,n);break;case"getId":const a=V.decode(s.buffer);Ni.log({id:a}),t(this,Ei,"m",_i).call(this,a);break;case"getName":case"setName":const r=V.decode(s.buffer);Ni.log({name:r}),this.updateName(r);break;case"getType":case"setType":const o=s.getUint8(0),c=Vi[o];Ni.log({typeEnum:o,type:c}),this.updateType(c);break;case"getMtu":let h=s.getUint16(0,!0);"webSocket"!=this.connectionType&&"udp"!=this.connectionType&&(h=Math.min(h,512)),Ni.log({mtu:h}),t(this,Ei,"m",$i).call(this,h);break;case"getCurrentTime":case"setCurrentTime":const l=Number(s.getBigUint64(0,!0));t(this,Ei,"m",Bi).call(this,l);break;default:throw Error(`uncaught messageType ${e}`)}}clear(){s(this,Oi,!1,"f")}}ki=new WeakMap,Ti=new WeakMap,Ii=new WeakMap,Li=new WeakMap,Ui=new WeakMap,xi=new WeakMap,Oi=new WeakMap,Ei=new WeakSet,Mi=function(){return this.eventDispatcher.dispatchEvent},Di=function(e){Ni.assertTypeWithError(e,"boolean"),s(this,ki,e,"f"),Ni.log({isCharging:t(this,ki,"f")}),t(this,Ei,"a",Mi).call(this,"isCharging",{isCharging:t(this,ki,"f")})},Wi=function(e){Ni.assertTypeWithError(e,"number"),s(this,Ti,e,"f"),Ni.log({batteryCurrent:t(this,Ti,"f")}),t(this,Ei,"a",Mi).call(this,"getBatteryCurrent",{batteryCurrent:t(this,Ti,"f")})},_i=function(e){Ni.assertTypeWithError(e,"string"),s(this,Ii,e,"f"),Ni.log({id:t(this,Ii,"f")}),t(this,Ei,"a",Mi).call(this,"getId",{id:t(this,Ii,"f")})},Fi=function(e){Ni.assertEnumWithError(e,Vi)},Ai=function(e){Ni.assertTypeWithError(e,"number"),Ni.assertWithError(e in Vi,`invalid typeEnum ${e}`)},Ri=async function(e){t(this,Ei,"m",Ai).call(this,e);const s=Uint8Array.from([e]);Ni.log({setTypeData:s});const i=this.waitForEvent("getType");this.sendMessage([{type:"setType",data:s.buffer}]),await i},$i=function(e){Ni.assertTypeWithError(e,"number"),t(this,xi,"f")!=e?(s(this,xi,e,"f"),t(this,Ei,"a",Mi).call(this,"getMtu",{mtu:t(this,xi,"f")})):Ni.log("redundant mtu assignment",e)},Bi=function(e){Ni.log({currentTime:e}),s(this,Oi,0!=e||Math.abs(Date.now()-e)<je,"f"),t(this,Oi,"f")||t(this,Ei,"m",Pi).call(this,!1)},Pi=async function(e){Ni.log("setting current time...");const t=new DataView(new ArrayBuffer(8));t.setBigUint64(0,BigInt(Date.now()),!0);const s=this.waitForEvent("getCurrentTime");this.sendMessage([{type:"setCurrentTime",data:t.buffer}],e),await s};const Hi=["none","strongClick100","strongClick60","strongClick30","sharpClick100","sharpClick60","sharpClick30","softBump100","softBump60","softBump30","doubleClick100","doubleClick60","tripleClick100","softFuzz60","strongBuzz100","alert750ms","alert1000ms","strongClick1_100","strongClick2_80","strongClick3_60","strongClick4_30","mediumClick100","mediumClick80","mediumClick60","sharpTick100","sharpTick80","sharpTick60","shortDoubleClickStrong100","shortDoubleClickStrong80","shortDoubleClickStrong60","shortDoubleClickStrong30","shortDoubleClickMedium100","shortDoubleClickMedium80","shortDoubleClickMedium60","shortDoubleSharpTick100","shortDoubleSharpTick80","shortDoubleSharpTick60","longDoubleSharpClickStrong100","longDoubleSharpClickStrong80","longDoubleSharpClickStrong60","longDoubleSharpClickStrong30","longDoubleSharpClickMedium100","longDoubleSharpClickMedium80","longDoubleSharpClickMedium60","longDoubleSharpTick100","longDoubleSharpTick80","longDoubleSharpTick60","buzz100","buzz80","buzz60","buzz40","buzz20","pulsingStrong100","pulsingStrong60","pulsingMedium100","pulsingMedium60","pulsingSharp100","pulsingSharp60","transitionClick100","transitionClick80","transitionClick60","transitionClick40","transitionClick20","transitionClick10","transitionHum100","transitionHum80","transitionHum60","transitionHum40","transitionHum20","transitionHum10","transitionRampDownLongSmooth2_100","transitionRampDownLongSmooth1_100","transitionRampDownMediumSmooth1_100","transitionRampDownMediumSmooth2_100","transitionRampDownShortSmooth1_100","transitionRampDownShortSmooth2_100","transitionRampDownLongSharp1_100","transitionRampDownLongSharp2_100","transitionRampDownMediumSharp1_100","transitionRampDownMediumSharp2_100","transitionRampDownShortSharp1_100","transitionRampDownShortSharp2_100","transitionRampUpLongSmooth1_100","transitionRampUpLongSmooth2_100","transitionRampUpMediumSmooth1_100","transitionRampUpMediumSmooth2_100","transitionRampUpShortSmooth1_100","transitionRampUpShortSmooth2_100","transitionRampUpLongSharp1_100","transitionRampUpLongSharp2_100","transitionRampUpMediumSharp1_100","transitionRampUpMediumSharp2_100","transitionRampUpShortSharp1_100","transitionRampUpShortSharp2_100","transitionRampDownLongSmooth1_50","transitionRampDownLongSmooth2_50","transitionRampDownMediumSmooth1_50","transitionRampDownMediumSmooth2_50","transitionRampDownShortSmooth1_50","transitionRampDownShortSmooth2_50","transitionRampDownLongSharp1_50","transitionRampDownLongSharp2_50","transitionRampDownMediumSharp1_50","transitionRampDownMediumSharp2_50","transitionRampDownShortSharp1_50","transitionRampDownShortSharp2_50","transitionRampUpLongSmooth1_50","transitionRampUpLongSmooth2_50","transitionRampUpMediumSmooth1_50","transitionRampUpMediumSmooth2_50","transitionRampUpShortSmooth1_50","transitionRampUpShortSmooth2_50","transitionRampUpLongSharp1_50","transitionRampUpLongSharp2_50","transitionRampUpMediumSharp1_50","transitionRampUpMediumSharp2_50","transitionRampUpShortSharp1_50","transitionRampUpShortSharp2_50","longBuzz100","smoothHum50","smoothHum40","smoothHum30","smoothHum20","smoothHum10"];var Ji,Ki,Qi,Zi,Xi,Yi,en,tn,sn,nn,an,rn,on,cn,hn,ln,fn,gn,un;const dn=W("VibrationManager",{log:!1}),mn=["front","rear"],pn=["waveformEffect","waveform"],vn=["getVibrationLocations","triggerVibration"],wn=vn,yn=2550,bn=1270;class Sn{constructor(){Ji.add(this),gn.set(this,[]),J(this)}get waitForEvent(){return this.eventDispatcher.waitForEvent}async triggerVibration(e,s=!0){let i;e.forEach((e=>{const{type:s}=e;let n,{locations:a}=e;switch(a=a||this.vibrationLocations.slice(),a=a.filter((e=>this.vibrationLocations.includes(e))),s){case"waveformEffect":{const{segments:s,loopCount:i}=e;n=t(this,Ji,"m",cn).call(this,a,s,i)}break;case"waveform":{const{segments:s}=e;n=t(this,Ji,"m",hn).call(this,a,s)}break;default:throw Error(`invalid vibration type "${s}"`)}dn.log({type:s,arrayBuffer:n}),i=z(i,n)})),await this.sendMessage([{type:"triggerVibration",data:i}],s)}get vibrationLocations(){return t(this,gn,"f")}parseMessage(e,s){if(dn.log({messageType:e}),"getVibrationLocations"!==e)throw Error(`uncaught messageType ${e}`);{const e=Array.from(new Uint8Array(s.buffer)).map((e=>mn[e])).filter(Boolean);t(this,Ji,"m",un).call(this,e)}}}var Cn,En,Mn,kn,Dn,Tn,Wn,In,_n,Ln,Un,Fn,An,Rn,xn,$n,On;gn=new WeakMap,Ji=new WeakSet,Ki=function(){return this.eventDispatcher.dispatchEvent},Qi=function(e){dn.assertTypeWithError(e,"string"),dn.assertWithError(mn.includes(e),`invalid location "${e}"`)},Zi=function(e){t(this,Ji,"m",Yi).call(this,e),e.forEach((e=>{t(this,Ji,"m",Qi).call(this,e)}))},Xi=function(e){t(this,Ji,"m",Zi).call(this,e);let s=0;return e.forEach((e=>{const t=mn.indexOf(e);s|=1<<t})),dn.log({locationsBitmask:s}),dn.assertWithError(s>0,"locationsBitmask must not be zero"),s},Yi=function(e){dn.assertWithError(Array.isArray(e),"passed non-array"),dn.assertWithError(e.length>0,"passed empty array")},en=function(e){dn.assertWithError(Hi.includes(e),`invalid waveformEffect "${e}"`)},tn=function(e){if(null!=e.effect){const s=e.effect;t(this,Ji,"m",en).call(this,s)}else{if(null==e.delay)throw Error("no effect or delay found in waveformEffectSegment");{const{delay:t}=e;dn.assertWithError(t>=0,`delay must be 0ms or greater (got ${t})`),dn.assertWithError(t<=bn,`delay must be 1270ms or less (got ${t})`)}}if(null!=e.loopCount){const{loopCount:s}=e;t(this,Ji,"m",sn).call(this,s)}},sn=function(e){dn.assertTypeWithError(e,"number"),dn.assertWithError(e>=0,`waveformEffectSegmentLoopCount must be 0 or greater (got ${e})`),dn.assertWithError(e<=3,`waveformEffectSegmentLoopCount must be 3 or fewer (got ${e})`)},nn=function(e){t(this,Ji,"m",Yi).call(this,e),dn.assertWithError(e.length<=8,`must have 8 waveformEffectSegments or fewer (got ${e.length})`),e.forEach((e=>{t(this,Ji,"m",tn).call(this,e)}))},an=function(e){dn.assertTypeWithError(e,"number"),dn.assertWithError(e>=0,`waveformEffectSequenceLoopCount must be 0 or greater (got ${e})`),dn.assertWithError(e<=6,`waveformEffectSequenceLoopCount must be 6 or fewer (got ${e})`)},rn=function(e){dn.assertTypeWithError(e.amplitude,"number"),dn.assertWithError(e.amplitude>=0,`amplitude must be 0 or greater (got ${e.amplitude})`),dn.assertWithError(e.amplitude<=1,`amplitude must be 1 or less (got ${e.amplitude})`),dn.assertTypeWithError(e.duration,"number"),dn.assertWithError(e.duration>0,`duration must be greater than 0ms (got ${e.duration}ms)`),dn.assertWithError(e.duration<=yn,`duration must be 2550ms or less (got ${e.duration}ms)`)},on=function(e){t(this,Ji,"m",Yi).call(this,e),dn.assertWithError(e.length<=20,`must have 20 waveformSegments or fewer (got ${e.length})`),e.forEach((e=>{t(this,Ji,"m",rn).call(this,e)}))},cn=function(e,s,i=0){t(this,Ji,"m",nn).call(this,s),t(this,Ji,"m",an).call(this,i);let n=[],a=0;const r=s.some((e=>{const{loopCount:t}=e;return null!=t&&t>0}))||0!=i;for(let e=0;e<s.length||r&&e<8;e++){const t=s[e]||{effect:"none"};if(null!=t.effect){const e=t.effect;n[a++]=Hi.indexOf(e)}else{if(null==t.delay)throw Error("invalid waveformEffectSegment");{const{delay:e}=t;n[a++]=128|Math.floor(e/10)}}}const o=0!=i;for(let e=0;e<s.length||o&&e<8;e++){const t=s[e]?.loopCount||0;0!=e&&4!=e||(n[a]=0);const i=e%4*2;n[a]|=t<<i,3!=e&&7!=e||a++}0!=i&&(n[a++]=i);const c=new DataView(Uint8Array.from(n).buffer);return dn.log({dataArray:n,dataView:c}),t(this,Ji,"m",fn).call(this,e,"waveformEffect",c)},hn=function(e,s){t(this,Ji,"m",on).call(this,s);const i=new DataView(new ArrayBuffer(2*s.length));return s.forEach(((e,t)=>{i.setUint8(2*t,Math.floor(127*e.amplitude)),i.setUint8(2*t+1,Math.floor(e.duration/10))})),dn.log({dataView:i}),t(this,Ji,"m",fn).call(this,e,"waveform",i)},ln=function(e){dn.assertTypeWithError(e,"string"),dn.assertWithError(pn.includes(e),`invalid vibrationType "${e}"`)},fn=function(e,s,i){dn.assertWithError(i?.byteLength>0,"no data received");const n=t(this,Ji,"m",Xi).call(this,e);t(this,Ji,"m",ln).call(this,s);const a=pn.indexOf(s);dn.log({locationsBitmask:n,vibrationTypeIndex:a,dataView:i});const r=z(n,a,i.byteLength,i);return dn.log({data:r}),r},un=function(e){s(this,gn,e,"f"),dn.log("vibrationLocations",e),t(this,Ji,"a",Ki).call(this,"getVibrationLocations",{vibrationLocations:t(this,gn,"f")})};const Bn=W("WifiManager",{log:!1}),Pn=["isWifiAvailable","getWifiSSID","setWifiSSID","getWifiPassword","setWifiPassword","getWifiConnectionEnabled","setWifiConnectionEnabled","isWifiConnected","ipAddress","isWifiSecure"],Nn=["getWifiSSID","getWifiPassword","getWifiConnectionEnabled","isWifiConnected","ipAddress","isWifiSecure"],Vn=Pn;class qn{constructor(){Cn.add(this),Mn.set(this,!1),Tn.set(this,""),In.set(this,""),Ln.set(this,void 0),Fn.set(this,!1),Rn.set(this,void 0),$n.set(this,!1),J(this)}get waitForEvent(){return this.eventDispatcher.waitForEvent}requestRequiredInformation(){Bn.log("requesting required wifi information");const e=Nn.map((e=>({type:e})));this.sendMessage(e,!1)}get isWifiAvailable(){return t(this,Mn,"f")}get wifiSSID(){return t(this,Tn,"f")}async setWifiSSID(e){if(t(this,Cn,"m",Dn).call(this),t(this,Ln,"f"))return void Bn.error("cannot change ssid while wifi connection is enabled");Bn.assertTypeWithError(e,"string"),Bn.assertRangeWithError("wifiSSID",e.length,1,32);const s=N.encode(e);Bn.log({setWifiSSIDData:s});const i=this.waitForEvent("getWifiSSID");this.sendMessage([{type:"setWifiSSID",data:s.buffer}]),await i}get wifiPassword(){return t(this,In,"f")}async setWifiPassword(e){if(t(this,Cn,"m",Dn).call(this),t(this,Ln,"f"))return void Bn.error("cannot change password while wifi connection is enabled");Bn.assertTypeWithError(e,"string"),e.length>0&&Bn.assertRangeWithError("wifiPassword",e.length,8,64);const s=N.encode(e);Bn.log({setWifiPasswordData:s});const i=this.waitForEvent("getWifiPassword");this.sendMessage([{type:"setWifiPassword",data:s.buffer}]),await i}get wifiConnectionEnabled(){return t(this,Ln,"f")}async setWifiConnectionEnabled(e,s=!0){if(t(this,Cn,"m",Dn).call(this),Bn.assertTypeWithError(e,"boolean"),t(this,Ln,"f")==e)return void Bn.log(`redundant wifiConnectionEnabled assignment ${e}`);const i=this.waitForEvent("getWifiConnectionEnabled");this.sendMessage([{type:"setWifiConnectionEnabled",data:Uint8Array.from([Number(e)]).buffer}],s),await i}async toggleWifiConnection(){return this.setWifiConnectionEnabled(!this.wifiConnectionEnabled)}async enableWifiConnection(){return this.setWifiConnectionEnabled(!0)}async disableWifiConnection(){return this.setWifiConnectionEnabled(!1)}get isWifiConnected(){return t(this,Fn,"f")}get ipAddress(){return t(this,Rn,"f")}get isWifiSecure(){return t(this,$n,"f")}parseMessage(e,s){switch(Bn.log({messageType:e}),e){case"isWifiAvailable":const i=Boolean(s.getUint8(0));Bn.log({isWifiAvailable:i}),t(this,Cn,"m",kn).call(this,i);break;case"getWifiSSID":case"setWifiSSID":const n=V.decode(s.buffer);Bn.log({ssid:n}),t(this,Cn,"m",Wn).call(this,n);break;case"getWifiPassword":case"setWifiPassword":const a=V.decode(s.buffer);Bn.log({password:a}),t(this,Cn,"m",_n).call(this,a);break;case"getWifiConnectionEnabled":case"setWifiConnectionEnabled":const r=Boolean(s.getUint8(0));Bn.log({enableWifiConnection:r}),t(this,Cn,"m",Un).call(this,r);break;case"isWifiConnected":const o=Boolean(s.getUint8(0));Bn.log({isWifiConnected:o}),t(this,Cn,"m",An).call(this,o);break;case"ipAddress":let c;4==s.byteLength&&(c=new Uint8Array(s.buffer.slice(0,4)).join(".")),Bn.log({ipAddress:c}),t(this,Cn,"m",xn).call(this,c);break;case"isWifiSecure":const h=Boolean(s.getUint8(0));Bn.log({isWifiSecure:h}),t(this,Cn,"m",On).call(this,h);break;default:throw Error(`uncaught messageType ${e}`)}}clear(){s(this,Tn,"","f"),s(this,In,"","f"),s(this,Rn,"","f"),s(this,Fn,!1,"f"),s(this,Mn,!1,"f")}}var zn,jn,Gn,Hn,Jn,Kn,Qn,Zn,Xn,Yn,ea,ta;Mn=new WeakMap,Tn=new WeakMap,In=new WeakMap,Ln=new WeakMap,Fn=new WeakMap,Rn=new WeakMap,$n=new WeakMap,Cn=new WeakSet,En=function(){return this.eventDispatcher.dispatchEvent},kn=function(e){Bn.assertTypeWithError(e,"boolean"),s(this,Mn,e,"f"),Bn.log({isWifiAvailable:t(this,Mn,"f")}),t(this,Cn,"a",En).call(this,"isWifiAvailable",{isWifiAvailable:t(this,Mn,"f")})},Dn=function(){Bn.assertWithError(t(this,Mn,"f"),"wifi is not available")},Wn=function(e){Bn.assertTypeWithError(e,"string"),s(this,Tn,e,"f"),Bn.log({wifiSSID:t(this,Tn,"f")}),t(this,Cn,"a",En).call(this,"getWifiSSID",{wifiSSID:t(this,Tn,"f")})},_n=function(e){Bn.assertTypeWithError(e,"string"),s(this,In,e,"f"),Bn.log({wifiPassword:t(this,In,"f")}),t(this,Cn,"a",En).call(this,"getWifiPassword",{wifiPassword:t(this,In,"f")})},Un=function(e){Bn.log({wifiConnectionEnabled:e}),s(this,Ln,e,"f"),t(this,Cn,"a",En).call(this,"getWifiConnectionEnabled",{wifiConnectionEnabled:e})},An=function(e){Bn.assertTypeWithError(e,"boolean"),s(this,Fn,e,"f"),Bn.log({isWifiConnected:t(this,Fn,"f")}),t(this,Cn,"a",En).call(this,"isWifiConnected",{isWifiConnected:t(this,Fn,"f")})},xn=function(e){s(this,Rn,e,"f"),Bn.log({ipAddress:t(this,Rn,"f")}),t(this,Cn,"a",En).call(this,"ipAddress",{ipAddress:t(this,Rn,"f")})},On=function(e){Bn.assertTypeWithError(e,"boolean"),s(this,$n,e,"f"),Bn.log({isWifiSecure:t(this,$n,"f")}),t(this,Cn,"a",En).call(this,"isWifiSecure",{isWifiSecure:t(this,$n,"f")})};const sa=W("BaseConnectionManager",{log:!1}),ia=["webBluetooth","noble","client","webSocket","udp"],na=["notConnected","connecting","connected","disconnecting"],aa=[...na,"connectionStatus","isConnected"],ra=[...zi,...Ts,...hs,...vn,...$e,...ci,...Pn,...ts],oa=["batteryLevel"],ca=["rx","tx"],ha=[...oa,...bi,...ca,...ra,"smp"];class la{get baseConstructor(){return this.constructor}static get isSupported(){return!1}get isSupported(){return this.baseConstructor.isSupported}get canUpdateFirmware(){return!1}get type(){return this.baseConstructor.type}constructor(){zn.add(this),Jn.set(this,"notConnected"),Zn.set(this,[]),Xn.set(this,!1),this.defaultMtu=23,this.mtu=this.defaultMtu,ea.set(this,new R(t(this,zn,"m",ta).bind(this),5e3)),t(this,zn,"m",Hn).call(this)}get status(){return t(this,Jn,"f")}set status(e){sa.assertEnumWithError(e,na),t(this,Jn,"f")!=e?(sa.log(`new connection status "${e}"`),s(this,Jn,e,"f"),this.onStatusUpdated(this.status),this.isConnected?t(this,ea,"f").start():t(this,ea,"f").stop(),"notConnected"==t(this,Jn,"f")&&(this.mtu=this.defaultMtu)):sa.log(`tried to assign same connection status "${e}"`)}get isConnected(){return"connected"==this.status}get isAvailable(){return!1}assertIsNotConnected(){sa.assertWithError(!this.isConnected,"device is already connected")}assertIsConnected(){sa.assertWithError(this.isConnected,"device is not connected")}assertIsConnectedAndNotDisconnecting(){this.assertIsConnected(),t(this,zn,"m",Qn).call(this)}async connect(){this.assertIsNotConnected(),t(this,zn,"m",Kn).call(this),this.status="connecting"}get canReconnect(){return!1}async reconnect(){this.assertIsNotConnected(),t(this,zn,"m",Kn).call(this),sa.assertWithError(this.canReconnect,"unable to reconnect"),this.status="connecting",sa.log("attempting to reconnect...")}async disconnect(){this.assertIsConnected(),t(this,zn,"m",Qn).call(this),this.status="disconnecting",sa.log("disconnecting from device...")}async sendSmpMessage(e){this.assertIsConnectedAndNotDisconnecting(),sa.log("sending smp message",e)}async sendTxMessages(e,i=!0){if(this.assertIsConnectedAndNotDisconnecting(),e&&(t(this,Zn,"f").push(...e),sa.log(`appended ${e.length} messages`)),!i)return void sa.log("not sending immediately - waiting until later");if(t(this,Xn,"f"))return void sa.log("already sending messages - waiting until later");if(0==t(this,Zn,"f").length)return void sa.log("no pendingMessages");s(this,Xn,!0,"f"),sa.log("sendTxMessages",t(this,Zn,"f").slice());const n=t(this,Zn,"f").map((e=>{t(jn,jn,"m",Gn).call(jn,e.type);const s=ra.indexOf(e.type),i=new DataView(new ArrayBuffer(2));return i.setUint16(0,e.data?.byteLength||0,!0),z(s,i,e.data)}));if(t(this,Zn,"f").length=0,this.mtu)for(;n.length>0;){if(n.every((e=>e.byteLength>this.mtu-3))){sa.log("every arrayBuffer is too big to send");break}sa.log("remaining arrayBuffers.length",n.length);let e=0,t=0;n.some((s=>{if(e+s.byteLength>this.mtu-3)return sa.log(`stopping appending arrayBuffers ( length ${s.byteLength} too much)`),!0;sa.log(`allowing arrayBuffer with length ${s.byteLength}`),t++,e+=s.byteLength}));const s=n.splice(0,t);sa.log({arrayBufferCount:t,arrayBuffersToSend:s});const i=z(...s);sa.log("sending arrayBuffer (partitioned)",i),await this.sendTxData(i)}else{const e=z(...n);sa.log("sending arrayBuffer (all)",e),await this.sendTxData(e)}s(this,Xn,!1,"f"),this.sendTxMessages(void 0,!0)}async sendTxData(e){sa.log("sendTxData",e)}parseRxMessage(e){bt(e,ra,t(this,zn,"m",Yn).bind(this),null,!0),this.onMessagesReceived()}clear(){s(this,Xn,!1,"f"),t(this,Zn,"f").length=0}remove(){this.clear(),this.onStatusUpdated=void 0,this.onMessageReceived=void 0,this.onMessagesReceived=void 0}}jn=la,Jn=new WeakMap,Zn=new WeakMap,Xn=new WeakMap,ea=new WeakMap,zn=new WeakSet,Gn=function(e){sa.assertEnumWithError(e,ra)},Hn=function(){sa.assertWithError(this.isSupported,`${this.constructor.name} is not supported`)},Kn=function(){sa.assertWithError("connecting"!=this.status,"device is already connecting")},Qn=function(){sa.assertWithError("disconnecting"!=this.status,"device is already disconnecting")},Yn=function(e,t){sa.log({messageType:e,dataView:t}),this.onMessageReceived(e,t)},ta=function(){this.isConnected||(sa.log("timer detected disconnection"),this.status="notConnected")};const fa=W("EventUtils",{log:!1});function ga(e,t){let s=e.addEventListener||e.addListener||e.on||e.AddEventListener;fa.assertWithError(s,"no add listener function found for target"),s=s.bind(e),Object.entries(t).forEach((([e,t])=>{s(e,t)}))}function ua(e,t){let s=e.removeEventListener||e.removeListener||e.RemoveEventListener;fa.assertWithError(s,"no remove listener function found for target"),s=s.bind(e),Object.entries(t).forEach((([e,t])=>{s(e,t)}))}const da=W("bluetoothUUIDs",{log:!1});if(n)var ma=window.BluetoothUUID;function pa(e){return da.assertTypeWithError(e,"string"),da.assertWithError(4==e.length,"value must be 4 characters long"),`ea6d${e}-a725-4f9b-893d-c3913e33b39f`}function va(e){return ma?.getCharacteristic?.(e)}function wa(e){return ma?.getService?.(e)}const ya=Object.freeze({services:{deviceInformation:{uuid:wa("device_information"),characteristics:{manufacturerName:{uuid:va("manufacturer_name_string")},modelNumber:{uuid:va("model_number_string")},hardwareRevision:{uuid:va("hardware_revision_string")},firmwareRevision:{uuid:va("firmware_revision_string")},softwareRevision:{uuid:va("software_revision_string")},pnpId:{uuid:va("pnp_id")},serialNumber:{uuid:va("serial_number_string")}}},battery:{uuid:wa("battery_service"),characteristics:{batteryLevel:{uuid:va("battery_level")}}},main:{uuid:pa("0000"),characteristics:{rx:{uuid:pa("1000")},tx:{uuid:pa("1001")}}},smp:{uuid:"8d53dc1d-1db7-4cd3-868b-8a527460aa84",characteristics:{smp:{uuid:"da2e7828-fbce-4e01-ae9e-261174997c48"}}}}}),ba=[ya.services.main.uuid],Sa=[ya.services.deviceInformation.uuid,ya.services.battery.uuid,ya.services.smp.uuid];function Ca(e){e=e.toString().toLowerCase();return Object.keys(ya.services).find((t=>{let s=ya.services[t].uuid.toString();return 4==e.length&&(s=s.slice(4,8)),e.includes("-")||(s=s.replaceAll("-","")),e==s}))}const Ea=[],Ma=[];function ka(e){var t;return e=e.toString().toLowerCase(),Object.values(ya.services).some((s=>{const i=Object.keys(s.characteristics);return t=i.find((t=>{let i=s.characteristics[t].uuid.toString();return 4==e.length&&(i=i.slice(4,8)),e.includes("-")||(i=i.replaceAll("-","")),e==i}))})),t}function Da(e){const t={broadcast:!1,read:!0,writeWithoutResponse:!1,write:!1,notify:!1,indicate:!1,authenticatedSignedWrites:!1,reliableWrite:!1,writableAuxiliaries:!1};switch(e){case"rx":case"tx":case"smp":t.read=!1}switch(e){case"batteryLevel":case"rx":case"smp":t.notify=!0}if("smp"===e)t.writeWithoutResponse=!0;if("tx"===e)t.write=!0;return t}Object.values(ya.services).forEach((e=>{if(!e.characteristics)return;const t=Object.keys(e.characteristics);t.forEach((s=>{const i=e.characteristics[s];ba.includes(e.uuid)&&(Ea.push(i.uuid),t.push(s)),Ma.push(i.uuid)}))}),[]);const Ta=W("BluetoothConnectionManager",{log:!1});class Wa extends la{constructor(){super(...arguments),this.isInRange=!0}get isAvailable(){return!0}onCharacteristicValueChanged(e,t){"rx"==e?this.parseRxMessage(t):this.onMessageReceived?.(e,t)}async writeCharacteristic(e,t){Ta.log("writeCharacteristic",...arguments)}async sendSmpMessage(e){super.sendSmpMessage(e),await this.writeCharacteristic("smp",e)}async sendTxData(e){super.sendTxData(e),0!=e.byteLength&&await this.writeCharacteristic("tx",e)}}var Ia,_a,La,Ua,Fa,Aa,Ra,xa,$a,Oa,Ba;const Pa=W("WebBluetoothConnectionManager",{log:!1});var Na;n&&(Na=window.navigator.bluetooth);class Va extends Wa{constructor(){super(...arguments),Ia.add(this),_a.set(this,{characteristicvaluechanged:t(this,Ia,"m",$a).bind(this)}),La.set(this,{gattserverdisconnected:t(this,Ia,"m",Ba).bind(this)}),Ua.set(this,void 0),Fa.set(this,new Map),Aa.set(this,new Map)}get bluetoothId(){return this.device.id}get canUpdateFirmware(){return t(this,Aa,"f").has("smp")}static get isSupported(){return Boolean(Na)}static get type(){return"webBluetooth"}get device(){return t(this,Ua,"f")}set device(e){t(this,Ua,"f")!=e?(t(this,Ua,"f")&&ua(t(this,Ua,"f"),t(this,La,"f")),e&&ga(e,t(this,La,"f")),s(this,Ua,e,"f")):Pa.log("tried to assign the same BluetoothDevice")}get server(){return t(this,Ua,"f")?.gatt}get isConnected(){return this.server?.connected||!1}async connect(){await super.connect();try{const e=await Na.requestDevice({filters:[{services:ba}],optionalServices:n?Sa:[]});Pa.log("got BluetoothDevice"),this.device=e,Pa.log("connecting to device...");const s=await this.server.connect();Pa.log(`connected to device? ${s.connected}`),await t(this,Ia,"m",Ra).call(this),Pa.log("fully connected"),this.status="connected"}catch(e){Pa.error(e),this.status="notConnected",this.server?.disconnect(),t(this,Ia,"m",xa).call(this)}}async disconnect(){await t(this,Ia,"m",xa).call(this),await super.disconnect(),this.server?.disconnect(),this.status="notConnected"}async writeCharacteristic(e,s){super.writeCharacteristic(e,s);const i=t(this,Aa,"f").get(e);Pa.assertWithError(i,`${e} characteristic not found`),Pa.log("writing characteristic",i,s);const n=i.properties||Da(e);n.writeWithoutResponse?(Pa.log("writing without response"),await i.writeValueWithoutResponse(s)):(Pa.log("writing with response"),await i.writeValueWithResponse(s)),Pa.log("wrote characteristic"),n.read&&!n.notify&&(Pa.log("reading value after write..."),await i.readValue(),(c||h)&&t(this,Ia,"m",Oa).call(this,i))}get canReconnect(){return Boolean(this.server&&!this.server.connected&&this.isInRange)}async reconnect(){await super.reconnect();try{await this.server.connect()}catch(e){Pa.error(e),this.isInRange=!1}this.isConnected?(Pa.log("successfully reconnected!"),await t(this,Ia,"m",Ra).call(this),this.status="connected"):(Pa.log("unable to reconnect"),this.status="notConnected")}remove(){super.remove(),this.device=void 0}}_a=new WeakMap,La=new WeakMap,Ua=new WeakMap,Fa=new WeakMap,Aa=new WeakMap,Ia=new WeakSet,Ra=async function(){t(this,Ia,"m",xa).call(this),Pa.log("getting services...");const e=await this.server.getPrimaryServices();Pa.log("got services",e.length),Pa.log("getting characteristics...");for(const s in e){const i=e[s];Pa.log({service:i});const n=Ca(i.uuid);Pa.assertWithError(n,`no name found for service uuid "${i.uuid}"`),Pa.log(`got "${n}" service`),i.name=n,t(this,Fa,"f").set(n,i),Pa.log(`getting characteristics for "${n}" service`);const a=await i.getCharacteristics();Pa.log(`got characteristics for "${n}" service`);for(const e in a){const s=a[e];Pa.log({characteristic:s});const i=ka(s.uuid);Pa.assertWithError(Boolean(i),`no name found for characteristic uuid "${s.uuid}" in "${n}" service`),Pa.log(`got "${i}" characteristic in "${n}" service`),s.name=i,t(this,Aa,"f").set(i,s),ga(s,t(this,_a,"f"));const r=s.properties||Da(i);r.notify&&(Pa.log(`starting notifications for "${i}" characteristic`),await s.startNotifications()),r.read&&(Pa.log(`reading "${i}" characteristic...`),await s.readValue(),(c||h)&&t(this,Ia,"m",Oa).call(this,s))}}},xa=async function(){this.device&&ua(this.device,t(this,La,"f"));const e=Array.from(t(this,Aa,"f").keys()).map((e=>{const s=t(this,Aa,"f").get(e);ua(s,t(this,_a,"f"));if((s.properties||Da(e)).notify)return Pa.log(`stopping notifications for "${e}" characteristic`),s.stopNotifications()}));return Promise.allSettled(e)},$a=function(e){Pa.log("oncharacteristicvaluechanged");const s=e.target;t(this,Ia,"m",Oa).call(this,s)},Oa=function(e){Pa.log("onCharacteristicValue");const t=e.name;Pa.assertWithError(Boolean(t),`no name found for characteristic with uuid "${e.uuid}"`),Pa.log(`oncharacteristicvaluechanged for "${t}" characteristic`);const s=e.value;Pa.assertWithError(s,`no data found for "${t}" characteristic`),Pa.log(`data for "${t}" characteristic`,Array.from(new Uint8Array(s.buffer)));try{this.onCharacteristicValueChanged(t,s)}catch(e){Pa.error(e)}},Ba=function(){Pa.log("gattserverdisconnected"),this.status="notConnected"};const qa=4294967296,za=9007199254740992;const ja={encode:function(e){let t,s=new ArrayBuffer(256),i=new DataView(s),n=0;function a(e){let a=s.byteLength;const r=n+e;for(;a<r;)a<<=1;if(a!==s.byteLength){const e=i;s=new ArrayBuffer(a),i=new DataView(s);const t=n+3>>2;for(let s=0;s<t;++s)i.setUint32(s<<2,e.getUint32(s<<2))}return t=e,i}function r(){n+=t}function o(e){r(a(1).setUint8(n,e))}function c(e){const t=a(e.length);for(let s=0;s<e.length;++s)t.setUint8(n+s,e[s]);r()}function h(e,t){t<24?o(e<<5|t):t<256?(o(e<<5|24),o(t)):t<65536?(o(e<<5|25),function(e){r(a(2).setUint16(n,e))}(t)):t<4294967296?(o(e<<5|26),function(e){r(a(4).setUint32(n,e))}(t)):(o(e<<5|27),function(e){const t=e%qa,s=(e-t)/qa,i=a(8);i.setUint32(n,s),i.setUint32(n+4,t),r()}(t))}if(function e(t){let s;const i=[];let l;if(!1===t)return o(244);if(!0===t)return o(245);if(null===t)return o(246);if(void 0===t)return o(247);switch(typeof t){case"number":if(Math.floor(t)===t){if(t>=0&&t<=za)return h(0,t);if(-za<=t&&t<0)return h(1,-(t+1))}return o(251),function(e){r(a(8).setFloat64(n,e))}(t);case"string":for(s=0;s<t.length;++s){let e=t.charCodeAt(s);e<128?i.push(e):e<2048?(i.push(192|e>>6),i.push(128|63&e)):e<55296?(i.push(224|e>>12),i.push(128|e>>6&63),i.push(128|63&e)):(e=(1023&e)<<10,e|=1023&t.charCodeAt(++s),e+=65536,i.push(240|e>>18),i.push(128|e>>12&63),i.push(128|e>>6&63),i.push(128|63&e))}return h(3,i.length),c(i);default:if(Array.isArray(t))for(l=t.length,h(4,l),s=0;s<l;++s)e(t[s]);else if(t instanceof Uint8Array)h(2,t.length),c(t);else{const i=Object.keys(t);for(l=i.length,h(5,l),s=0;s<l;++s){const n=i[s];e(n),e(t[n])}}}}(e),"slice"in s)return s.slice(0,n);const l=new ArrayBuffer(n),f=new DataView(l);for(let e=0;e<n;++e)f.setUint8(e,i.getUint8(e));return l},decode:function(e,t,s){const i=new DataView(e);let n=0;function a(e,t){return n+=e,t}function r(t){return a(t,new Uint8Array(e,n,t))}function o(){return a(1,i.getUint8(n))}function c(){return a(2,i.getUint16(n))}function h(){return a(4,i.getUint32(n))}function l(){return 255===i.getUint8(n)&&(n+=1,!0)}function f(e){if(e<24)return e;if(24===e)return o();if(25===e)return c();if(26===e)return h();if(27===e)return h()*qa+h();if(31===e)return-1;throw new Error("Invalid length encoding")}function g(e){const t=o();if(255===t)return-1;const s=f(31&t);if(s<0||t>>5!==e)throw new Error("Invalid indefinite length element");return s}function u(e,t){for(let s=0;s<t;++s){let s=o();128&s&&(s<224?(s=(31&s)<<6|63&o(),t-=1):s<240?(s=(15&s)<<12|(63&o())<<6|63&o(),t-=2):(s=(15&s)<<18|(63&o())<<12|(63&o())<<6|63&o(),t-=3)),s<65536?e.push(s):(s-=65536,e.push(55296|s>>10),e.push(56320|1023&s))}}"function"!=typeof t&&(t=function(e){return e}),"function"!=typeof s&&(s=function(){});const d=function e(){const h=o(),d=h>>5,m=31&h;let p,v;if(7===d)switch(m){case 25:return function(){const e=new ArrayBuffer(4),t=new DataView(e),s=c(),i=32768&s;let n=31744&s;const a=1023&s;if(31744===n)n=261120;else if(0!==n)n+=114688;else if(0!==a)return(i?-1:1)*a*5.960464477539063e-8;return t.setUint32(0,i<<16|n<<13|a<<13),t.getFloat32(0)}();case 26:return a(4,i.getFloat32(n));case 27:return a(8,i.getFloat64(n))}if(v=f(m),v<0&&(d<2||d>6))throw new Error("Invalid length");const w=[];let y;const b={};switch(d){case 0:return v;case 1:return-1-v;case 2:if(v<0){const e=[];let t=0;for(;(v=g(d))>=0;)t+=v,e.push(r(v));const s=new Uint8Array(t);let i=0;for(p=0;p<e.length;++p)s.set(e[p],i),i+=e[p].length;return s}return r(v);case 3:if(v<0)for(;(v=g(d))>=0;)u(w,v);else u(w,v);return String.fromCharCode.apply(null,w);case 4:if(v<0)for(y=[];!l();)y.push(e());else for(y=new Array(v),p=0;p<v;++p)y[p]=e();return y;case 5:for(p=0;p<v||v<0&&!l();++p){b[e()]=e()}return b;case 6:return t(e(),v);case 7:switch(v){case 20:return!1;case 21:return!0;case 22:return null;case 23:return;default:return s(v)}}}();if(n!==e.byteLength)throw new Error("Remaining bytes");return d}},Ga=W("mcumgr",{log:!1}),Ha=0,Ja=1,Ka=2,Qa=3,Za=0,Xa=1,Ya=8,er=0,tr=2,sr=3,ir=5,nr=0,ar=1,rr=5,or=0;class cr{constructor(){this._mtu=256,this._messageCallback=null,this._imageUploadProgressCallback=null,this._imageUploadNextCallback=null,this._fileUploadProgressCallback=null,this._fileUploadNextCallback=null,this._uploadIsInProgress=!1,this._downloadIsInProgress=!1,this._buffer=new Uint8Array,this._seq=0}onMessage(e){return this._messageCallback=e,this}onImageUploadNext(e){return this._imageUploadNextCallback=e,this}onImageUploadProgress(e){return this._imageUploadProgressCallback=e,this}onImageUploadFinished(e){return this._imageUploadFinishedCallback=e,this}onFileUploadNext(e){return this._fileUploadNextCallback=e,this}onFileUploadProgress(e){return this._fileUploadProgressCallback=e,this}onFileUploadFinished(e){return this._fileUploadFinishedCallback=e,this}onFileDownloadNext(e){return this._fileDownloadNextCallback=e,this}onFileDownloadProgress(e){return this._fileDownloadProgressCallback=e,this}onFileDownloadFinished(e){return this._fileDownloadFinishedCallback=e,this}_getMessage(e,t,s,i){let n=[];void 0!==i&&(n=[...new Uint8Array(ja.encode(i))]);const a=255&n.length,r=[e,0,n.length>>8,a,t>>8,255&t,this._seq,s,...n];return this._seq=(this._seq+1)%256,r}_notification(e){Ga.log("mcumgr - message received");const t=new Uint8Array(e);this._buffer=new Uint8Array([...this._buffer,...t]);const s=256*this._buffer[2]+this._buffer[3];this._buffer.length<s+8||(this._processMessage(this._buffer.slice(0,s+8)),this._buffer=this._buffer.slice(s+8))}_processMessage(e){const[t,,s,i,n,a,,r]=e,o=ja.decode(e.slice(8).buffer),c=256*s+i,h=256*n+a;return Ga.log("mcumgr - Process Message - Group: "+h+", Id: "+r+", Off: "+o.off),h===Xa&&r===ar&&o.off?(this._uploadOffset=o.off,void this._uploadNext()):t===Qa&&h===Ya&&r===or&&o.off?(this._uploadFileOffset=o.off,void this._uploadFileNext()):t===Ja&&h===Ya&&r===or?(this._downloadFileOffset+=o.data.length,null!=o.len&&(this._downloadFileLength=o.len),Ga.log("downloaded "+this._downloadFileOffset+" bytes of "+this._downloadFileLength),this._downloadFileLength>0&&this._fileDownloadProgressCallback({percentage:Math.floor(this._downloadFileOffset/this._downloadFileLength*100)}),this._messageCallback&&this._messageCallback({op:t,group:h,id:r,data:o,length:c}),void this._downloadFileNext()):void(this._messageCallback&&this._messageCallback({op:t,group:h,id:r,data:o,length:c}))}cmdReset(){return this._getMessage(Ka,Za,ir)}smpEcho(e){return this._getMessage(Ka,Za,er,{d:e})}cmdImageState(){return this._getMessage(Ha,Xa,nr)}cmdImageErase(){return this._getMessage(Ka,Xa,rr,{})}cmdImageTest(e){return this._getMessage(Ka,Xa,nr,{hash:e,confirm:!1})}cmdImageConfirm(e){return this._getMessage(Ka,Xa,nr,{hash:e,confirm:!0})}_hash(e){return crypto.subtle.digest("SHA-256",e)}async _uploadNext(){if(!this._uploadImage)return;if(this._uploadOffset>=this._uploadImage.byteLength)return this._uploadIsInProgress=!1,void this._imageUploadFinishedCallback();const e={data:new Uint8Array,off:this._uploadOffset};0===this._uploadOffset&&(e.len=this._uploadImage.byteLength,e.sha=new Uint8Array(await this._hash(this._uploadImage))),this._imageUploadProgressCallback({percentage:Math.floor(this._uploadOffset/this._uploadImage.byteLength*100)});const t=this._mtu-ja.encode(e).byteLength-8-3-5;e.data=new Uint8Array(this._uploadImage.slice(this._uploadOffset,this._uploadOffset+t)),this._uploadOffset+=t;const s=this._getMessage(Ka,Xa,ar,e);Ga.log("mcumgr - _uploadNext: Message Length: "+s.length),this._imageUploadNextCallback({packet:s})}async reset(){this._messageCallback=null,this._imageUploadProgressCallback=null,this._imageUploadNextCallback=null,this._fileUploadProgressCallback=null,this._fileUploadNextCallback=null,this._uploadIsInProgress=!1,this._downloadIsInProgress=!1,this._buffer=new Uint8Array,this._seq=0}async cmdUpload(e,t=0){this._uploadIsInProgress?Ga.error("Upload is already in progress."):(this._uploadIsInProgress=!0,this._uploadOffset=0,this._uploadImage=e,this._uploadSlot=t,this._uploadNext())}async cmdUploadFile(e,t){this._uploadIsInProgress?Ga.error("Upload is already in progress."):(this._uploadIsInProgress=!0,this._uploadFileOffset=0,this._uploadFile=e,this._uploadFilename=t,this._uploadFileNext())}async _uploadFileNext(){if(Ga.log("uploadFileNext - offset: "+this._uploadFileOffset+", length: "+this._uploadFile.byteLength),this._uploadFileOffset>=this._uploadFile.byteLength)return this._uploadIsInProgress=!1,void this._fileUploadFinishedCallback();const e={data:new Uint8Array,off:this._uploadFileOffset};0===this._uploadFileOffset&&(e.len=this._uploadFile.byteLength),e.name=this._uploadFilename,this._fileUploadProgressCallback({percentage:Math.floor(this._uploadFileOffset/this._uploadFile.byteLength*100)});const t=this._mtu-ja.encode(e).byteLength-8;e.data=new Uint8Array(this._uploadFile.slice(this._uploadFileOffset,this._uploadFileOffset+t)),this._uploadFileOffset+=t;const s=this._getMessage(Ka,Ya,or,e);Ga.log("mcumgr - _uploadNext: Message Length: "+s.length),this._fileUploadNextCallback({packet:s})}async cmdDownloadFile(e,t){this._downloadIsInProgress?Ga.error("Download is already in progress."):(this._downloadIsInProgress=!0,this._downloadFileOffset=0,this._downloadFileLength=0,this._downloadRemoteFilename=e,this._downloadLocalFilename=t,this._downloadFileNext())}async _downloadFileNext(){if(this._downloadFileLength>0&&this._downloadFileOffset>=this._downloadFileLength)return this._downloadIsInProgress=!1,void this._fileDownloadFinishedCallback();const e={off:this._downloadFileOffset};0===this._downloadFileOffset&&(e.name=this._downloadRemoteFilename);const t=this._getMessage(Ha,Ya,or,e);Ga.log("mcumgr - _downloadNext: Message Length: "+t.length),this._fileDownloadNextCallback({packet:t})}async imageInfo(e){const t={},s=new Uint8Array(e);if(s.length<32)throw new Error("Invalid image (too short file)");if(61!==s[0]||184!==s[1]||243!==s[2]||150!==s[3])throw new Error("Invalid image (wrong magic bytes)");if(0!==s[4]||0!==s[5]||0!==s[6]||0!==s[7])throw new Error("Invalid image (wrong load address)");const i=s[8]+256*s[9];if(0!==s[10]||0!==s[11])throw new Error("Invalid image (wrong protected TLV area size)");const n=s[12]+256*s[13]+65536*s[14]+s[15]*2**24;if(t.imageSize=n,s.length<n+i)throw new Error("Invalid image (wrong image size)");if(0!==s[16]||0!==s[17]||0!==s[18]||0!==s[19])throw new Error("Invalid image (wrong flags)");const a=`${s[20]}.${s[21]}.${s[22]+256*s[23]}`;return t.version=a,t.hash=[...new Uint8Array(await this._hash(e.slice(0,n+32)))].map((e=>e.toString(16).padStart(2,"0"))).join(""),t}}var hr,lr,fr,gr,ur,dr,mr,pr,vr,wr,yr,br,Sr,Cr,Er,Mr,kr,Dr,Tr,Wr,Ir;const _r=W("FirmwareManager",{log:!1}),Lr=["smp"],Ur=[...Lr,"firmwareImages","firmwareUploadProgress","firmwareStatus","firmwareUploadComplete"],Fr=["idle","uploading","uploaded","pending","testing","erasing"];class Ar{constructor(){hr.add(this),fr.set(this,"idle"),ur.set(this,void 0),pr.set(this,void 0),vr.set(this,new cr),t(this,hr,"m",wr).call(this),J(this)}get addEventListenter(){return this.eventDispatcher.addEventListener}get removeEventListener(){return this.eventDispatcher.removeEventListener}get waitForEvent(){return this.eventDispatcher.waitForEvent}parseMessage(e,s){if(_r.log({messageType:e}),"smp"!==e)throw Error(`uncaught messageType ${e}`);t(this,vr,"f")._notification(Array.from(new Uint8Array(s.buffer))),t(this,hr,"a",lr).call(this,"smp",{dataView:s})}async uploadFirmware(e){_r.log("uploadFirmware",e);const s=this.waitForEvent("firmwareUploadComplete");await this.getImages();const i=await H(e),n=await t(this,vr,"f").imageInfo(i);_r.log({imageInfo:n}),t(this,vr,"f").cmdUpload(i,1),t(this,hr,"m",gr).call(this,"uploading"),await s}get status(){return t(this,fr,"f")}get images(){return t(this,ur,"f")}async getImages(){const e=this.waitForEvent("firmwareImages");_r.log("getting firmware image state..."),this.sendMessage(Uint8Array.from(t(this,vr,"f").cmdImageState()).buffer),await e}async testImage(e=1){if(t(this,hr,"m",mr).call(this,e),t(this,hr,"m",dr).call(this),!t(this,ur,"f")[e])return void _r.log(`image ${e} not found`);if(1==t(this,ur,"f")[e].pending)return void _r.log(`image ${e} is already pending`);if(t(this,ur,"f")[e].empty)return void _r.log(`image ${e} is empty`);const s=this.waitForEvent("smp");_r.log("testing firmware image..."),this.sendMessage(Uint8Array.from(t(this,vr,"f").cmdImageTest(t(this,ur,"f")[e].hash)).buffer),await s}async eraseImage(){t(this,hr,"m",dr).call(this);const e=this.waitForEvent("smp");_r.log("erasing image..."),this.sendMessage(Uint8Array.from(t(this,vr,"f").cmdImageErase()).buffer),t(this,hr,"m",gr).call(this,"erasing"),await e,await this.getImages()}async confirmImage(e=0){if(t(this,hr,"m",mr).call(this,e),t(this,hr,"m",dr).call(this),!0===t(this,ur,"f")[e].confirmed)return void _r.log(`image ${e} is already confirmed`);const s=this.waitForEvent("smp");_r.log("confirming image..."),this.sendMessage(Uint8Array.from(t(this,vr,"f").cmdImageConfirm(t(this,ur,"f")[e].hash)).buffer),await s}async echo(e){_r.assertTypeWithError(e,"string");const s=this.waitForEvent("smp");_r.log("sending echo..."),this.sendMessage(Uint8Array.from(t(this,vr,"f").smpEcho(e)).buffer),await s}async reset(){const e=this.waitForEvent("smp");_r.log("resetting..."),this.sendMessage(Uint8Array.from(t(this,vr,"f").cmdReset()).buffer),await e}get mtu(){return t(this,pr,"f")}set mtu(e){s(this,pr,e,"f"),t(this,vr,"f")._mtu=e}}var Rr,xr,$r,Or,Br,Pr,Nr,Vr,qr,zr,jr,Gr,Hr,Jr,Kr,Qr,Zr,Xr;fr=new WeakMap,ur=new WeakMap,pr=new WeakMap,vr=new WeakMap,hr=new WeakSet,lr=function(){return this.eventDispatcher.dispatchEvent},gr=function(e){_r.assertEnumWithError(e,Fr),t(this,fr,"f")!=e?(s(this,fr,e,"f"),_r.log({firmwareStatus:t(this,fr,"f")}),t(this,hr,"a",lr).call(this,"firmwareStatus",{firmwareStatus:t(this,fr,"f")})):_r.log(`redundant firmwareStatus assignment "${e}"`)},dr=function(){_r.assertWithError(t(this,ur,"f"),"didn't get imageState")},mr=function(e){_r.assertTypeWithError(e,"number"),_r.assertWithError(0==e||1==e,"imageIndex must be 0 or 1")},wr=function(){t(this,vr,"f").onMessage(t(this,hr,"m",yr).bind(this)),t(this,vr,"f").onFileDownloadNext(t(this,hr,"m",br)),t(this,vr,"f").onFileDownloadProgress(t(this,hr,"m",Sr).bind(this)),t(this,vr,"f").onFileDownloadFinished(t(this,hr,"m",Cr).bind(this)),t(this,vr,"f").onFileUploadNext(t(this,hr,"m",Er).bind(this)),t(this,vr,"f").onFileUploadProgress(t(this,hr,"m",Mr).bind(this)),t(this,vr,"f").onFileUploadFinished(t(this,hr,"m",kr).bind(this)),t(this,vr,"f").onImageUploadNext(t(this,hr,"m",Dr).bind(this)),t(this,vr,"f").onImageUploadProgress(t(this,hr,"m",Tr).bind(this)),t(this,vr,"f").onImageUploadFinished(t(this,hr,"m",Wr).bind(this))},yr=function({op:e,group:s,id:i,data:n,length:a}){switch(_r.log("onMcuMessage",...arguments),s){case Za:switch(i){case er:_r.log(`echo "${n.r}"`);break;case tr:_r.table(n.tasks);break;case sr:_r.log(n)}break;case Xa:if(i===nr)t(this,hr,"m",Ir).call(this,n);break;default:throw Error(`uncaught mcuMessage group ${s}`)}},br=function(){_r.log("onMcuFileDownloadNext",...arguments)},Sr=function(){_r.log("onMcuFileDownloadProgress",...arguments)},Cr=function(){_r.log("onMcuFileDownloadFinished",...arguments)},Er=function(){_r.log("onMcuFileUploadNext")},Mr=function(){_r.log("onMcuFileUploadProgress")},kr=function(){_r.log("onMcuFileUploadFinished")},Dr=function({packet:e}){_r.log("onMcuImageUploadNext"),this.sendMessage(Uint8Array.from(e).buffer)},Tr=function({percentage:e}){const s=e/100;_r.log("onMcuImageUploadProgress",...arguments),t(this,hr,"a",lr).call(this,"firmwareUploadProgress",{progress:s})},Wr=async function(){_r.log("onMcuImageUploadFinished",...arguments),await this.getImages(),t(this,hr,"a",lr).call(this,"firmwareUploadProgress",{progress:100}),t(this,hr,"a",lr).call(this,"firmwareUploadComplete",{})},Ir=function({images:e}){if(!e)return void _r.log("no images found");s(this,ur,e,"f"),_r.log("images",t(this,ur,"f"));let i="idle";2==t(this,ur,"f").length&&(t(this,ur,"f")[1].bootable?t(this,ur,"f")[0].confirmed?t(this,ur,"f")[1].pending?(_r.log("reset to upload to the new firmware image"),i="pending"):(_r.log("Slot 1 has a valid image. run testImage() to test it or upload a different image."),i="uploaded"):(_r.log('Slot 0 has a valid image. Click "Confirm Image" to confirm it or wait and the device will swap images back.'),i="testing"):_r.warn('Slot 1 has a invalid image. Click "Erase Image" to erase it or upload a different image')),1==t(this,ur,"f").length&&(t(this,ur,"f").push({slot:1,empty:!0,version:"Empty",pending:!1,confirmed:!1,bootable:!1,active:!1,permanent:!1}),_r.log("Select a firmware upload image to upload to slot 1.")),t(this,hr,"m",gr).call(this,i),t(this,hr,"a",lr).call(this,"firmwareImages",{firmwareImages:t(this,ur,"f")})};const Yr=W("DeviceManager",{log:!1}),eo=["deviceConnected","deviceDisconnected","deviceIsConnected","availableDevices","connectedDevices"];class to{constructor(){if(Rr.add(this),xr.set(this,{getType:t(this,Rr,"m",$r).bind(this),isConnected:t(this,Rr,"m",Qr).bind(this)}),Or.set(this,[]),Br.set(this,!1),Pr.set(this,{devices:[]}),Nr.set(this,void 0),qr.set(this,"BS.Device"),Hr.set(this,[]),Jr.set(this,new _(this,eo)),to.shared&&this!=to.shared)throw Error("DeviceManager is a singleton - use DeviceManager.shared");this.CanUseLocalStorage&&(this.UseLocalStorage=!0)}onDevice(e){ga(e,t(this,xr,"f"))}OnDeviceConnectionStatusUpdated(e,s){if("notConnected"==s&&!e.canReconnect&&t(this,Hr,"f").includes(e)){const s=t(this,Hr,"f").indexOf(e);this.AvailableDevices.splice(s,1),t(this,Rr,"m",Zr).call(this)}}get ConnectedDevices(){return t(this,Or,"f")}get UseLocalStorage(){return t(this,Br,"f")}set UseLocalStorage(e){t(this,Rr,"m",Vr).call(this),Yr.assertTypeWithError(e,"boolean"),s(this,Br,e,"f"),t(this,Br,"f")&&!t(this,Nr,"f")&&t(this,Rr,"m",jr).call(this)}get CanUseLocalStorage(){return n&&window.localStorage}get AvailableDevices(){return t(this,Hr,"f")}get CanGetDevices(){return n&&navigator.bluetooth?.getDevices}async GetDevices(){if(!n)return void Yr.warn("GetDevices is only available in the browser");if(!navigator.bluetooth)return void Yr.warn("bluetooth is not available in this browser");if(c)return void Yr.warn("bluefy lists too many devices...");if(!navigator.bluetooth.getDevices)return void Yr.warn("bluetooth.getDevices() is not available in this browser");if(!this.CanGetDevices)return void Yr.log("CanGetDevices is false");t(this,Nr,"f")||t(this,Rr,"m",jr).call(this);const e=t(this,Nr,"f");if(!e.devices||0==e.devices.length)return void Yr.log("no devices found in configuration");const s=await navigator.bluetooth.getDevices();return Yr.log({bluetoothDevices:s}),s.forEach((s=>{if(!s.gatt)return;let i=e.devices.find((e=>s.id==e.bluetoothId));if(!i)return;let n=this.ConnectedDevices.filter((e=>"webBluetooth"==e.connectionType)).find((e=>e.bluetoothId==s.id));const a=this.AvailableDevices.filter((e=>"webBluetooth"==e.connectionType)).find((e=>e.bluetoothId==s.id));if(a)return void(n&&n?.bluetoothId==a.bluetoothId&&n!=a&&(this.AvailableDevices[t(this,Hr,"f").indexOf(a)]=n));if(n)return void this.AvailableDevices.push(n);const r=new Ec,o=new Va;o.device=s,s.name&&r._informationManager.updateName(s.name),r._informationManager.updateType(i.type),r.connectionManager=o,this.AvailableDevices.push(r)})),t(this,Rr,"m",Zr).call(this),this.AvailableDevices}get AddEventListener(){return t(this,Jr,"f").addEventListener}get RemoveEventListener(){return t(this,Jr,"f").removeEventListener}get RemoveEventListeners(){return t(this,Jr,"f").removeEventListeners}get RemoveAllEventListeners(){return t(this,Jr,"f").removeAllEventListeners}_CheckDeviceAvailability(e){e.isConnected||e.isAvailable||!t(this,Hr,"f").includes(e)||(Yr.log("removing device from availableDevices..."),t(this,Hr,"f").splice(t(this,Hr,"f").indexOf(e),1),t(this,Rr,"m",Zr).call(this))}}xr=new WeakMap,Or=new WeakMap,Br=new WeakMap,Pr=new WeakMap,Nr=new WeakMap,qr=new WeakMap,Hr=new WeakMap,Jr=new WeakMap,Rr=new WeakSet,$r=function(e){t(this,Br,"f")&&t(this,Rr,"m",Gr).call(this,e.target)},Vr=function(){Yr.assertWithError(n,"localStorage is only available in the browser"),Yr.assertWithError(window.localStorage,"localStorage not found")},zr=function(){t(this,Rr,"m",Vr).call(this),localStorage.setItem(t(this,qr,"f"),JSON.stringify(t(this,Nr,"f")))},jr=async function(){t(this,Rr,"m",Vr).call(this);let e=localStorage.getItem(t(this,qr,"f"));if("string"!=typeof e)return Yr.log("no info found in localStorage"),s(this,Nr,Object.assign({},t(this,Pr,"f")),"f"),void t(this,Rr,"m",zr).call(this);try{const t=JSON.parse(e);Yr.log({configuration:t}),s(this,Nr,t,"f"),this.CanGetDevices&&await this.GetDevices()}catch(e){Yr.error(e)}},Gr=function(e){if("webBluetooth"!=e.connectionType)return void Yr.log("localStorage is only for webBluetooth devices");t(this,Rr,"m",Vr).call(this);const s=t(this,Nr,"f").devices.findIndex((t=>t.bluetoothId==e.bluetoothId));-1!=s&&(t(this,Nr,"f").devices[s].type=e.type,t(this,Rr,"m",zr).call(this))},Kr=function(){return t(this,Jr,"f").dispatchEvent},Qr=function(e){const{target:s}=e;if(s.isConnected)if(t(this,Or,"f").includes(s))Yr.log("device already included");else{if(Yr.log("adding device",s),t(this,Or,"f").push(s),this.UseLocalStorage&&"webBluetooth"==s.connectionType){const e={type:s.type,bluetoothId:s.bluetoothId,ipAddress:s.ipAddress,isWifiSecure:s.isWifiSecure},i=t(this,Nr,"f").devices.findIndex((t=>t.bluetoothId==e.bluetoothId));-1==i?t(this,Nr,"f").devices.push(e):t(this,Nr,"f").devices[i]=e,t(this,Rr,"m",zr).call(this)}t(this,Rr,"a",Kr).call(this,"deviceConnected",{device:s}),t(this,Rr,"a",Kr).call(this,"deviceIsConnected",{device:s}),t(this,Rr,"m",Xr).call(this)}else t(this,Or,"f").includes(s)?(Yr.log("removing device",s),t(this,Or,"f").splice(t(this,Or,"f").indexOf(s),1),t(this,Rr,"a",Kr).call(this,"deviceDisconnected",{device:s}),t(this,Rr,"a",Kr).call(this,"deviceIsConnected",{device:s}),t(this,Rr,"m",Xr).call(this)):Yr.log("device already not included");if(this.CanGetDevices&&this.GetDevices(),s.isConnected&&!this.AvailableDevices.includes(s)){const e=this.AvailableDevices.find((e=>e.bluetoothId==s.bluetoothId));Yr.log({existingAvailableDevice:e}),e?this.AvailableDevices[this.AvailableDevices.indexOf(e)]=s:this.AvailableDevices.push(s),t(this,Rr,"m",Zr).call(this)}this._CheckDeviceAvailability(s)},Zr=function(){Yr.log({AvailableDevices:this.AvailableDevices}),t(this,Rr,"a",Kr).call(this,"availableDevices",{availableDevices:this.AvailableDevices})},Xr=function(){Yr.log({ConnectedDevices:this.ConnectedDevices}),t(this,Rr,"a",Kr).call(this,"connectedDevices",{connectedDevices:this.ConnectedDevices})},to.shared=new to;var so=to.shared;const io=W("ServerUtils",{log:!1}),no=["isScanningAvailable","isScanning","startScan","stopScan","discoveredDevice","discoveredDevices","expiredDiscoveredDevice","connectToDevice","disconnectFromDevice","connectedDevices","deviceMessage","requiredDeviceInformation"];function ao(e,...t){io.log("createMessage",...t);const s=t.map((t=>{"string"==typeof t&&(t={type:t}),null!=t.data?Array.isArray(t.data)||(t.data=[t.data]):t.data=[];const s=z(...t.data),i=s.byteLength;io.assertEnumWithError(t.type,e);const n=e.indexOf(t.type),a=new DataView(new ArrayBuffer(2));return a.setUint16(0,i,!0),z(n,a,s)}));return io.log("messageBuffers",...s),z(...s)}function ro(...e){return io.log("createServerMessage",...e),ao(no,...e)}function oo(...e){return io.log("createClientDeviceMessage",...e),ao(ha,...e)}ro("isScanningAvailable"),ro("isScanning"),ro("startScan"),ro("stopScan"),ro("discoveredDevices");const co=W("WebSocketUtils",{log:!1}),ho=["ping","pong","serverMessage"];function lo(...e){return co.log("createWebSocketMessage",...e),ao(ho,...e)}var fo,go,uo,mo,po,vo,wo,yo,bo,So,Co,Eo,Mo,ko,Do,To,Wo,Io;lo("ping"),lo("pong");const _o=W("WebSocketConnectionManager",{log:!1}),Lo=["ping","pong","batteryLevel","deviceInformation","message"];const Uo=["deviceInformation","batteryLevel"];class Fo extends la{get bluetoothId(){return t(this,go,"f")??""}constructor(e,i=!1,n){super(),fo.add(this),go.set(this,void 0),this.defaultMtu=1024,uo.set(this,void 0),mo.set(this,void 0),po.set(this,!1),yo.set(this,{open:t(this,fo,"m",bo).bind(this),message:t(this,fo,"m",So).bind(this),close:t(this,fo,"m",Co).bind(this),error:t(this,fo,"m",Eo).bind(this)}),Do.set(this,new R(t(this,fo,"m",To).bind(this),29e3)),this.ipAddress=e,this.isSecure=i,this.mtu=this.defaultMtu,s(this,go,n,"f")}get isAvailable(){return!0}static get isSupported(){return!0}static get type(){return"webSocket"}get webSocket(){return t(this,uo,"f")}set webSocket(e){t(this,uo,"f")!=e?(_o.log("assigning webSocket",e),t(this,uo,"f")&&(ua(t(this,uo,"f"),t(this,yo,"f")),t(this,uo,"f").readyState==t(this,uo,"f").OPEN&&t(this,uo,"f").close()),e&&ga(e,t(this,yo,"f")),s(this,uo,e,"f"),_o.log("assigned webSocket")):_o.log("redundant webSocket assignment")}get ipAddress(){return t(this,mo,"f")}set ipAddress(e){this.assertIsNotConnected(),t(this,mo,"f")!=e?(s(this,mo,e,"f"),_o.log(`updated ipAddress to "${this.ipAddress}"`)):_o.log(`redundnant ipAddress assignment "${e}"`)}get isSecure(){return t(this,po,"f")}set isSecure(e){this.assertIsNotConnected(),t(this,po,"f")!=e?(s(this,po,e,"f"),_o.log(`updated isSecure to "${this.isSecure}"`)):_o.log(`redundant isSecure assignment ${e}`)}get url(){return`${this.isSecure?"wss":"ws"}://${this.ipAddress}/ws`}async connect(){await super.connect();try{this.webSocket=new WebSocket(this.url)}catch(e){_o.error("error connecting to webSocket",e),this.status="notConnected"}}async disconnect(){await super.disconnect(),_o.log("closing websocket"),t(this,Do,"f").stop(),t(this,uo,"f")?.close()}get canReconnect(){return Boolean(this.webSocket)}async reconnect(){await super.reconnect(),this.webSocket=new WebSocket(this.url)}async sendSmpMessage(e){super.sendSmpMessage(e),_o.error("smp not supported on webSockets")}async sendTxData(e){await super.sendTxData(e),0!=e.byteLength&&t(this,fo,"m",wo).call(this,{type:"message",data:e})}remove(){super.remove(),this.webSocket=void 0}}var Ao,Ro,xo,$o,Oo,Bo,Po,No,Vo,qo,zo,jo,Go,Ho,Jo,Ko,Qo,Zo,Xo,Yo,ec,tc,sc,ic,nc,ac,rc,oc,cc,hc,lc,fc,gc,uc,dc,mc,pc,vc,wc,yc;go=new WeakMap,uo=new WeakMap,mo=new WeakMap,po=new WeakMap,yo=new WeakMap,Do=new WeakMap,fo=new WeakSet,vo=function(e){this.assertIsConnected(),_o.log("sending webSocket message",e),t(this,uo,"f").send(e),t(this,Do,"f").restart()},wo=function(...e){t(this,fo,"m",vo).call(this,function(...e){return _o.log("createWebSocketMessage",...e),ao(Lo,...e)}(...e))},bo=function(e){_o.log("webSocket.open",e),t(this,Do,"f").start(),this.status="connected",t(this,fo,"m",Io).call(this)},So=async function(e){const s=await e.data.arrayBuffer(),i=new DataView(s);_o.log(`webSocket.message (${i.byteLength} bytes)`),t(this,fo,"m",Mo).call(this,i)},Co=function(e){_o.log("webSocket.close",e),this.status="notConnected",t(this,Do,"f").stop()},Eo=function(e){_o.error("webSocket.error",e)},Mo=function(e){bt(e,Lo,t(this,fo,"m",ko).bind(this),null,!0)},ko=function(e,s){switch(_o.log(`received "${e}" message (${s.byteLength} bytes)`),e){case"ping":t(this,fo,"m",Wo).call(this);break;case"pong":break;case"batteryLevel":this.onMessageReceived?.("batteryLevel",s);break;case"deviceInformation":bt(s,bi,((e,t)=>{this.onMessageReceived(e,t)}));break;case"message":this.parseRxMessage(s);break;default:_o.error(`uncaught messageType "${e}"`)}},To=function(){_o.log("pinging"),t(this,fo,"m",wo).call(this,"ping")},Wo=function(){_o.log("ponging"),t(this,fo,"m",wo).call(this,"pong")},Io=function(){t(this,fo,"m",wo).call(this,...Uo)};const bc=W("Device",{log:!1}),Sc=["connectionMessage",...aa,...ca,...oa,...ji,...Si,...Ws,...fs,...wn,...Ne,...hi,...Vn,...is,...Ur],Cc=["isCharging","getBatteryCurrent","getId","getMtu","getName","getType","getCurrentTime","getSensorConfiguration","getSensorScalars","getVibrationLocations","getFileTypes","isWifiAvailable"];class Ec{get bluetoothId(){return t(this,Bo,"f")?.bluetoothId}get isAvailable(){return t(this,Bo,"f")?.isAvailable}constructor(){Ao.add(this),$o.set(this,new _(this,Sc)),Bo.set(this,void 0),this.sendTxMessages=t(this,Ao,"m",Po).bind(this),No.set(this,!1),Jo.set(this,Ro.ReconnectOnDisconnection),Ko.set(this,void 0),this.latestConnectionMessages=new Map,ic.set(this,new Ci),nc.set(this,0),this._informationManager=new Gi,rc.set(this,new Is),cc.set(this,Ro.ClearSensorConfigurationOnLeave),hc.set(this,new gs),lc.set(this,new Sn),fc.set(this,new qe),gc.set(this,new ui),uc.set(this,new Ar),this.sendSmpMessage=t(this,Ao,"m",mc).bind(this),pc.set(this,!1),vc.set(this,new qn),wc.set(this,new ns),t(this,ic,"f").eventDispatcher=t(this,$o,"f"),this._informationManager.sendMessage=this.sendTxMessages,this._informationManager.eventDispatcher=t(this,$o,"f"),t(this,rc,"f").sendMessage=this.sendTxMessages,t(this,rc,"f").eventDispatcher=t(this,$o,"f"),t(this,hc,"f").eventDispatcher=t(this,$o,"f"),t(this,lc,"f").sendMessage=this.sendTxMessages,t(this,lc,"f").eventDispatcher=t(this,$o,"f"),t(this,gc,"f").sendMessage=this.sendTxMessages,t(this,gc,"f").eventDispatcher=t(this,$o,"f"),t(this,fc,"f").sendMessage=this.sendTxMessages,t(this,fc,"f").eventDispatcher=t(this,$o,"f"),t(this,vc,"f").sendMessage=this.sendTxMessages,t(this,vc,"f").eventDispatcher=t(this,$o,"f"),t(this,wc,"f").sendMessage=this.sendTxMessages,t(this,wc,"f").eventDispatcher=t(this,$o,"f"),t(this,uc,"f").sendMessage=this.sendSmpMessage,t(this,uc,"f").eventDispatcher=t(this,$o,"f"),this.addEventListener("getMtu",(()=>{t(this,uc,"f").mtu=this.mtu,t(this,fc,"f").mtu=this.mtu,this.connectionManager.mtu=this.mtu})),this.addEventListener("getSensorConfiguration",(()=>{if("connecting"==this.connectionStatus){if(this.sensorTypes.includes("pressure")){bc.log("requesting required pressure information");const e=ls.map((e=>({type:e})));this.sendTxMessages(e,!1)}else bc.log("don't need to request pressure infomration");if(this.sensorTypes.includes("camera")){bc.log("requesting required camera information");const e=ss.map((e=>({type:e})));this.sendTxMessages(e,!1)}else bc.log("don't need to request camera infomration")}})),this.addEventListener("getFileTypes",(()=>{"connecting"==this.connectionStatus&&(this.fileTypes.length>0&&t(this,fc,"f").requestRequiredInformation(),this.fileTypes.includes("tflite")&&t(this,gc,"f").requestRequiredInformation())})),this.addEventListener("isWifiAvailable",(()=>{"connecting"==this.connectionStatus&&("client"!=this.connectionType||a)&&this.isWifiAvailable&&"client"!=this.connectionType&&t(this,vc,"f").requestRequiredInformation()})),so.onDevice(this),n&&window.addEventListener("beforeunload",(()=>{this.isConnected&&this.clearSensorConfigurationOnLeave&&this.clearSensorConfiguration()})),a&&process.on("exit",(()=>{this.isConnected&&this.clearSensorConfigurationOnLeave&&this.clearSensorConfiguration()}))}get addEventListener(){return t(this,$o,"f").addEventListener}get removeEventListener(){return t(this,$o,"f").removeEventListener}get waitForEvent(){return t(this,$o,"f").waitForEvent}get removeEventListeners(){return t(this,$o,"f").removeEventListeners}get removeAllEventListeners(){return t(this,$o,"f").removeAllEventListeners}get connectionManager(){return t(this,Bo,"f")}set connectionManager(e){this.connectionManager!=e?(this.connectionManager&&this.connectionManager.remove(),e&&(e.onStatusUpdated=t(this,Ao,"m",Qo).bind(this),e.onMessageReceived=t(this,Ao,"m",tc).bind(this),e.onMessagesReceived=t(this,Ao,"m",sc).bind(this)),s(this,Bo,e,"f"),bc.log("assigned new connectionManager",t(this,Bo,"f")),this._informationManager.connectionType=this.connectionType):bc.log("same connectionManager is already assigned")}async connect(e){if(bc.log("connect options",e),e)switch(e.type){case"webBluetooth":"webBluetooth"!=this.connectionType&&(this.connectionManager=new Va);break;case"webSocket":{let t=!1;if("webSocket"==this.connectionType){const s=this.connectionManager;s.ipAddress==e.ipAddress&&s.isSecure==e.isWifiSecure||(t=!0)}else t=!0;t&&(this.connectionManager=new Fo(e.ipAddress,e.isWifiSecure,this.bluetoothId))}break;case"udp":{let t=!1;if("udp"==this.connectionType){this.connectionManager.ipAddress!=e.ipAddress&&(t=!0),this.reconnectOnDisconnection=!0}else t=!0;t&&(this.connectionManager=new UDPConnectionManager(e.ipAddress,this.bluetoothId))}}if(this.connectionManager||(this.connectionManager=t(Ro,Ro,"m",xo).call(Ro)),t(this,Ao,"m",Yo).call(this),"client"==e?.type){bc.assertWithError("client"==this.connectionType,"expected clientConnectionManager");const t=this.connectionManager;return t.subType=e.subType,t.connect()}return bc.log("connectionManager type",this.connectionManager.type),this.connectionManager.connect()}get isConnected(){return t(this,No,"f")}get canReconnect(){return this.connectionManager?.canReconnect}async reconnect(){return t(this,Ao,"m",Go).call(this),t(this,Ao,"m",Yo).call(this),this.connectionManager?.reconnect()}static async Connect(){const e=new Ro;return await e.connect(),e}static get ReconnectOnDisconnection(){return t(this,Ro,"f",Ho)}static set ReconnectOnDisconnection(e){bc.assertTypeWithError(e,"boolean"),s(this,Ro,e,"f",Ho)}get reconnectOnDisconnection(){return t(this,Jo,"f")}set reconnectOnDisconnection(e){bc.assertTypeWithError(e,"boolean"),s(this,Jo,e,"f")}get connectionType(){return this.connectionManager?.type}async disconnect(){return t(this,Ao,"m",Vo).call(this),this.reconnectOnDisconnection&&(this.reconnectOnDisconnection=!1,this.addEventListener("isConnected",(()=>{this.reconnectOnDisconnection=!0}),{once:!0})),this.connectionManager.disconnect()}toggleConnection(){if(this.isConnected)this.disconnect();else if(this.canReconnect)try{this.reconnect()}catch(e){bc.error("error trying to reconnect",e),this.connect()}else this.connect()}get connectionStatus(){switch(t(this,Bo,"f")?.status){case"connected":return this.isConnected?"connected":"connecting";case"notConnected":case"connecting":case"disconnecting":return t(this,Bo,"f").status;default:return"notConnected"}}get isConnectionBusy(){return"connecting"==this.connectionStatus||"disconnecting"==this.connectionStatus}get deviceInformation(){return t(this,ic,"f").information}get batteryLevel(){return t(this,nc,"f")}get id(){return this._informationManager.id}get isCharging(){return this._informationManager.isCharging}get batteryCurrent(){return this._informationManager.batteryCurrent}get getBatteryCurrent(){return this._informationManager.getBatteryCurrent}get name(){return this._informationManager.name}get setName(){return this._informationManager.setName}get type(){return this._informationManager.type}get setType(){return this._informationManager.setType}get isInsole(){return this._informationManager.isInsole}get isGlove(){return this._informationManager.isGlove}get side(){return this._informationManager.side}get mtu(){return this._informationManager.mtu}get sensorTypes(){return Object.keys(this.sensorConfiguration)}get continuousSensorTypes(){return cs.filter((e=>this.sensorTypes.includes(e)))}get sensorConfiguration(){return t(this,rc,"f").configuration}async setSensorConfiguration(e,s){await t(this,rc,"f").setConfiguration(e,s)}async clearSensorConfiguration(){return t(this,rc,"f").clearSensorConfiguration()}static get ClearSensorConfigurationOnLeave(){return t(this,Ro,"f",oc)}static set ClearSensorConfigurationOnLeave(e){bc.assertTypeWithError(e,"boolean"),s(this,Ro,e,"f",oc)}get clearSensorConfigurationOnLeave(){return t(this,cc,"f")}set clearSensorConfigurationOnLeave(e){bc.assertTypeWithError(e,"boolean"),s(this,cc,e,"f")}get numberOfPressureSensors(){return t(this,hc,"f").pressureSensorDataManager.numberOfSensors}resetPressureRange(){t(this,hc,"f").pressureSensorDataManager.resetRange()}get vibrationLocations(){return t(this,lc,"f").vibrationLocations}async triggerVibration(e,s){t(this,lc,"f").triggerVibration(e,s)}get fileTypes(){return t(this,fc,"f").fileTypes}get maxFileLength(){return t(this,fc,"f").maxLength}get validFileTypes(){return Oe.filter((e=>!(e.includes("wifi")&&!this.isWifiAvailable)))}async sendFile(e,s){bc.assertWithError(this.validFileTypes.includes(e),`invalid fileType ${e}`);const i=this.waitForEvent("fileTransferComplete");t(this,fc,"f").send(e,s),await i}async receiveFile(e){const s=this.waitForEvent("fileTransferComplete");t(this,fc,"f").receive(e),await s}get fileTransferStatus(){return t(this,fc,"f").status}cancelFileTransfer(){t(this,fc,"f").cancel()}get tfliteName(){return t(this,gc,"f").name}get setTfliteName(){return t(this,gc,"f").setName}async sendTfliteConfiguration(e){e.type="tflite",t(this,gc,"f").sendConfiguration(e,!1);await t(this,fc,"f").send(e.type,e.file)||t(this,Ao,"m",Po).call(this)}get tfliteTask(){return t(this,gc,"f").task}get setTfliteTask(){return t(this,gc,"f").setTask}get tfliteSampleRate(){return t(this,gc,"f").sampleRate}get setTfliteSampleRate(){return t(this,gc,"f").setSampleRate}get tfliteSensorTypes(){return t(this,gc,"f").sensorTypes}get allowedTfliteSensorTypes(){return this.sensorTypes.filter((e=>gi.includes(e)))}get setTfliteSensorTypes(){return t(this,gc,"f").setSensorTypes}get tfliteIsReady(){return t(this,gc,"f").isReady}get tfliteInferencingEnabled(){return t(this,gc,"f").inferencingEnabled}get setTfliteInferencingEnabled(){return t(this,gc,"f").setInferencingEnabled}async enableTfliteInferencing(){return this.setTfliteInferencingEnabled(!0)}async disableTfliteInferencing(){return this.setTfliteInferencingEnabled(!1)}get toggleTfliteInferencing(){return t(this,gc,"f").toggleInferencingEnabled}get tfliteCaptureDelay(){return t(this,gc,"f").captureDelay}get setTfliteCaptureDelay(){return t(this,gc,"f").setCaptureDelay}get tfliteThreshold(){return t(this,gc,"f").threshold}get setTfliteThreshold(){return t(this,gc,"f").setThreshold}get canUpdateFirmware(){return t(this,Bo,"f")?.canUpdateFirmware}get uploadFirmware(){return t(this,Ao,"m",dc).call(this),t(this,uc,"f").uploadFirmware}get canReset(){return this.canUpdateFirmware}async reset(){return bc.assertWithError(this.canReset,"reset is not enabled for this device"),await t(this,uc,"f").reset(),t(this,Bo,"f").disconnect()}get firmwareStatus(){return t(this,uc,"f").status}get getFirmwareImages(){return t(this,Ao,"m",dc).call(this),t(this,uc,"f").getImages}get firmwareImages(){return t(this,uc,"f").images}get eraseFirmwareImage(){return t(this,Ao,"m",dc).call(this),t(this,uc,"f").eraseImage}get confirmFirmwareImage(){return t(this,Ao,"m",dc).call(this),t(this,uc,"f").confirmImage}get testFirmwareImage(){return t(this,Ao,"m",dc).call(this),t(this,uc,"f").testImage}get isServerSide(){return t(this,pc,"f")}set isServerSide(e){t(this,pc,"f")!=e?(bc.log({newIsServerSide:e}),s(this,pc,e,"f"),t(this,fc,"f").isServerSide=this.isServerSide):bc.log("redundant isServerSide assignment")}get isUkaton(){return this.deviceInformation.modelNumber.includes("Ukaton")}get isWifiAvailable(){return t(this,vc,"f").isWifiAvailable}get wifiSSID(){return t(this,vc,"f").wifiSSID}async setWifiSSID(e){return t(this,vc,"f").setWifiSSID(e)}get wifiPassword(){return t(this,vc,"f").wifiPassword}async setWifiPassword(e){return t(this,vc,"f").setWifiPassword(e)}get isWifiConnected(){return t(this,vc,"f").isWifiConnected}get ipAddress(){return t(this,vc,"f").ipAddress}get wifiConnectionEnabled(){return t(this,vc,"f").wifiConnectionEnabled}get enableWifiConnection(){return t(this,vc,"f").enableWifiConnection}get setWifiConnectionEnabled(){return t(this,vc,"f").setWifiConnectionEnabled}get disableWifiConnection(){return t(this,vc,"f").disableWifiConnection}get toggleWifiConnection(){return t(this,vc,"f").toggleWifiConnection}get isWifiSecure(){return t(this,vc,"f").isWifiSecure}async reconnectViaWebSockets(){bc.assertWithError(this.isWifiConnected,"wifi is not connected"),bc.assertWithError("webSocket"!=this.connectionType,"already connected via webSockets"),bc.assertTypeWithError(this.ipAddress,"string"),bc.log("reconnecting via websockets..."),await this.disconnect(),await this.connect({type:"webSocket",ipAddress:this.ipAddress,isWifiSecure:this.isWifiSecure})}async reconnectViaUDP(){bc.assertWithError(a,"udp is only available in node"),bc.assertWithError(this.isWifiConnected,"wifi is not connected"),bc.assertWithError("udp"!=this.connectionType,"already connected via udp"),bc.assertTypeWithError(this.ipAddress,"string"),bc.log("reconnecting via udp..."),await this.disconnect(),await this.connect({type:"udp",ipAddress:this.ipAddress})}get hasCamera(){return this.sensorTypes.includes("camera")}get cameraStatus(){return t(this,wc,"f").cameraStatus}async takePicture(){t(this,Ao,"m",yc).call(this),await t(this,wc,"f").takePicture()}async focusCamera(){t(this,Ao,"m",yc).call(this),await t(this,wc,"f").focus()}async stopCamera(){t(this,Ao,"m",yc).call(this),await t(this,wc,"f").stop()}async wakeCamera(){t(this,Ao,"m",yc).call(this),await t(this,wc,"f").wake()}async sleepCamera(){t(this,Ao,"m",yc).call(this),await t(this,wc,"f").sleep()}get cameraConfiguration(){return t(this,wc,"f").cameraConfiguration}get availableCameraConfigurationTypes(){return t(this,wc,"f").availableCameraConfigurationTypes}get cameraConfigurationRanges(){return t(this,wc,"f").cameraConfigurationRanges}get setCameraConfiguration(){return t(this,wc,"f").setCameraConfiguration}}var Mc,kc,Dc,Tc,Wc,Ic;Ro=Ec,$o=new WeakMap,Bo=new WeakMap,No=new WeakMap,Jo=new WeakMap,Ko=new WeakMap,ic=new WeakMap,nc=new WeakMap,rc=new WeakMap,cc=new WeakMap,hc=new WeakMap,lc=new WeakMap,fc=new WeakMap,gc=new WeakMap,uc=new WeakMap,pc=new WeakMap,vc=new WeakMap,wc=new WeakMap,Ao=new WeakSet,xo=function(){return new Va},Oo=function(){return t(this,$o,"f").dispatchEvent},Po=async function(e,s){await(t(this,Bo,"f")?.sendTxMessages(e,s))},Vo=function(){bc.assertWithError(this.isConnected,"notConnected")},qo=function(e){return e.every((e=>{const t=this.latestConnectionMessages.has(e);return t||bc.log(`didn't receive "${e}" message`),t}))},zo=function(){let e=t(this,Ao,"m",qo).call(this,Cc);return e&&this.sensorTypes.includes("pressure")&&(e=t(this,Ao,"m",qo).call(this,ls)),e&&this.isWifiAvailable&&(e=t(this,Ao,"m",qo).call(this,Nn)),e&&this.fileTypes.length>0&&(e=t(this,Ao,"m",qo).call(this,Ve)),e&&this.fileTypes.includes("tflite")&&(e=t(this,Ao,"m",qo).call(this,li)),e&&this.hasCamera&&(e=t(this,Ao,"m",qo).call(this,ss)),e},jo=function(){bc.log("requesting required information");const e=Cc.map((e=>({type:e})));t(this,Ao,"m",Po).call(this,e)},Go=function(){bc.assertWithError(this.canReconnect,"cannot reconnect to device")},Qo=function(e){bc.log({connectionStatus:e}),"notConnected"==e?(t(this,Ao,"m",ec).call(this),this.canReconnect&&this.reconnectOnDisconnection&&(bc.log("starting reconnect interval..."),s(this,Ko,setInterval((()=>{bc.log("attempting reconnect..."),this.reconnect()}),1e3),"f"))):null!=t(this,Ko,"f")&&(bc.log("clearing reconnect interval"),clearInterval(t(this,Ko,"f")),s(this,Ko,void 0,"f")),t(this,Ao,"m",Xo).call(this),"connected"!=e||t(this,No,"f")||"client"!=this.connectionType&&t(this,Ao,"m",jo).call(this),so.OnDeviceConnectionStatusUpdated(this,e)},Zo=function(e=!1){t(this,Ao,"a",Oo).call(this,"connectionStatus",{connectionStatus:this.connectionStatus}),t(this,Ao,"a",Oo).call(this,this.connectionStatus,{}),e&&t(this,Ao,"a",Oo).call(this,"isConnected",{isConnected:this.isConnected})},Xo=function(){switch(s(this,No,Boolean(this.connectionManager?.isConnected)&&t(this,Ao,"a",zo)&&this._informationManager.isCurrentTimeSet,"f"),this.connectionStatus){case"connected":t(this,No,"f")&&t(this,Ao,"m",Zo).call(this,!0);break;case"notConnected":t(this,Ao,"m",Zo).call(this,!0);break;default:t(this,Ao,"m",Zo).call(this,!1)}},Yo=function(){t(this,Ao,"m",ec).call(this),this._informationManager.clear(),t(this,ic,"f").clear(),t(this,gc,"f").clear(),t(this,vc,"f").clear(),t(this,wc,"f").clear()},ec=function(){this.connectionManager?.clear(),this.latestConnectionMessages.clear()},tc=function(e,s){if(bc.log({messageType:e,dataView:s}),"batteryLevel"===e){const e=s.getUint8(0);bc.log("received battery level",{batteryLevel:e}),t(this,Ao,"m",ac).call(this,e)}else if($e.includes(e))t(this,fc,"f").parseMessage(e,s);else if(ci.includes(e))t(this,gc,"f").parseMessage(e,s);else if(hs.includes(e))t(this,hc,"f").parseMessage(e,s);else if(Lr.includes(e))t(this,uc,"f").parseMessage(e,s);else if(bi.includes(e))t(this,ic,"f").parseMessage(e,s);else if(zi.includes(e))this._informationManager.parseMessage(e,s);else if(Ts.includes(e))t(this,rc,"f").parseMessage(e,s);else if(vn.includes(e))t(this,lc,"f").parseMessage(e,s);else if(Pn.includes(e))t(this,vc,"f").parseMessage(e,s);else{if(!ts.includes(e))throw Error(`uncaught messageType ${e}`);t(this,wc,"f").parseMessage(e,s)}this.latestConnectionMessages.set(e,s),e.startsWith("set")&&this.latestConnectionMessages.set(e.replace("set","get"),s),t(this,Ao,"a",Oo).call(this,"connectionMessage",{messageType:e,dataView:s})},sc=function(){!this.isConnected&&t(this,Ao,"a",zo)&&t(this,Ao,"m",Xo).call(this),"notConnected"!=this.connectionStatus&&t(this,Ao,"m",Po).call(this)},ac=function(e){bc.assertTypeWithError(e,"number"),t(this,nc,"f")!=e?(s(this,nc,e,"f"),bc.log({updatedBatteryLevel:t(this,nc,"f")}),t(this,Ao,"a",Oo).call(this,"batteryLevel",{batteryLevel:t(this,nc,"f")})):bc.log(`duplicate batteryLevel assignment ${e}`)},dc=function(){bc.assertWithError(this.canUpdateFirmware,"can't update firmware")},mc=function(e){return t(this,Ao,"m",dc).call(this),t(this,Bo,"f").sendSmpMessage(e)},yc=function(){bc.assertWithError(this.hasCamera,"camera not available")},Ho={value:!1},oc={value:!0};const _c=W("DevicePairPressureSensorDataManager",{log:!1});class Lc{constructor(){Mc.add(this),kc.set(this,{}),Dc.set(this,new it),Tc.set(this,new Ze),this.resetPressureRange()}resetPressureRange(){t(this,Dc,"f").reset(),t(this,Tc,"f").reset()}onDevicePressureData(e){const{pressure:s}=e.message,{side:i}=e.target;if(_c.log({pressure:s,side:i}),t(this,kc,"f")[i]=s,t(this,Mc,"a",Wc))return t(this,Mc,"m",Ic).call(this);_c.log("doesn't have all pressure data yet...")}}var Uc;kc=new WeakMap,Dc=new WeakMap,Tc=new WeakMap,Mc=new WeakSet,Wc=function(){return qi.every((e=>e in t(this,kc,"f")))},Ic=function(){const e={scaledSum:0,normalizedSum:0,sensors:{left:[],right:[]}};return qi.forEach((s=>{const i=t(this,kc,"f")[s];e.scaledSum+=i.scaledSum})),e.normalizedSum+=t(this,Tc,"f").updateAndGetNormalization(e.scaledSum,!1),e.scaledSum>0&&(e.center={x:0,y:0},qi.forEach((s=>{t(this,kc,"f")[s].sensors.forEach((t=>{const i={...t};i.weightedValue=t.scaledValue/e.scaledSum;let{x:n,y:a}=t.position;n/=2,"right"==s&&(n+=.5),i.position={x:n,y:a},e.center.x+=i.position.x*i.weightedValue,e.center.y+=i.position.y*i.weightedValue,e.sensors[s].push(i)}))})),e.normalizedCenter=t(this,Dc,"f").updateAndGetNormalization(e.center,!1)),_c.log({devicePairPressure:e}),e};const Fc=W("DevicePairSensorDataManager",{log:!1}),Ac=["pressure","sensorData"];class Rc{constructor(){Uc.set(this,{}),this.pressureSensorDataManager=new Lc}get dispatchEvent(){return this.eventDispatcher.dispatchEvent}resetPressureRange(){this.pressureSensorDataManager.resetPressureRange()}onDeviceSensorData(e){const{timestamp:s,sensorType:i}=e.message;let n;if(Fc.log({sensorType:i,timestamp:s,event:e}),t(this,Uc,"f")[i]||(t(this,Uc,"f")[i]={}),t(this,Uc,"f")[i][e.target.side]=s,"pressure"===i)n=this.pressureSensorDataManager.onDevicePressureData(e);else Fc.log(`uncaught sensorType "${i}"`);if(n){const e=Object.assign({},t(this,Uc,"f")[i]);this.dispatchEvent(i,{sensorType:i,timestamps:e,[i]:n}),this.dispatchEvent("sensorData",{sensorType:i,timestamps:e,[i]:n})}else Fc.log("no value received")}}var xc,$c,Oc,Bc,Pc,Nc,Vc,qc,zc,jc,Gc,Hc,Jc,Kc,Qc,Zc,Xc,Yc,eh;Uc=new WeakMap;const th=W("DevicePair",{log:!1});function sh(e){return`device${t=e,t[0].toUpperCase()+t.slice(1)}`;var t}const ih=["isConnected",...Ac,...Sc.map((e=>sh(e)))];class nh{constructor(e){xc.add(this),Oc.set(this,void 0),Bc.set(this,new _(this,ih)),Nc.set(this,void 0),Vc.set(this,void 0),Hc.set(this,{isConnected:t(this,xc,"m",Kc).bind(this),sensorData:t(this,xc,"m",Xc).bind(this),getType:t(this,xc,"m",Qc).bind(this)}),Zc.set(this,new Rc),s(this,Oc,e,"f"),t(this,Zc,"f").eventDispatcher=t(this,Bc,"f")}get sides(){return qi}get type(){return t(this,Oc,"f")}get addEventListener(){return t(this,Bc,"f").addEventListener}get removeEventListener(){return t(this,Bc,"f").removeEventListener}get waitForEvent(){return t(this,Bc,"f").waitForEvent}get removeEventListeners(){return t(this,Bc,"f").removeEventListeners}get removeAllEventListeners(){return t(this,Bc,"f").removeAllEventListeners}get left(){return t(this,Nc,"f")}get right(){return t(this,Vc,"f")}get isConnected(){return qi.every((e=>this[e]?.isConnected))}get isPartiallyConnected(){return qi.some((e=>this[e]?.isConnected))}get isHalfConnected(){return this.isPartiallyConnected&&!this.isConnected}assignDevice(e){if(!t(this,xc,"m",qc).call(this,e))return void th.log(`device is incorrect type ${e.type} for ${this.type} devicePair`);const i=e.side,n=this[i];if(e!=n){switch(n&&t(this,xc,"m",jc).call(this,n),t(this,xc,"m",zc).call(this,e),i){case"left":s(this,Nc,e,"f");break;case"right":s(this,Vc,e,"f")}return th.log(`assigned ${i} ${this.type} device`,e),this.resetPressureRange(),t(this,xc,"a",Pc).call(this,"isConnected",{isConnected:this.isConnected}),t(this,xc,"a",Pc).call(this,"deviceIsConnected",{device:e,isConnected:e.isConnected,side:i}),n}th.log("device already assigned")}async setSensorConfiguration(e){for(let t=0;t<qi.length;t++){const s=qi[t];this[s]?.isConnected&&await this[s].setSensorConfiguration(e)}}resetPressureRange(){qi.forEach((e=>this[e]?.resetPressureRange())),t(this,Zc,"f").resetPressureRange()}async triggerVibration(e,t){const s=qi.map((s=>this[s]?.triggerVibration(e,t))).filter(Boolean);return Promise.allSettled(s)}static get insoles(){return t(this,$c,"f",Yc)}static get gloves(){return t(this,$c,"f",eh)}}var ah,rh,oh,ch,hh;$c=nh,Oc=new WeakMap,Bc=new WeakMap,Nc=new WeakMap,Vc=new WeakMap,Hc=new WeakMap,Zc=new WeakMap,xc=new WeakSet,Pc=function(){return t(this,Bc,"f").dispatchEvent},qc=function(e){switch(this.type){case"insoles":return e.isInsole;case"gloves":return e.isGlove}},zc=function(e){ga(e,t(this,Hc,"f")),Sc.forEach((s=>{e.addEventListener(s,t(this,xc,"m",Jc).bind(this))}))},jc=function(e){ua(e,t(this,Hc,"f")),Sc.forEach((s=>{e.removeEventListener(s,t(this,xc,"m",Jc).bind(this))}))},Gc=function(e){const i=qi.some((i=>{if(this[i]!=e)return!1;switch(th.log(`removing ${i} ${this.type} device`,e),ua(e,t(this,Hc,"f")),i){case"left":s(this,Nc,void 0,"f");break;case"right":s(this,Vc,void 0,"f")}return!0}));return i&&t(this,xc,"a",Pc).call(this,"isConnected",{isConnected:this.isConnected}),i},Jc=function(e){const{type:s,target:i,message:n}=e;t(this,xc,"a",Pc).call(this,sh(s),{...n,device:i,side:i.side})},Kc=function(e){t(this,xc,"a",Pc).call(this,"isConnected",{isConnected:this.isConnected})},Qc=function(e){const{target:s}=e;if(this[s.side]==s)return;t(this,xc,"m",Gc).call(this,s)&&this.assignDevice(s)},Xc=function(e){this.isConnected&&t(this,Zc,"f").onDeviceSensorData(e)},Yc={value:new $c("insoles")},eh={value:new $c("gloves")},so.AddEventListener("deviceConnected",(e=>{const{device:s}=e.message;s.isInsole&&t($c,$c,"f",Yc).assignDevice(s),s.isGlove&&t($c,$c,"f",eh).assignDevice(s)}));const lh=W("ClientConnectionManager",{log:!1});class fh extends la{constructor(){super(...arguments),ah.add(this),rh.set(this,void 0),oh.set(this,!1)}static get isSupported(){return n}static get type(){return"client"}get canUpdateFirmware(){return!1}get bluetoothId(){return t(this,rh,"f")}set bluetoothId(e){lh.assertTypeWithError(e,"string"),t(this,rh,"f")!=e?s(this,rh,e,"f"):lh.log("redundant bluetoothId assignment")}get isConnected(){return t(this,oh,"f")}set isConnected(e){lh.assertTypeWithError(e,"boolean"),t(this,oh,"f")!=e?(s(this,oh,e,"f"),this.status=t(this,oh,"f")?"connected":"notConnected",this.isConnected&&t(this,ah,"m",ch).call(this)):lh.log("redundant newIsConnected assignment",e)}get isAvailable(){return this.client.isConnected}async connect(){await super.connect(),this.sendClientConnectMessage(this.subType)}async disconnect(){await super.disconnect(),this.sendClientDisconnectMessage()}get canReconnect(){return!0}async reconnect(){await super.reconnect(),this.sendClientConnectMessage()}async sendSmpMessage(e){super.sendSmpMessage(e),this.sendClientMessage({type:"smp",data:e})}async sendTxData(e){super.sendTxData(e),0!=e.byteLength&&this.sendClientMessage({type:"tx",data:e})}onClientMessage(e){lh.log({dataView:e}),bt(e,Sc,t(this,ah,"m",hh).bind(this),null,!0),this.onMessagesReceived()}}var gh,uh,dh,mh,ph,vh,wh,yh,bh,Sh,Ch,Eh,Mh,kh,Dh,Th,Wh,Ih,_h,Lh,Uh,Fh,Ah,Rh;rh=new WeakMap,oh=new WeakMap,ah=new WeakSet,ch=function(){this.sendRequiredDeviceInformationMessage()},hh=function(e,t){let s=0;switch(lh.log({messageType:e},t),e){case"isConnected":const i=Boolean(t.getUint8(s++));lh.log({isConnected:i}),this.isConnected=i;break;case"rx":this.parseRxMessage(t);break;default:this.onMessageReceived(e,t)}};const xh=W("BaseClient",{log:!1}),$h=["notConnected","connecting","connected","disconnecting","connectionStatus","isConnected","isScanningAvailable","isScanning","discoveredDevice","expiredDiscoveredDevice"];class Oh{constructor(){gh.add(this),mh.set(this,{}),ph.set(this,new _(this,$h)),this._reconnectOnDisconnection=this.baseConstructor.ReconnectOnDisconnection,vh.set(this,"notConnected"),bh.set(this,[]),Eh.set(this,!1),Th.set(this,!1),Fh.set(this,{})}get baseConstructor(){return this.constructor}get devices(){return t(this,mh,"f")}get addEventListener(){return t(this,ph,"f").addEventListener}get dispatchEvent(){return t(this,ph,"f").dispatchEvent}get removeEventListener(){return t(this,ph,"f").removeEventListener}get waitForEvent(){return t(this,ph,"f").waitForEvent}assertConnection(){xh.assertWithError(this.isConnected,"notConnected")}assertDisconnection(){xh.assertWithError(this.isDisconnected,"not disconnected")}static get ReconnectOnDisconnection(){return this._reconnectOnDisconnection}static set ReconnectOnDisconnection(e){xh.assertTypeWithError(e,"boolean"),this._reconnectOnDisconnection=e}get reconnectOnDisconnection(){return this._reconnectOnDisconnection}set reconnectOnDisconnection(e){xh.assertTypeWithError(e,"boolean"),this._reconnectOnDisconnection=e}get _connectionStatus(){return t(this,vh,"f")}set _connectionStatus(e){switch(xh.assertTypeWithError(e,"string"),xh.log({newConnectionStatus:e}),s(this,vh,e,"f"),this.dispatchEvent("connectionStatus",{connectionStatus:this.connectionStatus}),this.dispatchEvent(this.connectionStatus,{}),e){case"connected":case"notConnected":this.dispatchEvent("isConnected",{isConnected:this.isConnected}),this.isConnected||t(this,gh,"m",dh).call(this)}}get connectionStatus(){return this._connectionStatus}_sendRequiredMessages(){xh.log("sending required messages",t(this,bh,"f")),this.sendServerMessage(...t(this,gh,"a",yh))}parseMessage(e){xh.log("parseMessage",{dataView:e}),bt(e,no,t(this,gh,"m",Ch).bind(this),null,!0),t(this,gh,"m",Sh).call(this)}get isScanningAvailable(){return t(this,gh,"a",Mh)}requestIsScanningAvailable(){this.sendServerMessage("isScanningAvailable")}get isScanning(){return t(this,gh,"a",Wh)}startScan(){t(this,gh,"m",Uh).call(this),this.sendServerMessage("startScan")}stopScan(){t(this,gh,"m",Lh).call(this),this.sendServerMessage("stopScan")}toggleScan(){t(this,gh,"m",Dh).call(this),this.isScanning?this.stopScan():this.startScan()}get discoveredDevices(){return t(this,Fh,"f")}onDiscoveredDevice(e){xh.log({discoveredDevice:e}),t(this,Fh,"f")[e.bluetoothId]=e,this.dispatchEvent("discoveredDevice",{discoveredDevice:e})}requestDiscoveredDevices(){this.sendServerMessage({type:"discoveredDevices"})}connectToDevice(e,t){return this.requestConnectionToDevice(e,t)}requestConnectionToDevice(e,s){this.assertConnection(),xh.assertTypeWithError(e,"string");const i=t(this,gh,"m",Rh).call(this,e);return s?i.connect({type:"client",subType:s}):i.connect(),i}sendConnectToDeviceMessage(e,t){t?this.sendServerMessage({type:"connectToDevice",data:z(j(e),ia.indexOf(t))}):this.sendServerMessage({type:"connectToDevice",data:e})}createDevice(e){const s=new Ec,i=t(this,Fh,"f")[e],n=new fh;return n.discoveredDevice=Object.assign({},i),n.client=this,n.bluetoothId=e,n.sendClientMessage=this.sendDeviceMessage.bind(this,e),n.sendRequiredDeviceInformationMessage=this.sendRequiredDeviceInformationMessage.bind(this,e),n.sendClientConnectMessage=this.sendConnectToDeviceMessage.bind(this,e),n.sendClientDisconnectMessage=this.sendDisconnectFromDeviceMessage.bind(this,e),s.connectionManager=n,s}onConnectedBluetoothDeviceIds(e){xh.log({bluetoothIds:e}),e.forEach((e=>{const s=t(this,gh,"m",Rh).call(this,e);s.connectionManager.isConnected=!0,so._CheckDeviceAvailability(s)}))}disconnectFromDevice(e){this.requestDisconnectionFromDevice(e)}requestDisconnectionFromDevice(e){this.assertConnection(),xh.assertTypeWithError(e,"string");const t=this.devices[e];return xh.assertWithError(t,`no device found with id ${e}`),t.disconnect(),t}sendDisconnectFromDeviceMessage(e){this.sendServerMessage({type:"disconnectFromDevice",data:e})}sendDeviceMessage(e,...t){this.sendServerMessage({type:"deviceMessage",data:[e,oo(...t)]})}sendRequiredDeviceInformationMessage(e){this.sendServerMessage({type:"requiredDeviceInformation",data:[e]})}}var Bh,Ph,Nh,Vh,qh,zh,jh,Gh,Hh,Jh,Kh,Qh,Zh;uh=Oh,mh=new WeakMap,ph=new WeakMap,vh=new WeakMap,bh=new WeakMap,Eh=new WeakMap,Th=new WeakMap,Fh=new WeakMap,gh=new WeakSet,dh=function(){s(this,gh,!1,"a",kh),s(this,gh,!1,"a",Ih);for(const e in t(this,mh,"f")){t(this,mh,"f")[e].connectionManager.isConnected=!1}t(this,bh,"f").length=0},yh=function(){return t(uh,uh,"f",wh)},Sh=function(){"connecting"==this.connectionStatus&&(xh.log("checking if fully connected..."),t(this,bh,"f").includes("isScanningAvailable")?!this.isScanningAvailable||t(this,bh,"f").includes("isScanning")?(xh.log("fully connected"),this._connectionStatus="connected"):xh.log("not fully connected - didn't receive isScanning"):xh.log("not fully connected - didn't receive isScanningAvailable"))},Ch=function(e,i){let n=0;switch(xh.log({messageType:e},i),e){case"isScanningAvailable":{const e=Boolean(i.getUint8(n++));xh.log({isScanningAvailable:e}),s(this,gh,e,"a",kh)}break;case"isScanning":{const e=Boolean(i.getUint8(n++));xh.log({isScanning:e}),s(this,gh,e,"a",Ih)}break;case"discoveredDevice":{const{string:e}=yt(i,n);xh.log({discoveredDeviceString:e});const t=JSON.parse(e);xh.log({discoveredDevice:t}),this.onDiscoveredDevice(t)}break;case"expiredDiscoveredDevice":{const{string:e}=yt(i,n);t(this,gh,"m",Ah).call(this,e)}break;case"connectedDevices":{if(0==i.byteLength)break;const{string:e}=yt(i,n);xh.log({connectedBluetoothDeviceIdStrings:e});const t=JSON.parse(e).connectedDevices;xh.log({connectedBluetoothDeviceIds:t}),this.onConnectedBluetoothDeviceIds(t)}break;case"deviceMessage":{const{string:e,byteOffset:s}=yt(i,n);n=s;const a=t(this,mh,"f")[e];xh.assertWithError(a,`no device found for id ${e}`);const r=a.connectionManager,o=G(i,n);r.onClientMessage(o)}break;default:xh.error(`uncaught messageType "${e}"`)}"connecting"==this.connectionStatus&&t(this,bh,"f").push(e)},Mh=function(){return t(this,Eh,"f")},kh=function(e){xh.assertTypeWithError(e,"boolean"),s(this,Eh,e,"f"),this.dispatchEvent("isScanningAvailable",{isScanningAvailable:this.isScanningAvailable}),this.isScanningAvailable&&t(this,gh,"m",_h).call(this)},Dh=function(){this.assertConnection(),xh.assertWithError(this.isScanningAvailable,"scanning is not available")},Wh=function(){return t(this,Th,"f")},Ih=function(e){xh.assertTypeWithError(e,"boolean"),s(this,Th,e,"f"),this.dispatchEvent("isScanning",{isScanning:this.isScanning})},_h=function(){this.sendServerMessage("isScanning")},Lh=function(){xh.assertWithError(this.isScanning,"is not scanning")},Uh=function(){xh.assertWithError(!this.isScanning,"is already scanning")},Ah=function(e){xh.log({expiredBluetoothDeviceId:e});const s=t(this,Fh,"f")[e];s?(xh.log({expiredDiscoveredDevice:s}),delete t(this,Fh,"f")[e],this.dispatchEvent("expiredDiscoveredDevice",{discoveredDevice:s})):xh.warn(`no discoveredDevice found with id "${e}"`)},Rh=function(e){let s=t(this,mh,"f")[e];return s||(s=this.createDevice(e),t(this,mh,"f")[e]=s),s},Oh._reconnectOnDisconnection=!0,wh={value:["isScanningAvailable","discoveredDevices","connectedDevices"]};const Xh=W("WebSocketClient",{log:!1});Ph=new WeakMap,Vh=new WeakMap,Kh=new WeakMap,Bh=new WeakSet,Nh=function(...e){this.sendMessage(lo(...e))},qh=function(e){Xh.log("webSocket.open",e),t(this,Kh,"f").start(),this._sendRequiredMessages()},zh=async function(e){Xh.log("webSocket.message",e);const s=await e.data.arrayBuffer(),i=new DataView(s);t(this,Bh,"m",Hh).call(this,i)},jh=function(e){Xh.log("webSocket.close",e),this._connectionStatus="notConnected",Object.entries(this.devices).forEach((([e,t])=>{t.connectionManager.isConnected=!1})),t(this,Kh,"f").stop(),this.reconnectOnDisconnection&&setTimeout((()=>{this.reconnect()}),3e3)},Gh=function(e){Xh.error("webSocket.error",e)},Hh=function(e){bt(e,ho,t(this,Bh,"m",Jh).bind(this),null,!0)},Jh=function(e,s){switch(e){case"ping":t(this,Bh,"m",Zh).call(this);break;case"pong":break;case"serverMessage":this.parseMessage(s);break;default:Xh.error(`uncaught messageType "${e}"`)}},Qh=function(){t(this,Bh,"m",Nh).call(this,"ping")},Zh=function(){t(this,Bh,"m",Nh).call(this,"pong")};const Yh={addEventListeners:ga,removeEventListeners:ua},el={throttle:function(e,t,s=!1){let i=0,n=null,a=null;return function(...r){const o=Date.now(),c=t-(o-i);c<=0?(n&&(clearTimeout(n),n=null),i=o,e(...r)):s&&(a=r,n||(n=setTimeout((()=>{i=Date.now(),n=null,a&&(e(...a),a=null)}),c)))}},debounce:function(e,t,s=!1){let i=null;return function(...n){const a=s&&!i;i&&clearTimeout(i),i=setTimeout((()=>{i=null,s||e(...n)}),t),a&&e(...n)}}};e.CameraCommands=Zt,e.CameraConfigurationTypes=es,e.ContinuousSensorTypes=cs,e.DefaultNumberOfPressureSensors=8,e.Device=Ec,e.DeviceManager=so,e.DevicePair=nh,e.DevicePairTypes=["insoles","gloves"],e.DeviceTypes=Vi,e.Environment=y,e.EventUtils=Yh,e.FileTransferDirections=["sending","receiving"],e.FileTypes=Oe,e.MaxNameLength=30,e.MaxNumberOfVibrationWaveformEffectSegments=8,e.MaxNumberOfVibrationWaveformSegments=20,e.MaxSensorRate=65535,e.MaxVibrationWaveformEffectSegmentDelay=bn,e.MaxVibrationWaveformEffectSegmentLoopCount=3,e.MaxVibrationWaveformEffectSequenceLoopCount=6,e.MaxVibrationWaveformSegmentDuration=yn,e.MaxWifiPasswordLength=64,e.MaxWifiSSIDLength=32,e.MinNameLength=2,e.MinWifiPasswordLength=8,e.MinWifiSSIDLength=1,e.RangeHelper=Ze,e.SensorRateStep=5,e.SensorTypes=os,e.Sides=qi,e.TfliteSensorTypes=gi,e.TfliteTasks=fi,e.ThrottleUtils=el,e.VibrationLocations=mn,e.VibrationTypes=pn,e.VibrationWaveformEffects=Hi,e.WebSocketClient=class extends Oh{constructor(){super(...arguments),Bh.add(this),Ph.set(this,void 0),Vh.set(this,{open:t(this,Bh,"m",qh).bind(this),message:t(this,Bh,"m",zh).bind(this),close:t(this,Bh,"m",jh).bind(this),error:t(this,Bh,"m",Gh).bind(this)}),Kh.set(this,new R(t(this,Bh,"m",Qh).bind(this),3e4))}get webSocket(){return t(this,Ph,"f")}set webSocket(e){t(this,Ph,"f")!=e?(Xh.log("assigning webSocket",e),t(this,Ph,"f")&&ua(t(this,Ph,"f"),t(this,Vh,"f")),ga(e,t(this,Vh,"f")),s(this,Ph,e,"f"),Xh.log("assigned webSocket")):Xh.log("redundant webSocket assignment")}get readyState(){return this.webSocket?.readyState}get isConnected(){return this.readyState==WebSocket.OPEN}get isDisconnected(){return this.readyState==WebSocket.CLOSED}connect(e=`wss://${location.host}`){this.webSocket&&this.assertDisconnection(),this._connectionStatus="connecting",this.webSocket=new WebSocket(e)}disconnect(){this.assertConnection(),this.reconnectOnDisconnection&&(this.reconnectOnDisconnection=!1,this.webSocket.addEventListener("close",(()=>{this.reconnectOnDisconnection=!0}),{once:!0})),this._connectionStatus="disconnecting",this.webSocket.close()}reconnect(){this.assertDisconnection(),this.connect(this.webSocket.url)}toggleConnection(e){this.isConnected?this.disconnect():e&&this.webSocket?.url==e?this.reconnect():this.connect(e)}sendMessage(e){this.assertConnection(),t(this,Ph,"f").send(e),t(this,Kh,"f").restart()}sendServerMessage(...e){this.sendMessage(lo({type:"serverMessage",data:ro(...e)}))}},e.setAllConsoleLevelFlags=function(e){T.setAllLevelFlags(e)},e.setConsoleLevelFlagsForType=function(e,t){T.setLevelFlagsForType(e,t)}}));
|
|
5
|
+
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).BS={})}(this,(function(e){"use strict";function t(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)}function i(e,t,i,s,n){if("m"===s)throw new TypeError("Private method is not writable");if("a"===s&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===s?n.call(e,i):n?n.value=i:t.set(e,i),i}"function"==typeof SuppressedError&&SuppressedError;const s=!1,n="undefined"!=typeof window&&void 0!==window?.document,a="undefined"!=typeof process&&null!=process?.versions?.node,r=n&&navigator.userAgent||"";let o=!1;n?o=Boolean(navigator.bluetooth):a&&(o=!0);const c=n&&/Bluefy/i.test(r),h=n&&/WebBLE/i.test(r),l=n&&/Android/i.test(r),f=n&&/Safari/i.test(r)&&!/Chrome/i.test(r),g=n&&/iPad|iPhone|iPod/i.test(r),u=n&&/Macintosh/i.test(r),d=!n&&!a&&"undefined"!=typeof global&&"undefined"!=typeof Studio;var m,p,v,w,y=Object.freeze({__proto__:null,isAndroid:l,get isBluetoothSupported(){return o},isIOS:g,isInBluefy:c,isInBrowser:n,isInDev:s,isInLensStudio:d,isInNode:a,isInProduction:!0,isInWebBLE:h,isMac:u,isSafari:f});if(d){const e=function(...e){Studio.log(e.map((e=>new String(e))).join(","))};(w={}).log=e,w.warn=e.bind(w,"WARNING"),w.error=e.bind(w,"ERROR")}else w=console;function b(e){return(...t)=>{if(a){const i=function(){const e=(new Error).stack;if(!e)return"";const t=e.split("\n"),i=t[3]||t[2],s=i.match(/at (.*?) \(/)||i.match(/at (.*)/);return s?`[${s[1].trim()}]`:""}();e(i,...t)}else e(...t)}}if(!w.assert){const e=(e,...t)=>{e||w.warn(...t)};w.assert=e}if(!w.table){const e=(...e)=>{w.log(...e)};w.table=e}function S(){}const C=a?b(w.log.bind(w)):w.log.bind(w),M=a?b(w.warn.bind(w)):w.warn.bind(w),E=a?b(w.error.bind(w)):w.error.bind(w),k=a?b(w.table.bind(w)):w.table.bind(w),D=w.assert.bind(w);class W{constructor(e){if(v.set(this,{log:s,warn:s,assert:!0,error:!0,table:!0}),t(m,m,"f",p)[e])throw new Error(`"${e}" console already exists`);t(m,m,"f",p)[e]=this}setLevelFlags(e){Object.assign(t(this,v,"f"),e)}static setLevelFlagsForType(e,i){if(!t(this,m,"f",p)[e])throw new Error(`no console found with type "${e}"`);t(this,m,"f",p)[e].setLevelFlags(i)}static setAllLevelFlags(e){for(const i in t(this,m,"f",p))t(this,m,"f",p)[i].setLevelFlags(e)}static create(e,i){return t(this,m,"f",p)[e]||new m(e)}get log(){return t(this,v,"f").log?C:S}get warn(){return t(this,v,"f").warn?M:S}get error(){return t(this,v,"f").error?E:S}get assert(){return t(this,v,"f").assert?D:S}get table(){return t(this,v,"f").table?k:S}assertWithError(e,t){if(!Boolean(e))throw new Error(t)}assertTypeWithError(e,t){this.assertWithError(typeof e==t,`value ${e} of type "${typeof e}" not of type "${t}"`)}assertEnumWithError(e,t){this.assertWithError(t.includes(e),`invalid enum "${e}"`)}assertRangeWithError(e,t,i,s){this.assertWithError(t>=i&&t<=s,`${e} ${t} must be within ${i}-${s}`)}}function T(e,t){return W.create(e,t)}m=W,v=new WeakMap,p={value:{}};const I=T("EventDispatcher",{log:!1});class _{constructor(e,t){this.target=e,this.validEventTypes=t,this.listeners={},this.addEventListener=this.addEventListener.bind(this),this.removeEventListener=this.removeEventListener.bind(this),this.removeEventListeners=this.removeEventListeners.bind(this),this.removeAllEventListeners=this.removeAllEventListeners.bind(this),this.dispatchEvent=this.dispatchEvent.bind(this),this.waitForEvent=this.waitForEvent.bind(this)}isValidEventType(e){return this.validEventTypes.includes(e)}updateEventListeners(e){this.listeners[e]&&(this.listeners[e]=this.listeners[e].filter((t=>(t.shouldRemove&&I.log(`removing "${e}" eventListener`,t),!t.shouldRemove))))}addEventListener(e,t,i={once:!1}){if(!this.isValidEventType(e))throw new Error(`Invalid event type: ${e}`);this.listeners[e]||(this.listeners[e]=[],I.log(`creating "${e}" listeners array`,this.listeners[e]));this.listeners[e].find((e=>e.listener==t&&e.once==i.once))?I.log("already added listener"):(I.log(`adding "${e}" listener`,t,i),this.listeners[e].push({listener:t,once:i.once}),I.log(`currently have ${this.listeners[e].length} "${e}" listeners`))}removeEventListener(e,t){if(!this.isValidEventType(e))throw new Error(`Invalid event type: ${e}`);this.listeners[e]&&(I.log(`removing "${e}" listener...`,t),this.listeners[e].forEach((i=>{i.listener===t&&(I.log(`flagging "${e}" listener`,t),i.shouldRemove=!0)})),this.updateEventListeners(e))}removeEventListeners(e){if(!this.isValidEventType(e))throw new Error(`Invalid event type: ${e}`);this.listeners[e]&&(I.log(`removing "${e}" listeners...`),this.listeners[e]=[])}removeAllEventListeners(){I.log("removing listeners..."),this.listeners={}}dispatchEvent(e,t){if(!this.isValidEventType(e))throw new Error(`Invalid event type: ${e}`);this.listeners[e]&&(this.listeners[e].forEach((i=>{i.shouldRemove||(I.log(`dispatching "${e}" listener`,i),i.listener({type:e,target:this.target,message:t}),i.once&&(I.log(`flagging "${e}" listener`,i),i.shouldRemove=!0))})),this.updateEventListeners(e))}waitForEvent(e){return new Promise((t=>{this.addEventListener(e,(e=>{t(e)}),{once:!0})}))}}var L,U,R;const F=T("Timer",{log:!1});class A{get callback(){return t(this,L,"f")}set callback(e){F.assertTypeWithError(e,"function"),F.log({newCallback:e}),i(this,L,e,"f"),this.isRunning&&this.restart()}get interval(){return t(this,U,"f")}set interval(e){F.assertTypeWithError(e,"number"),F.assertWithError(e>0,"interval must be above 0"),F.log({newInterval:e}),i(this,U,e,"f"),this.isRunning&&this.restart()}constructor(e,t){L.set(this,void 0),U.set(this,void 0),R.set(this,void 0),this.interval=t,this.callback=e}get isRunning(){return null!=t(this,R,"f")}start(e=!1){this.isRunning?F.log("interval already running"):(F.log(`starting interval every ${t(this,U,"f")}ms`),i(this,R,setInterval(t(this,L,"f"),t(this,U,"f")),"f"),e&&t(this,L,"f").call(this))}stop(){this.isRunning?(F.log("stopping interval"),clearInterval(t(this,R,"f")),i(this,R,void 0,"f")):F.log("interval already not running")}restart(e=!1){this.stop(),this.start(e)}}function x(e){for(let t=0;t<8;++t)e=(1&e?0:3988292384)^e>>>1;return 4278190080^e}L=new WeakMap,U=new WeakMap,R=new WeakMap,T("checksum",{log:!1});const $=new Uint32Array(256);for(let e=0;e<256;++e)$[e]=x(e);function O(e){let t=new Uint8Array(e),i=0;for(let e=0;e<t.byteLength;++e){const s=255&i,n=t[e];i=($[s^n]^i>>>8)>>>0}return i}var B,N;B="undefined"==typeof TextEncoder?class{encode(e){const t=Array.from(e).map((e=>e.charCodeAt(0)));return Uint8Array.from(t)}}:TextEncoder,N="undefined"==typeof TextDecoder?class{decode(e){return Array.from(new Uint8Array(e)).map((e=>String.fromCharCode(e))).join("")}}:TextDecoder;const P=new B,V=new N,q=T("ArrayBufferUtils",{log:!1});function z(...e){const t=(e=(e=(e=e.filter((e=>null!=e||null!=e))).map((e=>{if("number"==typeof e){const t=e;return Uint8Array.from([Math.floor(t)])}if("boolean"==typeof e){const t=e;return Uint8Array.from([t?1:0])}if("string"==typeof e){return j(e)}if(e instanceof Array){return z(...e)}if(e instanceof ArrayBuffer)return e;if("buffer"in e&&e.buffer instanceof ArrayBuffer){return e.buffer}if(e instanceof DataView){return e.buffer}if("object"==typeof e){return function(e){return j(JSON.stringify(e))}(e)}return e}))).filter((e=>e&&"byteLength"in e))).reduce(((e,t)=>e+t.byteLength),0),i=new Uint8Array(t);let s=0;return e.forEach((e=>{i.set(new Uint8Array(e),s),s+=e.byteLength})),i.buffer}function j(e){const t=P.encode(e);return z(t.byteLength,t)}function G(e,t,i){let s;return null!=i&&(s=e.byteOffset+t+i),q.log({dataView:e,begin:t,end:s,length:i}),new DataView(e.buffer.slice(e.byteOffset+t,s))}async function H(e){let t;if(e instanceof Array)t=Uint8Array.from(e);else if(e instanceof DataView)t=e.buffer;else if("string"==typeof e||e instanceof URL){const i=await fetch(e);t=await i.arrayBuffer()}else if(e instanceof File)t=await e.arrayBuffer();else{if(!(e instanceof ArrayBuffer))throw{error:"invalid file type",file:e};t=e}return t}function J(e,{include:t,exclude:i}={}){const s=e=>{const s=t=>"string"==typeof t?e===t:t.test(e);return t?t.some(s):!i||!i.some(s)};for(const[t,i]of(e=>{const t=new Set;do{for(const i of Reflect.ownKeys(e))t.add([e,i])}while((e=Reflect.getPrototypeOf(e))&&e!==Object.prototype);return t})(e.constructor.prototype)){if("constructor"===i||!s(i))continue;const n=Reflect.getOwnPropertyDescriptor(t,i);n&&"function"==typeof n.value&&(e[i]=e[i].bind(e))}return e}var K,Q,Z,X,Y,ee,te,ie,se,ne,ae,re,oe,ce,he,le,fe,ge,ue,de,me,pe,ve,we,ye,be,Se,Ce,Me,Ee,ke,De,We,Te,Ie,_e,Le,Ue,Re,Fe,Ae;const xe=T("FileTransferManager",{log:!1}),$e=["getFileTypes","maxFileLength","getFileType","setFileType","getFileLength","setFileLength","getFileChecksum","setFileChecksum","setFileTransferCommand","fileTransferStatus","getFileBlock","setFileBlock","fileBytesTransferred"],Oe=["tflite","wifiServerCert","wifiServerKey"],Be=["idle","sending","receiving"],Ne=["startSend","startReceive","cancel"],Pe=[...$e,"fileTransferProgress","fileTransferComplete","fileReceived"],Ve=["maxFileLength","getFileLength","getFileChecksum","getFileType","fileTransferStatus"];class qe{constructor(){K.add(this),ie.set(this,[]),ae.set(this,Q.MaxLength),he.set(this,void 0),ue.set(this,0),ve.set(this,0),Ce.set(this,"idle"),We.set(this,[]),Ie.set(this,void 0),_e.set(this,0),Fe.set(this,!1),Ae.set(this,!1),J(this)}get addEventListener(){return this.eventDispatcher.addEventListener}get removeEventListener(){return this.eventDispatcher.removeEventListener}get waitForEvent(){return this.eventDispatcher.waitForEvent}get fileTypes(){return t(this,ie,"f")}static get MaxLength(){return t(this,Q,"f",ne)}get maxLength(){return t(this,ae,"f")}get type(){return t(this,he,"f")}get length(){return t(this,ue,"f")}get checksum(){return t(this,ve,"f")}get status(){return t(this,Ce,"f")}parseMessage(e,i){switch(xe.log({messageType:e}),e){case"getFileTypes":t(this,K,"m",se).call(this,i);break;case"maxFileLength":t(this,K,"m",re).call(this,i);break;case"getFileType":case"setFileType":t(this,K,"m",le).call(this,i);break;case"getFileLength":case"setFileLength":t(this,K,"m",de).call(this,i);break;case"getFileChecksum":case"setFileChecksum":t(this,K,"m",we).call(this,i);break;case"fileTransferStatus":t(this,K,"m",Me).call(this,i);break;case"getFileBlock":t(this,K,"m",Te).call(this,i);break;case"fileBytesTransferred":t(this,K,"m",Re).call(this,i);break;default:throw Error(`uncaught messageType ${e}`)}}async send(e,i){t(this,K,"m",ke).call(this),t(this,K,"m",X).call(this,e);const s=await H(i),n=s.byteLength,a=O(s);if(e!=this.type)xe.log("different fileTypes - sending");else if(n!=this.length)xe.log("different fileLengths - sending");else{if(a==this.checksum)return xe.log("already sent file"),!1;xe.log("different fileChecksums - sending")}const r=[];return r.push(t(this,K,"m",ge).call(this,e,!1)),r.push(t(this,K,"m",pe).call(this,n,!1)),r.push(t(this,K,"m",be).call(this,a,!1)),r.push(t(this,K,"m",Se).call(this,"startSend",!1)),this.sendMessage(),await Promise.all(r),await t(this,K,"m",Le).call(this,s),!0}async receive(e){t(this,K,"m",ke).call(this),t(this,K,"m",X).call(this,e),await t(this,K,"m",ge).call(this,e),await t(this,K,"m",Se).call(this,"startReceive")}async cancel(){t(this,K,"m",De).call(this),xe.log("cancelling file transfer..."),i(this,Fe,!0,"f"),await t(this,K,"m",Se).call(this,"cancel")}get isServerSide(){return t(this,Ae,"f")}set isServerSide(e){t(this,Ae,"f")!=e?(xe.log({newIsServerSide:e}),i(this,Ae,e,"f")):xe.log("redundant isServerSide assignment")}requestRequiredInformation(){xe.log("requesting required fileTransfer information");const e=Ve.map((e=>({type:e})));this.sendMessage(e,!1)}}Q=qe,ie=new WeakMap,ae=new WeakMap,he=new WeakMap,ue=new WeakMap,ve=new WeakMap,Ce=new WeakMap,We=new WeakMap,Ie=new WeakMap,_e=new WeakMap,Fe=new WeakMap,Ae=new WeakMap,K=new WeakSet,Z=function(){return this.eventDispatcher.dispatchEvent},X=function(e){xe.assertEnumWithError(e,Oe)},Y=function(e){xe.assertWithError(e in Oe,`invalid typeEnum ${e}`)},ee=function(e){xe.assertWithError(e in Be,`invalid statusEnum ${e}`)},te=function(e){xe.assertEnumWithError(e,Ne)},se=function(e){const s=Array.from(new Uint8Array(e.buffer)).map((e=>Oe[e])).filter(Boolean);i(this,ie,s,"f"),xe.log("fileTypes",s),t(this,K,"a",Z).call(this,"getFileTypes",{fileTypes:t(this,ie,"f")})},re=function(e){xe.log("parseFileMaxLength",e);const i=e.getUint32(0,!0);xe.log(`maxLength: ${i/1024}kB`),t(this,K,"m",oe).call(this,i)},oe=function(e){xe.log({maxLength:e}),i(this,ae,e,"f"),t(this,K,"a",Z).call(this,"maxFileLength",{maxFileLength:e})},ce=function(e){xe.assertWithError(e<=this.maxLength,`file length ${e}kB too large - must be ${this.maxLength}kB or less`)},le=function(e){xe.log("parseFileType",e);const i=e.getUint8(0);t(this,K,"m",Y).call(this,i);const s=Oe[i];t(this,K,"m",fe).call(this,s)},fe=function(e){xe.log({fileTransferType:e}),i(this,he,e,"f"),t(this,K,"a",Z).call(this,"getFileType",{fileType:e})},ge=async function(e,i){if(t(this,K,"m",X).call(this,e),this.type==e)return void xe.log(`redundant type assignment ${e}`);const s=this.waitForEvent("getFileType"),n=Oe.indexOf(e);this.sendMessage([{type:"setFileType",data:Uint8Array.from([n]).buffer}],i),await s},de=function(e){xe.log("parseFileLength",e);const i=e.getUint32(0,!0);t(this,K,"m",me).call(this,i)},me=function(e){xe.log(`length: ${e/1024}kB`),i(this,ue,e,"f"),t(this,K,"a",Z).call(this,"getFileLength",{fileLength:e})},pe=async function(e,i){if(xe.assertTypeWithError(e,"number"),t(this,K,"m",ce).call(this,e),this.length==e)return void xe.log(`redundant length assignment ${e}`);const s=this.waitForEvent("getFileLength"),n=new DataView(new ArrayBuffer(4));n.setUint32(0,e,!0),this.sendMessage([{type:"setFileLength",data:n.buffer}],i),await s},we=function(e){xe.log("checksum",e);const i=e.getUint32(0,!0);t(this,K,"m",ye).call(this,i)},ye=function(e){xe.log({checksum:e}),i(this,ve,e,"f"),t(this,K,"a",Z).call(this,"getFileChecksum",{fileChecksum:e})},be=async function(e,t){if(xe.assertTypeWithError(e,"number"),this.checksum==e)return void xe.log(`redundant checksum assignment ${e}`);const i=this.waitForEvent("getFileChecksum"),s=new DataView(new ArrayBuffer(4));s.setUint32(0,e,!0),this.sendMessage([{type:"setFileChecksum",data:s.buffer}],t),await i},Se=async function(e,i){t(this,K,"m",te).call(this,e);const s=this.waitForEvent("fileTransferStatus");xe.log(`setting command ${e}`);const n=Ne.indexOf(e);this.sendMessage([{type:"setFileTransferCommand",data:Uint8Array.from([n]).buffer}],i),await s},Me=function(e){xe.log("parseFileStatus",e);const i=e.getUint8(0);t(this,K,"m",ee).call(this,i);const s=Be[i];t(this,K,"m",Ee).call(this,s)},Ee=function(e){xe.log({status:e}),i(this,Ce,e,"f"),t(this,K,"a",Z).call(this,"fileTransferStatus",{fileTransferStatus:e}),t(this,We,"f").length=0,i(this,Fe,!1,"f")},ke=function(){xe.assertWithError("idle"==t(this,Ce,"f"),"status is not idle")},De=function(){xe.assertWithError("idle"!=t(this,Ce,"f"),"status is idle")},Te=async function(e){xe.log("parseFileBlock",e),t(this,We,"f").push(e.buffer);const i=t(this,We,"f").reduce(((e,t)=>e+t.byteLength),0),s=i/t(this,ue,"f");if(xe.log(`received ${i} of ${t(this,ue,"f")} bytes (${100*s}%)`),t(this,K,"a",Z).call(this,"fileTransferProgress",{progress:s}),i!=t(this,ue,"f")){const e=new DataView(new ArrayBuffer(4));if(e.setUint32(0,i,!0),this.isServerSide)return;return void await this.sendMessage([{type:"fileBytesTransferred",data:e.buffer}])}xe.log("file transfer complete");let n,a=(new Date).toLocaleString();switch(this.type){case"tflite":a+=".tflite";break;case"wifiServerCert":a+="_server.crt";break;case"wifiServerKey":a+="_server.key"}n="undefined"!=typeof File?new File(t(this,We,"f"),a):new Blob(t(this,We,"f"));const r=O(await n.arrayBuffer());xe.log({checksum:r}),r==t(this,ve,"f")?(xe.log("received file",n),t(this,K,"a",Z).call(this,"getFileBlock",{fileTransferBlock:e}),t(this,K,"a",Z).call(this,"fileTransferComplete",{direction:"receiving"}),t(this,K,"a",Z).call(this,"fileReceived",{file:n})):xe.error(`wrong checksum - expected ${t(this,ve,"f")}, got ${r}`)},Le=async function(e){return i(this,Ie,e,"f"),i(this,_e,0,"f"),t(this,K,"m",Ue).call(this)},Ue=async function(){if("sending"!=this.status)return;if(t(this,Fe,"f"))return void xe.error("not sending block - busy cancelling");if(!t(this,Ie,"f"))return void(this.isServerSide||xe.error("no buffer defined"));const e=t(this,Ie,"f");let s=t(this,_e,"f");const n=e.slice(s,s+(this.mtu-3-3));xe.log("slicedBuffer",n);const a=1-(e.byteLength-s)/e.byteLength;xe.log(`sending bytes ${s}-${s+n.byteLength} of ${e.byteLength} bytes (${100*a}%)`),t(this,K,"a",Z).call(this,"fileTransferProgress",{progress:a}),0==n.byteLength?(xe.log("finished sending buffer"),t(this,K,"a",Z).call(this,"fileTransferComplete",{direction:"sending"})):(await this.sendMessage([{type:"setFileBlock",data:n}]),i(this,_e,s+n.byteLength,"f"))},Re=async function(e){xe.log("parseBytesTransferred",e);const i=e.getUint32(0,!0);if(xe.log({bytesTransferred:i}),"sending"==this.status)return this.isServerSide||t(this,_e,"f")==i?void t(this,K,"m",Ue).call(this):(xe.error(`bytesTransferred are not equal - got ${i}, expected ${t(this,_e,"f")}`),void this.cancel());xe.error("not currently sending file")},ne={value:0};const ze=T("MathUtils",{log:!1});const je=65536;function Ge(e,t){const i=Date.now();var s;let n=(s=i)-s%je+e.getUint16(t,!0);return Math.abs(i-n)>6e4&&(ze.log("correcting timestamp delta"),n+=je*Math.sign(i-n)),n}var He,Je,Ke;const Qe={min:1/0,max:-1/0,span:0};class Ze{constructor(){He.add(this),Je.set(this,Object.assign({},Qe))}get min(){return t(this,Je,"f").min}get max(){return t(this,Je,"f").max}set min(e){t(this,Je,"f").min=e,t(this,Je,"f").max=Math.max(e,t(this,Je,"f").max),t(this,He,"m",Ke).call(this)}set max(e){t(this,Je,"f").max=e,t(this,Je,"f").min=Math.min(e,t(this,Je,"f").min),t(this,He,"m",Ke).call(this)}reset(){Object.assign(t(this,Je,"f"),Qe)}update(e){t(this,Je,"f").min=Math.min(e,t(this,Je,"f").min),t(this,Je,"f").max=Math.max(e,t(this,Je,"f").max),t(this,He,"m",Ke).call(this)}getNormalization(e,i){let s=function(e,t,i,s){return null==s&&(s=i-t),(e-t)/s}(e,t(this,Je,"f").min,t(this,Je,"f").max,t(this,Je,"f").span);return i&&(s*=t(this,Je,"f").span),s||0}updateAndGetNormalization(e,t){return this.update(e),this.getNormalization(e,t)}}var Xe,Ye,et,tt,it;Je=new WeakMap,He=new WeakSet,Ke=function(){t(this,Je,"f").span=t(this,Je,"f").max-t(this,Je,"f").min};class st{constructor(){Xe.set(this,{x:new Ze,y:new Ze})}reset(){t(this,Xe,"f").x.reset(),t(this,Xe,"f").y.reset()}update(e){t(this,Xe,"f").x.update(e.x),t(this,Xe,"f").y.update(e.y)}getNormalization(e,i){return{x:t(this,Xe,"f").x.getNormalization(e.x,i),y:t(this,Xe,"f").y.getNormalization(e.y,i)}}updateAndGetNormalization(e,t){return this.update(e),this.getNormalization(e,t)}}Xe=new WeakMap;const nt=T("PressureDataManager",{log:!1}),at=["pressure"],rt=at;class ot{constructor(){Ye.set(this,[]),et.set(this,void 0),tt.set(this,new Ze),it.set(this,new st)}get positions(){return t(this,Ye,"f")}get numberOfSensors(){return this.positions.length}parsePositions(e){const t=[];for(let i=0,s=0;s<e.byteLength;i++,s+=2)t.push({x:e.getUint8(s)/256,y:e.getUint8(s+1)/256});var s,n;nt.log({positions:t}),i(this,Ye,t,"f"),i(this,et,(s=this.numberOfSensors,n=()=>new Ze,new Array(s).fill(1).map(((e,t)=>{if("function"==typeof n)return n(t);{const e=n;return Object.assign({},e)}}))),"f"),this.resetRange()}resetRange(){t(this,et,"f")?.forEach((e=>e.reset())),t(this,it,"f").reset(),t(this,tt,"f").reset()}parseData(e,i){const s={sensors:[],scaledSum:0,normalizedSum:0};for(let n=0,a=0;a<e.byteLength;n++,a+=2){const r=e.getUint16(a,!0);let o=r*i/this.numberOfSensors;const c=t(this,et,"f")[n].updateAndGetNormalization(o,!1),h=this.positions[n];s.sensors[n]={rawValue:r,scaledValue:o,normalizedValue:c,position:h,weightedValue:0},s.scaledSum+=o}return s.normalizedSum=t(this,tt,"f").updateAndGetNormalization(s.scaledSum,!1),s.scaledSum>0&&(s.center={x:0,y:0},s.sensors.forEach((e=>{e.weightedValue=e.scaledValue/s.scaledSum,s.center.x+=e.position.x*e.weightedValue,s.center.y+=e.position.y*e.weightedValue})),s.normalizedCenter=t(this,it,"f").updateAndGetNormalization(s.center,!1)),nt.log({pressure:s}),s}}Ye=new WeakMap,et=new WeakMap,tt=new WeakMap,it=new WeakMap;const ct=T("MotionSensorDataManager",{log:!1}),ht=["still","walking","running","bicycle","vehicle","tilting"],lt=["portraitUpright","landscapeLeft","portraitUpsideDown","landscapeRight","unknown"];class ft{parseVector3(e,t){let[i,s,n]=[e.getInt16(0,!0),e.getInt16(2,!0),e.getInt16(4,!0)].map((e=>e*t));const a={x:i,y:s,z:n};return ct.log({vector:a}),a}parseQuaternion(e,t){let[i,s,n,a]=[e.getInt16(0,!0),e.getInt16(2,!0),e.getInt16(4,!0),e.getInt16(6,!0)].map((e=>e*t));const r={x:i,y:s,z:n,w:a};return ct.log({quaternion:r}),r}parseEuler(e,t){let[i,s,n]=[e.getInt16(0,!0),e.getInt16(2,!0),e.getInt16(4,!0)].map((e=>e*t));s*=-1,i*=-1,i<0&&(i+=360);const a={heading:i,pitch:s,roll:n};return ct.log({euler:a}),a}parseStepCounter(e){ct.log("parseStepCounter",e);const t=e.getUint32(0,!0);return ct.log({stepCount:t}),t}parseActivity(e){ct.log("parseActivity",e);const t={},i=e.getUint8(0);return ct.log("activityBitfield",i.toString(2)),ht.forEach(((e,s)=>{t[e]=Boolean(i&1<<s)})),ct.log("activity",t),t}parseDeviceOrientation(e){ct.log("parseDeviceOrientation",e);const t=e.getUint8(0),i=lt[t];return ct.assertWithError(i,"undefined deviceOrientation"),ct.log({deviceOrientation:i}),i}}var gt,ut;const dt=["barometer"],mt=dt,pt=T("BarometerSensorDataManager",{log:!1});class vt{constructor(){gt.add(this)}parseData(e,i){const s=e.getUint32(0,!0)*i,n=t(this,gt,"m",ut).call(this,s);return pt.log({pressure:s,altitude:n}),{pressure:s}}}gt=new WeakSet,ut=function(e){const t=.0065;return 288.15/t*(1-Math.pow(e/101325,.19026643566373183))};const wt=T("ParseUtils",{log:!1});function yt(e,t=0){const i=e.getUint8(t++);return{string:V.decode(e.buffer.slice(e.byteOffset+t,e.byteOffset+t+i)),byteOffset:t+=i}}function bt(e,t,i,s,n=!1){let a=0;for(;a<e.byteLength;){const r=e.getUint8(a++);wt.assertWithError(r in t,`invalid messageTypeEnum ${r}`);const o=t[r];let c;n?(c=e.getUint16(a,!0),a+=2):c=e.getUint8(a++),wt.log({messageTypeEnum:r,messageType:o,messageLength:c,dataView:e,byteOffset:a});const h=G(e,a,c);wt.log({_dataView:h}),i(o,h,s),a+=c}}var St,Ct,Mt,Et,kt,Dt,Wt,Tt,It,_t,Lt,Ut,Rt,Ft,At,xt,$t,Ot,Bt,Nt,Pt,Vt,qt,zt,jt,Gt,Ht,Jt,Kt;const Qt=T("CameraManager",{log:!1}),Zt=["focus","takePicture","stop","sleep","wake"],Xt=["idle","focusing","takingPicture","asleep"],Yt=["headerSize","header","imageSize","image","footerSize","footer"],ei=["resolution","qualityFactor","shutter","gain","redGain","greenGain","blueGain"],ti=["cameraStatus","cameraCommand","getCameraConfiguration","setCameraConfiguration","cameraData"],ii=["getCameraConfiguration","cameraStatus"],si=[...ti,"cameraImageProgress","cameraImage"];class ni{constructor(){St.add(this),Et.set(this,void 0),Ut.set(this,0),Rt.set(this,void 0),Ft.set(this,0),At.set(this,0),xt.set(this,void 0),$t.set(this,0),Ot.set(this,0),Bt.set(this,void 0),Nt.set(this,0),Pt.set(this,!1),qt.set(this,{}),zt.set(this,void 0),jt.set(this,{resolution:{min:100,max:720},qualityFactor:{min:15,max:60},shutter:{min:4,max:16383},gain:{min:1,max:248},redGain:{min:0,max:1023},greenGain:{min:0,max:1023},blueGain:{min:0,max:1023}}),J(this)}get waitForEvent(){return this.eventDispatcher.waitForEvent}requestRequiredInformation(){Qt.log("requesting required camera information");const e=ii.map((e=>({type:e})));this.sendMessage(e,!1)}get cameraStatus(){return t(this,Et,"f")}async focus(){t(this,St,"m",It).call(this),await t(this,St,"m",Wt).call(this,"focus")}async takePicture(){t(this,St,"m",It).call(this),await t(this,St,"m",Wt).call(this,"takePicture")}async stop(){t(this,St,"m",It).call(this),await t(this,St,"m",Wt).call(this,"stop")}async sleep(){t(this,St,"m",It).call(this),await t(this,St,"m",Wt).call(this,"sleep")}async wake(){t(this,St,"m",Tt).call(this),await t(this,St,"m",Wt).call(this,"wake")}get cameraConfiguration(){return t(this,qt,"f")}get availableCameraConfigurationTypes(){return t(this,zt,"f")}get cameraConfigurationRanges(){return t(this,jt,"f")}async setCameraConfiguration(e){if(Qt.log({newCameraConfiguration:e}),t(this,St,"m",Ht).call(this,e))return void Qt.log("redundant camera configuration");const i=t(this,St,"m",Kt).call(this,e);Qt.log({setCameraConfigurationData:i});const s=this.waitForEvent("getCameraConfiguration");this.sendMessage([{type:"setCameraConfiguration",data:i.buffer}]),await s}static AssertValidCameraConfigurationType(e){Qt.assertEnumWithError(e,ei)}static AssertValidCameraConfigurationTypeEnum(e){Qt.assertTypeWithError(e,"number"),Qt.assertWithError(e in ei,`invalid cameraConfigurationTypeEnum ${e}`)}parseMessage(e,i){switch(Qt.log({messageType:e,dataView:i}),e){case"cameraStatus":t(this,St,"m",kt).call(this,i);break;case"getCameraConfiguration":case"setCameraConfiguration":t(this,St,"m",Gt).call(this,i);break;case"cameraData":t(this,St,"m",_t).call(this,i);break;default:throw Error(`uncaught messageType ${e}`)}}clear(){i(this,Et,void 0,"f"),i(this,Ft,0,"f"),i(this,$t,0,"f"),i(this,Nt,0,"f")}}function ai(e,t,i){const s=function(e,t,i){const s=new ArrayBuffer(44+2*e.length),n=new DataView(s);ri(n,0,"RIFF"),n.setUint32(4,36+2*e.length,!0),ri(n,8,"WAVE"),ri(n,12,"fmt "),n.setUint32(16,16,!0),n.setUint16(20,1,!0),n.setUint16(22,i,!0),n.setUint32(24,t,!0),n.setUint32(28,t*i*2,!0),n.setUint16(32,2*i,!0),n.setUint16(34,16,!0),ri(n,36,"data"),n.setUint32(40,2*e.length,!0);for(let t=0;t<e.length;t++)n.setInt16(44+2*t,32767*e[t],!0);return s}(e,t,i);return new Blob([s],{type:"audio/wav"})}function ri(e,t,i){for(let s=0;s<i.length;s++)e.setUint8(t+s,i.charCodeAt(s))}var oi,ci,hi,li,fi,gi,ui,di,mi,pi,vi,wi,yi,bi,Si,Ci,Mi,Ei,ki,Di,Wi,Ti,Ii,_i;Ct=ni,Et=new WeakMap,Ut=new WeakMap,Rt=new WeakMap,Ft=new WeakMap,At=new WeakMap,xt=new WeakMap,$t=new WeakMap,Ot=new WeakMap,Bt=new WeakMap,Nt=new WeakMap,Pt=new WeakMap,qt=new WeakMap,zt=new WeakMap,jt=new WeakMap,St=new WeakSet,Mt=function(){return this.eventDispatcher.dispatchEvent},kt=function(e){const i=e.getUint8(0),s=Xt[i];t(this,St,"m",Dt).call(this,s)},Dt=function(e){if(Qt.assertEnumWithError(e,Xt),e==t(this,Et,"f"))return void Qt.log(`redundant cameraStatus ${e}`);const s=t(this,Et,"f");i(this,Et,e,"f"),Qt.log(`updated cameraStatus to "${this.cameraStatus}"`),t(this,St,"a",Mt).call(this,"cameraStatus",{cameraStatus:this.cameraStatus,previousCameraStatus:s}),"takingPicture"!=t(this,Et,"f")&&t(this,$t,"f")>0&&!t(this,Pt,"f")&&t(this,St,"m",Vt).call(this)},Wt=async function(e,t){Qt.assertEnumWithError(e,Zt),Qt.log(`sending camera command "${e}"`);const i=this.waitForEvent("cameraStatus");Qt.log(`setting command "${e}"`);const s=Zt.indexOf(e);this.sendMessage([{type:"cameraCommand",data:Uint8Array.from([s]).buffer}],t),await i},Tt=function(){Qt.assertWithError("asleep"==t(this,Et,"f"),`camera is not asleep - currently ${t(this,Et,"f")}`)},It=function(){Qt.assertWithError("asleep"!=t(this,Et,"f"),`camera is not awake - currently ${t(this,Et,"f")}`)},_t=function(e){Qt.log("parsing camera data",e),bt(e,Yt,t(this,St,"m",Lt).bind(this),null,!0)},Lt=function(e,s){switch(Qt.log({cameraDataType:e,dataView:s}),e){case"headerSize":i(this,Ut,s.getUint16(0,!0),"f"),Qt.log({headerSize:t(this,Ut,"f")}),i(this,Rt,void 0,"f"),t(this,Ft,"f");break;case"header":i(this,Rt,z(t(this,Rt,"f"),s),"f"),Qt.log({headerData:t(this,Rt,"f")}),i(this,Ft,t(this,Rt,"f")?.byteLength/t(this,Ut,"f"),"f"),Qt.log({headerProgress:t(this,Ft,"f")}),t(this,St,"a",Mt).call(this,"cameraImageProgress",{progress:t(this,Ft,"f"),type:"header"}),1==t(this,Ft,"f")&&Qt.log("finished getting header data");break;case"imageSize":i(this,At,s.getUint16(0,!0),"f"),Qt.log({imageSize:t(this,At,"f")}),i(this,xt,void 0,"f"),t(this,$t,"f"),i(this,Pt,!1,"f");break;case"image":i(this,xt,z(t(this,xt,"f"),s),"f"),Qt.log({imageData:t(this,xt,"f")}),i(this,$t,t(this,xt,"f")?.byteLength/t(this,At,"f"),"f"),Qt.log({imageProgress:t(this,$t,"f")}),t(this,St,"a",Mt).call(this,"cameraImageProgress",{progress:t(this,$t,"f"),type:"image"}),1==t(this,$t,"f")&&(Qt.log("finished getting image data"),1==t(this,Ft,"f")&&t(this,St,"m",Vt).call(this));break;case"footerSize":i(this,Ot,s.getUint16(0,!0),"f"),Qt.log({footerSize:t(this,Ot,"f")}),i(this,Bt,void 0,"f"),t(this,Nt,"f");break;case"footer":i(this,Bt,z(t(this,Bt,"f"),s),"f"),Qt.log({footerData:t(this,Bt,"f")}),i(this,Nt,t(this,Bt,"f")?.byteLength/t(this,Ot,"f"),"f"),Qt.log({footerProgress:t(this,Nt,"f")}),t(this,St,"a",Mt).call(this,"cameraImageProgress",{progress:t(this,Nt,"f"),type:"footer"}),1==t(this,Nt,"f")&&(Qt.log("finished getting footer data"),1==t(this,$t,"f")&&t(this,St,"m",Vt).call(this))}},Vt=function(){Qt.log("building image...");const e=z(t(this,Rt,"f"),t(this,xt,"f"),t(this,Bt,"f"));Qt.log({imageData:e});let s=new Blob([e],{type:"image/jpeg"});Qt.log("created blob",s);const n=URL.createObjectURL(s);Qt.log("created url",n),t(this,St,"a",Mt).call(this,"cameraImage",{url:n,blob:s}),i(this,Pt,!0,"f")},Gt=function(e){const s={};let n=0;for(;n<e.byteLength;){const t=e.getUint8(n++),i=ei[t];Qt.assertWithError(i,`invalid cameraConfigurationTypeIndex ${t}`),s[i]=e.getUint16(n,!0),n+=2}Qt.log({parsedCameraConfiguration:s}),i(this,zt,Object.keys(s),"f"),i(this,qt,s,"f"),t(this,St,"a",Mt).call(this,"getCameraConfiguration",{cameraConfiguration:t(this,qt,"f")})},Ht=function(e){return Object.keys(e).every((t=>this.cameraConfiguration[t]==e[t]))},Jt=function(e){Qt.assertWithError(t(this,zt,"f"),"must get initial cameraConfiguration");const i=t(this,zt,"f")?.includes(e);return Qt.assertWithError(i,`unavailable camera configuration type "${e}"`),i},Kt=function(e){let i=Object.keys(e);i=i.filter((e=>t(this,St,"m",Jt).call(this,e)));const s=new DataView(new ArrayBuffer(3*i.length));return i.forEach(((t,i)=>{Ct.AssertValidCameraConfigurationType(t);const n=ei.indexOf(t);s.setUint8(3*i,n);const a=e[t];s.setUint16(3*i+1,a,!0)})),Qt.log({sensorConfigurationData:s}),s},T("AudioUtils",{log:!0});const Li=T("MicrophoneManager",{log:!1}),Ui=["start","stop","vad"],Ri=["idle","streaming","vad"],Fi=["sampleRate","bitDepth"],Ai=["8","16"],xi=["microphoneStatus","microphoneCommand","getMicrophoneConfiguration","setMicrophoneConfiguration","microphoneData"],$i={sampleRate:["8000","16000"],bitDepth:Ai},Oi=["getMicrophoneConfiguration","microphoneStatus"],Bi=[...xi,"isRecordingMicrophone","microphoneRecording"];class Ni{constructor(){oi.add(this),li.set(this,void 0),pi.set(this,.001),vi.set(this,0),bi.set(this,{}),Si.set(this,void 0),Di.set(this,void 0),Wi.set(this,void 0),Ti.set(this,void 0),Ii.set(this,!1),_i.set(this,void 0),J(this)}get waitForEvent(){return this.eventDispatcher.waitForEvent}requestRequiredInformation(){Li.log("requesting required microphone information");const e=Oi.map((e=>({type:e})));this.sendMessage(e,!1)}get microphoneStatus(){return t(this,li,"f")}async start(){await t(this,oi,"m",ui).call(this,"start")}async stop(){t(this,oi,"m",di).call(this),await t(this,oi,"m",ui).call(this,"stop")}async vad(){await t(this,oi,"m",ui).call(this,"vad")}async toggle(){switch(this.microphoneStatus){case"idle":this.start();break;case"streaming":this.stop()}}get microphoneConfiguration(){return t(this,bi,"f")}get availableMicrophoneConfigurationTypes(){return t(this,Si,"f")}get bitDepth(){return t(this,bi,"f").bitDepth}get sampleRate(){return t(this,bi,"f").sampleRate}async setMicrophoneConfiguration(e){if(Li.log({newMicrophoneConfiguration:e}),t(this,oi,"m",Mi).call(this,e))return void Li.log("redundant microphone configuration");const i=t(this,oi,"m",ki).call(this,e);Li.log({setMicrophoneConfigurationData:i});const s=this.waitForEvent("getMicrophoneConfiguration");this.sendMessage([{type:"setMicrophoneConfiguration",data:i.buffer}]),await s}static AssertValidMicrophoneConfigurationType(e){Li.assertEnumWithError(e,Fi)}static AssertValidMicrophoneConfigurationTypeEnum(e){Li.assertTypeWithError(e,"number"),Li.assertWithError(e in Fi,`invalid microphoneConfigurationTypeEnum ${e}`)}parseMessage(e,i){switch(Li.log({messageType:e,dataView:i}),e){case"microphoneStatus":t(this,oi,"m",fi).call(this,i);break;case"getMicrophoneConfiguration":case"setMicrophoneConfiguration":t(this,oi,"m",Ci).call(this,i);break;case"microphoneData":t(this,oi,"m",wi).call(this,i);break;default:throw Error(`uncaught messageType ${e}`)}}get audioContext(){return t(this,Di,"f")}set audioContext(e){t(this,Di,"f")!=e?(i(this,Di,e,"f"),Li.log("assigned new audioContext",t(this,Di,"f")),t(this,Di,"f")?i(this,vi,t(this,Di,"f").currentTime,"f"):(t(this,Ti,"f")&&(t(this,Ti,"f").disconnect(),i(this,Ti,void 0,"f")),t(this,Wi,"f")&&(t(this,Wi,"f").disconnect(),i(this,Wi,void 0,"f")))):Li.log("redundant audioContext assignment",t(this,Di,"f"))}get gainNode(){return Li.assertWithError(t(this,Di,"f"),"audioContext assignment required for gainNode"),t(this,Wi,"f")||(Li.log("creating gainNode..."),i(this,Wi,t(this,Di,"f").createGain(),"f"),Li.log("created gainNode",t(this,Wi,"f"))),t(this,Wi,"f")}get mediaStreamDestination(){return Li.assertWithError(t(this,Di,"f"),"audioContext assignment required for mediaStreamDestination"),t(this,Ti,"f")||(Li.log("creating mediaStreamDestination..."),i(this,Ti,t(this,Di,"f").createMediaStreamDestination(),"f"),this.gainNode?.connect(t(this,Ti,"f")),Li.log("created mediaStreamDestination",t(this,Ti,"f"))),t(this,Ti,"f")}get isRecording(){return t(this,Ii,"f")}startRecording(){this.isRecording?Li.log("already recording"):(i(this,_i,[],"f"),i(this,Ii,!0,"f"),t(this,oi,"a",hi).call(this,"isRecordingMicrophone",{isRecordingMicrophone:this.isRecording}))}stopRecording(){if(this.isRecording){if(i(this,Ii,!1,"f"),t(this,_i,"f")&&t(this,_i,"f").length>0){Li.log("parsing microphone data...",t(this,_i,"f").length);const e=z(...t(this,_i,"f")),i=new Float32Array(e),s=ai(i,Number(this.sampleRate),1),n=URL.createObjectURL(s);t(this,oi,"a",hi).call(this,"microphoneRecording",{samples:i,sampleRate:this.sampleRate,bitDepth:this.bitDepth,blob:s,url:n})}i(this,_i,void 0,"f"),t(this,oi,"a",hi).call(this,"isRecordingMicrophone",{isRecordingMicrophone:this.isRecording})}else Li.log("already not recording")}toggleRecording(){t(this,Ii,"f")?this.stopRecording():this.startRecording()}clear(){i(this,li,void 0,"f"),i(this,bi,{},"f"),this.isRecording&&this.stopRecording()}}var Pi;ci=Ni,li=new WeakMap,pi=new WeakMap,vi=new WeakMap,bi=new WeakMap,Si=new WeakMap,Di=new WeakMap,Wi=new WeakMap,Ti=new WeakMap,Ii=new WeakMap,_i=new WeakMap,oi=new WeakSet,hi=function(){return this.eventDispatcher.dispatchEvent},fi=function(e){const i=e.getUint8(0),s=Ri[i];t(this,oi,"m",gi).call(this,s)},gi=function(e){if(Li.assertEnumWithError(e,Ri),e==t(this,li,"f"))return void Li.log(`redundant microphoneStatus ${e}`);const s=t(this,li,"f");i(this,li,e,"f"),Li.log(`updated microphoneStatus to "${this.microphoneStatus}"`),t(this,oi,"a",hi).call(this,"microphoneStatus",{microphoneStatus:this.microphoneStatus,previousMicrophoneStatus:s})},ui=async function(e,t){Li.assertEnumWithError(e,Ui),Li.log(`sending microphone command "${e}"`);const i=this.waitForEvent("microphoneStatus");Li.log(`setting command "${e}"`);const s=Ui.indexOf(e);this.sendMessage([{type:"microphoneCommand",data:Uint8Array.from([s]).buffer}],t),await i},di=function(){Li.assertWithError("idle"!=t(this,li,"f"),"microphone is idle")},mi=function(){Li.assertEnumWithError(this.bitDepth,Ai)},wi=function(e){t(this,oi,"m",mi).call(this),Li.log("parsing microphone data",e);const s=e.byteLength/t(this,oi,"a",yi),n=new Float32Array(s);for(let t=0;t<s;t++){let i;switch(this.bitDepth){case"16":i=e.getInt16(2*t,!0),n[t]=i/32768;break;case"8":i=e.getInt8(t),n[t]=i/128}}if(Li.log("samples",n),t(this,Ii,"f")&&t(this,_i,"f")&&t(this,_i,"f").push(n),t(this,Di,"f")&&t(this,Wi,"f")){const e=t(this,Di,"f").createBuffer(1,n.length,Number(this.sampleRate));e.getChannelData(0).set(n);const s=t(this,Di,"f").createBufferSource();s.buffer=e;const a=e.getChannelData(0),r=Number(this.sampleRate);for(let e=0;e<t(this,pi,"f")*r;e++)a[e]*=e/(t(this,pi,"f")*r);for(let e=a.length-1;e>=a.length-t(this,pi,"f")*r;e--)a[e]*=(a.length-e)/(t(this,pi,"f")*r);s.connect(t(this,Wi,"f")),t(this,vi,"f")<t(this,Di,"f").currentTime&&i(this,vi,t(this,Di,"f").currentTime,"f"),s.start(t(this,vi,"f")),i(this,vi,t(this,vi,"f")+e.duration,"f")}t(this,oi,"a",hi).call(this,"microphoneData",{samples:n,sampleRate:this.sampleRate,bitDepth:this.bitDepth})},yi=function(){switch(this.bitDepth){case"8":return 1;case"16":return 2}},Ci=function(e){const s={};let n=0;for(;n<e.byteLength;){const t=e.getUint8(n++),i=Fi[t];Li.assertWithError(i,`invalid microphoneConfigurationTypeIndex ${t}`);let a=e.getUint8(n++);const r=$i[i],o=r[a];Li.assertEnumWithError(o,r),Li.log({microphoneConfigurationType:i,value:o}),s[i]=o}Li.log({parsedMicrophoneConfiguration:s}),i(this,Si,Object.keys(s),"f"),i(this,bi,s,"f"),t(this,oi,"a",hi).call(this,"getMicrophoneConfiguration",{microphoneConfiguration:t(this,bi,"f")})},Mi=function(e){return Object.keys(e).every((t=>this.microphoneConfiguration[t]==e[t]))},Ei=function(e){Li.assertWithError(t(this,Si,"f"),"must get initial microphoneConfiguration");const i=t(this,Si,"f")?.includes(e);return Li.assertWithError(i,`unavailable microphone configuration type "${e}"`),i},ki=function(e){let i=Object.keys(e);i=i.filter((e=>t(this,oi,"m",Ei).call(this,e)));const s=new DataView(new ArrayBuffer(2*i.length));return i.forEach(((t,i)=>{ci.AssertValidMicrophoneConfigurationType(t);const n=Fi.indexOf(t);s.setUint8(2*i,n);let a=e[t];"number"==typeof a&&(a=a.toString());const r=$i[t];Li.assertEnumWithError(a,r);const o=r.indexOf(a);s.setUint8(2*i+1,o)})),Li.log({sensorConfigurationData:s}),s};const Vi=T("SensorDataManager",{log:!1}),qi=[...at,"acceleration","gravity","linearAcceleration","gyroscope","magnetometer","gameRotation","rotation","orientation","activity","stepCounter","stepDetector","deviceOrientation","tapDetector",...dt,"camera","microphone"],zi=[...rt,"acceleration","gravity","linearAcceleration","gyroscope","magnetometer","gameRotation","rotation","orientation",...mt],ji=["getPressurePositions","getSensorScalars","sensorData"],Gi=["getPressurePositions"],Hi=[...ji,...qi];class Ji{constructor(){this.pressureSensorDataManager=new ot,this.motionSensorDataManager=new ft,this.barometerSensorDataManager=new vt,Pi.set(this,new Map)}static AssertValidSensorType(e){Vi.assertEnumWithError(e,qi)}static AssertValidSensorTypeEnum(e){Vi.assertTypeWithError(e,"number"),Vi.assertWithError(e in qi,`invalid sensorTypeEnum ${e}`)}get dispatchEvent(){return this.eventDispatcher.dispatchEvent}parseMessage(e,t){switch(Vi.log({messageType:e}),e){case"getSensorScalars":this.parseScalars(t);break;case"getPressurePositions":this.pressureSensorDataManager.parsePositions(t);break;case"sensorData":this.parseData(t);break;default:throw Error(`uncaught messageType ${e}`)}}parseScalars(e){for(let i=0;i<e.byteLength;i+=5){const s=e.getUint8(i),n=qi[s];if(!n){Vi.warn(`unknown sensorType index ${s}`);continue}const a=e.getFloat32(i+1,!0);Vi.log({sensorType:n,sensorScalar:a}),t(this,Pi,"f").set(n,a)}}parseData(e){Vi.log("sensorData",Array.from(new Uint8Array(e.buffer)));let t=0;const i=Ge(e,t);t+=2;bt(new DataView(e.buffer,t),qi,this.parseDataCallback.bind(this),{timestamp:i})}parseDataCallback(e,i,{timestamp:s}){const n=t(this,Pi,"f").get(e)||1;let a=null;switch(e){case"pressure":a=this.pressureSensorDataManager.parseData(i,n);break;case"acceleration":case"gravity":case"linearAcceleration":case"gyroscope":case"magnetometer":a=this.motionSensorDataManager.parseVector3(i,n);break;case"gameRotation":case"rotation":a=this.motionSensorDataManager.parseQuaternion(i,n);break;case"orientation":a=this.motionSensorDataManager.parseEuler(i,n);break;case"stepCounter":a=this.motionSensorDataManager.parseStepCounter(i);break;case"stepDetector":case"tapDetector":a={};break;case"activity":a=this.motionSensorDataManager.parseActivity(i);break;case"deviceOrientation":a=this.motionSensorDataManager.parseDeviceOrientation(i);break;case"barometer":a=this.barometerSensorDataManager.parseData(i,n);break;case"camera":case"microphone":return;default:Vi.error(`uncaught sensorType "${e}"`)}Vi.assertWithError(null!=a,`no sensorData defined for sensorType "${e}"`),Vi.log({sensorType:e,sensorData:a}),this.dispatchEvent(e,{sensorType:e,[e]:a,timestamp:s}),this.dispatchEvent("sensorData",{sensorType:e,[e]:a,timestamp:s})}}var Ki,Qi,Zi,Xi,Yi,es,ts,is,ss,ns,as,rs,os;Pi=new WeakMap;const cs=T("SensorConfigurationManager",{log:!1}),hs=["getSensorConfiguration","setSensorConfiguration"],ls=hs;class fs{constructor(){Ki.add(this),Xi.set(this,void 0),es.set(this,{}),J(this)}get addEventListener(){return this.eventDispatcher.addEventListener}get waitForEvent(){return this.eventDispatcher.waitForEvent}get configuration(){return t(this,es,"f")}async setConfiguration(e,i){if(i&&(e=Object.assign({...this.zeroSensorConfiguration},e)),cs.log({newSensorConfiguration:e}),t(this,Ki,"m",is).call(this,e))return void cs.log("redundant sensor configuration");const s=t(this,Ki,"m",rs).call(this,e);cs.log({setSensorConfigurationData:s});const n=this.waitForEvent("getSensorConfiguration");this.sendMessage([{type:"setSensorConfiguration",data:s.buffer}]),await n}static get ZeroSensorConfiguration(){return t(this,Qi,"f",os)}get zeroSensorConfiguration(){const e={};return t(this,Xi,"f").forEach((t=>{e[t]=0})),e}async clearSensorConfiguration(){return this.setConfiguration(this.zeroSensorConfiguration)}parseMessage(e,i){switch(cs.log({messageType:e}),e){case"getSensorConfiguration":case"setSensorConfiguration":const s=t(this,Ki,"m",ss).call(this,i);t(this,Ki,"m",ts).call(this,s);break;default:throw Error(`uncaught messageType ${e}`)}}}var gs,us,ds,ms,ps,vs,ws,ys,bs,Ss,Cs,Ms,Es,ks,Ds,Ws,Ts,Is,_s,Ls,Us,Rs,Fs,As,xs,$s,Os,Bs,Ns,Ps,Vs;Qi=fs,Xi=new WeakMap,es=new WeakMap,Ki=new WeakSet,Zi=function(){return this.eventDispatcher.dispatchEvent},Yi=function(e){cs.assertWithError(t(this,Xi,"f"),"must get initial sensorConfiguration");const i=t(this,Xi,"f")?.includes(e);return cs.log(i,`unavailable sensor type "${e}"`),i},ts=function(e){i(this,es,e,"f"),cs.log({updatedConfiguration:t(this,es,"f")}),t(this,Ki,"a",Zi).call(this,"getSensorConfiguration",{sensorConfiguration:this.configuration})},is=function(e){return Object.keys(e).every((t=>this.configuration[t]==e[t]))},ss=function(e){const t={};for(let i=0;i<e.byteLength;i+=3){const s=e.getUint8(i),n=qi[s],a=e.getUint16(i+1,!0);cs.log({sensorType:n,sensorRate:a}),n?t[n]=a:cs.warn(`unknown sensorType index ${s}`)}return cs.log({parsedSensorConfiguration:t}),i(this,Xi,Object.keys(t),"f"),t},ns=function(e){cs.assertTypeWithError(e,"number"),cs.assertWithError(e>=0,`sensorRate must be 0 or greater (got ${e})`),cs.assertWithError(e<65535,`sensorRate must be 0 or greater (got ${e})`),cs.assertWithError(e%5==0,"sensorRate must be multiple of 5")},as=function(e){t(Qi,Qi,"m",ns).call(Qi,e)},rs=function(e){let i=Object.keys(e);i=i.filter((e=>t(this,Ki,"m",Yi).call(this,e)));const s=new DataView(new ArrayBuffer(3*i.length));return i.forEach(((i,n)=>{Ji.AssertValidSensorType(i);const a=qi.indexOf(i);s.setUint8(3*n,a);const r=e[i];t(this,Ki,"m",as).call(this,r),s.setUint16(3*n+1,r,!0)})),cs.log({sensorConfigurationData:s}),s},os={value:{}},qi.forEach((e=>{t(Qi,Qi,"f",os)[e]=0}));const qs=T("TfliteManager",{log:!1}),zs=["getTfliteName","setTfliteName","getTfliteTask","setTfliteTask","getTfliteSampleRate","setTfliteSampleRate","getTfliteSensorTypes","setTfliteSensorTypes","tfliteIsReady","getTfliteCaptureDelay","setTfliteCaptureDelay","getTfliteThreshold","setTfliteThreshold","getTfliteInferencingEnabled","setTfliteInferencingEnabled","tfliteInference"],js=zs,Gs=["getTfliteName","getTfliteTask","getTfliteSampleRate","getTfliteSensorTypes","tfliteIsReady","getTfliteCaptureDelay","getTfliteThreshold","getTfliteInferencingEnabled"],Hs=["classification","regression"],Js=["pressure","linearAcceleration","gyroscope","magnetometer"];class Ks{constructor(){gs.add(this),ps.set(this,void 0),ys.set(this,void 0),Cs.set(this,void 0),ks.set(this,[]),Ts.set(this,void 0),Us.set(this,void 0),As.set(this,void 0),Os.set(this,void 0),Vs.set(this,void 0),J(this)}get addEventListenter(){return this.eventDispatcher.addEventListener}get removeEventListener(){return this.eventDispatcher.removeEventListener}get waitForEvent(){return this.eventDispatcher.waitForEvent}get name(){return t(this,ps,"f")}async setName(e,t){if(qs.assertTypeWithError(e,"string"),this.name==e)return void qs.log(`redundant name assignment ${e}`);const i=this.waitForEvent("getTfliteName"),s=P.encode(e);this.sendMessage([{type:"setTfliteName",data:s.buffer}],t),await i}get task(){return t(this,ys,"f")}async setTask(e,i){if(t(this,gs,"m",us).call(this,e),this.task==e)return void qs.log(`redundant task assignment ${e}`);const s=this.waitForEvent("getTfliteTask"),n=Hs.indexOf(e);this.sendMessage([{type:"setTfliteTask",data:Uint8Array.from([n]).buffer}],i),await s}get sampleRate(){return t(this,Cs,"f")}async setSampleRate(e,i){if(qs.assertTypeWithError(e,"number"),e-=e%5,qs.assertWithError(e>=5,`sampleRate must be multiple of 5 greater than 0 (got ${e})`),t(this,Cs,"f")==e)return void qs.log(`redundant sampleRate assignment ${e}`);const s=this.waitForEvent("getTfliteSampleRate"),n=new DataView(new ArrayBuffer(2));n.setUint16(0,e,!0),this.sendMessage([{type:"setTfliteSampleRate",data:n.buffer}],i),await s}static AssertValidSensorType(e){Ji.AssertValidSensorType(e);const t=e;qs.assertWithError(Js.includes(t),`invalid tflite sensorType "${e}"`)}get sensorTypes(){return t(this,ks,"f").slice()}async setSensorTypes(e,t){e.forEach((e=>{Ks.AssertValidSensorType(e)}));const i=this.waitForEvent("getTfliteSensorTypes");var s;const n=(e=(s=e).filter(((e,t)=>s.indexOf(e)==t))).map((e=>qi.indexOf(e))).sort();qs.log(e,n),this.sendMessage([{type:"setTfliteSensorTypes",data:Uint8Array.from(n).buffer}],t),await i}get isReady(){return t(this,Ts,"f")}get captureDelay(){return t(this,Us,"f")}async setCaptureDelay(e,i){if(qs.assertTypeWithError(e,"number"),t(this,Us,"f")==e)return void qs.log(`redundant captureDelay assignment ${e}`);const s=this.waitForEvent("getTfliteCaptureDelay"),n=new DataView(new ArrayBuffer(2));n.setUint16(0,e,!0),this.sendMessage([{type:"setTfliteCaptureDelay",data:n.buffer}],i),await s}get threshold(){return t(this,As,"f")}async setThreshold(e,i){if(qs.assertTypeWithError(e,"number"),qs.assertWithError(e>=0,`threshold must be positive (got ${e})`),t(this,As,"f")==e)return void qs.log(`redundant threshold assignment ${e}`);const s=this.waitForEvent("getTfliteThreshold"),n=new DataView(new ArrayBuffer(4));n.setFloat32(0,e,!0),this.sendMessage([{type:"setTfliteThreshold",data:n.buffer}],i),await s}get inferencingEnabled(){return t(this,Os,"f")}async setInferencingEnabled(e,i=!0){if(qs.assertTypeWithError(e,"boolean"),!e&&!this.isReady)return;if(t(this,gs,"m",Ls).call(this),t(this,Os,"f")==e)return void qs.log(`redundant inferencingEnabled assignment ${e}`);const s=this.waitForEvent("getTfliteInferencingEnabled");this.sendMessage([{type:"setTfliteInferencingEnabled",data:Uint8Array.from([Number(e)]).buffer}],i),await s}async toggleInferencingEnabled(){return this.setInferencingEnabled(!this.inferencingEnabled)}async enableInferencing(){this.inferencingEnabled||this.setInferencingEnabled(!0)}async disableInferencing(){this.inferencingEnabled&&this.setInferencingEnabled(!1)}parseMessage(e,i){switch(qs.log({messageType:e}),e){case"getTfliteName":case"setTfliteName":t(this,gs,"m",vs).call(this,i);break;case"getTfliteTask":case"setTfliteTask":t(this,gs,"m",bs).call(this,i);break;case"getTfliteSampleRate":case"setTfliteSampleRate":t(this,gs,"m",Ms).call(this,i);break;case"getTfliteSensorTypes":case"setTfliteSensorTypes":t(this,gs,"m",Ds).call(this,i);break;case"tfliteIsReady":t(this,gs,"m",Is).call(this,i);break;case"getTfliteCaptureDelay":case"setTfliteCaptureDelay":t(this,gs,"m",Rs).call(this,i);break;case"getTfliteThreshold":case"setTfliteThreshold":t(this,gs,"m",xs).call(this,i);break;case"getTfliteInferencingEnabled":case"setTfliteInferencingEnabled":t(this,gs,"m",Bs).call(this,i);break;case"tfliteInference":t(this,gs,"m",Ps).call(this,i);break;default:throw Error(`uncaught messageType ${e}`)}}get configuration(){return t(this,Vs,"f")}sendConfiguration(e,s){if(e==t(this,Vs,"f"))return void qs.log("redundant tflite configuration assignment");if(i(this,Vs,e,"f"),qs.log("assigned new tflite configuration",this.configuration),!this.configuration)return;const{name:n,task:a,captureDelay:r,sampleRate:o,threshold:c,sensorTypes:h}=this.configuration;this.setName(n,!1),this.setTask(a,!1),null!=r&&this.setCaptureDelay(r,!1),this.setSampleRate(o,!1),null!=c&&this.setThreshold(c,!1),this.setSensorTypes(h,s)}clear(){i(this,Vs,void 0,"f"),i(this,Os,!1,"f"),i(this,ks,[],"f"),i(this,Cs,0,"f"),i(this,Ts,!1,"f")}requestRequiredInformation(){qs.log("requesting required tflite information");const e=Gs.map((e=>({type:e})));this.sendMessage(e,!1)}}var Qs,Zs,Xs,Ys,en;ps=new WeakMap,ys=new WeakMap,Cs=new WeakMap,ks=new WeakMap,Ts=new WeakMap,Us=new WeakMap,As=new WeakMap,Os=new WeakMap,Vs=new WeakMap,gs=new WeakSet,us=function(e){qs.assertEnumWithError(e,Hs)},ds=function(e){qs.assertWithError(e in Hs,`invalid taskEnum ${e}`)},ms=function(){return this.eventDispatcher.dispatchEvent},vs=function(e){qs.log("parseName",e);const i=V.decode(e.buffer);t(this,gs,"m",ws).call(this,i)},ws=function(e){qs.log({name:e}),i(this,ps,e,"f"),t(this,gs,"a",ms).call(this,"getTfliteName",{tfliteName:e})},bs=function(e){qs.log("parseTask",e);const i=e.getUint8(0);t(this,gs,"m",ds).call(this,i);const s=Hs[i];t(this,gs,"m",Ss).call(this,s)},Ss=function(e){qs.log({task:e}),i(this,ys,e,"f"),t(this,gs,"a",ms).call(this,"getTfliteTask",{tfliteTask:e})},Ms=function(e){qs.log("parseSampleRate",e);const i=e.getUint16(0,!0);t(this,gs,"m",Es).call(this,i)},Es=function(e){qs.log({sampleRate:e}),i(this,Cs,e,"f"),t(this,gs,"a",ms).call(this,"getTfliteSampleRate",{tfliteSampleRate:e})},Ds=function(e){qs.log("parseSensorTypes",e);const i=[];for(let t=0;t<e.byteLength;t++){const s=e.getUint8(t),n=qi[s];n?Js.includes(n)?i.push(n):qs.error(`invalid tfliteSensorType ${n}`):qs.error(`invalid sensorTypeEnum ${s}`)}t(this,gs,"m",Ws).call(this,i)},Ws=function(e){qs.log({sensorTypes:e}),i(this,ks,e,"f"),t(this,gs,"a",ms).call(this,"getTfliteSensorTypes",{tfliteSensorTypes:e})},Is=function(e){qs.log("parseIsReady",e);const i=Boolean(e.getUint8(0));t(this,gs,"m",_s).call(this,i)},_s=function(e){qs.log({isReady:e}),i(this,Ts,e,"f"),t(this,gs,"a",ms).call(this,"tfliteIsReady",{tfliteIsReady:e})},Ls=function(){qs.assertWithError(this.isReady,"tflite is not ready")},Rs=function(e){qs.log("parseCaptureDelay",e);const i=e.getUint16(0,!0);t(this,gs,"m",Fs).call(this,i)},Fs=function(e){qs.log({captureDelay:e}),i(this,Us,e,"f"),t(this,gs,"a",ms).call(this,"getTfliteCaptureDelay",{tfliteCaptureDelay:e})},xs=function(e){qs.log("parseThreshold",e);const i=e.getFloat32(0,!0);t(this,gs,"m",$s).call(this,i)},$s=function(e){qs.log({threshold:e}),i(this,As,e,"f"),t(this,gs,"a",ms).call(this,"getTfliteThreshold",{tfliteThreshold:e})},Bs=function(e){qs.log("parseInferencingEnabled",e);const i=Boolean(e.getUint8(0));t(this,gs,"m",Ns).call(this,i)},Ns=function(e){qs.log({inferencingEnabled:e}),i(this,Os,e,"f"),t(this,gs,"a",ms).call(this,"getTfliteInferencingEnabled",{tfliteInferencingEnabled:e})},Ps=function(e){qs.log("parseInference",e);const i=Ge(e,0);qs.log({timestamp:i});const s=[];for(let t=0,i=2;i<e.byteLength;t++,i+=4){const t=e.getFloat32(i,!0);s.push(t)}qs.log("values",s);const n={timestamp:i,values:s};if("classification"==this.task){let e=0,i=0;if(s.forEach(((t,s)=>{t>e&&(e=t,i=s)})),qs.log({maxIndex:i,maxValue:e}),n.maxIndex=i,n.maxValue=e,t(this,Vs,"f")?.classes){const{classes:e}=t(this,Vs,"f");n.maxClass=e[i],n.classValues={},s.forEach(((t,i)=>{const s=e[i];n.classValues[s]=t}))}}t(this,gs,"a",ms).call(this,"tfliteInference",{tfliteInference:n})};const tn=T("DeviceInformationManager",{log:!1}),sn=["manufacturerName","modelNumber","hardwareRevision","firmwareRevision","softwareRevision","pnpId","serialNumber"],nn=[...sn,"deviceInformation"];class an{constructor(){Qs.add(this),Xs.set(this,{})}get information(){return t(this,Xs,"f")}clear(){i(this,Xs,{},"f")}parseMessage(e,i){switch(tn.log({messageType:e}),e){case"manufacturerName":const s=V.decode(i.buffer);tn.log({manufacturerName:s}),t(this,Qs,"m",en).call(this,{manufacturerName:s});break;case"modelNumber":const n=V.decode(i.buffer);tn.log({modelNumber:n}),t(this,Qs,"m",en).call(this,{modelNumber:n});break;case"softwareRevision":const a=V.decode(i.buffer);tn.log({softwareRevision:a}),t(this,Qs,"m",en).call(this,{softwareRevision:a});break;case"hardwareRevision":const r=V.decode(i.buffer);tn.log({hardwareRevision:r}),t(this,Qs,"m",en).call(this,{hardwareRevision:r});break;case"firmwareRevision":const o=V.decode(i.buffer);tn.log({firmwareRevision:o}),t(this,Qs,"m",en).call(this,{firmwareRevision:o});break;case"pnpId":const c={source:1===i.getUint8(0)?"Bluetooth":"USB",productId:i.getUint16(3,!0),productVersion:i.getUint16(5,!0),vendorId:0};"Bluetooth"==c.source&&(c.vendorId=i.getUint16(1,!0)),tn.log({pnpId:c}),t(this,Qs,"m",en).call(this,{pnpId:c});break;case"serialNumber":const h=V.decode(i.buffer);tn.log({serialNumber:h});break;default:throw Error(`uncaught messageType ${e}`)}}}var rn,on,cn,hn,ln,fn,gn,un,dn,mn,pn,vn,wn,yn,bn,Sn,Cn,Mn;Xs=new WeakMap,Qs=new WeakSet,Zs=function(){return this.eventDispatcher.dispatchEvent},Ys=function(){return sn.filter((e=>"serialNumber"!=e)).every((e=>e in t(this,Xs,"f")))},en=function(e){tn.log({partialDeviceInformation:e});Object.keys(e).forEach((i=>{t(this,Qs,"a",Zs).call(this,i,{[i]:e[i]})})),Object.assign(t(this,Xs,"f"),e),tn.log({deviceInformation:t(this,Xs,"f")}),t(this,Qs,"a",Ys)&&(tn.log("completed deviceInformation"),t(this,Qs,"a",Zs).call(this,"deviceInformation",{deviceInformation:this.information}))};const En=T("InformationManager",{log:!1}),kn=["leftInsole","rightInsole","leftGlove","rightGlove","glasses","generic"],Dn=["left","right"],Wn=["isCharging","getBatteryCurrent","getMtu","getId","getName","setName","getType","setType","getCurrentTime","setCurrentTime"],Tn=Wn;class In{constructor(){rn.add(this),cn.set(this,!1),ln.set(this,void 0),gn.set(this,void 0),dn.set(this,""),mn.set(this,void 0),yn.set(this,0),Sn.set(this,!1),J(this)}get waitForEvent(){return this.eventDispatcher.waitForEvent}get isCharging(){return t(this,cn,"f")}get batteryCurrent(){return t(this,ln,"f")}async getBatteryCurrent(){En.log("getting battery current...");const e=this.waitForEvent("getBatteryCurrent");this.sendMessage([{type:"getBatteryCurrent"}]),await e}get id(){return t(this,gn,"f")}get name(){return t(this,dn,"f")}updateName(e){En.assertTypeWithError(e,"string"),i(this,dn,e,"f"),En.log({updatedName:t(this,dn,"f")}),t(this,rn,"a",on).call(this,"getName",{name:t(this,dn,"f")})}async setName(e){En.assertTypeWithError(e,"string"),En.assertRangeWithError("newName",e.length,2,30);const t=P.encode(e);En.log({setNameData:t});const i=this.waitForEvent("getName");this.sendMessage([{type:"setName",data:t.buffer}]),await i}get type(){return t(this,mn,"f")}get typeEnum(){return kn.indexOf(this.type)}updateType(e){t(this,rn,"m",pn).call(this,e),e!=this.type?(i(this,mn,e,"f"),En.log({updatedType:t(this,mn,"f")}),t(this,rn,"a",on).call(this,"getType",{type:t(this,mn,"f")})):En.log("redundant type assignment")}async setType(e){t(this,rn,"m",pn).call(this,e);const i=kn.indexOf(e);t(this,rn,"m",wn).call(this,i)}get isInsole(){switch(this.type){case"leftInsole":case"rightInsole":return!0;default:return!1}}get isGlove(){switch(this.type){case"leftGlove":case"rightGlove":return!0;default:return!1}}get side(){switch(this.type){case"leftInsole":case"leftGlove":default:return"left";case"rightInsole":case"rightGlove":return"right"}}get mtu(){return t(this,yn,"f")}get isCurrentTimeSet(){return t(this,Sn,"f")}parseMessage(e,i){switch(En.log({messageType:e}),e){case"isCharging":const s=Boolean(i.getUint8(0));En.log({isCharging:s}),t(this,rn,"m",hn).call(this,s);break;case"getBatteryCurrent":const n=i.getFloat32(0,!0);En.log({batteryCurrent:n}),t(this,rn,"m",fn).call(this,n);break;case"getId":const a=V.decode(i.buffer);En.log({id:a}),t(this,rn,"m",un).call(this,a);break;case"getName":case"setName":const r=V.decode(i.buffer);En.log({name:r}),this.updateName(r);break;case"getType":case"setType":const o=i.getUint8(0),c=kn[o];En.log({typeEnum:o,type:c}),this.updateType(c);break;case"getMtu":let h=i.getUint16(0,!0);"webSocket"!=this.connectionType&&"udp"!=this.connectionType&&(h=Math.min(h,512)),En.log({mtu:h}),t(this,rn,"m",bn).call(this,h);break;case"getCurrentTime":case"setCurrentTime":const l=Number(i.getBigUint64(0,!0));t(this,rn,"m",Cn).call(this,l);break;default:throw Error(`uncaught messageType ${e}`)}}clear(){i(this,Sn,!1,"f")}}cn=new WeakMap,ln=new WeakMap,gn=new WeakMap,dn=new WeakMap,mn=new WeakMap,yn=new WeakMap,Sn=new WeakMap,rn=new WeakSet,on=function(){return this.eventDispatcher.dispatchEvent},hn=function(e){En.assertTypeWithError(e,"boolean"),i(this,cn,e,"f"),En.log({isCharging:t(this,cn,"f")}),t(this,rn,"a",on).call(this,"isCharging",{isCharging:t(this,cn,"f")})},fn=function(e){En.assertTypeWithError(e,"number"),i(this,ln,e,"f"),En.log({batteryCurrent:t(this,ln,"f")}),t(this,rn,"a",on).call(this,"getBatteryCurrent",{batteryCurrent:t(this,ln,"f")})},un=function(e){En.assertTypeWithError(e,"string"),i(this,gn,e,"f"),En.log({id:t(this,gn,"f")}),t(this,rn,"a",on).call(this,"getId",{id:t(this,gn,"f")})},pn=function(e){En.assertEnumWithError(e,kn)},vn=function(e){En.assertTypeWithError(e,"number"),En.assertWithError(e in kn,`invalid typeEnum ${e}`)},wn=async function(e){t(this,rn,"m",vn).call(this,e);const i=Uint8Array.from([e]);En.log({setTypeData:i});const s=this.waitForEvent("getType");this.sendMessage([{type:"setType",data:i.buffer}]),await s},bn=function(e){En.assertTypeWithError(e,"number"),t(this,yn,"f")!=e?(i(this,yn,e,"f"),t(this,rn,"a",on).call(this,"getMtu",{mtu:t(this,yn,"f")})):En.log("redundant mtu assignment",e)},Cn=function(e){En.log({currentTime:e}),i(this,Sn,0!=e||Math.abs(Date.now()-e)<je,"f"),t(this,Sn,"f")||t(this,rn,"m",Mn).call(this,!1)},Mn=async function(e){En.log("setting current time...");const t=new DataView(new ArrayBuffer(8));t.setBigUint64(0,BigInt(Date.now()),!0);const i=this.waitForEvent("getCurrentTime");this.sendMessage([{type:"setCurrentTime",data:t.buffer}],e),await i};const _n=["none","strongClick100","strongClick60","strongClick30","sharpClick100","sharpClick60","sharpClick30","softBump100","softBump60","softBump30","doubleClick100","doubleClick60","tripleClick100","softFuzz60","strongBuzz100","alert750ms","alert1000ms","strongClick1_100","strongClick2_80","strongClick3_60","strongClick4_30","mediumClick100","mediumClick80","mediumClick60","sharpTick100","sharpTick80","sharpTick60","shortDoubleClickStrong100","shortDoubleClickStrong80","shortDoubleClickStrong60","shortDoubleClickStrong30","shortDoubleClickMedium100","shortDoubleClickMedium80","shortDoubleClickMedium60","shortDoubleSharpTick100","shortDoubleSharpTick80","shortDoubleSharpTick60","longDoubleSharpClickStrong100","longDoubleSharpClickStrong80","longDoubleSharpClickStrong60","longDoubleSharpClickStrong30","longDoubleSharpClickMedium100","longDoubleSharpClickMedium80","longDoubleSharpClickMedium60","longDoubleSharpTick100","longDoubleSharpTick80","longDoubleSharpTick60","buzz100","buzz80","buzz60","buzz40","buzz20","pulsingStrong100","pulsingStrong60","pulsingMedium100","pulsingMedium60","pulsingSharp100","pulsingSharp60","transitionClick100","transitionClick80","transitionClick60","transitionClick40","transitionClick20","transitionClick10","transitionHum100","transitionHum80","transitionHum60","transitionHum40","transitionHum20","transitionHum10","transitionRampDownLongSmooth2_100","transitionRampDownLongSmooth1_100","transitionRampDownMediumSmooth1_100","transitionRampDownMediumSmooth2_100","transitionRampDownShortSmooth1_100","transitionRampDownShortSmooth2_100","transitionRampDownLongSharp1_100","transitionRampDownLongSharp2_100","transitionRampDownMediumSharp1_100","transitionRampDownMediumSharp2_100","transitionRampDownShortSharp1_100","transitionRampDownShortSharp2_100","transitionRampUpLongSmooth1_100","transitionRampUpLongSmooth2_100","transitionRampUpMediumSmooth1_100","transitionRampUpMediumSmooth2_100","transitionRampUpShortSmooth1_100","transitionRampUpShortSmooth2_100","transitionRampUpLongSharp1_100","transitionRampUpLongSharp2_100","transitionRampUpMediumSharp1_100","transitionRampUpMediumSharp2_100","transitionRampUpShortSharp1_100","transitionRampUpShortSharp2_100","transitionRampDownLongSmooth1_50","transitionRampDownLongSmooth2_50","transitionRampDownMediumSmooth1_50","transitionRampDownMediumSmooth2_50","transitionRampDownShortSmooth1_50","transitionRampDownShortSmooth2_50","transitionRampDownLongSharp1_50","transitionRampDownLongSharp2_50","transitionRampDownMediumSharp1_50","transitionRampDownMediumSharp2_50","transitionRampDownShortSharp1_50","transitionRampDownShortSharp2_50","transitionRampUpLongSmooth1_50","transitionRampUpLongSmooth2_50","transitionRampUpMediumSmooth1_50","transitionRampUpMediumSmooth2_50","transitionRampUpShortSmooth1_50","transitionRampUpShortSmooth2_50","transitionRampUpLongSharp1_50","transitionRampUpLongSharp2_50","transitionRampUpMediumSharp1_50","transitionRampUpMediumSharp2_50","transitionRampUpShortSharp1_50","transitionRampUpShortSharp2_50","longBuzz100","smoothHum50","smoothHum40","smoothHum30","smoothHum20","smoothHum10"];var Ln,Un,Rn,Fn,An,xn,$n,On,Bn,Nn,Pn,Vn,qn,zn,jn,Gn,Hn,Jn,Kn;const Qn=T("VibrationManager",{log:!1}),Zn=["front","rear"],Xn=["waveformEffect","waveform"],Yn=["getVibrationLocations","triggerVibration"],ea=Yn,ta=2550,ia=1270;class sa{constructor(){Ln.add(this),Jn.set(this,[]),J(this)}get waitForEvent(){return this.eventDispatcher.waitForEvent}async triggerVibration(e,i=!0){let s;e.forEach((e=>{const{type:i}=e;let n,{locations:a}=e;switch(a=a||this.vibrationLocations.slice(),a=a.filter((e=>this.vibrationLocations.includes(e))),i){case"waveformEffect":{const{segments:i,loopCount:s}=e;n=t(this,Ln,"m",zn).call(this,a,i,s)}break;case"waveform":{const{segments:i}=e;n=t(this,Ln,"m",jn).call(this,a,i)}break;default:throw Error(`invalid vibration type "${i}"`)}Qn.log({type:i,arrayBuffer:n}),s=z(s,n)})),await this.sendMessage([{type:"triggerVibration",data:s}],i)}get vibrationLocations(){return t(this,Jn,"f")}parseMessage(e,i){if(Qn.log({messageType:e}),"getVibrationLocations"!==e)throw Error(`uncaught messageType ${e}`);{const e=Array.from(new Uint8Array(i.buffer)).map((e=>Zn[e])).filter(Boolean);t(this,Ln,"m",Kn).call(this,e)}}}var na,aa,ra,oa,ca,ha,la,fa,ga,ua,da,ma,pa,va,wa,ya,ba;Jn=new WeakMap,Ln=new WeakSet,Un=function(){return this.eventDispatcher.dispatchEvent},Rn=function(e){Qn.assertTypeWithError(e,"string"),Qn.assertWithError(Zn.includes(e),`invalid location "${e}"`)},Fn=function(e){t(this,Ln,"m",xn).call(this,e),e.forEach((e=>{t(this,Ln,"m",Rn).call(this,e)}))},An=function(e){t(this,Ln,"m",Fn).call(this,e);let i=0;return e.forEach((e=>{const t=Zn.indexOf(e);i|=1<<t})),Qn.log({locationsBitmask:i}),Qn.assertWithError(i>0,"locationsBitmask must not be zero"),i},xn=function(e){Qn.assertWithError(Array.isArray(e),"passed non-array"),Qn.assertWithError(e.length>0,"passed empty array")},$n=function(e){Qn.assertWithError(_n.includes(e),`invalid waveformEffect "${e}"`)},On=function(e){if(null!=e.effect){const i=e.effect;t(this,Ln,"m",$n).call(this,i)}else{if(null==e.delay)throw Error("no effect or delay found in waveformEffectSegment");{const{delay:t}=e;Qn.assertWithError(t>=0,`delay must be 0ms or greater (got ${t})`),Qn.assertWithError(t<=ia,`delay must be 1270ms or less (got ${t})`)}}if(null!=e.loopCount){const{loopCount:i}=e;t(this,Ln,"m",Bn).call(this,i)}},Bn=function(e){Qn.assertTypeWithError(e,"number"),Qn.assertWithError(e>=0,`waveformEffectSegmentLoopCount must be 0 or greater (got ${e})`),Qn.assertWithError(e<=3,`waveformEffectSegmentLoopCount must be 3 or fewer (got ${e})`)},Nn=function(e){t(this,Ln,"m",xn).call(this,e),Qn.assertWithError(e.length<=8,`must have 8 waveformEffectSegments or fewer (got ${e.length})`),e.forEach((e=>{t(this,Ln,"m",On).call(this,e)}))},Pn=function(e){Qn.assertTypeWithError(e,"number"),Qn.assertWithError(e>=0,`waveformEffectSequenceLoopCount must be 0 or greater (got ${e})`),Qn.assertWithError(e<=6,`waveformEffectSequenceLoopCount must be 6 or fewer (got ${e})`)},Vn=function(e){Qn.assertTypeWithError(e.amplitude,"number"),Qn.assertWithError(e.amplitude>=0,`amplitude must be 0 or greater (got ${e.amplitude})`),Qn.assertWithError(e.amplitude<=1,`amplitude must be 1 or less (got ${e.amplitude})`),Qn.assertTypeWithError(e.duration,"number"),Qn.assertWithError(e.duration>0,`duration must be greater than 0ms (got ${e.duration}ms)`),Qn.assertWithError(e.duration<=ta,`duration must be 2550ms or less (got ${e.duration}ms)`)},qn=function(e){t(this,Ln,"m",xn).call(this,e),Qn.assertWithError(e.length<=20,`must have 20 waveformSegments or fewer (got ${e.length})`),e.forEach((e=>{t(this,Ln,"m",Vn).call(this,e)}))},zn=function(e,i,s=0){t(this,Ln,"m",Nn).call(this,i),t(this,Ln,"m",Pn).call(this,s);let n=[],a=0;const r=i.some((e=>{const{loopCount:t}=e;return null!=t&&t>0}))||0!=s;for(let e=0;e<i.length||r&&e<8;e++){const t=i[e]||{effect:"none"};if(null!=t.effect){const e=t.effect;n[a++]=_n.indexOf(e)}else{if(null==t.delay)throw Error("invalid waveformEffectSegment");{const{delay:e}=t;n[a++]=128|Math.floor(e/10)}}}const o=0!=s;for(let e=0;e<i.length||o&&e<8;e++){const t=i[e]?.loopCount||0;0!=e&&4!=e||(n[a]=0);const s=e%4*2;n[a]|=t<<s,3!=e&&7!=e||a++}0!=s&&(n[a++]=s);const c=new DataView(Uint8Array.from(n).buffer);return Qn.log({dataArray:n,dataView:c}),t(this,Ln,"m",Hn).call(this,e,"waveformEffect",c)},jn=function(e,i){t(this,Ln,"m",qn).call(this,i);const s=new DataView(new ArrayBuffer(2*i.length));return i.forEach(((e,t)=>{s.setUint8(2*t,Math.floor(127*e.amplitude)),s.setUint8(2*t+1,Math.floor(e.duration/10))})),Qn.log({dataView:s}),t(this,Ln,"m",Hn).call(this,e,"waveform",s)},Gn=function(e){Qn.assertTypeWithError(e,"string"),Qn.assertWithError(Xn.includes(e),`invalid vibrationType "${e}"`)},Hn=function(e,i,s){Qn.assertWithError(s?.byteLength>0,"no data received");const n=t(this,Ln,"m",An).call(this,e);t(this,Ln,"m",Gn).call(this,i);const a=Xn.indexOf(i);Qn.log({locationsBitmask:n,vibrationTypeIndex:a,dataView:s});const r=z(n,a,s.byteLength,s);return Qn.log({data:r}),r},Kn=function(e){i(this,Jn,e,"f"),Qn.log("vibrationLocations",e),t(this,Ln,"a",Un).call(this,"getVibrationLocations",{vibrationLocations:t(this,Jn,"f")})};const Sa=T("WifiManager",{log:!1}),Ca=["isWifiAvailable","getWifiSSID","setWifiSSID","getWifiPassword","setWifiPassword","getWifiConnectionEnabled","setWifiConnectionEnabled","isWifiConnected","ipAddress","isWifiSecure"],Ma=["getWifiSSID","getWifiPassword","getWifiConnectionEnabled","isWifiConnected","ipAddress","isWifiSecure"],Ea=Ca;class ka{constructor(){na.add(this),ra.set(this,!1),ha.set(this,""),fa.set(this,""),ua.set(this,void 0),ma.set(this,!1),va.set(this,void 0),ya.set(this,!1),J(this)}get waitForEvent(){return this.eventDispatcher.waitForEvent}requestRequiredInformation(){Sa.log("requesting required wifi information");const e=Ma.map((e=>({type:e})));this.sendMessage(e,!1)}get isWifiAvailable(){return t(this,ra,"f")}get wifiSSID(){return t(this,ha,"f")}async setWifiSSID(e){if(t(this,na,"m",ca).call(this),t(this,ua,"f"))return void Sa.error("cannot change ssid while wifi connection is enabled");Sa.assertTypeWithError(e,"string"),Sa.assertRangeWithError("wifiSSID",e.length,1,32);const i=P.encode(e);Sa.log({setWifiSSIDData:i});const s=this.waitForEvent("getWifiSSID");this.sendMessage([{type:"setWifiSSID",data:i.buffer}]),await s}get wifiPassword(){return t(this,fa,"f")}async setWifiPassword(e){if(t(this,na,"m",ca).call(this),t(this,ua,"f"))return void Sa.error("cannot change password while wifi connection is enabled");Sa.assertTypeWithError(e,"string"),e.length>0&&Sa.assertRangeWithError("wifiPassword",e.length,8,64);const i=P.encode(e);Sa.log({setWifiPasswordData:i});const s=this.waitForEvent("getWifiPassword");this.sendMessage([{type:"setWifiPassword",data:i.buffer}]),await s}get wifiConnectionEnabled(){return t(this,ua,"f")}async setWifiConnectionEnabled(e,i=!0){if(t(this,na,"m",ca).call(this),Sa.assertTypeWithError(e,"boolean"),t(this,ua,"f")==e)return void Sa.log(`redundant wifiConnectionEnabled assignment ${e}`);const s=this.waitForEvent("getWifiConnectionEnabled");this.sendMessage([{type:"setWifiConnectionEnabled",data:Uint8Array.from([Number(e)]).buffer}],i),await s}async toggleWifiConnection(){return this.setWifiConnectionEnabled(!this.wifiConnectionEnabled)}async enableWifiConnection(){return this.setWifiConnectionEnabled(!0)}async disableWifiConnection(){return this.setWifiConnectionEnabled(!1)}get isWifiConnected(){return t(this,ma,"f")}get ipAddress(){return t(this,va,"f")}get isWifiSecure(){return t(this,ya,"f")}parseMessage(e,i){switch(Sa.log({messageType:e}),e){case"isWifiAvailable":const s=Boolean(i.getUint8(0));Sa.log({isWifiAvailable:s}),t(this,na,"m",oa).call(this,s);break;case"getWifiSSID":case"setWifiSSID":const n=V.decode(i.buffer);Sa.log({ssid:n}),t(this,na,"m",la).call(this,n);break;case"getWifiPassword":case"setWifiPassword":const a=V.decode(i.buffer);Sa.log({password:a}),t(this,na,"m",ga).call(this,a);break;case"getWifiConnectionEnabled":case"setWifiConnectionEnabled":const r=Boolean(i.getUint8(0));Sa.log({enableWifiConnection:r}),t(this,na,"m",da).call(this,r);break;case"isWifiConnected":const o=Boolean(i.getUint8(0));Sa.log({isWifiConnected:o}),t(this,na,"m",pa).call(this,o);break;case"ipAddress":let c;4==i.byteLength&&(c=new Uint8Array(i.buffer.slice(0,4)).join(".")),Sa.log({ipAddress:c}),t(this,na,"m",wa).call(this,c);break;case"isWifiSecure":const h=Boolean(i.getUint8(0));Sa.log({isWifiSecure:h}),t(this,na,"m",ba).call(this,h);break;default:throw Error(`uncaught messageType ${e}`)}}clear(){i(this,ha,"","f"),i(this,fa,"","f"),i(this,va,"","f"),i(this,ma,!1,"f"),i(this,ra,!1,"f")}}var Da,Wa,Ta,Ia,_a,La,Ua,Ra,Fa,Aa,xa,$a;ra=new WeakMap,ha=new WeakMap,fa=new WeakMap,ua=new WeakMap,ma=new WeakMap,va=new WeakMap,ya=new WeakMap,na=new WeakSet,aa=function(){return this.eventDispatcher.dispatchEvent},oa=function(e){Sa.assertTypeWithError(e,"boolean"),i(this,ra,e,"f"),Sa.log({isWifiAvailable:t(this,ra,"f")}),t(this,na,"a",aa).call(this,"isWifiAvailable",{isWifiAvailable:t(this,ra,"f")})},ca=function(){Sa.assertWithError(t(this,ra,"f"),"wifi is not available")},la=function(e){Sa.assertTypeWithError(e,"string"),i(this,ha,e,"f"),Sa.log({wifiSSID:t(this,ha,"f")}),t(this,na,"a",aa).call(this,"getWifiSSID",{wifiSSID:t(this,ha,"f")})},ga=function(e){Sa.assertTypeWithError(e,"string"),i(this,fa,e,"f"),Sa.log({wifiPassword:t(this,fa,"f")}),t(this,na,"a",aa).call(this,"getWifiPassword",{wifiPassword:t(this,fa,"f")})},da=function(e){Sa.log({wifiConnectionEnabled:e}),i(this,ua,e,"f"),t(this,na,"a",aa).call(this,"getWifiConnectionEnabled",{wifiConnectionEnabled:e})},pa=function(e){Sa.assertTypeWithError(e,"boolean"),i(this,ma,e,"f"),Sa.log({isWifiConnected:t(this,ma,"f")}),t(this,na,"a",aa).call(this,"isWifiConnected",{isWifiConnected:t(this,ma,"f")})},wa=function(e){i(this,va,e,"f"),Sa.log({ipAddress:t(this,va,"f")}),t(this,na,"a",aa).call(this,"ipAddress",{ipAddress:t(this,va,"f")})},ba=function(e){Sa.assertTypeWithError(e,"boolean"),i(this,ya,e,"f"),Sa.log({isWifiSecure:t(this,ya,"f")}),t(this,na,"a",aa).call(this,"isWifiSecure",{isWifiSecure:t(this,ya,"f")})};const Oa=T("BaseConnectionManager",{log:!1}),Ba=["webBluetooth","noble","client","webSocket","udp"],Na=["notConnected","connecting","connected","disconnecting"],Pa=[...Na,"connectionStatus","isConnected"],Va=[...Wn,...hs,...ji,...Yn,...$e,...zs,...Ca,...ti,...xi],qa=["batteryLevel"],za=["rx","tx"],ja=[...qa,...sn,...za,...Va,"smp"];class Ga{get baseConstructor(){return this.constructor}static get isSupported(){return!1}get isSupported(){return this.baseConstructor.isSupported}get canUpdateFirmware(){return!1}get type(){return this.baseConstructor.type}constructor(){Da.add(this),_a.set(this,"notConnected"),Ra.set(this,[]),Fa.set(this,!1),this.defaultMtu=23,this.mtu=this.defaultMtu,xa.set(this,new A(t(this,Da,"m",$a).bind(this),5e3)),t(this,Da,"m",Ia).call(this)}get status(){return t(this,_a,"f")}set status(e){Oa.assertEnumWithError(e,Na),t(this,_a,"f")!=e?(Oa.log(`new connection status "${e}"`),i(this,_a,e,"f"),this.onStatusUpdated(this.status),this.isConnected?t(this,xa,"f").start():t(this,xa,"f").stop(),"notConnected"==t(this,_a,"f")&&(this.mtu=this.defaultMtu)):Oa.log(`tried to assign same connection status "${e}"`)}get isConnected(){return"connected"==this.status}get isAvailable(){return!1}assertIsNotConnected(){Oa.assertWithError(!this.isConnected,"device is already connected")}assertIsConnected(){Oa.assertWithError(this.isConnected,"device is not connected")}assertIsConnectedAndNotDisconnecting(){this.assertIsConnected(),t(this,Da,"m",Ua).call(this)}async connect(){this.assertIsNotConnected(),t(this,Da,"m",La).call(this),this.status="connecting"}get canReconnect(){return!1}async reconnect(){this.assertIsNotConnected(),t(this,Da,"m",La).call(this),Oa.assertWithError(this.canReconnect,"unable to reconnect"),this.status="connecting",Oa.log("attempting to reconnect...")}async disconnect(){this.assertIsConnected(),t(this,Da,"m",Ua).call(this),this.status="disconnecting",Oa.log("disconnecting from device...")}async sendSmpMessage(e){this.assertIsConnectedAndNotDisconnecting(),Oa.log("sending smp message",e)}async sendTxMessages(e,s=!0){if(this.assertIsConnectedAndNotDisconnecting(),e&&(t(this,Ra,"f").push(...e),Oa.log(`appended ${e.length} messages`)),!s)return void Oa.log("not sending immediately - waiting until later");if(t(this,Fa,"f"))return void Oa.log("already sending messages - waiting until later");if(0==t(this,Ra,"f").length)return void Oa.log("no pendingMessages");i(this,Fa,!0,"f"),Oa.log("sendTxMessages",t(this,Ra,"f").slice());const n=t(this,Ra,"f").map((e=>{t(Wa,Wa,"m",Ta).call(Wa,e.type);const i=Va.indexOf(e.type),s=new DataView(new ArrayBuffer(2));return s.setUint16(0,e.data?.byteLength||0,!0),z(i,s,e.data)}));if(t(this,Ra,"f").length=0,this.mtu)for(;n.length>0;){if(n.every((e=>e.byteLength>this.mtu-3))){Oa.log("every arrayBuffer is too big to send");break}Oa.log("remaining arrayBuffers.length",n.length);let e=0,t=0;n.some((i=>{if(e+i.byteLength>this.mtu-3)return Oa.log(`stopping appending arrayBuffers ( length ${i.byteLength} too much)`),!0;Oa.log(`allowing arrayBuffer with length ${i.byteLength}`),t++,e+=i.byteLength}));const i=n.splice(0,t);Oa.log({arrayBufferCount:t,arrayBuffersToSend:i});const s=z(...i);Oa.log("sending arrayBuffer (partitioned)",s),await this.sendTxData(s)}else{const e=z(...n);Oa.log("sending arrayBuffer (all)",e),await this.sendTxData(e)}i(this,Fa,!1,"f"),this.sendTxMessages(void 0,!0)}async sendTxData(e){Oa.log("sendTxData",e)}parseRxMessage(e){bt(e,Va,t(this,Da,"m",Aa).bind(this),null,!0),this.onMessagesReceived()}clear(){i(this,Fa,!1,"f"),t(this,Ra,"f").length=0}remove(){this.clear(),this.onStatusUpdated=void 0,this.onMessageReceived=void 0,this.onMessagesReceived=void 0}}Wa=Ga,_a=new WeakMap,Ra=new WeakMap,Fa=new WeakMap,xa=new WeakMap,Da=new WeakSet,Ta=function(e){Oa.assertEnumWithError(e,Va)},Ia=function(){Oa.assertWithError(this.isSupported,`${this.constructor.name} is not supported`)},La=function(){Oa.assertWithError("connecting"!=this.status,"device is already connecting")},Ua=function(){Oa.assertWithError("disconnecting"!=this.status,"device is already disconnecting")},Aa=function(e,t){Oa.log({messageType:e,dataView:t}),this.onMessageReceived(e,t)},$a=function(){this.isConnected||(Oa.log("timer detected disconnection"),this.status="notConnected")};const Ha=T("EventUtils",{log:!1});function Ja(e,t){let i=e.addEventListener||e.addListener||e.on||e.AddEventListener;Ha.assertWithError(i,"no add listener function found for target"),i=i.bind(e),Object.entries(t).forEach((([e,t])=>{i(e,t)}))}function Ka(e,t){let i=e.removeEventListener||e.removeListener||e.RemoveEventListener;Ha.assertWithError(i,"no remove listener function found for target"),i=i.bind(e),Object.entries(t).forEach((([e,t])=>{i(e,t)}))}const Qa=T("bluetoothUUIDs",{log:!1});if(n)var Za=window.BluetoothUUID;function Xa(e){return Qa.assertTypeWithError(e,"string"),Qa.assertWithError(4==e.length,"value must be 4 characters long"),`ea6d${e}-a725-4f9b-893d-c3913e33b39f`}function Ya(e){return Za?.getCharacteristic?.(e)}function er(e){return Za?.getService?.(e)}const tr=Object.freeze({services:{deviceInformation:{uuid:er("device_information"),characteristics:{manufacturerName:{uuid:Ya("manufacturer_name_string")},modelNumber:{uuid:Ya("model_number_string")},hardwareRevision:{uuid:Ya("hardware_revision_string")},firmwareRevision:{uuid:Ya("firmware_revision_string")},softwareRevision:{uuid:Ya("software_revision_string")},pnpId:{uuid:Ya("pnp_id")},serialNumber:{uuid:Ya("serial_number_string")}}},battery:{uuid:er("battery_service"),characteristics:{batteryLevel:{uuid:Ya("battery_level")}}},main:{uuid:Xa("0000"),characteristics:{rx:{uuid:Xa("1000")},tx:{uuid:Xa("1001")}}},smp:{uuid:"8d53dc1d-1db7-4cd3-868b-8a527460aa84",characteristics:{smp:{uuid:"da2e7828-fbce-4e01-ae9e-261174997c48"}}}}}),ir=[tr.services.main.uuid],sr=[tr.services.deviceInformation.uuid,tr.services.battery.uuid,tr.services.smp.uuid];function nr(e){e=e.toString().toLowerCase();return Object.keys(tr.services).find((t=>{let i=tr.services[t].uuid.toString();return 4==e.length&&(i=i.slice(4,8)),e.includes("-")||(i=i.replaceAll("-","")),e==i}))}const ar=[],rr=[];function or(e){var t;return e=e.toString().toLowerCase(),Object.values(tr.services).some((i=>{const s=Object.keys(i.characteristics);return t=s.find((t=>{let s=i.characteristics[t].uuid.toString();return 4==e.length&&(s=s.slice(4,8)),e.includes("-")||(s=s.replaceAll("-","")),e==s}))})),t}function cr(e){const t={broadcast:!1,read:!0,writeWithoutResponse:!1,write:!1,notify:!1,indicate:!1,authenticatedSignedWrites:!1,reliableWrite:!1,writableAuxiliaries:!1};switch(e){case"rx":case"tx":case"smp":t.read=!1}switch(e){case"batteryLevel":case"rx":case"smp":t.notify=!0}if("smp"===e)t.writeWithoutResponse=!0;if("tx"===e)t.write=!0;return t}Object.values(tr.services).forEach((e=>{if(!e.characteristics)return;const t=Object.keys(e.characteristics);t.forEach((i=>{const s=e.characteristics[i];ir.includes(e.uuid)&&(ar.push(s.uuid),t.push(i)),rr.push(s.uuid)}))}),[]);const hr=T("BluetoothConnectionManager",{log:!1});class lr extends Ga{constructor(){super(...arguments),this.isInRange=!0}get isAvailable(){return!0}onCharacteristicValueChanged(e,t){"rx"==e?this.parseRxMessage(t):this.onMessageReceived?.(e,t)}async writeCharacteristic(e,t){hr.log("writeCharacteristic",...arguments)}async sendSmpMessage(e){super.sendSmpMessage(e),await this.writeCharacteristic("smp",e)}async sendTxData(e){super.sendTxData(e),0!=e.byteLength&&await this.writeCharacteristic("tx",e)}}var fr,gr,ur,dr,mr,pr,vr,wr,yr,br,Sr;const Cr=T("WebBluetoothConnectionManager",{log:!1});var Mr;n&&(Mr=window.navigator.bluetooth);class Er extends lr{constructor(){super(...arguments),fr.add(this),gr.set(this,{characteristicvaluechanged:t(this,fr,"m",yr).bind(this)}),ur.set(this,{gattserverdisconnected:t(this,fr,"m",Sr).bind(this)}),dr.set(this,void 0),mr.set(this,new Map),pr.set(this,new Map)}get bluetoothId(){return this.device.id}get canUpdateFirmware(){return t(this,pr,"f").has("smp")}static get isSupported(){return Boolean(Mr)}static get type(){return"webBluetooth"}get device(){return t(this,dr,"f")}set device(e){t(this,dr,"f")!=e?(t(this,dr,"f")&&Ka(t(this,dr,"f"),t(this,ur,"f")),e&&Ja(e,t(this,ur,"f")),i(this,dr,e,"f")):Cr.log("tried to assign the same BluetoothDevice")}get server(){return t(this,dr,"f")?.gatt}get isConnected(){return this.server?.connected||!1}async connect(){await super.connect();try{const e=await Mr.requestDevice({filters:[{services:ir}],optionalServices:n?sr:[]});Cr.log("got BluetoothDevice"),this.device=e,Cr.log("connecting to device...");const i=await this.server.connect();Cr.log(`connected to device? ${i.connected}`),await t(this,fr,"m",vr).call(this),Cr.log("fully connected"),this.status="connected"}catch(e){Cr.error(e),this.status="notConnected",this.server?.disconnect(),t(this,fr,"m",wr).call(this)}}async disconnect(){await t(this,fr,"m",wr).call(this),await super.disconnect(),this.server?.disconnect(),this.status="notConnected"}async writeCharacteristic(e,i){super.writeCharacteristic(e,i);const s=t(this,pr,"f").get(e);Cr.assertWithError(s,`${e} characteristic not found`),Cr.log("writing characteristic",s,i);const n=s.properties||cr(e);n.writeWithoutResponse?(Cr.log("writing without response"),await s.writeValueWithoutResponse(i)):(Cr.log("writing with response"),await s.writeValueWithResponse(i)),Cr.log("wrote characteristic"),n.read&&!n.notify&&(Cr.log("reading value after write..."),await s.readValue(),(c||h)&&t(this,fr,"m",br).call(this,s))}get canReconnect(){return Boolean(this.server&&!this.server.connected&&this.isInRange)}async reconnect(){await super.reconnect();try{await this.server.connect()}catch(e){Cr.error(e),this.isInRange=!1}this.isConnected?(Cr.log("successfully reconnected!"),await t(this,fr,"m",vr).call(this),this.status="connected"):(Cr.log("unable to reconnect"),this.status="notConnected")}remove(){super.remove(),this.device=void 0}}gr=new WeakMap,ur=new WeakMap,dr=new WeakMap,mr=new WeakMap,pr=new WeakMap,fr=new WeakSet,vr=async function(){t(this,fr,"m",wr).call(this),Cr.log("getting services...");const e=await this.server.getPrimaryServices();Cr.log("got services",e.length),Cr.log("getting characteristics...");for(const i in e){const s=e[i];Cr.log({service:s});const n=nr(s.uuid);Cr.assertWithError(n,`no name found for service uuid "${s.uuid}"`),Cr.log(`got "${n}" service`),s.name=n,t(this,mr,"f").set(n,s),Cr.log(`getting characteristics for "${n}" service`);const a=await s.getCharacteristics();Cr.log(`got characteristics for "${n}" service`);for(const e in a){const i=a[e];Cr.log({characteristic:i});const s=or(i.uuid);Cr.assertWithError(Boolean(s),`no name found for characteristic uuid "${i.uuid}" in "${n}" service`),Cr.log(`got "${s}" characteristic in "${n}" service`),i.name=s,t(this,pr,"f").set(s,i),Ja(i,t(this,gr,"f"));const r=i.properties||cr(s);r.notify&&(Cr.log(`starting notifications for "${s}" characteristic`),await i.startNotifications()),r.read&&(Cr.log(`reading "${s}" characteristic...`),await i.readValue(),(c||h)&&t(this,fr,"m",br).call(this,i))}}},wr=async function(){this.device&&Ka(this.device,t(this,ur,"f"));const e=Array.from(t(this,pr,"f").keys()).map((e=>{const i=t(this,pr,"f").get(e);Ka(i,t(this,gr,"f"));if((i.properties||cr(e)).notify)return Cr.log(`stopping notifications for "${e}" characteristic`),i.stopNotifications()}));return Promise.allSettled(e)},yr=function(e){Cr.log("oncharacteristicvaluechanged");const i=e.target;t(this,fr,"m",br).call(this,i)},br=function(e){Cr.log("onCharacteristicValue");const t=e.name;Cr.assertWithError(Boolean(t),`no name found for characteristic with uuid "${e.uuid}"`),Cr.log(`oncharacteristicvaluechanged for "${t}" characteristic`);const i=e.value;Cr.assertWithError(i,`no data found for "${t}" characteristic`),Cr.log(`data for "${t}" characteristic`,Array.from(new Uint8Array(i.buffer)));try{this.onCharacteristicValueChanged(t,i)}catch(e){Cr.error(e)}},Sr=function(){Cr.log("gattserverdisconnected"),this.status="notConnected"};const kr=4294967296,Dr=9007199254740992;const Wr={encode:function(e){let t,i=new ArrayBuffer(256),s=new DataView(i),n=0;function a(e){let a=i.byteLength;const r=n+e;for(;a<r;)a<<=1;if(a!==i.byteLength){const e=s;i=new ArrayBuffer(a),s=new DataView(i);const t=n+3>>2;for(let i=0;i<t;++i)s.setUint32(i<<2,e.getUint32(i<<2))}return t=e,s}function r(){n+=t}function o(e){r(a(1).setUint8(n,e))}function c(e){const t=a(e.length);for(let i=0;i<e.length;++i)t.setUint8(n+i,e[i]);r()}function h(e,t){t<24?o(e<<5|t):t<256?(o(e<<5|24),o(t)):t<65536?(o(e<<5|25),function(e){r(a(2).setUint16(n,e))}(t)):t<4294967296?(o(e<<5|26),function(e){r(a(4).setUint32(n,e))}(t)):(o(e<<5|27),function(e){const t=e%kr,i=(e-t)/kr,s=a(8);s.setUint32(n,i),s.setUint32(n+4,t),r()}(t))}if(function e(t){let i;const s=[];let l;if(!1===t)return o(244);if(!0===t)return o(245);if(null===t)return o(246);if(void 0===t)return o(247);switch(typeof t){case"number":if(Math.floor(t)===t){if(t>=0&&t<=Dr)return h(0,t);if(-Dr<=t&&t<0)return h(1,-(t+1))}return o(251),function(e){r(a(8).setFloat64(n,e))}(t);case"string":for(i=0;i<t.length;++i){let e=t.charCodeAt(i);e<128?s.push(e):e<2048?(s.push(192|e>>6),s.push(128|63&e)):e<55296?(s.push(224|e>>12),s.push(128|e>>6&63),s.push(128|63&e)):(e=(1023&e)<<10,e|=1023&t.charCodeAt(++i),e+=65536,s.push(240|e>>18),s.push(128|e>>12&63),s.push(128|e>>6&63),s.push(128|63&e))}return h(3,s.length),c(s);default:if(Array.isArray(t))for(l=t.length,h(4,l),i=0;i<l;++i)e(t[i]);else if(t instanceof Uint8Array)h(2,t.length),c(t);else{const s=Object.keys(t);for(l=s.length,h(5,l),i=0;i<l;++i){const n=s[i];e(n),e(t[n])}}}}(e),"slice"in i)return i.slice(0,n);const l=new ArrayBuffer(n),f=new DataView(l);for(let e=0;e<n;++e)f.setUint8(e,s.getUint8(e));return l},decode:function(e,t,i){const s=new DataView(e);let n=0;function a(e,t){return n+=e,t}function r(t){return a(t,new Uint8Array(e,n,t))}function o(){return a(1,s.getUint8(n))}function c(){return a(2,s.getUint16(n))}function h(){return a(4,s.getUint32(n))}function l(){return 255===s.getUint8(n)&&(n+=1,!0)}function f(e){if(e<24)return e;if(24===e)return o();if(25===e)return c();if(26===e)return h();if(27===e)return h()*kr+h();if(31===e)return-1;throw new Error("Invalid length encoding")}function g(e){const t=o();if(255===t)return-1;const i=f(31&t);if(i<0||t>>5!==e)throw new Error("Invalid indefinite length element");return i}function u(e,t){for(let i=0;i<t;++i){let i=o();128&i&&(i<224?(i=(31&i)<<6|63&o(),t-=1):i<240?(i=(15&i)<<12|(63&o())<<6|63&o(),t-=2):(i=(15&i)<<18|(63&o())<<12|(63&o())<<6|63&o(),t-=3)),i<65536?e.push(i):(i-=65536,e.push(55296|i>>10),e.push(56320|1023&i))}}"function"!=typeof t&&(t=function(e){return e}),"function"!=typeof i&&(i=function(){});const d=function e(){const h=o(),d=h>>5,m=31&h;let p,v;if(7===d)switch(m){case 25:return function(){const e=new ArrayBuffer(4),t=new DataView(e),i=c(),s=32768&i;let n=31744&i;const a=1023&i;if(31744===n)n=261120;else if(0!==n)n+=114688;else if(0!==a)return(s?-1:1)*a*5.960464477539063e-8;return t.setUint32(0,s<<16|n<<13|a<<13),t.getFloat32(0)}();case 26:return a(4,s.getFloat32(n));case 27:return a(8,s.getFloat64(n))}if(v=f(m),v<0&&(d<2||d>6))throw new Error("Invalid length");const w=[];let y;const b={};switch(d){case 0:return v;case 1:return-1-v;case 2:if(v<0){const e=[];let t=0;for(;(v=g(d))>=0;)t+=v,e.push(r(v));const i=new Uint8Array(t);let s=0;for(p=0;p<e.length;++p)i.set(e[p],s),s+=e[p].length;return i}return r(v);case 3:if(v<0)for(;(v=g(d))>=0;)u(w,v);else u(w,v);return String.fromCharCode.apply(null,w);case 4:if(v<0)for(y=[];!l();)y.push(e());else for(y=new Array(v),p=0;p<v;++p)y[p]=e();return y;case 5:for(p=0;p<v||v<0&&!l();++p){b[e()]=e()}return b;case 6:return t(e(),v);case 7:switch(v){case 20:return!1;case 21:return!0;case 22:return null;case 23:return;default:return i(v)}}}();if(n!==e.byteLength)throw new Error("Remaining bytes");return d}},Tr=T("mcumgr",{log:!1}),Ir=0,_r=1,Lr=2,Ur=3,Rr=0,Fr=1,Ar=8,xr=0,$r=2,Or=3,Br=5,Nr=0,Pr=1,Vr=5,qr=0;class zr{constructor(){this._mtu=256,this._messageCallback=null,this._imageUploadProgressCallback=null,this._imageUploadNextCallback=null,this._fileUploadProgressCallback=null,this._fileUploadNextCallback=null,this._uploadIsInProgress=!1,this._downloadIsInProgress=!1,this._buffer=new Uint8Array,this._seq=0}onMessage(e){return this._messageCallback=e,this}onImageUploadNext(e){return this._imageUploadNextCallback=e,this}onImageUploadProgress(e){return this._imageUploadProgressCallback=e,this}onImageUploadFinished(e){return this._imageUploadFinishedCallback=e,this}onFileUploadNext(e){return this._fileUploadNextCallback=e,this}onFileUploadProgress(e){return this._fileUploadProgressCallback=e,this}onFileUploadFinished(e){return this._fileUploadFinishedCallback=e,this}onFileDownloadNext(e){return this._fileDownloadNextCallback=e,this}onFileDownloadProgress(e){return this._fileDownloadProgressCallback=e,this}onFileDownloadFinished(e){return this._fileDownloadFinishedCallback=e,this}_getMessage(e,t,i,s){let n=[];void 0!==s&&(n=[...new Uint8Array(Wr.encode(s))]);const a=255&n.length,r=[e,0,n.length>>8,a,t>>8,255&t,this._seq,i,...n];return this._seq=(this._seq+1)%256,r}_notification(e){Tr.log("mcumgr - message received");const t=new Uint8Array(e);this._buffer=new Uint8Array([...this._buffer,...t]);const i=256*this._buffer[2]+this._buffer[3];this._buffer.length<i+8||(this._processMessage(this._buffer.slice(0,i+8)),this._buffer=this._buffer.slice(i+8))}_processMessage(e){const[t,,i,s,n,a,,r]=e,o=Wr.decode(e.slice(8).buffer),c=256*i+s,h=256*n+a;return Tr.log("mcumgr - Process Message - Group: "+h+", Id: "+r+", Off: "+o.off),h===Fr&&r===Pr&&o.off?(this._uploadOffset=o.off,void this._uploadNext()):t===Ur&&h===Ar&&r===qr&&o.off?(this._uploadFileOffset=o.off,void this._uploadFileNext()):t===_r&&h===Ar&&r===qr?(this._downloadFileOffset+=o.data.length,null!=o.len&&(this._downloadFileLength=o.len),Tr.log("downloaded "+this._downloadFileOffset+" bytes of "+this._downloadFileLength),this._downloadFileLength>0&&this._fileDownloadProgressCallback({percentage:Math.floor(this._downloadFileOffset/this._downloadFileLength*100)}),this._messageCallback&&this._messageCallback({op:t,group:h,id:r,data:o,length:c}),void this._downloadFileNext()):void(this._messageCallback&&this._messageCallback({op:t,group:h,id:r,data:o,length:c}))}cmdReset(){return this._getMessage(Lr,Rr,Br)}smpEcho(e){return this._getMessage(Lr,Rr,xr,{d:e})}cmdImageState(){return this._getMessage(Ir,Fr,Nr)}cmdImageErase(){return this._getMessage(Lr,Fr,Vr,{})}cmdImageTest(e){return this._getMessage(Lr,Fr,Nr,{hash:e,confirm:!1})}cmdImageConfirm(e){return this._getMessage(Lr,Fr,Nr,{hash:e,confirm:!0})}_hash(e){return crypto.subtle.digest("SHA-256",e)}async _uploadNext(){if(!this._uploadImage)return;if(this._uploadOffset>=this._uploadImage.byteLength)return this._uploadIsInProgress=!1,void this._imageUploadFinishedCallback();const e={data:new Uint8Array,off:this._uploadOffset};0===this._uploadOffset&&(e.len=this._uploadImage.byteLength,e.sha=new Uint8Array(await this._hash(this._uploadImage))),this._imageUploadProgressCallback({percentage:Math.floor(this._uploadOffset/this._uploadImage.byteLength*100)});const t=this._mtu-Wr.encode(e).byteLength-8-3-5;e.data=new Uint8Array(this._uploadImage.slice(this._uploadOffset,this._uploadOffset+t)),this._uploadOffset+=t;const i=this._getMessage(Lr,Fr,Pr,e);Tr.log("mcumgr - _uploadNext: Message Length: "+i.length),this._imageUploadNextCallback({packet:i})}async reset(){this._messageCallback=null,this._imageUploadProgressCallback=null,this._imageUploadNextCallback=null,this._fileUploadProgressCallback=null,this._fileUploadNextCallback=null,this._uploadIsInProgress=!1,this._downloadIsInProgress=!1,this._buffer=new Uint8Array,this._seq=0}async cmdUpload(e,t=0){this._uploadIsInProgress?Tr.error("Upload is already in progress."):(this._uploadIsInProgress=!0,this._uploadOffset=0,this._uploadImage=e,this._uploadSlot=t,this._uploadNext())}async cmdUploadFile(e,t){this._uploadIsInProgress?Tr.error("Upload is already in progress."):(this._uploadIsInProgress=!0,this._uploadFileOffset=0,this._uploadFile=e,this._uploadFilename=t,this._uploadFileNext())}async _uploadFileNext(){if(Tr.log("uploadFileNext - offset: "+this._uploadFileOffset+", length: "+this._uploadFile.byteLength),this._uploadFileOffset>=this._uploadFile.byteLength)return this._uploadIsInProgress=!1,void this._fileUploadFinishedCallback();const e={data:new Uint8Array,off:this._uploadFileOffset};0===this._uploadFileOffset&&(e.len=this._uploadFile.byteLength),e.name=this._uploadFilename,this._fileUploadProgressCallback({percentage:Math.floor(this._uploadFileOffset/this._uploadFile.byteLength*100)});const t=this._mtu-Wr.encode(e).byteLength-8;e.data=new Uint8Array(this._uploadFile.slice(this._uploadFileOffset,this._uploadFileOffset+t)),this._uploadFileOffset+=t;const i=this._getMessage(Lr,Ar,qr,e);Tr.log("mcumgr - _uploadNext: Message Length: "+i.length),this._fileUploadNextCallback({packet:i})}async cmdDownloadFile(e,t){this._downloadIsInProgress?Tr.error("Download is already in progress."):(this._downloadIsInProgress=!0,this._downloadFileOffset=0,this._downloadFileLength=0,this._downloadRemoteFilename=e,this._downloadLocalFilename=t,this._downloadFileNext())}async _downloadFileNext(){if(this._downloadFileLength>0&&this._downloadFileOffset>=this._downloadFileLength)return this._downloadIsInProgress=!1,void this._fileDownloadFinishedCallback();const e={off:this._downloadFileOffset};0===this._downloadFileOffset&&(e.name=this._downloadRemoteFilename);const t=this._getMessage(Ir,Ar,qr,e);Tr.log("mcumgr - _downloadNext: Message Length: "+t.length),this._fileDownloadNextCallback({packet:t})}async imageInfo(e){const t={},i=new Uint8Array(e);if(i.length<32)throw new Error("Invalid image (too short file)");if(61!==i[0]||184!==i[1]||243!==i[2]||150!==i[3])throw new Error("Invalid image (wrong magic bytes)");if(0!==i[4]||0!==i[5]||0!==i[6]||0!==i[7])throw new Error("Invalid image (wrong load address)");const s=i[8]+256*i[9];if(0!==i[10]||0!==i[11])throw new Error("Invalid image (wrong protected TLV area size)");const n=i[12]+256*i[13]+65536*i[14]+i[15]*2**24;if(t.imageSize=n,i.length<n+s)throw new Error("Invalid image (wrong image size)");if(0!==i[16]||0!==i[17]||0!==i[18]||0!==i[19])throw new Error("Invalid image (wrong flags)");const a=`${i[20]}.${i[21]}.${i[22]+256*i[23]}`;return t.version=a,t.hash=[...new Uint8Array(await this._hash(e.slice(0,n+32)))].map((e=>e.toString(16).padStart(2,"0"))).join(""),t}}var jr,Gr,Hr,Jr,Kr,Qr,Zr,Xr,Yr,eo,to,io,so,no,ao,ro,oo,co,ho,lo,fo;const go=T("FirmwareManager",{log:!1}),uo=["smp"],mo=[...uo,"firmwareImages","firmwareUploadProgress","firmwareStatus","firmwareUploadComplete"],po=["idle","uploading","uploaded","pending","testing","erasing"];class vo{constructor(){jr.add(this),Hr.set(this,"idle"),Kr.set(this,void 0),Xr.set(this,void 0),Yr.set(this,new zr),t(this,jr,"m",eo).call(this),J(this)}get addEventListenter(){return this.eventDispatcher.addEventListener}get removeEventListener(){return this.eventDispatcher.removeEventListener}get waitForEvent(){return this.eventDispatcher.waitForEvent}parseMessage(e,i){if(go.log({messageType:e}),"smp"!==e)throw Error(`uncaught messageType ${e}`);t(this,Yr,"f")._notification(Array.from(new Uint8Array(i.buffer))),t(this,jr,"a",Gr).call(this,"smp",{dataView:i})}async uploadFirmware(e){go.log("uploadFirmware",e);const i=this.waitForEvent("firmwareUploadComplete");await this.getImages();const s=await H(e),n=await t(this,Yr,"f").imageInfo(s);go.log({imageInfo:n}),t(this,Yr,"f").cmdUpload(s,1),t(this,jr,"m",Jr).call(this,"uploading"),await i}get status(){return t(this,Hr,"f")}get images(){return t(this,Kr,"f")}async getImages(){const e=this.waitForEvent("firmwareImages");go.log("getting firmware image state..."),this.sendMessage(Uint8Array.from(t(this,Yr,"f").cmdImageState()).buffer),await e}async testImage(e=1){if(t(this,jr,"m",Zr).call(this,e),t(this,jr,"m",Qr).call(this),!t(this,Kr,"f")[e])return void go.log(`image ${e} not found`);if(1==t(this,Kr,"f")[e].pending)return void go.log(`image ${e} is already pending`);if(t(this,Kr,"f")[e].empty)return void go.log(`image ${e} is empty`);const i=this.waitForEvent("smp");go.log("testing firmware image..."),this.sendMessage(Uint8Array.from(t(this,Yr,"f").cmdImageTest(t(this,Kr,"f")[e].hash)).buffer),await i}async eraseImage(){t(this,jr,"m",Qr).call(this);const e=this.waitForEvent("smp");go.log("erasing image..."),this.sendMessage(Uint8Array.from(t(this,Yr,"f").cmdImageErase()).buffer),t(this,jr,"m",Jr).call(this,"erasing"),await e,await this.getImages()}async confirmImage(e=0){if(t(this,jr,"m",Zr).call(this,e),t(this,jr,"m",Qr).call(this),!0===t(this,Kr,"f")[e].confirmed)return void go.log(`image ${e} is already confirmed`);const i=this.waitForEvent("smp");go.log("confirming image..."),this.sendMessage(Uint8Array.from(t(this,Yr,"f").cmdImageConfirm(t(this,Kr,"f")[e].hash)).buffer),await i}async echo(e){go.assertTypeWithError(e,"string");const i=this.waitForEvent("smp");go.log("sending echo..."),this.sendMessage(Uint8Array.from(t(this,Yr,"f").smpEcho(e)).buffer),await i}async reset(){const e=this.waitForEvent("smp");go.log("resetting..."),this.sendMessage(Uint8Array.from(t(this,Yr,"f").cmdReset()).buffer),await e}get mtu(){return t(this,Xr,"f")}set mtu(e){i(this,Xr,e,"f"),t(this,Yr,"f")._mtu=e}}var wo,yo,bo,So,Co,Mo,Eo,ko,Do,Wo,To,Io,_o,Lo,Uo,Ro,Fo,Ao;Hr=new WeakMap,Kr=new WeakMap,Xr=new WeakMap,Yr=new WeakMap,jr=new WeakSet,Gr=function(){return this.eventDispatcher.dispatchEvent},Jr=function(e){go.assertEnumWithError(e,po),t(this,Hr,"f")!=e?(i(this,Hr,e,"f"),go.log({firmwareStatus:t(this,Hr,"f")}),t(this,jr,"a",Gr).call(this,"firmwareStatus",{firmwareStatus:t(this,Hr,"f")})):go.log(`redundant firmwareStatus assignment "${e}"`)},Qr=function(){go.assertWithError(t(this,Kr,"f"),"didn't get imageState")},Zr=function(e){go.assertTypeWithError(e,"number"),go.assertWithError(0==e||1==e,"imageIndex must be 0 or 1")},eo=function(){t(this,Yr,"f").onMessage(t(this,jr,"m",to).bind(this)),t(this,Yr,"f").onFileDownloadNext(t(this,jr,"m",io)),t(this,Yr,"f").onFileDownloadProgress(t(this,jr,"m",so).bind(this)),t(this,Yr,"f").onFileDownloadFinished(t(this,jr,"m",no).bind(this)),t(this,Yr,"f").onFileUploadNext(t(this,jr,"m",ao).bind(this)),t(this,Yr,"f").onFileUploadProgress(t(this,jr,"m",ro).bind(this)),t(this,Yr,"f").onFileUploadFinished(t(this,jr,"m",oo).bind(this)),t(this,Yr,"f").onImageUploadNext(t(this,jr,"m",co).bind(this)),t(this,Yr,"f").onImageUploadProgress(t(this,jr,"m",ho).bind(this)),t(this,Yr,"f").onImageUploadFinished(t(this,jr,"m",lo).bind(this))},to=function({op:e,group:i,id:s,data:n,length:a}){switch(go.log("onMcuMessage",...arguments),i){case Rr:switch(s){case xr:go.log(`echo "${n.r}"`);break;case $r:go.table(n.tasks);break;case Or:go.log(n)}break;case Fr:if(s===Nr)t(this,jr,"m",fo).call(this,n);break;default:throw Error(`uncaught mcuMessage group ${i}`)}},io=function(){go.log("onMcuFileDownloadNext",...arguments)},so=function(){go.log("onMcuFileDownloadProgress",...arguments)},no=function(){go.log("onMcuFileDownloadFinished",...arguments)},ao=function(){go.log("onMcuFileUploadNext")},ro=function(){go.log("onMcuFileUploadProgress")},oo=function(){go.log("onMcuFileUploadFinished")},co=function({packet:e}){go.log("onMcuImageUploadNext"),this.sendMessage(Uint8Array.from(e).buffer)},ho=function({percentage:e}){const i=e/100;go.log("onMcuImageUploadProgress",...arguments),t(this,jr,"a",Gr).call(this,"firmwareUploadProgress",{progress:i})},lo=async function(){go.log("onMcuImageUploadFinished",...arguments),await this.getImages(),t(this,jr,"a",Gr).call(this,"firmwareUploadProgress",{progress:100}),t(this,jr,"a",Gr).call(this,"firmwareUploadComplete",{})},fo=function({images:e}){if(!e)return void go.log("no images found");i(this,Kr,e,"f"),go.log("images",t(this,Kr,"f"));let s="idle";2==t(this,Kr,"f").length&&(t(this,Kr,"f")[1].bootable?t(this,Kr,"f")[0].confirmed?t(this,Kr,"f")[1].pending?(go.log("reset to upload to the new firmware image"),s="pending"):(go.log("Slot 1 has a valid image. run testImage() to test it or upload a different image."),s="uploaded"):(go.log('Slot 0 has a valid image. Click "Confirm Image" to confirm it or wait and the device will swap images back.'),s="testing"):go.warn('Slot 1 has a invalid image. Click "Erase Image" to erase it or upload a different image')),1==t(this,Kr,"f").length&&(t(this,Kr,"f").push({slot:1,empty:!0,version:"Empty",pending:!1,confirmed:!1,bootable:!1,active:!1,permanent:!1}),go.log("Select a firmware upload image to upload to slot 1.")),t(this,jr,"m",Jr).call(this,s),t(this,jr,"a",Gr).call(this,"firmwareImages",{firmwareImages:t(this,Kr,"f")})};const xo=T("DeviceManager",{log:!1}),$o=["deviceConnected","deviceDisconnected","deviceIsConnected","availableDevices","connectedDevices"];class Oo{constructor(){if(wo.add(this),yo.set(this,{getType:t(this,wo,"m",bo).bind(this),isConnected:t(this,wo,"m",Ro).bind(this)}),So.set(this,[]),Co.set(this,!1),Mo.set(this,{devices:[]}),Eo.set(this,void 0),Do.set(this,"BS.Device"),_o.set(this,[]),Lo.set(this,new _(this,$o)),Oo.shared&&this!=Oo.shared)throw Error("DeviceManager is a singleton - use DeviceManager.shared");this.CanUseLocalStorage&&(this.UseLocalStorage=!0)}onDevice(e){Ja(e,t(this,yo,"f"))}OnDeviceConnectionStatusUpdated(e,i){if("notConnected"==i&&!e.canReconnect&&t(this,_o,"f").includes(e)){const i=t(this,_o,"f").indexOf(e);this.AvailableDevices.splice(i,1),t(this,wo,"m",Fo).call(this)}}get ConnectedDevices(){return t(this,So,"f")}get UseLocalStorage(){return t(this,Co,"f")}set UseLocalStorage(e){t(this,wo,"m",ko).call(this),xo.assertTypeWithError(e,"boolean"),i(this,Co,e,"f"),t(this,Co,"f")&&!t(this,Eo,"f")&&t(this,wo,"m",To).call(this)}get CanUseLocalStorage(){return n&&window.localStorage}get AvailableDevices(){return t(this,_o,"f")}get CanGetDevices(){return n&&navigator.bluetooth?.getDevices}async GetDevices(){if(!n)return void xo.warn("GetDevices is only available in the browser");if(!navigator.bluetooth)return void xo.warn("bluetooth is not available in this browser");if(c)return void xo.warn("bluefy lists too many devices...");if(!navigator.bluetooth.getDevices)return void xo.warn("bluetooth.getDevices() is not available in this browser");if(!this.CanGetDevices)return void xo.log("CanGetDevices is false");t(this,Eo,"f")||t(this,wo,"m",To).call(this);const e=t(this,Eo,"f");if(!e.devices||0==e.devices.length)return void xo.log("no devices found in configuration");const i=await navigator.bluetooth.getDevices();return xo.log({bluetoothDevices:i}),i.forEach((i=>{if(!i.gatt)return;let s=e.devices.find((e=>i.id==e.bluetoothId));if(!s)return;let n=this.ConnectedDevices.filter((e=>"webBluetooth"==e.connectionType)).find((e=>e.bluetoothId==i.id));const a=this.AvailableDevices.filter((e=>"webBluetooth"==e.connectionType)).find((e=>e.bluetoothId==i.id));if(a)return void(n&&n?.bluetoothId==a.bluetoothId&&n!=a&&(this.AvailableDevices[t(this,_o,"f").indexOf(a)]=n));if(n)return void this.AvailableDevices.push(n);const r=new ch,o=new Er;o.device=i,i.name&&r._informationManager.updateName(i.name),r._informationManager.updateType(s.type),r.connectionManager=o,this.AvailableDevices.push(r)})),t(this,wo,"m",Fo).call(this),this.AvailableDevices}get AddEventListener(){return t(this,Lo,"f").addEventListener}get RemoveEventListener(){return t(this,Lo,"f").removeEventListener}get RemoveEventListeners(){return t(this,Lo,"f").removeEventListeners}get RemoveAllEventListeners(){return t(this,Lo,"f").removeAllEventListeners}_CheckDeviceAvailability(e){e.isConnected||e.isAvailable||!t(this,_o,"f").includes(e)||(xo.log("removing device from availableDevices..."),t(this,_o,"f").splice(t(this,_o,"f").indexOf(e),1),t(this,wo,"m",Fo).call(this))}}yo=new WeakMap,So=new WeakMap,Co=new WeakMap,Mo=new WeakMap,Eo=new WeakMap,Do=new WeakMap,_o=new WeakMap,Lo=new WeakMap,wo=new WeakSet,bo=function(e){t(this,Co,"f")&&t(this,wo,"m",Io).call(this,e.target)},ko=function(){xo.assertWithError(n,"localStorage is only available in the browser"),xo.assertWithError(window.localStorage,"localStorage not found")},Wo=function(){t(this,wo,"m",ko).call(this),localStorage.setItem(t(this,Do,"f"),JSON.stringify(t(this,Eo,"f")))},To=async function(){t(this,wo,"m",ko).call(this);let e=localStorage.getItem(t(this,Do,"f"));if("string"!=typeof e)return xo.log("no info found in localStorage"),i(this,Eo,Object.assign({},t(this,Mo,"f")),"f"),void t(this,wo,"m",Wo).call(this);try{const t=JSON.parse(e);xo.log({configuration:t}),i(this,Eo,t,"f"),this.CanGetDevices&&await this.GetDevices()}catch(e){xo.error(e)}},Io=function(e){if("webBluetooth"!=e.connectionType)return void xo.log("localStorage is only for webBluetooth devices");t(this,wo,"m",ko).call(this);const i=t(this,Eo,"f").devices.findIndex((t=>t.bluetoothId==e.bluetoothId));-1!=i&&(t(this,Eo,"f").devices[i].type=e.type,t(this,wo,"m",Wo).call(this))},Uo=function(){return t(this,Lo,"f").dispatchEvent},Ro=function(e){const{target:i}=e;if(i.isConnected)if(t(this,So,"f").includes(i))xo.log("device already included");else{if(xo.log("adding device",i),t(this,So,"f").push(i),this.UseLocalStorage&&"webBluetooth"==i.connectionType){const e={type:i.type,bluetoothId:i.bluetoothId,ipAddress:i.ipAddress,isWifiSecure:i.isWifiSecure},s=t(this,Eo,"f").devices.findIndex((t=>t.bluetoothId==e.bluetoothId));-1==s?t(this,Eo,"f").devices.push(e):t(this,Eo,"f").devices[s]=e,t(this,wo,"m",Wo).call(this)}t(this,wo,"a",Uo).call(this,"deviceConnected",{device:i}),t(this,wo,"a",Uo).call(this,"deviceIsConnected",{device:i}),t(this,wo,"m",Ao).call(this)}else t(this,So,"f").includes(i)?(xo.log("removing device",i),t(this,So,"f").splice(t(this,So,"f").indexOf(i),1),t(this,wo,"a",Uo).call(this,"deviceDisconnected",{device:i}),t(this,wo,"a",Uo).call(this,"deviceIsConnected",{device:i}),t(this,wo,"m",Ao).call(this)):xo.log("device already not included");if(this.CanGetDevices&&this.GetDevices(),i.isConnected&&!this.AvailableDevices.includes(i)){const e=this.AvailableDevices.find((e=>e.bluetoothId==i.bluetoothId));xo.log({existingAvailableDevice:e}),e?this.AvailableDevices[this.AvailableDevices.indexOf(e)]=i:this.AvailableDevices.push(i),t(this,wo,"m",Fo).call(this)}this._CheckDeviceAvailability(i)},Fo=function(){xo.log({AvailableDevices:this.AvailableDevices}),t(this,wo,"a",Uo).call(this,"availableDevices",{availableDevices:this.AvailableDevices})},Ao=function(){xo.log({ConnectedDevices:this.ConnectedDevices}),t(this,wo,"a",Uo).call(this,"connectedDevices",{connectedDevices:this.ConnectedDevices})},Oo.shared=new Oo;var Bo=Oo.shared;const No=T("ServerUtils",{log:!1}),Po=["isScanningAvailable","isScanning","startScan","stopScan","discoveredDevice","discoveredDevices","expiredDiscoveredDevice","connectToDevice","disconnectFromDevice","connectedDevices","deviceMessage","requiredDeviceInformation"];function Vo(e,...t){No.log("createMessage",...t);const i=t.map((t=>{"string"==typeof t&&(t={type:t}),null!=t.data?Array.isArray(t.data)||(t.data=[t.data]):t.data=[];const i=z(...t.data),s=i.byteLength;No.assertEnumWithError(t.type,e);const n=e.indexOf(t.type),a=new DataView(new ArrayBuffer(2));return a.setUint16(0,s,!0),z(n,a,i)}));return No.log("messageBuffers",...i),z(...i)}function qo(...e){return No.log("createServerMessage",...e),Vo(Po,...e)}function zo(...e){return No.log("createClientDeviceMessage",...e),Vo(ja,...e)}qo("isScanningAvailable"),qo("isScanning"),qo("startScan"),qo("stopScan"),qo("discoveredDevices");const jo=T("WebSocketUtils",{log:!1}),Go=["ping","pong","serverMessage"];function Ho(...e){return jo.log("createWebSocketMessage",...e),Vo(Go,...e)}var Jo,Ko,Qo,Zo,Xo,Yo,ec,tc,ic,sc,nc,ac,rc,oc,cc,hc,lc,fc;Ho("ping"),Ho("pong");const gc=T("WebSocketConnectionManager",{log:!1}),uc=["ping","pong","batteryLevel","deviceInformation","message"];const dc=["deviceInformation","batteryLevel"];class mc extends Ga{get bluetoothId(){return t(this,Ko,"f")??""}constructor(e,s=!1,n){super(),Jo.add(this),Ko.set(this,void 0),this.defaultMtu=1024,Qo.set(this,void 0),Zo.set(this,void 0),Xo.set(this,!1),tc.set(this,{open:t(this,Jo,"m",ic).bind(this),message:t(this,Jo,"m",sc).bind(this),close:t(this,Jo,"m",nc).bind(this),error:t(this,Jo,"m",ac).bind(this)}),cc.set(this,new A(t(this,Jo,"m",hc).bind(this),29e3)),this.ipAddress=e,this.isSecure=s,this.mtu=this.defaultMtu,i(this,Ko,n,"f")}get isAvailable(){return!0}static get isSupported(){return!0}static get type(){return"webSocket"}get webSocket(){return t(this,Qo,"f")}set webSocket(e){t(this,Qo,"f")!=e?(gc.log("assigning webSocket",e),t(this,Qo,"f")&&(Ka(t(this,Qo,"f"),t(this,tc,"f")),t(this,Qo,"f").readyState==t(this,Qo,"f").OPEN&&t(this,Qo,"f").close()),e&&Ja(e,t(this,tc,"f")),i(this,Qo,e,"f"),gc.log("assigned webSocket")):gc.log("redundant webSocket assignment")}get ipAddress(){return t(this,Zo,"f")}set ipAddress(e){this.assertIsNotConnected(),t(this,Zo,"f")!=e?(i(this,Zo,e,"f"),gc.log(`updated ipAddress to "${this.ipAddress}"`)):gc.log(`redundnant ipAddress assignment "${e}"`)}get isSecure(){return t(this,Xo,"f")}set isSecure(e){this.assertIsNotConnected(),t(this,Xo,"f")!=e?(i(this,Xo,e,"f"),gc.log(`updated isSecure to "${this.isSecure}"`)):gc.log(`redundant isSecure assignment ${e}`)}get url(){return`${this.isSecure?"wss":"ws"}://${this.ipAddress}/ws`}async connect(){await super.connect();try{this.webSocket=new WebSocket(this.url)}catch(e){gc.error("error connecting to webSocket",e),this.status="notConnected"}}async disconnect(){await super.disconnect(),gc.log("closing websocket"),t(this,cc,"f").stop(),t(this,Qo,"f")?.close()}get canReconnect(){return Boolean(this.webSocket)}async reconnect(){await super.reconnect(),this.webSocket=new WebSocket(this.url)}async sendSmpMessage(e){super.sendSmpMessage(e),gc.error("smp not supported on webSockets")}async sendTxData(e){await super.sendTxData(e),0!=e.byteLength&&t(this,Jo,"m",ec).call(this,{type:"message",data:e})}remove(){super.remove(),this.webSocket=void 0}}var pc,vc,wc,yc,bc,Sc,Cc,Mc,Ec,kc,Dc,Wc,Tc,Ic,_c,Lc,Uc,Rc,Fc,Ac,xc,$c,Oc,Bc,Nc,Pc,Vc,qc,zc,jc,Gc,Hc,Jc,Kc,Qc,Zc,Xc,Yc,eh,th,ih,sh,nh;Ko=new WeakMap,Qo=new WeakMap,Zo=new WeakMap,Xo=new WeakMap,tc=new WeakMap,cc=new WeakMap,Jo=new WeakSet,Yo=function(e){this.assertIsConnected(),gc.log("sending webSocket message",e),t(this,Qo,"f").send(e),t(this,cc,"f").restart()},ec=function(...e){t(this,Jo,"m",Yo).call(this,function(...e){return gc.log("createWebSocketMessage",...e),Vo(uc,...e)}(...e))},ic=function(e){gc.log("webSocket.open",e),t(this,cc,"f").start(),this.status="connected",t(this,Jo,"m",fc).call(this)},sc=async function(e){const i=await e.data.arrayBuffer(),s=new DataView(i);gc.log(`webSocket.message (${s.byteLength} bytes)`),t(this,Jo,"m",rc).call(this,s)},nc=function(e){gc.log("webSocket.close",e),this.status="notConnected",t(this,cc,"f").stop()},ac=function(e){gc.error("webSocket.error",e)},rc=function(e){bt(e,uc,t(this,Jo,"m",oc).bind(this),null,!0)},oc=function(e,i){switch(gc.log(`received "${e}" message (${i.byteLength} bytes)`),e){case"ping":t(this,Jo,"m",lc).call(this);break;case"pong":break;case"batteryLevel":this.onMessageReceived?.("batteryLevel",i);break;case"deviceInformation":bt(i,sn,((e,t)=>{this.onMessageReceived(e,t)}));break;case"message":this.parseRxMessage(i);break;default:gc.error(`uncaught messageType "${e}"`)}},hc=function(){gc.log("pinging"),t(this,Jo,"m",ec).call(this,"ping")},lc=function(){gc.log("ponging"),t(this,Jo,"m",ec).call(this,"pong")},fc=function(){t(this,Jo,"m",ec).call(this,...dc)};const ah=T("Device",{log:!1}),rh=["connectionMessage",...Pa,...za,...qa,...Tn,...nn,...ls,...Hi,...ea,...Pe,...js,...Ea,...si,...Bi,...mo],oh=["isCharging","getBatteryCurrent","getId","getMtu","getName","getType","getCurrentTime","getSensorConfiguration","getSensorScalars","getVibrationLocations","getFileTypes","isWifiAvailable"];class ch{get bluetoothId(){return t(this,Sc,"f")?.bluetoothId}get isAvailable(){return t(this,Sc,"f")?.isAvailable}constructor(){pc.add(this),yc.set(this,new _(this,rh)),Sc.set(this,void 0),this.sendTxMessages=t(this,pc,"m",Cc).bind(this),Mc.set(this,!1),_c.set(this,vc.ReconnectOnDisconnection),Lc.set(this,void 0),this.latestConnectionMessages=new Map,Bc.set(this,new an),Nc.set(this,0),this._informationManager=new In,Vc.set(this,new fs),zc.set(this,vc.ClearSensorConfigurationOnLeave),jc.set(this,new Ji),Gc.set(this,new sa),Hc.set(this,new qe),Jc.set(this,new Ks),Kc.set(this,new vo),this.sendSmpMessage=t(this,pc,"m",Zc).bind(this),Xc.set(this,!1),Yc.set(this,new ka),eh.set(this,new ni),ih.set(this,new Ni),t(this,Bc,"f").eventDispatcher=t(this,yc,"f"),this._informationManager.sendMessage=this.sendTxMessages,this._informationManager.eventDispatcher=t(this,yc,"f"),t(this,Vc,"f").sendMessage=this.sendTxMessages,t(this,Vc,"f").eventDispatcher=t(this,yc,"f"),t(this,jc,"f").eventDispatcher=t(this,yc,"f"),t(this,Gc,"f").sendMessage=this.sendTxMessages,t(this,Gc,"f").eventDispatcher=t(this,yc,"f"),t(this,Jc,"f").sendMessage=this.sendTxMessages,t(this,Jc,"f").eventDispatcher=t(this,yc,"f"),t(this,Hc,"f").sendMessage=this.sendTxMessages,t(this,Hc,"f").eventDispatcher=t(this,yc,"f"),t(this,Yc,"f").sendMessage=this.sendTxMessages,t(this,Yc,"f").eventDispatcher=t(this,yc,"f"),t(this,eh,"f").sendMessage=this.sendTxMessages,t(this,eh,"f").eventDispatcher=t(this,yc,"f"),t(this,ih,"f").sendMessage=this.sendTxMessages,t(this,ih,"f").eventDispatcher=t(this,yc,"f"),t(this,Kc,"f").sendMessage=this.sendSmpMessage,t(this,Kc,"f").eventDispatcher=t(this,yc,"f"),this.addEventListener("getMtu",(()=>{t(this,Kc,"f").mtu=this.mtu,t(this,Hc,"f").mtu=this.mtu,this.connectionManager.mtu=this.mtu})),this.addEventListener("getSensorConfiguration",(()=>{if("connecting"==this.connectionStatus){if(this.sensorTypes.includes("pressure")){ah.log("requesting required pressure information");const e=Gi.map((e=>({type:e})));this.sendTxMessages(e,!1)}else ah.log("don't need to request pressure infomration");if(this.sensorTypes.includes("camera")){ah.log("requesting required camera information");const e=ii.map((e=>({type:e})));this.sendTxMessages(e,!1)}else ah.log("don't need to request camera infomration");if(this.sensorTypes.includes("microphone")){ah.log("requesting required microphone information");const e=Oi.map((e=>({type:e})));this.sendTxMessages(e,!1)}else ah.log("don't need to request microphone infomration")}})),this.addEventListener("getFileTypes",(()=>{"connecting"==this.connectionStatus&&(this.fileTypes.length>0&&t(this,Hc,"f").requestRequiredInformation(),this.fileTypes.includes("tflite")&&t(this,Jc,"f").requestRequiredInformation())})),this.addEventListener("isWifiAvailable",(()=>{"connecting"==this.connectionStatus&&("client"!=this.connectionType||a)&&this.isWifiAvailable&&"client"!=this.connectionType&&t(this,Yc,"f").requestRequiredInformation()})),Bo.onDevice(this),n&&window.addEventListener("beforeunload",(()=>{this.isConnected&&this.clearSensorConfigurationOnLeave&&this.clearSensorConfiguration()})),a&&process.on("exit",(()=>{this.isConnected&&this.clearSensorConfigurationOnLeave&&this.clearSensorConfiguration()}))}get addEventListener(){return t(this,yc,"f").addEventListener}get removeEventListener(){return t(this,yc,"f").removeEventListener}get waitForEvent(){return t(this,yc,"f").waitForEvent}get removeEventListeners(){return t(this,yc,"f").removeEventListeners}get removeAllEventListeners(){return t(this,yc,"f").removeAllEventListeners}get connectionManager(){return t(this,Sc,"f")}set connectionManager(e){this.connectionManager!=e?(this.connectionManager&&this.connectionManager.remove(),e&&(e.onStatusUpdated=t(this,pc,"m",Uc).bind(this),e.onMessageReceived=t(this,pc,"m",$c).bind(this),e.onMessagesReceived=t(this,pc,"m",Oc).bind(this)),i(this,Sc,e,"f"),ah.log("assigned new connectionManager",t(this,Sc,"f")),this._informationManager.connectionType=this.connectionType):ah.log("same connectionManager is already assigned")}async connect(e){if(ah.log("connect options",e),e)switch(e.type){case"webBluetooth":"webBluetooth"!=this.connectionType&&(this.connectionManager=new Er);break;case"webSocket":{let t=!1;if("webSocket"==this.connectionType){const i=this.connectionManager;i.ipAddress==e.ipAddress&&i.isSecure==e.isWifiSecure||(t=!0)}else t=!0;t&&(this.connectionManager=new mc(e.ipAddress,e.isWifiSecure,this.bluetoothId))}break;case"udp":{let t=!1;if("udp"==this.connectionType){this.connectionManager.ipAddress!=e.ipAddress&&(t=!0),this.reconnectOnDisconnection=!0}else t=!0;t&&(this.connectionManager=new UDPConnectionManager(e.ipAddress,this.bluetoothId))}}if(this.connectionManager||(this.connectionManager=t(vc,vc,"m",wc).call(vc)),t(this,pc,"m",Ac).call(this),"client"==e?.type){ah.assertWithError("client"==this.connectionType,"expected clientConnectionManager");const t=this.connectionManager;return t.subType=e.subType,t.connect()}return ah.log("connectionManager type",this.connectionManager.type),this.connectionManager.connect()}get isConnected(){return t(this,Mc,"f")}get canReconnect(){return this.connectionManager?.canReconnect}async reconnect(){return t(this,pc,"m",Tc).call(this),t(this,pc,"m",Ac).call(this),this.connectionManager?.reconnect()}static async Connect(){const e=new vc;return await e.connect(),e}static get ReconnectOnDisconnection(){return t(this,vc,"f",Ic)}static set ReconnectOnDisconnection(e){ah.assertTypeWithError(e,"boolean"),i(this,vc,e,"f",Ic)}get reconnectOnDisconnection(){return t(this,_c,"f")}set reconnectOnDisconnection(e){ah.assertTypeWithError(e,"boolean"),i(this,_c,e,"f")}get connectionType(){return this.connectionManager?.type}async disconnect(){return t(this,pc,"m",Ec).call(this),this.reconnectOnDisconnection&&(this.reconnectOnDisconnection=!1,this.addEventListener("isConnected",(()=>{this.reconnectOnDisconnection=!0}),{once:!0})),this.connectionManager.disconnect()}toggleConnection(){if(this.isConnected)this.disconnect();else if(this.canReconnect)try{this.reconnect()}catch(e){ah.error("error trying to reconnect",e),this.connect()}else this.connect()}get connectionStatus(){switch(t(this,Sc,"f")?.status){case"connected":return this.isConnected?"connected":"connecting";case"notConnected":case"connecting":case"disconnecting":return t(this,Sc,"f").status;default:return"notConnected"}}get isConnectionBusy(){return"connecting"==this.connectionStatus||"disconnecting"==this.connectionStatus}get deviceInformation(){return t(this,Bc,"f").information}get batteryLevel(){return t(this,Nc,"f")}get id(){return this._informationManager.id}get isCharging(){return this._informationManager.isCharging}get batteryCurrent(){return this._informationManager.batteryCurrent}get getBatteryCurrent(){return this._informationManager.getBatteryCurrent}get name(){return this._informationManager.name}get setName(){return this._informationManager.setName}get type(){return this._informationManager.type}get setType(){return this._informationManager.setType}get isInsole(){return this._informationManager.isInsole}get isGlove(){return this._informationManager.isGlove}get side(){return this._informationManager.side}get mtu(){return this._informationManager.mtu}get sensorTypes(){return Object.keys(this.sensorConfiguration)}get continuousSensorTypes(){return zi.filter((e=>this.sensorTypes.includes(e)))}get sensorConfiguration(){return t(this,Vc,"f").configuration}async setSensorConfiguration(e,i){await t(this,Vc,"f").setConfiguration(e,i)}async clearSensorConfiguration(){return t(this,Vc,"f").clearSensorConfiguration()}static get ClearSensorConfigurationOnLeave(){return t(this,vc,"f",qc)}static set ClearSensorConfigurationOnLeave(e){ah.assertTypeWithError(e,"boolean"),i(this,vc,e,"f",qc)}get clearSensorConfigurationOnLeave(){return t(this,zc,"f")}set clearSensorConfigurationOnLeave(e){ah.assertTypeWithError(e,"boolean"),i(this,zc,e,"f")}get numberOfPressureSensors(){return t(this,jc,"f").pressureSensorDataManager.numberOfSensors}resetPressureRange(){t(this,jc,"f").pressureSensorDataManager.resetRange()}get vibrationLocations(){return t(this,Gc,"f").vibrationLocations}async triggerVibration(e,i){t(this,Gc,"f").triggerVibration(e,i)}get fileTypes(){return t(this,Hc,"f").fileTypes}get maxFileLength(){return t(this,Hc,"f").maxLength}get validFileTypes(){return Oe.filter((e=>!(e.includes("wifi")&&!this.isWifiAvailable)))}async sendFile(e,i){ah.assertWithError(this.validFileTypes.includes(e),`invalid fileType ${e}`);const s=this.waitForEvent("fileTransferComplete");t(this,Hc,"f").send(e,i),await s}async receiveFile(e){const i=this.waitForEvent("fileTransferComplete");t(this,Hc,"f").receive(e),await i}get fileTransferStatus(){return t(this,Hc,"f").status}cancelFileTransfer(){t(this,Hc,"f").cancel()}get tfliteName(){return t(this,Jc,"f").name}get setTfliteName(){return t(this,Jc,"f").setName}async sendTfliteConfiguration(e){e.type="tflite",t(this,Jc,"f").sendConfiguration(e,!1);await t(this,Hc,"f").send(e.type,e.file)||t(this,pc,"m",Cc).call(this)}get tfliteTask(){return t(this,Jc,"f").task}get setTfliteTask(){return t(this,Jc,"f").setTask}get tfliteSampleRate(){return t(this,Jc,"f").sampleRate}get setTfliteSampleRate(){return t(this,Jc,"f").setSampleRate}get tfliteSensorTypes(){return t(this,Jc,"f").sensorTypes}get allowedTfliteSensorTypes(){return this.sensorTypes.filter((e=>Js.includes(e)))}get setTfliteSensorTypes(){return t(this,Jc,"f").setSensorTypes}get tfliteIsReady(){return t(this,Jc,"f").isReady}get tfliteInferencingEnabled(){return t(this,Jc,"f").inferencingEnabled}get setTfliteInferencingEnabled(){return t(this,Jc,"f").setInferencingEnabled}async enableTfliteInferencing(){return this.setTfliteInferencingEnabled(!0)}async disableTfliteInferencing(){return this.setTfliteInferencingEnabled(!1)}get toggleTfliteInferencing(){return t(this,Jc,"f").toggleInferencingEnabled}get tfliteCaptureDelay(){return t(this,Jc,"f").captureDelay}get setTfliteCaptureDelay(){return t(this,Jc,"f").setCaptureDelay}get tfliteThreshold(){return t(this,Jc,"f").threshold}get setTfliteThreshold(){return t(this,Jc,"f").setThreshold}get canUpdateFirmware(){return t(this,Sc,"f")?.canUpdateFirmware}get uploadFirmware(){return t(this,pc,"m",Qc).call(this),t(this,Kc,"f").uploadFirmware}get canReset(){return this.canUpdateFirmware}async reset(){return ah.assertWithError(this.canReset,"reset is not enabled for this device"),await t(this,Kc,"f").reset(),t(this,Sc,"f").disconnect()}get firmwareStatus(){return t(this,Kc,"f").status}get getFirmwareImages(){return t(this,pc,"m",Qc).call(this),t(this,Kc,"f").getImages}get firmwareImages(){return t(this,Kc,"f").images}get eraseFirmwareImage(){return t(this,pc,"m",Qc).call(this),t(this,Kc,"f").eraseImage}get confirmFirmwareImage(){return t(this,pc,"m",Qc).call(this),t(this,Kc,"f").confirmImage}get testFirmwareImage(){return t(this,pc,"m",Qc).call(this),t(this,Kc,"f").testImage}get isServerSide(){return t(this,Xc,"f")}set isServerSide(e){t(this,Xc,"f")!=e?(ah.log({newIsServerSide:e}),i(this,Xc,e,"f"),t(this,Hc,"f").isServerSide=this.isServerSide):ah.log("redundant isServerSide assignment")}get isUkaton(){return this.deviceInformation.modelNumber.includes("Ukaton")}get isWifiAvailable(){return t(this,Yc,"f").isWifiAvailable}get wifiSSID(){return t(this,Yc,"f").wifiSSID}async setWifiSSID(e){return t(this,Yc,"f").setWifiSSID(e)}get wifiPassword(){return t(this,Yc,"f").wifiPassword}async setWifiPassword(e){return t(this,Yc,"f").setWifiPassword(e)}get isWifiConnected(){return t(this,Yc,"f").isWifiConnected}get ipAddress(){return t(this,Yc,"f").ipAddress}get wifiConnectionEnabled(){return t(this,Yc,"f").wifiConnectionEnabled}get enableWifiConnection(){return t(this,Yc,"f").enableWifiConnection}get setWifiConnectionEnabled(){return t(this,Yc,"f").setWifiConnectionEnabled}get disableWifiConnection(){return t(this,Yc,"f").disableWifiConnection}get toggleWifiConnection(){return t(this,Yc,"f").toggleWifiConnection}get isWifiSecure(){return t(this,Yc,"f").isWifiSecure}async reconnectViaWebSockets(){ah.assertWithError(this.isWifiConnected,"wifi is not connected"),ah.assertWithError("webSocket"!=this.connectionType,"already connected via webSockets"),ah.assertTypeWithError(this.ipAddress,"string"),ah.log("reconnecting via websockets..."),await this.disconnect(),await this.connect({type:"webSocket",ipAddress:this.ipAddress,isWifiSecure:this.isWifiSecure})}async reconnectViaUDP(){ah.assertWithError(a,"udp is only available in node"),ah.assertWithError(this.isWifiConnected,"wifi is not connected"),ah.assertWithError("udp"!=this.connectionType,"already connected via udp"),ah.assertTypeWithError(this.ipAddress,"string"),ah.log("reconnecting via udp..."),await this.disconnect(),await this.connect({type:"udp",ipAddress:this.ipAddress})}get hasCamera(){return this.sensorTypes.includes("camera")}get cameraStatus(){return t(this,eh,"f").cameraStatus}async takePicture(){t(this,pc,"m",th).call(this),await t(this,eh,"f").takePicture()}async focusCamera(){t(this,pc,"m",th).call(this),await t(this,eh,"f").focus()}async stopCamera(){t(this,pc,"m",th).call(this),await t(this,eh,"f").stop()}async wakeCamera(){t(this,pc,"m",th).call(this),await t(this,eh,"f").wake()}async sleepCamera(){t(this,pc,"m",th).call(this),await t(this,eh,"f").sleep()}get cameraConfiguration(){return t(this,eh,"f").cameraConfiguration}get availableCameraConfigurationTypes(){return t(this,eh,"f").availableCameraConfigurationTypes}get cameraConfigurationRanges(){return t(this,eh,"f").cameraConfigurationRanges}get setCameraConfiguration(){return t(this,eh,"f").setCameraConfiguration}get hasMicrophone(){return this.sensorTypes.includes("microphone")}get microphoneStatus(){return t(this,ih,"f").microphoneStatus}async startMicrophone(){t(this,pc,"m",sh).call(this),await t(this,ih,"f").start()}async stopMicrophone(){t(this,pc,"m",sh).call(this),await t(this,ih,"f").stop()}async enableMicrophoneVad(){t(this,pc,"m",sh).call(this),await t(this,ih,"f").vad()}async toggleMicrophone(){t(this,pc,"m",sh).call(this),await t(this,ih,"f").toggle()}get microphoneConfiguration(){return t(this,ih,"f").microphoneConfiguration}get availableMicrophoneConfigurationTypes(){return t(this,ih,"f").availableMicrophoneConfigurationTypes}get setMicrophoneConfiguration(){return t(this,ih,"f").setMicrophoneConfiguration}get audioContext(){return t(this,pc,"m",nh).call(this),t(this,ih,"f").audioContext}set audioContext(e){t(this,pc,"m",nh).call(this),t(this,ih,"f").audioContext=e}get microphoneMediaStreamDestination(){return t(this,pc,"m",nh).call(this),t(this,ih,"f").mediaStreamDestination}get microphoneGainNode(){return t(this,pc,"m",nh).call(this),t(this,ih,"f").gainNode}get isRecordingMicrophone(){return t(this,ih,"f").isRecording}startRecordingMicrophone(){t(this,pc,"m",nh).call(this),t(this,ih,"f").startRecording()}stopRecordingMicrophone(){t(this,pc,"m",nh).call(this),t(this,ih,"f").stopRecording()}toggleMicrophoneRecording(){t(this,pc,"m",nh).call(this),t(this,ih,"f").toggleRecording()}}var hh,lh,fh,gh,uh,dh;vc=ch,yc=new WeakMap,Sc=new WeakMap,Mc=new WeakMap,_c=new WeakMap,Lc=new WeakMap,Bc=new WeakMap,Nc=new WeakMap,Vc=new WeakMap,zc=new WeakMap,jc=new WeakMap,Gc=new WeakMap,Hc=new WeakMap,Jc=new WeakMap,Kc=new WeakMap,Xc=new WeakMap,Yc=new WeakMap,eh=new WeakMap,ih=new WeakMap,pc=new WeakSet,wc=function(){return new Er},bc=function(){return t(this,yc,"f").dispatchEvent},Cc=async function(e,i){await(t(this,Sc,"f")?.sendTxMessages(e,i))},Ec=function(){ah.assertWithError(this.isConnected,"notConnected")},kc=function(e){return e.every((e=>{const t=this.latestConnectionMessages.has(e);return t||ah.log(`didn't receive "${e}" message`),t}))},Dc=function(){let e=t(this,pc,"m",kc).call(this,oh);return e&&this.sensorTypes.includes("pressure")&&(e=t(this,pc,"m",kc).call(this,Gi)),e&&this.isWifiAvailable&&(e=t(this,pc,"m",kc).call(this,Ma)),e&&this.fileTypes.length>0&&(e=t(this,pc,"m",kc).call(this,Ve)),e&&this.fileTypes.includes("tflite")&&(e=t(this,pc,"m",kc).call(this,Gs)),e&&this.hasCamera&&(e=t(this,pc,"m",kc).call(this,ii)),e},Wc=function(){ah.log("requesting required information");const e=oh.map((e=>({type:e})));t(this,pc,"m",Cc).call(this,e)},Tc=function(){ah.assertWithError(this.canReconnect,"cannot reconnect to device")},Uc=function(e){ah.log({connectionStatus:e}),"notConnected"==e?(t(this,pc,"m",xc).call(this),this.canReconnect&&this.reconnectOnDisconnection&&(ah.log("starting reconnect interval..."),i(this,Lc,setInterval((()=>{ah.log("attempting reconnect..."),this.reconnect()}),1e3),"f"))):null!=t(this,Lc,"f")&&(ah.log("clearing reconnect interval"),clearInterval(t(this,Lc,"f")),i(this,Lc,void 0,"f")),t(this,pc,"m",Fc).call(this),"connected"!=e||t(this,Mc,"f")||"client"!=this.connectionType&&t(this,pc,"m",Wc).call(this),Bo.OnDeviceConnectionStatusUpdated(this,e)},Rc=function(e=!1){t(this,pc,"a",bc).call(this,"connectionStatus",{connectionStatus:this.connectionStatus}),t(this,pc,"a",bc).call(this,this.connectionStatus,{}),e&&t(this,pc,"a",bc).call(this,"isConnected",{isConnected:this.isConnected})},Fc=function(){switch(i(this,Mc,Boolean(this.connectionManager?.isConnected)&&t(this,pc,"a",Dc)&&this._informationManager.isCurrentTimeSet,"f"),this.connectionStatus){case"connected":t(this,Mc,"f")&&t(this,pc,"m",Rc).call(this,!0);break;case"notConnected":t(this,pc,"m",Rc).call(this,!0);break;default:t(this,pc,"m",Rc).call(this,!1)}},Ac=function(){t(this,pc,"m",xc).call(this),this._informationManager.clear(),t(this,Bc,"f").clear(),t(this,Jc,"f").clear(),t(this,Yc,"f").clear(),t(this,eh,"f").clear(),t(this,ih,"f").clear()},xc=function(){this.connectionManager?.clear(),this.latestConnectionMessages.clear()},$c=function(e,i){if(ah.log({messageType:e,dataView:i}),"batteryLevel"===e){const e=i.getUint8(0);ah.log("received battery level",{batteryLevel:e}),t(this,pc,"m",Pc).call(this,e)}else if($e.includes(e))t(this,Hc,"f").parseMessage(e,i);else if(zs.includes(e))t(this,Jc,"f").parseMessage(e,i);else if(ji.includes(e))t(this,jc,"f").parseMessage(e,i);else if(uo.includes(e))t(this,Kc,"f").parseMessage(e,i);else if(sn.includes(e))t(this,Bc,"f").parseMessage(e,i);else if(Wn.includes(e))this._informationManager.parseMessage(e,i);else if(hs.includes(e))t(this,Vc,"f").parseMessage(e,i);else if(Yn.includes(e))t(this,Gc,"f").parseMessage(e,i);else if(Ca.includes(e))t(this,Yc,"f").parseMessage(e,i);else if(ti.includes(e))t(this,eh,"f").parseMessage(e,i);else{if(!xi.includes(e))throw Error(`uncaught messageType ${e}`);t(this,ih,"f").parseMessage(e,i)}this.latestConnectionMessages.set(e,i),e.startsWith("set")&&this.latestConnectionMessages.set(e.replace("set","get"),i),t(this,pc,"a",bc).call(this,"connectionMessage",{messageType:e,dataView:i})},Oc=function(){!this.isConnected&&t(this,pc,"a",Dc)&&t(this,pc,"m",Fc).call(this),"notConnected"!=this.connectionStatus&&t(this,pc,"m",Cc).call(this)},Pc=function(e){ah.assertTypeWithError(e,"number"),t(this,Nc,"f")!=e?(i(this,Nc,e,"f"),ah.log({updatedBatteryLevel:t(this,Nc,"f")}),t(this,pc,"a",bc).call(this,"batteryLevel",{batteryLevel:t(this,Nc,"f")})):ah.log(`duplicate batteryLevel assignment ${e}`)},Qc=function(){ah.assertWithError(this.canUpdateFirmware,"can't update firmware")},Zc=function(e){return t(this,pc,"m",Qc).call(this),t(this,Sc,"f").sendSmpMessage(e)},th=function(){ah.assertWithError(this.hasCamera,"camera not available")},sh=function(){ah.assertWithError(this.hasMicrophone,"microphone not available")},nh=function(){ah.assertWithError(AudioContext,"WebAudio is not supported")},Ic={value:!1},qc={value:!0};const mh=T("DevicePairPressureSensorDataManager",{log:!1});class ph{constructor(){hh.add(this),lh.set(this,{}),fh.set(this,new st),gh.set(this,new Ze),this.resetPressureRange()}resetPressureRange(){t(this,fh,"f").reset(),t(this,gh,"f").reset()}onDevicePressureData(e){const{pressure:i}=e.message,{side:s}=e.target;if(mh.log({pressure:i,side:s}),t(this,lh,"f")[s]=i,t(this,hh,"a",uh))return t(this,hh,"m",dh).call(this);mh.log("doesn't have all pressure data yet...")}}var vh;lh=new WeakMap,fh=new WeakMap,gh=new WeakMap,hh=new WeakSet,uh=function(){return Dn.every((e=>e in t(this,lh,"f")))},dh=function(){const e={scaledSum:0,normalizedSum:0,sensors:{left:[],right:[]}};return Dn.forEach((i=>{const s=t(this,lh,"f")[i];e.scaledSum+=s.scaledSum})),e.normalizedSum+=t(this,gh,"f").updateAndGetNormalization(e.scaledSum,!1),e.scaledSum>0&&(e.center={x:0,y:0},Dn.forEach((i=>{t(this,lh,"f")[i].sensors.forEach((t=>{const s={...t};s.weightedValue=t.scaledValue/e.scaledSum;let{x:n,y:a}=t.position;n/=2,"right"==i&&(n+=.5),s.position={x:n,y:a},e.center.x+=s.position.x*s.weightedValue,e.center.y+=s.position.y*s.weightedValue,e.sensors[i].push(s)}))})),e.normalizedCenter=t(this,fh,"f").updateAndGetNormalization(e.center,!1)),mh.log({devicePairPressure:e}),e};const wh=T("DevicePairSensorDataManager",{log:!1}),yh=["pressure","sensorData"];class bh{constructor(){vh.set(this,{}),this.pressureSensorDataManager=new ph}get dispatchEvent(){return this.eventDispatcher.dispatchEvent}resetPressureRange(){this.pressureSensorDataManager.resetPressureRange()}onDeviceSensorData(e){const{timestamp:i,sensorType:s}=e.message;let n;if(wh.log({sensorType:s,timestamp:i,event:e}),t(this,vh,"f")[s]||(t(this,vh,"f")[s]={}),t(this,vh,"f")[s][e.target.side]=i,"pressure"===s)n=this.pressureSensorDataManager.onDevicePressureData(e);else wh.log(`uncaught sensorType "${s}"`);if(n){const e=Object.assign({},t(this,vh,"f")[s]);this.dispatchEvent(s,{sensorType:s,timestamps:e,[s]:n}),this.dispatchEvent("sensorData",{sensorType:s,timestamps:e,[s]:n})}else wh.log("no value received")}}var Sh,Ch,Mh,Eh,kh,Dh,Wh,Th,Ih,_h,Lh,Uh,Rh,Fh,Ah,xh,$h,Oh,Bh;vh=new WeakMap;const Nh=T("DevicePair",{log:!1});function Ph(e){return`device${t=e,t[0].toUpperCase()+t.slice(1)}`;var t}const Vh=["isConnected",...yh,...rh.map((e=>Ph(e)))];class qh{constructor(e){Sh.add(this),Mh.set(this,void 0),Eh.set(this,new _(this,Vh)),Dh.set(this,void 0),Wh.set(this,void 0),Uh.set(this,{isConnected:t(this,Sh,"m",Fh).bind(this),sensorData:t(this,Sh,"m",$h).bind(this),getType:t(this,Sh,"m",Ah).bind(this)}),xh.set(this,new bh),i(this,Mh,e,"f"),t(this,xh,"f").eventDispatcher=t(this,Eh,"f")}get sides(){return Dn}get type(){return t(this,Mh,"f")}get addEventListener(){return t(this,Eh,"f").addEventListener}get removeEventListener(){return t(this,Eh,"f").removeEventListener}get waitForEvent(){return t(this,Eh,"f").waitForEvent}get removeEventListeners(){return t(this,Eh,"f").removeEventListeners}get removeAllEventListeners(){return t(this,Eh,"f").removeAllEventListeners}get left(){return t(this,Dh,"f")}get right(){return t(this,Wh,"f")}get isConnected(){return Dn.every((e=>this[e]?.isConnected))}get isPartiallyConnected(){return Dn.some((e=>this[e]?.isConnected))}get isHalfConnected(){return this.isPartiallyConnected&&!this.isConnected}assignDevice(e){if(!t(this,Sh,"m",Th).call(this,e))return void Nh.log(`device is incorrect type ${e.type} for ${this.type} devicePair`);const s=e.side,n=this[s];if(e!=n){switch(n&&t(this,Sh,"m",_h).call(this,n),t(this,Sh,"m",Ih).call(this,e),s){case"left":i(this,Dh,e,"f");break;case"right":i(this,Wh,e,"f")}return Nh.log(`assigned ${s} ${this.type} device`,e),this.resetPressureRange(),t(this,Sh,"a",kh).call(this,"isConnected",{isConnected:this.isConnected}),t(this,Sh,"a",kh).call(this,"deviceIsConnected",{device:e,isConnected:e.isConnected,side:s}),n}Nh.log("device already assigned")}async setSensorConfiguration(e){for(let t=0;t<Dn.length;t++){const i=Dn[t];this[i]?.isConnected&&await this[i].setSensorConfiguration(e)}}resetPressureRange(){Dn.forEach((e=>this[e]?.resetPressureRange())),t(this,xh,"f").resetPressureRange()}async triggerVibration(e,t){const i=Dn.map((i=>this[i]?.triggerVibration(e,t))).filter(Boolean);return Promise.allSettled(i)}static get insoles(){return t(this,Ch,"f",Oh)}static get gloves(){return t(this,Ch,"f",Bh)}}var zh,jh,Gh,Hh,Jh;Ch=qh,Mh=new WeakMap,Eh=new WeakMap,Dh=new WeakMap,Wh=new WeakMap,Uh=new WeakMap,xh=new WeakMap,Sh=new WeakSet,kh=function(){return t(this,Eh,"f").dispatchEvent},Th=function(e){switch(this.type){case"insoles":return e.isInsole;case"gloves":return e.isGlove}},Ih=function(e){Ja(e,t(this,Uh,"f")),rh.forEach((i=>{e.addEventListener(i,t(this,Sh,"m",Rh).bind(this))}))},_h=function(e){Ka(e,t(this,Uh,"f")),rh.forEach((i=>{e.removeEventListener(i,t(this,Sh,"m",Rh).bind(this))}))},Lh=function(e){const s=Dn.some((s=>{if(this[s]!=e)return!1;switch(Nh.log(`removing ${s} ${this.type} device`,e),Ka(e,t(this,Uh,"f")),s){case"left":i(this,Dh,void 0,"f");break;case"right":i(this,Wh,void 0,"f")}return!0}));return s&&t(this,Sh,"a",kh).call(this,"isConnected",{isConnected:this.isConnected}),s},Rh=function(e){const{type:i,target:s,message:n}=e;t(this,Sh,"a",kh).call(this,Ph(i),{...n,device:s,side:s.side})},Fh=function(e){t(this,Sh,"a",kh).call(this,"isConnected",{isConnected:this.isConnected})},Ah=function(e){const{target:i}=e;if(this[i.side]==i)return;t(this,Sh,"m",Lh).call(this,i)&&this.assignDevice(i)},$h=function(e){this.isConnected&&t(this,xh,"f").onDeviceSensorData(e)},Oh={value:new Ch("insoles")},Bh={value:new Ch("gloves")},Bo.AddEventListener("deviceConnected",(e=>{const{device:i}=e.message;i.isInsole&&t(Ch,Ch,"f",Oh).assignDevice(i),i.isGlove&&t(Ch,Ch,"f",Bh).assignDevice(i)}));const Kh=T("ClientConnectionManager",{log:!1});class Qh extends Ga{constructor(){super(...arguments),zh.add(this),jh.set(this,void 0),Gh.set(this,!1)}static get isSupported(){return n}static get type(){return"client"}get canUpdateFirmware(){return!1}get bluetoothId(){return t(this,jh,"f")}set bluetoothId(e){Kh.assertTypeWithError(e,"string"),t(this,jh,"f")!=e?i(this,jh,e,"f"):Kh.log("redundant bluetoothId assignment")}get isConnected(){return t(this,Gh,"f")}set isConnected(e){Kh.assertTypeWithError(e,"boolean"),t(this,Gh,"f")!=e?(i(this,Gh,e,"f"),this.status=t(this,Gh,"f")?"connected":"notConnected",this.isConnected&&t(this,zh,"m",Hh).call(this)):Kh.log("redundant newIsConnected assignment",e)}get isAvailable(){return this.client.isConnected}async connect(){await super.connect(),this.sendClientConnectMessage(this.subType)}async disconnect(){await super.disconnect(),this.sendClientDisconnectMessage()}get canReconnect(){return!0}async reconnect(){await super.reconnect(),this.sendClientConnectMessage()}async sendSmpMessage(e){super.sendSmpMessage(e),this.sendClientMessage({type:"smp",data:e})}async sendTxData(e){super.sendTxData(e),0!=e.byteLength&&this.sendClientMessage({type:"tx",data:e})}onClientMessage(e){Kh.log({dataView:e}),bt(e,rh,t(this,zh,"m",Jh).bind(this),null,!0),this.onMessagesReceived()}}var Zh,Xh,Yh,el,tl,il,sl,nl,al,rl,ol,cl,hl,ll,fl,gl,ul,dl,ml,pl,vl,wl,yl,bl;jh=new WeakMap,Gh=new WeakMap,zh=new WeakSet,Hh=function(){this.sendRequiredDeviceInformationMessage()},Jh=function(e,t){let i=0;switch(Kh.log({messageType:e},t),e){case"isConnected":const s=Boolean(t.getUint8(i++));Kh.log({isConnected:s}),this.isConnected=s;break;case"rx":this.parseRxMessage(t);break;default:this.onMessageReceived(e,t)}};const Sl=T("BaseClient",{log:!1}),Cl=["notConnected","connecting","connected","disconnecting","connectionStatus","isConnected","isScanningAvailable","isScanning","discoveredDevice","expiredDiscoveredDevice"];class Ml{constructor(){Zh.add(this),el.set(this,{}),tl.set(this,new _(this,Cl)),this._reconnectOnDisconnection=this.baseConstructor.ReconnectOnDisconnection,il.set(this,"notConnected"),al.set(this,[]),cl.set(this,!1),gl.set(this,!1),wl.set(this,{})}get baseConstructor(){return this.constructor}get devices(){return t(this,el,"f")}get addEventListener(){return t(this,tl,"f").addEventListener}get dispatchEvent(){return t(this,tl,"f").dispatchEvent}get removeEventListener(){return t(this,tl,"f").removeEventListener}get waitForEvent(){return t(this,tl,"f").waitForEvent}assertConnection(){Sl.assertWithError(this.isConnected,"notConnected")}assertDisconnection(){Sl.assertWithError(this.isDisconnected,"not disconnected")}static get ReconnectOnDisconnection(){return this._reconnectOnDisconnection}static set ReconnectOnDisconnection(e){Sl.assertTypeWithError(e,"boolean"),this._reconnectOnDisconnection=e}get reconnectOnDisconnection(){return this._reconnectOnDisconnection}set reconnectOnDisconnection(e){Sl.assertTypeWithError(e,"boolean"),this._reconnectOnDisconnection=e}get _connectionStatus(){return t(this,il,"f")}set _connectionStatus(e){switch(Sl.assertTypeWithError(e,"string"),Sl.log({newConnectionStatus:e}),i(this,il,e,"f"),this.dispatchEvent("connectionStatus",{connectionStatus:this.connectionStatus}),this.dispatchEvent(this.connectionStatus,{}),e){case"connected":case"notConnected":this.dispatchEvent("isConnected",{isConnected:this.isConnected}),this.isConnected||t(this,Zh,"m",Yh).call(this)}}get connectionStatus(){return this._connectionStatus}_sendRequiredMessages(){Sl.log("sending required messages",t(this,al,"f")),this.sendServerMessage(...t(this,Zh,"a",nl))}parseMessage(e){Sl.log("parseMessage",{dataView:e}),bt(e,Po,t(this,Zh,"m",ol).bind(this),null,!0),t(this,Zh,"m",rl).call(this)}get isScanningAvailable(){return t(this,Zh,"a",hl)}requestIsScanningAvailable(){this.sendServerMessage("isScanningAvailable")}get isScanning(){return t(this,Zh,"a",ul)}startScan(){t(this,Zh,"m",vl).call(this),this.sendServerMessage("startScan")}stopScan(){t(this,Zh,"m",pl).call(this),this.sendServerMessage("stopScan")}toggleScan(){t(this,Zh,"m",fl).call(this),this.isScanning?this.stopScan():this.startScan()}get discoveredDevices(){return t(this,wl,"f")}onDiscoveredDevice(e){Sl.log({discoveredDevice:e}),t(this,wl,"f")[e.bluetoothId]=e,this.dispatchEvent("discoveredDevice",{discoveredDevice:e})}requestDiscoveredDevices(){this.sendServerMessage({type:"discoveredDevices"})}connectToDevice(e,t){return this.requestConnectionToDevice(e,t)}requestConnectionToDevice(e,i){this.assertConnection(),Sl.assertTypeWithError(e,"string");const s=t(this,Zh,"m",bl).call(this,e);return i?s.connect({type:"client",subType:i}):s.connect(),s}sendConnectToDeviceMessage(e,t){t?this.sendServerMessage({type:"connectToDevice",data:z(j(e),Ba.indexOf(t))}):this.sendServerMessage({type:"connectToDevice",data:e})}createDevice(e){const i=new ch,s=t(this,wl,"f")[e],n=new Qh;return n.discoveredDevice=Object.assign({},s),n.client=this,n.bluetoothId=e,n.sendClientMessage=this.sendDeviceMessage.bind(this,e),n.sendRequiredDeviceInformationMessage=this.sendRequiredDeviceInformationMessage.bind(this,e),n.sendClientConnectMessage=this.sendConnectToDeviceMessage.bind(this,e),n.sendClientDisconnectMessage=this.sendDisconnectFromDeviceMessage.bind(this,e),i.connectionManager=n,i}onConnectedBluetoothDeviceIds(e){Sl.log({bluetoothIds:e}),e.forEach((e=>{const i=t(this,Zh,"m",bl).call(this,e);i.connectionManager.isConnected=!0,Bo._CheckDeviceAvailability(i)}))}disconnectFromDevice(e){this.requestDisconnectionFromDevice(e)}requestDisconnectionFromDevice(e){this.assertConnection(),Sl.assertTypeWithError(e,"string");const t=this.devices[e];return Sl.assertWithError(t,`no device found with id ${e}`),t.disconnect(),t}sendDisconnectFromDeviceMessage(e){this.sendServerMessage({type:"disconnectFromDevice",data:e})}sendDeviceMessage(e,...t){this.sendServerMessage({type:"deviceMessage",data:[e,zo(...t)]})}sendRequiredDeviceInformationMessage(e){this.sendServerMessage({type:"requiredDeviceInformation",data:[e]})}}var El,kl,Dl,Wl,Tl,Il,_l,Ll,Ul,Rl,Fl,Al,xl;Xh=Ml,el=new WeakMap,tl=new WeakMap,il=new WeakMap,al=new WeakMap,cl=new WeakMap,gl=new WeakMap,wl=new WeakMap,Zh=new WeakSet,Yh=function(){i(this,Zh,!1,"a",ll),i(this,Zh,!1,"a",dl);for(const e in t(this,el,"f")){t(this,el,"f")[e].connectionManager.isConnected=!1}t(this,al,"f").length=0},nl=function(){return t(Xh,Xh,"f",sl)},rl=function(){"connecting"==this.connectionStatus&&(Sl.log("checking if fully connected..."),t(this,al,"f").includes("isScanningAvailable")?!this.isScanningAvailable||t(this,al,"f").includes("isScanning")?(Sl.log("fully connected"),this._connectionStatus="connected"):Sl.log("not fully connected - didn't receive isScanning"):Sl.log("not fully connected - didn't receive isScanningAvailable"))},ol=function(e,s){let n=0;switch(Sl.log({messageType:e},s),e){case"isScanningAvailable":{const e=Boolean(s.getUint8(n++));Sl.log({isScanningAvailable:e}),i(this,Zh,e,"a",ll)}break;case"isScanning":{const e=Boolean(s.getUint8(n++));Sl.log({isScanning:e}),i(this,Zh,e,"a",dl)}break;case"discoveredDevice":{const{string:e}=yt(s,n);Sl.log({discoveredDeviceString:e});const t=JSON.parse(e);Sl.log({discoveredDevice:t}),this.onDiscoveredDevice(t)}break;case"expiredDiscoveredDevice":{const{string:e}=yt(s,n);t(this,Zh,"m",yl).call(this,e)}break;case"connectedDevices":{if(0==s.byteLength)break;const{string:e}=yt(s,n);Sl.log({connectedBluetoothDeviceIdStrings:e});const t=JSON.parse(e).connectedDevices;Sl.log({connectedBluetoothDeviceIds:t}),this.onConnectedBluetoothDeviceIds(t)}break;case"deviceMessage":{const{string:e,byteOffset:i}=yt(s,n);n=i;const a=t(this,el,"f")[e];Sl.assertWithError(a,`no device found for id ${e}`);const r=a.connectionManager,o=G(s,n);r.onClientMessage(o)}break;default:Sl.error(`uncaught messageType "${e}"`)}"connecting"==this.connectionStatus&&t(this,al,"f").push(e)},hl=function(){return t(this,cl,"f")},ll=function(e){Sl.assertTypeWithError(e,"boolean"),i(this,cl,e,"f"),this.dispatchEvent("isScanningAvailable",{isScanningAvailable:this.isScanningAvailable}),this.isScanningAvailable&&t(this,Zh,"m",ml).call(this)},fl=function(){this.assertConnection(),Sl.assertWithError(this.isScanningAvailable,"scanning is not available")},ul=function(){return t(this,gl,"f")},dl=function(e){Sl.assertTypeWithError(e,"boolean"),i(this,gl,e,"f"),this.dispatchEvent("isScanning",{isScanning:this.isScanning})},ml=function(){this.sendServerMessage("isScanning")},pl=function(){Sl.assertWithError(this.isScanning,"is not scanning")},vl=function(){Sl.assertWithError(!this.isScanning,"is already scanning")},yl=function(e){Sl.log({expiredBluetoothDeviceId:e});const i=t(this,wl,"f")[e];i?(Sl.log({expiredDiscoveredDevice:i}),delete t(this,wl,"f")[e],this.dispatchEvent("expiredDiscoveredDevice",{discoveredDevice:i})):Sl.warn(`no discoveredDevice found with id "${e}"`)},bl=function(e){let i=t(this,el,"f")[e];return i||(i=this.createDevice(e),t(this,el,"f")[e]=i),i},Ml._reconnectOnDisconnection=!0,sl={value:["isScanningAvailable","discoveredDevices","connectedDevices"]};const $l=T("WebSocketClient",{log:!1});kl=new WeakMap,Wl=new WeakMap,Fl=new WeakMap,El=new WeakSet,Dl=function(...e){this.sendMessage(Ho(...e))},Tl=function(e){$l.log("webSocket.open",e),t(this,Fl,"f").start(),this._sendRequiredMessages()},Il=async function(e){$l.log("webSocket.message",e);const i=await e.data.arrayBuffer(),s=new DataView(i);t(this,El,"m",Ul).call(this,s)},_l=function(e){$l.log("webSocket.close",e),this._connectionStatus="notConnected",Object.entries(this.devices).forEach((([e,t])=>{t.connectionManager.isConnected=!1})),t(this,Fl,"f").stop(),this.reconnectOnDisconnection&&setTimeout((()=>{this.reconnect()}),3e3)},Ll=function(e){$l.error("webSocket.error",e)},Ul=function(e){bt(e,Go,t(this,El,"m",Rl).bind(this),null,!0)},Rl=function(e,i){switch(e){case"ping":t(this,El,"m",xl).call(this);break;case"pong":break;case"serverMessage":this.parseMessage(i);break;default:$l.error(`uncaught messageType "${e}"`)}},Al=function(){t(this,El,"m",Dl).call(this,"ping")},xl=function(){t(this,El,"m",Dl).call(this,"pong")};const Ol={addEventListeners:Ja,removeEventListeners:Ka},Bl={throttle:function(e,t,i=!1){let s=0,n=null,a=null;return function(...r){const o=Date.now(),c=t-(o-s);c<=0?(n&&(clearTimeout(n),n=null),s=o,e(...r)):i&&(a=r,n||(n=setTimeout((()=>{s=Date.now(),n=null,a&&(e(...a),a=null)}),c)))}},debounce:function(e,t,i=!1){let s=null;return function(...n){const a=i&&!s;s&&clearTimeout(s),s=setTimeout((()=>{s=null,i||e(...n)}),t),a&&e(...n)}}};e.CameraCommands=Zt,e.CameraConfigurationTypes=ei,e.ContinuousSensorTypes=zi,e.DefaultNumberOfPressureSensors=8,e.Device=ch,e.DeviceManager=Bo,e.DevicePair=qh,e.DevicePairTypes=["insoles","gloves"],e.DeviceTypes=kn,e.Environment=y,e.EventUtils=Ol,e.FileTransferDirections=["sending","receiving"],e.FileTypes=Oe,e.MaxNameLength=30,e.MaxNumberOfVibrationWaveformEffectSegments=8,e.MaxNumberOfVibrationWaveformSegments=20,e.MaxSensorRate=65535,e.MaxVibrationWaveformEffectSegmentDelay=ia,e.MaxVibrationWaveformEffectSegmentLoopCount=3,e.MaxVibrationWaveformEffectSequenceLoopCount=6,e.MaxVibrationWaveformSegmentDuration=ta,e.MaxWifiPasswordLength=64,e.MaxWifiSSIDLength=32,e.MicrophoneCommands=Ui,e.MicrophoneConfigurationTypes=Fi,e.MicrophoneConfigurationValues=$i,e.MinNameLength=2,e.MinWifiPasswordLength=8,e.MinWifiSSIDLength=1,e.RangeHelper=Ze,e.SensorRateStep=5,e.SensorTypes=qi,e.Sides=Dn,e.TfliteSensorTypes=Js,e.TfliteTasks=Hs,e.ThrottleUtils=Bl,e.VibrationLocations=Zn,e.VibrationTypes=Xn,e.VibrationWaveformEffects=_n,e.WebSocketClient=class extends Ml{constructor(){super(...arguments),El.add(this),kl.set(this,void 0),Wl.set(this,{open:t(this,El,"m",Tl).bind(this),message:t(this,El,"m",Il).bind(this),close:t(this,El,"m",_l).bind(this),error:t(this,El,"m",Ll).bind(this)}),Fl.set(this,new A(t(this,El,"m",Al).bind(this),3e4))}get webSocket(){return t(this,kl,"f")}set webSocket(e){t(this,kl,"f")!=e?($l.log("assigning webSocket",e),t(this,kl,"f")&&Ka(t(this,kl,"f"),t(this,Wl,"f")),Ja(e,t(this,Wl,"f")),i(this,kl,e,"f"),$l.log("assigned webSocket")):$l.log("redundant webSocket assignment")}get readyState(){return this.webSocket?.readyState}get isConnected(){return this.readyState==WebSocket.OPEN}get isDisconnected(){return this.readyState==WebSocket.CLOSED}connect(e=`wss://${location.host}`){this.webSocket&&this.assertDisconnection(),this._connectionStatus="connecting",this.webSocket=new WebSocket(e)}disconnect(){this.assertConnection(),this.reconnectOnDisconnection&&(this.reconnectOnDisconnection=!1,this.webSocket.addEventListener("close",(()=>{this.reconnectOnDisconnection=!0}),{once:!0})),this._connectionStatus="disconnecting",this.webSocket.close()}reconnect(){this.assertDisconnection(),this.connect(this.webSocket.url)}toggleConnection(e){this.isConnected?this.disconnect():e&&this.webSocket?.url==e?this.reconnect():this.connect(e)}sendMessage(e){this.assertConnection(),t(this,kl,"f").send(e),t(this,Fl,"f").restart()}sendServerMessage(...e){this.sendMessage(Ho({type:"serverMessage",data:qo(...e)}))}},e.setAllConsoleLevelFlags=function(e){W.setAllLevelFlags(e)},e.setConsoleLevelFlagsForType=function(e,t){W.setLevelFlagsForType(e,t)}}));
|
|
6
6
|
//# sourceMappingURL=brilliantsole.min.js.map
|