no message

This commit is contained in:
mh
2025-12-17 08:04:01 +01:00
parent 284ed6ff3b
commit 5f127b9ede
2 changed files with 109 additions and 165 deletions
+1 -15
View File
@@ -3,20 +3,6 @@
{ "type": "SelectVariable", "name": "VarProduction", "caption": "Produktion (kWh)" }, { "type": "SelectVariable", "name": "VarProduction", "caption": "Produktion (kWh)" },
{ "type": "SelectVariable", "name": "VarConsumption", "caption": "Verbrauch (kWh)" }, { "type": "SelectVariable", "name": "VarConsumption", "caption": "Verbrauch (kWh)" },
{ "type": "SelectVariable", "name": "VarFeedIn", "caption": "Einspeisung (kWh)" }, { "type": "SelectVariable", "name": "VarFeedIn", "caption": "Einspeisung (kWh)" },
{ "type": "SelectVariable", "name": "VarGrid", "caption": "Bezug Netz (kWh)" }, { "type": "SelectVariable", "name": "VarGrid", "caption": "Bezug Netz (kWh)" }
{ "type": "Label", "caption": "" },
{
"type": "Select",
"name": "DefaultRange",
"caption": "Standard-Zeitraum",
"options": [
{ "caption": "Tag", "value": "day" },
{ "caption": "Woche", "value": "week" },
{ "caption": "Monat", "value": "month" },
{ "caption": "Gesamt", "value": "total" }
]
}
] ]
} }
+107 -149
View File
@@ -2,8 +2,9 @@
declare(strict_types=1); declare(strict_types=1);
class Energy_Pie extends IPSModule class EnergyPie 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';
@@ -17,13 +18,14 @@ class Energy_Pie extends IPSModule
$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'); $this->RegisterPropertyString('DefaultRange', 'day');
// UI state (internal, no object tree clutter) // 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 HTML-SDK visualization // Enable individual visualization (HTML-SDK)
$this->SetVisualizationType(1); $this->SetVisualizationType(1);
} }
@@ -31,165 +33,155 @@ class Energy_Pie extends IPSModule
{ {
parent::ApplyChanges(); parent::ApplyChanges();
if ($this->ReadAttributeString(self::ATTR_RANGE) === '') { // First-time init: if range is empty, set it to property default
$range = $this->ReadAttributeString(self::ATTR_RANGE);
if ($range === '') {
$this->WriteAttributeString(self::ATTR_RANGE, $this->ReadPropertyString('DefaultRange')); $this->WriteAttributeString(self::ATTR_RANGE, $this->ReadPropertyString('DefaultRange'));
} }
$date = $this->ReadAttributeString(self::ATTR_DATE); // Push initial view data
if ($date === '' || !$this->isValidDate($date)) {
$this->WriteAttributeString(self::ATTR_DATE, date('Y-m-d'));
}
$this->RecalculateAndPush(); $this->RecalculateAndPush();
} }
public function GetVisualizationTile(): string public function GetVisualizationTile(): string
{ {
$path = __DIR__ . '/module.html'; $path = __DIR__ . '/module.html';
return file_exists($path) if (!file_exists($path)) {
? file_get_contents($path) return '<div style="padding:12px;font-family:sans-serif;">module.html fehlt</div>';
: '<div style="padding:12px">module.html fehlt</div>'; }
return file_get_contents($path);
} }
public function RequestAction($Ident, $Value): void public function RequestAction($Ident, $Value): void
{ {
switch ($Ident) { switch ($Ident) {
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);
if ($range === 'week') { $this->RecalculateAndPush();
$this->snapDateToWeekMonday();
}
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);
if ($this->ReadAttributeString(self::ATTR_RANGE) === 'week') { $this->RecalculateAndPush();
$this->snapDateToWeekMonday();
}
break; break;
case 'Prev': case 'Prev':
case 'Next': case 'Next':
case 'Today': case 'Today':
$this->ShiftDate($Ident); $this->ShiftDate($Ident);
if ($this->ReadAttributeString(self::ATTR_RANGE) === 'week') { $this->RecalculateAndPush();
$this->snapDateToWeekMonday();
}
break; break;
case 'Refresh': case 'Refresh':
$this->RecalculateAndPush();
break; break;
default: default:
return; throw new Exception('Unknown Ident: ' . $Ident);
} }
$this->RecalculateAndPush();
} }
/* ========================================================= */ /**
/* ===================== CORE LOGIC ======================== */ * Compute values (later from archive), then push to tile via UpdateVisualizationValue.
/* ========================================================= */ */
private function RecalculateAndPush(): void
{
$range = $this->ReadAttributeString(self::ATTR_RANGE);
$date = $this->ReadAttributeString(self::ATTR_DATE);
private function RecalculateAndPush(): void [$tStart, $tEnd] = $this->getRange($range, $date);
{
$range = $this->ReadAttributeString(self::ATTR_RANGE);
$date = $this->ReadAttributeString(self::ATTR_DATE);
[$tStart, $tEnd] = $this->getRange($range, $date); // --- PLACEHOLDER CALCULATION ---
// Replace these with your later delta calculation from logged data:
// $prod = $this->readDelta($this->ReadPropertyInteger('VarProduction'), $tStart, $tEnd);
// etc.
$prod = 12.3;
$cons = 8.7;
$feed = 3.1;
$grid = 5.6;
// Deltas aus dem Archiv // If you prefer, you can already set them to 0.0 for "no calc yet"
$prod = $this->readDelta($this->ReadPropertyInteger('VarProduction'), $tStart, $tEnd); // $prod = $cons = $feed = $grid = 0.0;
$feed = $this->readDelta($this->ReadPropertyInteger('VarFeedIn'), $tStart, $tEnd);
$grid = $this->readDelta($this->ReadPropertyInteger('VarGrid'), $tStart, $tEnd);
// Hausverbrauch = Produktion - Einspeisung + Netz $payload = [
$house = $prod - $feed + $grid; 'range' => $range,
'date' => $date,
'tStart' => $tStart,
'tEnd' => $tEnd,
'values' => [
'Produktion' => (float)$prod,
'Verbrauch' => (float)$cons,
'Einspeisung' => (float)$feed,
'Netz' => (float)$grid
]
];
// optionaler Schutz (z.B. wenn Logs/Resets Mist bauen) $this->UpdateVisualizationValue($payload);
if ($house < 0) {
$house = 0.0;
} }
// Debug ins Log, damit du die Rechnung sofort prüfen kannst /**
$this->LogMessage( * Range rules:
sprintf( * - day: chosen date 00:00:00 .. next day 00:00:00
"EnergyPie | Range=%s Date=%s | %s -> %s | Prod=%.3f Feed=%.3f Grid=%.3f House=%.3f", * - week: Monday 00:00:00 .. next Monday 00:00:00 (Mo–So)
$range, * - month: first of month 00:00:00 .. first of next month 00:00:00
$date, * - total: 0 .. now (placeholder)
date('Y-m-d H:i:s', $tStart), */
date('Y-m-d H:i:s', $tEnd),
$prod,
$feed,
$grid,
$house
),
KL_NOTIFY
);
$payload = [
'range' => $range,
'date' => $date,
'tStart' => $tStart,
'tEnd' => $tEnd,
'values' => [
'Produktion' => (float)$prod,
'Einspeisung' => (float)$feed,
'Netz' => (float)$grid,
'Hausverbrauch'=> (float)$house
]
];
$this->UpdateVisualizationValue(json_encode($payload, JSON_THROW_ON_ERROR));
}
/* ========================================================= */
/* ===================== TIME RANGES ======================= */
/* ========================================================= */
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('today'); $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 // 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));
return [$start, strtotime('+1 month', $start)]; $end = strtotime(date('Y-m-01 00:00:00', strtotime('+1 month', $start)));
return [$start, $end];
default: default:
return [$base, $base + 86400]; return [$base, $base + 86400];
} }
} }
/**
* 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;
} }
@@ -198,80 +190,46 @@ private function RecalculateAndPush(): void
return; return;
} }
$base = strtotime($this->ReadAttributeString(self::ATTR_DATE) . ' 00:00:00') ?: strtotime('today'); $date = $this->ReadAttributeString(self::ATTR_DATE);
$dir = ($action === 'Prev') ? -1 : 1; $base = strtotime($date . ' 00:00:00');
if ($base === false) {
$base = strtotime(date('Y-m-d') . ' 00:00:00');
}
match ($range) { $sign = ($action === 'Prev') ? -1 : 1;
'day' => $base = strtotime(($dir === -1 ? '-1 day' : '+1 day'), $base),
'week' => $base = strtotime(($dir === -7 ? '-7 day' : '+7 day'), $base), switch ($range) {
'month' => $base = strtotime(($dir === -1 ? '-1 month' : '+1 month'), $base), case 'day':
default => null $base = strtotime(($sign === -1 ? '-1 day' : '+1 day'), $base);
}; break;
case 'week':
$base = strtotime(($sign === -1 ? '-7 day' : '+7 day'), $base);
break;
case 'month':
$base = strtotime(($sign === -1 ? '-1 month' : '+1 month'), $base);
break;
}
$this->WriteAttributeString(self::ATTR_DATE, date('Y-m-d', $base)); $this->WriteAttributeString(self::ATTR_DATE, date('Y-m-d', $base));
} }
private function snapDateToWeekMonday(): void
{
$base = strtotime($this->ReadAttributeString(self::ATTR_DATE) . ' 00:00:00') ?: strtotime('today');
$dow = (int)date('N', $base);
$this->WriteAttributeString(self::ATTR_DATE, date('Y-m-d', $base - (($dow - 1) * 86400)));
}
/* ========================================================= */
/* ===================== ARCHIVE READ ====================== */
/* ========================================================= */
private function readDelta(int $varId, int $tStart, int $tEnd): float
{
if ($varId <= 0 || !IPS_VariableExists($varId)) {
return 0.0;
}
$archiveID = IPS_GetInstanceListByModuleID('{43192F0B-135B-4CE7-A0A7-1475603F3060}')[0] ?? 0;
if ($archiveID <= 0) {
return 0.0;
}
$values = AC_GetLoggedValues($archiveID, $varId, $tStart - 86400, $tEnd + 86400, 0);
if (empty($values)) {
return 0.0;
}
usort($values, static fn($a, $b) => $a['TimeStamp'] <=> $b['TimeStamp']);
$vStart = null;
$vEnd = null;
foreach ($values as $v) {
if ($v['TimeStamp'] <= $tStart) {
$vStart = (float)$v['Value'];
}
if ($v['TimeStamp'] <= $tEnd) {
$vEnd = (float)$v['Value'];
}
if ($v['TimeStamp'] > $tEnd) {
break;
}
}
if ($vStart === null || $vEnd === null) {
return 0.0;
}
$diff = $vEnd - $vStart;
return ($diff < 0) ? 0.0 : round($diff, 3);
}
/* ========================================================= */
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);
} }
// Optional helper for the "actions" test button in form.json
public function TestPush(): void
{
$this->RecalculateAndPush();
}
} }
?> ?>