added trendlogs and some fixes

This commit is contained in:
jhartworks committed 2026-11-11 12:02:23 +01:00
1 parent bc375e4c17
commit 70e8c5dcbc
8 files changed
+1057 -584

No files matched your search

+90 -2
View File
@@ -282,7 +282,7 @@ class NextFloor extends IPSModuleStrict
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)) {
if (!preg_match('#^(?:nextfloor-(?:designer|3d|editor|card-editor|trend)\\.js|lang/[a-z]{2}\\.json)$#', $asset)) {
$this->sendError(404, 'asset_not_found');
return;
}
@@ -314,6 +314,7 @@ class NextFloor extends IPSModuleStrict
$result = match ($request['action']) {
'bootstrap' => $this->bootstrap(),
'variables/snapshot' => $this->variablesSnapshot((int) ($request['revision'] ?? -1)),
'archive/trend' => $this->archiveTrend($request),
'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'] ?? '')),
@@ -380,10 +381,16 @@ class NextFloor extends IPSModuleStrict
foreach (IPS_GetChildrenIDs(0) as $child) {
$this->collectObjects($child, [], null, $variables, $areas, $nodes);
}
$archives = $this->archiveVariables();
$byVariable = [];
foreach ($variables as $variable) {
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) {
@@ -836,6 +843,87 @@ class NextFloor extends IPSModuleStrict
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