import { LitElement, html, PropertyValues, css, TemplateResult, nothing, svg, } from "lit"; import { customElement, query, property, state } from "lit/decorators.js"; import "@material/web/dialog/dialog.js"; import "@material/web/iconbutton/filled-tonal-icon-button.js"; import "@material/web/iconbutton/icon-button.js"; import "@material/web/textfield/outlined-text-field.js"; import "@material/web/button/outlined-button.js"; import "@material/web/button/filled-button.js"; import "@material/web/progress/circular-progress.js"; import "@material/web/select/outlined-select.js"; import "@material/web/select/select-option.js"; import "@material/web/list/list.js"; import "@material/web/list/list-item.js"; import type { MdOutlinedTextField } from "@material/web/textfield/outlined-text-field"; import type { MdOutlinedSelect } from "@material/web/select/outlined-select.js"; import { ImprovSerialCurrentState, ImprovSerialErrorState, Logger, State, } from "./const.js"; import { ImprovSerial, Ssid } from "./serial.js"; import { fireEvent } from "./util/fire-event"; const ERROR_ICON = "⚠️"; const OK_ICON = "🎉"; const infoIcon = svg` `; const wifiIcon = svg` `; const networkWifiFull = svg` `; const networkWifi3Bar = svg` `; const networkWifi2Bar = svg` `; const networkWifi1Bar = svg` `; const lockIcon = svg` `; const lockUnlockedRightIcon = svg` `; const visibilityIcon = svg` `; const visibilityOffIcon = svg` `; /** Name of the network with the strongest signal, null if there are none. */ function strongestSsid(networks: Ssid[]): string | null { return networks.length ? networks.reduce((best, ssid) => (ssid.rssi > best.rssi ? ssid : best)) .name : null; } function getWifiIcon(rssi: number): TemplateResult { if (rssi >= -50) return networkWifiFull; if (rssi >= -60) return networkWifi3Bar; if (rssi >= -70) return networkWifi2Bar; return networkWifi1Bar; } function getSignalStrengthClass(rssi: number): string { if (rssi >= -50) return "signal-excellent"; if (rssi >= -60) return "signal-good"; if (rssi >= -70) return "signal-fair"; return "signal-weak"; } @customElement("improv-wifi-serial-provision-dialog") class SerialProvisionDialog extends LitElement { @property() public port?: SerialPort; public logger: Logger = console; public learnMoreUrl?: TemplateResult; @state() private _state: State = "CONNECTING"; @state() private _client?: ImprovSerial; @state() private _busy = false; @state() private _error?: string | TemplateResult; @state() private _selectedSsid: string | null = null; // undefined = not loaded // null = not available @state() private _ssids?: Ssid[] | null; @state() private _showPassword = false; // Show the configure form while already provisioned, to change the network. @state() private _reprovision = false; private _unsubSSIDs?: () => Promise; @query("md-outlined-select") private _selectSSID!: MdOutlinedSelect; @query("md-outlined-text-field[name=ssid]") private _inputSSID!: MdOutlinedTextField; @query("md-outlined-text-field[name=password]") private _inputPassword?: MdOutlinedTextField; protected render() { if (!this.port) { return html``; } let heading: TemplateResult = html`${this._client?.info?.name ?? nothing}`; let content: TemplateResult; let actions: TemplateResult | undefined; if (this._state === "CONNECTING" || !this._client) { content = this._renderProgress("Connecting"); } else if (this._state === "ERROR") { content = this._renderMessage( ERROR_ICON, `An error occurred. ${this._error}`, ); actions = this._renderCloseAction(); } else if (this._client!.state === ImprovSerialCurrentState.STOPPED) { content = this._renderMessage( ERROR_ICON, "The connected device has Wi-Fi turned off, so it can't be configured right now. Enable the device's Wi-Fi, then try again.", ); actions = this._renderCloseAction(); } else if (this._showConfigureForm) { if (this._busy) { content = this._renderProgress("Provisioning"); } else { heading = html`${wifiIcon}Configure Wi-Fi`; if (this._ssids === undefined) { content = this._renderProgress("Searching for networks"); } else { content = this._renderImprovReady(); actions = html`${this._renderCloseAction()} Connect `; } } } else if (this._client!.state === ImprovSerialCurrentState.PROVISIONING) { content = this._renderProgress("Provisioning"); } else if (this._client!.state === ImprovSerialCurrentState.PROVISIONED) { content = html` ${this._client?.info ? this._renderDeviceInfo() : nothing}
${OK_ICON}
Provisioned!
`; actions = html`${this._renderCloseAction()} Change Wi-Fi ${ this._client!.nextUrl === undefined ? nothing : html`Visit Device` }`; } else { content = this._renderMessage( ERROR_ICON, `Unexpected state: ${this._state} - ${this._client!.state}`, ); actions = this._renderCloseAction(); } return html`
${heading}
${content}
${actions ? html`
${actions}
` : nothing}
`; } _renderCloseAction() { return html`Close`; } _renderProgress(label: string) { return html`
${label}
`; } _renderMessage(icon: string, label: string) { return html`
${icon}
${label}
`; } _renderImprovReady() { let error: string | undefined; switch (this._client!.error) { case ImprovSerialErrorState.UNABLE_TO_CONNECT: error = "Unable to connect"; break; case ImprovSerialErrorState.NO_ERROR: break; // Happens after scanning for networks if device // doesn't support the command. case ImprovSerialErrorState.UNKNOWN_RPC_COMMAND: if (this._ssids !== null) { error = `Unknown RPC command`; } break; case ImprovSerialErrorState.TIMEOUT: error = `Timeout`; break; default: error = `Unknown error (${this._client!.error})`; } const selectedSsid = this._ssids?.find( (info) => info.name === this._selectedSsid, ); return html` ${this._client?.info ? this._renderDeviceInfo() : nothing}
Enter credentials of the Wi-Fi network that you want your device to connect to.
${error ? html`

${error}

` : nothing} ${ this._ssids !== null ? html` { const index = (ev.target as MdOutlinedSelect).selectedIndex; // The "Join Other" item is always the last item. this._selectedSsid = index === this._ssids!.length ? null : this._ssids![index].name; }} @closed=${(ev: Event) => ev.stopPropagation()} > ${this._ssids!.map( (info, idx) => html` ${getWifiIcon(info.rssi)} ${info.name} ${info.rssi}dB ${ info.secured ? lockIcon : lockUnlockedRightIcon } `, )} Join other… ` : nothing } ${ // Show input box if no wifi networks found or "Join Other" selected this._selectedSsid === null ? html` ` : nothing } ${ // Show password if custom SSID or needs password !selectedSsid || selectedSsid.secured ? html` { if (ev.key === "Enter") { this._provision(); } }} > ${this._showPassword ? visibilityOffIcon : visibilityIcon} ` : nothing } `; } _renderDeviceInfo(): TemplateResult { return html`
${infoIcon}Device Info
Name${this._client!.info!.name}
Firmware${this._client!.info!.firmware}
Version${this._client!.info!.version}
Chip${this._client!.info!.chipFamily}
${ this._client!.info!.osName ? html`
OS${this._client!.info!.osName}
` : nothing } ${ this._client!.info!.osVersion ? html`
OS Version${this._client!.info!.osVersion}
` : nothing }
`; } private _togglePasswordVisibility(event: Event) { event.preventDefault(); event.stopPropagation(); this._showPassword = !this._showPassword; } // Whether the network configuration form is the active view. private get _showConfigureForm(): boolean { return ( this._client?.state === ImprovSerialCurrentState.READY || (this._client?.state === ImprovSerialCurrentState.PROVISIONED && this._reprovision) ); } // Scan while (and only while) the configure form is shown. Driven from // `updated()`, so entering the form starts scanning and leaving it stops. private _syncScanning() { const shouldScan = this._state === "IMPROV-STATE" && !this._busy && this._showConfigureForm; if (shouldScan === !!this._unsubSSIDs) { return; } if (shouldScan) { this._unsubSSIDs = this._client!.subscribeSSIDs((networks) => { if (networks === null) { // Scanning isn't available; fall back to manual network entry. this._selectedSsid = null; } else if (this._ssids == null) { // First result: default to the network with the strongest signal. this._selectedSsid = strongestSsid(networks); } else if ( this._selectedSsid !== null && !networks.some((s) => s.name === this._selectedSsid) ) { // A merged scan never drops networks, but the selection persists // across scan restarts (after a failed provision, or reopening to // change Wi-Fi), and the first fresh scan may not include it yet. // Re-default when that happens; keep "Join other" (null) as-is. this._selectedSsid = strongestSsid(networks); } this._ssids = networks; }); } else { this._stopScanning(); } } private async _stopScanning() { if (!this._unsubSSIDs) { return; } const unsubscribe = this._unsubSSIDs; this._unsubSSIDs = undefined; await unsubscribe(); } private async _provision() { // Read the form before setting `_busy`: that swaps the form for a progress // view, and the render happens during any await below — after which the // fields no longer exist and we'd provision with an empty password. const ssid = this._selectedSsid === null ? this._inputSSID.value : this._selectedSsid; const password = this._inputPassword?.value || ""; this._busy = true; // Wait for any in-flight scan to settle before provisioning so we don't // have two RPC commands in flight at once. Marking busy above already tells // `_syncScanning` to stop, but the provision RPC needs it stopped *now*. await this._stopScanning(); try { await this._client!.provision( ssid, password, // Devices try to connect for ~30s before reporting failure. Our // timeout must comfortably exceed that: it's only a safety net, and if // it fires first the device's late failure packet rejects the *next* // RPC we send (the resumed network scan) instead of this one. 45000, ); // Success: leave the change-Wi-Fi form and show the provisioned screen. this._reprovision = false; } catch (err) { // No need to do error handling because we listen for `error-changed` // events. Clearing busy resumes scanning via `_syncScanning`. console.log(err); } finally { this._busy = false; } } private _changeWifi() { this._reprovision = true; } protected updated(changedProps: PropertyValues) { super.updated(changedProps); if (changedProps.has("port") && this.port) { this._connect(); } this._syncScanning(); let toFocus: LitElement | undefined; if ( changedProps.has("_ssids") && changedProps.get("_ssids") === undefined && this._ssids != null ) { // Only focus on the first result, not on every background scan update. toFocus = this._selectSSID; } else if ( changedProps.has("_selectedSsid") && this._selectedSsid === null ) { toFocus = this._inputSSID; } if (toFocus) { toFocus.updateComplete.then(() => toFocus!.focus()); } } private async _connect() { let client: ImprovSerial; try { client = new ImprovSerial(this.port!, this.logger); } catch (err) { this._state = "ERROR"; this._error = (err as any).message || err || "Unknown error"; return; } client.addEventListener("state-changed", () => { this._state = "IMPROV-STATE"; this.requestUpdate(); }); client.addEventListener("error-changed", () => this.requestUpdate()); try { await client.initialize(10000); } catch (err: any) { this._state = "ERROR"; this._error = this.learnMoreUrl ? html` Unable to detect Improv service on connected device. Learn how to resolve this ` : err.message; return; } client.addEventListener("disconnect", () => { this._state = "ERROR"; this._error = "Disconnected"; }); if (client.nextUrl) { this.requestUpdate(); } this._client = client; // Scanning starts from `_syncScanning` once the configure form is shown. } private async _handleClose() { const eventData = { improv: false, provisioned: false, }; if (this._client) { eventData.improv = true; eventData.provisioned = this._client.state === ImprovSerialCurrentState.PROVISIONED; await this._client.close(); this._client = undefined; } fireEvent(this, "closed" as any, eventData); this.parentNode!.removeChild(this); } disconnectedCallback() { super.disconnectedCallback(); // Stop scanning when the dialog goes away. Not awaited: closing the client // cancels the reader, which may leave the in-flight scan unsettled. this._stopScanning(); } static styles = css` :host { --md-dialog-max-width: 390px; --md-dialog-container-max-block-size: none !important; --md-sys-color-primary: var(--improv-primary-color, #03a9f4); --md-sys-color-on-primary: var(--improv-on-primary-color, #fff); --md-ref-typeface-brand: system-ui, sans-serif; --md-ref-typeface-plain: system-ui, sans-serif; font-family: system-ui, sans-serif; } md-dialog { --md-dialog-container-color: var(--improv-container-color, #fff); --md-dialog-container-max-block-size: none !important; max-height: 90vh !important; } md-dialog [slot="content"], form[slot="content"] { overflow: visible !important; max-height: none !important; } md-outlined-text-field, md-outlined-select { display: block; margin-top: 16px; } .center { text-align: center; } md-circular-progress { margin-bottom: 16px; } a.has-button { text-decoration: none; } .icon { font-size: 50px; line-height: 80px; color: black; } .error { color: #db4437; } .device-info { margin-bottom: 16px; padding: 16px; background-color: #d6d6d6; border-radius: 8px; border: 1px solid #676767; } .device-info > div:first-child { justify-content: flex-start; align-items: center; gap: 8px; } .device-info > div { display: flex; color: #5f6368; justify-content: space-between; } .device-info > div > span { color: #1f1f1f; } md-select-option[value="-1"] { border-top: 1px solid #ccc; } md-outlined-select[name="ssid_select"] { width: 100%; } .network-details { display: flex; align-items: center; gap: 4px; color: #5f6368; font-size: 0.85em; } .signal-strength { min-width: 45px; text-align: right; } .lock-icon { font-size: 18px; } .lock-secured { color: #34a853; } .lock-unsecured { color: #ea4335; } .signal-excellent, .signal-good { color: #34a853; } .signal-fair { color: #fbbc04; } .signal-weak { color: #ea4335; } `; } declare global { interface HTMLElementTagNameMap { "improv-wifi-serial-provision-dialog": SerialProvisionDialog; } }