brilliantsole 0.0.26 → 0.0.27

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 (110) hide show
  1. package/README.md +16 -10
  2. package/assets/3d/rightHand.glb +0 -0
  3. package/assets/images/ukaton-pressure-0.svg +9 -0
  4. package/assets/images/ukaton-pressure-1.svg +9 -0
  5. package/assets/images/ukaton-pressure-10.svg +9 -0
  6. package/assets/images/ukaton-pressure-11.svg +9 -0
  7. package/assets/images/ukaton-pressure-12.svg +9 -0
  8. package/assets/images/ukaton-pressure-13.svg +9 -0
  9. package/assets/images/ukaton-pressure-14.svg +9 -0
  10. package/assets/images/ukaton-pressure-15.svg +9 -0
  11. package/assets/images/ukaton-pressure-2.svg +9 -0
  12. package/assets/images/ukaton-pressure-3.svg +9 -0
  13. package/assets/images/ukaton-pressure-4.svg +9 -0
  14. package/assets/images/ukaton-pressure-5.svg +9 -0
  15. package/assets/images/ukaton-pressure-6.svg +9 -0
  16. package/assets/images/ukaton-pressure-7.svg +9 -0
  17. package/assets/images/ukaton-pressure-8.svg +9 -0
  18. package/assets/images/ukaton-pressure-9.svg +9 -0
  19. package/assets/images/ukaton-right-insole.svg +798 -0
  20. package/build/brilliantsole.cjs +255 -119
  21. package/build/brilliantsole.cjs.map +1 -1
  22. package/build/brilliantsole.js +283 -140
  23. package/build/brilliantsole.js.map +1 -1
  24. package/build/brilliantsole.ls.js +210 -103
  25. package/build/brilliantsole.ls.js.map +1 -1
  26. package/build/brilliantsole.min.js +1 -1
  27. package/build/brilliantsole.min.js.map +1 -1
  28. package/build/brilliantsole.module.d.ts +76 -60
  29. package/build/brilliantsole.module.js +282 -140
  30. package/build/brilliantsole.module.js.map +1 -1
  31. package/build/brilliantsole.module.min.d.ts +76 -60
  32. package/build/brilliantsole.module.min.js +1 -1
  33. package/build/brilliantsole.module.min.js.map +1 -1
  34. package/build/brilliantsole.node.module.d.ts +75 -60
  35. package/build/brilliantsole.node.module.js +254 -119
  36. package/build/brilliantsole.node.module.js.map +1 -1
  37. package/build/dts/BS.d.ts +2 -2
  38. package/build/dts/Device.d.ts +11 -7
  39. package/build/dts/DeviceManager.d.ts +1 -0
  40. package/build/dts/InformationManager.d.ts +6 -5
  41. package/build/dts/connection/BaseConnectionManager.d.ts +2 -0
  42. package/build/dts/connection/ClientConnectionManager.d.ts +4 -0
  43. package/build/dts/connection/bluetooth/BluetoothConnectionManager.d.ts +1 -0
  44. package/build/dts/connection/bluetooth/NobleConnectionManager.d.ts +1 -0
  45. package/build/dts/connection/bluetooth/WebBluetoothConnectionManager.d.ts +1 -0
  46. package/build/dts/devicePair/DevicePair.d.ts +14 -10
  47. package/build/dts/devicePair/DevicePairPressureSensorDataManager.d.ts +8 -4
  48. package/build/dts/devicePair/DevicePairSensorDataManager.d.ts +2 -2
  49. package/build/dts/server/BaseClient.d.ts +1 -0
  50. package/build/dts/utils/CenterOfPressureHelper.d.ts +2 -2
  51. package/build/dts/utils/MathUtils.d.ts +2 -0
  52. package/build/index.d.ts +76 -60
  53. package/build/index.node.d.ts +75 -60
  54. package/examples/3d/script.js +90 -17
  55. package/examples/balance/script.js +2 -1
  56. package/examples/basic/index.html +21 -2
  57. package/examples/basic/script.js +17 -3
  58. package/examples/bottango/index.html +11 -1
  59. package/examples/bottango/script.js +2 -2
  60. package/examples/center-of-pressure/index.html +114 -114
  61. package/examples/center-of-pressure/script.js +1 -1
  62. package/examples/device-pair/index.html +58 -58
  63. package/examples/device-pair/script.js +12 -8
  64. package/examples/gloves/index.html +116 -0
  65. package/examples/gloves/scene.html +124 -0
  66. package/examples/gloves/script.js +615 -0
  67. package/examples/graph/index.html +11 -1
  68. package/examples/graph/script.js +2 -2
  69. package/examples/pressure/index.html +180 -12
  70. package/examples/pressure/script.js +144 -7
  71. package/examples/recording/index.html +191 -183
  72. package/examples/server/index.html +11 -1
  73. package/examples/server/script.js +6 -3
  74. package/examples/ukaton-firmware-update/index.html +20 -0
  75. package/examples/ukaton-firmware-update/manifest.json +11 -0
  76. package/examples/ukaton-firmware-update/merged-firmware.bin +0 -0
  77. package/examples/webxr/script.js +3 -3
  78. package/package.json +1 -1
  79. package/src/BS.ts +3 -8
  80. package/src/Device.ts +41 -8
  81. package/src/DeviceInformationManager.ts +4 -2
  82. package/src/DeviceManager.ts +10 -1
  83. package/src/FileTransferManager.ts +1 -1
  84. package/src/FirmwareManager.ts +1 -1
  85. package/src/InformationManager.ts +24 -7
  86. package/src/TfliteManager.ts +1 -1
  87. package/src/connection/BaseConnectionManager.ts +23 -6
  88. package/src/connection/ClientConnectionManager.ts +13 -1
  89. package/src/connection/bluetooth/BluetoothConnectionManager.ts +6 -1
  90. package/src/connection/bluetooth/NobleConnectionManager.ts +8 -1
  91. package/src/connection/bluetooth/WebBluetoothConnectionManager.ts +5 -1
  92. package/src/devicePair/DevicePair.ts +53 -27
  93. package/src/devicePair/DevicePairPressureSensorDataManager.ts +51 -23
  94. package/src/devicePair/DevicePairSensorDataManager.ts +5 -5
  95. package/src/scanner/NobleScanner.ts +5 -3
  96. package/src/sensor/BarometerSensorDataManager.ts +1 -1
  97. package/src/sensor/MotionSensorDataManager.ts +1 -1
  98. package/src/sensor/PressureSensorDataManager.ts +13 -8
  99. package/src/sensor/SensorConfigurationManager.ts +3 -3
  100. package/src/sensor/SensorDataManager.ts +1 -1
  101. package/src/server/BaseClient.ts +43 -2
  102. package/src/server/BaseServer.ts +149 -39
  103. package/src/server/udp/UDPServer.ts +1 -1
  104. package/src/server/websocket/WebSocketClient.ts +3 -2
  105. package/src/server/websocket/WebSocketServer.ts +1 -1
  106. package/src/utils/CenterOfPressureHelper.ts +5 -5
  107. package/src/utils/MathUtils.ts +31 -1
  108. package/src/utils/ParseUtils.ts +1 -1
  109. package/src/utils/checksum.ts +1 -1
  110. package/src/utils/mcumgr.js +1 -1
@@ -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),C=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?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?M:y}get table(){return e(this,p,"f").table?C: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 x{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 A(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:!0});const $=new Uint32Array(256);for(let e=0;e<256;++e)$[e]=A(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 q(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 q(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 q(e){const t=P.encode(e);return j(t.byteLength,t)}function G(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,Ce,Me,De,ke,Te,_e,We,Ie,Le,Ue;const Fe=k("FileTransferManager",{log:!0}),Re=["maxFileLength","getFileType","setFileType","getFileLength","setFileLength","getFileChecksum","setFileChecksum","setFileTransferCommand","fileTransferStatus","getFileBlock","setFileBlock","fileBytesTransferred"],xe=["tflite"],Ae=["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",Ce).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",Ce).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",Me).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,xe)},Y=function(e){Fe.assertWithError(e in xe,`invalid typeEnum ${e}`)},ee=function(e){Fe.assertWithError(e in Ae,`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=xe[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=xe.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=Ae[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},Ce=function(){Fe.assertWithError("idle"==e(this,be,"f"),"status is not idle")},Me=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:!0});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,qe,Ge;const He={min:1/0,max:-1/0,span:0};class Je{constructor(){je.add(this),qe.set(this,Object.assign({},He))}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,je,"m",Ge).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,je,"m",Ge).call(this)}reset(){Object.assign(e(this,qe,"f"),He)}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,je,"m",Ge).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 Qe,Ke,Ze,Xe;qe=new WeakMap,je=new WeakSet,Ge=function(){e(this,qe,"f").span=e(this,qe,"f").max-e(this,qe,"f").min};class Ye{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){return{x:e(this,Qe,"f").x.getNormalization(t.x,!1),y:e(this,Qe,"f").y.getNormalization(t.y,!1)}}updateAndGetNormalization(e){return this.update(e),this.getNormalization(e)}}Qe=new WeakMap;const et=k("PressureDataManager",{log:!0}),tt=["pressure"],st=tt,it=8;class nt{constructor(){Ke.set(this,[]),Ze.set(this,void 0),Xe.set(this,new Ye)}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;et.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,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),o=a*s,c=e(this,Ze,"f")[n].updateAndGetNormalization(o,!0),h=this.positions[n];i.sensors[n]={rawValue:a,scaledValue:o,normalizedValue:c,position:h,weightedValue:0},i.scaledSum+=o,i.normalizedSum+=c/this.numberOfSensors}return i.scaledSum>0&&i.normalizedSum>.001&&(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,Xe,"f").updateAndGetNormalization(i.center)),et.log({pressure:i}),i}}Ke=new WeakMap,Ze=new WeakMap,Xe=new WeakMap;const rt=k("MotionSensorDataManager",{log:!0}),at=["still","walking","running","bicycle","vehicle","tilting"],ot=["portraitUpright","landscapeLeft","portraitUpsideDown","landscapeRight","unknown"];class ct{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 rt.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 rt.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 rt.log({euler:r}),r}parseStepCounter(e){rt.log("parseStepCounter",e);const t=e.getUint32(0,!0);return rt.log({stepCount:t}),t}parseActivity(e){rt.log("parseActivity",e);const t={},s=e.getUint8(0);return rt.log("activityBitfield",s.toString(2)),at.forEach(((e,i)=>{t[e]=Boolean(s&1<<i)})),rt.log("activity",t),t}parseDeviceOrientation(e){rt.log("parseDeviceOrientation",e);const t=e.getUint8(0),s=ot[t];return rt.assertWithError(s,"undefined deviceOrientation"),rt.log({deviceOrientation:s}),s}}var ht,lt;const gt=["barometer"],ft=gt,ut=k("BarometerSensorDataManager",{log:!0});class dt{constructor(){ht.add(this)}parseData(t,s){const i=t.getUint32(0,!0)*s,n=e(this,ht,"m",lt).call(this,i);return ut.log({pressure:i,altitude:n}),{pressure:i}}}ht=new WeakSet,lt=function(e){const t=.0065;return 288.15/t*(1-Math.pow(e/101325,.19026643566373183))};const mt=k("ParseUtils",{log:!0});function pt(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 vt(e,t,s,i,n=!1){let r=0;for(;r<e.byteLength;){const a=e.getUint8(r++);mt.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++),mt.log({messageTypeEnum:a,messageType:o,messageLength:c,dataView:e,byteOffset:r});const h=G(e,r,c);mt.log({_dataView:h}),s(o,h,i),r+=c}}var wt;const yt=k("SensorDataManager",{log:!0}),bt=[...tt,"acceleration","gravity","linearAcceleration","gyroscope","magnetometer","gameRotation","rotation","orientation","activity","stepCounter","stepDetector","deviceOrientation",...gt],St=[...st,"acceleration","gravity","linearAcceleration","gyroscope","magnetometer","gameRotation","rotation",...ft],Et=["getPressurePositions","getSensorScalars","sensorData"],Ct=[...Et,...bt];class Mt{constructor(){this.pressureSensorDataManager=new nt,this.motionSensorDataManager=new ct,this.barometerSensorDataManager=new dt,wt.set(this,new Map)}static AssertValidSensorType(e){yt.assertEnumWithError(e,bt)}static AssertValidSensorTypeEnum(e){yt.assertTypeWithError(e,"number"),yt.assertWithError(e in bt,`invalid sensorTypeEnum ${e}`)}get dispatchEvent(){return this.eventDispatcher.dispatchEvent}parseMessage(e,t){switch(yt.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=bt[i];if(!n){yt.warn(`unknown sensorType index ${i}`);continue}const r=t.getFloat32(s+1,!0);yt.log({sensorType:n,sensorScalar:r}),e(this,wt,"f").set(n,r)}}parseData(e){yt.log("sensorData",Array.from(new Uint8Array(e.buffer)));let t=0;const s=ze(e,t);t+=2;vt(new DataView(e.buffer,t),bt,this.parseDataCallback.bind(this),{timestamp:s})}parseDataCallback(t,s,{timestamp:i}){const n=e(this,wt,"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:yt.error(`uncaught sensorType "${t}"`)}yt.assertWithError(null!=r,`no sensorData defined for sensorType "${t}"`),yt.log({sensorType:t,sensorData:r}),this.dispatchEvent(t,{sensorType:t,[t]:r,timestamp:i}),this.dispatchEvent("sensorData",{sensorType:t,[t]:r,timestamp:i})}}var Dt,kt,Tt,_t,Wt,It,Lt,Ut,Ft,Rt,xt,At,$t;wt=new WeakMap;const Ot=k("SensorConfigurationManager",{log:!0}),Bt=65535,Nt=5,Pt=["getSensorConfiguration","setSensorConfiguration"],Vt=Pt;class zt{constructor(){Dt.add(this),_t.set(this,void 0),It.set(this,void 0),J(this)}get addEventListener(){return this.eventDispatcher.addEventListener}get waitForEvent(){return this.eventDispatcher.waitForEvent}get configuration(){return e(this,It,"f")}async setConfiguration(t,s){if(s&&(t=Object.assign({...this.zeroSensorConfiguration},t)),Ot.log({newSensorConfiguration:t}),e(this,Dt,"m",Ut).call(this,t))return void Ot.log("redundant sensor configuration");const i=e(this,Dt,"m",At).call(this,t);Ot.log({setSensorConfigurationData:i});const n=this.waitForEvent("getSensorConfiguration");this.sendMessage([{type:"setSensorConfiguration",data:i.buffer}]),await n}static get ZeroSensorConfiguration(){return e(this,kt,"f",$t)}get zeroSensorConfiguration(){const e={};return bt.forEach((t=>{e[t]=0})),e}async clearSensorConfiguration(){return this.setConfiguration(this.zeroSensorConfiguration)}parseMessage(t,s){switch(Ot.log({messageType:t}),t){case"getSensorConfiguration":case"setSensorConfiguration":const i=e(this,Dt,"m",Ft).call(this,s);e(this,Dt,"m",Lt).call(this,i);break;default:throw Error(`uncaught messageType ${t}`)}}}var jt,qt,Gt,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;kt=zt,_t=new WeakMap,It=new WeakMap,Dt=new WeakSet,Tt=function(){return this.eventDispatcher.dispatchEvent},Wt=function(t){Ot.assertWithError(e(this,_t,"f"),"must get initial sensorConfiguration");const s=e(this,_t,"f")?.includes(t);return Ot.assert(s,`unavailable sensor type "${t}"`),s},Lt=function(s){t(this,It,s,"f"),Ot.log({updatedConfiguration:e(this,It,"f")}),e(this,Dt,"a",Tt).call(this,"getSensorConfiguration",{sensorConfiguration:this.configuration})},Ut=function(e){return Object.keys(e).every((t=>this.configuration[t]==e[t]))},Ft=function(e){const s={};for(let t=0;t<e.byteLength;t+=3){const i=e.getUint8(t),n=bt[i];if(!n){Ot.warn(`unknown sensorType index ${i}`);continue}const r=e.getUint16(t+1,!0);Ot.log({sensorType:n,sensorRate:r}),s[n]=r}return Ot.log({parsedSensorConfiguration:s}),t(this,_t,Object.keys(s),"f"),s},Rt=function(e){Ot.assertTypeWithError(e,"number"),Ot.assertWithError(e>=0,`sensorRate must be 0 or greater (got ${e})`),Ot.assertWithError(e<65535,`sensorRate must be 0 or greater (got ${e})`),Ot.assertWithError(e%5==0,"sensorRate must be multiple of 5")},xt=function(t){e(kt,kt,"m",Rt).call(kt,t)},At=function(t){let s=Object.keys(t);s=s.filter((t=>e(this,Dt,"m",Wt).call(this,t)));const i=new DataView(new ArrayBuffer(3*s.length));return s.forEach(((s,n)=>{Mt.AssertValidSensorType(s);const r=bt.indexOf(s);i.setUint8(3*n,r);const a=t[s];e(this,Dt,"m",xt).call(this,a),i.setUint16(3*n+1,a,!0)})),Ot.log({sensorConfigurationData:i}),i},$t={value:{}},bt.forEach((t=>{e(kt,kt,"f",$t)[t]=0}));const bs=k("TfliteManager",{log:!0}),Ss=["getTfliteName","setTfliteName","getTfliteTask","setTfliteTask","getTfliteSampleRate","setTfliteSampleRate","getTfliteSensorTypes","setTfliteSensorTypes","tfliteIsReady","getTfliteCaptureDelay","setTfliteCaptureDelay","getTfliteThreshold","setTfliteThreshold","getTfliteInferencingEnabled","setTfliteInferencingEnabled","tfliteInference"],Es=Ss,Cs=["classification","regression"],Ms=["pressure","linearAcceleration","gyroscope","magnetometer"];class Ds{constructor(){jt.add(this),Jt.set(this,void 0),Zt.set(this,void 0),es.set(this,void 0),is.set(this,[]),as.set(this,void 0),ls.set(this,void 0),us.set(this,void 0),ps.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,Jt,"f")}async setName(e,t){if(bs.assertTypeWithError(e,"string"),this.name==e)return void bs.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,Zt,"f")}async setTask(t,s){if(e(this,jt,"m",qt).call(this,t),this.task==t)return void bs.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,es,"f")}async setSampleRate(t,s){if(bs.assertTypeWithError(t,"number"),t-=t%5,bs.assertWithError(t>=5,`sampleRate must be multiple of 5 greater than 0 (got ${t})`),e(this,es,"f")==t)return void bs.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){Mt.AssertValidSensorType(e),bs.assertWithError(Ms.includes(e),`invalid tflite sensorType "${e}"`)}get sensorTypes(){return e(this,is,"f").slice()}async setSensorTypes(e,t){e.forEach((e=>{Ds.AssertValidSensorType(e)}));const s=this.waitForEvent("getTfliteSensorTypes");var i;const n=(e=(i=e).filter(((e,t)=>i.indexOf(e)==t))).map((e=>bt.indexOf(e))).sort();bs.log(e,n),this.sendMessage([{type:"setTfliteSensorTypes",data:Uint8Array.from(n).buffer}],t),await s}get isReady(){return e(this,as,"f")}get captureDelay(){return e(this,ls,"f")}async setCaptureDelay(t,s){if(bs.assertTypeWithError(t,"number"),e(this,ls,"f")==t)return void bs.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,us,"f")}async setThreshold(t,s){if(bs.assertTypeWithError(t,"number"),bs.assertWithError(t>=0,`threshold must be positive (got ${t})`),e(this,us,"f")==t)return void bs.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,ps,"f")}async setInferencingEnabled(t,s=!0){if(bs.assertTypeWithError(t,"boolean"),!t&&!this.isReady)return;if(e(this,jt,"m",hs).call(this),e(this,ps,"f")==t)return void bs.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(bs.log({messageType:t}),t){case"getTfliteName":case"setTfliteName":e(this,jt,"m",Qt).call(this,s);break;case"getTfliteTask":case"setTfliteTask":e(this,jt,"m",Xt).call(this,s);break;case"getTfliteSampleRate":case"setTfliteSampleRate":e(this,jt,"m",ts).call(this,s);break;case"getTfliteSensorTypes":case"setTfliteSensorTypes":e(this,jt,"m",ns).call(this,s);break;case"tfliteIsReady":e(this,jt,"m",os).call(this,s);break;case"getTfliteCaptureDelay":case"setTfliteCaptureDelay":e(this,jt,"m",gs).call(this,s);break;case"getTfliteThreshold":case"setTfliteThreshold":e(this,jt,"m",ds).call(this,s);break;case"getTfliteInferencingEnabled":case"setTfliteInferencingEnabled":e(this,jt,"m",vs).call(this,s);break;case"tfliteInference":e(this,jt,"m",ys).call(this,s);break;default:throw Error(`uncaught messageType ${t}`)}}}var ks,Ts,_s,Ws,Is;Jt=new WeakMap,Zt=new WeakMap,es=new WeakMap,is=new WeakMap,as=new WeakMap,ls=new WeakMap,us=new WeakMap,ps=new WeakMap,jt=new WeakSet,qt=function(e){bs.assertEnumWithError(e,Cs)},Gt=function(e){bs.assertWithError(e in Cs,`invalid taskEnum ${e}`)},Ht=function(){return this.eventDispatcher.dispatchEvent},Qt=function(t){bs.log("parseName",t);const s=V.decode(t.buffer);e(this,jt,"m",Kt).call(this,s)},Kt=function(s){bs.log({name:s}),t(this,Jt,s,"f"),e(this,jt,"a",Ht).call(this,"getTfliteName",{tfliteName:s})},Xt=function(t){bs.log("parseTask",t);const s=t.getUint8(0);e(this,jt,"m",Gt).call(this,s);const i=Cs[s];e(this,jt,"m",Yt).call(this,i)},Yt=function(s){bs.log({task:s}),t(this,Zt,s,"f"),e(this,jt,"a",Ht).call(this,"getTfliteTask",{tfliteTask:s})},ts=function(t){bs.log("parseSampleRate",t);const s=t.getUint16(0,!0);e(this,jt,"m",ss).call(this,s)},ss=function(s){bs.log({sampleRate:s}),t(this,es,s,"f"),e(this,jt,"a",Ht).call(this,"getTfliteSampleRate",{tfliteSampleRate:s})},ns=function(t){bs.log("parseSensorTypes",t);const s=[];for(let e=0;e<t.byteLength;e++){const i=t.getUint8(e),n=bt[i];n?s.push(n):bs.error(`invalid sensorTypeEnum ${i}`)}e(this,jt,"m",rs).call(this,s)},rs=function(s){bs.log({sensorTypes:s}),t(this,is,s,"f"),e(this,jt,"a",Ht).call(this,"getTfliteSensorTypes",{tfliteSensorTypes:s})},os=function(t){bs.log("parseIsReady",t);const s=Boolean(t.getUint8(0));e(this,jt,"m",cs).call(this,s)},cs=function(s){bs.log({isReady:s}),t(this,as,s,"f"),e(this,jt,"a",Ht).call(this,"tfliteIsReady",{tfliteIsReady:s})},hs=function(){bs.assertWithError(this.isReady,"tflite is not ready")},gs=function(t){bs.log("parseCaptureDelay",t);const s=t.getUint16(0,!0);e(this,jt,"m",fs).call(this,s)},fs=function(s){bs.log({captureDelay:s}),t(this,ls,s,"f"),e(this,jt,"a",Ht).call(this,"getTfliteCaptureDelay",{tfliteCaptureDelay:s})},ds=function(t){bs.log("parseThreshold",t);const s=t.getFloat32(0,!0);e(this,jt,"m",ms).call(this,s)},ms=function(s){bs.log({threshold:s}),t(this,us,s,"f"),e(this,jt,"a",Ht).call(this,"getTfliteThreshold",{tfliteThreshold:s})},vs=function(t){bs.log("parseInferencingEnabled",t);const s=Boolean(t.getUint8(0));e(this,jt,"m",ws).call(this,s)},ws=function(s){bs.log({inferencingEnabled:s}),t(this,ps,s,"f"),e(this,jt,"a",Ht).call(this,"getTfliteInferencingEnabled",{tfliteInferencingEnabled:s})},ys=function(t){bs.log("parseInference",t);const s=ze(t,0);bs.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)}bs.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)})),bs.log({maxIndex:t,maxValue:e}),n.maxIndex=t,n.maxValue=e}e(this,jt,"a",Ht).call(this,"tfliteInference",{tfliteInference:n})};const Ls=k("DeviceInformationManager",{log:!0}),Us=["manufacturerName","modelNumber","softwareRevision","hardwareRevision","firmwareRevision","pnpId","serialNumber"],Fs=[...Us,"deviceInformation"];class Rs{constructor(){ks.add(this),_s.set(this,{})}get information(){return e(this,_s,"f")}clear(){t(this,_s,{},"f")}parseMessage(t,s){switch(Ls.log({messageType:t}),t){case"manufacturerName":const i=V.decode(s.buffer);Ls.log({manufacturerName:i}),e(this,ks,"m",Is).call(this,{manufacturerName:i});break;case"modelNumber":const n=V.decode(s.buffer);Ls.log({modelNumber:n}),e(this,ks,"m",Is).call(this,{modelNumber:n});break;case"softwareRevision":const r=V.decode(s.buffer);Ls.log({softwareRevision:r}),e(this,ks,"m",Is).call(this,{softwareRevision:r});break;case"hardwareRevision":const a=V.decode(s.buffer);Ls.log({hardwareRevision:a}),e(this,ks,"m",Is).call(this,{hardwareRevision:a});break;case"firmwareRevision":const o=V.decode(s.buffer);Ls.log({firmwareRevision:o}),e(this,ks,"m",Is).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)),Ls.log({pnpId:c}),e(this,ks,"m",Is).call(this,{pnpId:c});break;case"serialNumber":const h=V.decode(s.buffer);Ls.log({serialNumber:h});break;default:throw Error(`uncaught messageType ${t}`)}}}var xs,As,$s,Os,Bs,Ns,Ps,Vs,zs,js,qs,Gs,Hs,Js,Qs,Ks,Zs,Xs;_s=new WeakMap,ks=new WeakSet,Ts=function(){return this.eventDispatcher.dispatchEvent},Ws=function(){return Us.every((t=>t in e(this,_s,"f")))},Is=function(t){Ls.log({partialDeviceInformation:t});Object.keys(t).forEach((s=>{e(this,ks,"a",Ts).call(this,s,{[s]:t[s]})})),Object.assign(e(this,_s,"f"),t),Ls.log({deviceInformation:e(this,_s,"f")}),e(this,ks,"a",Ws)&&(Ls.log("completed deviceInformation"),e(this,ks,"a",Ts).call(this,"deviceInformation",{deviceInformation:this.information}))};const Ys=k("InformationManager",{log:!0}),ei=["leftInsole","rightInsole"],ti=["left","right"],si=2,ii=30,ni=["isCharging","getBatteryCurrent","getMtu","getId","getName","setName","getType","setType","getCurrentTime","setCurrentTime"],ri=ni;class ai{constructor(){xs.add(this),$s.set(this,!1),Bs.set(this,void 0),Ps.set(this,void 0),zs.set(this,""),js.set(this,void 0),Js.set(this,0),Ks.set(this,!1),J(this)}get waitForEvent(){return this.eventDispatcher.waitForEvent}get isCharging(){return e(this,$s,"f")}get batteryCurrent(){return e(this,Bs,"f")}async getBatteryCurrent(){Ys.log("getting battery current...");const e=this.waitForEvent("getBatteryCurrent");this.sendMessage([{type:"getBatteryCurrent"}]),await e}get id(){return e(this,Ps,"f")}get name(){return e(this,zs,"f")}updateName(s){Ys.assertTypeWithError(s,"string"),t(this,zs,s,"f"),Ys.log({updatedName:e(this,zs,"f")}),e(this,xs,"a",As).call(this,"getName",{name:e(this,zs,"f")})}async setName(e){Ys.assertTypeWithError(e,"string"),Ys.assertWithError(e.length>=2,`name must be greater than 2 characters long ("${e}" is ${e.length} characters long)`),Ys.assertWithError(e.length<30,`name must be less than 30 characters long ("${e}" is ${e.length} characters long)`);const t=P.encode(e);Ys.log({setNameData:t});const s=this.waitForEvent("getName");this.sendMessage([{type:"setName",data:t.buffer}]),await s}get type(){return e(this,js,"f")}get typeEnum(){return ei.indexOf(this.type)}updateType(s){e(this,xs,"m",qs).call(this,s),s!=this.type?(t(this,js,s,"f"),Ys.log({updatedType:e(this,js,"f")}),e(this,xs,"a",As).call(this,"getType",{type:e(this,js,"f")})):Ys.log("redundant type assignment")}async setType(t){e(this,xs,"m",qs).call(this,t);const s=ei.indexOf(t);e(this,xs,"m",Hs).call(this,s)}get isInsole(){switch(this.type){case"leftInsole":case"rightInsole":return!0;default:return!1}}get insoleSide(){switch(this.type){case"leftInsole":return"left";case"rightInsole":return"right"}}get mtu(){return e(this,Js,"f")}get isCurrentTimeSet(){return e(this,Ks,"f")}parseMessage(t,s){switch(Ys.log({messageType:t}),t){case"isCharging":const i=Boolean(s.getUint8(0));Ys.log({isCharging:i}),e(this,xs,"m",Os).call(this,i);break;case"getBatteryCurrent":const n=s.getFloat32(0,!0);Ys.log({batteryCurrent:n}),e(this,xs,"m",Ns).call(this,n);break;case"getId":const r=V.decode(s.buffer);Ys.log({id:r}),e(this,xs,"m",Vs).call(this,r);break;case"getName":case"setName":const a=V.decode(s.buffer);Ys.log({name:a}),this.updateName(a);break;case"getType":case"setType":const o=s.getUint8(0),c=ei[o];Ys.log({typeEnum:o,type:c}),this.updateType(c);break;case"getMtu":const h=s.getUint16(0,!0);Ys.log({mtu:h}),e(this,xs,"m",Qs).call(this,h);break;case"getCurrentTime":case"setCurrentTime":const l=Number(s.getBigUint64(0,!0));e(this,xs,"m",Zs).call(this,l);break;default:throw Error(`uncaught messageType ${t}`)}}clear(){t(this,Ks,!1,"f")}}$s=new WeakMap,Bs=new WeakMap,Ps=new WeakMap,zs=new WeakMap,js=new WeakMap,Js=new WeakMap,Ks=new WeakMap,xs=new WeakSet,As=function(){return this.eventDispatcher.dispatchEvent},Os=function(s){Ys.assertTypeWithError(s,"boolean"),t(this,$s,s,"f"),Ys.log({isCharging:e(this,$s,"f")}),e(this,xs,"a",As).call(this,"isCharging",{isCharging:e(this,$s,"f")})},Ns=function(s){Ys.assertTypeWithError(s,"number"),t(this,Bs,s,"f"),Ys.log({batteryCurrent:e(this,Bs,"f")}),e(this,xs,"a",As).call(this,"getBatteryCurrent",{batteryCurrent:e(this,Bs,"f")})},Vs=function(s){Ys.assertTypeWithError(s,"string"),t(this,Ps,s,"f"),Ys.log({id:e(this,Ps,"f")}),e(this,xs,"a",As).call(this,"getId",{id:e(this,Ps,"f")})},qs=function(e){Ys.assertEnumWithError(e,ei)},Gs=function(e){Ys.assertTypeWithError(e,"number"),Ys.assertWithError(e in ei,`invalid typeEnum ${e}`)},Hs=async function(t){e(this,xs,"m",Gs).call(this,t);const s=Uint8Array.from([t]);Ys.log({setTypeData:s});const i=this.waitForEvent("getType");this.sendMessage([{type:"setType",data:s.buffer}]),await i},Qs=function(s){Ys.assertTypeWithError(s,"number"),e(this,Js,"f")!=s?(t(this,Js,s,"f"),e(this,xs,"a",As).call(this,"getMtu",{mtu:e(this,Js,"f")})):Ys.log("redundant mtu assignment",s)},Zs=function(s){Ys.log({currentTime:s}),t(this,Ks,0!=s||Math.abs(Date.now()-s)<Ve,"f"),e(this,Ks,"f")||e(this,xs,"m",Xs).call(this,!1)},Xs=async function(e){Ys.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 oi=["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 ci,hi,li,gi,fi,ui,di,mi,pi,vi,wi,yi,bi,Si,Ei,Ci;const Mi=k("VibrationManager"),Di=["front","rear"],ki=["waveformEffect","waveform"],Ti=8,_i=2550,Wi=1270,Ii=3,Li=20,Ui=6;class Fi{constructor(){ci.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||Di.slice(),s){case"waveformEffect":{const{segments:s,loopCount:i}=t;n=e(this,ci,"m",bi).call(this,r,s,i)}break;case"waveform":{const{segments:s}=t;n=e(this,ci,"m",Si).call(this,r,s)}break;default:throw Error(`invalid vibration type "${s}"`)}Mi.log({type:s,arrayBuffer:n}),i=j(i,n)})),await this.sendMessage([{type:"triggerVibration",data:i}],s)}}var Ri,xi,Ai,$i,Oi,Bi,Ni,Pi,Vi,zi,ji,qi,Gi,Hi,Ji;ci=new WeakSet,hi=function(e){Mi.assertTypeWithError(e,"string"),Mi.assertWithError(Di.includes(e),`invalid location "${e}"`)},li=function(t){e(this,ci,"m",fi).call(this,t),t.forEach((t=>{e(this,ci,"m",hi).call(this,t)}))},gi=function(t){e(this,ci,"m",li).call(this,t);let s=0;return t.forEach((e=>{const t=Di.indexOf(e);s|=1<<t})),Mi.log({locationsBitmask:s}),Mi.assertWithError(s>0,"locationsBitmask must not be zero"),s},fi=function(e){Mi.assertWithError(Array.isArray(e),"passed non-array"),Mi.assertWithError(e.length>0,"passed empty array")},ui=function(e){Mi.assertWithError(oi.includes(e),`invalid waveformEffect "${e}"`)},di=function(t){if(null!=t.effect){const s=t.effect;e(this,ci,"m",ui).call(this,s)}else{if(null==t.delay)throw Error("no effect or delay found in waveformEffectSegment");{const{delay:e}=t;Mi.assertWithError(e>=0,`delay must be 0ms or greater (got ${e})`),Mi.assertWithError(e<=Wi,`delay must be 1270ms or less (got ${e})`)}}if(null!=t.loopCount){const{loopCount:s}=t;e(this,ci,"m",mi).call(this,s)}},mi=function(e){Mi.assertTypeWithError(e,"number"),Mi.assertWithError(e>=0,`waveformEffectSegmentLoopCount must be 0 or greater (got ${e})`),Mi.assertWithError(e<=3,`waveformEffectSegmentLoopCount must be 3 or fewer (got ${e})`)},pi=function(t){e(this,ci,"m",fi).call(this,t),Mi.assertWithError(t.length<=8,`must have 8 waveformEffectSegments or fewer (got ${t.length})`),t.forEach((t=>{e(this,ci,"m",di).call(this,t)}))},vi=function(e){Mi.assertTypeWithError(e,"number"),Mi.assertWithError(e>=0,`waveformEffectSequenceLoopCount must be 0 or greater (got ${e})`),Mi.assertWithError(e<=6,`waveformEffectSequenceLoopCount must be 6 or fewer (got ${e})`)},wi=function(e){Mi.assertTypeWithError(e.amplitude,"number"),Mi.assertWithError(e.amplitude>=0,`amplitude must be 0 or greater (got ${e.amplitude})`),Mi.assertWithError(e.amplitude<=1,`amplitude must be 1 or less (got ${e.amplitude})`),Mi.assertTypeWithError(e.duration,"number"),Mi.assertWithError(e.duration>0,`duration must be greater than 0ms (got ${e.duration}ms)`),Mi.assertWithError(e.duration<=_i,`duration must be 2550ms or less (got ${e.duration}ms)`)},yi=function(t){e(this,ci,"m",fi).call(this,t),Mi.assertWithError(t.length<=20,`must have 20 waveformSegments or fewer (got ${t.length})`),t.forEach((t=>{e(this,ci,"m",wi).call(this,t)}))},bi=function(t,s,i=0){e(this,ci,"m",pi).call(this,s),e(this,ci,"m",vi).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++]=oi.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 Mi.log({dataArray:n,dataView:c}),e(this,ci,"m",Ci).call(this,t,"waveformEffect",c)},Si=function(t,s){e(this,ci,"m",yi).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))})),Mi.log({dataView:i}),e(this,ci,"m",Ci).call(this,t,"waveform",i)},Ei=function(e){Mi.assertTypeWithError(e,"string"),Mi.assertWithError(ki.includes(e),`invalid vibrationType "${e}"`)},Ci=function(t,s,i){Mi.assertWithError(i?.byteLength>0,"no data received");const n=e(this,ci,"m",gi).call(this,t);e(this,ci,"m",Ei).call(this,s);const r=ki.indexOf(s);Mi.log({locationsBitmask:n,vibrationTypeIndex:r,dataView:i});const a=j(n,r,i.byteLength,i);return Mi.log({data:a}),a};const Qi=k("BaseConnectionManager",{log:!0}),Ki=["notConnected","connecting","connected","disconnecting"],Zi=[...Ki,"connectionStatus","isConnected"],Xi=[...ni,...Pt,...Et,"triggerVibration",...Ss,...Re],Yi=["batteryLevel"],en=["rx","tx"],tn=[...Yi,...Us,...en,...Xi,"smp"];class sn{get baseConstructor(){return this.constructor}static get isSupported(){return!1}get isSupported(){return this.baseConstructor.isSupported}get type(){return this.baseConstructor.type}constructor(){Ri.add(this),Oi.set(this,"notConnected"),ji.set(this,[]),qi.set(this,!1),Hi.set(this,new x(e(this,Ri,"m",Ji).bind(this),5e3)),e(this,Ri,"m",$i).call(this)}get status(){return e(this,Oi,"f")}set status(s){Qi.assertEnumWithError(s,Ki),e(this,Oi,"f")!=s?(Qi.log(`new connection status "${s}"`),t(this,Oi,s,"f"),this.onStatusUpdated(this.status),this.isConnected?e(this,Hi,"f").start():e(this,Hi,"f").stop(),"notConnected"==e(this,Oi,"f")&&(this.mtu=void 0)):Qi.log(`tried to assign same connection status "${s}"`)}get isConnected(){return"connected"==this.status}async connect(){e(this,Ri,"m",Bi).call(this),e(this,Ri,"m",Ni).call(this),this.status="connecting"}get canReconnect(){return!1}async reconnect(){e(this,Ri,"m",Bi).call(this),e(this,Ri,"m",Ni).call(this),Qi.assert(this.canReconnect,"unable to reconnect")}async disconnect(){e(this,Ri,"m",Pi).call(this),e(this,Ri,"m",Vi).call(this),this.status="disconnecting",Qi.log("disconnecting from device...")}async sendSmpMessage(t){e(this,Ri,"m",zi).call(this),Qi.log("sending smp message",t)}async sendTxMessages(s,i=!0){if(e(this,Ri,"m",zi).call(this),s&&(e(this,ji,"f").push(...s),Qi.log(`appended ${s.length} messages`)),!i)return void Qi.log("not sending immediately - waiting until later");if(e(this,qi,"f"))return void console.log("already sending messages - waiting until later");t(this,qi,!0,"f"),Qi.log("sendTxMessages",e(this,ji,"f").slice());const n=e(this,ji,"f").map((t=>{e(xi,xi,"m",Ai).call(xi,t.type);const s=Xi.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,ji,"f").length=0,this.mtu)for(;n.length>0;){let e=0,t=0;n.some((s=>{if(e+s.byteLength>this.mtu-3)return!0;t++,e+=s.byteLength}));const s=n.splice(0,t);Qi.log({arrayBufferCount:t,arrayBuffersToSend:s});const i=j(...s);Qi.log("sending arrayBuffer",i),await this.sendTxData(i)}else{const e=j(...n);Qi.log("sending arrayBuffer",e),await this.sendTxData(e)}t(this,qi,!1,"f")}async sendTxData(e){Qi.log("sendTxData",e)}parseRxMessage(t){vt(t,Xi,e(this,Ri,"m",Gi).bind(this),null,!0),this.onMessagesReceived()}clear(){t(this,qi,!1,"f"),e(this,ji,"f").length=0}}xi=sn,Oi=new WeakMap,ji=new WeakMap,qi=new WeakMap,Hi=new WeakMap,Ri=new WeakSet,Ai=function(e){Qi.assertEnumWithError(e,Xi)},$i=function(){Qi.assertWithError(this.isSupported,`${this.constructor.name} is not supported`)},Bi=function(){Qi.assertWithError(!this.isConnected,"device is already connected")},Ni=function(){Qi.assertWithError("connecting"!=this.status,"device is already connecting")},Pi=function(){Qi.assertWithError(this.isConnected,"device is not connected")},Vi=function(){Qi.assertWithError("disconnecting"!=this.status,"device is already disconnecting")},zi=function(){e(this,Ri,"m",Pi).call(this),e(this,Ri,"m",Vi).call(this)},Gi=function(e,t){Qi.log({messageType:e,dataView:t}),this.onMessageReceived(e,t)},Ji=function(){this.isConnected||(Qi.log("timer detected disconnection"),this.status="notConnected")};const nn=k("EventUtils",{log:!1});function rn(e,t){let s=e.addEventListener||e.addListener||e.on||e.AddEventListener;nn.assertWithError(s,"no add listener function found for target"),s=s.bind(e),Object.entries(t).forEach((([e,t])=>{s(e,t)}))}function an(e,t){let s=e.removeEventListener||e.removeListener||e.RemoveEventListener;nn.assertWithError(s,"no remove listener function found for target"),s=s.bind(e),Object.entries(t).forEach((([e,t])=>{s(e,t)}))}const on=k("bluetoothUUIDs",{log:!1});if(i)var cn=window.BluetoothUUID;function hn(e){return on.assertTypeWithError(e,"string"),on.assertWithError(4==e.length,"value must be 4 characters long"),`ea6da725-${e}-4f9b-893d-c3913e33b39f`}function ln(e){return cn?.getCharacteristic?.(e)}function gn(e){return cn?.getService?.(e)}const fn=Object.freeze({services:{deviceInformation:{uuid:gn("device_information"),characteristics:{manufacturerName:{uuid:ln("manufacturer_name_string")},modelNumber:{uuid:ln("model_number_string")},hardwareRevision:{uuid:ln("hardware_revision_string")},firmwareRevision:{uuid:ln("firmware_revision_string")},softwareRevision:{uuid:ln("software_revision_string")},pnpId:{uuid:ln("pnp_id")},serialNumber:{uuid:ln("serial_number_string")}}},battery:{uuid:gn("battery_service"),characteristics:{batteryLevel:{uuid:ln("battery_level")}}},main:{uuid:hn("0000"),characteristics:{rx:{uuid:hn("1000")},tx:{uuid:hn("1001")}}},smp:{uuid:"8d53dc1d-1db7-4cd3-868b-8a527460aa84",characteristics:{smp:{uuid:"da2e7828-fbce-4e01-ae9e-261174997c48"}}}}}),un=[fn.services.main.uuid],dn=[fn.services.deviceInformation.uuid,fn.services.battery.uuid,fn.services.smp.uuid];function mn(e){e=e.toString().toLowerCase();return Object.keys(fn.services).find((t=>{let s=fn.services[t].uuid.toString();return 4==e.length&&(s=s.slice(4,8)),e.includes("-")||(s=s.replaceAll("-","")),e==s}))}const pn=[],vn=[];function wn(e){var t;return e=e.toString().toLowerCase(),Object.values(fn.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 yn(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(fn.services).forEach((e=>{if(!e.characteristics)return;const t=Object.keys(e.characteristics);t.forEach((s=>{const i=e.characteristics[s];un.includes(e.uuid)&&(pn.push(i.uuid),t.push(s)),vn.push(i.uuid)}))}),[]);const bn=k("BluetoothConnectionManager",{log:!0});class Sn extends sn{constructor(){super(...arguments),this.isInRange=!0}onCharacteristicValueChanged(e,t){"rx"==e?this.parseRxMessage(t):this.onMessageReceived?.(e,t)}async writeCharacteristic(e,t){bn.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 En,Cn,Mn,Dn,kn,Tn,_n,Wn,In,Ln,Un;const Fn=k("WebBluetoothConnectionManager",{log:!0});var Rn;i&&(Rn=window.navigator.bluetooth);class xn extends Sn{constructor(){super(...arguments),En.add(this),Cn.set(this,{characteristicvaluechanged:e(this,En,"m",In).bind(this)}),Mn.set(this,{gattserverdisconnected:e(this,En,"m",Un).bind(this)}),Dn.set(this,void 0),kn.set(this,new Map),Tn.set(this,new Map)}get bluetoothId(){return this.device.id}static get isSupported(){return Boolean(Rn)}static get type(){return"webBluetooth"}get device(){return e(this,Dn,"f")}set device(s){e(this,Dn,"f")!=s?(e(this,Dn,"f")&&an(e(this,Dn,"f"),e(this,Mn,"f")),s&&rn(s,e(this,Mn,"f")),t(this,Dn,s,"f")):Fn.log("tried to assign the same BluetoothDevice")}get server(){return e(this,Dn,"f")?.gatt}get isConnected(){return this.server?.connected||!1}async connect(){await super.connect();try{const t=await Rn.requestDevice({filters:[{services:un}],optionalServices:i?dn:[]});Fn.log("got BluetoothDevice"),this.device=t,Fn.log("connecting to device...");const s=await this.server.connect();Fn.log(`connected to device? ${s.connected}`),await e(this,En,"m",_n).call(this),Fn.log("fully connected"),this.status="connected"}catch(t){Fn.error(t),this.status="notConnected",this.server?.disconnect(),e(this,En,"m",Wn).call(this)}}async disconnect(){await e(this,En,"m",Wn).call(this),await super.disconnect(),this.server?.disconnect(),this.status="notConnected"}async writeCharacteristic(t,s){super.writeCharacteristic(t,s);const i=e(this,Tn,"f").get(t);Fn.assertWithError(i,`${t} characteristic not found`),Fn.log("writing characteristic",i,s);const n=i.properties||yn(t);n.writeWithoutResponse?(Fn.log("writing without response"),await i.writeValueWithoutResponse(s)):(Fn.log("writing with response"),await i.writeValueWithResponse(s)),Fn.log("wrote characteristic"),n.read&&!n.notify&&(Fn.log("reading value after write..."),await i.readValue(),(o||c)&&e(this,En,"m",Ln).call(this,i))}get canReconnect(){return Boolean(this.server&&!this.server.connected&&this.isInRange)}async reconnect(){await super.reconnect(),Fn.log("attempting to reconnect..."),this.status="connecting";try{await this.server.connect()}catch(e){Fn.error(e),this.isInRange=!1}this.isConnected?(Fn.log("successfully reconnected!"),await e(this,En,"m",_n).call(this),this.status="connected"):(Fn.log("unable to reconnect"),this.status="notConnected")}}Cn=new WeakMap,Mn=new WeakMap,Dn=new WeakMap,kn=new WeakMap,Tn=new WeakMap,En=new WeakSet,_n=async function(){e(this,En,"m",Wn).call(this),Fn.log("getting services...");const t=await this.server.getPrimaryServices();Fn.log("got services",t.length),Fn.log("getting characteristics...");for(const s in t){const i=t[s];Fn.log({service:i});const n=mn(i.uuid);Fn.assertWithError(n,`no name found for service uuid "${i.uuid}"`),Fn.log(`got "${n}" service`),i.name=n,e(this,kn,"f").set(n,i),Fn.log(`getting characteristics for "${n}" service`);const r=await i.getCharacteristics();Fn.log(`got characteristics for "${n}" service`);for(const t in r){const s=r[t];Fn.log({characteristic:s});const i=wn(s.uuid);Fn.assertWithError(Boolean(i),`no name found for characteristic uuid "${s.uuid}" in "${n}" service`),Fn.log(`got "${i}" characteristic in "${n}" service`),s.name=i,e(this,Tn,"f").set(i,s),rn(s,e(this,Cn,"f"));const a=s.properties||yn(i);a.notify&&(Fn.log(`starting notifications for "${i}" characteristic`),await s.startNotifications()),a.read&&(Fn.log(`reading "${i}" characteristic...`),await s.readValue(),(o||c)&&e(this,En,"m",Ln).call(this,s))}}},Wn=async function(){this.device&&an(this.device,e(this,Mn,"f"));const t=Array.from(e(this,Tn,"f").keys()).map((t=>{const s=e(this,Tn,"f").get(t);an(s,e(this,Cn,"f"));if((s.properties||yn(t)).notify)return Fn.log(`stopping notifications for "${t}" characteristic`),s.stopNotifications()}));return Promise.allSettled(t)},In=function(t){Fn.log("oncharacteristicvaluechanged");const s=t.target;e(this,En,"m",Ln).call(this,s)},Ln=function(e){Fn.log("onCharacteristicValue");const t=e.name;Fn.assertWithError(Boolean(t),`no name found for characteristic with uuid "${e.uuid}"`),Fn.log(`oncharacteristicvaluechanged for "${t}" characteristic`);const s=e.value;Fn.assertWithError(s,`no data found for "${t}" characteristic`),Fn.log(`data for "${t}" characteristic`,Array.from(new Uint8Array(s.buffer)));try{this.onCharacteristicValueChanged(t,s)}catch(e){Fn.error(e)}},Un=function(){Fn.log("gattserverdisconnected"),this.status="notConnected"};const An=4294967296,$n=9007199254740992;const On={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%An,s=(e-t)/An,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<=$n)return h(0,t);if(-$n<=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()*An+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}},Bn=k("mcumgr",{log:!0}),Nn=0,Pn=1,Vn=2,zn=3,jn=0,qn=1,Gn=8,Hn=0,Jn=2,Qn=3,Kn=5,Zn=0,Xn=1,Yn=5,er=0;class tr{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(On.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){Bn.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=On.decode(e.slice(8).buffer),c=256*s+i,h=256*n+r;return Bn.log("mcumgr - Process Message - Group: "+h+", Id: "+a+", Off: "+o.off),h===qn&&a===Xn&&o.off?(this._uploadOffset=o.off,void this._uploadNext()):t===zn&&h===Gn&&a===er&&o.off?(this._uploadFileOffset=o.off,void this._uploadFileNext()):t===Pn&&h===Gn&&a===er?(this._downloadFileOffset+=o.data.length,null!=o.len&&(this._downloadFileLength=o.len),Bn.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(Vn,jn,Kn)}smpEcho(e){return this._getMessage(Vn,jn,Hn,{d:e})}cmdImageState(){return this._getMessage(Nn,qn,Zn)}cmdImageErase(){return this._getMessage(Vn,qn,Yn,{})}cmdImageTest(e){return this._getMessage(Vn,qn,Zn,{hash:e,confirm:!1})}cmdImageConfirm(e){return this._getMessage(Vn,qn,Zn,{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-On.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(Vn,qn,Xn,e);Bn.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?Bn.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?Bn.error("Upload is already in progress."):(this._uploadIsInProgress=!0,this._uploadFileOffset=0,this._uploadFile=e,this._uploadFilename=t,this._uploadFileNext())}async _uploadFileNext(){if(Bn.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-On.encode(e).byteLength-8;e.data=new Uint8Array(this._uploadFile.slice(this._uploadFileOffset,this._uploadFileOffset+t)),this._uploadFileOffset+=t;const s=this._getMessage(Vn,Gn,er,e);Bn.log("mcumgr - _uploadNext: Message Length: "+s.length),this._fileUploadNextCallback({packet:s})}async cmdDownloadFile(e,t){this._downloadIsInProgress?Bn.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(Nn,Gn,er,e);Bn.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 sr,ir,nr,rr,ar,or,cr,hr,lr,gr,fr,ur,dr,mr,pr,vr,wr,yr,br,Sr,Er;const Cr=k("FirmwareManager",{log:!0}),Mr=["smp"],Dr=[...Mr,"firmwareImages","firmwareUploadProgress","firmwareStatus","firmwareUploadComplete"],kr=["idle","uploading","uploaded","pending","testing","erasing"];class Tr{constructor(){sr.add(this),nr.set(this,"idle"),ar.set(this,void 0),hr.set(this,void 0),lr.set(this,new tr),e(this,sr,"m",gr).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(Cr.log({messageType:t}),"smp"!==t)throw Error(`uncaught messageType ${t}`);e(this,lr,"f")._notification(Array.from(new Uint8Array(s.buffer))),e(this,sr,"a",ir).call(this,"smp",{dataView:s})}async uploadFirmware(t){Cr.log("uploadFirmware",t);const s=this.waitForEvent("firmwareUploadComplete");await this.getImages();const i=await H(t),n=await e(this,lr,"f").imageInfo(i);Cr.log({imageInfo:n}),e(this,lr,"f").cmdUpload(i,1),e(this,sr,"m",rr).call(this,"uploading"),await s}get status(){return e(this,nr,"f")}get images(){return e(this,ar,"f")}async getImages(){const t=this.waitForEvent("firmwareImages");Cr.log("getting firmware image state..."),this.sendMessage(Uint8Array.from(e(this,lr,"f").cmdImageState()).buffer),await t}async testImage(t=1){if(e(this,sr,"m",cr).call(this,t),e(this,sr,"m",or).call(this),!e(this,ar,"f")[t])return void Cr.log(`image ${t} not found`);if(1==e(this,ar,"f")[t].pending)return void Cr.log(`image ${t} is already pending`);if(e(this,ar,"f")[t].empty)return void Cr.log(`image ${t} is empty`);const s=this.waitForEvent("smp");Cr.log("testing firmware image..."),this.sendMessage(Uint8Array.from(e(this,lr,"f").cmdImageTest(e(this,ar,"f")[t].hash)).buffer),await s}async eraseImage(){e(this,sr,"m",or).call(this);const t=this.waitForEvent("smp");Cr.log("erasing image..."),this.sendMessage(Uint8Array.from(e(this,lr,"f").cmdImageErase()).buffer),e(this,sr,"m",rr).call(this,"erasing"),await t,await this.getImages()}async confirmImage(t=0){if(e(this,sr,"m",cr).call(this,t),e(this,sr,"m",or).call(this),!0===e(this,ar,"f")[t].confirmed)return void Cr.log(`image ${t} is already confirmed`);const s=this.waitForEvent("smp");Cr.log("confirming image..."),this.sendMessage(Uint8Array.from(e(this,lr,"f").cmdImageConfirm(e(this,ar,"f")[t].hash)).buffer),await s}async echo(t){Cr.assertTypeWithError(t,"string");const s=this.waitForEvent("smp");Cr.log("sending echo..."),this.sendMessage(Uint8Array.from(e(this,lr,"f").smpEcho(t)).buffer),await s}async reset(){const t=this.waitForEvent("smp");Cr.log("resetting..."),this.sendMessage(Uint8Array.from(e(this,lr,"f").cmdReset()).buffer),await t}get mtu(){return e(this,hr,"f")}set mtu(s){t(this,hr,s,"f"),e(this,lr,"f")._mtu=s}}var _r,Wr,Ir,Lr,Ur,Fr,Rr,xr,Ar,$r,Or,Br,Nr,Pr,Vr,zr,jr,qr;nr=new WeakMap,ar=new WeakMap,hr=new WeakMap,lr=new WeakMap,sr=new WeakSet,ir=function(){return this.eventDispatcher.dispatchEvent},rr=function(s){Cr.assertEnumWithError(s,kr),e(this,nr,"f")!=s?(t(this,nr,s,"f"),Cr.log({firmwareStatus:e(this,nr,"f")}),e(this,sr,"a",ir).call(this,"firmwareStatus",{firmwareStatus:e(this,nr,"f")})):Cr.log(`redundant firmwareStatus assignment "${s}"`)},or=function(){Cr.assertWithError(e(this,ar,"f"),"didn't get imageState")},cr=function(e){Cr.assertTypeWithError(e,"number"),Cr.assertWithError(0==e||1==e,"imageIndex must be 0 or 1")},gr=function(){e(this,lr,"f").onMessage(e(this,sr,"m",fr).bind(this)),e(this,lr,"f").onFileDownloadNext(e(this,sr,"m",ur)),e(this,lr,"f").onFileDownloadProgress(e(this,sr,"m",dr).bind(this)),e(this,lr,"f").onFileDownloadFinished(e(this,sr,"m",mr).bind(this)),e(this,lr,"f").onFileUploadNext(e(this,sr,"m",pr).bind(this)),e(this,lr,"f").onFileUploadProgress(e(this,sr,"m",vr).bind(this)),e(this,lr,"f").onFileUploadFinished(e(this,sr,"m",wr).bind(this)),e(this,lr,"f").onImageUploadNext(e(this,sr,"m",yr).bind(this)),e(this,lr,"f").onImageUploadProgress(e(this,sr,"m",br).bind(this)),e(this,lr,"f").onImageUploadFinished(e(this,sr,"m",Sr).bind(this))},fr=function({op:t,group:s,id:i,data:n,length:r}){switch(Cr.log("onMcuMessage",...arguments),s){case jn:switch(i){case Hn:Cr.log(`echo "${n.r}"`);break;case Jn:Cr.table(n.tasks);break;case Qn:Cr.log(n)}break;case qn:if(i===Zn)e(this,sr,"m",Er).call(this,n);break;default:throw Error(`uncaught mcuMessage group ${s}`)}},ur=function(){Cr.log("onMcuFileDownloadNext",...arguments)},dr=function(){Cr.log("onMcuFileDownloadProgress",...arguments)},mr=function(){Cr.log("onMcuFileDownloadFinished",...arguments)},pr=function(){Cr.log("onMcuFileUploadNext")},vr=function(){Cr.log("onMcuFileUploadProgress")},wr=function(){Cr.log("onMcuFileUploadFinished")},yr=function({packet:e}){Cr.log("onMcuImageUploadNext"),this.sendMessage(Uint8Array.from(e).buffer)},br=function({percentage:t}){const s=t/100;Cr.log("onMcuImageUploadProgress",...arguments),e(this,sr,"a",ir).call(this,"firmwareUploadProgress",{progress:s})},Sr=async function(){Cr.log("onMcuImageUploadFinished",...arguments),await this.getImages(),e(this,sr,"a",ir).call(this,"firmwareUploadProgress",{progress:100}),e(this,sr,"a",ir).call(this,"firmwareUploadComplete",{})},Er=function({images:s}){if(!s)return void Cr.log("no images found");t(this,ar,s,"f"),Cr.log("images",e(this,ar,"f"));let i="idle";2==e(this,ar,"f").length&&(e(this,ar,"f")[1].bootable?e(this,ar,"f")[0].confirmed?e(this,ar,"f")[1].pending?(Cr.log("reset to upload to the new firmware image"),i="pending"):(Cr.log("Slot 1 has a valid image. run testImage() to test it or upload a different image."),i="uploaded"):(Cr.log('Slot 0 has a valid image. Click "Confirm Image" to confirm it or wait and the device will swap images back.'),i="testing"):Cr.warn('Slot 1 has a invalid image. Click "Erase Image" to erase it or upload a different image')),1==e(this,ar,"f").length&&(e(this,ar,"f").push({slot:1,empty:!0,version:"Empty",pending:!1,confirmed:!1,bootable:!1,active:!1,permanent:!1}),Cr.log("Select a firmware upload image to upload to slot 1.")),e(this,sr,"m",rr).call(this,i),e(this,sr,"a",ir).call(this,"firmwareImages",{firmwareImages:e(this,ar,"f")})};const Gr=k("DeviceManager",{log:!0}),Hr=["deviceConnected","deviceDisconnected","deviceIsConnected","availableDevices","connectedDevices"];class Jr{constructor(){if(_r.add(this),Wr.set(this,{getType:e(this,_r,"m",Ir).bind(this),isConnected:e(this,_r,"m",zr).bind(this)}),Lr.set(this,[]),Ur.set(this,!1),Fr.set(this,{devices:[]}),Rr.set(this,void 0),Ar.set(this,"BS.Device"),Nr.set(this,[]),Pr.set(this,new I(this,Hr)),Jr.shared&&this!=Jr.shared)throw Error("DeviceManager is a singleton - use DeviceManager.shared");this.CanUseLocalStorage&&(this.UseLocalStorage=!0)}onDevice(t){rn(t,e(this,Wr,"f"))}OnDeviceConnectionStatusUpdated(t,s){if("notConnected"==s&&!t.canReconnect&&e(this,Nr,"f").includes(t)){const s=e(this,Nr,"f").indexOf(t);this.AvailableDevices.splice(s,1),e(this,_r,"m",jr).call(this)}}get ConnectedDevices(){return e(this,Lr,"f")}get UseLocalStorage(){return e(this,Ur,"f")}set UseLocalStorage(s){e(this,_r,"m",xr).call(this),Gr.assertTypeWithError(s,"boolean"),t(this,Ur,s,"f"),e(this,Ur,"f")&&!e(this,Rr,"f")&&e(this,_r,"m",Or).call(this)}get CanUseLocalStorage(){return i&&window.localStorage}get AvailableDevices(){return e(this,Nr,"f")}get CanGetDevices(){return i&&navigator.bluetooth?.getDevices}async GetDevices(){if(!i)return void Gr.warn("GetDevices is only available in the browser");if(!navigator.bluetooth)return void Gr.warn("bluetooth is not available in this browser");if(o)return void Gr.warn("bluefy lists too many devices...");if(!navigator.bluetooth.getDevices)return void Gr.warn("bluetooth.getDevices() is not available in this browser");if(!this.CanGetDevices)return void Gr.log("CanGetDevices is false");e(this,Rr,"f")||e(this,_r,"m",Or).call(this);const t=e(this,Rr,"f");if(!t.devices||0==t.devices.length)return void Gr.log("no devices found in configuration");const s=await navigator.bluetooth.getDevices();return Gr.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,Nr,"f").indexOf(r)]=n));if(n)return void this.AvailableDevices.push(n);const a=new Fa,o=new xn;o.device=s,s.name&&a._informationManager.updateName(s.name),a._informationManager.updateType(i.type),a.connectionManager=o,this.AvailableDevices.push(a)})),e(this,_r,"m",jr).call(this),this.AvailableDevices}get AddEventListener(){return e(this,Pr,"f").addEventListener}get RemoveEventListener(){return e(this,Pr,"f").removeEventListener}get RemoveEventListeners(){return e(this,Pr,"f").removeEventListeners}get RemoveAllEventListeners(){return e(this,Pr,"f").removeAllEventListeners}}Wr=new WeakMap,Lr=new WeakMap,Ur=new WeakMap,Fr=new WeakMap,Rr=new WeakMap,Ar=new WeakMap,Nr=new WeakMap,Pr=new WeakMap,_r=new WeakSet,Ir=function(t){e(this,Ur,"f")&&e(this,_r,"m",Br).call(this,t.target)},xr=function(){Gr.assertWithError(i,"localStorage is only available in the browser"),Gr.assertWithError(window.localStorage,"localStorage not found")},$r=function(){e(this,_r,"m",xr).call(this),localStorage.setItem(e(this,Ar,"f"),JSON.stringify(e(this,Rr,"f")))},Or=async function(){e(this,_r,"m",xr).call(this);let s=localStorage.getItem(e(this,Ar,"f"));if("string"!=typeof s)return Gr.log("no info found in localStorage"),t(this,Rr,Object.assign({},e(this,Fr,"f")),"f"),void e(this,_r,"m",$r).call(this);try{const e=JSON.parse(s);Gr.log({configuration:e}),t(this,Rr,e,"f"),this.CanGetDevices&&await this.GetDevices()}catch(e){Gr.error(e)}},Br=function(t){if("webBluetooth"!=t.connectionType)return void Gr.log("localStorage is only for webBluetooth devices");e(this,_r,"m",xr).call(this);const s=e(this,Rr,"f").devices.findIndex((e=>e.bluetoothId==t.bluetoothId));-1!=s&&(e(this,Rr,"f").devices[s].type=t.type,e(this,_r,"m",$r).call(this))},Vr=function(){return e(this,Pr,"f").dispatchEvent},zr=function(t){const{target:s}=t;if(s.isConnected)if(e(this,Lr,"f").includes(s))Gr.log("device already included");else{if(Gr.log("adding device",s),e(this,Lr,"f").push(s),this.UseLocalStorage&&"webBluetooth"==s.connectionType){const t={type:s.type,bluetoothId:s.bluetoothId},i=e(this,Rr,"f").devices.findIndex((e=>e.bluetoothId==t.bluetoothId));-1==i?e(this,Rr,"f").devices.push(t):e(this,Rr,"f").devices[i]=t,e(this,_r,"m",$r).call(this)}e(this,_r,"a",Vr).call(this,"deviceConnected",{device:s}),e(this,_r,"a",Vr).call(this,"deviceIsConnected",{device:s}),e(this,_r,"m",qr).call(this)}else e(this,Lr,"f").includes(s)?(Gr.log("removing device",s),e(this,Lr,"f").splice(e(this,Lr,"f").indexOf(s),1),e(this,_r,"a",Vr).call(this,"deviceDisconnected",{device:s}),e(this,_r,"a",Vr).call(this,"deviceIsConnected",{device:s}),e(this,_r,"m",qr).call(this)):Gr.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));Gr.log({existingAvailableDevice:t}),t?this.AvailableDevices[this.AvailableDevices.indexOf(t)]=s:this.AvailableDevices.push(s),e(this,_r,"m",jr).call(this)}},jr=function(){Gr.log({AvailableDevices:this.AvailableDevices}),e(this,_r,"a",Vr).call(this,"availableDevices",{availableDevices:this.AvailableDevices})},qr=function(){Gr.log({ConnectedDevices:this.ConnectedDevices}),e(this,_r,"a",Vr).call(this,"connectedDevices",{connectedDevices:this.ConnectedDevices})},Jr.shared=new Jr;var Qr,Kr,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,Ca,Ma,Da,ka,Ta,_a,Wa=Jr.shared;const Ia=k("Device",{log:!0}),La=["connectionMessage",...Zi,...en,...Yi,...ri,...Fs,...Vt,...Ct,...Be,...Es,...Dr],Ua=["isCharging","getBatteryCurrent","getId","getMtu","getName","getType","getCurrentTime","getSensorConfiguration","getSensorScalars","getPressurePositions","maxFileLength","getFileLength","getFileChecksum","getFileType","fileTransferStatus","getTfliteName","getTfliteTask","getTfliteSampleRate","getTfliteSensorTypes","tfliteIsReady","getTfliteCaptureDelay","getTfliteThreshold","getTfliteInferencingEnabled"];class Fa{get bluetoothId(){return e(this,ea,"f")?.bluetoothId}constructor(){Qr.add(this),Xr.set(this,new I(this,La)),ea.set(this,void 0),this.sendTxMessages=e(this,Qr,"m",ta).bind(this),sa.set(this,!1),ca.set(this,Kr.ReconnectOnDisconnection),ha.set(this,void 0),this.latestConnectionMessage=new Map,pa.set(this,new Rs),va.set(this,0),this._informationManager=new ai,ya.set(this,new zt),Sa.set(this,Kr.ClearSensorConfigurationOnLeave),Ea.set(this,new Mt),Ca.set(this,new Fi),Ma.set(this,new Ne),Da.set(this,new Ds),ka.set(this,new Tr),this.sendSmpMessage=e(this,Qr,"m",Ta).bind(this),_a.set(this,!1),e(this,pa,"f").eventDispatcher=e(this,Xr,"f"),this._informationManager.sendMessage=this.sendTxMessages,this._informationManager.eventDispatcher=e(this,Xr,"f"),e(this,ya,"f").sendMessage=this.sendTxMessages,e(this,ya,"f").eventDispatcher=e(this,Xr,"f"),e(this,Ea,"f").eventDispatcher=e(this,Xr,"f"),e(this,Ca,"f").sendMessage=this.sendTxMessages,e(this,Da,"f").sendMessage=this.sendTxMessages,e(this,Da,"f").eventDispatcher=e(this,Xr,"f"),e(this,Ma,"f").sendMessage=this.sendTxMessages,e(this,Ma,"f").eventDispatcher=e(this,Xr,"f"),e(this,ka,"f").sendMessage=this.sendSmpMessage,e(this,ka,"f").eventDispatcher=e(this,Xr,"f"),this.addEventListener("getMtu",(()=>{e(this,ka,"f").mtu=this.mtu,e(this,Ma,"f").mtu=this.mtu,this.connectionManager.mtu=this.mtu})),Wa.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,Xr,"f").addEventListener}get removeEventListener(){return e(this,Xr,"f").removeEventListener}get waitForEvent(){return e(this,Xr,"f").waitForEvent}get removeEventListeners(){return e(this,Xr,"f").removeEventListeners}get removeAllEventListeners(){return e(this,Xr,"f").removeAllEventListeners}get connectionManager(){return e(this,ea,"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,Qr,"m",la).bind(this),s.onMessageReceived=e(this,Qr,"m",da).bind(this),s.onMessagesReceived=e(this,Qr,"m",ma).bind(this)),t(this,ea,s,"f"),Ia.log("assigned new connectionManager",e(this,ea,"f"))):Ia.log("same connectionManager is already assigned")}async connect(){return this.connectionManager||(this.connectionManager=e(Kr,Kr,"m",Zr).call(Kr)),e(this,Qr,"m",ua).call(this),this.connectionManager.connect()}get isConnected(){return e(this,sa,"f")}get canReconnect(){return this.connectionManager?.canReconnect}async reconnect(){return e(this,Qr,"m",aa).call(this),e(this,Qr,"m",ua).call(this),this.connectionManager?.reconnect()}static async Connect(){const e=new Kr;return await e.connect(),e}static get ReconnectOnDisconnection(){return e(this,Kr,"f",oa)}static set ReconnectOnDisconnection(e){Ia.assertTypeWithError(e,"boolean"),t(this,Kr,e,"f",oa)}get reconnectOnDisconnection(){return e(this,ca,"f")}set reconnectOnDisconnection(e){Ia.assertTypeWithError(e,"boolean"),t(this,ca,e,"f")}get connectionType(){return this.connectionManager?.type}async disconnect(){return e(this,Qr,"m",ia).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,ea,"f")?.status){case"connected":return this.isConnected?"connected":"connecting";case"notConnected":case"connecting":case"disconnecting":return e(this,ea,"f").status;default:return"notConnected"}}get isConnectionBusy(){return"connecting"==this.connectionStatus||"disconnecting"==this.connectionStatus}get deviceInformation(){return e(this,pa,"f").information}get batteryLevel(){return e(this,va,"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 insoleSide(){return this._informationManager.insoleSide}get mtu(){return this._informationManager.mtu}get sensorTypes(){return Object.keys(this.sensorConfiguration)}get continuousSensorTypes(){return St.filter((e=>this.sensorTypes.includes(e)))}get sensorConfiguration(){return e(this,ya,"f").configuration}async setSensorConfiguration(t,s){await e(this,ya,"f").setConfiguration(t,s)}async clearSensorConfiguration(){return e(this,ya,"f").clearSensorConfiguration()}static get ClearSensorConfigurationOnLeave(){return e(this,Kr,"f",ba)}static set ClearSensorConfigurationOnLeave(e){Ia.assertTypeWithError(e,"boolean"),t(this,Kr,e,"f",ba)}get clearSensorConfigurationOnLeave(){return e(this,Sa,"f")}set clearSensorConfigurationOnLeave(e){Ia.assertTypeWithError(e,"boolean"),t(this,Sa,e,"f")}get numberOfPressureSensors(){return e(this,Ea,"f").pressureSensorDataManager.numberOfSensors}resetPressureRange(){e(this,Ea,"f").pressureSensorDataManager.resetRange()}async triggerVibration(t,s){e(this,Ca,"f").triggerVibration(t,s)}get maxFileLength(){return e(this,Ma,"f").maxLength}async sendFile(t,s){const i=this.waitForEvent("fileTransferComplete");e(this,Ma,"f").send(t,s),await i}async receiveFile(t){const s=this.waitForEvent("fileTransferComplete");e(this,Ma,"f").receive(t),await s}get fileTransferStatus(){return e(this,Ma,"f").status}cancelFileTransfer(){e(this,Ma,"f").cancel()}get tfliteName(){return e(this,Da,"f").name}get setTfliteName(){return e(this,Da,"f").setName}get tfliteTask(){return e(this,Da,"f").task}get setTfliteTask(){return e(this,Da,"f").setTask}get tfliteSampleRate(){return e(this,Da,"f").sampleRate}get setTfliteSampleRate(){return e(this,Da,"f").setSampleRate}get tfliteSensorTypes(){return e(this,Da,"f").sensorTypes}get allowedTfliteSensorTypes(){return this.sensorTypes.filter((e=>Ms.includes(e)))}get setTfliteSensorTypes(){return e(this,Da,"f").setSensorTypes}get tfliteIsReady(){return e(this,Da,"f").isReady}get tfliteInferencingEnabled(){return e(this,Da,"f").inferencingEnabled}get setTfliteInferencingEnabled(){return e(this,Da,"f").setInferencingEnabled}async enableTfliteInferencing(){return this.setTfliteInferencingEnabled(!0)}async disableTfliteInferencing(){return this.setTfliteInferencingEnabled(!1)}get toggleTfliteInferencing(){return e(this,Da,"f").toggleInferencingEnabled}get tfliteCaptureDelay(){return e(this,Da,"f").captureDelay}get setTfliteCaptureDelay(){return e(this,Da,"f").setCaptureDelay}get tfliteThreshold(){return e(this,Da,"f").threshold}get setTfliteThreshold(){return e(this,Da,"f").setThreshold}get uploadFirmware(){return e(this,ka,"f").uploadFirmware}async reset(){return await e(this,ka,"f").reset(),e(this,ea,"f").disconnect()}get firmwareStatus(){return e(this,ka,"f").status}get getFirmwareImages(){return e(this,ka,"f").getImages}get firmwareImages(){return e(this,ka,"f").images}get eraseFirmwareImage(){return e(this,ka,"f").eraseImage}get confirmFirmwareImage(){return e(this,ka,"f").confirmImage}get testFirmwareImage(){return e(this,ka,"f").testImage}get isServerSide(){return e(this,_a,"f")}set isServerSide(s){e(this,_a,"f")!=s?(Ia.log({newIsServerSide:s}),t(this,_a,s,"f"),e(this,Ma,"f").isServerSide=this.isServerSide):Ia.log("redundant isServerSide assignment")}}var Ra,xa,Aa,$a,Oa;Kr=Fa,Xr=new WeakMap,ea=new WeakMap,sa=new WeakMap,ca=new WeakMap,ha=new WeakMap,pa=new WeakMap,va=new WeakMap,ya=new WeakMap,Sa=new WeakMap,Ea=new WeakMap,Ca=new WeakMap,Ma=new WeakMap,Da=new WeakMap,ka=new WeakMap,_a=new WeakMap,Qr=new WeakSet,Zr=function(){return new xn},Yr=function(){return e(this,Xr,"f").dispatchEvent},ta=async function(t,s){await(e(this,ea,"f")?.sendTxMessages(t,s))},ia=function(){Ia.assertWithError(this.isConnected,"notConnected")},na=function(){return Ua.every((e=>this.latestConnectionMessage.has(e)))},ra=function(){const t=Ua.map((e=>({type:e})));e(this,Qr,"m",ta).call(this,t)},aa=function(){Ia.assertWithError(this.canReconnect,"cannot reconnect to device")},la=function(s){Ia.log({connectionStatus:s}),"notConnected"==s?this.canReconnect&&this.reconnectOnDisconnection&&(Ia.log("starting reconnect interval..."),t(this,ha,setInterval((()=>{Ia.log("attempting reconnect..."),this.reconnect()}),1e3),"f")):null!=e(this,ha,"f")&&(Ia.log("clearing reconnect interval"),clearInterval(e(this,ha,"f")),t(this,ha,void 0,"f")),e(this,Qr,"m",fa).call(this),"connected"!=s||e(this,sa,"f")||e(this,Qr,"m",ra).call(this),Wa.OnDeviceConnectionStatusUpdated(this,s)},ga=function(t=!1){e(this,Qr,"a",Yr).call(this,"connectionStatus",{connectionStatus:this.connectionStatus}),e(this,Qr,"a",Yr).call(this,this.connectionStatus,{}),t&&e(this,Qr,"a",Yr).call(this,"isConnected",{isConnected:this.isConnected})},fa=function(){switch(t(this,sa,Boolean(this.connectionManager?.isConnected)&&e(this,Qr,"a",na)&&this._informationManager.isCurrentTimeSet,"f"),this.connectionStatus){case"connected":e(this,sa,"f")&&e(this,Qr,"m",ga).call(this,!0);break;case"notConnected":e(this,Qr,"m",ga).call(this,!0);break;default:e(this,Qr,"m",ga).call(this,!1)}},ua=function(){this.connectionManager?.clear(),this.latestConnectionMessage.clear(),this._informationManager.clear(),e(this,pa,"f").clear()},da=function(t,s){if(Ia.log({messageType:t,dataView:s}),"batteryLevel"===t){const t=s.getUint8(0);Ia.log("received battery level",{batteryLevel:t}),e(this,Qr,"m",wa).call(this,t)}else if(Re.includes(t))e(this,Ma,"f").parseMessage(t,s);else if(Ss.includes(t))e(this,Da,"f").parseMessage(t,s);else if(Et.includes(t))e(this,Ea,"f").parseMessage(t,s);else if(Mr.includes(t))e(this,ka,"f").parseMessage(t,s);else if(Us.includes(t))e(this,pa,"f").parseMessage(t,s);else if(ni.includes(t))this._informationManager.parseMessage(t,s);else{if(!Pt.includes(t))throw Error(`uncaught messageType ${t}`);e(this,ya,"f").parseMessage(t,s)}this.latestConnectionMessage.set(t,s),e(this,Qr,"a",Yr).call(this,"connectionMessage",{messageType:t,dataView:s})},ma=function(){!this.isConnected&&e(this,Qr,"a",na)&&e(this,Qr,"m",fa).call(this),"notConnected"!=this.connectionStatus&&e(this,Qr,"m",ta).call(this)},wa=function(s){Ia.assertTypeWithError(s,"number"),e(this,va,"f")!=s?(t(this,va,s,"f"),Ia.log({updatedBatteryLevel:e(this,va,"f")}),e(this,Qr,"a",Yr).call(this,"batteryLevel",{batteryLevel:e(this,va,"f")})):Ia.log(`duplicate batteryLevel assignment ${s}`)},Ta=function(t){return e(this,ea,"f").sendSmpMessage(t)},oa={value:!1},ba={value:!0};const Ba=k("DevicePairPressureSensorDataManager",{log:!0});class Na{constructor(){Ra.add(this),xa.set(this,{}),Aa.set(this,new Ye)}resetPressureRange(){e(this,Aa,"f").reset()}onDevicePressureData(t){const{pressure:s}=t.message,i=t.target.insoleSide;if(Ba.log({pressure:s,insoleSide:i}),e(this,xa,"f")[i]=s,e(this,Ra,"a",$a))return e(this,Ra,"m",Oa).call(this);Ba.log("doesn't have all pressure data yet...")}}var Pa;xa=new WeakMap,Aa=new WeakMap,Ra=new WeakSet,$a=function(){return ti.every((t=>t in e(this,xa,"f")))},Oa=function(){const t={rawSum:0,normalizedSum:0};return ti.forEach((s=>{t.rawSum+=e(this,xa,"f")[s].scaledSum,t.normalizedSum+=e(this,xa,"f")[s].normalizedSum})),t.normalizedSum>.001&&(t.center={x:0,y:0},ti.forEach((s=>{const i=e(this,xa,"f")[s],n=i.normalizedSum/t.normalizedSum;n>0&&(null!=i.normalizedCenter?.y&&(t.center.y+=i.normalizedCenter.y*n),"right"==s&&(t.center.x=n))})),t.normalizedCenter=e(this,Aa,"f").updateAndGetNormalization(t.center)),Ba.log({devicePairPressure:t}),t};const Va=k("DevicePairSensorDataManager",{log:!0}),za=["pressure","sensorData"];class ja{constructor(){Pa.set(this,{}),this.pressureSensorDataManager=new Na}get dispatchEvent(){return this.eventDispatcher.dispatchEvent}resetPressureRange(){this.pressureSensorDataManager.resetPressureRange()}onDeviceSensorData(t){const{timestamp:s,sensorType:i}=t.message;let n;if(Va.log({sensorType:i,timestamp:s,event:t}),e(this,Pa,"f")[i]||(e(this,Pa,"f")[i]={}),e(this,Pa,"f")[i][t.target.insoleSide]=s,"pressure"===i)n=this.pressureSensorDataManager.onDevicePressureData(t);else Va.log(`uncaught sensorType "${i}"`);if(n){const t=Object.assign({},e(this,Pa,"f")[i]);this.dispatchEvent(i,{sensorType:i,timestamps:t,[i]:n}),this.dispatchEvent("sensorData",{sensorType:i,timestamps:t,[i]:n})}else Va.log("no value received")}}var qa,Ga,Ha,Ja,Qa,Ka,Za,Xa,Ya,eo,to,so,io,no,ro,ao;Pa=new WeakMap;const oo=k("DevicePair",{log:!0});function co(e){return`device${t=e,t[0].toUpperCase()+t.slice(1)}`;var t}const ho=["isConnected",...za,...La.map((e=>co(e)))];class lo{constructor(){qa.add(this),Ha.set(this,new I(this,ho)),Qa.set(this,void 0),Ka.set(this,void 0),eo.set(this,{isConnected:e(this,qa,"m",so).bind(this),sensorData:e(this,qa,"m",ro).bind(this),getType:e(this,qa,"m",io).bind(this)}),no.set(this,new ja),e(this,no,"f").eventDispatcher=e(this,Ha,"f")}get sides(){return ti}get addEventListener(){return e(this,Ha,"f").addEventListener}get removeEventListener(){return e(this,Ha,"f").removeEventListener}get waitForEvent(){return e(this,Ha,"f").waitForEvent}get removeEventListeners(){return e(this,Ha,"f").removeEventListeners}get removeAllEventListeners(){return e(this,Ha,"f").removeAllEventListeners}get left(){return e(this,Qa,"f")}get right(){return e(this,Ka,"f")}get isConnected(){return ti.every((e=>this[e]?.isConnected))}get isPartiallyConnected(){return ti.some((e=>this[e]?.isConnected))}get isHalfConnected(){return this.isPartiallyConnected&&!this.isConnected}assignInsole(s){if(!s.isInsole)return void oo.warn("device is not an insole");const i=s.insoleSide,n=this[i];if(s!=n){switch(n&&e(this,qa,"m",Xa).call(this,n),e(this,qa,"m",Za).call(this,s),i){case"left":t(this,Qa,s,"f");break;case"right":t(this,Ka,s,"f")}return oo.log(`assigned ${i} insole`,s),this.resetPressureRange(),e(this,qa,"a",Ja).call(this,"isConnected",{isConnected:this.isConnected}),e(this,qa,"a",Ja).call(this,"deviceIsConnected",{device:s,isConnected:s.isConnected,side:i}),n}oo.log("device already assigned")}async setSensorConfiguration(e){for(let t=0;t<ti.length;t++){const s=ti[t];this[s]?.isConnected&&await this[s].setSensorConfiguration(e)}}resetPressureRange(){e(this,no,"f").resetPressureRange()}async triggerVibration(e,t){const s=ti.map((s=>this[s]?.triggerVibration(e,t))).filter(Boolean);return Promise.allSettled(s)}static get shared(){return e(this,Ga,"f",ao)}}Ga=lo,Ha=new WeakMap,Qa=new WeakMap,Ka=new WeakMap,eo=new WeakMap,no=new WeakMap,qa=new WeakSet,Ja=function(){return e(this,Ha,"f").dispatchEvent},Za=function(t){rn(t,e(this,eo,"f")),La.forEach((s=>{t.addEventListener(s,e(this,qa,"m",to).bind(this))}))},Xa=function(t){an(t,e(this,eo,"f")),La.forEach((s=>{t.removeEventListener(s,e(this,qa,"m",to).bind(this))}))},Ya=function(t){const s=ti.some((s=>this[s]==t&&(oo.log(`removing ${s} insole`,t),an(t,e(this,eo,"f")),delete this[s],!0)));return s&&e(this,qa,"a",Ja).call(this,"isConnected",{isConnected:this.isConnected}),s},to=function(t){const{type:s,target:i,message:n}=t;e(this,qa,"a",Ja).call(this,co(s),{...n,device:i,side:i.insoleSide})},so=function(t){e(this,qa,"a",Ja).call(this,"isConnected",{isConnected:this.isConnected})},io=function(t){const{target:s}=t;if(this[s.insoleSide]==s)return;e(this,qa,"m",Ya).call(this,s)&&this.assignInsole(s)},ro=function(t){this.isConnected&&e(this,no,"f").onDeviceSensorData(t)},ao={value:new Ga},Wa.AddEventListener("deviceConnected",(t=>{const{device:s}=t.message;s.isInsole&&e(Ga,Ga,"f",ao).assignInsole(s)}));const go=k("ServerUtils",{log:!1}),fo=["isScanningAvailable","isScanning","startScan","stopScan","discoveredDevice","discoveredDevices","expiredDiscoveredDevice","connectToDevice","disconnectFromDevice","connectedDevices","deviceMessage"];function uo(e,...t){go.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;go.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 go.log("messageBuffers",...s),j(...s)}function mo(...e){return go.log("createServerMessage",...e),uo(fo,...e)}function po(...e){return go.log("createClientDeviceMessage",...e),uo(tn,...e)}var vo,wo,yo,bo,So;mo("isScanningAvailable"),mo("isScanning"),mo("startScan"),mo("stopScan"),mo("discoveredDevices");const Eo=k("ClientConnectionManager",{log:!0}),Co=[...Us,"batteryLevel"];class Mo extends sn{constructor(){super(...arguments),vo.add(this),wo.set(this,void 0),yo.set(this,!1)}static get isSupported(){return i}static get type(){return"client"}get bluetoothId(){return e(this,wo,"f")}set bluetoothId(s){Eo.assertTypeWithError(s,"string"),e(this,wo,"f")!=s?t(this,wo,s,"f"):Eo.log("redundant bluetoothId assignment")}get isConnected(){return e(this,yo,"f")}set isConnected(s){Eo.assertTypeWithError(s,"boolean"),e(this,yo,"f")!=s?(t(this,yo,s,"f"),this.status=e(this,yo,"f")?"connected":"notConnected",this.isConnected&&e(this,vo,"m",bo).call(this)):Eo.log("redundant newIsConnected assignment",s)}async connect(){await super.connect(),this.sendClientConnectMessage()}async disconnect(){await super.disconnect(),this.sendClientDisconnectMessage()}get canReconnect(){return!0}async reconnect(){await super.reconnect(),Eo.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){Eo.log({dataView:t}),vt(t,La,e(this,vo,"m",So).bind(this),null,!0),this.onMessagesReceived()}}var Do,ko,To,_o,Wo,Io,Lo,Uo,Fo,Ro,xo,Ao,$o,Oo,Bo,No,Po,Vo,zo;wo=new WeakMap,yo=new WeakMap,vo=new WeakSet,bo=function(){this.sendClientMessage(...Co)},So=function(e,t){let s=0;switch(Eo.log({messageType:e},t),e){case"isConnected":const i=Boolean(t.getUint8(s++));Eo.log({isConnected:i}),this.isConnected=i;break;case"rx":this.parseRxMessage(t);break;default:this.onMessageReceived(e,t)}};const jo=k("BaseClient",{log:!0}),qo=["notConnected","connecting","connected","disconnecting","connectionStatus","isConnected","isScanningAvailable","isScanning","discoveredDevice","expiredDiscoveredDevice"];class Go{constructor(){Do.add(this),To.set(this,{}),_o.set(this,new I(this,qo)),this._reconnectOnDisconnection=this.baseConstructor.ReconnectOnDisconnection,Wo.set(this,"notConnected"),Lo.set(this,!1),xo.set(this,!1),Po.set(this,{})}get baseConstructor(){return this.constructor}get devices(){return e(this,To,"f")}get addEventListener(){return e(this,_o,"f").addEventListener}get dispatchEvent(){return e(this,_o,"f").dispatchEvent}get removeEventListener(){return e(this,_o,"f").removeEventListener}get waitForEvent(){return e(this,_o,"f").waitForEvent}assertConnection(){jo.assertWithError(this.isConnected,"notConnected")}assertDisconnection(){jo.assertWithError(this.isDisconnected,"not disconnected")}static get ReconnectOnDisconnection(){return this._reconnectOnDisconnection}static set ReconnectOnDisconnection(e){jo.assertTypeWithError(e,"boolean"),this._reconnectOnDisconnection=e}get reconnectOnDisconnection(){return this._reconnectOnDisconnection}set reconnectOnDisconnection(e){jo.assertTypeWithError(e,"boolean"),this._reconnectOnDisconnection=e}get _connectionStatus(){return e(this,Wo,"f")}set _connectionStatus(s){switch(jo.assertTypeWithError(s,"string"),jo.log({newConnectionStatus:s}),t(this,Wo,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?this.sendServerMessage("isScanningAvailable","discoveredDevices","connectedDevices"):e(this,Do,"m",ko).call(this)}}get connectionStatus(){return this._connectionStatus}parseMessage(t){jo.log("parseMessage",{dataView:t}),vt(t,fo,e(this,Do,"m",Io).bind(this),null,!0)}get isScanningAvailable(){return e(this,Do,"a",Uo)}requestIsScanningAvailable(){this.sendServerMessage("isScanningAvailable")}get isScanning(){return e(this,Do,"a",Ao)}startScan(){e(this,Do,"m",No).call(this),this.sendServerMessage("startScan")}stopScan(){e(this,Do,"m",Bo).call(this),this.sendServerMessage("stopScan")}toggleScan(){e(this,Do,"m",Ro).call(this),this.isScanning?this.stopScan():this.startScan()}get discoveredDevices(){return e(this,Po,"f")}onDiscoveredDevice(t){jo.log({discoveredDevice:t}),e(this,Po,"f")[t.bluetoothId]=t,this.dispatchEvent("discoveredDevice",{discoveredDevice:t})}requestDiscoveredDevices(){this.sendServerMessage({type:"discoveredDevices"})}connectToDevice(e){return this.requestConnectionToDevice(e)}requestConnectionToDevice(t){this.assertConnection(),jo.assertTypeWithError(t,"string");const s=e(this,Do,"m",zo).call(this,t);return s.connect(),s}sendConnectToDeviceMessage(e){this.sendServerMessage({type:"connectToDevice",data:e})}createDevice(e){const t=new Fa,s=new Mo;return 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){jo.log({bluetoothIds:t}),t.forEach((t=>{e(this,Do,"m",zo).call(this,t).connectionManager.isConnected=!0}))}disconnectFromDevice(e){this.requestDisconnectionFromDevice(e)}requestDisconnectionFromDevice(e){this.assertConnection(),jo.assertTypeWithError(e,"string");const t=this.devices[e];return jo.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,po(...t)]})}}To=new WeakMap,_o=new WeakMap,Wo=new WeakMap,Lo=new WeakMap,xo=new WeakMap,Po=new WeakMap,Do=new WeakSet,ko=function(){t(this,Do,!1,"a",Fo),t(this,Do,!1,"a",$o);for(const t in e(this,To,"f")){e(this,To,"f")[t].connectionManager.isConnected=!1}},Io=function(s,i){let n=0;switch(jo.log({messageType:s},i),s){case"isScanningAvailable":{const e=Boolean(i.getUint8(n++));jo.log({isScanningAvailable:e}),t(this,Do,e,"a",Fo)}break;case"isScanning":{const e=Boolean(i.getUint8(n++));jo.log({isScanning:e}),t(this,Do,e,"a",$o)}break;case"discoveredDevice":{const{string:e}=pt(i,n);jo.log({discoveredDeviceString:e});const t=JSON.parse(e);jo.log({discoveredDevice:t}),this.onDiscoveredDevice(t)}break;case"expiredDiscoveredDevice":{const{string:t}=pt(i,n);e(this,Do,"m",Vo).call(this,t)}break;case"connectedDevices":{if(0==i.byteLength)break;const{string:e}=pt(i,n);jo.log({connectedBluetoothDeviceIdStrings:e});const t=JSON.parse(e).connectedDevices;jo.log({connectedBluetoothDeviceIds:t}),this.onConnectedBluetoothDeviceIds(t)}break;case"deviceMessage":{const{string:t,byteOffset:s}=pt(i,n);n=s;const r=e(this,To,"f")[t];jo.assertWithError(r,`no device found for id ${t}`);const a=r.connectionManager,o=G(i,n);a.onClientMessage(o)}break;default:jo.error(`uncaught messageType "${s}"`)}},Uo=function(){return e(this,Lo,"f")},Fo=function(s){jo.assertTypeWithError(s,"boolean"),t(this,Lo,s,"f"),this.dispatchEvent("isScanningAvailable",{isScanningAvailable:this.isScanningAvailable}),this.isScanningAvailable&&e(this,Do,"m",Oo).call(this)},Ro=function(){this.assertConnection(),jo.assertWithError(this.isScanningAvailable,"scanning is not available")},Ao=function(){return e(this,xo,"f")},$o=function(e){jo.assertTypeWithError(e,"boolean"),t(this,xo,e,"f"),this.dispatchEvent("isScanning",{isScanning:this.isScanning})},Oo=function(){this.sendServerMessage("isScanning")},Bo=function(){jo.assertWithError(this.isScanning,"is not scanning")},No=function(){jo.assertWithError(!this.isScanning,"is already scanning")},Vo=function(t){jo.log({expiredBluetoothDeviceId:t});const s=e(this,Po,"f")[t];s?(jo.log({expiredDiscoveredDevice:s}),delete e(this,Po,"f")[t],this.dispatchEvent("expiredDiscoveredDevice",{discoveredDevice:s})):jo.warn(`no discoveredDevice found with id "${t}"`)},zo=function(t){let s=e(this,To,"f")[t];return s||(s=this.createDevice(t),e(this,To,"f")[t]=s),s},Go._reconnectOnDisconnection=!0;const Ho=k("WebSocketUtils",{log:!1}),Jo=["ping","pong","serverMessage"];function Qo(...e){return Ho.log("createWebSocketMessage",...e),uo(Jo,...e)}var Ko,Zo,Xo,Yo,ec,tc,sc,ic,nc,rc,ac,oc,cc;Qo("ping"),Qo("pong");const hc=k("WebSocketClient",{log:!0});class lc extends Go{constructor(){super(...arguments),Ko.add(this),Zo.set(this,void 0),Yo.set(this,{open:e(this,Ko,"m",ec).bind(this),message:e(this,Ko,"m",tc).bind(this),close:e(this,Ko,"m",sc).bind(this),error:e(this,Ko,"m",ic).bind(this)}),ac.set(this,new x(e(this,Ko,"m",oc).bind(this),3e7))}get webSocket(){return e(this,Zo,"f")}set webSocket(s){e(this,Zo,"f")!=s?(hc.log("assigning webSocket",s),e(this,Zo,"f")&&an(e(this,Zo,"f"),e(this,Yo,"f")),rn(s,e(this,Yo,"f")),t(this,Zo,s,"f"),hc.log("assigned webSocket")):hc.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,Zo,"f").send(t)}sendServerMessage(...e){this.sendMessage(Qo({type:"serverMessage",data:mo(...e)}))}}Zo=new WeakMap,Yo=new WeakMap,ac=new WeakMap,Ko=new WeakSet,Xo=function(...e){this.sendMessage(Qo(...e))},ec=function(t){hc.log("webSocket.open",t),e(this,ac,"f").start(),this._connectionStatus="connected"},tc=async function(t){hc.log("webSocket.message",t),e(this,ac,"f").restart();const s=await t.data.arrayBuffer(),i=new DataView(s);e(this,Ko,"m",nc).call(this,i)},sc=function(t){hc.log("webSocket.close",t),this._connectionStatus="notConnected",Object.entries(this.devices).forEach((([e,t])=>{t.connectionManager.isConnected=!1})),e(this,ac,"f").stop(),this.reconnectOnDisconnection&&setTimeout((()=>{this.reconnect()}),3e3)},ic=function(e){hc.error("webSocket.error",e.message)},nc=function(t){vt(t,Jo,e(this,Ko,"m",rc).bind(this),null,!0)},rc=function(t,s){switch(t){case"ping":e(this,Ko,"m",cc).call(this);break;case"pong":break;case"serverMessage":this.parseMessage(s);break;default:hc.error(`uncaught messageType "${t}"`)}},oc=function(){e(this,Ko,"m",Xo).call(this,"ping")},cc=function(){e(this,Ko,"m",Xo).call(this,"pong")};export{St as ContinuousSensorTypes,it as DefaultNumberOfPressureSensors,Fa as Device,Wa as DeviceManager,lo as DevicePair,ei as DeviceTypes,w as Environment,Oe as FileTransferDirections,xe as FileTypes,ti as InsoleSides,ii as MaxNameLength,Ti as MaxNumberOfVibrationWaveformEffectSegments,Li as MaxNumberOfVibrationWaveformSegments,Bt as MaxSensorRate,Wi as MaxVibrationWaveformEffectSegmentDelay,Ii as MaxVibrationWaveformEffectSegmentLoopCount,Ui as MaxVibrationWaveformEffectSequenceLoopCount,_i as MaxVibrationWaveformSegmentDuration,si as MinNameLength,Je as RangeHelper,Nt as SensorRateStep,bt as SensorTypes,Ms as TfliteSensorTypes,Cs as TfliteTasks,Di as VibrationLocations,ki as VibrationTypes,oi as VibrationWaveformEffects,lc 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,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};
6
6
  //# sourceMappingURL=brilliantsole.module.min.js.map