brilliantsole 0.0.27 → 0.0.28

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (167) hide show
  1. package/assets/3d/anchor.glb +0 -0
  2. package/assets/3d/coin.glb +0 -0
  3. package/assets/3d/glasses.glb +0 -0
  4. package/assets/audio/bounceMedium.wav +0 -0
  5. package/assets/audio/bounceStrong.wav +0 -0
  6. package/assets/audio/bounceWeak.wav +0 -0
  7. package/assets/audio/coin.wav +0 -0
  8. package/assets/audio/getUp.wav +0 -0
  9. package/assets/audio/grab.wav +0 -0
  10. package/assets/audio/kick.wav +0 -0
  11. package/assets/audio/platterFadeIn old.wav +0 -0
  12. package/assets/audio/platterFadeIn.wav +0 -0
  13. package/assets/audio/platterFadeOut.wav +0 -0
  14. package/assets/audio/punch.wav +0 -0
  15. package/assets/audio/punchSqueak.wav +0 -0
  16. package/assets/audio/purr.wav +0 -0
  17. package/assets/audio/purrFadeOut.wav +0 -0
  18. package/assets/audio/release.wav +0 -0
  19. package/assets/audio/splat.wav +0 -0
  20. package/assets/audio/stomp.wav +0 -0
  21. package/build/brilliantsole.cjs +2627 -775
  22. package/build/brilliantsole.cjs.map +1 -1
  23. package/build/brilliantsole.js +2273 -721
  24. package/build/brilliantsole.js.map +1 -1
  25. package/build/brilliantsole.ls.js +2096 -535
  26. package/build/brilliantsole.ls.js.map +1 -1
  27. package/build/brilliantsole.min.js +1 -1
  28. package/build/brilliantsole.min.js.map +1 -1
  29. package/build/brilliantsole.module.d.ts +235 -65
  30. package/build/brilliantsole.module.js +2266 -722
  31. package/build/brilliantsole.module.js.map +1 -1
  32. package/build/brilliantsole.module.min.d.ts +235 -65
  33. package/build/brilliantsole.module.min.js +1 -1
  34. package/build/brilliantsole.module.min.js.map +1 -1
  35. package/build/brilliantsole.node.module.d.ts +229 -62
  36. package/build/brilliantsole.node.module.js +2619 -776
  37. package/build/brilliantsole.node.module.js.map +1 -1
  38. package/build/dts/BS-output.d.ts +10 -0
  39. package/build/dts/BS.d.ts +20 -8
  40. package/build/dts/CameraManager.d.ts +72 -0
  41. package/build/dts/Device.d.ts +46 -13
  42. package/build/dts/DeviceInformationManager.d.ts +4 -4
  43. package/build/dts/DeviceManager.d.ts +2 -0
  44. package/build/dts/FileTransferManager.d.ts +18 -8
  45. package/build/dts/InformationManager.d.ts +2 -0
  46. package/build/dts/TfliteManager.d.ts +22 -2
  47. package/build/dts/WifiManager.d.ts +61 -0
  48. package/build/dts/connection/BaseConnectionManager.d.ts +35 -3
  49. package/build/dts/connection/ClientConnectionManager.d.ts +7 -2
  50. package/build/dts/connection/bluetooth/NobleConnectionManager.d.ts +2 -1
  51. package/build/dts/connection/bluetooth/WebBluetoothConnectionManager.d.ts +1 -0
  52. package/build/dts/connection/bluetooth/bluetoothUUIDs.d.ts +2 -2
  53. package/build/dts/connection/udp/UDPConnectionManager.d.ts +28 -0
  54. package/build/dts/connection/webSocket/WebSocketConnectionManager.d.ts +25 -0
  55. package/build/dts/devicePair/DevicePair.d.ts +5 -5
  56. package/build/dts/scanner/BaseScanner.d.ts +4 -1
  57. package/build/dts/scanner/NobleScanner.d.ts +2 -1
  58. package/build/dts/sensor/MotionSensorDataManager.d.ts +5 -2
  59. package/build/dts/sensor/SensorDataManager.d.ts +5 -4
  60. package/build/dts/server/BaseClient.d.ts +5 -3
  61. package/build/dts/server/ServerUtils.d.ts +1 -1
  62. package/build/dts/server/websocket/WebSocketUtils.d.ts +1 -1
  63. package/build/dts/utils/Console.d.ts +2 -0
  64. package/build/dts/utils/ThrottleUtils.d.ts +2 -0
  65. package/build/dts/vibration/VibrationManager.d.ts +19 -2
  66. package/build/index.d.ts +232 -62
  67. package/build/index.node.d.ts +226 -59
  68. package/examples/3d/scene.html +19 -5
  69. package/examples/3d-generic/index.html +144 -0
  70. package/examples/3d-generic/script.js +266 -0
  71. package/examples/basic/index.html +211 -16
  72. package/examples/basic/script.js +731 -105
  73. package/examples/edge-impulse/script.js +135 -44
  74. package/examples/edge-impulse-test/README.md +11 -0
  75. package/examples/edge-impulse-test/edge-impulse-standalone.js +7228 -0
  76. package/examples/edge-impulse-test/edge-impulse-standalone.wasm +0 -0
  77. package/examples/edge-impulse-test/index.html +75 -0
  78. package/examples/edge-impulse-test/run-impulse.js +135 -0
  79. package/examples/edge-impulse-test/script.js +200 -0
  80. package/examples/gloves/edge-impulse-standalone.js +7228 -0
  81. package/examples/gloves/edge-impulse-standalone.wasm +0 -0
  82. package/examples/gloves/index.html +4 -1
  83. package/examples/gloves/run-impulse.js +135 -0
  84. package/examples/gloves/script.js +367 -51
  85. package/examples/graph/script.js +94 -37
  86. package/examples/punch/index.html +135 -0
  87. package/examples/punch/punch.tflite +0 -0
  88. package/examples/punch/script.js +169 -0
  89. package/examples/server/index.html +98 -22
  90. package/examples/server/script.js +317 -109
  91. package/examples/ukaton-firmware-update/merged-firmware.bin +0 -0
  92. package/examples/utils/aframe/aframe-master.min.js +2 -0
  93. package/examples/utils/aframe/bs-vibration.js +150 -0
  94. package/examples/utils/aframe/force-pushable.js +80 -0
  95. package/examples/utils/aframe/grabbable-anchor.js +46 -0
  96. package/examples/utils/aframe/grabbable-listener.js +31 -0
  97. package/examples/utils/aframe/grabbable-physics-body.js +190 -0
  98. package/examples/utils/aframe/grow-shrink.js +25 -0
  99. package/examples/utils/aframe/hand-punch.js +119 -0
  100. package/examples/utils/aframe/my-obb-collider.js +293 -0
  101. package/examples/utils/aframe/occlude-hand-tracking-controls.js +47 -0
  102. package/examples/utils/aframe/occlude-mesh.js +42 -0
  103. package/examples/utils/aframe/palm-up-detector.js +47 -0
  104. package/examples/utils/aframe/shadow-material.js +20 -0
  105. package/examples/utils/aframe/soft-shadow-light.js +9 -0
  106. package/examples/webxr-2/assets/3d/soccerBall.glb +0 -0
  107. package/examples/webxr-2/assets/audio/shellBounce.wav +0 -0
  108. package/examples/webxr-2/assets/audio/shellHit.wav +0 -0
  109. package/examples/webxr-2/assets/audio/shellKick.wav +0 -0
  110. package/examples/webxr-2/assets/audio/soccerBounce.wav +0 -0
  111. package/examples/webxr-2/assets/audio/soccerKick.mp3 +0 -0
  112. package/examples/webxr-2/assets/images/shellTexture.png +0 -0
  113. package/examples/webxr-2/components/bs-ankle.js +337 -0
  114. package/examples/webxr-2/components/coin.js +84 -0
  115. package/examples/webxr-2/components/custom-wrap.js +17 -0
  116. package/examples/webxr-2/components/goomba.js +3250 -0
  117. package/examples/webxr-2/components/init-shell-material.js +215 -0
  118. package/examples/webxr-2/components/platter.js +172 -0
  119. package/examples/webxr-2/components/shell.js +374 -0
  120. package/examples/webxr-2/components/soccer-ball.js +250 -0
  121. package/examples/webxr-2/components/squashed-goomba.js +249 -0
  122. package/examples/webxr-2/edge-impulse-standalone.js +7228 -0
  123. package/examples/webxr-2/edge-impulse-standalone.wasm +0 -0
  124. package/examples/webxr-2/index.html +996 -0
  125. package/examples/webxr-2/kick.tflite +0 -0
  126. package/examples/webxr-2/kick2.tflite +0 -0
  127. package/examples/webxr-2/run-impulse.js +135 -0
  128. package/examples/webxr-2/script.js +384 -0
  129. package/package.json +2 -1
  130. package/src/.prettierrc +4 -0
  131. package/src/BS.ts +70 -8
  132. package/src/CameraManager.ts +499 -0
  133. package/src/Device.ts +581 -86
  134. package/src/DeviceInformationManager.ts +19 -10
  135. package/src/DeviceManager.ts +85 -25
  136. package/src/FileTransferManager.ts +145 -20
  137. package/src/InformationManager.ts +40 -15
  138. package/src/TfliteManager.ts +171 -25
  139. package/src/WifiManager.ts +323 -0
  140. package/src/connection/BaseConnectionManager.ts +128 -30
  141. package/src/connection/ClientConnectionManager.ts +34 -10
  142. package/src/connection/bluetooth/BluetoothConnectionManager.ts +8 -2
  143. package/src/connection/bluetooth/NobleConnectionManager.ts +147 -41
  144. package/src/connection/bluetooth/WebBluetoothConnectionManager.ts +99 -34
  145. package/src/connection/bluetooth/bluetoothUUIDs.ts +40 -13
  146. package/src/connection/udp/UDPConnectionManager.ts +356 -0
  147. package/src/connection/websocket/WebSocketConnectionManager.ts +282 -0
  148. package/src/devicePair/DevicePair.ts +95 -25
  149. package/src/devicePair/DevicePairPressureSensorDataManager.ts +27 -7
  150. package/src/scanner/BaseScanner.ts +49 -11
  151. package/src/scanner/NobleScanner.ts +76 -14
  152. package/src/sensor/MotionSensorDataManager.ts +21 -6
  153. package/src/sensor/PressureSensorDataManager.ts +37 -8
  154. package/src/sensor/SensorConfigurationManager.ts +73 -22
  155. package/src/sensor/SensorDataManager.ts +104 -23
  156. package/src/server/BaseClient.ts +150 -36
  157. package/src/server/BaseServer.ts +50 -2
  158. package/src/server/ServerUtils.ts +39 -9
  159. package/src/server/udp/UDPServer.ts +73 -22
  160. package/src/server/udp/UDPUtils.ts +9 -2
  161. package/src/server/websocket/WebSocketClient.ts +27 -7
  162. package/src/server/websocket/WebSocketUtils.ts +4 -2
  163. package/src/utils/Console.ts +62 -9
  164. package/src/utils/ParseUtils.ts +24 -5
  165. package/src/utils/ThrottleUtils.ts +62 -0
  166. package/src/utils/Timer.ts +1 -1
  167. package/src/vibration/VibrationManager.ts +166 -40
@@ -2,5 +2,5 @@
2
2
  * @copyright Zack Qattan 2024
3
3
  * @license MIT
4
4
  */
5
- function e(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 t(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 s=!1,i="undefined"!=typeof window&&void 0!==window?.document,n="undefined"!=typeof process&&null!=process?.versions?.node,r=i&&navigator.userAgent||"";let a=!1;i?a=Boolean(navigator.bluetooth):n&&(a=!0);const o=i&&/Bluefy/i.test(r),c=i&&/WebBLE/i.test(r),h=i&&/Android/i.test(r),l=i&&/Safari/i.test(r)&&!/Chrome/i.test(r),g=i&&/iPad|iPhone|iPod/i.test(r),f=i&&/Macintosh/i.test(r),u=!i&&!n&&"undefined"!=typeof global&&"undefined"!=typeof Studio;var d,m,p,v,w=Object.freeze({__proto__:null,isAndroid:h,get isBluetoothSupported(){return a},isIOS:g,isInBluefy:o,isInBrowser:i,isInDev:s,isInLensStudio:u,isInNode:n,isInProduction:!0,isInWebBLE:c,isMac:f,isSafari:l});if(u){const e=function(...e){Studio.log(e.map((e=>new String(e))).join(","))};(v={}).log=e,v.warn=e.bind(v,"WARNING"),v.error=e.bind(v,"ERROR")}else v=console;if(!v.assert){const e=(e,...t)=>{e||v.warn(...t)};v.assert=e}if(!v.table){const e=(...e)=>{v.log(...e)};v.table=e}function y(){}const b=v.log.bind(v),S=v.warn.bind(v),E=v.error.bind(v),M=v.table.bind(v),C=v.assert.bind(v);class D{constructor(t){if(p.set(this,{log:s,warn:s,assert:!0,error:!0,table:!0}),e(d,d,"f",m)[t])throw new Error(`"${t}" console already exists`);e(d,d,"f",m)[t]=this}setLevelFlags(t){Object.assign(e(this,p,"f"),t)}static setLevelFlagsForType(t,s){if(!e(this,d,"f",m)[t])throw new Error(`no console found with type "${t}"`);e(this,d,"f",m)[t].setLevelFlags(s)}static setAllLevelFlags(t){for(const s in e(this,d,"f",m))e(this,d,"f",m)[s].setLevelFlags(t)}static create(t,s){return e(this,d,"f",m)[t]||new d(t)}get log(){return e(this,p,"f").log?b:y}get warn(){return e(this,p,"f").warn?S:y}get error(){return e(this,p,"f").error?E:y}get assert(){return e(this,p,"f").assert?C:y}get table(){return e(this,p,"f").table?M:y}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}"`)}}function k(e,t){return D.create(e,t)}function T(e,t){D.setLevelFlagsForType(e,t)}function _(e){D.setAllLevelFlags(e)}d=D,p=new WeakMap,m={value:{}};const W=k("EventDispatcher",{log:!1});class I{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&&W.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]=[],W.log(`creating "${e}" listeners array`,this.listeners[e]));this.listeners[e].find((e=>e.listener==t&&e.once==s.once))?W.log("already added listener"):(W.log(`adding "${e}" listener`,t,s),this.listeners[e].push({listener:t,once:s.once}),W.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]&&(W.log(`removing "${e}" listener...`,t),this.listeners[e].forEach((s=>{s.listener===t&&(W.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]&&(W.log(`removing "${e}" listeners...`),this.listeners[e]=[])}removeAllEventListeners(){W.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||(W.log(`dispatching "${e}" listener`,s),s.listener({type:e,target:this.target,message:t}),s.once&&(W.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 R=k("Timer",{log:!1});class A{get callback(){return e(this,L,"f")}set callback(e){R.assertTypeWithError(e,"function"),R.log({newCallback:e}),t(this,L,e,"f"),this.isRunning&&this.restart()}get interval(){return e(this,U,"f")}set interval(e){R.assertTypeWithError(e,"number"),R.assertWithError(e>0,"interval must be above 0"),R.log({newInterval:e}),t(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!=e(this,F,"f")}start(s=!1){this.isRunning?R.log("interval already running"):(R.log("starting interval"),t(this,F,setInterval(e(this,L,"f"),e(this,U,"f")),"f"),s&&e(this,L,"f").call(this))}stop(){this.isRunning?(R.log("stopping interval"),clearInterval(e(this,F,"f")),t(this,F,void 0,"f")):R.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,k("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,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,z=k("ArrayBufferUtils",{log:!1});function j(...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 G(e)}if(e instanceof Array){return j(...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 G(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 G(e){const t=P.encode(e);return j(t.byteLength,t)}function q(e,t,s){let i;return null!=s&&(i=e.byteOffset+t+s),z.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 Q,K,Z,X,Y,ee,te,se,ie,ne,re,ae,oe,ce,he,le,ge,fe,ue,de,me,pe,ve,we,ye,be,Se,Ee,Me,Ce,De,ke,Te,_e,We,Ie,Le,Ue;const Fe=k("FileTransferManager",{log:!1}),Re=["maxFileLength","getFileType","setFileType","getFileLength","setFileLength","getFileChecksum","setFileChecksum","setFileTransferCommand","fileTransferStatus","getFileBlock","setFileBlock","fileBytesTransferred"],Ae=["tflite"],xe=["idle","sending","receiving"],$e=["startSend","startReceive","cancel"],Oe=["sending","receiving"],Be=[...Re,"fileTransferProgress","fileTransferComplete","fileReceived"];class Ne{constructor(){Q.add(this),ie.set(this,K.MaxLength),oe.set(this,void 0),ge.set(this,0),me.set(this,0),be.set(this,"idle"),De.set(this,[]),Te.set(this,void 0),_e.set(this,0),Ue.set(this,!1),J(this)}get addEventListener(){return this.eventDispatcher.addEventListener}get removeEventListener(){return this.eventDispatcher.removeEventListener}get waitForEvent(){return this.eventDispatcher.waitForEvent}static get MaxLength(){return e(this,K,"f",se)}get maxLength(){return e(this,ie,"f")}get type(){return e(this,oe,"f")}get length(){return e(this,ge,"f")}get checksum(){return e(this,me,"f")}get status(){return e(this,be,"f")}parseMessage(t,s){switch(Fe.log({messageType:t}),t){case"maxFileLength":e(this,Q,"m",ne).call(this,s);break;case"getFileType":case"setFileType":e(this,Q,"m",ce).call(this,s);break;case"getFileLength":case"setFileLength":e(this,Q,"m",fe).call(this,s);break;case"getFileChecksum":case"setFileChecksum":e(this,Q,"m",pe).call(this,s);break;case"fileTransferStatus":e(this,Q,"m",Se).call(this,s);break;case"getFileBlock":e(this,Q,"m",ke).call(this,s);break;case"fileBytesTransferred":e(this,Q,"m",Le).call(this,s);break;default:throw Error(`uncaught messageType ${t}`)}}async send(t,s){e(this,Q,"m",Me).call(this),e(this,Q,"m",X).call(this,t);const i=await H(s),n=[];n.push(e(this,Q,"m",le).call(this,t,!1));const r=i.byteLength;n.push(e(this,Q,"m",de).call(this,r,!1));const a=O(i);n.push(e(this,Q,"m",we).call(this,a,!1)),n.push(e(this,Q,"m",ye).call(this,"startSend",!1)),this.sendMessage(),await Promise.all(n),await e(this,Q,"m",We).call(this,i)}async receive(t){e(this,Q,"m",Me).call(this),e(this,Q,"m",X).call(this,t),await e(this,Q,"m",le).call(this,t),await e(this,Q,"m",ye).call(this,"startReceive")}async cancel(){e(this,Q,"m",Ce).call(this),Fe.log("cancelling file transfer..."),await e(this,Q,"m",ye).call(this,"cancel")}get isServerSide(){return e(this,Ue,"f")}set isServerSide(s){e(this,Ue,"f")!=s?(Fe.log({newIsServerSide:s}),t(this,Ue,s,"f")):Fe.log("redundant isServerSide assignment")}}K=Ne,ie=new WeakMap,oe=new WeakMap,ge=new WeakMap,me=new WeakMap,be=new WeakMap,De=new WeakMap,Te=new WeakMap,_e=new WeakMap,Ue=new WeakMap,Q=new WeakSet,Z=function(){return this.eventDispatcher.dispatchEvent},X=function(e){Fe.assertEnumWithError(e,Ae)},Y=function(e){Fe.assertWithError(e in Ae,`invalid typeEnum ${e}`)},ee=function(e){Fe.assertWithError(e in xe,`invalid statusEnum ${e}`)},te=function(e){Fe.assertEnumWithError(e,$e)},ne=function(t){Fe.log("parseFileMaxLength",t);const s=t.getUint32(0,!0);Fe.log(`maxLength: ${s/1024}kB`),e(this,Q,"m",re).call(this,s)},re=function(s){Fe.log({maxLength:s}),t(this,ie,s,"f"),e(this,Q,"a",Z).call(this,"maxFileLength",{maxFileLength:s})},ae=function(e){Fe.assertWithError(e<=this.maxLength,`file length ${e}kB too large - must be ${this.maxLength}kB or less`)},ce=function(t){Fe.log("parseFileType",t);const s=t.getUint8(0);e(this,Q,"m",Y).call(this,s);const i=Ae[s];e(this,Q,"m",he).call(this,i)},he=function(s){Fe.log({fileTransferType:s}),t(this,oe,s,"f"),e(this,Q,"a",Z).call(this,"getFileType",{fileType:s})},le=async function(t,s){if(e(this,Q,"m",X).call(this,t),this.type==t)return void Fe.log(`redundant type assignment ${t}`);const i=this.waitForEvent("getFileType"),n=Ae.indexOf(t);this.sendMessage([{type:"setFileType",data:Uint8Array.from([n]).buffer}],s),await i},fe=function(t){Fe.log("parseFileLength",t);const s=t.getUint32(0,!0);e(this,Q,"m",ue).call(this,s)},ue=function(s){Fe.log(`length: ${s/1024}kB`),t(this,ge,s,"f"),e(this,Q,"a",Z).call(this,"getFileLength",{fileLength:s})},de=async function(t,s){if(Fe.assertTypeWithError(t,"number"),e(this,Q,"m",ae).call(this,t),this.length==t)return void Fe.log(`redundant length assignment ${t}`);const i=this.waitForEvent("getFileLength"),n=new DataView(new ArrayBuffer(4));n.setUint32(0,t,!0),this.sendMessage([{type:"setFileLength",data:n.buffer}],s),await i},pe=function(t){Fe.log("checksum",t);const s=t.getUint32(0,!0);e(this,Q,"m",ve).call(this,s)},ve=function(s){Fe.log({checksum:s}),t(this,me,s,"f"),e(this,Q,"a",Z).call(this,"getFileChecksum",{fileChecksum:s})},we=async function(e,t){if(Fe.assertTypeWithError(e,"number"),this.checksum==e)return void Fe.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},ye=async function(t,s){e(this,Q,"m",te).call(this,t);const i=this.waitForEvent("fileTransferStatus");Fe.log(`setting command ${t}`);const n=$e.indexOf(t);this.sendMessage([{type:"setFileTransferCommand",data:Uint8Array.from([n]).buffer}],s),await i},Se=function(t){Fe.log("parseFileStatus",t);const s=t.getUint8(0);e(this,Q,"m",ee).call(this,s);const i=xe[s];e(this,Q,"m",Ee).call(this,i)},Ee=function(s){Fe.log({status:s}),t(this,be,s,"f"),e(this,Q,"a",Z).call(this,"fileTransferStatus",{fileTransferStatus:s}),e(this,De,"f").length=0},Me=function(){Fe.assertWithError("idle"==e(this,be,"f"),"status is not idle")},Ce=function(){Fe.assertWithError("idle"!=e(this,be,"f"),"status is idle")},ke=async function(t){Fe.log("parseFileBlock",t),e(this,De,"f").push(t.buffer);const s=e(this,De,"f").reduce(((e,t)=>e+t.byteLength),0),i=s/e(this,ge,"f");if(Fe.log(`received ${s} of ${e(this,ge,"f")} bytes (${100*i}%)`),e(this,Q,"a",Z).call(this,"fileTransferProgress",{progress:i}),s!=e(this,ge,"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}])}Fe.log("file transfer complete");let n,r=(new Date).toLocaleString();if("tflite"===this.type)r+=".tflite";n="undefined"!=typeof File?new File(e(this,De,"f"),r):new Blob(e(this,De,"f"));const a=O(await n.arrayBuffer());Fe.log({checksum:a}),a==e(this,me,"f")?(Fe.log("received file",n),e(this,Q,"a",Z).call(this,"getFileBlock",{fileTransferBlock:t}),e(this,Q,"a",Z).call(this,"fileTransferComplete",{direction:"receiving"}),e(this,Q,"a",Z).call(this,"fileReceived",{file:n})):Fe.error(`wrong checksum - expected ${e(this,me,"f")}, got ${a}`)},We=async function(s){return t(this,Te,s,"f"),t(this,_e,0,"f"),e(this,Q,"m",Ie).call(this)},Ie=async function(){if("sending"!=this.status)return;if(!e(this,Te,"f"))return void(this.isServerSide||Fe.error("no buffer defined"));const s=e(this,Te,"f");let i=e(this,_e,"f");const n=s.slice(i,i+(this.mtu-3-3));Fe.log("slicedBuffer",n);const r=1-(s.byteLength-i)/s.byteLength;Fe.log(`sending bytes ${i}-${i+n.byteLength} of ${s.byteLength} bytes (${100*r}%)`),e(this,Q,"a",Z).call(this,"fileTransferProgress",{progress:r}),0==n.byteLength?(Fe.log("finished sending buffer"),e(this,Q,"a",Z).call(this,"fileTransferComplete",{direction:"sending"})):(await this.sendMessage([{type:"setFileBlock",data:n}]),t(this,_e,i+n.byteLength,"f"))},Le=async function(t){Fe.log("parseBytesTransferred",t);const s=t.getUint32(0,!0);if(Fe.log({bytesTransferred:s}),"sending"==this.status)return this.isServerSide||e(this,_e,"f")==s?void e(this,Q,"m",Ie).call(this):(Fe.error(`bytesTransferred are not equal - got ${s}, expected ${e(this,_e,"f")}`),void this.cancel());Fe.error("not currently sending file")},se={value:0};const Pe=k("MathUtils",{log:!1});const Ve=65536;function ze(e,t){const s=Date.now();var i;let n=(i=s)-i%Ve+e.getUint16(t,!0);return Math.abs(s-n)>6e4&&(Pe.log("correcting timestamp delta"),n+=Ve*Math.sign(s-n)),n}var je,Ge,qe;const He={min:1/0,max:-1/0,span:0};class Je{constructor(){je.add(this),Ge.set(this,Object.assign({},He))}get min(){return e(this,Ge,"f").min}get max(){return e(this,Ge,"f").max}set min(t){e(this,Ge,"f").min=t,e(this,Ge,"f").max=Math.max(t,e(this,Ge,"f").max),e(this,je,"m",qe).call(this)}set max(t){e(this,Ge,"f").max=t,e(this,Ge,"f").min=Math.min(t,e(this,Ge,"f").min),e(this,je,"m",qe).call(this)}reset(){Object.assign(e(this,Ge,"f"),He)}update(t){e(this,Ge,"f").min=Math.min(t,e(this,Ge,"f").min),e(this,Ge,"f").max=Math.max(t,e(this,Ge,"f").max),e(this,je,"m",qe).call(this)}getNormalization(t,s){let i=function(e,t,s,i){return null==i&&(i=s-t),(e-t)/i}(t,e(this,Ge,"f").min,e(this,Ge,"f").max,e(this,Ge,"f").span);return s&&(i*=e(this,Ge,"f").span),i||0}updateAndGetNormalization(e,t){return this.update(e),this.getNormalization(e,t)}}var Qe,Ke,Ze,Xe,Ye;Ge=new WeakMap,je=new WeakSet,qe=function(){e(this,Ge,"f").span=e(this,Ge,"f").max-e(this,Ge,"f").min};class et{constructor(){Qe.set(this,{x:new Je,y:new Je})}reset(){e(this,Qe,"f").x.reset(),e(this,Qe,"f").y.reset()}update(t){e(this,Qe,"f").x.update(t.x),e(this,Qe,"f").y.update(t.y)}getNormalization(t,s){return{x:e(this,Qe,"f").x.getNormalization(t.x,s),y:e(this,Qe,"f").y.getNormalization(t.y,s)}}updateAndGetNormalization(e,t){return this.update(e),this.getNormalization(e,t)}}Qe=new WeakMap;const tt=k("PressureDataManager",{log:!1}),st=["pressure"],it=st,nt=8;class rt{constructor(){Ke.set(this,[]),Ze.set(this,void 0),Xe.set(this,new Je),Ye.set(this,new et)}get positions(){return e(this,Ke,"f")}get numberOfSensors(){return this.positions.length}parsePositions(e){const s=[];for(let t=0,i=0;i<e.byteLength;t++,i+=2)s.push({x:e.getUint8(i)/256,y:e.getUint8(i+1)/256});var i,n;tt.log({positions:s}),t(this,Ke,s,"f"),t(this,Ze,(i=this.numberOfSensors,n=()=>new Je,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(){e(this,Ze,"f")?.forEach((e=>e.reset())),e(this,Ye,"f").reset(),e(this,Xe,"f").reset()}parseData(t,s){const i={sensors:[],scaledSum:0,normalizedSum:0};for(let n=0,r=0;r<t.byteLength;n++,r+=2){const a=t.getUint16(r,!0);let o=a*s/this.numberOfSensors;const c=e(this,Ze,"f")[n].updateAndGetNormalization(o,!1),h=this.positions[n];i.sensors[n]={rawValue:a,scaledValue:o,normalizedValue:c,position:h,weightedValue:0},i.scaledSum+=o}return i.normalizedSum=e(this,Xe,"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=e(this,Ye,"f").updateAndGetNormalization(i.center,!1)),tt.log({pressure:i}),i}}Ke=new WeakMap,Ze=new WeakMap,Xe=new WeakMap,Ye=new WeakMap;const at=k("MotionSensorDataManager",{log:!1}),ot=["still","walking","running","bicycle","vehicle","tilting"],ct=["portraitUpright","landscapeLeft","portraitUpsideDown","landscapeRight","unknown"];class ht{parseVector3(e,t){let[s,i,n]=[e.getInt16(0,!0),e.getInt16(2,!0),e.getInt16(4,!0)].map((e=>e*t));const r={x:s,y:i,z:n};return at.log({vector:r}),r}parseQuaternion(e,t){let[s,i,n,r]=[e.getInt16(0,!0),e.getInt16(2,!0),e.getInt16(4,!0),e.getInt16(6,!0)].map((e=>e*t));const a={x:s,y:i,z:n,w:r};return at.log({quaternion:a}),a}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+=360;const r={heading:s,pitch:i,roll:n};return at.log({euler:r}),r}parseStepCounter(e){at.log("parseStepCounter",e);const t=e.getUint32(0,!0);return at.log({stepCount:t}),t}parseActivity(e){at.log("parseActivity",e);const t={},s=e.getUint8(0);return at.log("activityBitfield",s.toString(2)),ot.forEach(((e,i)=>{t[e]=Boolean(s&1<<i)})),at.log("activity",t),t}parseDeviceOrientation(e){at.log("parseDeviceOrientation",e);const t=e.getUint8(0),s=ct[t];return at.assertWithError(s,"undefined deviceOrientation"),at.log({deviceOrientation:s}),s}}var lt,gt;const ft=["barometer"],ut=ft,dt=k("BarometerSensorDataManager",{log:!1});class mt{constructor(){lt.add(this)}parseData(t,s){const i=t.getUint32(0,!0)*s,n=e(this,lt,"m",gt).call(this,i);return dt.log({pressure:i,altitude:n}),{pressure:i}}}lt=new WeakSet,gt=function(e){const t=.0065;return 288.15/t*(1-Math.pow(e/101325,.19026643566373183))};const pt=k("ParseUtils",{log:!1});function vt(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 wt(e,t,s,i,n=!1){let r=0;for(;r<e.byteLength;){const a=e.getUint8(r++);pt.assertWithError(a in t,`invalid messageTypeEnum ${a}`);const o=t[a];let c;n?(c=e.getUint16(r,!0),r+=2):c=e.getUint8(r++),pt.log({messageTypeEnum:a,messageType:o,messageLength:c,dataView:e,byteOffset:r});const h=q(e,r,c);pt.log({_dataView:h}),s(o,h,i),r+=c}}var yt;const bt=k("SensorDataManager",{log:!1}),St=[...st,"acceleration","gravity","linearAcceleration","gyroscope","magnetometer","gameRotation","rotation","orientation","activity","stepCounter","stepDetector","deviceOrientation",...ft],Et=[...it,"acceleration","gravity","linearAcceleration","gyroscope","magnetometer","gameRotation","rotation",...ut],Mt=["getPressurePositions","getSensorScalars","sensorData"],Ct=[...Mt,...St];class Dt{constructor(){this.pressureSensorDataManager=new rt,this.motionSensorDataManager=new ht,this.barometerSensorDataManager=new mt,yt.set(this,new Map)}static AssertValidSensorType(e){bt.assertEnumWithError(e,St)}static AssertValidSensorTypeEnum(e){bt.assertTypeWithError(e,"number"),bt.assertWithError(e in St,`invalid sensorTypeEnum ${e}`)}get dispatchEvent(){return this.eventDispatcher.dispatchEvent}parseMessage(e,t){switch(bt.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(t){for(let s=0;s<t.byteLength;s+=5){const i=t.getUint8(s),n=St[i];if(!n){bt.warn(`unknown sensorType index ${i}`);continue}const r=t.getFloat32(s+1,!0);bt.log({sensorType:n,sensorScalar:r}),e(this,yt,"f").set(n,r)}}parseData(e){bt.log("sensorData",Array.from(new Uint8Array(e.buffer)));let t=0;const s=ze(e,t);t+=2;wt(new DataView(e.buffer,t),St,this.parseDataCallback.bind(this),{timestamp:s})}parseDataCallback(t,s,{timestamp:i}){const n=e(this,yt,"f").get(t)||1;let r=null;switch(t){case"pressure":r=this.pressureSensorDataManager.parseData(s,n);break;case"acceleration":case"gravity":case"linearAcceleration":case"gyroscope":case"magnetometer":r=this.motionSensorDataManager.parseVector3(s,n);break;case"gameRotation":case"rotation":r=this.motionSensorDataManager.parseQuaternion(s,n);break;case"orientation":r=this.motionSensorDataManager.parseEuler(s,n);break;case"stepCounter":r=this.motionSensorDataManager.parseStepCounter(s);break;case"stepDetector":r={};break;case"activity":r=this.motionSensorDataManager.parseActivity(s);break;case"deviceOrientation":r=this.motionSensorDataManager.parseDeviceOrientation(s);break;case"barometer":r=this.barometerSensorDataManager.parseData(s,n);break;default:bt.error(`uncaught sensorType "${t}"`)}bt.assertWithError(null!=r,`no sensorData defined for sensorType "${t}"`),bt.log({sensorType:t,sensorData:r}),this.dispatchEvent(t,{sensorType:t,[t]:r,timestamp:i}),this.dispatchEvent("sensorData",{sensorType:t,[t]:r,timestamp:i})}}var kt,Tt,_t,Wt,It,Lt,Ut,Ft,Rt,At,xt,$t,Ot;yt=new WeakMap;const Bt=k("SensorConfigurationManager",{log:!1}),Nt=65535,Pt=5,Vt=["getSensorConfiguration","setSensorConfiguration"],zt=Vt;class jt{constructor(){kt.add(this),Wt.set(this,void 0),Lt.set(this,void 0),J(this)}get addEventListener(){return this.eventDispatcher.addEventListener}get waitForEvent(){return this.eventDispatcher.waitForEvent}get configuration(){return e(this,Lt,"f")}async setConfiguration(t,s){if(s&&(t=Object.assign({...this.zeroSensorConfiguration},t)),Bt.log({newSensorConfiguration:t}),e(this,kt,"m",Ft).call(this,t))return void Bt.log("redundant sensor configuration");const i=e(this,kt,"m",$t).call(this,t);Bt.log({setSensorConfigurationData:i});const n=this.waitForEvent("getSensorConfiguration");this.sendMessage([{type:"setSensorConfiguration",data:i.buffer}]),await n}static get ZeroSensorConfiguration(){return e(this,Tt,"f",Ot)}get zeroSensorConfiguration(){const t={};return e(this,Wt,"f").forEach((e=>{t[e]=0})),t}async clearSensorConfiguration(){return this.setConfiguration(this.zeroSensorConfiguration)}parseMessage(t,s){switch(Bt.log({messageType:t}),t){case"getSensorConfiguration":case"setSensorConfiguration":const i=e(this,kt,"m",Rt).call(this,s);e(this,kt,"m",Ut).call(this,i);break;default:throw Error(`uncaught messageType ${t}`)}}}var Gt,qt,Ht,Jt,Qt,Kt,Zt,Xt,Yt,es,ts,ss,is,ns,rs,as,os,cs,hs,ls,gs,fs,us,ds,ms,ps,vs,ws,ys,bs;Tt=jt,Wt=new WeakMap,Lt=new WeakMap,kt=new WeakSet,_t=function(){return this.eventDispatcher.dispatchEvent},It=function(t){Bt.assertWithError(e(this,Wt,"f"),"must get initial sensorConfiguration");const s=e(this,Wt,"f")?.includes(t);return Bt.log(s,`unavailable sensor type "${t}"`),s},Ut=function(s){t(this,Lt,s,"f"),Bt.log({updatedConfiguration:e(this,Lt,"f")}),e(this,kt,"a",_t).call(this,"getSensorConfiguration",{sensorConfiguration:this.configuration})},Ft=function(e){return Object.keys(e).every((t=>this.configuration[t]==e[t]))},Rt=function(e){const s={};for(let t=0;t<e.byteLength;t+=3){const i=e.getUint8(t),n=St[i];if(!n){Bt.warn(`unknown sensorType index ${i}`);continue}const r=e.getUint16(t+1,!0);Bt.log({sensorType:n,sensorRate:r}),s[n]=r}return Bt.log({parsedSensorConfiguration:s}),t(this,Wt,Object.keys(s),"f"),s},At=function(e){Bt.assertTypeWithError(e,"number"),Bt.assertWithError(e>=0,`sensorRate must be 0 or greater (got ${e})`),Bt.assertWithError(e<65535,`sensorRate must be 0 or greater (got ${e})`),Bt.assertWithError(e%5==0,"sensorRate must be multiple of 5")},xt=function(t){e(Tt,Tt,"m",At).call(Tt,t)},$t=function(t){let s=Object.keys(t);s=s.filter((t=>e(this,kt,"m",It).call(this,t)));const i=new DataView(new ArrayBuffer(3*s.length));return s.forEach(((s,n)=>{Dt.AssertValidSensorType(s);const r=St.indexOf(s);i.setUint8(3*n,r);const a=t[s];e(this,kt,"m",xt).call(this,a),i.setUint16(3*n+1,a,!0)})),Bt.log({sensorConfigurationData:i}),i},Ot={value:{}},St.forEach((t=>{e(Tt,Tt,"f",Ot)[t]=0}));const Ss=k("TfliteManager",{log:!1}),Es=["getTfliteName","setTfliteName","getTfliteTask","setTfliteTask","getTfliteSampleRate","setTfliteSampleRate","getTfliteSensorTypes","setTfliteSensorTypes","tfliteIsReady","getTfliteCaptureDelay","setTfliteCaptureDelay","getTfliteThreshold","setTfliteThreshold","getTfliteInferencingEnabled","setTfliteInferencingEnabled","tfliteInference"],Ms=Es,Cs=["classification","regression"],Ds=["pressure","linearAcceleration","gyroscope","magnetometer"];class ks{constructor(){Gt.add(this),Qt.set(this,void 0),Xt.set(this,void 0),ts.set(this,void 0),ns.set(this,[]),os.set(this,void 0),gs.set(this,void 0),ds.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 e(this,Qt,"f")}async setName(e,t){if(Ss.assertTypeWithError(e,"string"),this.name==e)return void Ss.log(`redundant name assignment ${e}`);const s=this.waitForEvent("getTfliteName"),i=P.encode(e);this.sendMessage([{type:"setTfliteName",data:i.buffer}],t),await s}get task(){return e(this,Xt,"f")}async setTask(t,s){if(e(this,Gt,"m",qt).call(this,t),this.task==t)return void Ss.log(`redundant task assignment ${t}`);const i=this.waitForEvent("getTfliteTask"),n=Cs.indexOf(t);this.sendMessage([{type:"setTfliteTask",data:Uint8Array.from([n]).buffer}],s),await i}get sampleRate(){return e(this,ts,"f")}async setSampleRate(t,s){if(Ss.assertTypeWithError(t,"number"),t-=t%5,Ss.assertWithError(t>=5,`sampleRate must be multiple of 5 greater than 0 (got ${t})`),e(this,ts,"f")==t)return void Ss.log(`redundant sampleRate assignment ${t}`);const i=this.waitForEvent("getTfliteSampleRate"),n=new DataView(new ArrayBuffer(2));n.setUint16(0,t,!0),this.sendMessage([{type:"setTfliteSampleRate",data:n.buffer}],s),await i}static AssertValidSensorType(e){Dt.AssertValidSensorType(e),Ss.assertWithError(Ds.includes(e),`invalid tflite sensorType "${e}"`)}get sensorTypes(){return e(this,ns,"f").slice()}async setSensorTypes(e,t){e.forEach((e=>{ks.AssertValidSensorType(e)}));const s=this.waitForEvent("getTfliteSensorTypes");var i;const n=(e=(i=e).filter(((e,t)=>i.indexOf(e)==t))).map((e=>St.indexOf(e))).sort();Ss.log(e,n),this.sendMessage([{type:"setTfliteSensorTypes",data:Uint8Array.from(n).buffer}],t),await s}get isReady(){return e(this,os,"f")}get captureDelay(){return e(this,gs,"f")}async setCaptureDelay(t,s){if(Ss.assertTypeWithError(t,"number"),e(this,gs,"f")==t)return void Ss.log(`redundant captureDelay assignment ${t}`);const i=this.waitForEvent("getTfliteCaptureDelay"),n=new DataView(new ArrayBuffer(2));n.setUint16(0,t,!0),this.sendMessage([{type:"setTfliteCaptureDelay",data:n.buffer}],s),await i}get threshold(){return e(this,ds,"f")}async setThreshold(t,s){if(Ss.assertTypeWithError(t,"number"),Ss.assertWithError(t>=0,`threshold must be positive (got ${t})`),e(this,ds,"f")==t)return void Ss.log(`redundant threshold assignment ${t}`);const i=this.waitForEvent("getTfliteThreshold"),n=new DataView(new ArrayBuffer(4));n.setFloat32(0,t,!0),this.sendMessage([{type:"setTfliteThreshold",data:n.buffer}],s),await i}get inferencingEnabled(){return e(this,vs,"f")}async setInferencingEnabled(t,s=!0){if(Ss.assertTypeWithError(t,"boolean"),!t&&!this.isReady)return;if(e(this,Gt,"m",ls).call(this),e(this,vs,"f")==t)return void Ss.log(`redundant inferencingEnabled assignment ${t}`);const i=this.waitForEvent("getTfliteInferencingEnabled");this.sendMessage([{type:"setTfliteInferencingEnabled",data:Uint8Array.from([Number(t)]).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(t,s){switch(Ss.log({messageType:t}),t){case"getTfliteName":case"setTfliteName":e(this,Gt,"m",Kt).call(this,s);break;case"getTfliteTask":case"setTfliteTask":e(this,Gt,"m",Yt).call(this,s);break;case"getTfliteSampleRate":case"setTfliteSampleRate":e(this,Gt,"m",ss).call(this,s);break;case"getTfliteSensorTypes":case"setTfliteSensorTypes":e(this,Gt,"m",rs).call(this,s);break;case"tfliteIsReady":e(this,Gt,"m",cs).call(this,s);break;case"getTfliteCaptureDelay":case"setTfliteCaptureDelay":e(this,Gt,"m",fs).call(this,s);break;case"getTfliteThreshold":case"setTfliteThreshold":e(this,Gt,"m",ms).call(this,s);break;case"getTfliteInferencingEnabled":case"setTfliteInferencingEnabled":e(this,Gt,"m",ws).call(this,s);break;case"tfliteInference":e(this,Gt,"m",bs).call(this,s);break;default:throw Error(`uncaught messageType ${t}`)}}}var Ts,_s,Ws,Is,Ls;Qt=new WeakMap,Xt=new WeakMap,ts=new WeakMap,ns=new WeakMap,os=new WeakMap,gs=new WeakMap,ds=new WeakMap,vs=new WeakMap,Gt=new WeakSet,qt=function(e){Ss.assertEnumWithError(e,Cs)},Ht=function(e){Ss.assertWithError(e in Cs,`invalid taskEnum ${e}`)},Jt=function(){return this.eventDispatcher.dispatchEvent},Kt=function(t){Ss.log("parseName",t);const s=V.decode(t.buffer);e(this,Gt,"m",Zt).call(this,s)},Zt=function(s){Ss.log({name:s}),t(this,Qt,s,"f"),e(this,Gt,"a",Jt).call(this,"getTfliteName",{tfliteName:s})},Yt=function(t){Ss.log("parseTask",t);const s=t.getUint8(0);e(this,Gt,"m",Ht).call(this,s);const i=Cs[s];e(this,Gt,"m",es).call(this,i)},es=function(s){Ss.log({task:s}),t(this,Xt,s,"f"),e(this,Gt,"a",Jt).call(this,"getTfliteTask",{tfliteTask:s})},ss=function(t){Ss.log("parseSampleRate",t);const s=t.getUint16(0,!0);e(this,Gt,"m",is).call(this,s)},is=function(s){Ss.log({sampleRate:s}),t(this,ts,s,"f"),e(this,Gt,"a",Jt).call(this,"getTfliteSampleRate",{tfliteSampleRate:s})},rs=function(t){Ss.log("parseSensorTypes",t);const s=[];for(let e=0;e<t.byteLength;e++){const i=t.getUint8(e),n=St[i];n?s.push(n):Ss.error(`invalid sensorTypeEnum ${i}`)}e(this,Gt,"m",as).call(this,s)},as=function(s){Ss.log({sensorTypes:s}),t(this,ns,s,"f"),e(this,Gt,"a",Jt).call(this,"getTfliteSensorTypes",{tfliteSensorTypes:s})},cs=function(t){Ss.log("parseIsReady",t);const s=Boolean(t.getUint8(0));e(this,Gt,"m",hs).call(this,s)},hs=function(s){Ss.log({isReady:s}),t(this,os,s,"f"),e(this,Gt,"a",Jt).call(this,"tfliteIsReady",{tfliteIsReady:s})},ls=function(){Ss.assertWithError(this.isReady,"tflite is not ready")},fs=function(t){Ss.log("parseCaptureDelay",t);const s=t.getUint16(0,!0);e(this,Gt,"m",us).call(this,s)},us=function(s){Ss.log({captureDelay:s}),t(this,gs,s,"f"),e(this,Gt,"a",Jt).call(this,"getTfliteCaptureDelay",{tfliteCaptureDelay:s})},ms=function(t){Ss.log("parseThreshold",t);const s=t.getFloat32(0,!0);e(this,Gt,"m",ps).call(this,s)},ps=function(s){Ss.log({threshold:s}),t(this,ds,s,"f"),e(this,Gt,"a",Jt).call(this,"getTfliteThreshold",{tfliteThreshold:s})},ws=function(t){Ss.log("parseInferencingEnabled",t);const s=Boolean(t.getUint8(0));e(this,Gt,"m",ys).call(this,s)},ys=function(s){Ss.log({inferencingEnabled:s}),t(this,vs,s,"f"),e(this,Gt,"a",Jt).call(this,"getTfliteInferencingEnabled",{tfliteInferencingEnabled:s})},bs=function(t){Ss.log("parseInference",t);const s=ze(t,0);Ss.log({timestamp:s});const i=[];for(let e=0,s=2;s<t.byteLength;e++,s+=4){const e=t.getFloat32(s,!0);i.push(e)}Ss.log("values",i);const n={timestamp:s,values:i};if("classification"==this.task){let e=0,t=0;i.forEach(((s,i)=>{s>e&&(e=s,t=i)})),Ss.log({maxIndex:t,maxValue:e}),n.maxIndex=t,n.maxValue=e}e(this,Gt,"a",Jt).call(this,"tfliteInference",{tfliteInference:n})};const Us=k("DeviceInformationManager",{log:!1}),Fs=["manufacturerName","modelNumber","softwareRevision","hardwareRevision","firmwareRevision","pnpId","serialNumber"],Rs=[...Fs,"deviceInformation"];class As{constructor(){Ts.add(this),Ws.set(this,{})}get information(){return e(this,Ws,"f")}clear(){t(this,Ws,{},"f")}parseMessage(t,s){switch(Us.log({messageType:t}),t){case"manufacturerName":const i=V.decode(s.buffer);Us.log({manufacturerName:i}),e(this,Ts,"m",Ls).call(this,{manufacturerName:i});break;case"modelNumber":const n=V.decode(s.buffer);Us.log({modelNumber:n}),e(this,Ts,"m",Ls).call(this,{modelNumber:n});break;case"softwareRevision":const r=V.decode(s.buffer);Us.log({softwareRevision:r}),e(this,Ts,"m",Ls).call(this,{softwareRevision:r});break;case"hardwareRevision":const a=V.decode(s.buffer);Us.log({hardwareRevision:a}),e(this,Ts,"m",Ls).call(this,{hardwareRevision:a});break;case"firmwareRevision":const o=V.decode(s.buffer);Us.log({firmwareRevision:o}),e(this,Ts,"m",Ls).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)),Us.log({pnpId:c}),e(this,Ts,"m",Ls).call(this,{pnpId:c});break;case"serialNumber":const h=V.decode(s.buffer);Us.log({serialNumber:h});break;default:throw Error(`uncaught messageType ${t}`)}}}var xs,$s,Os,Bs,Ns,Ps,Vs,zs,js,Gs,qs,Hs,Js,Qs,Ks,Zs,Xs,Ys;Ws=new WeakMap,Ts=new WeakSet,_s=function(){return this.eventDispatcher.dispatchEvent},Is=function(){return Fs.filter((e=>"serialNumber"!=e)).every((t=>t in e(this,Ws,"f")))},Ls=function(t){Us.log({partialDeviceInformation:t});Object.keys(t).forEach((s=>{e(this,Ts,"a",_s).call(this,s,{[s]:t[s]})})),Object.assign(e(this,Ws,"f"),t),Us.log({deviceInformation:e(this,Ws,"f")}),e(this,Ts,"a",Is)&&(Us.log("completed deviceInformation"),e(this,Ts,"a",_s).call(this,"deviceInformation",{deviceInformation:this.information}))};const ei=k("InformationManager",{log:!1}),ti=["leftInsole","rightInsole","leftGlove","rightGlove","glasses","generic"],si=["left","right"],ii=2,ni=30,ri=["isCharging","getBatteryCurrent","getMtu","getId","getName","setName","getType","setType","getCurrentTime","setCurrentTime"],ai=ri;class oi{constructor(){xs.add(this),Os.set(this,!1),Ns.set(this,void 0),Vs.set(this,void 0),js.set(this,""),Gs.set(this,void 0),Qs.set(this,0),Zs.set(this,!1),J(this)}get waitForEvent(){return this.eventDispatcher.waitForEvent}get isCharging(){return e(this,Os,"f")}get batteryCurrent(){return e(this,Ns,"f")}async getBatteryCurrent(){ei.log("getting battery current...");const e=this.waitForEvent("getBatteryCurrent");this.sendMessage([{type:"getBatteryCurrent"}]),await e}get id(){return e(this,Vs,"f")}get name(){return e(this,js,"f")}updateName(s){ei.assertTypeWithError(s,"string"),t(this,js,s,"f"),ei.log({updatedName:e(this,js,"f")}),e(this,xs,"a",$s).call(this,"getName",{name:e(this,js,"f")})}async setName(e){ei.assertTypeWithError(e,"string"),ei.assertWithError(e.length>=2,`name must be greater than 2 characters long ("${e}" is ${e.length} characters long)`),ei.assertWithError(e.length<30,`name must be less than 30 characters long ("${e}" is ${e.length} characters long)`);const t=P.encode(e);ei.log({setNameData:t});const s=this.waitForEvent("getName");this.sendMessage([{type:"setName",data:t.buffer}]),await s}get type(){return e(this,Gs,"f")}get typeEnum(){return ti.indexOf(this.type)}updateType(s){e(this,xs,"m",qs).call(this,s),s!=this.type?(t(this,Gs,s,"f"),ei.log({updatedType:e(this,Gs,"f")}),e(this,xs,"a",$s).call(this,"getType",{type:e(this,Gs,"f")})):ei.log("redundant type assignment")}async setType(t){e(this,xs,"m",qs).call(this,t);const s=ti.indexOf(t);e(this,xs,"m",Js).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 e(this,Qs,"f")}get isCurrentTimeSet(){return e(this,Zs,"f")}parseMessage(t,s){switch(ei.log({messageType:t}),t){case"isCharging":const n=Boolean(s.getUint8(0));ei.log({isCharging:n}),e(this,xs,"m",Bs).call(this,n);break;case"getBatteryCurrent":const r=s.getFloat32(0,!0);ei.log({batteryCurrent:r}),e(this,xs,"m",Ps).call(this,r);break;case"getId":const a=V.decode(s.buffer);ei.log({id:a}),e(this,xs,"m",zs).call(this,a);break;case"getName":case"setName":const o=V.decode(s.buffer);ei.log({name:o}),this.updateName(o);break;case"getType":case"setType":const c=s.getUint8(0),h=ti[c];ei.log({typeEnum:c,type:h}),this.updateType(h);break;case"getMtu":let l=s.getUint16(0,!0);i&&(l=Math.min(l,512)),ei.log({mtu:l}),e(this,xs,"m",Ks).call(this,l);break;case"getCurrentTime":case"setCurrentTime":const g=Number(s.getBigUint64(0,!0));e(this,xs,"m",Xs).call(this,g);break;default:throw Error(`uncaught messageType ${t}`)}}clear(){t(this,Zs,!1,"f")}}Os=new WeakMap,Ns=new WeakMap,Vs=new WeakMap,js=new WeakMap,Gs=new WeakMap,Qs=new WeakMap,Zs=new WeakMap,xs=new WeakSet,$s=function(){return this.eventDispatcher.dispatchEvent},Bs=function(s){ei.assertTypeWithError(s,"boolean"),t(this,Os,s,"f"),ei.log({isCharging:e(this,Os,"f")}),e(this,xs,"a",$s).call(this,"isCharging",{isCharging:e(this,Os,"f")})},Ps=function(s){ei.assertTypeWithError(s,"number"),t(this,Ns,s,"f"),ei.log({batteryCurrent:e(this,Ns,"f")}),e(this,xs,"a",$s).call(this,"getBatteryCurrent",{batteryCurrent:e(this,Ns,"f")})},zs=function(s){ei.assertTypeWithError(s,"string"),t(this,Vs,s,"f"),ei.log({id:e(this,Vs,"f")}),e(this,xs,"a",$s).call(this,"getId",{id:e(this,Vs,"f")})},qs=function(e){ei.assertEnumWithError(e,ti)},Hs=function(e){ei.assertTypeWithError(e,"number"),ei.assertWithError(e in ti,`invalid typeEnum ${e}`)},Js=async function(t){e(this,xs,"m",Hs).call(this,t);const s=Uint8Array.from([t]);ei.log({setTypeData:s});const i=this.waitForEvent("getType");this.sendMessage([{type:"setType",data:s.buffer}]),await i},Ks=function(s){ei.assertTypeWithError(s,"number"),e(this,Qs,"f")!=s?(t(this,Qs,s,"f"),e(this,xs,"a",$s).call(this,"getMtu",{mtu:e(this,Qs,"f")})):ei.log("redundant mtu assignment",s)},Xs=function(s){ei.log({currentTime:s}),t(this,Zs,0!=s||Math.abs(Date.now()-s)<Ve,"f"),e(this,Zs,"f")||e(this,xs,"m",Ys).call(this,!1)},Ys=async function(e){ei.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 ci=["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 hi,li,gi,fi,ui,di,mi,pi,vi,wi,yi,bi,Si,Ei,Mi,Ci;const Di=k("VibrationManager"),ki=["front","rear"],Ti=["waveformEffect","waveform"],_i=8,Wi=2550,Ii=1270,Li=3,Ui=20,Fi=6;class Ri{constructor(){hi.add(this),J(this)}async triggerVibration(t,s=!0){let i;t.forEach((t=>{const{type:s}=t;let n,{locations:r}=t;switch(r=r||ki.slice(),s){case"waveformEffect":{const{segments:s,loopCount:i}=t;n=e(this,hi,"m",Si).call(this,r,s,i)}break;case"waveform":{const{segments:s}=t;n=e(this,hi,"m",Ei).call(this,r,s)}break;default:throw Error(`invalid vibration type "${s}"`)}Di.log({type:s,arrayBuffer:n}),i=j(i,n)})),await this.sendMessage([{type:"triggerVibration",data:i}],s)}}var Ai,xi,$i,Oi,Bi,Ni,Pi,Vi,zi,ji,Gi,qi,Hi,Ji,Qi,Ki;hi=new WeakSet,li=function(e){Di.assertTypeWithError(e,"string"),Di.assertWithError(ki.includes(e),`invalid location "${e}"`)},gi=function(t){e(this,hi,"m",ui).call(this,t),t.forEach((t=>{e(this,hi,"m",li).call(this,t)}))},fi=function(t){e(this,hi,"m",gi).call(this,t);let s=0;return t.forEach((e=>{const t=ki.indexOf(e);s|=1<<t})),Di.log({locationsBitmask:s}),Di.assertWithError(s>0,"locationsBitmask must not be zero"),s},ui=function(e){Di.assertWithError(Array.isArray(e),"passed non-array"),Di.assertWithError(e.length>0,"passed empty array")},di=function(e){Di.assertWithError(ci.includes(e),`invalid waveformEffect "${e}"`)},mi=function(t){if(null!=t.effect){const s=t.effect;e(this,hi,"m",di).call(this,s)}else{if(null==t.delay)throw Error("no effect or delay found in waveformEffectSegment");{const{delay:e}=t;Di.assertWithError(e>=0,`delay must be 0ms or greater (got ${e})`),Di.assertWithError(e<=Ii,`delay must be 1270ms or less (got ${e})`)}}if(null!=t.loopCount){const{loopCount:s}=t;e(this,hi,"m",pi).call(this,s)}},pi=function(e){Di.assertTypeWithError(e,"number"),Di.assertWithError(e>=0,`waveformEffectSegmentLoopCount must be 0 or greater (got ${e})`),Di.assertWithError(e<=3,`waveformEffectSegmentLoopCount must be 3 or fewer (got ${e})`)},vi=function(t){e(this,hi,"m",ui).call(this,t),Di.assertWithError(t.length<=8,`must have 8 waveformEffectSegments or fewer (got ${t.length})`),t.forEach((t=>{e(this,hi,"m",mi).call(this,t)}))},wi=function(e){Di.assertTypeWithError(e,"number"),Di.assertWithError(e>=0,`waveformEffectSequenceLoopCount must be 0 or greater (got ${e})`),Di.assertWithError(e<=6,`waveformEffectSequenceLoopCount must be 6 or fewer (got ${e})`)},yi=function(e){Di.assertTypeWithError(e.amplitude,"number"),Di.assertWithError(e.amplitude>=0,`amplitude must be 0 or greater (got ${e.amplitude})`),Di.assertWithError(e.amplitude<=1,`amplitude must be 1 or less (got ${e.amplitude})`),Di.assertTypeWithError(e.duration,"number"),Di.assertWithError(e.duration>0,`duration must be greater than 0ms (got ${e.duration}ms)`),Di.assertWithError(e.duration<=Wi,`duration must be 2550ms or less (got ${e.duration}ms)`)},bi=function(t){e(this,hi,"m",ui).call(this,t),Di.assertWithError(t.length<=20,`must have 20 waveformSegments or fewer (got ${t.length})`),t.forEach((t=>{e(this,hi,"m",yi).call(this,t)}))},Si=function(t,s,i=0){e(this,hi,"m",vi).call(this,s),e(this,hi,"m",wi).call(this,i);let n=[],r=0;const a=s.some((e=>{const{loopCount:t}=e;return null!=t&&t>0}))||0!=i;for(let e=0;e<s.length||a&&e<8;e++){const t=s[e]||{effect:"none"};if(null!=t.effect){const e=t.effect;n[r++]=ci.indexOf(e)}else{if(null==t.delay)throw Error("invalid waveformEffectSegment");{const{delay:e}=t;n[r++]=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[r]=0);const i=e%4*2;n[r]|=t<<i,3!=e&&7!=e||r++}0!=i&&(n[r++]=i);const c=new DataView(Uint8Array.from(n).buffer);return Di.log({dataArray:n,dataView:c}),e(this,hi,"m",Ci).call(this,t,"waveformEffect",c)},Ei=function(t,s){e(this,hi,"m",bi).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))})),Di.log({dataView:i}),e(this,hi,"m",Ci).call(this,t,"waveform",i)},Mi=function(e){Di.assertTypeWithError(e,"string"),Di.assertWithError(Ti.includes(e),`invalid vibrationType "${e}"`)},Ci=function(t,s,i){Di.assertWithError(i?.byteLength>0,"no data received");const n=e(this,hi,"m",fi).call(this,t);e(this,hi,"m",Mi).call(this,s);const r=Ti.indexOf(s);Di.log({locationsBitmask:n,vibrationTypeIndex:r,dataView:i});const a=j(n,r,i.byteLength,i);return Di.log({data:a}),a};const Zi=k("BaseConnectionManager",{log:!1}),Xi=["notConnected","connecting","connected","disconnecting"],Yi=[...Xi,"connectionStatus","isConnected"],en=[...ri,...Vt,...Mt,"triggerVibration",...Es,...Re],tn=["batteryLevel"],sn=["rx","tx"],nn=[...tn,...Fs,...sn,...en,"smp"];class rn{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(){Ai.add(this),Bi.set(this,"notConnected"),Gi.set(this,[]),qi.set(this,!1),Hi.set(this,23),this.mtu=e(this,Hi,"f"),Qi.set(this,new A(e(this,Ai,"m",Ki).bind(this),5e3)),e(this,Ai,"m",Oi).call(this)}get status(){return e(this,Bi,"f")}set status(s){Zi.assertEnumWithError(s,Xi),e(this,Bi,"f")!=s?(Zi.log(`new connection status "${s}"`),t(this,Bi,s,"f"),this.onStatusUpdated(this.status),this.isConnected?e(this,Qi,"f").start():e(this,Qi,"f").stop(),"notConnected"==e(this,Bi,"f")&&(this.mtu=e(this,Hi,"f"))):Zi.log(`tried to assign same connection status "${s}"`)}get isConnected(){return"connected"==this.status}get isAvailable(){return!1}async connect(){e(this,Ai,"m",Ni).call(this),e(this,Ai,"m",Pi).call(this),this.status="connecting"}get canReconnect(){return!1}async reconnect(){e(this,Ai,"m",Ni).call(this),e(this,Ai,"m",Pi).call(this),Zi.assert(this.canReconnect,"unable to reconnect")}async disconnect(){e(this,Ai,"m",Vi).call(this),e(this,Ai,"m",zi).call(this),this.status="disconnecting",Zi.log("disconnecting from device...")}async sendSmpMessage(t){e(this,Ai,"m",ji).call(this),Zi.log("sending smp message",t)}async sendTxMessages(s,i=!0){if(e(this,Ai,"m",ji).call(this),s&&(e(this,Gi,"f").push(...s),Zi.log(`appended ${s.length} messages`)),!i)return void Zi.log("not sending immediately - waiting until later");if(e(this,qi,"f"))return void Zi.log("already sending messages - waiting until later");t(this,qi,!0,"f"),Zi.log("sendTxMessages",e(this,Gi,"f").slice());const n=e(this,Gi,"f").map((t=>{e(xi,xi,"m",$i).call(xi,t.type);const s=en.indexOf(t.type),i=new DataView(new ArrayBuffer(2));return i.setUint16(0,t.data?.byteLength||0,!0),j(s,i,t.data)}));if(e(this,Gi,"f").length=0,this.mtu)for(;n.length>0;){if(n.every((e=>e.byteLength>this.mtu-3))){Zi.log("every arrayBuffer is too big to send");break}Zi.log("remaining arrayBuffers.length",n.length);let e=0,t=0;n.some((s=>{if(e+s.byteLength>this.mtu-3)return Zi.log(`stopping appending arrayBuffers ( length ${s.byteLength} too much)`),!0;Zi.log(`allowing arrayBuffer with length ${s.byteLength}`),t++,e+=s.byteLength}));const s=n.splice(0,t);Zi.log({arrayBufferCount:t,arrayBuffersToSend:s});const i=j(...s);Zi.log("sending arrayBuffer (partitioned)",i),await this.sendTxData(i)}else{const e=j(...n);Zi.log("sending arrayBuffer (all)",e),await this.sendTxData(e)}t(this,qi,!1,"f")}async sendTxData(e){Zi.log("sendTxData",e)}parseRxMessage(t){wt(t,en,e(this,Ai,"m",Ji).bind(this),null,!0),this.onMessagesReceived()}clear(){t(this,qi,!1,"f"),e(this,Gi,"f").length=0}}xi=rn,Bi=new WeakMap,Gi=new WeakMap,qi=new WeakMap,Hi=new WeakMap,Qi=new WeakMap,Ai=new WeakSet,$i=function(e){Zi.assertEnumWithError(e,en)},Oi=function(){Zi.assertWithError(this.isSupported,`${this.constructor.name} is not supported`)},Ni=function(){Zi.assertWithError(!this.isConnected,"device is already connected")},Pi=function(){Zi.assertWithError("connecting"!=this.status,"device is already connecting")},Vi=function(){Zi.assertWithError(this.isConnected,"device is not connected")},zi=function(){Zi.assertWithError("disconnecting"!=this.status,"device is already disconnecting")},ji=function(){e(this,Ai,"m",Vi).call(this),e(this,Ai,"m",zi).call(this)},Ji=function(e,t){Zi.log({messageType:e,dataView:t}),this.onMessageReceived(e,t)},Ki=function(){this.isConnected||(Zi.log("timer detected disconnection"),this.status="notConnected")};const an=k("EventUtils",{log:!1});function on(e,t){let s=e.addEventListener||e.addListener||e.on||e.AddEventListener;an.assertWithError(s,"no add listener function found for target"),s=s.bind(e),Object.entries(t).forEach((([e,t])=>{s(e,t)}))}function cn(e,t){let s=e.removeEventListener||e.removeListener||e.RemoveEventListener;an.assertWithError(s,"no remove listener function found for target"),s=s.bind(e),Object.entries(t).forEach((([e,t])=>{s(e,t)}))}const hn=k("bluetoothUUIDs",{log:!1});if(i)var ln=window.BluetoothUUID;function gn(e){return hn.assertTypeWithError(e,"string"),hn.assertWithError(4==e.length,"value must be 4 characters long"),`ea6da725-${e}-4f9b-893d-c3913e33b39f`}function fn(e){return ln?.getCharacteristic?.(e)}function un(e){return ln?.getService?.(e)}const dn=Object.freeze({services:{deviceInformation:{uuid:un("device_information"),characteristics:{manufacturerName:{uuid:fn("manufacturer_name_string")},modelNumber:{uuid:fn("model_number_string")},hardwareRevision:{uuid:fn("hardware_revision_string")},firmwareRevision:{uuid:fn("firmware_revision_string")},softwareRevision:{uuid:fn("software_revision_string")},pnpId:{uuid:fn("pnp_id")},serialNumber:{uuid:fn("serial_number_string")}}},battery:{uuid:un("battery_service"),characteristics:{batteryLevel:{uuid:fn("battery_level")}}},main:{uuid:gn("0000"),characteristics:{rx:{uuid:gn("1000")},tx:{uuid:gn("1001")}}},smp:{uuid:"8d53dc1d-1db7-4cd3-868b-8a527460aa84",characteristics:{smp:{uuid:"da2e7828-fbce-4e01-ae9e-261174997c48"}}}}}),mn=[dn.services.main.uuid],pn=[dn.services.deviceInformation.uuid,dn.services.battery.uuid,dn.services.smp.uuid];function vn(e){e=e.toString().toLowerCase();return Object.keys(dn.services).find((t=>{let s=dn.services[t].uuid.toString();return 4==e.length&&(s=s.slice(4,8)),e.includes("-")||(s=s.replaceAll("-","")),e==s}))}const wn=[],yn=[];function bn(e){var t;return e=e.toString().toLowerCase(),Object.values(dn.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 Sn(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(dn.services).forEach((e=>{if(!e.characteristics)return;const t=Object.keys(e.characteristics);t.forEach((s=>{const i=e.characteristics[s];mn.includes(e.uuid)&&(wn.push(i.uuid),t.push(s)),yn.push(i.uuid)}))}),[]);const En=k("BluetoothConnectionManager",{log:!1});class Mn extends rn{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){En.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 Cn,Dn,kn,Tn,_n,Wn,In,Ln,Un,Fn,Rn;const An=k("WebBluetoothConnectionManager",{log:!1});var xn;i&&(xn=window.navigator.bluetooth);class $n extends Mn{constructor(){super(...arguments),Cn.add(this),Dn.set(this,{characteristicvaluechanged:e(this,Cn,"m",Un).bind(this)}),kn.set(this,{gattserverdisconnected:e(this,Cn,"m",Rn).bind(this)}),Tn.set(this,void 0),_n.set(this,new Map),Wn.set(this,new Map)}get bluetoothId(){return this.device.id}get canUpdateFirmware(){return e(this,Wn,"f").has("smp")}static get isSupported(){return Boolean(xn)}static get type(){return"webBluetooth"}get device(){return e(this,Tn,"f")}set device(s){e(this,Tn,"f")!=s?(e(this,Tn,"f")&&cn(e(this,Tn,"f"),e(this,kn,"f")),s&&on(s,e(this,kn,"f")),t(this,Tn,s,"f")):An.log("tried to assign the same BluetoothDevice")}get server(){return e(this,Tn,"f")?.gatt}get isConnected(){return this.server?.connected||!1}async connect(){await super.connect();try{const t=await xn.requestDevice({filters:[{services:mn}],optionalServices:i?pn:[]});An.log("got BluetoothDevice"),this.device=t,An.log("connecting to device...");const s=await this.server.connect();An.log(`connected to device? ${s.connected}`),await e(this,Cn,"m",In).call(this),An.log("fully connected"),this.status="connected"}catch(t){An.error(t),this.status="notConnected",this.server?.disconnect(),e(this,Cn,"m",Ln).call(this)}}async disconnect(){await e(this,Cn,"m",Ln).call(this),await super.disconnect(),this.server?.disconnect(),this.status="notConnected"}async writeCharacteristic(t,s){super.writeCharacteristic(t,s);const i=e(this,Wn,"f").get(t);An.assertWithError(i,`${t} characteristic not found`),An.log("writing characteristic",i,s);const n=i.properties||Sn(t);n.writeWithoutResponse?(An.log("writing without response"),await i.writeValueWithoutResponse(s)):(An.log("writing with response"),await i.writeValueWithResponse(s)),An.log("wrote characteristic"),n.read&&!n.notify&&(An.log("reading value after write..."),await i.readValue(),(o||c)&&e(this,Cn,"m",Fn).call(this,i))}get canReconnect(){return Boolean(this.server&&!this.server.connected&&this.isInRange)}async reconnect(){await super.reconnect(),An.log("attempting to reconnect..."),this.status="connecting";try{await this.server.connect()}catch(e){An.error(e),this.isInRange=!1}this.isConnected?(An.log("successfully reconnected!"),await e(this,Cn,"m",In).call(this),this.status="connected"):(An.log("unable to reconnect"),this.status="notConnected")}}Dn=new WeakMap,kn=new WeakMap,Tn=new WeakMap,_n=new WeakMap,Wn=new WeakMap,Cn=new WeakSet,In=async function(){e(this,Cn,"m",Ln).call(this),An.log("getting services...");const t=await this.server.getPrimaryServices();An.log("got services",t.length),An.log("getting characteristics...");for(const s in t){const i=t[s];An.log({service:i});const n=vn(i.uuid);An.assertWithError(n,`no name found for service uuid "${i.uuid}"`),An.log(`got "${n}" service`),i.name=n,e(this,_n,"f").set(n,i),An.log(`getting characteristics for "${n}" service`);const r=await i.getCharacteristics();An.log(`got characteristics for "${n}" service`);for(const t in r){const s=r[t];An.log({characteristic:s});const i=bn(s.uuid);An.assertWithError(Boolean(i),`no name found for characteristic uuid "${s.uuid}" in "${n}" service`),An.log(`got "${i}" characteristic in "${n}" service`),s.name=i,e(this,Wn,"f").set(i,s),on(s,e(this,Dn,"f"));const a=s.properties||Sn(i);a.notify&&(An.log(`starting notifications for "${i}" characteristic`),await s.startNotifications()),a.read&&(An.log(`reading "${i}" characteristic...`),await s.readValue(),(o||c)&&e(this,Cn,"m",Fn).call(this,s))}}},Ln=async function(){this.device&&cn(this.device,e(this,kn,"f"));const t=Array.from(e(this,Wn,"f").keys()).map((t=>{const s=e(this,Wn,"f").get(t);cn(s,e(this,Dn,"f"));if((s.properties||Sn(t)).notify)return An.log(`stopping notifications for "${t}" characteristic`),s.stopNotifications()}));return Promise.allSettled(t)},Un=function(t){An.log("oncharacteristicvaluechanged");const s=t.target;e(this,Cn,"m",Fn).call(this,s)},Fn=function(e){An.log("onCharacteristicValue");const t=e.name;An.assertWithError(Boolean(t),`no name found for characteristic with uuid "${e.uuid}"`),An.log(`oncharacteristicvaluechanged for "${t}" characteristic`);const s=e.value;An.assertWithError(s,`no data found for "${t}" characteristic`),An.log(`data for "${t}" characteristic`,Array.from(new Uint8Array(s.buffer)));try{this.onCharacteristicValueChanged(t,s)}catch(e){An.error(e)}},Rn=function(){An.log("gattserverdisconnected"),this.status="notConnected"};const On=4294967296,Bn=9007199254740992;const Nn={encode:function(e){let t,s=new ArrayBuffer(256),i=new DataView(s),n=0;function r(e){let r=s.byteLength;const a=n+e;for(;r<a;)r<<=1;if(r!==s.byteLength){const e=i;s=new ArrayBuffer(r),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 a(){n+=t}function o(e){a(r(1).setUint8(n,e))}function c(e){const t=r(e.length);for(let s=0;s<e.length;++s)t.setUint8(n+s,e[s]);a()}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){a(r(2).setUint16(n,e))}(t)):t<4294967296?(o(e<<5|26),function(e){a(r(4).setUint32(n,e))}(t)):(o(e<<5|27),function(e){const t=e%On,s=(e-t)/On,i=r(8);i.setUint32(n,s),i.setUint32(n+4,t),a()}(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<=Bn)return h(0,t);if(-Bn<=t&&t<0)return h(1,-(t+1))}return o(251),function(e){a(r(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),g=new DataView(l);for(let e=0;e<n;++e)g.setUint8(e,i.getUint8(e));return l},decode:function(e,t,s){const i=new DataView(e);let n=0;function r(e,t){return n+=e,t}function a(t){return r(t,new Uint8Array(e,n,t))}function o(){return r(1,i.getUint8(n))}function c(){return r(2,i.getUint16(n))}function h(){return r(4,i.getUint32(n))}function l(){return 255===i.getUint8(n)&&(n+=1,!0)}function g(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()*On+h();if(31===e)return-1;throw new Error("Invalid length encoding")}function f(e){const t=o();if(255===t)return-1;const s=g(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 r=1023&s;if(31744===n)n=261120;else if(0!==n)n+=114688;else if(0!==r)return(i?-1:1)*r*5.960464477539063e-8;return t.setUint32(0,i<<16|n<<13|r<<13),t.getFloat32(0)}();case 26:return r(4,i.getFloat32(n));case 27:return r(8,i.getFloat64(n))}if(v=g(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=f(d))>=0;)t+=v,e.push(a(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 a(v);case 3:if(v<0)for(;(v=f(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}},Pn=k("mcumgr",{log:!1}),Vn=0,zn=1,jn=2,Gn=3,qn=0,Hn=1,Jn=8,Qn=0,Kn=2,Zn=3,Xn=5,Yn=0,er=1,tr=5,sr=0;class ir{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(Nn.encode(i))]);const r=255&n.length,a=[e,0,n.length>>8,r,t>>8,255&t,this._seq,s,...n];return this._seq=(this._seq+1)%256,a}_notification(e){Pn.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,r,,a]=e,o=Nn.decode(e.slice(8).buffer),c=256*s+i,h=256*n+r;return Pn.log("mcumgr - Process Message - Group: "+h+", Id: "+a+", Off: "+o.off),h===Hn&&a===er&&o.off?(this._uploadOffset=o.off,void this._uploadNext()):t===Gn&&h===Jn&&a===sr&&o.off?(this._uploadFileOffset=o.off,void this._uploadFileNext()):t===zn&&h===Jn&&a===sr?(this._downloadFileOffset+=o.data.length,null!=o.len&&(this._downloadFileLength=o.len),Pn.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:a,data:o,length:c}),void this._downloadFileNext()):void(this._messageCallback&&this._messageCallback({op:t,group:h,id:a,data:o,length:c}))}cmdReset(){return this._getMessage(jn,qn,Xn)}smpEcho(e){return this._getMessage(jn,qn,Qn,{d:e})}cmdImageState(){return this._getMessage(Vn,Hn,Yn)}cmdImageErase(){return this._getMessage(jn,Hn,tr,{})}cmdImageTest(e){return this._getMessage(jn,Hn,Yn,{hash:e,confirm:!1})}cmdImageConfirm(e){return this._getMessage(jn,Hn,Yn,{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-Nn.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(jn,Hn,er,e);Pn.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?Pn.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?Pn.error("Upload is already in progress."):(this._uploadIsInProgress=!0,this._uploadFileOffset=0,this._uploadFile=e,this._uploadFilename=t,this._uploadFileNext())}async _uploadFileNext(){if(Pn.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-Nn.encode(e).byteLength-8;e.data=new Uint8Array(this._uploadFile.slice(this._uploadFileOffset,this._uploadFileOffset+t)),this._uploadFileOffset+=t;const s=this._getMessage(jn,Jn,sr,e);Pn.log("mcumgr - _uploadNext: Message Length: "+s.length),this._fileUploadNextCallback({packet:s})}async cmdDownloadFile(e,t){this._downloadIsInProgress?Pn.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(Vn,Jn,sr,e);Pn.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 r=`${s[20]}.${s[21]}.${s[22]+256*s[23]}`;return t.version=r,t.hash=[...new Uint8Array(await this._hash(e.slice(0,n+32)))].map((e=>e.toString(16).padStart(2,"0"))).join(""),t}}var nr,rr,ar,or,cr,hr,lr,gr,fr,ur,dr,mr,pr,vr,wr,yr,br,Sr,Er,Mr,Cr;const Dr=k("FirmwareManager",{log:!1}),kr=["smp"],Tr=[...kr,"firmwareImages","firmwareUploadProgress","firmwareStatus","firmwareUploadComplete"],_r=["idle","uploading","uploaded","pending","testing","erasing"];class Wr{constructor(){nr.add(this),ar.set(this,"idle"),cr.set(this,void 0),gr.set(this,void 0),fr.set(this,new ir),e(this,nr,"m",ur).call(this),J(this)}get addEventListenter(){return this.eventDispatcher.addEventListener}get removeEventListener(){return this.eventDispatcher.removeEventListener}get waitForEvent(){return this.eventDispatcher.waitForEvent}parseMessage(t,s){if(Dr.log({messageType:t}),"smp"!==t)throw Error(`uncaught messageType ${t}`);e(this,fr,"f")._notification(Array.from(new Uint8Array(s.buffer))),e(this,nr,"a",rr).call(this,"smp",{dataView:s})}async uploadFirmware(t){Dr.log("uploadFirmware",t);const s=this.waitForEvent("firmwareUploadComplete");await this.getImages();const i=await H(t),n=await e(this,fr,"f").imageInfo(i);Dr.log({imageInfo:n}),e(this,fr,"f").cmdUpload(i,1),e(this,nr,"m",or).call(this,"uploading"),await s}get status(){return e(this,ar,"f")}get images(){return e(this,cr,"f")}async getImages(){const t=this.waitForEvent("firmwareImages");Dr.log("getting firmware image state..."),this.sendMessage(Uint8Array.from(e(this,fr,"f").cmdImageState()).buffer),await t}async testImage(t=1){if(e(this,nr,"m",lr).call(this,t),e(this,nr,"m",hr).call(this),!e(this,cr,"f")[t])return void Dr.log(`image ${t} not found`);if(1==e(this,cr,"f")[t].pending)return void Dr.log(`image ${t} is already pending`);if(e(this,cr,"f")[t].empty)return void Dr.log(`image ${t} is empty`);const s=this.waitForEvent("smp");Dr.log("testing firmware image..."),this.sendMessage(Uint8Array.from(e(this,fr,"f").cmdImageTest(e(this,cr,"f")[t].hash)).buffer),await s}async eraseImage(){e(this,nr,"m",hr).call(this);const t=this.waitForEvent("smp");Dr.log("erasing image..."),this.sendMessage(Uint8Array.from(e(this,fr,"f").cmdImageErase()).buffer),e(this,nr,"m",or).call(this,"erasing"),await t,await this.getImages()}async confirmImage(t=0){if(e(this,nr,"m",lr).call(this,t),e(this,nr,"m",hr).call(this),!0===e(this,cr,"f")[t].confirmed)return void Dr.log(`image ${t} is already confirmed`);const s=this.waitForEvent("smp");Dr.log("confirming image..."),this.sendMessage(Uint8Array.from(e(this,fr,"f").cmdImageConfirm(e(this,cr,"f")[t].hash)).buffer),await s}async echo(t){Dr.assertTypeWithError(t,"string");const s=this.waitForEvent("smp");Dr.log("sending echo..."),this.sendMessage(Uint8Array.from(e(this,fr,"f").smpEcho(t)).buffer),await s}async reset(){const t=this.waitForEvent("smp");Dr.log("resetting..."),this.sendMessage(Uint8Array.from(e(this,fr,"f").cmdReset()).buffer),await t}get mtu(){return e(this,gr,"f")}set mtu(s){t(this,gr,s,"f"),e(this,fr,"f")._mtu=s}}var Ir,Lr,Ur,Fr,Rr,Ar,xr,$r,Or,Br,Nr,Pr,Vr,zr,jr,Gr,qr,Hr;ar=new WeakMap,cr=new WeakMap,gr=new WeakMap,fr=new WeakMap,nr=new WeakSet,rr=function(){return this.eventDispatcher.dispatchEvent},or=function(s){Dr.assertEnumWithError(s,_r),e(this,ar,"f")!=s?(t(this,ar,s,"f"),Dr.log({firmwareStatus:e(this,ar,"f")}),e(this,nr,"a",rr).call(this,"firmwareStatus",{firmwareStatus:e(this,ar,"f")})):Dr.log(`redundant firmwareStatus assignment "${s}"`)},hr=function(){Dr.assertWithError(e(this,cr,"f"),"didn't get imageState")},lr=function(e){Dr.assertTypeWithError(e,"number"),Dr.assertWithError(0==e||1==e,"imageIndex must be 0 or 1")},ur=function(){e(this,fr,"f").onMessage(e(this,nr,"m",dr).bind(this)),e(this,fr,"f").onFileDownloadNext(e(this,nr,"m",mr)),e(this,fr,"f").onFileDownloadProgress(e(this,nr,"m",pr).bind(this)),e(this,fr,"f").onFileDownloadFinished(e(this,nr,"m",vr).bind(this)),e(this,fr,"f").onFileUploadNext(e(this,nr,"m",wr).bind(this)),e(this,fr,"f").onFileUploadProgress(e(this,nr,"m",yr).bind(this)),e(this,fr,"f").onFileUploadFinished(e(this,nr,"m",br).bind(this)),e(this,fr,"f").onImageUploadNext(e(this,nr,"m",Sr).bind(this)),e(this,fr,"f").onImageUploadProgress(e(this,nr,"m",Er).bind(this)),e(this,fr,"f").onImageUploadFinished(e(this,nr,"m",Mr).bind(this))},dr=function({op:t,group:s,id:i,data:n,length:r}){switch(Dr.log("onMcuMessage",...arguments),s){case qn:switch(i){case Qn:Dr.log(`echo "${n.r}"`);break;case Kn:Dr.table(n.tasks);break;case Zn:Dr.log(n)}break;case Hn:if(i===Yn)e(this,nr,"m",Cr).call(this,n);break;default:throw Error(`uncaught mcuMessage group ${s}`)}},mr=function(){Dr.log("onMcuFileDownloadNext",...arguments)},pr=function(){Dr.log("onMcuFileDownloadProgress",...arguments)},vr=function(){Dr.log("onMcuFileDownloadFinished",...arguments)},wr=function(){Dr.log("onMcuFileUploadNext")},yr=function(){Dr.log("onMcuFileUploadProgress")},br=function(){Dr.log("onMcuFileUploadFinished")},Sr=function({packet:e}){Dr.log("onMcuImageUploadNext"),this.sendMessage(Uint8Array.from(e).buffer)},Er=function({percentage:t}){const s=t/100;Dr.log("onMcuImageUploadProgress",...arguments),e(this,nr,"a",rr).call(this,"firmwareUploadProgress",{progress:s})},Mr=async function(){Dr.log("onMcuImageUploadFinished",...arguments),await this.getImages(),e(this,nr,"a",rr).call(this,"firmwareUploadProgress",{progress:100}),e(this,nr,"a",rr).call(this,"firmwareUploadComplete",{})},Cr=function({images:s}){if(!s)return void Dr.log("no images found");t(this,cr,s,"f"),Dr.log("images",e(this,cr,"f"));let i="idle";2==e(this,cr,"f").length&&(e(this,cr,"f")[1].bootable?e(this,cr,"f")[0].confirmed?e(this,cr,"f")[1].pending?(Dr.log("reset to upload to the new firmware image"),i="pending"):(Dr.log("Slot 1 has a valid image. run testImage() to test it or upload a different image."),i="uploaded"):(Dr.log('Slot 0 has a valid image. Click "Confirm Image" to confirm it or wait and the device will swap images back.'),i="testing"):Dr.warn('Slot 1 has a invalid image. Click "Erase Image" to erase it or upload a different image')),1==e(this,cr,"f").length&&(e(this,cr,"f").push({slot:1,empty:!0,version:"Empty",pending:!1,confirmed:!1,bootable:!1,active:!1,permanent:!1}),Dr.log("Select a firmware upload image to upload to slot 1.")),e(this,nr,"m",or).call(this,i),e(this,nr,"a",rr).call(this,"firmwareImages",{firmwareImages:e(this,cr,"f")})};const Jr=k("DeviceManager",{log:!1}),Qr=["deviceConnected","deviceDisconnected","deviceIsConnected","availableDevices","connectedDevices"];class Kr{constructor(){if(Ir.add(this),Lr.set(this,{getType:e(this,Ir,"m",Ur).bind(this),isConnected:e(this,Ir,"m",Gr).bind(this)}),Fr.set(this,[]),Rr.set(this,!1),Ar.set(this,{devices:[]}),xr.set(this,void 0),Or.set(this,"BS.Device"),Vr.set(this,[]),zr.set(this,new I(this,Qr)),Kr.shared&&this!=Kr.shared)throw Error("DeviceManager is a singleton - use DeviceManager.shared");this.CanUseLocalStorage&&(this.UseLocalStorage=!0)}onDevice(t){on(t,e(this,Lr,"f"))}OnDeviceConnectionStatusUpdated(t,s){if("notConnected"==s&&!t.canReconnect&&e(this,Vr,"f").includes(t)){const s=e(this,Vr,"f").indexOf(t);this.AvailableDevices.splice(s,1),e(this,Ir,"m",qr).call(this)}}get ConnectedDevices(){return e(this,Fr,"f")}get UseLocalStorage(){return e(this,Rr,"f")}set UseLocalStorage(s){e(this,Ir,"m",$r).call(this),Jr.assertTypeWithError(s,"boolean"),t(this,Rr,s,"f"),e(this,Rr,"f")&&!e(this,xr,"f")&&e(this,Ir,"m",Nr).call(this)}get CanUseLocalStorage(){return i&&window.localStorage}get AvailableDevices(){return e(this,Vr,"f")}get CanGetDevices(){return i&&navigator.bluetooth?.getDevices}async GetDevices(){if(!i)return void Jr.warn("GetDevices is only available in the browser");if(!navigator.bluetooth)return void Jr.warn("bluetooth is not available in this browser");if(o)return void Jr.warn("bluefy lists too many devices...");if(!navigator.bluetooth.getDevices)return void Jr.warn("bluetooth.getDevices() is not available in this browser");if(!this.CanGetDevices)return void Jr.log("CanGetDevices is false");e(this,xr,"f")||e(this,Ir,"m",Nr).call(this);const t=e(this,xr,"f");if(!t.devices||0==t.devices.length)return void Jr.log("no devices found in configuration");const s=await navigator.bluetooth.getDevices();return Jr.log({bluetoothDevices:s}),s.forEach((s=>{if(!s.gatt)return;let i=t.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 r=this.AvailableDevices.filter((e=>"webBluetooth"==e.connectionType)).find((e=>e.bluetoothId==s.id));if(r)return void(n&&n?.bluetoothId==r.bluetoothId&&n!=r&&(this.AvailableDevices[e(this,Vr,"f").indexOf(r)]=n));if(n)return void this.AvailableDevices.push(n);const a=new $a,o=new $n;o.device=s,s.name&&a._informationManager.updateName(s.name),a._informationManager.updateType(i.type),a.connectionManager=o,this.AvailableDevices.push(a)})),e(this,Ir,"m",qr).call(this),this.AvailableDevices}get AddEventListener(){return e(this,zr,"f").addEventListener}get RemoveEventListener(){return e(this,zr,"f").removeEventListener}get RemoveEventListeners(){return e(this,zr,"f").removeEventListeners}get RemoveAllEventListeners(){return e(this,zr,"f").removeAllEventListeners}_CheckDeviceAvailability(t){t.isConnected||t.isAvailable||!e(this,Vr,"f").includes(t)||(Jr.log("removing device from availableDevices..."),e(this,Vr,"f").splice(e(this,Vr,"f").indexOf(t),1),e(this,Ir,"m",qr).call(this))}}Lr=new WeakMap,Fr=new WeakMap,Rr=new WeakMap,Ar=new WeakMap,xr=new WeakMap,Or=new WeakMap,Vr=new WeakMap,zr=new WeakMap,Ir=new WeakSet,Ur=function(t){e(this,Rr,"f")&&e(this,Ir,"m",Pr).call(this,t.target)},$r=function(){Jr.assertWithError(i,"localStorage is only available in the browser"),Jr.assertWithError(window.localStorage,"localStorage not found")},Br=function(){e(this,Ir,"m",$r).call(this),localStorage.setItem(e(this,Or,"f"),JSON.stringify(e(this,xr,"f")))},Nr=async function(){e(this,Ir,"m",$r).call(this);let s=localStorage.getItem(e(this,Or,"f"));if("string"!=typeof s)return Jr.log("no info found in localStorage"),t(this,xr,Object.assign({},e(this,Ar,"f")),"f"),void e(this,Ir,"m",Br).call(this);try{const e=JSON.parse(s);Jr.log({configuration:e}),t(this,xr,e,"f"),this.CanGetDevices&&await this.GetDevices()}catch(e){Jr.error(e)}},Pr=function(t){if("webBluetooth"!=t.connectionType)return void Jr.log("localStorage is only for webBluetooth devices");e(this,Ir,"m",$r).call(this);const s=e(this,xr,"f").devices.findIndex((e=>e.bluetoothId==t.bluetoothId));-1!=s&&(e(this,xr,"f").devices[s].type=t.type,e(this,Ir,"m",Br).call(this))},jr=function(){return e(this,zr,"f").dispatchEvent},Gr=function(t){const{target:s}=t;if(s.isConnected)if(e(this,Fr,"f").includes(s))Jr.log("device already included");else{if(Jr.log("adding device",s),e(this,Fr,"f").push(s),this.UseLocalStorage&&"webBluetooth"==s.connectionType){const t={type:s.type,bluetoothId:s.bluetoothId},i=e(this,xr,"f").devices.findIndex((e=>e.bluetoothId==t.bluetoothId));-1==i?e(this,xr,"f").devices.push(t):e(this,xr,"f").devices[i]=t,e(this,Ir,"m",Br).call(this)}e(this,Ir,"a",jr).call(this,"deviceConnected",{device:s}),e(this,Ir,"a",jr).call(this,"deviceIsConnected",{device:s}),e(this,Ir,"m",Hr).call(this)}else e(this,Fr,"f").includes(s)?(Jr.log("removing device",s),e(this,Fr,"f").splice(e(this,Fr,"f").indexOf(s),1),e(this,Ir,"a",jr).call(this,"deviceDisconnected",{device:s}),e(this,Ir,"a",jr).call(this,"deviceIsConnected",{device:s}),e(this,Ir,"m",Hr).call(this)):Jr.log("device already not included");if(this.CanGetDevices&&this.GetDevices(),s.isConnected&&!this.AvailableDevices.includes(s)){const t=this.AvailableDevices.find((e=>e.bluetoothId==s.bluetoothId));Jr.log({existingAvailableDevice:t}),t?this.AvailableDevices[this.AvailableDevices.indexOf(t)]=s:this.AvailableDevices.push(s),e(this,Ir,"m",qr).call(this)}this._CheckDeviceAvailability(s)},qr=function(){Jr.log({AvailableDevices:this.AvailableDevices}),e(this,Ir,"a",jr).call(this,"availableDevices",{availableDevices:this.AvailableDevices})},Hr=function(){Jr.log({ConnectedDevices:this.ConnectedDevices}),e(this,Ir,"a",jr).call(this,"connectedDevices",{connectedDevices:this.ConnectedDevices})},Kr.shared=new Kr;var Zr,Xr,Yr,ea,ta,sa,ia,na,ra,aa,oa,ca,ha,la,ga,fa,ua,da,ma,pa,va,wa,ya,ba,Sa,Ea,Ma,Ca,Da,ka,Ta,_a,Wa,Ia,La,Ua,Fa=Kr.shared;const Ra=k("Device",{log:!0}),Aa=["connectionMessage",...Yi,...sn,...tn,...ai,...Rs,...zt,...Ct,...Be,...Ms,...Tr],xa=["isCharging","getBatteryCurrent","getId","getMtu","getName","getType","getCurrentTime","getSensorConfiguration","getSensorScalars","getPressurePositions","maxFileLength","getFileLength","getFileChecksum","getFileType","fileTransferStatus","getTfliteName","getTfliteTask","getTfliteSampleRate","getTfliteSensorTypes","tfliteIsReady","getTfliteCaptureDelay","getTfliteThreshold","getTfliteInferencingEnabled"];class $a{get bluetoothId(){return e(this,sa,"f")?.bluetoothId}get isAvailable(){return e(this,sa,"f")?.isAvailable}constructor(){Zr.add(this),ea.set(this,new I(this,Aa)),sa.set(this,void 0),this.sendTxMessages=e(this,Zr,"m",ia).bind(this),na.set(this,!1),la.set(this,Xr.ReconnectOnDisconnection),ga.set(this,void 0),this.latestConnectionMessages=new Map,ya.set(this,new As),ba.set(this,0),this._informationManager=new oi,Ea.set(this,new jt),Ca.set(this,Xr.ClearSensorConfigurationOnLeave),Da.set(this,new Dt),ka.set(this,new Ri),Ta.set(this,new Ne),_a.set(this,new ks),Wa.set(this,new Wr),this.sendSmpMessage=e(this,Zr,"m",La).bind(this),Ua.set(this,!1),e(this,ya,"f").eventDispatcher=e(this,ea,"f"),this._informationManager.sendMessage=this.sendTxMessages,this._informationManager.eventDispatcher=e(this,ea,"f"),e(this,Ea,"f").sendMessage=this.sendTxMessages,e(this,Ea,"f").eventDispatcher=e(this,ea,"f"),e(this,Da,"f").eventDispatcher=e(this,ea,"f"),e(this,ka,"f").sendMessage=this.sendTxMessages,e(this,_a,"f").sendMessage=this.sendTxMessages,e(this,_a,"f").eventDispatcher=e(this,ea,"f"),e(this,Ta,"f").sendMessage=this.sendTxMessages,e(this,Ta,"f").eventDispatcher=e(this,ea,"f"),e(this,Wa,"f").sendMessage=this.sendSmpMessage,e(this,Wa,"f").eventDispatcher=e(this,ea,"f"),this.addEventListener("getMtu",(()=>{e(this,Wa,"f").mtu=this.mtu,e(this,Ta,"f").mtu=this.mtu,this.connectionManager.mtu=this.mtu})),Fa.onDevice(this),i&&window.addEventListener("beforeunload",(()=>{this.isConnected&&this.clearSensorConfigurationOnLeave&&this.clearSensorConfiguration()})),n&&process.on("exit",(()=>{this.isConnected&&this.clearSensorConfigurationOnLeave&&this.clearSensorConfiguration()}))}get addEventListener(){return e(this,ea,"f").addEventListener}get removeEventListener(){return e(this,ea,"f").removeEventListener}get waitForEvent(){return e(this,ea,"f").waitForEvent}get removeEventListeners(){return e(this,ea,"f").removeEventListeners}get removeAllEventListeners(){return e(this,ea,"f").removeAllEventListeners}get connectionManager(){return e(this,sa,"f")}set connectionManager(s){this.connectionManager!=s?(this.connectionManager&&(this.connectionManager.onStatusUpdated=void 0,this.connectionManager.onMessageReceived=void 0,this.connectionManager.onMessagesReceived=void 0),s&&(s.onStatusUpdated=e(this,Zr,"m",fa).bind(this),s.onMessageReceived=e(this,Zr,"m",va).bind(this),s.onMessagesReceived=e(this,Zr,"m",wa).bind(this)),t(this,sa,s,"f"),Ra.log("assigned new connectionManager",e(this,sa,"f"))):Ra.log("same connectionManager is already assigned")}async connect(){return this.connectionManager||(this.connectionManager=e(Xr,Xr,"m",Yr).call(Xr)),e(this,Zr,"m",ma).call(this),this.connectionManager.connect()}get isConnected(){return e(this,na,"f")}get canReconnect(){return this.connectionManager?.canReconnect}async reconnect(){return e(this,Zr,"m",ca).call(this),e(this,Zr,"m",ma).call(this),this.connectionManager?.reconnect()}static async Connect(){const e=new Xr;return await e.connect(),e}static get ReconnectOnDisconnection(){return e(this,Xr,"f",ha)}static set ReconnectOnDisconnection(e){Ra.assertTypeWithError(e,"boolean"),t(this,Xr,e,"f",ha)}get reconnectOnDisconnection(){return e(this,la,"f")}set reconnectOnDisconnection(e){Ra.assertTypeWithError(e,"boolean"),t(this,la,e,"f")}get connectionType(){return this.connectionManager?.type}async disconnect(){return e(this,Zr,"m",ra).call(this),this.reconnectOnDisconnection&&(this.reconnectOnDisconnection=!1,this.addEventListener("isConnected",(()=>{this.reconnectOnDisconnection=!0}),{once:!0})),this.connectionManager.disconnect()}toggleConnection(){this.isConnected?this.disconnect():this.canReconnect?this.reconnect():this.connect()}get connectionStatus(){switch(e(this,sa,"f")?.status){case"connected":return this.isConnected?"connected":"connecting";case"notConnected":case"connecting":case"disconnecting":return e(this,sa,"f").status;default:return"notConnected"}}get isConnectionBusy(){return"connecting"==this.connectionStatus||"disconnecting"==this.connectionStatus}get deviceInformation(){return e(this,ya,"f").information}get batteryLevel(){return e(this,ba,"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 Et.filter((e=>this.sensorTypes.includes(e)))}get sensorConfiguration(){return e(this,Ea,"f").configuration}async setSensorConfiguration(t,s){await e(this,Ea,"f").setConfiguration(t,s)}async clearSensorConfiguration(){return e(this,Ea,"f").clearSensorConfiguration()}static get ClearSensorConfigurationOnLeave(){return e(this,Xr,"f",Ma)}static set ClearSensorConfigurationOnLeave(e){Ra.assertTypeWithError(e,"boolean"),t(this,Xr,e,"f",Ma)}get clearSensorConfigurationOnLeave(){return e(this,Ca,"f")}set clearSensorConfigurationOnLeave(e){Ra.assertTypeWithError(e,"boolean"),t(this,Ca,e,"f")}get numberOfPressureSensors(){return e(this,Da,"f").pressureSensorDataManager.numberOfSensors}resetPressureRange(){e(this,Da,"f").pressureSensorDataManager.resetRange()}async triggerVibration(t,s){e(this,ka,"f").triggerVibration(t,s)}get maxFileLength(){return e(this,Ta,"f").maxLength}async sendFile(t,s){const i=this.waitForEvent("fileTransferComplete");e(this,Ta,"f").send(t,s),await i}async receiveFile(t){const s=this.waitForEvent("fileTransferComplete");e(this,Ta,"f").receive(t),await s}get fileTransferStatus(){return e(this,Ta,"f").status}cancelFileTransfer(){e(this,Ta,"f").cancel()}get tfliteName(){return e(this,_a,"f").name}get setTfliteName(){return e(this,_a,"f").setName}get tfliteTask(){return e(this,_a,"f").task}get setTfliteTask(){return e(this,_a,"f").setTask}get tfliteSampleRate(){return e(this,_a,"f").sampleRate}get setTfliteSampleRate(){return e(this,_a,"f").setSampleRate}get tfliteSensorTypes(){return e(this,_a,"f").sensorTypes}get allowedTfliteSensorTypes(){return this.sensorTypes.filter((e=>Ds.includes(e)))}get setTfliteSensorTypes(){return e(this,_a,"f").setSensorTypes}get tfliteIsReady(){return e(this,_a,"f").isReady}get tfliteInferencingEnabled(){return e(this,_a,"f").inferencingEnabled}get setTfliteInferencingEnabled(){return e(this,_a,"f").setInferencingEnabled}async enableTfliteInferencing(){return this.setTfliteInferencingEnabled(!0)}async disableTfliteInferencing(){return this.setTfliteInferencingEnabled(!1)}get toggleTfliteInferencing(){return e(this,_a,"f").toggleInferencingEnabled}get tfliteCaptureDelay(){return e(this,_a,"f").captureDelay}get setTfliteCaptureDelay(){return e(this,_a,"f").setCaptureDelay}get tfliteThreshold(){return e(this,_a,"f").threshold}get setTfliteThreshold(){return e(this,_a,"f").setThreshold}get canUpdateFirmware(){return e(this,sa,"f")?.canUpdateFirmware}get uploadFirmware(){return e(this,Zr,"m",Ia).call(this),e(this,Wa,"f").uploadFirmware}async reset(){return e(this,Zr,"m",Ia).call(this),await e(this,Wa,"f").reset(),e(this,sa,"f").disconnect()}get firmwareStatus(){return e(this,Wa,"f").status}get getFirmwareImages(){return e(this,Zr,"m",Ia).call(this),e(this,Wa,"f").getImages}get firmwareImages(){return e(this,Wa,"f").images}get eraseFirmwareImage(){return e(this,Zr,"m",Ia).call(this),e(this,Wa,"f").eraseImage}get confirmFirmwareImage(){return e(this,Zr,"m",Ia).call(this),e(this,Wa,"f").confirmImage}get testFirmwareImage(){return e(this,Zr,"m",Ia).call(this),e(this,Wa,"f").testImage}get isServerSide(){return e(this,Ua,"f")}set isServerSide(s){e(this,Ua,"f")!=s?(Ra.log({newIsServerSide:s}),t(this,Ua,s,"f"),e(this,Ta,"f").isServerSide=this.isServerSide):Ra.log("redundant isServerSide assignment")}get isUkaton(){return this.deviceInformation.modelNumber.includes("Ukaton")}}var Oa,Ba,Na,Pa,Va,za;Xr=$a,ea=new WeakMap,sa=new WeakMap,na=new WeakMap,la=new WeakMap,ga=new WeakMap,ya=new WeakMap,ba=new WeakMap,Ea=new WeakMap,Ca=new WeakMap,Da=new WeakMap,ka=new WeakMap,Ta=new WeakMap,_a=new WeakMap,Wa=new WeakMap,Ua=new WeakMap,Zr=new WeakSet,Yr=function(){return new $n},ta=function(){return e(this,ea,"f").dispatchEvent},ia=async function(t,s){await(e(this,sa,"f")?.sendTxMessages(t,s))},ra=function(){Ra.assertWithError(this.isConnected,"notConnected")},aa=function(){return xa.every((e=>{const t=this.latestConnectionMessages.has(e);return t||Ra.log(`didn't receive "${e}" message`),t}))},oa=function(){const t=xa.map((e=>({type:e})));e(this,Zr,"m",ia).call(this,t)},ca=function(){Ra.assertWithError(this.canReconnect,"cannot reconnect to device")},fa=function(s){Ra.log({connectionStatus:s}),"notConnected"==s?(e(this,Zr,"m",pa).call(this),this.canReconnect&&this.reconnectOnDisconnection&&(Ra.log("starting reconnect interval..."),t(this,ga,setInterval((()=>{Ra.log("attempting reconnect..."),this.reconnect()}),1e3),"f"))):null!=e(this,ga,"f")&&(Ra.log("clearing reconnect interval"),clearInterval(e(this,ga,"f")),t(this,ga,void 0,"f")),e(this,Zr,"m",da).call(this),"connected"!=s||e(this,na,"f")||e(this,Zr,"m",oa).call(this),Fa.OnDeviceConnectionStatusUpdated(this,s)},ua=function(t=!1){e(this,Zr,"a",ta).call(this,"connectionStatus",{connectionStatus:this.connectionStatus}),e(this,Zr,"a",ta).call(this,this.connectionStatus,{}),t&&e(this,Zr,"a",ta).call(this,"isConnected",{isConnected:this.isConnected})},da=function(){switch(t(this,na,Boolean(this.connectionManager?.isConnected)&&e(this,Zr,"a",aa)&&this._informationManager.isCurrentTimeSet,"f"),this.connectionStatus){case"connected":e(this,na,"f")&&e(this,Zr,"m",ua).call(this,!0);break;case"notConnected":e(this,Zr,"m",ua).call(this,!0);break;default:e(this,Zr,"m",ua).call(this,!1)}},ma=function(){e(this,Zr,"m",pa).call(this),this._informationManager.clear(),e(this,ya,"f").clear()},pa=function(){this.connectionManager?.clear(),this.latestConnectionMessages.clear()},va=function(t,s){if(Ra.log({messageType:t,dataView:s}),"batteryLevel"===t){const t=s.getUint8(0);Ra.log("received battery level",{batteryLevel:t}),e(this,Zr,"m",Sa).call(this,t)}else if(Re.includes(t))e(this,Ta,"f").parseMessage(t,s);else if(Es.includes(t))e(this,_a,"f").parseMessage(t,s);else if(Mt.includes(t))e(this,Da,"f").parseMessage(t,s);else if(kr.includes(t))e(this,Wa,"f").parseMessage(t,s);else if(Fs.includes(t))e(this,ya,"f").parseMessage(t,s);else if(ri.includes(t))this._informationManager.parseMessage(t,s);else{if(!Vt.includes(t))throw Error(`uncaught messageType ${t}`);e(this,Ea,"f").parseMessage(t,s)}this.latestConnectionMessages.set(t,s),e(this,Zr,"a",ta).call(this,"connectionMessage",{messageType:t,dataView:s})},wa=function(){!this.isConnected&&e(this,Zr,"a",aa)&&e(this,Zr,"m",da).call(this),"notConnected"!=this.connectionStatus&&e(this,Zr,"m",ia).call(this)},Sa=function(s){Ra.assertTypeWithError(s,"number"),e(this,ba,"f")!=s?(t(this,ba,s,"f"),Ra.log({updatedBatteryLevel:e(this,ba,"f")}),e(this,Zr,"a",ta).call(this,"batteryLevel",{batteryLevel:e(this,ba,"f")})):Ra.log(`duplicate batteryLevel assignment ${s}`)},Ia=function(){Ra.assertWithError(this.canUpdateFirmware,"can't update firmware")},La=function(t){return e(this,Zr,"m",Ia).call(this),e(this,sa,"f").sendSmpMessage(t)},ha={value:!1},Ma={value:!0};const ja=k("DevicePairPressureSensorDataManager",{log:!1});class Ga{constructor(){Oa.add(this),Ba.set(this,{}),Na.set(this,new et),Pa.set(this,new Je),this.resetPressureRange()}resetPressureRange(){e(this,Na,"f").reset(),e(this,Pa,"f").reset()}onDevicePressureData(t){const{pressure:s}=t.message,{side:i}=t.target;if(ja.log({pressure:s,side:i}),e(this,Ba,"f")[i]=s,e(this,Oa,"a",Va))return e(this,Oa,"m",za).call(this);ja.log("doesn't have all pressure data yet...")}}var qa;Ba=new WeakMap,Na=new WeakMap,Pa=new WeakMap,Oa=new WeakSet,Va=function(){return si.every((t=>t in e(this,Ba,"f")))},za=function(){const t={scaledSum:0,normalizedSum:0,sensors:{left:[],right:[]}};return si.forEach((s=>{const i=e(this,Ba,"f")[s];t.scaledSum+=i.scaledSum})),t.normalizedSum+=e(this,Pa,"f").updateAndGetNormalization(t.scaledSum,!1),t.scaledSum>0&&(t.center={x:0,y:0},si.forEach((s=>{e(this,Ba,"f")[s].sensors.forEach((e=>{const i={...e};i.weightedValue=e.scaledValue/t.scaledSum;let{x:n,y:r}=e.position;n/=2,"right"==s&&(n+=.5),i.position={x:n,y:r},t.center.x+=i.position.x*i.weightedValue,t.center.y+=i.position.y*i.weightedValue,t.sensors[s].push(i)}))})),t.normalizedCenter=e(this,Na,"f").updateAndGetNormalization(t.center,!1)),ja.log({devicePairPressure:t}),t};const Ha=k("DevicePairSensorDataManager",{log:!1}),Ja=["pressure","sensorData"];class Qa{constructor(){qa.set(this,{}),this.pressureSensorDataManager=new Ga}get dispatchEvent(){return this.eventDispatcher.dispatchEvent}resetPressureRange(){this.pressureSensorDataManager.resetPressureRange()}onDeviceSensorData(t){const{timestamp:s,sensorType:i}=t.message;let n;if(Ha.log({sensorType:i,timestamp:s,event:t}),e(this,qa,"f")[i]||(e(this,qa,"f")[i]={}),e(this,qa,"f")[i][t.target.side]=s,"pressure"===i)n=this.pressureSensorDataManager.onDevicePressureData(t);else Ha.log(`uncaught sensorType "${i}"`);if(n){const t=Object.assign({},e(this,qa,"f")[i]);this.dispatchEvent(i,{sensorType:i,timestamps:t,[i]:n}),this.dispatchEvent("sensorData",{sensorType:i,timestamps:t,[i]:n})}else Ha.log("no value received")}}var Ka,Za,Xa,Ya,eo,to,so,io,no,ro,ao,oo,co,ho,lo,go,fo,uo,mo;qa=new WeakMap;const po=k("DevicePair",{log:!1});function vo(e){return`device${t=e,t[0].toUpperCase()+t.slice(1)}`;var t}const wo=["isConnected",...Ja,...Aa.map((e=>vo(e)))],yo=["insoles","gloves"];class bo{constructor(s){Ka.add(this),Xa.set(this,void 0),Ya.set(this,new I(this,wo)),to.set(this,void 0),so.set(this,void 0),oo.set(this,{isConnected:e(this,Ka,"m",ho).bind(this),sensorData:e(this,Ka,"m",fo).bind(this),getType:e(this,Ka,"m",lo).bind(this)}),go.set(this,new Qa),t(this,Xa,s,"f"),e(this,go,"f").eventDispatcher=e(this,Ya,"f")}get sides(){return si}get type(){return e(this,Xa,"f")}get addEventListener(){return e(this,Ya,"f").addEventListener}get removeEventListener(){return e(this,Ya,"f").removeEventListener}get waitForEvent(){return e(this,Ya,"f").waitForEvent}get removeEventListeners(){return e(this,Ya,"f").removeEventListeners}get removeAllEventListeners(){return e(this,Ya,"f").removeAllEventListeners}get left(){return e(this,to,"f")}get right(){return e(this,so,"f")}get isConnected(){return si.every((e=>this[e]?.isConnected))}get isPartiallyConnected(){return si.some((e=>this[e]?.isConnected))}get isHalfConnected(){return this.isPartiallyConnected&&!this.isConnected}assignDevice(s){if(!e(this,Ka,"m",io).call(this,s))return void po.warn(`device is incorrect type ${s.type} for ${this.type} devicePair`);const i=s.side,n=this[i];if(s!=n){switch(n&&e(this,Ka,"m",ro).call(this,n),e(this,Ka,"m",no).call(this,s),i){case"left":t(this,to,s,"f");break;case"right":t(this,so,s,"f")}return po.log(`assigned ${i} device`,s),this.resetPressureRange(),e(this,Ka,"a",eo).call(this,"isConnected",{isConnected:this.isConnected}),e(this,Ka,"a",eo).call(this,"deviceIsConnected",{device:s,isConnected:s.isConnected,side:i}),n}po.log("device already assigned")}async setSensorConfiguration(e){for(let t=0;t<si.length;t++){const s=si[t];this[s]?.isConnected&&await this[s].setSensorConfiguration(e)}}resetPressureRange(){si.forEach((e=>this[e]?.resetPressureRange())),e(this,go,"f").resetPressureRange()}async triggerVibration(e,t){const s=si.map((s=>this[s]?.triggerVibration(e,t))).filter(Boolean);return Promise.allSettled(s)}static get insoles(){return e(this,Za,"f",uo)}static get gloves(){return e(this,Za,"f",mo)}}Za=bo,Xa=new WeakMap,Ya=new WeakMap,to=new WeakMap,so=new WeakMap,oo=new WeakMap,go=new WeakMap,Ka=new WeakSet,eo=function(){return e(this,Ya,"f").dispatchEvent},io=function(e){switch(this.type){case"insoles":return e.isInsole;case"gloves":return e.isGlove}},no=function(t){on(t,e(this,oo,"f")),Aa.forEach((s=>{t.addEventListener(s,e(this,Ka,"m",co).bind(this))}))},ro=function(t){cn(t,e(this,oo,"f")),Aa.forEach((s=>{t.removeEventListener(s,e(this,Ka,"m",co).bind(this))}))},ao=function(t){const s=si.some((s=>this[s]==t&&(po.log(`removing ${s} device`,t),cn(t,e(this,oo,"f")),delete this[s],!0)));return s&&e(this,Ka,"a",eo).call(this,"isConnected",{isConnected:this.isConnected}),s},co=function(t){const{type:s,target:i,message:n}=t;e(this,Ka,"a",eo).call(this,vo(s),{...n,device:i,side:i.side})},ho=function(t){e(this,Ka,"a",eo).call(this,"isConnected",{isConnected:this.isConnected})},lo=function(t){const{target:s}=t;if(this[s.side]==s)return;e(this,Ka,"m",ao).call(this,s)&&this.assignDevice(s)},fo=function(t){this.isConnected&&e(this,go,"f").onDeviceSensorData(t)},uo={value:new Za("insoles")},mo={value:new Za("gloves")},Fa.AddEventListener("deviceConnected",(t=>{const{device:s}=t.message;s.isInsole&&e(Za,Za,"f",uo).assignDevice(s),s.isGlove&&e(Za,Za,"f",mo).assignDevice(s)}));const So=k("ServerUtils",{log:!1}),Eo=["isScanningAvailable","isScanning","startScan","stopScan","discoveredDevice","discoveredDevices","expiredDiscoveredDevice","connectToDevice","disconnectFromDevice","connectedDevices","deviceMessage"];function Mo(e,...t){So.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=j(...t.data),i=s.byteLength;So.assertEnumWithError(t.type,e);const n=e.indexOf(t.type),r=new DataView(new ArrayBuffer(2));return r.setUint16(0,i,!0),j(n,r,s)}));return So.log("messageBuffers",...s),j(...s)}function Co(...e){return So.log("createServerMessage",...e),Mo(Eo,...e)}function Do(...e){return So.log("createClientDeviceMessage",...e),Mo(nn,...e)}var ko,To,_o,Wo,Io;Co("isScanningAvailable"),Co("isScanning"),Co("startScan"),Co("stopScan"),Co("discoveredDevices");const Lo=k("ClientConnectionManager",{log:!1}),Uo=[...Fs,"batteryLevel"];class Fo extends rn{constructor(){super(...arguments),ko.add(this),To.set(this,void 0),_o.set(this,!1)}static get isSupported(){return i}static get type(){return"client"}get canUpdateFirmware(){return!1}get bluetoothId(){return e(this,To,"f")}set bluetoothId(s){Lo.assertTypeWithError(s,"string"),e(this,To,"f")!=s?t(this,To,s,"f"):Lo.log("redundant bluetoothId assignment")}get isConnected(){return e(this,_o,"f")}set isConnected(s){Lo.assertTypeWithError(s,"boolean"),e(this,_o,"f")!=s?(t(this,_o,s,"f"),this.status=e(this,_o,"f")?"connected":"notConnected",this.isConnected&&e(this,ko,"m",Wo).call(this)):Lo.log("redundant newIsConnected assignment",s)}get isAvailable(){return this.client.isConnected}async connect(){await super.connect(),this.sendClientConnectMessage()}async disconnect(){await super.disconnect(),this.sendClientDisconnectMessage()}get canReconnect(){return!0}async reconnect(){await super.reconnect(),Lo.log("attempting to reconnect..."),this.connect()}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(t){Lo.log({dataView:t}),wt(t,Aa,e(this,ko,"m",Io).bind(this),null,!0),this.onMessagesReceived()}}var Ro,Ao,xo,$o,Oo,Bo,No,Po,Vo,zo,jo,Go,qo,Ho,Jo,Qo,Ko,Zo,Xo,Yo,ec,tc,sc,ic;To=new WeakMap,_o=new WeakMap,ko=new WeakSet,Wo=function(){this.sendClientMessage(...Uo)},Io=function(e,t){let s=0;switch(Lo.log({messageType:e},t),e){case"isConnected":const i=Boolean(t.getUint8(s++));Lo.log({isConnected:i}),this.isConnected=i;break;case"rx":this.parseRxMessage(t);break;default:this.onMessageReceived(e,t)}};const nc=k("BaseClient",{log:!1}),rc=["notConnected","connecting","connected","disconnecting","connectionStatus","isConnected","isScanningAvailable","isScanning","discoveredDevice","expiredDiscoveredDevice"];class ac{constructor(){Ro.add(this),$o.set(this,{}),Oo.set(this,new I(this,rc)),this._reconnectOnDisconnection=this.baseConstructor.ReconnectOnDisconnection,Bo.set(this,"notConnected"),Vo.set(this,[]),Go.set(this,!1),Qo.set(this,!1),tc.set(this,{})}get baseConstructor(){return this.constructor}get devices(){return e(this,$o,"f")}get addEventListener(){return e(this,Oo,"f").addEventListener}get dispatchEvent(){return e(this,Oo,"f").dispatchEvent}get removeEventListener(){return e(this,Oo,"f").removeEventListener}get waitForEvent(){return e(this,Oo,"f").waitForEvent}assertConnection(){nc.assertWithError(this.isConnected,"notConnected")}assertDisconnection(){nc.assertWithError(this.isDisconnected,"not disconnected")}static get ReconnectOnDisconnection(){return this._reconnectOnDisconnection}static set ReconnectOnDisconnection(e){nc.assertTypeWithError(e,"boolean"),this._reconnectOnDisconnection=e}get reconnectOnDisconnection(){return this._reconnectOnDisconnection}set reconnectOnDisconnection(e){nc.assertTypeWithError(e,"boolean"),this._reconnectOnDisconnection=e}get _connectionStatus(){return e(this,Bo,"f")}set _connectionStatus(s){switch(nc.assertTypeWithError(s,"string"),nc.log({newConnectionStatus:s}),t(this,Bo,s,"f"),this.dispatchEvent("connectionStatus",{connectionStatus:this.connectionStatus}),this.dispatchEvent(this.connectionStatus,{}),s){case"connected":case"notConnected":this.dispatchEvent("isConnected",{isConnected:this.isConnected}),this.isConnected||e(this,Ro,"m",xo).call(this)}}get connectionStatus(){return this._connectionStatus}_sendRequiredMessages(){nc.log("sending required messages",e(this,Vo,"f")),this.sendServerMessage(...e(this,Ro,"a",Po))}parseMessage(t){nc.log("parseMessage",{dataView:t}),wt(t,Eo,e(this,Ro,"m",jo).bind(this),null,!0),e(this,Ro,"m",zo).call(this)}get isScanningAvailable(){return e(this,Ro,"a",qo)}requestIsScanningAvailable(){this.sendServerMessage("isScanningAvailable")}get isScanning(){return e(this,Ro,"a",Ko)}startScan(){e(this,Ro,"m",ec).call(this),this.sendServerMessage("startScan")}stopScan(){e(this,Ro,"m",Yo).call(this),this.sendServerMessage("stopScan")}toggleScan(){e(this,Ro,"m",Jo).call(this),this.isScanning?this.stopScan():this.startScan()}get discoveredDevices(){return e(this,tc,"f")}onDiscoveredDevice(t){nc.log({discoveredDevice:t}),e(this,tc,"f")[t.bluetoothId]=t,this.dispatchEvent("discoveredDevice",{discoveredDevice:t})}requestDiscoveredDevices(){this.sendServerMessage({type:"discoveredDevices"})}connectToDevice(e){return this.requestConnectionToDevice(e)}requestConnectionToDevice(t){this.assertConnection(),nc.assertTypeWithError(t,"string");const s=e(this,Ro,"m",ic).call(this,t);return s.connect(),s}sendConnectToDeviceMessage(e){this.sendServerMessage({type:"connectToDevice",data:e})}createDevice(e){const t=new $a,s=new Fo;return s.client=this,s.bluetoothId=e,s.sendClientMessage=this.sendDeviceMessage.bind(this,e),s.sendClientConnectMessage=this.sendConnectToDeviceMessage.bind(this,e),s.sendClientDisconnectMessage=this.sendDisconnectFromDeviceMessage.bind(this,e),t.connectionManager=s,t}onConnectedBluetoothDeviceIds(t){nc.log({bluetoothIds:t}),t.forEach((t=>{const s=e(this,Ro,"m",ic).call(this,t);s.connectionManager.isConnected=!0,Fa._CheckDeviceAvailability(s)}))}disconnectFromDevice(e){this.requestDisconnectionFromDevice(e)}requestDisconnectionFromDevice(e){this.assertConnection(),nc.assertTypeWithError(e,"string");const t=this.devices[e];return nc.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,Do(...t)]})}}Ao=ac,$o=new WeakMap,Oo=new WeakMap,Bo=new WeakMap,Vo=new WeakMap,Go=new WeakMap,Qo=new WeakMap,tc=new WeakMap,Ro=new WeakSet,xo=function(){t(this,Ro,!1,"a",Ho),t(this,Ro,!1,"a",Zo);for(const t in e(this,$o,"f")){e(this,$o,"f")[t].connectionManager.isConnected=!1}e(this,Vo,"f").length=0},Po=function(){return e(Ao,Ao,"f",No)},zo=function(){"connecting"==this.connectionStatus&&(nc.log("checking if fully connected..."),e(this,Vo,"f").includes("isScanningAvailable")?!this.isScanningAvailable||e(this,Vo,"f").includes("isScanning")?(nc.log("fully connected"),this._connectionStatus="connected"):nc.log("not fully connected - didn't receive isScanning"):nc.log("not fully connected - didn't receive isScanningAvailable"))},jo=function(s,i){let n=0;switch(nc.log({messageType:s},i),s){case"isScanningAvailable":{const e=Boolean(i.getUint8(n++));nc.log({isScanningAvailable:e}),t(this,Ro,e,"a",Ho)}break;case"isScanning":{const e=Boolean(i.getUint8(n++));nc.log({isScanning:e}),t(this,Ro,e,"a",Zo)}break;case"discoveredDevice":{const{string:e}=vt(i,n);nc.log({discoveredDeviceString:e});const t=JSON.parse(e);nc.log({discoveredDevice:t}),this.onDiscoveredDevice(t)}break;case"expiredDiscoveredDevice":{const{string:t}=vt(i,n);e(this,Ro,"m",sc).call(this,t)}break;case"connectedDevices":{if(0==i.byteLength)break;const{string:e}=vt(i,n);nc.log({connectedBluetoothDeviceIdStrings:e});const t=JSON.parse(e).connectedDevices;nc.log({connectedBluetoothDeviceIds:t}),this.onConnectedBluetoothDeviceIds(t)}break;case"deviceMessage":{const{string:t,byteOffset:s}=vt(i,n);n=s;const r=e(this,$o,"f")[t];nc.assertWithError(r,`no device found for id ${t}`);const a=r.connectionManager,o=q(i,n);a.onClientMessage(o)}break;default:nc.error(`uncaught messageType "${s}"`)}"connecting"==this.connectionStatus&&e(this,Vo,"f").push(s)},qo=function(){return e(this,Go,"f")},Ho=function(s){nc.assertTypeWithError(s,"boolean"),t(this,Go,s,"f"),this.dispatchEvent("isScanningAvailable",{isScanningAvailable:this.isScanningAvailable}),this.isScanningAvailable&&e(this,Ro,"m",Xo).call(this)},Jo=function(){this.assertConnection(),nc.assertWithError(this.isScanningAvailable,"scanning is not available")},Ko=function(){return e(this,Qo,"f")},Zo=function(e){nc.assertTypeWithError(e,"boolean"),t(this,Qo,e,"f"),this.dispatchEvent("isScanning",{isScanning:this.isScanning})},Xo=function(){this.sendServerMessage("isScanning")},Yo=function(){nc.assertWithError(this.isScanning,"is not scanning")},ec=function(){nc.assertWithError(!this.isScanning,"is already scanning")},sc=function(t){nc.log({expiredBluetoothDeviceId:t});const s=e(this,tc,"f")[t];s?(nc.log({expiredDiscoveredDevice:s}),delete e(this,tc,"f")[t],this.dispatchEvent("expiredDiscoveredDevice",{discoveredDevice:s})):nc.warn(`no discoveredDevice found with id "${t}"`)},ic=function(t){let s=e(this,$o,"f")[t];return s||(s=this.createDevice(t),e(this,$o,"f")[t]=s),s},ac._reconnectOnDisconnection=!0,No={value:["isScanningAvailable","discoveredDevices","connectedDevices"]};const oc=k("WebSocketUtils",{log:!1}),cc=["ping","pong","serverMessage"];function hc(...e){return oc.log("createWebSocketMessage",...e),Mo(cc,...e)}var lc,gc,fc,uc,dc,mc,pc,vc,wc,yc,bc,Sc,Ec;hc("ping"),hc("pong");const Mc=k("WebSocketClient",{log:!1});class Cc extends ac{constructor(){super(...arguments),lc.add(this),gc.set(this,void 0),uc.set(this,{open:e(this,lc,"m",dc).bind(this),message:e(this,lc,"m",mc).bind(this),close:e(this,lc,"m",pc).bind(this),error:e(this,lc,"m",vc).bind(this)}),bc.set(this,new A(e(this,lc,"m",Sc).bind(this),3e7))}get webSocket(){return e(this,gc,"f")}set webSocket(s){e(this,gc,"f")!=s?(Mc.log("assigning webSocket",s),e(this,gc,"f")&&cn(e(this,gc,"f"),e(this,uc,"f")),on(s,e(this,uc,"f")),t(this,gc,s,"f"),Mc.log("assigned webSocket")):Mc.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(t){this.assertConnection(),e(this,gc,"f").send(t)}sendServerMessage(...e){this.sendMessage(hc({type:"serverMessage",data:Co(...e)}))}}gc=new WeakMap,uc=new WeakMap,bc=new WeakMap,lc=new WeakSet,fc=function(...e){this.sendMessage(hc(...e))},dc=function(t){Mc.log("webSocket.open",t),e(this,bc,"f").start(),this._sendRequiredMessages()},mc=async function(t){Mc.log("webSocket.message",t),e(this,bc,"f").restart();const s=await t.data.arrayBuffer(),i=new DataView(s);e(this,lc,"m",wc).call(this,i)},pc=function(t){Mc.log("webSocket.close",t),this._connectionStatus="notConnected",Object.entries(this.devices).forEach((([e,t])=>{t.connectionManager.isConnected=!1})),e(this,bc,"f").stop(),this.reconnectOnDisconnection&&setTimeout((()=>{this.reconnect()}),3e3)},vc=function(e){Mc.error("webSocket.error",e.message)},wc=function(t){wt(t,cc,e(this,lc,"m",yc).bind(this),null,!0)},yc=function(t,s){switch(t){case"ping":e(this,lc,"m",Ec).call(this);break;case"pong":break;case"serverMessage":this.parseMessage(s);break;default:Mc.error(`uncaught messageType "${t}"`)}},Sc=function(){e(this,lc,"m",fc).call(this,"ping")},Ec=function(){e(this,lc,"m",fc).call(this,"pong")};export{Et as ContinuousSensorTypes,nt as DefaultNumberOfPressureSensors,$a as Device,Fa as DeviceManager,bo as DevicePair,yo as DevicePairTypes,ti as DeviceTypes,w as Environment,Oe as FileTransferDirections,Ae as FileTypes,ni as MaxNameLength,_i as MaxNumberOfVibrationWaveformEffectSegments,Ui as MaxNumberOfVibrationWaveformSegments,Nt as MaxSensorRate,Ii as MaxVibrationWaveformEffectSegmentDelay,Li as MaxVibrationWaveformEffectSegmentLoopCount,Fi as MaxVibrationWaveformEffectSequenceLoopCount,Wi as MaxVibrationWaveformSegmentDuration,ii as MinNameLength,Je as RangeHelper,Pt as SensorRateStep,St as SensorTypes,si as Sides,Ds as TfliteSensorTypes,Cs as TfliteTasks,ki as VibrationLocations,Ti as VibrationTypes,ci as VibrationWaveformEffects,Cc as WebSocketClient,_ as setAllConsoleLevelFlags,T as setConsoleLevelFlagsForType};
5
+ function e(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 t(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 s=!1,i="undefined"!=typeof window&&void 0!==window?.document,n="undefined"!=typeof process&&null!=process?.versions?.node,a=i&&navigator.userAgent||"";let r=!1;i?r=Boolean(navigator.bluetooth):n&&(r=!0);const o=i&&/Bluefy/i.test(a),c=i&&/WebBLE/i.test(a),h=i&&/Android/i.test(a),l=i&&/Safari/i.test(a)&&!/Chrome/i.test(a),f=i&&/iPad|iPhone|iPod/i.test(a),g=i&&/Macintosh/i.test(a),u=!i&&!n&&"undefined"!=typeof global&&"undefined"!=typeof Studio;var d,m,p,v,w=Object.freeze({__proto__:null,isAndroid:h,get isBluetoothSupported(){return r},isIOS:f,isInBluefy:o,isInBrowser:i,isInDev:s,isInLensStudio:u,isInNode:n,isInProduction:!0,isInWebBLE:c,isMac:g,isSafari:l});if(u){const e=function(...e){Studio.log(e.map((e=>new String(e))).join(","))};(v={}).log=e,v.warn=e.bind(v,"WARNING"),v.error=e.bind(v,"ERROR")}else v=console;function y(e){return(...t)=>{if(n){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(!v.assert){const e=(e,...t)=>{e||v.warn(...t)};v.assert=e}if(!v.table){const e=(...e)=>{v.log(...e)};v.table=e}function b(){}const S=n?y(v.log.bind(v)):v.log.bind(v),C=n?y(v.warn.bind(v)):v.warn.bind(v),E=n?y(v.error.bind(v)):v.error.bind(v),k=n?y(v.table.bind(v)):v.table.bind(v),M=v.assert.bind(v);class D{constructor(t){if(p.set(this,{log:s,warn:s,assert:!0,error:!0,table:!0}),e(d,d,"f",m)[t])throw new Error(`"${t}" console already exists`);e(d,d,"f",m)[t]=this}setLevelFlags(t){Object.assign(e(this,p,"f"),t)}static setLevelFlagsForType(t,s){if(!e(this,d,"f",m)[t])throw new Error(`no console found with type "${t}"`);e(this,d,"f",m)[t].setLevelFlags(s)}static setAllLevelFlags(t){for(const s in e(this,d,"f",m))e(this,d,"f",m)[s].setLevelFlags(t)}static create(t,s){return e(this,d,"f",m)[t]||new d(t)}get log(){return e(this,p,"f").log?S:b}get warn(){return e(this,p,"f").warn?C:b}get error(){return e(this,p,"f").error?E:b}get assert(){return e(this,p,"f").assert?M:b}get table(){return e(this,p,"f").table?k:b}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 T(e,t){return D.create(e,t)}function W(e,t){D.setLevelFlagsForType(e,t)}function I(e){D.setAllLevelFlags(e)}d=D,p=new WeakMap,m={value:{}};const _=T("EventDispatcher",{log:!1});class L{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&&_.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]=[],_.log(`creating "${e}" listeners array`,this.listeners[e]));this.listeners[e].find((e=>e.listener==t&&e.once==s.once))?_.log("already added listener"):(_.log(`adding "${e}" listener`,t,s),this.listeners[e].push({listener:t,once:s.once}),_.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]&&(_.log(`removing "${e}" listener...`,t),this.listeners[e].forEach((s=>{s.listener===t&&(_.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]&&(_.log(`removing "${e}" listeners...`),this.listeners[e]=[])}removeAllEventListeners(){_.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||(_.log(`dispatching "${e}" listener`,s),s.listener({type:e,target:this.target,message:t}),s.once&&(_.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 U,F,A;const R=T("Timer",{log:!1});class x{get callback(){return e(this,U,"f")}set callback(e){R.assertTypeWithError(e,"function"),R.log({newCallback:e}),t(this,U,e,"f"),this.isRunning&&this.restart()}get interval(){return e(this,F,"f")}set interval(e){R.assertTypeWithError(e,"number"),R.assertWithError(e>0,"interval must be above 0"),R.log({newInterval:e}),t(this,F,e,"f"),this.isRunning&&this.restart()}constructor(e,t){U.set(this,void 0),F.set(this,void 0),A.set(this,void 0),this.interval=t,this.callback=e}get isRunning(){return null!=e(this,A,"f")}start(s=!1){this.isRunning?R.log("interval already running"):(R.log(`starting interval every ${e(this,F,"f")}ms`),t(this,A,setInterval(e(this,U,"f"),e(this,F,"f")),"f"),s&&e(this,U,"f").call(this))}stop(){this.isRunning?(R.log("stopping interval"),clearInterval(e(this,A,"f")),t(this,A,void 0,"f")):R.log("interval already not running")}restart(e=!1){this.stop(),this.start(e)}}function $(e){for(let t=0;t<8;++t)e=(1&e?0:3988292384)^e>>>1;return 4278190080^e}U=new WeakMap,F=new WeakMap,A=new WeakMap,T("checksum",{log:!1});const O=new Uint32Array(256);for(let e=0;e<256;++e)O[e]=$(e);function B(e){let t=new Uint8Array(e),s=0;for(let e=0;e<t.byteLength;++e){const i=255&s,n=t[e];s=(O[i^n]^s>>>8)>>>0}return s}var P,N;P="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 V=new P,q=new N,z=T("ArrayBufferUtils",{log:!1});function j(...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 G(e)}if(e instanceof Array){return j(...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 G(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 G(e){const t=V.encode(e);return j(t.byteLength,t)}function H(e,t,s){let i;return null!=s&&(i=e.byteOffset+t+s),z.log({dataView:e,begin:t,end:i,length:s}),new DataView(e.buffer.slice(e.byteOffset+t,i))}async function J(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 K(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 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,ke,Me,De,Te,We,Ie,_e,Le,Ue,Fe,Ae,Re,xe;const $e=T("FileTransferManager",{log:!1}),Oe=["getFileTypes","maxFileLength","getFileType","setFileType","getFileLength","setFileLength","getFileChecksum","setFileChecksum","setFileTransferCommand","fileTransferStatus","getFileBlock","setFileBlock","fileBytesTransferred"],Be=["tflite","wifiServerCert","wifiServerKey"],Pe=["idle","sending","receiving"],Ne=["startSend","startReceive","cancel"],Ve=["sending","receiving"],qe=[...Oe,"fileTransferProgress","fileTransferComplete","fileReceived"],ze=["maxFileLength","getFileLength","getFileChecksum","getFileType","fileTransferStatus"];class je{constructor(){Q.add(this),ie.set(this,[]),re.set(this,Z.MaxLength),le.set(this,void 0),de.set(this,0),we.set(this,0),Ee.set(this,"idle"),We.set(this,[]),_e.set(this,void 0),Le.set(this,0),Re.set(this,!1),xe.set(this,!1),K(this)}get addEventListener(){return this.eventDispatcher.addEventListener}get removeEventListener(){return this.eventDispatcher.removeEventListener}get waitForEvent(){return this.eventDispatcher.waitForEvent}get fileTypes(){return e(this,ie,"f")}static get MaxLength(){return e(this,Z,"f",ae)}get maxLength(){return e(this,re,"f")}get type(){return e(this,le,"f")}get length(){return e(this,de,"f")}get checksum(){return e(this,we,"f")}get status(){return e(this,Ee,"f")}parseMessage(t,s){switch($e.log({messageType:t}),t){case"getFileTypes":e(this,Q,"m",ne).call(this,s);break;case"maxFileLength":e(this,Q,"m",oe).call(this,s);break;case"getFileType":case"setFileType":e(this,Q,"m",fe).call(this,s);break;case"getFileLength":case"setFileLength":e(this,Q,"m",me).call(this,s);break;case"getFileChecksum":case"setFileChecksum":e(this,Q,"m",ye).call(this,s);break;case"fileTransferStatus":e(this,Q,"m",ke).call(this,s);break;case"getFileBlock":e(this,Q,"m",Ie).call(this,s);break;case"fileBytesTransferred":e(this,Q,"m",Ae).call(this,s);break;default:throw Error(`uncaught messageType ${t}`)}}async send(t,s){e(this,Q,"m",De).call(this),e(this,Q,"m",Y).call(this,t);const i=await J(s),n=i.byteLength,a=B(i);if(t!=this.type)$e.log("different fileTypes - sending");else if(n!=this.length)$e.log("different fileLengths - sending");else{if(a==this.checksum)return $e.log("already sent file"),!1;$e.log("different fileChecksums - sending")}const r=[];return r.push(e(this,Q,"m",ue).call(this,t,!1)),r.push(e(this,Q,"m",ve).call(this,n,!1)),r.push(e(this,Q,"m",Se).call(this,a,!1)),r.push(e(this,Q,"m",Ce).call(this,"startSend",!1)),this.sendMessage(),await Promise.all(r),await e(this,Q,"m",Ue).call(this,i),!0}async receive(t){e(this,Q,"m",De).call(this),e(this,Q,"m",Y).call(this,t),await e(this,Q,"m",ue).call(this,t),await e(this,Q,"m",Ce).call(this,"startReceive")}async cancel(){e(this,Q,"m",Te).call(this),$e.log("cancelling file transfer..."),t(this,Re,!0,"f"),await e(this,Q,"m",Ce).call(this,"cancel")}get isServerSide(){return e(this,xe,"f")}set isServerSide(s){e(this,xe,"f")!=s?($e.log({newIsServerSide:s}),t(this,xe,s,"f")):$e.log("redundant isServerSide assignment")}requestRequiredInformation(){$e.log("requesting required fileTransfer information");const e=ze.map((e=>({type:e})));this.sendMessage(e,!1)}}Z=je,ie=new WeakMap,re=new WeakMap,le=new WeakMap,de=new WeakMap,we=new WeakMap,Ee=new WeakMap,We=new WeakMap,_e=new WeakMap,Le=new WeakMap,Re=new WeakMap,xe=new WeakMap,Q=new WeakSet,X=function(){return this.eventDispatcher.dispatchEvent},Y=function(e){$e.assertEnumWithError(e,Be)},ee=function(e){$e.assertWithError(e in Be,`invalid typeEnum ${e}`)},te=function(e){$e.assertWithError(e in Pe,`invalid statusEnum ${e}`)},se=function(e){$e.assertEnumWithError(e,Ne)},ne=function(s){const i=Array.from(new Uint8Array(s.buffer)).map((e=>Be[e])).filter(Boolean);t(this,ie,i,"f"),$e.log("fileTypes",i),e(this,Q,"a",X).call(this,"getFileTypes",{fileTypes:e(this,ie,"f")})},oe=function(t){$e.log("parseFileMaxLength",t);const s=t.getUint32(0,!0);$e.log(`maxLength: ${s/1024}kB`),e(this,Q,"m",ce).call(this,s)},ce=function(s){$e.log({maxLength:s}),t(this,re,s,"f"),e(this,Q,"a",X).call(this,"maxFileLength",{maxFileLength:s})},he=function(e){$e.assertWithError(e<=this.maxLength,`file length ${e}kB too large - must be ${this.maxLength}kB or less`)},fe=function(t){$e.log("parseFileType",t);const s=t.getUint8(0);e(this,Q,"m",ee).call(this,s);const i=Be[s];e(this,Q,"m",ge).call(this,i)},ge=function(s){$e.log({fileTransferType:s}),t(this,le,s,"f"),e(this,Q,"a",X).call(this,"getFileType",{fileType:s})},ue=async function(t,s){if(e(this,Q,"m",Y).call(this,t),this.type==t)return void $e.log(`redundant type assignment ${t}`);const i=this.waitForEvent("getFileType"),n=Be.indexOf(t);this.sendMessage([{type:"setFileType",data:Uint8Array.from([n]).buffer}],s),await i},me=function(t){$e.log("parseFileLength",t);const s=t.getUint32(0,!0);e(this,Q,"m",pe).call(this,s)},pe=function(s){$e.log(`length: ${s/1024}kB`),t(this,de,s,"f"),e(this,Q,"a",X).call(this,"getFileLength",{fileLength:s})},ve=async function(t,s){if($e.assertTypeWithError(t,"number"),e(this,Q,"m",he).call(this,t),this.length==t)return void $e.log(`redundant length assignment ${t}`);const i=this.waitForEvent("getFileLength"),n=new DataView(new ArrayBuffer(4));n.setUint32(0,t,!0),this.sendMessage([{type:"setFileLength",data:n.buffer}],s),await i},ye=function(t){$e.log("checksum",t);const s=t.getUint32(0,!0);e(this,Q,"m",be).call(this,s)},be=function(s){$e.log({checksum:s}),t(this,we,s,"f"),e(this,Q,"a",X).call(this,"getFileChecksum",{fileChecksum:s})},Se=async function(e,t){if($e.assertTypeWithError(e,"number"),this.checksum==e)return void $e.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},Ce=async function(t,s){e(this,Q,"m",se).call(this,t);const i=this.waitForEvent("fileTransferStatus");$e.log(`setting command ${t}`);const n=Ne.indexOf(t);this.sendMessage([{type:"setFileTransferCommand",data:Uint8Array.from([n]).buffer}],s),await i},ke=function(t){$e.log("parseFileStatus",t);const s=t.getUint8(0);e(this,Q,"m",te).call(this,s);const i=Pe[s];e(this,Q,"m",Me).call(this,i)},Me=function(s){$e.log({status:s}),t(this,Ee,s,"f"),e(this,Q,"a",X).call(this,"fileTransferStatus",{fileTransferStatus:s}),e(this,We,"f").length=0,t(this,Re,!1,"f")},De=function(){$e.assertWithError("idle"==e(this,Ee,"f"),"status is not idle")},Te=function(){$e.assertWithError("idle"!=e(this,Ee,"f"),"status is idle")},Ie=async function(t){$e.log("parseFileBlock",t),e(this,We,"f").push(t.buffer);const s=e(this,We,"f").reduce(((e,t)=>e+t.byteLength),0),i=s/e(this,de,"f");if($e.log(`received ${s} of ${e(this,de,"f")} bytes (${100*i}%)`),e(this,Q,"a",X).call(this,"fileTransferProgress",{progress:i}),s!=e(this,de,"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}])}$e.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(e(this,We,"f"),a):new Blob(e(this,We,"f"));const r=B(await n.arrayBuffer());$e.log({checksum:r}),r==e(this,we,"f")?($e.log("received file",n),e(this,Q,"a",X).call(this,"getFileBlock",{fileTransferBlock:t}),e(this,Q,"a",X).call(this,"fileTransferComplete",{direction:"receiving"}),e(this,Q,"a",X).call(this,"fileReceived",{file:n})):$e.error(`wrong checksum - expected ${e(this,we,"f")}, got ${r}`)},Ue=async function(s){return t(this,_e,s,"f"),t(this,Le,0,"f"),e(this,Q,"m",Fe).call(this)},Fe=async function(){if("sending"!=this.status)return;if(e(this,Re,"f"))return void $e.error("not sending block - busy cancelling");if(!e(this,_e,"f"))return void(this.isServerSide||$e.error("no buffer defined"));const s=e(this,_e,"f");let i=e(this,Le,"f");const n=s.slice(i,i+(this.mtu-3-3));$e.log("slicedBuffer",n);const a=1-(s.byteLength-i)/s.byteLength;$e.log(`sending bytes ${i}-${i+n.byteLength} of ${s.byteLength} bytes (${100*a}%)`),e(this,Q,"a",X).call(this,"fileTransferProgress",{progress:a}),0==n.byteLength?($e.log("finished sending buffer"),e(this,Q,"a",X).call(this,"fileTransferComplete",{direction:"sending"})):(await this.sendMessage([{type:"setFileBlock",data:n}]),t(this,Le,i+n.byteLength,"f"))},Ae=async function(t){$e.log("parseBytesTransferred",t);const s=t.getUint32(0,!0);if($e.log({bytesTransferred:s}),"sending"==this.status)return this.isServerSide||e(this,Le,"f")==s?void e(this,Q,"m",Fe).call(this):($e.error(`bytesTransferred are not equal - got ${s}, expected ${e(this,Le,"f")}`),void this.cancel());$e.error("not currently sending file")},ae={value:0};const Ge=T("MathUtils",{log:!1});const He=65536;function Je(e,t){const s=Date.now();var i;let n=(i=s)-i%He+e.getUint16(t,!0);return Math.abs(s-n)>6e4&&(Ge.log("correcting timestamp delta"),n+=He*Math.sign(s-n)),n}var Ke,Qe,Ze;const Xe={min:1/0,max:-1/0,span:0};class Ye{constructor(){Ke.add(this),Qe.set(this,Object.assign({},Xe))}get min(){return e(this,Qe,"f").min}get max(){return e(this,Qe,"f").max}set min(t){e(this,Qe,"f").min=t,e(this,Qe,"f").max=Math.max(t,e(this,Qe,"f").max),e(this,Ke,"m",Ze).call(this)}set max(t){e(this,Qe,"f").max=t,e(this,Qe,"f").min=Math.min(t,e(this,Qe,"f").min),e(this,Ke,"m",Ze).call(this)}reset(){Object.assign(e(this,Qe,"f"),Xe)}update(t){e(this,Qe,"f").min=Math.min(t,e(this,Qe,"f").min),e(this,Qe,"f").max=Math.max(t,e(this,Qe,"f").max),e(this,Ke,"m",Ze).call(this)}getNormalization(t,s){let i=function(e,t,s,i){return null==i&&(i=s-t),(e-t)/i}(t,e(this,Qe,"f").min,e(this,Qe,"f").max,e(this,Qe,"f").span);return s&&(i*=e(this,Qe,"f").span),i||0}updateAndGetNormalization(e,t){return this.update(e),this.getNormalization(e,t)}}var et,tt,st,it,nt;Qe=new WeakMap,Ke=new WeakSet,Ze=function(){e(this,Qe,"f").span=e(this,Qe,"f").max-e(this,Qe,"f").min};class at{constructor(){et.set(this,{x:new Ye,y:new Ye})}reset(){e(this,et,"f").x.reset(),e(this,et,"f").y.reset()}update(t){e(this,et,"f").x.update(t.x),e(this,et,"f").y.update(t.y)}getNormalization(t,s){return{x:e(this,et,"f").x.getNormalization(t.x,s),y:e(this,et,"f").y.getNormalization(t.y,s)}}updateAndGetNormalization(e,t){return this.update(e),this.getNormalization(e,t)}}et=new WeakMap;const rt=T("PressureDataManager",{log:!1}),ot=["pressure"],ct=ot,ht=8;class lt{constructor(){tt.set(this,[]),st.set(this,void 0),it.set(this,new Ye),nt.set(this,new at)}get positions(){return e(this,tt,"f")}get numberOfSensors(){return this.positions.length}parsePositions(e){const s=[];for(let t=0,i=0;i<e.byteLength;t++,i+=2)s.push({x:e.getUint8(i)/256,y:e.getUint8(i+1)/256});var i,n;rt.log({positions:s}),t(this,tt,s,"f"),t(this,st,(i=this.numberOfSensors,n=()=>new Ye,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(){e(this,st,"f")?.forEach((e=>e.reset())),e(this,nt,"f").reset(),e(this,it,"f").reset()}parseData(t,s){const i={sensors:[],scaledSum:0,normalizedSum:0};for(let n=0,a=0;a<t.byteLength;n++,a+=2){const r=t.getUint16(a,!0);let o=r*s/this.numberOfSensors;const c=e(this,st,"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=e(this,it,"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=e(this,nt,"f").updateAndGetNormalization(i.center,!1)),rt.log({pressure:i}),i}}tt=new WeakMap,st=new WeakMap,it=new WeakMap,nt=new WeakMap;const ft=T("MotionSensorDataManager",{log:!1}),gt=["still","walking","running","bicycle","vehicle","tilting"],ut=["portraitUpright","landscapeLeft","portraitUpsideDown","landscapeRight","unknown"];class dt{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 ft.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 ft.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 ft.log({euler:a}),a}parseStepCounter(e){ft.log("parseStepCounter",e);const t=e.getUint32(0,!0);return ft.log({stepCount:t}),t}parseActivity(e){ft.log("parseActivity",e);const t={},s=e.getUint8(0);return ft.log("activityBitfield",s.toString(2)),gt.forEach(((e,i)=>{t[e]=Boolean(s&1<<i)})),ft.log("activity",t),t}parseDeviceOrientation(e){ft.log("parseDeviceOrientation",e);const t=e.getUint8(0),s=ut[t];return ft.assertWithError(s,"undefined deviceOrientation"),ft.log({deviceOrientation:s}),s}}var mt,pt;const vt=["barometer"],wt=vt,yt=T("BarometerSensorDataManager",{log:!1});class bt{constructor(){mt.add(this)}parseData(t,s){const i=t.getUint32(0,!0)*s,n=e(this,mt,"m",pt).call(this,i);return yt.log({pressure:i,altitude:n}),{pressure:i}}}mt=new WeakSet,pt=function(e){const t=.0065;return 288.15/t*(1-Math.pow(e/101325,.19026643566373183))};const St=T("ParseUtils",{log:!1});function Ct(e,t=0){const s=e.getUint8(t++);return{string:q.decode(e.buffer.slice(e.byteOffset+t,e.byteOffset+t+s)),byteOffset:t+=s}}function Et(e,t,s,i,n=!1){let a=0;for(;a<e.byteLength;){const r=e.getUint8(a++);St.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++),St.log({messageTypeEnum:r,messageType:o,messageLength:c,dataView:e,byteOffset:a});const h=H(e,a,c);St.log({_dataView:h}),s(o,h,i),a+=c}}var kt,Mt,Dt,Tt,Wt,It,_t,Lt,Ut,Ft,At,Rt,xt,$t,Ot,Bt,Pt,Nt,Vt,qt,zt,jt,Gt,Ht,Jt,Kt,Qt,Zt,Xt;const Yt=T("CameraManager",{log:!1}),es=["focus","takePicture","stop","sleep","wake"],ts=["idle","focusing","takingPicture","asleep"],ss=["headerSize","header","imageSize","image","footerSize","footer"],is=["resolution","qualityFactor","shutter","gain","redGain","greenGain","blueGain"],ns=["cameraStatus","cameraCommand","getCameraConfiguration","setCameraConfiguration","cameraData"],as=["getCameraConfiguration","cameraStatus"],rs=[...ns,"cameraImageProgress","cameraImage"];class os{constructor(){kt.add(this),Tt.set(this,void 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,0),Vt.set(this,void 0),qt.set(this,0),zt.set(this,!1),Gt.set(this,{}),Ht.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}}),K(this)}get waitForEvent(){return this.eventDispatcher.waitForEvent}requestRequiredInformation(){Yt.log("requesting required camera information");const e=as.map((e=>({type:e})));this.sendMessage(e,!1)}get cameraStatus(){return e(this,Tt,"f")}async focus(){e(this,kt,"m",Ut).call(this),await e(this,kt,"m",_t).call(this,"focus")}async takePicture(){e(this,kt,"m",Ut).call(this),await e(this,kt,"m",_t).call(this,"takePicture")}async stop(){e(this,kt,"m",Ut).call(this),await e(this,kt,"m",_t).call(this,"stop")}async sleep(){e(this,kt,"m",Ut).call(this),await e(this,kt,"m",_t).call(this,"sleep")}async wake(){e(this,kt,"m",Lt).call(this),await e(this,kt,"m",_t).call(this,"wake")}get cameraConfiguration(){return e(this,Gt,"f")}get availableCameraConfigurationTypes(){return e(this,Ht,"f")}get cameraConfigurationRanges(){return e(this,Jt,"f")}async setCameraConfiguration(t){if(Yt.log({newCameraConfiguration:t}),e(this,kt,"m",Qt).call(this,t))return void Yt.log("redundant camera configuration");const s=e(this,kt,"m",Xt).call(this,t);Yt.log({setCameraConfigurationData:s});const i=this.waitForEvent("getCameraConfiguration");this.sendMessage([{type:"setCameraConfiguration",data:s.buffer}]),await i}static AssertValidCameraConfigurationType(e){Yt.assertEnumWithError(e,is)}static AssertValidCameraConfigurationTypeEnum(e){Yt.assertTypeWithError(e,"number"),Yt.assertWithError(e in is,`invalid cameraConfigurationTypeEnum ${e}`)}parseMessage(t,s){switch(Yt.log({messageType:t,dataView:s}),t){case"cameraStatus":e(this,kt,"m",Wt).call(this,s);break;case"getCameraConfiguration":case"setCameraConfiguration":e(this,kt,"m",Kt).call(this,s);break;case"cameraData":e(this,kt,"m",Ft).call(this,s);break;default:throw Error(`uncaught messageType ${t}`)}}clear(){t(this,Tt,void 0,"f"),t(this,$t,0,"f"),t(this,Pt,0,"f"),t(this,qt,0,"f")}}var cs;Mt=os,Tt=new WeakMap,Rt=new WeakMap,xt=new WeakMap,$t=new WeakMap,Ot=new WeakMap,Bt=new WeakMap,Pt=new WeakMap,Nt=new WeakMap,Vt=new WeakMap,qt=new WeakMap,zt=new WeakMap,Gt=new WeakMap,Ht=new WeakMap,Jt=new WeakMap,kt=new WeakSet,Dt=function(){return this.eventDispatcher.dispatchEvent},Wt=function(t){const s=t.getUint8(0),i=ts[s];e(this,kt,"m",It).call(this,i)},It=function(s){if(Yt.assertEnumWithError(s,ts),s==e(this,Tt,"f"))return void Yt.log(`redundant cameraStatus ${s}`);const i=e(this,Tt,"f");t(this,Tt,s,"f"),Yt.log(`updated cameraStatus to "${this.cameraStatus}"`),e(this,kt,"a",Dt).call(this,"cameraStatus",{cameraStatus:this.cameraStatus,previousCameraStatus:i}),"takingPicture"!=e(this,Tt,"f")&&e(this,Pt,"f")>0&&!e(this,zt,"f")&&e(this,kt,"m",jt).call(this)},_t=async function(e,t){Yt.assertEnumWithError(e,es),Yt.log(`sending camera command "${e}"`);const s=this.waitForEvent("cameraStatus");Yt.log(`setting command "${e}"`);const i=es.indexOf(e);this.sendMessage([{type:"cameraCommand",data:Uint8Array.from([i]).buffer}],t),await s},Lt=function(){Yt.assertWithError("asleep"==e(this,Tt,"f"),`camera is not asleep - currently ${e(this,Tt,"f")}`)},Ut=function(){Yt.assertWithError("asleep"!=e(this,Tt,"f"),`camera is not awake - currently ${e(this,Tt,"f")}`)},Ft=function(t){Yt.log("parsing camera data",t),Et(t,ss,e(this,kt,"m",At).bind(this),null,!0)},At=function(s,i){switch(Yt.log({cameraDataType:s,dataView:i}),s){case"headerSize":t(this,Rt,i.getUint16(0,!0),"f"),Yt.log({headerSize:e(this,Rt,"f")}),t(this,xt,void 0,"f"),e(this,$t,"f");break;case"header":t(this,xt,j(e(this,xt,"f"),i),"f"),Yt.log({headerData:e(this,xt,"f")}),t(this,$t,e(this,xt,"f")?.byteLength/e(this,Rt,"f"),"f"),Yt.log({headerProgress:e(this,$t,"f")}),e(this,kt,"a",Dt).call(this,"cameraImageProgress",{progress:e(this,$t,"f"),type:"header"}),1==e(this,$t,"f")&&Yt.log("finished getting header data");break;case"imageSize":t(this,Ot,i.getUint16(0,!0),"f"),Yt.log({imageSize:e(this,Ot,"f")}),t(this,Bt,void 0,"f"),e(this,Pt,"f"),t(this,zt,!1,"f");break;case"image":t(this,Bt,j(e(this,Bt,"f"),i),"f"),Yt.log({imageData:e(this,Bt,"f")}),t(this,Pt,e(this,Bt,"f")?.byteLength/e(this,Ot,"f"),"f"),Yt.log({imageProgress:e(this,Pt,"f")}),1==e(this,Pt,"f")&&(Yt.log("finished getting image data"),1==e(this,$t,"f")&&e(this,kt,"m",jt).call(this)),e(this,kt,"a",Dt).call(this,"cameraImageProgress",{progress:e(this,Pt,"f"),type:"image"});break;case"footerSize":t(this,Nt,i.getUint16(0,!0),"f"),Yt.log({footerSize:e(this,Nt,"f")}),t(this,Vt,void 0,"f"),e(this,qt,"f");break;case"footer":t(this,Vt,j(e(this,Vt,"f"),i),"f"),Yt.log({footerData:e(this,Vt,"f")}),t(this,qt,e(this,Vt,"f")?.byteLength/e(this,Nt,"f"),"f"),Yt.log({footerProgress:e(this,qt,"f")}),e(this,kt,"a",Dt).call(this,"cameraImageProgress",{progress:e(this,qt,"f"),type:"footer"}),1==e(this,qt,"f")&&(Yt.log("finished getting footer data"),1==e(this,Pt,"f")&&e(this,kt,"m",jt).call(this))}},jt=function(){Yt.log("building image...");const s=j(e(this,xt,"f"),e(this,Bt,"f"),e(this,Vt,"f"));Yt.log({imageData:s});let i=new Blob([s],{type:"image/jpeg"});Yt.log("created blob",i);const n=URL.createObjectURL(i);Yt.log("created url",n),e(this,kt,"a",Dt).call(this,"cameraImage",{url:n,blob:i}),t(this,zt,!0,"f")},Kt=function(s){const i={};let n=0;for(;n<s.byteLength;){const e=s.getUint8(n++),t=is[e];Yt.assertWithError(t,`invalid cameraConfigurationTypeIndex ${e}`),i[t]=s.getUint16(n,!0),n+=2}Yt.log({parsedCameraConfiguration:i}),t(this,Ht,Object.keys(i),"f"),t(this,Gt,i,"f"),e(this,kt,"a",Dt).call(this,"getCameraConfiguration",{cameraConfiguration:e(this,Gt,"f")})},Qt=function(e){return Object.keys(e).every((t=>this.cameraConfiguration[t]==e[t]))},Zt=function(t){Yt.assertWithError(e(this,Ht,"f"),"must get initial cameraConfiguration");const s=e(this,Ht,"f")?.includes(t);return Yt.assertWithError(s,`unavailable camera configuration type "${t}"`),s},Xt=function(t){let s=Object.keys(t);s=s.filter((t=>e(this,kt,"m",Zt).call(this,t)));const i=new DataView(new ArrayBuffer(3*s.length));return s.forEach(((e,s)=>{Mt.AssertValidCameraConfigurationType(e);const n=is.indexOf(e);i.setUint8(3*s,n);const a=t[e];i.setUint16(3*s+1,a,!0)})),Yt.log({sensorConfigurationData:i}),i};const hs=T("SensorDataManager",{log:!1}),ls=[...ot,"acceleration","gravity","linearAcceleration","gyroscope","magnetometer","gameRotation","rotation","orientation","activity","stepCounter","stepDetector","deviceOrientation","tapDetector",...vt,"camera"],fs=[...ct,"acceleration","gravity","linearAcceleration","gyroscope","magnetometer","gameRotation","rotation","orientation",...wt],gs=["getPressurePositions","getSensorScalars","sensorData"],us=["getPressurePositions"],ds=[...gs,...ls];class ms{constructor(){this.pressureSensorDataManager=new lt,this.motionSensorDataManager=new dt,this.barometerSensorDataManager=new bt,cs.set(this,new Map)}static AssertValidSensorType(e){hs.assertEnumWithError(e,ls)}static AssertValidSensorTypeEnum(e){hs.assertTypeWithError(e,"number"),hs.assertWithError(e in ls,`invalid sensorTypeEnum ${e}`)}get dispatchEvent(){return this.eventDispatcher.dispatchEvent}parseMessage(e,t){switch(hs.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(t){for(let s=0;s<t.byteLength;s+=5){const i=t.getUint8(s),n=ls[i];if(!n){hs.warn(`unknown sensorType index ${i}`);continue}const a=t.getFloat32(s+1,!0);hs.log({sensorType:n,sensorScalar:a}),e(this,cs,"f").set(n,a)}}parseData(e){hs.log("sensorData",Array.from(new Uint8Array(e.buffer)));let t=0;const s=Je(e,t);t+=2;Et(new DataView(e.buffer,t),ls,this.parseDataCallback.bind(this),{timestamp:s})}parseDataCallback(t,s,{timestamp:i}){const n=e(this,cs,"f").get(t)||1;let a=null;switch(t){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:hs.error(`uncaught sensorType "${t}"`)}hs.assertWithError(null!=a,`no sensorData defined for sensorType "${t}"`),hs.log({sensorType:t,sensorData:a}),this.dispatchEvent(t,{sensorType:t,[t]:a,timestamp:i}),this.dispatchEvent("sensorData",{sensorType:t,[t]:a,timestamp:i})}}var ps,vs,ws,ys,bs,Ss,Cs,Es,ks,Ms,Ds,Ts,Ws;cs=new WeakMap;const Is=T("SensorConfigurationManager",{log:!1}),_s=65535,Ls=5,Us=["getSensorConfiguration","setSensorConfiguration"],Fs=Us;class As{constructor(){ps.add(this),ys.set(this,void 0),Ss.set(this,{}),K(this)}get addEventListener(){return this.eventDispatcher.addEventListener}get waitForEvent(){return this.eventDispatcher.waitForEvent}get configuration(){return e(this,Ss,"f")}async setConfiguration(t,s){if(s&&(t=Object.assign({...this.zeroSensorConfiguration},t)),Is.log({newSensorConfiguration:t}),e(this,ps,"m",Es).call(this,t))return void Is.log("redundant sensor configuration");const i=e(this,ps,"m",Ts).call(this,t);Is.log({setSensorConfigurationData:i});const n=this.waitForEvent("getSensorConfiguration");this.sendMessage([{type:"setSensorConfiguration",data:i.buffer}]),await n}static get ZeroSensorConfiguration(){return e(this,vs,"f",Ws)}get zeroSensorConfiguration(){const t={};return e(this,ys,"f").forEach((e=>{t[e]=0})),t}async clearSensorConfiguration(){return this.setConfiguration(this.zeroSensorConfiguration)}parseMessage(t,s){switch(Is.log({messageType:t}),t){case"getSensorConfiguration":case"setSensorConfiguration":const i=e(this,ps,"m",ks).call(this,s);e(this,ps,"m",Cs).call(this,i);break;default:throw Error(`uncaught messageType ${t}`)}}}var 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,oi,ci,hi,li,fi;vs=As,ys=new WeakMap,Ss=new WeakMap,ps=new WeakSet,ws=function(){return this.eventDispatcher.dispatchEvent},bs=function(t){Is.assertWithError(e(this,ys,"f"),"must get initial sensorConfiguration");const s=e(this,ys,"f")?.includes(t);return Is.log(s,`unavailable sensor type "${t}"`),s},Cs=function(s){t(this,Ss,s,"f"),Is.log({updatedConfiguration:e(this,Ss,"f")}),e(this,ps,"a",ws).call(this,"getSensorConfiguration",{sensorConfiguration:this.configuration})},Es=function(e){return Object.keys(e).every((t=>this.configuration[t]==e[t]))},ks=function(e){const s={};for(let t=0;t<e.byteLength;t+=3){const i=e.getUint8(t),n=ls[i],a=e.getUint16(t+1,!0);Is.log({sensorType:n,sensorRate:a}),n?s[n]=a:Is.warn(`unknown sensorType index ${i}`)}return Is.log({parsedSensorConfiguration:s}),t(this,ys,Object.keys(s),"f"),s},Ms=function(e){Is.assertTypeWithError(e,"number"),Is.assertWithError(e>=0,`sensorRate must be 0 or greater (got ${e})`),Is.assertWithError(e<65535,`sensorRate must be 0 or greater (got ${e})`),Is.assertWithError(e%5==0,"sensorRate must be multiple of 5")},Ds=function(t){e(vs,vs,"m",Ms).call(vs,t)},Ts=function(t){let s=Object.keys(t);s=s.filter((t=>e(this,ps,"m",bs).call(this,t)));const i=new DataView(new ArrayBuffer(3*s.length));return s.forEach(((s,n)=>{ms.AssertValidSensorType(s);const a=ls.indexOf(s);i.setUint8(3*n,a);const r=t[s];e(this,ps,"m",Ds).call(this,r),i.setUint16(3*n+1,r,!0)})),Is.log({sensorConfigurationData:i}),i},Ws={value:{}},ls.forEach((t=>{e(vs,vs,"f",Ws)[t]=0}));const gi=T("TfliteManager",{log:!1}),ui=["getTfliteName","setTfliteName","getTfliteTask","setTfliteTask","getTfliteSampleRate","setTfliteSampleRate","getTfliteSensorTypes","setTfliteSensorTypes","tfliteIsReady","getTfliteCaptureDelay","setTfliteCaptureDelay","getTfliteThreshold","setTfliteThreshold","getTfliteInferencingEnabled","setTfliteInferencingEnabled","tfliteInference"],di=ui,mi=["getTfliteName","getTfliteTask","getTfliteSampleRate","getTfliteSensorTypes","tfliteIsReady","getTfliteCaptureDelay","getTfliteThreshold","getTfliteInferencingEnabled"],pi=["classification","regression"],vi=["pressure","linearAcceleration","gyroscope","magnetometer"];class wi{constructor(){Rs.add(this),Bs.set(this,void 0),Vs.set(this,void 0),js.set(this,void 0),Js.set(this,[]),Zs.set(this,void 0),ti.set(this,void 0),ni.set(this,void 0),oi.set(this,void 0),fi.set(this,void 0),K(this)}get addEventListenter(){return this.eventDispatcher.addEventListener}get removeEventListener(){return this.eventDispatcher.removeEventListener}get waitForEvent(){return this.eventDispatcher.waitForEvent}get name(){return e(this,Bs,"f")}async setName(e,t){if(gi.assertTypeWithError(e,"string"),this.name==e)return void gi.log(`redundant name assignment ${e}`);const s=this.waitForEvent("getTfliteName"),i=V.encode(e);this.sendMessage([{type:"setTfliteName",data:i.buffer}],t),await s}get task(){return e(this,Vs,"f")}async setTask(t,s){if(e(this,Rs,"m",xs).call(this,t),this.task==t)return void gi.log(`redundant task assignment ${t}`);const i=this.waitForEvent("getTfliteTask"),n=pi.indexOf(t);this.sendMessage([{type:"setTfliteTask",data:Uint8Array.from([n]).buffer}],s),await i}get sampleRate(){return e(this,js,"f")}async setSampleRate(t,s){if(gi.assertTypeWithError(t,"number"),t-=t%5,gi.assertWithError(t>=5,`sampleRate must be multiple of 5 greater than 0 (got ${t})`),e(this,js,"f")==t)return void gi.log(`redundant sampleRate assignment ${t}`);const i=this.waitForEvent("getTfliteSampleRate"),n=new DataView(new ArrayBuffer(2));n.setUint16(0,t,!0),this.sendMessage([{type:"setTfliteSampleRate",data:n.buffer}],s),await i}static AssertValidSensorType(e){ms.AssertValidSensorType(e);const t=e;gi.assertWithError(vi.includes(t),`invalid tflite sensorType "${e}"`)}get sensorTypes(){return e(this,Js,"f").slice()}async setSensorTypes(e,t){e.forEach((e=>{wi.AssertValidSensorType(e)}));const s=this.waitForEvent("getTfliteSensorTypes");var i;const n=(e=(i=e).filter(((e,t)=>i.indexOf(e)==t))).map((e=>ls.indexOf(e))).sort();gi.log(e,n),this.sendMessage([{type:"setTfliteSensorTypes",data:Uint8Array.from(n).buffer}],t),await s}get isReady(){return e(this,Zs,"f")}get captureDelay(){return e(this,ti,"f")}async setCaptureDelay(t,s){if(gi.assertTypeWithError(t,"number"),e(this,ti,"f")==t)return void gi.log(`redundant captureDelay assignment ${t}`);const i=this.waitForEvent("getTfliteCaptureDelay"),n=new DataView(new ArrayBuffer(2));n.setUint16(0,t,!0),this.sendMessage([{type:"setTfliteCaptureDelay",data:n.buffer}],s),await i}get threshold(){return e(this,ni,"f")}async setThreshold(t,s){if(gi.assertTypeWithError(t,"number"),gi.assertWithError(t>=0,`threshold must be positive (got ${t})`),e(this,ni,"f")==t)return void gi.log(`redundant threshold assignment ${t}`);const i=this.waitForEvent("getTfliteThreshold"),n=new DataView(new ArrayBuffer(4));n.setFloat32(0,t,!0),this.sendMessage([{type:"setTfliteThreshold",data:n.buffer}],s),await i}get inferencingEnabled(){return e(this,oi,"f")}async setInferencingEnabled(t,s=!0){if(gi.assertTypeWithError(t,"boolean"),!t&&!this.isReady)return;if(e(this,Rs,"m",ei).call(this),e(this,oi,"f")==t)return void gi.log(`redundant inferencingEnabled assignment ${t}`);const i=this.waitForEvent("getTfliteInferencingEnabled");this.sendMessage([{type:"setTfliteInferencingEnabled",data:Uint8Array.from([Number(t)]).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(t,s){switch(gi.log({messageType:t}),t){case"getTfliteName":case"setTfliteName":e(this,Rs,"m",Ps).call(this,s);break;case"getTfliteTask":case"setTfliteTask":e(this,Rs,"m",qs).call(this,s);break;case"getTfliteSampleRate":case"setTfliteSampleRate":e(this,Rs,"m",Gs).call(this,s);break;case"getTfliteSensorTypes":case"setTfliteSensorTypes":e(this,Rs,"m",Ks).call(this,s);break;case"tfliteIsReady":e(this,Rs,"m",Xs).call(this,s);break;case"getTfliteCaptureDelay":case"setTfliteCaptureDelay":e(this,Rs,"m",si).call(this,s);break;case"getTfliteThreshold":case"setTfliteThreshold":e(this,Rs,"m",ai).call(this,s);break;case"getTfliteInferencingEnabled":case"setTfliteInferencingEnabled":e(this,Rs,"m",ci).call(this,s);break;case"tfliteInference":e(this,Rs,"m",li).call(this,s);break;default:throw Error(`uncaught messageType ${t}`)}}get configuration(){return e(this,fi,"f")}sendConfiguration(s,i){if(s==e(this,fi,"f"))return void gi.log("redundant tflite configuration assignment");if(t(this,fi,s,"f"),gi.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(){t(this,fi,void 0,"f"),t(this,oi,!1,"f"),t(this,Js,[],"f"),t(this,js,0,"f"),t(this,Zs,!1,"f")}requestRequiredInformation(){gi.log("requesting required tflite information");const e=mi.map((e=>({type:e})));this.sendMessage(e,!1)}}var yi,bi,Si,Ci,Ei;Bs=new WeakMap,Vs=new WeakMap,js=new WeakMap,Js=new WeakMap,Zs=new WeakMap,ti=new WeakMap,ni=new WeakMap,oi=new WeakMap,fi=new WeakMap,Rs=new WeakSet,xs=function(e){gi.assertEnumWithError(e,pi)},$s=function(e){gi.assertWithError(e in pi,`invalid taskEnum ${e}`)},Os=function(){return this.eventDispatcher.dispatchEvent},Ps=function(t){gi.log("parseName",t);const s=q.decode(t.buffer);e(this,Rs,"m",Ns).call(this,s)},Ns=function(s){gi.log({name:s}),t(this,Bs,s,"f"),e(this,Rs,"a",Os).call(this,"getTfliteName",{tfliteName:s})},qs=function(t){gi.log("parseTask",t);const s=t.getUint8(0);e(this,Rs,"m",$s).call(this,s);const i=pi[s];e(this,Rs,"m",zs).call(this,i)},zs=function(s){gi.log({task:s}),t(this,Vs,s,"f"),e(this,Rs,"a",Os).call(this,"getTfliteTask",{tfliteTask:s})},Gs=function(t){gi.log("parseSampleRate",t);const s=t.getUint16(0,!0);e(this,Rs,"m",Hs).call(this,s)},Hs=function(s){gi.log({sampleRate:s}),t(this,js,s,"f"),e(this,Rs,"a",Os).call(this,"getTfliteSampleRate",{tfliteSampleRate:s})},Ks=function(t){gi.log("parseSensorTypes",t);const s=[];for(let e=0;e<t.byteLength;e++){const i=t.getUint8(e),n=ls[i];n?vi.includes(n)?s.push(n):gi.error(`invalid tfliteSensorType ${n}`):gi.error(`invalid sensorTypeEnum ${i}`)}e(this,Rs,"m",Qs).call(this,s)},Qs=function(s){gi.log({sensorTypes:s}),t(this,Js,s,"f"),e(this,Rs,"a",Os).call(this,"getTfliteSensorTypes",{tfliteSensorTypes:s})},Xs=function(t){gi.log("parseIsReady",t);const s=Boolean(t.getUint8(0));e(this,Rs,"m",Ys).call(this,s)},Ys=function(s){gi.log({isReady:s}),t(this,Zs,s,"f"),e(this,Rs,"a",Os).call(this,"tfliteIsReady",{tfliteIsReady:s})},ei=function(){gi.assertWithError(this.isReady,"tflite is not ready")},si=function(t){gi.log("parseCaptureDelay",t);const s=t.getUint16(0,!0);e(this,Rs,"m",ii).call(this,s)},ii=function(s){gi.log({captureDelay:s}),t(this,ti,s,"f"),e(this,Rs,"a",Os).call(this,"getTfliteCaptureDelay",{tfliteCaptureDelay:s})},ai=function(t){gi.log("parseThreshold",t);const s=t.getFloat32(0,!0);e(this,Rs,"m",ri).call(this,s)},ri=function(s){gi.log({threshold:s}),t(this,ni,s,"f"),e(this,Rs,"a",Os).call(this,"getTfliteThreshold",{tfliteThreshold:s})},ci=function(t){gi.log("parseInferencingEnabled",t);const s=Boolean(t.getUint8(0));e(this,Rs,"m",hi).call(this,s)},hi=function(s){gi.log({inferencingEnabled:s}),t(this,oi,s,"f"),e(this,Rs,"a",Os).call(this,"getTfliteInferencingEnabled",{tfliteInferencingEnabled:s})},li=function(t){gi.log("parseInference",t);const s=Je(t,0);gi.log({timestamp:s});const i=[];for(let e=0,s=2;s<t.byteLength;e++,s+=4){const e=t.getFloat32(s,!0);i.push(e)}gi.log("values",i);const n={timestamp:s,values:i};if("classification"==this.task){let t=0,s=0;if(i.forEach(((e,i)=>{e>t&&(t=e,s=i)})),gi.log({maxIndex:s,maxValue:t}),n.maxIndex=s,n.maxValue=t,e(this,fi,"f")?.classes){const{classes:t}=e(this,fi,"f");n.maxClass=t[s],n.classValues={},i.forEach(((e,s)=>{const i=t[s];n.classValues[i]=e}))}}e(this,Rs,"a",Os).call(this,"tfliteInference",{tfliteInference:n})};const ki=T("DeviceInformationManager",{log:!1}),Mi=["manufacturerName","modelNumber","hardwareRevision","firmwareRevision","softwareRevision","pnpId","serialNumber"],Di=[...Mi,"deviceInformation"];class Ti{constructor(){yi.add(this),Si.set(this,{})}get information(){return e(this,Si,"f")}clear(){t(this,Si,{},"f")}parseMessage(t,s){switch(ki.log({messageType:t}),t){case"manufacturerName":const i=q.decode(s.buffer);ki.log({manufacturerName:i}),e(this,yi,"m",Ei).call(this,{manufacturerName:i});break;case"modelNumber":const n=q.decode(s.buffer);ki.log({modelNumber:n}),e(this,yi,"m",Ei).call(this,{modelNumber:n});break;case"softwareRevision":const a=q.decode(s.buffer);ki.log({softwareRevision:a}),e(this,yi,"m",Ei).call(this,{softwareRevision:a});break;case"hardwareRevision":const r=q.decode(s.buffer);ki.log({hardwareRevision:r}),e(this,yi,"m",Ei).call(this,{hardwareRevision:r});break;case"firmwareRevision":const o=q.decode(s.buffer);ki.log({firmwareRevision:o}),e(this,yi,"m",Ei).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)),ki.log({pnpId:c}),e(this,yi,"m",Ei).call(this,{pnpId:c});break;case"serialNumber":const h=q.decode(s.buffer);ki.log({serialNumber:h});break;default:throw Error(`uncaught messageType ${t}`)}}}var Wi,Ii,_i,Li,Ui,Fi,Ai,Ri,xi,$i,Oi,Bi,Pi,Ni,Vi,qi,zi,ji;Si=new WeakMap,yi=new WeakSet,bi=function(){return this.eventDispatcher.dispatchEvent},Ci=function(){return Mi.filter((e=>"serialNumber"!=e)).every((t=>t in e(this,Si,"f")))},Ei=function(t){ki.log({partialDeviceInformation:t});Object.keys(t).forEach((s=>{e(this,yi,"a",bi).call(this,s,{[s]:t[s]})})),Object.assign(e(this,Si,"f"),t),ki.log({deviceInformation:e(this,Si,"f")}),e(this,yi,"a",Ci)&&(ki.log("completed deviceInformation"),e(this,yi,"a",bi).call(this,"deviceInformation",{deviceInformation:this.information}))};const Gi=T("InformationManager",{log:!1}),Hi=["leftInsole","rightInsole","leftGlove","rightGlove","glasses","generic"],Ji=["left","right"],Ki=2,Qi=30,Zi=["isCharging","getBatteryCurrent","getMtu","getId","getName","setName","getType","setType","getCurrentTime","setCurrentTime"],Xi=Zi;class Yi{constructor(){Wi.add(this),_i.set(this,!1),Ui.set(this,void 0),Ai.set(this,void 0),xi.set(this,""),$i.set(this,void 0),Ni.set(this,0),qi.set(this,!1),K(this)}get waitForEvent(){return this.eventDispatcher.waitForEvent}get isCharging(){return e(this,_i,"f")}get batteryCurrent(){return e(this,Ui,"f")}async getBatteryCurrent(){Gi.log("getting battery current...");const e=this.waitForEvent("getBatteryCurrent");this.sendMessage([{type:"getBatteryCurrent"}]),await e}get id(){return e(this,Ai,"f")}get name(){return e(this,xi,"f")}updateName(s){Gi.assertTypeWithError(s,"string"),t(this,xi,s,"f"),Gi.log({updatedName:e(this,xi,"f")}),e(this,Wi,"a",Ii).call(this,"getName",{name:e(this,xi,"f")})}async setName(e){Gi.assertTypeWithError(e,"string"),Gi.assertRangeWithError("newName",e.length,2,30);const t=V.encode(e);Gi.log({setNameData:t});const s=this.waitForEvent("getName");this.sendMessage([{type:"setName",data:t.buffer}]),await s}get type(){return e(this,$i,"f")}get typeEnum(){return Hi.indexOf(this.type)}updateType(s){e(this,Wi,"m",Oi).call(this,s),s!=this.type?(t(this,$i,s,"f"),Gi.log({updatedType:e(this,$i,"f")}),e(this,Wi,"a",Ii).call(this,"getType",{type:e(this,$i,"f")})):Gi.log("redundant type assignment")}async setType(t){e(this,Wi,"m",Oi).call(this,t);const s=Hi.indexOf(t);e(this,Wi,"m",Pi).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 e(this,Ni,"f")}get isCurrentTimeSet(){return e(this,qi,"f")}parseMessage(t,s){switch(Gi.log({messageType:t}),t){case"isCharging":const i=Boolean(s.getUint8(0));Gi.log({isCharging:i}),e(this,Wi,"m",Li).call(this,i);break;case"getBatteryCurrent":const n=s.getFloat32(0,!0);Gi.log({batteryCurrent:n}),e(this,Wi,"m",Fi).call(this,n);break;case"getId":const a=q.decode(s.buffer);Gi.log({id:a}),e(this,Wi,"m",Ri).call(this,a);break;case"getName":case"setName":const r=q.decode(s.buffer);Gi.log({name:r}),this.updateName(r);break;case"getType":case"setType":const o=s.getUint8(0),c=Hi[o];Gi.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)),Gi.log({mtu:h}),e(this,Wi,"m",Vi).call(this,h);break;case"getCurrentTime":case"setCurrentTime":const l=Number(s.getBigUint64(0,!0));e(this,Wi,"m",zi).call(this,l);break;default:throw Error(`uncaught messageType ${t}`)}}clear(){t(this,qi,!1,"f")}}_i=new WeakMap,Ui=new WeakMap,Ai=new WeakMap,xi=new WeakMap,$i=new WeakMap,Ni=new WeakMap,qi=new WeakMap,Wi=new WeakSet,Ii=function(){return this.eventDispatcher.dispatchEvent},Li=function(s){Gi.assertTypeWithError(s,"boolean"),t(this,_i,s,"f"),Gi.log({isCharging:e(this,_i,"f")}),e(this,Wi,"a",Ii).call(this,"isCharging",{isCharging:e(this,_i,"f")})},Fi=function(s){Gi.assertTypeWithError(s,"number"),t(this,Ui,s,"f"),Gi.log({batteryCurrent:e(this,Ui,"f")}),e(this,Wi,"a",Ii).call(this,"getBatteryCurrent",{batteryCurrent:e(this,Ui,"f")})},Ri=function(s){Gi.assertTypeWithError(s,"string"),t(this,Ai,s,"f"),Gi.log({id:e(this,Ai,"f")}),e(this,Wi,"a",Ii).call(this,"getId",{id:e(this,Ai,"f")})},Oi=function(e){Gi.assertEnumWithError(e,Hi)},Bi=function(e){Gi.assertTypeWithError(e,"number"),Gi.assertWithError(e in Hi,`invalid typeEnum ${e}`)},Pi=async function(t){e(this,Wi,"m",Bi).call(this,t);const s=Uint8Array.from([t]);Gi.log({setTypeData:s});const i=this.waitForEvent("getType");this.sendMessage([{type:"setType",data:s.buffer}]),await i},Vi=function(s){Gi.assertTypeWithError(s,"number"),e(this,Ni,"f")!=s?(t(this,Ni,s,"f"),e(this,Wi,"a",Ii).call(this,"getMtu",{mtu:e(this,Ni,"f")})):Gi.log("redundant mtu assignment",s)},zi=function(s){Gi.log({currentTime:s}),t(this,qi,0!=s||Math.abs(Date.now()-s)<He,"f"),e(this,qi,"f")||e(this,Wi,"m",ji).call(this,!1)},ji=async function(e){Gi.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 en=["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 tn,sn,nn,an,rn,on,cn,hn,ln,fn,gn,un,dn,mn,pn,vn,wn,yn,bn;const Sn=T("VibrationManager",{log:!1}),Cn=["front","rear"],En=["waveformEffect","waveform"],kn=["getVibrationLocations","triggerVibration"],Mn=kn,Dn=8,Tn=2550,Wn=1270,In=3,_n=20,Ln=6;class Un{constructor(){tn.add(this),yn.set(this,[]),K(this)}get waitForEvent(){return this.eventDispatcher.waitForEvent}async triggerVibration(t,s=!0){let i;t.forEach((t=>{const{type:s}=t;let n,{locations:a}=t;switch(a=a||this.vibrationLocations.slice(),a=a.filter((e=>this.vibrationLocations.includes(e))),s){case"waveformEffect":{const{segments:s,loopCount:i}=t;n=e(this,tn,"m",mn).call(this,a,s,i)}break;case"waveform":{const{segments:s}=t;n=e(this,tn,"m",pn).call(this,a,s)}break;default:throw Error(`invalid vibration type "${s}"`)}Sn.log({type:s,arrayBuffer:n}),i=j(i,n)})),await this.sendMessage([{type:"triggerVibration",data:i}],s)}get vibrationLocations(){return e(this,yn,"f")}parseMessage(t,s){if(Sn.log({messageType:t}),"getVibrationLocations"!==t)throw Error(`uncaught messageType ${t}`);{const t=Array.from(new Uint8Array(s.buffer)).map((e=>Cn[e])).filter(Boolean);e(this,tn,"m",bn).call(this,t)}}}var Fn,An,Rn,xn,$n,On,Bn,Pn,Nn,Vn,qn,zn,jn,Gn,Hn,Jn,Kn;yn=new WeakMap,tn=new WeakSet,sn=function(){return this.eventDispatcher.dispatchEvent},nn=function(e){Sn.assertTypeWithError(e,"string"),Sn.assertWithError(Cn.includes(e),`invalid location "${e}"`)},an=function(t){e(this,tn,"m",on).call(this,t),t.forEach((t=>{e(this,tn,"m",nn).call(this,t)}))},rn=function(t){e(this,tn,"m",an).call(this,t);let s=0;return t.forEach((e=>{const t=Cn.indexOf(e);s|=1<<t})),Sn.log({locationsBitmask:s}),Sn.assertWithError(s>0,"locationsBitmask must not be zero"),s},on=function(e){Sn.assertWithError(Array.isArray(e),"passed non-array"),Sn.assertWithError(e.length>0,"passed empty array")},cn=function(e){Sn.assertWithError(en.includes(e),`invalid waveformEffect "${e}"`)},hn=function(t){if(null!=t.effect){const s=t.effect;e(this,tn,"m",cn).call(this,s)}else{if(null==t.delay)throw Error("no effect or delay found in waveformEffectSegment");{const{delay:e}=t;Sn.assertWithError(e>=0,`delay must be 0ms or greater (got ${e})`),Sn.assertWithError(e<=Wn,`delay must be 1270ms or less (got ${e})`)}}if(null!=t.loopCount){const{loopCount:s}=t;e(this,tn,"m",ln).call(this,s)}},ln=function(e){Sn.assertTypeWithError(e,"number"),Sn.assertWithError(e>=0,`waveformEffectSegmentLoopCount must be 0 or greater (got ${e})`),Sn.assertWithError(e<=3,`waveformEffectSegmentLoopCount must be 3 or fewer (got ${e})`)},fn=function(t){e(this,tn,"m",on).call(this,t),Sn.assertWithError(t.length<=8,`must have 8 waveformEffectSegments or fewer (got ${t.length})`),t.forEach((t=>{e(this,tn,"m",hn).call(this,t)}))},gn=function(e){Sn.assertTypeWithError(e,"number"),Sn.assertWithError(e>=0,`waveformEffectSequenceLoopCount must be 0 or greater (got ${e})`),Sn.assertWithError(e<=6,`waveformEffectSequenceLoopCount must be 6 or fewer (got ${e})`)},un=function(e){Sn.assertTypeWithError(e.amplitude,"number"),Sn.assertWithError(e.amplitude>=0,`amplitude must be 0 or greater (got ${e.amplitude})`),Sn.assertWithError(e.amplitude<=1,`amplitude must be 1 or less (got ${e.amplitude})`),Sn.assertTypeWithError(e.duration,"number"),Sn.assertWithError(e.duration>0,`duration must be greater than 0ms (got ${e.duration}ms)`),Sn.assertWithError(e.duration<=Tn,`duration must be 2550ms or less (got ${e.duration}ms)`)},dn=function(t){e(this,tn,"m",on).call(this,t),Sn.assertWithError(t.length<=20,`must have 20 waveformSegments or fewer (got ${t.length})`),t.forEach((t=>{e(this,tn,"m",un).call(this,t)}))},mn=function(t,s,i=0){e(this,tn,"m",fn).call(this,s),e(this,tn,"m",gn).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++]=en.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 Sn.log({dataArray:n,dataView:c}),e(this,tn,"m",wn).call(this,t,"waveformEffect",c)},pn=function(t,s){e(this,tn,"m",dn).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))})),Sn.log({dataView:i}),e(this,tn,"m",wn).call(this,t,"waveform",i)},vn=function(e){Sn.assertTypeWithError(e,"string"),Sn.assertWithError(En.includes(e),`invalid vibrationType "${e}"`)},wn=function(t,s,i){Sn.assertWithError(i?.byteLength>0,"no data received");const n=e(this,tn,"m",rn).call(this,t);e(this,tn,"m",vn).call(this,s);const a=En.indexOf(s);Sn.log({locationsBitmask:n,vibrationTypeIndex:a,dataView:i});const r=j(n,a,i.byteLength,i);return Sn.log({data:r}),r},bn=function(s){t(this,yn,s,"f"),Sn.log("vibrationLocations",s),e(this,tn,"a",sn).call(this,"getVibrationLocations",{vibrationLocations:e(this,yn,"f")})};const Qn=T("WifiManager",{log:!1}),Zn=1,Xn=32,Yn=8,ea=64,ta=["isWifiAvailable","getWifiSSID","setWifiSSID","getWifiPassword","setWifiPassword","getWifiConnectionEnabled","setWifiConnectionEnabled","isWifiConnected","ipAddress","isWifiSecure"],sa=["getWifiSSID","getWifiPassword","getWifiConnectionEnabled","isWifiConnected","ipAddress","isWifiSecure"],ia=ta;class na{constructor(){Fn.add(this),Rn.set(this,!1),On.set(this,""),Pn.set(this,""),Vn.set(this,void 0),zn.set(this,!1),Gn.set(this,void 0),Jn.set(this,!1),K(this)}get waitForEvent(){return this.eventDispatcher.waitForEvent}requestRequiredInformation(){Qn.log("requesting required wifi information");const e=sa.map((e=>({type:e})));this.sendMessage(e,!1)}get isWifiAvailable(){return e(this,Rn,"f")}get wifiSSID(){return e(this,On,"f")}async setWifiSSID(t){if(e(this,Fn,"m",$n).call(this),e(this,Vn,"f"))return void Qn.error("cannot change ssid while wifi connection is enabled");Qn.assertTypeWithError(t,"string"),Qn.assertRangeWithError("wifiSSID",t.length,1,32);const s=V.encode(t);Qn.log({setWifiSSIDData:s});const i=this.waitForEvent("getWifiSSID");this.sendMessage([{type:"setWifiSSID",data:s.buffer}]),await i}get wifiPassword(){return e(this,Pn,"f")}async setWifiPassword(t){if(e(this,Fn,"m",$n).call(this),e(this,Vn,"f"))return void Qn.error("cannot change password while wifi connection is enabled");Qn.assertTypeWithError(t,"string"),t.length>0&&Qn.assertRangeWithError("wifiPassword",t.length,8,64);const s=V.encode(t);Qn.log({setWifiPasswordData:s});const i=this.waitForEvent("getWifiPassword");this.sendMessage([{type:"setWifiPassword",data:s.buffer}]),await i}get wifiConnectionEnabled(){return e(this,Vn,"f")}async setWifiConnectionEnabled(t,s=!0){if(e(this,Fn,"m",$n).call(this),Qn.assertTypeWithError(t,"boolean"),e(this,Vn,"f")==t)return void Qn.log(`redundant wifiConnectionEnabled assignment ${t}`);const i=this.waitForEvent("getWifiConnectionEnabled");this.sendMessage([{type:"setWifiConnectionEnabled",data:Uint8Array.from([Number(t)]).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 e(this,zn,"f")}get ipAddress(){return e(this,Gn,"f")}get isWifiSecure(){return e(this,Jn,"f")}parseMessage(t,s){switch(Qn.log({messageType:t}),t){case"isWifiAvailable":const i=Boolean(s.getUint8(0));Qn.log({isWifiAvailable:i}),e(this,Fn,"m",xn).call(this,i);break;case"getWifiSSID":case"setWifiSSID":const n=q.decode(s.buffer);Qn.log({ssid:n}),e(this,Fn,"m",Bn).call(this,n);break;case"getWifiPassword":case"setWifiPassword":const a=q.decode(s.buffer);Qn.log({password:a}),e(this,Fn,"m",Nn).call(this,a);break;case"getWifiConnectionEnabled":case"setWifiConnectionEnabled":const r=Boolean(s.getUint8(0));Qn.log({enableWifiConnection:r}),e(this,Fn,"m",qn).call(this,r);break;case"isWifiConnected":const o=Boolean(s.getUint8(0));Qn.log({isWifiConnected:o}),e(this,Fn,"m",jn).call(this,o);break;case"ipAddress":let c;4==s.byteLength&&(c=new Uint8Array(s.buffer.slice(0,4)).join(".")),Qn.log({ipAddress:c}),e(this,Fn,"m",Hn).call(this,c);break;case"isWifiSecure":const h=Boolean(s.getUint8(0));Qn.log({isWifiSecure:h}),e(this,Fn,"m",Kn).call(this,h);break;default:throw Error(`uncaught messageType ${t}`)}}clear(){t(this,On,"","f"),t(this,Pn,"","f"),t(this,Gn,"","f"),t(this,zn,!1,"f"),t(this,Rn,!1,"f")}}var aa,ra,oa,ca,ha,la,fa,ga,ua,da,ma,pa;Rn=new WeakMap,On=new WeakMap,Pn=new WeakMap,Vn=new WeakMap,zn=new WeakMap,Gn=new WeakMap,Jn=new WeakMap,Fn=new WeakSet,An=function(){return this.eventDispatcher.dispatchEvent},xn=function(s){Qn.assertTypeWithError(s,"boolean"),t(this,Rn,s,"f"),Qn.log({isWifiAvailable:e(this,Rn,"f")}),e(this,Fn,"a",An).call(this,"isWifiAvailable",{isWifiAvailable:e(this,Rn,"f")})},$n=function(){Qn.assertWithError(e(this,Rn,"f"),"wifi is not available")},Bn=function(s){Qn.assertTypeWithError(s,"string"),t(this,On,s,"f"),Qn.log({wifiSSID:e(this,On,"f")}),e(this,Fn,"a",An).call(this,"getWifiSSID",{wifiSSID:e(this,On,"f")})},Nn=function(s){Qn.assertTypeWithError(s,"string"),t(this,Pn,s,"f"),Qn.log({wifiPassword:e(this,Pn,"f")}),e(this,Fn,"a",An).call(this,"getWifiPassword",{wifiPassword:e(this,Pn,"f")})},qn=function(s){Qn.log({wifiConnectionEnabled:s}),t(this,Vn,s,"f"),e(this,Fn,"a",An).call(this,"getWifiConnectionEnabled",{wifiConnectionEnabled:s})},jn=function(s){Qn.assertTypeWithError(s,"boolean"),t(this,zn,s,"f"),Qn.log({isWifiConnected:e(this,zn,"f")}),e(this,Fn,"a",An).call(this,"isWifiConnected",{isWifiConnected:e(this,zn,"f")})},Hn=function(s){t(this,Gn,s,"f"),Qn.log({ipAddress:e(this,Gn,"f")}),e(this,Fn,"a",An).call(this,"ipAddress",{ipAddress:e(this,Gn,"f")})},Kn=function(s){Qn.assertTypeWithError(s,"boolean"),t(this,Jn,s,"f"),Qn.log({isWifiSecure:e(this,Jn,"f")}),e(this,Fn,"a",An).call(this,"isWifiSecure",{isWifiSecure:e(this,Jn,"f")})};const va=T("BaseConnectionManager",{log:!1}),wa=["webBluetooth","noble","client","webSocket","udp"],ya=["notConnected","connecting","connected","disconnecting"],ba=[...ya,"connectionStatus","isConnected"],Sa=[...Zi,...Us,...gs,...kn,...Oe,...ui,...ta,...ns],Ca=["batteryLevel"],Ea=["rx","tx"],ka=[...Ca,...Mi,...Ea,...Sa,"smp"];class Ma{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(){aa.add(this),ha.set(this,"notConnected"),ga.set(this,[]),ua.set(this,!1),this.defaultMtu=23,this.mtu=this.defaultMtu,ma.set(this,new x(e(this,aa,"m",pa).bind(this),5e3)),e(this,aa,"m",ca).call(this)}get status(){return e(this,ha,"f")}set status(s){va.assertEnumWithError(s,ya),e(this,ha,"f")!=s?(va.log(`new connection status "${s}"`),t(this,ha,s,"f"),this.onStatusUpdated(this.status),this.isConnected?e(this,ma,"f").start():e(this,ma,"f").stop(),"notConnected"==e(this,ha,"f")&&(this.mtu=this.defaultMtu)):va.log(`tried to assign same connection status "${s}"`)}get isConnected(){return"connected"==this.status}get isAvailable(){return!1}assertIsNotConnected(){va.assertWithError(!this.isConnected,"device is already connected")}assertIsConnected(){va.assertWithError(this.isConnected,"device is not connected")}assertIsConnectedAndNotDisconnecting(){this.assertIsConnected(),e(this,aa,"m",fa).call(this)}async connect(){this.assertIsNotConnected(),e(this,aa,"m",la).call(this),this.status="connecting"}get canReconnect(){return!1}async reconnect(){this.assertIsNotConnected(),e(this,aa,"m",la).call(this),va.assertWithError(this.canReconnect,"unable to reconnect"),this.status="connecting",va.log("attempting to reconnect...")}async disconnect(){this.assertIsConnected(),e(this,aa,"m",fa).call(this),this.status="disconnecting",va.log("disconnecting from device...")}async sendSmpMessage(e){this.assertIsConnectedAndNotDisconnecting(),va.log("sending smp message",e)}async sendTxMessages(s,i=!0){if(this.assertIsConnectedAndNotDisconnecting(),s&&(e(this,ga,"f").push(...s),va.log(`appended ${s.length} messages`)),!i)return void va.log("not sending immediately - waiting until later");if(e(this,ua,"f"))return void va.log("already sending messages - waiting until later");if(0==e(this,ga,"f").length)return void va.log("no pendingMessages");t(this,ua,!0,"f"),va.log("sendTxMessages",e(this,ga,"f").slice());const n=e(this,ga,"f").map((t=>{e(ra,ra,"m",oa).call(ra,t.type);const s=Sa.indexOf(t.type),i=new DataView(new ArrayBuffer(2));return i.setUint16(0,t.data?.byteLength||0,!0),j(s,i,t.data)}));if(e(this,ga,"f").length=0,this.mtu)for(;n.length>0;){if(n.every((e=>e.byteLength>this.mtu-3))){va.log("every arrayBuffer is too big to send");break}va.log("remaining arrayBuffers.length",n.length);let e=0,t=0;n.some((s=>{if(e+s.byteLength>this.mtu-3)return va.log(`stopping appending arrayBuffers ( length ${s.byteLength} too much)`),!0;va.log(`allowing arrayBuffer with length ${s.byteLength}`),t++,e+=s.byteLength}));const s=n.splice(0,t);va.log({arrayBufferCount:t,arrayBuffersToSend:s});const i=j(...s);va.log("sending arrayBuffer (partitioned)",i),await this.sendTxData(i)}else{const e=j(...n);va.log("sending arrayBuffer (all)",e),await this.sendTxData(e)}t(this,ua,!1,"f"),this.sendTxMessages(void 0,!0)}async sendTxData(e){va.log("sendTxData",e)}parseRxMessage(t){Et(t,Sa,e(this,aa,"m",da).bind(this),null,!0),this.onMessagesReceived()}clear(){t(this,ua,!1,"f"),e(this,ga,"f").length=0}remove(){this.clear(),this.onStatusUpdated=void 0,this.onMessageReceived=void 0,this.onMessagesReceived=void 0}}ra=Ma,ha=new WeakMap,ga=new WeakMap,ua=new WeakMap,ma=new WeakMap,aa=new WeakSet,oa=function(e){va.assertEnumWithError(e,Sa)},ca=function(){va.assertWithError(this.isSupported,`${this.constructor.name} is not supported`)},la=function(){va.assertWithError("connecting"!=this.status,"device is already connecting")},fa=function(){va.assertWithError("disconnecting"!=this.status,"device is already disconnecting")},da=function(e,t){va.log({messageType:e,dataView:t}),this.onMessageReceived(e,t)},pa=function(){this.isConnected||(va.log("timer detected disconnection"),this.status="notConnected")};const Da=T("EventUtils",{log:!1});function Ta(e,t){let s=e.addEventListener||e.addListener||e.on||e.AddEventListener;Da.assertWithError(s,"no add listener function found for target"),s=s.bind(e),Object.entries(t).forEach((([e,t])=>{s(e,t)}))}function Wa(e,t){let s=e.removeEventListener||e.removeListener||e.RemoveEventListener;Da.assertWithError(s,"no remove listener function found for target"),s=s.bind(e),Object.entries(t).forEach((([e,t])=>{s(e,t)}))}const Ia=T("bluetoothUUIDs",{log:!1});if(i)var _a=window.BluetoothUUID;function La(e){return Ia.assertTypeWithError(e,"string"),Ia.assertWithError(4==e.length,"value must be 4 characters long"),`ea6d${e}-a725-4f9b-893d-c3913e33b39f`}function Ua(e){return _a?.getCharacteristic?.(e)}function Fa(e){return _a?.getService?.(e)}const Aa=Object.freeze({services:{deviceInformation:{uuid:Fa("device_information"),characteristics:{manufacturerName:{uuid:Ua("manufacturer_name_string")},modelNumber:{uuid:Ua("model_number_string")},hardwareRevision:{uuid:Ua("hardware_revision_string")},firmwareRevision:{uuid:Ua("firmware_revision_string")},softwareRevision:{uuid:Ua("software_revision_string")},pnpId:{uuid:Ua("pnp_id")},serialNumber:{uuid:Ua("serial_number_string")}}},battery:{uuid:Fa("battery_service"),characteristics:{batteryLevel:{uuid:Ua("battery_level")}}},main:{uuid:La("0000"),characteristics:{rx:{uuid:La("1000")},tx:{uuid:La("1001")}}},smp:{uuid:"8d53dc1d-1db7-4cd3-868b-8a527460aa84",characteristics:{smp:{uuid:"da2e7828-fbce-4e01-ae9e-261174997c48"}}}}}),Ra=[Aa.services.main.uuid],xa=[Aa.services.deviceInformation.uuid,Aa.services.battery.uuid,Aa.services.smp.uuid];function $a(e){e=e.toString().toLowerCase();return Object.keys(Aa.services).find((t=>{let s=Aa.services[t].uuid.toString();return 4==e.length&&(s=s.slice(4,8)),e.includes("-")||(s=s.replaceAll("-","")),e==s}))}const Oa=[],Ba=[];function Pa(e){var t;return e=e.toString().toLowerCase(),Object.values(Aa.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 Na(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(Aa.services).forEach((e=>{if(!e.characteristics)return;const t=Object.keys(e.characteristics);t.forEach((s=>{const i=e.characteristics[s];Ra.includes(e.uuid)&&(Oa.push(i.uuid),t.push(s)),Ba.push(i.uuid)}))}),[]);const Va=T("BluetoothConnectionManager",{log:!1});class qa extends Ma{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){Va.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 za,ja,Ga,Ha,Ja,Ka,Qa,Za,Xa,Ya,er;const tr=T("WebBluetoothConnectionManager",{log:!1});var sr;i&&(sr=window.navigator.bluetooth);class ir extends qa{constructor(){super(...arguments),za.add(this),ja.set(this,{characteristicvaluechanged:e(this,za,"m",Xa).bind(this)}),Ga.set(this,{gattserverdisconnected:e(this,za,"m",er).bind(this)}),Ha.set(this,void 0),Ja.set(this,new Map),Ka.set(this,new Map)}get bluetoothId(){return this.device.id}get canUpdateFirmware(){return e(this,Ka,"f").has("smp")}static get isSupported(){return Boolean(sr)}static get type(){return"webBluetooth"}get device(){return e(this,Ha,"f")}set device(s){e(this,Ha,"f")!=s?(e(this,Ha,"f")&&Wa(e(this,Ha,"f"),e(this,Ga,"f")),s&&Ta(s,e(this,Ga,"f")),t(this,Ha,s,"f")):tr.log("tried to assign the same BluetoothDevice")}get server(){return e(this,Ha,"f")?.gatt}get isConnected(){return this.server?.connected||!1}async connect(){await super.connect();try{const t=await sr.requestDevice({filters:[{services:Ra}],optionalServices:i?xa:[]});tr.log("got BluetoothDevice"),this.device=t,tr.log("connecting to device...");const s=await this.server.connect();tr.log(`connected to device? ${s.connected}`),await e(this,za,"m",Qa).call(this),tr.log("fully connected"),this.status="connected"}catch(t){tr.error(t),this.status="notConnected",this.server?.disconnect(),e(this,za,"m",Za).call(this)}}async disconnect(){await e(this,za,"m",Za).call(this),await super.disconnect(),this.server?.disconnect(),this.status="notConnected"}async writeCharacteristic(t,s){super.writeCharacteristic(t,s);const i=e(this,Ka,"f").get(t);tr.assertWithError(i,`${t} characteristic not found`),tr.log("writing characteristic",i,s);const n=i.properties||Na(t);n.writeWithoutResponse?(tr.log("writing without response"),await i.writeValueWithoutResponse(s)):(tr.log("writing with response"),await i.writeValueWithResponse(s)),tr.log("wrote characteristic"),n.read&&!n.notify&&(tr.log("reading value after write..."),await i.readValue(),(o||c)&&e(this,za,"m",Ya).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){tr.error(e),this.isInRange=!1}this.isConnected?(tr.log("successfully reconnected!"),await e(this,za,"m",Qa).call(this),this.status="connected"):(tr.log("unable to reconnect"),this.status="notConnected")}remove(){super.remove(),this.device=void 0}}ja=new WeakMap,Ga=new WeakMap,Ha=new WeakMap,Ja=new WeakMap,Ka=new WeakMap,za=new WeakSet,Qa=async function(){e(this,za,"m",Za).call(this),tr.log("getting services...");const t=await this.server.getPrimaryServices();tr.log("got services",t.length),tr.log("getting characteristics...");for(const s in t){const i=t[s];tr.log({service:i});const n=$a(i.uuid);tr.assertWithError(n,`no name found for service uuid "${i.uuid}"`),tr.log(`got "${n}" service`),i.name=n,e(this,Ja,"f").set(n,i),tr.log(`getting characteristics for "${n}" service`);const a=await i.getCharacteristics();tr.log(`got characteristics for "${n}" service`);for(const t in a){const s=a[t];tr.log({characteristic:s});const i=Pa(s.uuid);tr.assertWithError(Boolean(i),`no name found for characteristic uuid "${s.uuid}" in "${n}" service`),tr.log(`got "${i}" characteristic in "${n}" service`),s.name=i,e(this,Ka,"f").set(i,s),Ta(s,e(this,ja,"f"));const r=s.properties||Na(i);r.notify&&(tr.log(`starting notifications for "${i}" characteristic`),await s.startNotifications()),r.read&&(tr.log(`reading "${i}" characteristic...`),await s.readValue(),(o||c)&&e(this,za,"m",Ya).call(this,s))}}},Za=async function(){this.device&&Wa(this.device,e(this,Ga,"f"));const t=Array.from(e(this,Ka,"f").keys()).map((t=>{const s=e(this,Ka,"f").get(t);Wa(s,e(this,ja,"f"));if((s.properties||Na(t)).notify)return tr.log(`stopping notifications for "${t}" characteristic`),s.stopNotifications()}));return Promise.allSettled(t)},Xa=function(t){tr.log("oncharacteristicvaluechanged");const s=t.target;e(this,za,"m",Ya).call(this,s)},Ya=function(e){tr.log("onCharacteristicValue");const t=e.name;tr.assertWithError(Boolean(t),`no name found for characteristic with uuid "${e.uuid}"`),tr.log(`oncharacteristicvaluechanged for "${t}" characteristic`);const s=e.value;tr.assertWithError(s,`no data found for "${t}" characteristic`),tr.log(`data for "${t}" characteristic`,Array.from(new Uint8Array(s.buffer)));try{this.onCharacteristicValueChanged(t,s)}catch(e){tr.error(e)}},er=function(){tr.log("gattserverdisconnected"),this.status="notConnected"};const nr=4294967296,ar=9007199254740992;const rr={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%nr,s=(e-t)/nr,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<=ar)return h(0,t);if(-ar<=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()*nr+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}},or=T("mcumgr",{log:!1}),cr=0,hr=1,lr=2,fr=3,gr=0,ur=1,dr=8,mr=0,pr=2,vr=3,wr=5,yr=0,br=1,Sr=5,Cr=0;class Er{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(rr.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){or.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=rr.decode(e.slice(8).buffer),c=256*s+i,h=256*n+a;return or.log("mcumgr - Process Message - Group: "+h+", Id: "+r+", Off: "+o.off),h===ur&&r===br&&o.off?(this._uploadOffset=o.off,void this._uploadNext()):t===fr&&h===dr&&r===Cr&&o.off?(this._uploadFileOffset=o.off,void this._uploadFileNext()):t===hr&&h===dr&&r===Cr?(this._downloadFileOffset+=o.data.length,null!=o.len&&(this._downloadFileLength=o.len),or.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,gr,wr)}smpEcho(e){return this._getMessage(lr,gr,mr,{d:e})}cmdImageState(){return this._getMessage(cr,ur,yr)}cmdImageErase(){return this._getMessage(lr,ur,Sr,{})}cmdImageTest(e){return this._getMessage(lr,ur,yr,{hash:e,confirm:!1})}cmdImageConfirm(e){return this._getMessage(lr,ur,yr,{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-rr.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(lr,ur,br,e);or.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?or.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?or.error("Upload is already in progress."):(this._uploadIsInProgress=!0,this._uploadFileOffset=0,this._uploadFile=e,this._uploadFilename=t,this._uploadFileNext())}async _uploadFileNext(){if(or.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-rr.encode(e).byteLength-8;e.data=new Uint8Array(this._uploadFile.slice(this._uploadFileOffset,this._uploadFileOffset+t)),this._uploadFileOffset+=t;const s=this._getMessage(lr,dr,Cr,e);or.log("mcumgr - _uploadNext: Message Length: "+s.length),this._fileUploadNextCallback({packet:s})}async cmdDownloadFile(e,t){this._downloadIsInProgress?or.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(cr,dr,Cr,e);or.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 kr,Mr,Dr,Tr,Wr,Ir,_r,Lr,Ur,Fr,Ar,Rr,xr,$r,Or,Br,Pr,Nr,Vr,qr,zr;const jr=T("FirmwareManager",{log:!1}),Gr=["smp"],Hr=[...Gr,"firmwareImages","firmwareUploadProgress","firmwareStatus","firmwareUploadComplete"],Jr=["idle","uploading","uploaded","pending","testing","erasing"];class Kr{constructor(){kr.add(this),Dr.set(this,"idle"),Wr.set(this,void 0),Lr.set(this,void 0),Ur.set(this,new Er),e(this,kr,"m",Fr).call(this),K(this)}get addEventListenter(){return this.eventDispatcher.addEventListener}get removeEventListener(){return this.eventDispatcher.removeEventListener}get waitForEvent(){return this.eventDispatcher.waitForEvent}parseMessage(t,s){if(jr.log({messageType:t}),"smp"!==t)throw Error(`uncaught messageType ${t}`);e(this,Ur,"f")._notification(Array.from(new Uint8Array(s.buffer))),e(this,kr,"a",Mr).call(this,"smp",{dataView:s})}async uploadFirmware(t){jr.log("uploadFirmware",t);const s=this.waitForEvent("firmwareUploadComplete");await this.getImages();const i=await J(t),n=await e(this,Ur,"f").imageInfo(i);jr.log({imageInfo:n}),e(this,Ur,"f").cmdUpload(i,1),e(this,kr,"m",Tr).call(this,"uploading"),await s}get status(){return e(this,Dr,"f")}get images(){return e(this,Wr,"f")}async getImages(){const t=this.waitForEvent("firmwareImages");jr.log("getting firmware image state..."),this.sendMessage(Uint8Array.from(e(this,Ur,"f").cmdImageState()).buffer),await t}async testImage(t=1){if(e(this,kr,"m",_r).call(this,t),e(this,kr,"m",Ir).call(this),!e(this,Wr,"f")[t])return void jr.log(`image ${t} not found`);if(1==e(this,Wr,"f")[t].pending)return void jr.log(`image ${t} is already pending`);if(e(this,Wr,"f")[t].empty)return void jr.log(`image ${t} is empty`);const s=this.waitForEvent("smp");jr.log("testing firmware image..."),this.sendMessage(Uint8Array.from(e(this,Ur,"f").cmdImageTest(e(this,Wr,"f")[t].hash)).buffer),await s}async eraseImage(){e(this,kr,"m",Ir).call(this);const t=this.waitForEvent("smp");jr.log("erasing image..."),this.sendMessage(Uint8Array.from(e(this,Ur,"f").cmdImageErase()).buffer),e(this,kr,"m",Tr).call(this,"erasing"),await t,await this.getImages()}async confirmImage(t=0){if(e(this,kr,"m",_r).call(this,t),e(this,kr,"m",Ir).call(this),!0===e(this,Wr,"f")[t].confirmed)return void jr.log(`image ${t} is already confirmed`);const s=this.waitForEvent("smp");jr.log("confirming image..."),this.sendMessage(Uint8Array.from(e(this,Ur,"f").cmdImageConfirm(e(this,Wr,"f")[t].hash)).buffer),await s}async echo(t){jr.assertTypeWithError(t,"string");const s=this.waitForEvent("smp");jr.log("sending echo..."),this.sendMessage(Uint8Array.from(e(this,Ur,"f").smpEcho(t)).buffer),await s}async reset(){const t=this.waitForEvent("smp");jr.log("resetting..."),this.sendMessage(Uint8Array.from(e(this,Ur,"f").cmdReset()).buffer),await t}get mtu(){return e(this,Lr,"f")}set mtu(s){t(this,Lr,s,"f"),e(this,Ur,"f")._mtu=s}}var Qr,Zr,Xr,Yr,eo,to,so,io,no,ao,ro,oo,co,ho,lo,fo,go,uo;Dr=new WeakMap,Wr=new WeakMap,Lr=new WeakMap,Ur=new WeakMap,kr=new WeakSet,Mr=function(){return this.eventDispatcher.dispatchEvent},Tr=function(s){jr.assertEnumWithError(s,Jr),e(this,Dr,"f")!=s?(t(this,Dr,s,"f"),jr.log({firmwareStatus:e(this,Dr,"f")}),e(this,kr,"a",Mr).call(this,"firmwareStatus",{firmwareStatus:e(this,Dr,"f")})):jr.log(`redundant firmwareStatus assignment "${s}"`)},Ir=function(){jr.assertWithError(e(this,Wr,"f"),"didn't get imageState")},_r=function(e){jr.assertTypeWithError(e,"number"),jr.assertWithError(0==e||1==e,"imageIndex must be 0 or 1")},Fr=function(){e(this,Ur,"f").onMessage(e(this,kr,"m",Ar).bind(this)),e(this,Ur,"f").onFileDownloadNext(e(this,kr,"m",Rr)),e(this,Ur,"f").onFileDownloadProgress(e(this,kr,"m",xr).bind(this)),e(this,Ur,"f").onFileDownloadFinished(e(this,kr,"m",$r).bind(this)),e(this,Ur,"f").onFileUploadNext(e(this,kr,"m",Or).bind(this)),e(this,Ur,"f").onFileUploadProgress(e(this,kr,"m",Br).bind(this)),e(this,Ur,"f").onFileUploadFinished(e(this,kr,"m",Pr).bind(this)),e(this,Ur,"f").onImageUploadNext(e(this,kr,"m",Nr).bind(this)),e(this,Ur,"f").onImageUploadProgress(e(this,kr,"m",Vr).bind(this)),e(this,Ur,"f").onImageUploadFinished(e(this,kr,"m",qr).bind(this))},Ar=function({op:t,group:s,id:i,data:n,length:a}){switch(jr.log("onMcuMessage",...arguments),s){case gr:switch(i){case mr:jr.log(`echo "${n.r}"`);break;case pr:jr.table(n.tasks);break;case vr:jr.log(n)}break;case ur:if(i===yr)e(this,kr,"m",zr).call(this,n);break;default:throw Error(`uncaught mcuMessage group ${s}`)}},Rr=function(){jr.log("onMcuFileDownloadNext",...arguments)},xr=function(){jr.log("onMcuFileDownloadProgress",...arguments)},$r=function(){jr.log("onMcuFileDownloadFinished",...arguments)},Or=function(){jr.log("onMcuFileUploadNext")},Br=function(){jr.log("onMcuFileUploadProgress")},Pr=function(){jr.log("onMcuFileUploadFinished")},Nr=function({packet:e}){jr.log("onMcuImageUploadNext"),this.sendMessage(Uint8Array.from(e).buffer)},Vr=function({percentage:t}){const s=t/100;jr.log("onMcuImageUploadProgress",...arguments),e(this,kr,"a",Mr).call(this,"firmwareUploadProgress",{progress:s})},qr=async function(){jr.log("onMcuImageUploadFinished",...arguments),await this.getImages(),e(this,kr,"a",Mr).call(this,"firmwareUploadProgress",{progress:100}),e(this,kr,"a",Mr).call(this,"firmwareUploadComplete",{})},zr=function({images:s}){if(!s)return void jr.log("no images found");t(this,Wr,s,"f"),jr.log("images",e(this,Wr,"f"));let i="idle";2==e(this,Wr,"f").length&&(e(this,Wr,"f")[1].bootable?e(this,Wr,"f")[0].confirmed?e(this,Wr,"f")[1].pending?(jr.log("reset to upload to the new firmware image"),i="pending"):(jr.log("Slot 1 has a valid image. run testImage() to test it or upload a different image."),i="uploaded"):(jr.log('Slot 0 has a valid image. Click "Confirm Image" to confirm it or wait and the device will swap images back.'),i="testing"):jr.warn('Slot 1 has a invalid image. Click "Erase Image" to erase it or upload a different image')),1==e(this,Wr,"f").length&&(e(this,Wr,"f").push({slot:1,empty:!0,version:"Empty",pending:!1,confirmed:!1,bootable:!1,active:!1,permanent:!1}),jr.log("Select a firmware upload image to upload to slot 1.")),e(this,kr,"m",Tr).call(this,i),e(this,kr,"a",Mr).call(this,"firmwareImages",{firmwareImages:e(this,Wr,"f")})};const mo=T("DeviceManager",{log:!1}),po=["deviceConnected","deviceDisconnected","deviceIsConnected","availableDevices","connectedDevices"];class vo{constructor(){if(Qr.add(this),Zr.set(this,{getType:e(this,Qr,"m",Xr).bind(this),isConnected:e(this,Qr,"m",fo).bind(this)}),Yr.set(this,[]),eo.set(this,!1),to.set(this,{devices:[]}),so.set(this,void 0),no.set(this,"BS.Device"),co.set(this,[]),ho.set(this,new L(this,po)),vo.shared&&this!=vo.shared)throw Error("DeviceManager is a singleton - use DeviceManager.shared");this.CanUseLocalStorage&&(this.UseLocalStorage=!0)}onDevice(t){Ta(t,e(this,Zr,"f"))}OnDeviceConnectionStatusUpdated(t,s){if("notConnected"==s&&!t.canReconnect&&e(this,co,"f").includes(t)){const s=e(this,co,"f").indexOf(t);this.AvailableDevices.splice(s,1),e(this,Qr,"m",go).call(this)}}get ConnectedDevices(){return e(this,Yr,"f")}get UseLocalStorage(){return e(this,eo,"f")}set UseLocalStorage(s){e(this,Qr,"m",io).call(this),mo.assertTypeWithError(s,"boolean"),t(this,eo,s,"f"),e(this,eo,"f")&&!e(this,so,"f")&&e(this,Qr,"m",ro).call(this)}get CanUseLocalStorage(){return i&&window.localStorage}get AvailableDevices(){return e(this,co,"f")}get CanGetDevices(){return i&&navigator.bluetooth?.getDevices}async GetDevices(){if(!i)return void mo.warn("GetDevices is only available in the browser");if(!navigator.bluetooth)return void mo.warn("bluetooth is not available in this browser");if(o)return void mo.warn("bluefy lists too many devices...");if(!navigator.bluetooth.getDevices)return void mo.warn("bluetooth.getDevices() is not available in this browser");if(!this.CanGetDevices)return void mo.log("CanGetDevices is false");e(this,so,"f")||e(this,Qr,"m",ro).call(this);const t=e(this,so,"f");if(!t.devices||0==t.devices.length)return void mo.log("no devices found in configuration");const s=await navigator.bluetooth.getDevices();return mo.log({bluetoothDevices:s}),s.forEach((s=>{if(!s.gatt)return;let i=t.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[e(this,co,"f").indexOf(a)]=n));if(n)return void this.AvailableDevices.push(n);const r=new Oc,o=new ir;o.device=s,s.name&&r._informationManager.updateName(s.name),r._informationManager.updateType(i.type),r.connectionManager=o,this.AvailableDevices.push(r)})),e(this,Qr,"m",go).call(this),this.AvailableDevices}get AddEventListener(){return e(this,ho,"f").addEventListener}get RemoveEventListener(){return e(this,ho,"f").removeEventListener}get RemoveEventListeners(){return e(this,ho,"f").removeEventListeners}get RemoveAllEventListeners(){return e(this,ho,"f").removeAllEventListeners}_CheckDeviceAvailability(t){t.isConnected||t.isAvailable||!e(this,co,"f").includes(t)||(mo.log("removing device from availableDevices..."),e(this,co,"f").splice(e(this,co,"f").indexOf(t),1),e(this,Qr,"m",go).call(this))}}Zr=new WeakMap,Yr=new WeakMap,eo=new WeakMap,to=new WeakMap,so=new WeakMap,no=new WeakMap,co=new WeakMap,ho=new WeakMap,Qr=new WeakSet,Xr=function(t){e(this,eo,"f")&&e(this,Qr,"m",oo).call(this,t.target)},io=function(){mo.assertWithError(i,"localStorage is only available in the browser"),mo.assertWithError(window.localStorage,"localStorage not found")},ao=function(){e(this,Qr,"m",io).call(this),localStorage.setItem(e(this,no,"f"),JSON.stringify(e(this,so,"f")))},ro=async function(){e(this,Qr,"m",io).call(this);let s=localStorage.getItem(e(this,no,"f"));if("string"!=typeof s)return mo.log("no info found in localStorage"),t(this,so,Object.assign({},e(this,to,"f")),"f"),void e(this,Qr,"m",ao).call(this);try{const e=JSON.parse(s);mo.log({configuration:e}),t(this,so,e,"f"),this.CanGetDevices&&await this.GetDevices()}catch(e){mo.error(e)}},oo=function(t){if("webBluetooth"!=t.connectionType)return void mo.log("localStorage is only for webBluetooth devices");e(this,Qr,"m",io).call(this);const s=e(this,so,"f").devices.findIndex((e=>e.bluetoothId==t.bluetoothId));-1!=s&&(e(this,so,"f").devices[s].type=t.type,e(this,Qr,"m",ao).call(this))},lo=function(){return e(this,ho,"f").dispatchEvent},fo=function(t){const{target:s}=t;if(s.isConnected)if(e(this,Yr,"f").includes(s))mo.log("device already included");else{if(mo.log("adding device",s),e(this,Yr,"f").push(s),this.UseLocalStorage&&"webBluetooth"==s.connectionType){const t={type:s.type,bluetoothId:s.bluetoothId,ipAddress:s.ipAddress,isWifiSecure:s.isWifiSecure},i=e(this,so,"f").devices.findIndex((e=>e.bluetoothId==t.bluetoothId));-1==i?e(this,so,"f").devices.push(t):e(this,so,"f").devices[i]=t,e(this,Qr,"m",ao).call(this)}e(this,Qr,"a",lo).call(this,"deviceConnected",{device:s}),e(this,Qr,"a",lo).call(this,"deviceIsConnected",{device:s}),e(this,Qr,"m",uo).call(this)}else e(this,Yr,"f").includes(s)?(mo.log("removing device",s),e(this,Yr,"f").splice(e(this,Yr,"f").indexOf(s),1),e(this,Qr,"a",lo).call(this,"deviceDisconnected",{device:s}),e(this,Qr,"a",lo).call(this,"deviceIsConnected",{device:s}),e(this,Qr,"m",uo).call(this)):mo.log("device already not included");if(this.CanGetDevices&&this.GetDevices(),s.isConnected&&!this.AvailableDevices.includes(s)){const t=this.AvailableDevices.find((e=>e.bluetoothId==s.bluetoothId));mo.log({existingAvailableDevice:t}),t?this.AvailableDevices[this.AvailableDevices.indexOf(t)]=s:this.AvailableDevices.push(s),e(this,Qr,"m",go).call(this)}this._CheckDeviceAvailability(s)},go=function(){mo.log({AvailableDevices:this.AvailableDevices}),e(this,Qr,"a",lo).call(this,"availableDevices",{availableDevices:this.AvailableDevices})},uo=function(){mo.log({ConnectedDevices:this.ConnectedDevices}),e(this,Qr,"a",lo).call(this,"connectedDevices",{connectedDevices:this.ConnectedDevices})},vo.shared=new vo;var wo=vo.shared;const yo=T("ServerUtils",{log:!1}),bo=["isScanningAvailable","isScanning","startScan","stopScan","discoveredDevice","discoveredDevices","expiredDiscoveredDevice","connectToDevice","disconnectFromDevice","connectedDevices","deviceMessage","requiredDeviceInformation"];function So(e,...t){yo.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=j(...t.data),i=s.byteLength;yo.assertEnumWithError(t.type,e);const n=e.indexOf(t.type),a=new DataView(new ArrayBuffer(2));return a.setUint16(0,i,!0),j(n,a,s)}));return yo.log("messageBuffers",...s),j(...s)}function Co(...e){return yo.log("createServerMessage",...e),So(bo,...e)}function Eo(...e){return yo.log("createClientDeviceMessage",...e),So(ka,...e)}Co("isScanningAvailable"),Co("isScanning"),Co("startScan"),Co("stopScan"),Co("discoveredDevices");const ko=T("WebSocketUtils",{log:!1}),Mo=["ping","pong","serverMessage"];function Do(...e){return ko.log("createWebSocketMessage",...e),So(Mo,...e)}var To,Wo,Io,_o,Lo,Uo,Fo,Ao,Ro,xo,$o,Oo,Bo,Po,No,Vo,qo,zo;Do("ping"),Do("pong");const jo=T("WebSocketConnectionManager",{log:!1}),Go=["ping","pong","batteryLevel","deviceInformation","message"];const Ho=["deviceInformation","batteryLevel"];class Jo extends Ma{get bluetoothId(){return e(this,Wo,"f")??""}constructor(s,i=!1,n){super(),To.add(this),Wo.set(this,void 0),this.defaultMtu=1024,Io.set(this,void 0),_o.set(this,void 0),Lo.set(this,!1),Ao.set(this,{open:e(this,To,"m",Ro).bind(this),message:e(this,To,"m",xo).bind(this),close:e(this,To,"m",$o).bind(this),error:e(this,To,"m",Oo).bind(this)}),No.set(this,new x(e(this,To,"m",Vo).bind(this),29e3)),this.ipAddress=s,this.isSecure=i,this.mtu=this.defaultMtu,t(this,Wo,n,"f")}get isAvailable(){return!0}static get isSupported(){return!0}static get type(){return"webSocket"}get webSocket(){return e(this,Io,"f")}set webSocket(s){e(this,Io,"f")!=s?(jo.log("assigning webSocket",s),e(this,Io,"f")&&(Wa(e(this,Io,"f"),e(this,Ao,"f")),e(this,Io,"f").readyState==e(this,Io,"f").OPEN&&e(this,Io,"f").close()),s&&Ta(s,e(this,Ao,"f")),t(this,Io,s,"f"),jo.log("assigned webSocket")):jo.log("redundant webSocket assignment")}get ipAddress(){return e(this,_o,"f")}set ipAddress(s){this.assertIsNotConnected(),e(this,_o,"f")!=s?(t(this,_o,s,"f"),jo.log(`updated ipAddress to "${this.ipAddress}"`)):jo.log(`redundnant ipAddress assignment "${s}"`)}get isSecure(){return e(this,Lo,"f")}set isSecure(s){this.assertIsNotConnected(),e(this,Lo,"f")!=s?(t(this,Lo,s,"f"),jo.log(`updated isSecure to "${this.isSecure}"`)):jo.log(`redundant isSecure assignment ${s}`)}get url(){return`${this.isSecure?"wss":"ws"}://${this.ipAddress}/ws`}async connect(){await super.connect();try{this.webSocket=new WebSocket(this.url)}catch(e){jo.error("error connecting to webSocket",e),this.status="notConnected"}}async disconnect(){await super.disconnect(),jo.log("closing websocket"),e(this,No,"f").stop(),e(this,Io,"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),jo.error("smp not supported on webSockets")}async sendTxData(t){await super.sendTxData(t),0!=t.byteLength&&e(this,To,"m",Fo).call(this,{type:"message",data:t})}remove(){super.remove(),this.webSocket=void 0}}var 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,bc,Sc,Cc,Ec,kc,Mc,Dc,Tc,Wc,Ic,_c,Lc,Uc,Fc,Ac;Wo=new WeakMap,Io=new WeakMap,_o=new WeakMap,Lo=new WeakMap,Ao=new WeakMap,No=new WeakMap,To=new WeakSet,Uo=function(t){this.assertIsConnected(),jo.log("sending webSocket message",t),e(this,Io,"f").send(t),e(this,No,"f").restart()},Fo=function(...t){e(this,To,"m",Uo).call(this,function(...e){return jo.log("createWebSocketMessage",...e),So(Go,...e)}(...t))},Ro=function(t){jo.log("webSocket.open",t),e(this,No,"f").start(),this.status="connected",e(this,To,"m",zo).call(this)},xo=async function(t){const s=await t.data.arrayBuffer(),i=new DataView(s);jo.log(`webSocket.message (${i.byteLength} bytes)`),e(this,To,"m",Bo).call(this,i)},$o=function(t){jo.log("webSocket.close",t),this.status="notConnected",e(this,No,"f").stop()},Oo=function(e){jo.error("webSocket.error",e)},Bo=function(t){Et(t,Go,e(this,To,"m",Po).bind(this),null,!0)},Po=function(t,s){switch(jo.log(`received "${t}" message (${s.byteLength} bytes)`),t){case"ping":e(this,To,"m",qo).call(this);break;case"pong":break;case"batteryLevel":this.onMessageReceived?.("batteryLevel",s);break;case"deviceInformation":Et(s,Mi,((e,t)=>{this.onMessageReceived(e,t)}));break;case"message":this.parseRxMessage(s);break;default:jo.error(`uncaught messageType "${t}"`)}},Vo=function(){jo.log("pinging"),e(this,To,"m",Fo).call(this,"ping")},qo=function(){jo.log("ponging"),e(this,To,"m",Fo).call(this,"pong")},zo=function(){e(this,To,"m",Fo).call(this,...Ho)};const Rc=T("Device",{log:!1}),xc=["connectionMessage",...ba,...Ea,...Ca,...Xi,...Di,...Fs,...ds,...Mn,...qe,...di,...ia,...rs,...Hr],$c=["isCharging","getBatteryCurrent","getId","getMtu","getName","getType","getCurrentTime","getSensorConfiguration","getSensorScalars","getVibrationLocations","getFileTypes","isWifiAvailable"];class Oc{get bluetoothId(){return e(this,ec,"f")?.bluetoothId}get isAvailable(){return e(this,ec,"f")?.isAvailable}constructor(){Ko.add(this),Xo.set(this,new L(this,xc)),ec.set(this,void 0),this.sendTxMessages=e(this,Ko,"m",tc).bind(this),sc.set(this,!1),hc.set(this,Qo.ReconnectOnDisconnection),lc.set(this,void 0),this.latestConnectionMessages=new Map,wc.set(this,new Ti),yc.set(this,0),this._informationManager=new Yi,Sc.set(this,new As),Ec.set(this,Qo.ClearSensorConfigurationOnLeave),kc.set(this,new ms),Mc.set(this,new Un),Dc.set(this,new je),Tc.set(this,new wi),Wc.set(this,new Kr),this.sendSmpMessage=e(this,Ko,"m",_c).bind(this),Lc.set(this,!1),Uc.set(this,new na),Fc.set(this,new os),e(this,wc,"f").eventDispatcher=e(this,Xo,"f"),this._informationManager.sendMessage=this.sendTxMessages,this._informationManager.eventDispatcher=e(this,Xo,"f"),e(this,Sc,"f").sendMessage=this.sendTxMessages,e(this,Sc,"f").eventDispatcher=e(this,Xo,"f"),e(this,kc,"f").eventDispatcher=e(this,Xo,"f"),e(this,Mc,"f").sendMessage=this.sendTxMessages,e(this,Mc,"f").eventDispatcher=e(this,Xo,"f"),e(this,Tc,"f").sendMessage=this.sendTxMessages,e(this,Tc,"f").eventDispatcher=e(this,Xo,"f"),e(this,Dc,"f").sendMessage=this.sendTxMessages,e(this,Dc,"f").eventDispatcher=e(this,Xo,"f"),e(this,Uc,"f").sendMessage=this.sendTxMessages,e(this,Uc,"f").eventDispatcher=e(this,Xo,"f"),e(this,Fc,"f").sendMessage=this.sendTxMessages,e(this,Fc,"f").eventDispatcher=e(this,Xo,"f"),e(this,Wc,"f").sendMessage=this.sendSmpMessage,e(this,Wc,"f").eventDispatcher=e(this,Xo,"f"),this.addEventListener("getMtu",(()=>{e(this,Wc,"f").mtu=this.mtu,e(this,Dc,"f").mtu=this.mtu,this.connectionManager.mtu=this.mtu})),this.addEventListener("getSensorConfiguration",(()=>{if("connecting"==this.connectionStatus){if(this.sensorTypes.includes("pressure")){Rc.log("requesting required pressure information");const e=us.map((e=>({type:e})));this.sendTxMessages(e,!1)}else Rc.log("don't need to request pressure infomration");if(this.sensorTypes.includes("camera")){Rc.log("requesting required camera information");const e=as.map((e=>({type:e})));this.sendTxMessages(e,!1)}else Rc.log("don't need to request camera infomration")}})),this.addEventListener("getFileTypes",(()=>{"connecting"==this.connectionStatus&&(this.fileTypes.length>0&&e(this,Dc,"f").requestRequiredInformation(),this.fileTypes.includes("tflite")&&e(this,Tc,"f").requestRequiredInformation())})),this.addEventListener("isWifiAvailable",(()=>{"connecting"==this.connectionStatus&&("client"!=this.connectionType||n)&&this.isWifiAvailable&&"client"!=this.connectionType&&e(this,Uc,"f").requestRequiredInformation()})),wo.onDevice(this),i&&window.addEventListener("beforeunload",(()=>{this.isConnected&&this.clearSensorConfigurationOnLeave&&this.clearSensorConfiguration()})),n&&process.on("exit",(()=>{this.isConnected&&this.clearSensorConfigurationOnLeave&&this.clearSensorConfiguration()}))}get addEventListener(){return e(this,Xo,"f").addEventListener}get removeEventListener(){return e(this,Xo,"f").removeEventListener}get waitForEvent(){return e(this,Xo,"f").waitForEvent}get removeEventListeners(){return e(this,Xo,"f").removeEventListeners}get removeAllEventListeners(){return e(this,Xo,"f").removeAllEventListeners}get connectionManager(){return e(this,ec,"f")}set connectionManager(s){this.connectionManager!=s?(this.connectionManager&&this.connectionManager.remove(),s&&(s.onStatusUpdated=e(this,Ko,"m",fc).bind(this),s.onMessageReceived=e(this,Ko,"m",pc).bind(this),s.onMessagesReceived=e(this,Ko,"m",vc).bind(this)),t(this,ec,s,"f"),Rc.log("assigned new connectionManager",e(this,ec,"f")),this._informationManager.connectionType=this.connectionType):Rc.log("same connectionManager is already assigned")}async connect(t){if(Rc.log("connect options",t),t)switch(t.type){case"webBluetooth":"webBluetooth"!=this.connectionType&&(this.connectionManager=new ir);break;case"webSocket":{let e=!1;if("webSocket"==this.connectionType){const s=this.connectionManager;s.ipAddress==t.ipAddress&&s.isSecure==t.isWifiSecure||(e=!0)}else e=!0;e&&(this.connectionManager=new Jo(t.ipAddress,t.isWifiSecure,this.bluetoothId))}break;case"udp":{let e=!1;if("udp"==this.connectionType){this.connectionManager.ipAddress!=t.ipAddress&&(e=!0),this.reconnectOnDisconnection=!0}else e=!0;e&&(this.connectionManager=new UDPConnectionManager(t.ipAddress,this.bluetoothId))}}if(this.connectionManager||(this.connectionManager=e(Qo,Qo,"m",Zo).call(Qo)),e(this,Ko,"m",dc).call(this),"client"==t?.type){Rc.assertWithError("client"==this.connectionType,"expected clientConnectionManager");const e=this.connectionManager;return e.subType=t.subType,e.connect()}return Rc.log("connectionManager type",this.connectionManager.type),this.connectionManager.connect()}get isConnected(){return e(this,sc,"f")}get canReconnect(){return this.connectionManager?.canReconnect}async reconnect(){return e(this,Ko,"m",oc).call(this),e(this,Ko,"m",dc).call(this),this.connectionManager?.reconnect()}static async Connect(){const e=new Qo;return await e.connect(),e}static get ReconnectOnDisconnection(){return e(this,Qo,"f",cc)}static set ReconnectOnDisconnection(e){Rc.assertTypeWithError(e,"boolean"),t(this,Qo,e,"f",cc)}get reconnectOnDisconnection(){return e(this,hc,"f")}set reconnectOnDisconnection(e){Rc.assertTypeWithError(e,"boolean"),t(this,hc,e,"f")}get connectionType(){return this.connectionManager?.type}async disconnect(){return e(this,Ko,"m",ic).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){Rc.error("error trying to reconnect",e),this.connect()}else this.connect()}get connectionStatus(){switch(e(this,ec,"f")?.status){case"connected":return this.isConnected?"connected":"connecting";case"notConnected":case"connecting":case"disconnecting":return e(this,ec,"f").status;default:return"notConnected"}}get isConnectionBusy(){return"connecting"==this.connectionStatus||"disconnecting"==this.connectionStatus}get deviceInformation(){return e(this,wc,"f").information}get batteryLevel(){return e(this,yc,"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 fs.filter((e=>this.sensorTypes.includes(e)))}get sensorConfiguration(){return e(this,Sc,"f").configuration}async setSensorConfiguration(t,s){await e(this,Sc,"f").setConfiguration(t,s)}async clearSensorConfiguration(){return e(this,Sc,"f").clearSensorConfiguration()}static get ClearSensorConfigurationOnLeave(){return e(this,Qo,"f",Cc)}static set ClearSensorConfigurationOnLeave(e){Rc.assertTypeWithError(e,"boolean"),t(this,Qo,e,"f",Cc)}get clearSensorConfigurationOnLeave(){return e(this,Ec,"f")}set clearSensorConfigurationOnLeave(e){Rc.assertTypeWithError(e,"boolean"),t(this,Ec,e,"f")}get numberOfPressureSensors(){return e(this,kc,"f").pressureSensorDataManager.numberOfSensors}resetPressureRange(){e(this,kc,"f").pressureSensorDataManager.resetRange()}get vibrationLocations(){return e(this,Mc,"f").vibrationLocations}async triggerVibration(t,s){e(this,Mc,"f").triggerVibration(t,s)}get fileTypes(){return e(this,Dc,"f").fileTypes}get maxFileLength(){return e(this,Dc,"f").maxLength}get validFileTypes(){return Be.filter((e=>!(e.includes("wifi")&&!this.isWifiAvailable)))}async sendFile(t,s){Rc.assertWithError(this.validFileTypes.includes(t),`invalid fileType ${t}`);const i=this.waitForEvent("fileTransferComplete");e(this,Dc,"f").send(t,s),await i}async receiveFile(t){const s=this.waitForEvent("fileTransferComplete");e(this,Dc,"f").receive(t),await s}get fileTransferStatus(){return e(this,Dc,"f").status}cancelFileTransfer(){e(this,Dc,"f").cancel()}get tfliteName(){return e(this,Tc,"f").name}get setTfliteName(){return e(this,Tc,"f").setName}async sendTfliteConfiguration(t){t.type="tflite",e(this,Tc,"f").sendConfiguration(t,!1);await e(this,Dc,"f").send(t.type,t.file)||e(this,Ko,"m",tc).call(this)}get tfliteTask(){return e(this,Tc,"f").task}get setTfliteTask(){return e(this,Tc,"f").setTask}get tfliteSampleRate(){return e(this,Tc,"f").sampleRate}get setTfliteSampleRate(){return e(this,Tc,"f").setSampleRate}get tfliteSensorTypes(){return e(this,Tc,"f").sensorTypes}get allowedTfliteSensorTypes(){return this.sensorTypes.filter((e=>vi.includes(e)))}get setTfliteSensorTypes(){return e(this,Tc,"f").setSensorTypes}get tfliteIsReady(){return e(this,Tc,"f").isReady}get tfliteInferencingEnabled(){return e(this,Tc,"f").inferencingEnabled}get setTfliteInferencingEnabled(){return e(this,Tc,"f").setInferencingEnabled}async enableTfliteInferencing(){return this.setTfliteInferencingEnabled(!0)}async disableTfliteInferencing(){return this.setTfliteInferencingEnabled(!1)}get toggleTfliteInferencing(){return e(this,Tc,"f").toggleInferencingEnabled}get tfliteCaptureDelay(){return e(this,Tc,"f").captureDelay}get setTfliteCaptureDelay(){return e(this,Tc,"f").setCaptureDelay}get tfliteThreshold(){return e(this,Tc,"f").threshold}get setTfliteThreshold(){return e(this,Tc,"f").setThreshold}get canUpdateFirmware(){return e(this,ec,"f")?.canUpdateFirmware}get uploadFirmware(){return e(this,Ko,"m",Ic).call(this),e(this,Wc,"f").uploadFirmware}get canReset(){return this.canUpdateFirmware}async reset(){return Rc.assertWithError(this.canReset,"reset is not enabled for this device"),await e(this,Wc,"f").reset(),e(this,ec,"f").disconnect()}get firmwareStatus(){return e(this,Wc,"f").status}get getFirmwareImages(){return e(this,Ko,"m",Ic).call(this),e(this,Wc,"f").getImages}get firmwareImages(){return e(this,Wc,"f").images}get eraseFirmwareImage(){return e(this,Ko,"m",Ic).call(this),e(this,Wc,"f").eraseImage}get confirmFirmwareImage(){return e(this,Ko,"m",Ic).call(this),e(this,Wc,"f").confirmImage}get testFirmwareImage(){return e(this,Ko,"m",Ic).call(this),e(this,Wc,"f").testImage}get isServerSide(){return e(this,Lc,"f")}set isServerSide(s){e(this,Lc,"f")!=s?(Rc.log({newIsServerSide:s}),t(this,Lc,s,"f"),e(this,Dc,"f").isServerSide=this.isServerSide):Rc.log("redundant isServerSide assignment")}get isUkaton(){return this.deviceInformation.modelNumber.includes("Ukaton")}get isWifiAvailable(){return e(this,Uc,"f").isWifiAvailable}get wifiSSID(){return e(this,Uc,"f").wifiSSID}async setWifiSSID(t){return e(this,Uc,"f").setWifiSSID(t)}get wifiPassword(){return e(this,Uc,"f").wifiPassword}async setWifiPassword(t){return e(this,Uc,"f").setWifiPassword(t)}get isWifiConnected(){return e(this,Uc,"f").isWifiConnected}get ipAddress(){return e(this,Uc,"f").ipAddress}get wifiConnectionEnabled(){return e(this,Uc,"f").wifiConnectionEnabled}get enableWifiConnection(){return e(this,Uc,"f").enableWifiConnection}get setWifiConnectionEnabled(){return e(this,Uc,"f").setWifiConnectionEnabled}get disableWifiConnection(){return e(this,Uc,"f").disableWifiConnection}get toggleWifiConnection(){return e(this,Uc,"f").toggleWifiConnection}get isWifiSecure(){return e(this,Uc,"f").isWifiSecure}async reconnectViaWebSockets(){Rc.assertWithError(this.isWifiConnected,"wifi is not connected"),Rc.assertWithError("webSocket"!=this.connectionType,"already connected via webSockets"),Rc.assertTypeWithError(this.ipAddress,"string"),Rc.log("reconnecting via websockets..."),await this.disconnect(),await this.connect({type:"webSocket",ipAddress:this.ipAddress,isWifiSecure:this.isWifiSecure})}async reconnectViaUDP(){Rc.assertWithError(n,"udp is only available in node"),Rc.assertWithError(this.isWifiConnected,"wifi is not connected"),Rc.assertWithError("udp"!=this.connectionType,"already connected via udp"),Rc.assertTypeWithError(this.ipAddress,"string"),Rc.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 e(this,Fc,"f").cameraStatus}async takePicture(){e(this,Ko,"m",Ac).call(this),await e(this,Fc,"f").takePicture()}async focusCamera(){e(this,Ko,"m",Ac).call(this),await e(this,Fc,"f").focus()}async stopCamera(){e(this,Ko,"m",Ac).call(this),await e(this,Fc,"f").stop()}async wakeCamera(){e(this,Ko,"m",Ac).call(this),await e(this,Fc,"f").wake()}async sleepCamera(){e(this,Ko,"m",Ac).call(this),await e(this,Fc,"f").sleep()}get cameraConfiguration(){return e(this,Fc,"f").cameraConfiguration}get availableCameraConfigurationTypes(){return e(this,Fc,"f").availableCameraConfigurationTypes}get cameraConfigurationRanges(){return e(this,Fc,"f").cameraConfigurationRanges}get setCameraConfiguration(){return e(this,Fc,"f").setCameraConfiguration}}var Bc,Pc,Nc,Vc,qc,zc;Qo=Oc,Xo=new WeakMap,ec=new WeakMap,sc=new WeakMap,hc=new WeakMap,lc=new WeakMap,wc=new WeakMap,yc=new WeakMap,Sc=new WeakMap,Ec=new WeakMap,kc=new WeakMap,Mc=new WeakMap,Dc=new WeakMap,Tc=new WeakMap,Wc=new WeakMap,Lc=new WeakMap,Uc=new WeakMap,Fc=new WeakMap,Ko=new WeakSet,Zo=function(){return new ir},Yo=function(){return e(this,Xo,"f").dispatchEvent},tc=async function(t,s){await(e(this,ec,"f")?.sendTxMessages(t,s))},ic=function(){Rc.assertWithError(this.isConnected,"notConnected")},nc=function(e){return e.every((e=>{const t=this.latestConnectionMessages.has(e);return t||Rc.log(`didn't receive "${e}" message`),t}))},ac=function(){let t=e(this,Ko,"m",nc).call(this,$c);return t&&this.sensorTypes.includes("pressure")&&(t=e(this,Ko,"m",nc).call(this,us)),t&&this.isWifiAvailable&&(t=e(this,Ko,"m",nc).call(this,sa)),t&&this.fileTypes.length>0&&(t=e(this,Ko,"m",nc).call(this,ze)),t&&this.fileTypes.includes("tflite")&&(t=e(this,Ko,"m",nc).call(this,mi)),t&&this.hasCamera&&(t=e(this,Ko,"m",nc).call(this,as)),t},rc=function(){Rc.log("requesting required information");const t=$c.map((e=>({type:e})));e(this,Ko,"m",tc).call(this,t)},oc=function(){Rc.assertWithError(this.canReconnect,"cannot reconnect to device")},fc=function(s){Rc.log({connectionStatus:s}),"notConnected"==s?(e(this,Ko,"m",mc).call(this),this.canReconnect&&this.reconnectOnDisconnection&&(Rc.log("starting reconnect interval..."),t(this,lc,setInterval((()=>{Rc.log("attempting reconnect..."),this.reconnect()}),1e3),"f"))):null!=e(this,lc,"f")&&(Rc.log("clearing reconnect interval"),clearInterval(e(this,lc,"f")),t(this,lc,void 0,"f")),e(this,Ko,"m",uc).call(this),"connected"!=s||e(this,sc,"f")||"client"!=this.connectionType&&e(this,Ko,"m",rc).call(this),wo.OnDeviceConnectionStatusUpdated(this,s)},gc=function(t=!1){e(this,Ko,"a",Yo).call(this,"connectionStatus",{connectionStatus:this.connectionStatus}),e(this,Ko,"a",Yo).call(this,this.connectionStatus,{}),t&&e(this,Ko,"a",Yo).call(this,"isConnected",{isConnected:this.isConnected})},uc=function(){switch(t(this,sc,Boolean(this.connectionManager?.isConnected)&&e(this,Ko,"a",ac)&&this._informationManager.isCurrentTimeSet,"f"),this.connectionStatus){case"connected":e(this,sc,"f")&&e(this,Ko,"m",gc).call(this,!0);break;case"notConnected":e(this,Ko,"m",gc).call(this,!0);break;default:e(this,Ko,"m",gc).call(this,!1)}},dc=function(){e(this,Ko,"m",mc).call(this),this._informationManager.clear(),e(this,wc,"f").clear(),e(this,Tc,"f").clear(),e(this,Uc,"f").clear(),e(this,Fc,"f").clear()},mc=function(){this.connectionManager?.clear(),this.latestConnectionMessages.clear()},pc=function(t,s){if(Rc.log({messageType:t,dataView:s}),"batteryLevel"===t){const t=s.getUint8(0);Rc.log("received battery level",{batteryLevel:t}),e(this,Ko,"m",bc).call(this,t)}else if(Oe.includes(t))e(this,Dc,"f").parseMessage(t,s);else if(ui.includes(t))e(this,Tc,"f").parseMessage(t,s);else if(gs.includes(t))e(this,kc,"f").parseMessage(t,s);else if(Gr.includes(t))e(this,Wc,"f").parseMessage(t,s);else if(Mi.includes(t))e(this,wc,"f").parseMessage(t,s);else if(Zi.includes(t))this._informationManager.parseMessage(t,s);else if(Us.includes(t))e(this,Sc,"f").parseMessage(t,s);else if(kn.includes(t))e(this,Mc,"f").parseMessage(t,s);else if(ta.includes(t))e(this,Uc,"f").parseMessage(t,s);else{if(!ns.includes(t))throw Error(`uncaught messageType ${t}`);e(this,Fc,"f").parseMessage(t,s)}this.latestConnectionMessages.set(t,s),t.startsWith("set")&&this.latestConnectionMessages.set(t.replace("set","get"),s),e(this,Ko,"a",Yo).call(this,"connectionMessage",{messageType:t,dataView:s})},vc=function(){!this.isConnected&&e(this,Ko,"a",ac)&&e(this,Ko,"m",uc).call(this),"notConnected"!=this.connectionStatus&&e(this,Ko,"m",tc).call(this)},bc=function(s){Rc.assertTypeWithError(s,"number"),e(this,yc,"f")!=s?(t(this,yc,s,"f"),Rc.log({updatedBatteryLevel:e(this,yc,"f")}),e(this,Ko,"a",Yo).call(this,"batteryLevel",{batteryLevel:e(this,yc,"f")})):Rc.log(`duplicate batteryLevel assignment ${s}`)},Ic=function(){Rc.assertWithError(this.canUpdateFirmware,"can't update firmware")},_c=function(t){return e(this,Ko,"m",Ic).call(this),e(this,ec,"f").sendSmpMessage(t)},Ac=function(){Rc.assertWithError(this.hasCamera,"camera not available")},cc={value:!1},Cc={value:!0};const jc=T("DevicePairPressureSensorDataManager",{log:!1});class Gc{constructor(){Bc.add(this),Pc.set(this,{}),Nc.set(this,new at),Vc.set(this,new Ye),this.resetPressureRange()}resetPressureRange(){e(this,Nc,"f").reset(),e(this,Vc,"f").reset()}onDevicePressureData(t){const{pressure:s}=t.message,{side:i}=t.target;if(jc.log({pressure:s,side:i}),e(this,Pc,"f")[i]=s,e(this,Bc,"a",qc))return e(this,Bc,"m",zc).call(this);jc.log("doesn't have all pressure data yet...")}}var Hc;Pc=new WeakMap,Nc=new WeakMap,Vc=new WeakMap,Bc=new WeakSet,qc=function(){return Ji.every((t=>t in e(this,Pc,"f")))},zc=function(){const t={scaledSum:0,normalizedSum:0,sensors:{left:[],right:[]}};return Ji.forEach((s=>{const i=e(this,Pc,"f")[s];t.scaledSum+=i.scaledSum})),t.normalizedSum+=e(this,Vc,"f").updateAndGetNormalization(t.scaledSum,!1),t.scaledSum>0&&(t.center={x:0,y:0},Ji.forEach((s=>{e(this,Pc,"f")[s].sensors.forEach((e=>{const i={...e};i.weightedValue=e.scaledValue/t.scaledSum;let{x:n,y:a}=e.position;n/=2,"right"==s&&(n+=.5),i.position={x:n,y:a},t.center.x+=i.position.x*i.weightedValue,t.center.y+=i.position.y*i.weightedValue,t.sensors[s].push(i)}))})),t.normalizedCenter=e(this,Nc,"f").updateAndGetNormalization(t.center,!1)),jc.log({devicePairPressure:t}),t};const Jc=T("DevicePairSensorDataManager",{log:!1}),Kc=["pressure","sensorData"];class Qc{constructor(){Hc.set(this,{}),this.pressureSensorDataManager=new Gc}get dispatchEvent(){return this.eventDispatcher.dispatchEvent}resetPressureRange(){this.pressureSensorDataManager.resetPressureRange()}onDeviceSensorData(t){const{timestamp:s,sensorType:i}=t.message;let n;if(Jc.log({sensorType:i,timestamp:s,event:t}),e(this,Hc,"f")[i]||(e(this,Hc,"f")[i]={}),e(this,Hc,"f")[i][t.target.side]=s,"pressure"===i)n=this.pressureSensorDataManager.onDevicePressureData(t);else Jc.log(`uncaught sensorType "${i}"`);if(n){const t=Object.assign({},e(this,Hc,"f")[i]);this.dispatchEvent(i,{sensorType:i,timestamps:t,[i]:n}),this.dispatchEvent("sensorData",{sensorType:i,timestamps:t,[i]:n})}else Jc.log("no value received")}}var Zc,Xc,Yc,eh,th,sh,ih,nh,ah,rh,oh,ch,hh,lh,fh,gh,uh,dh,mh;Hc=new WeakMap;const ph=T("DevicePair",{log:!1});function vh(e){return`device${t=e,t[0].toUpperCase()+t.slice(1)}`;var t}const wh=["isConnected",...Kc,...xc.map((e=>vh(e)))],yh=["insoles","gloves"];class bh{constructor(s){Zc.add(this),Yc.set(this,void 0),eh.set(this,new L(this,wh)),sh.set(this,void 0),ih.set(this,void 0),ch.set(this,{isConnected:e(this,Zc,"m",lh).bind(this),sensorData:e(this,Zc,"m",uh).bind(this),getType:e(this,Zc,"m",fh).bind(this)}),gh.set(this,new Qc),t(this,Yc,s,"f"),e(this,gh,"f").eventDispatcher=e(this,eh,"f")}get sides(){return Ji}get type(){return e(this,Yc,"f")}get addEventListener(){return e(this,eh,"f").addEventListener}get removeEventListener(){return e(this,eh,"f").removeEventListener}get waitForEvent(){return e(this,eh,"f").waitForEvent}get removeEventListeners(){return e(this,eh,"f").removeEventListeners}get removeAllEventListeners(){return e(this,eh,"f").removeAllEventListeners}get left(){return e(this,sh,"f")}get right(){return e(this,ih,"f")}get isConnected(){return Ji.every((e=>this[e]?.isConnected))}get isPartiallyConnected(){return Ji.some((e=>this[e]?.isConnected))}get isHalfConnected(){return this.isPartiallyConnected&&!this.isConnected}assignDevice(s){if(!e(this,Zc,"m",nh).call(this,s))return void ph.log(`device is incorrect type ${s.type} for ${this.type} devicePair`);const i=s.side,n=this[i];if(s!=n){switch(n&&e(this,Zc,"m",rh).call(this,n),e(this,Zc,"m",ah).call(this,s),i){case"left":t(this,sh,s,"f");break;case"right":t(this,ih,s,"f")}return ph.log(`assigned ${i} ${this.type} device`,s),this.resetPressureRange(),e(this,Zc,"a",th).call(this,"isConnected",{isConnected:this.isConnected}),e(this,Zc,"a",th).call(this,"deviceIsConnected",{device:s,isConnected:s.isConnected,side:i}),n}ph.log("device already assigned")}async setSensorConfiguration(e){for(let t=0;t<Ji.length;t++){const s=Ji[t];this[s]?.isConnected&&await this[s].setSensorConfiguration(e)}}resetPressureRange(){Ji.forEach((e=>this[e]?.resetPressureRange())),e(this,gh,"f").resetPressureRange()}async triggerVibration(e,t){const s=Ji.map((s=>this[s]?.triggerVibration(e,t))).filter(Boolean);return Promise.allSettled(s)}static get insoles(){return e(this,Xc,"f",dh)}static get gloves(){return e(this,Xc,"f",mh)}}var Sh,Ch,Eh,kh,Mh;Xc=bh,Yc=new WeakMap,eh=new WeakMap,sh=new WeakMap,ih=new WeakMap,ch=new WeakMap,gh=new WeakMap,Zc=new WeakSet,th=function(){return e(this,eh,"f").dispatchEvent},nh=function(e){switch(this.type){case"insoles":return e.isInsole;case"gloves":return e.isGlove}},ah=function(t){Ta(t,e(this,ch,"f")),xc.forEach((s=>{t.addEventListener(s,e(this,Zc,"m",hh).bind(this))}))},rh=function(t){Wa(t,e(this,ch,"f")),xc.forEach((s=>{t.removeEventListener(s,e(this,Zc,"m",hh).bind(this))}))},oh=function(s){const i=Ji.some((i=>{if(this[i]!=s)return!1;switch(ph.log(`removing ${i} ${this.type} device`,s),Wa(s,e(this,ch,"f")),i){case"left":t(this,sh,void 0,"f");break;case"right":t(this,ih,void 0,"f")}return!0}));return i&&e(this,Zc,"a",th).call(this,"isConnected",{isConnected:this.isConnected}),i},hh=function(t){const{type:s,target:i,message:n}=t;e(this,Zc,"a",th).call(this,vh(s),{...n,device:i,side:i.side})},lh=function(t){e(this,Zc,"a",th).call(this,"isConnected",{isConnected:this.isConnected})},fh=function(t){const{target:s}=t;if(this[s.side]==s)return;e(this,Zc,"m",oh).call(this,s)&&this.assignDevice(s)},uh=function(t){this.isConnected&&e(this,gh,"f").onDeviceSensorData(t)},dh={value:new Xc("insoles")},mh={value:new Xc("gloves")},wo.AddEventListener("deviceConnected",(t=>{const{device:s}=t.message;s.isInsole&&e(Xc,Xc,"f",dh).assignDevice(s),s.isGlove&&e(Xc,Xc,"f",mh).assignDevice(s)}));const Dh=T("ClientConnectionManager",{log:!1});class Th extends Ma{constructor(){super(...arguments),Sh.add(this),Ch.set(this,void 0),Eh.set(this,!1)}static get isSupported(){return i}static get type(){return"client"}get canUpdateFirmware(){return!1}get bluetoothId(){return e(this,Ch,"f")}set bluetoothId(s){Dh.assertTypeWithError(s,"string"),e(this,Ch,"f")!=s?t(this,Ch,s,"f"):Dh.log("redundant bluetoothId assignment")}get isConnected(){return e(this,Eh,"f")}set isConnected(s){Dh.assertTypeWithError(s,"boolean"),e(this,Eh,"f")!=s?(t(this,Eh,s,"f"),this.status=e(this,Eh,"f")?"connected":"notConnected",this.isConnected&&e(this,Sh,"m",kh).call(this)):Dh.log("redundant newIsConnected assignment",s)}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(t){Dh.log({dataView:t}),Et(t,xc,e(this,Sh,"m",Mh).bind(this),null,!0),this.onMessagesReceived()}}var Wh,Ih,_h,Lh,Uh,Fh,Ah,Rh,xh,$h,Oh,Bh,Ph,Nh,Vh,qh,zh,jh,Gh,Hh,Jh,Kh,Qh,Zh;Ch=new WeakMap,Eh=new WeakMap,Sh=new WeakSet,kh=function(){this.sendRequiredDeviceInformationMessage()},Mh=function(e,t){let s=0;switch(Dh.log({messageType:e},t),e){case"isConnected":const i=Boolean(t.getUint8(s++));Dh.log({isConnected:i}),this.isConnected=i;break;case"rx":this.parseRxMessage(t);break;default:this.onMessageReceived(e,t)}};const Xh=T("BaseClient",{log:!1}),Yh=["notConnected","connecting","connected","disconnecting","connectionStatus","isConnected","isScanningAvailable","isScanning","discoveredDevice","expiredDiscoveredDevice"];class el{constructor(){Wh.add(this),Lh.set(this,{}),Uh.set(this,new L(this,Yh)),this._reconnectOnDisconnection=this.baseConstructor.ReconnectOnDisconnection,Fh.set(this,"notConnected"),xh.set(this,[]),Bh.set(this,!1),qh.set(this,!1),Kh.set(this,{})}get baseConstructor(){return this.constructor}get devices(){return e(this,Lh,"f")}get addEventListener(){return e(this,Uh,"f").addEventListener}get dispatchEvent(){return e(this,Uh,"f").dispatchEvent}get removeEventListener(){return e(this,Uh,"f").removeEventListener}get waitForEvent(){return e(this,Uh,"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 e(this,Fh,"f")}set _connectionStatus(s){switch(Xh.assertTypeWithError(s,"string"),Xh.log({newConnectionStatus:s}),t(this,Fh,s,"f"),this.dispatchEvent("connectionStatus",{connectionStatus:this.connectionStatus}),this.dispatchEvent(this.connectionStatus,{}),s){case"connected":case"notConnected":this.dispatchEvent("isConnected",{isConnected:this.isConnected}),this.isConnected||e(this,Wh,"m",_h).call(this)}}get connectionStatus(){return this._connectionStatus}_sendRequiredMessages(){Xh.log("sending required messages",e(this,xh,"f")),this.sendServerMessage(...e(this,Wh,"a",Rh))}parseMessage(t){Xh.log("parseMessage",{dataView:t}),Et(t,bo,e(this,Wh,"m",Oh).bind(this),null,!0),e(this,Wh,"m",$h).call(this)}get isScanningAvailable(){return e(this,Wh,"a",Ph)}requestIsScanningAvailable(){this.sendServerMessage("isScanningAvailable")}get isScanning(){return e(this,Wh,"a",zh)}startScan(){e(this,Wh,"m",Jh).call(this),this.sendServerMessage("startScan")}stopScan(){e(this,Wh,"m",Hh).call(this),this.sendServerMessage("stopScan")}toggleScan(){e(this,Wh,"m",Vh).call(this),this.isScanning?this.stopScan():this.startScan()}get discoveredDevices(){return e(this,Kh,"f")}onDiscoveredDevice(t){Xh.log({discoveredDevice:t}),e(this,Kh,"f")[t.bluetoothId]=t,this.dispatchEvent("discoveredDevice",{discoveredDevice:t})}requestDiscoveredDevices(){this.sendServerMessage({type:"discoveredDevices"})}connectToDevice(e,t){return this.requestConnectionToDevice(e,t)}requestConnectionToDevice(t,s){this.assertConnection(),Xh.assertTypeWithError(t,"string");const i=e(this,Wh,"m",Zh).call(this,t);return s?i.connect({type:"client",subType:s}):i.connect(),i}sendConnectToDeviceMessage(e,t){t?this.sendServerMessage({type:"connectToDevice",data:j(G(e),wa.indexOf(t))}):this.sendServerMessage({type:"connectToDevice",data:e})}createDevice(t){const s=new Oc,i=e(this,Kh,"f")[t],n=new Th;return n.discoveredDevice=Object.assign({},i),n.client=this,n.bluetoothId=t,n.sendClientMessage=this.sendDeviceMessage.bind(this,t),n.sendRequiredDeviceInformationMessage=this.sendRequiredDeviceInformationMessage.bind(this,t),n.sendClientConnectMessage=this.sendConnectToDeviceMessage.bind(this,t),n.sendClientDisconnectMessage=this.sendDisconnectFromDeviceMessage.bind(this,t),s.connectionManager=n,s}onConnectedBluetoothDeviceIds(t){Xh.log({bluetoothIds:t}),t.forEach((t=>{const s=e(this,Wh,"m",Zh).call(this,t);s.connectionManager.isConnected=!0,wo._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,Eo(...t)]})}sendRequiredDeviceInformationMessage(e){this.sendServerMessage({type:"requiredDeviceInformation",data:[e]})}}var tl,sl,il,nl,al,rl,ol,cl,hl,ll,fl,gl,ul;Ih=el,Lh=new WeakMap,Uh=new WeakMap,Fh=new WeakMap,xh=new WeakMap,Bh=new WeakMap,qh=new WeakMap,Kh=new WeakMap,Wh=new WeakSet,_h=function(){t(this,Wh,!1,"a",Nh),t(this,Wh,!1,"a",jh);for(const t in e(this,Lh,"f")){e(this,Lh,"f")[t].connectionManager.isConnected=!1}e(this,xh,"f").length=0},Rh=function(){return e(Ih,Ih,"f",Ah)},$h=function(){"connecting"==this.connectionStatus&&(Xh.log("checking if fully connected..."),e(this,xh,"f").includes("isScanningAvailable")?!this.isScanningAvailable||e(this,xh,"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"))},Oh=function(s,i){let n=0;switch(Xh.log({messageType:s},i),s){case"isScanningAvailable":{const e=Boolean(i.getUint8(n++));Xh.log({isScanningAvailable:e}),t(this,Wh,e,"a",Nh)}break;case"isScanning":{const e=Boolean(i.getUint8(n++));Xh.log({isScanning:e}),t(this,Wh,e,"a",jh)}break;case"discoveredDevice":{const{string:e}=Ct(i,n);Xh.log({discoveredDeviceString:e});const t=JSON.parse(e);Xh.log({discoveredDevice:t}),this.onDiscoveredDevice(t)}break;case"expiredDiscoveredDevice":{const{string:t}=Ct(i,n);e(this,Wh,"m",Qh).call(this,t)}break;case"connectedDevices":{if(0==i.byteLength)break;const{string:e}=Ct(i,n);Xh.log({connectedBluetoothDeviceIdStrings:e});const t=JSON.parse(e).connectedDevices;Xh.log({connectedBluetoothDeviceIds:t}),this.onConnectedBluetoothDeviceIds(t)}break;case"deviceMessage":{const{string:t,byteOffset:s}=Ct(i,n);n=s;const a=e(this,Lh,"f")[t];Xh.assertWithError(a,`no device found for id ${t}`);const r=a.connectionManager,o=H(i,n);r.onClientMessage(o)}break;default:Xh.error(`uncaught messageType "${s}"`)}"connecting"==this.connectionStatus&&e(this,xh,"f").push(s)},Ph=function(){return e(this,Bh,"f")},Nh=function(s){Xh.assertTypeWithError(s,"boolean"),t(this,Bh,s,"f"),this.dispatchEvent("isScanningAvailable",{isScanningAvailable:this.isScanningAvailable}),this.isScanningAvailable&&e(this,Wh,"m",Gh).call(this)},Vh=function(){this.assertConnection(),Xh.assertWithError(this.isScanningAvailable,"scanning is not available")},zh=function(){return e(this,qh,"f")},jh=function(e){Xh.assertTypeWithError(e,"boolean"),t(this,qh,e,"f"),this.dispatchEvent("isScanning",{isScanning:this.isScanning})},Gh=function(){this.sendServerMessage("isScanning")},Hh=function(){Xh.assertWithError(this.isScanning,"is not scanning")},Jh=function(){Xh.assertWithError(!this.isScanning,"is already scanning")},Qh=function(t){Xh.log({expiredBluetoothDeviceId:t});const s=e(this,Kh,"f")[t];s?(Xh.log({expiredDiscoveredDevice:s}),delete e(this,Kh,"f")[t],this.dispatchEvent("expiredDiscoveredDevice",{discoveredDevice:s})):Xh.warn(`no discoveredDevice found with id "${t}"`)},Zh=function(t){let s=e(this,Lh,"f")[t];return s||(s=this.createDevice(t),e(this,Lh,"f")[t]=s),s},el._reconnectOnDisconnection=!0,Ah={value:["isScanningAvailable","discoveredDevices","connectedDevices"]};const dl=T("WebSocketClient",{log:!1});class ml extends el{constructor(){super(...arguments),tl.add(this),sl.set(this,void 0),nl.set(this,{open:e(this,tl,"m",al).bind(this),message:e(this,tl,"m",rl).bind(this),close:e(this,tl,"m",ol).bind(this),error:e(this,tl,"m",cl).bind(this)}),fl.set(this,new x(e(this,tl,"m",gl).bind(this),3e4))}get webSocket(){return e(this,sl,"f")}set webSocket(s){e(this,sl,"f")!=s?(dl.log("assigning webSocket",s),e(this,sl,"f")&&Wa(e(this,sl,"f"),e(this,nl,"f")),Ta(s,e(this,nl,"f")),t(this,sl,s,"f"),dl.log("assigned webSocket")):dl.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(t){this.assertConnection(),e(this,sl,"f").send(t),e(this,fl,"f").restart()}sendServerMessage(...e){this.sendMessage(Do({type:"serverMessage",data:Co(...e)}))}}sl=new WeakMap,nl=new WeakMap,fl=new WeakMap,tl=new WeakSet,il=function(...e){this.sendMessage(Do(...e))},al=function(t){dl.log("webSocket.open",t),e(this,fl,"f").start(),this._sendRequiredMessages()},rl=async function(t){dl.log("webSocket.message",t);const s=await t.data.arrayBuffer(),i=new DataView(s);e(this,tl,"m",hl).call(this,i)},ol=function(t){dl.log("webSocket.close",t),this._connectionStatus="notConnected",Object.entries(this.devices).forEach((([e,t])=>{t.connectionManager.isConnected=!1})),e(this,fl,"f").stop(),this.reconnectOnDisconnection&&setTimeout((()=>{this.reconnect()}),3e3)},cl=function(e){dl.error("webSocket.error",e)},hl=function(t){Et(t,Mo,e(this,tl,"m",ll).bind(this),null,!0)},ll=function(t,s){switch(t){case"ping":e(this,tl,"m",ul).call(this);break;case"pong":break;case"serverMessage":this.parseMessage(s);break;default:dl.error(`uncaught messageType "${t}"`)}},gl=function(){e(this,tl,"m",il).call(this,"ping")},ul=function(){e(this,tl,"m",il).call(this,"pong")};const pl={addEventListeners:Ta,removeEventListeners:Wa},vl={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)}}};export{es as CameraCommands,is as CameraConfigurationTypes,fs as ContinuousSensorTypes,ht as DefaultNumberOfPressureSensors,Oc as Device,wo as DeviceManager,bh as DevicePair,yh as DevicePairTypes,Hi as DeviceTypes,w as Environment,pl as EventUtils,Ve as FileTransferDirections,Be as FileTypes,Qi as MaxNameLength,Dn as MaxNumberOfVibrationWaveformEffectSegments,_n as MaxNumberOfVibrationWaveformSegments,_s as MaxSensorRate,Wn as MaxVibrationWaveformEffectSegmentDelay,In as MaxVibrationWaveformEffectSegmentLoopCount,Ln as MaxVibrationWaveformEffectSequenceLoopCount,Tn as MaxVibrationWaveformSegmentDuration,ea as MaxWifiPasswordLength,Xn as MaxWifiSSIDLength,Ki as MinNameLength,Yn as MinWifiPasswordLength,Zn as MinWifiSSIDLength,Ye as RangeHelper,Ls as SensorRateStep,ls as SensorTypes,Ji as Sides,vi as TfliteSensorTypes,pi as TfliteTasks,vl as ThrottleUtils,Cn as VibrationLocations,En as VibrationTypes,en as VibrationWaveformEffects,ml as WebSocketClient,I as setAllConsoleLevelFlags,W as setConsoleLevelFlagsForType};
6
6
  //# sourceMappingURL=brilliantsole.module.min.js.map