Files
Symcon_Belevo_Energiemanage…/Energy_Pie/module.php
2025-12-17 07:50:58 +01:00

252 lines
7.9 KiB
PHP

<?php
declare(strict_types=1);
class Energy_Pie extends IPSModule
{
private const ATTR_RANGE = 'Range';
private const ATTR_DATE = 'Date';
public function Create(): void
{
parent::Create();
// Source variables (logged counters, kWh)
$this->RegisterPropertyInteger('VarProduction', 0);
$this->RegisterPropertyInteger('VarConsumption', 0);
$this->RegisterPropertyInteger('VarFeedIn', 0);
$this->RegisterPropertyInteger('VarGrid', 0);
$this->RegisterPropertyString('DefaultRange', 'day');
// UI state (internal, no object tree clutter)
$this->RegisterAttributeString(self::ATTR_RANGE, 'day');
$this->RegisterAttributeString(self::ATTR_DATE, date('Y-m-d'));
// Enable HTML-SDK visualization
$this->SetVisualizationType(1);
}
public function ApplyChanges(): void
{
parent::ApplyChanges();
if ($this->ReadAttributeString(self::ATTR_RANGE) === '') {
$this->WriteAttributeString(self::ATTR_RANGE, $this->ReadPropertyString('DefaultRange'));
}
$date = $this->ReadAttributeString(self::ATTR_DATE);
if ($date === '' || !$this->isValidDate($date)) {
$this->WriteAttributeString(self::ATTR_DATE, date('Y-m-d'));
}
$this->RecalculateAndPush();
}
public function GetVisualizationTile(): string
{
$path = __DIR__ . '/module.html';
return file_exists($path)
? file_get_contents($path)
: '<div style="padding:12px">module.html fehlt</div>';
}
public function RequestAction($Ident, $Value): void
{
switch ($Ident) {
case 'SetRange':
$range = (string)$Value;
if (!in_array($range, ['day', 'week', 'month', 'total'], true)) {
return;
}
$this->WriteAttributeString(self::ATTR_RANGE, $range);
if ($range === 'week') {
$this->snapDateToWeekMonday();
}
break;
case 'SetDate':
$date = (string)$Value;
if (!$this->isValidDate($date)) {
return;
}
$this->WriteAttributeString(self::ATTR_DATE, $date);
if ($this->ReadAttributeString(self::ATTR_RANGE) === 'week') {
$this->snapDateToWeekMonday();
}
break;
case 'Prev':
case 'Next':
case 'Today':
$this->ShiftDate($Ident);
if ($this->ReadAttributeString(self::ATTR_RANGE) === 'week') {
$this->snapDateToWeekMonday();
}
break;
case 'Refresh':
break;
default:
return;
}
$this->RecalculateAndPush();
}
/* ========================================================= */
/* ===================== CORE LOGIC ======================== */
/* ========================================================= */
private function RecalculateAndPush(): void
{
$range = $this->ReadAttributeString(self::ATTR_RANGE);
$date = $this->ReadAttributeString(self::ATTR_DATE);
[$tStart, $tEnd] = $this->getRange($range, $date);
$prod = $this->readDelta($this->ReadPropertyInteger('VarProduction'), $tStart, $tEnd);
$cons = $this->readDelta($this->ReadPropertyInteger('VarConsumption'), $tStart, $tEnd);
$feed = $this->readDelta($this->ReadPropertyInteger('VarFeedIn'), $tStart, $tEnd);
$grid = $this->readDelta($this->ReadPropertyInteger('VarGrid'), $tStart, $tEnd);
$payload = [
'range' => $range,
'date' => $date,
'tStart' => $tStart,
'tEnd' => $tEnd,
'values' => [
'Produktion' => $prod,
'Verbrauch' => $cons,
'Einspeisung' => $feed,
'Netz' => $grid
]
];
$this->UpdateVisualizationValue(json_encode($payload, JSON_THROW_ON_ERROR));
}
/* ========================================================= */
/* ===================== TIME RANGES ======================= */
/* ========================================================= */
private function getRange(string $range, string $dateYmd): array
{
$now = time();
if ($range === 'total') {
return [0, $now];
}
$base = strtotime($dateYmd . ' 00:00:00') ?: strtotime('today');
switch ($range) {
case 'day':
return [$base, $base + 86400];
case 'week':
$dow = (int)date('N', $base); // 1=Mon
$start = $base - (($dow - 1) * 86400);
return [$start, $start + 7 * 86400];
case 'month':
$start = strtotime(date('Y-m-01 00:00:00', $base));
return [$start, strtotime('+1 month', $start)];
default:
return [$base, $base + 86400];
}
}
private function ShiftDate(string $action): void
{
$range = $this->ReadAttributeString(self::ATTR_RANGE);
if ($range === 'total') {
return;
}
if ($action === 'Today') {
$this->WriteAttributeString(self::ATTR_DATE, date('Y-m-d'));
return;
}
$base = strtotime($this->ReadAttributeString(self::ATTR_DATE) . ' 00:00:00') ?: strtotime('today');
$dir = ($action === 'Prev') ? -1 : 1;
match ($range) {
'day' => $base = strtotime(($dir === -1 ? '-1 day' : '+1 day'), $base),
'week' => $base = strtotime(($dir === -7 ? '-7 day' : '+7 day'), $base),
'month' => $base = strtotime(($dir === -1 ? '-1 month' : '+1 month'), $base),
default => null
};
$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
{
if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $ymd)) {
return false;
}
[$y, $m, $d] = array_map('intval', explode('-', $ymd));
return checkdate($m, $d, $y);
}
}
?>