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 */
/**
* EnergyMe API Client
* Unified client for all API calls with consistent authentication and error handling
*/
class EnergyMeAPI {
constructor() {
this.baseUrl = ''; // Same origin
this.defaultHeaders = {
'Content-Type': 'application/json',
'Connection': 'close' // Prevent keep-alive to reduce ESP32 load
};
this.getTimeoutMs = 5000;
this.otherTimeoutMs = 10000;
this.longTimeoutMs = 30000; // For operations that may take longer (e.g. backups)
}
/**
* Internal fetch with timeout
*/
async _fetchWithTimeout(url, config, timeoutMs) {
const controller = new AbortController();
const id = setTimeout(() => controller.abort(), timeoutMs);
config.signal = controller.signal;
try {
const response = await fetch(url, config);
clearTimeout(id);
return response;
} catch (error) {
clearTimeout(id);
throw error;
}
}
/**
* Make an API call (digest auth handled automatically by browser)
* @param {string} endpoint - API endpoint (with or without /api/v1/ prefix)
* @param {Object} options - Fetch options
* @param {number} timeoutMs - Timeout in milliseconds
* @returns {Promise<Response>} - Fetch response
*/
async apiCall(endpoint, options = {}, timeoutMs = this.otherTimeoutMs) {
// Normalize endpoint to use /api/v1/ prefix if not already present
let url = endpoint;
if (!endpoint.startsWith('/api/v1/')) {
url = `/api/v1/${endpoint.replace(/^\//, '')}`;
}
const config = {
...options,
headers: options.headers !== undefined
? { ...options.headers } // Caller-provided headers only (e.g. {} for multipart)
: { ...this.defaultHeaders } // Default headers for normal JSON calls
};
try {
const response = await this._fetchWithTimeout(url, config, timeoutMs);
// The device refuses everything but the way out while it still holds the shipped
// default password. This is recovery, not enforcement - the server is what blocks
// the request. It exists for the tab that was already open when the physical button
// reset the password, which would otherwise just fill up with failed fetches.
if (response.status === 403) {
const reason = await this._readErrorReason(response);
if (reason === 'default_password') {
window.location.href = '/';
throw new Error('The default password is still in use - redirecting to set a new one');
}
}
// For digest auth, 401 means credentials are required (browser will prompt).
// Surface the server's own message when it sent one: change-password answers 401
// for a wrong current password with a real explanation, and replacing every 401
// with the same generic string made that message unreachable.
if (response.status === 401) {
const message = await this._readErrorMessage(response);
throw new Error(message || 'Authentication required - please refresh the page');
}
return response;
} catch (error) {
console.error(`API call failed for ${url}:`, error);
throw error;
}
}
/**
* Read the machine-readable `reason` from an error response without consuming the body
* for callers that still need it. Returns null when the body is absent or not JSON.
* @param {Response} response
* @returns {Promise<string|null>}
*/
async _readErrorReason(response) {
try {
const body = await response.clone().json();
return body && body.reason ? body.reason : null;
} catch {
return null;
}
}
/**
* Read the human-readable `error` from an error response, leaving the original body
* readable. Returns null when the body is absent or not JSON.
* @param {Response} response
* @returns {Promise<string|null>}
*/
async _readErrorMessage(response) {
try {
const body = await response.clone().json();
return body && body.error ? body.error : null;
} catch {
return null;
}
}
/**
* GET request helper
* @param {string} endpoint - API endpoint
* @param {Object} options - Additional options
* @param {string} options.responseType - Response type: 'json' (default), 'text', 'blob'
* @returns {Promise<any>} - Parsed response
*/
async get(endpoint, options = {}) {
const { responseType = 'json' } = options;
const response = await this.apiCall(endpoint, { method: 'GET' }, this.getTimeoutMs);
if (!response.ok) {
throw new Error(`GET ${endpoint} failed: ${response.status}`);
}
switch (responseType) {
case 'text':
return response.text();
case 'blob':
return response.blob();
case 'json':
default:
return response.json();
}
}
/**
* POST request helper
* @param {string} endpoint - API endpoint
* @param {any} data - Request body data
* @returns {Promise<any>} - Parsed JSON response
*/
async post(endpoint, data = null) {
const options = {
method: 'POST',
body: data ? JSON.stringify(data) : null
};
const response = await this.apiCall(endpoint, options, this.otherTimeoutMs);
if (!response.ok) {
const errorText = await response.text();
throw new Error(`POST ${endpoint} failed: ${response.status} - ${errorText}`);
}
return response.json().catch(() => ({})); // Some endpoints return empty response
}
/**
* PUT request helper
* @param {string} endpoint - API endpoint
* @param {any} data - Request body data
* @returns {Promise<any>} - Parsed JSON response
*/
async put(endpoint, data) {
const response = await this.apiCall(endpoint, {
method: 'PUT',
body: JSON.stringify(data)
}, this.otherTimeoutMs);
if (!response.ok) {
const errorText = await response.text();
throw new Error(`PUT ${endpoint} failed: ${response.status} - ${errorText}`);
}
return response.json().catch(() => ({}));
}
/**
* PATCH request helper
* @param {string} endpoint - API endpoint
* @param {any} data - Request body data
* @returns {Promise<any>} - Parsed JSON response
*/
async patch(endpoint, data) {
const response = await this.apiCall(endpoint, {
method: 'PATCH',
body: JSON.stringify(data)
}, this.otherTimeoutMs);
if (!response.ok) {
const errorText = await response.text();
throw new Error(`PATCH ${endpoint} failed: ${response.status} - ${errorText}`);
}
return response.json().catch(() => ({}));
}
/**
* DELETE request helper
* @param {string} endpoint - API endpoint
* @returns {Promise<any>} - Parsed JSON response
*/
async delete(endpoint) {
const response = await this.apiCall(endpoint, {
method: 'DELETE'
}, this.otherTimeoutMs);
if (!response.ok) {
const errorText = await response.text();
throw new Error(`DELETE ${endpoint} failed: ${response.status} - ${errorText}`);
}
return response.json().catch(() => ({}));
}
// API helper methods for common operations
/**
* Get meter values
*/
async getMeterValues() {
return this.get('ade7953/meter-values');
}
/**
* Get channel configuration
*/
async getChannelConfig(index = null) {
const endpoint = index !== null ? `ade7953/channel?index=${index}` : 'ade7953/channel';
return this.get(endpoint);
}
/**
* Set channel configuration
*/
async setChannelConfig(channelData) {
return this.put('ade7953/channel', channelData);
}
/**
* Patch channel configuration (partial update)
* Note: channelData must include 'index' field
*/
async patchChannelConfig(channelData) {
return this.patch('ade7953/channel', channelData);
}
/**
* Get log levels
*/
async getLogLevels() {
return this.get('logs/level');
}
/**
* Set log levels
*/
async setLogLevels(data) {
return this.put('logs/level', data);
}
/**
* Get system info
*/
async getSystemInfo() {
return this.get('system/info');
}
/**
* Restart system
*/
async restartSystem() {
return this.post('system/restart');
}
/**
* Factory reset
*/
async factoryReset() {
return this.post('system/factory-reset');
}
/**
* Get system time
*/
async getSystemTime() {
return this.get('system/time');
}
/**
* Set system time (for devices without internet connectivity)
* @param {number} unixSeconds - Unix timestamp in seconds
*/
async setSystemTime(unixSeconds) {
return this.post('system/time', { unixTime: unixSeconds });
}
/**
* Get custom MQTT config
*/
async getCustomMqttConfig() {
return this.get('custom-mqtt/config');
}
/**
* Set custom MQTT config
*/
async setCustomMqttConfig(config) {
return this.put('custom-mqtt/config', config);
}
/**
* Get InfluxDB config
*/
async getInfluxDbConfig() {
return this.get('influxdb/config');
}
/**
* Set InfluxDB config
*/
async setInfluxDbConfig(config) {
return this.put('influxdb/config', config);
}
/**
* Get LED brightness
*/
async getLedBrightness() {
return this.get('led/brightness');
}
/**
* Set LED brightness
*/
async setLedBrightness(brightness) {
return this.put('led/brightness', { brightness });
}
/**
* Start disco mode on the user LED layer. The device caps and defaults the
* duration, and releases the layer itself when it elapses.
* @param {number} [durationMs] - Omit to take the device default
*/
async setLedDisco(durationMs) {
const body = { pattern: 'disco' };
if (durationMs) { body.duration_ms = durationMs; }
return this.put('led/color', body);
}
/**
* Release the user LED layer, revealing whatever system layer is occupied
*/
async clearLedColor() {
return this.delete('led/color');
}
/**
* Get ADE7953 configuration
*/
async getAde7953Config() {
return this.get('ade7953/config');
}
/**
* Set ADE7953 configuration
*/
async setAde7953Config(config) {
return this.put('ade7953/config', config);
}
/**
* Get grid frequency
*/
async getGridFrequency() {
return this.get('ade7953/grid-frequency');
}
/**
* Reset energy values for a specific channel or all channels
* @param {number} [channelIndex] - Optional channel index. If omitted, resets all channels.
*/
async resetEnergyValues(channelIndex) {
const url = channelIndex !== undefined
? `ade7953/energy/reset?index=${channelIndex}`
: 'ade7953/energy/reset';
return this.post(url);
}
/**
* Get firmware update info
*/
async getFirmwareUpdateInfo() {
return this.get('firmware/update-info');
}
/**
* Get crash info
*/
async getCrashInfo() {
return this.get('crash/info');
}
/**
* Clear crash dump
*/
async clearCrashDump() {
return this.post('crash/clear');
}
/**
* Get list of files
* @param {string} folder - Optional folder path to filter files
*/
async getFileList(folder = null) {
const endpoint = folder ? `list-files?folder=${encodeURIComponent(folder)}` : 'list-files';
return this.get(endpoint);
}
/**
* Reset WiFi configuration
*/
async resetWifi() {
return this.post('network/wifi/reset');
}
/**
* Set new WiFi credentials
* @param {string} ssid - The WiFi network name
* @param {string} password - The WiFi password
*/
async setWifiCredentials(ssid, password) {
return this.post('network/wifi/credentials', { ssid, password });
}
/**
* Get WiFi provisioning status (state, connected, ssid, ip, rssi, credentialWriteFailed)
*/
async getWifiStatus() {
return this.get('network/wifi/status');
}
/**
* Get the WiFi scan state. The scan is async on the device: poll until status is not 'running'.
* @param {boolean} refresh - Ask the device to start a fresh scan instead of serving its cache
*/
async scanWifiNetworks(refresh = false) {
return this.get('network/wifi/scan' + (refresh ? '?refresh=1' : ''));
}
/**
* Get the last WiFi disconnect diagnostics (reason of a failed association)
*/
async getWifiDiagnostics() {
return this.get('network/wifi/diagnostics');
}
/**
* Get network configuration (static IP)
*/
async getNetworkConfig() {
return this.get('network/config');
}
/**
* Set network configuration (full update). The device restarts to apply.
* @param {object} config - { useStaticIp, ip, gateway, subnet, dns1, dns2, fallbackToDhcp }
*/
async setNetworkConfig(config) {
return this.put('network/config', config);
}
/**
* Reset network configuration to defaults. The device restarts to apply.
*/
async resetNetworkConfig() {
return this.post('network/config/reset');
}
/**
* Get Ethernet status (Home Pro only; 404 on products without Ethernet)
*/
async getEthernetStatus() {
return this.get('network/ethernet/status');
}
/**
* Get Ethernet status, or null when the product has no Ethernet (the status
* endpoint answers 404, or reports enabled:false). Transient failures still
* throw so callers can retry.
*/
async getEthernetStatusIfAvailable() {
try {
const status = await this.getEthernetStatus();
return (status && status.enabled) ? status : null;
} catch (error) {
if (String(error.message).includes('404')) return null;
throw error;
}
}
/**
* Get Ethernet configuration (static IP)
*/
async getEthernetConfig() {
return this.get('network/ethernet/config');
}
/**
* Set Ethernet configuration (full update). The device restarts to apply.
* @param {object} config - { useStaticIp, ip, gateway, subnet, dns1, dns2 }
*/
async setEthernetConfig(config) {
return this.put('network/ethernet/config', config);
}
/**
* Reset Ethernet configuration to defaults. The device restarts to apply.
*/
async resetEthernetConfig() {
return this.post('network/ethernet/config/reset');
}
/**
* Get health status
*/
async getHealth() {
return this.get('health');
}
/**
* Get authentication status
*/
async getAuthStatus() {
return this.get('auth/status');
}
/**
* Change password
*/
async changePassword(currentPassword, newPassword) {
return this.post('auth/change-password', {
currentPassword,
newPassword
});
}
/**
* Reset password to default
*/
async resetPassword() {
return this.post('auth/reset-password');
}
/**
* Get OTA status
*/
async getOtaStatus() {
return this.get('ota/status');
}
/**
* Rollback firmware
*/
async rollbackFirmware() {
return this.post('ota/rollback');
}
/**
* Get system statistics
*/
async getSystemStatistics() {
return this.get('system/statistics');
}
/**
* Get system secrets status
*/
async getSystemSecrets() {
return this.get('system/secrets');
}
/**
* Get logs
*/
async getLogs() {
return this.get('logs', { responseType: 'text' });
}
/**
* Clear logs
*/
async clearLogs() {
return this.post('logs/clear');
}
/**
* Get custom MQTT status
*/
async getCustomMqttStatus() {
return this.get('custom-mqtt/status');
}
/**
* Reset custom MQTT config
*/
async resetCustomMqttConfig() {
return this.post('custom-mqtt/config/reset');
}
/**
* Get MQTT cloud services status
*/
async getMqttCloudServices() {
return this.get('mqtt/cloud-services');
}
/**
* Set MQTT cloud services status
*/
async setMqttCloudServices(enabled) {
return this.put('mqtt/cloud-services', { enabled });
}
/**
* Get InfluxDB status
*/
async getInfluxDbStatus() {
return this.get('influxdb/status');
}
/**
* Reset InfluxDB config
*/
async resetInfluxDbConfig() {
return this.post('influxdb/config/reset');
}
/**
* Reset ADE7953 configuration
*/
async resetAde7953Config() {
return this.post('ade7953/config/reset');
}
/**
* Get ADE7953 sample time
*/
async getAde7953SampleTime() {
return this.get('ade7953/sample-time');
}
/**
* Set ADE7953 sample time
*/
async setAde7953SampleTime(sampleTime) {
return this.put('ade7953/sample-time', { sampleTime });
}
/**
* Read ADE7953 register
*/
async readAde7953Register(address, bits = 32, signed = false) {
return this.get(`ade7953/register?address=${address}&bits=${bits}&signed=${signed}`);
}
/**
* Write ADE7953 register
*/
async writeAde7953Register(address, value, bits = 32, signed = false) {
return this.put('ade7953/register', { address, value, bits, signed });
}
/**
* Get crash dump
*/
async getCrashDump(offset = 0, size = 1024) {
return this.get(`crash/dump?offset=${offset}&size=${size}`);
}
/**
* Get specific file content
*/
async getFile(filepath) {
return this.get(`files/${encodeURIComponent(filepath)}`);
}
/**
* Get specific file content as text
*/
async getFileAsText(filepath) {
return this.get(`files/${encodeURIComponent(filepath)}`, { responseType: 'text' });
}
/**
* Upload a file to LittleFS
* @param {string} filepath - Target file path on device
* @param {File|Blob} file - File to upload
*/
async uploadFile(filepath, file) {
const formData = new FormData();
formData.append('file', file, filepath);
const response = await this.apiCall(`files/${encodeURIComponent(filepath)}`, {
method: 'POST',
body: formData,
headers: {} // Let browser set Content-Type with boundary
}, this.otherTimeoutMs);
if (!response.ok) {
const errorText = await response.text();
throw new Error(`File upload failed: ${response.status} - ${errorText}`);
}
return response.json().catch(() => ({}));
}
/**
* Delete a file from LittleFS
* @param {string} filepath - File path to delete
*/
async deleteFile(filepath) {
return this.post('delete-file', { filepath });
}
/**
* Get safe mode status
*/
async getSafeModeStatus() {
return this.get('system/safe-mode');
}
/**
* Clear safe mode
*/
async clearSafeMode() {
return this.post('system/safe-mode/clear');
}
/**
* Get UDP log destination
*/
async getUdpLogDestination() {
return this.get('logs-udp-destination');
}
/**
* Set UDP log destination
* @param {string} host - UDP destination host
* @param {number} port - UDP destination port
*/
async setUdpLogDestination(host, port) {
return this.put('logs-udp-destination', { host, port });
}
/**
* Update all channels configuration (bulk update)
* @param {Array} channels - Array of channel configurations
*/
async updateAllChannels(channels) {
return this.put('ade7953/channels', { channels });
}
/**
* Arm waveform capture
* @param {number} channelIndex - Channel index for capture
* @param {string} signal - Signal type to capture
*/
async armWaveformCapture(channelIndex, signal) {
return this.post('ade7953/waveform/arm', { index: channelIndex, signal });
}
/**
* Get waveform capture status
*/
async getWaveformStatus() {
return this.get('ade7953/waveform/status');
}
/**
* Get captured waveform data
*/
async getWaveformData() {
return this.get('ade7953/waveform/data');
}
/**
* Download configuration backup as JSON file
* @returns {Promise<Blob>} - JSON backup file blob
*/
async downloadConfigurationBackup() {
const response = await this.apiCall('backup/configuration', {
method: 'GET'
}, this.getTimeoutMs);
if (!response.ok) {
throw new Error(`Configuration backup failed: ${response.status}`);
}
return response.blob();
}
/**
* Download filesystem backup as TAR file
* @returns {Promise<Blob>} - TAR backup file blob
*/
async downloadFilesystemBackup() {
const response = await this.apiCall('backup/filesystem', {
method: 'GET'
}, this.otherTimeoutMs); // May take longer for large filesystems
if (!response.ok) {
throw new Error(`Filesystem backup failed: ${response.status}`);
}
return response.blob();
}
/**
* Restore configuration from JSON backup file
* @param {File|Blob} file - JSON backup file
* @param {boolean} force - Skip device ID validation (allows cross-device restore)
*/
async restoreConfiguration(file, force = false) {
const formData = new FormData();
formData.append('file', file);
const url = force ? 'restore/configuration?force=true' : 'restore/configuration';
const response = await this.apiCall(url, {
method: 'POST',
body: formData,
headers: {} // Let browser set Content-Type with boundary
}, this.longTimeoutMs);
if (!response.ok) {
const errorText = await response.text();
throw new Error(`Configuration restore failed: ${response.status} - ${errorText}`);
}
return response.json().catch(() => ({}));
}
/**
* Restore filesystem from TAR backup file
* @param {File|Blob} file - TAR backup file
*/
async restoreFilesystem(file) {
const formData = new FormData();
formData.append('file', file);
const response = await this.apiCall('restore/filesystem', {
method: 'POST',
body: formData,
headers: {} // Let browser set Content-Type with boundary
}, this.longTimeoutMs);
if (!response.ok) {
const errorText = await response.text();
throw new Error(`Filesystem restore failed: ${response.status} - ${errorText}`);
}
return response.json().catch(() => ({}));
}
}
// Create global instance
window.energyApi = new EnergyMeAPI();
/**
* Display name for an active network interface reported by the device.
* @param {string} name - 'ethernet' | 'wifi' | 'none'
*/
function formatInterfaceName(name) {
var names = { 'ethernet': 'Ethernet', 'wifi': 'WiFi', 'none': 'None' };
return names[name] || 'N/A';
}
/**
* Show a toast notification.
* @param {string} message - Text to display
* @param {'success'|'error'|''} type - Message type for coloring ('' or falsy = info)
* @param {number} [timeout] - Auto-dismiss after ms (default: 3000 success, 5000 error, 2000 info)
*/
function showStatus(message, type, timeout) {
if (!message) return;
// Ensure container exists
var container = document.getElementById('toast-container');
if (!container) {
container = document.createElement('div');
container.id = 'toast-container';
document.body.appendChild(container);
}
var toast = document.createElement('div');
toast.className = 'toast ' + (type || 'info');
toast.textContent = message;
container.appendChild(toast);
// Trigger show after a frame so the transition plays
requestAnimationFrame(function() {
toast.classList.add('show');
});
if (typeof timeout === 'undefined') {
timeout = (type === 'error') ? 5000 : (type === 'success') ? 3000 : 2000;
}
setTimeout(function() {
toast.classList.remove('show');
setTimeout(function() { toast.remove(); }, 300);
}, timeout);
}
// Backward compatibility aliases
window.authAPI = window.energyApi; // For existing code using authAPI
window.authManager = { apiCall: (endpoint, options) => window.energyApi.apiCall(endpoint, options) };f4329a85eThis file is pinned to the selected release. Download the original to open it in your design tool.