Files
NextFloor/symcon/NextFloor/module.php
T

841 lines
35 KiB
PHP

<?php
declare(strict_types=1);
/**
* NextFloor for IP-Symcon.
*
* One visualization instance owns a floor-plan project. Its protected WebHook serves the designer as
* a console tab and the same viewer in an HTML-SDK tile iframe. The frontend receives every variable
* in the object tree with a friendly path; it never asks an end user to type an object id.
*/
class NextFloor extends IPSModuleStrict
{
private const MAX_BUILDING_BYTES = 8_000_000;
private const MAX_IMAGE_BYTES = 8_000_000;
private const MAX_HISTORY = 20;
public function Create(): void
{
parent::Create();
$this->RegisterPropertyString('Title', 'NextFloor');
$this->RegisterAttributeString('Building', '');
$this->RegisterAttributeString('Images', '{}');
$this->RegisterAttributeString('Packs', '[]');
$this->RegisterAttributeString('History', '[]');
$this->RegisterAttributeString('AccessToken', '');
$this->RegisterAttributeString('StateHash', '');
$this->RegisterAttributeString('HookError', '');
$this->RegisterAttributeInteger('BuildingRevision', 0);
$this->RegisterAttributeInteger('StateRevision', 0);
$this->RegisterMessage(0, IPS_KERNELSTARTED);
$this->RegisterTimer('WebHookRetry', 0, 'NFSC_RetryWebHook($_IPS[\'TARGET\']);');
$this->ensureAccessToken();
$this->SetVisualizationType(1);
$this->ensureWebHook();
}
public function ApplyChanges(): void
{
parent::ApplyChanges();
$this->SetVisualizationType(1);
$this->ensureWebHook();
}
public function MessageSink(int $TimeStamp, int $SenderID, int $Message, array $Data): void
{
parent::MessageSink($TimeStamp, $SenderID, $Message, $Data);
if ($SenderID === 0 && $Message === IPS_KERNELSTARTED) {
$this->ensureWebHook();
}
}
/** Timer callback; stops itself as soon as the volatile hook has been restored. */
public function RetryWebHook(): void
{
$this->ensureWebHook();
}
/** Explicit recovery from the console without recreating the instance or changing its project. */
public function RepairWebHook(): string
{
if (!$this->ensureWebHook()) {
return $this->hookErrorMessage();
}
return 'WebHook registriert: /hook/' . $this->hookPath() . '. Jetzt den Designer öffnen.';
}
/** URL returned to the console form. It opens in a console tab, as IPSView does. */
public function OpenDesigner(): string
{
$this->requireWebHook();
// `link:` is the documented Form-Button marker for a relative Symcon WebHook URL.
return 'link:' . $this->designerUrl('designer');
}
/** Invalidates links from copied browser history and returns a fresh designer URL. */
public function RotateAccessToken(): string
{
$this->requireWebHook();
$this->WriteAttributeString('AccessToken', $this->newToken());
return 'link:' . $this->designerUrl('designer');
}
/** The custom tile is deliberately an iframe: the full 3D viewer can lazy-load its assets via the same protected hook. */
public function GetVisualizationTile(): string
{
if (!$this->ensureWebHook()) {
return '<div style="padding:16px;font-family:system-ui">'
. htmlspecialchars($this->hookErrorMessage(), ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8') . '</div>';
}
$src = htmlspecialchars($this->designerUrl('tile'), ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
return '<style>html,body{margin:0;width:100%;height:100%;overflow:hidden}iframe{display:block;width:100%;height:100%;min-height:260px;border:0;background:#111}</style>'
. '<iframe title="NextFloor" src="' . $src . '" loading="eager" allow="fullscreen"></iframe>';
}
/** IP-Symcon calls this for /hook/nextfloor/<instance id>/... */
protected function ProcessHookData(): void
{
$requestPath = (string) ($_SERVER['REQUEST_URI'] ?? '');
if ($requestPath === '') {
$requestPath = (string) ($_SERVER['SCRIPT_NAME'] ?? '');
}
$path = (string) (parse_url($requestPath, PHP_URL_PATH) ?? '');
$prefix = '/hook/' . $this->hookPath();
if (!str_starts_with($path, $prefix)) {
$this->sendError(404, 'not_found');
return;
}
if (!$this->hasValidToken()) {
$this->sendError(403, 'forbidden');
return;
}
$tail = trim(substr($path, strlen($prefix)), '/');
try {
if ($tail === '' || $tail === 'designer') {
$this->sendDesignerPage();
return;
}
if ($tail === 'api') {
$this->handleApi();
return;
}
if (str_starts_with($tail, 'assets/')) {
$this->sendAsset(substr($tail, strlen('assets/')));
return;
}
$this->sendError(404, 'not_found');
} catch (Throwable $error) {
$this->LogMessage('WebHook error: ' . $error->getMessage(), KL_ERROR);
$this->sendError(500, 'internal_error');
}
}
// --------------------------------------------------------------------- WebHook pages
private function ensureWebHook(): bool
{
// Native hooks are volatile. Create/ApplyChanges can run before WebHook Control is ready;
// register again after the kernel has started and whenever a designer/tile link is requested.
if (IPS_GetKernelRunlevel() !== KR_READY) {
$this->SetStatus(104);
$this->SetTimerInterval('WebHookRetry', 5000);
return false;
}
try {
$registered = $this->RegisterHook($this->hookPath());
// Older native implementations return void; an explicit false reports rejection.
if ($registered === false) {
throw new RuntimeException('Symcon hat die Registrierung von /hook/' . $this->hookPath() . ' abgelehnt.');
}
} catch (Throwable $error) {
$message = $error->getMessage();
if ($message !== $this->ReadAttributeString('HookError')) {
$this->LogMessage('WebHook-Registrierung fehlgeschlagen: ' . $message, KL_ERROR);
}
$this->WriteAttributeString('HookError', $message);
$this->SetStatus(200);
$this->SetTimerInterval('WebHookRetry', 5000);
return false;
}
$this->WriteAttributeString('HookError', '');
$this->SetTimerInterval('WebHookRetry', 0);
$this->SetStatus(102);
return true;
}
private function requireWebHook(): void
{
if (!$this->ensureWebHook()) {
throw new RuntimeException($this->hookErrorMessage());
}
}
private function hookErrorMessage(): string
{
if (IPS_GetKernelRunlevel() !== KR_READY) {
return 'IP-Symcon startet noch. Der NextFloor-WebHook wird nach dem Start automatisch registriert.';
}
return 'NextFloor-WebHook nicht verfügbar: ' . $this->ReadAttributeString('HookError')
. ' Bitte in der NextFloor-Instanz „WebHook reparieren“ ausführen.';
}
private function hookPath(): string
{
return 'nextfloor/' . $this->InstanceID;
}
private function designerUrl(string $mode): string
{
return '/hook/' . $this->hookPath() . '/designer?mode=' . rawurlencode($mode) . '&token=' . rawurlencode($this->ensureAccessToken());
}
private function ensureAccessToken(): string
{
$token = $this->ReadAttributeString('AccessToken');
if ($token === '') {
$token = $this->newToken();
$this->WriteAttributeString('AccessToken', $token);
}
return $token;
}
private function newToken(): string
{
return bin2hex(random_bytes(32));
}
private function hasValidToken(): bool
{
// The first HTML request carries the random URL token. It also sets an HttpOnly cookie
// below, so lazy ES-module imports (which cannot inherit a query string) stay protected.
$provided = (string) ($_GET['token'] ?? $_COOKIE[$this->cookieName()] ?? '');
return $provided !== '' && hash_equals($this->ensureAccessToken(), $provided);
}
private function cookieName(): string
{
return 'NFSC_' . $this->InstanceID;
}
private function setAccessCookie(): void
{
setcookie($this->cookieName(), $this->ensureAccessToken(), [
'expires' => 0,
'path' => '/hook/' . $this->hookPath() . '/',
'secure' => (($_SERVER['HTTPS'] ?? '') !== '' && ($_SERVER['HTTPS'] ?? '') !== 'off'),
'httponly' => true,
'samesite' => 'Strict'
]);
}
private function sendDesignerPage(): void
{
$this->setAccessCookie();
$config = [
'endpoint' => '/hook/' . $this->hookPath(),
'token' => $this->ensureAccessToken(),
'language' => 'de',
'title' => $this->ReadPropertyString('Title') ?: 'NextFloor'
];
$asset = '/hook/' . $this->hookPath() . '/assets/nextfloor-designer.js?v=' . rawurlencode($this->moduleVersion())
. '&token=' . rawurlencode($this->ensureAccessToken());
header('Content-Type: text/html; charset=utf-8');
header('Cache-Control: no-store');
echo '<!doctype html><html lang="de"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">'
. '<title>' . htmlspecialchars($config['title'], ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8') . '</title>'
. '<style>html,body{width:100%;height:100%;margin:0;background:#111;color:#e1e1e1}body>nextfloor-panel,body>nextfloor-card{display:block;width:100%;height:100%}</style>'
. '</head><body><p style="padding:1rem;font-family:system-ui">NextFloor wird geladen …</p>'
. '<script>window.__NEXTFLOOR_SYMCON__=' . json_encode($config, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) . ';</script>'
. '<script type="module" src="' . htmlspecialchars($asset, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8') . '"></script></body></html>';
}
private function sendAsset(string $asset): void
{
// Only build artifacts are public through the authenticated hook. No request can escape the module folder.
if (!preg_match('#^(?:nextfloor-(?:designer|3d|editor|card-editor)\\.js|lang/[a-z]{2}\\.json)$#', $asset)) {
$this->sendError(404, 'asset_not_found');
return;
}
$file = __DIR__ . '/assets/' . $asset;
if (!is_file($file)) {
$this->sendError(503, 'assets_not_built');
return;
}
header('Content-Type: ' . (str_ends_with($asset, '.json') ? 'application/json; charset=utf-8' : 'text/javascript; charset=utf-8'));
header('Cache-Control: private, max-age=3600');
readfile($file);
}
// --------------------------------------------------------------------- JSON API
private function handleApi(): void
{
if (($_SERVER['REQUEST_METHOD'] ?? 'GET') !== 'POST') {
$this->sendError(405, 'method_not_allowed');
return;
}
$request = json_decode((string) file_get_contents('php://input'), true);
if (!is_array($request) || !is_string($request['action'] ?? null)) {
$this->sendError(400, 'invalid_request');
return;
}
try {
$result = match ($request['action']) {
'bootstrap' => $this->bootstrap(),
'variables/snapshot' => $this->variablesSnapshot((int) ($request['revision'] ?? -1)),
'building/get' => ['building' => $this->building(), 'revision' => $this->ReadAttributeInteger('BuildingRevision'), 'version' => $this->moduleVersion()],
'building/save' => ['revision' => $this->saveBuilding($this->arrayValue($request, 'building'))],
'image/get' => $this->imageGet((string) ($request['image_id'] ?? '')),
'image/set' => $this->imageSet((string) ($request['image_id'] ?? ''), (string) ($request['data'] ?? '')),
'image/delete' => $this->imageDelete((string) ($request['image_id'] ?? '')),
'packs/list' => ['packs' => $this->allPacks()],
'packs/import' => $this->packImport((string) ($request['pack'] ?? '')),
'packs/remove' => $this->packRemove((string) ($request['pack_id'] ?? '')),
'history/list' => ['snapshots' => $this->historyList()],
'history/snapshot' => ['id' => $this->takeSnapshot(isset($request['name']) ? (string) $request['name'] : null)],
'history/get' => $this->historyGet((string) ($request['snapshot_id'] ?? '')),
'history/restore' => $this->historyRestore((string) ($request['snapshot_id'] ?? '')),
'history/delete' => $this->historyDelete((string) ($request['snapshot_id'] ?? '')),
'backup/export' => ['format' => 'nextfloor-backup', 'version' => 1, 'building' => $this->building(), 'packs' => $this->importedPacks()],
'backup/import' => $this->backupImport($this->arrayValue($request, 'building'), $request['packs'] ?? []),
'variables/action' => $this->variableAction((string) ($request['domain'] ?? ''), (string) ($request['service'] ?? ''), $this->arrayValue($request, 'data')),
default => throw new RuntimeException('unknown_action')
};
$this->sendJson($result);
} catch (InvalidArgumentException $error) {
$this->sendError(400, $error->getMessage());
} catch (RuntimeException $error) {
$this->sendError(404, $error->getMessage());
}
}
private function bootstrap(): array
{
$objects = $this->objectTree();
$stateRevision = $this->stateRevision($objects);
return [
'state_revision' => $stateRevision,
'building_revision' => $this->ReadAttributeInteger('BuildingRevision'),
'variables' => $objects['variables'],
'areas' => $objects['areas'],
'objects' => $objects['objects']
];
}
private function variablesSnapshot(int $knownRevision): array
{
$objects = $this->objectTree();
$stateRevision = $this->stateRevision($objects);
$result = [
'state_revision' => $stateRevision,
'building_revision' => $this->ReadAttributeInteger('BuildingRevision')
];
if ($stateRevision !== $knownRevision) {
$result['variables'] = $objects['variables'];
$result['areas'] = $objects['areas'];
$result['objects'] = $objects['objects'];
}
return $result;
}
/** Export real object nodes, not paths reconstructed from variable names. */
private function objectTree(): array
{
$variables = [];
$areas = [];
$nodes = [];
foreach (IPS_GetChildrenIDs(0) as $child) {
$this->collectObjects($child, [], null, $variables, $areas, $nodes);
}
$byVariable = [];
foreach ($variables as $variable) {
$byVariable[$variable['attributes']['symcon_id']] = $variable['entity_id'];
}
// A link stays at its original position in the tree and selects its target variable.
foreach ($nodes as &$node) {
if ($node['object_type'] === 6) {
$target = (int) IPS_GetLink($node['object_id'])['TargetID'];
if (isset($byVariable[$target])) {
$node['entity_id'] = $byVariable[$target];
}
}
}
unset($node);
usort($variables, static fn(array $a, array $b): int => strnatcasecmp($a['path'], $b['path']));
usort($areas, static fn(array $a, array $b): int => strnatcasecmp($a['name'], $b['name']));
return ['variables' => $variables, 'areas' => $areas, 'objects' => $nodes];
}
private function collectObjects(int $objectID, array $parents, ?int $nearestCategory, array &$variables, array &$areas, array &$nodes): void
{
if (!IPS_ObjectExists($objectID)) {
return;
}
$object = IPS_GetObject($objectID);
$name = IPS_GetName($objectID);
$path = [...$parents, $name];
$type = (int) $object['ObjectType'];
$node = [
'object_id' => $objectID,
'parent_id' => (int) $object['ParentID'],
'name' => $name,
'path' => implode(' / ', $path),
'object_type' => $type,
'position' => (int) $object['ObjectPosition'],
'hidden' => (bool) $object['ObjectIsHidden'],
'icon' => (string) $object['ObjectIcon']
];
if ($type === 1) { // OBJECTTYPE_INSTANCE: the logical console view separates system modules.
$node['module_type'] = (int) IPS_GetInstance($objectID)['ModuleInfo']['ModuleType'];
}
if ($type === 0) { // OBJECTTYPE_CATEGORY
$nearestCategory = $objectID;
$areas[] = ['area_id' => 'symcon-category-' . $objectID, 'name' => implode(' / ', $path)];
}
if ($type === 2) { // OBJECTTYPE_VARIABLE
$variable = $this->describeVariable($objectID, $name, implode(' / ', $path), $nearestCategory);
$variables[] = $variable;
$node['entity_id'] = $variable['entity_id'];
}
$nodes[] = $node;
foreach (IPS_GetChildrenIDs($objectID) as $child) {
$this->collectObjects($child, $path, $nearestCategory, $variables, $areas, $nodes);
}
}
private function describeVariable(int $variableID, string $name, string $path, ?int $categoryID): array
{
$variable = IPS_GetVariable($variableID);
$profile = (string) ($variable['VariableCustomProfile'] ?: $variable['VariableProfile']);
$value = GetValue($variableID);
$kind = $this->kindFor($variable, $profile, $name . ' ' . $path);
$attributes = [
'symcon_id' => $variableID,
'symcon_path' => $path,
'symcon_profile' => $profile,
'symcon_variable_type' => (int) $variable['VariableType'],
'symcon_has_action' => ((int) ($variable['VariableCustomAction'] ?: $variable['VariableAction'])) !== 0,
'symcon_formatted' => GetValueFormatted($variableID),
'device_class' => $this->deviceClassFor($profile, $name . ' ' . $path)
];
$profileData = $profile !== '' && IPS_VariableProfileExists($profile) ? IPS_GetVariableProfile($profile) : null;
if (is_array($profileData) && (string) ($profileData['Suffix'] ?? '') !== '') {
$attributes['unit_of_measurement'] = trim((string) $profileData['Suffix']);
}
if ($kind === 'light' && is_numeric($value)) {
$attributes['brightness'] = (int) round(max(0, min(100, (float) $value)) * 2.55);
$attributes['color_mode'] = 'brightness';
$attributes['supported_color_modes'] = ['brightness'];
}
if ($kind === 'cover' && is_numeric($value)) {
$attributes['current_position'] = max(0, min(100, (int) round((float) $value)));
$attributes['supported_features'] = 4;
}
if ($kind === 'climate' && is_numeric($value)) {
// A Symcon thermostat commonly exposes one writable setpoint. Present it as both
// target and current temperature so all existing NextFloor climate displays can use it.
$attributes['current_temperature'] = (float) $value;
$attributes['temperature'] = (float) $value;
$attributes['hvac_modes'] = ['off', 'heat'];
$attributes['hvac_action'] = (float) $value > 0 ? 'heating' : 'idle';
}
return [
'entity_id' => $kind . '.' . $variableID,
'name' => $name,
'path' => $path,
'state' => $this->stateFor($kind, $value),
'attributes' => $attributes,
'area_id' => $categoryID === null ? null : 'symcon-category-' . $categoryID,
'device_id' => 'symcon-variable-' . $variableID
];
}
private function kindFor(array $variable, string $profile, string $haystack): string
{
$text = mb_strtolower($profile . ' ' . $haystack);
$type = (int) $variable['VariableType'];
$action = (int) ($variable['VariableCustomAction'] ?: $variable['VariableAction']);
if (preg_match('/roll|jalous|raff|shutter|blind|markise|cover|tor|garage/', $text)) {
return 'cover';
}
if (preg_match('/schloss|lock/', $text)) {
return 'lock';
}
if ($action !== 0 && preg_match('/licht|lampe|light|dimm|intensity/', $text)) {
return 'light';
}
if ($action !== 0 && preg_match('/heizung|thermostat|heating|climate|hvac/', $text)) {
return 'climate';
}
if ($action !== 0 && preg_match('/szene|scene|script|taster|button/', $text)) {
return 'script';
}
if ($type === 0 && $action !== 0) {
return 'switch';
}
if ($type === 0) {
return 'binary_sensor';
}
return 'sensor';
}
private function deviceClassFor(string $profile, string $haystack): string
{
$text = mb_strtolower($profile . ' ' . $haystack);
return match (true) {
str_contains($text, 'temperature') || str_contains($text, 'temperatur') => 'temperature',
str_contains($text, 'humidity') || str_contains($text, 'feuchte') => 'humidity',
str_contains($text, 'co2') => 'carbon_dioxide',
str_contains($text, 'watt') || str_contains($text, 'power') || str_contains($text, 'leistung') => 'power',
preg_match('/kontakt|fenster|tür|tuer|motion|bewegung|presence|anwesen/', $text) === 1 => 'opening',
default => ''
};
}
private function stateFor(string $kind, mixed $value): string
{
if ($kind === 'cover' && is_numeric($value)) {
return (float) $value <= 0 ? 'closed' : ((float) $value >= 100 ? 'open' : 'opening');
}
if ($kind === 'light' && is_numeric($value)) {
return (float) $value > 0 ? 'on' : 'off';
}
if ($kind === 'lock' && is_bool($value)) {
return $value ? 'locked' : 'unlocked';
}
if ($kind === 'climate' && is_numeric($value)) {
return (float) $value > 0 ? 'heat' : 'off';
}
if (is_bool($value)) {
return $value ? 'on' : 'off';
}
if (is_float($value)) {
return rtrim(rtrim(sprintf('%.6F', $value), '0'), '.');
}
return (string) $value;
}
private function stateRevision(array $objects): int
{
$hash = hash('sha256', json_encode($objects, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE));
if (!hash_equals($this->ReadAttributeString('StateHash'), $hash)) {
$this->WriteAttributeString('StateHash', $hash);
$this->WriteAttributeInteger('StateRevision', $this->ReadAttributeInteger('StateRevision') + 1);
}
return $this->ReadAttributeInteger('StateRevision');
}
// --------------------------------------------------------------------- plan, packs, images and history
private function building(): array
{
$stored = $this->jsonAttribute('Building', null);
return is_array($stored) ? $stored : $this->emptyBuilding();
}
private function emptyBuilding(): array
{
return [
'version' => 1,
'floors' => [],
'settings' => ['wall_exterior' => 0.24, 'wall_interior' => 0.12, 'grid' => 0.05, 'north' => 0, 'roof' => ['type' => 'none', 'pitch' => 35, 'overhang' => 0.4]],
'energy' => ['meter' => null, 'grid' => null, 'grid_invert' => false, 'solar' => null, 'battery' => null, 'battery_invert' => false, 'battery_soc' => null, 'consumption' => null, 'tariff' => null],
'presence' => []
];
}
private function saveBuilding(array $building): int
{
if (($building['version'] ?? null) !== 1 || !is_array($building['floors'] ?? null) || !is_array($building['settings'] ?? null)) {
throw new InvalidArgumentException('invalid_building');
}
$encoded = json_encode($building, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR);
if (strlen($encoded) > self::MAX_BUILDING_BYTES) {
throw new InvalidArgumentException('building_too_large');
}
$this->WriteAttributeString('Building', $encoded);
$revision = $this->ReadAttributeInteger('BuildingRevision') + 1;
$this->WriteAttributeInteger('BuildingRevision', $revision);
$this->UpdateVisualizationValue(json_encode(['building_revision' => $revision]));
return $revision;
}
private function imageGet(string $imageID): array
{
$images = $this->jsonAttribute('Images', []);
if (!is_array($images) || !isset($images[$imageID])) {
throw new RuntimeException('not_found');
}
return ['data' => $images[$imageID]];
}
private function imageSet(string $imageID, string $data): array
{
if (!preg_match('/^[A-Za-z0-9_.-]{1,64}$/', $imageID) || !str_starts_with($data, 'data:image/') || strlen($data) > self::MAX_IMAGE_BYTES) {
throw new InvalidArgumentException('invalid_image');
}
$images = $this->jsonAttribute('Images', []);
$images[$imageID] = $data;
$this->writeJsonAttribute('Images', $images);
return [];
}
private function imageDelete(string $imageID): array
{
$images = $this->jsonAttribute('Images', []);
unset($images[$imageID]);
$this->writeJsonAttribute('Images', $images);
return [];
}
private function allPacks(): array
{
return [...$this->builtInPacks(), ...$this->importedPacks()];
}
private function builtInPacks(): array
{
$packs = [];
foreach (glob(__DIR__ . '/packs/*.json') ?: [] as $file) {
$pack = json_decode((string) file_get_contents($file), true);
if (is_array($pack) && is_string($pack['id'] ?? null) && is_array($pack['items'] ?? null)) {
$packs[] = [...$pack, 'builtin' => true];
}
}
return $packs;
}
private function importedPacks(): array
{
$packs = $this->jsonAttribute('Packs', []);
return is_array($packs) ? array_values($packs) : [];
}
private function packImport(string $source): array
{
$pack = json_decode($source, true);
if (!is_array($pack) || !is_string($pack['id'] ?? null) || !is_string($pack['name'] ?? null) || !is_array($pack['items'] ?? null)) {
throw new InvalidArgumentException('invalid_pack');
}
if (in_array($pack['id'], array_column($this->builtInPacks(), 'id'), true)) {
throw new InvalidArgumentException('builtin_pack');
}
$entry = [...$pack, 'imported_at' => time()];
$packs = array_values(array_filter($this->importedPacks(), static fn(array $old): bool => $old['id'] !== $entry['id']));
$packs[] = $entry;
$this->writeJsonAttribute('Packs', $packs);
return ['id' => $entry['id'], 'name' => $entry['name'], 'publisher' => (string) ($entry['publisher'] ?? ''), 'items' => count($entry['items'])];
}
private function packRemove(string $packID): array
{
$before = $this->importedPacks();
$after = array_values(array_filter($before, static fn(array $pack): bool => $pack['id'] !== $packID));
if (count($before) === count($after)) {
throw new RuntimeException('not_found');
}
$this->writeJsonAttribute('Packs', $after);
return [];
}
private function takeSnapshot(?string $name = null): string
{
$history = $this->history();
$id = substr(bin2hex(random_bytes(12)), 0, 12);
$entry = ['id' => $id, 'revision' => $this->ReadAttributeInteger('BuildingRevision'), 'saved_at' => time(), 'building' => $this->building()];
if ($name !== null && trim($name) !== '') {
$entry['name'] = mb_substr(trim($name), 0, 60);
}
$history[] = $entry;
$this->writeJsonAttribute('History', array_slice($history, -self::MAX_HISTORY));
return $id;
}
private function historyList(): array
{
$history = array_reverse($this->history());
return array_map(function (array $entry): array {
$building = is_array($entry['building'] ?? null) ? $entry['building'] : [];
return [
'id' => $entry['id'],
'revision' => $entry['revision'],
'saved_at' => $entry['saved_at'],
'floors' => count($building['floors'] ?? []),
'rooms' => array_sum(array_map(static fn(array $floor): int => count($floor['rooms'] ?? []), $building['floors'] ?? [])),
'furniture' => array_sum(array_map(static fn(array $floor): int => count($floor['furniture'] ?? []), $building['floors'] ?? [])),
...isset($entry['name']) ? ['name' => $entry['name']] : []
];
}, $history);
}
private function historyGet(string $id): array
{
foreach ($this->history() as $entry) {
if (($entry['id'] ?? '') === $id) {
return ['building' => $entry['building']];
}
}
throw new RuntimeException('not_found');
}
private function historyRestore(string $id): array
{
$snapshot = $this->historyGet($id);
$this->takeSnapshot();
return ['revision' => $this->saveBuilding($snapshot['building'])];
}
private function historyDelete(string $id): array
{
$history = $this->history();
$after = array_values(array_filter($history, static fn(array $entry): bool => ($entry['id'] ?? '') !== $id));
if (count($history) === count($after)) {
throw new RuntimeException('not_found');
}
$this->writeJsonAttribute('History', $after);
return [];
}
private function backupImport(array $building, mixed $packs): array
{
if (!is_array($packs)) {
throw new InvalidArgumentException('invalid_packs');
}
$this->takeSnapshot();
$accepted = array_values(array_filter($packs, static fn(mixed $pack): bool => is_array($pack) && is_string($pack['id'] ?? null) && is_array($pack['items'] ?? null)));
$this->writeJsonAttribute('Packs', $accepted);
return ['revision' => $this->saveBuilding($building), 'building' => $building, 'packs' => count($accepted), 'skipped' => []];
}
private function history(): array
{
$history = $this->jsonAttribute('History', []);
return is_array($history) ? array_values($history) : [];
}
// --------------------------------------------------------------------- variable actions
private function variableAction(string $domain, string $service, array $data): array
{
$entity = $data['entity_id'] ?? null;
$entities = is_array($entity) ? $entity : [$entity];
foreach ($entities as $entityID) {
if (!is_string($entityID)) {
continue;
}
$variableID = $this->variableIdForEntity($entityID);
if ($variableID === null || !IPS_VariableExists($variableID)) {
continue;
}
$this->writeAction($variableID, $domain, $service, $data);
}
return [];
}
private function variableIdForEntity(string $entityID): ?int
{
return preg_match('/^[a-z_]+\\.(\\d+)$/', $entityID, $matches) === 1 ? (int) $matches[1] : null;
}
private function writeAction(int $variableID, string $domain, string $service, array $data): void
{
$variable = IPS_GetVariable($variableID);
$current = GetValue($variableID);
$value = match ($service) {
'toggle', 'media_play_pause' => is_bool($current) ? !$current : (is_numeric($current) ? ((float) $current > 0 ? 0 : 100) : true),
'turn_on', 'open_cover', 'lock' => $this->onValue($variable, $data),
'turn_off', 'close_cover', 'unlock' => $this->offValue($variable),
'set_cover_position', 'set_cover_tilt_position' => $data['position'] ?? $data['tilt_position'] ?? $current,
'set_percentage' => $data['percentage'] ?? $current,
'set_temperature' => $data['temperature'] ?? $current,
'set_hvac_mode' => ($data['hvac_mode'] ?? '') === 'off' ? $this->offValue($variable) : $this->onValue($variable, $data),
'press' => true,
default => $this->onValue($variable, $data)
};
$this->setVariable($variableID, $variable, $value);
}
private function onValue(array $variable, array $data): mixed
{
$type = (int) $variable['VariableType'];
if ($type === 0) {
return true;
}
if (isset($data['brightness_pct'])) {
return (float) $data['brightness_pct'];
}
return $type === 3 ? 'on' : 100;
}
private function offValue(array $variable): mixed
{
return match ((int) $variable['VariableType']) {
0 => false,
3 => 'off',
default => 0
};
}
private function setVariable(int $variableID, array $variable, mixed $value): void
{
$type = (int) $variable['VariableType'];
$cast = match ($type) {
0 => (bool) $value,
1 => (int) round((float) $value),
2 => (float) $value,
default => (string) $value
};
$action = (int) ($variable['VariableCustomAction'] ?: $variable['VariableAction']);
if ($action !== 0) {
RequestAction($variableID, $cast);
} else {
SetValue($variableID, $cast);
}
}
// --------------------------------------------------------------------- small helpers
private function moduleVersion(): string
{
$library = json_decode((string) file_get_contents(__DIR__ . '/../library.json'), true, 512, JSON_THROW_ON_ERROR);
return (string) $library['version'];
}
private function arrayValue(array $source, string $key): array
{
if (!is_array($source[$key] ?? null)) {
throw new InvalidArgumentException('invalid_' . $key);
}
return $source[$key];
}
private function jsonAttribute(string $name, mixed $fallback): mixed
{
$value = json_decode($this->ReadAttributeString($name), true);
return $value === null && json_last_error() !== JSON_ERROR_NONE ? $fallback : $value;
}
private function writeJsonAttribute(string $name, mixed $value): void
{
$this->WriteAttributeString($name, json_encode($value, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR));
}
private function sendJson(array $data): void
{
header('Content-Type: application/json; charset=utf-8');
header('Cache-Control: no-store');
echo json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
}
private function sendError(int $status, string $error): void
{
http_response_code($status);
$this->sendJson(['error' => $error]);
}
}