/* index.tsx - ESP3D WebUI WiFi Settings Tab Copyright (c) 2025 Mike Melancon. All rights reserved. This code is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This code is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with This code; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ import { Fragment, TargetedMouseEvent } from "preact" import { useState, useEffect } from "preact/hooks" import { useToastsContext, useUiContextFn } from "../../contexts" import { ButtonImg, Loading } from "../../components/Controls" import Input from "../../components/Controls/Fields/Input" import Select from "../../components/Controls/Fields/Select" import { Save } from "preact-feather" import { T } from "../../components/Translations" import WifiStats from "./WifiStats" import { getWebSocketService } from "../../hooks/useWebSocketService" import { GetSettingsCommand, Settings } from "../../Services/Commands/GetSettingsCommand" import { Command } from "../../Services/Commands/Command" import { useTargetCommands } from "../../hooks" export type SystemStats = { version?: string ip?: string hostname?: string ipMode?: string gateway?: string netmask?: string dns?: string channel?: string signal?: string apSSID?: string wifiMode?: string flashSize?: string cpuTemperature?: string currentWifiMode?: string connectedTo?: string } const encodePassword = (password: string): string => { return password.replace("%", "%25").replace("!", "%21").replace("?", "%3F").replace("~", "%75") } const WifiTab = () => { const [isLoading, setIsLoading] = useState(false) const [isSaving, setIsSaving] = useState(false) const [hasChanges, setHasChanges] = useState(false) const { targetCommands } = useTargetCommands() const controllerService = getWebSocketService(); const { toasts } = useToastsContext() // Settings state const [originalSettings, setOriginalSettings] = useState({}) // Stats state const [wifiStats, setWifiStats] = useState({}) // Form state const [hostname, setHostname] = useState("") const [wifiMode, setWifiMode] = useState("") const [stationSSID, setStationSSID] = useState("") const [stationPassword, setStationPassword] = useState("") const [stationMinSecurity, setStationMinSecurity] = useState("") const [stationIpMode, setStationIpMode] = useState("") const [stationIP, setStationIP] = useState("") const [stationGateway, setStationGateway] = useState("") const [stationNetmask, setStationNetmask] = useState("") const [apSSID, setApSSID] = useState("") const [apPassword, setApPassword] = useState("") const [apChannel, setApChannel] = useState("") const [apIP, setApIP] = useState("") const [apCountry, setApCountry] = useState("") // Wrapper functions to convert callbacks to match Input/Select signatures const handleHostnameChange = (value: string | number | null) => { if (value !== null) setHostname(String(value)) } const handleWifiModeChange = (value: string | null) => { if (value !== null) setWifiMode(value) } const handleStationSSIDChange = (value: string | number | null) => { if (value !== null) setStationSSID(String(value)) } const handleStationPasswordChange = (value: string | number | null) => { if (value !== null) setStationPassword(String(value)) } const handleStationMinSecurityChange = (value: string | null) => { if (value !== null) setStationMinSecurity(value) } const handleStationIpModeChange = (value: string | null) => { if (value !== null) setStationIpMode(value) } const handleStationIPChange = (value: string | number | null) => { if (value !== null) setStationIP(String(value)) } const handleStationGatewayChange = (value: string | number | null) => { if (value !== null) setStationGateway(String(value)) } const handleStationNetmaskChange = (value: string | number | null) => { if (value !== null) setStationNetmask(String(value)) } const handleApSSIDChange = (value: string | number | null) => { if (value !== null) setApSSID(String(value)) } const handleApPasswordChange = (value: string | number | null) => { if (value !== null) setApPassword(String(value)) } const handleApCountryChange = (value: string | null) => { if (value !== null) setApCountry(value) } const handleApChannelChange = (value: string | number | null) => { if (value !== null) setApChannel(String(value)) } const handleApIPChange = (value: string | number | null) => { if (value !== null) setApIP(String(value)) } const getParam = (data: any, param: string): string | undefined => { return data?.find((field: any) => field.id.replace(": ", "") === param)?.value } // Load WiFi settings on component mount const loadSettings = async () => { setIsLoading(true) try { await controllerService ?.send(new GetSettingsCommand()) .then((command) => { const settings = command.getSettings(); setOriginalSettings(settings); setWifiMode(settings.wifiMode || ""); setHostname(settings.hostname || ""); setStationSSID(settings.stationSSID || ""); setStationIpMode(settings.stationIpMode || ""); setStationPassword(settings.stationPassword || ""); setStationMinSecurity(settings.stationMinSecurity || ""); setStationIP(settings.stationIP || ""); setStationGateway(settings.stationGateway || ""); setStationNetmask(settings.stationNetmask || ""); setApSSID(settings.apSSID || ""); setApPassword(settings.apPassword || ""); setApChannel(settings.apChannel || ""); setApIP(settings.apIP || ""); setApCountry(settings.apCountry || ""); setIsLoading(false) }).catch((error) => { setIsLoading(false) console.error("Failed to load WiFi settings:", error) }) ; } catch { setIsLoading(false) } } const getWifiStats = (): void => { setIsLoading(true) targetCommands("[ESP420]json=yes", undefined, { echo: false } ,{onSuccess: (result: any) => { const jsonResult = JSON.parse(result) if (jsonResult.cmd != 420 || jsonResult.status == "error" || !jsonResult.data) { toasts.addToast({ content: T("S194"), type: "error" }) setIsLoading(false) return } const wifiStatistics = { version: getParam(jsonResult.data, "FWversion"), ip: getParam(jsonResult.data, "IP"), hostname: getParam(jsonResult.data, "Hostname"), ipMode: getParam(jsonResult.data, "IP Mode"), gateway: getParam(jsonResult.data, "Gateway"), netmask: getParam(jsonResult.data, "Mask"), dns: getParam(jsonResult.data, "DNS"), channel: getParam(jsonResult.data, "Channel"), signal: getParam(jsonResult.data, "Signal"), wifiMode: getParam(jsonResult.data, "Current WiFi Mode"), flashSize: getParam(jsonResult.data, "Flash Size"), cpuTemperature: getParam(jsonResult.data, "CPU Temperature"), currentWifiMode: getParam(jsonResult.data, "Current WiFi Mode"), apSSID: getParam(jsonResult.data, "SSID"), connectedTo: getParam(jsonResult.data, "Connected to"), } setWifiStats(wifiStatistics) // // setProps([...jsonResult.data]) // // about = [...jsonResult.data] setIsLoading(false) }, onFail: (error: any) => { setIsLoading(false) toasts.addToast({ content: error, type: "error" }) console.log(error) }}) } // Refresh WiFi stats const refreshWifiStats = async () => { try { getWifiStats() } catch (error) { console.error("Failed to refresh WiFi stats:", error) } } // Check if settings have changed useEffect(() => { const changed = hostname !== originalSettings.hostname || wifiMode !== originalSettings.wifiMode || stationSSID !== originalSettings.stationSSID || stationPassword !== originalSettings.stationPassword || stationMinSecurity !== originalSettings.stationMinSecurity || stationIpMode !== originalSettings.stationIpMode || stationIP !== originalSettings.stationIP || stationGateway !== originalSettings.stationGateway || stationNetmask !== originalSettings.stationNetmask || apSSID !== originalSettings.apSSID || apPassword !== originalSettings.apPassword || apChannel !== originalSettings.apChannel || apIP !== originalSettings.apIP || apCountry !== originalSettings.apCountry setHasChanges(changed) }, [ hostname, wifiMode, stationSSID, stationPassword, stationMinSecurity, stationIpMode, stationIP, stationGateway, stationNetmask, apSSID, apPassword, apChannel, apIP, apCountry, originalSettings, ]) // Save settings const saveSettings = async () => { setIsSaving(true) try { if (hostname !== originalSettings?.hostname) { await controllerService?.send( new Command(`$Hostname=${ hostname}`) ); } if (wifiMode !== originalSettings?.wifiMode) { await controllerService?.send( new Command(`$WiFi/Mode=${ wifiMode}`) ); } if (stationSSID !== originalSettings?.stationSSID) { await controllerService?.send( new Command(`$Sta/SSID=${ stationSSID}`) ); } if (stationIpMode !== originalSettings?.stationIpMode) { await controllerService?.send( new Command(`$Sta/IPMode=${ stationIpMode}`) ); } if (stationPassword !== originalSettings?.stationPassword) { await controllerService?.send( new Command( `$Sta/Password=${ encodePassword(stationPassword ?? "")}` ) ); } if (stationMinSecurity !== originalSettings?.stationMinSecurity) { await controllerService?.send( new Command(`$Sta/MinSecurity=${ stationMinSecurity}`) ); } if (stationIP !== originalSettings?.stationIP) { await controllerService?.send( new Command(`$Sta/IP=${ stationIP}`) ); } if (stationGateway !== originalSettings?.stationGateway) { await controllerService?.send( new Command(`$Sta/Gateway=${ stationGateway}`) ); } if (stationNetmask !== originalSettings?.stationNetmask) { await controllerService?.send( new Command(`$Sta/Netmask=${ stationNetmask}`) ); } if (apSSID !== originalSettings?.apSSID) { await controllerService?.send( new Command(`$AP/SSID=${ apSSID}`) ); } if (apPassword !== originalSettings?.apPassword) { await controllerService?.send( new Command( `$AP/Password=${ encodePassword(apPassword ?? "")}` ) ); } if (apChannel !== originalSettings?.apChannel) { await controllerService?.send( new Command(`$AP/Channel=${ apChannel}`) ); } if (apIP !== originalSettings?.apIP) { await controllerService?.send(new Command(`$AP/IP=${ apIP}`)); } if (apCountry !== originalSettings?.apCountry) { await controllerService?.send( new Command(`$AP/Country=${ apCountry}`) ); } // Reload settings after save await loadSettings() useUiContextFn.haptic() } catch (error) { console.error("Failed to save settings:", error) } finally { setIsSaving(false) } } // Load settings on mount useEffect(() => { loadSettings() refreshWifiStats() }, []) let style: string= hasChanges ? "max-height: calc(100dvh - 170px); overflow-y: scroll;" : "max-height: 100%; overflow-y: scroll;" return (
{isLoading && } {!isLoading && ( {/*

{T("S35")}

*/}
{/* Main Settings - Label and Input on same row */}
Hostname:
WiFi Mode:
Password:
{/* Min Security and IP Mode */}
Min Security:
{/* Static IP Settings */} {stationIpMode === "Static" && (
)} )} {/* Access Point Settings */} {(wifiMode === "STA>AP" || wifiMode === "AP") && (

Access Point Settings

{/* AP SSID and Password */}
SSID:
Password:
{/* AP Country and Channel */}
Country:
{/* AP IP */}
IP Address:
)} {/* Action Buttons */}
)}
{hasChanges && ( } disabled={isSaving} onClick={(e: TargetedMouseEvent) => { useUiContextFn.haptic() e.currentTarget.blur() saveSettings() }} /> )}
) } export { WifiTab }