RegisterPropertyInteger('TargetCategoryID', 0); $this->RegisterPropertyFloat('GlobalPricePerKWh', 0.0); $this->RegisterPropertyString('Counters', '[]'); // Die Berechnungszustände liegen bewusst im Hauptmodul. Childinstanzen // enthalten ausschließlich die (bei Bedarf ausgeblendeten) Anzeigevariablen. $this->RegisterAttributeString('CounterState', '{}'); $this->RegisterAttributeString('CounterChildren', '{}'); $this->RegisterAttributeString('RegisteredSourceIDs', '[]'); $this->RegisterTimer('Update', 0, 'ECM_UpdateValues(' . $this->InstanceID . ');'); } public function ApplyChanges() { parent::ApplyChanges(); $this->SetTimerInterval('Update', 60 * 1000); $this->SynchronizeChildren(); $this->UpdateSourceMessages(); $this->UpdateValues(); $categoryID = $this->ReadPropertyInteger('TargetCategoryID'); $this->SetStatus(($categoryID > 0 && IPS_ObjectExists($categoryID)) ? 102 : 201); } public function MessageSink($TimeStamp, $SenderID, $Message, $Data) { if ($Message === VM_UPDATE) { $this->UpdateValues(); } } /** Erstellt bzw. aktualisiert für jeden Tabellen-Eintrag eine Childinstanz. */ public function SynchronizeChildren() { if (!$this->EnterLock()) { return; } try { $categoryID = $this->ReadPropertyInteger('TargetCategoryID'); if ($categoryID <= 0 || !IPS_ObjectExists($categoryID)) { $this->SetStatus(201); return; } $children = $this->ReadJsonAttribute('CounterChildren', []); foreach ($this->GetCounters() as $counter) { $key = $counter['Key']; $childID = isset($children[$key]) ? (int) $children[$key] : 0; if ($childID <= 0 || !$this->IsManagedChild($childID)) { $childID = $this->FindManagedChild($categoryID, $key); } if ($childID <= 0) { $existingID = @IPS_GetObjectIDByIdent($key, $categoryID); if ($existingID !== false) { $this->Log('Zähler "' . $counter['Name'] . '": der Ident ' . $key . ' ist in der Zielkategorie bereits durch Objekt ' . $existingID . ' belegt.'); continue; } $childID = IPS_CreateInstance(self::CHILD_MODULE_ID); IPS_SetParent($childID, $categoryID); IPS_SetIdent($childID, $key); } elseif (IPS_GetObject($childID)['ParentID'] !== $categoryID) { $existingID = @IPS_GetObjectIDByIdent($key, $categoryID); if ($existingID !== false && $existingID !== $childID) { $this->Log('Zähler "' . $counter['Name'] . '": die Childinstanz kann nicht verschoben werden, weil der Ident ' . $key . ' in der Zielkategorie belegt ist.'); continue; } IPS_SetParent($childID, $categoryID); } IPS_SetName($childID, $counter['Name']); $this->ConfigureChild($childID, $key, $counter['VariableID']); $children[$key] = $childID; } $this->WriteAttributeString('CounterChildren', json_encode($children)); $this->SetStatus(102); } catch (\Throwable $exception) { $this->Log('Childinstanzen konnten nicht synchronisiert werden: ' . $exception->getMessage()); $this->SetStatus(201); } finally { $this->LeaveLock(); } } /** Liest alle Quellzähler aus und schreibt die sechs Werte in ihre Childinstanz. */ public function UpdateValues() { if (!$this->EnterLock()) { return; } try { $states = $this->ReadJsonAttribute('CounterState', []); $children = $this->ReadJsonAttribute('CounterChildren', []); $today = date('Y-m-d'); $month = date('Y-m'); foreach ($this->GetCounters() as $counter) { $key = $counter['Key']; $sourceID = $counter['VariableID']; if (!IPS_VariableExists($sourceID)) { $this->Log('Zähler "' . $counter['Name'] . '": Quellvariable ' . $sourceID . ' existiert nicht.'); continue; } $sourceValue = GetValue($sourceID); if (!is_numeric($sourceValue)) { $this->Log('Zähler "' . $counter['Name'] . '": Quellvariable enthält keinen numerischen Wert.'); continue; } $state = $this->NormalizeState($states[$key] ?? [], $today, $month); $currentValue = (float) $sourceValue; // Die erste Messung setzt nur die Referenz. Dadurch wird kein bereits // vorhandener Zählerstand irrtümlich als neuer Verbrauch gewertet. if (!$state['initialized']) { $state['initialized'] = true; $state['lastRaw'] = $currentValue; } else { $delta = $currentValue - $state['lastRaw']; if ($delta >= 0) { $state['totalEnergy'] += $delta; $state['dayEnergy'] += $delta; $state['monthEnergy'] += $delta; } else { // Ein zurückgesetzter/überlaufener Hardwarezähler darf den // bereits berechneten Verbrauch nicht negativ verändern. $this->Log('Zähler "' . $counter['Name'] . '": fallender Zählerstand erkannt; neue Referenz gesetzt.'); } $state['lastRaw'] = $currentValue; } $states[$key] = $state; $childID = isset($children[$key]) ? (int) $children[$key] : 0; if ($childID > 0 && IPS_InstanceExists($childID)) { $this->WriteChildValues($childID, $state, $counter['PricePerKWh']); } } $this->WriteAttributeString('CounterState', json_encode($states)); } finally { $this->LeaveLock(); } } /** Setzt ausschließlich die im Hauptmodul berechneten Gesamtwerte zurück. */ public function ResetTotalEnergy() { $this->ResetEnergy('totalEnergy'); } /** Setzt ausschließlich die im Hauptmodul berechneten Tageswerte zurück. */ public function ResetDayEnergy() { $this->ResetEnergy('dayEnergy'); } /** Setzt ausschließlich die im Hauptmodul berechneten Monatswerte zurück. */ public function ResetMonthEnergy() { $this->ResetEnergy('monthEnergy'); } /** * Übernimmt den aktuellen Rohzählerstand als Gesamtenergie eines einzelnen * Counters. Diese Methode wird über den Initialisierungsbutton des Childs * aufgerufen, die Zustandsführung bleibt aber im Hauptmodul. */ public function SetCounterTotalEnergyFromSource(string $counterKey): bool { // Noch nicht verarbeitete Änderungen sollen Tages- und Monatswerte // weiterhin korrekt fortschreiben, bevor nur der Gesamtwert gesetzt wird. $this->UpdateValues(); if (!$this->EnterLock()) { return false; } try { $counter = null; foreach ($this->GetCounters() as $configuredCounter) { if ($configuredCounter['Key'] === $counterKey) { $counter = $configuredCounter; break; } } if ($counter === null || !IPS_VariableExists($counter['VariableID'])) { $this->Log('Gesamtenergie konnte nicht gesetzt werden: Quellzähler für ' . $counterKey . ' ist nicht verfügbar.'); return false; } $sourceValue = GetValue($counter['VariableID']); if (!is_numeric($sourceValue)) { $this->Log('Gesamtenergie konnte nicht gesetzt werden: Quellzähler für ' . $counter['Name'] . ' enthält keinen numerischen Wert.'); return false; } $states = $this->ReadJsonAttribute('CounterState', []); $state = $this->NormalizeState($states[$counterKey] ?? [], date('Y-m-d'), date('Y-m')); $currentValue = (float) $sourceValue; $state['initialized'] = true; $state['lastRaw'] = $currentValue; $state['totalEnergy'] = max(0.0, $currentValue); $states[$counterKey] = $state; $this->WriteAttributeString('CounterState', json_encode($states)); $children = $this->ReadJsonAttribute('CounterChildren', []); $childID = isset($children[$counterKey]) ? (int) $children[$counterKey] : 0; if ($childID > 0 && IPS_InstanceExists($childID)) { $this->WriteChildValues($childID, $state, $counter['PricePerKWh']); } return true; } finally { $this->LeaveLock(); } } private function ResetEnergy(string $field) { // Vor dem Reset wird ein möglicherweise noch nicht verarbeiteter Anstieg // übernommen. Der externe Zählerstand selbst bleibt stets unverändert. $this->UpdateValues(); if (!$this->EnterLock()) { return; } try { $states = $this->ReadJsonAttribute('CounterState', []); $children = $this->ReadJsonAttribute('CounterChildren', []); foreach ($this->GetCounters() as $counter) { $key = $counter['Key']; $state = $this->NormalizeState($states[$key] ?? [], date('Y-m-d'), date('Y-m')); $state[$field] = 0.0; $states[$key] = $state; $childID = isset($children[$key]) ? (int) $children[$key] : 0; if ($childID > 0 && IPS_InstanceExists($childID)) { $this->WriteChildValues($childID, $state, $counter['PricePerKWh']); } } $this->WriteAttributeString('CounterState', json_encode($states)); } finally { $this->LeaveLock(); } } private function UpdateSourceMessages() { $previousSources = $this->ReadJsonAttribute('RegisteredSourceIDs', []); foreach ($previousSources as $sourceID) { if (IPS_VariableExists((int) $sourceID)) { $this->UnregisterMessage((int) $sourceID, VM_UPDATE); } } $sources = []; foreach ($this->GetCounters() as $counter) { $sourceID = $counter['VariableID']; if (IPS_VariableExists($sourceID) && !in_array($sourceID, $sources, true)) { $this->RegisterMessage($sourceID, VM_UPDATE); $sources[] = $sourceID; } } $this->WriteAttributeString('RegisteredSourceIDs', json_encode($sources)); } private function GetCounters(): array { $configuredCounters = json_decode($this->ReadPropertyString('Counters'), true); if (!is_array($configuredCounters)) { return []; } $counters = []; $usedSources = []; foreach ($configuredCounters as $configuredCounter) { if (!is_array($configuredCounter)) { continue; } // Die englischen Konfigurationsschlüssel sind die dauerhaften // Schnittstellennamen. Die Fallbacks halten bereits angelegte // Instanzen mit dem Formular der ersten Version funktionsfähig. $name = trim((string) ($configuredCounter['CounterName'] ?? $configuredCounter['Name'] ?? '')); $sourceID = (int) ($configuredCounter['SourceVariableID'] ?? $configuredCounter['VariableID'] ?? 0); if ($name === '' || $sourceID <= 0) { continue; } if (in_array($sourceID, $usedSources, true)) { $this->Log('Zähler "' . $name . '": dieselbe Quellvariable wurde mehrfach konfiguriert und wird nur einmal verwendet.'); continue; } $usedSources[] = $sourceID; $globalPrice = max(0.0, $this->ReadPropertyFloat('GlobalPricePerKWh')); // Der globale Tarif ist der Standard. Ein Zeilentarif ist nur dann // wirksam, wenn er ausdrücklich über den Schalter aktiviert wurde. $hasOwnTariff = (bool) ($configuredCounter['UseOwnTariff'] ?? false); $price = $hasOwnTariff ? max(0.0, (float) ($configuredCounter['PricePerKWh'] ?? 0)) : $globalPrice; $counters[] = [ // Die Quellvariable ist der stabile Schlüssel. Ein Umbenennen des // Zählers erhält damit die Childinstanz und ihre Historie. 'Key' => 'counter_' . $sourceID, 'Name' => $name, 'VariableID' => $sourceID, 'PricePerKWh' => $price ]; } return $counters; } private function NormalizeState(array $state, string $today, string $month): array { $normalized = [ 'initialized' => (bool) ($state['initialized'] ?? false), 'lastRaw' => (float) ($state['lastRaw'] ?? 0), 'totalEnergy' => max(0.0, (float) ($state['totalEnergy'] ?? 0)), 'dayEnergy' => max(0.0, (float) ($state['dayEnergy'] ?? 0)), 'monthEnergy' => max(0.0, (float) ($state['monthEnergy'] ?? 0)), 'dayStamp' => (string) ($state['dayStamp'] ?? $today), 'monthStamp' => (string) ($state['monthStamp'] ?? $month) ]; if ($normalized['dayStamp'] !== $today) { $normalized['dayEnergy'] = 0.0; $normalized['dayStamp'] = $today; } if ($normalized['monthStamp'] !== $month) { $normalized['monthEnergy'] = 0.0; $normalized['monthStamp'] = $month; } return $normalized; } private function WriteChildValues(int $childID, array $state, float $pricePerKWh) { $values = [ 'TotalEnergy' => $state['totalEnergy'], 'TotalCost' => $state['totalEnergy'] * $pricePerKWh, 'DayEnergy' => $state['dayEnergy'], 'DayCost' => $state['dayEnergy'] * $pricePerKWh, 'MonthEnergy' => $state['monthEnergy'], 'MonthCost' => $state['monthEnergy'] * $pricePerKWh ]; foreach ($values as $ident => $value) { $variableID = @IPS_GetObjectIDByIdent($ident, $childID); if ($variableID !== false && IPS_VariableExists($variableID)) { SetValue($variableID, round((float) $value, 4)); } } } private function FindManagedChild(int $categoryID, string $key): int { $childID = @IPS_GetObjectIDByIdent($key, $categoryID); return ($childID !== false && $this->IsManagedChild($childID)) ? $childID : 0; } private function IsManagedChild(int $childID): bool { if (!IPS_InstanceExists($childID)) { return false; } $instance = IPS_GetInstance($childID); return ($instance['ModuleInfo']['ModuleID'] ?? '') === self::CHILD_MODULE_ID; } private function ConfigureChild(int $childID, string $key, int $sourceVariableID) { $configuration = json_decode(IPS_GetConfiguration($childID), true); if (!is_array($configuration)) { $configuration = []; } $configuration['ParentInstanceID'] = $this->InstanceID; $configuration['CounterKey'] = $key; $configuration['SourceVariableID'] = $sourceVariableID; IPS_SetConfiguration($childID, json_encode($configuration)); IPS_ApplyChanges($childID); } private function ReadJsonAttribute(string $name, array $default): array { $value = json_decode($this->ReadAttributeString($name), true); return is_array($value) ? $value : $default; } private function EnterLock(): bool { return IPS_SemaphoreEnter('EnergyCounterMain_' . $this->InstanceID, 1000); } private function LeaveLock() { IPS_SemaphoreLeave('EnergyCounterMain_' . $this->InstanceID); } private function Log(string $message) { IPS_LogMessage('EnergyCounterMain', $message); } }