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/index.css">
<link rel="stylesheet" type="text/css" href="/css/tooltip.css">
<link rel="icon" type="image/svg+xml" href="/favicon.svg">
<title>EnergyMe</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css" integrity="sha384-5e2ESR8Ycmos6g3gAKr1Jvwye8sW4U1u/cAKulfVJnkakCcMqhOudbtPnvJ+nbv7" crossorigin="anonymous">
</head>
<body>
<div class="header">EnergyMe</div>
<div class="subheader" id="productSubheader">Home</div>
<div class="buttonNavigation-container">
<a class="buttonNavigation" type="inner" href="/info">💡 Info</a>
<a class="buttonNavigation" type="inner" href="/configuration">⚙️ Configuration</a>
<a class="buttonNavigation" type="inner" href="/integrations">🔗 Integrations</a>
<a class="buttonNavigation" type="inner" href="/update">🚀 Update</a>
</div>
<!-- Energy Flow Diagram - Simple Layout -->
<div id="energy-flow-section" class="section-box energy-flow-section">
<div class="power-flow">
<!-- Main flow area -->
<div class="power-flow-main">
<!-- Top: Solar (optional) -->
<div id="pf-solar" class="pf-node pf-solar" style="display: none;">
<div class="pf-icon">☀️</div>
<div class="pf-value" id="solar-power">0 W</div>
<div class="pf-connector pf-connector-bottom"></div>
</div>
<!-- Middle row: Grid - Center - Home -->
<div class="pf-middle-row">
<div id="pf-grid" class="pf-node pf-grid">
<div class="pf-icon">⚡</div>
<div class="pf-value" id="grid-power">0 W</div>
<div class="pf-connector pf-connector-right"></div>
</div>
<div class="pf-center">
<div class="pf-center-dot"></div>
</div>
<div id="pf-home" class="pf-node pf-home">
<div class="pf-connector pf-connector-left"></div>
<div class="pf-icon">🏠</div>
<div class="pf-value" id="home-power">0 W</div>
</div>
</div>
<!-- Bottom: Battery (optional) -->
<div id="pf-battery" class="pf-node pf-battery" style="display: none;">
<div class="pf-connector pf-connector-top"></div>
<div class="pf-icon">🔋</div>
<div class="pf-value" id="battery-power">0 W</div>
</div>
</div>
<!-- Loads panel (right side on desktop, below on mobile) -->
<div id="pf-loads" class="pf-loads" style="display: none;">
<div class="pf-loads-header">Loads</div>
<div id="pf-loads-list" class="pf-loads-list"></div>
</div>
</div>
<!-- Sparkline tooltip -->
<div id="sparkline-tooltip" class="sparkline-tooltip">
<canvas id="sparkline-canvas" width="120" height="40"></canvas>
</div>
</div>
<!-- Charts Section -->
<div class="section-box">
<div class="chart-header">
<h3 id="main-chart-title">Energy Consumption</h3>
<div class="chart-controls">
<div class="view-selector" id="chart-type-selector" style="display: none;">
<button id="consumption-view" class="view-toggle active">Consumption</button>
<button id="balance-view" class="view-toggle">Balance</button>
</div>
<div class="view-selector">
<button id="daily-view" class="view-toggle active">Daily</button>
<button id="monthly-view" class="view-toggle">Monthly</button>
<button id="yearly-view" class="view-toggle">Yearly</button>
<button id="total-view" class="view-toggle">Total</button>
</div>
<div class="date-selector">
<input type="date" id="date-picker" />
<input type="month" id="month-picker" style="display: none;" />
<input type="number" id="year-picker" min="2020" max="2100" style="display: none; width: 80px;" />
<button id="prev-period" class="nav-button">◀</button>
<button id="next-period" class="nav-button">▶</button>
</div>
</div>
</div>
<div id="consumption-chart" style="position: relative;">
<div class="chart-loading">📊 Crunching the numbers...</div>
<canvas id="consumption-chart-canvas" style="display: none;"></canvas>
<button id="download-csv" class="tooltip" style="position: absolute; top: 2px; right: 2px; display: none;">
<i class="fas fa-download"></i>
</button>
</div>
<!-- Consumption Sharing Breakdown -->
<div id="consumption-sharing-section" class="consumption-sharing-section" style="display: none;">
<div style="position: relative; height: 300px;">
<canvas id="consumption-pie-canvas" style="display: none;"></canvas>
<div class="chart-loading">📊 Loading breakdown...</div>
</div>
<div id="consumption-total-row" style="display: none; text-align: center; margin-top: 8px;">
<span class="kpi-label">🏠 Total: </span><span id="consumption-total-value" class="kpi-value" style="font-size: 16px;"></span><span class="kpi-unit"> kWh</span>
</div>
</div>
<div id="balance-chart" style="position: relative; display: none;">
<div class="chart-loading">🔋 Calculating energy flows...</div>
<canvas id="balance-chart-canvas" style="display: none;"></canvas>
<button id="download-balance-csv" class="tooltip" style="position: absolute; top: 2px; right: 2px; display: none;">
<i class="fas fa-download"></i>
</button>
</div>
<!-- Balance KPIs -->
<div id="balance-kpis-section" class="energy-kpis" style="display: none;">
<div id="balance-kpi-grid-import" class="kpi-card">
<div class="kpi-label">🔌 Grid Import</div>
<div class="kpi-value" id="balance-kpi-grid-import-value">0</div>
<div class="kpi-unit">kWh</div>
</div>
<div id="balance-kpi-grid-export" class="kpi-card">
<div class="kpi-label">⚡ Grid Export</div>
<div class="kpi-value" id="balance-kpi-grid-export-value">0</div>
<div class="kpi-unit">kWh</div>
</div>
<div id="balance-kpi-production" class="kpi-card" style="display: none;">
<div class="kpi-label"><span id="balance-kpi-production-icon">☀️</span> <span id="balance-kpi-production-label">Production</span></div>
<div class="kpi-value" id="balance-kpi-production-value">0</div>
<div class="kpi-unit">kWh</div>
</div>
<div id="balance-kpi-home" class="kpi-card">
<div class="kpi-label">🏠 Home Consumption</div>
<div class="kpi-value" id="balance-kpi-home-value">0</div>
<div class="kpi-unit">kWh</div>
</div>
<div id="balance-kpi-self-consumption" class="kpi-card" style="display: none;">
<div class="kpi-label">🏠 Self-Consumption
<span class="info-tooltip">
<button class="info-tooltip-icon" onclick="toggleTooltip(this, event)" aria-label="More info about Self-Consumption">ⓘ</button>
<div class="info-tooltip-popover" role="tooltip">
<strong>Self-Consumption</strong> = share of solar production used directly on-site.<br><br>
Formula: (Production − Grid Export) ÷ Production<br><br>
100 % means all generated energy was consumed locally; 0 % means everything was exported to the grid.
</div>
</span>
</div>
<div class="kpi-value" id="balance-kpi-self-consumption-value">0%</div>
</div>
<div id="balance-kpi-autosufficiency" class="kpi-card" style="display: none;">
<div class="kpi-label">🌱 Autosufficiency
<span class="info-tooltip">
<button class="info-tooltip-icon" onclick="toggleTooltip(this, event)" aria-label="More info about Autosufficiency">ⓘ</button>
<div class="info-tooltip-popover" role="tooltip">
<strong>Autosufficiency</strong> = share of home consumption covered by own production (solar / battery).<br><br>
Formula: (Home Consumption − Grid Import) ÷ Home Consumption<br><br>
100 % means the home was fully self-powered; 0 % means all energy came from the grid.
</div>
</span>
</div>
<div class="kpi-value" id="balance-kpi-autosufficiency-value">0%</div>
</div>
<div id="balance-kpi-battery-charge" class="kpi-card" style="display: none;">
<div class="kpi-label">🔋 Battery Charged</div>
<div class="kpi-value" id="balance-kpi-battery-charge-value">0</div>
<div class="kpi-unit">kWh</div>
</div>
<div id="balance-kpi-battery-discharge" class="kpi-card" style="display: none;">
<div class="kpi-label">🔋 Battery Discharged</div>
<div class="kpi-value" id="balance-kpi-battery-discharge-value">0</div>
<div class="kpi-unit">kWh</div>
</div>
</div>
<!-- Energy KPIs (Consumption View) -->
<div id="energy-kpis-section" class="energy-kpis" style="display: none;">
<div id="kpi-grid-import" class="kpi-card">
<div class="kpi-label">🔌 Grid Import</div>
<div class="kpi-value" id="kpi-grid-import-value">0</div>
<div class="kpi-unit">kWh</div>
</div>
<div id="kpi-grid-export" class="kpi-card">
<div class="kpi-label">⚡ Grid Export</div>
<div class="kpi-value" id="kpi-grid-export-value">0</div>
<div class="kpi-unit">kWh</div>
</div>
<div id="kpi-production" class="kpi-card" style="display: none;">
<div class="kpi-label">☀️ Production</div>
<div class="kpi-value" id="kpi-production-value">0</div>
<div class="kpi-unit">kWh</div>
</div>
<div id="kpi-self-consumption" class="kpi-card" style="display: none;">
<div class="kpi-label">🏠 Self-Consumption
<span class="info-tooltip">
<button class="info-tooltip-icon" onclick="toggleTooltip(this, event)" aria-label="More info about Self-Consumption">ⓘ</button>
<div class="info-tooltip-popover" role="tooltip">
<strong>Self-Consumption</strong> = share of solar production used directly on-site.<br><br>
Formula: (Production − Grid Export) ÷ Production<br><br>
100 % means all generated energy was consumed locally; 0 % means everything was exported to the grid.
</div>
</span>
</div>
<div class="kpi-value" id="kpi-self-consumption-value">0%</div>
</div>
<div id="kpi-autosufficiency" class="kpi-card" style="display: none;">
<div class="kpi-label">🌱 Autosufficiency
<span class="info-tooltip">
<button class="info-tooltip-icon" onclick="toggleTooltip(this, event)" aria-label="More info about Autosufficiency">ⓘ</button>
<div class="info-tooltip-popover" role="tooltip">
<strong>Autosufficiency</strong> = share of home consumption covered by own production (solar / battery).<br><br>
Formula: (Home Consumption − Grid Import) ÷ Home Consumption<br><br>
100 % means the home was fully self-powered; 0 % means all energy came from the grid.
</div>
</span>
</div>
<div class="kpi-value" id="kpi-autosufficiency-value">0%</div>
</div>
<div id="kpi-battery-charge" class="kpi-card" style="display: none;">
<div class="kpi-label">🔋 Battery Charged</div>
<div class="kpi-value" id="kpi-battery-charge-value">0</div>
<div class="kpi-unit">kWh</div>
</div>
<div id="kpi-battery-discharge" class="kpi-card" style="display: none;">
<div class="kpi-label">🔋 Battery Discharged</div>
<div class="kpi-value" id="kpi-battery-discharge-value">0</div>
<div class="kpi-unit">kWh</div>
</div>
</div>
</div>
<!-- External libraries -->
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0" integrity="sha384-e6nUZLBkQ86NJ6TVVKAeSaK8jWa3NhkYWZFomE39AvDbQWeie9PlQqM3pmYW5d1g" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/pako@2.1.0/dist/pako.min.js" integrity="sha384-rNlaE5fs9dGIjmxWDALQh/RBAaGRYT5ChrzHo6tRfgrZ36iRFAiquP5g41Jsv+0j" crossorigin="anonymous"></script>
<!-- EnergyMe modules -->
<script src="/js/api-client.js"></script>
<script src="/js/issues.js"></script>
<script src="/js/data-helpers.js"></script>
<script src="/js/chart-helpers.js"></script>
<script src="/js/power-flow.js"></script>
<script src="/js/tooltip.js"></script>
</body>
<script>
// ============================================================================
// PAGE STATE
// ============================================================================
let channelData = {};
let meterData = {};
let availableDates = [];
let availableMonths = [];
let availableYears = [];
let currentView = 'daily';
let currentChartType = 'consumption';
let currentDate = null;
let currentMonth = null;
let currentYear = null;
let hasBalanceCapability = false;
let meterDataUpdateInProgress = false;
let balanceData = null;
// ============================================================================
// INITIALIZATION
// ============================================================================
async function initializePage() {
try {
// Get channel configuration and current meter data
[channelData, meterData] = await Promise.all([
energyApi.getChannelConfig(),
energyApi.getMeterValues()
]);
// Initialize modules with data
ChannelCache.setChannelData(channelData);
PowerFlowState.init();
// Update real-time displays immediately
PowerFlowHelpers.updateEnergyFlow(meterData, channelData);
// Load charts in parallel
loadChartsAsync();
// Set up event listeners
setupEventListeners();
} catch (error) {
console.error('Error initializing page:', error);
ChartHelpers.showErrorMessage('Failed to load energy data');
}
}
async function loadChartsAsync() {
try {
await loadAvailableDates();
if (availableDates.length > 0) {
// Lists are local dates clamped to local today, so the last entry is the
// most recent local day/month/year with data
currentDate = availableDates[availableDates.length - 1];
currentMonth = availableMonths[availableMonths.length - 1];
currentYear = availableYears[availableYears.length - 1];
document.getElementById('date-picker').value = currentDate;
document.getElementById('month-picker').value = currentMonth;
document.getElementById('year-picker').value = currentYear;
updateNavigationButtons();
await loadAndDisplayCharts();
} else {
ChartHelpers.showNoDataMessage();
}
} catch (error) {
console.error('Error loading charts:', error);
ChartHelpers.showErrorMessage('Failed to load chart data');
}
}
function daysOfUtcMonth(yearMonth, lastDay = null) {
const [year, month] = yearMonth.split('-').map(Number);
const count = lastDay || new Date(Date.UTC(year, month, 0)).getUTCDate();
return Array.from({ length: count }, (_, i) => `${yearMonth}-${String(i + 1).padStart(2, '0')}`);
}
// File names are UTC dates; the pickers and navigation work in local dates
async function loadAvailableDates() {
try {
const utcDates = new Set();
const now = new Date();
const utcToday = now.toISOString().substring(0, 10);
const utcMonth = utcToday.substring(0, 7);
const utcYear = utcToday.substring(0, 4);
const dailyFiles = await energyApi.getFileList('energy/daily') || {};
ArchiveCache.dailyFilesSet.clear();
Object.keys(dailyFiles)
.filter(filename => filename.endsWith('.csv.gz') || filename.endsWith('.csv'))
.map(filename => filename.replace('.csv.gz', '').replace('.csv', ''))
.forEach(date => {
ArchiveCache.dailyFilesSet.add(date);
utcDates.add(date);
});
const monthlyFiles = await energyApi.getFileList('energy/monthly') || {};
const monthlyArchives = Object.keys(monthlyFiles).filter(f => f.endsWith('.csv.gz')).map(f => f.replace('.csv.gz', ''));
ArchiveCache.archiveFiles.monthly = new Map(monthlyArchives.map(key => [key, monthlyFiles[key + '.csv.gz']]));
monthlyArchives.forEach(yearMonth => {
if (yearMonth < utcMonth) daysOfUtcMonth(yearMonth).forEach(d => utcDates.add(d));
else if (yearMonth === utcMonth) daysOfUtcMonth(yearMonth, now.getUTCDate()).forEach(d => utcDates.add(d));
});
// A yearly archive holds the year's completed months
const yearlyFiles = await energyApi.getFileList('energy/yearly') || {};
const yearlyArchives = Object.keys(yearlyFiles).filter(f => f.endsWith('.csv.gz')).map(f => f.replace('.csv.gz', ''));
ArchiveCache.archiveFiles.yearly = new Map(yearlyArchives.map(key => [key, yearlyFiles[key + '.csv.gz']]));
yearlyArchives.forEach(year => {
const lastMonth = year < utcYear ? 12 : year === utcYear ? now.getUTCMonth() : 0;
for (let month = 1; month <= lastMonth; month++) {
daysOfUtcMonth(`${year}-${String(month).padStart(2, '0')}`).forEach(d => utcDates.add(d));
}
});
availableDates = EnergyAggregation.localDatesForUtcDates([...utcDates]);
availableMonths = [...new Set(availableDates.map(d => d.substring(0, 7)))];
availableYears = [...new Set(availableDates.map(d => d.substring(0, 4)))];
} catch (error) {
console.error('Error loading available dates:', error);
availableDates = [];
availableMonths = [];
availableYears = [];
}
}
// ============================================================================
// EVENT LISTENERS
// ============================================================================
function setupEventListeners() {
document.getElementById('consumption-view').addEventListener('click', () => switchChartType('consumption'));
document.getElementById('balance-view').addEventListener('click', () => switchChartType('balance'));
document.getElementById('daily-view').addEventListener('click', () => switchView('daily'));
document.getElementById('monthly-view').addEventListener('click', () => switchView('monthly'));
document.getElementById('yearly-view').addEventListener('click', () => switchView('yearly'));
document.getElementById('total-view').addEventListener('click', () => switchView('total'));
document.getElementById('date-picker').addEventListener('change', async (e) => {
currentDate = e.target.value;
updateNavigationButtons();
await loadAndDisplayCharts();
});
document.getElementById('month-picker').addEventListener('change', async (e) => {
currentMonth = e.target.value;
updateNavigationButtons();
await loadAndDisplayCharts();
});
document.getElementById('year-picker').addEventListener('change', async (e) => {
currentYear = e.target.value;
updateNavigationButtons();
await loadAndDisplayCharts();
});
document.getElementById('prev-period').addEventListener('click', navigatePrevious);
document.getElementById('next-period').addEventListener('click', navigateNext);
// Initialize view visibility (consumption by default)
switchChartType(currentChartType);
}
async function navigatePrevious() {
if (currentView === 'total') return;
const lists = { daily: availableDates, monthly: availableMonths, yearly: availableYears };
const current = { daily: currentDate, monthly: currentMonth, yearly: currentYear };
const pickers = { daily: 'date-picker', monthly: 'month-picker', yearly: 'year-picker' };
const list = lists[currentView];
const currentIndex = list.indexOf(current[currentView]);
if (currentIndex > 0) {
const newValue = list[currentIndex - 1];
if (currentView === 'daily') currentDate = newValue;
else if (currentView === 'monthly') currentMonth = newValue;
else currentYear = newValue;
document.getElementById(pickers[currentView]).value = newValue;
updateNavigationButtons();
await loadAndDisplayCharts();
}
}
async function navigateNext() {
if (currentView === 'total') return;
const lists = { daily: availableDates, monthly: availableMonths, yearly: availableYears };
const current = { daily: currentDate, monthly: currentMonth, yearly: currentYear };
const pickers = { daily: 'date-picker', monthly: 'month-picker', yearly: 'year-picker' };
const list = lists[currentView];
const currentIndex = list.indexOf(current[currentView]);
if (currentIndex < list.length - 1) {
const newValue = list[currentIndex + 1];
if (currentView === 'daily') currentDate = newValue;
else if (currentView === 'monthly') currentMonth = newValue;
else currentYear = newValue;
document.getElementById(pickers[currentView]).value = newValue;
updateNavigationButtons();
await loadAndDisplayCharts();
}
}
function switchView(view) {
currentView = view;
document.getElementById('daily-view').classList.toggle('active', view === 'daily');
document.getElementById('monthly-view').classList.toggle('active', view === 'monthly');
document.getElementById('yearly-view').classList.toggle('active', view === 'yearly');
document.getElementById('total-view').classList.toggle('active', view === 'total');
document.getElementById('date-picker').style.display = view === 'daily' ? 'block' : 'none';
document.getElementById('month-picker').style.display = view === 'monthly' ? 'block' : 'none';
document.getElementById('year-picker').style.display = view === 'yearly' ? 'block' : 'none';
const dateSelector = document.querySelector('.date-selector');
dateSelector.style.display = view === 'total' ? 'none' : 'flex';
updateNavigationButtons();
loadAndDisplayCharts();
}
function switchChartType(chartType) {
currentChartType = chartType;
document.getElementById('consumption-view').classList.toggle('active', chartType === 'consumption');
document.getElementById('balance-view').classList.toggle('active', chartType === 'balance');
document.getElementById('consumption-chart').style.display = chartType === 'consumption' ? 'block' : 'none';
document.getElementById('balance-chart').style.display = chartType === 'balance' ? 'block' : 'none';
// Toggle between consumption sharing and balance KPIs
const consumptionSharingSection = document.getElementById('consumption-sharing-section');
const balanceKpisSection = document.getElementById('balance-kpis-section');
const energyKpisSection = document.getElementById('energy-kpis-section');
const consumptionTotalRow = document.getElementById('consumption-total-row');
if (chartType === 'consumption') {
if (consumptionSharingSection) consumptionSharingSection.style.display = 'block';
if (consumptionTotalRow && consumptionTotalRow.dataset.ready) consumptionTotalRow.style.display = 'block';
if (balanceKpisSection) balanceKpisSection.style.display = 'none';
if (energyKpisSection) energyKpisSection.style.display = 'none';
} else {
if (consumptionSharingSection) consumptionSharingSection.style.display = 'none';
if (consumptionTotalRow) consumptionTotalRow.style.display = 'none';
if (balanceKpisSection) balanceKpisSection.style.display = 'flex';
if (energyKpisSection) energyKpisSection.style.display = 'none';
}
document.getElementById('main-chart-title').textContent = chartType === 'consumption' ? 'Energy Consumption' : 'Energy Balance';
}
function updateNavigationButtons() {
const lists = { daily: availableDates, monthly: availableMonths, yearly: availableYears, total: [] };
const current = { daily: currentDate, monthly: currentMonth, yearly: currentYear, total: null };
const list = lists[currentView];
const currentIndex = list.length > 0 ? list.indexOf(current[currentView]) : -1;
document.getElementById('prev-period').disabled = currentIndex <= 0;
document.getElementById('next-period').disabled = currentIndex < 0 || currentIndex >= list.length - 1;
}
// ============================================================================
// CHART LOADING
// ============================================================================
// The period simply has no samples yet (a new device, the first hour of a day, a file
// holding only its header): not a failure, so it gets a neutral message, not the red one.
class NoEnergyDataError extends Error {}
// Bumped per load so a slow load finishing after the user switched period is discarded
let chartLoadSeq = 0;
async function loadAndDisplayCharts() {
const periods = { daily: currentDate, monthly: currentMonth, yearly: currentYear, total: 'all time' };
// Total needs the listing (its first year), the others their period
if (currentView === 'total' ? availableYears.length === 0 : !periods[currentView]) return;
const view = currentView;
const seq = ++chartLoadSeq;
try {
ChartHelpers.showLoadingMessage(currentChartType);
const period = view === 'total' ? null : periods[view];
const utcDates = EnergyAggregation.utcDatesForPeriod(view, period, availableYears[0]);
const { entries, fetchFailed } = await loadEnergyEntries(utcDates);
if (seq !== chartLoadSeq) return;
const result = EnergyAggregation.finalize(EnergyAggregation.aggregate(entries, view, period));
if (Object.keys(result.imported).length === 0) {
if (fetchFailed) throw new Error('Energy files could not be fetched');
throw new NoEnergyDataError();
}
displayCharts(result, view);
} catch (error) {
if (seq !== chartLoadSeq) return;
if (error instanceof NoEnergyDataError) {
ChartHelpers.setChartMessage('📊', `No energy data yet for ${periods[view]}. It appears once the first hourly values are recorded.`);
return;
}
console.error('Error loading charts:', error);
ChartHelpers.showErrorMessage(`Failed to load energy data for ${periods[view]}`);
}
}
// A file that does not exist is expected (no data then); anything else is a failure
function isMissingFileError(error) {
return /^No |: 404$/.test((error && error.message) || '');
}
// Readings for the given UTC dates: the daily file where the device still has one,
// otherwise that month's archive, otherwise those months' rows of the yearly archive
// (the firmware merges finished months into it). Overlaps are harmless:
// EnergyAggregation dedupes by channel and timestamp.
async function loadEnergyEntries(utcDates) {
const entries = [];
let fetchFailed = false;
const append = rows => { for (const row of rows) entries.push(row); };
const noteError = error => { if (!isMissingFileError(error)) fetchFailed = true; };
const archiveMonths = new Set();
for (const date of utcDates) {
if (ArchiveCache.dailyFilesSet.has(date)) {
try {
append(DataHelpers.parseCsvEnergyData(await DataHelpers.loadDailyCsvData(date)));
continue;
} catch (e) { noteError(e); }
}
archiveMonths.add(date.substring(0, 7));
}
const yearlyMonths = {};
for (const yearMonth of archiveMonths) {
const known = ArchiveCache.archiveFiles.monthly;
if (!known || known.has(yearMonth)) {
try {
append(DataHelpers.parseCsvEnergyData(await ArchiveCache.loadArchiveWithCache('monthly', yearMonth)));
continue;
} catch (e) { noteError(e); }
}
const year = yearMonth.substring(0, 4);
(yearlyMonths[year] = yearlyMonths[year] || []).push(yearMonth);
}
for (const [year, months] of Object.entries(yearlyMonths)) {
try {
append(DataHelpers.parseCsvEnergyData(await ArchiveCache.loadArchiveWithCache('yearly', year), months));
} catch (e) { noteError(e); }
}
return { entries, fetchFailed };
}
function displayCharts(result, view) {
ChartHelpers.restoreChartCanvases(currentChartType);
ChartHelpers.updateConsumptionChart(result.imported, view, result.exported, channelData, currentChartType);
ChartHelpers.updateConsumptionSharing(result.imported, view, channelData, currentChartType);
hasBalanceCapability = ChannelCache.production.length > 0 || ChannelCache.battery.length > 0 || ChannelCache.inverter.length > 0;
balanceData = ChartHelpers.updateBalanceChart(result.rawImported, view, result.rawImported, result.rawExported, hasBalanceCapability);
ChartHelpers.updateBalanceKPIView(balanceData, hasBalanceCapability);
setupCsvDownload(result.imported, view);
}
// ============================================================================
// CSV DOWNLOAD
// ============================================================================
const CSV_PERIOD_HEADERS = { daily: 'Local time', monthly: 'Date', yearly: 'Month', total: 'Year' };
function csvPeriodHeader(viewType) {
const timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone;
return timeZone ? `${CSV_PERIOD_HEADERS[viewType]} (${timeZone})` : CSV_PERIOD_HEADERS[viewType];
}
function csvField(value) {
const text = String(value);
return /[",\r\n]/.test(text) ? `"${text.replace(/"/g, '""')}"` : text;
}
// Blob instead of a data: URI, so a '#' in a channel label cannot truncate the file
function downloadCsv(filename, rows) {
const csv = rows.map(row => row.map(csvField).join(',')).join('\n') + '\n';
const url = URL.createObjectURL(new Blob([csv], { type: 'text/csv;charset=utf-8' }));
const link = document.createElement('a');
link.href = url;
link.download = filename;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
// Deferred: some browsers cancel a download whose URL is revoked synchronously
setTimeout(() => URL.revokeObjectURL(url), 10000);
}
function setupCsvDownload(consumptionData, viewType) {
const period = { daily: currentDate, monthly: currentMonth, yearly: currentYear, total: null }[viewType];
const fileSuffix = `${viewType}_${period || 'all'}`;
document.getElementById('download-csv').onclick = function() {
const periods = Object.keys(consumptionData).sort();
const channels = new Set();
periods.forEach(key => Object.keys(consumptionData[key]).forEach(ch => channels.add(ch)));
const channelArray = [...channels].sort((a, b) => {
if (a === 'Other') return 1;
if (b === 'Other') return -1;
return parseInt(a) - parseInt(b);
});
const rows = [[csvPeriodHeader(viewType), ...channelArray.map(ch => ChartHelpers.getChannelLabel(ch, channelData))]];
periods.forEach(key => {
rows.push([EnergyAggregation.csvPeriodLabel(key, viewType, period),
...channelArray.map(ch => (consumptionData[key][ch] || 0).toFixed(3))]);
});
downloadCsv(`energy_consumption_${fileSuffix}.csv`, rows);
};
document.getElementById('download-balance-csv').onclick = function() {
if (!balanceData) return;
const rows = [[csvPeriodHeader(viewType), 'Grid Import (kWh)', 'Grid Export (kWh)', 'PV (kWh)', 'Battery Discharge (kWh)', 'Battery Charge (kWh)', 'Home (kWh)']];
balanceData.periods.forEach((key, i) => {
rows.push([EnergyAggregation.csvPeriodLabel(key, viewType, period),
...['gridImport', 'gridExport', 'pv', 'batteryDischarge', 'batteryCharge', 'homeConsumption'].map(series => balanceData[series][i].toFixed(3))]);
});
downloadCsv(`energy_balance_${fileSuffix}.csv`, rows);
};
}
// ============================================================================
// STARTUP CHECKS
// ============================================================================
async function fetchFirmwareUpdateInfo() {
try {
const data = await energyApi.getFirmwareUpdateInfo();
if (data.isLatest === false) {
document.querySelector('.buttonNavigation[href="/update"]').innerHTML += ' 🔔';
}
} catch (error) {
console.error('Error fetching firmware update info:', error);
}
}
// checkDefaultPassword() lived here and raised a dismissible alert(). It is gone because
// the dashboard is no longer served in the state it warned about: "/" serves the password
// gate while the default password is active, and the API refuses everything but the way
// out. A warning that could be clicked away was never the enforcement anyway.
// ============================================================================
// PAGE STARTUP
// ============================================================================
document.addEventListener('DOMContentLoaded', async () => {
ChartHelpers.initSparkline();
// First, so a Pro does not read "Home" for the whole init; not awaited, because the
// label is cosmetic and must not delay the meter data.
energyApi.getAuthStatus().then(status => {
if (status && status.productName) document.getElementById('productSubheader').textContent = status.productName;
}).catch(() => {});
await initializePage();
await fetchFirmwareUpdateInfo();
PowerFlowHelpers.setupSparklineHovers(PowerFlowState.flowHistory, PowerFlowState.loadHistory, PowerFlowConfig.NODE_COLORS);
// Real-time meter data updates
setInterval(async () => {
if (meterDataUpdateInProgress) return;
try {
meterDataUpdateInProgress = true;
meterData = await energyApi.getMeterValues();
PowerFlowHelpers.updateEnergyFlow(meterData, channelData);
} catch (error) {
console.error('Error updating meter data:', error);
} finally {
meterDataUpdateInProgress = false;
}
}, 1000);
});
</script>
</html>
f4329a85eThis file is pinned to the selected release. Download the original to open it in your design tool.