no message

This commit is contained in:
belevo\mh
2025-12-18 08:32:15 +01:00
parent feb7301fc1
commit d1f0b876aa
2 changed files with 213 additions and 162 deletions

View File

@@ -1,6 +1,5 @@
<div id="wrap" <div id="wrap" style="padding:12px;font-family:system-ui,-apple-system,Segoe UI,Roboto,sans-serif;">
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;">
@@ -23,8 +22,12 @@
<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;display:grid;grid-template-columns:repeat(2,minmax(0,1fr)); style="margin-top:14px;
gap:14px;max-width:880px;"> display:grid;
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>
@@ -32,37 +35,67 @@
<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>
#wrap { /* Responsive: bei schmalen Screens 1 Spalte */
position: relative; @media (max-width: 720px) {
overflow: hidden; #grid { grid-template-columns: 1fr !important; }
} }
#wrap::before { /* Quantum-Waves Hintergrund */
content: ""; #wrap{
position: absolute; position:relative;
inset: -40%; overflow:hidden;
min-height:100vh;
}
#wrap::before{
content:"";
position:absolute;
inset:-50%;
background: background:
radial-gradient(circle at 20% 20%, rgba(99,179,255,0.18), transparent 45%), radial-gradient(circle at 20% 25%, rgba(99,179,255,.20), transparent 45%),
radial-gradient(circle at 80% 30%, rgba(168,85,247,0.16), transparent 50%), radial-gradient(circle at 80% 35%, rgba(168,85,247,.18), transparent 50%),
radial-gradient(circle at 50% 80%, rgba(255,255,255,0.06), transparent 55%); radial-gradient(circle at 55% 80%, rgba(255,255,255,.07), transparent 55%);
filter: blur(18px); filter: blur(20px);
animation: auroraMove 10s ease-in-out infinite alternate; opacity:.9;
pointer-events: none; animation: qDrift 14s ease-in-out infinite alternate;
z-index: 0; pointer-events:none;
z-index:0;
} }
#wrap > * { #wrap::after{
position: relative; content:"";
z-index: 1; position:absolute;
inset:-30%;
background:
repeating-radial-gradient(circle at 30% 40%,
rgba(255,255,255,.06) 0px,
rgba(255,255,255,0) 14px,
rgba(255,255,255,0) 28px),
repeating-linear-gradient(120deg,
rgba(168,85,247,.06) 0px,
rgba(168,85,247,0) 18px,
rgba(99,179,255,.05) 36px,
rgba(99,179,255,0) 54px);
mix-blend-mode: overlay;
opacity:.35;
animation: qWaves 10s linear infinite;
pointer-events:none;
z-index:0;
} }
@keyframes auroraMove { #wrap > *{
from { transform: translate3d(-2%, -2%, 0) scale(1.02); } position:relative;
to { transform: translate3d( 2%, 2%, 0) scale(1.06); } z-index:1;
}
@keyframes qDrift{
from{ transform: translate3d(-2%, -2%, 0) scale(1.02) rotate(-2deg); }
to { transform: translate3d( 2%, 2%, 0) scale(1.08) rotate( 2deg); }
}
@keyframes qWaves{
from{ transform: translate3d(0,0,0) rotate(0deg); }
to { transform: translate3d(6%, -4%, 0) rotate(360deg); }
} }
</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") {
@@ -83,7 +116,7 @@
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) {
@@ -116,10 +149,9 @@
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;
@@ -135,18 +167,17 @@
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); // ~18s if (tryCall() || tries >= 150) clearInterval(timer);
}, 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;
@@ -156,49 +187,44 @@ function donutCard({ title, percent, subtitle, color }) {
<div style="border:1px solid rgba(255,255,255,0.12); <div style="border:1px solid rgba(255,255,255,0.12);
border-radius:16px; border-radius:16px;
padding:14px; padding:14px;
min-height:210px; min-height:260px;
width:100%;
display:flex; display:flex;
flex-direction:column; flex-direction:column;
align-items:center; align-items:center;
justify-content:center; justify-content:center;
gap:10px;"> gap:12px;
<!-- Titel oben --> background:rgba(0,0,0,0.08);
backdrop-filter: blur(2px);">
<div style="font-size:14px;font-weight:700;opacity:.9;"> <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="90" cy="90" r="${r}"
<circle cx="85" cy="85" r="${r}"
fill="none" fill="none"
stroke="rgba(255,255,255,0.10)" stroke="rgba(255,255,255,0.10)"
stroke-width="18" /> stroke-width="18" />
<circle cx="85" cy="85" r="${r}" <circle cx="90" cy="90" r="${r}"
fill="none" fill="none"
stroke="${color}" stroke="${color}"
stroke-width="18" stroke-width="18"
stroke-linecap="butt" stroke-linecap="butt"
stroke-dasharray="${dash} ${gap}" stroke-dasharray="${dash} ${gap}"
transform="rotate(-90 85 85)" /> transform="rotate(-90 90 90)" />
</svg> </svg>
<!-- Prozent im Kreis --> <div style="position:absolute;inset:0;display:flex;
<div style="position:absolute; align-items:center;justify-content:center;
inset:0; font-weight:800;font-size:24px;">
display:flex;
align-items:center;
justify-content:center;
font-weight:800;
font-size:22px;">
${escapeHtml(percent.toFixed(1))}% ${escapeHtml(percent.toFixed(1))}%
</div> </div>
</div> </div>
<!-- Untertitel unten -->
<div style="font-size:12px;opacity:.65;text-align:center;"> <div style="font-size:12px;opacity:.65;text-align:center;">
${escapeHtml(subtitle)} ${escapeHtml(subtitle)}
</div> </div>
</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);
@@ -208,12 +234,10 @@ function donutCard({ title, percent, subtitle, color }) {
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);
@@ -223,7 +247,6 @@ function donutCard({ title, percent, subtitle, color }) {
} 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 {
@@ -244,6 +267,7 @@ function donutCard({ title, percent, subtitle, color }) {
color: '#A855F7' color: '#A855F7'
}) })
].join(''); ].join('');
} }
// --- cache --- // --- cache ---
function saveLast(data) { function saveLast(data) {
@@ -257,7 +281,6 @@ function donutCard({ title, percent, subtitle, color }) {
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) {}
@@ -278,16 +301,13 @@ function donutCard({ title, percent, subtitle, color }) {
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();

View File

@@ -3,6 +3,7 @@
declare(strict_types=1); declare(strict_types=1);
class Energy_Pie extends IPSModule class Energy_Pie extends IPSModule
{ {
// Attribute keys for UI state
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
@@ -13,30 +14,28 @@ class Energy_Pie extends IPSModule
$this->RegisterPropertyInteger('VarConsumption', 0); $this->RegisterPropertyInteger('VarConsumption', 0);
$this->RegisterPropertyInteger('VarFeedIn', 0); $this->RegisterPropertyInteger('VarFeedIn', 0);
$this->RegisterPropertyInteger('VarGrid', 0); $this->RegisterPropertyInteger('VarGrid', 0);
// Default range for first startup
$this->RegisterPropertyString('DefaultRange', 'day');
// 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!)
$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 // First-time init: if range is empty, set it to property default
$range = $this->ReadAttributeString(self::ATTR_RANGE); $range = $this->ReadAttributeString(self::ATTR_RANGE);
if (!in_array($range, ['day', 'week', 'month', 'total'], true)) { if ($range === '') {
$this->WriteAttributeString(self::ATTR_RANGE, 'day'); $this->WriteAttributeString(self::ATTR_RANGE, $this->ReadPropertyString('DefaultRange'));
} }
// ensure date valid (not empty/invalid/future)
$date = $this->ReadAttributeString(self::ATTR_DATE); $date = $this->ReadAttributeString(self::ATTR_DATE);
// Wenn Datum leer/ungültig oder in der Zukunft -> heute setzen
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) // Push initial view data
// 2000ms = alle 2 Sekunden (stabil, aber nicht ganz so brutal wie 1000ms)
$this->SetTimerInterval('AutoPush', 2000);
$this->RecalculateAndPush(); $this->RecalculateAndPush();
} }
public function GetVisualizationTile(): string public function GetVisualizationTile(): string
@@ -53,15 +52,16 @@ class Energy_Pie extends IPSModule
case 'SetRange': case 'SetRange':
$range = (string)$Value; $range = (string)$Value;
if (!in_array($range, ['day', 'week', 'month', 'total'], true)) { if (!in_array($range, ['day', 'week', 'month', 'total'], true)) {
return; throw new Exception('Invalid range: ' . $range);
} }
$this->WriteAttributeString(self::ATTR_RANGE, $range); $this->WriteAttributeString(self::ATTR_RANGE, $range);
$this->RecalculateAndPush(); $this->RecalculateAndPush();
break; break;
case 'SetDate': case 'SetDate':
// Expect YYYY-MM-DD from HTML <input type="date">
$date = (string)$Value; $date = (string)$Value;
if (!$this->isValidDate($date)) { if (!$this->isValidDate($date)) {
return; throw new Exception('Invalid date: ' . $date);
} }
$this->WriteAttributeString(self::ATTR_DATE, $date); $this->WriteAttributeString(self::ATTR_DATE, $date);
$this->RecalculateAndPush(); $this->RecalculateAndPush();
@@ -76,36 +76,45 @@ class Energy_Pie extends IPSModule
$this->RecalculateAndPush(); $this->RecalculateAndPush();
break; break;
default: default:
// ignore unknown throw new Exception('Unknown Ident: ' . $Ident);
return;
} }
} }
private function RecalculateAndPush(): void /**
{ * Compute values (later from archive), then push to tile via UpdateVisualizationValue.
*/
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);
// Debug-Container initialisieren (sonst "Undefined variable")
$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
if (!$hasData && $range !== 'total') { if (!$hasData && $range !== 'total') {
// nimm Produktion als Referenz für "letzte Daten"
$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));
// Range neu berechnen für dieses Datum
$date = $this->ReadAttributeString(self::ATTR_DATE); $date = $this->ReadAttributeString(self::ATTR_DATE);
[$tStart, $tEnd] = $this->getRange($range, $date); [$tStart, $tEnd] = $this->getRange($range, $date);
// Deltas nochmal holen (jetzt sollte count>0 werden)
$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;
if ($house < 0) $house = 0.0; if ($house < 0) $house = 0.0;
$payload = [ $payload = [
@@ -120,7 +129,6 @@ class Energy_Pie extends IPSModule
'Netz' => (float)$grid, 'Netz' => (float)$grid,
'Hausverbrauch' => (float)$house 'Hausverbrauch' => (float)$house
], ],
// kannst du später entfernen
'debug' => [ 'debug' => [
'prod' => $dbgProd, 'prod' => $dbgProd,
'feed' => $dbgFeed, 'feed' => $dbgFeed,
@@ -128,21 +136,38 @@ class Energy_Pie extends IPSModule
] ]
]; ];
$this->UpdateVisualizationValue(json_encode($payload, JSON_THROW_ON_ERROR)); $this->UpdateVisualizationValue(json_encode($payload, JSON_THROW_ON_ERROR));
} }
/**
* Range rules:
* - day: chosen date 00:00:00 .. next day 00:00:00
* - week: Monday 00:00:00 .. next Monday 00:00:00 (MoSo)
* - month: first of month 00:00:00 .. first of next month 00:00:00
* - total: 0 .. now (placeholder)
*/
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') {
// Later: use oldest log timestamp as start
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');
if ($base === false) {
// fallback to today
$base = strtotime(date('Y-m-d') . ' 00:00:00');
}
switch ($range) { switch ($range) {
case 'day': case 'day':
return [$base, $base + 86400]; $start = $base;
$end = $start + 86400;
return [$start, $end];
case 'week': case 'week':
$dow = (int)date('N', $base); // 1=Mon..7=Sun // date('N'): 1=Mon .. 7=Sun
$start = $base - (($dow - 1) * 86400); $dow = (int)date('N', $base);
return [$start, $start + 7 * 86400]; $start = $base - (($dow - 1) * 86400); // Monday
$end = $start + (7 * 86400); // next Monday
return [$start, $end];
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)));
@@ -151,12 +176,7 @@ class Energy_Pie extends IPSModule
return [$base, $base + 86400]; return [$base, $base + 86400];
} }
} }
public function GetVisualizationPopup(): string
{
// Popup (Fullscreen) soll das gleiche HTML wie das Tile anzeigen
$this->RecalculateAndPush();
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 = [
@@ -208,16 +228,24 @@ class Energy_Pie extends IPSModule
if ($archiveID <= 0) { if ($archiveID <= 0) {
return 0; return 0;
} }
// Hole den letzten Eintrag (0..now, limit=1 -> der neueste)
$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;
} }
// Bei limit=1 kommt genau ein Eintrag (der neueste)
return (int)$values[0]['TimeStamp']; return (int)$values[0]['TimeStamp'];
} }
/**
* Buttons for quick navigation.
*/
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') {
// total ignores date
return; return;
} }
if ($action === 'Today') { if ($action === 'Today') {
@@ -225,7 +253,10 @@ class Energy_Pie extends IPSModule
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');
if ($base === false) {
$base = 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':
@@ -242,13 +273,13 @@ class Energy_Pie extends IPSModule
} }
private function isValidDate(string $ymd): bool private function isValidDate(string $ymd): bool
{ {
// expects YYYY-MM-DD
if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $ymd)) { if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $ymd)) {
return false; return false;
} }
[$y, $m, $d] = array_map('intval', explode('-', $ymd)); [$y, $m, $d] = array_map('intval', explode('-', $ymd));
return checkdate($m, $d, $y); return checkdate($m, $d, $y);
} }
} }
?> ?>