Loading files
This file is pinned to the selected release. Download the original to open it in your design tool.
<!-- SPDX-License-Identifier: GPL-3.0-or-later -->
<!-- Copyright (C) 2025 Jibril Sharafi -->
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" type="text/css" href="/css/button.css">
<link rel="stylesheet" type="text/css" href="/css/styles.css">
<link rel="stylesheet" type="text/css" href="/css/section.css">
<link rel="stylesheet" type="text/css" href="/css/typography.css">
<link rel="stylesheet" type="text/css" href="/css/forms.css">
<link rel="stylesheet" type="text/css" href="/css/reboot-wait.css">
<link rel="icon" type="image/svg+xml" href="/favicon.svg">
<title>Configuration</title>
<style>
/* Slider-specific styles */
.slider {
-webkit-appearance: none;
appearance: none;
width: 100%;
height: 15px;
border-radius: 5px;
background: linear-gradient(to right, var(--green) 0%, var(--green) calc(var(--slider-value, 50%) - 1.25%), #d3d3d3 calc(var(--slider-value, 50%) + 1.25%), #d3d3d3 100%);
outline: none;
opacity: 0.7;
-webkit-transition: .2s;
transition: opacity .2s;
}
.slider:hover {
opacity: 1;
}
.slider::-webkit-slider-thumb {
-webkit-appearance: none;
appearance: none;
width: 25px;
height: 25px;
border-radius: 50%;
background: var(--green);
cursor: pointer;
}
.slider::-moz-range-thumb {
width: 25px;
height: 25px;
border-radius: 50%;
background: var(--green);
cursor: pointer;
}
/* Page-specific mobile styles */
@media screen and (max-width: 768px) {
.slider {
height: 20px;
margin: 10px 0;
}
.slider::-webkit-slider-thumb {
width: 30px;
height: 30px;
}
.slider::-moz-range-thumb {
width: 30px;
height: 30px;
}
}
.portal-banner {
margin-top: 18px;
padding: 14px 18px;
background: linear-gradient(135deg, rgba(8,191,129,0.08), rgba(3,160,155,0.13));
border: 1px solid rgba(8,191,129,0.28);
border-radius: 12px;
}
.portal-banner p {
margin: 0 0 12px 0;
font-size: 0.88em;
color: #555;
}
.portal-cta {
display: inline-flex;
align-items: center;
gap: 6px;
padding: 9px 22px;
background: linear-gradient(135deg, #08bf81, #03a09b);
color: #fff;
border-radius: 50px;
text-decoration: none;
font-weight: bold;
font-size: 0.92em;
box-shadow: 0 4px 14px rgba(8,191,129,0.32);
transition: box-shadow 0.18s ease, transform 0.18s ease;
letter-spacing: 0.01em;
}
.portal-cta:hover {
box-shadow: 0 6px 20px rgba(8,191,129,0.52);
transform: translateY(-1px);
}
.portal-cta:active {
transform: scale(0.97);
box-shadow: 0 2px 8px rgba(8,191,129,0.22);
}
.portal-cta-disabled {
background: linear-gradient(135deg, #b0b0b0, #c8c8c8);
box-shadow: 0 2px 8px rgba(0,0,0,0.10);
opacity: 0.72;
pointer-events: none;
cursor: default;
}
/* Disco mode: the page joins in while the device LED does. Purely decorative,
so it never blocks input. */
#discoOverlay {
position: fixed;
inset: 0;
z-index: 9000;
pointer-events: none;
opacity: 0;
transition: opacity 0.4s ease;
background-color: rgba(0, 0, 0, 0.55);
}
#discoOverlay.dancing {
opacity: 1;
animation: discoTint 3.2s steps(1, end) infinite;
}
/* 400 ms a colour, i.e. 2.5 Hz. Deliberately slower than the LED's 120 ms step:
a full-screen flash above ~3 Hz is a photosensitivity risk in a way a pinpoint
LED is not. */
@keyframes discoTint {
0% { background-color: rgba(120, 0, 0, 0.62); }
12.5% { background-color: rgba(0, 110, 0, 0.62); }
25% { background-color: rgba(0, 0, 130, 0.62); }
37.5% { background-color: rgba(120, 110, 0, 0.62); }
50% { background-color: rgba(115, 0, 125, 0.62); }
62.5% { background-color: rgba(0, 110, 120, 0.62); }
75% { background-color: rgba(125, 60, 0, 0.62); }
87.5% { background-color: rgba(90, 90, 90, 0.62); }
}
@media (prefers-reduced-motion: reduce) {
#discoOverlay.dancing {
animation: none;
}
}
/* Loading indicator for config fields that show a stale default until
their real value arrives from the device (checkbox, slider, selects). */
.field-spinner {
display: inline-block;
width: 14px;
height: 14px;
border: 2px solid var(--green);
border-right-color: transparent;
border-radius: 50%;
animation: field-spin 0.7s linear infinite;
vertical-align: middle;
margin-left: 8px;
}
@keyframes field-spin {
to { transform: rotate(360deg); }
}
.config-input.field-loading {
opacity: 0.5;
}
/* WiFi network picker - same look as wifi-setup.html */
.wifi-list-header { display: flex; justify-content: space-between; align-items: center; margin: 15px 0 6px; font-weight: 600; }
.wifi-scan-button { background: none; border: 1px solid #ccc; border-radius: 5px; padding: 4px 10px; cursor: pointer; font-size: 0.85em; color: inherit; }
.wifi-scan-button:hover:not(:disabled) { background: #f0f0f0; }
.wifi-scan-button:disabled { opacity: 0.6; cursor: default; }
.wifi-network-list { list-style: none; margin: 0 0 12px; padding: 0; border: 1px solid #ddd; border-radius: 8px; overflow-y: auto; max-height: 260px; }
.wifi-network-list li { display: flex; align-items: center; gap: 8px; padding: 10px 12px; cursor: pointer; border-bottom: 1px solid #eee; }
.wifi-network-list li:last-child { border-bottom: none; }
.wifi-network-list li:hover, .wifi-network-list li.selected { background: #f0f0f0; }
.wifi-network-list li.wifi-list-note { cursor: default; color: #777; font-style: italic; background: none; }
.wifi-network-name { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.wifi-network-meta { flex: none; display: flex; align-items: center; gap: 7px; font-size: 0.8em; color: #666; }
.wifi-bars { display: inline-flex; align-items: flex-end; gap: 2px; height: 13px; }
.wifi-bars i { display: block; width: 3px; background: #d0d0d0; border-radius: 1px; }
.wifi-bars i.on { background: var(--green, #2e7d32); }
.wifi-bars i:nth-child(1) { height: 5px; }
.wifi-bars i:nth-child(2) { height: 9px; }
.wifi-bars i:nth-child(3) { height: 13px; }
</style>
</head>
<body>
<div id="discoOverlay"></div>
<div class="buttonNavigation-container">
<a class="buttonNavigation" type="home" href="/">🏠 Home</a>
<a class="buttonNavigation" type="inner" href="/calibration">⚖️ Calibration</a>
<a class="buttonNavigation" type="inner" href="/channel">📺 Channel</a>
</div>
<div class="section-box">
<h2>Cloud Services</h2>
<p><i>Cloud services are used to send data to the cloud. This is useful for monitoring the device
remotely and get the latest firmware updates.</i></p>
<input type="checkbox" id="cloudServices" class="config-input field-loading" disabled>
<label for="cloudServices">Enable cloud services</label>
<span id="cloudServicesSpinner" class="field-spinner"></span>
<br><br>
<button class="buttonForm" onclick="setCloudServices()" id="setCloudServicesButton">☁️ Set cloud services</button>
<div id="portalBanner" class="portal-banner">
<p id="portalMsg">🔍 Checking certificates...</p>
<a id="portalLink" href="#" target="_blank" rel="noopener noreferrer" class="portal-cta portal-cta-disabled">
⏳ Add to EnergyMe Portal ›
</a>
</div>
</div>
<div class="section-box">
<h2>LED</h2>
<p><i>LED brightness is used to adjust the brightness of the status LED on the device. Keeping a small
amount of brightness is recommended.</i></p>
<input type="range" id="ledBrightness" class="config-input slider field-loading" min="0" max="100"
oninput="updateBrightnessValue()" disabled>
<span id="ledBrightnessValue"> </span>
<span id="ledBrightnessSpinner" class="field-spinner"></span>
<br><br>
<button class="buttonForm" onclick="setLedBrightness()" id="setLedBrightnessButton">💡 Set brightness</button>
<p><i>Disco mode runs a short burst of colours on the status LED, then hands it back to the device.
Handy to confirm you are looking at the right meter.</i></p>
<button class="buttonForm" onclick="startDisco()" id="discoButton">🪩 Disco mode</button>
</div>
<div class="section-box">
<h2>Logging</h2>
<p><i>Logging is used to record events and errors. It is useful for debugging and troubleshooting.</i></p>
<div>
<h3>Print</h3>
<p><i>Print logging is used to display events and errors when the serial monitor is available. The serial
monitor is available when the device is connected to a computer via USB.</i></p>
<select id="printLogLevel" class="config-input field-loading" disabled></select>
<span id="printLogLevelSpinner" class="field-spinner"></span>
</div>
<br>
<div>
<h3>Save</h3>
<p><i>Save logging is used to record events and errors to the internal memory of the device. The internal
memory is limited, so it is recommended to only use this for troubleshooting.</i></p>
<select id="saveLogLevel" class="config-input field-loading" disabled></select>
<span id="saveLogLevelSpinner" class="field-spinner"></span>
</div>
<br>
<button class="buttonForm" onclick="setLogLevel()" id="setLogLevel">📝 Set logging level</button>
<button class="buttonForm" onclick="clearLogs()" id="clearLogs">🗑️ Clear log</button>
<a class="buttonForm" href="/log" id="log" style="float: right;">📋 Explore log</a>
</div>
<div class="section-box">
<h2>Time</h2>
<p><i>Sync the device time with your browser. Useful for devices without internet connectivity (isolated networks).</i></p>
<p id="currentDeviceTime">Device time: Loading...</p>
<button class="buttonForm" onclick="syncTime()" id="syncTime">🕐 Sync Time with browser</button>
</div>
<div class="section-box">
<h2>Change Password</h2>
<p><i>Change your password to secure your device. Default credentials should be changed immediately after first login.</i></p>
<div style="display: flex; flex-direction: column; gap: 10px; margin: 15px 0;">
<div>
<label for="currentPassword">Current Password:</label>
<input type="password" id="currentPassword" class="config-input" placeholder="Enter current password" style="width: 100%; padding: 8px; border: 1px solid #ddd; border-radius: 5px;">
</div>
<div>
<label for="newPassword">New Password:</label>
<input type="password" id="newPassword" class="config-input" placeholder="Enter new password (min. 8 characters)" style="width: 100%; padding: 8px; border: 1px solid #ddd; border-radius: 5px;">
</div>
<div>
<label for="confirmPassword">Confirm New Password:</label>
<input type="password" id="confirmPassword" class="config-input" placeholder="Confirm new password" style="width: 100%; padding: 8px; border: 1px solid #ddd; border-radius: 5px;">
</div>
</div>
<button class="buttonForm" onclick="changePassword()" id="changePasswordButton">🔑 Change Password</button>
</div>
<div class="section-box">
<h2>Restart Device</h2>
<p><i>You already know that restarting a device magically fixes most issues. It will take 10 seconds.</i></p>
<button class="buttonForm" onclick="restart()" id="restart">🔄 Restart</button>
</div>
<div class="section-box">
<h2>WiFi Configuration</h2>
<p><i>Advanced WiFi network settings. By default the device uses DHCP. Changing these requires a restart to take effect.</i></p>
<!-- Current network (live, read-only) so the user knows the starting point -->
<div id="currentNetworkBox"
style="background-color: #f5f5f5; border: 1px solid #e0e0e0; border-radius: 8px; padding: 12px 15px; margin: 12px 0;">
<div style="font-weight: 600; margin-bottom: 8px;">Current WiFi network</div>
<div style="display: grid; grid-template-columns: auto 1fr; gap: 5px 14px; font-size: 0.9em;">
<span style="color: #666;">Status</span><span id="curStatus">Loading...</span>
<span style="color: #666;">Mode</span><span id="curMode">-</span>
<span style="color: #666;">SSID</span><span id="curSsid">-</span>
<span style="color: #666;">IP address</span><span id="curIp">-</span>
<span style="color: #666;">Gateway</span><span id="curGateway">-</span>
<span style="color: #666;">Subnet mask</span><span id="curSubnet">-</span>
<span style="color: #666;">DNS</span><span id="curDns">-</span>
<span style="color: #666;">Signal</span><span id="curRssi">-</span>
</div>
</div>
<!-- Explicit either/or choice: DHCP vs Static IP -->
<fieldset style="border: 1px solid #e0e0e0; border-radius: 8px; padding: 8px 15px 10px; margin: 12px 0;">
<legend style="padding: 0 6px; font-weight: 600;">IP address mode</legend>
<label style="display: block; padding: 6px 0; cursor: pointer;">
<input type="radio" name="ipMode" value="dhcp" onchange="onIpModeChange()" checked>
Automatic (DHCP) - recommended
</label>
<label style="display: block; padding: 6px 0; cursor: pointer;">
<input type="radio" name="ipMode" value="static" onchange="onIpModeChange()">
Static IP - set the address manually
</label>
</fieldset>
<div id="staticIpFields" style="display: none; flex-direction: column; gap: 10px; margin: 15px 0;">
<div>
<label for="staticIp">IP Address:</label>
<input type="text" id="staticIp" class="config-input" inputmode="decimal" placeholder="e.g. 192.168.1.50" maxlength="15" style="width: 100%; padding: 8px; border: 1px solid #ddd; border-radius: 5px;">
</div>
<div>
<label for="staticGateway">Gateway (your router):</label>
<input type="text" id="staticGateway" class="config-input" inputmode="decimal" placeholder="e.g. 192.168.1.1" maxlength="15" onblur="prefillDnsFromGateway('staticGateway', 'staticDns1')" style="width: 100%; padding: 8px; border: 1px solid #ddd; border-radius: 5px;">
</div>
<div>
<label for="staticSubnet">Subnet Mask:</label>
<input type="text" id="staticSubnet" class="config-input" inputmode="decimal" placeholder="e.g. 255.255.255.0" maxlength="15" style="width: 100%; padding: 8px; border: 1px solid #ddd; border-radius: 5px;">
</div>
<div>
<label for="staticDns1">Primary DNS:</label>
<input type="text" id="staticDns1" class="config-input" inputmode="decimal" placeholder="defaults to your gateway" maxlength="15" style="width: 100%; padding: 8px; border: 1px solid #ddd; border-radius: 5px;">
<small style="color: #666;">Leave blank to use your gateway, or set a specific server (e.g. 8.8.8.8).</small>
</div>
<div>
<label for="staticDns2">Secondary DNS (optional):</label>
<input type="text" id="staticDns2" class="config-input" inputmode="decimal" placeholder="e.g. 1.1.1.1" maxlength="15" style="width: 100%; padding: 8px; border: 1px solid #ddd; border-radius: 5px;">
</div>
<div>
<input type="checkbox" id="fallbackToDhcp" class="config-input" onchange="updateRiskWarning()" checked>
<label for="fallbackToDhcp">Auto-recover to DHCP if this static IP fails (recommended)</label>
<small style="display: block; color: #666; margin-top: 4px;">
After restart the device checks the static IP. If it can't reach the internet, it reboots
once back into automatic (DHCP) so the device stays reachable. A separate boot-failure
safeguard also reverts to DHCP if the device can't start on the static IP - that one is always on.
</small>
</div>
</div>
<!-- Shown only when the user disables auto-recovery on a static IP -->
<div id="networkRiskWarning" role="alert"
style="display: none; background-color: #fff3cd; color: #856404; padding: 10px; border-radius: 5px; margin: 10px 0;">
⚠️ Warning - auto-recovery is off. If this static IP is wrong or conflicts with another device,
the device may become unreachable and you would have to recover it through the WiFi setup portal.
Keep auto-recovery on unless you are sure the address is correct.
</div>
<button class="buttonForm" onclick="setNetworkConfiguration()" id="setNetworkConfigButton">🌐 Apply & restart</button>
</div>
<!-- Ethernet (Home Pro only) - stays hidden unless the status endpoint reports Ethernet is available -->
<div class="section-box" id="ethernetSection" style="display: none;">
<h2>Ethernet Configuration</h2>
<p><i>Wired network settings. By default the device uses DHCP. Changing these requires a restart to take effect.</i></p>
<!-- Current Ethernet state (live, read-only) so the user knows the starting point -->
<div id="currentEthernetBox"
style="background-color: #f5f5f5; border: 1px solid #e0e0e0; border-radius: 8px; padding: 12px 15px; margin: 12px 0;">
<div style="font-weight: 600; margin-bottom: 8px;">Current Ethernet</div>
<div style="display: grid; grid-template-columns: auto 1fr; gap: 5px 14px; font-size: 0.9em;">
<span style="color: #666;">Link</span><span id="curEthLink">Loading...</span>
<span style="color: #666;">Active interface</span><span id="curEthActiveInterface">-</span>
<span style="color: #666;">Mode</span><span id="curEthMode">-</span>
<span style="color: #666;">IP address</span><span id="curEthIp">-</span>
<span style="color: #666;">Gateway</span><span id="curEthGateway">-</span>
<span style="color: #666;">Subnet mask</span><span id="curEthSubnet">-</span>
<span style="color: #666;">DNS</span><span id="curEthDns">-</span>
<span style="color: #666;">MAC address</span><span id="curEthMac">-</span>
</div>
</div>
<!-- Explicit either/or choice: DHCP vs Static IP -->
<fieldset style="border: 1px solid #e0e0e0; border-radius: 8px; padding: 8px 15px 10px; margin: 12px 0;">
<legend style="padding: 0 6px; font-weight: 600;">IP address mode</legend>
<label style="display: block; padding: 6px 0; cursor: pointer;">
<input type="radio" name="ethIpMode" value="dhcp" onchange="onEthIpModeChange()" checked>
Automatic (DHCP) - recommended
</label>
<label style="display: block; padding: 6px 0; cursor: pointer;">
<input type="radio" name="ethIpMode" value="static" onchange="onEthIpModeChange()">
Static IP - set the address manually
</label>
</fieldset>
<div id="ethStaticIpFields" style="display: none; flex-direction: column; gap: 10px; margin: 15px 0;">
<div>
<label for="ethStaticIp">IP Address:</label>
<input type="text" id="ethStaticIp" class="config-input" inputmode="decimal" placeholder="e.g. 192.168.1.51" maxlength="15" style="width: 100%; padding: 8px; border: 1px solid #ddd; border-radius: 5px;">
</div>
<div>
<label for="ethStaticGateway">Gateway (your router):</label>
<input type="text" id="ethStaticGateway" class="config-input" inputmode="decimal" placeholder="e.g. 192.168.1.1" maxlength="15" onblur="prefillDnsFromGateway('ethStaticGateway', 'ethStaticDns1')" style="width: 100%; padding: 8px; border: 1px solid #ddd; border-radius: 5px;">
</div>
<div>
<label for="ethStaticSubnet">Subnet Mask:</label>
<input type="text" id="ethStaticSubnet" class="config-input" inputmode="decimal" placeholder="e.g. 255.255.255.0" maxlength="15" style="width: 100%; padding: 8px; border: 1px solid #ddd; border-radius: 5px;">
</div>
<div>
<label for="ethStaticDns1">Primary DNS:</label>
<input type="text" id="ethStaticDns1" class="config-input" inputmode="decimal" placeholder="defaults to your gateway" maxlength="15" style="width: 100%; padding: 8px; border: 1px solid #ddd; border-radius: 5px;">
<small style="color: #666;">Leave blank to use your gateway, or set a specific server (e.g. 8.8.8.8).</small>
</div>
<div>
<label for="ethStaticDns2">Secondary DNS (optional):</label>
<input type="text" id="ethStaticDns2" class="config-input" inputmode="decimal" placeholder="e.g. 1.1.1.1" maxlength="15" style="width: 100%; padding: 8px; border: 1px solid #ddd; border-radius: 5px;">
</div>
</div>
<button class="buttonForm" onclick="setEthernetConfiguration()" id="setEthConfigButton">🔌 Apply & restart</button>
<button class="buttonForm" onclick="resetEthernetConfiguration()" id="resetEthConfigButton">↩️ Reset to DHCP & restart</button>
</div>
<div class="section-box">
<h2>Switch WiFi Network</h2>
<p><i>Pick a network from the list, or type the name of a hidden one. The device saves the credentials and joins the new network without restarting.</i></p>
<div class="wifi-list-header">
<span>Nearby networks</span>
<button type="button" class="wifi-scan-button" onclick="scanWifi()" id="scanWifi">↻ Scan</button>
</div>
<ul id="wifiNetworkList" class="wifi-network-list">
<li class="wifi-list-note">Press Scan to list the networks the device can see.</li>
</ul>
<div style="display: flex; flex-direction: column; gap: 10px; margin: 15px 0;">
<div>
<label for="newWifiSsid">Network Name (SSID):</label>
<input type="text" id="newWifiSsid" class="config-input" placeholder="Pick from the list above, or type it" maxlength="32" style="width: 100%; padding: 8px; border: 1px solid #ddd; border-radius: 5px;">
</div>
<div>
<label for="newWifiPassword">Password:</label>
<input type="password" id="newWifiPassword" class="config-input" placeholder="Enter WiFi password" maxlength="63" style="width: 100%; padding: 8px; border: 1px solid #ddd; border-radius: 5px;">
</div>
</div>
<div class="warning-box"
style="background-color: #fff3cd; color: #856404; padding: 10px; border-radius: 5px; margin: 10px 0;"> ⚠️
<span id="switchWifiWarning">Warning: The device leaves this network to join the new one. You will lose access at this address.</span>
</div>
<button class="buttonForm" onclick="switchWifi()" id="switchWifi">📶 Switch Network</button>
</div>
<div class="section-box">
<h2>Disconnect from WiFi</h2>
<p><i>This will erase the WiFi credentials, reset the IP settings to automatic (DHCP) and restart the device.</i></p>
<p id="disconnectWifiApHelp"><i>The device will create a password-protected WiFi network called "EnergyMe-XXXXXXXXXX"
(where XXXXXXXXXX is the device ID). The password is printed on the device.
Connect to that network and navigate to <a href="http://172.31.42.1"
target="_blank">http://172.31.42.1</a>
if the device does not redirect you automatically.
You can then configure the device to connect to your WiFi network.</i></p>
<div class="warning-box"
style="background-color: #fff3cd; color: #856404; padding: 10px; border-radius: 5px; margin: 10px 0;"> ⚠️
<span id="disconnectWifiWarning">Warning: You will lose access to the device until you reconnect it to WiFi.</span>
</div>
<button class="buttonForm" onclick="disconnectWifi()" id="disconnect">📶 Disconnect</button>
</div>
<div class="section-box">
<h2>Factory Reset</h2>
<p><i>This will reset the device to its factory settings. Useful if you are having issues with the device or
want to start fresh.</i></p>
<div class="warning-box"
style="background-color: #fff3cd; color: #856404; padding: 10px; border-radius: 5px; margin: 10px 0;"> ⚠️
Warning: This will erase all configurations, data, and WiFi credentials. This action cannot be undone.
</div>
<button class="buttonForm" onclick="factoryReset()" id="factoryReset">🏭 Reset</button>
<div id="provisioningInstructions" style="display: none; background-color: #d1ecf1; color: #0c5460; padding: 15px; border-radius: 5px; margin: 15px 0;">
<h3 style="margin-top: 0;">✅ Factory reset done - reconnect the device</h3>
<p>This device has left your WiFi network and is now waiting to be set up again. It is no longer
reachable at this address.</p>
<ol>
<li>Wait about 30 seconds for the device to finish restarting.</li>
<li>On your phone or laptop, join the WiFi network <b id="apSsidName">EnergyMe-<device id></b>.</li>
<li>The setup page should open by itself. If it does not, open <b>http://172.31.42.1</b> in a browser.</li>
<li>Pick your WiFi network there and enter its password.</li>
</ol>
<p style="margin-bottom: 0;"><i>The LED blinks blue quickly while the device is waiting to be set up.</i></p>
</div>
</div>
<script src="/js/api-client.js"></script>
<script src="/js/reboot-wait.js"></script>
<script src="/js/issues.js"></script>
<script>
var logLevels = ["Verbose", "Debug", "Info", "Warning", "Error", "Fatal"];
// Shows a spinner + dims the control while its real value is still loading,
// instead of letting the user see a stale hardcoded default (e.g. brightness 50%).
function setFieldLoading(inputId, spinnerId, isLoading) {
var input = document.getElementById(inputId);
var spinner = document.getElementById(spinnerId);
input.disabled = isLoading;
input.classList.toggle('field-loading', isLoading);
spinner.style.display = isLoading ? 'inline-block' : 'none';
}
function populateDropdown() {
var printLogLevel = document.getElementById("printLogLevel");
var saveLogLevel = document.getElementById("saveLogLevel");
// Clear existing options
printLogLevel.innerHTML = "";
saveLogLevel.innerHTML = "";
for (var i = 0; i < logLevels.length; i++) {
var opt = document.createElement("option");
opt.value = logLevels[i];
opt.innerHTML = logLevels[i];
printLogLevel.appendChild(opt.cloneNode(true));
// Exclude "Verbose" from saveLogLevel
if (logLevels[i] !== "Verbose") {
saveLogLevel.appendChild(opt.cloneNode(true));
}
}
}
async function restart() {
const restartButton = document.getElementById("restart");
restartButton.disabled = true;
restartButton.classList.add('loading');
try {
await energyApi.restartSystem();
window.rebootWait.show();
} catch (error) {
showStatus("Error restarting device: " + error.message, 'error');
restartButton.disabled = false;
restartButton.classList.remove('loading');
}
}
function loadDeviceTime() {
energyApi.getSystemTime()
.then(response => {
const timeEl = document.getElementById("currentDeviceTime");
const syncStatus = response.synced ? "✅ Synced" : "⚠️ Not synced";
const localTime = new Date(response.unixTime * 1000).toLocaleString();
timeEl.innerHTML = `Device time: <strong>${localTime}</strong> <span style="color: #888;">(${response.isoTime} UTC)</span> ${syncStatus}`;
})
.catch(error => {
document.getElementById("currentDeviceTime").innerHTML = "Device time: Error loading";
});
}
async function syncTime() {
const syncButton = document.getElementById("syncTime");
syncButton.disabled = true;
syncButton.classList.add('loading');
try {
showStatus('Syncing time...', 'info');
const unixSeconds = Math.floor(Date.now() / 1000);
const response = await energyApi.setSystemTime(unixSeconds);
showStatus('Time synchronized successfully! New time: ' + response.newTime, 'success');
loadDeviceTime();
} catch (error) {
showStatus('Error syncing time: ' + error.message, 'error');
} finally {
syncButton.disabled = false;
syncButton.classList.remove('loading');
}
}
// Load device time on page load
document.addEventListener("DOMContentLoaded", function() {
loadDeviceTime();
});
async function switchWifi() {
const ssid = document.getElementById("newWifiSsid").value.trim();
const password = document.getElementById("newWifiPassword").value;
if (!ssid) {
showStatus('Please enter a WiFi network name (SSID).', 'error');
return;
}
// The snapshot is missing when the system info request failed at page load; without
// it a wired device would silently take the WiFi-only flow below.
if (!currentNetwork) await loadCurrentNetwork();
const wired = isServedOverEthernet();
const userConfirmed = window.confirm(wired
? "Switch WiFi to '" + ssid + "'? The device stays reachable over Ethernet."
: "Are you sure you want to switch to WiFi network '" + ssid + "'? The device will leave this network and you will lose access at this address.");
if (!userConfirmed) {
return;
}
const button = document.getElementById("switchWifi");
button.disabled = true;
button.classList.add('loading');
try {
await energyApi.setWifiCredentials(ssid, password);
// Clear the form
document.getElementById("newWifiSsid").value = "";
document.getElementById("newWifiPassword").value = "";
if (wired) {
waitForWifiOutcome(button);
return;
}
// Browsing the WiFi address of a wired device: that address is going away, but
// the device does not restart and keeps answering on the wire. Continue there.
var net = currentNetwork || {};
if (net.ethLinkUp && net.ethLocalIp && net.ethLocalIp !== "0.0.0.0") {
showStatus("WiFi is switching. Continuing on the Ethernet address " + net.ethLocalIp + "...", 'info');
setTimeout(function () { location.href = "http://" + net.ethLocalIp + "/configuration"; }, 2000);
return;
}
// No way to know the device's new address in advance (unlike the static-IP
// case). Best-effort poll energyme.local, same target the DHCP branch of
// network-config-apply uses; if the new network doesn't overlap with this
// one, the wait screen's own timeout and fallback cover it.
window.rebootWait.show({ redirectTo: "http://energyme.local", baseUrl: "http://energyme.local" });
// Don't restore button - the device leaves this network, so the page goes unreachable
} catch (error) {
button.disabled = false;
button.classList.remove('loading');
showStatus("Error switching WiFi network: " + error.message, 'error');
}
}
// True when this page is reached over the wire, so a WiFi change does not cut the
// session. Browsing the WiFi address of a wired device still counts as WiFi.
// Always false on products without Ethernet, which keeps their flow unchanged.
function isServedOverEthernet() {
var net = currentNetwork || {};
if (!net.ethLinkUp || !net.ethLocalIp || net.ethLocalIp === "0.0.0.0") return false;
// Only a page opened at the Ethernet address is known to be wired: a hostname
// (energyme.local) may resolve to the WiFi address that is about to go away
return location.hostname === net.ethLocalIp;
}
function updateWiredTexts() {
if (!isServedOverEthernet()) return;
document.getElementById("switchWifiWarning").textContent =
"The device stays reachable over Ethernet while WiFi switches. The result is reported here.";
document.getElementById("disconnectWifiApHelp").style.display = "none";
document.getElementById("disconnectWifiWarning").textContent =
"The device stays reachable over Ethernet after the restart. If a static Ethernet IP was set, it comes back on a DHCP address.";
}
// Messages live inside the list itself, so the feedback is where the user is looking.
function setWifiListNote(message) {
var list = document.getElementById("wifiNetworkList");
list.innerHTML = "";
var note = document.createElement("li");
note.className = "wifi-list-note";
note.textContent = message;
list.appendChild(note);
}
function wifiSignalBars(rssi) {
var filled = rssi >= -60 ? 3 : (rssi >= -72 ? 2 : 1);
var bars = document.createElement("span");
bars.className = "wifi-bars";
bars.title = rssi + " dBm";
for (var i = 1; i <= 3; i++) {
var bar = document.createElement("i");
if (i <= filled) bar.className = "on";
bars.appendChild(bar);
}
return bars;
}
// Strongest first, one row per SSID (mesh and repeaters announce the same name many times)
function renderWifiNetworks(networks) {
var list = document.getElementById("wifiNetworkList");
list.innerHTML = "";
var seen = Object.create(null); // SSIDs are attacker-controlled: "constructor" must not read as already seen
networks.sort(function (a, b) { return b.rssi - a.rssi; }).forEach(function (network) {
if (!network.ssid || seen[network.ssid]) return;
seen[network.ssid] = true;
var item = document.createElement("li");
var name = document.createElement("span");
name.className = "wifi-network-name";
name.textContent = network.ssid;
var meta = document.createElement("span");
meta.className = "wifi-network-meta";
if (network.secure) {
var lock = document.createElement("span");
lock.textContent = "🔒";
lock.title = "Password protected";
meta.appendChild(lock);
}
meta.appendChild(wifiSignalBars(network.rssi));
item.appendChild(name);
item.appendChild(meta);
item.addEventListener("click", function () {
var previous = list.querySelector(".selected");
if (previous) previous.classList.remove("selected");
item.classList.add("selected");
document.getElementById("newWifiSsid").value = network.ssid;
var password = document.getElementById("newWifiPassword");
password.value = "";
if (network.secure) password.focus();
});
list.appendChild(item);
});
if (!list.children.length) setWifiListNote("No networks found. Scan again, or type the network name below.");
}
// The scan is async on the device, so poll until it ends.
function scanWifi() {
const button = document.getElementById("scanWifi");
button.disabled = true;
button.textContent = "Scanning...";
setWifiListNote("Looking for networks...");
var startedAt = Date.now();
var done = false;
var finish = function (errorNote) {
if (done) return;
done = true;
clearInterval(timer);
button.disabled = false;
button.textContent = "↻ Scan again";
if (errorNote) setWifiListNote(errorNote);
};
var poll = function (refresh) {
energyApi.scanWifiNetworks(refresh).then(function (data) {
if (done || data.status === 'running') return;
if (data.status === 'unavailable') {
finish("Could not scan right now. Type the network name below, or scan again.");
return;
}
renderWifiNetworks(data.networks || []);
finish();
}).catch(function () {
// A dropped request during scanning is normal on a busy radio.
});
if (Date.now() - startedAt > 25000) finish("Scanning is taking too long. Type the network name below, or scan again.");
};
var timer = setInterval(function () { poll(false); }, 1500);
poll(true);
}
// Wired only: the session survives the WiFi change, so report how it ended instead of
// sending the browser somewhere else. Same verdict rules as wifi-setup.html.
function waitForWifiOutcome(button) {
showStatus("Credentials saved. Joining the new network...", 'info');
var startedAt = Date.now();
var done = false;
var finish = function (message, kind) {
if (done) return;
done = true;
clearInterval(timer);
button.disabled = false;
button.classList.remove('loading');
showStatus(message, kind, 10000);
loadCurrentNetwork();
};
var timer = setInterval(function () {
var elapsed = Date.now() - startedAt;
// The first seconds can still report the previous association.
if (elapsed < 4000) return;
energyApi.getWifiStatus().then(function (d) {
if (d.credentialWriteFailed) {
finish("The device could not store the credentials. Try again.", 'error');
} else if (d.connected) {
finish("WiFi connected to '" + d.ssid + "' (" + d.ip + ").", 'success');
} else if (d.state === 0 || d.state === 2) {
// Back to unprovisioned or assist means the attempt was given up on.
energyApi.getWifiDiagnostics()
.then(function (diag) { return diag && diag.reason; })
.catch(function () { return null; })
.then(function (reason) {
finish("WiFi could not join that network" + (reason ? " (" + reason + ")" : "")
+ ". Check the network name and password.", 'error');
});
} else if (elapsed > 60000) {
finish("WiFi has not connected yet. The device keeps trying: check the network name and password.", 'error');
}
}).catch(function () {
if (elapsed > 60000) finish("Lost contact with the device while WiFi was switching.", 'error');
});
}, 2000);
}
async function disconnectWifi() {
if (!currentNetwork) await loadCurrentNetwork();
const wired = isServedOverEthernet();
const confirm = window.confirm(wired
? "Erase the WiFi credentials? All IP settings go back to DHCP and the device restarts. It stays reachable over Ethernet."
: "Are you sure you want to disconnect from WiFi? You will lose access to the device until you reconnect it to WiFi.");
if (!confirm) {
return;
}
const button = document.getElementById("disconnect");
button.disabled = true;
button.classList.add('loading');
try {
showStatus("Disconnecting from WiFi...", 'info');
await energyApi.resetWifi();
if (wired) {
// The reset also puts Ethernet back on DHCP: a static address this page
// was loaded from is gone after the restart.
var wasStatic = currentEthernet && currentEthernet.staticApplied;
window.rebootWait.show(wasStatic ? { redirectTo: "http://energyme.local", baseUrl: "http://energyme.local" } : {});
return;
}
showStatus("WiFi credentials erased. Connect to the 'EnergyMe-<device id>' network (password is printed on the device) and open http://172.31.42.1", 'success', 10000);
} catch (error) {
// Treat "signal is aborted without reason" as successful (it means WiFi was reset)
if (error.message && error.message.includes("signal is aborted without reason")) {
showStatus("WiFi credentials erased. Connect to the 'EnergyMe-<device id>' network (password is printed on the device) and open http://172.31.42.1", 'success', 10000);
} else {
showStatus("Error disconnecting from WiFi: " + error.message, 'error');
}
} finally {
button.disabled = false;
button.classList.remove('loading');
}
}
function showProvisioningInstructions() {
// _deviceId comes from loadDeviceInfo() on page load; the SSID is built the
// same way the firmware builds it (WIFI_CONFIG_PORTAL_SSID "-" DEVICE_ID).
if (_deviceId) {
document.getElementById("apSsidName").textContent = "EnergyMe-" + _deviceId;
}
document.getElementById("provisioningInstructions").style.display = "block";
document.getElementById("provisioningInstructions").scrollIntoView({ behavior: "smooth", block: "center" });
}
async function factoryReset() {
const confirm = window.confirm("Are you sure you want to reset the device to factory settings? All configurations and data will be lost.");
if (!confirm) {
return;
}
const button = document.getElementById("factoryReset");
button.disabled = true;
button.classList.add('loading');
try {
showStatus("Resetting to factory settings...", 'info');
await energyApi.factoryReset();
// Deliberately no redirect: the reset erases the WiFi credentials, so
// the device leaves this network and comes back only on its own SoftAP.
// Any navigation from here can only land on an unreachable host.
showStatus("Factory reset done. Follow the steps below to reconnect the device.", 'success', 10000);
button.classList.remove('loading'); // Stays disabled: this device is gone from the network
showProvisioningInstructions();
} catch (error) {
showStatus("Error resetting to factory settings: " + error.message, 'error');
button.disabled = false;
button.classList.remove('loading');
}
}
async function changePassword() {
const currentPassword = document.getElementById("currentPassword").value;
const newPassword = document.getElementById("newPassword").value;
const confirmPassword = document.getElementById("confirmPassword").value;
// Validation
if (!currentPassword) {
showStatus('Please enter your current password.', 'error');
return;
}
if (!newPassword) {
showStatus('Please enter a new password.', 'error');
return;
}
if (newPassword.length < 8) {
showStatus('New password must be at least 8 characters long.', 'error');
return;
}
if (newPassword !== confirmPassword) {
showStatus('New passwords do not match.', 'error');
return;
}
const button = document.getElementById("changePasswordButton");
button.disabled = true;
button.classList.add('loading');
try {
showStatus('Changing password...', 'info');
await energyApi.changePassword(currentPassword, newPassword);
showStatus('Password changed successfully! Please use your new password on next login.', 'success');
// Clear the form
document.getElementById("currentPassword").value = "";
document.getElementById("newPassword").value = "";
document.getElementById("confirmPassword").value = "";
} catch (error) {
showStatus('Error changing password: ' + error.message, 'error');
} finally {
button.disabled = false;
button.classList.remove('loading');
}
}
async function setLogLevel() {
const button = document.getElementById("setLogLevel");
button.disabled = true;
button.classList.add('loading');
try {
const printLogLevel = document.getElementById("printLogLevel").value.toUpperCase();
const saveLogLevel = document.getElementById("saveLogLevel").value.toUpperCase();
// API expects string values like "VERBOSE", "DEBUG", etc.
const validLevels = ["VERBOSE", "DEBUG", "INFO", "WARNING", "ERROR", "FATAL"];
// Validate that the levels are valid
if (!validLevels.includes(printLogLevel) || !validLevels.includes(saveLogLevel)) {
showStatus('Invalid log level selected', 'error');
button.disabled = false;
button.classList.remove('loading');
return;
}
console.log("Setting log levels:", { print: printLogLevel, save: saveLogLevel });
showStatus('Setting log level...', 'info');
await energyApi.setLogLevels({
print: printLogLevel,
save: saveLogLevel
});
showStatus('Log level set successfully', 'success');
} catch (error) {
showStatus('Error setting log level: ' + error.message, 'error');
} finally {
button.disabled = false;
button.classList.remove('loading');
}
}
function getLogLevel() {
return energyApi.getLogLevels()
.then(data => {
// API returns string values like "VERBOSE", "DEBUG", etc.
// Convert to dropdown format (first letter uppercase, rest lowercase)
function formatLevelForDropdown(level) {
if (!level) return "Debug";
return level.charAt(0).toUpperCase() + level.slice(1).toLowerCase();
}
var printLogLevel = formatLevelForDropdown(data.print);
var saveLogLevel = formatLevelForDropdown(data.save);
populateDropdown();
document.getElementById("printLogLevel").value = printLogLevel;
document.getElementById("saveLogLevel").value = saveLogLevel;
})
.catch(error => {
console.log("Error getting log levels. Response: " + error.message);
})
.finally(() => {
setFieldLoading("printLogLevel", "printLogLevelSpinner", false);
setFieldLoading("saveLogLevel", "saveLogLevelSpinner", false);
});
}
async function clearLogs() {
const confirm = window.confirm("Are you sure you want to clear the log?");
if (!confirm) {
return;
}
const button = document.getElementById("clearLogs");
button.disabled = true;
button.classList.add('loading');
try {
showStatus('Clearing logs...', 'info');
await energyApi.clearLogs();
showStatus('Log cleared successfully', 'success');
} catch (error) {
showStatus('Error clearing log: ' + error.message, 'error');
} finally {
button.disabled = false;
button.classList.remove('loading');
}
}
let _deviceId = '';
let _devBuild = false;
let _cloudEnabled = false;
let _hasSecrets = false;
let _secretsChecked = false;
async function loadDeviceInfo() {
try {
const data = await energyApi.getSystemInfo();
_deviceId = (data.static && data.static.device && data.static.device.id) || '';
_devBuild = (data.static && data.static.device && data.static.device.devBuild) || false;
updatePortalLink();
} catch (error) {
console.log('Error loading device info: ' + error.message);
}
}
function updatePortalLink() {
const banner = document.getElementById('portalBanner');
banner.style.display = 'block';
// Keep the banner visible from first paint. Until both the device id
// and the secrets check have resolved, leave the "Checking
// certificates..." placeholder showing rather than hiding the whole
// banner - avoids the ~1s blank-then-pop-in while the config loads.
if (!_deviceId || !_secretsChecked) { return; }
const link = document.getElementById('portalLink');
if (!_hasSecrets) {
link.href = '#';
link.classList.add('portal-cta-disabled');
link.textContent = '🔒 Add to EnergyMe Portal ›';
document.getElementById('portalMsg').textContent = 'Cloud services are not available on this device (community build - no provisioning secrets).';
} else if (_cloudEnabled) {
const base = _devBuild
? 'https://portal-dev.energyme.net'
: 'https://portal.energyme.net';
link.href = base + '/devices/claim?device_id=' + _deviceId;
link.classList.remove('portal-cta-disabled');
link.textContent = '☁️ Add to EnergyMe Portal ›';
document.getElementById('portalMsg').textContent = 'Ready to monitor remotely? Add this meter to your EnergyMe Portal.';
} else {
link.href = '#';
link.classList.add('portal-cta-disabled');
link.textContent = '🔒 Add to EnergyMe Portal ›';
document.getElementById('portalMsg').textContent = 'Enable cloud services above to unlock remote monitoring on EnergyMe Portal.';
}
}
function getCloudServices() {
return energyApi.getMqttCloudServices()
.then(data => {
document.getElementById("cloudServices").checked = data.enabled;
_cloudEnabled = data.enabled;
updatePortalLink();
})
.catch(error => {
console.log("Error getting cloud services status. Response: " + error.message);
})
.finally(() => {
setFieldLoading("cloudServices", "cloudServicesSpinner", false);
});
}
async function setCloudServices() {
const button = document.getElementById("setCloudServicesButton");
button.disabled = true;
button.classList.add('loading');
try {
showStatus('Updating cloud services...', 'info');
// First check secrets status
const secretsResponse = await energyApi.getSystemSecrets();
const isEnabled = document.getElementById("cloudServices").checked;
// If no secrets but cloud services is checked, prevent that
if (!secretsResponse.hasSecrets && isEnabled) {
showStatus('Cannot enable: firmware does not include secrets', 'error');
document.getElementById("cloudServices").checked = false;
button.disabled = false;
button.classList.remove('loading');
return;
}
// Send the configuration
await energyApi.setMqttCloudServices(isEnabled);
showStatus('Cloud services updated', 'success');
getCloudServices();
} catch (error) {
showStatus('Error: ' + error.message, 'error');
} finally {
button.disabled = false;
button.classList.remove('loading');
}
}
function getLedBrightness() {
return energyApi.getLedBrightness()
.then(data => {
// Assuming API returns brightness as 0-100 range
document.getElementById("ledBrightness").value = data.brightness;
updateBrightnessValue();
})
.catch(error => {
console.log("Error getting LED brightness. Response: " + error.message);
})
.finally(() => {
setFieldLoading("ledBrightness", "ledBrightnessSpinner", false);
});
}
async function setLedBrightness() {
const button = document.getElementById("setLedBrightnessButton");
button.disabled = true;
button.classList.add('loading');
try {
showStatus('Setting brightness...', 'info');
const brightness = parseInt(document.getElementById("ledBrightness").value);
await energyApi.setLedBrightness(brightness);
showStatus('Brightness set successfully', 'success');
} catch (error) {
showStatus('Error: ' + error.message, 'error');
} finally {
button.disabled = false;
button.classList.remove('loading');
}
}
// Well under the API's 60 s ceiling: 10 s is enough to spot which meter you are
// looking at. The countdown is cosmetic - the device releases the layer on its
// own schedule regardless of what the button shows.
const DISCO_DURATION_MS = 10000;
async function startDisco() {
const button = document.getElementById("discoButton");
const overlay = document.getElementById("discoOverlay");
const label = button.innerHTML;
button.disabled = true;
try {
await energyApi.setLedDisco(DISCO_DURATION_MS);
} catch (error) {
showStatus('Error: ' + error.message, 'error');
button.disabled = false;
return;
}
overlay.classList.add('dancing');
let remaining = Math.round(DISCO_DURATION_MS / 1000);
button.innerHTML = `🪩 Dancing... ${remaining}s`;
const countdown = setInterval(() => {
remaining--;
if (remaining > 0) {
button.innerHTML = `🪩 Dancing... ${remaining}s`;
return;
}
clearInterval(countdown);
overlay.classList.remove('dancing');
button.innerHTML = label;
button.disabled = false;
}, 1000);
}
function updateBrightnessValue() {
var slider = document.getElementById("ledBrightness");
var output = document.getElementById("ledBrightnessValue");
var percentage = parseInt(slider.value);
slider.style.setProperty('--slider-value', percentage + '%');
slider.title = percentage + "%";
output.innerHTML = percentage + "%";
}
// Live network snapshot, used to prefill static fields with the working values.
var currentNetwork = null;
function getSelectedIpMode(groupName) {
var checked = document.querySelector('input[name="' + groupName + '"]:checked');
return checked ? checked.value : "dhcp";
}
function setSelectedIpMode(groupName, mode) {
var radio = document.querySelector('input[name="' + groupName + '"][value="' + mode + '"]');
if (radio) radio.checked = true;
}
function updateRiskWarning() {
var show = getSelectedIpMode("ipMode") === "static" && !document.getElementById("fallbackToDhcp").checked;
document.getElementById("networkRiskWarning").style.display = show ? "block" : "none";
}
function prefillDnsFromGateway(gwId, dnsId) {
var gateway = document.getElementById(gwId).value.trim();
var dns1 = document.getElementById(dnsId);
if (gateway && !dns1.value.trim()) dns1.value = gateway;
}
// Seed empty static fields from the current working addresses so "static"
// becomes "pin my current address" - the safe, common case.
// values: { ip, gateway, subnet, dns1 }; idPrefix: "static" or "ethStatic".
function prefillStaticFields(values, idPrefix) {
var valid = function (v) { return v && v !== "0.0.0.0"; };
var seed = function (idSuffix, val) {
var field = document.getElementById(idPrefix + idSuffix);
if (!field.value.trim() && valid(val)) field.value = val;
};
seed("Ip", values.ip);
seed("Gateway", values.gateway);
seed("Subnet", values.subnet);
seed("Dns1", values.dns1);
}
function prefillStaticFromCurrent() {
if (!currentNetwork || !currentNetwork.wifiConnected) return;
prefillStaticFields({
ip: currentNetwork.wifiLocalIp,
gateway: currentNetwork.wifiGatewayIp,
subnet: currentNetwork.wifiSubnetMask,
dns1: currentNetwork.wifiDnsIp
}, "static");
}
function onIpModeChange() {
var isStatic = getSelectedIpMode("ipMode") === "static";
document.getElementById("staticIpFields").style.display = isStatic ? "flex" : "none";
if (isStatic) prefillStaticFromCurrent();
updateRiskWarning();
}
function loadCurrentNetwork() {
return energyApi.getSystemInfo()
.then(data => {
var net = (data && data.dynamic && data.dynamic.network) || {};
currentNetwork = net;
var set = function (id, val) { document.getElementById(id).textContent = val || "N/A"; };
if (net.wifiConnected) {
document.getElementById("curStatus").textContent = "Connected";
document.getElementById("curStatus").style.color = "var(--green, #2e7d32)";
} else {
document.getElementById("curStatus").textContent = "Disconnected";
document.getElementById("curStatus").style.color = "#c62828";
}
set("curSsid", net.wifiSsid);
set("curIp", net.wifiLocalIp);
set("curGateway", net.wifiGatewayIp);
set("curSubnet", net.wifiSubnetMask);
set("curDns", net.wifiDnsIp);
document.getElementById("curRssi").textContent =
net.wifiRssi ? (net.wifiRssi + " dBm " + signalQualityLabel(net.wifiRssi)) : "N/A";
updateWiredTexts();
})
.catch(error => {
document.getElementById("curStatus").textContent = "Unavailable";
console.log("Error getting current network info. Response: " + error.message);
});
}
function signalQualityLabel(rssi) {
if (rssi > -50) return "(Excellent)";
if (rssi > -60) return "(Good)";
if (rssi > -70) return "(Fair)";
return "(Poor)";
}
function isValidIpv4(value) {
if (!value) return false;
var parts = value.split(".");
if (parts.length !== 4) return false;
for (var i = 0; i < parts.length; i++) {
if (!/^\d{1,3}$/.test(parts[i])) return false;
var n = parseInt(parts[i], 10);
if (n < 0 || n > 255) return false;
}
return true;
}
function getNetworkConfiguration() {
return energyApi.getNetworkConfig()
.then(data => {
setSelectedIpMode("ipMode", data.useStaticIp ? "static" : "dhcp");
document.getElementById("curMode").textContent = data.useStaticIp ? "Static IP" : "DHCP (automatic)";
document.getElementById("staticIp").value = data.ip || "";
document.getElementById("staticGateway").value = data.gateway || "";
document.getElementById("staticSubnet").value = data.subnet || "";
document.getElementById("staticDns1").value = data.dns1 || "";
document.getElementById("staticDns2").value = data.dns2 || "";
document.getElementById("fallbackToDhcp").checked = data.fallbackToDhcp !== false;
onIpModeChange();
})
.catch(error => {
setSelectedIpMode("ipMode", "dhcp");
onIpModeChange();
console.log("Error getting network configuration. Response: " + error.message);
});
}
// The firmware refuses 0.0.0.0 for the address, the gateway and the subnet mask.
function isUsableIpv4(value) {
return isValidIpv4(value) && value !== "0.0.0.0";
}
// Where the wait screen should look for the device after a restart that changes the
// address of ONE interface. When this page is served over the other interface its
// address does not change, so stay on this origin (empty options = same-origin defaults).
function rebootWaitTarget(changesEthernet, newUrl) {
if (isServedOverEthernet() !== changesEthernet) return {};
return { redirectTo: newUrl, baseUrl: newUrl };
}
async function setNetworkConfiguration() {
const useStaticIp = getSelectedIpMode("ipMode") === "static";
const ip = document.getElementById("staticIp").value.trim();
const gateway = document.getElementById("staticGateway").value.trim();
const subnet = document.getElementById("staticSubnet").value.trim();
// Primary DNS must never be empty for a static config (empty DNS breaks name resolution),
// so default it to the gateway when the user leaves it blank.
const dns1 = document.getElementById("staticDns1").value.trim() || gateway;
const dns2 = document.getElementById("staticDns2").value.trim();
const fallbackToDhcp = document.getElementById("fallbackToDhcp").checked;
if (useStaticIp) {
if (!isUsableIpv4(ip)) { showStatus('Please enter a valid IP address.', 'error'); return; }
if (!isUsableIpv4(gateway)) { showStatus('Please enter a valid gateway address.', 'error'); return; }
if (!isUsableIpv4(subnet)) { showStatus('Please enter a valid subnet mask.', 'error'); return; }
if (!isValidIpv4(dns1)) { showStatus('Primary DNS is not a valid IP address.', 'error'); return; }
if (dns2 && !isValidIpv4(dns2)) { showStatus('Secondary DNS is not a valid IP address.', 'error'); return; }
}
const userConfirmed = window.confirm("Apply WiFi configuration? The device will restart and may be reachable at a different address.");
if (!userConfirmed) return;
const button = document.getElementById("setNetworkConfigButton");
button.disabled = true;
button.classList.add('loading');
try {
showStatus("Applying WiFi configuration...", 'info');
await energyApi.setNetworkConfig({
useStaticIp: useStaticIp,
ip: ip,
gateway: gateway,
subnet: subnet,
dns1: dns1,
dns2: dns2,
fallbackToDhcp: fallbackToDhcp
});
// After the restart the device may answer at a new address. For a static IP that is
// the address the user just entered; for DHCP its mDNS name (energyme.local) follows
// it whatever lease it gets. Poll and redirect against that new address, not the
// one this page was loaded from.
const targetUrl = useStaticIp ? ("http://" + ip) : "http://energyme.local";
window.rebootWait.show(rebootWaitTarget(false, targetUrl));
// Don't restore button - the device is restarting
} catch (error) {
button.disabled = false;
button.classList.remove('loading');
showStatus("Error setting WiFi configuration: " + error.message, 'error');
}
}
// Ethernet (Home Pro only). Live status snapshot, used to prefill static fields
// with the working values; null while the section is hidden.
var currentEthernet = null;
function prefillEthStaticFromCurrent() {
if (!currentEthernet || !currentEthernet.linkUp) return;
prefillStaticFields(currentEthernet, "ethStatic");
}
function onEthIpModeChange() {
var isStatic = getSelectedIpMode("ethIpMode") === "static";
document.getElementById("ethStaticIpFields").style.display = isStatic ? "flex" : "none";
if (isStatic) prefillEthStaticFromCurrent();
}
// Reveals the Ethernet section only when the device actually has Ethernet
// (404 or enabled:false means it does not; the catch keeps the section
// hidden on transient errors too - this page loads once, no retry cycle).
async function loadEthernet() {
// Already known from the system info: no Ethernet, so no request (and no 404).
if (currentNetwork && currentNetwork.ethEnabled === false) return;
try {
var status = await energyApi.getEthernetStatusIfAvailable();
if (!status) return;
currentEthernet = status;
document.getElementById("ethernetSection").style.display = "block";
var set = function (id, val) { document.getElementById(id).textContent = val || "N/A"; };
var link = document.getElementById("curEthLink");
link.textContent = status.linkUp ? "Up" : "Down";
link.style.color = status.linkUp ? "var(--green, #2e7d32)" : "#c62828";
set("curEthActiveInterface", formatInterfaceName(status.activeInterface));
set("curEthIp", status.ip);
set("curEthGateway", status.gateway);
set("curEthSubnet", status.subnet);
set("curEthDns", status.dns1);
set("curEthMac", status.mac);
var config;
try {
config = await energyApi.getEthernetConfig();
} catch (error) {
// The form below would show DHCP with empty fields, and applying that
// would overwrite a stored static configuration.
document.getElementById("setEthConfigButton").disabled = true;
document.getElementById("resetEthConfigButton").disabled = true;
showStatus("Could not load the Ethernet configuration. Reload the page to change it.", 'error');
return;
}
setSelectedIpMode("ethIpMode", config.useStaticIp ? "static" : "dhcp");
// The boot-fail backstop can keep a static configuration stored but unused.
document.getElementById("curEthMode").textContent = !config.useStaticIp ? "DHCP (automatic)"
: (status.staticApplied ? "Static IP" : "Static IP (not applied, using DHCP)");
document.getElementById("ethStaticIp").value = config.ip || "";
document.getElementById("ethStaticGateway").value = config.gateway || "";
document.getElementById("ethStaticSubnet").value = config.subnet || "";
document.getElementById("ethStaticDns1").value = config.dns1 || "";
document.getElementById("ethStaticDns2").value = config.dns2 || "";
onEthIpModeChange();
} catch (error) {
console.log("Error getting Ethernet status. Response: " + error.message);
}
}
// Shared confirm -> disable button -> API call -> reboot-wait scaffold for the
// Ethernet actions. After the restart the device may answer at a new address,
// so poll and redirect against targetUrl, not the one this page was loaded from.
async function ethApplyAndReboot(buttonId, confirmMsg, pendingMsg, apiCall, targetUrl, errorPrefix) {
if (!window.confirm(confirmMsg)) return;
const button = document.getElementById(buttonId);
button.disabled = true;
button.classList.add('loading');
try {
showStatus(pendingMsg, 'info');
await apiCall();
window.rebootWait.show(rebootWaitTarget(true, targetUrl));
// Don't restore button - the device is restarting
} catch (error) {
button.disabled = false;
button.classList.remove('loading');
showStatus(errorPrefix + error.message, 'error');
}
}
async function setEthernetConfiguration() {
const useStaticIp = getSelectedIpMode("ethIpMode") === "static";
const ip = document.getElementById("ethStaticIp").value.trim();
const gateway = document.getElementById("ethStaticGateway").value.trim();
const subnet = document.getElementById("ethStaticSubnet").value.trim();
// Primary DNS must never be empty for a static config (empty DNS breaks name resolution),
// so default it to the gateway when the user leaves it blank.
const dns1 = document.getElementById("ethStaticDns1").value.trim() || gateway;
const dns2 = document.getElementById("ethStaticDns2").value.trim();
if (useStaticIp) {
if (!isUsableIpv4(ip)) { showStatus('Please enter a valid IP address.', 'error'); return; }
if (!isUsableIpv4(gateway)) { showStatus('Please enter a valid gateway address.', 'error'); return; }
if (!isUsableIpv4(subnet)) { showStatus('Please enter a valid subnet mask.', 'error'); return; }
if (!isValidIpv4(dns1)) { showStatus('Primary DNS is not a valid IP address.', 'error'); return; }
if (dns2 && !isValidIpv4(dns2)) { showStatus('Secondary DNS is not a valid IP address.', 'error'); return; }
// Same rules as the firmware. A wrong static address is not caught at run time
// (the link alone makes it "up"), so catch what can be caught here.
if (ip.indexOf("172.31.42.") === 0) { showStatus('172.31.42.x is reserved for the recovery access point. Please pick another address.', 'error'); return; }
var toInt = function (a) { return a.split(".").reduce(function (acc, part) { return acc * 256 + parseInt(part, 10); }, 0); };
var mask = toInt(subnet);
var inverted = 4294967295 - mask; // A valid mask is ones then zeros, so its inverse is 2^n - 1
if ((inverted & (inverted + 1)) !== 0) { showStatus('The subnet mask is not valid (example: 255.255.255.0).', 'error'); return; }
if (((toInt(ip) & mask) >>> 0) !== ((toInt(gateway) & mask) >>> 0)) { showStatus('The gateway must be inside the same network as the IP address.', 'error'); return; }
}
// For a static IP the new address is the one the user just entered; for DHCP
// the mDNS name (energyme.local) follows the device whatever lease it gets.
await ethApplyAndReboot(
"setEthConfigButton",
"Apply Ethernet configuration? The device will restart and may be reachable at a different address.",
"Applying Ethernet configuration...",
() => energyApi.setEthernetConfig({
useStaticIp: useStaticIp,
ip: ip,
gateway: gateway,
subnet: subnet,
dns1: dns1,
dns2: dns2
}),
useStaticIp ? ("http://" + ip) : "http://energyme.local",
"Error setting Ethernet configuration: "
);
}
async function resetEthernetConfiguration() {
// Back on DHCP after the restart, so poll the mDNS name rather than
// whatever static address this page may have been loaded from.
await ethApplyAndReboot(
"resetEthConfigButton",
"Reset Ethernet configuration to DHCP? The device will restart and may be reachable at a different address.",
"Resetting Ethernet configuration...",
() => energyApi.resetEthernetConfig(),
"http://energyme.local",
"Error resetting Ethernet configuration: "
);
}
function checkHasSecrets() {
energyApi.getSystemSecrets()
.then(response => {
_hasSecrets = response.hasSecrets;
_secretsChecked = true;
updatePortalLink();
// If no secrets available, disable cloud services option
if (!response.hasSecrets) {
var cloudServicesCheckbox = document.getElementById("cloudServices");
cloudServicesCheckbox.disabled = true;
cloudServicesCheckbox.checked = false;
// Create warning message if it doesn't exist
if (!document.getElementById("cloud-services-warning")) {
var warningDiv = document.createElement("div");
warningDiv.id = "cloud-services-warning";
warningDiv.className = "warning-box";
warningDiv.style.backgroundColor = "#fff3cd";
warningDiv.style.color = "#856404";
warningDiv.style.padding = "10px";
warningDiv.style.borderRadius = "5px";
warningDiv.style.marginTop = "10px";
warningDiv.innerHTML = "⚠️ Cloud services require secrets to be included in the firmware. This build doesn't include secrets.";
// Insert after the cloud services label
var labelElement = document.querySelector("label[for='cloudServices']");
labelElement.parentNode.insertBefore(warningDiv, labelElement.nextSibling);
}
}
})
.catch(error => {
console.log("Error checking secrets status:", error.message);
});
}
// Sequential API loading to prevent overwhelming the ESP32
async function loadConfigurationData() {
const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms));
const DELAY_BETWEEN_REQUESTS = 100;
try {
console.log("Loading configuration data sequentially...");
await loadDeviceInfo();
await delay(DELAY_BETWEEN_REQUESTS);
await getCloudServices();
await delay(DELAY_BETWEEN_REQUESTS);
await getLedBrightness();
await delay(DELAY_BETWEEN_REQUESTS);
await getLogLevel();
await delay(DELAY_BETWEEN_REQUESTS);
await loadCurrentNetwork();
await delay(DELAY_BETWEEN_REQUESTS);
await getNetworkConfiguration();
await delay(DELAY_BETWEEN_REQUESTS);
await loadEthernet();
await delay(DELAY_BETWEEN_REQUESTS);
await checkHasSecrets();
console.log("Configuration data loaded successfully");
} catch (error) {
console.error("Error loading configuration data:", error);
showStatus('Error loading configuration data. Please refresh the page.', 'error', 10000);
}
}
document.addEventListener("DOMContentLoaded", function () {
// Load configuration data sequentially to prevent ESP32 overload
loadConfigurationData();
});
</script>
</body>
</html>f4329a85eThis file is pinned to the selected release. Download the original to open it in your design tool.