first commit
This commit is contained in:
commit
403a19ac85
158 files changed
+25101
No files matched your search
@@ -0,0 +1,598 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
/** Local Magic 1/2 integration via the devolo mDNS/HTTP/Protobuf API. */
|
||||
class DevoloMagic extends IPSModule
|
||||
{
|
||||
private const STATUS_CONFIGURATION = 200;
|
||||
private const STATUS_DISCOVERY = 201;
|
||||
private const STATUS_AUTHENTICATION = 202;
|
||||
private const STATUS_COMMUNICATION = 203;
|
||||
private const DNSSD_CONTROL_GUID = '{780B2D48-916C-4D59-AD35-5A429B2355A5}';
|
||||
|
||||
public function Create()
|
||||
{
|
||||
parent::Create();
|
||||
$this->RegisterPropertyBoolean('Disable', false);
|
||||
$this->RegisterPropertyString('Host', '');
|
||||
$this->RegisterPropertyString('Password', '');
|
||||
$this->RegisterPropertyInteger('UpdateInterval', 60);
|
||||
$this->RegisterPropertyInteger('GuestWiFiDuration', 0);
|
||||
$this->RegisterPropertyString('DeviceApiUrl', '');
|
||||
$this->RegisterPropertyString('PlcNetApiUrl', '');
|
||||
$this->RegisterAttributeString('DeviceService', '{}');
|
||||
$this->RegisterAttributeString('PlcNetService', '{}');
|
||||
$this->RegisterAttributeString('NetworkTopology', '{}');
|
||||
$this->RegisterAttributeString('LastError', '');
|
||||
|
||||
$this->CreateProfiles();
|
||||
$this->RegisterVariables();
|
||||
$this->RegisterTimer('UpdateData', 0, 'DevoloMagic_UpdateData($_IPS[\'TARGET\']);');
|
||||
$this->SetVisualizationType(1);
|
||||
}
|
||||
|
||||
public function ApplyChanges()
|
||||
{
|
||||
parent::ApplyChanges();
|
||||
$this->CreateProfiles();
|
||||
if ($this->ReadPropertyBoolean('Disable')) {
|
||||
$this->SetTimerInterval('UpdateData', 0);
|
||||
$this->SetStatus(IS_INACTIVE);
|
||||
} elseif (!$this->HasMinimumConfiguration()) {
|
||||
$this->SetTimerInterval('UpdateData', 0);
|
||||
$this->SetStatus(self::STATUS_CONFIGURATION);
|
||||
$this->WriteError('Bitte Host/IP-Adresse oder beide manuellen API-Endpunkte konfigurieren.');
|
||||
} else {
|
||||
$this->SetTimerInterval('UpdateData', max(10, $this->ReadPropertyInteger('UpdateInterval')) * 1000);
|
||||
$this->SetStatus(IS_ACTIVE);
|
||||
$this->SetSummary($this->ReadPropertyString('Host') ?: 'manuelle API-Endpunkte');
|
||||
}
|
||||
$this->SendTopology();
|
||||
}
|
||||
|
||||
public function GetConfigurationForm()
|
||||
{
|
||||
$deviceService = $this->ReadJsonAttribute('DeviceService');
|
||||
$plcService = $this->ReadJsonAttribute('PlcNetService');
|
||||
$found = $this->ServiceSummary('Geräte-API', $deviceService) . "\n" . $this->ServiceSummary('PLC-API', $plcService);
|
||||
return json_encode([
|
||||
'elements' => [
|
||||
['type' => 'CheckBox', 'name' => 'Disable', 'caption' => 'Instanz deaktivieren'],
|
||||
['type' => 'ExpansionPanel', 'caption' => 'Verbindung', 'items' => [
|
||||
['type' => 'ValidationTextBox', 'name' => 'Host', 'caption' => 'IP-Adresse oder mDNS-Name des Magic-Adapters'],
|
||||
['type' => 'PasswordTextBox', 'name' => 'Password', 'caption' => 'Gerätepasswort'],
|
||||
['type' => 'NumberSpinner', 'name' => 'UpdateInterval', 'minimum' => 10, 'maximum' => 3600, 'suffix' => ' Sekunden', 'caption' => 'Aktualisierungsintervall'],
|
||||
['type' => 'NumberSpinner', 'name' => 'GuestWiFiDuration', 'minimum' => 0, 'maximum' => 1440, 'suffix' => ' Minuten', 'caption' => 'Gäste-WLAN-Dauer (0 = unbegrenzt)']
|
||||
]],
|
||||
['type' => 'ExpansionPanel', 'caption' => 'Manuelle API-Endpunkte (nur bei fehlendem mDNS)', 'expanded' => false, 'items' => [
|
||||
['type' => 'ValidationTextBox', 'name' => 'DeviceApiUrl', 'caption' => 'Geräte-API-Basis-URL'],
|
||||
['type' => 'ValidationTextBox', 'name' => 'PlcNetApiUrl', 'caption' => 'PLC-API-Basis-URL']
|
||||
]],
|
||||
['type' => 'Label', 'caption' => $found]
|
||||
],
|
||||
'actions' => [
|
||||
['type' => 'Button', 'caption' => 'APIs suchen', 'onClick' => 'DevoloMagic_Discover($id);'],
|
||||
['type' => 'Button', 'caption' => 'Jetzt aktualisieren', 'onClick' => 'DevoloMagic_UpdateData($id);']
|
||||
],
|
||||
'status' => [
|
||||
['code' => self::STATUS_CONFIGURATION, 'icon' => 'error', 'caption' => 'Konfiguration unvollständig'],
|
||||
['code' => self::STATUS_DISCOVERY, 'icon' => 'error', 'caption' => 'Magic-API nicht gefunden'],
|
||||
['code' => self::STATUS_AUTHENTICATION, 'icon' => 'error', 'caption' => 'Gerätepasswort abgelehnt'],
|
||||
['code' => self::STATUS_COMMUNICATION, 'icon' => 'error', 'caption' => 'Magic-Adapter nicht erreichbar']
|
||||
]
|
||||
]);
|
||||
}
|
||||
|
||||
public function Discover()
|
||||
{
|
||||
if ($this->ReadPropertyString('Host') === '') {
|
||||
$this->WriteError('Für die automatische Suche wird eine IP-Adresse oder ein mDNS-Name benötigt.');
|
||||
$this->SetStatus(self::STATUS_CONFIGURATION);
|
||||
} else {
|
||||
$found = $this->DiscoverServices();
|
||||
if ($found['device'] || $found['plcnet']) {
|
||||
$this->WriteError('');
|
||||
$this->SetStatus(IS_ACTIVE);
|
||||
} else {
|
||||
$this->WriteError('Keine passende devolo-Magic-API per mDNS gefunden.');
|
||||
$this->SetStatus(self::STATUS_DISCOVERY);
|
||||
}
|
||||
}
|
||||
$this->SendTopology();
|
||||
}
|
||||
|
||||
public function UpdateData()
|
||||
{
|
||||
if ($this->ReadPropertyBoolean('Disable') || !$this->HasMinimumConfiguration() || !IPS_SemaphoreEnter('DevoloMagic.' . $this->InstanceID, 1000)) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
$endpoints = $this->GetEndpoints();
|
||||
if ($endpoints['plcnet'] !== null) {
|
||||
$network = $this->ReadNetworkOverview($this->HttpGet($endpoints['plcnet']['url'], 'GetNetworkOverview'));
|
||||
$this->ApplyNetworkOverview($network, $endpoints['plcnet']);
|
||||
}
|
||||
if ($endpoints['device'] !== null) {
|
||||
$this->ReadDeviceData($endpoints['device']);
|
||||
}
|
||||
$this->SetValue('LastUpdate', time());
|
||||
$this->WriteError('');
|
||||
$this->SetStatus(IS_ACTIVE);
|
||||
} catch (RuntimeException $exception) {
|
||||
$code = $exception->getCode();
|
||||
$this->SetStatus(in_array($code, [self::STATUS_DISCOVERY, self::STATUS_AUTHENTICATION], true) ? $code : self::STATUS_COMMUNICATION);
|
||||
$this->WriteError($exception->getMessage());
|
||||
$this->SendDebug(__FUNCTION__, $exception->getMessage(), 0);
|
||||
} finally {
|
||||
$this->SendTopology();
|
||||
IPS_SemaphoreLeave('DevoloMagic.' . $this->InstanceID);
|
||||
}
|
||||
}
|
||||
|
||||
public function RequestAction($ident, $value)
|
||||
{
|
||||
try {
|
||||
if ($ident === 'Refresh') {
|
||||
$this->UpdateData();
|
||||
return;
|
||||
}
|
||||
if ($ident === 'LedEnabled') {
|
||||
$this->SetLed((bool) $value);
|
||||
return;
|
||||
}
|
||||
if ($ident === 'GuestWiFi') {
|
||||
$this->SetGuestWiFi((bool) $value);
|
||||
return;
|
||||
}
|
||||
} catch (RuntimeException $exception) {
|
||||
$this->SetStatus($exception->getCode() === self::STATUS_AUTHENTICATION ? self::STATUS_AUTHENTICATION : self::STATUS_COMMUNICATION);
|
||||
$this->WriteError($exception->getMessage());
|
||||
$this->SendTopology();
|
||||
return;
|
||||
}
|
||||
throw new InvalidArgumentException('Unbekannte Aktion: ' . $ident);
|
||||
}
|
||||
|
||||
public function GetVisualizationTile()
|
||||
{
|
||||
$html = file_get_contents(__DIR__ . '/module.html');
|
||||
return ($html === false ? '<div>Visualisierung nicht verfügbar.</div>' : $html)
|
||||
. '<script>handleMessage(' . json_encode($this->GetTopologyMessage(), JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT) . ');</script>';
|
||||
}
|
||||
|
||||
private function RegisterVariables(): void
|
||||
{
|
||||
$stringVariables = ['DeviceName' => 'Gerätename', 'Product' => 'Produkt', 'Firmware' => 'Firmware', 'SerialNumber' => 'Seriennummer', 'MacAddress' => 'Powerline-MAC-Adresse', 'IPAddress' => 'IP-Adresse', 'NetworkName' => 'Powerline-Netzwerk', 'WiFiClientDetails' => 'WLAN-Clientdetails', 'NetworkOverview' => 'Powerline-Übersicht', 'LastError' => 'Letzter Fehler'];
|
||||
foreach ($stringVariables as $ident => $name) {
|
||||
$this->RegisterVariableString($ident, $name);
|
||||
}
|
||||
$integerVariables = ['PowerlineDevices' => 'Powerline-Adapter', 'WiFiClients' => 'WLAN-Clients', 'WiFiClients2GHz' => 'WLAN-Clients 2,4 GHz', 'WiFiClients5GHz' => 'WLAN-Clients 5 GHz'];
|
||||
foreach ($integerVariables as $ident => $name) {
|
||||
$this->RegisterVariableInteger($ident, $name);
|
||||
}
|
||||
$this->RegisterVariableFloat('PowerlineTxRate', 'Powerline Senden', 'DevoloMagic.MbitPerSecond');
|
||||
$this->RegisterVariableFloat('PowerlineRxRate', 'Powerline Empfangen', 'DevoloMagic.MbitPerSecond');
|
||||
$this->RegisterVariableBoolean('LedEnabled', 'LEDs aktiviert', '~Switch');
|
||||
$this->RegisterVariableBoolean('GuestWiFi', 'Gäste-WLAN aktiv', '~Switch');
|
||||
$this->RegisterVariableInteger('GuestWiFiRemaining', 'Gäste-WLAN Restlaufzeit', 'DevoloMagic.Minutes');
|
||||
$this->RegisterVariableInteger('DeviceUptime', 'Laufzeit', 'DevoloMagic.Seconds');
|
||||
$this->RegisterVariableInteger('LastUpdate', 'Letzte Aktualisierung', '~UnixTimestamp');
|
||||
$this->EnableAction('LedEnabled');
|
||||
$this->EnableAction('GuestWiFi');
|
||||
}
|
||||
|
||||
private function CreateProfiles(): void
|
||||
{
|
||||
$this->CreateProfile('DevoloMagic.MbitPerSecond', VARIABLETYPE_FLOAT, ' Mbit/s', 0, 2500, 1);
|
||||
$this->CreateProfile('DevoloMagic.Minutes', VARIABLETYPE_INTEGER, ' min', 0, 1440, 1);
|
||||
$this->CreateProfile('DevoloMagic.Seconds', VARIABLETYPE_INTEGER, ' s', 0, 0, 0);
|
||||
}
|
||||
|
||||
private function CreateProfile(string $name, int $type, string $suffix, float $min, float $max, float $step): void
|
||||
{
|
||||
if (!IPS_VariableProfileExists($name)) {
|
||||
IPS_CreateVariableProfile($name, $type);
|
||||
IPS_SetVariableProfileText($name, '', $suffix);
|
||||
IPS_SetVariableProfileValues($name, $min, $max, $step);
|
||||
}
|
||||
}
|
||||
|
||||
private function HasMinimumConfiguration(): bool
|
||||
{
|
||||
return $this->ReadPropertyString('Host') !== '' || ($this->ReadPropertyString('DeviceApiUrl') !== '' && $this->ReadPropertyString('PlcNetApiUrl') !== '');
|
||||
}
|
||||
|
||||
/** @return array{device: ?array, plcnet: ?array} */
|
||||
private function GetEndpoints(): array
|
||||
{
|
||||
$device = $this->ManualEndpoint($this->ReadPropertyString('DeviceApiUrl'));
|
||||
$plcnet = $this->ManualEndpoint($this->ReadPropertyString('PlcNetApiUrl'));
|
||||
if (($device === null || $plcnet === null) && $this->ReadPropertyString('Host') !== '') {
|
||||
$this->DiscoverServices();
|
||||
}
|
||||
$device = $device ?? $this->StoredEndpoint('DeviceService');
|
||||
$plcnet = $plcnet ?? $this->StoredEndpoint('PlcNetService');
|
||||
if ($device === null && $plcnet === null) {
|
||||
throw new RuntimeException('Keinen Magic-API-Endpunkt gefunden. Prüfe IP/Name, mDNS oder die manuellen API-Endpunkte.', self::STATUS_DISCOVERY);
|
||||
}
|
||||
return ['device' => $device, 'plcnet' => $plcnet];
|
||||
}
|
||||
|
||||
/** @return array{device: bool, plcnet: bool} */
|
||||
private function DiscoverServices(): array
|
||||
{
|
||||
$ids = IPS_GetInstanceListByModuleID(self::DNSSD_CONTROL_GUID);
|
||||
if (count($ids) === 0) {
|
||||
return ['device' => false, 'plcnet' => false];
|
||||
}
|
||||
$result = ['device' => false, 'plcnet' => false];
|
||||
foreach (['device', 'plcnet'] as $kind) {
|
||||
$service = $this->FindMatchingService($ids[0], $kind);
|
||||
if ($service !== null) {
|
||||
$this->WriteAttributeString($kind === 'device' ? 'DeviceService' : 'PlcNetService', json_encode($service));
|
||||
$result[$kind] = true;
|
||||
}
|
||||
}
|
||||
return $result;
|
||||
}
|
||||
|
||||
private function FindMatchingService(int $dnssdId, string $kind): ?array
|
||||
{
|
||||
$type = '_dvl-' . $kind . 'api._tcp';
|
||||
$types = @ZC_QueryServiceType($dnssdId, $type, 'local.');
|
||||
if (!is_array($types)) {
|
||||
return null;
|
||||
}
|
||||
foreach ($types as $entry) {
|
||||
$services = @ZC_QueryService($dnssdId, (string) ($entry['Name'] ?? ''), $type, 'local.');
|
||||
if (!is_array($services)) {
|
||||
continue;
|
||||
}
|
||||
foreach ($services as $service) {
|
||||
if (is_array($service) && $this->MatchesConfiguredHost($service)) {
|
||||
$endpoint = $this->EndpointFromService($service);
|
||||
if ($endpoint !== null) {
|
||||
return $endpoint;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private function MatchesConfiguredHost(array $service): bool
|
||||
{
|
||||
$configured = $this->NormalizeHost($this->ReadPropertyString('Host'));
|
||||
if ($configured === $this->NormalizeHost((string) ($service['Host'] ?? ''))) {
|
||||
return true;
|
||||
}
|
||||
$ips = $service['IPv4'] ?? [];
|
||||
$ips = is_array($ips) ? $ips : [$ips];
|
||||
$resolved = filter_var($configured, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) ? $configured : gethostbyname($configured);
|
||||
foreach ($ips as $ip) {
|
||||
if ((string) $ip === $configured || (string) $ip === $resolved) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private function EndpointFromService(array $service): ?array
|
||||
{
|
||||
$properties = $this->ParseTxtRecords($service['TXTRecords'] ?? []);
|
||||
$path = trim((string) ($properties['Path'] ?? $properties['path'] ?? ''), '/');
|
||||
$version = trim((string) ($properties['Version'] ?? ''));
|
||||
$ips = $service['IPv4'] ?? [];
|
||||
$ips = is_array($ips) ? $ips : [$ips];
|
||||
$host = (string) ($ips[0] ?? $service['Host'] ?? '');
|
||||
$port = (int) ($service['Port'] ?? 0);
|
||||
if ($host === '' || $port <= 0 || $path === '' || $version === '') {
|
||||
return null;
|
||||
}
|
||||
if (str_contains($host, ':') && !str_starts_with($host, '[')) {
|
||||
$host = '[' . $host . ']';
|
||||
}
|
||||
return ['url' => 'http://' . $host . ':' . $port . '/' . $path . '/' . rawurlencode($version), 'host' => (string) ($service['Host'] ?? ''), 'ipv4' => array_values($ips), 'port' => $port, 'properties' => $properties];
|
||||
}
|
||||
|
||||
private function ParseTxtRecords($records): array
|
||||
{
|
||||
$result = [];
|
||||
if (!is_array($records)) {
|
||||
return $result;
|
||||
}
|
||||
foreach ($records as $key => $record) {
|
||||
if (!is_int($key)) {
|
||||
$result[(string) $key] = (string) $record;
|
||||
} elseif (is_string($record)) {
|
||||
$parts = explode('=', $record, 2);
|
||||
$result[$parts[0]] = $parts[1] ?? 'true';
|
||||
}
|
||||
}
|
||||
return $result;
|
||||
}
|
||||
|
||||
private function StoredEndpoint(string $attribute): ?array
|
||||
{
|
||||
$endpoint = $this->ReadJsonAttribute($attribute);
|
||||
return isset($endpoint['url']) && is_string($endpoint['url']) ? $endpoint : null;
|
||||
}
|
||||
|
||||
private function ManualEndpoint(string $url): ?array
|
||||
{
|
||||
$url = rtrim(trim($url), '/');
|
||||
if ($url === '') {
|
||||
return null;
|
||||
}
|
||||
$parts = parse_url($url);
|
||||
if (!is_array($parts) || !isset($parts['scheme'], $parts['host']) || !in_array($parts['scheme'], ['http', 'https'], true)) {
|
||||
throw new RuntimeException('Ungültige manuelle API-Basis-URL: ' . $url, self::STATUS_CONFIGURATION);
|
||||
}
|
||||
return ['url' => $url, 'host' => $parts['host'], 'ipv4' => [], 'port' => $parts['port'] ?? 0, 'properties' => []];
|
||||
}
|
||||
|
||||
private function ReadDeviceData(array $endpoint): void
|
||||
{
|
||||
$features = $this->Features($endpoint);
|
||||
if (in_array('led', $features, true)) {
|
||||
$message = self::DecodeMessage($this->HttpGet($endpoint['url'], 'LedSettingsGet'));
|
||||
$this->SetValue('LedEnabled', self::FirstVarint($message, 1) === 0);
|
||||
}
|
||||
if (in_array('wifi1', $features, true)) {
|
||||
$this->ReadWiFiClients($endpoint['url']);
|
||||
$this->ReadGuestWiFi($endpoint['url']);
|
||||
}
|
||||
if (in_array('restart', $features, true)) {
|
||||
$message = self::DecodeMessage($this->HttpGet($endpoint['url'], 'UptimeGet'));
|
||||
$this->SetValue('DeviceUptime', self::FirstVarint($message, 1));
|
||||
}
|
||||
}
|
||||
|
||||
private function ReadWiFiClients(string $url): void
|
||||
{
|
||||
$message = self::DecodeMessage($this->HttpGet($url, 'WifiConnectedStationsGet'));
|
||||
$clients = [];
|
||||
$band2 = 0;
|
||||
$band5 = 0;
|
||||
foreach (self::Messages($message, 1) as $client) {
|
||||
$band = self::FirstVarint($client, 3);
|
||||
$band2 += $band === 1 ? 1 : 0;
|
||||
$band5 += $band === 2 ? 1 : 0;
|
||||
$clients[] = ['mac' => self::FirstText($client, 1), 'type' => self::MapValue(self::FirstVarint($client, 2), [1 => 'Haupt-WLAN', 2 => 'Gast-WLAN', 3 => 'Station']), 'band' => self::MapValue($band, [1 => '2,4 GHz', 2 => '5 GHz']), 'rxRate' => self::FirstVarint($client, 4), 'txRate' => self::FirstVarint($client, 5)];
|
||||
}
|
||||
$this->SetValue('WiFiClients', count($clients));
|
||||
$this->SetValue('WiFiClients2GHz', $band2);
|
||||
$this->SetValue('WiFiClients5GHz', $band5);
|
||||
$this->SetValue('WiFiClientDetails', json_encode($clients, JSON_UNESCAPED_SLASHES));
|
||||
}
|
||||
|
||||
private function ReadGuestWiFi(string $url): void
|
||||
{
|
||||
$message = self::DecodeMessage($this->HttpGet($url, 'WifiGuestAccessGet'));
|
||||
$this->SetValue('GuestWiFi', self::FirstVarint($message, 1) === 1);
|
||||
$this->SetValue('GuestWiFiRemaining', self::FirstVarint($message, 2));
|
||||
}
|
||||
|
||||
private function ReadNetworkOverview(string $data): array
|
||||
{
|
||||
return self::FirstMessage(self::DecodeMessage($data), 1);
|
||||
}
|
||||
|
||||
private function ApplyNetworkOverview(array $network, array $endpoint): void
|
||||
{
|
||||
$localMac = (string) ($endpoint['properties']['PlcMacAddress'] ?? $this->GetValue('MacAddress'));
|
||||
$devices = [];
|
||||
foreach (self::Messages($network, 1) as $entry) {
|
||||
$device = ['productName' => self::FirstText($entry, 1), 'productId' => self::FirstText($entry, 2), 'firmware' => self::FirstText($entry, 3), 'fullVersion' => self::FirstText($entry, 4), 'userDeviceName' => self::FirstText($entry, 5), 'userNetworkName' => self::FirstText($entry, 6), 'mac' => self::FirstText($entry, 7), 'topology' => self::MapValue(self::FirstVarint($entry, 8), [1 => 'lokal', 2 => 'entfernt']), 'technology' => self::MapValue(self::FirstVarint($entry, 9), [3 => 'HPAV Thunderbolt', 4 => 'HPAV Panther', 7 => 'G.hn']), 'ip' => self::FirstText($entry, 11), 'attachedToRouter' => self::FirstVarint($entry, 12) === 1];
|
||||
$device['local'] = self::NormalizeMac($device['mac']) === self::NormalizeMac($localMac);
|
||||
$devices[] = $device;
|
||||
}
|
||||
if ($localMac === '') {
|
||||
foreach ($devices as $index => $device) {
|
||||
if ($device['topology'] === 'lokal') {
|
||||
$devices[$index]['local'] = true;
|
||||
$localMac = $device['mac'];
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
$links = [];
|
||||
$maxTx = 0.0;
|
||||
$maxRx = 0.0;
|
||||
foreach (self::Messages($network, 2) as $entry) {
|
||||
$link = ['from' => self::FirstText($entry, 1), 'to' => self::FirstText($entry, 2), 'tx' => self::FirstDouble($entry, 3), 'rx' => self::FirstDouble($entry, 4)];
|
||||
if ($link['from'] === '' || $link['to'] === '') {
|
||||
continue;
|
||||
}
|
||||
if (self::NormalizeMac($link['from']) === self::NormalizeMac($localMac)) {
|
||||
$maxTx = max($maxTx, $link['tx']);
|
||||
$maxRx = max($maxRx, $link['rx']);
|
||||
}
|
||||
$links[] = $link;
|
||||
}
|
||||
foreach ($devices as $device) {
|
||||
if (!$device['local']) {
|
||||
continue;
|
||||
}
|
||||
$this->SetValue('DeviceName', $device['userDeviceName']);
|
||||
$this->SetValue('Product', $device['productName']);
|
||||
$this->SetValue('Firmware', $device['firmware'] ?: $device['fullVersion']);
|
||||
$this->SetValue('MacAddress', $device['mac']);
|
||||
$this->SetValue('IPAddress', $device['ip']);
|
||||
$this->SetValue('NetworkName', $device['userNetworkName']);
|
||||
break;
|
||||
}
|
||||
$this->SetValue('SerialNumber', (string) ($endpoint['properties']['SN'] ?? ''));
|
||||
$this->SetValue('PowerlineDevices', count($devices));
|
||||
$this->SetValue('PowerlineTxRate', $maxTx);
|
||||
$this->SetValue('PowerlineRxRate', $maxRx);
|
||||
$topology = ['updated' => date('c'), 'localMac' => $localMac, 'devices' => $devices, 'links' => $links];
|
||||
$this->WriteAttributeString('NetworkTopology', json_encode($topology));
|
||||
$this->SetValue('NetworkOverview', json_encode($topology, JSON_UNESCAPED_SLASHES));
|
||||
}
|
||||
|
||||
private function SetLed(bool $enabled): void
|
||||
{
|
||||
$endpoint = $this->GetEndpoints()['device'];
|
||||
if ($endpoint === null || !in_array('led', $this->Features($endpoint), true)) {
|
||||
throw new RuntimeException('Dieser Adapter meldet keine steuerbare LED-Funktion.', self::STATUS_DISCOVERY);
|
||||
}
|
||||
$response = self::DecodeMessage($this->HttpPost($endpoint['url'], 'LedSettingsSet', self::EncodeVarintField(1, $enabled ? 0 : 1)));
|
||||
if (self::FirstVarint($response, 1) !== 0) {
|
||||
throw new RuntimeException('LED-Einstellung wurde vom Adapter abgelehnt.', self::STATUS_COMMUNICATION);
|
||||
}
|
||||
$this->SetValue('LedEnabled', $enabled);
|
||||
}
|
||||
|
||||
private function SetGuestWiFi(bool $enabled): void
|
||||
{
|
||||
$endpoint = $this->GetEndpoints()['device'];
|
||||
if ($endpoint === null || !in_array('wifi1', $this->Features($endpoint), true)) {
|
||||
throw new RuntimeException('Dieser Adapter meldet keine Gäste-WLAN-Funktion.', self::STATUS_DISCOVERY);
|
||||
}
|
||||
$payload = self::EncodeVarintField(1, $enabled ? 1 : 0);
|
||||
if ($enabled) {
|
||||
$payload .= self::EncodeVarintField(2, max(0, $this->ReadPropertyInteger('GuestWiFiDuration')));
|
||||
}
|
||||
$response = self::DecodeMessage($this->HttpPost($endpoint['url'], 'WifiGuestAccessSet', $payload));
|
||||
if (self::FirstVarint($response, 1) !== 0) {
|
||||
throw new RuntimeException('Gäste-WLAN-Einstellung wurde vom Adapter abgelehnt.', self::STATUS_COMMUNICATION);
|
||||
}
|
||||
$this->SetValue('GuestWiFi', $enabled);
|
||||
}
|
||||
|
||||
private function Features(array $endpoint): array
|
||||
{
|
||||
return array_values(array_filter(array_map('trim', explode(',', strtolower((string) ($endpoint['properties']['Features'] ?? ''))))));
|
||||
}
|
||||
|
||||
private function HttpGet(string $baseUrl, string $endpoint): string
|
||||
{
|
||||
return $this->HttpRequest('GET', $baseUrl, $endpoint, '');
|
||||
}
|
||||
|
||||
private function HttpPost(string $baseUrl, string $endpoint, string $payload): string
|
||||
{
|
||||
return $this->HttpRequest('POST', $baseUrl, $endpoint, $payload);
|
||||
}
|
||||
|
||||
private function HttpRequest(string $method, string $baseUrl, string $endpoint, string $payload): string
|
||||
{
|
||||
$url = rtrim($baseUrl, '/') . '/' . rawurlencode($endpoint);
|
||||
$password = $this->ReadPropertyString('Password');
|
||||
$response = $this->ExecuteCurlRequest($method, $url, $payload, $password);
|
||||
if ($response['status'] === 401 && $password !== '') {
|
||||
$response = $this->ExecuteCurlRequest($method, $url, $payload, hash('sha256', $password));
|
||||
}
|
||||
if ($response['error'] !== '') {
|
||||
throw new RuntimeException('Verbindung zu ' . $this->HostForLog($url) . ' fehlgeschlagen: ' . $response['error'], self::STATUS_COMMUNICATION);
|
||||
}
|
||||
if ($response['status'] === 401 || $response['status'] === 403) {
|
||||
throw new RuntimeException('Gerätepasswort wurde abgelehnt.', self::STATUS_AUTHENTICATION);
|
||||
}
|
||||
if ($response['status'] < 200 || $response['status'] >= 300 || $response['body'] === '') {
|
||||
throw new RuntimeException('Magic-API antwortet für ' . $endpoint . ' mit HTTP ' . $response['status'] . '.', self::STATUS_COMMUNICATION);
|
||||
}
|
||||
return $response['body'];
|
||||
}
|
||||
|
||||
private function ExecuteCurlRequest(string $method, string $url, string $payload, string $password): array
|
||||
{
|
||||
$curl = curl_init();
|
||||
if ($curl === false) {
|
||||
throw new RuntimeException('cURL konnte nicht initialisiert werden.', self::STATUS_COMMUNICATION);
|
||||
}
|
||||
$headers = ['Accept: application/x-protobuf'];
|
||||
if ($method === 'POST') {
|
||||
$headers[] = 'Content-Type: application/x-protobuf';
|
||||
}
|
||||
curl_setopt_array($curl, [CURLOPT_URL => $url, CURLOPT_RETURNTRANSFER => true, CURLOPT_CUSTOMREQUEST => $method, CURLOPT_USERPWD => 'devolo:' . $password, CURLOPT_HTTPAUTH => CURLAUTH_DIGEST, CURLOPT_CONNECTTIMEOUT => 5, CURLOPT_TIMEOUT => 15, CURLOPT_FOLLOWLOCATION => false, CURLOPT_HTTPHEADER => $headers, CURLOPT_POSTFIELDS => $method === 'POST' ? $payload : null]);
|
||||
$body = curl_exec($curl);
|
||||
$result = ['body' => is_string($body) ? $body : '', 'status' => (int) curl_getinfo($curl, CURLINFO_RESPONSE_CODE), 'error' => curl_errno($curl) === 0 ? '' : curl_error($curl)];
|
||||
curl_close($curl);
|
||||
return $result;
|
||||
}
|
||||
|
||||
private function GetTopologyMessage(): string
|
||||
{
|
||||
$topology = $this->ReadJsonAttribute('NetworkTopology');
|
||||
$topology['online'] = $this->GetStatus() === IS_ACTIVE;
|
||||
$topology['error'] = $this->ReadAttributeString('LastError');
|
||||
$topology['updated'] = $topology['updated'] ?? '';
|
||||
$topology['devices'] = $topology['devices'] ?? [];
|
||||
$topology['links'] = $topology['links'] ?? [];
|
||||
return json_encode($topology, JSON_UNESCAPED_SLASHES) ?: '{}';
|
||||
}
|
||||
|
||||
private function SendTopology(): void { $this->UpdateVisualizationValue($this->GetTopologyMessage()); }
|
||||
private function WriteError(string $error): void { $this->WriteAttributeString('LastError', $error); $this->SetValue('LastError', $error); }
|
||||
private function ReadJsonAttribute(string $name): array { $data = json_decode($this->ReadAttributeString($name), true); return is_array($data) ? $data : []; }
|
||||
private function ServiceSummary(string $title, array $service): string { return $title . ': ' . ($service['url'] ?? 'noch nicht gefunden'); }
|
||||
private function NormalizeHost(string $host): string { $host = strtolower(rtrim(trim($host), '.')); return str_ends_with($host, '.local') ? substr($host, 0, -6) : $host; }
|
||||
private static function NormalizeMac(string $mac): string { return strtolower((string) preg_replace('/[^a-f0-9]/i', '', $mac)); }
|
||||
private function HostForLog(string $url): string { $parts = parse_url($url); return is_array($parts) ? (string) ($parts['host'] ?? $url) : $url; }
|
||||
|
||||
/** @return array<int, array<int, array{wire: int, value: int|string}>> */
|
||||
private static function DecodeMessage(string $data): array
|
||||
{
|
||||
$offset = 0;
|
||||
$result = [];
|
||||
while ($offset < strlen($data)) {
|
||||
$key = self::ReadVarint($data, $offset);
|
||||
$field = $key >> 3;
|
||||
$wire = $key & 0x07;
|
||||
if ($field === 0) {
|
||||
throw new RuntimeException('Ungültige Protobuf-Nachricht.', self::STATUS_COMMUNICATION);
|
||||
}
|
||||
if ($wire === 0) {
|
||||
$value = self::ReadVarint($data, $offset);
|
||||
} elseif ($wire === 1) {
|
||||
$value = self::ReadBytes($data, $offset, 8);
|
||||
} elseif ($wire === 2) {
|
||||
$value = self::ReadBytes($data, $offset, self::ReadVarint($data, $offset));
|
||||
} elseif ($wire === 5) {
|
||||
$value = self::ReadBytes($data, $offset, 4);
|
||||
} else {
|
||||
throw new RuntimeException('Nicht unterstützter Protobuf-Wire-Type.', self::STATUS_COMMUNICATION);
|
||||
}
|
||||
$result[$field][] = ['wire' => $wire, 'value' => $value];
|
||||
}
|
||||
return $result;
|
||||
}
|
||||
|
||||
private static function ReadVarint(string $data, int &$offset): int
|
||||
{
|
||||
$value = 0;
|
||||
$shift = 0;
|
||||
while ($offset < strlen($data) && $shift < 63) {
|
||||
$byte = ord($data[$offset++]);
|
||||
$value |= ($byte & 0x7f) << $shift;
|
||||
if (($byte & 0x80) === 0) {
|
||||
return $value;
|
||||
}
|
||||
$shift += 7;
|
||||
}
|
||||
throw new RuntimeException('Unvollständige Protobuf-Varint.', self::STATUS_COMMUNICATION);
|
||||
}
|
||||
|
||||
private static function ReadBytes(string $data, int &$offset, int $count): string
|
||||
{
|
||||
if ($count < 0 || $offset + $count > strlen($data)) {
|
||||
throw new RuntimeException('Unvollständige Protobuf-Daten.', self::STATUS_COMMUNICATION);
|
||||
}
|
||||
$value = substr($data, $offset, $count);
|
||||
$offset += $count;
|
||||
return $value;
|
||||
}
|
||||
|
||||
private static function FirstVarint(array $message, int $field): int { $entry = $message[$field][0] ?? null; return is_array($entry) && $entry['wire'] === 0 ? (int) $entry['value'] : 0; }
|
||||
private static function FirstBytes(array $message, int $field): string { $entry = $message[$field][0] ?? null; return is_array($entry) && $entry['wire'] === 2 ? (string) $entry['value'] : ''; }
|
||||
private static function FirstText(array $message, int $field): string { return trim(self::FirstBytes($message, $field)); }
|
||||
private static function FirstMessage(array $message, int $field): array { $bytes = self::FirstBytes($message, $field); return $bytes === '' ? [] : self::DecodeMessage($bytes); }
|
||||
private static function FirstDouble(array $message, int $field): float { $entry = $message[$field][0] ?? null; return !is_array($entry) || $entry['wire'] !== 1 || strlen((string) $entry['value']) !== 8 ? 0.0 : (float) unpack('evalue', $entry['value'])['value']; }
|
||||
private static function Messages(array $message, int $field): array { $result = []; foreach ($message[$field] ?? [] as $entry) { if ($entry['wire'] === 2 && $entry['value'] !== '') { $result[] = self::DecodeMessage($entry['value']); } } return $result; }
|
||||
private static function MapValue(int $value, array $map): string { return $map[$value] ?? 'unbekannt'; }
|
||||
private static function EncodeVarintField(int $field, int $value): string { return self::EncodeVarint($field << 3) . self::EncodeVarint($value); }
|
||||
private static function EncodeVarint(int $value): string { $bytes = ''; do { $byte = $value & 0x7f; $value >>= 7; $bytes .= chr($value > 0 ? $byte | 0x80 : $byte); } while ($value > 0); return $bytes; }
|
||||
}
|
||||
Reference in new issue
Block a user