fix: refactor MQTT handling and improve counter data extraction logic in CounterClient

This commit is contained in:
jhartworks
2026-04-16 16:03:34 +02:00
parent ce5292fe17
commit 75d9e77126
+116 -271
View File
@@ -50,8 +50,6 @@ class CounterClient extends IPSModule
if ($mqttClientId > 0 && IPS_InstanceExists($mqttClientId) && $mqttTopic !== '') { if ($mqttClientId > 0 && IPS_InstanceExists($mqttClientId) && $mqttTopic !== '') {
$this->MqttPublish($mqttClientId, $mqttTopic, $json, true); $this->MqttPublish($mqttClientId, $mqttTopic, $json, true);
} else {
IPS_LogMessage('CounterClient', 'MQTT ist aktiviert, aber ungültige MQTT Client ID oder Topic.');
} }
} }
} }
@@ -64,346 +62,213 @@ class CounterClient extends IPSModule
return ''; return '';
} }
$counterIds = IPS_GetChildrenIDs($counterCategoryId);
$payload = [ $payload = [
'timestamp' => date('Y-m-d H:i:s'), 'timestamp' => date('Y-m-d H:i:s'),
'counters' => [] 'counters' => []
]; ];
foreach ($counterIds as $counterObjectId) { $counterFolders = IPS_GetChildrenIDs($counterCategoryId);
if (!IPS_ObjectExists($counterObjectId)) {
foreach ($counterFolders as $counterFolderId) {
if (!IPS_ObjectExists($counterFolderId)) {
continue; continue;
} }
$obj = IPS_GetObject($counterObjectId); $obj = IPS_GetObject($counterFolderId);
if ((int)$obj['ObjectType'] !== 0) { if ((int)$obj['ObjectType'] !== 0) {
continue; continue;
} }
$counterName = IPS_GetName($counterObjectId); $counterName = IPS_GetName($counterFolderId);
$counterId = $this->makeSlug($counterName); $counterId = $this->makeSlug($counterName);
$entries = $this->CollectVariablesRecursive($counterObjectId, [], []);
IPS_LogMessage('CounterClient', 'Counter "' . $counterName . '" -> gefundene Variablen: ' . count($entries));
if (count($entries) === 0) {
continue;
}
$counterData = [ $counterData = [
'id' => $counterId, 'id' => $counterId,
'name' => $counterName 'name' => $counterName
]; ];
$tempSlots = []; $found = 0;
$pressureSlots = []; $children = IPS_GetChildrenIDs($counterFolderId);
$recognizedCount = 0;
foreach ($entries as $entry) { foreach ($children as $childId) {
$classified = $this->ClassifyEntry($entry); if (!IPS_ObjectExists($childId)) {
if ($classified === null) {
IPS_LogMessage('CounterClient', 'Ignoriert: ' . $entry['context']);
continue; continue;
} }
$recognizedCount++; if (IPS_LinkExists($childId)) {
$link = IPS_GetLink($childId);
$targetId = (int)$link['TargetID'];
$linkName = IPS_GetName($childId);
$field = $classified['field']; if ($targetId <= 0 || !IPS_ObjectExists($targetId)) {
$value = $classified['value'];
$unit = $classified['unit'];
IPS_LogMessage('CounterClient', 'Erkannt: ' . $entry['context'] . ' => ' . $field . ' = ' . $value . ' [' . $unit . ']');
if ($field === 'temperature_auto') {
$tempSlots[] = $classified;
continue; continue;
} }
if ($field === 'pressure_auto') { if (IPS_VariableExists($targetId)) {
$pressureSlots[] = $classified; if ($this->addVariableToCounter($counterData, $targetId, $counterName . ' ' . $linkName)) {
$found++;
}
} else {
$subChildren = IPS_GetChildrenIDs($targetId);
foreach ($subChildren as $subChildId) {
if (IPS_VariableExists($subChildId)) {
if ($this->addVariableToCounter($counterData, $subChildId, $counterName . ' ' . $linkName . ' ' . IPS_GetName($targetId))) {
$found++;
}
}
}
}
continue; continue;
} }
$counterData[$field] = $value; if (IPS_VariableExists($childId)) {
if ($this->addVariableToCounter($counterData, $childId, $counterName)) {
$found++;
}
continue;
}
if ($field === 'total_value' && !isset($counterData['unit']) && $unit !== '') { $subChildren = IPS_GetChildrenIDs($childId);
$counterData['unit'] = $unit; foreach ($subChildren as $subChildId) {
if (IPS_VariableExists($subChildId)) {
if ($this->addVariableToCounter($counterData, $subChildId, $counterName . ' ' . IPS_GetName($childId))) {
$found++;
}
}
} }
} }
$this->assignInOutValues($counterData, $tempSlots, 'temperature_in_value', 'temperature_out_value'); $counterData['type'] = $this->DetectCounterType($counterData, $counterName);
$this->assignInOutValues($counterData, $pressureSlots, 'pressure_in_value', 'pressure_out_value');
$contextString = mb_strtolower($counterName);
foreach ($entries as $entry) {
$contextString .= ' ' . $entry['context'];
}
$counterData['type'] = $this->DetectCounterType($counterData, $contextString);
if (!isset($counterData['unit'])) { if (!isset($counterData['unit'])) {
$counterData['unit'] = $this->inferDefaultUnit($counterData); $counterData['unit'] = $this->inferDefaultUnit($counterData);
} }
if ($recognizedCount > 0) { if ($found > 0) {
$payload['counters'][] = $counterData; $payload['counters'][] = $counterData;
} else { } else {
IPS_LogMessage('CounterClient', 'Counter ohne erkannte Messwerte: ' . $counterName); IPS_LogMessage('CounterClient', 'Counter ohne erkannte Messwerte übersprungen: ' . $counterName);
} }
} }
return json_encode($payload, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); return json_encode($payload, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
} }
private function CollectVariablesRecursive(int $objectId, array $path, array $visited): array private function addVariableToCounter(array &$counterData, int $varId, string $contextPrefix): bool
{ {
$result = [];
if (isset($visited[$objectId])) {
return $result;
}
$visited[$objectId] = true;
if (!IPS_ObjectExists($objectId)) {
return $result;
}
if (IPS_LinkExists($objectId)) {
$link = IPS_GetLink($objectId);
$targetId = (int)$link['TargetID'];
$linkName = IPS_GetName($objectId);
if ($targetId > 0 && IPS_ObjectExists($targetId)) {
$newPath = $path;
if ($linkName !== '') {
$newPath[] = $linkName;
}
return $this->CollectVariablesRecursive($targetId, $newPath, $visited);
}
return $result;
}
if (IPS_VariableExists($objectId)) {
$varName = IPS_GetName($objectId);
$parts = $path;
if (count($parts) === 0 || end($parts) !== $varName) {
$parts[] = $varName;
}
$result[] = [
'varId' => $objectId,
'context' => implode(' ', $parts)
];
return $result;
}
$obj = IPS_GetObject($objectId);
$objName = IPS_GetName($objectId);
$newPath = $path;
if ($objName !== '') {
$newPath[] = $objName;
}
$children = IPS_GetChildrenIDs($objectId);
foreach ($children as $childId) {
$sub = $this->CollectVariablesRecursive($childId, $newPath, $visited);
foreach ($sub as $entry) {
$result[] = $entry;
}
}
return $result;
}
private function ClassifyEntry(array $entry): ?array
{
$varId = (int)$entry['varId'];
if (!IPS_VariableExists($varId)) { if (!IPS_VariableExists($varId)) {
return null; return false;
} }
$var = IPS_GetVariable($varId); $var = IPS_GetVariable($varId);
$type = (int)$var['VariableType']; $type = (int)$var['VariableType'];
if ($type !== 1 && $type !== 2) { if ($type !== 1 && $type !== 2) {
return null; return false;
} }
$value = GetValue($varId); $value = GetValue($varId);
if (!is_numeric($value)) { if (!is_numeric($value)) {
return null; return false;
} }
$value = round((float)$value, 3); $value = round((float)$value, 3);
$context = mb_strtolower($entry['context']);
$unit = $this->extractUnitFromVariable($varId, $var, $value);
if ($unit === '') {
IPS_LogMessage('CounterClient', 'Variable ohne erkennbare Einheit ignoriert: ' . $context);
return null;
}
$varName = IPS_GetName($varId);
$context = mb_strtolower(trim($contextPrefix . ' ' . $varName));
$unit = $this->getVariableUnit($varId, $var, $value);
$unitNorm = $this->normalizeUnit($unit); $unitNorm = $this->normalizeUnit($unit);
if ($unitNorm === '') {
IPS_LogMessage('CounterClient', 'Keine Einheit erkannt: ' . $context);
return false;
}
if ($this->isTotalUnit($unitNorm, $context)) { if ($this->isTotalUnit($unitNorm, $context)) {
return [ $counterData['total_value'] = $value;
'field' => 'total_value', if (!isset($counterData['unit'])) {
'value' => $value, $counterData['unit'] = $this->formatOutputUnit($unitNorm);
'unit' => $this->formatOutputUnit($unitNorm), }
'name' => $context return true;
];
} }
if ($this->isPowerUnit($unitNorm, $context)) { if ($this->isPowerUnit($unitNorm, $context)) {
return [ $counterData['power_value'] = $value;
'field' => 'power_value', return true;
'value' => $value,
'unit' => $unitNorm,
'name' => $context
];
} }
if ($this->isFlowUnit($unitNorm, $context)) { if ($this->isFlowUnit($unitNorm, $context)) {
return [ $counterData['flow_value'] = $value;
'field' => 'flow_value', return true;
'value' => $value,
'unit' => $unitNorm,
'name' => $context
];
} }
if ($unitNorm === 'a') { if ($unitNorm === 'a') {
return [ $counterData['current_value'] = $value;
'field' => 'current_value', return true;
'value' => $value,
'unit' => $unitNorm,
'name' => $context
];
} }
if ($unitNorm === 'v') { if ($unitNorm === 'v') {
return [ $counterData['voltage_value'] = $value;
'field' => 'voltage_value', return true;
'value' => $value,
'unit' => $unitNorm,
'name' => $context
];
} }
if ($unitNorm === 'hz') { if ($unitNorm === 'hz') {
return [ $counterData['frequency_value'] = $value;
'field' => 'frequency_value', return true;
'value' => $value,
'unit' => $unitNorm,
'name' => $context
];
} }
if (in_array($unitNorm, ['bar', 'mbar', 'pa'], true)) { if (in_array($unitNorm, ['bar', 'mbar', 'pa'], true)) {
if ($this->looksLikeIn($context)) {
return [
'field' => 'pressure_in_value',
'value' => $value,
'unit' => $unitNorm,
'name' => $context
];
}
if ($this->looksLikeOut($context)) { if ($this->looksLikeOut($context)) {
return [ $counterData['pressure_out_value'] = $value;
'field' => 'pressure_out_value', } else {
'value' => $value, $counterData['pressure_in_value'] = $value;
'unit' => $unitNorm,
'name' => $context
];
} }
return true;
return [
'field' => 'pressure_auto',
'value' => $value,
'unit' => $unitNorm,
'name' => $context
];
} }
if (in_array($unitNorm, ['°c', 'c', 'k'], true)) { if (in_array($unitNorm, ['°c', 'c', 'k'], true)) {
if ($this->looksLikeIn($context)) {
return [
'field' => 'temperature_in_value',
'value' => $value,
'unit' => $unitNorm,
'name' => $context
];
}
if ($this->looksLikeOut($context)) { if ($this->looksLikeOut($context)) {
return [ $counterData['temperature_out_value'] = $value;
'field' => 'temperature_out_value', } else {
'value' => $value, $counterData['temperature_in_value'] = $value;
'unit' => $unitNorm,
'name' => $context
];
} }
return true;
return [
'field' => 'temperature_auto',
'value' => $value,
'unit' => $unitNorm,
'name' => $context
];
} }
if ($unitNorm === 'cos' || $unitNorm === 'cosphi' || $unitNorm === 'pf') { if ($unitNorm === 'cos' || $unitNorm === 'cosphi' || $unitNorm === 'pf') {
return [ $counterData['power_factor'] = $value;
'field' => 'power_factor', return true;
'value' => $value,
'unit' => $unitNorm,
'name' => $context
];
} }
IPS_LogMessage('CounterClient', 'Nicht erkannt: ' . $context . ' | Unit: ' . $unitNorm); IPS_LogMessage('CounterClient', 'Nicht zugeordnet: ' . $context . ' | Einheit: ' . $unitNorm . ' | Wert: ' . $value);
return null; return false;
} }
private function assignInOutValues(array &$counterData, array $items, string $fieldIn, string $fieldOut): void
private function getVariableUnit(int $varId, array $var, float $value): string
{ {
foreach ($items as $item) { if (function_exists('IPS_GetPresentation')) {
if ($this->looksLikeIn($item['name']) && !isset($counterData[$fieldIn])) { try {
$counterData[$fieldIn] = $item['value']; $presentation = @IPS_GetPresentation($varId);
continue; if (is_array($presentation)) {
if (isset($presentation['Suffix']) && trim((string)$presentation['Suffix']) !== '') {
return trim((string)$presentation['Suffix']);
} }
if (isset($presentation['Prefix']) && trim((string)$presentation['Prefix']) !== '') {
if ($this->looksLikeOut($item['name']) && !isset($counterData[$fieldOut])) { return trim((string)$presentation['Prefix']);
$counterData[$fieldOut] = $item['value']; }
continue; if (isset($presentation['Unit']) && trim((string)$presentation['Unit']) !== '') {
return trim((string)$presentation['Unit']);
}
}
} catch (\Throwable $e) {
} }
} }
foreach ($items as $item) {
if (!isset($counterData[$fieldIn])) {
$counterData[$fieldIn] = $item['value'];
continue;
}
if (!isset($counterData[$fieldOut])) {
$counterData[$fieldOut] = $item['value'];
continue;
}
}
}
private function extractUnitFromVariable(int $varId, array $var, float $value): string
{
$profileName = ''; $profileName = '';
if (isset($var['VariableCustomProfile']) && $var['VariableCustomProfile'] !== '') {
if ($var['VariableCustomProfile'] !== '') {
$profileName = $var['VariableCustomProfile']; $profileName = $var['VariableCustomProfile'];
} elseif ($var['VariableProfile'] !== '') { } elseif (isset($var['VariableProfile']) && $var['VariableProfile'] !== '') {
$profileName = $var['VariableProfile']; $profileName = $var['VariableProfile'];
} }
@@ -412,37 +277,33 @@ private function ClassifyEntry(array $entry): ?array
$suffix = trim((string)$profile['Suffix']); $suffix = trim((string)$profile['Suffix']);
$prefix = trim((string)$profile['Prefix']); $prefix = trim((string)$profile['Prefix']);
$unit = trim($prefix . ' ' . $suffix); $unit = trim($prefix . ' ' . $suffix);
if ($unit !== '') { if ($unit !== '') {
return $unit; return $unit;
} }
} }
$formatted = GetValueFormatted($varId); $formatted = GetValueFormatted($varId);
$unitFromFormatted = $this->extractUnitFromFormattedValue($formatted, $value); return $this->extractUnitFromFormattedValue($formatted, $value);
if ($unitFromFormatted !== '') {
return $unitFromFormatted;
} }
return '';
}
private function extractUnitFromFormattedValue(string $formatted, float $value): string private function extractUnitFromFormattedValue(string $formatted, float $value): string
{ {
$formatted = trim($formatted); $formatted = trim($formatted);
if ($formatted === '') { if ($formatted === '') {
return ''; return '';
} }
$valueStr1 = number_format($value, 2, ',', '.'); $search = [
$valueStr2 = number_format($value, 3, ',', '.'); number_format($value, 0, ',', '.'),
$valueStr3 = str_replace('.', ',', (string)$value); number_format($value, 1, ',', '.'),
$valueStr4 = str_replace(',', '.', (string)$value); number_format($value, 2, ',', '.'),
number_format($value, 3, ',', '.'),
str_replace('.', ',', (string)$value),
str_replace(',', '.', (string)$value),
(string)$value
];
$unit = $formatted; $unit = $formatted;
$search = [$valueStr1, $valueStr2, $valueStr3, $valueStr4];
foreach ($search as $needle) { foreach ($search as $needle) {
if ($needle !== '') { if ($needle !== '') {
$unit = str_replace($needle, '', $unit); $unit = str_replace($needle, '', $unit);
@@ -450,12 +311,10 @@ private function ClassifyEntry(array $entry): ?array
} }
$unit = trim($unit); $unit = trim($unit);
$unit = preg_replace('/^[\-\+\d\.,\s]+/u', '', $unit); $unit = preg_replace('/^[\-\+\d\.,\s]+/u', '', $unit);
$unit = trim($unit); return trim($unit);
return $unit;
} }
private function DetectCounterType(array $counterData, string $context): string private function DetectCounterType(array $counterData, string $context): string
{ {
$unit = isset($counterData['unit']) ? $this->normalizeUnit((string)$counterData['unit']) : ''; $unit = isset($counterData['unit']) ? $this->normalizeUnit((string)$counterData['unit']) : '';
@@ -608,20 +467,6 @@ private function ClassifyEntry(array $entry): ?array
return $text; return $text;
} }
private function buildContextString(array $pathParts, string $varName): string
{
$parts = $pathParts;
if ($varName !== '') {
$parts[] = $varName;
}
$parts = array_values(array_filter($parts, function ($v) {
return trim((string)$v) !== '';
}));
return implode(' ', $parts);
}
public function MqttPublish($server_id, $topic, $payload, $retain) public function MqttPublish($server_id, $topic, $payload, $retain)
{ {
if (!IPS_InstanceExists($server_id)) { if (!IPS_InstanceExists($server_id)) {