import { Logger, ChipFamily, SpiFlashAddresses } from "./const"; export declare class ESPLoader extends EventTarget { port: SerialPort; logger: Logger; private _parent?; __chipFamily?: ChipFamily; __chipName: string | null; __chipRevision: number | null; __chipVariant: string | null; _efuses: any[]; _flashsize: number; debug: boolean; IS_STUB: boolean; connected: boolean; flashSize: string | null; __inputBuffer?: number[]; __inputBufferReadIndex?: number; __totalBytesRead?: number; currentBaudRate: number; private _maxUSBSerialBaudrate?; __reader?: ReadableStreamDefaultReader; private SLIP_END; private SLIP_ESC; private SLIP_ESC_END; private SLIP_ESC_ESC; private _isESP32S2NativeUSB; private _initializationSucceeded; private __commandLock; private __isReconfiguring; private __abandonCurrentOperation; private _suppressDisconnect; private __consoleMode; _isUsbJtagOrOtg: boolean | undefined; /** * Check if device is using USB-JTAG or USB-OTG (not external serial chip) * Returns undefined if not yet determined */ get isUsbJtagOrOtg(): boolean | undefined; private __adaptiveBlockMultiplier; private __adaptiveMaxInFlightMultiplier; private __consecutiveSuccessfulChunks; private __lastAdaptiveAdjustment; private __isCDCDevice; constructor(port: SerialPort, logger: Logger, _parent?: ESPLoader | undefined); get chipFamily(): ChipFamily; set chipFamily(value: ChipFamily); get chipName(): string | null; set chipName(value: string | null); get chipRevision(): number | null; set chipRevision(value: number | null); get chipVariant(): string | null; set chipVariant(value: string | null); private get _consoleMode(); private set _consoleMode(value); setConsoleMode(value: boolean): void; private get _inputBuffer(); private get _inputBufferReadIndex(); private set _inputBufferReadIndex(value); private get _inputBufferAvailable(); private _readByte; private _clearInputBuffer; private _compactInputBuffer; private get _totalBytesRead(); private set _totalBytesRead(value); private get _commandLock(); private set _commandLock(value); private get _isReconfiguring(); private set _isReconfiguring(value); private get _abandonCurrentOperation(); private set _abandonCurrentOperation(value); private get _adaptiveBlockMultiplier(); private set _adaptiveBlockMultiplier(value); private get _adaptiveMaxInFlightMultiplier(); private set _adaptiveMaxInFlightMultiplier(value); private get _consecutiveSuccessfulChunks(); private set _consecutiveSuccessfulChunks(value); private get _lastAdaptiveAdjustment(); private set _lastAdaptiveAdjustment(value); private get _isCDCDevice(); private set _isCDCDevice(value); private detectUSBSerialChip; initialize(): Promise; /** * Detect chip type using GET_SECURITY_INFO (for newer chips) or magic value (for older chips) */ detectChip(): Promise; getChipRevision(): Promise; /** * Power on the flash chip for ESP32-P4 Rev 301 (ECO6) * The flash chip is powered off by default on ECO6, when the default flash * voltage changed from 1.8V to 3.3V. This is to prevent damage to 1.8V flash chips. */ powerOnFlash(): Promise; /** * Get security info including chip ID (ESP32-C3 and later) */ getSecurityInfo(): Promise<{ flags: number; flashCryptCnt: number; keyPurposes: number[]; chipId: number; apiVersion: number; }>; /** * Get MAC address from efuses */ getMacAddress(): Promise; /** * @name readLoop * Reads data from the input stream and places it in the inputBuffer */ readLoop(): Promise; state_DTR: boolean; state_RTS: boolean; setRTS(state: boolean): Promise; setDTR(state: boolean): Promise; setDTRandRTS(dtr: boolean, rts: boolean): Promise; private runSignalSequence; /** * @name hardResetUSBJTAGSerial * USB-JTAG/Serial reset for Web Serial (Desktop) */ hardResetUSBJTAGSerial(): Promise; /** * @name hardResetClassic * Classic reset for Web Serial (Desktop) DTR = IO0, RTS = EN */ hardResetClassic(): Promise; /** * Reset to firmware mode (not bootloader) for Web Serial * Keeps IO0=HIGH during reset so chip boots into firmware */ hardResetToFirmware(): Promise; /** * @name hardResetUnixTight * Unix Tight reset for Web Serial (Desktop) - sets DTR and RTS simultaneously */ hardResetUnixTight(): Promise; setRTSWebUSB(state: boolean): Promise; setDTRWebUSB(state: boolean): Promise; setDTRandRTSWebUSB(dtr: boolean, rts: boolean): Promise; /** * @name hardResetUSBJTAGSerialInvertedDTRWebUSB * USB-JTAG/Serial reset with inverted DTR for WebUSB (Android) */ hardResetUSBJTAGSerialInvertedDTRWebUSB(): Promise; /** * @name hardResetClassicLongDelayWebUSB * Classic reset with longer delays for WebUSB (Android) * Specifically for CP2102/CH340 which may need more time */ hardResetClassicLongDelayWebUSB(): Promise; /** * @name hardResetClassicShortDelayWebUSB * Classic reset with shorter delays for WebUSB (Android) */ hardResetClassicShortDelayWebUSB(): Promise; /** * @name hardResetInvertedWebUSB * Inverted reset sequence for WebUSB (Android) - both signals inverted */ hardResetInvertedWebUSB(): Promise; /** * @name hardResetInvertedDTRWebUSB * Only DTR inverted for WebUSB (Android) */ hardResetInvertedDTRWebUSB(): Promise; /** * @name hardResetInvertedRTSWebUSB * Only RTS inverted for WebUSB (Android) */ hardResetInvertedRTSWebUSB(): Promise; /** * Check if we're using WebUSB (Android) or Web Serial (Desktop) */ private isWebUSB; /** * @name connectWithResetStrategies * Try different reset strategies to enter bootloader mode * Similar to esptool.py's connect() method with multiple reset strategies */ connectWithResetStrategies(): Promise; /** * @name watchdogReset * Watchdog reset for ESP32-S2/S3/P4 with USB-OTG or USB-JTAG/Serial * Uses RTC watchdog timer to reset the chip - works when DTR/RTS signals are not available * This is an alias for rtcWdtResetChipSpecific() for backwards compatibility * Note: ESP32-C3, ESP32-C5, ESP32-C6 do NOT boot correctly after WDT reset */ watchdogReset(): Promise; /** * RTC watchdog timer reset for ESP32-S2, ESP32-S3, ESP32-P4, and ESP32-S31 * Uses specific registers for each chip family * Note: ESP32-C3 does NOT boot correctly after WDT reset * Note: ESP32-C5, ESP32-C6, ESP32-C61, ESP32-H2 do NOT support WDT reset (no usable RTC WDT path) */ rtcWdtResetChipSpecific(): Promise; /** * Reset device from bootloader mode to firmware mode * Automatically selects the correct reset strategy based on USB connection type * @param clearForceDownloadFlag - If true, clears the force download boot flag (USB-OTG only) * @returns true if port will change (USB-OTG), false otherwise */ resetToFirmwareMode(clearForceDownloadFlag?: boolean): Promise; hardReset(bootloader?: boolean): Promise; /** * @name macAddr * The MAC address burned into the OTP memory of the ESP chip */ macAddr(): any[]; readRegister(reg: number): Promise; /** * @name checkCommand * Send a command packet, check that the command succeeded and * return a tuple with the value and data. * See the ESP Serial Protocol for more details on what value/data are * * Commands are serialized to prevent concurrent execution which can cause * WritableStream lock contention on CP210x adapters under Windows */ checkCommand(opcode: number, buffer: number[], checksum?: number, timeout?: number): Promise<[number, number[]]>; /** * @name sendCommand * Send a slip-encoded, checksummed command over the UART, * does not check response */ sendCommand(opcode: number, buffer: number[], checksum?: number): Promise; /** * @name readPacket * Generator to read SLIP packets from a serial port. * Yields one full SLIP packet at a time, raises exception on timeout or invalid data. * * Two implementations: * - Burst: CDC devices (Native USB) and CH343 - very fast processing * - Byte-by-byte: CH340, CP2102, and other USB-Serial adapters - stable fast processing */ readPacket(timeout: number): Promise; /** * @name getResponse * Read response data and decodes the slip packet, then parses * out the value/data and returns as a tuple of (value, data) where * each is a list of bytes */ getResponse(opcode: number, timeout?: number): Promise<[number, number[]]>; /** * @name checksum * Calculate checksum of a blob, as it is defined by the ROM */ checksum(data: number[], state?: number): number; getC5CrystalFreqRomExpect(): Promise; getC5CrystalFreqDetected(): Promise; setBaudrate(baud: number): Promise; private setBaudrateC5Rom; reconfigurePort(baud: number): Promise; /** * @name syncWithTimeout * Sync with timeout that can be abandoned (for reset strategy loop) * This is internally time-bounded and checks the abandon flag */ syncWithTimeout(timeoutMs: number): Promise; /** * @name sync * Put into ROM bootload mode & attempt to synchronize with the * ESP ROM bootloader, we will retry a few times */ sync(): Promise; /** * @name _sync * Perform a soft-sync using AT sync packets, does not perform * any hardware resetting */ _sync(): Promise; /** * @name getFlashWriteSize * Get the Flash write size based on the chip */ getFlashWriteSize(): 1024 | 16384; /** * @name flashData * Program a full, uncompressed binary file into SPI Flash at * a given offset. If an ESP32 and md5 string is passed in, will also * verify memory. ESP8266 does not have checksum memory verification in * ROM */ flashData(binaryData: ArrayBuffer, updateProgress: (bytesWritten: number, totalBytes: number) => void, offset?: number, compress?: boolean): Promise; /** * @name flashBlock * Send one block of data to program into SPI Flash memory */ flashBlock(data: number[], seq: number, timeout?: number): Promise; flashDeflBlock(data: number[], seq: number, timeout?: number): Promise; /** * @name flashBegin * Prepare for flashing by attaching SPI chip and erasing the * number of blocks requred. */ flashBegin(size?: number, offset?: number, encrypted?: boolean): Promise; /** * @name flashDeflBegin * */ flashDeflBegin(size?: number, compressedSize?: number, offset?: number): Promise; flashFinish(): Promise; flashDeflFinish(): Promise; getBootloaderOffset(): number; flashId(): Promise; getChipFamily(): ChipFamily; writeRegister(address: number, value: number, mask?: number, delayUs?: number, delayAfterUs?: number): Promise; setDataLengths(spiAddresses: SpiFlashAddresses, mosiBits: number, misoBits: number): Promise; waitDone(spiCmdReg: number, spiCmdUsr: number): Promise; runSpiFlashCommand(spiflashCommand: number, data: number[], readBits?: number): Promise; detectFlashSize(): Promise; /** * @name getEraseSize * Calculate an erase size given a specific size in bytes. * Provides a workaround for the bootloader erase bug on ESP8266. */ getEraseSize(offset: number, size: number): number; /** * @name memBegin (592) * Start downloading an application image to RAM */ memBegin(size: number, blocks: number, blocksize: number, offset: number): Promise<[number, number[]]>; /** * @name memBlock (609) * Send a block of an image to RAM */ memBlock(data: number[], seq: number): Promise<[number, number[]]>; /** * @name memFinish (615) * Leave download mode and run the application * * Sending ESP_MEM_END usually sends a correct response back, however sometimes * (with ROM loader) the executed code may reset the UART or change the baud rate * before the transmit FIFO is empty. So in these cases we set a short timeout and * ignore errors. */ memFinish(entrypoint?: number): Promise<[number, number[]]>; runStub(skipFlashDetection?: boolean): Promise; __writer?: WritableStreamDefaultWriter; __writeChain: Promise; private get _reader(); private set _reader(value); private get _writer(); private set _writer(value); private get _writeChain(); private set _writeChain(value); writeToStream(data: number[]): Promise; disconnect(): Promise; /** * @name releaseReaderWriter * Release reader and writer locks without closing the port * Used when switching to console mode */ releaseReaderWriter(): Promise; /** * @name resetToFirmware * Public method to reset device from bootloader to firmware for console mode * Automatically detects USB-JTAG/Serial and USB-OTG devices and performs appropriate reset * @returns true if reset was performed, false if not needed */ resetToFirmware(): Promise; /** * @name detectUsbConnectionType * Detect if device is using USB-JTAG/Serial or USB-OTG (not external serial chip) * Uses USB PID (Product ID) for reliable detection - does NOT require chipFamily * @returns true if USB-JTAG or USB-OTG, false if external serial chip */ detectUsbConnectionType(): Promise; getUsbMode(): Promise<{ mode: "uart" | "usb-jtag-serial" | "usb-otg"; uartNo: number; }>; /** * Check if the current chip supports USB-JTAG or USB-OTG * @returns true if chip has native USB support (JTAG or OTG) */ supportsNativeUsb(): boolean; /** * @name _ensureStreamsReady * After a hardware reset, ensure port streams are available. * On WebUSB, recreates streams since they break after reset. * On Web Serial, waits for streams to become available. */ private _ensureStreamsReady; /** * @name enterConsoleMode * Prepare device for console mode by resetting to firmware * Handles both USB-JTAG/OTG devices (closes port) and external serial chips (keeps port open) * @returns true if port was closed (USB-JTAG), false if port stays open (serial chip) */ enterConsoleMode(): Promise; /** * @name _clearForceDownloadBootIfNeeded * Read and clear the force download boot flag if it is set * This should ONLY be called when on ROM (not stub) and before WDT reset * Clearing it on every connect causes issues with flash operations * Returns true if the flag was cleared, false if it was already clear */ private _clearForceDownloadBootIfNeeded; /** * @name _resetToFirmwareIfNeeded * Reset device from bootloader to firmware when switching to console mode * Detects USB-JTAG/Serial and USB-OTG devices and performs appropriate reset * @returns true if reconnect was performed, false otherwise */ private _resetToFirmwareIfNeeded; /** * @name reconnectAndResume * Reconnect the serial port to flush browser buffers and reload stub */ reconnect(): Promise; /** * @name reconnectToBootloader * Close and reopen the port, then reset ESP to bootloader mode * This is needed after Improv or other operations that leave ESP in firmware mode */ reconnectToBootloader(): Promise; /** * @name exitConsoleMode * Exit console mode and return to bootloader * For ESP32-S2, uses reconnectToBootloader which will trigger port change * @returns true if manual reconnection is needed (ESP32-S2), false otherwise */ exitConsoleMode(): Promise; /** * @name isConsoleResetSupported * Check if console reset is supported for this device * ESP32-S2 USB-JTAG/CDC does not support reset in console mode * because any reset causes USB port to be lost (hardware limitation) */ isConsoleResetSupported(): boolean; /** * @name resetInConsoleMode * Reset device while in console mode (firmware mode) * * NOTE: For ESP32-S2 USB-JTAG/CDC, ANY reset (hardware or software) causes * the USB port to be lost because the device switches USB modes during reset. * This is a hardware limitation - use isConsoleResetSupported() to check first. */ resetInConsoleMode(): Promise; /** * @name syncAndWdtReset * Open a new bootloader port, sync with ROM (no stub, no reset strategies), and fire WDT reset. * This is used for ESP32-S2 USB-OTG devices which require WDT reset to switch modes. * After WDT reset the port will re-enumerate again. * The user must select the new port after this method is called. * @param newPort - The bootloader port selected by the user */ syncAndWdtReset(newPort: SerialPort): Promise; /** * @name drainInputBuffer * Actively drain the input buffer by reading data for a specified time. * Simple approach for some drivers (especially CP210x on Windows) that have * issues with buffer flushing. * * Based on esptool.py fix: https://github.com/espressif/esptool/commit/5338ea054e5099ac7be235c54034802ac8a43162 * * @param bufferingTime - Time in milliseconds to wait for the buffer to fill */ drainInputBuffer(bufferingTime?: number): Promise; /** * @name flushSerialBuffers * Flush any pending data in the TX and RX serial port buffers * This clears both the application RX buffer and waits for hardware buffers to drain */ flushSerialBuffers(): Promise; /** * @name readFlash * Read flash memory from the chip (only works with stub loader) * @param addr - Address to read from * @param size - Number of bytes to read * @param onPacketReceived - Optional callback function called when packet is received * @param options - Optional parameters for advanced control * - chunkSize: Amount of data to request from ESP in one command (bytes) * - blockSize: Size of each data block sent by ESP (bytes) * - maxInFlight: Maximum unacknowledged bytes (bytes) * @returns Uint8Array containing the flash data */ readFlash(addr: number, size: number, onPacketReceived?: (packet: Uint8Array, progress: number, totalSize: number) => void, options?: { chunkSize?: number; blockSize?: number; maxInFlight?: number; }): Promise; } declare class EspStubLoader extends ESPLoader { IS_STUB: boolean; /** * @name memBegin (592) * Start downloading an application image to RAM */ memBegin(size: number, _blocks: number, _blocksize: number, offset: number): Promise<[number, number[]]>; /** * @name eraseFlash * Erase entire flash chip */ eraseFlash(): Promise; /** * @name eraseRegion * Erase a specific region of flash */ eraseRegion(offset: number, size: number): Promise; } export {};