initial commit
This commit is contained in:
commit
faa518ccd8
10 files changed
+704
No files matched your search
@@ -0,0 +1,106 @@
|
||||
{
|
||||
"elements": [
|
||||
{
|
||||
"type": "SelectCategory",
|
||||
"name": "TargetCategoryID",
|
||||
"caption": "Category for counter child instances"
|
||||
},
|
||||
{
|
||||
"type": "NumberSpinner",
|
||||
"name": "GlobalPricePerKWh",
|
||||
"caption": "Global electricity tariff per kWh (€)",
|
||||
"digits": 4
|
||||
},
|
||||
{
|
||||
"type": "List",
|
||||
"name": "Counters",
|
||||
"caption": "Counters (meter values must be cumulative kWh values)",
|
||||
"rowCount": 6,
|
||||
"add": true,
|
||||
"delete": true,
|
||||
"columns": [
|
||||
{
|
||||
"caption": "Counter name",
|
||||
"name": "CounterName",
|
||||
"width": "250px",
|
||||
"add": "New counter",
|
||||
"edit": {
|
||||
"type": "ValidationTextBox"
|
||||
}
|
||||
},
|
||||
{
|
||||
"caption": "Meter value variable",
|
||||
"name": "SourceVariableID",
|
||||
"width": "300px",
|
||||
"add": 0,
|
||||
"edit": {
|
||||
"type": "SelectVariable",
|
||||
"validVariableTypes": [1, 2]
|
||||
}
|
||||
},
|
||||
{
|
||||
"caption": "Use custom tariff",
|
||||
"name": "UseOwnTariff",
|
||||
"width": "170px",
|
||||
"add": false,
|
||||
"edit": {
|
||||
"type": "CheckBox"
|
||||
}
|
||||
},
|
||||
{
|
||||
"caption": "Custom tariff per kWh (€)",
|
||||
"name": "PricePerKWh",
|
||||
"width": "150px",
|
||||
"add": 0,
|
||||
"edit": {
|
||||
"type": "NumberSpinner",
|
||||
"digits": 4
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"type": "Label",
|
||||
"caption": "Unless a custom tariff is enabled, the counter uses the global electricity tariff. Meter values are evaluated continuously; daily and monthly values reset automatically. Manual resets affect calculated values only, never the source variable."
|
||||
}
|
||||
],
|
||||
"actions": [
|
||||
{
|
||||
"type": "Button",
|
||||
"caption": "Synchronize child instances",
|
||||
"onClick": "ECM_SynchronizeChildren($id);"
|
||||
},
|
||||
{
|
||||
"type": "Button",
|
||||
"caption": "Update values now",
|
||||
"onClick": "ECM_UpdateValues($id);"
|
||||
},
|
||||
{
|
||||
"type": "Button",
|
||||
"caption": "Reset total values",
|
||||
"onClick": "ECM_ResetTotalEnergy($id);"
|
||||
},
|
||||
{
|
||||
"type": "Button",
|
||||
"caption": "Reset daily values",
|
||||
"onClick": "ECM_ResetDayEnergy($id);"
|
||||
},
|
||||
{
|
||||
"type": "Button",
|
||||
"caption": "Reset monthly values",
|
||||
"onClick": "ECM_ResetMonthEnergy($id);"
|
||||
}
|
||||
],
|
||||
"status": [
|
||||
{
|
||||
"code": 102,
|
||||
"icon": "active",
|
||||
"caption": "Active"
|
||||
},
|
||||
{
|
||||
"code": 201,
|
||||
"icon": "error",
|
||||
"caption": "Category missing or invalid"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
{
|
||||
"translations": {
|
||||
"de": {
|
||||
"Energy Counter Evaluation": "Energiezähler Auswertung",
|
||||
"Category for counter child instances": "Kategorie für die Zähler-Childinstanzen",
|
||||
"Global electricity tariff per kWh (€)": "Globaler Stromtarif je kWh (€)",
|
||||
"Counters (meter values must be cumulative kWh values)": "Zähler (Zählerstände müssen kumulierte kWh-Werte sein)",
|
||||
"Counter name": "Name des Zählers",
|
||||
"New counter": "Neuer Zähler",
|
||||
"Meter value variable": "Zählerstand-Variable",
|
||||
"Use custom tariff": "Eigener Tarif verwenden",
|
||||
"Custom tariff per kWh (€)": "Eigener Tarif je kWh (€)",
|
||||
"Unless a custom tariff is enabled, the counter uses the global electricity tariff. Meter values are evaluated continuously; daily and monthly values reset automatically. Manual resets affect calculated values only, never the source variable.": "Ist kein eigener Tarif aktiviert, verwendet der Zähler den globalen Stromtarif. Der Zählerstand wird fortlaufend ausgewertet; Tages- und Monatswerte werden automatisch zurückgesetzt. Manuelle Resets wirken nur auf die berechneten Werte, nie auf die Quellvariable.",
|
||||
"Synchronize child instances": "Childinstanzen synchronisieren",
|
||||
"Update values now": "Werte jetzt aktualisieren",
|
||||
"Reset total values": "Gesamtwerte zurücksetzen",
|
||||
"Reset daily values": "Tageswerte zurücksetzen",
|
||||
"Reset monthly values": "Monatswerte zurücksetzen",
|
||||
"Active": "Aktiv",
|
||||
"Category missing or invalid": "Kategorie fehlt oder ist ungültig"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"id": "{3BEE9E77-1A50-4D12-99B8-E3547443882E}",
|
||||
"name": "EnergyCounterMain",
|
||||
"type": 3,
|
||||
"vendor": "J.H. Artworks",
|
||||
"aliases": [
|
||||
"Energy Counter Evaluation"
|
||||
],
|
||||
"url": "https://jh-artworks.com",
|
||||
"parentRequirements": [],
|
||||
"childRequirements": [],
|
||||
"implemented": [],
|
||||
"prefix": "ECM"
|
||||
}
|
||||
@@ -0,0 +1,368 @@
|
||||
<?php
|
||||
|
||||
class EnergyCounterMain extends IPSModule
|
||||
{
|
||||
private const CHILD_MODULE_ID = '{C96F6499-8F3E-4EBF-AF8D-2C45E989D2F6}';
|
||||
|
||||
public function Create()
|
||||
{
|
||||
parent::Create();
|
||||
|
||||
$this->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);
|
||||
$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');
|
||||
}
|
||||
|
||||
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)
|
||||
{
|
||||
$configuration = json_decode(IPS_GetConfiguration($childID), true);
|
||||
if (!is_array($configuration)) {
|
||||
$configuration = [];
|
||||
}
|
||||
$configuration['ParentInstanceID'] = $this->InstanceID;
|
||||
$configuration['CounterKey'] = $key;
|
||||
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);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user