import { LitElement, html, css } from 'lit'; import { customElement, state, property, query } from 'lit/decorators.js'; import type { PyodideInterface } from 'pyodide'; import '@material/mwc-button'; import '@material/mwc-icon-button'; import '@material/mwc-linear-progress'; import '@material/mwc-circular-progress'; import '@material/mwc-formfield'; import '@material/mwc-radio'; import '@material/mwc-dialog'; import { mdiChip, mdiShimmer, mdiAutorenew, mdiClose, mdiAlert } from '@mdi/js'; import './usf-icon'; import './usf-icon-button'; import './usf-file-upload'; import { parseFirmwareBuffer, validateFirmwareChecksum, } from './firmware-selector'; import './firmware-selector'; import type { Manifest, FirmwareType } from './const'; import { FirmwareNames, ApplicationNames, ApplicationType, ApplicationTypeToFirmwareType, mdiFirmware, LegacyTypeToFirmwareType, } from './const'; import { setupPyodide, PyodideLoadState } from './setup-pyodide'; import { downloadFile } from './utils'; enum UploadProgressState { IDLE, CONNECTING, FLASHING, } enum FlashingStep { IDLE, SELECTING_PORT, PORT_SELECTION_CANCELLED, LOADING_PYODIDE, PROBING, PROBING_COMPLETE, PROBING_FAILED, SELECT_FIRMWARE, INSTALLING, INSTALL_FAILED, DONE, } @customElement('flashing-dialog') export class FlashingDialog extends LitElement { static styles = css` :host { --mdc-theme-primary: #03a9f4; } a { color: var(--mdc-theme-primary); } .metadata { font-size: 0.8em; } img { vertical-align: middle; } #closeButton { position: absolute; top: 10px; right: 10px; } p.spinner { text-align: center; font-size: 2em; } p.firmware-metadata { font-size: 0.8em; line-height: 1.2; overflow: auto; } span.progress-text { font-size: 0.8em; } mwc-button usf-icon { margin-right: 0.2em; } #firmwareInstallButtons { margin-left: -3px; text-align: left; } #firmwareInstallButtons mwc-button { display: block; } #firmwareInstallButtons mwc-button:not(:last-child) { margin-bottom: 0.3em; } .centered { text-align: center; } td usf-icon { vertical-align: bottom; } section.warning { background-color: hsl(38, 96%, 90%); font-size: 0.9em; margin-left: -24px; margin-right: -24px; padding-left: 24px; padding-right: 24px; padding-top: 12px; padding-bottom: 12px; } section.warning h2 usf-icon { vertical-align: text-bottom; } section.warning code { font-weight: bold; } `; @state() private flashingStep: FlashingStep = FlashingStep.IDLE; @property() public pyodide?: PyodideInterface; @state() private pyodideLoadState: PyodideLoadState = PyodideLoadState.LOADING_PYODIDE; @property() public manifest!: Manifest; private debugLog = ''; @state() private selectedFirmware?: any; @state() private serialPort?: SerialPort; private pyFlasher?: any; @state() private uploadProgress = 0; @state() private progressState: UploadProgressState = UploadProgressState.IDLE; @query('mwc-dialog') private mwcDialog!: HTMLDialogElement; public firstUpdated(changedProperties: Map) { super.firstUpdated(changedProperties); this.mwcDialog.addEventListener('close', this.close); this.selectSerialPort(); } private getFirmwareMetadata() { if (!this.selectedFirmware) { return html``; } let metadata; try { metadata = this.selectedFirmware.get_nabucasa_metadata(); } catch (e) { return html``; } const fwTypeValue = metadata.fw_type .value as keyof typeof LegacyTypeToFirmwareType; if (fwTypeValue in LegacyTypeToFirmwareType) { metadata.fw_type = LegacyTypeToFirmwareType[fwTypeValue]; } return html`
Type ${FirmwareNames[metadata.fw_type.value as FirmwareType] || 'unknown'}
SDK Version ${this.simpleVersion(metadata.sdk_version)}
EZSP Version ${this.simpleVersion(metadata.ezsp_version) || '-'}
`; } private async selectSerialPort() { this.flashingStep = FlashingStep.SELECTING_PORT; const options: SerialPortRequestOptions = {}; if (this.manifest.usb_filters) { options.filters = this.manifest.usb_filters.map(f => ({ usbProductId: f.pid, usbVendorId: f.vid, })); } try { this.serialPort = await navigator.serial.requestPort(options); } catch (err) { console.log(err); this.mwcDialog.open = true; this.serialPort = undefined; this.flashingStep = FlashingStep.PORT_SELECTION_CANCELLED; return; } this.mwcDialog.open = true; this.flashingStep = FlashingStep.LOADING_PYODIDE; this.pyodide = await setupPyodide(newLoadState => { this.pyodideLoadState = newLoadState; }); await this.onPyodideLoaded(); } private async onPyodideLoaded() { const pyodide = this.pyodide!; pyodide.setStdout({ batched: (msg: string) => { console.log(msg); this.debugLog += `${msg}\n`; }, }); pyodide.setStderr({ batched: (msg: string) => { console.warn(msg); this.debugLog += `${msg}\n`; }, }); // Set up the flasher pyodide .pyimport('webserial_transport') .set_global_serial_port(this.serialPort); const PyApplicationType = pyodide.pyimport( 'universal_silabs_flasher.const' ).ApplicationType; const PyResetTarget = pyodide.pyimport( 'universal_silabs_flasher.const' ).ResetTarget; const PyFlasher = pyodide.pyimport( 'universal_silabs_flasher.flasher' ).Flasher; this.pyFlasher = PyFlasher.callKwargs({ probe_methods: pyodide.toPy( this.manifest.probe_methods.map(pm => [ PyApplicationType(pm.protocol), pm.baudrate, ]) ), device: '/dev/webserial', // the device name is ignored bootloader_reset: pyodide.toPy( this.manifest.bootloader_reset.map(method => PyResetTarget(method)) ), }); await this.detectRunningFirmware(); } private async detectRunningFirmware() { this.flashingStep = FlashingStep.PROBING; try { await this.pyFlasher.probe_app_type(); } catch (e) { console.error('Probing failed: ', e); this.pyFlasher = undefined; this.serialPort = undefined; this.flashingStep = FlashingStep.PROBING_FAILED; return; } this.flashingStep = FlashingStep.PROBING_COMPLETE; } private selectFirmware() { this.flashingStep = FlashingStep.SELECT_FIRMWARE; } private onFirmwareLoaded(e: CustomEvent) { this.selectedFirmware = e.detail.firmware; } private async flashFirmware() { this.flashingStep = FlashingStep.INSTALLING; this.uploadProgress = 0; await this.pyFlasher.enter_bootloader(); try { await this.pyFlasher.flash_firmware.callKwargs(this.selectedFirmware, { progress_callback: (current: number, total: number) => { this.uploadProgress = current / total; }, }); this.flashingStep = FlashingStep.DONE; } catch (e) { this.flashingStep = FlashingStep.INSTALL_FAILED; } } private async close() { if (this.serialPort) { await this.serialPort.close(); } this.parentNode!.removeChild(this); } private showDebugLog() { const debugText = `data:text/plain;charset=utf-8,${encodeURIComponent( this.debugLog )}`; downloadFile(debugText, 'silabs_flasher.log'); } private formatHeadingText(text: string) { if (text.length < 20) { return text; } // FIXME: this moves the closing `x` out of the way return text + '\u00A0'.repeat(8); } private simpleVersion(version: any) { if (!version) { return null; } return Array.from(version.components.toJs()) .map((c: any) => c.data) .join(''); } render() { let content = html``; let headingText = 'Connecting'; let showDebugLogButton = true; let showCloseButton = true; let hideActions = false; if (this.flashingStep === FlashingStep.SELECTING_PORT) { if (this.mwcDialog) { this.mwcDialog.open = false; } hideActions = true; showDebugLogButton = false; headingText = 'Select a serial port'; content = html`

Plug in and select your ${this.manifest.product_name}

`; } else if (this.flashingStep === FlashingStep.PORT_SELECTION_CANCELLED) { showDebugLogButton = false; headingText = 'Serial port was not selected'; content = html`

If you didn't select a serial port because the ${this.manifest.product_name} was missing, make sure the USB port it's plugged into works and the ${this.manifest.product_name} is detected by your operating system.

If you are using Windows or macOS, install the Silicon Labs CP2102 driver.

Retry `; } else if ( [FlashingStep.LOADING_PYODIDE, FlashingStep.PROBING].includes( this.flashingStep ) ) { hideActions = true; showDebugLogButton = false; headingText = ''; content = html`

Connecting...
This can take a few seconds.

`; } else if (this.flashingStep === FlashingStep.PROBING_FAILED) { const isMacOS = navigator.userAgent.includes('Mac OS'); const isUsingCP210x = this.manifest.usb_filters.find( filter => filter.vid == 4292 && filter.pid == 60000 ); headingText = 'Connection failed'; content = html`${isMacOS && isUsingCP210x ? html`

macOS Driver Bug

The built-in drivers on macOS do not work properly with the ${this.manifest.product_name}. Install the updated Silicon Labs CP2102 driver and re-connect to the serial port titled CP210x USB to UART Bridge Controller (cu.SLAB_USBtoUART).

` : ''}

The running firmware could not be detected.

Make sure the USB port works and if you are using a USB extension cable, make sure the cable can transfer data. Unplug the ${this.manifest.product_name} and plug it back in to reset and try again.

Retry `; } else if (this.flashingStep === FlashingStep.PROBING_COMPLETE) { hideActions = true; showDebugLogButton = false; headingText = this.manifest.product_name; const { Version } = this.pyodide!.pyimport( 'universal_silabs_flasher.common' ); const appType: ApplicationType = this.pyFlasher.app_type.value; const compatibleFirmwareType: FirmwareType | undefined = ApplicationTypeToFirmwareType[appType]; const compatibleFirmware = this.manifest.firmwares.find( fw => fw.type === compatibleFirmwareType && Version(fw.version) > this.pyFlasher.app_version && !Version(fw.version).compatible_with(this.pyFlasher.app_version) ); // Show a one-click "upgrade" button if possible let upgradeButton; if (compatibleFirmware) { upgradeButton = html` { const response = await fetch(compatibleFirmware.url); const firmwareData = await response.arrayBuffer(); if (compatibleFirmware.checksum) { validateFirmwareChecksum( firmwareData, compatibleFirmware.checksum ); } this.selectedFirmware = await parseFirmwareBuffer( this.pyodide!, firmwareData ); this.flashFirmware(); }} > Upgrade to  ${compatibleFirmware.version} `; } content = html`

${ ApplicationNames[appType] || 'unknown' } ${this.simpleVersion(this.pyFlasher.app_version)}
${this.manifest.product_name}

${upgradeButton || ''} Change firmware
`; } else if (this.flashingStep === FlashingStep.SELECT_FIRMWARE) { headingText = this.manifest.product_name; content = html`

Select new firmware to install.

${this.selectedFirmware ? html`

${this.getFirmwareMetadata()}

` : ''} Install `; } else if (this.flashingStep === FlashingStep.INSTALLING) { // Hide the close button to prevent it from being accidentally clicked during flashing. // The bootloader is resilient so nothing will actually break that can't be fixed by retrying. hideActions = true; showCloseButton = false; headingText = 'Installing firmware'; content = html`

The new firmware is now installing. Do not disconnect the ${this.manifest.product_name} or close this browser window.

Progress: ${(+this.uploadProgress * 100).toFixed(1)}%

`; } else if (this.flashingStep === FlashingStep.INSTALL_FAILED) { headingText = 'Installation failed'; content = html`

Firmware installation failed. Unplug your ${this.manifest.product_name} and plug it back in to retry.

Retry `; } else if (this.flashingStep === FlashingStep.DONE) { headingText = 'Installation success'; content = html`

Firmware has been successfully installed.

Continue `; } return html` ${showCloseButton ? html` ` : ''} ${content} ${showDebugLogButton ? html` Debug Log ` : ''} `; } } declare global { interface HTMLElementTagNameMap { 'flashing-dialog': FlashingDialog; } }