false, 'error' => 'login_required', ], 401); } function bytes_human(int|float $bytes): string { $units = ['B', 'KB', 'MB', 'GB', 'TB']; $v = (float)$bytes; $i = 0; while ($v >= 1024 && $i < count($units) - 1) { $v /= 1024; $i++; } return ($i === 0 ? (string)(int)$v : number_format($v, 2)) . ' ' . $units[$i]; } function command_short(string $value, int $limit = 120): string { $value = trim(preg_replace('/\s+/', ' ', $value) ?? ''); if ($value === '') { return 'N/A'; } return mb_strlen($value) > $limit ? mb_substr($value, 0, $limit - 1) . '...' : $value; } function human_seconds(int $s): string { $d = intdiv($s, 86400); $s %= 86400; $h = intdiv($s, 3600); $s %= 3600; $m = intdiv($s, 60); return ($d > 0 ? $d . 'd ' : '') . sprintf('%02dh %02dm', $h, $m); } function human_remaining_seconds(int $seconds): string { if ($seconds <= 0) { return '-'; } $hours = intdiv($seconds, 3600); $minutes = intdiv($seconds % 3600, 60); if ($hours > 0) { return sprintf('%dh %02dm', $hours, $minutes); } return sprintf('%dm', max(1, $minutes)); } function dmesg_log(): array { $path = '/tmp/dmesg.log'; if (!is_readable($path)) { return [ 'path' => $path, 'available' => false, 'lines' => [], 'line_count' => 0, 'size_bytes' => 0, 'updated_at' => null, 'message' => 'dmesg log is not available yet.', ]; } $size = filesize($path) ?: 0; $chunk = file_get_contents($path); if ($chunk === false) { return [ 'path' => $path, 'available' => false, 'lines' => [], 'line_count' => 0, 'size_bytes' => $size, 'updated_at' => null, 'message' => 'failed to open dmesg log.', ]; } $lines = array_values(array_filter( preg_split('/\R/', $chunk) ?: [], static fn($line): bool => trim((string)$line) !== '' )); return [ 'path' => $path, 'available' => true, 'lines' => array_reverse($lines), 'line_count' => count($lines), 'size_bytes' => $size, 'updated_at' => date('Y-m-d H:i:s', filemtime($path) ?: time()), ]; } function throttled_event_status(?int $flags, string $raw, int $activeBit, int $seenBit, string $statePath): array { $now = time(); $windowSeconds = 600; $recoverySeconds = 300; $active = $flags !== null && (bool)($flags & $activeBit); $seen = $flags !== null && (bool)($flags & $seenBit); if (is_file($statePath) && !is_writable($statePath)) { @chmod($statePath, 0666); } $state = [ 'active' => false, 'active_since' => null, 'last_detected_at' => null, 'last_cleared_at' => null, 'last_duration_seconds' => 0, 'updated_at' => null, 'events' => [], ]; $fp = @fopen($statePath, 'c+'); if ($fp !== false) { @chmod($statePath, 0666); @flock($fp, LOCK_EX); $saved = stream_get_contents($fp); $decoded = json_decode((string)$saved, true); if (is_array($decoded)) { $state = array_merge($state, array_intersect_key($decoded, $state)); } $state['events'] = array_values(array_filter( is_array($state['events'] ?? null) ? $state['events'] : [], static fn($event): bool => is_array($event) && is_numeric($event['start'] ?? null) )); $wasActive = !empty($state['active']); $activeSince = is_numeric($state['active_since'] ?? null) ? (int)$state['active_since'] : null; if ($flags !== null) { if ($active) { if (!$wasActive || $activeSince === null) { $activeSince = $now; $state['last_detected_at'] = $now; $state['events'][] = [ 'start' => $now, 'end' => null, 'duration_seconds' => 0, ]; } $state['active'] = true; $state['active_since'] = $activeSince; } else { if ($wasActive && $activeSince !== null) { $state['last_cleared_at'] = $now; $state['last_duration_seconds'] = max(0, $now - $activeSince); $lastIndex = count($state['events']) - 1; if ($lastIndex >= 0 && empty($state['events'][$lastIndex]['end'])) { $state['events'][$lastIndex]['end'] = $now; $state['events'][$lastIndex]['duration_seconds'] = $state['last_duration_seconds']; } else { $state['events'][] = [ 'start' => $activeSince, 'end' => $now, 'duration_seconds' => $state['last_duration_seconds'], ]; } } $state['active'] = false; $state['active_since'] = null; } $keepAfter = $now - 86400; $state['events'] = array_slice(array_values(array_filter( $state['events'], static function ($event) use ($keepAfter, $now): bool { $start = (int)($event['start'] ?? 0); $end = is_numeric($event['end'] ?? null) ? (int)$event['end'] : $now; return $start > 0 && max($start, $end) >= $keepAfter; } )), -200); $state['updated_at'] = $now; ftruncate($fp, 0); rewind($fp); fwrite($fp, json_encode($state, JSON_UNESCAPED_SLASHES)); fflush($fp); @chmod($statePath, 0666); } @flock($fp, LOCK_UN); fclose($fp); } $duration = 0; if ($active && is_numeric($state['active_since'] ?? null)) { $duration = max(0, $now - (int)$state['active_since']); } elseif (is_numeric($state['last_duration_seconds'] ?? null)) { $duration = max(0, (int)$state['last_duration_seconds']); } $dateValue = static fn($ts): ?string => is_numeric($ts) && (int)$ts > 0 ? date('Y-m-d H:i:s', (int)$ts) : null; $windowStart = $now - $windowSeconds; $recentCount = 0; $recentActiveSeconds = 0; $events = is_array($state['events'] ?? null) ? $state['events'] : []; foreach ($events as $event) { if (!is_array($event) || !is_numeric($event['start'] ?? null)) { continue; } $start = (int)$event['start']; $end = is_numeric($event['end'] ?? null) ? (int)$event['end'] : $now; if ($end < $windowStart || $start > $now) { continue; } $overlapStart = max($start, $windowStart); $overlapEnd = min(max($end, $overlapStart), $now); if ($overlapEnd > $overlapStart) { $recentCount++; $recentActiveSeconds += $overlapEnd - $overlapStart; } } $lastClearedAt = is_numeric($state['last_cleared_at'] ?? null) ? (int)$state['last_cleared_at'] : null; $recovering = !$active && $lastClearedAt !== null && ($now - $lastClearedAt) <= $recoverySeconds; $repeated = $recentCount >= 2; $stateLabel = 'normal'; if ($active) { $stateLabel = 'active'; } elseif ($repeated) { $stateLabel = 'repeated'; } elseif ($recovering) { $stateLabel = 'recovering'; } return [ 'available' => $flags !== null, 'raw' => $raw, 'flags' => $flags, 'active' => $active, 'seen_since_boot' => $seen, 'active_since' => $dateValue($state['active_since'] ?? null), 'last_detected_at' => $dateValue($state['last_detected_at'] ?? null), 'last_cleared_at' => $dateValue($state['last_cleared_at'] ?? null), 'duration_seconds' => $duration, 'last_duration_seconds' => (int)($state['last_duration_seconds'] ?? 0), 'updated_at' => $dateValue($state['updated_at'] ?? null), 'state_label' => $stateLabel, 'recovering' => $recovering, 'repeated_recently' => $repeated, 'recovery_window_seconds' => $recoverySeconds, 'recent_window_seconds' => $windowSeconds, 'recent_event_count' => $recentCount, 'recent_active_seconds' => $recentActiveSeconds, 'recent_active_percent' => round($recentActiveSeconds / $windowSeconds * 100, 1), ]; } function read_throttled_flags(): array { $result = sh(['/usr/bin/vcgencmd', 'get_throttled'], false, 3); $raw = trim((string)$result['out']); $flags = null; $source = 'direct'; if ((int)$result['code'] === 0 && preg_match('/throttled=0x([0-9a-f]+)/i', $raw, $m)) { $flags = hexdec($m[1]); } if ($flags === null) { $sudoResult = sh(['/usr/bin/vcgencmd', 'get_throttled'], true, 3); $sudoRaw = trim((string)$sudoResult['out']); if ((int)$sudoResult['code'] === 0 && preg_match('/throttled=0x([0-9a-f]+)/i', $sudoRaw, $m)) { $result = $sudoResult; $raw = $sudoRaw; $flags = hexdec($m[1]); $source = 'sudo'; } } return [ 'result' => $result, 'raw' => $raw, 'flags' => $flags, 'source' => $source, ]; } function throttled_statuses(): array { $read = read_throttled_flags(); $raw = (string)$read['raw']; $flags = $read['flags']; $source = (string)$read['source']; $lowVoltage = throttled_event_status($flags, $raw, 0x1, 0x10000, '/tmp/control-low-voltage-state.json'); $throttling = throttled_event_status($flags, $raw, 0x4, 0x40000, '/tmp/control-throttling-state.json'); $lowVoltage['source'] = $source; $lowVoltage['freq_capped'] = $flags !== null && (bool)($flags & 0x2); $lowVoltage['throttled'] = $flags !== null && (bool)($flags & 0x4); $lowVoltage['soft_temp_limit'] = $flags !== null && (bool)($flags & 0x8); $throttling['source'] = $source; $throttling['low_voltage'] = $flags !== null && (bool)($flags & 0x1); $throttling['freq_capped'] = $flags !== null && (bool)($flags & 0x2); $throttling['soft_temp_limit'] = $flags !== null && (bool)($flags & 0x8); return [ 'low_voltage' => $lowVoltage, 'throttling' => $throttling, ]; } function low_voltage_status(): array { return throttled_statuses()['low_voltage']; } function fan_paths(): array { $candidates = glob('/sys/devices/platform/cooling_fan/hwmon/hwmon*/pwm1') ?: []; $candidates = array_merge( $candidates, glob('/sys/class/hwmon/hwmon*/pwm1') ?: [] ); foreach ($candidates as $pwm) { $dir = dirname($pwm); return [ 'base' => $dir, 'pwm' => $pwm, 'enable' => $dir . '/pwm1_enable', 'rpm' => $dir . '/fan1_input', 'name' => first_readable([$dir . '/name']) ?: 'cooling_fan', ]; } return [ 'base' => 'N/A', 'pwm' => 'N/A', 'enable' => 'N/A', 'rpm' => 'N/A', 'name' => 'N/A', ]; } function read_int_file(string $file): int { if ($file === '' || $file === 'N/A' || !is_readable($file)) { return 0; } $raw = trim((string)@file_get_contents($file)); return is_numeric($raw) ? (int)$raw : 0; } function cpu_temp(): float { $raw = first_readable([ '/sys/class/thermal/thermal_zone0/temp', '/sys/devices/virtual/thermal/thermal_zone0/temp', ]); if ($raw !== '' && is_numeric($raw)) { return round(((float)$raw) / 1000, 2); } $vc = sh(['/usr/bin/vcgencmd', 'measure_temp'], false, 3)['out']; if (preg_match('/([0-9.]+)/', $vc, $m)) { return round((float)$m[1], 2); } return 0.0; } function fan_target_pwm(float $temp): int { if ($temp >= 80) { return 255; } if ($temp <= 50) { return 0; } $ratio = ($temp - 50) / 30; return max(0, min(255, (int)round($ratio * 255))); } function fan_ramped_pwm(int $current, int $desired, float $temp): int { if ($temp >= 80) { return $desired; } if ($desired > $current) { return min($desired, $current + 2); } if ($desired < $current) { return max($desired, $current - 2); } return $desired; } function write_sys_value(string $path, int $value): bool { if ($path === '' || $path === 'N/A') { return false; } if (@file_put_contents($path, $value . "\n", LOCK_EX) !== false) { return true; } $cmd = 'printf ' . escapeshellarg($value . "\n") . ' > ' . escapeshellarg($path); return sh(['/bin/sh', '-lc', $cmd], true, 5)['code'] === 0; } function apply_fan_policy(): array { $state = get_control_state(); $paths = fan_paths(); $temp = cpu_temp(); $mode = (string)($state['mode'] ?? 'auto'); if (!in_array($mode, ['auto', 'manual', 'off'], true)) { $mode = 'auto'; } $manualPwm = max(0, min(255, (int)($state['manual_pwm'] ?? 120))); $currentPwm = read_int_file($paths['pwm']); $desired = match ($mode) { 'manual' => $manualPwm, 'off' => 0, default => fan_target_pwm($temp), }; $target = $mode === 'auto' ? fan_ramped_pwm($currentPwm, $desired, $temp) : $desired; $enableOk = write_sys_value($paths['enable'], $mode === 'off' ? 0 : 1); $pwmOk = write_sys_value($paths['pwm'], $target); usleep(60000); $actualPwm = read_int_file($paths['pwm']); $rpm = read_int_file($paths['rpm']); return [ 'mode' => $mode, 'target_pwm' => $target, 'actual_pwm' => $actualPwm, 'temp_c' => $temp, 'rpm' => $rpm, 'ok' => $enableOk && $pwmOk, 'paths' => $paths, 'enable_value' => first_readable([$paths['enable']]) ?: 'N/A', ]; } function mem_info(): array { $rows = []; foreach (@file('/proc/meminfo', FILE_IGNORE_NEW_LINES) ?: [] as $line) { if (preg_match('/^([^:]+):\s+(\d+)/', $line, $m)) { $rows[$m[1]] = (int)$m[2]; } } $total = (int)($rows['MemTotal'] ?? 0); $available = (int)($rows['MemAvailable'] ?? 0); $used = max(0, $total - $available); $swapTotal = (int)($rows['SwapTotal'] ?? 0); $swapFree = (int)($rows['SwapFree'] ?? 0); return [ 'total_mb' => round($total / 1024), 'used_mb' => round($used / 1024), 'free_mb' => round($available / 1024), 'percent' => $total > 0 ? round($used / $total * 100, 1) : 0, 'swap_total_mb' => round($swapTotal / 1024), 'swap_used_mb' => round(max(0, $swapTotal - $swapFree) / 1024), ]; } function disk_info(string $path = '/var/www/control'): array { $total = @disk_total_space($path) ?: 0; $free = @disk_free_space($path) ?: 0; if ($total <= 0 || $free <= 0) { $out = trim(sh(['/bin/df', '-kP', $path], false, 3)['out']); $lines = preg_split('/\R/', $out); $parts = isset($lines[1]) ? preg_split('/\s+/', trim($lines[1])) : []; if (count($parts) >= 6) { $total = (int)$parts[1] * 1024; $free = (int)$parts[3] * 1024; } } $used = max(0, $total - $free); return [ 'path' => '/', 'total_kb' => (int)round($total / 1024), 'used_kb' => (int)round($used / 1024), 'free_kb' => (int)round($free / 1024), 'percent' => $total > 0 ? round($used / $total * 100, 1) : 0, ]; } function active_user_info(): array { $out = trim(sh(['/usr/bin/who'], false, 3)['out']); if ($out === '') { return [ 'users' => 0, 'sessions' => 0, 'names' => '', 'display' => '0 users / 0 sessions', ]; } $lines = preg_split('/\R/', $out) ?: []; $lines = array_values(array_filter($lines, fn($line) => trim($line) !== '')); $names = []; foreach ($lines as $line) { $parts = preg_split('/\s+/', trim($line)); if (!empty($parts[0])) { $names[$parts[0]] = true; } } $userNames = array_keys($names); return [ 'users' => count($userNames), 'sessions' => count($lines), 'names' => implode(', ', $userNames), 'display' => count($userNames) . ' users / ' . count($lines) . ' sessions', ]; } function os_info(): array { $os = []; foreach (@file('/etc/os-release', FILE_IGNORE_NEW_LINES) ?: [] as $line) { if (preg_match('/^([A-Z_]+)=(.*)$/', $line, $m)) { $os[$m[1]] = trim($m[2], '"'); } } $uptimeRaw = trim((string)@file_get_contents('/proc/uptime')); $uptimeSec = $uptimeRaw !== '' ? (int)floor((float)explode(' ', $uptimeRaw)[0]) : 0; return [ 'hostname' => gethostname() ?: 'N/A', 'os' => $os['PRETTY_NAME'] ?? 'N/A', 'kernel' => php_uname('r'), 'arch' => php_uname('m'), 'model' => trim(@file_get_contents('/proc/device-tree/model') ?: '') ?: 'N/A', 'uptime' => human_seconds($uptimeSec), 'uptime_seconds' => $uptimeSec, ]; } function network_info(): array { $rows = []; foreach (glob('/sys/class/net/*') ?: [] as $dir) { $name = basename($dir); if ($name === 'lo') { continue; } $rx = (int)first_readable([$dir . '/statistics/rx_bytes']); $tx = (int)first_readable([$dir . '/statistics/tx_bytes']); $rows[] = [ 'name' => $name, 'state' => first_readable([$dir . '/operstate']) ?: 'unknown', 'carrier' => first_readable([$dir . '/carrier']) === '1' ? 'up' : 'down', 'mac' => first_readable([$dir . '/address']) ?: 'N/A', 'mtu' => first_readable([$dir . '/mtu']) ?: 'N/A', 'rx_bytes' => $rx, 'tx_bytes' => $tx, 'rx_human' => bytes_human($rx), 'tx_human' => bytes_human($tx), 'ipv4' => trim(sh(['/usr/sbin/ip', '-4', '-o', 'addr', 'show', 'dev', $name], false, 3)['out']) ?: 'N/A', ]; } return $rows; } function latest_sensor(): array { $stmt = db()->query(" SELECT * FROM sensor_logs ORDER BY id DESC LIMIT 1 "); return $stmt->fetch() ?: []; } function sensor_history(int $limit = 240): array { $limit = max(1, min(1500, $limit)); $stmt = db()->query(" SELECT sl.recorded_at AS time, sl.cpu_temp_c AS temp_c, sl.fan_rpm, sl.fan_efficiency, sl.rp1_temp_c, sl.cpu_voltage, sl.cpu_watts, sl.battery_voltage, sl.battery_percent, sl.pwm_value AS fan_pwm, sl.pwm_percent, sl.pwm_mode, sl.cpu_load_1, sl.cpu_load_5, sl.cpu_load_15, sl.disk_total_kb, sl.disk_used_kb, sl.disk_free_kb, sl.mem_total_mb, sl.mem_used_mb, CASE WHEN sl.mem_total_mb > 0 THEN ROUND(sl.mem_used_mb / sl.mem_total_mb * 100, 1) ELSE 0 END AS mem_percent FROM sensor_logs sl ORDER BY sl.id DESC LIMIT {$limit} "); return array_reverse($stmt->fetchAll()); } function numeric_median(array $values): ?float { $numbers = []; foreach ($values as $value) { if ($value !== null && $value !== '' && is_numeric($value)) { $numbers[] = (float)$value; } } if ($numbers === []) { return null; } sort($numbers, SORT_NUMERIC); $count = count($numbers); $mid = intdiv($count, 2); return ($count % 2) === 1 ? $numbers[$mid] : ($numbers[$mid - 1] + $numbers[$mid]) / 2; } function numeric_trimmed_average(array $values, float $trimRatio = 0.1): ?float { $numbers = []; foreach ($values as $value) { if ($value !== null && $value !== '' && is_numeric($value)) { $number = (float)$value; if ($number > 0) { $numbers[] = $number; } } } if ($numbers === []) { return null; } sort($numbers, SORT_NUMERIC); $trim = (int)floor(count($numbers) * max(0.0, min(0.4, $trimRatio))); if ($trim > 0 && count($numbers) > ($trim * 2 + 2)) { $numbers = array_slice($numbers, $trim, count($numbers) - ($trim * 2)); } return array_sum($numbers) / count($numbers); } function clamp_float(float $value, float $min, float $max): float { return max($min, min($max, $value)); } function battery_trend_history(int $hours = 24): array { $hours = max(1, min(48, $hours)); static $cache = []; $cacheKey = (string)$hours; $now = time(); if ( isset($cache[$cacheKey]) && ($now - (int)$cache[$cacheKey]['time']) < 55 && is_array($cache[$cacheKey]['rows']) ) { return $cache[$cacheKey]['rows']; } $stmt = db()->query(" SELECT FLOOR(UNIX_TIMESTAMP(recorded_at) / 60) AS bucket, MIN(recorded_at) AS time, AVG(battery_percent) AS battery_percent, AVG(battery_voltage) AS battery_voltage, AVG(cpu_watts) AS cpu_watts, AVG(cpu_load_1) AS cpu_load_1, COUNT(*) AS samples FROM sensor_logs FORCE INDEX (idx_recorded_at) WHERE recorded_at >= DATE_SUB(NOW(), INTERVAL {$hours} HOUR) AND battery_percent IS NOT NULL GROUP BY bucket ORDER BY bucket ASC "); $rows = []; foreach ($stmt->fetchAll() as $row) { $time = strtotime((string)($row['time'] ?? '')); if ($time <= 0 || !is_numeric($row['battery_percent'] ?? null)) { continue; } $rows[] = [ 'time' => $time, 'battery_percent' => (float)$row['battery_percent'], 'battery_voltage' => is_numeric($row['battery_voltage'] ?? null) ? (float)$row['battery_voltage'] : null, 'cpu_watts' => is_numeric($row['cpu_watts'] ?? null) ? (float)$row['cpu_watts'] : null, 'cpu_load_1' => is_numeric($row['cpu_load_1'] ?? null) ? (float)$row['cpu_load_1'] : null, 'samples' => (int)($row['samples'] ?? 0), ]; } $cache[$cacheKey] = [ 'time' => $now, 'rows' => $rows, ]; return $rows; } function battery_profile_history(int $days = 45): array { $days = max(3, min(90, $days)); static $cache = []; $cacheKey = (string)$days; $now = time(); $cacheFile = sys_get_temp_dir() . '/control-battery-profile-' . $days . 'd.json'; if ( isset($cache[$cacheKey]) && ($now - (int)$cache[$cacheKey]['time']) < 600 && is_array($cache[$cacheKey]['rows']) ) { return $cache[$cacheKey]['rows']; } if (is_readable($cacheFile)) { $raw = @file_get_contents($cacheFile); $decoded = is_string($raw) ? json_decode($raw, true) : null; if ( is_array($decoded) && isset($decoded['created_at'], $decoded['rows']) && is_array($decoded['rows']) && ($now - (int)$decoded['created_at']) < 21600 ) { $cache[$cacheKey] = [ 'time' => $now, 'rows' => $decoded['rows'], ]; return $decoded['rows']; } } $maxId = (int)db()->query("SELECT MAX(id) FROM sensor_logs")->fetchColumn(); $minId = max(1, $maxId - 3000000); $stmt = db()->query(" SELECT recorded_at AS time, battery_percent, battery_voltage, cpu_watts, cpu_load_1, 1 AS samples FROM sensor_logs FORCE INDEX (idx_recorded_at) WHERE recorded_at >= DATE_SUB(NOW(), INTERVAL {$days} DAY) AND battery_percent IS NOT NULL AND id >= {$minId} AND MOD(id, 300) = 0 ORDER BY recorded_at ASC "); $rows = []; foreach ($stmt->fetchAll() as $row) { $time = strtotime((string)($row['time'] ?? '')); if ($time <= 0 || !is_numeric($row['battery_percent'] ?? null)) { continue; } $rows[] = [ 'time' => $time, 'battery_percent' => (float)$row['battery_percent'], 'battery_voltage' => is_numeric($row['battery_voltage'] ?? null) ? (float)$row['battery_voltage'] : null, 'cpu_watts' => is_numeric($row['cpu_watts'] ?? null) ? (float)$row['cpu_watts'] : null, 'cpu_load_1' => is_numeric($row['cpu_load_1'] ?? null) ? (float)$row['cpu_load_1'] : null, 'samples' => (int)($row['samples'] ?? 0), ]; } $cache[$cacheKey] = [ 'time' => $now, 'rows' => $rows, ]; @file_put_contents( $cacheFile, json_encode([ 'created_at' => $now, 'days' => $days, 'rows' => $rows, ], JSON_UNESCAPED_UNICODE) ); return $rows; } function battery_trend_candidate(array $trendRows, float $currentPercent, int $windowSeconds, ?float $recentWatts): ?array { if (count($trendRows) < 6) { return null; } $lastTime = (int)$trendRows[count($trendRows) - 1]['time']; $rows = array_values(array_filter($trendRows, static function (array $row) use ($lastTime, $windowSeconds): bool { return (int)$row['time'] >= ($lastTime - $windowSeconds) && is_numeric($row['battery_percent'] ?? null); })); $count = count($rows); if ($count < 6) { return null; } $first = $rows[0]; $last = $rows[$count - 1]; $elapsed = max(1, (int)$last['time'] - (int)$first['time']); if ($elapsed < 600) { return null; } $edgeCount = max(3, min(10, (int)floor($count * 0.12))); $startSoc = numeric_median(array_column(array_slice($rows, 0, $edgeCount), 'battery_percent')); $endSoc = numeric_median(array_column(array_slice($rows, -$edgeCount), 'battery_percent')); if ($startSoc === null || $endSoc === null) { return null; } $drop = $startSoc - $endSoc; $minDrop = $windowSeconds <= 3600 ? 0.12 : 0.22; if ($drop < $minDrop) { return null; } $rate = $drop / $elapsed; if ($rate <= 0) { return null; } $windowWatts = numeric_trimmed_average(array_column($rows, 'cpu_watts'), 0.1); $loadFactor = 1.0; if ($recentWatts !== null && $recentWatts > 0 && $windowWatts !== null && $windowWatts > 0) { $loadFactor = 1 + ((clamp_float($recentWatts / $windowWatts, 0.65, 1.75) - 1) * 0.45); $rate *= $loadFactor; } $seconds = (int)round($currentPercent / $rate); if ($seconds <= 0) { return null; } $confidence = min(1.0, $elapsed / $windowSeconds) * min(1.0, $drop / 1.2) * min(1.0, $count / 90); return [ 'seconds' => $seconds, 'rate_per_second' => $rate, 'drop_percent' => round($drop, 3), 'elapsed_seconds' => $elapsed, 'window_seconds' => $windowSeconds, 'sample_count' => $count, 'confidence' => round($confidence, 4), 'weight' => max(0.05, $confidence), 'avg_watts' => $windowWatts === null ? null : round($windowWatts, 3), 'load_factor' => round($loadFactor, 3), 'source' => 'recent_window', ]; } function battery_learned_profile_candidate(array $profileRows, float $currentPercent, ?float $recentWatts): ?array { if (count($profileRows) < 24) { return null; } $now = time(); $rates = []; $dropSum = 0.0; $sampleSum = 0; $socBuckets = []; $minSoc = max(0.0, $currentPercent - 70.0); $maxSoc = min(100.0, $currentPercent + 8.0); for ($i = 1, $count = count($profileRows); $i < $count; $i++) { $prev = $profileRows[$i - 1]; $row = $profileRows[$i]; $elapsed = (int)$row['time'] - (int)$prev['time']; if ($elapsed < 240 || $elapsed > 900) { continue; } $startSoc = (float)$prev['battery_percent']; $endSoc = (float)$row['battery_percent']; $avgSoc = ($startSoc + $endSoc) / 2; if ($avgSoc < $minSoc || $avgSoc > $maxSoc) { continue; } $drop = $startSoc - $endSoc; if ($drop < 0.03 || $drop > 8.0) { continue; } $avgWatts = numeric_trimmed_average([$prev['cpu_watts'] ?? null, $row['cpu_watts'] ?? null], 0.0); $loadFactor = 1.0; if ($recentWatts !== null && $recentWatts > 0 && $avgWatts !== null && $avgWatts > 0) { $loadFactor = 1 + ((clamp_float($recentWatts / $avgWatts, 0.55, 1.95) - 1) * 0.5); } $socDistance = abs($currentPercent - $avgSoc); $socWeight = 1 / (1 + ($socDistance / 18)); $ageDays = max(0.0, ($now - (int)$row['time']) / 86400); $recencyWeight = 1 / (1 + ($ageDays / 45)); $sampleWeight = min(1.0, max(1, ((int)$prev['samples'] + (int)$row['samples']) / 2) / 30); $weight = max(0.01, $socWeight * $recencyWeight * $sampleWeight); $rates[] = [ 'rate' => ($drop / $elapsed) * $loadFactor, 'weight' => $weight, 'soc' => $avgSoc, 'drop' => $drop, 'watts' => $avgWatts, ]; $dropSum += $drop; $sampleSum += (int)$prev['samples'] + (int)$row['samples']; $bucket = (int)(floor($avgSoc / 10) * 10); $socBuckets[$bucket] = true; } if (count($rates) < 12 || $dropSum < 1.0) { return null; } $weightedRate = 0.0; $weightSum = 0.0; foreach ($rates as $row) { $weightedRate += (float)$row['rate'] * (float)$row['weight']; $weightSum += (float)$row['weight']; } if ($weightedRate <= 0 || $weightSum <= 0) { return null; } $rate = $weightedRate / $weightSum; $seconds = (int)round($currentPercent / $rate); if ($seconds <= 0) { return null; } $watts = numeric_trimmed_average(array_column($rates, 'watts'), 0.1); $confidence = min(1.0, count($rates) / 240) * min(1.0, $dropSum / 18) * min(1.0, count($socBuckets) / 5); return [ 'seconds' => $seconds, 'rate_per_second' => $rate, 'drop_percent' => round($dropSum, 3), 'elapsed_seconds' => null, 'window_seconds' => null, 'sample_count' => $sampleSum, 'confidence' => round($confidence, 4), 'weight' => max(0.05, $confidence * 0.9), 'avg_watts' => $watts === null ? null : round($watts, 3), 'load_factor' => null, 'source' => 'learned_profile', 'intervals' => count($rates), 'soc_buckets' => count($socBuckets), ]; } function battery_power_fallback_estimate(float $percent, array $history): array { $wattValues = []; foreach (array_slice($history, -180) as $row) { $watts = $row['cpu_watts'] ?? null; if ($watts !== null && $watts !== '' && is_numeric($watts) && (float)$watts > 0) { $wattValues[] = (float)$watts; } } $avgWatts = numeric_trimmed_average($wattValues, 0.12); if (BATTERY_CAPACITY_WH > 0 && $avgWatts !== null && $avgWatts > 0) { $remainingWh = BATTERY_CAPACITY_WH * ($percent / 100); $seconds = (int)round(($remainingWh / $avgWatts) * 3600); return [ 'display' => human_remaining_seconds($seconds), 'seconds' => $seconds, 'source' => 'capacity_power_fallback', 'avg_watts' => round($avgWatts, 3), 'capacity_wh' => BATTERY_CAPACITY_WH, ]; } return [ 'display' => '-', 'seconds' => null, 'source' => BATTERY_CAPACITY_WH > 0 ? 'avg_watts_missing' : 'battery_capacity_missing', 'avg_watts' => $avgWatts === null ? null : round($avgWatts, 3), ]; } function battery_remaining_estimate(array $battery, array $history, array $trendRows = [], array $profileRows = []): array { $percent = $battery['percent'] ?? null; if ($percent === null || $percent === '' || !is_numeric($percent)) { return [ 'display' => '-', 'seconds' => null, 'source' => 'battery_soc_missing', 'avg_watts' => null, ]; } $percent = max(0.0, min(100.0, (float)$percent)); $recentWatts = numeric_trimmed_average(array_column(array_slice($trendRows, -10), 'cpu_watts'), 0.1) ?? numeric_trimmed_average(array_column(array_slice($history, -90), 'cpu_watts'), 0.1); $candidates = []; foreach ([1800, 3600, 10800, 21600, 43200, 86400] as $windowSeconds) { $candidate = battery_trend_candidate($trendRows, $percent, $windowSeconds, $recentWatts); if ($candidate !== null) { $candidates[] = $candidate; } } $learned = battery_learned_profile_candidate($profileRows, $percent, $recentWatts); if ($learned !== null) { $candidates[] = $learned; } if ($candidates !== []) { $weightedRate = 0.0; $weightSum = 0.0; foreach ($candidates as $candidate) { $weight = (float)$candidate['weight']; $weightedRate += (float)$candidate['rate_per_second'] * $weight; $weightSum += $weight; } if ($weightedRate > 0 && $weightSum > 0) { $rate = $weightedRate / $weightSum; $seconds = (int)round($percent / $rate); $avgWatts = numeric_trimmed_average(array_column($candidates, 'avg_watts'), 0.0); return [ 'display' => human_remaining_seconds($seconds), 'seconds' => $seconds, 'source' => 'soc_multi_window', 'avg_watts' => $avgWatts === null ? null : round($avgWatts, 3), 'recent_watts' => $recentWatts === null ? null : round($recentWatts, 3), 'drop_per_hour' => round($rate * 3600, 3), 'confidence' => round(array_sum(array_column($candidates, 'confidence')) / count($candidates), 3), 'sources' => array_values(array_unique(array_column($candidates, 'source'))), 'windows' => array_map(static function (array $candidate): array { return [ 'source' => $candidate['source'], 'minutes' => $candidate['window_seconds'] === null ? null : (int)round($candidate['window_seconds'] / 60), 'drop_percent' => $candidate['drop_percent'], 'confidence' => $candidate['confidence'], 'load_factor' => $candidate['load_factor'], 'intervals' => $candidate['intervals'] ?? null, 'soc_buckets' => $candidate['soc_buckets'] ?? null, ]; }, $candidates), ]; } } return battery_power_fallback_estimate($percent, $history); } function add_battery_remaining_history(array $history): array { $wattWindow = []; $socWindow = []; foreach ($history as $index => $row) { $watts = $row['cpu_watts'] ?? null; if ($watts !== null && $watts !== '' && is_numeric($watts) && (float)$watts > 0) { $wattWindow[] = (float)$watts; if (count($wattWindow) > 180) { array_shift($wattWindow); } } $percent = $row['battery_percent'] ?? null; $time = strtotime((string)($row['time'] ?? '')); if ($percent !== null && $percent !== '' && is_numeric($percent) && $time > 0) { $socWindow[] = [ 'time' => $time, 'soc' => (float)$percent, ]; if (count($socWindow) > 240) { array_shift($socWindow); } } $history[$index]['battery_remaining_seconds'] = null; if (!is_numeric($percent)) { continue; } $safePercent = max(0.0, min(100.0, (float)$percent)); if (count($socWindow) >= 30) { $first = $socWindow[0]; $last = $socWindow[count($socWindow) - 1]; $elapsed = max(1, (int)$last['time'] - (int)$first['time']); $drop = (float)$first['soc'] - (float)$last['soc']; if ($elapsed >= 120 && $drop >= 0.12) { $history[$index]['battery_remaining_seconds'] = (int)round($safePercent / ($drop / $elapsed)); continue; } } $avgWatts = numeric_trimmed_average($wattWindow, 0.12); if (BATTERY_CAPACITY_WH > 0 && $avgWatts !== null && $avgWatts > 0) { $safePercent = max(0.0, min(100.0, (float)$percent)); $remainingWh = BATTERY_CAPACITY_WH * ($safePercent / 100); $history[$index]['battery_remaining_seconds'] = (int)round(($remainingWh / $avgWatts) * 3600); } } return $history; } function process_service_name(int $pid): string { $cgroup = @file('/proc/' . $pid . '/cgroup', FILE_IGNORE_NEW_LINES) ?: []; foreach ($cgroup as $line) { if (preg_match('/([^\/:]+\.service)(?:\/|$)/', $line, $m)) { return $m[1]; } } return 'N/A'; } function process_args(int $pid): string { $raw = @file_get_contents('/proc/' . $pid . '/cmdline'); if (is_string($raw) && $raw !== '') { return command_short(str_replace("\0", ' ', trim($raw, "\0"))); } $comm = trim((string)@file_get_contents('/proc/' . $pid . '/comm')); return $comm !== '' ? $comm : 'N/A'; } function process_resource_data(int $limit = 6): array { $limit = max(3, min(12, $limit)); $ps = sh([ '/bin/ps', '-eo', 'pid=,ppid=,user=,pcpu=,pmem=,rss=,comm=,args=', '--sort=-pcpu', ], false, 4)['out']; $cpu = []; $mem = []; foreach (preg_split('/\R/', trim($ps)) ?: [] as $line) { $line = trim($line); if ($line === '') { continue; } $parts = preg_split('/\s+/', $line, 8); if (count($parts) < 8 || !ctype_digit($parts[0])) { continue; } $pid = (int)$parts[0]; $row = [ 'pid' => $pid, 'ppid' => (int)$parts[1], 'user' => $parts[2], 'cpu_percent' => round((float)$parts[3], 1), 'mem_percent' => round((float)$parts[4], 1), 'rss_mb' => round(((int)$parts[5]) / 1024, 1), 'name' => $parts[6], 'service' => process_service_name($pid), 'command' => command_short($parts[7]), ]; if ($row['cpu_percent'] > 0 || count($cpu) < $limit) { $cpu[] = $row; } $mem[] = $row; } usort($mem, fn($a, $b) => ($b['mem_percent'] <=> $a['mem_percent']) ?: ($b['rss_mb'] <=> $a['rss_mb'])); return [ 'cpu' => array_slice($cpu, 0, $limit), 'memory' => array_slice($mem, 0, $limit), ]; } function notice_process_signature(array $processes): string { $cpu = null; foreach (($processes['cpu'] ?? []) as $row) { if (!is_array($row)) { continue; } $command = (string)($row['command'] ?? $row['name'] ?? ''); $service = (string)($row['service'] ?? ''); if ( str_contains($command, '/bin/ps') || str_contains($command, 'api.php') || str_contains($command, 'php-fpm') || $service === 'fanpanel-apply.service' ) { continue; } $cpu = $row; break; } $mem = null; foreach (($processes['memory'] ?? []) as $row) { if (!is_array($row)) { continue; } $mem = $row; break; } return hash('sha256', json_encode([ 'cpu' => $cpu === null ? null : [ 'pid' => $cpu['pid'] ?? null, 'service' => $cpu['service'] ?? null, 'command' => $cpu['command'] ?? $cpu['name'] ?? null, ], 'mem' => $mem === null ? null : [ 'pid' => $mem['pid'] ?? null, 'service' => $mem['service'] ?? null, 'command' => $mem['command'] ?? $mem['name'] ?? null, ], ], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)); } function trimmed_average(array $values, float $fallback): float { $values = array_values(array_filter( $values, fn($value) => is_numeric($value) && (float)$value > 0 )); if (count($values) < 5) { return $fallback; } sort($values, SORT_NUMERIC); $trim = (int)floor(count($values) * 0.1); if ($trim > 0 && count($values) > $trim * 2) { $values = array_slice($values, $trim, count($values) - ($trim * 2)); } return array_sum($values) / max(1, count($values)); } function notice_rolling_baseline(array $history, float $temp, float $rpm, float $pwm, array $state = []): array { $rows = array_slice($history, -180); if (count($rows) > 3) { $rows = array_slice($rows, 0, -3); } $temps = []; $rpms = []; $pwms = []; foreach ($rows as $row) { $rowTemp = (float)($row['temp_c'] ?? 0); $rowRpm = (float)($row['fan_rpm'] ?? 0); $rowPwm = (float)($row['fan_pwm'] ?? 0); if ($rowTemp > 0) $temps[] = $rowTemp; if ($rowRpm > 0) $rpms[] = $rowRpm; if ($rowPwm > 0) $pwms[] = $rowPwm; } $fallbackTemp = (float)($state['baseline_temp'] ?? 0) > 0 ? (float)$state['baseline_temp'] : $temp; $fallbackRpm = (float)($state['baseline_rpm'] ?? 0) > 0 ? (float)$state['baseline_rpm'] : $rpm; $fallbackPwm = (float)($state['baseline_pwm'] ?? 0) > 0 ? (float)$state['baseline_pwm'] : $pwm; return [ 'temp' => trimmed_average($temps, $fallbackTemp), 'rpm' => trimmed_average($rpms, $fallbackRpm), 'pwm' => trimmed_average($pwms, $fallbackPwm), 'samples' => count($rows), ]; } function fan_spike_analysis(array $history, array $fan, array $system, array $processes = []): array { $rpm = (float)($fan['rpm'] ?? 0); $pwm = (float)($fan['pwm'] ?? 0); $temp = (float)($system['temp_c'] ?? 0); $state = system_notice_state(); $rollingBaseline = notice_rolling_baseline($history, $temp, $rpm, $pwm, $state); $currentState = (string)($state['state'] ?? 'normal'); if (!in_array($currentState, ['normal', 'alert'], true)) { $currentState = 'normal'; } $bootEpoch = (int)(time() - max(0, (int)($system['uptime_seconds'] ?? 0))); $alertStartedEpoch = strtotime((string)($state['alert_started_at'] ?? '')) ?: 0; if ($currentState === 'alert' && $bootEpoch > 0 && ($alertStartedEpoch === 0 || $alertStartedEpoch < $bootEpoch)) { $currentState = 'normal'; } $rpmAvg = $currentState === 'alert' ? (float)($state['baseline_rpm'] ?? 0) : (float)$rollingBaseline['rpm']; $pwmAvg = $currentState === 'alert' ? (float)($state['baseline_pwm'] ?? 0) : (float)$rollingBaseline['pwm']; $tempAvg = $currentState === 'alert' ? (float)($state['baseline_temp'] ?? 0) : (float)$rollingBaseline['temp']; if ($rpmAvg <= 0) $rpmAvg = $rpm; if ($pwmAvg <= 0) $pwmAvg = $pwm; if ($tempAvg <= 0) $tempAvg = $temp; $rpmDelta = $rpm - $rpmAvg; $pwmDelta = $pwm - $pwmAvg; $tempDelta = $temp - $tempAvg; $rollingRpmDelta = $rpm - (float)$rollingBaseline['rpm']; $rollingTempDelta = $temp - (float)$rollingBaseline['temp']; $mode = (string)($fan['mode'] ?? ''); if ($mode === 'off') { $offBaselineReason = 'fan_off_baseline'; $hasOffBaseline = (string)($state['active_reason'] ?? '') === $offBaselineReason; $tempAvg = $hasOffBaseline && (float)($state['baseline_temp'] ?? 0) > 0 ? (float)$state['baseline_temp'] : $temp; $rpmAvg = $hasOffBaseline && (float)($state['baseline_rpm'] ?? 0) >= 0 ? (float)$state['baseline_rpm'] : $rpm; $pwmAvg = $hasOffBaseline && (float)($state['baseline_pwm'] ?? 0) >= 0 ? (float)$state['baseline_pwm'] : $pwm; if (!$hasOffBaseline) { save_system_notice_state('normal', $tempAvg, $rpmAvg, $pwmAvg, $offBaselineReason); } return [ 'active' => false, 'summary' => 'Fan off baseline is fixed.', 'rpm_delta' => round($rpm - $rpmAvg, 1), 'pwm_delta' => round($pwm - $pwmAvg, 1), 'temp_delta' => round($temp - $tempAvg, 1), 'rpm_avg' => round($rpmAvg, 1), 'pwm_avg' => round($pwmAvg, 1), 'temp_avg' => round($tempAvg, 1), 'notice_state' => 'normal', 'baseline_source' => 'frozen_off', 'baseline_samples' => (int)$rollingBaseline['samples'], ]; } $rpmExpected = $mode !== 'off' && ($pwm >= 20 || $pwmAvg >= 20); $reasons = []; if ($rpmExpected && abs($rpmDelta) >= 1000) $reasons[] = 'RPM ' . signed_delta_text($rpmDelta); if (abs($tempDelta) >= 3.0) $reasons[] = 'TEMP ' . signed_delta_text($tempDelta, 'C'); $spiking = false; if ($currentState === 'normal') { $spiking = $reasons !== []; if ($spiking) { save_system_notice_state( 'alert', $tempAvg, $rpmAvg, $pwmAvg, implode(', ', $reasons), true, $tempDelta, $rpmDelta, notice_process_signature($processes) ); } else { save_system_notice_state('normal', $rollingBaseline['temp'], $rollingBaseline['rpm'], $rollingBaseline['pwm']); } } else { $recovered = (abs($rpmDelta) <= 500 && abs($tempDelta) <= 1.5) || (abs($rollingRpmDelta) <= 500 && abs($rollingTempDelta) <= 1.5); if ($recovered || $reasons === []) { $currentState = 'normal'; save_system_notice_state('normal', $rollingBaseline['temp'], $rollingBaseline['rpm'], $rollingBaseline['pwm']); $tempAvg = (float)$rollingBaseline['temp']; $rpmAvg = (float)$rollingBaseline['rpm']; $pwmAvg = (float)$rollingBaseline['pwm']; $rpmDelta = $rpm - $rpmAvg; $pwmDelta = $pwm - $pwmAvg; $tempDelta = $temp - $tempAvg; } else { save_system_notice_state( 'alert', $tempAvg, $rpmAvg, $pwmAvg, implode(', ', $reasons), false, $tempDelta, $rpmDelta, notice_process_signature($processes) ); } } $summary = 'No system notice detected in recent samples.'; if ($spiking) { $summary = 'System notice: ' . implode(', ', $reasons); } elseif ($currentState === 'alert' && $reasons !== []) { $summary = 'System notice active: ' . implode(', ', $reasons); } return [ 'active' => $spiking, 'summary' => $summary, 'rpm_delta' => round($rpmDelta, 1), 'pwm_delta' => round($pwmDelta, 1), 'temp_delta' => round($tempDelta, 1), 'rpm_avg' => round($rpmAvg, 1), 'pwm_avg' => round($pwmAvg, 1), 'temp_avg' => round($tempAvg, 1), 'notice_state' => $spiking ? 'alert' : $currentState, 'baseline_source' => $currentState === 'alert' ? 'frozen_alert' : 'rolling', 'baseline_samples' => (int)$rollingBaseline['samples'], ]; } function system_notice_state(): array { $stmt = db()->query(" SELECT state, baseline_temp, baseline_rpm, baseline_pwm, active_reason, active_temp_delta, active_rpm_delta, process_signature, alert_started_at, last_alert_at, updated_at FROM system_notice_state WHERE id = 1 LIMIT 1 "); return $stmt->fetch() ?: []; } function save_system_notice_state( string $state, float $baselineTemp, float $baselineRpm, float $baselinePwm, ?string $reason = null, bool $alertStarted = false, float $activeTempDelta = 0.0, float $activeRpmDelta = 0.0, ?string $processSignature = null ): void { $stmt = db()->prepare(" INSERT INTO system_notice_state ( id, state, baseline_temp, baseline_rpm, baseline_pwm, active_reason, active_temp_delta, active_rpm_delta, process_signature, alert_started_at, last_alert_at ) VALUES ( 1, :state, :baseline_temp, :baseline_rpm, :baseline_pwm, :active_reason, :active_temp_delta, :active_rpm_delta, :process_signature, IF(:alert_started = 1, CURRENT_TIMESTAMP, NULL), IF(:alert_started_last = 1, CURRENT_TIMESTAMP, NULL) ) ON DUPLICATE KEY UPDATE state = VALUES(state), baseline_temp = VALUES(baseline_temp), baseline_rpm = VALUES(baseline_rpm), baseline_pwm = VALUES(baseline_pwm), active_reason = VALUES(active_reason), active_temp_delta = VALUES(active_temp_delta), active_rpm_delta = VALUES(active_rpm_delta), process_signature = VALUES(process_signature), alert_started_at = IF(:alert_started_update = 1, CURRENT_TIMESTAMP, alert_started_at), last_alert_at = IF(:alert_started_last_update = 1, CURRENT_TIMESTAMP, last_alert_at), updated_at = CURRENT_TIMESTAMP "); $stmt->execute([ ':state' => in_array($state, ['normal', 'alert'], true) ? $state : 'normal', ':baseline_temp' => round($baselineTemp, 2), ':baseline_rpm' => round($baselineRpm, 2), ':baseline_pwm' => round($baselinePwm, 2), ':active_reason' => $reason, ':active_temp_delta' => round($activeTempDelta, 2), ':active_rpm_delta' => round($activeRpmDelta, 2), ':process_signature' => $processSignature, ':alert_started' => $alertStarted ? 1 : 0, ':alert_started_last' => $alertStarted ? 1 : 0, ':alert_started_update' => $alertStarted ? 1 : 0, ':alert_started_last_update' => $alertStarted ? 1 : 0, ]); } function add_fan_spike_log(array $spike, array $fan, array $system, array $processes): int { $summary = (string)($spike['summary'] ?? ''); $rpmDelta = round((float)($spike['rpm_delta'] ?? 0), 1); $pwmDelta = round((float)($spike['pwm_delta'] ?? 0), 1); $tempDelta = round((float)($spike['temp_delta'] ?? 0), 1); $spikeKey = 'fan:' . date('YmdHi'); $loggedProcesses = notice_downward_only($tempDelta, $rpmDelta) ? ['cpu' => [], 'memory' => []] : $processes; $stmt = db()->prepare(" INSERT IGNORE INTO fan_spike_logs ( spike_key, summary, rpm_delta, pwm_delta, temp_delta, current_rpm, current_pwm, current_temp, cpu_process, memory_process ) VALUES ( :spike_key, :summary, :rpm_delta, :pwm_delta, :temp_delta, :current_rpm, :current_pwm, :current_temp, :cpu_process, :memory_process ) "); $stmt->execute([ ':spike_key' => $spikeKey, ':summary' => $summary !== '' ? $summary : null, ':rpm_delta' => $rpmDelta, ':pwm_delta' => $pwmDelta, ':temp_delta' => $tempDelta, ':current_rpm' => $fan['rpm'] ?? null, ':current_pwm' => $fan['pwm'] ?? null, ':current_temp' => $system['temp_c'] ?? null, ':cpu_process' => json_encode($loggedProcesses['cpu'] ?? [], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), ':memory_process' => json_encode($loggedProcesses['memory'] ?? [], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), ]); if ($stmt->rowCount() <= 0) { return 0; } return (int)db()->lastInsertId(); } function signed_delta_text(float $value, string $suffix = ''): string { $sign = $value >= 0 ? '+' : ''; return $sign . number_format($value, 1) . $suffix; } function signed_delta_compact(float $value, int $decimals, string $suffix = ''): string { $sign = $value >= 0 ? '+' : ''; return $sign . number_format($value, $decimals) . $suffix; } function display_process_name(array $row): string { $service = (string)($row['service'] ?? ''); if ($service !== '' && $service !== 'N/A') { return $service; } $command = (string)($row['command'] ?? $row['name'] ?? ''); if ( str_contains($command, '/codex ') || str_contains($command, '/codex') || str_contains($command, 'codex app-server') ) { return 'codex'; } if (str_contains($command, '.vscode-server')) { return 'vscode-server'; } if (str_contains($command, 'python3 -m homeassistant')) { return 'homeassistant'; } if (str_contains($command, 'firefox')) { return 'firefox'; } if ($command === '') { $command = (string)($row['name'] ?? ''); } return $command !== '' ? $command : 'N/A'; } function process_identity(array $row): string { return implode('|', [ (string)($row['pid'] ?? ''), (string)($row['service'] ?? ''), (string)($row['command'] ?? $row['name'] ?? ''), ]); } function expected_process_text(array $processes): string { $cpu = null; foreach (($processes['cpu'] ?? []) as $row) { if (!is_array($row)) { continue; } $command = (string)($row['command'] ?? $row['name'] ?? ''); $service = (string)($row['service'] ?? ''); if ( str_contains($command, '/bin/ps') || str_contains($command, 'api.php') || str_contains($command, 'php-fpm') || $service === 'fanpanel-apply.service' ) { continue; } $cpu = $row; break; } if ($cpu !== null && (float)($cpu['cpu_percent'] ?? 0) >= 1.0) { return 'CPU ' . display_process_name($cpu); } $mem = null; foreach (($processes['memory'] ?? []) as $row) { if (!is_array($row)) { continue; } $mem = $row; break; } if ($mem !== null) { return 'MEM ' . display_process_name($mem); } return 'CPU/MEM 원인 후보 없음'; } function expected_process_detail_text(array $processes): string { $cpu = null; foreach (($processes['cpu'] ?? []) as $row) { if (!is_array($row)) { continue; } $command = (string)($row['command'] ?? $row['name'] ?? ''); $service = (string)($row['service'] ?? ''); if ( str_contains($command, '/bin/ps') || str_contains($command, 'api.php') || str_contains($command, 'php-fpm') || $service === 'fanpanel-apply.service' ) { continue; } $cpu = $row; break; } $mem = null; foreach (($processes['memory'] ?? []) as $row) { if (!is_array($row)) { continue; } $mem = $row; break; } if ($cpu !== null && $mem !== null && process_identity($mem) === process_identity($cpu)) { return display_process_name($cpu); } $parts = []; if ($cpu !== null) { $parts[] = sprintf('CPU %.1f%% %s', (float)($cpu['cpu_percent'] ?? 0), display_process_name($cpu)); } if ($mem !== null) { $parts[] = sprintf('RAM %.1f%% %s', (float)($mem['mem_percent'] ?? 0), display_process_name($mem)); } return $parts === [] ? '원인 후보 없음' : implode(' / ', $parts); } function delta_state_text(float $value): string { return $value >= 0 ? '높음' : '낮음'; } function notice_downward_only(float $tempDelta, float $rpmDelta): bool { $tempTriggered = abs($tempDelta) >= 3.0; $rpmTriggered = abs($rpmDelta) >= 1000; if (!$tempTriggered && !$rpmTriggered) { return false; } if ($tempTriggered && $tempDelta >= 0) { return false; } if ($rpmTriggered && $rpmDelta >= 0) { return false; } return true; } function send_fan_spike_notify(array $spike, array $fan, array $system, array $processes): array { $tempDelta = (float)($spike['temp_delta'] ?? 0); $rpmDelta = (float)($spike['rpm_delta'] ?? 0); $tempAvg = (float)($spike['temp_avg'] ?? 0); $rpmAvg = (float)($spike['rpm_avg'] ?? 0); $pwmAvg = (float)($spike['pwm_avg'] ?? 0); $reasons = []; if (abs($tempDelta) >= 3.0) { $reasons[] = '온도 평균보다 ' . ($tempDelta >= 0 ? '상승' : '하강'); } if (abs($rpmDelta) >= 1000) { $reasons[] = '팬RPM 평균보다 ' . ($rpmDelta >= 0 ? '상승' : '하강'); } if ($reasons === []) { $reasons[] = '순간 변화'; } $body = '기록된 이유: ' . implode(', ', $reasons) . "\n평균: " . number_format($tempAvg, 1) . '°C / ' . number_format($rpmAvg, 0) . ' RPM / PWM ' . number_format($pwmAvg, 0) . "\n현재: " . number_format((float)($system['temp_c'] ?? 0), 1) . '°C / ' . number_format((float)($fan['rpm'] ?? 0), 0) . ' RPM / PWM ' . number_format((float)($fan['pwm'] ?? 0), 0) . (notice_downward_only($tempDelta, $rpmDelta) ? '' : "\n원인 후보: " . expected_process_detail_text($processes)); return send_ha_notify([ 'title' => '시스템 유의사항', 'message' => $body, 'level' => 'warning', 'url' => '/', 'tag' => 'control-system-notice', 'data' => [ 'channel' => 'control_system', 'notification_icon' => 'mdi:fan-alert', 'color' => '#f59e0b', 'sticky' => 'false', 'renotify' => 'true', 'summary' => $spike['summary'] ?? '', 'rpm_delta' => $spike['rpm_delta'] ?? 0, 'pwm_delta' => $spike['pwm_delta'] ?? 0, 'temp_delta' => $spike['temp_delta'] ?? 0, 'expected_process' => expected_process_text($processes), ], ]); } function latest_system_notice_notify_epoch(): int { return latest_ha_notify_epoch_by_tag('control-system-notice'); } function fan_spike_history(int $limit = 100): array { $limit = max(1, min(500, $limit)); $stmt = db()->query(" SELECT id, created_at, summary, rpm_delta, pwm_delta, temp_delta, current_rpm, current_pwm, current_temp, cpu_process, memory_process FROM fan_spike_logs WHERE id IN ( SELECT MAX(id) FROM fan_spike_logs GROUP BY DATE_FORMAT(created_at, '%Y-%m-%d %H:%i') ) ORDER BY id DESC LIMIT {$limit} "); $rows = $stmt->fetchAll(); foreach ($rows as &$row) { $row['cpu_process'] = json_decode((string)($row['cpu_process'] ?? '[]'), true) ?: []; $row['memory_process'] = json_decode((string)($row['memory_process'] ?? '[]'), true) ?: []; } unset($row); return $rows; } function dnsmasq_leases(): array { $map = []; foreach (@file('/var/lib/misc/dnsmasq.leases', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) ?: [] as $line) { $p = preg_split('/\s+/', trim($line)); if (count($p) >= 4) { $mac = strtolower($p[1]); $map[$mac] = [ 'expire_ts' => (int)$p[0], 'mac' => $mac, 'ip' => $p[2], 'hostname' => $p[3] === '*' ? 'N/A' : $p[3], ]; } } return $map; } function wifi_client_aliases(): array { try { $rows = db()->query("SELECT mac, hostname FROM wifi_client_aliases")->fetchAll(); } catch (Throwable) { return []; } $aliases = []; foreach ($rows as $row) { $mac = strtolower((string)($row['mac'] ?? '')); $hostname = trim((string)($row['hostname'] ?? '')); if (wifi_valid_mac($mac) && $hostname !== '') { $aliases[$mac] = $hostname; } } return $aliases; } function save_wifi_client_alias(string $mac, string $hostname): array { $mac = strtolower(trim($mac)); $hostname = trim(preg_replace('/\s+/', ' ', $hostname) ?? ''); if (!wifi_valid_mac($mac)) { throw new InvalidArgumentException('bad_mac'); } if ($hostname === '' || mb_strlen($hostname) > 80) { throw new InvalidArgumentException('bad_hostname'); } $stmt = db()->prepare(" INSERT INTO wifi_client_aliases (mac, hostname) VALUES (:mac, :hostname) ON DUPLICATE KEY UPDATE hostname = VALUES(hostname), updated_at = CURRENT_TIMESTAMP "); $stmt->execute([ ':mac' => $mac, ':hostname' => $hostname, ]); return [ 'mac' => $mac, 'hostname' => $hostname, ]; } function iw_station_dump(string $iface): string { if (!preg_match('/^[A-Za-z0-9_.:-]+$/', $iface)) { return ''; } return sh(['/usr/sbin/iw', 'dev', $iface, 'station', 'dump'], true, 4)['out']; } function parse_live_wifi_rows(string $iface, string $band, string $text, array $leases, array $aliases): array { $rows = []; $cur = null; foreach (explode("\n", $text) as $line) { $t = trim($line); if (preg_match('/^Station\s+([0-9a-f:]+)/i', $t, $m)) { if ($cur !== null) { $rows[] = $cur; } $mac = strtolower($m[1]); $lease = $leases[$mac] ?? []; $leaseHostname = (string)($lease['hostname'] ?? 'N/A'); $aliasHostname = $aliases[$mac] ?? null; $hostname = $aliasHostname ?: $leaseHostname; $hostnameSource = $aliasHostname ? 'alias' : ($leaseHostname === 'N/A' ? 'generated' : 'lease'); $cur = [ 'band' => $band, 'iface' => $iface, 'mac' => $mac, 'ip' => $lease['ip'] ?? 'N/A', 'hostname' => $hostname === 'N/A' ? '기기-' . strtoupper(substr(str_replace(':', '', $mac), -6)) : $hostname, 'hostname_source' => $hostnameSource, 'name' => $hostname === 'N/A' ? $mac : $hostname, 'signal' => 'N/A', 'tx_bitrate' => 'N/A', 'rx_bitrate' => 'N/A', 'signal_source' => 'missing', 'tx_bitrate_source' => 'missing', 'rx_bitrate_source' => 'missing', 'connected_time' => 'N/A', 'inactive_time' => 'N/A', 'rx_bytes' => 0, 'tx_bytes' => 0, 'rx_packets' => 0, 'tx_packets' => 0, 'tx_failed' => 0, ]; continue; } if ($cur === null) { continue; } if (preg_match('/^signal:\s+(.+)/', $t, $m)) { $cur['signal'] = $m[1]; $cur['signal_source'] = 'iw'; } elseif (preg_match('/^tx bitrate:\s+(.+)/', $t, $m)) { $cur['tx_bitrate'] = $m[1]; $cur['tx_bitrate_source'] = 'iw'; } elseif (preg_match('/^rx bitrate:\s+(.+)/', $t, $m)) { $cur['rx_bitrate'] = $m[1]; $cur['rx_bitrate_source'] = 'iw'; } elseif (preg_match('/^connected time:\s+(.+)/', $t, $m)) $cur['connected_time'] = $m[1]; elseif (preg_match('/^inactive time:\s+(.+)/', $t, $m)) $cur['inactive_time'] = $m[1]; elseif (preg_match('/^rx bytes:\s+(\d+)/', $t, $m)) $cur['rx_bytes'] = (int)$m[1]; elseif (preg_match('/^tx bytes:\s+(\d+)/', $t, $m)) $cur['tx_bytes'] = (int)$m[1]; elseif (preg_match('/^rx packets:\s+(\d+)/', $t, $m)) $cur['rx_packets'] = (int)$m[1]; elseif (preg_match('/^tx packets:\s+(\d+)/', $t, $m)) $cur['tx_packets'] = (int)$m[1]; elseif (preg_match('/^tx failed:\s+(\d+)/', $t, $m)) $cur['tx_failed'] = (int)$m[1]; } if ($cur !== null) { $rows[] = $cur; } return $rows; } function wifi_time_ms(string $value): int { if (preg_match('/(\d+)/', $value, $m)) { return (int)$m[1]; } return PHP_INT_MAX; } function wifi_unknown(mixed $value): bool { $text = strtoupper(trim((string)$value)); return $text === '' || $text === 'N/A' || $text === '-'; } function wifi_bitrate_mbps(mixed $value): ?float { if (preg_match('/([0-9]+(?:\.[0-9]+)?)/', (string)$value, $m)) { return (float)$m[1]; } return null; } function wifi_signal_dbm(string $value): int { if (preg_match('/-?\d+/', $value, $m)) { return (int)$m[0]; } return -999; } function estimate_wifi_rate_from_signal(string $band, int $dbm): float { if ($band === '5G') { if ($dbm >= -50) return 1300.0; if ($dbm >= -58) return 866.7; if ($dbm >= -66) return 585.0; if ($dbm >= -73) return 390.0; if ($dbm >= -80) return 173.3; return 54.0; } if ($dbm >= -50) return 300.0; if ($dbm >= -58) return 144.4; if ($dbm >= -66) return 72.2; if ($dbm >= -73) return 39.0; if ($dbm >= -80) return 19.5; return 6.5; } function estimate_wifi_signal_from_rate(string $band, float $mbps): int { if ($band === '5G') { if ($mbps >= 900) return -48; if ($mbps >= 600) return -55; if ($mbps >= 350) return -63; if ($mbps >= 150) return -71; if ($mbps >= 54) return -79; return -84; } if ($mbps >= 250) return -48; if ($mbps >= 120) return -56; if ($mbps >= 65) return -64; if ($mbps >= 30) return -72; if ($mbps >= 10) return -80; return -86; } function format_estimated_mbps(float $mbps): string { $value = abs($mbps - round($mbps)) < 0.05 ? (string)(int)round($mbps) : number_format($mbps, 1); return $value . ' MBit/s (추정)'; } function apply_wifi_estimates(array $clients): array { foreach ($clients as &$client) { $band = (string)($client['band'] ?? '2.4G'); $signalDbm = wifi_signal_dbm((string)($client['signal'] ?? '')); $txMbps = wifi_bitrate_mbps($client['tx_bitrate'] ?? null); $rxMbps = wifi_bitrate_mbps($client['rx_bitrate'] ?? null); if (wifi_unknown($client['signal'] ?? null)) { $sourceRate = max($txMbps ?? 0.0, $rxMbps ?? 0.0); $signalDbm = $sourceRate > 0 ? estimate_wifi_signal_from_rate($band, $sourceRate) : ($band === '5G' ? -67 : -70); $client['signal'] = $signalDbm . ' dBm (추정)'; $client['signal_source'] = $sourceRate > 0 ? 'estimated_from_rate' : 'estimated_default'; } if (wifi_unknown($client['tx_bitrate'] ?? null)) { $base = $rxMbps ?? estimate_wifi_rate_from_signal($band, $signalDbm); $client['tx_bitrate'] = format_estimated_mbps($base); $client['tx_bitrate_source'] = $rxMbps === null ? 'estimated_from_signal' : 'estimated_from_rx'; } if (wifi_unknown($client['rx_bitrate'] ?? null)) { $base = $txMbps ?? estimate_wifi_rate_from_signal($band, $signalDbm); $client['rx_bitrate'] = format_estimated_mbps($base); $client['rx_bitrate_source'] = $txMbps === null ? 'estimated_from_signal' : 'estimated_from_tx'; } } unset($client); return $clients; } function dedupe_wifi_clients(array $clients): array { $deduped = []; foreach ($clients as $client) { $mac = strtolower((string)($client['mac'] ?? '')); $key = $mac !== '' && $mac !== 'n/a' ? 'mac:' . $mac : 'row:' . ($client['band'] ?? '') . ':' . ($client['ip'] ?? '') . ':' . ($client['hostname'] ?? ''); if (!isset($deduped[$key])) { $deduped[$key] = $client; continue; } $currentInactive = wifi_time_ms((string)($deduped[$key]['inactive_time'] ?? '')); $nextInactive = wifi_time_ms((string)($client['inactive_time'] ?? '')); $currentSignal = wifi_signal_dbm((string)($deduped[$key]['signal'] ?? '')); $nextSignal = wifi_signal_dbm((string)($client['signal'] ?? '')); if ($nextInactive < $currentInactive || ($nextInactive === $currentInactive && $nextSignal > $currentSignal)) { $deduped[$key] = $client; } } return array_values($deduped); } function wifi_connected_time_missing(mixed $value): bool { $text = strtoupper(trim((string)$value)); return $text === '' || $text === 'N/A' || $text === '-'; } function wifi_valid_mac(string $mac): bool { return preg_match('/^[0-9a-f]{2}(?::[0-9a-f]{2}){5}$/', strtolower($mac)) === 1; } function prune_observed_wifi_sessions(PDO $pdo, array $visibleMacs): void { $visibleMacs = array_values(array_unique(array_filter( array_map(static fn($mac) => strtolower((string)$mac), $visibleMacs), static fn($mac) => wifi_valid_mac($mac) ))); if ($visibleMacs === []) { $pdo->exec("DELETE FROM wifi_observed_sessions WHERE band = '5G'"); return; } $placeholders = implode(',', array_fill(0, count($visibleMacs), '?')); $stmt = $pdo->prepare(" DELETE FROM wifi_observed_sessions WHERE band = '5G' AND mac NOT IN ($placeholders) "); $stmt->execute($visibleMacs); } function observed_wifi_duration_seconds(array $clients): array { $targets = []; $visible5gMacs = []; foreach ($clients as $client) { $band = (string)($client['band'] ?? ''); $mac = strtolower((string)($client['mac'] ?? '')); if ($band !== '5G' || !wifi_valid_mac($mac)) { continue; } $visible5gMacs[] = $mac; if (!wifi_connected_time_missing($client['connected_time'] ?? null)) { continue; } $targets[$mac] = [ 'mac' => $mac, 'band' => $band, 'iface' => (string)($client['iface'] ?? ''), 'ip' => (string)($client['ip'] ?? ''), 'hostname' => (string)($client['hostname'] ?? ''), ]; } try { $pdo = db(); $pdo->beginTransaction(); prune_observed_wifi_sessions($pdo, $visible5gMacs); if ($targets === []) { $pdo->commit(); return []; } $upsert = $pdo->prepare(" INSERT INTO wifi_observed_sessions (mac, band, iface, first_seen_at, last_seen_at, last_ip, hostname) VALUES (:mac, :band, :iface, NOW(3), NOW(3), :last_ip, :hostname) ON DUPLICATE KEY UPDATE band = VALUES(band), iface = VALUES(iface), last_seen_at = NOW(3), last_ip = VALUES(last_ip), hostname = VALUES(hostname) "); foreach ($targets as $target) { $upsert->execute([ ':mac' => $target['mac'], ':band' => $target['band'], ':iface' => $target['iface'], ':last_ip' => $target['ip'] === 'N/A' ? null : $target['ip'], ':hostname' => $target['hostname'] === 'N/A' ? null : $target['hostname'], ]); } $placeholders = implode(',', array_fill(0, count($targets), '?')); $stmt = $pdo->prepare(" SELECT mac, GREATEST(0, TIMESTAMPDIFF(SECOND, first_seen_at, NOW(3))) AS observed_seconds FROM wifi_observed_sessions WHERE mac IN ($placeholders) "); $stmt->execute(array_keys($targets)); $rows = $stmt->fetchAll(); $pdo->commit(); $seconds = []; foreach ($rows as $row) { $seconds[strtolower((string)$row['mac'])] = (int)$row['observed_seconds']; } return $seconds; } catch (Throwable) { if (isset($pdo) && $pdo instanceof PDO && $pdo->inTransaction()) { $pdo->rollBack(); } return []; } } function apply_observed_wifi_connected_time(array $clients): array { $observedSeconds = observed_wifi_duration_seconds($clients); if ($observedSeconds === []) { return $clients; } foreach ($clients as &$client) { $mac = strtolower((string)($client['mac'] ?? '')); if (($client['band'] ?? '') !== '5G' || !wifi_connected_time_missing($client['connected_time'] ?? null) || !array_key_exists($mac, $observedSeconds) ) { continue; } $client['connected_time'] = (string)$observedSeconds[$mac]; $client['connected_time_source'] = 'observed'; } unset($client); return $clients; } function wifi_data(): array { $leases = dnsmasq_leases(); $aliases = wifi_client_aliases(); $clients = []; foreach (['wlan0' => '2.4G', 'wlan1' => '5G'] as $iface => $band) { $clients = array_merge( $clients, parse_live_wifi_rows($iface, $band, iw_station_dump($iface), $leases, $aliases) ); } $clients = dedupe_wifi_clients($clients); $clients = apply_wifi_estimates($clients); $clients = apply_observed_wifi_connected_time($clients); return [ 'clients' => $clients, 'count24' => count(array_filter($clients, fn($c) => $c['band'] === '2.4G')), 'count5' => count(array_filter($clients, fn($c) => $c['band'] === '5G')), 'leases' => array_values($leases), ]; } function action_rows(int $limit = 80): array { $limit = max(1, min(300, $limit)); $stmt = db()->query(" SELECT created_at AS ts, action_type AS action, CONCAT( action_type, IF(pwm_mode IS NULL, '', CONCAT(' ', pwm_mode)), IF(pwm_value IS NULL, '', CONCAT(' pwm ', pwm_value)), IF(note IS NULL OR note = '', '', CONCAT(' / ', note)) ) AS message, success, actor_ip FROM fan_actions ORDER BY id DESC LIMIT {$limit} "); return $stmt->fetchAll(); } function custom_systemd_service_names(): array { $paths = glob('/etc/systemd/system/*.service') ?: []; $names = []; foreach ($paths as $path) { if (is_link($path)) { continue; } $name = basename($path); if (preg_match('/^[A-Za-z0-9_.@:-]+\.service$/', $name)) { $names[] = $name; } } sort($names, SORT_NATURAL | SORT_FLAG_CASE); return $names; } function parse_systemctl_show_records(string $out): array { $records = []; $current = []; foreach (preg_split('/\R/', trim($out)) as $line) { if ($line === '') { if (!empty($current['Id'])) { $records[$current['Id']] = $current; } $current = []; continue; } $parts = explode('=', $line, 2); if (count($parts) === 2) { $current[$parts[0]] = $parts[1]; } } if (!empty($current['Id'])) { $records[$current['Id']] = $current; } return $records; } function systemd_service_logs(string $unit, int $limit = 12): array { $limit = max(1, min(50, $limit)); $cmd = [ '/usr/bin/journalctl', '-u', $unit, '-n', (string)$limit, '--no-pager', '--output=short-iso', ]; $result = sh($cmd, false, 4); if ((int)$result['code'] !== 0) { $result = sh($cmd, true, 4); } $lines = array_values(array_filter( preg_split('/\R/', trim((string)$result['out'])), static fn($line) => trim((string)$line) !== '' )); return [ 'ok' => (int)$result['code'] === 0, 'lines' => $lines, 'error' => (int)$result['code'] === 0 ? '' : (string)$result['out'], ]; } function custom_systemd_services(): array { $cachePath = '/tmp/control-custom-services.json'; if (is_file($cachePath) && filemtime($cachePath) >= time() - 5) { $cached = json_decode((string)@file_get_contents($cachePath), true); if (is_array($cached)) { return $cached; } } $names = custom_systemd_service_names(); if (!$names) { return []; } $show = sh(array_merge([ '/usr/bin/systemctl', 'show', ], $names, [ '--no-pager', '-p', 'Id', '-p', 'LoadState', '-p', 'ActiveState', '-p', 'SubState', '-p', 'UnitFileState', '-p', 'Description', '-p', 'FragmentPath', '-p', 'ActiveEnterTimestamp', '-p', 'InactiveEnterTimestamp', '-p', 'ExecMainPID', '-p', 'NRestarts', ]), false, 6); $records = parse_systemctl_show_records((string)$show['out']); $rows = []; foreach ($names as $name) { $record = $records[$name] ?? []; $logs = systemd_service_logs($name, 12); $rows[] = [ 'name' => $name, 'description' => (string)($record['Description'] ?? ''), 'load' => (string)($record['LoadState'] ?? ''), 'active' => (string)($record['ActiveState'] ?? 'unknown'), 'sub' => (string)($record['SubState'] ?? ''), 'enabled' => (string)($record['UnitFileState'] ?? ''), 'pid' => (int)($record['ExecMainPID'] ?? 0), 'restarts' => (int)($record['NRestarts'] ?? 0), 'active_enter' => (string)($record['ActiveEnterTimestamp'] ?? ''), 'inactive_enter' => (string)($record['InactiveEnterTimestamp'] ?? ''), 'fragment' => (string)($record['FragmentPath'] ?? ''), 'logs' => $logs['lines'], 'logs_ok' => $logs['ok'], 'logs_error' => $logs['ok'] ? '' : $logs['error'], ]; } @file_put_contents($cachePath, json_encode($rows, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)); return $rows; } function collect_snapshot(bool $applyFan = true): array { if ($applyFan) { $policy = apply_fan_policy(); } else { $state = get_control_state(); $policy = [ 'mode' => (string)($state['mode'] ?? 'auto'), 'target_pwm' => (int)($state['manual_pwm'] ?? 120), 'actual_pwm' => 0, 'temp_c' => 0.0, 'rpm' => 0, 'ok' => true, 'paths' => [], 'enable_value' => 'N/A', ]; } $latest = latest_sensor(); $pwm = isset($latest['pwm_value']) ? (int)$latest['pwm_value'] : 0; if ($latest === false || $latest === [] || !isset($latest['pwm_value'])) { $pwm = (int)$policy['actual_pwm']; } $rpm = (int)($latest['fan_rpm'] ?? 0); if ($rpm <= 0) { $rpm = (int)$policy['rpm']; } $temp = (float)($latest['cpu_temp_c'] ?? 0); if ($temp <= 0) { $temp = (float)$policy['temp_c']; } $load = sys_getloadavg() ?: [0, 0, 0]; $mem = mem_info(); $disk = disk_info('/'); $os = os_info(); $throttledStatuses = throttled_statuses(); $cpuPower = $applyFan ? cpu_power_status() : [ 'voltage' => isset($latest['cpu_voltage']) ? (float)$latest['cpu_voltage'] : null, 'watts' => isset($latest['cpu_watts']) ? (float)$latest['cpu_watts'] : null, ]; $battery = $applyFan ? battery_status() : [ 'voltage' => isset($latest['battery_voltage']) ? (float)$latest['battery_voltage'] : null, 'percent' => isset($latest['battery_percent']) ? (float)$latest['battery_percent'] : null, ]; if ($applyFan) { add_sensor_log([ 'cpu_temp_c' => $temp, 'fan_rpm' => $rpm, 'fan_efficiency' => fan_efficiency($rpm, $temp, $cpuPower['watts'] ?? null), 'rp1_temp_c' => rp1_temp_c(), 'cpu_voltage' => $cpuPower['voltage'], 'cpu_watts' => $cpuPower['watts'], 'battery_voltage' => $battery['voltage'], 'battery_percent' => $battery['percent'], 'pwm_value' => $pwm, 'pwm_percent' => round($pwm / 255 * 100, 2), 'pwm_mode' => $policy['mode'], 'cpu_load_1' => round((float)$load[0], 2), 'cpu_load_5' => round((float)$load[1], 2), 'cpu_load_15' => round((float)$load[2], 2), 'mem_total_mb' => $mem['total_mb'], 'mem_used_mb' => $mem['used_mb'], 'mem_free_mb' => $mem['free_mb'], 'disk_total_kb' => $disk['total_kb'], 'disk_used_kb' => $disk['used_kb'], 'disk_free_kb' => $disk['free_kb'], 'uptime_seconds' => $os['uptime_seconds'], 'hostname' => $os['hostname'], ]); } $fan = [ 'mode' => $policy['mode'], 'pwm' => $pwm, 'percent' => round($pwm / 255 * 100, 1), 'rpm' => $rpm, 'enable' => $policy['enable_value'], 'target_pwm' => $policy['target_pwm'], 'policy_ok' => $policy['ok'], 'paths' => $policy['paths'], ]; $system = array_merge($os, [ 'temp_c' => $temp, 'load' => [ round((float)$load[0], 2), round((float)$load[1], 2), round((float)$load[2], 2), ], 'active_users' => active_user_info(), 'memory' => $mem, 'disk' => $disk, 'low_voltage' => $throttledStatuses['low_voltage'], 'throttling' => $throttledStatuses['throttling'], ]); $history = add_battery_remaining_history(sensor_history(240)); $batteryTrend = battery_trend_history(24); $batteryProfile = battery_profile_history(45); $battery['remaining'] = battery_remaining_estimate($battery, $history, $batteryTrend, $batteryProfile); $processes = process_resource_data(6); $fanSpike = fan_spike_analysis($history, $fan, $system, $processes); if (!empty($fanSpike['active'])) { $latestNoticeNotify = latest_system_notice_notify_epoch(); $spikeLogId = add_fan_spike_log($fanSpike, $fan, $system, $processes); if ($spikeLogId > 0) { $fanSpike['log_id'] = $spikeLogId; if ($latestNoticeNotify <= 0 || time() - $latestNoticeNotify >= HA_NOTIFY_SYSTEM_NOTICE_COOLDOWN) { $fanSpike['notify'] = send_fan_spike_notify($fanSpike, $fan, $system, $processes); } else { $fanSpike['notify'] = [ 'sent' => 0, 'failed' => 0, 'skipped' => 'system_notice_cooldown', 'cooldown_seconds' => HA_NOTIFY_SYSTEM_NOTICE_COOLDOWN, ]; } } } $snapshot = [ 'ok' => true, 'generated_at' => date('Y-m-d H:i:s'), 'time_ms' => (int)round(microtime(true) * 1000), 'fan' => $fan, 'system' => $system, 'battery' => $battery, 'wifi' => wifi_data(), 'history' => $history, 'processes' => $processes, 'custom_services' => custom_systemd_services(), 'fan_spike' => $fanSpike, 'fan_spike_history' => fan_spike_history(100), 'ha_notify_history' => ha_notify_log_rows(20), ]; return $snapshot; } function control_api_dispatch(): void { $action = $_GET['action'] ?? $_POST['action'] ?? 'status'; if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST') { require_csrf(); } try { if ($action === 'dmesg') { json_out([ 'ok' => true, 'data' => dmesg_log(), ]); } if ($action === 'status') { json_out([ 'ok' => true, 'data' => collect_snapshot(false), ]); } if ($action === 'fan') { $mode = (string)($_POST['mode'] ?? 'auto'); $pwm = max(0, min(255, (int)($_POST['pwm'] ?? 120))); if (!in_array($mode, ['auto', 'manual', 'off'], true)) { json_out([ 'ok' => false, 'error' => 'bad_mode', ], 400); } set_control_state($mode, $pwm); add_fan_action( 'fan_set', $mode, $pwm, 'web fan control', true ); $data = collect_snapshot(true); json_out([ 'ok' => true, 'data' => $data, ]); } if ($action === 'reboot') { $phrase = trim((string)($_POST['phrase'] ?? '')); $password = (string)($_POST['password'] ?? ''); if ($phrase !== '재부팅') { json_out([ 'ok' => false, 'error' => 'bad_reboot_phrase', 'message' => '재부팅 확인 단어가 올바르지 않습니다.', ], 400); } if (!hash_equals(APP_PASSWORD, $password)) { json_out([ 'ok' => false, 'error' => 'bad_reboot_password', 'message' => '관리자 암호가 올바르지 않습니다.', ], 403); } add_fan_action( 'system_reboot', null, null, 'web reboot requested', true ); $result = sh(['/usr/sbin/reboot'], true, 5); if ($result['code'] !== 0) { json_out([ 'ok' => false, 'error' => 'reboot_failed', 'message' => trim($result['out']) !== '' ? trim($result['out']) : 'reboot command failed', ], 500); } json_out([ 'ok' => true, 'data' => [ 'message' => 'reboot_requested', ], ]); } if ($action === 'wifi') { $verb = (string)($_POST['verb'] ?? ''); $unit = (string)($_POST['unit'] ?? ''); $allowedUnits = [ 'hostapd-24g.service', 'hostapd-5g.service', 'dnsmasq.service', ]; if ( !in_array($unit, $allowedUnits, true) || !in_array($verb, ['restart', 'reload'], true) ) { json_out([ 'ok' => false, 'error' => 'bad_wifi_request', ], 400); } $result = sh(['/usr/bin/systemctl', $verb, $unit], true, 25); $out = $result['out']; add_fan_action( 'wifi_' . $verb, null, null, $unit . "\n" . mb_substr($out, 0, 1000), true ); json_out([ 'ok' => true, 'output' => $out, 'data' => collect_snapshot(false), ]); } if ($action === 'wifi_alias') { $alias = save_wifi_client_alias( (string)($_POST['mac'] ?? ''), (string)($_POST['hostname'] ?? '') ); json_out([ 'ok' => true, 'data' => [ 'alias' => $alias, 'status' => collect_snapshot(false), ], ]); } if ($action === 'collect') { json_out([ 'ok' => true, 'data' => collect_snapshot(true), ]); } json_out([ 'ok' => false, 'error' => 'unknown_action', ], 404); } catch (Throwable $e) { json_out([ 'ok' => false, 'error' => 'exception', 'message' => $e->getMessage(), ], 500); } } if (!$controlApiLibrary) { control_api_dispatch(); }