Compare commits

...
10 Commits
Author SHA1 Message Date
jhartworks ffab78281a Refactor CounterClient to CounterServer with improved payload handling and measurement storage
- Renamed class from CounterClient to CounterServer for clarity.
- Updated properties to include Connector and SourceJSON.
- Removed MQTT-related properties and methods.
- Implemented checkTable method to handle JSON input and database operations.
- Added logic for inserting/updating meter devices and measurements in the database.
- Simplified unit handling and removed unused methods.
- Enhanced logging for better debugging and error tracking.
2026-04-16 16:06:53 +02:00
jhartworks 75d9e77126 fix: refactor MQTT handling and improve counter data extraction logic in CounterClient 2026-04-16 16:03:34 +02:00
jhartworks ce5292fe17 fix: enhance variable context handling and improve unit extraction logic in ClassifyEntry method 2026-04-16 15:54:34 +02:00
jhartworks 3c3ad7efc1 fix: refactor CounterServer to CounterClient and update property registrations for improved functionality 2026-04-16 15:49:14 +02:00
jhartworks d85e01ca16 fix: refactor MQTT topic generation and enhance variable classification logic 2026-04-16 15:41:39 +02:00
jhartworks 9702a88cb3 fix: enhance variable naming logic and update build number in library.json 2026-04-16 15:21:30 +02:00
jhartworks 82f2fdc54c fix: update timer registration to use correct function call and increment build number 2026-04-16 14:25:00 +02:00
jhartworks 89ec935d04 fix: remove ProjectIdPortal field from form configuration 2026-04-16 14:20:10 +02:00
jhartworks cdcff3ba1d fix: change Projectname field type to ValidationTextBox for improved validation 2026-04-16 14:19:29 +02:00
jhartworks 16cf2c8468 fix: add Projectname and ProjectIdPortal properties to module and form configuration 2026-04-16 14:18:27 +02:00
4 changed files with 289 additions and 265 deletions
+278 -260
View File
@@ -12,10 +12,10 @@ class CounterClient extends IPSModule
$this->RegisterPropertyBoolean('EnableMQTT', false); $this->RegisterPropertyBoolean('EnableMQTT', false);
$this->RegisterPropertyInteger('MqttClientID', 0); $this->RegisterPropertyInteger('MqttClientID', 0);
$this->RegisterPropertyString('Projectname', ''); $this->RegisterPropertyString('Projectname', '');
$this->RegisterPropertyInteger('Projectyear', 2026); $this->RegisterPropertyInteger('Projectyear', 2026);
$this->RegisterPropertyInteger('Projectnumber', 0); $this->RegisterPropertyInteger('Projectnumber', 0);
$this->RegisterTimer('Update', 0, 'SECC_BuildAndStorePayload('.$this->InstanceID.');'); $this->RegisterTimer('Update', 0, 'SECC_BuildAndStorePayload(' . $this->InstanceID . ');');
} }
public function ApplyChanges() public function ApplyChanges()
@@ -46,12 +46,10 @@ class CounterClient extends IPSModule
if ($this->ReadPropertyBoolean('EnableMQTT')) { if ($this->ReadPropertyBoolean('EnableMQTT')) {
$mqttClientId = $this->ReadPropertyInteger('MqttClientID'); $mqttClientId = $this->ReadPropertyInteger('MqttClientID');
$mqttTopic = 'Projekte'.$this->ReadPropertyInteger('Projectyear').'/P'.$this->ReadPropertyInteger('Projectnumber').'/Counters'; $mqttTopic = 'Projekte' . $this->ReadPropertyInteger('Projectyear') . '/P' . $this->ReadPropertyInteger('Projectnumber') . '/Counters';
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,367 +62,393 @@ 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);
$obj = IPS_GetObject($counterObjectId);
if ($obj['ObjectType'] != 0) { foreach ($counterFolders as $counterFolderId) {
if (!IPS_ObjectExists($counterFolderId)) {
continue; continue;
} }
$counterName = IPS_GetName($counterObjectId); $obj = IPS_GetObject($counterFolderId);
if ((int)$obj['ObjectType'] !== 0) {
continue;
}
$counterName = IPS_GetName($counterFolderId);
$counterId = $this->makeSlug($counterName); $counterId = $this->makeSlug($counterName);
$varIds = $this->CollectVariablesRecursive($counterObjectId);
if (count($varIds) === 0) {
continue;
}
$counterData = [ $counterData = [
'id' => $counterId, 'id' => $counterId,
'name' => $counterName 'name' => $counterName
]; ];
$tempSlots = []; $found = 0;
$pressureSlots = []; $children = IPS_GetChildrenIDs($counterFolderId);
foreach ($varIds as $varId) { foreach ($children as $childId) {
$classified = $this->ClassifyVariable($varId); if (!IPS_ObjectExists($childId)) {
if ($classified === null) {
continue; continue;
} }
$field = $classified['field']; if (IPS_LinkExists($childId)) {
$value = $classified['value']; $link = IPS_GetLink($childId);
$unit = $classified['unit']; $targetId = (int)$link['TargetID'];
$linkName = IPS_GetName($childId);
if ($targetId <= 0 || !IPS_ObjectExists($targetId)) {
continue;
}
if (IPS_VariableExists($targetId)) {
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++;
}
}
}
}
if ($field === 'temperature_auto') {
$tempSlots[] = $classified;
continue; continue;
} }
if ($field === 'pressure_auto') { if (IPS_VariableExists($childId)) {
$pressureSlots[] = $classified; if ($this->addVariableToCounter($counterData, $childId, $counterName)) {
$found++;
}
continue; continue;
} }
$counterData[$field] = $value; $subChildren = IPS_GetChildrenIDs($childId);
foreach ($subChildren as $subChildId) {
if ($field === 'total_value' && !isset($counterData['unit']) && $unit !== '') { if (IPS_VariableExists($subChildId)) {
$counterData['unit'] = $unit; 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');
$counterData['type'] = $this->DetectCounterType($counterData);
if (!isset($counterData['unit'])) { if (!isset($counterData['unit'])) {
$counterData['unit'] = $this->inferDefaultUnit($counterData); $counterData['unit'] = $this->inferDefaultUnit($counterData);
} }
if (count($counterData) > 3) { if ($found > 0) {
$payload['counters'][] = $counterData; $payload['counters'][] = $counterData;
} else {
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 private function addVariableToCounter(array &$counterData, int $varId, string $contextPrefix): bool
{
$result = [];
$children = IPS_GetChildrenIDs($objectId);
foreach ($children as $childId) {
if (IPS_LinkExists($childId)) {
$link = IPS_GetLink($childId);
$targetId = (int) $link['TargetID'];
if (IPS_VariableExists($targetId)) {
$result[$targetId] = $targetId;
} elseif (IPS_ObjectExists($targetId)) {
foreach ($this->CollectVariablesRecursive($targetId) as $subVarId) {
$result[$subVarId] = $subVarId;
}
}
continue;
}
if (IPS_VariableExists($childId)) {
$result[$childId] = $childId;
continue;
}
if (IPS_ObjectExists($childId)) {
foreach ($this->CollectVariablesRecursive($childId) as $subVarId) {
$result[$subVarId] = $subVarId;
}
}
}
return array_values($result);
}
private function ClassifyVariable(int $varId): ?array
{ {
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;
}
$profileName = '';
if ($var['VariableCustomProfile'] !== '') {
$profileName = $var['VariableCustomProfile'];
} elseif ($var['VariableProfile'] !== '') {
$profileName = $var['VariableProfile'];
}
if ($profileName === '' || !IPS_VariableProfileExists($profileName)) {
return null;
}
$profile = IPS_GetVariableProfile($profileName);
$suffix = trim((string) $profile['Suffix']);
$prefix = trim((string) $profile['Prefix']);
$unit = trim($prefix . ' ' . $suffix);
if ($unit === '') {
return null;
} }
$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);
$varName = mb_strtolower(IPS_GetName($varId));
$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 (in_array($unitNorm, ['kwh', 'wh', 'mwh', 'm3', 'l'], true)) { if ($unitNorm === '') {
return [ IPS_LogMessage('CounterClient', 'Keine Einheit erkannt: ' . $context);
'field' => 'total_value', return false;
'value' => $value,
'unit' => $suffix !== '' ? trim($suffix) : $unitNorm,
'name' => $varName
];
} }
if (in_array($unitNorm, ['kw', 'w', 'mw'], true)) { if ($this->isTotalUnit($unitNorm, $context)) {
return [ $counterData['total_value'] = $value;
'field' => 'power_value', if (!isset($counterData['unit'])) {
'value' => $value, $counterData['unit'] = $this->formatOutputUnit($unitNorm);
'unit' => $unitNorm, }
'name' => $varName return true;
];
} }
if (in_array($unitNorm, ['m3/h', 'l/h', 'l/min'], true)) { if ($this->isPowerUnit($unitNorm, $context)) {
return [ $counterData['power_value'] = $value;
'field' => 'flow_value', return true;
'value' => $value, }
'unit' => $unitNorm,
'name' => $varName if ($this->isFlowUnit($unitNorm, $context)) {
]; $counterData['flow_value'] = $value;
return true;
} }
if ($unitNorm === 'a') { if ($unitNorm === 'a') {
return [ $counterData['current_value'] = $value;
'field' => 'current_value', return true;
'value' => $value,
'unit' => $unitNorm,
'name' => $varName
];
} }
if ($unitNorm === 'v') { if ($unitNorm === 'v') {
return [ $counterData['voltage_value'] = $value;
'field' => 'voltage_value', return true;
'value' => $value,
'unit' => $unitNorm,
'name' => $varName
];
} }
if ($unitNorm === 'hz') { if ($unitNorm === 'hz') {
return [ $counterData['frequency_value'] = $value;
'field' => 'frequency_value', return true;
'value' => $value,
'unit' => $unitNorm,
'name' => $varName
];
} }
if (in_array($unitNorm, ['bar', 'mbar', 'pa'], true)) { if (in_array($unitNorm, ['bar', 'mbar', 'pa'], true)) {
if ($this->looksLikeIn($varName)) { if ($this->looksLikeOut($context)) {
return [ $counterData['pressure_out_value'] = $value;
'field' => 'pressure_in_value', } else {
'value' => $value, $counterData['pressure_in_value'] = $value;
'unit' => $unitNorm,
'name' => $varName
];
} }
return true;
if ($this->looksLikeOut($varName)) {
return [
'field' => 'pressure_out_value',
'value' => $value,
'unit' => $unitNorm,
'name' => $varName
];
}
return [
'field' => 'pressure_auto',
'value' => $value,
'unit' => $unitNorm,
'name' => $varName
];
} }
if (in_array($unitNorm, ['°c', 'c', 'k'], true)) { if (in_array($unitNorm, ['°c', 'c', 'k'], true)) {
if ($this->looksLikeIn($varName)) { if ($this->looksLikeOut($context)) {
return [ $counterData['temperature_out_value'] = $value;
'field' => 'temperature_in_value', } else {
'value' => $value, $counterData['temperature_in_value'] = $value;
'unit' => $unitNorm,
'name' => $varName
];
} }
return true;
if ($this->looksLikeOut($varName)) {
return [
'field' => 'temperature_out_value',
'value' => $value,
'unit' => $unitNorm,
'name' => $varName
];
}
return [
'field' => 'temperature_auto',
'value' => $value,
'unit' => $unitNorm,
'name' => $varName
];
} }
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' => $varName
];
} }
return null; IPS_LogMessage('CounterClient', 'Nicht zugeordnet: ' . $context . ' | Einheit: ' . $unitNorm . ' | Wert: ' . $value);
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 ($this->looksLikeOut($item['name']) && !isset($counterData[$fieldOut])) { }
$counterData[$fieldOut] = $item['value']; if (isset($presentation['Prefix']) && trim((string)$presentation['Prefix']) !== '') {
continue; return trim((string)$presentation['Prefix']);
}
if (isset($presentation['Unit']) && trim((string)$presentation['Unit']) !== '') {
return trim((string)$presentation['Unit']);
}
}
} catch (\Throwable $e) {
} }
} }
foreach ($items as $item) { $profileName = '';
if (!isset($counterData[$fieldIn])) { if (isset($var['VariableCustomProfile']) && $var['VariableCustomProfile'] !== '') {
$counterData[$fieldIn] = $item['value']; $profileName = $var['VariableCustomProfile'];
continue; } elseif (isset($var['VariableProfile']) && $var['VariableProfile'] !== '') {
} $profileName = $var['VariableProfile'];
}
if (!isset($counterData[$fieldOut])) { if ($profileName !== '' && IPS_VariableProfileExists($profileName)) {
$counterData[$fieldOut] = $item['value']; $profile = IPS_GetVariableProfile($profileName);
continue; $suffix = trim((string)$profile['Suffix']);
$prefix = trim((string)$profile['Prefix']);
$unit = trim($prefix . ' ' . $suffix);
if ($unit !== '') {
return $unit;
} }
} }
$formatted = GetValueFormatted($varId);
return $this->extractUnitFromFormattedValue($formatted, $value);
} }
private function DetectCounterType(array $counterData): string private function extractUnitFromFormattedValue(string $formatted, float $value): string
{ {
$unit = isset($counterData['unit']) ? $this->normalizeUnit((string) $counterData['unit']) : ''; $formatted = trim($formatted);
if ($formatted === '') {
return '';
}
$search = [
number_format($value, 0, ',', '.'),
number_format($value, 1, ',', '.'),
number_format($value, 2, ',', '.'),
number_format($value, 3, ',', '.'),
str_replace('.', ',', (string)$value),
str_replace(',', '.', (string)$value),
(string)$value
];
$unit = $formatted;
foreach ($search as $needle) {
if ($needle !== '') {
$unit = str_replace($needle, '', $unit);
}
}
$unit = trim($unit);
$unit = preg_replace('/^[\-\+\d\.,\s]+/u', '', $unit);
return trim($unit);
}
private function DetectCounterType(array $counterData, string $context): string
{
$unit = isset($counterData['unit']) ? $this->normalizeUnit((string)$counterData['unit']) : '';
$ctx = mb_strtolower($context);
if (isset($counterData['voltage_value']) || isset($counterData['current_value']) || isset($counterData['frequency_value']) || isset($counterData['power_factor'])) { if (isset($counterData['voltage_value']) || isset($counterData['current_value']) || isset($counterData['frequency_value']) || isset($counterData['power_factor'])) {
return 'electricity'; return 'electricity';
} }
if (isset($counterData['temperature_in_value']) || isset($counterData['temperature_out_value'])) { if (isset($counterData['temperature_in_value']) || isset($counterData['temperature_out_value'])) {
if (strpos($ctx, 'kalt') !== false || strpos($ctx, 'cool') !== false || strpos($ctx, 'kaelte') !== false || strpos($ctx, 'kälte') !== false) {
return 'cooling';
}
return 'heat'; return 'heat';
} }
if ($unit === 'm3' || $unit === 'l') { if ($unit === 'm3' || $unit === 'l') {
if (strpos($ctx, 'gas') !== false) {
return 'gas';
}
return 'water'; return 'water';
} }
if ($unit === 'kwh' || $unit === 'mwh' || $unit === 'wh') { if ($unit === 'kwh' || $unit === 'kw/h' || $unit === 'mwh' || $unit === 'wh') {
if (isset($counterData['temperature_in_value']) || isset($counterData['flow_value'])) { if (isset($counterData['flow_value']) || strpos($ctx, 'waerme') !== false || strpos($ctx, 'wärme') !== false || strpos($ctx, 'warmwasser') !== false || strpos($ctx, 'heizung') !== false) {
return 'heat'; return 'heat';
} }
return 'electricity'; return 'electricity';
} }
if (strpos($ctx, 'gas') !== false) {
return 'gas';
}
return 'other'; return 'other';
} }
private function inferDefaultUnit(array $counterData): string private function inferDefaultUnit(array $counterData): string
{ {
if (isset($counterData['total_value'])) { if (isset($counterData['total_value'])) {
if ($counterData['type'] === 'water') { if ($counterData['type'] === 'water' || $counterData['type'] === 'gas') {
return 'm3'; return 'm³';
} }
return 'kWh'; return 'kWh';
} }
return ''; return '';
} }
private function isTotalUnit(string $unitNorm, string $context): bool
{
if (in_array($unitNorm, ['kwh', 'wh', 'mwh', 'm3', 'l', 'kw/h', 'w/h', 'mw/h'], true)) {
return true;
}
if (strpos($context, 'energy') !== false && in_array($unitNorm, ['kw', 'w', 'mw'], true)) {
return true;
}
if (strpos($context, 'volume') !== false && in_array($unitNorm, ['m3', 'l'], true)) {
return true;
}
return false;
}
private function isPowerUnit(string $unitNorm, string $context): bool
{
if (in_array($unitNorm, ['kw', 'w', 'mw'], true)) {
if (strpos($context, 'energy') !== false) {
return false;
}
return true;
}
return false;
}
private function isFlowUnit(string $unitNorm, string $context): bool
{
if (in_array($unitNorm, ['m3/h', 'l/h', 'l/min'], true)) {
return true;
}
if (strpos($context, 'flow') !== false && in_array($unitNorm, ['m3', 'l'], true)) {
return true;
}
return false;
}
private function formatOutputUnit(string $unitNorm): string
{
if ($unitNorm === 'm3') {
return 'm³';
}
if ($unitNorm === 'kwh') {
return 'kWh';
}
if ($unitNorm === 'kw/h') {
return 'kW/h';
}
return $unitNorm;
}
private function looksLikeIn(string $name): bool private function looksLikeIn(string $name): bool
{ {
$name = mb_strtolower($name);
return strpos($name, 'vorlauf') !== false return strpos($name, 'vorlauf') !== false
|| strpos($name, 'vl') !== false || strpos($name, 'vl') !== false
|| strpos($name, 'flow') !== false || strpos($name, 'flow') !== false
|| strpos($name, 'ein') !== false || strpos($name, 'ein') !== false
|| strpos($name, 'in') !== false; || strpos($name, 'iv') !== false
|| strpos($name, 'inlet') !== false;
} }
private function looksLikeOut(string $name): bool private function looksLikeOut(string $name): bool
{ {
$name = mb_strtolower($name);
return strpos($name, 'ruecklauf') !== false return strpos($name, 'ruecklauf') !== false
|| strpos($name, 'rücklauf') !== false || strpos($name, 'rücklauf') !== false
|| strpos($name, 'rl') !== false || strpos($name, 'rl') !== false
|| strpos($name, 'return') !== false || strpos($name, 'return') !== false
|| strpos($name, 'aus') !== false || strpos($name, 'aus') !== false
|| strpos($name, 'out') !== false; || strpos($name, 'ri') !== false
|| strpos($name, 'outlet') !== false;
} }
private function normalizeUnit(string $unit): string private function normalizeUnit(string $unit): string
{ {
$unit = mb_strtolower(trim($unit)); $unit = mb_strtolower(trim($unit));
$unit = str_replace([' ', '°'], ['', '°'], $unit); $unit = str_replace(["\xc2\xa0", ' '], '', $unit);
$unit = str_replace(['m³', '㎥'], 'm3', $unit); $unit = str_replace(['m³', '㎥'], 'm3', $unit);
return $unit; return $unit;
} }
@@ -442,73 +466,67 @@ class CounterClient extends IPSModule
return $text; return $text;
} }
public function MqttPublish($server_id, $topic, $payload, $retain) {
// ensure server instance exists public function MqttPublish($server_id, $topic, $payload, $retain)
if(!IPS_InstanceExists($server_id)) { {
if (!IPS_InstanceExists($server_id)) {
return false; return false;
} }
$ips_var_type = 3; $ips_var_type = 3;
$module_id = '{01C00ADD-D04E-452E-B66A-D253278743FE}';
$ident = 'TempMQTTDevice_' . $this->InstanceID;
if (!IPS_SemaphoreEnter($ident, 100)) {
return false;
}
$module_id = "{01C00ADD-D04E-452E-B66A-D253278743FE}" /* Module ID of MQTT Server Device */; try {
$ident = "TempMQTTDevice"; $id = @IPS_GetObjectIDByIdent($ident, $this->InstanceID);
if ($id === false) {
// enter semaphore to ensure the temporary device gets used by one thread at a time
if(IPS_SemaphoreEnter($ident, 100)) {
// get temporary MQTT Server Device or create if needed
$id = @IPS_GetObjectIDByIdent($ident, $_IPS['SELF']);
if($id === false) {
$id = @IPS_CreateInstance($module_id); $id = @IPS_CreateInstance($module_id);
if($id === false) { if ($id === false) {
return false; return false;
} }
IPS_SetParent($id, $_IPS['SELF']); IPS_SetParent($id, $this->InstanceID);
IPS_SetIdent($id, $ident); IPS_SetIdent($id, $ident);
} }
// ensure the specified server instance is actually compatible if (!IPS_IsInstanceCompatible($id, $server_id)) {
if(!IPS_IsInstanceCompatible($id, $server_id)) {
return false; return false;
} }
// ensure that the temporary device is actually connected to the correct server instance
$inst_config = IPS_GetInstance($id); $inst_config = IPS_GetInstance($id);
if($inst_config["ConnectionID"] != $server_id) { if ((int)$inst_config['ConnectionID'] !== (int)$server_id) {
IPS_DisconnectInstance($id); IPS_DisconnectInstance($id);
if(!@IPS_ConnectInstance($id, $server_id)) { if (!@IPS_ConnectInstance($id, $server_id)) {
return false; return false;
} }
} }
// name object to help with debugging IPS_SetName($id, 'Temporary MQTT Device for: ' . $topic);
IPS_SetName($id, "Temporary MQTT Device for: " . $topic);
// configure temporary device $config_arr = [
$config_arr = array( 'Retain' => $retain,
"Retain" => $retain, 'Topic' => $topic,
"Topic" => $topic, 'Type' => $ips_var_type
"Type" => $ips_var_type ];
);
$config_str = json_encode($config_arr); IPS_SetConfiguration($id, json_encode($config_arr));
IPS_SetConfiguration($id, $config_str); IPS_SetHidden($id, true);
IPS_SetHidden($id,true);
IPS_ApplyChanges($id); IPS_ApplyChanges($id);
// get Value variable and use it to publish the payload $var_id = @IPS_GetObjectIDByIdent('Value', $id);
$var_id = @IPS_GetObjectIDByIdent("Value", $id); if ($var_id === false) {
RequestAction($var_id, $payload); return false;
}
RequestAction($var_id, $payload);
} finally {
IPS_SemaphoreLeave($ident); IPS_SemaphoreLeave($ident);
} else { // semaphore timeout
return false;
} }
return true; return true;
} // MQTT_Publish }
} }
?> ?>
+6 -1
View File
@@ -13,12 +13,17 @@
"validVariableTypes": [3] "validVariableTypes": [3]
}, },
{ {
"type": "ValidationTextBox",
"name": "Projectname",
"caption": "Projekt-Name"
},
{
"type": "NumberSpinner", "type": "NumberSpinner",
"name": "ProjectIdPortal", "name": "ProjectIdPortal",
"caption": "Project-ID (Portal)", "caption": "Project-ID (Portal)",
"digits": 0 "digits": 0
}, },
{ {
"type": "NumberSpinner", "type": "NumberSpinner",
"name": "UpdateTime", "name": "UpdateTime",
"caption": "Aktualisierungszeit (Sekunden)", "caption": "Aktualisierungszeit (Sekunden)",
+4 -3
View File
@@ -9,8 +9,9 @@ class CounterServer extends IPSModule
$this->RegisterPropertyInteger('Connector', 0); $this->RegisterPropertyInteger('Connector', 0);
$this->RegisterPropertyInteger('SourceJSON', 0); $this->RegisterPropertyInteger('SourceJSON', 0);
$this->RegisterPropertyInteger('UpdateTime', 60); $this->RegisterPropertyInteger('UpdateTime', 60);
$this->RegisterPropertyString('Projectname', 60);
$this->RegisterPropertyInteger('ProjectIdPortal', -1); $this->RegisterPropertyInteger('ProjectIdPortal', -1);
$this->RegisterTimer('Update', 0, 'SECT_checkTable($_IPS[\'TARGET\']);'); $this->RegisterTimer('Update', 0, 'SECS_checkTable('.$this->InstanceID.');');
} }
public function ApplyChanges() public function ApplyChanges()
@@ -49,7 +50,7 @@ class CounterServer extends IPSModule
$clientId = (string)$this->InstanceID; $clientId = (string)$this->InstanceID;
$clientName = IPS_GetName($this->InstanceID); $clientName = IPS_GetName($this->InstanceID);
$projectName = $this->ReadPropertyString('Projectname');
$timestamp = $payload['timestamp'] ?? date('Y-m-d H:i:s'); $timestamp = $payload['timestamp'] ?? date('Y-m-d H:i:s');
$counters = $payload['counters'] ?? []; $counters = $payload['counters'] ?? [];
$projectId = $this->ReadPropertyInteger('ProjectIdPortal'); $projectId = $this->ReadPropertyInteger('ProjectIdPortal');
@@ -75,7 +76,7 @@ class CounterServer extends IPSModule
'" . $this->esc($counterId) . "', '" . $this->esc($counterId) . "',
'" . hash('sha256', $projectId.$clientId . '_' . $counterId) . "', '" . hash('sha256', $projectId.$clientId . '_' . $counterId) . "',
'" . $this->esc($clientId) . "', '" . $this->esc($clientId) . "',
'" . $this->esc($clientName) . "', '" . $this->esc($projectName.'_'. $counterId) . "',
'" . $this->esc($type) . "', '" . $this->esc($type) . "',
'" . $this->esc($unit) . "', '" . $this->esc($unit) . "',
1 1
+1 -1
View File
@@ -8,6 +8,6 @@
"date": 1491343200 "date": 1491343200
}, },
"version": "1.1", "version": "1.1",
"build": 0, "build": 5,
"date": 0 "date": 0
} }