Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

esp-web-flasher

Package Overview
Dependencies
Maintainers
1
Versions
20
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

esp-web-flasher - npm Package Compare versions

Comparing version 2.1.0 to 2.1.1

1

dist/esp_loader.d.ts

@@ -73,2 +73,3 @@ /// <reference types="w3c-web-serial" />

setBaudrate(baud: number): Promise<void>;
reconfigurePort(baud: number): Promise<void>;
/**

@@ -75,0 +76,0 @@ * @name sync

20

dist/esp_loader.js

@@ -1,2 +0,2 @@

import { CHIP_FAMILY_ESP32, CHIP_FAMILY_ESP32S2, CHIP_FAMILY_ESP8266, MAX_TIMEOUT, DEFAULT_TIMEOUT, ERASE_REGION_TIMEOUT_PER_MB, ESP32S2_DATAREGVALUE, ESP32_DATAREGVALUE, ESP8266_DATAREGVALUE, ESP_CHANGE_BAUDRATE, ESP_CHECKSUM_MAGIC, ESP_FLASH_BEGIN, ESP_FLASH_DATA, ESP_FLASH_END, ESP_MEM_BEGIN, ESP_MEM_DATA, ESP_MEM_END, ESP_READ_REG, ESP_SPI_ATTACH, ESP_SPI_SET_PARAMS, ESP_SYNC, FLASH_SECTOR_SIZE, FLASH_WRITE_SIZE, STUB_FLASH_WRITE_SIZE, MEM_END_ROM_TIMEOUT, ROM_INVALID_RECV_MSG, SYNC_PACKET, SYNC_TIMEOUT, USB_RAM_BLOCK, ESP_ERASE_FLASH, CHIP_ERASE_TIMEOUT, timeoutPerMb, } from "./const";
import { CHIP_FAMILY_ESP32, CHIP_FAMILY_ESP32S2, CHIP_FAMILY_ESP8266, MAX_TIMEOUT, DEFAULT_TIMEOUT, ERASE_REGION_TIMEOUT_PER_MB, ESP32S2_DATAREGVALUE, ESP32_DATAREGVALUE, ESP8266_DATAREGVALUE, ESP_CHANGE_BAUDRATE, ESP_CHECKSUM_MAGIC, ESP_FLASH_BEGIN, ESP_FLASH_DATA, ESP_FLASH_END, ESP_MEM_BEGIN, ESP_MEM_DATA, ESP_MEM_END, ESP_READ_REG, ESP_SPI_ATTACH, ESP_SPI_SET_PARAMS, ESP_SYNC, FLASH_SECTOR_SIZE, FLASH_WRITE_SIZE, STUB_FLASH_WRITE_SIZE, MEM_END_ROM_TIMEOUT, ROM_INVALID_RECV_MSG, SYNC_PACKET, SYNC_TIMEOUT, USB_RAM_BLOCK, ESP_ERASE_FLASH, CHIP_ERASE_TIMEOUT, timeoutPerMb, ESP_ROM_BAUD, } from "./const";
import { getStubCode } from "./stubs";

@@ -396,7 +396,2 @@ import { pack, sleep, slipEncode, toHex, unpack } from "./util";

async setBaudrate(baud) {
var _a, _b;
if (this._parent) {
await this._parent.setBaudrate(baud);
return;
}
if (this.chipFamily == CHIP_FAMILY_ESP8266) {

@@ -407,4 +402,4 @@ throw new Error("Changing baud rate is not supported on the ESP8266");

try {
// Send 115200 as the old one, otherwise the STUB seems to not work properly after changing the baud rate.
let buffer = pack("<II", baud, 115200);
// Send ESP_ROM_BAUD(115200) as the old one if running STUB otherwise 0
let buffer = pack("<II", baud, this.IS_STUB ? ESP_ROM_BAUD : 0);
await this.checkCommand(ESP_CHANGE_BAUDRATE, buffer);

@@ -416,2 +411,11 @@ }

}
if (this._parent) {
await this._parent.reconfigurePort(baud);
}
else {
await this.reconfigurePort(baud);
}
}
async reconfigurePort(baud) {
var _a, _b;
try {

@@ -418,0 +422,0 @@ // SerialPort does not allow to be reconfigured while open so we close and re-open

@@ -1,1 +0,1 @@

const t=t=>{let e=[];for(let i of t)219==i?e=e.concat([219,221]):192==i?e=e.concat([219,220]):e.push(i);return e},e=t=>{let e=[];for(let i=0;i<t.length;i++){let a=t.charCodeAt(i);a<=255&&e.push(a)}return e},i=(t,...e)=>{let i=0;if(t.replace(/[<>]/,"").length!=e.length)throw new Error("Pack format to Argument count mismatch");let a=[],s=!0;const r=(t,e)=>{for(let i=0;i<e;i++)s?a.push(t>>8*i&255):a.push(t>>8*(e-i)&255)};for(let a=0;a<t.length;a++)if("<"==t[a])s=!0;else if(">"==t[a])s=!1;else if("B"==t[a])r(e[i],1),i++;else if("H"==t[a])r(e[i],2),i++;else{if("I"!=t[a])throw new Error(`Unhandled character "${t[a]}" in pack format`);r(e[i],4),i++}return a},a=(t,e=2)=>"0x"+t.toString(16).toUpperCase().padStart(e,"0"),s=t=>new Promise((e=>setTimeout(e,t))),r=e(" UUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUU"),n=33382,h=50,o=12882,l=async t=>{let i;return t==h?i=await import("./esp32-9a0a29d9.js"):t==o?i=await import("./esp32s2-70924167.js"):33382==t&&(i=await import("./esp8266-695df45b.js")),{...i,text:e(atob(i.text)),data:e(atob(i.data))}};class c extends EventTarget{constructor(t,e,i){super(),this.port=t,this.logger=e,this._parent=i,this.chipName=null,this._efuses=new Array(4).fill(0),this._flashsize=4194304,this.debug=!1,this.IS_STUB=!1,this.connected=!0,this.stopReadLoop=!1}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 t,e=await this.readRegister(1610612856);if(353510656==e)this.chipFamily=h;else if(401408==e)this.chipFamily=33382;else{if(1280!=e)throw new Error("Unknown Chip.");this.chipFamily=o}33382==this.chipFamily?t=1072693328:(this.chipFamily==h||this.chipFamily==o)&&(t=1610719232);for(let e=0;e<4;e++)this._efuses[e]=await this.readRegister(t+4*e);this.chipFamily==h&&(this.chipName="ESP32"),this.chipFamily==o&&(this.chipName="ESP32-S2"),33382==this.chipFamily&&(16&this._efuses[0]||65536&this._efuses[2]?this.chipName="ESP8285":this.chipName="ESP8266EX")}async readLoop(){this.logger.debug("Starting read loop"),this._reader=this.port.readable.getReader();try{for(;!this.stopReadLoop;){const{value:t,done:e}=await this._reader.read();if(e){this._reader.releaseLock();break}t&&0!==t.length&&this._inputBuffer.push(...Array.from(t))}}catch(t){console.error("Read loop got disconnected"),this.connected=!1,this.dispatchEvent(new Event("disconnect"))}this.logger.debug("Finished read loop")}async hardReset(t=!1){this.logger.log("Try hard reset."),await this.port.setSignals({dataTerminalReady:!1,requestToSend:!0}),await this.port.setSignals({dataTerminalReady:t,requestToSend:!1}),await new Promise((t=>setTimeout(t,1e3)))}macAddr(){let t,e=new Array(6).fill(0),i=this._efuses[0],a=this._efuses[1],s=this._efuses[2],r=this._efuses[3];if(33382==this.chipFamily){if(0!=r)t=[r>>16&255,r>>8&255,255&r];else if(0==(a>>16&255))t=[24,254,52];else{if(1!=(a>>16&255))throw new Error("Couldnt determine OUI");t=[172,208,116]}e[0]=t[0],e[1]=t[1],e[2]=t[2],e[3]=a>>8&255,e[4]=255&a,e[5]=i>>24&255}else if(this.chipFamily==h)e[0]=s>>8&255,e[1]=255&s,e[2]=a>>24&255,e[3]=a>>16&255,e[4]=a>>8&255,e[5]=255&a;else{if(this.chipFamily!=o)throw new Error("Unknown chip family");e[0]=s>>8&255,e[1]=255&s,e[2]=a>>24&255,e[3]=a>>16&255,e[4]=a>>8&255,e[5]=255&a}return e}async readRegister(t){this.debug&&this.logger.debug("Reading Register",t);let e=i("I",t);return((t,e)=>{let i=0,a=[];for(let s of t)if("B"==s)a.push(255&e[i]),i+=1;else if("H"==s)a.push(255&e[i]|(255&e[i+1])<<8),i+=2;else{if("I"!=s)throw new Error(`Unhandled character "${s}" in unpack format`);a.push(255&e[i]|(255&e[i+1])<<8|(255&e[i+2])<<16|(255&e[i+3])<<24),i+=4}return a})("I",(await this.checkCommand(10,e))[0])[0]}async checkCommand(t,e,i=0,s=3e3){s=Math.min(s,12e5),await this.sendCommand(t,e,i);let[r,n]=await this.getResponse(t,s);if(null===n)throw new Error("Didn't get enough status bytes");let l=0;if(this.IS_STUB||33382==this.chipFamily?l=2:[h,o].includes(this.chipFamily)?l=4:[2,4].includes(n.length)&&(l=n.length),n.length<l)throw new Error("Didn't get enough status bytes");let c=n.slice(-l,n.length);if(n=n.slice(0,-l),this.debug&&(this.logger.debug("status",c),this.logger.debug("value",r),this.logger.debug("data",n)),1==c[0])throw 5==c[1]?new Error("Invalid (unsupported) command "+a(t)):new Error("Command failure error code "+a(c[1]));return[r,n]}async sendCommand(e,a,s=0){this._inputBuffer.length=0;let r=[192,0];r.push(e),r=r.concat(i("H",a.length)),r=r.concat(t(i("I",s))),r=r.concat(t(a)),r.push(192),this.debug&&this.logger.debug("Writing "+r.length+" byte"+(1==r.length?"":"s")+":",r),await this.writeToStream(r)}async getResponse(t,e=3e3){let i=[],a=0,r=!1,n=Date.now();for(;Date.now()-n<e;){if(this._inputBuffer.length>0){let t=this._inputBuffer.shift();219==t?r=!0:r?(221==t?i.push(220):220==t?i.push(192):i=i.concat([219,t]),r=!1):i.push(t)}else await s(10);if(i.length>0&&192!=i[0]&&i.shift(),i.length>1&&1!=i[1]&&i.shift(),i.length>2&&i[2]!=t&&i.shift(),i.length>4&&(a=i[3]+(i[4]<<8)),i.length==a+10)break}if(i.length!=a+10)return this.logger.log("Timed out after "+e+" milliseconds"),[null,null];this.debug&&this.logger.debug("Reading "+i.length+" byte"+(1==i.length?"":"s")+":",i);let h=i.slice(5,9),o=i.slice(9,-1);return this.debug&&this.logger.debug("value:",h,"data:",o),[h,o]}async readBuffer(t=3e3){let e=[],i=!1,a=Date.now();for(;Date.now()-a<t;){if(this._inputBuffer.length>0){let t=this._inputBuffer.shift();219==t?i=!0:i?(221==t?e.push(220):220==t?e.push(192):e=e.concat([219,t]),i=!1):e.push(t)}else await s(10);if(e.length>0&&192!=e[0]&&e.shift(),e.length>1&&192==e[e.length-1])break}if(e.length<2)return this.logger.log("Timed out after "+t+" milliseconds"),null;this.debug&&this.logger.debug("Reading "+e.length+" byte"+(1==e.length?"":"s")+":",e);let r=e.slice(1,-1);return this.debug&&this.logger.debug("data:",r),r}checksum(t,e=239){for(let i of t)e^=i;return e}async setBaudrate(t){var e,a;if(this._parent)await this._parent.setBaudrate(t);else{if(33382==this.chipFamily)throw new Error("Changing baud rate is not supported on the ESP8266");this.logger.log("Attempting to change baud rate to "+t+"...");try{let e=i("<II",t,115200);await this.checkCommand(15,e)}catch(e){throw console.error(e),new Error(`Unable to change the baud rate to ${t}: No response from set baud rate command.`)}try{this.stopReadLoop=!0,await(null===(e=this._reader)||void 0===e?void 0:e.cancel()),null===(a=this._reader)||void 0===a||a.releaseLock(),await this.port.close(),await this.port.open({baudRate:t}),this.stopReadLoop=!1,this.readLoop(),this.logger.log(`Changed baud rate to ${t}`)}catch(e){throw console.error(e),new Error(`Unable to change the baud rate to ${t}: ${e}`)}}}async sync(){for(let t=0;t<5;t++){if(await this._sync())return await s(100),!0;await s(100)}throw new Error("Couldn't sync to ESP. Try resetting.")}async _sync(){await this.sendCommand(8,r);for(let t=0;t<8;t++){let[t,e]=await this.getResponse(8,100);if(null!==e&&(e.length>1&&0==e[0]&&0==e[1]))return!0}return!1}getFlashWriteSize(){return this.IS_STUB?16384:1024}async flashData(t,e,i=0){let a=t.byteLength;this.logger.log("Writing data with filesize:"+a),await this.flashBegin(a,i);let s=[],r=0,n=0,h=0,o=Date.now(),l=this.getFlashWriteSize();for(;a-h>0;)a-h>=l?s=Array.from(new Uint8Array(t,h,l)):(s=Array.from(new Uint8Array(t,h,a-h)),s=s.concat(new Array(l-s.length).fill(255))),await this.flashBlock(s,r,2e3),r+=1,n+=s.length,h+=l,e(n);this.logger.log("Took "+(Date.now()-o)+"ms to write "+a+" bytes")}async flashBlock(t,e,a=100){await this.checkCommand(3,i("<IIII",t.length,e,0,0).concat(t),this.checksum(t),a)}async flashBegin(t=0,e=0,s=!1){let r,n,l=this.getFlashWriteSize();[h,o].includes(this.chipFamily)&&await this.checkCommand(13,new Array(8).fill(0)),this.chipFamily==h&&(n=i("<IIIIII",0,this._flashsize,65536,4096,256,65535),await this.checkCommand(11,n));let c,g=Math.floor((t+l-1)/l);r=33382==this.chipFamily?this.getEraseSize(e,t):t,c=this.IS_STUB?3e3:((t,e)=>{let i=Math.floor(t*(e/486));return i<3e3?3e3:i})(3e4,t);let d=Date.now();return n=i("<IIII",r,g,l,e),this.chipFamily==o&&(n=n.concat(i("<I",s?1:0))),this.logger.log("Erase size "+r+", blocks "+g+", block size "+l+", offset "+a(e,4)+", encrypted "+(s?"yes":"no")),await this.checkCommand(2,n,0,c),0==t||this.IS_STUB||this.logger.log("Took "+(Date.now()-d)+"ms to erase "+g+" bytes"),g}async flashFinish(){let t=i("<I",1);await this.checkCommand(4,t)}getEraseSize(t,e){let i=4096,a=Math.floor((e+i-1)/i),s=16-Math.floor(t/i)%16;return a<s&&(s=a),a<2*s?Math.floor((a+1)/2*i):(a-s)*i}async memBegin(t,e,a,s){return await this.checkCommand(5,i("<IIII",t,e,a,s))}async memBlock(t,e){return await this.checkCommand(7,i("<IIII",t.length,e,0,0).concat(t),this.checksum(t))}async memFinish(t=0){let e=this.IS_STUB?3e3:50,a=i("<II",0==t?1:0,t);return await this.checkCommand(6,a,0,e)}async runStub(){const t=await l(this.chipFamily);let e=2048;this.logger.log("Uploading stub...");for(let i of["text","data"])if(Object.keys(t).includes(i)){let a=t[i+"_start"],s=t[i].length,r=Math.floor((s+e-1)/e);await this.memBegin(s,r,e,a);for(let a of Array(r).keys()){let r=a*e,n=r+e;n>s&&(n=s),await this.memBlock(t[i].slice(r,n),a)}}this.logger.log("Running stub..."),await this.memFinish(t.entry);const i=await this.readBuffer(100),a=String.fromCharCode(...i);if("OHAI"!=a)throw new Error("Failed to start stub. Unexpected response: "+a);this.logger.log("Stub is now running...");return new g(this.port,this.logger,this)}async writeToStream(t){const e=this.port.writable.getWriter();await e.write(new Uint8Array(t));try{e.releaseLock()}catch(t){console.error("Ignoring release lock error",t)}}async disconnect(){this._parent?await this._parent.disconnect():(this._reader&&await this._reader.cancel(),await this.port.writable.getWriter().close(),await this.port.close(),this.connected=!1)}}class g extends c{constructor(){super(...arguments),this.IS_STUB=!0}async memBegin(t,e,i,s){let r=await l(this.chipFamily),n=s,h=s+t;console.log(n,h),console.log(r.data_start,r.data.length,r.text_start,r.text.length);for(let[t,e]of[[r.data_start,r.data_start+r.data.length],[r.text_start,r.text_start+r.text.length]])if(n<e&&h>t)throw new Error("Software loader is resident at "+a(t,8)+"-"+a(e,8)+". Can't load binary at overlapping address range "+a(n,8)+"-"+a(h,8)+". Try changing the binary loading address.")}async eraseFlash(){await this.checkCommand(208,[],0,6e5)}}const d=async t=>{const e=await navigator.serial.requestPort();return t.log("Connecting..."),await e.open({baudRate:115200}),t.log("Connected successfully."),new c(e,t)};export{h as CHIP_FAMILY_ESP32,o as CHIP_FAMILY_ESP32S2,n as CHIP_FAMILY_ESP8266,c as ESPLoader,d as connect};
const t=t=>{let e=[];for(let i of t)219==i?e=e.concat([219,221]):192==i?e=e.concat([219,220]):e.push(i);return e},e=t=>{let e=[];for(let i=0;i<t.length;i++){let a=t.charCodeAt(i);a<=255&&e.push(a)}return e},i=(t,...e)=>{let i=0;if(t.replace(/[<>]/,"").length!=e.length)throw new Error("Pack format to Argument count mismatch");let a=[],s=!0;const r=(t,e)=>{for(let i=0;i<e;i++)s?a.push(t>>8*i&255):a.push(t>>8*(e-i)&255)};for(let a=0;a<t.length;a++)if("<"==t[a])s=!0;else if(">"==t[a])s=!1;else if("B"==t[a])r(e[i],1),i++;else if("H"==t[a])r(e[i],2),i++;else{if("I"!=t[a])throw new Error(`Unhandled character "${t[a]}" in pack format`);r(e[i],4),i++}return a},a=(t,e=2)=>"0x"+t.toString(16).toUpperCase().padStart(e,"0"),s=t=>new Promise((e=>setTimeout(e,t))),r=e(" UUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUU"),n=33382,h=50,o=12882,l=async t=>{let i;return t==h?i=await import("./esp32-9a0a29d9.js"):t==o?i=await import("./esp32s2-70924167.js"):33382==t&&(i=await import("./esp8266-695df45b.js")),{...i,text:e(atob(i.text)),data:e(atob(i.data))}};class c extends EventTarget{constructor(t,e,i){super(),this.port=t,this.logger=e,this._parent=i,this.chipName=null,this._efuses=new Array(4).fill(0),this._flashsize=4194304,this.debug=!1,this.IS_STUB=!1,this.connected=!0,this.stopReadLoop=!1}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 t,e=await this.readRegister(1610612856);if(353510656==e)this.chipFamily=h;else if(401408==e)this.chipFamily=33382;else{if(1280!=e)throw new Error("Unknown Chip.");this.chipFamily=o}33382==this.chipFamily?t=1072693328:(this.chipFamily==h||this.chipFamily==o)&&(t=1610719232);for(let e=0;e<4;e++)this._efuses[e]=await this.readRegister(t+4*e);this.chipFamily==h&&(this.chipName="ESP32"),this.chipFamily==o&&(this.chipName="ESP32-S2"),33382==this.chipFamily&&(16&this._efuses[0]||65536&this._efuses[2]?this.chipName="ESP8285":this.chipName="ESP8266EX")}async readLoop(){this.logger.debug("Starting read loop"),this._reader=this.port.readable.getReader();try{for(;!this.stopReadLoop;){const{value:t,done:e}=await this._reader.read();if(e){this._reader.releaseLock();break}t&&0!==t.length&&this._inputBuffer.push(...Array.from(t))}}catch(t){console.error("Read loop got disconnected"),this.connected=!1,this.dispatchEvent(new Event("disconnect"))}this.logger.debug("Finished read loop")}async hardReset(t=!1){this.logger.log("Try hard reset."),await this.port.setSignals({dataTerminalReady:!1,requestToSend:!0}),await this.port.setSignals({dataTerminalReady:t,requestToSend:!1}),await new Promise((t=>setTimeout(t,1e3)))}macAddr(){let t,e=new Array(6).fill(0),i=this._efuses[0],a=this._efuses[1],s=this._efuses[2],r=this._efuses[3];if(33382==this.chipFamily){if(0!=r)t=[r>>16&255,r>>8&255,255&r];else if(0==(a>>16&255))t=[24,254,52];else{if(1!=(a>>16&255))throw new Error("Couldnt determine OUI");t=[172,208,116]}e[0]=t[0],e[1]=t[1],e[2]=t[2],e[3]=a>>8&255,e[4]=255&a,e[5]=i>>24&255}else if(this.chipFamily==h)e[0]=s>>8&255,e[1]=255&s,e[2]=a>>24&255,e[3]=a>>16&255,e[4]=a>>8&255,e[5]=255&a;else{if(this.chipFamily!=o)throw new Error("Unknown chip family");e[0]=s>>8&255,e[1]=255&s,e[2]=a>>24&255,e[3]=a>>16&255,e[4]=a>>8&255,e[5]=255&a}return e}async readRegister(t){this.debug&&this.logger.debug("Reading Register",t);let e=i("I",t);return((t,e)=>{let i=0,a=[];for(let s of t)if("B"==s)a.push(255&e[i]),i+=1;else if("H"==s)a.push(255&e[i]|(255&e[i+1])<<8),i+=2;else{if("I"!=s)throw new Error(`Unhandled character "${s}" in unpack format`);a.push(255&e[i]|(255&e[i+1])<<8|(255&e[i+2])<<16|(255&e[i+3])<<24),i+=4}return a})("I",(await this.checkCommand(10,e))[0])[0]}async checkCommand(t,e,i=0,s=3e3){s=Math.min(s,12e5),await this.sendCommand(t,e,i);let[r,n]=await this.getResponse(t,s);if(null===n)throw new Error("Didn't get enough status bytes");let l=0;if(this.IS_STUB||33382==this.chipFamily?l=2:[h,o].includes(this.chipFamily)?l=4:[2,4].includes(n.length)&&(l=n.length),n.length<l)throw new Error("Didn't get enough status bytes");let c=n.slice(-l,n.length);if(n=n.slice(0,-l),this.debug&&(this.logger.debug("status",c),this.logger.debug("value",r),this.logger.debug("data",n)),1==c[0])throw 5==c[1]?new Error("Invalid (unsupported) command "+a(t)):new Error("Command failure error code "+a(c[1]));return[r,n]}async sendCommand(e,a,s=0){this._inputBuffer.length=0;let r=[192,0];r.push(e),r=r.concat(i("H",a.length)),r=r.concat(t(i("I",s))),r=r.concat(t(a)),r.push(192),this.debug&&this.logger.debug("Writing "+r.length+" byte"+(1==r.length?"":"s")+":",r),await this.writeToStream(r)}async getResponse(t,e=3e3){let i=[],a=0,r=!1,n=Date.now();for(;Date.now()-n<e;){if(this._inputBuffer.length>0){let t=this._inputBuffer.shift();219==t?r=!0:r?(221==t?i.push(220):220==t?i.push(192):i=i.concat([219,t]),r=!1):i.push(t)}else await s(10);if(i.length>0&&192!=i[0]&&i.shift(),i.length>1&&1!=i[1]&&i.shift(),i.length>2&&i[2]!=t&&i.shift(),i.length>4&&(a=i[3]+(i[4]<<8)),i.length==a+10)break}if(i.length!=a+10)return this.logger.log("Timed out after "+e+" milliseconds"),[null,null];this.debug&&this.logger.debug("Reading "+i.length+" byte"+(1==i.length?"":"s")+":",i);let h=i.slice(5,9),o=i.slice(9,-1);return this.debug&&this.logger.debug("value:",h,"data:",o),[h,o]}async readBuffer(t=3e3){let e=[],i=!1,a=Date.now();for(;Date.now()-a<t;){if(this._inputBuffer.length>0){let t=this._inputBuffer.shift();219==t?i=!0:i?(221==t?e.push(220):220==t?e.push(192):e=e.concat([219,t]),i=!1):e.push(t)}else await s(10);if(e.length>0&&192!=e[0]&&e.shift(),e.length>1&&192==e[e.length-1])break}if(e.length<2)return this.logger.log("Timed out after "+t+" milliseconds"),null;this.debug&&this.logger.debug("Reading "+e.length+" byte"+(1==e.length?"":"s")+":",e);let r=e.slice(1,-1);return this.debug&&this.logger.debug("data:",r),r}checksum(t,e=239){for(let i of t)e^=i;return e}async setBaudrate(t){if(33382==this.chipFamily)throw new Error("Changing baud rate is not supported on the ESP8266");this.logger.log("Attempting to change baud rate to "+t+"...");try{let e=i("<II",t,this.IS_STUB?115200:0);await this.checkCommand(15,e)}catch(e){throw console.error(e),new Error(`Unable to change the baud rate to ${t}: No response from set baud rate command.`)}this._parent?await this._parent.reconfigurePort(t):await this.reconfigurePort(t)}async reconfigurePort(t){var e,i;try{this.stopReadLoop=!0,await(null===(e=this._reader)||void 0===e?void 0:e.cancel()),null===(i=this._reader)||void 0===i||i.releaseLock(),await this.port.close(),await this.port.open({baudRate:t}),this.stopReadLoop=!1,this.readLoop(),this.logger.log(`Changed baud rate to ${t}`)}catch(e){throw console.error(e),new Error(`Unable to change the baud rate to ${t}: ${e}`)}}async sync(){for(let t=0;t<5;t++){if(await this._sync())return await s(100),!0;await s(100)}throw new Error("Couldn't sync to ESP. Try resetting.")}async _sync(){await this.sendCommand(8,r);for(let t=0;t<8;t++){let[t,e]=await this.getResponse(8,100);if(null!==e&&(e.length>1&&0==e[0]&&0==e[1]))return!0}return!1}getFlashWriteSize(){return this.IS_STUB?16384:1024}async flashData(t,e,i=0){let a=t.byteLength;this.logger.log("Writing data with filesize:"+a),await this.flashBegin(a,i);let s=[],r=0,n=0,h=0,o=Date.now(),l=this.getFlashWriteSize();for(;a-h>0;)a-h>=l?s=Array.from(new Uint8Array(t,h,l)):(s=Array.from(new Uint8Array(t,h,a-h)),s=s.concat(new Array(l-s.length).fill(255))),await this.flashBlock(s,r,2e3),r+=1,n+=s.length,h+=l,e(n);this.logger.log("Took "+(Date.now()-o)+"ms to write "+a+" bytes")}async flashBlock(t,e,a=100){await this.checkCommand(3,i("<IIII",t.length,e,0,0).concat(t),this.checksum(t),a)}async flashBegin(t=0,e=0,s=!1){let r,n,l=this.getFlashWriteSize();[h,o].includes(this.chipFamily)&&await this.checkCommand(13,new Array(8).fill(0)),this.chipFamily==h&&(n=i("<IIIIII",0,this._flashsize,65536,4096,256,65535),await this.checkCommand(11,n));let c,g=Math.floor((t+l-1)/l);r=33382==this.chipFamily?this.getEraseSize(e,t):t,c=this.IS_STUB?3e3:((t,e)=>{let i=Math.floor(t*(e/486));return i<3e3?3e3:i})(3e4,t);let d=Date.now();return n=i("<IIII",r,g,l,e),this.chipFamily==o&&(n=n.concat(i("<I",s?1:0))),this.logger.log("Erase size "+r+", blocks "+g+", block size "+l+", offset "+a(e,4)+", encrypted "+(s?"yes":"no")),await this.checkCommand(2,n,0,c),0==t||this.IS_STUB||this.logger.log("Took "+(Date.now()-d)+"ms to erase "+g+" bytes"),g}async flashFinish(){let t=i("<I",1);await this.checkCommand(4,t)}getEraseSize(t,e){let i=4096,a=Math.floor((e+i-1)/i),s=16-Math.floor(t/i)%16;return a<s&&(s=a),a<2*s?Math.floor((a+1)/2*i):(a-s)*i}async memBegin(t,e,a,s){return await this.checkCommand(5,i("<IIII",t,e,a,s))}async memBlock(t,e){return await this.checkCommand(7,i("<IIII",t.length,e,0,0).concat(t),this.checksum(t))}async memFinish(t=0){let e=this.IS_STUB?3e3:50,a=i("<II",0==t?1:0,t);return await this.checkCommand(6,a,0,e)}async runStub(){const t=await l(this.chipFamily);let e=2048;this.logger.log("Uploading stub...");for(let i of["text","data"])if(Object.keys(t).includes(i)){let a=t[i+"_start"],s=t[i].length,r=Math.floor((s+e-1)/e);await this.memBegin(s,r,e,a);for(let a of Array(r).keys()){let r=a*e,n=r+e;n>s&&(n=s),await this.memBlock(t[i].slice(r,n),a)}}this.logger.log("Running stub..."),await this.memFinish(t.entry);const i=await this.readBuffer(100),a=String.fromCharCode(...i);if("OHAI"!=a)throw new Error("Failed to start stub. Unexpected response: "+a);this.logger.log("Stub is now running...");return new g(this.port,this.logger,this)}async writeToStream(t){const e=this.port.writable.getWriter();await e.write(new Uint8Array(t));try{e.releaseLock()}catch(t){console.error("Ignoring release lock error",t)}}async disconnect(){this._parent?await this._parent.disconnect():(this._reader&&await this._reader.cancel(),await this.port.writable.getWriter().close(),await this.port.close(),this.connected=!1)}}class g extends c{constructor(){super(...arguments),this.IS_STUB=!0}async memBegin(t,e,i,s){let r=await l(this.chipFamily),n=s,h=s+t;console.log(n,h),console.log(r.data_start,r.data.length,r.text_start,r.text.length);for(let[t,e]of[[r.data_start,r.data_start+r.data.length],[r.text_start,r.text_start+r.text.length]])if(n<e&&h>t)throw new Error("Software loader is resident at "+a(t,8)+"-"+a(e,8)+". Can't load binary at overlapping address range "+a(n,8)+"-"+a(h,8)+". Try changing the binary loading address.")}async eraseFlash(){await this.checkCommand(208,[],0,6e5)}}const d=async t=>{const e=await navigator.serial.requestPort();return t.log("Connecting..."),await e.open({baudRate:115200}),t.log("Connected successfully."),new c(e,t)};export{h as CHIP_FAMILY_ESP32,o as CHIP_FAMILY_ESP32S2,n as CHIP_FAMILY_ESP8266,c as ESPLoader,d as connect};
{
"name": "esp-web-flasher",
"version": "2.1.0",
"version": "2.1.1",
"description": "Flash ESP devices using WebSerial",

@@ -5,0 +5,0 @@ "main": "dist/index.js",

@@ -36,2 +36,3 @@ import {

timeoutPerMb,
ESP_ROM_BAUD,
} from "./const";

@@ -454,7 +455,2 @@ import { getStubCode } from "./stubs";

async setBaudrate(baud: number) {
if (this._parent) {
await this._parent.setBaudrate(baud);
return;
}
if (this.chipFamily == CHIP_FAMILY_ESP8266) {

@@ -467,4 +463,4 @@ throw new Error("Changing baud rate is not supported on the ESP8266");

try {
// Send 115200 as the old one, otherwise the STUB seems to not work properly after changing the baud rate.
let buffer = pack("<II", baud, 115200);
// Send ESP_ROM_BAUD(115200) as the old one if running STUB otherwise 0
let buffer = pack("<II", baud, this.IS_STUB ? ESP_ROM_BAUD : 0);
await this.checkCommand(ESP_CHANGE_BAUDRATE, buffer);

@@ -478,2 +474,10 @@ } catch (e) {

if (this._parent) {
await this._parent.reconfigurePort(baud);
} else {
await this.reconfigurePort(baud);
}
}
async reconfigurePort(baud: number) {
try {

@@ -480,0 +484,0 @@ // SerialPort does not allow to be reconfigured while open so we close and re-open

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc