import React, { useState, useEffect, useRef } from "react"; import { BLEDeviceManager, DeviceType, createEmulatorBluetooth, } from "@tomquist/hmjs-ble"; import { DeviceInfo, RuntimeInfo, CellInfo, TimerInfo, TimerInfoResponse, MQTTConfig, HMDeviceProtocol, WIFI_ILLEGAL_CHARACTERS, WIFI_PASSWORD_MIN_LENGTH, CHARGE_MODE, DEVICE_FAMILIES, DeviceFamily, } from "@tomquist/hmjs-protocol"; import { DisclaimerModal, BluetoothUnsupportedModal, ConnectionPanel, DeviceInfoTab, RuntimeTab, CellInfoTab, TimersTab, ConfigurationTab, DeviceControlTab, AdvancedTab, FamilyStatusTab, } from "./components"; import { isIOS, isBluetoothSupported } from "./utils/platform.js"; // Tabs enum enum TabType { DeviceInfo = "device-info-tab", Runtime = "runtime-tab", CellInfo = "cell-tab", Timers = "timers-tab", Configuration = "config-tab", DeviceControl = "device-control-tab", FamilyStatus = "family-status-tab", Advanced = "advanced-tab", } /** Tabs that only make sense on a B2500 */ const B2500_TABS = new Set([ TabType.Runtime, TabType.CellInfo, TabType.Timers, TabType.DeviceControl, ]); // Found device interface interface FoundDevice { device: BluetoothDevice; name: string; id: string; } const App: React.FC = () => { // Disclaimer state const [disclaimerAccepted, setDisclaimerAccepted] = useState(false); // An emulated device in marsemu (?emulator=ws://localhost:7101/) instead // of Web Bluetooth const [emulatorUrl, setEmulatorUrl] = useState( () => new URLSearchParams(window.location.search).get("emulator") ?? "", ); const emulatorRef = useRef<{ url: string; bluetooth: Bluetooth } | null>( null, ); const emulatorBluetooth = (): Bluetooth | undefined => { const url = emulatorUrl.trim(); if (!url) return undefined; if (emulatorRef.current?.url !== url) { emulatorRef.current = { url, bluetooth: createEmulatorBluetooth(url) }; } return emulatorRef.current.bluetooth; }; // Web Bluetooth unsupported state (irrelevant when talking to an emulator) const [bluetoothUnsupported, setBluetoothUnsupported] = useState( () => !isBluetoothSupported() && !new URLSearchParams(window.location.search).get("emulator"), ); // State variables const [activeTab, setActiveTab] = useState(TabType.DeviceInfo); const [isConnected, setIsConnected] = useState(false); const [isScanning, setIsScanning] = useState(false); const [connectionStatus, setConnectionStatus] = useState("Disconnected"); // Family of the connected device; undefined until known (treated as B2500) const [family, setFamily] = useState(undefined); const isB2500 = family === undefined || family === "b2500"; const [autoReconnect, setAutoReconnect] = useState(true); const [selectedDevice, setSelectedDevice] = useState( null, ); const [allowAnyDevice, setAllowAnyDevice] = useState(false); const [deviceType, setDeviceType] = useState("b2500"); // Track previous active tab for refresh logic const prevActiveTabRef = useRef(activeTab); // Device info states const [deviceInfo, setDeviceInfo] = useState(null); const [infoStatus, setInfoStatus] = useState("-"); const [lastUpdateTime, setLastUpdateTime] = useState("-"); // Runtime info state const [runtimeInfo, setRuntimeInfo] = useState(null); // Cell info state const [cellInfo, setCellInfo] = useState(null); // Timer schedule state const [timerInfo, setTimerInfo] = useState(null); // Logs state const [logs, setLogs] = useState([]); // Advanced mode state const [rawResponses, setRawResponses] = useState([]); // Device manager ref to maintain instance between renders const deviceManagerRef = useRef(null); // Format hex dump for display (similar to hexdump -C) const formatHexDump = (data: Uint8Array): string => { const lines: string[] = []; for (let i = 0; i < data.length; i += 16) { const chunk = data.slice(i, i + 16); // Offset (8 hex digits) const offset = i.toString(16).padStart(8, "0"); // Hex bytes (16 bytes per line, grouped by 8) const hexPart1 = Array.from(chunk.slice(0, 8)) .map((b) => b.toString(16).padStart(2, "0")) .join(" "); const hexPart2 = Array.from(chunk.slice(8, 16)) .map((b) => b.toString(16).padStart(2, "0")) .join(" "); // Pad hex parts to fixed width const paddedHex1 = hexPart1.padEnd(23, " "); // 8 bytes * 2 chars + 7 spaces = 23 const paddedHex2 = hexPart2.padEnd(23, " "); // ASCII representation const ascii = Array.from(chunk) .map((b) => (b >= 32 && b <= 126 ? String.fromCharCode(b) : ".")) .join(""); // Combine parts: offset + hex1 + hex2 + ascii lines.push(`${offset} ${paddedHex1} ${paddedHex2} |${ascii}|`); } return lines.join("\n"); }; // Initialize device manager useEffect(() => { // Log function for device manager const logFunction = (message: string, ...args: unknown[]): void => { console.log(message, ...args); // Format the message if it has replacements let formattedMessage = message; if (args.length > 0) { try { // Try to format any objects formattedMessage = args.reduce((msg, arg, index) => { if (typeof arg === "object") { return msg.replace(`{${index}}`, JSON.stringify(arg)); } return msg.replace(`{${index}}`, String(arg)); }, message); } catch { // Fallback to basic string concatenation if formatting fails formattedMessage = `${message} ${args.join(" ")}`; } } setLogs((prevLogs) => [ ...prevLogs, `${new Date().toLocaleTimeString()} - ${formattedMessage}`, ]); }; // Create a new device manager deviceManagerRef.current = new BLEDeviceManager({ autoReconnect: true, reconnectDelay: 2000, logger: logFunction, }); const deviceManager = deviceManagerRef.current; // Set up event listeners deviceManager.on("connect", (device: BluetoothDevice) => { setIsConnected(true); setConnectionStatus(`Connected to ${device.name || "device"}`); // Update the selected device if needed const newDevice = { device, name: device.name || "Unknown Device", id: device.id || "unknown", }; setSelectedDevice(newDevice); // Automatically get device info setTimeout(async () => { try { // Log connection state for debugging logFunction( `Connection state before getDeviceInfo: isConnected=${deviceManager.isConnected()}`, ); await deviceManager.getDeviceInfo(); // Ensure connection state remains true even if the internal flag gets reset setIsConnected(true); // Log connection state after successful device info retrieval logFunction( `Connection state after getDeviceInfo: isConnected=${deviceManager.isConnected()}`, ); } catch (error) { logFunction( `Error getting initial device info: ${error instanceof Error ? error.message : String(error)}`, ); } }, 1000); }); deviceManager.on("familyDetected", (detected: DeviceFamily) => { setFamily(detected); if (detected !== "b2500") { setActiveTab((tab) => B2500_TABS.has(tab) ? TabType.FamilyStatus : tab, ); } }); deviceManager.on("disconnect", () => { setIsConnected(false); setFamily(undefined); setConnectionStatus("Disconnected"); // Clear all device data when device disconnects setDeviceInfo(null); setRuntimeInfo(null); setCellInfo(null); setTimerInfo(null); setInfoStatus("-"); setLastUpdateTime("-"); setSelectedDevice(null); setRawResponses([]); }); deviceManager.on("reconnect", (device: BluetoothDevice) => { setIsConnected(true); setConnectionStatus(`Reconnected to ${device.name || "device"}`); setSelectedDevice({ device, name: device.name || "Unknown Device", id: device.id || "unknown", }); }); deviceManager.on("error", (error: Error) => { logFunction(`Error: ${error.message}`); }); deviceManager.on("deviceInfo", (info: DeviceInfo) => { logFunction("Received device info: " + JSON.stringify(info)); setDeviceInfo(info); setInfoStatus("Success"); setLastUpdateTime(new Date().toLocaleTimeString()); }); deviceManager.on("runtimeInfo", (info: RuntimeInfo) => { logFunction("Received runtime info"); setRuntimeInfo(info); }); deviceManager.on("cellInfo", (info: CellInfo) => { logFunction( `Received cell info: SOC=${info.soc}%, Temp=${info.temperature1}°C, Cells=${info.cellVoltages.length}`, ); setCellInfo(info); }); deviceManager.on("timerInfo", (info: TimerInfoResponse) => { logFunction( `Received timer schedule: ${info.timers.length} timer entries`, ); setTimerInfo(info); }); deviceManager.on("rawData", (data: Uint8Array) => { const timestamp = new Date().toLocaleTimeString(); const hexDump = formatHexDump(data); setRawResponses((prevResponses) => [ ...prevResponses, `${timestamp} - ${hexDump}`, ]); }); // Check if Web Bluetooth API is supported if ( !isBluetoothSupported() && !new URLSearchParams(window.location.search).get("emulator") ) { logFunction("Web Bluetooth API is not supported in this browser"); setBluetoothUnsupported(true); setConnectionStatus("Bluetooth not supported in this browser"); } // Clean up event listeners on unmount return () => { // No need to clean up event listeners since they'll be garbage collected // when the device manager instance is no longer referenced }; }, []); // Update device manager when autoReconnect changes useEffect(() => { if (deviceManagerRef.current) { deviceManagerRef.current.setAutoReconnect(autoReconnect); } }, [autoReconnect]); // Update device manager when deviceType changes useEffect(() => { if (deviceManagerRef.current) { deviceManagerRef.current.setDeviceType(deviceType); } }, [deviceType]); // Refresh data when tab changes useEffect(() => { if (isConnected && prevActiveTabRef.current !== activeTab) { // Runtime tab if (activeTab === TabType.Runtime) { getRuntimeInfo(); } // Cell Info tab else if (activeTab === TabType.CellInfo) { getCellInfo(); } // Timers tab else if (activeTab === TabType.Timers) { getTimerSchedule(); } } // Update previous tab reference prevActiveTabRef.current = activeTab; }, [activeTab, isConnected]); // eslint-disable-line react-hooks/exhaustive-deps // Scan for devices and connect automatically const scanForDevices = async () => { try { // If already connected, disconnect first if (isConnected && deviceManagerRef.current) { await deviceManagerRef.current.disconnect(); } // Clear all device data when starting a new scan setDeviceInfo(null); setRuntimeInfo(null); setCellInfo(null); setTimerInfo(null); setInfoStatus("-"); setLastUpdateTime("-"); setConnectionStatus("Scanning for devices..."); setIsScanning(true); try { if (deviceManagerRef.current) { // Use the BLE package's scanForDevices method const device = await deviceManagerRef.current.scanForDevices({ acceptAllDevices: allowAnyDevice, bluetooth: emulatorBluetooth(), }); // Only proceed if we have a valid device. Whitelabeled devices may // advertise no name, so allow unnamed devices when accept-all is on. if (device.id && (device.name || allowAnyDevice)) { const deviceName = device.name || "Unnamed Device"; const newDevice = { device, name: deviceName, id: device.id, }; // Store selected device setSelectedDevice(newDevice); // Connect to the device immediately setInfoStatus("Connecting..."); setConnectionStatus(`Connecting to ${deviceName}...`); await deviceManagerRef.current.connect(device); } else { setConnectionStatus("No devices found"); } } } catch (e) { addLog(`Scanning error: ${e instanceof Error ? e.message : String(e)}`); setConnectionStatus("Scan canceled or failed"); } setIsScanning(false); } catch (error) { addLog( `Scan failed: ${error instanceof Error ? error.message : String(error)}`, ); setConnectionStatus("Scan Failed"); setIsScanning(false); } }; // Disconnect from device const disconnectFromDevice = () => { if (deviceManagerRef.current) { deviceManagerRef.current.disconnect(); // Clear all device data when disconnecting setDeviceInfo(null); setRuntimeInfo(null); setCellInfo(null); setTimerInfo(null); setInfoStatus("-"); setLastUpdateTime("-"); setSelectedDevice(null); setConnectionStatus("Disconnected"); setIsConnected(false); setRawResponses([]); } }; // Get device info const getDeviceInfo = async () => { try { setInfoStatus("Fetching..."); if (deviceManagerRef.current) { const deviceManager = deviceManagerRef.current; // Log connection state before request addLog( `Connection state before getDeviceInfo: isConnected=${deviceManager.isConnected()}`, ); // If device is not connected according to device manager but our state says it is, try to reconnect if (!deviceManager.isConnected() && isConnected && selectedDevice) { addLog("Connection state mismatch - attempting to reconnect..."); const savedDevice = selectedDevice.device; try { await deviceManager.connect(savedDevice); addLog("Reconnection successful"); } catch (reconnectError) { addLog( `Reconnection failed: ${reconnectError instanceof Error ? reconnectError.message : String(reconnectError)}`, ); setIsConnected(false); setInfoStatus("Failed - Disconnected"); throw new Error("Failed to reconnect to device"); } } addLog(`Sending getDeviceInfo command...`); await deviceManager.getDeviceInfo(); // Always ensure our connection state is synchronized setIsConnected(true); } } catch (error) { addLog( `Error getting device info: ${error instanceof Error ? error.message : String(error)}`, ); setInfoStatus("Failed"); } }; // Get runtime info const getRuntimeInfo = async () => { try { if (deviceManagerRef.current) { const deviceManager = deviceManagerRef.current; // Log connection state before request addLog( `Connection state before getRuntimeInfo: isConnected=${deviceManager.isConnected()}`, ); // If device is not connected according to device manager but our state says it is, try to reconnect if (!deviceManager.isConnected() && isConnected && selectedDevice) { addLog("Connection state mismatch - attempting to reconnect..."); const savedDevice = selectedDevice.device; try { await deviceManager.connect(savedDevice); addLog("Reconnection successful"); } catch (reconnectError) { addLog( `Reconnection failed: ${reconnectError instanceof Error ? reconnectError.message : String(reconnectError)}`, ); setIsConnected(false); throw new Error("Failed to reconnect to device"); } } addLog(`Sending getRuntimeInfo command...`); await deviceManager.getRuntimeInfo(); // Log success addLog(`Runtime info request successful`); // Always ensure our connection state is synchronized setIsConnected(true); } } catch (error) { addLog( `Error getting runtime info: ${error instanceof Error ? error.message : String(error)}`, ); } }; // Get cell info const getCellInfo = async () => { try { if (deviceManagerRef.current) { const deviceManager = deviceManagerRef.current; // Log connection state before request addLog( `Connection state before getCellInfo: isConnected=${deviceManager.isConnected()}`, ); // If device is not connected according to device manager but our state says it is, try to reconnect if (!deviceManager.isConnected() && isConnected && selectedDevice) { addLog("Connection state mismatch - attempting to reconnect..."); const savedDevice = selectedDevice.device; try { await deviceManager.connect(savedDevice); addLog("Reconnection successful"); } catch (reconnectError) { addLog( `Reconnection failed: ${reconnectError instanceof Error ? reconnectError.message : String(reconnectError)}`, ); setIsConnected(false); throw new Error("Failed to reconnect to device"); } } addLog(`Sending getCellInfo command...`); await deviceManager.getCellInfo(); // Log success addLog(`Cell info request successful`); // Always ensure our connection state is synchronized setIsConnected(true); } } catch (error) { addLog( `Error getting cell info: ${error instanceof Error ? error.message : String(error)}`, ); } }; // Read the timer schedule from the device const getTimerSchedule = async () => { try { if (deviceManagerRef.current) { const deviceManager = deviceManagerRef.current; addLog( `Connection state before getTimers: isConnected=${deviceManager.isConnected()}`, ); if (!deviceManager.isConnected() && isConnected && selectedDevice) { addLog("Connection state mismatch - attempting to reconnect..."); const savedDevice = selectedDevice.device; try { await deviceManager.connect(savedDevice); addLog("Reconnection successful"); } catch (reconnectError) { addLog( `Reconnection failed: ${reconnectError instanceof Error ? reconnectError.message : String(reconnectError)}`, ); setIsConnected(false); throw new Error("Failed to reconnect to device"); } } addLog("Sending getTimers command..."); await deviceManager.getTimers(); addLog("Timer schedule request successful"); setIsConnected(true); } } catch (error) { addLog( `Error getting timer schedule: ${error instanceof Error ? error.message : String(error)}`, ); } }; // Write the complete timer schedule back to the device const setTimerSchedule = async (timers: TimerInfo[]) => { if (!timers.length) { alert("Read the current schedule from the device first"); return; } if ( !confirm( `Overwrite all ${timers.length} timer slots on the device?\n\n` + "The schedule is stored in the device's flash memory, so avoid " + "writing it repeatedly.", ) ) { return; } try { if (deviceManagerRef.current) { const deviceManager = deviceManagerRef.current; addLog( `Connection state before setTimers: isConnected=${deviceManager.isConnected()}`, ); if (!deviceManager.isConnected() && isConnected && selectedDevice) { addLog("Connection state mismatch - attempting to reconnect..."); const savedDevice = selectedDevice.device; try { await deviceManager.connect(savedDevice); addLog("Reconnection successful"); } catch (reconnectError) { addLog( `Reconnection failed: ${reconnectError instanceof Error ? reconnectError.message : String(reconnectError)}`, ); setIsConnected(false); throw new Error("Failed to reconnect to device"); } } addLog(`Sending setTimers command with ${timers.length} entries...`); await deviceManager.setTimers(timers); addLog("Timer schedule sent successfully"); alert("Timer schedule sent successfully"); setIsConnected(true); } } catch (error) { addLog( `Error setting timer schedule: ${error instanceof Error ? error.message : String(error)}`, ); alert( `Failed to set timer schedule: ${error instanceof Error ? error.message : String(error)}`, ); } }; // Set WiFi config const setWifiConfig = async (ssid: string, password: string) => { if (!ssid) { alert("SSID is required"); return; } if (!password) { alert("Password is required"); return; } // Catch the characters the device cannot store before asking the user to // confirm - otherwise the device accepts the command and then silently // fails to join the network. const illegalIn = (value: string) => WIFI_ILLEGAL_CHARACTERS.filter((char) => value.includes(char)); const illegalFields = [ { label: "SSID", chars: illegalIn(ssid) }, { label: "Password", chars: illegalIn(password) }, ].filter((field) => field.chars.length > 0); if (illegalFields.length > 0) { alert( `${illegalFields .map( (field) => `${field.label} contains ${field.chars.map((char) => `\`${char}\``).join(" and ")}`, ) .join("\n")}\n\n` + `The device cannot store these characters and will fail to connect. ` + `Change your WiFi credentials to avoid them.`, ); return; } if (password.length < WIFI_PASSWORD_MIN_LENGTH) { alert( `Password must be at least ${WIFI_PASSWORD_MIN_LENGTH} characters.`, ); return; } // Confirm before sending if ( !confirm( `Are you sure you want to set WiFi to:\nSSID: ${ssid}\nPassword: [hidden]`, ) ) { return; } try { if (deviceManagerRef.current) { const deviceManager = deviceManagerRef.current; // Log connection state before request addLog( `Connection state before setWifiConfig: isConnected=${deviceManager.isConnected()}`, ); // If device is not connected according to device manager but our state says it is, try to reconnect if (!deviceManager.isConnected() && isConnected && selectedDevice) { addLog("Connection state mismatch - attempting to reconnect..."); const savedDevice = selectedDevice.device; try { await deviceManager.connect(savedDevice); addLog("Reconnection successful"); } catch (reconnectError) { addLog( `Reconnection failed: ${reconnectError instanceof Error ? reconnectError.message : String(reconnectError)}`, ); setIsConnected(false); throw new Error("Failed to reconnect to device"); } } addLog(`Sending setWifiConfig command...`); await deviceManager.setWifiConfig(ssid, password); addLog("WiFi configuration sent successfully"); alert("WiFi configuration set successfully"); // Always ensure our connection state is synchronized setIsConnected(true); } } catch (error) { addLog( `Error setting WiFi config: ${error instanceof Error ? error.message : String(error)}`, ); alert( `Failed to set WiFi configuration: ${error instanceof Error ? error.message : String(error)}`, ); } }; // Set MQTT config const setMqttConfig = async (config: MQTTConfig) => { if (!config.host) { alert("Host is required"); return; } if (!config.port) { alert("Port is required"); return; } // Confirm before sending if ( !confirm( `Are you sure you want to set MQTT to:\nHost: ${config.host}\nPort: ${config.port}\nSSL: ${config.ssl ? "Yes" : "No"}\nUsername: ${config.username || "[none]"}\nPassword: ${config.password ? "[hidden]" : "[none]"}`, ) ) { return; } try { if (deviceManagerRef.current) { const deviceManager = deviceManagerRef.current; // Log connection state before request addLog( `Connection state before setMqttConfig: isConnected=${deviceManager.isConnected()}`, ); // If device is not connected according to device manager but our state says it is, try to reconnect if (!deviceManager.isConnected() && isConnected && selectedDevice) { addLog("Connection state mismatch - attempting to reconnect..."); const savedDevice = selectedDevice.device; try { await deviceManager.connect(savedDevice); addLog("Reconnection successful"); } catch (reconnectError) { addLog( `Reconnection failed: ${reconnectError instanceof Error ? reconnectError.message : String(reconnectError)}`, ); setIsConnected(false); throw new Error("Failed to reconnect to device"); } } addLog(`Sending setMqttConfig command...`); await deviceManager.setMqttConfig(config); addLog("MQTT configuration sent successfully"); alert("MQTT configuration set successfully"); // Always ensure our connection state is synchronized setIsConnected(true); } } catch (error) { addLog( `Error setting MQTT config: ${error instanceof Error ? error.message : String(error)}`, ); alert( `Failed to set MQTT configuration: ${error instanceof Error ? error.message : String(error)}`, ); } }; // Reset MQTT config /** * Run a command against the connected device, reconnecting first if our * connection state has drifted, and reporting failures the same way the * other handlers do. */ const runDeviceCommand = async ( label: string, run: (deviceManager: BLEDeviceManager) => Promise, successMessage?: string, ) => { try { const deviceManager = deviceManagerRef.current; if (!deviceManager) return; // BLEDeviceManager keeps the device in a private `device` field, so the // app's own selectedDevice is what we can reconnect from. if (!deviceManager.isConnected() && isConnected && selectedDevice) { addLog("Connection state mismatch - attempting to reconnect..."); const savedDevice = selectedDevice.device; try { await deviceManager.connect(savedDevice); addLog("Reconnection successful"); } catch (reconnectError) { addLog( `Reconnection failed: ${reconnectError instanceof Error ? reconnectError.message : String(reconnectError)}`, ); setIsConnected(false); throw new Error("Failed to reconnect to device"); } } addLog(`Sending ${label} command...`); await run(deviceManager); addLog(`${label} sent successfully`); if (successMessage) alert(successMessage); setIsConnected(true); } catch (error) { const message = error instanceof Error ? error.message : String(error); addLog(`Error sending ${label}: ${message}`); alert(`Failed to send ${label}: ${message}`); } }; const setDod = async (percent: number) => runDeviceCommand( "set DOD", (dm) => dm.setDod(percent), `Depth of discharge set to ${percent}%`, ); const setDischargeThreshold = async (watts: number) => runDeviceCommand( "set discharge threshold", (dm) => dm.setDischargeThreshold(watts), `Discharge threshold set to ${watts}W`, ); const setChargeMode = async (mode: number) => runDeviceCommand( "set charge mode", (dm) => dm.setChargeMode(mode), `Charging mode set to ${mode === CHARGE_MODE.FULL ? "fully charge, then discharge" : "charge and discharge together"}`, ); const setOutputChannels = async (mask: number) => runDeviceCommand( "set output channels", (dm) => dm.setOutputChannels(mask), "Output channels updated", ); const setAdaptiveMode = async (enabled: boolean) => runDeviceCommand( "set adaptive mode", (dm) => dm.setAdaptiveMode(enabled), `Adaptive mode ${enabled ? "enabled" : "disabled"}`, ); const setDeviceDateTime = async () => { const now = new Date(); if (!confirm(`Set the device clock to ${now.toLocaleString()}?`)) return; return runDeviceCommand( "set date/time", (dm) => dm.setDateTime(now), "Device clock updated", ); }; const restartDevice = async () => { if ( !confirm( "Restart the device? The Bluetooth connection will drop until it comes back up.", ) ) { return; } return runDeviceCommand("restart device", (dm) => dm.restartDevice()); }; const runDiagnosis = async () => { if (!confirm("Ask the device to re-run its CT diagnosis?")) return; return runDeviceCommand("run diagnosis", (dm) => dm.runDiagnosis()); }; const getWifiInfo = async () => runDeviceCommand("read WiFi info", (dm) => dm.getWifiInfo()); const getErrorInfo = async () => runDeviceCommand("read error info", (dm) => dm.getErrorInfo()); const resetMqttConfig = async () => { // Confirm before sending if (!confirm("Are you sure you want to reset the MQTT configuration?")) { return; } try { if (deviceManagerRef.current) { const deviceManager = deviceManagerRef.current; // Log connection state before request addLog( `Connection state before resetMqttConfig: isConnected=${deviceManager.isConnected()}`, ); // If device is not connected according to device manager but our state says it is, try to reconnect if (!deviceManager.isConnected() && isConnected && selectedDevice) { addLog("Connection state mismatch - attempting to reconnect..."); const savedDevice = selectedDevice.device; try { await deviceManager.connect(savedDevice); addLog("Reconnection successful"); } catch (reconnectError) { addLog( `Reconnection failed: ${reconnectError instanceof Error ? reconnectError.message : String(reconnectError)}`, ); setIsConnected(false); throw new Error("Failed to reconnect to device"); } } addLog(`Sending resetMqttConfig command...`); await deviceManager.resetMqttConfig(); addLog("MQTT configuration reset successfully"); alert("MQTT configuration reset successfully"); // Always ensure our connection state is synchronized setIsConnected(true); } } catch (error) { addLog( `Error resetting MQTT config: ${error instanceof Error ? error.message : String(error)}`, ); alert( `Failed to reset MQTT configuration: ${error instanceof Error ? error.message : String(error)}`, ); } }; // Convert hex string to bytes const parseHexString = (hexString: string): Uint8Array => { // Clean up the hex string - remove spaces and 0x prefixes const cleanHex = hexString.replace(/\s+/g, "").replace(/0x/gi, ""); // Validate hex string if (!/^[0-9a-fA-F]+$/.test(cleanHex)) { throw new Error( "Invalid hex string - must contain only hex characters (0-9, A-F)", ); } if (cleanHex.length % 2 !== 0) { throw new Error( "Invalid hex string - must have even number of characters", ); } // Convert to byte array const bytes = new Uint8Array(cleanHex.length / 2); for (let i = 0; i < cleanHex.length; i += 2) { bytes[i / 2] = parseInt(cleanHex.substr(i, 2), 16); } return bytes; }; // Build command from command type and payload const buildCommand = ( commandType: string, payload: string, payloadType: "hex" | "string" = "hex", ): string => { // Parse command type (hex or decimal) let cmdType: number; if (commandType.startsWith("0x") || commandType.startsWith("0X")) { cmdType = parseInt(commandType, 16); } else if (/^[0-9a-fA-F]+$/.test(commandType) && commandType.length <= 2) { cmdType = parseInt(commandType, 16); } else { cmdType = parseInt(commandType, 10); } if (isNaN(cmdType) || cmdType < 0 || cmdType > 255) { throw new Error( "Invalid command type - must be 0-255 (decimal) or 0x00-0xFF (hex)", ); } // Parse payload if provided let payloadBytes: Uint8Array | null = null; if (payload.trim()) { if (payloadType === "string") { // Convert string to UTF-8 bytes const encoder = new TextEncoder(); payloadBytes = encoder.encode(payload); } else { // Parse as hex string payloadBytes = parseHexString(payload.trim()); } } // Create command using protocol const protocol = new HMDeviceProtocol(); const commandBytes = protocol.createCommandMessage(cmdType, payloadBytes); // Convert to hex string for display return Array.from(commandBytes) .map((b) => b.toString(16).padStart(2, "0")) .join(" "); }; // Send raw hex command const sendRawCommand = async (hexString: string) => { if (!deviceManagerRef.current) { throw new Error("Device manager not initialized"); } if (!isConnected) { throw new Error("Not connected to device"); } // Parse hex string in the UI layer const bytes = parseHexString(hexString); addLog(`Sending raw command: ${hexString}`); await deviceManagerRef.current.sendRawBytes(bytes); }; // Add log message const addLog = (message: string) => { setLogs((prevLogs) => [ ...prevLogs, `${new Date().toLocaleTimeString()} - ${message}`, ]); }; // Clear logs const clearLogs = () => { setLogs([]); addLog("Logs cleared"); }; if (bluetoothUnsupported) { return ; } if (!disclaimerAccepted) { return setDisclaimerAccepted(true)} />; } return (

Marstek BLE Tool

Connect to your Marstek battery or meter and manage its settings. {family && ` Connected device: ${DEVICE_FAMILIES[family].label}.`}

{isB2500 && ( )} {isB2500 && ( )} {isB2500 && ( )} {isB2500 && ( )}
{activeTab === TabType.DeviceInfo && ( )} {activeTab === TabType.Runtime && ( )} {activeTab === TabType.CellInfo && ( )} {activeTab === TabType.Timers && ( )} {activeTab === TabType.Configuration && ( )} {activeTab === TabType.DeviceControl && ( )} {activeTab === TabType.FamilyStatus && ( setLogs((prev) => [ ...prev, `${new Date().toLocaleTimeString()} - ${message}`, ]) } /> )} {activeTab === TabType.Advanced && ( )}
{/* Logs Panel - Always visible */}

Debug Logs

{ // Auto-scroll to bottom when logs update if (el) { el.scrollTop = el.scrollHeight; } }} > {logs.map((log, index) => (
{log}
))}
); }; export default App;