no message

This commit is contained in:
mh
2025-12-18 08:31:04 +01:00
parent f4e87772e1
commit feb7301fc1
2 changed files with 90 additions and 229 deletions
+88 -166
View File
@@ -1,4 +1,6 @@
<div id="wrap" style="padding:12px;font-family:system-ui,-apple-system,Segoe UI,Roboto,sans-serif;">
<div id="wrap"
style="padding:12px;font-family:system-ui,-apple-system,Segoe UI,Roboto,sans-serif;">
<!-- Controls --> <!-- Controls -->
<div style="display:flex;gap:10px;flex-wrap:wrap;align-items:center;"> <div style="display:flex;gap:10px;flex-wrap:wrap;align-items:center;">
<label style="display:flex;gap:6px;align-items:center;"> <label style="display:flex;gap:6px;align-items:center;">
@@ -10,124 +12,65 @@
<option value="total">Gesamt</option> <option value="total">Gesamt</option>
</select> </select>
</label> </label>
<label style="display:flex;gap:6px;align-items:center;"> <label style="display:flex;gap:6px;align-items:center;">
<span>Datum</span> <span>Datum</span>
<input id="date" type="date" /> <input id="date" type="date" />
</label> </label>
<button id="prev" type="button"></button> <button id="prev" type="button"></button>
<button id="today" type="button">Letzter Zeitpunkt</button> <button id="today" type="button">Letzter Zeitpunkt</button>
<button id="next" type="button"></button> <button id="next" type="button"></button>
</div> </div>
<div id="period" style="margin-top:10px;font-size:12px;opacity:0.75;"></div> <div id="period" style="margin-top:10px;font-size:12px;opacity:0.75;"></div>
<div id="hint" style="margin-top:6px;font-size:12px;opacity:0.8;"></div> <div id="hint" style="margin-top:6px;font-size:12px;opacity:0.8;"></div>
<div id="grid" <div id="grid"
style="margin-top:14px; style="margin-top:14px;display:grid;grid-template-columns:repeat(2,minmax(0,1fr));
display:grid; gap:14px;max-width:880px;">
grid-template-columns:repeat(2,minmax(0,1fr));
gap:14px;
width:100%;
max-width:none;">
</div> </div>
<!-- Debug/Status --> <!-- Debug/Status -->
<div id="dbg" style="margin-top:10px;font-size:12px;opacity:0.75;"></div> <div id="dbg" style="margin-top:10px;font-size:12px;opacity:0.75;"></div>
<!-- Fehler --> <!-- Fehler -->
<div id="err" style="margin-top:6px;font-size:12px;opacity:0.9;color:#ffb4b4;"></div> <div id="err" style="margin-top:6px;font-size:12px;opacity:0.9;color:#ffb4b4;"></div>
</div> </div>
<style> <style>
/* Responsive: bei schmalen Screens 1 Spalte */ #wrap {
@media (max-width: 720px) { position: relative;
#grid { grid-template-columns: 1fr !important; } overflow: hidden;
} }
#wrap::before {
/* Statischer "Fluid" Hintergrund in Donut-Farben */ content: "";
#wrap{ position: absolute;
position:relative; inset: -40%;
overflow:hidden;
min-height:100vh;
/* Grundton, damit es nicht "lochig" wirkt */
background: rgba(18, 18, 22, 1);
}
/* Nur EIN Layer, statisch */
#wrap::before{
content:"";
position:absolute;
inset:-35%;
background: background:
radial-gradient(520px 420px at 18% 18%, rgba(99,179,255,0.42), transparent 60%), radial-gradient(circle at 20% 20%, rgba(99,179,255,0.18), transparent 45%),
radial-gradient(560px 460px at 82% 28%, rgba(168,85,247,0.38), transparent 62%), radial-gradient(circle at 80% 30%, rgba(168,85,247,0.16), transparent 50%),
radial-gradient(620px 520px at 55% 85%, rgba(99,179,255,0.26), transparent 64%), radial-gradient(circle at 50% 80%, rgba(255,255,255,0.06), transparent 55%);
radial-gradient(700px 560px at 35% 70%, rgba(168,85,247,0.22), transparent 66%), filter: blur(18px);
radial-gradient(900px 700px at 50% 50%, rgba(255,255,255,0.06), transparent 70%); animation: auroraMove 10s ease-in-out infinite alternate;
filter: blur(18px); /* weniger blur = mehr sichtbar */ pointer-events: none;
opacity: 1; z-index: 0;
pointer-events:none; }
z-index:0; #wrap > * {
} position: relative;
z-index: 1;
/* Content über dem Background */ }
#wrap > *{ @keyframes auroraMove {
position:relative; from { transform: translate3d(-2%, -2%, 0) scale(1.02); }
z-index:1; to { transform: translate3d( 2%, 2%, 0) scale(1.06); }
} }
#period {
font-size: 15px; /* größer */
font-weight: 600; /* dicker */
letter-spacing: 0.2px;
opacity: 0.95;
}
/* Werte-Zeile (Produktion / Verbrauch / …) */
#hint {
margin-top: 6px;
font-size: 15px; /* größer */
font-weight: 700; /* noch etwas dicker */
letter-spacing: 0.3px;
opacity: 1;
}
#hint .kv {
display: inline-block;
margin-right: 14px;
white-space: nowrap;
}
#hint .kv b {
font-weight: 800;
}
/* App/kleine Breite: untereinander */
@media (max-width: 720px) {
#hint .kv {
display: block;
margin: 4px 0;
}
}
</style> </style>
<!-- 1) Puffer-Handler: fängt Symcon-Messages ab, selbst wenn UI noch nicht ready ist --> <!-- 1) Puffer-Handler: fängt Symcon-Messages ab, selbst wenn UI noch nicht ready ist -->
<script> <script>
window.__EnergyPieQueue = window.__EnergyPieQueue || []; window.__EnergyPieQueue = window.__EnergyPieQueue || [];
window.__EnergyPieReady = false; window.__EnergyPieReady = false;
// Symcon ruft handleMessage evtl. sehr früh auf -> wir puffern.
window.handleMessage = function (data) { window.handleMessage = function (data) {
window.__EnergyPieQueue.push(data); window.__EnergyPieQueue.push(data);
if (window.__EnergyPieReady && typeof window.__EnergyPieConsume === "function") { if (window.__EnergyPieReady && typeof window.__EnergyPieConsume === "function") {
const q = window.__EnergyPieQueue.splice(0); const q = window.__EnergyPieQueue.splice(0);
q.forEach(d => window.__EnergyPieConsume(d)); q.forEach(d => window.__EnergyPieConsume(d));
} }
}; };
</script> </script>
<script> <script>
(function () { (function () {
const elRange = document.getElementById('range'); const elRange = document.getElementById('range');
@@ -140,10 +83,8 @@
const elGrid = document.getElementById('grid'); const elGrid = document.getElementById('grid');
const elDbg = document.getElementById('dbg'); const elDbg = document.getElementById('dbg');
const elErr = document.getElementById('err'); const elErr = document.getElementById('err');
// Start nicht "grau/leer"
// Start nicht "leer"
elGrid.innerHTML = '<div style="opacity:.75;padding:12px;">Lade Daten…</div>'; elGrid.innerHTML = '<div style="opacity:.75;padding:12px;">Lade Daten…</div>';
// --- helpers --- // --- helpers ---
function toNum(x) { function toNum(x) {
const n = Number(x); const n = Number(x);
@@ -171,22 +112,19 @@
const mi = String(d.getMinutes()).padStart(2,'0'); const mi = String(d.getMinutes()).padStart(2,'0');
return `${dd}.${mm}.${yyyy} ${hh}:${mi}`; return `${dd}.${mm}.${yyyy} ${hh}:${mi}`;
} }
function showErr(e) { function showErr(e) {
const msg = (e && e.message) ? e.message : String(e); const msg = (e && e.message) ? e.message : String(e);
elErr.textContent = 'JS-Fehler: ' + msg; elErr.textContent = 'JS-Fehler: ' + msg;
} }
// Global error trap
window.addEventListener('error', (ev) => showErr(ev.error || ev.message)); window.addEventListener('error', (ev) => showErr(ev.error || ev.message));
window.addEventListener('unhandledrejection', (ev) => showErr(ev.reason)); window.addEventListener('unhandledrejection', (ev) => showErr(ev.reason));
// --- requestAction robust finden (Popup hat das oft am parent) ---
// --- requestAction robust finden ---
function getRequestAction() { function getRequestAction() {
if (typeof window.requestAction === 'function') return window.requestAction; if (typeof window.requestAction === 'function') return window.requestAction;
if (typeof window.parent?.requestAction === 'function') return window.parent.requestAction; if (typeof window.parent?.requestAction === 'function') return window.parent.requestAction;
return null; return null;
} }
function safeRequestAction(ident, value) { function safeRequestAction(ident, value) {
const tryCall = () => { const tryCall = () => {
const ra = getRequestAction(); const ra = getRequestAction();
@@ -196,88 +134,86 @@
} }
return false; return false;
}; };
if (tryCall()) return; if (tryCall()) return;
// Popup/Fullscreen: manchmal kommt requestAction deutlich später -> länger retry
let tries = 0; let tries = 0;
const timer = setInterval(() => { const timer = setInterval(() => {
tries++; tries++;
if (tryCall() || tries >= 150) clearInterval(timer); if (tryCall() || tries >= 150) clearInterval(timer); // ~18s
}, 120); }, 120);
} }
function safeRefreshSoon() { function safeRefreshSoon() {
setTimeout(() => safeRequestAction('Refresh', 1), 150); setTimeout(() => safeRequestAction('Refresh', 1), 150);
} }
// --- donut card --- // --- donut card ---
function donutCard({ title, percent, subtitle, color }) { function donutCard({ title, percent, subtitle, color }) {
const share = clamp01(percent / 100); const share = clamp01(percent / 100);
const r = 56; const r = 56;
const c = 2 * Math.PI * r; const c = 2 * Math.PI * r;
let dash = share * c; const dash = share * c;
// Schutz gegen Rundungs-Artefakte bei 99.9..100% const gap = c - dash;
if (dash > c - 0.01) dash = c; return `
<div style="border:1px solid rgba(255,255,255,0.12);
return ` border-radius:16px;
<div style="padding:18px 10px; padding:14px;
width:100%; min-height:210px;
display:flex; display:flex;
flex-direction:column; flex-direction:column;
align-items:center; align-items:center;
justify-content:center; justify-content:center;
gap:12px;"> gap:10px;">
<!-- Titel oben -->
<div style="font-size:15px;font-weight:800;opacity:.95;"> <div style="font-size:14px;font-weight:700;opacity:.9;">
${escapeHtml(title)} ${escapeHtml(title)}
</div> </div>
<!-- Donut -->
<div style="position:relative;width:180px;height:180px;"> <div style="position:relative;width:170px;height:170px;">
<svg width="180" height="180" viewBox="0 0 180 180"> <svg width="170" height="170" viewBox="0 0 170 170">
<circle cx="85" cy="85" r="${r}"
<!-- Anteilsegment --> fill="none"
<circle cx="90" cy="90" r="${r}" stroke="rgba(255,255,255,0.10)"
fill="none" stroke-width="18" />
stroke="${color}" <circle cx="85" cy="85" r="${r}"
stroke-width="18" fill="none"
stroke-linecap="butt" stroke="${color}"
stroke-dasharray="${dash} ${c}" stroke-width="18"
transform="rotate(-90 90 90)" stroke-linecap="butt"
style="filter: drop-shadow(0 0 12px ${color});" /> stroke-dasharray="${dash} ${gap}"
</svg> transform="rotate(-90 85 85)" />
</svg>
<div style="position:absolute;inset:0;display:flex; <!-- Prozent im Kreis -->
align-items:center;justify-content:center; <div style="position:absolute;
font-weight:900;font-size:26px;"> inset:0;
${escapeHtml(percent.toFixed(1))}% display:flex;
align-items:center;
justify-content:center;
font-weight:800;
font-size:22px;">
${escapeHtml(percent.toFixed(1))}%
</div>
</div>
<!-- Untertitel unten -->
<div style="font-size:12px;opacity:.65;text-align:center;">
${escapeHtml(subtitle)}
</div> </div>
</div> </div>
`;
<div style="font-size:13px;opacity:.75;text-align:center;">
${escapeHtml(subtitle)}
</div>
</div>
`;
} }
function render(data) { function render(data) {
const values = data?.values || {}; const values = data?.values || {};
const prod = toNum(values?.Produktion); const prod = toNum(values?.Produktion);
const cons = toNum(values?.Hausverbrauch); const cons = toNum(values?.Hausverbrauch);
const grid = toNum(values?.Netz); const grid = toNum(values?.Netz);
const eigen = cons - grid; const eigen = cons - grid;
const eigenClamped = eigen < 0 ? 0 : eigen; const eigenClamped = eigen < 0 ? 0 : eigen;
const evq = (prod > 0) ? (eigenClamped / prod * 100) : 0; const evq = (prod > 0) ? (eigenClamped / prod * 100) : 0;
const autark = (cons > 0) ? (eigenClamped / cons * 100) : 0; const autark = (cons > 0) ? (eigenClamped / cons * 100) : 0;
// Controls sync
if (data?.range) elRange.value = data.range; if (data?.range) elRange.value = data.range;
if (data?.date) elDate.value = data.date; if (data?.date) elDate.value = data.date;
const isTotal = (data?.range === 'total'); const isTotal = (data?.range === 'total');
elDate.disabled = isTotal; elDate.disabled = isTotal;
// Zeitraum-Text
if (data?.tStart && data?.tEnd) { if (data?.tStart && data?.tEnd) {
const s = new Date(data.tStart * 1000); const s = new Date(data.tStart * 1000);
const e = new Date(data.tEnd * 1000); const e = new Date(data.tEnd * 1000);
@@ -287,18 +223,13 @@ return `
} else { } else {
elPeriod.textContent = ''; elPeriod.textContent = '';
} }
// Hint
if (data?.hasData === false) { if (data?.hasData === false) {
elHint.textContent = 'Keine Logdaten für den gewählten Zeitraum.'; elHint.textContent = 'Keine Logdaten für den gewählten Zeitraum.';
} else { } else {
elHint.innerHTML = ` elHint.textContent =
<span class="kv"><b>Produktion:</b> ${escapeHtml(prod.toFixed(2))} kWh</span> `Produktion: ${prod.toFixed(2)} kWh · Verbrauch: ${cons.toFixed(2)} kWh · Netzbezug: ${grid.toFixed(2)} kWh · Eigenverbrauch: ${eigenClamped.toFixed(2)} kWh`;
<span class="kv"><b>Verbrauch:</b> ${escapeHtml(cons.toFixed(2))} kWh</span>
<span class="kv"><b>Netzbezug:</b> ${escapeHtml(grid.toFixed(2))} kWh</span>
<span class="kv"><b>Eigenverbrauch:</b> ${escapeHtml(eigenClamped.toFixed(2))} kWh</span>
`;
} }
elGrid.innerHTML = [ elGrid.innerHTML = [
donutCard({ donutCard({
title: 'Eigenverbrauchsquote', title: 'Eigenverbrauchsquote',
@@ -313,10 +244,7 @@ return `
color: '#A855F7' color: '#A855F7'
}) })
].join(''); ].join('');
} }
// --- cache --- // --- cache ---
function saveLast(data) { function saveLast(data) {
try { sessionStorage.setItem('EnergyPie_last', JSON.stringify(data)); } catch(e) {} try { sessionStorage.setItem('EnergyPie_last', JSON.stringify(data)); } catch(e) {}
@@ -329,7 +257,7 @@ return `
return null; return null;
} }
} }
// 2) Consumer für gepufferte Symcon-Messages
window.__EnergyPieConsume = function (data) { window.__EnergyPieConsume = function (data) {
if (typeof data === 'string') { if (typeof data === 'string') {
try { data = JSON.parse(data); } catch(e) {} try { data = JSON.parse(data); } catch(e) {}
@@ -338,10 +266,8 @@ return `
saveLast(data); saveLast(data);
render(data); render(data);
}; };
// UI events // UI events
elRange.addEventListener('change', () => safeRequestAction('SetRange', elRange.value)); elRange.addEventListener('change', () => safeRequestAction('SetRange', elRange.value));
let dateTimer = null; let dateTimer = null;
function pushDateNow() { function pushDateNow() {
if (dateTimer) clearTimeout(dateTimer); if (dateTimer) clearTimeout(dateTimer);
@@ -349,28 +275,24 @@ return `
} }
elDate.addEventListener('input', pushDateNow); elDate.addEventListener('input', pushDateNow);
elDate.addEventListener('change', pushDateNow); elDate.addEventListener('change', pushDateNow);
elPrev.addEventListener('click', () => safeRequestAction('Prev', 1)); elPrev.addEventListener('click', () => safeRequestAction('Prev', 1));
elToday.addEventListener('click', () => safeRequestAction('Today', 1)); elToday.addEventListener('click', () => safeRequestAction('Today', 1));
elNext.addEventListener('click', () => safeRequestAction('Next', 1)); elNext.addEventListener('click', () => safeRequestAction('Next', 1));
// On load: cached sofort rendern
const cached = loadLast(); const cached = loadLast();
if (cached) render(cached); if (cached) render(cached);
// UI ready -> Queue flushen
window.__EnergyPieReady = true; window.__EnergyPieReady = true;
if (window.__EnergyPieQueue && window.__EnergyPieQueue.length) { if (window.__EnergyPieQueue && window.__EnergyPieQueue.length) {
const q = window.__EnergyPieQueue.splice(0); const q = window.__EnergyPieQueue.splice(0);
q.forEach(d => window.__EnergyPieConsume(d)); q.forEach(d => window.__EnergyPieConsume(d));
} }
// Refresh on start + on fullscreen/resize/visibility changes
safeRefreshSoon(); safeRefreshSoon();
document.addEventListener('visibilitychange', () => { document.addEventListener('visibilitychange', () => {
if (!document.hidden) safeRefreshSoon(); if (!document.hidden) safeRefreshSoon();
}); });
window.addEventListener('resize', () => safeRefreshSoon()); window.addEventListener('resize', () => safeRefreshSoon());
window.addEventListener('pageshow', () => safeRefreshSoon()); window.addEventListener('pageshow', () => safeRefreshSoon());
})(); })();
</script> </script>
+2 -63
View File
@@ -1,57 +1,44 @@
<?php <?php
declare(strict_types=1); declare(strict_types=1);
class Energy_Pie extends IPSModule class Energy_Pie extends IPSModule
{ {
private const ATTR_RANGE = 'Range'; private const ATTR_RANGE = 'Range';
private const ATTR_DATE = 'Date'; private const ATTR_DATE = 'Date';
public function Create(): void public function Create(): void
{ {
parent::Create(); parent::Create();
// Source variables (logged counters, kWh) // Source variables (logged counters, kWh)
$this->RegisterPropertyInteger('VarProduction', 0); $this->RegisterPropertyInteger('VarProduction', 0);
$this->RegisterPropertyInteger('VarConsumption', 0); $this->RegisterPropertyInteger('VarConsumption', 0);
$this->RegisterPropertyInteger('VarFeedIn', 0); $this->RegisterPropertyInteger('VarFeedIn', 0);
$this->RegisterPropertyInteger('VarGrid', 0); $this->RegisterPropertyInteger('VarGrid', 0);
// Persisted UI state // Persisted UI state
$this->RegisterAttributeString(self::ATTR_RANGE, 'day'); $this->RegisterAttributeString(self::ATTR_RANGE, 'day');
$this->RegisterAttributeString(self::ATTR_DATE, date('Y-m-d')); $this->RegisterAttributeString(self::ATTR_DATE, date('Y-m-d'));
// Enable individual visualization (HTML-SDK) // Enable individual visualization (HTML-SDK)
$this->SetVisualizationType(1); $this->SetVisualizationType(1);
// IMPORTANT: Timer calls global helper below (must exist!) // IMPORTANT: Timer calls global helper below (must exist!)
$this->RegisterTimer('AutoPush', 0, 'IPS_RequestAction($_IPS["TARGET"], "Refresh", 1);'); $this->RegisterTimer('AutoPush', 0, 'IPS_RequestAction($_IPS["TARGET"], "Refresh", 1);');
} }
public function ApplyChanges(): void public function ApplyChanges(): void
{ {
parent::ApplyChanges(); parent::ApplyChanges();
// ensure range valid // ensure range valid
$range = $this->ReadAttributeString(self::ATTR_RANGE); $range = $this->ReadAttributeString(self::ATTR_RANGE);
if (!in_array($range, ['day', 'week', 'month', 'total'], true)) { if (!in_array($range, ['day', 'week', 'month', 'total'], true)) {
$this->WriteAttributeString(self::ATTR_RANGE, 'day'); $this->WriteAttributeString(self::ATTR_RANGE, 'day');
} }
// ensure date valid (not empty/invalid/future) // ensure date valid (not empty/invalid/future)
$date = $this->ReadAttributeString(self::ATTR_DATE); $date = $this->ReadAttributeString(self::ATTR_DATE);
if ($date === '' || !$this->isValidDate($date) || strtotime($date . ' 00:00:00') > time()) { if ($date === '' || !$this->isValidDate($date) || strtotime($date . ' 00:00:00') > time()) {
$this->WriteAttributeString(self::ATTR_DATE, date('Y-m-d')); $this->WriteAttributeString(self::ATTR_DATE, date('Y-m-d'));
} }
// Fullscreen-Fix: push periodically (adjust as you like) // Fullscreen-Fix: push periodically (adjust as you like)
// 2000ms = alle 2 Sekunden (stabil, aber nicht ganz so brutal wie 1000ms) // 2000ms = alle 2 Sekunden (stabil, aber nicht ganz so brutal wie 1000ms)
$this->SetTimerInterval('AutoPush', 2000); $this->SetTimerInterval('AutoPush', 2000);
$this->RecalculateAndPush(); $this->RecalculateAndPush();
} }
public function GetVisualizationTile(): string public function GetVisualizationTile(): string
{ {
$path = __DIR__ . '/module.html'; $path = __DIR__ . '/module.html';
@@ -60,7 +47,6 @@ class Energy_Pie extends IPSModule
} }
return file_get_contents($path); return file_get_contents($path);
} }
public function RequestAction($Ident, $Value): void public function RequestAction($Ident, $Value): void
{ {
switch ($Ident) { switch ($Ident) {
@@ -72,7 +58,6 @@ class Energy_Pie extends IPSModule
$this->WriteAttributeString(self::ATTR_RANGE, $range); $this->WriteAttributeString(self::ATTR_RANGE, $range);
$this->RecalculateAndPush(); $this->RecalculateAndPush();
break; break;
case 'SetDate': case 'SetDate':
$date = (string)$Value; $date = (string)$Value;
if (!$this->isValidDate($date)) { if (!$this->isValidDate($date)) {
@@ -81,62 +66,48 @@ class Energy_Pie extends IPSModule
$this->WriteAttributeString(self::ATTR_DATE, $date); $this->WriteAttributeString(self::ATTR_DATE, $date);
$this->RecalculateAndPush(); $this->RecalculateAndPush();
break; break;
case 'Prev': case 'Prev':
case 'Next': case 'Next':
case 'Today': case 'Today':
$this->ShiftDate($Ident); $this->ShiftDate($Ident);
$this->RecalculateAndPush(); $this->RecalculateAndPush();
break; break;
case 'Refresh': case 'Refresh':
$this->RecalculateAndPush(); $this->RecalculateAndPush();
break; break;
default: default:
// ignore unknown // ignore unknown
return; return;
} }
} }
private function RecalculateAndPush(): void private function RecalculateAndPush(): void
{ {
$range = $this->ReadAttributeString(self::ATTR_RANGE); $range = $this->ReadAttributeString(self::ATTR_RANGE);
$date = $this->ReadAttributeString(self::ATTR_DATE); $date = $this->ReadAttributeString(self::ATTR_DATE);
[$tStart, $tEnd] = $this->getRange($range, $date); [$tStart, $tEnd] = $this->getRange($range, $date);
$dbgProd = []; $dbgProd = [];
$dbgFeed = []; $dbgFeed = [];
$dbgGrid = []; $dbgGrid = [];
$prod = $this->readDelta($this->ReadPropertyInteger('VarProduction'), $tStart, $tEnd, $dbgProd); $prod = $this->readDelta($this->ReadPropertyInteger('VarProduction'), $tStart, $tEnd, $dbgProd);
$feed = $this->readDelta($this->ReadPropertyInteger('VarFeedIn'), $tStart, $tEnd, $dbgFeed); $feed = $this->readDelta($this->ReadPropertyInteger('VarFeedIn'), $tStart, $tEnd, $dbgFeed);
$grid = $this->readDelta($this->ReadPropertyInteger('VarGrid'), $tStart, $tEnd, $dbgGrid); $grid = $this->readDelta($this->ReadPropertyInteger('VarGrid'), $tStart, $tEnd, $dbgGrid);
$hasData = (($dbgProd['count'] ?? 0) > 0) || (($dbgFeed['count'] ?? 0) > 0) || (($dbgGrid['count'] ?? 0) > 0); $hasData = (($dbgProd['count'] ?? 0) > 0) || (($dbgFeed['count'] ?? 0) > 0) || (($dbgGrid['count'] ?? 0) > 0);
// Auto-jump to last log day if none found // Auto-jump to last log day if none found
if (!$hasData && $range !== 'total') { if (!$hasData && $range !== 'total') {
$lastTs = $this->getLastLogTimestamp($this->ReadPropertyInteger('VarProduction')); $lastTs = $this->getLastLogTimestamp($this->ReadPropertyInteger('VarProduction'));
if ($lastTs > 0) { if ($lastTs > 0) {
$this->WriteAttributeString(self::ATTR_DATE, date('Y-m-d', $lastTs)); $this->WriteAttributeString(self::ATTR_DATE, date('Y-m-d', $lastTs));
$date = $this->ReadAttributeString(self::ATTR_DATE); $date = $this->ReadAttributeString(self::ATTR_DATE);
[$tStart, $tEnd] = $this->getRange($range, $date); [$tStart, $tEnd] = $this->getRange($range, $date);
$prod = $this->readDelta($this->ReadPropertyInteger('VarProduction'), $tStart, $tEnd, $dbgProd); $prod = $this->readDelta($this->ReadPropertyInteger('VarProduction'), $tStart, $tEnd, $dbgProd);
$feed = $this->readDelta($this->ReadPropertyInteger('VarFeedIn'), $tStart, $tEnd, $dbgFeed); $feed = $this->readDelta($this->ReadPropertyInteger('VarFeedIn'), $tStart, $tEnd, $dbgFeed);
$grid = $this->readDelta($this->ReadPropertyInteger('VarGrid'), $tStart, $tEnd, $dbgGrid); $grid = $this->readDelta($this->ReadPropertyInteger('VarGrid'), $tStart, $tEnd, $dbgGrid);
$hasData = (($dbgProd['count'] ?? 0) > 0) || (($dbgFeed['count'] ?? 0) > 0) || (($dbgGrid['count'] ?? 0) > 0); $hasData = (($dbgProd['count'] ?? 0) > 0) || (($dbgFeed['count'] ?? 0) > 0) || (($dbgGrid['count'] ?? 0) > 0);
} }
} }
// House = Prod - Feed + Grid // House = Prod - Feed + Grid
$house = $prod - $feed + $grid; $house = $prod - $feed + $grid;
if ($house < 0) $house = 0.0; if ($house < 0) $house = 0.0;
$payload = [ $payload = [
'range' => $range, 'range' => $range,
'date' => $date, 'date' => $date,
@@ -156,46 +127,36 @@ class Energy_Pie extends IPSModule
'grid' => $dbgGrid 'grid' => $dbgGrid
] ]
]; ];
$this->UpdateVisualizationValue(json_encode($payload, JSON_THROW_ON_ERROR)); $this->UpdateVisualizationValue(json_encode($payload, JSON_THROW_ON_ERROR));
} }
private function getRange(string $range, string $dateYmd): array private function getRange(string $range, string $dateYmd): array
{ {
$now = time(); $now = time();
if ($range === 'total') { if ($range === 'total') {
return [0, $now]; return [0, $now];
} }
$base = strtotime($dateYmd . ' 00:00:00') ?: strtotime(date('Y-m-d') . ' 00:00:00'); $base = strtotime($dateYmd . ' 00:00:00') ?: strtotime(date('Y-m-d') . ' 00:00:00');
switch ($range) { switch ($range) {
case 'day': case 'day':
return [$base, $base + 86400]; return [$base, $base + 86400];
case 'week': case 'week':
$dow = (int)date('N', $base); // 1=Mon..7=Sun $dow = (int)date('N', $base); // 1=Mon..7=Sun
$start = $base - (($dow - 1) * 86400); $start = $base - (($dow - 1) * 86400);
return [$start, $start + 7 * 86400]; return [$start, $start + 7 * 86400];
case 'month': case 'month':
$start = strtotime(date('Y-m-01 00:00:00', $base)); $start = strtotime(date('Y-m-01 00:00:00', $base));
$end = strtotime(date('Y-m-01 00:00:00', strtotime('+1 month', $start))); $end = strtotime(date('Y-m-01 00:00:00', strtotime('+1 month', $start)));
return [$start, $end]; return [$start, $end];
default: default:
return [$base, $base + 86400]; return [$base, $base + 86400];
} }
} }
public function GetVisualizationPopup(): string public function GetVisualizationPopup(): string
{ {
// Popup (Fullscreen) soll das gleiche HTML wie das Tile anzeigen // Popup (Fullscreen) soll das gleiche HTML wie das Tile anzeigen
$this->RecalculateAndPush(); $this->RecalculateAndPush();
return $this->GetVisualizationTile(); return $this->GetVisualizationTile();
} }
private function readDelta(int $varId, int $tStart, int $tEnd, array &$dbg): float private function readDelta(int $varId, int $tStart, int $tEnd, array &$dbg): float
{ {
$dbg = [ $dbg = [
@@ -207,84 +168,65 @@ class Energy_Pie extends IPSModule
'vStart' => null, 'vStart' => null,
'vEnd' => null 'vEnd' => null
]; ];
if ($varId <= 0 || !IPS_VariableExists($varId)) { if ($varId <= 0 || !IPS_VariableExists($varId)) {
return 0.0; return 0.0;
} }
$archiveID = IPS_GetInstanceListByModuleID('{43192F0B-135B-4CE7-A0A7-1475603F3060}')[0] ?? 0; $archiveID = IPS_GetInstanceListByModuleID('{43192F0B-135B-4CE7-A0A7-1475603F3060}')[0] ?? 0;
$dbg['archiveId'] = $archiveID; $dbg['archiveId'] = $archiveID;
if ($archiveID <= 0) { if ($archiveID <= 0) {
return 0.0; return 0.0;
} }
$values = @AC_GetLoggedValues($archiveID, $varId, $tStart - 86400, $tEnd + 86400, 0); $values = @AC_GetLoggedValues($archiveID, $varId, $tStart - 86400, $tEnd + 86400, 0);
if (empty($values)) { if (empty($values)) {
return 0.0; return 0.0;
} }
usort($values, static fn($a, $b) => (int)$a['TimeStamp'] <=> (int)$b['TimeStamp']); usort($values, static fn($a, $b) => (int)$a['TimeStamp'] <=> (int)$b['TimeStamp']);
$dbg['count'] = count($values); $dbg['count'] = count($values);
$dbg['first'] = (float)$values[0]['Value']; $dbg['first'] = (float)$values[0]['Value'];
$dbg['last'] = (float)$values[count($values) - 1]['Value']; $dbg['last'] = (float)$values[count($values) - 1]['Value'];
$vStart = null; $vStart = null;
$vEnd = null; $vEnd = null;
foreach ($values as $v) { foreach ($values as $v) {
$ts = (int)$v['TimeStamp']; $ts = (int)$v['TimeStamp'];
if ($ts <= $tStart) $vStart = (float)$v['Value']; if ($ts <= $tStart) $vStart = (float)$v['Value'];
if ($ts <= $tEnd) $vEnd = (float)$v['Value']; if ($ts <= $tEnd) $vEnd = (float)$v['Value'];
if ($ts > $tEnd) break; if ($ts > $tEnd) break;
} }
if ($vStart === null) $vStart = $dbg['first']; if ($vStart === null) $vStart = $dbg['first'];
if ($vEnd === null) $vEnd = $dbg['last']; if ($vEnd === null) $vEnd = $dbg['last'];
$dbg['vStart'] = $vStart; $dbg['vStart'] = $vStart;
$dbg['vEnd'] = $vEnd; $dbg['vEnd'] = $vEnd;
$diff = $vEnd - $vStart; $diff = $vEnd - $vStart;
return ($diff < 0) ? 0.0 : (float)$diff; return ($diff < 0) ? 0.0 : (float)$diff;
} }
private function getLastLogTimestamp(int $varId): int private function getLastLogTimestamp(int $varId): int
{ {
if ($varId <= 0 || !IPS_VariableExists($varId)) { if ($varId <= 0 || !IPS_VariableExists($varId)) {
return 0; return 0;
} }
$archiveID = IPS_GetInstanceListByModuleID('{43192F0B-135B-4CE7-A0A7-1475603F3060}')[0] ?? 0; $archiveID = IPS_GetInstanceListByModuleID('{43192F0B-135B-4CE7-A0A7-1475603F3060}')[0] ?? 0;
if ($archiveID <= 0) { if ($archiveID <= 0) {
return 0; return 0;
} }
$values = @AC_GetLoggedValues($archiveID, $varId, 0, time(), 1); $values = @AC_GetLoggedValues($archiveID, $varId, 0, time(), 1);
if (empty($values)) { if (empty($values)) {
return 0; return 0;
} }
return (int)$values[0]['TimeStamp']; return (int)$values[0]['TimeStamp'];
} }
private function ShiftDate(string $action): void private function ShiftDate(string $action): void
{ {
$range = $this->ReadAttributeString(self::ATTR_RANGE); $range = $this->ReadAttributeString(self::ATTR_RANGE);
if ($range === 'total') { if ($range === 'total') {
return; return;
} }
if ($action === 'Today') { if ($action === 'Today') {
$this->WriteAttributeString(self::ATTR_DATE, date('Y-m-d')); $this->WriteAttributeString(self::ATTR_DATE, date('Y-m-d'));
return; return;
} }
$date = $this->ReadAttributeString(self::ATTR_DATE); $date = $this->ReadAttributeString(self::ATTR_DATE);
$base = strtotime($date . ' 00:00:00') ?: strtotime(date('Y-m-d') . ' 00:00:00'); $base = strtotime($date . ' 00:00:00') ?: strtotime(date('Y-m-d') . ' 00:00:00');
$sign = ($action === 'Prev') ? -1 : 1; $sign = ($action === 'Prev') ? -1 : 1;
switch ($range) { switch ($range) {
case 'day': case 'day':
$base = strtotime(($sign === -1 ? '-1 day' : '+1 day'), $base); $base = strtotime(($sign === -1 ? '-1 day' : '+1 day'), $base);
@@ -296,10 +238,8 @@ class Energy_Pie extends IPSModule
$base = strtotime(($sign === -1 ? '-1 month' : '+1 month'), $base); $base = strtotime(($sign === -1 ? '-1 month' : '+1 month'), $base);
break; break;
} }
$this->WriteAttributeString(self::ATTR_DATE, date('Y-m-d', $base)); $this->WriteAttributeString(self::ATTR_DATE, date('Y-m-d', $base));
} }
private function isValidDate(string $ymd): bool private function isValidDate(string $ymd): bool
{ {
if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $ymd)) { if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $ymd)) {
@@ -311,5 +251,4 @@ class Energy_Pie extends IPSModule
} }
?>
?>