diff --git a/Abrechnung/module.php b/Abrechnung/module.php index c179424..4bf92dd 100644 --- a/Abrechnung/module.php +++ b/Abrechnung/module.php @@ -215,7 +215,7 @@ public function GenerateInvoices() return 0.0; } -private function GetValueAt(int $varId, int $timestamp) +private function GetValueAt(int $varId, int $timestamp, bool $nearestAfter = false) { $archiveID = @IPS_GetInstanceListByModuleID('{43192F0B-135B-4CE7-A0A7-1475603F3060}')[0]; if (!$archiveID || !IPS_VariableExists($varId)) { @@ -223,22 +223,14 @@ private function GetValueAt(int $varId, int $timestamp) return null; } - // Letzter Wert <= Timestamp - $before = @AC_GetLoggedValues($archiveID, $varId, 0, $timestamp, 1); - $beforeVal = ($before && count($before) > 0) ? floatval($before[count($before)-1]['Value']) : null; - - // Erster Wert >= Timestamp - $after = @AC_GetLoggedValues($archiveID, $varId, $timestamp, time(), 1); - $afterVal = ($after && count($after) > 0) ? floatval($after[0]['Value']) : null; - - // Wert auswählen: Priorität nach Timestamp - if ($afterVal !== null) { - IPS_LogMessage('Abrechnung', "Variable $varId: Wert nach Timestamp gefunden = $afterVal"); - return $afterVal; - } - if ($beforeVal !== null) { - IPS_LogMessage('Abrechnung', "Variable $varId: Wert vor Timestamp gefunden = $beforeVal"); - return $beforeVal; + if ($nearestAfter) { + // Endwert: erster Wert >= Timestamp + $values = @AC_GetLoggedValues($archiveID, $varId, $timestamp, $timestamp + 86400, 1); + if ($values && count($values) > 0) return floatval($values[0]['Value']); + } else { + // Startwert: letzter Wert <= Timestamp + $values = @AC_GetLoggedValues($archiveID, $varId, 0, $timestamp, 1); + if ($values && count($values) > 0) return floatval($values[count($values)-1]['Value']); } // Fallback auf aktuellen Wert @@ -249,8 +241,9 @@ private function GetValueAt(int $varId, int $timestamp) private function AddMeterToPDFRow($meter, $tariffs, $from, $to, $type) { - $startVal = $this->GetValueAt($meter['var_consumption'], $from); - $endVal = $this->GetValueAt($meter['var_consumption'], $to); + $startVal = $this->GetValueAt($meter['var_consumption'], $from, false); // letzter Wert ≤ Start + $endVal = $this->GetValueAt($meter['var_consumption'], $to, true); // erster Wert ≥ Ende + IPS_LogMessage('Abrechnung', "Meter {$meter['name']} ($type) von " . date('d.m.Y H:i', $from) . " bis " . date('d.m.Y H:i', $to) . ": start=$startVal, end=$endVal");