1243 lines
58 KiB
PHP
1243 lines
58 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
require_once __DIR__ . '/libs/Access.php';
|
|
require_once __DIR__ . '/libs/Users.php';
|
|
require_once __DIR__ . '/libs/Permissions.php';
|
|
|
|
/**
|
|
* NextFloor for IP-Symcon.
|
|
*
|
|
* One visualization instance owns a floor-plan project. Its protected WebHook serves the designer as
|
|
* a browser tab and the same viewer in an HTML-SDK tile iframe. Admins receive the native object tree;
|
|
* user sessions receive only authorized live bindings. Object selections always use named choices.
|
|
*/
|
|
class NextFloor extends IPSModuleStrict
|
|
{
|
|
use NextFloorAccess, NextFloorUsers, NextFloorPermissions;
|
|
private const MAX_BUILDING_BYTES = 8_000_000;
|
|
private const MAX_IMAGE_BYTES = 8_000_000;
|
|
private const MAX_HISTORY = 20;
|
|
private const MAX_API_RESPONSE_BYTES = 256 * 1024;
|
|
private const TRANSFER_CHUNK_BYTES = 128 * 1024;
|
|
private const MAX_TRANSFER_BYTES = 64 * 1024 * 1024;
|
|
private const TRANSFER_TTL = 120;
|
|
private const HOOK_RETRY_MS = 5000;
|
|
private const HOOK_MAINTENANCE_MS = 30000;
|
|
|
|
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('Accounts', '{}');
|
|
$this->RegisterAttributeString('Sessions', '{}');
|
|
$this->RegisterAttributeString('ConsoleTickets', '{}');
|
|
$this->RegisterAttributeString('LoginThrottle', '{}');
|
|
$this->RegisterAttributeString('LoginDummyHash', '');
|
|
$this->RegisterAttributeString('SelectedAccount', '');
|
|
$this->RegisterAttributeString('StateHash', '');
|
|
$this->RegisterAttributeString('HookError', '');
|
|
$this->RegisterAttributeInteger('BuildingRevision', 0);
|
|
$this->RegisterAttributeInteger('StateRevision', 0);
|
|
$this->RegisterMessage(0, IPS_KERNELSTARTED);
|
|
$this->RegisterMessage(0, KR_READY);
|
|
$this->RegisterTimer('WebHookRetry', 0, 'NFSC_RetryWebHook($_IPS[\'TARGET\']);');
|
|
|
|
$this->ensureAccessToken();
|
|
if ($this->ReadAttributeString('LoginDummyHash') === '') $this->WriteAttributeString('LoginDummyHash', $this->passwordHash($this->newToken()));
|
|
$this->SetVisualizationType(1);
|
|
$this->ensureWebHook(true);
|
|
}
|
|
|
|
public function ApplyChanges(): void
|
|
{
|
|
parent::ApplyChanges();
|
|
$this->RegisterMessage(0, IPS_KERNELSTARTED);
|
|
$this->RegisterMessage(0, KR_READY);
|
|
$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 === KR_READY || $Message === IPS_KERNELSTARTED)) {
|
|
$this->ensureWebHook();
|
|
}
|
|
}
|
|
|
|
/** Keep the volatile route registered, including resets after successful startup or module reload. */
|
|
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.';
|
|
}
|
|
|
|
/** Browser link returned to the console form; link: does not create a native Pro Console tab. */
|
|
public function OpenDesigner(): string
|
|
{
|
|
$this->requireWebHook();
|
|
// `link:` is the documented Form-Button marker for a relative Symcon WebHook URL.
|
|
return 'link:' . $this->designerUrl('designer');
|
|
}
|
|
|
|
/** Revoke all logins and outstanding console tickets, then issue a fresh one-use designer link. */
|
|
public function RotateAccessToken(): string
|
|
{
|
|
$this->requireWebHook();
|
|
$this->WriteAttributeString('AccessToken', $this->newToken());
|
|
$this->WriteAttributeString('Sessions', '{}');
|
|
$this->WriteAttributeString('ConsoleTickets', '{}');
|
|
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');
|
|
$title = htmlspecialchars($this->viewTitle(), 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="' . $title . '" src="' . $src . '" loading="eager" allow="fullscreen"></iframe>';
|
|
}
|
|
|
|
/** IP-Symcon calls this for /hook/nextfloor/<instance id>/... */
|
|
protected function ProcessHookData(): void
|
|
{
|
|
$this->requestUser = null;
|
|
$this->requestScope = null;
|
|
// Keep a same-origin Origin on native form POSTs; no-referrer can turn it into "null".
|
|
header('Referrer-Policy: same-origin');
|
|
header('X-Content-Type-Options: nosniff');
|
|
header('X-Frame-Options: SAMEORIGIN');
|
|
header("Content-Security-Policy: frame-ancestors 'self'; object-src 'none'; base-uri 'none'");
|
|
$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 ($path !== $prefix && !str_starts_with($path, $prefix . '/')) {
|
|
$this->sendError(404, 'not_found');
|
|
return;
|
|
}
|
|
$tail = trim(substr($path, strlen($prefix)), '/');
|
|
try {
|
|
$method = (string) ($_SERVER['REQUEST_METHOD'] ?? 'GET');
|
|
$this->requestUser = $this->resolveSession();
|
|
if ($tail === 'login') {
|
|
if ($method === 'POST') $this->passwordLogin();
|
|
elseif ($method !== 'GET') $this->sendError(405, 'method_not_allowed');
|
|
elseif ($this->requestUser !== null) $this->accessRedirect($this->entryUrl());
|
|
else $this->loginPage();
|
|
return;
|
|
}
|
|
if (($tail === 'designer' || $tail === '') && $method === 'GET' && isset($_GET['ticket'])) {
|
|
// Always exchange and remove a ticket, even if another user was already logged in.
|
|
if (is_string($_GET['ticket']) && $this->exchangeConsoleTicket($_GET['ticket'])) $this->accessRedirect($this->entryUrl());
|
|
else $this->loginPage('Der Konsolen-Link ist abgelaufen oder wurde schon verwendet. Bitte erneut in der Konsole öffnen.', 401);
|
|
return;
|
|
}
|
|
if ($this->requestUser === null) {
|
|
if ($tail === '' || $tail === 'designer') $this->accessRedirect($this->entryUrl('login'));
|
|
else $this->sendError(401, 'authentication_required');
|
|
return;
|
|
}
|
|
if ($tail === 'logout') {
|
|
if ($method !== 'POST' || !$this->validCsrf()) $this->sendError(403, 'csrf_invalid');
|
|
else $this->logoutSession();
|
|
return;
|
|
}
|
|
if ($tail === '' || $tail === 'designer') {
|
|
if ($method !== 'GET') { $this->sendError(405, 'method_not_allowed'); return; }
|
|
$this->sendDesignerPage();
|
|
return;
|
|
}
|
|
if ($tail === 'api') {
|
|
$this->handleApi();
|
|
return;
|
|
}
|
|
if (str_starts_with($tail, 'assets/')) {
|
|
if ($method !== 'GET') { $this->sendError(405, 'method_not_allowed'); return; }
|
|
if (!$this->isAdministrator() && preg_match('#^assets/nextfloor-(?:editor|card-editor)\.js$#D', $tail)) { $this->sendError(403, 'admin_required'); return; }
|
|
$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 $duringCreate = false): bool
|
|
{
|
|
// Register in Create as documented, even while Symcon initializes. Re-register after
|
|
// startup/update and keep maintaining the route: WebHook Control can reset later too.
|
|
$ready = IPS_GetKernelRunlevel() === KR_READY;
|
|
if (!$ready && !$duringCreate) {
|
|
$this->SetStatus(104);
|
|
$this->SetTimerInterval('WebHookRetry', self::HOOK_RETRY_MS);
|
|
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) {
|
|
if (!$ready) {
|
|
$this->SetStatus(104);
|
|
$this->SetTimerInterval('WebHookRetry', self::HOOK_RETRY_MS);
|
|
return false;
|
|
}
|
|
$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', self::HOOK_RETRY_MS);
|
|
return false;
|
|
}
|
|
if (!$ready) {
|
|
$this->SetStatus(104);
|
|
$this->SetTimerInterval('WebHookRetry', self::HOOK_RETRY_MS);
|
|
return false;
|
|
}
|
|
$this->WriteAttributeString('HookError', '');
|
|
$this->SetTimerInterval('WebHookRetry', self::HOOK_MAINTENANCE_MS);
|
|
$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 viewTitle(): string
|
|
{
|
|
return trim($this->ReadPropertyString('Title')) ?: 'NextFloor';
|
|
}
|
|
|
|
private function designerUrl(string $mode): string
|
|
{
|
|
return $mode === 'tile' ? '/hook/' . $this->hookPath() . '/designer?mode=tile' : $this->consoleUrl();
|
|
}
|
|
|
|
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 sendDesignerPage(): void
|
|
{
|
|
$config = [
|
|
'endpoint' => '/hook/' . $this->hookPath(),
|
|
'csrf' => $this->requestUser['csrf'],
|
|
'user' => $this->publicAccess(),
|
|
'language' => 'de',
|
|
'title' => $this->viewTitle()
|
|
];
|
|
$asset = '/hook/' . $this->hookPath() . '/assets/nextfloor-designer.js?v=' . rawurlencode($this->moduleVersion());
|
|
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{display:flex;flex-direction:column}body>nextfloor-panel,body>nextfloor-card{display:block;flex:1;min-height:0;width:100%}.nf-session-bar{display:flex;align-items:center;gap:10px;padding:5px 12px;font:12px/1.4 system-ui;background:#20252d;border-bottom:1px solid #ffffff15}.nf-session-bar span{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.nf-session-bar form{margin:0 0 0 auto;flex-shrink:0}.nf-session-bar button{font:inherit;padding:5px 12px;border:1px solid #ffffff25;border-radius:7px;background:#ffffff0a;color:inherit;cursor:pointer}</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 | JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT) . ';</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|trend|hydronics)\\.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;
|
|
}
|
|
if (!$this->validCsrf()) { $this->sendError(403, 'csrf_invalid'); return; }
|
|
$limit = $this->isAdministrator() ? self::MAX_TRANSFER_BYTES : 65536;
|
|
$raw = (string) file_get_contents('php://input', false, null, 0, $limit + 1);
|
|
if (strlen($raw) > $limit) { $this->sendError(413, 'request_too_large'); return; }
|
|
$request = json_decode($raw, true);
|
|
if (!is_array($request) || !is_string($request['action'] ?? null)) {
|
|
$this->sendError(400, 'invalid_request');
|
|
return;
|
|
}
|
|
|
|
try {
|
|
$this->authorizeApi($request['action'], $request);
|
|
$result = match ($request['action']) {
|
|
'bootstrap' => $this->bootstrap(),
|
|
'variables/snapshot' => $this->variablesSnapshot((int) ($request['revision'] ?? -1)),
|
|
'archive/trend' => $this->archiveTrend($request),
|
|
'building/get' => ['building' => $this->visibleBuilding(), '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')),
|
|
'transport/read' => $this->readTransfer((string) ($request['transfer_id'] ?? ''), (int) ($request['index'] ?? -1)),
|
|
'transport/release' => $this->releaseTransfer((string) ($request['transfer_id'] ?? '')),
|
|
default => throw new RuntimeException('unknown_action')
|
|
};
|
|
$this->sendApiResult($result, ($request['transport'] ?? '') === 'nextfloor-chunks-v1');
|
|
} catch (NextFloorDenied $error) {
|
|
$this->sendError(403, $error->getMessage());
|
|
} catch (InvalidArgumentException $error) {
|
|
$this->sendError(400, $error->getMessage());
|
|
} catch (RuntimeException $error) {
|
|
$this->sendError(404, $error->getMessage());
|
|
}
|
|
}
|
|
|
|
private function bootstrap(): array
|
|
{
|
|
$objects = $this->visibleTree($this->objectTree());
|
|
$stateRevision = $this->stateRevision($objects);
|
|
return [
|
|
'access' => $this->publicAccess(),
|
|
'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->visibleTree($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);
|
|
}
|
|
$archives = $this->archiveVariables();
|
|
$byVariable = [];
|
|
foreach ($variables as &$variable) {
|
|
$id = $variable['attributes']['symcon_id'];
|
|
if (isset($archives[$id]) && !isset($variable['attributes']['symcon_schedule'])) {
|
|
$variable['attributes']['symcon_archive'] = $archives[$id];
|
|
}
|
|
$byVariable[$variable['attributes']['symcon_id']] = $variable['entity_id'];
|
|
}
|
|
unset($variable);
|
|
// 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.
|
|
$module = IPS_GetInstance($objectID)['ModuleInfo'];
|
|
$node['module_type'] = (int) $module['ModuleType'];
|
|
$node['module_id'] = (string) ($module['ModuleID'] ?? '');
|
|
}
|
|
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'];
|
|
}
|
|
if ($type === 4 && function_exists('IPS_GetEvent')) {
|
|
$event = IPS_GetEvent($objectID);
|
|
if ((int) ($event['EventType'] ?? -1) === 2) {
|
|
$schedule = $this->describeSchedule($objectID, $name, implode(' / ', $path), $event);
|
|
$variables[] = $schedule;
|
|
$node['entity_id'] = $schedule['entity_id'];
|
|
}
|
|
}
|
|
$nodes[] = $node;
|
|
foreach (IPS_GetChildrenIDs($objectID) as $child) {
|
|
$this->collectObjects($child, $path, $nearestCategory, $variables, $areas, $nodes);
|
|
}
|
|
}
|
|
|
|
private function describeSchedule(int $eventID, string $name, string $path, array $event): array
|
|
{
|
|
// Export presentation only; action scripts and action parameters stay in Symcon.
|
|
$actions = array_map(static fn(array $action): array => [
|
|
'id' => (int) $action['ID'], 'name' => (string) $action['Name'], 'color' => (int) ($action['Color'] ?? 0)
|
|
], $event['ScheduleActions'] ?? []);
|
|
$groups = array_map(static fn(array $group): array => [
|
|
'id' => (int) $group['ID'], 'days' => (int) $group['Days'],
|
|
'points' => array_map(static fn(array $point): array => [
|
|
'id' => (int) $point['ID'], 'hour' => (int) $point['Start']['Hour'],
|
|
'minute' => (int) $point['Start']['Minute'], 'second' => (int) $point['Start']['Second'],
|
|
'action' => (int) $point['ActionID']
|
|
], $group['Points'] ?? [])
|
|
], $event['ScheduleGroups'] ?? []);
|
|
return ['entity_id' => 'schedule.' . $eventID, 'name' => $name, 'path' => $path,
|
|
'state' => ($event['EventActive'] ?? false) ? 'on' : 'off',
|
|
'attributes' => ['symcon_id' => $eventID, 'symcon_schedule' => true,
|
|
'groups' => $groups, 'actions' => $actions, 'next_run' => (int) ($event['NextRun'] ?? 0),
|
|
'next_action' => (int) ($event['NextActionID'] ?? 0), 'last_action' => (int) ($event['LastActionID'] ?? 0)]];
|
|
}
|
|
|
|
private function describeVariable(int $variableID, string $name, string $path, ?int $categoryID): array
|
|
{
|
|
$variable = IPS_GetVariable($variableID);
|
|
$meta = $this->variableMetadata($variableID, $variable);
|
|
$profile = $meta['profile'];
|
|
$unit = $meta['unit'];
|
|
$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),
|
|
'symcon_value' => $value,
|
|
'device_class' => $this->deviceClassFor($profile, $name, $unit)
|
|
];
|
|
if ($unit !== '') {
|
|
$attributes['unit_of_measurement'] = $unit;
|
|
}
|
|
if (in_array((int) $variable['VariableType'], [1, 2], true)) {
|
|
// Keep the actual numeric reading even when legacy name heuristics chose an actuator domain.
|
|
// Existing synthetic entity IDs stay stable so saved plan mappings keep working.
|
|
$attributes['symcon_numeric_value'] = $value;
|
|
$attributes['symcon_min'] = $meta['min'];
|
|
$attributes['symcon_max'] = $meta['max'];
|
|
$attributes['symcon_step'] = $meta['step'];
|
|
}
|
|
if ($kind === 'light' && is_numeric($value)) {
|
|
$attributes['brightness'] = (int) round($this->valuePercent((float) $value, $meta) * 2.55);
|
|
$attributes['color_mode'] = 'brightness';
|
|
$attributes['supported_color_modes'] = ['brightness'];
|
|
}
|
|
if ($kind === 'cover' && is_numeric($value)) {
|
|
$attributes['current_position'] = $this->valuePercent((float) $value, $meta);
|
|
$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';
|
|
}
|
|
$state = $this->stateFor($kind, $value);
|
|
if (in_array($kind, ['light', 'cover'], true) && is_numeric($value)) {
|
|
$on = $this->valuePercent((float) $value, $meta) > 0;
|
|
$state = $kind === 'light' ? ($on ? 'on' : 'off') : ($on ? 'open' : 'closed');
|
|
}
|
|
return [
|
|
'entity_id' => $kind . '.' . $variableID,
|
|
'name' => $name,
|
|
'path' => $path,
|
|
'state' => $state,
|
|
'attributes' => $attributes,
|
|
'area_id' => $categoryID === null ? null : 'symcon-category-' . $categoryID,
|
|
'device_id' => 'symcon-variable-' . $variableID
|
|
];
|
|
}
|
|
|
|
/** The effective Symcon 9 presentation takes precedence over an old profile's range and unit. */
|
|
private function variableMetadata(int $variableID, array $variable): array
|
|
{
|
|
$presentation = IPS_GetVariablePresentation($variableID);
|
|
$profile = (string) ($presentation['PROFILE'] ?? (($variable['VariableCustomProfile'] ?? '') ?: ($variable['VariableProfile'] ?? '')));
|
|
$legacy = $profile !== '' && IPS_VariableProfileExists($profile) ? IPS_GetVariableProfile($profile) : [];
|
|
$min = (float) ($presentation['MIN'] ?? $legacy['MinValue'] ?? 0);
|
|
$max = (float) ($presentation['MAX'] ?? $legacy['MaxValue'] ?? 100);
|
|
if (!is_finite($min) || !is_finite($max) || $max <= $min) {
|
|
[$min, $max] = [0.0, 100.0];
|
|
}
|
|
$step = (float) ($presentation['STEP_SIZE'] ?? $legacy['StepSize'] ?? 0);
|
|
return ['profile' => $profile, 'unit' => trim((string) ($presentation['SUFFIX'] ?? $legacy['Suffix'] ?? '')),
|
|
'min' => $min, 'max' => $max, 'step' => is_finite($step) && $step > 0 ? $step : 0.0];
|
|
}
|
|
|
|
private function valuePercent(float $value, array $meta): float
|
|
{
|
|
return max(0, min(100, ($value - $meta['min']) / ($meta['max'] - $meta['min']) * 100));
|
|
}
|
|
|
|
private function percentValue(mixed $percent, array $meta): float
|
|
{
|
|
if (!is_numeric($percent) || !is_finite((float) $percent)) {
|
|
throw new InvalidArgumentException('invalid_control_percentage');
|
|
}
|
|
$value = $meta['min'] + max(0, min(100, (float) $percent)) / 100 * ($meta['max'] - $meta['min']);
|
|
if ($meta['step'] > 0) {
|
|
$value = $meta['min'] + round(($value - $meta['min']) / $meta['step']) * $meta['step'];
|
|
}
|
|
return max($meta['min'], min($meta['max'], $value));
|
|
}
|
|
|
|
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 $unit = ''): string
|
|
{
|
|
$text = str_replace('co₂', 'co2', mb_strtolower($profile . ' ' . $haystack));
|
|
$unitClass = match (preg_replace('/[\s\x{00A0}]+/u', '', mb_strtolower($unit))) {
|
|
'°c', '°f', '℃', '℉', 'k' => 'temperature',
|
|
'ppm' => str_contains($text, 'co2') || str_contains($text, 'co₂') ? 'carbon_dioxide' : '',
|
|
'w', 'kw' => 'power',
|
|
'lx', 'lux' => 'illuminance',
|
|
default => ''
|
|
};
|
|
if ($unitClass !== '') {
|
|
return $unitClass;
|
|
}
|
|
return match (true) {
|
|
str_contains($text, 'temperature') || str_contains($text, 'temperatur') => 'temperature',
|
|
str_contains($text, 'humidity') || str_contains($text, 'feucht') => 'humidity',
|
|
str_contains($text, 'co2') => 'carbon_dioxide',
|
|
str_contains($text, 'illuminance') || str_contains($text, 'beleuchtungsst') => 'illuminance',
|
|
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', $this->encodeResponse($objects));
|
|
// Distinct user scopes must not invalidate one global revision on every alternating poll.
|
|
if ($this->requestUser !== null && !$this->isAdministrator()) return (int) hexdec(substr($hash, 0, 12));
|
|
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) : [];
|
|
}
|
|
|
|
// --------------------------------------------------------------------- archive trends (read-only)
|
|
|
|
/** One bulk metadata query per archive, never one query for every exported variable. */
|
|
private function archiveVariables(): array
|
|
{
|
|
if (!function_exists('AC_GetAggregationVariables') || !function_exists('IPS_GetInstanceListByModuleID')) return [];
|
|
$result = [];
|
|
foreach (IPS_GetInstanceListByModuleID('{43192F0B-135B-4CE7-A0A7-1475603F3060}') as $archiveID) {
|
|
try {
|
|
foreach (AC_GetAggregationVariables($archiveID, false) as $entry) {
|
|
if (!($entry['AggregationActive'] ?? false)) continue;
|
|
$id = (int) $entry['VariableID'];
|
|
$result[$id] ??= ['id' => (int) $archiveID, 'counter' => (int) $entry['AggregationType'] === 1,
|
|
'first' => (int) ($entry['FirstTime'] ?? 0), 'last' => (int) ($entry['LastTime'] ?? 0)];
|
|
}
|
|
} catch (Throwable) { /* An unavailable archive must not break live values or the designer. */ }
|
|
}
|
|
return $result;
|
|
}
|
|
|
|
/** Archive Control API: AC_GetLoggedValues / AC_GetAggregatedValues, bounded at 10,000 records. */
|
|
private function archiveTrend(array $request): array
|
|
{
|
|
if (!is_string($request['entity_id'] ?? null)) throw new InvalidArgumentException('invalid_trend_variable');
|
|
$id = $this->variableIdForEntity($request['entity_id']);
|
|
if ($id === null || !IPS_VariableExists($id)) throw new InvalidArgumentException('invalid_trend_variable');
|
|
$start = $request['start'] ?? null;
|
|
$end = $request['end'] ?? null;
|
|
if (!is_int($start) || !is_int($end) || $start < 1 || $end <= $start || $end > 253402300799) {
|
|
throw new InvalidArgumentException('invalid_trend_range');
|
|
}
|
|
$levels = ['minute' => 6, '5minutes' => 5, '15minutes' => 8, 'hour' => 0, 'day' => 1, 'week' => 2, 'month' => 3, 'year' => 4];
|
|
$mode = $request['aggregation'] ?? 'auto';
|
|
if (!is_string($mode) || !in_array($mode, ['auto', 'raw', ...array_keys($levels)], true)) throw new InvalidArgumentException('invalid_trend_aggregation');
|
|
$meta = $this->archiveVariables()[$id] ?? null;
|
|
if ($meta === null) throw new RuntimeException('variable_not_logged');
|
|
$type = (int) IPS_GetVariable($id)['VariableType'];
|
|
$span = $end - $start;
|
|
$automatic = $mode === 'auto';
|
|
if ($automatic) $mode = $span <= 172800 ? 'raw' : ($span <= 2678400 ? 'hour' : ($span <= 34560000 ? 'day' : 'month'));
|
|
if ($type === 3) $mode = 'raw';
|
|
$archive = $meta['id'];
|
|
$limit = $type === 3 ? 1000 : 10000;
|
|
// Bound expensive, computed minute aggregates and prevent silently truncated long requests.
|
|
$seconds = ['minute' => 60, '5minutes' => 300, '15minutes' => 900, 'hour' => 3600, 'day' => 86400, 'week' => 604800, 'month' => 2419200, 'year' => 31536000];
|
|
if ($mode !== 'raw' && $span / $seconds[$mode] > $limit - 2) throw new InvalidArgumentException('trend_range_too_large_for_resolution');
|
|
$rows = $mode === 'raw' ? AC_GetLoggedValues($archive, $id, $start, $end, $limit)
|
|
: AC_GetAggregatedValues($archive, $id, $levels[$mode], $start, $end, $limit);
|
|
if ($automatic && $type !== 3 && $mode === 'raw' && count($rows) >= $limit) {
|
|
$mode = 'minute';
|
|
$rows = AC_GetAggregatedValues($archive, $id, $levels[$mode], $start, $end, $limit);
|
|
}
|
|
$truncated = count($rows) >= $limit;
|
|
$points = [];
|
|
foreach ($rows as $row) {
|
|
$timestamp = (int) $row['TimeStamp'];
|
|
if ($timestamp < $start || $timestamp > $end) continue;
|
|
$raw = $mode === 'raw' ? $row['Value'] : $row['Avg'];
|
|
$value = $type === 3 ? mb_substr((string) $raw, 0, 4096) : (is_bool($raw) ? (int) $raw : (is_numeric($raw) ? (float) $raw : null));
|
|
if ($value === null || (is_float($value) && !is_finite($value))) continue;
|
|
$point = ['t' => $timestamp, 'v' => $value, 'd' => max(0, (int) ($row['Duration'] ?? 0))];
|
|
if ($mode !== 'raw' && is_numeric($row['Min'] ?? null) && is_numeric($row['Max'] ?? null)) {
|
|
$point['min'] = (float) $row['Min']; $point['max'] = (float) $row['Max'];
|
|
}
|
|
$points[] = $point;
|
|
}
|
|
// Raw archives only store changes. Carry the last known state into the requested range.
|
|
if ($mode === 'raw' && !$truncated && $start > 1) {
|
|
$previous = AC_GetLoggedValues($archive, $id, 0, $start - 1, 1);
|
|
if ($previous && !array_filter($points, static fn(array $p): bool => $p['t'] === $start)) {
|
|
$v = $previous[0]['Value'];
|
|
if ($type === 3 || is_bool($v) || is_numeric($v)) {
|
|
$points[] = ['t' => $start, 'v' => $type === 3 ? mb_substr((string) $v, 0, 4096) : (float) $v, 'd' => 0];
|
|
}
|
|
}
|
|
}
|
|
usort($points, static fn(array $a, array $b): int => $a['t'] <=> $b['t']);
|
|
return ['entity_id' => (string) $request['entity_id'], 'start' => $start, 'end' => $end,
|
|
'aggregation' => $mode, 'counter' => $meta['counter'], 'type' => $type, 'limit' => $limit, 'truncated' => $truncated, 'points' => $points];
|
|
}
|
|
|
|
// --------------------------------------------------------------------- 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;
|
|
}
|
|
if ($domain === 'schedule' && $service === 'set_active') {
|
|
if (preg_match('/^schedule\.(\d+)$/', $entityID, $match) !== 1 || !IPS_EventExists((int) $match[1])
|
|
|| (int) IPS_GetEvent((int) $match[1])['EventType'] !== 2 || !is_bool($data['active'] ?? null)) {
|
|
throw new InvalidArgumentException('invalid_schedule');
|
|
}
|
|
if (!IPS_SetEventActive((int) $match[1], $data['active'])) throw new RuntimeException('schedule_update_failed');
|
|
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);
|
|
if ($domain === 'symcon' && $service === 'set_value') {
|
|
if ((int) ($variable['VariableCustomAction'] ?: $variable['VariableAction']) === 0) throw new InvalidArgumentException('variable_readonly');
|
|
$type = (int) $variable['VariableType'];
|
|
$value = $data['value'] ?? null;
|
|
if ($type === 0 && !is_bool($value)) throw new InvalidArgumentException('invalid_boolean');
|
|
if (in_array($type, [1, 2], true)) {
|
|
$meta = $this->variableMetadata($variableID, $variable);
|
|
if (!is_numeric($value) || !is_finite((float) $value) || (float) $value < $meta['min'] || (float) $value > $meta['max']
|
|
|| ($type === 1 && (float) $value !== floor((float) $value))) throw new InvalidArgumentException('invalid_value');
|
|
}
|
|
if ($type === 3 && !is_string($value)) throw new InvalidArgumentException('invalid_string');
|
|
$this->setVariable($variableID, $variable, $value);
|
|
return;
|
|
}
|
|
if ($domain === 'cover' && $service === 'stop_cover') {
|
|
throw new InvalidArgumentException('cover_stop_not_supported');
|
|
}
|
|
if (in_array($domain, ['light', 'cover'], true) && in_array((int) $variable['VariableType'], [1, 2], true)) {
|
|
$meta = $this->variableMetadata($variableID, $variable);
|
|
$percent = match ($service) {
|
|
'toggle' => (float) $current > $meta['min'] ? 0 : 100,
|
|
'turn_off', 'close_cover', 'close_cover_tilt' => 0,
|
|
'set_cover_position' => $data['position'] ?? null,
|
|
'set_cover_tilt_position' => $data['tilt_position'] ?? null,
|
|
'turn_on' => $data['brightness_pct'] ?? (isset($data['brightness']) ? (float) $data['brightness'] / 2.55 : 100),
|
|
'open_cover', 'open_cover_tilt' => 100,
|
|
default => throw new InvalidArgumentException('unsupported_control_service')
|
|
};
|
|
$this->setVariable($variableID, $variable, $this->percentValue($percent, $meta));
|
|
return;
|
|
}
|
|
$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
|
|
{
|
|
$encoded = $this->encodeResponse($data);
|
|
header('Content-Type: application/json; charset=utf-8');
|
|
header('Cache-Control: no-store');
|
|
echo $encoded;
|
|
}
|
|
|
|
private function encodeResponse(array $data): string
|
|
{
|
|
return json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_INVALID_UTF8_SUBSTITUTE | JSON_THROW_ON_ERROR);
|
|
}
|
|
|
|
/** Never emit a JSON response near the kernel's default 1 MiB PHP output limit. */
|
|
private function sendApiResult(array $data, bool $supportsChunks): void
|
|
{
|
|
$encoded = $this->encodeResponse($data);
|
|
if (strlen($encoded) <= self::MAX_API_RESPONSE_BYTES) {
|
|
header('Content-Type: application/json; charset=utf-8');
|
|
header('Cache-Control: no-store');
|
|
echo $encoded;
|
|
return;
|
|
}
|
|
if (!$supportsChunks) {
|
|
$this->sendError(409, 'client_update_required: Bitte den Designer neu laden.');
|
|
return;
|
|
}
|
|
$this->sendJson(['_nextfloor_transfer' => $this->createTransfer($encoded)]);
|
|
}
|
|
|
|
/** Large results use private, short-lived snapshots, not the module's size-limited SetBuffer. */
|
|
private function transferDirectory(): string
|
|
{
|
|
$directory = rtrim(sys_get_temp_dir(), '/\\') . DIRECTORY_SEPARATOR . 'nextfloor-transfers-' . $this->InstanceID;
|
|
if (is_link($directory) || (!is_dir($directory) && !mkdir($directory, 0700, true) && !is_dir($directory))) {
|
|
throw new RuntimeException('transfer_storage_unavailable');
|
|
}
|
|
return $directory;
|
|
}
|
|
|
|
private function transferFile(string $id): string
|
|
{
|
|
if (preg_match('/^[a-f0-9]{32}$/D', $id) !== 1) {
|
|
throw new InvalidArgumentException('invalid_transfer_id');
|
|
}
|
|
return $this->transferDirectory() . DIRECTORY_SEPARATOR . $id . '.json';
|
|
}
|
|
|
|
private function createTransfer(string $encoded): array
|
|
{
|
|
$bytes = strlen($encoded);
|
|
if ($bytes > self::MAX_TRANSFER_BYTES) {
|
|
throw new InvalidArgumentException('response_too_large');
|
|
}
|
|
$active = 0;
|
|
foreach (glob($this->transferDirectory() . DIRECTORY_SEPARATOR . '*.json') ?: [] as $file) {
|
|
if (preg_match('/^[a-f0-9]{32}\.json$/D', basename($file)) !== 1 || is_link($file)) continue;
|
|
if ((int) filemtime($file) < time() - self::TRANSFER_TTL) {
|
|
unlink($file);
|
|
if (is_file($file . '.owner') && !is_link($file . '.owner')) unlink($file . '.owner');
|
|
} else {
|
|
$active++;
|
|
}
|
|
}
|
|
if ($active >= 8) throw new RuntimeException('transfer_busy: Bitte kurz warten und erneut laden.');
|
|
$id = bin2hex(random_bytes(16));
|
|
$file = $this->transferFile($id);
|
|
$handle = fopen($file, 'xb');
|
|
if ($handle === false) throw new RuntimeException('transfer_storage_unavailable');
|
|
chmod($file, 0600);
|
|
try {
|
|
$written = 0;
|
|
while ($written < $bytes) {
|
|
$count = fwrite($handle, substr($encoded, $written));
|
|
if ($count === false || $count === 0) throw new RuntimeException('transfer_write_failed');
|
|
$written += $count;
|
|
}
|
|
} catch (Throwable $error) {
|
|
fclose($handle);
|
|
unlink($file);
|
|
throw $error;
|
|
}
|
|
fclose($handle);
|
|
if (file_put_contents($file . '.owner', $this->transferOwner(), LOCK_EX) === false) {
|
|
unlink($file);
|
|
throw new RuntimeException('transfer_storage_unavailable');
|
|
}
|
|
chmod($file . '.owner', 0600);
|
|
return ['id' => $id, 'bytes' => $bytes, 'chunk_bytes' => self::TRANSFER_CHUNK_BYTES, 'chunks' => (int) ceil($bytes / self::TRANSFER_CHUNK_BYTES)];
|
|
}
|
|
|
|
private function transferOwner(): string
|
|
{
|
|
return hash('sha256', (string) ($this->requestUser['session_id'] ?? 'internal') . ':' . (string) ($this->requestUser['epoch'] ?? ''));
|
|
}
|
|
|
|
private function ownsTransfer(string $file): bool
|
|
{
|
|
$owner = $file . '.owner';
|
|
return is_file($owner) && !is_link($owner) && hash_equals($this->transferOwner(), (string) file_get_contents($owner));
|
|
}
|
|
|
|
private function readTransfer(string $id, int $index): array
|
|
{
|
|
$file = $this->transferFile($id);
|
|
if (!is_file($file) || is_link($file) || !$this->ownsTransfer($file)) throw new RuntimeException('transfer_not_found');
|
|
if ((int) filemtime($file) < time() - self::TRANSFER_TTL) {
|
|
unlink($file);
|
|
unlink($file . '.owner');
|
|
throw new RuntimeException('transfer_expired: Bitte erneut laden.');
|
|
}
|
|
$bytes = (int) filesize($file);
|
|
if ($index < 0 || $index >= (int) ceil($bytes / self::TRANSFER_CHUNK_BYTES)) {
|
|
throw new InvalidArgumentException('invalid_transfer_index');
|
|
}
|
|
$handle = fopen($file, 'rb');
|
|
if ($handle === false) throw new RuntimeException('transfer_not_found');
|
|
try {
|
|
if (fseek($handle, $index * self::TRANSFER_CHUNK_BYTES) !== 0) throw new RuntimeException('transfer_read_failed');
|
|
$data = fread($handle, self::TRANSFER_CHUNK_BYTES);
|
|
if ($data === false) throw new RuntimeException('transfer_read_failed');
|
|
} finally {
|
|
fclose($handle);
|
|
}
|
|
touch($file); // Active slow connections keep their immutable snapshot alive.
|
|
return ['index' => $index, 'data' => base64_encode($data)];
|
|
}
|
|
|
|
private function releaseTransfer(string $id): array
|
|
{
|
|
$file = $this->transferFile($id);
|
|
if (is_file($file) && !is_link($file) && $this->ownsTransfer($file)) { unlink($file); unlink($file . '.owner'); }
|
|
return [];
|
|
}
|
|
|
|
private function sendError(int $status, string $error): void
|
|
{
|
|
http_response_code($status);
|
|
$this->sendJson(['error' => $error]);
|
|
}
|
|
}
|