first commit
This commit is contained in:
commit
403a19ac85
158 files changed
+25101
No files matched your search
@@ -0,0 +1,109 @@
|
||||
<style>
|
||||
body { margin: 0; overflow: hidden; font-family: Arial, sans-serif; color: #303742; }
|
||||
.devolo-topology { height: 100%; min-height: 250px; display: flex; flex-direction: column; }
|
||||
.devolo-toolbar { display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 4px 8px; font-size: 12px; }
|
||||
.devolo-status { display: flex; align-items: center; gap: 6px; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.devolo-dot { width: 9px; height: 9px; border-radius: 50%; background: #9aa4b2; flex: 0 0 auto; }
|
||||
.devolo-dot.online { background: #2b9b69; box-shadow: 0 0 0 3px rgba(43, 155, 105, .16); }
|
||||
.devolo-dot.error { background: #c84c4c; box-shadow: 0 0 0 3px rgba(200, 76, 76, .16); }
|
||||
.devolo-refresh { border: 0; border-radius: 4px; padding: 4px 8px; background: #e7edf3; color: inherit; cursor: pointer; }
|
||||
.devolo-refresh:hover { background: #d5e1eb; }
|
||||
.devolo-canvas { flex: 1; min-height: 0; width: 100%; }
|
||||
.devolo-link { fill: none; stroke: #8ca1b3; stroke-width: 3; stroke-linecap: round; opacity: .72; }
|
||||
.devolo-link.active { stroke: #2a8ac5; stroke-dasharray: 10 8; animation: devolo-flow 2.4s linear infinite; }
|
||||
.devolo-rate { fill: #52616f; font-size: 11px; text-anchor: middle; paint-order: stroke; stroke: #fff; stroke-width: 3px; stroke-linejoin: round; }
|
||||
.devolo-node { cursor: default; }
|
||||
.devolo-node circle { fill: #f5f8fb; stroke: #7891a6; stroke-width: 2; }
|
||||
.devolo-node.local circle { fill: #e2f2fb; stroke: #217bb2; stroke-width: 3; }
|
||||
.devolo-node text { fill: #27313b; text-anchor: middle; pointer-events: none; }
|
||||
.devolo-name { font-size: 12px; font-weight: bold; }
|
||||
.devolo-product { font-size: 10px; fill: #617080 !important; }
|
||||
.devolo-empty { fill: #687584; text-anchor: middle; font-size: 14px; }
|
||||
@keyframes devolo-flow { to { stroke-dashoffset: -36; } }
|
||||
@media (prefers-reduced-motion: reduce) { .devolo-link.active { animation: none; } }
|
||||
@media (prefers-color-scheme: dark) {
|
||||
body { color: #e7eef5; background: #1d2730; }
|
||||
.devolo-refresh { background: #334552; color: #e7eef5; }
|
||||
.devolo-refresh:hover { background: #405663; }
|
||||
.devolo-rate { fill: #d3dde5; stroke: #1d2730; }
|
||||
.devolo-node circle { fill: #263541; stroke: #91a8ba; }
|
||||
.devolo-node.local circle { fill: #17425d; stroke: #58a9d9; }
|
||||
.devolo-node text { fill: #f1f6fa; }
|
||||
.devolo-node .devolo-product { fill: #bed0dd !important; }
|
||||
.devolo-empty { fill: #bed0dd; }
|
||||
}
|
||||
</style>
|
||||
<div class="devolo-topology">
|
||||
<div class="devolo-toolbar">
|
||||
<div class="devolo-status"><span id="devolo-dot" class="devolo-dot"></span><span id="devolo-status">Noch keine Netzwerkdaten</span></div>
|
||||
<button class="devolo-refresh" type="button" onclick="if (window.requestAction) { requestAction('Refresh', true); }">Aktualisieren</button>
|
||||
</div>
|
||||
<svg id="devolo-canvas" class="devolo-canvas" viewBox="0 0 600 310" preserveAspectRatio="xMidYMid meet" role="img" aria-label="Devolo Powerline-Netzwerktopologie">
|
||||
<defs><marker id="devolo-arrow" viewBox="0 0 10 10" refX="8" refY="5" markerWidth="5" markerHeight="5" orient="auto-start-reverse"><path d="M 0 0 L 10 5 L 0 10 z" fill="#2a8ac5"></path></marker></defs>
|
||||
<g id="devolo-graph"></g>
|
||||
</svg>
|
||||
</div>
|
||||
<script>
|
||||
const devoloSvg = 'http://www.w3.org/2000/svg';
|
||||
function devoloElement(type, attributes, text) {
|
||||
const element = document.createElementNS(devoloSvg, type);
|
||||
Object.keys(attributes || {}).forEach(key => element.setAttribute(key, attributes[key]));
|
||||
if (text !== undefined) element.textContent = text;
|
||||
return element;
|
||||
}
|
||||
function devoloMac(value) { return String(value || '').replace(/[^a-f0-9]/ig, '').toLowerCase(); }
|
||||
function devoloShort(value, max) { value = String(value || 'Unbekannter Adapter'); return value.length > max ? value.slice(0, max - 1) + '…' : value; }
|
||||
function devoloRate(value) { return Number(value || 0).toLocaleString('de-DE', { maximumFractionDigits: 0 }); }
|
||||
function handleMessage(message) {
|
||||
let data = message;
|
||||
if (typeof message === 'string') {
|
||||
try { data = JSON.parse(message); } catch (_) { data = {}; }
|
||||
}
|
||||
const graph = document.getElementById('devolo-graph');
|
||||
const status = document.getElementById('devolo-status');
|
||||
const dot = document.getElementById('devolo-dot');
|
||||
if (!graph || !status || !dot) return;
|
||||
graph.replaceChildren();
|
||||
const devices = Array.isArray(data.devices) ? data.devices : [];
|
||||
const links = Array.isArray(data.links) ? data.links : [];
|
||||
const online = Boolean(data.online);
|
||||
dot.className = 'devolo-dot ' + (online ? 'online' : (data.error ? 'error' : ''));
|
||||
status.textContent = data.error || (devices.length ? (devices.length + ' Magic-Adapter · ' + (data.updated ? new Date(data.updated).toLocaleTimeString('de-DE') : 'aktuell')) : 'Noch keine Netzwerkdaten');
|
||||
if (!devices.length) {
|
||||
graph.appendChild(devoloElement('text', { x: 300, y: 155, class: 'devolo-empty' }, 'Beim nächsten Abruf erscheint hier die Powerline-Topologie.'));
|
||||
return;
|
||||
}
|
||||
const localMac = devoloMac(data.localMac);
|
||||
let localIndex = devices.findIndex(device => device.local || devoloMac(device.mac) === localMac);
|
||||
if (localIndex < 0) localIndex = 0;
|
||||
const positions = new Map();
|
||||
const remotes = devices.filter((_, index) => index !== localIndex);
|
||||
devices.forEach((device, index) => {
|
||||
if (index === localIndex) {
|
||||
positions.set(devoloMac(device.mac), { x: 300, y: 155 });
|
||||
return;
|
||||
}
|
||||
const remoteIndex = remotes.indexOf(device);
|
||||
const angle = -Math.PI / 2 + (Math.PI * 2 * remoteIndex / Math.max(remotes.length, 1));
|
||||
positions.set(devoloMac(device.mac), { x: 300 + 210 * Math.cos(angle), y: 155 + 105 * Math.sin(angle) });
|
||||
});
|
||||
links.forEach(link => {
|
||||
const from = positions.get(devoloMac(link.from));
|
||||
const to = positions.get(devoloMac(link.to));
|
||||
if (!from || !to) return;
|
||||
const tx = Number(link.tx || 0), rx = Number(link.rx || 0), active = tx > 0 || rx > 0;
|
||||
const path = devoloElement('line', { x1: from.x, y1: from.y, x2: to.x, y2: to.y, class: 'devolo-link' + (active ? ' active' : ''), 'marker-end': active ? 'url(#devolo-arrow)' : '' });
|
||||
if (active) path.style.animationDuration = Math.max(0.8, 3.8 - Math.min(2.7, Math.max(tx, rx) / 850)) + 's';
|
||||
graph.appendChild(path);
|
||||
graph.appendChild(devoloElement('text', { x: (from.x + to.x) / 2, y: (from.y + to.y) / 2 - 6, class: 'devolo-rate' }, devoloRate(tx) + ' ↔ ' + devoloRate(rx) + ' Mbit/s'));
|
||||
});
|
||||
devices.forEach((device, index) => {
|
||||
const pos = positions.get(devoloMac(device.mac));
|
||||
const group = devoloElement('g', { class: 'devolo-node' + (index === localIndex ? ' local' : '') });
|
||||
group.appendChild(devoloElement('circle', { cx: pos.x, cy: pos.y, r: index === localIndex ? 36 : 30 }));
|
||||
group.appendChild(devoloElement('text', { x: pos.x, y: pos.y - 3, class: 'devolo-name' }, devoloShort(device.userDeviceName || device.productName || device.mac, 18)));
|
||||
group.appendChild(devoloElement('text', { x: pos.x, y: pos.y + 13, class: 'devolo-product' }, devoloShort(device.productName || device.technology || 'Magic', 20)));
|
||||
graph.appendChild(group);
|
||||
});
|
||||
}
|
||||
</script>
|
||||
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"id": "{09C49C6D-AF55-444E-8C5D-B50A90232E3A}",
|
||||
"name": "Devolo Magic",
|
||||
"type": 3,
|
||||
"vendor": "devolo",
|
||||
"aliases": ["Magic 1 / Magic 2 Netzwerkadapter"],
|
||||
"parentRequirements": [],
|
||||
"childRequirements": [],
|
||||
"implemented": [],
|
||||
"prefix": "DevoloMagic",
|
||||
"url": "https://github.com/demel42/IPSymconDevoloPLC"
|
||||
}
|
||||
@@ -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; }
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"translations": {
|
||||
"de": {}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user