Shelly Modul generisch erweitern
Tests / test (push) Successful in 46s

This commit is contained in:
dh
2026-09-17 10:19:56 +00:00
parent 4cbec75d56
commit 1baa63f23e
7 changed files with 1006 additions and 309 deletions
+233 -78
View File
@@ -9,11 +9,54 @@ class ShellyModul extends IPSModule
private const MQTT_SERVER_MODULE_ID = '{C6D2AEB3-6E1F-4B2E-8E69-3A1A00246850}';
private const MQTT_TX_DATA_ID = '{043EA491-0325-4ADD-8FC2-A30C8EEB4D3F}';
private const GROUP_PROPERTIES = [
'device' => 'CreateDeviceInfo',
'inputs' => 'CreateInputs',
'switches' => 'CreateSwitches',
'covers' => 'CreateCovers',
'lights' => 'CreateLights',
'power' => 'CreatePower',
'voltage' => 'CreateVoltage',
'current' => 'CreateCurrent',
'energy' => 'CreateEnergy',
'frequency' => 'CreateFrequency',
'power_factor' => 'CreatePowerFactor',
'meters' => 'CreateMeterDetails',
'temperature' => 'CreateTemperature',
'humidity' => 'CreateHumidity',
'illuminance' => 'CreateIlluminance',
'battery' => 'CreateBattery',
'environment' => 'CreateEnvironment',
'system' => 'CreateSystem',
'other' => 'CreateOther',
];
public function Create()
{
parent::Create();
$this->RegisterPropertyBoolean('UseDeviceTopicFilter', false);
$this->RegisterPropertyString('DeviceTopicPrefix', 'shelly');
$this->RegisterPropertyBoolean('CreateOnline', true);
$this->RegisterPropertyBoolean('CreateDeviceInfo', true);
$this->RegisterPropertyBoolean('CreateInputs', true);
$this->RegisterPropertyBoolean('CreateSwitches', true);
$this->RegisterPropertyBoolean('CreateCovers', true);
$this->RegisterPropertyBoolean('CreateLights', true);
$this->RegisterPropertyBoolean('CreatePower', true);
$this->RegisterPropertyBoolean('CreateVoltage', true);
$this->RegisterPropertyBoolean('CreateCurrent', true);
$this->RegisterPropertyBoolean('CreateEnergy', true);
$this->RegisterPropertyBoolean('CreateFrequency', true);
$this->RegisterPropertyBoolean('CreatePowerFactor', true);
$this->RegisterPropertyBoolean('CreateMeterDetails', true);
$this->RegisterPropertyBoolean('CreateTemperature', true);
$this->RegisterPropertyBoolean('CreateHumidity', true);
$this->RegisterPropertyBoolean('CreateIlluminance', true);
$this->RegisterPropertyBoolean('CreateBattery', true);
$this->RegisterPropertyBoolean('CreateEnvironment', true);
$this->RegisterPropertyBoolean('CreateSystem', false);
$this->RegisterPropertyBoolean('CreateOther', false);
$this->RegisterPropertyBoolean('Debug', false);
$this->ConnectParent(self::MQTT_SERVER_MODULE_ID);
}
@@ -42,25 +85,32 @@ class ShellyModul extends IPSModule
return;
}
$topicParts = explode('/', $topic);
if (count($topicParts) < 2) {
return;
}
$deviceTopic = array_shift($topicParts);
if (!$this->isAcceptedDeviceTopic($deviceTopic)) {
$topicInfo = ShellyParser::parseTopic($topic);
if ($topicInfo === null || !$this->isAcceptedDeviceTopic($topicInfo['deviceTopic'])) {
return;
}
$this->debug('MQTT empfangen', $topic . ' -> ' . $payload);
$deviceTopic = $topicInfo['deviceTopic'];
if ($topicParts === ['online']) {
if ($topicInfo['kind'] === 'online') {
$this->handleOnline($deviceTopic, $payload);
return;
}
if ($topicParts === ['events', 'rpc']) {
$this->handleRpc($deviceTopic, $payload);
$decoded = $this->decodePayload($payload);
if ($decoded === null) {
return;
}
if ($topicInfo['kind'] === 'rpc') {
$this->handleRpc($deviceTopic, $decoded);
} elseif ($topicInfo['kind'] === 'component_status' && $topicInfo['component'] !== null) {
$this->updatePoints($deviceTopic, ShellyParser::pointsFromComponent($topicInfo['component'], $decoded));
} elseif ($topicInfo['kind'] === 'status') {
$this->updatePoints($deviceTopic, ShellyParser::pointsFromStatus($decoded));
} elseif ($topicInfo['kind'] === 'announce') {
$this->updatePoints($deviceTopic, ShellyParser::pointsFromAnnounce($decoded));
}
}
@@ -76,7 +126,6 @@ class ShellyModul extends IPSModule
if (!IPS_ObjectExists($folderID) || IPS_GetParent($folderID) !== $this->InstanceID) {
throw new InvalidArgumentException('Der Geräteordner gehört nicht zu dieser Instanz.');
}
if (preg_match('/_output_(\d+)$/', $variableIdent, $matches) !== 1) {
throw new InvalidArgumentException('Unbekannter Shelly-Ausgang: ' . $variableIdent);
}
@@ -92,7 +141,7 @@ class ShellyModul extends IPSModule
public function SetOutput(string $DeviceTopic, int $Output, bool $Value): void
{
if (!$this->isAcceptedDeviceTopic($DeviceTopic)) {
throw new InvalidArgumentException('Das Geräte-Topic entspricht nicht dem konfigurierten Präfix.');
throw new InvalidArgumentException('Das Geräte-Topic ist ungültig oder entspricht nicht dem aktiven Filter.');
}
if ($Output < 0) {
throw new InvalidArgumentException('Der Ausgangsindex darf nicht negativ sein.');
@@ -102,18 +151,31 @@ class ShellyModul extends IPSModule
'id' => random_int(1, 2147483647),
'src' => 'enelix-symcon-' . $this->InstanceID,
'method' => 'Switch.Set',
'params' => [
'id' => $Output,
'on' => $Value,
],
'params' => ['id' => $Output, 'on' => $Value],
], JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR);
$this->publish($DeviceTopic . '/rpc', $payload);
}
private function decodePayload(string $payload): ?array
{
try {
$decoded = json_decode($payload, true, 512, JSON_THROW_ON_ERROR);
} catch (JsonException $exception) {
$this->debug('Ungültige Shelly-Nutzdaten', $exception->getMessage());
return null;
}
return is_array($decoded) ? $decoded : null;
}
private function handleOnline(string $deviceTopic, string $payload): void
{
$value = ShellyParser::toBoolean($payload);
if (!$this->ReadPropertyBoolean('CreateOnline')) {
return;
}
$value = $this->toBoolean($payload);
if ($value === null) {
$this->debug('Online-Status ignoriert', $payload);
return;
@@ -125,77 +187,158 @@ class ShellyModul extends IPSModule
}
}
private function handleRpc(string $deviceTopic, string $payload): void
private function handleRpc(string $deviceTopic, array $rpc): void
{
try {
$rpc = json_decode($payload, true, 512, JSON_THROW_ON_ERROR);
} catch (JsonException $exception) {
$this->debug('Ungültiges Shelly-RPC', $exception->getMessage());
return;
}
if (!is_array($rpc)) {
return;
}
$source = $rpc['src'] ?? '';
if (!is_string($source) || ShellyParser::extractType($source) === 'unknown') {
return;
if ($this->ReadPropertyBoolean('CreateDeviceInfo') && is_string($source)) {
$type = ShellyParser::extractType($source);
if ($type !== 'unknown') {
$typeID = $this->ensureVariable($deviceTopic, 'type', 'Typ', 3, '', 20);
if ($typeID > 0) {
SetValue($typeID, $type);
}
}
}
$params = $rpc['params'] ?? null;
if (!is_array($params)) {
return;
}
$this->updatePoints($deviceTopic, ShellyParser::pointsFromRpc($rpc));
}
$typeID = $this->ensureVariable($deviceTopic, 'type', 'Typ', 3, '', 20);
if ($typeID > 0) {
SetValue($typeID, ShellyParser::extractType($source));
}
/**
* @param array<int, array{component: string, path: string, value: bool|int|float|string}> $points
*/
private function updatePoints(string $deviceTopic, array $points): void
{
foreach ($points as $point) {
$group = ShellyParser::groupForPoint($point['component'], $point['path']);
if (!$this->isGroupEnabled($group)) {
continue;
}
$mapped = ShellyParser::mapParams($params);
foreach ($mapped['inputs'] as $index => $value) {
$definition = $this->pointDefinition($deviceTopic, $point);
$variableID = $this->ensureVariable(
$deviceTopic,
'input_' . $index,
'Input ' . $index,
0,
'',
100 + $index
$definition['suffix'],
$definition['name'],
$definition['type'],
$definition['profile'],
$definition['position'],
$definition['action']
);
if ($variableID > 0) {
$value = $point['value'];
if ($definition['type'] === 1 && is_float($value)) {
$value = (int) $value;
} elseif ($definition['type'] === 2 && is_int($value)) {
$value = (float) $value;
}
SetValue($variableID, $value);
}
}
}
foreach ($mapped['outputs'] as $index => $value) {
$variableID = $this->ensureVariable(
$deviceTopic,
'output_' . $index,
'Output ' . $index,
0,
'~Switch',
200 + $index,
true
);
if ($variableID > 0) {
SetValue($variableID, $value);
}
private function isGroupEnabled(string $group): bool
{
$property = self::GROUP_PROPERTIES[$group] ?? 'CreateOther';
return $this->ReadPropertyBoolean($property);
}
/**
* @param array{component: string, path: string, value: bool|int|float|string} $point
* @return array{suffix: string, name: string, type: int, profile: string, position: int, action: bool}
*/
private function pointDefinition(string $deviceTopic, array $point): array
{
[$componentType, $componentIndex] = array_pad(explode(':', $point['component'], 2), 2, null);
if ($componentType === 'switch' && $point['path'] === 'output' && ctype_digit((string) $componentIndex)) {
$index = (int) $componentIndex;
return [
'suffix' => 'output_' . $index,
'name' => 'Output ' . $index,
'type' => 0,
'profile' => '~Switch',
'position' => 200 + $index,
'action' => true,
];
}
if ($mapped['temperature'] !== null) {
$variableID = $this->ensureVariable(
$deviceTopic,
'temperature',
'Temperatur',
2,
'~Temperature',
300
);
if ($variableID > 0) {
SetValue($variableID, $mapped['temperature']);
}
if (($componentType === 'input' && $point['path'] === 'state')
|| ($componentType === 'switch' && $point['path'] === 'input')) {
$index = ctype_digit((string) $componentIndex) ? (int) $componentIndex : 0;
return [
'suffix' => 'input_' . $index,
'name' => 'Input ' . $index,
'type' => 0,
'profile' => '',
'position' => 100 + $index,
'action' => false,
];
}
if ($componentType === 'switch' && str_ends_with(strtolower($point['path']), 'temperature.tc')) {
return [
'suffix' => 'temperature',
'name' => 'Temperatur',
'type' => 2,
'profile' => '~Temperature',
'position' => 300,
'action' => false,
];
}
$source = $point['component'] . '.' . $point['path'];
$normalized = strtolower($source);
$normalized = preg_replace('/[^a-z0-9_]+/', '_', $normalized) ?? 'value';
$normalized = trim($normalized, '_');
$suffix = 'dp_' . substr($normalized, 0, 48) . '_' . substr(hash('sha256', $source), 0, 8);
return [
'suffix' => $suffix,
'name' => $this->displayName($point['component'], $point['path']),
'type' => ShellyParser::variableType($point['value'], $point['path']),
'profile' => $this->profileForPoint($point['component'], $point['path']),
'position' => 1000 + (int) (hexdec(substr(hash('sha256', $source), 0, 4)) % 50000),
'action' => false,
];
}
private function displayName(string $component, string $path): string
{
$fieldNames = [
'apower' => 'Wirkleistung',
'aprtpower' => 'Scheinleistung',
'voltage' => 'Spannung',
'current' => 'Strom',
'freq' => 'Frequenz',
'pf' => 'Leistungsfaktor',
'total' => 'Gesamt',
'rh' => 'Luftfeuchtigkeit',
'tc' => 'Temperatur',
'current_pos' => 'Position',
'brightness' => 'Helligkeit',
];
$componentLabel = ucfirst(str_replace(':', ' ', $component));
$parts = explode('.', $path);
foreach ($parts as &$part) {
$lower = strtolower($part);
$part = $fieldNames[$lower] ?? ucfirst(str_replace('_', ' ', $part));
}
unset($part);
return $componentLabel . ' - ' . implode(' / ', $parts);
}
private function profileForPoint(string $component, string $path): string
{
$fullPath = strtolower($component . '.' . $path);
if (preg_match('/(^|\.)(temperature|tc)(\.|$)/', $fullPath) === 1) {
return '~Temperature';
}
if (preg_match('/(^|\.)(humidity|rh)(\.|$)/', $fullPath) === 1) {
return '~Humidity';
}
return '';
}
private function ensureVariable(
@@ -224,7 +367,7 @@ class ShellyModul extends IPSModule
IPS_SetName($variableID, $name);
IPS_SetPosition($variableID, $position);
if ($profile !== '') {
if ($profile !== '' && IPS_VariableProfileExists($profile)) {
IPS_SetVariableCustomProfile($variableID, $profile);
}
if ($action) {
@@ -258,7 +401,6 @@ class ShellyModul extends IPSModule
{
$ident = 'action_handler';
$scriptID = @IPS_GetObjectIDByIdent($ident, $this->InstanceID);
if ($scriptID === false) {
$scriptID = IPS_CreateScript(0);
IPS_SetParent($scriptID, $this->InstanceID);
@@ -310,14 +452,14 @@ PHP
private function isAcceptedDeviceTopic(string $deviceTopic): bool
{
if ($deviceTopic === '' || strlen($deviceTopic) > 128) {
if ($deviceTopic === '' || strlen($deviceTopic) > 300 || preg_match('//u', $deviceTopic) !== 1) {
return false;
}
if (preg_match('//u', $deviceTopic) !== 1) {
if (preg_match('/[\x00-\x1F\x7F#\+]/u', $deviceTopic) === 1) {
return false;
}
if (preg_match('/[\x00-\x1F\x7F\/#\+]/u', $deviceTopic) === 1) {
return false;
if (!$this->ReadPropertyBoolean('UseDeviceTopicFilter')) {
return true;
}
$prefix = trim($this->ReadPropertyString('DeviceTopicPrefix'));
@@ -336,15 +478,28 @@ PHP
return substr($normalized, 0, 48) . '_' . substr(hash('sha256', $deviceTopic), 0, 8);
}
private function toBoolean(string $value): ?bool
{
$normalized = strtolower(trim($value));
if (in_array($normalized, ['true', '1', 'on', 'online'], true)) {
return true;
}
if (in_array($normalized, ['false', '0', 'off', 'offline'], true)) {
return false;
}
return null;
}
private function debug(string $title, $message): void
{
if (!$this->ReadPropertyBoolean('Debug')) {
return;
}
if (!is_string($message)) {
$message = json_encode($message, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
}
$this->SendDebug($title, (string) $message, 0);
}
}