import{_ as e,d as t,g as r,n as i,y as a,H as s,I as o,q as n,v as c,w as l}from"./c.998383f4.js";import{C as h,d,e as g,f as p,g as m,t as u,h as f,i as y,j as w,E as _,R as b,D as I,k,l as $,S as v,n as S,o as B,p as F,q as D,r as C,u as R,v as z,w as U,F as x,x as E,y as T,z as A,A as L,B as V,G as P,H as M,I as W,J as O,K as j,L as q,M as N,N as H,O as Q,P as G,Q as J,T as K,U as X,V as Y,W as Z,X as ee,Y as te}from"./c.d3b09e82.js";class re extends i{constructor(){super(...arguments),this.indeterminate=!1,this.progress=0,this.density=0,this.closed=!1}open(){this.closed=!1}close(){this.closed=!0}render(){const e={"mdc-circular-progress--closed":this.closed,"mdc-circular-progress--indeterminate":this.indeterminate},t=48+4*this.density,r={width:`${t}px`,height:`${t}px`};return a`
      <div
        class="mdc-circular-progress ${s(e)}"
        style="${o(r)}"
        role="progressbar"
        aria-label="${n(this.ariaLabel)}"
        aria-valuemin="0"
        aria-valuemax="1"
        aria-valuenow="${n(this.indeterminate?void 0:this.progress)}">
        ${this.renderDeterminateContainer()}
        ${this.renderIndeterminateContainer()}
      </div>`}renderDeterminateContainer(){const e=48+4*this.density,t=e/2,r=this.density>=-3?18+11*this.density/6:12.5+5*(this.density+3)/4,i=6.2831852*r,s=(1-this.progress)*i,o=this.density>=-3?4+this.density*(1/3):3+(this.density+3)*(1/6);return a`
      <div class="mdc-circular-progress__determinate-container">
        <svg class="mdc-circular-progress__determinate-circle-graphic"
             viewBox="0 0 ${e} ${e}">
          <circle class="mdc-circular-progress__determinate-track"
                  cx="${t}" cy="${t}" r="${r}"
                  stroke-width="${o}"></circle>
          <circle class="mdc-circular-progress__determinate-circle"
                  cx="${t}" cy="${t}" r="${r}"
                  stroke-dasharray="${6.2831852*r}"
                  stroke-dashoffset="${s}"
                  stroke-width="${o}"></circle>
        </svg>
      </div>`}renderIndeterminateContainer(){return a`
      <div class="mdc-circular-progress__indeterminate-container">
        <div class="mdc-circular-progress__spinner-layer">
          ${this.renderIndeterminateSpinnerLayer()}
        </div>
      </div>`}renderIndeterminateSpinnerLayer(){const e=48+4*this.density,t=e/2,r=this.density>=-3?18+11*this.density/6:12.5+5*(this.density+3)/4,i=6.2831852*r,s=.5*i,o=this.density>=-3?4+this.density*(1/3):3+(this.density+3)*(1/6);return a`
        <div class="mdc-circular-progress__circle-clipper mdc-circular-progress__circle-left">
          <svg class="mdc-circular-progress__indeterminate-circle-graphic"
               viewBox="0 0 ${e} ${e}">
            <circle cx="${t}" cy="${t}" r="${r}"
                    stroke-dasharray="${i}"
                    stroke-dashoffset="${s}"
                    stroke-width="${o}"></circle>
          </svg>
        </div>
        <div class="mdc-circular-progress__gap-patch">
          <svg class="mdc-circular-progress__indeterminate-circle-graphic"
               viewBox="0 0 ${e} ${e}">
            <circle cx="${t}" cy="${t}" r="${r}"
                    stroke-dasharray="${i}"
                    stroke-dashoffset="${s}"
                    stroke-width="${.8*o}"></circle>
          </svg>
        </div>
        <div class="mdc-circular-progress__circle-clipper mdc-circular-progress__circle-right">
          <svg class="mdc-circular-progress__indeterminate-circle-graphic"
               viewBox="0 0 ${e} ${e}">
            <circle cx="${t}" cy="${t}" r="${r}"
                    stroke-dasharray="${i}"
                    stroke-dashoffset="${s}"
                    stroke-width="${o}"></circle>
          </svg>
        </div>`}update(e){super.update(e),e.has("progress")&&(this.progress>1&&(this.progress=1),this.progress<0&&(this.progress=0))}}e([t({type:Boolean,reflect:!0})],re.prototype,"indeterminate",void 0),e([t({type:Number,reflect:!0})],re.prototype,"progress",void 0),e([t({type:Number,reflect:!0})],re.prototype,"density",void 0),e([t({type:Boolean,reflect:!0})],re.prototype,"closed",void 0),e([r,t({type:String,attribute:"aria-label"})],re.prototype,"ariaLabel",void 0);const ie=c`.mdc-circular-progress__determinate-circle,.mdc-circular-progress__indeterminate-circle-graphic{stroke:#6200ee;stroke:var(--mdc-theme-primary, #6200ee)}.mdc-circular-progress__determinate-track{stroke:transparent}@keyframes mdc-circular-progress-container-rotate{to{transform:rotate(360deg)}}@keyframes mdc-circular-progress-spinner-layer-rotate{12.5%{transform:rotate(135deg)}25%{transform:rotate(270deg)}37.5%{transform:rotate(405deg)}50%{transform:rotate(540deg)}62.5%{transform:rotate(675deg)}75%{transform:rotate(810deg)}87.5%{transform:rotate(945deg)}100%{transform:rotate(1080deg)}}@keyframes mdc-circular-progress-color-1-fade-in-out{from{opacity:.99}25%{opacity:.99}26%{opacity:0}89%{opacity:0}90%{opacity:.99}to{opacity:.99}}@keyframes mdc-circular-progress-color-2-fade-in-out{from{opacity:0}15%{opacity:0}25%{opacity:.99}50%{opacity:.99}51%{opacity:0}to{opacity:0}}@keyframes mdc-circular-progress-color-3-fade-in-out{from{opacity:0}40%{opacity:0}50%{opacity:.99}75%{opacity:.99}76%{opacity:0}to{opacity:0}}@keyframes mdc-circular-progress-color-4-fade-in-out{from{opacity:0}65%{opacity:0}75%{opacity:.99}90%{opacity:.99}to{opacity:0}}@keyframes mdc-circular-progress-left-spin{from{transform:rotate(265deg)}50%{transform:rotate(130deg)}to{transform:rotate(265deg)}}@keyframes mdc-circular-progress-right-spin{from{transform:rotate(-265deg)}50%{transform:rotate(-130deg)}to{transform:rotate(-265deg)}}.mdc-circular-progress{display:inline-flex;position:relative;direction:ltr;line-height:0;transition:opacity 250ms 0ms cubic-bezier(0.4, 0, 0.6, 1)}.mdc-circular-progress__determinate-container,.mdc-circular-progress__indeterminate-circle-graphic,.mdc-circular-progress__indeterminate-container,.mdc-circular-progress__spinner-layer{position:absolute;width:100%;height:100%}.mdc-circular-progress__determinate-container{transform:rotate(-90deg)}.mdc-circular-progress__indeterminate-container{font-size:0;letter-spacing:0;white-space:nowrap;opacity:0}.mdc-circular-progress__determinate-circle-graphic,.mdc-circular-progress__indeterminate-circle-graphic{fill:transparent}.mdc-circular-progress__determinate-circle{transition:stroke-dashoffset 500ms 0ms cubic-bezier(0, 0, 0.2, 1)}.mdc-circular-progress__gap-patch{position:absolute;top:0;left:47.5%;box-sizing:border-box;width:5%;height:100%;overflow:hidden}.mdc-circular-progress__gap-patch .mdc-circular-progress__indeterminate-circle-graphic{left:-900%;width:2000%;transform:rotate(180deg)}.mdc-circular-progress__circle-clipper{display:inline-flex;position:relative;width:50%;height:100%;overflow:hidden}.mdc-circular-progress__circle-clipper .mdc-circular-progress__indeterminate-circle-graphic{width:200%}.mdc-circular-progress__circle-right .mdc-circular-progress__indeterminate-circle-graphic{left:-100%}.mdc-circular-progress--indeterminate .mdc-circular-progress__determinate-container{opacity:0}.mdc-circular-progress--indeterminate .mdc-circular-progress__indeterminate-container{opacity:1}.mdc-circular-progress--indeterminate .mdc-circular-progress__indeterminate-container{animation:mdc-circular-progress-container-rotate 1568.2352941176ms linear infinite}.mdc-circular-progress--indeterminate .mdc-circular-progress__spinner-layer{animation:mdc-circular-progress-spinner-layer-rotate 5332ms cubic-bezier(0.4, 0, 0.2, 1) infinite both}.mdc-circular-progress--indeterminate .mdc-circular-progress__color-1{animation:mdc-circular-progress-spinner-layer-rotate 5332ms cubic-bezier(0.4, 0, 0.2, 1) infinite both,mdc-circular-progress-color-1-fade-in-out 5332ms cubic-bezier(0.4, 0, 0.2, 1) infinite both}.mdc-circular-progress--indeterminate .mdc-circular-progress__color-2{animation:mdc-circular-progress-spinner-layer-rotate 5332ms cubic-bezier(0.4, 0, 0.2, 1) infinite both,mdc-circular-progress-color-2-fade-in-out 5332ms cubic-bezier(0.4, 0, 0.2, 1) infinite both}.mdc-circular-progress--indeterminate .mdc-circular-progress__color-3{animation:mdc-circular-progress-spinner-layer-rotate 5332ms cubic-bezier(0.4, 0, 0.2, 1) infinite both,mdc-circular-progress-color-3-fade-in-out 5332ms cubic-bezier(0.4, 0, 0.2, 1) infinite both}.mdc-circular-progress--indeterminate .mdc-circular-progress__color-4{animation:mdc-circular-progress-spinner-layer-rotate 5332ms cubic-bezier(0.4, 0, 0.2, 1) infinite both,mdc-circular-progress-color-4-fade-in-out 5332ms cubic-bezier(0.4, 0, 0.2, 1) infinite both}.mdc-circular-progress--indeterminate .mdc-circular-progress__circle-left .mdc-circular-progress__indeterminate-circle-graphic{animation:mdc-circular-progress-left-spin 1333ms cubic-bezier(0.4, 0, 0.2, 1) infinite both}.mdc-circular-progress--indeterminate .mdc-circular-progress__circle-right .mdc-circular-progress__indeterminate-circle-graphic{animation:mdc-circular-progress-right-spin 1333ms cubic-bezier(0.4, 0, 0.2, 1) infinite both}.mdc-circular-progress--closed{opacity:0}:host{display:inline-flex}.mdc-circular-progress__determinate-track{stroke:transparent;stroke:var(--mdc-circular-progress-track-color, transparent)}`;let ae=class extends re{};ae.styles=[ie],ae=e([l("mwc-circular-progress")],ae);const se=async e=>{let t;return e==h?t=await import("./c.a2dcbc2e.js"):e==d?t=await import("./c.3109ccc6.js"):e==g?t=await import("./c.c1dbd867.js"):e==p?t=await import("./c.144419c0.js"):e==m&&(t=await import("./c.18e9678b.js")),{...t,text:u(atob(t.text)),data:u(atob(t.data))}},oe={b:{u:DataView.prototype.getInt8,p:DataView.prototype.setInt8,bytes:1},B:{u:DataView.prototype.getUint8,p:DataView.prototype.setUint8,bytes:1},h:{u:DataView.prototype.getInt16,p:DataView.prototype.setInt16,bytes:2},H:{u:DataView.prototype.getUint16,p:DataView.prototype.setUint16,bytes:2},i:{u:DataView.prototype.getInt32,p:DataView.prototype.setInt32,bytes:4},I:{u:DataView.prototype.getUint32,p:DataView.prototype.setUint32,bytes:4},q:{u:DataView.prototype.getInt64,p:DataView.prototype.setInt64,bytes:8},Q:{u:DataView.prototype.getUint64,p:DataView.prototype.setUint64,bytes:8}},ne=(e,...t)=>{let r=0;if(e.replace(/[<>]/,"").length!=t.length)throw"Pack format to Argument count mismatch";let i=[],a=!0;for(let i=0;i<e.length;i++)"<"==e[i]?a=!0:">"==e[i]?a=!1:(s(e[i],t[r]),r++);function s(e,t){if(!(e in oe))throw"Unhandled character '"+e+"' in pack format";let r=oe[e].bytes,s=new DataView(new ArrayBuffer(r));oe[e].p.bind(s)(0,t,a);for(let e=0;e<r;e++)i.push(s.getUint8(e))}return i},ce=(e,t)=>{let r=0,i=[],a=!0;for(let t of e)"<"==t?a=!0:">"==t?a=!1:s(t);function s(e){if(!(e in oe))throw"Unhandled character '"+e+"' in unpack format";let s=oe[e].bytes,o=new DataView(new ArrayBuffer(s));for(let e=0;e<s;e++)o.setUint8(e,255&t[r+e]);let n=oe[e].u.bind(o);i.push(n(0,a)),r+=s}return i};class le extends EventTarget{constructor(e,t,r){super(),this.port=e,this.logger=t,this._parent=r,this.chipName=null,this._efuses=new Array(4).fill(0),this._flashsize=4194304,this.debug=!1,this.IS_STUB=!1,this.connected=!0,this.flashSize=null}get _inputBuffer(){return this._parent?this._parent._inputBuffer:this.__inputBuffer}async initialize(){await this.hardReset(!0),this._parent||(this.__inputBuffer=[],this.readLoop()),await this.sync();let e=await this.readRegister(f),t=K[e>>>0];if(void 0===t)throw new Error(`Unknown Chip: Hex: ${y(e>>>0,8).toLowerCase()} Number: ${e}`);this.chipName=t.name,this.chipFamily=t.family;let r=w(this.getChipFamily()).macFuse;for(let e=0;e<4;e++)this._efuses[e]=await this.readRegister(r+4*e);this.logger.log(`Chip type ${this.chipName}`)}async readLoop(){this.debug&&this.logger.debug("Starting read loop"),this._reader=this.port.readable.getReader();try{for(;;){const{value:e,done:t}=await this._reader.read();if(t){this._reader.releaseLock();break}e&&0!==e.length&&this._inputBuffer.push(...Array.from(e))}}catch(e){console.error("Read loop got disconnected")}this.connected=!1,this.dispatchEvent(new Event("disconnect")),this.logger.debug("Finished read loop")}async hardReset(e=!1){this.logger.log("Try hard reset."),await this.port.setSignals({dataTerminalReady:!1,requestToSend:!0}),await this.port.setSignals({dataTerminalReady:e,requestToSend:!1}),await new Promise((e=>setTimeout(e,1e3)))}macAddr(){let e,t=new Array(6).fill(0),r=this._efuses[0],i=this._efuses[1],a=this._efuses[2],s=this._efuses[3];if(this.chipFamily==p){if(0!=s)e=[s>>16&255,s>>8&255,255&s];else if(0==(i>>16&255))e=[24,254,52];else{if(1!=(i>>16&255))throw new Error("Couldnt determine OUI");e=[172,208,116]}t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=i>>8&255,t[4]=255&i,t[5]=r>>24&255}else if(this.chipFamily==h)t[0]=a>>8&255,t[1]=255&a,t[2]=i>>24&255,t[3]=i>>16&255,t[4]=i>>8&255,t[5]=255&i;else{if(this.chipFamily!=d&&this.chipFamily!=g&&this.chipFamily!=m)throw new Error("Unknown chip family");t[0]=i>>8&255,t[1]=255&i,t[2]=r>>24&255,t[3]=r>>16&255,t[4]=r>>8&255,t[5]=255&r}return t}async readRegister(e){this.debug&&this.logger.debug("Reading from Register "+y(e,8));let t=ne("<I",e);await this.sendCommand(_,t);let[r,i]=await this.getResponse(_);return r}async checkCommand(e,t,r=0,i=I){i=Math.min(i,X),await this.sendCommand(e,t,r);let[a,s]=await this.getResponse(e,i);if(null===s)throw new Error("Didn't get enough status bytes");let o=0;if(this.IS_STUB||this.chipFamily==p?o=2:[h,d,g,m].includes(this.chipFamily)?o=4:[2,4].includes(s.length)&&(o=s.length),s.length<o)throw new Error("Didn't get enough status bytes");let n=s.slice(-o,s.length);if(s=s.slice(0,-o),this.debug&&(this.logger.debug("status",n),this.logger.debug("value",a),this.logger.debug("data",s)),1==n[0])throw n[1]==b?new Error("Invalid (unsupported) command "+y(e)):new Error("Command failure error code "+y(n[1]));return[a,s]}async sendCommand(e,t,r=0){let i=k([...ne("<BBHI",0,e,t.length,r),...t]);this.debug&&this.logger.debug(`Writing ${i.length} byte${1==i.length?"":"s"}:`,i),await this.writeToStream(i)}async readPacket(e){let t=null,r=!1,i=[];for(;;){let a=Date.now();for(i=[];Date.now()-a<e;){if(this._inputBuffer.length>0){i.push(this._inputBuffer.shift());break}await $(10)}if(0==i.length){throw new v("Timed out waiting for packet "+(null===t?"header":"content"))}this.debug&&this.logger.debug("Read "+i.length+" bytes: "+S(i));for(let e of i)if(null===t){if(192!=e)throw this.debug&&(this.logger.debug("Read invalid data: "+S(i)),this.logger.debug("Remaining data in serial buffer: "+S(this._inputBuffer))),new v("Invalid head of packet ("+y(e)+")");t=[]}else if(r)if(r=!1,220==e)t.push(192);else{if(221!=e)throw this.debug&&(this.logger.debug("Read invalid data: "+S(i)),this.logger.debug("Remaining data in serial buffer: "+S(this._inputBuffer))),new v("Invalid SLIP escape (0xdb, "+y(e)+")");t.push(219)}else if(219==e)r=!0;else{if(192==e)return this.debug&&this.logger.debug("Received full packet: "+S(t)),t;t.push(e)}}throw new v("Invalid state")}async getResponse(e,t=I){for(let r=0;r<100;r++){const r=await this.readPacket(t);if(r.length<8)continue;const[i,a,s,o]=ce("<BBHI",r.slice(0,8));if(1!=i)continue;const n=r.slice(8);if(null==e||a==e)return[o,n];if(0!=n[0]&&n[1]==b)throw this._inputBuffer.length=0,new Error(`Invalid (unsupported) command ${y(e)}`)}throw"Response doesn't match request"}checksum(e,t=B){for(let r of e)t^=r;return t}async setBaudrate(e){if(this.chipFamily==p)throw new Error("Changing baud rate is not supported on the ESP8266");this.logger.log("Attempting to change baud rate to "+e+"...");try{let t=ne("<II",e,this.IS_STUB?F:0);await this.checkCommand(D,t)}catch(t){throw console.error(t),new Error(`Unable to change the baud rate to ${e}: No response from set baud rate command.`)}this._parent?await this._parent.reconfigurePort(e):await this.reconfigurePort(e)}async reconfigurePort(e){var t;try{await(null===(t=this._reader)||void 0===t?void 0:t.cancel()),await this.port.close(),await this.port.open({baudRate:e}),this.readLoop(),this.logger.log(`Changed baud rate to ${e}`)}catch(t){throw console.error(t),new Error(`Unable to change the baud rate to ${e}: ${t}`)}}async sync(){for(let e=0;e<5;e++){if(this._inputBuffer.length=0,await this._sync())return await $(100),!0;await $(100)}throw new Error("Couldn't sync to ESP. Try resetting.")}async _sync(){await this.sendCommand(C,R);for(let e=0;e<8;e++)try{let[e,t]=await this.getResponse(C,z);if(t.length>1&&0==t[0]&&0==t[1])return!0}catch(e){}return!1}getFlashWriteSize(){return this.IS_STUB?U:x}async flashData(e,t,r=0,i=!1){if(e.byteLength>=8){var a=Array.from(new Uint8Array(e,0,4));let t=a[0],r=a[2],i=a[3];this.logger.log(`Image header, Magic=${y(t)}, FlashMode=${y(r)}, FlashSizeFreq=${y(i)}`)}let s,o=e.byteLength,n=0,c=I;i?(s=E(new Uint8Array(e),{level:9}).buffer,n=s.byteLength,this.logger.log(`Writing data with filesize: ${o}. Compressed Size: ${n}`),c=await this.flashDeflBegin(o,n,r)):(this.logger.log(`Writing data with filesize: ${o}`),s=e,await this.flashBegin(o,r));let l=[],h=0,d=0,g=0,p=Date.now(),m=this.getFlashWriteSize(),u=i?n:o;for(;u-g>0;)this.debug&&this.logger.log(`Writing at ${y(r+h*m,8)} `),u-g>=m?l=Array.from(new Uint8Array(s,g,m)):(l=Array.from(new Uint8Array(s,g,u-g)),i||(l=l.concat(new Array(m-l.length).fill(255)))),i?await this.flashDeflBlock(l,h,c):await this.flashBlock(l,h),h+=1,d+=i?Math.round(l.length*o/n):l.length,g+=m,t(Math.min(d,o),o);this.logger.log("Took "+(Date.now()-p)+"ms to write "+u+" bytes"),this.IS_STUB&&(await this.flashBegin(0,0),i?await this.flashDeflFinish():await this.flashFinish())}async flashBlock(e,t,r=I){await this.checkCommand(T,ne("<IIII",e.length,t,0,0).concat(e),this.checksum(e),r)}async flashDeflBlock(e,t,r=I){await this.checkCommand(A,ne("<IIII",e.length,t,0,0).concat(e),this.checksum(e),r)}async flashBegin(e=0,t=0,r=!1){let i,a,s=this.getFlashWriteSize();!this.IS_STUB&&[h,d,g,m].includes(this.chipFamily)&&await this.checkCommand(L,new Array(8).fill(0));let o,n=Math.floor((e+s-1)/s);i=this.chipFamily==p?this.getEraseSize(t,e):e,o=this.IS_STUB?I:Y(te,e);let c=Date.now();return a=ne("<IIII",i,n,s,t),this.chipFamily!=h&&this.chipFamily!=d&&this.chipFamily!=g&&this.chipFamily!=m||(a=a.concat(ne("<I",r?1:0))),this.logger.log("Erase size "+i+", blocks "+n+", block size "+y(s,4)+", offset "+y(t,4)+", encrypted "+(r?"yes":"no")),await this.checkCommand(V,a,0,o),0==e||this.IS_STUB||this.logger.log("Took "+(Date.now()-c)+"ms to erase "+n+" bytes"),n}async flashDeflBegin(e=0,t=0,r=0,i=!1){let a,s=this.getFlashWriteSize(),o=Math.floor((t+s-1)/s),n=Math.floor((e+s-1)/s),c=0,l=0;return this.IS_STUB?(c=e,l=Y(te,c)):(c=n*s,l=I),a=ne("<IIII",c,o,s,r),await this.checkCommand(P,a,0,l),l}async flashFinish(){let e=ne("<I",1);await this.checkCommand(M,e)}async flashDeflFinish(){let e=ne("<I",1);await this.checkCommand(W,e)}getBootloaderOffset(){return w(this.getChipFamily()).flashOffs}async flashId(){return await this.runSpiFlashCommand(159,[],24)}getChipFamily(){return this._parent?this._parent.chipFamily:this.chipFamily}async writeRegister(e,t,r=4294967295,i=0,a=0){let s=ne("<IIII",e,t,r,i);a>0&&s.concat(ne("<IIII",w(this.getChipFamily()).uartDateReg,0,0,a)),await this.checkCommand(O,s)}async setDataLengths(e,t,r){if(-1!=e.mosiDlenOffs){let i=e.regBase+e.mosiDlenOffs,a=e.regBase+e.misoDlenOffs;t>0&&await this.writeRegister(i,t-1),r>0&&await this.writeRegister(a,r-1)}else{let i=e.regBase+e.usr1Offs,a=(0==r?0:r-1)<<8|(0==t?0:t-1)<<17;await this.writeRegister(i,a)}}async waitDone(e,t){for(let r=0;r<10;r++){if(0==(await this.readRegister(e)&t))return}throw Error("SPI command did not complete in time")}async runSpiFlashCommand(e,t,r=0){let i=w(this.getChipFamily()),a=i.regBase,s=a,o=a+i.usrOffs,n=a+i.usr2Offs,c=a+i.w0Offs,l=1<<18;if(r>32)throw new Error("Reading more than 32 bits back from a SPI flash operation is unsupported");if(t.length>64)throw new Error("Writing more than 64 bytes of data with one SPI command is unsupported");let h=8*t.length,d=await this.readRegister(o),g=await this.readRegister(n),p=1<<31;if(r>0&&(p|=268435456),h>0&&(p|=134217728),await this.setDataLengths(i,h,r),await this.writeRegister(o,p),await this.writeRegister(n,7<<28|e),0==h)await this.writeRegister(c,0);else{t.concat(new Array(t.length%4).fill(0));let e=ce("I".repeat(Math.floor(t.length/4)),t),r=c;this.logger.debug(`Words Length: ${e.length}`);for(const t of e)this.logger.debug(`Writing word ${y(t)} to register offset ${y(r)}`),await this.writeRegister(r,t),r+=4}await this.writeRegister(s,l),await this.waitDone(s,l);let m=await this.readRegister(c);return await this.writeRegister(o,d),await this.writeRegister(n,g),m}async detectFlashSize(){this.logger.log("Detecting Flash Size");let e=await this.flashId(),t=255&e,r=e>>16&255;this.logger.log(`FlashId: ${y(e)}`),this.logger.log(`Flash Manufacturer: ${t.toString(16)}`),this.logger.log(`Flash Device: ${(e>>8&255).toString(16)}${r.toString(16)}`),this.flashSize=j[r],this.logger.log(`Auto-detected Flash size: ${this.flashSize}`)}getEraseSize(e,t){let r=Z,i=Math.floor((t+r-1)/r),a=16-Math.floor(e/r)%16;return i<a&&(a=i),i<2*a?Math.floor((i+1)/2*r):(i-a)*r}async memBegin(e,t,r,i){return await this.checkCommand(q,ne("<IIII",e,t,r,i))}async memBlock(e,t){return await this.checkCommand(N,ne("<IIII",e.length,t,0,0).concat(e),this.checksum(e))}async memFinish(e=0){let t=this.IS_STUB?I:H,r=ne("<II",0==e?1:0,e);return await this.checkCommand(Q,r,0,t)}async runStub(){const e=await se(this.chipFamily);let t,r=ee;this.logger.log("Uploading stub...");for(let t of["text","data"])if(Object.keys(e).includes(t)){let i=e[t+"_start"],a=e[t].length,s=Math.floor((a+r-1)/r);await this.memBegin(a,s,r,i);for(let i of Array(s).keys()){let s=i*r,o=s+r;o>a&&(o=a),await this.memBlock(e[t].slice(s,o),i)}}this.logger.log("Running stub..."),await this.memFinish(e.entry);const i=await this.readPacket(500);if(t=String.fromCharCode(...i),"OHAI"!=t)throw new Error("Failed to start stub. Unexpected response: "+t);this.logger.log("Stub is now running...");const a=new he(this.port,this.logger,this);return await a.detectFlashSize(),a}async writeToStream(e){const t=this.port.writable.getWriter();await t.write(new Uint8Array(e));try{t.releaseLock()}catch(e){console.error("Ignoring release lock error",e)}}async disconnect(){this._parent?await this._parent.disconnect():(await this.port.writable.getWriter().close(),await new Promise((e=>{this._reader||e(void 0),this.addEventListener("disconnect",e,{once:!0}),this._reader.cancel()})),this.connected=!1)}}class he extends le{constructor(){super(...arguments),this.IS_STUB=!0}async memBegin(e,t,r,i){let a=await se(this.chipFamily),s=i,o=i+e;console.log(s,o),console.log(a.data_start,a.data.length,a.text_start,a.text.length);for(let[e,t]of[[a.data_start,a.data_start+a.data.length],[a.text_start,a.text_start+a.text.length]])if(s<t&&o>e)throw new Error("Software loader is resident at "+y(e,8)+"-"+y(t,8)+". Can't load binary at overlapping address range "+y(s,8)+"-"+y(o,8)+". Try changing the binary loading address.")}async eraseFlash(){await this.checkCommand(G,[],0,J)}}const de=async e=>{const t=await navigator.serial.requestPort();return e.log("Connecting..."),await t.open({baudRate:F}),e.log("Connected successfully."),new le(t,e)},ge=async e=>{import("./c.274132bb.js");const t=document.createElement("esphome-no-port-picked-dialog");return t.doTryAgain=e,document.body.append(t),!0};export{le as E,de as c,ge as o};
