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 Power Flow Helpers
* Energy flow diagram logic and animations
*/
// ============================================================================
// POWER FLOW CONFIGURATION
// ============================================================================
const PowerFlowConfig = {
MAX_HISTORY: 60,
SPARKLINE_ALPHA: 0.7,
SPARKLINE_CANVAS_WIDTH: 120,
SPARKLINE_CANVAS_HEIGHT: 40,
FLOW_SPEED_THRESHOLDS: [
{ watts: 10, duration: '2s' },
{ watts: 100, duration: '1.5s' },
{ watts: 500, duration: '1s' },
{ watts: 1000, duration: '0.7s' },
{ watts: 2000, duration: '0.5s' },
{ watts: 5000, duration: '0.4s' },
{ watts: Infinity, duration: '0.3s' }
],
LOAD_COLOR_THRESHOLDS: [
{ ratio: 0.3, color: '#4CAF50' },
{ ratio: 0.6, color: '#FF9800' },
{ ratio: Infinity, color: '#f44336' }
],
ACTIVE_LINE_THRESHOLD: 10,
OTHER_HYSTERESIS_THRESHOLD: 10,
OTHER_HYSTERESIS_COUNT: 3,
OTHER_LOAD_COLOR: '#888',
TOOLTIP_HEIGHT: 50,
TOOLTIP_X_OFFSET: 60,
NODE_COLORS: {
solar: '#FF9800',
grid: '#2196F3',
battery: '#9C27B0',
home: '#4CAF50'
}
};
// ============================================================================
// POWER FLOW STATE
// ============================================================================
const PowerFlowState = {
flowHistory: {
solar: null,
grid: null,
battery: null,
home: null
},
filteredPowers: { solar: null, grid: null, battery: null, home: null },
loadHistory: {},
loadFilteredPowers: {},
otherLoadCounter: 0,
otherLoadShown: false,
previousLoadKeys: null,
init() {
this.flowHistory = {
solar: new CircularBuffer(PowerFlowConfig.MAX_HISTORY),
grid: new CircularBuffer(PowerFlowConfig.MAX_HISTORY),
battery: new CircularBuffer(PowerFlowConfig.MAX_HISTORY),
home: new CircularBuffer(PowerFlowConfig.MAX_HISTORY)
};
}
};
// ============================================================================
// POWER FLOW HELPERS
// ============================================================================
const PowerFlowHelpers = {
/**
* Format power value with appropriate unit
*/
formatPower(watts) {
return watts.toFixed(0) + ' W';
},
/**
* Calculate animation speed based on power
*/
getFlowSpeed(watts) {
const absWatts = Math.abs(watts);
for (const threshold of PowerFlowConfig.FLOW_SPEED_THRESHOLDS) {
if (absWatts <= threshold.watts) {
return threshold.duration;
}
}
return PowerFlowConfig.FLOW_SPEED_THRESHOLDS[PowerFlowConfig.FLOW_SPEED_THRESHOLDS.length - 1].duration;
},
/**
* Get color intensity based on power
*/
getLoadColor(watts, maxWatts) {
const absWatts = Math.abs(watts);
const ratio = Math.min(absWatts / Math.max(maxWatts, 1000), 1);
for (const threshold of PowerFlowConfig.LOAD_COLOR_THRESHOLDS) {
if (ratio < threshold.ratio) {
return threshold.color;
}
}
return PowerFlowConfig.LOAD_COLOR_THRESHOLDS[PowerFlowConfig.LOAD_COLOR_THRESHOLDS.length - 1].color;
},
/**
* Add history point with exponential filtering
*/
addToFlowHistory(nodeType, value) {
if (PowerFlowState.filteredPowers[nodeType] === null) {
PowerFlowState.filteredPowers[nodeType] = value;
} else {
PowerFlowState.filteredPowers[nodeType] = PowerFlowConfig.SPARKLINE_ALPHA * value +
(1 - PowerFlowConfig.SPARKLINE_ALPHA) * PowerFlowState.filteredPowers[nodeType];
}
PowerFlowState.flowHistory[nodeType].push(PowerFlowState.filteredPowers[nodeType]);
},
/**
* Add load history point with exponential filtering
*/
addToLoadHistory(loadKey, value) {
if (!PowerFlowState.loadHistory[loadKey]) {
PowerFlowState.loadHistory[loadKey] = new CircularBuffer(PowerFlowConfig.MAX_HISTORY);
PowerFlowState.loadFilteredPowers[loadKey] = null;
}
if (PowerFlowState.loadFilteredPowers[loadKey] === null) {
PowerFlowState.loadFilteredPowers[loadKey] = value;
} else {
PowerFlowState.loadFilteredPowers[loadKey] = PowerFlowConfig.SPARKLINE_ALPHA * value +
(1 - PowerFlowConfig.SPARKLINE_ALPHA) * PowerFlowState.loadFilteredPowers[loadKey];
}
PowerFlowState.loadHistory[loadKey].push(PowerFlowState.loadFilteredPowers[loadKey]);
},
/**
* Setup hover events for main energy nodes
*/
setupSparklineHovers(flowHistory, loadHistory, nodeColors) {
const nodes = [
{ id: 'pf-solar', type: 'solar' },
{ id: 'pf-grid', type: 'grid' },
{ id: 'pf-battery', type: 'battery' },
{ id: 'pf-home', type: 'home' }
];
nodes.forEach(({ id, type }) => {
const el = document.getElementById(id);
if (!el) return;
const iconEl = el.querySelector('.pf-icon');
if (!iconEl) return;
iconEl.style.cursor = 'pointer';
iconEl.addEventListener('mouseenter', () => ChartHelpers.showSparkline(type, iconEl, false, flowHistory, loadHistory, nodeColors));
iconEl.addEventListener('mouseleave', () => ChartHelpers.hideSparkline());
});
},
/**
* Setup hover events for load nodes
*/
setupLoadSparklineHovers(flowHistory, loadHistory, nodeColors) {
const loadNodes = document.querySelectorAll('.pf-load-item');
loadNodes.forEach((node) => {
const valueEl = node.querySelector('.pf-load-value');
if (!valueEl) return;
const loadKey = valueEl.id.replace('load-value-', '');
node.style.cursor = 'pointer';
node.addEventListener('mouseenter', () => ChartHelpers.showSparkline(loadKey, node, true, flowHistory, loadHistory, nodeColors));
node.addEventListener('mouseleave', () => ChartHelpers.hideSparkline());
});
},
/**
* Update energy flow diagram with real-time data (Simple Layout)
*/
updateEnergyFlow(meterData, channelData) {
const flowSection = document.getElementById('energy-flow-section');
// Nothing to draw without data: hide the whole section instead of showing an empty box
if (!meterData || !Array.isArray(meterData) || meterData.length === 0 || !channelData || !Array.isArray(channelData)) {
if (flowSection) flowSection.style.display = 'none';
return;
}
const gridChannels = ChannelCache.grid;
const productionChannels = ChannelCache.production;
const batteryChannels = ChannelCache.battery;
const inverterChannels = ChannelCache.inverter;
const hasPV = productionChannels.length > 0;
const hasInverter = inverterChannels.length > 0;
const hasBattery = batteryChannels.length > 0;
const hasGrid = gridChannels.length > 0;
const hasStorage = hasInverter || hasBattery;
const hasAnySource = hasGrid || hasPV || hasStorage;
// Monitored loads = any channel that is not a known source
const sourceIndices = new Set([
...gridChannels.map(ch => ch.index),
...productionChannels.map(ch => ch.index),
...batteryChannels.map(ch => ch.index),
...inverterChannels.map(ch => ch.index)
]);
let loadSum = 0;
let hasLoads = false;
meterData.forEach(m => {
if (!sourceIndices.has(m.index)) {
loadSum += m.data.activePower;
hasLoads = true;
}
});
// The house is drawn whenever there is at least one source or one load.
const hasHome = hasAnySource || hasLoads;
if (flowSection) {
flowSection.style.display = hasHome ? '' : 'none';
flowSection.classList.add('visible');
}
if (!hasHome) return;
// Show/hide nodes - only ever draw what actually exists (no ghost sources)
const pfSolar = document.getElementById('pf-solar');
const pfBattery = document.getElementById('pf-battery');
const pfGrid = document.getElementById('pf-grid');
const pfHome = document.getElementById('pf-home');
const pfCenter = flowSection ? flowSection.querySelector('.pf-center') : null;
// Solar node: only show pure PV channels
if (pfSolar) {
pfSolar.style.display = hasPV ? 'flex' : 'none';
const solarIcon = pfSolar.querySelector('.pf-icon');
if (solarIcon) solarIcon.textContent = '☀️';
}
// Battery/Inverter node: show inverter if available, else battery if available
// Inverter replaces battery in the UI since it controls battery charging/discharging
if (pfBattery) {
pfBattery.style.display = hasStorage ? 'flex' : 'none';
// Update icon and value ID based on what we're showing
const batteryIcon = pfBattery.querySelector('.pf-icon');
const batteryValue = pfBattery.querySelector('.pf-value');
if (hasInverter && batteryIcon) {
batteryIcon.textContent = '⚙️';
if (batteryValue) batteryValue.id = 'inverter-power';
} else if (hasBattery && batteryIcon) {
batteryIcon.textContent = '🔋';
if (batteryValue) batteryValue.id = 'battery-power';
}
}
// Grid node: shown only with a grid channel. When absent but other sources exist we
// keep its (invisible) slot so the junction stays centred under the solar/battery
// connectors; with loads only we collapse it so the house centres on its own.
if (pfGrid) {
if (hasGrid) {
pfGrid.style.display = 'flex';
pfGrid.style.visibility = '';
} else if (hasAnySource) {
pfGrid.style.display = 'flex';
pfGrid.style.visibility = 'hidden';
} else {
pfGrid.style.display = 'none';
pfGrid.style.visibility = '';
}
}
// Home node: always shown here (we have at least one source or load)
if (pfHome) pfHome.style.display = 'flex';
// Center junction: only meaningful when at least one source feeds the home
if (pfCenter) pfCenter.style.display = hasAnySource ? 'flex' : 'none';
// Calculate power values
let gridPower = 0;
gridChannels.forEach(ch => {
const meter = meterData.find(m => m.index === ch.index);
if (meter) gridPower += meter.data.activePower;
});
// Pure PV production (absolute value, never negative)
let solarPower = 0;
productionChannels.forEach(ch => {
const meter = meterData.find(m => m.index === ch.index);
if (meter) solarPower += Math.abs(meter.data.activePower);
});
// Inverter power (can be positive=discharging or negative=charging)
let inverterPower = 0;
inverterChannels.forEach(ch => {
const meter = meterData.find(m => m.index === ch.index);
if (meter) inverterPower += meter.data.activePower;
});
// Battery power (separate from inverter, if it exists)
let batteryPower = 0;
batteryChannels.forEach(ch => {
const meter = meterData.find(m => m.index === ch.index);
if (meter) batteryPower += meter.data.activePower;
});
// Storage net power: inverter takes priority (it controls the battery)
const storagePower = hasInverter ? inverterPower : batteryPower;
// Home power = sum of available sources (all incoming energy goes to the house).
// With no source monitored we cannot derive it from supply, so fall back to the
// sum of monitored loads - all we know in that case.
const homePower = hasAnySource ? (gridPower + solarPower + storagePower) : loadSum;
// Record history
this.addToFlowHistory('solar', solarPower);
this.addToFlowHistory('grid', gridPower);
this.addToFlowHistory('battery', storagePower);
this.addToFlowHistory('home', Math.max(0, homePower));
// Update display values
const gridPowerEl = document.getElementById('grid-power');
const homePowerEl = document.getElementById('home-power');
const solarPowerEl = document.getElementById('solar-power');
const storageValueId = hasInverter ? 'inverter-power' : 'battery-power';
const storagePowerEl = document.getElementById(storageValueId);
if (hasGrid && gridPowerEl) gridPowerEl.textContent = this.formatPower(gridPower);
if (homePowerEl) homePowerEl.textContent = this.formatPower(Math.max(0, homePower));
if (hasPV && solarPowerEl) solarPowerEl.textContent = this.formatPower(solarPower);
if (hasStorage && storagePowerEl) storagePowerEl.textContent = this.formatPower(storagePower);
// Update connectors - a connector is hidden (display:none) when its node does not
// exist, so no orphan stub is left pointing at nothing. The home connector follows
// the sources: with loads only there is no junction flow to animate.
this.updateConnector('pf-solar', solarPower, hasPV);
this.updateConnector('pf-grid', gridPower, hasGrid);
// Home flow follows the displayed (clamped) value: when net consumption is <= 0
// (e.g. net export, or storage charging) nothing flows into the house, so no pulse.
this.updateConnector('pf-home', Math.max(0, homePower), hasAnySource);
this.updateConnector('pf-battery', storagePower, hasStorage);
// Update load breakdown
this.updateLoadBreakdown(hasGrid, hasPV, hasStorage, gridPower, solarPower, storagePower, homePower, meterData, channelData);
},
/**
* Update connector animation state
*/
updateConnector(nodeId, power, isVisible) {
const node = document.getElementById(nodeId);
if (!node) return;
const connector = node.querySelector('.pf-connector');
if (!connector) return;
// The base connector is a static gray bar; when the node is absent we must hide the
// bar itself, not just stop the animation, or it dangles pointing at nothing.
if (!isVisible) {
connector.style.display = 'none';
connector.classList.remove('active', 'reversed');
return;
}
connector.style.display = '';
const isActive = Math.abs(power) > PowerFlowConfig.ACTIVE_LINE_THRESHOLD;
connector.classList.toggle('active', isActive);
// Grid: positive=import (normal dir), negative=export (reversed)
// Battery (pf-connector-top): base dir is center→battery (charge).
// Discharge (positive) needs reversed.
// Solar and Home: single direction, no reversal needed.
if (nodeId === 'pf-grid') {
connector.classList.toggle('reversed', isActive && power < 0);
} else if (nodeId === 'pf-battery') {
connector.classList.toggle('reversed', isActive && power > 0);
} else {
connector.classList.remove('reversed');
}
},
/**
* Update load breakdown section (simple list)
*/
updateLoadBreakdown(hasGrid, hasPV, hasStorage, gridPower, solarPower, storagePower, homePower, meterData, channelData) {
const gridIndices = ChannelCache.grid.map(ch => ch.index);
const productionIndices = ChannelCache.production.map(ch => ch.index);
const batteryIndices = ChannelCache.battery.map(ch => ch.index);
const inverterIndices = ChannelCache.inverter.map(ch => ch.index);
const specialIndices = new Set([...gridIndices, ...productionIndices, ...batteryIndices, ...inverterIndices]);
const loadChannels = meterData.filter(ch => !specialIndices.has(ch.index));
// Count shared group labels
const groupLabelCounts = {};
loadChannels.forEach(ch => {
const groupLabel = channelData[ch.index]?.groupLabel;
if (groupLabel) {
groupLabelCounts[groupLabel] = (groupLabelCounts[groupLabel] || 0) + 1;
}
});
// Aggregate loads
const aggregatedLoads = [];
const processedGroups = new Set();
let trackedLoadPower = 0;
loadChannels.forEach(ch => {
const groupLabel = channelData[ch.index]?.groupLabel;
const isSharedGroup = groupLabel && groupLabelCounts[groupLabel] > 1;
if (isSharedGroup) {
if (!processedGroups.has(groupLabel)) {
let groupPower = 0;
const groupIndices = [];
loadChannels.forEach(c => {
if (channelData[c.index]?.groupLabel === groupLabel) {
groupPower += c.data.activePower;
groupIndices.push(c.index);
}
});
aggregatedLoads.push({
key: 'group-' + groupIndices.join('-'),
label: groupLabel,
icon: channelData[ch.index]?.icon || '⚡',
power: groupPower
});
trackedLoadPower += groupPower;
processedGroups.add(groupLabel);
}
} else {
aggregatedLoads.push({
key: 'ch-' + ch.index,
label: ch.label,
icon: channelData[ch.index]?.icon || '⚡',
power: ch.data.activePower
});
trackedLoadPower += ch.data.activePower;
}
});
// Calculate "Other"
const otherPower = Math.max(0, homePower - trackedLoadPower);
const hasLoads = aggregatedLoads.length > 0;
if (hasGrid && hasLoads) {
if (otherPower > PowerFlowConfig.OTHER_HYSTERESIS_THRESHOLD) {
PowerFlowState.otherLoadCounter++;
if (PowerFlowState.otherLoadCounter >= PowerFlowConfig.OTHER_HYSTERESIS_COUNT && !PowerFlowState.otherLoadShown) {
PowerFlowState.otherLoadShown = true;
}
} else {
PowerFlowState.otherLoadCounter = 0;
}
if (PowerFlowState.otherLoadShown) {
aggregatedLoads.push({
key: 'other',
label: 'Other',
icon: '❓',
power: otherPower,
isOther: true
});
}
}
// Get containers (new simple structure)
const pfLoads = document.getElementById('pf-loads');
const loadsList = document.getElementById('pf-loads-list');
if (!hasLoads) {
if (pfLoads) pfLoads.style.display = 'none';
PowerFlowState.previousLoadKeys = null;
return;
}
if (pfLoads) pfLoads.style.display = 'flex';
const currentLoadKeys = aggregatedLoads.map(l => l.key).join(',');
const shouldRebuild = currentLoadKeys !== PowerFlowState.previousLoadKeys;
const maxPower = Math.max(...aggregatedLoads.map(l => Math.abs(l.power)), 1);
if (shouldRebuild) {
PowerFlowState.previousLoadKeys = currentLoadKeys;
let loadsHtml = '';
aggregatedLoads.forEach((load) => {
const color = load.isOther ? PowerFlowConfig.OTHER_LOAD_COLOR : this.getLoadColor(load.power, maxPower);
loadsHtml += '<div class="pf-load-item' + (load.isOther ? ' other' : '') + '" style="border-left-color: ' + color + ';">';
loadsHtml += '<div class="pf-load-name">' + load.label + '</div>';
loadsHtml += '<div class="pf-load-value" id="load-value-' + load.key + '">' + this.formatPower(load.power) + '</div>';
loadsHtml += '</div>';
this.addToLoadHistory(load.key, load.power);
});
if (loadsList) loadsList.innerHTML = loadsHtml;
this.setupLoadSparklineHovers(PowerFlowState.flowHistory, PowerFlowState.loadHistory, PowerFlowConfig.NODE_COLORS);
} else {
aggregatedLoads.forEach((load) => {
const valueEl = document.getElementById('load-value-' + load.key);
if (valueEl) {
valueEl.textContent = this.formatPower(load.power);
}
this.addToLoadHistory(load.key, load.power);
});
}
}
};
// Export to global scope
window.PowerFlowConfig = PowerFlowConfig;
window.PowerFlowState = PowerFlowState;
window.PowerFlowHelpers = PowerFlowHelpers;
f4329a85eThis file is pinned to the selected release. Download the original to open it in your design tool.