PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, PDO::ATTR_EMULATE_PREPARES => false, ] ); } function db(bool $forceReconnect = false): PDO { static $pdo = null; static $lastPing = 0.0; if ($forceReconnect) { $pdo = null; $lastPing = 0.0; } if ($pdo instanceof PDO) { if ((microtime(true) - $lastPing) < 5.0) { return $pdo; } try { $pdo->query('SELECT 1'); $lastPing = microtime(true); return $pdo; } catch (PDOException $e) { if (db_connection_lost($e)) { $pdo = null; $lastPing = 0.0; } else { throw $e; } } } bootstrap_db(); $pdo = db_connect(); $lastPing = microtime(true); return $pdo; } function db_connect(): PDO { $pdo = new PDO( 'mysql:host=' . DB_HOST . ';port=' . DB_PORT . ';dbname=' . DB_NAME . ';charset=utf8mb4', DB_USER, DB_PASS, [ PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, PDO::ATTR_EMULATE_PREPARES => false, ] ); $pdo->exec("SET time_zone = '+09:00'"); return $pdo; } function db_connection_lost(PDOException $e): bool { $info = $e->errorInfo; $driverCode = isset($info[1]) ? (int)$info[1] : 0; $message = $e->getMessage(); return in_array($driverCode, [2006, 2013], true) || str_contains($message, 'server has gone away') || str_contains($message, 'Lost connection'); } function bootstrap_db(): void { static $done = false; if ($done) { return; } $pdo = db_server(); $pdo->exec(" CREATE DATABASE IF NOT EXISTS `" . DB_NAME . "` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci "); $pdo->exec("USE `" . DB_NAME . "`"); $pdo->exec(" CREATE TABLE IF NOT EXISTS control_state ( id TINYINT UNSIGNED NOT NULL PRIMARY KEY, mode VARCHAR(16) NOT NULL DEFAULT 'auto', manual_pwm INT NOT NULL DEFAULT 120, updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci "); $pdo->exec(" CREATE TABLE IF NOT EXISTS fan_actions ( id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, action_type VARCHAR(64) NOT NULL, pwm_mode VARCHAR(16) NULL, pwm_value INT NULL, note TEXT NULL, actor_ip VARCHAR(64) NULL, success TINYINT(1) NOT NULL DEFAULT 1, INDEX idx_created_at (created_at), INDEX idx_action_type (action_type) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci "); $pdo->exec(" CREATE TABLE IF NOT EXISTS sensor_logs ( id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, recorded_at DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3), cpu_temp_c DECIMAL(6,2) NULL, fan_rpm INT NULL, fan_efficiency DECIMAL(10,2) NULL, rp1_temp_c DECIMAL(6,2) NULL, cpu_voltage DECIMAL(6,3) NULL, cpu_watts DECIMAL(8,3) NULL, battery_voltage DECIMAL(6,3) NULL, battery_percent DECIMAL(6,2) NULL, pwm_value INT NULL, pwm_percent DECIMAL(5,2) NULL, pwm_mode VARCHAR(16) NULL, cpu_load_1 DECIMAL(8,2) NULL, cpu_load_5 DECIMAL(8,2) NULL, cpu_load_15 DECIMAL(8,2) NULL, mem_total_mb INT NULL, mem_used_mb INT NULL, mem_free_mb INT NULL, disk_total_kb BIGINT NULL, disk_used_kb BIGINT NULL, disk_free_kb BIGINT NULL, uptime_seconds BIGINT NULL, hostname VARCHAR(255) NULL, create_ip VARCHAR(64) NULL, INDEX idx_recorded_at (recorded_at), INDEX idx_pwm_mode (pwm_mode) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci "); $pdo->exec(" CREATE TABLE IF NOT EXISTS fan_spike_logs ( id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, spike_key VARCHAR(32) NULL, summary VARCHAR(255) NULL, rpm_delta DECIMAL(10,2) NULL, pwm_delta DECIMAL(10,2) NULL, temp_delta DECIMAL(10,2) NULL, current_rpm INT NULL, current_pwm INT NULL, current_temp DECIMAL(6,2) NULL, cpu_process LONGTEXT NULL, memory_process LONGTEXT NULL, UNIQUE KEY uniq_spike_key (spike_key), INDEX idx_created_at (created_at) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci "); $pdo->exec(" CREATE TABLE IF NOT EXISTS wifi_observed_sessions ( mac VARCHAR(17) NOT NULL PRIMARY KEY, band VARCHAR(16) NOT NULL, iface VARCHAR(32) NOT NULL, first_seen_at DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3), last_seen_at DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3), last_ip VARCHAR(64) NULL, hostname VARCHAR(255) NULL, INDEX idx_last_seen_at (last_seen_at), INDEX idx_band (band) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci "); $pdo->exec(" CREATE TABLE IF NOT EXISTS remember_tokens ( id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, selector CHAR(24) NOT NULL, validator_hash CHAR(64) NOT NULL, created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, expires_at DATETIME NOT NULL, last_used_at DATETIME NULL, last_ip VARCHAR(64) NULL, user_agent VARCHAR(255) NULL, UNIQUE KEY uniq_selector (selector), INDEX idx_expires_at (expires_at) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci "); $pdo->exec(" CREATE TABLE IF NOT EXISTS ha_notify_logs ( id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, event VARCHAR(32) NOT NULL, target VARCHAR(16) NULL, title VARCHAR(255) NULL, tag VARCHAR(128) NULL, actor_ip VARCHAR(64) NULL, http_code INT NULL, error VARCHAR(255) NULL, meta JSON NULL, INDEX idx_created_at (created_at), INDEX idx_event (event), INDEX idx_tag (tag) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci "); $pdo->exec(" CREATE TABLE IF NOT EXISTS system_notice_state ( id TINYINT UNSIGNED NOT NULL PRIMARY KEY, state VARCHAR(16) NOT NULL DEFAULT 'normal', baseline_temp DECIMAL(8,2) NULL, baseline_rpm DECIMAL(12,2) NULL, baseline_pwm DECIMAL(8,2) NULL, active_reason VARCHAR(255) NULL, active_temp_delta DECIMAL(8,2) NULL, active_rpm_delta DECIMAL(12,2) NULL, process_signature VARCHAR(255) NULL, alert_started_at DATETIME NULL, last_alert_at DATETIME NULL, updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci "); $pdo->exec(" INSERT IGNORE INTO control_state (id, mode, manual_pwm) VALUES (1, 'auto', 120) "); foreach ([ "ALTER TABLE sensor_logs ADD COLUMN create_ip VARCHAR(64) NULL", "ALTER TABLE sensor_logs ADD COLUMN disk_total_kb BIGINT NULL AFTER mem_free_mb", "ALTER TABLE sensor_logs ADD COLUMN disk_used_kb BIGINT NULL AFTER disk_total_kb", "ALTER TABLE sensor_logs ADD COLUMN disk_free_kb BIGINT NULL AFTER disk_used_kb", "ALTER TABLE sensor_logs ADD COLUMN fan_efficiency DECIMAL(10,2) NULL AFTER fan_rpm", "ALTER TABLE sensor_logs ADD COLUMN rp1_temp_c DECIMAL(6,2) NULL AFTER fan_efficiency", "ALTER TABLE sensor_logs ADD COLUMN cpu_voltage DECIMAL(6,3) NULL AFTER rp1_temp_c", "ALTER TABLE sensor_logs ADD COLUMN cpu_watts DECIMAL(8,3) NULL AFTER cpu_voltage", "ALTER TABLE sensor_logs ADD COLUMN battery_voltage DECIMAL(6,3) NULL AFTER cpu_watts", "ALTER TABLE sensor_logs ADD COLUMN battery_percent DECIMAL(6,2) NULL AFTER battery_voltage", "ALTER TABLE sensor_logs DROP COLUMN battery_current_amps", "ALTER TABLE sensor_logs DROP COLUMN battery_watts", "ALTER TABLE sensor_logs DROP COLUMN created_ip", "ALTER TABLE fan_spike_logs ADD COLUMN spike_key VARCHAR(32) NULL AFTER created_at", "ALTER TABLE fan_spike_logs ADD UNIQUE KEY uniq_spike_key (spike_key)", "ALTER TABLE system_notice_state ADD COLUMN active_temp_delta DECIMAL(8,2) NULL AFTER active_reason", "ALTER TABLE system_notice_state ADD COLUMN active_rpm_delta DECIMAL(12,2) NULL AFTER active_temp_delta", "ALTER TABLE system_notice_state ADD COLUMN process_signature VARCHAR(255) NULL AFTER active_rpm_delta", "ALTER TABLE sensor_logs DROP COLUMN disk_total_gb", "ALTER TABLE sensor_logs DROP COLUMN disk_used_gb", "ALTER TABLE sensor_logs DROP COLUMN disk_free_gb", "ALTER TABLE sensor_logs DROP COLUMN input_voltage", "ALTER TABLE sensor_logs DROP COLUMN cpu_core_voltage", "ALTER TABLE sensor_logs DROP COLUMN cpu_core_amps", "ALTER TABLE sensor_logs DROP COLUMN system_watts", "ALTER TABLE sensor_logs DROP COLUMN cpu_freq_mhz", "ALTER TABLE sensor_logs DROP COLUMN cpu_freq_min_mhz", "ALTER TABLE sensor_logs DROP COLUMN cpu_freq_max_mhz", "ALTER TABLE sensor_logs DROP COLUMN arm_clock_mhz", "ALTER TABLE sensor_logs DROP COLUMN core_clock_mhz", "ALTER TABLE sensor_logs DROP COLUMN isp_clock_mhz", "ALTER TABLE sensor_logs DROP COLUMN v3d_clock_mhz", "ALTER TABLE sensor_logs DROP COLUMN emmc_clock_mhz", "ALTER TABLE sensor_logs DROP COLUMN uart_clock_mhz", "ALTER TABLE sensor_logs DROP COLUMN hdmi_clock_mhz", "ALTER TABLE sensor_logs DROP COLUMN sdram_c_voltage", "ALTER TABLE sensor_logs DROP COLUMN sdram_i_voltage", "ALTER TABLE sensor_logs DROP COLUMN sdram_p_voltage", "ALTER TABLE sensor_logs DROP COLUMN rp1_adc_in1_voltage", "ALTER TABLE sensor_logs DROP COLUMN rp1_adc_in2_voltage", "ALTER TABLE sensor_logs DROP COLUMN rp1_adc_in3_voltage", "ALTER TABLE sensor_logs DROP COLUMN rp1_adc_in4_voltage", "ALTER TABLE sensor_logs DROP COLUMN cooling_state", "ALTER TABLE sensor_logs DROP COLUMN cooling_max_state", "ALTER TABLE sensor_logs DROP COLUMN regulator_3v3_voltage", "ALTER TABLE sensor_logs DROP COLUMN regulator_5v_voltage", "ALTER TABLE sensor_logs DROP COLUMN regulator_vdd_3v3_voltage", "ALTER TABLE sensor_logs DROP COLUMN regulator_wl_on", "ALTER TABLE sensor_logs DROP COLUMN regulator_sd_io_voltage", "ALTER TABLE sensor_logs DROP COLUMN pcie_link_speed", "ALTER TABLE sensor_logs DROP COLUMN pcie_link_width", "ALTER TABLE sensor_logs DROP COLUMN throttled_raw", "ALTER TABLE sensor_logs DROP COLUMN under_voltage_now", "ALTER TABLE sensor_logs DROP COLUMN throttled_now", "ALTER TABLE sensor_logs DROP COLUMN freq_capped_now", "ALTER TABLE sensor_logs DROP COLUMN soft_temp_limit_now", "ALTER TABLE sensor_logs DROP COLUMN under_voltage_seen", "ALTER TABLE sensor_logs DROP COLUMN throttled_seen", "ALTER TABLE sensor_logs DROP COLUMN freq_capped_seen", "ALTER TABLE sensor_logs DROP COLUMN soft_temp_limit_seen", "ALTER TABLE sensor_logs DROP COLUMN ac_power_ok", "ALTER TABLE sensor_logs DROP COLUMN charging_enabled", "ALTER TABLE fan_spike_logs DROP COLUMN io_process", "DROP TABLE top_process_logs", "DROP TABLE wifi_station_logs", "DROP TABLE software_status_logs", "DROP TABLE helper_command_logs", "DROP TABLE service_units", "DROP TABLE failed_units", "DROP TABLE timer_units", "DROP TABLE journal_warning_logs", "DROP TABLE installed_packages", "DROP TABLE upgradable_packages", ] as $sql) { try { $pdo->exec($sql); } catch (Throwable) { } } $done = true; } bootstrap_db(); function e(mixed $value): string { return htmlspecialchars( (string)$value, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8' ); } function json_out(array $payload, int $status = 200): never { http_response_code($status); header('Content-Type: application/json; charset=utf-8'); header('Cache-Control: no-store'); echo json_encode( $payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES ); exit; } function ha_notify_targets(): array { global $controlHaNotifyConfig; $configured = is_array($controlHaNotifyConfig['targets'] ?? null) ? $controlHaNotifyConfig['targets'] : []; if ($configured !== []) { return $configured; } return [ ['name' => 'seoul', 'base' => 'https://ha.seoul.chaegeon.com'], ['name' => 'main', 'base' => 'https://ha.chaegeon.com'], ]; } function ha_notify_log(string $event, array $context = []): void { try { $stmt = db()->prepare(" INSERT INTO ha_notify_logs ( event, target, title, tag, actor_ip, http_code, error, meta ) VALUES ( :event, :target, :title, :tag, :actor_ip, :http_code, :error, :meta ) "); $stmt->execute([ ':event' => mb_substr($event, 0, 32), ':target' => isset($context['target']) ? mb_substr((string)$context['target'], 0, 16) : null, ':title' => isset($context['title']) ? mb_substr((string)$context['title'], 0, 255) : null, ':tag' => isset($context['tag']) ? mb_substr((string)$context['tag'], 0, 128) : null, ':actor_ip' => mb_substr((string)($_SERVER['REMOTE_ADDR'] ?? ''), 0, 64), ':http_code' => isset($context['http_code']) ? (int)$context['http_code'] : null, ':error' => isset($context['error']) ? mb_substr((string)$context['error'], 0, 255) : null, ':meta' => json_encode($context, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), ]); } catch (Throwable) { } } function latest_ha_notify_epoch_by_tag(string $tag): int { $stmt = db()->prepare(" SELECT UNIX_TIMESTAMP(MAX(created_at)) FROM ha_notify_logs WHERE event = 'send_success' AND tag = :tag "); $stmt->execute([':tag' => $tag]); return (int)($stmt->fetchColumn() ?: 0); } function ha_notify_due(string $tag, int $cooldownSeconds): bool { $latest = latest_ha_notify_epoch_by_tag($tag); return $latest <= 0 || time() - $latest >= $cooldownSeconds; } function ha_notify_default_data(string $level, string $tag, string $url = '/'): array { $level = in_array($level, ['critical', 'warning', 'info'], true) ? $level : 'info'; $isCritical = $level === 'critical'; $isWarning = $level === 'warning'; $absoluteUrl = str_starts_with($url, 'http://') || str_starts_with($url, 'https://') ? $url : 'https://' . APP_HOST . '/' . ltrim($url, '/'); return [ 'ttl' => 0, 'priority' => 'high', 'channel' => $isCritical ? 'control_critical' : ($isWarning ? 'control_warning' : 'control_status'), 'importance' => $isCritical ? 'max' : 'high', 'tag' => $tag, 'group' => 'control', 'sticky' => $isCritical ? 'true' : 'false', 'persistent' => $isCritical, 'renotify' => 'true', 'color' => $isCritical ? '#ff3b30' : ($isWarning ? '#ffcc00' : '#3b82f6'), 'notification_icon' => $isCritical ? 'mdi:alert-circle' : ($isWarning ? 'mdi:alert' : 'mdi:information'), 'vibrationPattern' => $isCritical ? '900,250,900,250,1400' : '250,150,250', 'ledColor' => $isCritical ? 'red' : ($isWarning ? 'yellow' : 'blue'), 'visibility' => 'public', 'timeout' => $isCritical ? 0 : 1800, 'clickAction' => $absoluteUrl, 'url' => $absoluteUrl, 'actions' => [ [ 'action' => 'URI', 'title' => 'Control', 'uri' => $absoluteUrl, ], ], ]; } function ha_notify_log_rows(int $limit = 20): array { $limit = max(1, min(100, $limit)); $stmt = db()->query(" SELECT id, created_at, event, target, title, tag, http_code, error, meta FROM ha_notify_logs ORDER BY id DESC LIMIT " . $limit . " "); $rows = []; foreach ($stmt->fetchAll() as $row) { $meta = json_decode((string)($row['meta'] ?? ''), true); $data = is_array($meta['data'] ?? null) ? $meta['data'] : []; $rows[] = [ 'id' => (int)$row['id'], 'created_at' => (string)$row['created_at'], 'event' => (string)$row['event'], 'target' => $row['target'], 'title' => $row['title'], 'tag' => $row['tag'], 'http_code' => $row['http_code'] === null ? null : (int)$row['http_code'], 'error' => $row['error'], 'level' => (string)($data['level'] ?? ''), 'channel' => (string)($data['channel'] ?? ''), 'icon' => (string)($data['notification_icon'] ?? ''), ]; } return $rows; } function send_ha_notify(array $payload): array { $title = mb_substr((string)($payload['title'] ?? APP_NAME), 0, 255); $message = mb_substr((string)($payload['message'] ?? $payload['body'] ?? ''), 0, 4000); $level = (string)($payload['level'] ?? 'info'); $tag = mb_substr((string)($payload['tag'] ?? 'control-notify'), 0, 128); $logTag = mb_substr((string)($payload['log_tag'] ?? $tag), 0, 128); $url = (string)($payload['url'] ?? '/'); $data = ha_notify_default_data($level, $tag, $url); if (is_array($payload['data'] ?? null)) { $data = array_replace_recursive($data, $payload['data']); } $data['level'] = $level; $body = json_encode([ 'title' => $title, 'message' => $message, 'data' => $data, ], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); if (HA_NOTIFY_WEBHOOK_ID === '') { ha_notify_log('send_failed', [ 'target' => null, 'title' => $title, 'tag' => $logTag, 'http_code' => null, 'error' => 'ha_notify_webhook_missing', 'data' => $data, ]); return [ 'sent' => 0, 'failed' => 0, 'target' => null, 'http_code' => null, 'error' => 'ha_notify_webhook_missing', ]; } $attempts = 0; foreach (ha_notify_targets() as $target) { $name = (string)($target['name'] ?? 'ha'); $base = rtrim((string)($target['base'] ?? $target['base_url'] ?? $target['url'] ?? ''), '/'); if ($base === '') { continue; } $attempts++; $ch = curl_init($base . '/api/webhook/' . rawurlencode(HA_NOTIFY_WEBHOOK_ID)); curl_setopt_array($ch, [ CURLOPT_POST => true, CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Content-Type: application/json'], CURLOPT_POSTFIELDS => $body, CURLOPT_CONNECTTIMEOUT => 3, CURLOPT_TIMEOUT => 8, ]); $response = curl_exec($ch); $httpCode = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE); $error = $response === false ? curl_error($ch) : null; curl_close($ch); if ($error === null && $httpCode >= 200 && $httpCode < 300) { ha_notify_log('send_success', [ 'target' => $name, 'title' => $title, 'tag' => $logTag, 'http_code' => $httpCode, 'data' => $data, ]); return [ 'sent' => 1, 'failed' => 0, 'target' => $name, 'http_code' => $httpCode, 'error' => null, ]; } ha_notify_log('send_failed', [ 'target' => $name, 'title' => $title, 'tag' => $logTag, 'http_code' => $httpCode, 'error' => $error ?: ('HTTP ' . $httpCode), ]); } return [ 'sent' => 0, 'failed' => $attempts, 'target' => null, 'http_code' => null, 'error' => 'ha_notify_failed', ]; } function clear_ha_notification(string $tag, string $title = 'Control 알림 해제'): array { return send_ha_notify([ 'title' => $title, 'message' => 'clear_notification', 'level' => 'info', 'tag' => $tag, 'log_tag' => $tag . '-clear', 'data' => [ 'tag' => $tag, 'channel' => 'control_status', 'notification_icon' => 'mdi:bell-check', 'persistent' => false, 'sticky' => 'false', 'renotify' => 'false', 'timeout' => 1, ], ]); } function battery_low_notify_profile(float $percent): array { if ($percent <= 5.0) { return [ 'label' => '긴급', 'level' => 'critical', 'channel' => 'control_critical', 'importance' => 'max', 'icon' => 'mdi:battery-alert-variant-outline', 'color' => '#b91c1c', 'sticky' => 'true', 'persistent' => true, 'vibration' => '900,200,900,200,1400,250,1800', 'led' => 'red', ]; } if ($percent <= 10.0) { return [ 'label' => '위험', 'level' => 'critical', 'channel' => 'control_battery_critical', 'importance' => 'max', 'icon' => 'mdi:battery-10', 'color' => '#dc2626', 'sticky' => 'true', 'persistent' => true, 'vibration' => '900,250,900,250,1400', 'led' => 'red', ]; } if ($percent <= 15.0) { return [ 'label' => '경고', 'level' => 'warning', 'channel' => 'control_battery_warning', 'importance' => 'high', 'icon' => 'mdi:battery-20', 'color' => '#f97316', 'sticky' => 'true', 'persistent' => true, 'vibration' => '600,200,900,200,900', 'led' => 'yellow', ]; } return [ 'label' => '주의', 'level' => 'warning', 'channel' => 'control_battery', 'importance' => 'high', 'icon' => 'mdi:battery-alert', 'color' => '#f59e0b', 'sticky' => 'false', 'persistent' => false, 'vibration' => '250,150,250', 'led' => 'yellow', ]; } function send_battery_low_notify_if_needed(array $battery): array { $percent = $battery['percent'] ?? null; if ($percent === null || $percent === '' || !is_numeric($percent)) { return [ 'sent' => 0, 'failed' => 0, 'skipped' => 'battery_soc_missing', ]; } $percent = (float)$percent; $voltage = isset($battery['voltage']) && is_numeric($battery['voltage']) ? (float)$battery['voltage'] : null; $tag = 'control-battery-low'; if ($percent > 20.0) { $latestLow = latest_ha_notify_epoch_by_tag($tag); $latestClear = latest_ha_notify_epoch_by_tag($tag . '-clear'); if ( $latestLow > 0 && $latestLow > $latestClear && ha_notify_due($tag . '-clear', HA_NOTIFY_BATTERY_CLEAR_COOLDOWN) ) { return clear_ha_notification($tag, '배터리 SOC 복구'); } return [ 'sent' => 0, 'failed' => 0, 'skipped' => 'battery_soc_ok', ]; } if (!ha_notify_due($tag, HA_NOTIFY_BATTERY_LOW_COOLDOWN)) { return [ 'sent' => 0, 'failed' => 0, 'skipped' => 'battery_low_cooldown', ]; } $profile = battery_low_notify_profile($percent); $body = 'Battery SOC ' . number_format($percent, 2) . '%' . ($voltage === null ? '' : ' / ' . number_format($voltage, 3) . 'V') . "\n" . $profile['label'] . ' 단계입니다.'; return send_ha_notify([ 'title' => '배터리 SOC ' . $profile['label'], 'message' => $body, 'level' => $profile['level'], 'url' => '/', 'tag' => $tag, 'data' => [ 'channel' => $profile['channel'], 'notification_icon' => $profile['icon'], 'color' => $profile['color'], 'sticky' => $profile['sticky'], 'persistent' => $profile['persistent'], 'renotify' => 'true', 'importance' => $profile['importance'], 'vibrationPattern' => $profile['vibration'], 'ledColor' => $profile['led'], 'battery_percent' => round($percent, 2), 'battery_voltage' => $voltage === null ? null : round($voltage, 3), ], ]); } function signed_in(): bool { if (isset($_SESSION['control_login']) && $_SESSION['control_login'] === true) { return true; } return auto_login_from_cookie(); } function require_login(): void { if (!signed_in()) { header('Location: /'); exit; } } function remember_cookie_options(int $expires): array { return [ 'expires' => $expires, 'path' => '/', 'domain' => '', 'secure' => !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off', 'httponly' => true, 'samesite' => 'Lax', ]; } function issue_remember_token(): void { $selector = bin2hex(random_bytes(12)); $validator = bin2hex(random_bytes(32)); $expires = time() + REMEMBER_DAYS * 86400; $stmt = db()->prepare(" INSERT INTO remember_tokens ( selector, validator_hash, expires_at, last_ip, user_agent ) VALUES ( :selector, :validator_hash, FROM_UNIXTIME(:expires_at), :last_ip, :user_agent ) "); $stmt->execute([ ':selector' => $selector, ':validator_hash' => hash('sha256', $validator), ':expires_at' => $expires, ':last_ip' => $_SERVER['REMOTE_ADDR'] ?? 'cli', ':user_agent' => mb_substr((string)($_SERVER['HTTP_USER_AGENT'] ?? ''), 0, 255), ]); setcookie( REMEMBER_COOKIE, $selector . ':' . $validator, remember_cookie_options($expires) ); db()->exec(" DELETE FROM remember_tokens WHERE expires_at < NOW() "); } function clear_remember_token(): void { $raw = (string)($_COOKIE[REMEMBER_COOKIE] ?? ''); $parts = explode(':', $raw, 2); if (count($parts) === 2 && preg_match('/^[a-f0-9]{24}$/', $parts[0])) { $stmt = db()->prepare(" DELETE FROM remember_tokens WHERE selector = :selector "); $stmt->execute([ ':selector' => $parts[0], ]); } setcookie( REMEMBER_COOKIE, '', remember_cookie_options(time() - 3600) ); unset($_COOKIE[REMEMBER_COOKIE]); } function auto_login_from_cookie(): bool { $raw = (string)($_COOKIE[REMEMBER_COOKIE] ?? ''); if ($raw === '') { return false; } $parts = explode(':', $raw, 2); if ( count($parts) !== 2 || !preg_match('/^[a-f0-9]{24}$/', $parts[0]) || !preg_match('/^[a-f0-9]{64}$/', $parts[1]) ) { clear_remember_token(); return false; } [$selector, $validator] = $parts; $stmt = db()->prepare(" SELECT id, validator_hash, UNIX_TIMESTAMP(expires_at) AS expires_ts FROM remember_tokens WHERE selector = :selector LIMIT 1 "); $stmt->execute([ ':selector' => $selector, ]); $row = $stmt->fetch(); if (!$row || (int)$row['expires_ts'] < time()) { clear_remember_token(); return false; } if (!hash_equals((string)$row['validator_hash'], hash('sha256', $validator))) { clear_remember_token(); return false; } $_SESSION['control_login'] = true; $stmt = db()->prepare(" UPDATE remember_tokens SET last_used_at = NOW(), last_ip = :last_ip, user_agent = :user_agent WHERE id = :id "); $stmt->execute([ ':id' => $row['id'], ':last_ip' => $_SERVER['REMOTE_ADDR'] ?? 'cli', ':user_agent' => mb_substr((string)($_SERVER['HTTP_USER_AGENT'] ?? ''), 0, 255), ]); return true; } function csrf_token(): string { if (empty($_SESSION['csrf'])) { $_SESSION['csrf'] = bin2hex(random_bytes(24)); } return (string)$_SESSION['csrf']; } function require_csrf(): void { $token = $_POST['csrf'] ?? $_SERVER['HTTP_X_CSRF_TOKEN'] ?? ''; if (!hash_equals(csrf_token(), (string)$token)) { json_out([ 'ok' => false, 'error' => 'bad_csrf', ], 403); } } function sh(array $cmd, bool $root = false, int $timeout = 8): array { $full = $cmd; if ( $root && function_exists('posix_geteuid') && posix_geteuid() !== 0 ) { $full = array_merge( ['/usr/bin/sudo', '-n'], $cmd ); } $escaped = array_map('escapeshellarg', $full); $command = '/usr/bin/timeout ' . (int)$timeout . 's ' . implode(' ', $escaped) . ' 2>&1'; $output = []; $code = 0; exec($command, $output, $code); return [ 'code' => $code, 'out' => implode("\n", $output), ]; } function first_readable(array $files): string { foreach ($files as $file) { if (!is_readable($file)) { continue; } $value = trim((string)@file_get_contents($file)); if ($value !== '') { return $value; } } return ''; } function get_control_state(): array { $stmt = db()->query(" SELECT * FROM control_state WHERE id = 1 LIMIT 1 "); $row = $stmt->fetch() ?: []; return [ 'mode' => $row['mode'] ?? 'auto', 'manual_pwm' => isset($row['manual_pwm']) ? (int)$row['manual_pwm'] : 120, 'updated_at' => $row['updated_at'] ?? null, ]; } function set_control_state(string $mode, int $manualPwm): void { if (!in_array($mode, ['auto', 'manual', 'off'], true)) { $mode = 'auto'; } $manualPwm = max(0, min(255, $manualPwm)); $stmt = db()->prepare(" INSERT INTO control_state (id, mode, manual_pwm) VALUES (1, :mode, :manual_pwm) ON DUPLICATE KEY UPDATE mode = VALUES(mode), manual_pwm = VALUES(manual_pwm), updated_at = CURRENT_TIMESTAMP "); $stmt->execute([ ':mode' => $mode, ':manual_pwm' => $manualPwm, ]); } function rp1_temp_c(): ?float { foreach (glob('/sys/class/hwmon/hwmon*') ?: [] as $dir) { if (trim(first_readable([$dir . '/name'])) !== 'rp1_adc') { continue; } $raw = first_readable([$dir . '/temp1_input']); if ($raw !== '' && is_numeric($raw)) { return round(((float)$raw) / 1000, 2); } } return null; } function cpu_power_status(): array { $out = sh(['/usr/bin/vcgencmd', 'pmic_read_adc'], false, 3)['out']; $voltage = null; $amps = null; foreach (preg_split('/\R/', trim($out)) ?: [] as $line) { if (preg_match('/VDD_CORE_V\\s+[^=]+=([-+]?[0-9]*\\.?[0-9]+)V/', $line, $m)) { $voltage = (float)$m[1]; } elseif (preg_match('/VDD_CORE_A\\s+[^=]+=([-+]?[0-9]*\\.?[0-9]+)A/', $line, $m)) { $amps = (float)$m[1]; } } return [ 'voltage' => $voltage === null ? null : round($voltage, 3), 'amps' => $amps === null ? null : round($amps, 3), 'watts' => ($voltage === null || $amps === null) ? null : round($voltage * $amps, 3), ]; } function i2cget_byte(int $bus, int $address, int $register): ?int { $bin = null; foreach (['/usr/sbin/i2cget', '/usr/bin/i2cget'] as $candidate) { if (is_executable($candidate)) { $bin = $candidate; break; } } if ($bin === null) { return null; } $result = sh([ $bin, '-y', (string)$bus, sprintf('0x%02x', $address), sprintf('0x%02x', $register), ], true, 2); if ((int)$result['code'] !== 0) { return null; } $raw = trim((string)$result['out']); if (!preg_match('/0x([0-9a-f]{1,2})/i', $raw, $m)) { return null; } return hexdec($m[1]); } function i2cget_word_bytes(int $bus, int $address, int $register): ?array { $msb = i2cget_byte($bus, $address, $register); $lsb = i2cget_byte($bus, $address, $register + 1); if ($msb === null || $lsb === null) { return null; } return [$msb, $lsb]; } function battery_status(): array { $voltage = null; $percent = null; $vcell = i2cget_word_bytes(1, 0x36, 0x02); if ($vcell !== null) { [$msb, $lsb] = $vcell; $raw = ($msb << 4) | ($lsb >> 4); $voltage = round($raw * 0.00125, 3); } $soc = i2cget_word_bytes(1, 0x36, 0x04); if ($soc !== null) { [$msb, $lsb] = $soc; $percent = round((($msb << 8) | $lsb) / 256, 2); } return [ 'voltage' => $voltage, 'percent' => $percent, ]; } function fan_efficiency(?int $rpm, ?float $cpuTemp, ?float $cpuWatts): ?int { if ( $rpm === null || $cpuTemp === null || $cpuWatts === null || $cpuWatts <= 0 ) { return null; } if ($rpm <= 0) { return 0; } $ambientTemp = 25.0; $maxRpm = 10000.0; $fanRatio = max(0.0, min(1.0, $rpm / $maxRpm)); $deltaTemp = max(0.1, $cpuTemp - $ambientTemp); $thermalResistance = $deltaTemp / max($cpuWatts, 0.1); // 핵심: °C/W 낮을수록 좋음 if ($thermalResistance <= 6.0) { $thermalScore = 100; } elseif ($thermalResistance <= 7.0) { $thermalScore = 95; } elseif ($thermalResistance <= 8.0) { $thermalScore = 88; } elseif ($thermalResistance <= 9.0) { $thermalScore = 80; } elseif ($thermalResistance <= 10.0) { $thermalScore = 72; } elseif ($thermalResistance <= 11.0) { $thermalScore = 64; } elseif ($thermalResistance <= 12.0) { $thermalScore = 56; } elseif ($thermalResistance <= 13.0) { $thermalScore = 48; } elseif ($thermalResistance <= 14.0) { $thermalScore = 40; } elseif ($thermalResistance <= 16.0) { $thermalScore = 30; } elseif ($thermalResistance <= 18.0) { $thermalScore = 20; } else { $thermalScore = 10; } // 목표 온도: 58~65°C if ($cpuTemp < 45.0) { $tempScore = 70; } elseif ($cpuTemp < 50.0) { $tempScore = 80; } elseif ($cpuTemp < 55.0) { $tempScore = 90; } elseif ($cpuTemp < 58.0) { $tempScore = 96; } elseif ($cpuTemp < 65.0) { $tempScore = 100; } elseif ($cpuTemp < 70.0) { $tempScore = 88; } elseif ($cpuTemp < 75.0) { $tempScore = 72; } elseif ($cpuTemp < 80.0) { $tempScore = 52; } elseif ($cpuTemp < 85.0) { $tempScore = 30; } else { $tempScore = 10; } // RPM은 비용. 단, 고온에서 고RPM은 정상이라 과하게 깎지 않음. if ($fanRatio < 0.20) { $fanScore = 85; } elseif ($fanRatio < 0.40) { $fanScore = 100; } elseif ($fanRatio < 0.60) { $fanScore = 92; } elseif ($fanRatio < 0.75) { $fanScore = 82; } elseif ($fanRatio < 0.90) { $fanScore = 70; } else { $fanScore = 58; } $penalty = 0.0; $bonus = 0.0; // 고RPM인데도 온도가 높으면 비효율 if ($fanRatio >= 0.85 && $cpuTemp >= 80.0) { $penalty += 18; } elseif ($fanRatio >= 0.75 && $cpuTemp >= 75.0) { $penalty += 10; } // 저부하인데 팬이 너무 높으면 낭비 if ($cpuWatts < 2.0 && $fanRatio >= 0.70) { $penalty += 12; } elseif ($cpuWatts < 3.0 && $fanRatio >= 0.85) { $penalty += 8; } // 차가운데 팬이 높으면 과냉각 if ($cpuTemp < 55.0 && $fanRatio >= 0.70) { $penalty += 12; } // 고부하인데 온도 잘 잡으면 보너스 if ($cpuWatts >= 5.0 && $cpuTemp <= 68.0 && $fanRatio <= 0.75) { $bonus += 8; } elseif ($cpuWatts >= 4.0 && $cpuTemp <= 65.0 && $fanRatio <= 0.65) { $bonus += 5; } $score = ($thermalScore * 0.65) + ($tempScore * 0.25) + ($fanScore * 0.10) - $penalty + $bonus; return max(0, min(100, (int)round($score))); } function add_fan_action( string $type, ?string $mode, ?int $pwm, ?string $note, bool $success = true ): void { $stmt = db()->prepare(" INSERT INTO fan_actions ( action_type, pwm_mode, pwm_value, note, actor_ip, success ) VALUES ( :action_type, :pwm_mode, :pwm_value, :note, :actor_ip, :success ) "); $stmt->execute([ ':action_type' => $type, ':pwm_mode' => $mode, ':pwm_value' => $pwm, ':note' => $note, ':actor_ip' => $_SERVER['REMOTE_ADDR'] ?? 'cli', ':success' => $success ? 1 : 0, ]); } function add_sensor_log(array $r): void { $stmt = db()->prepare(" INSERT INTO sensor_logs ( cpu_temp_c, fan_rpm, fan_efficiency, rp1_temp_c, cpu_voltage, cpu_watts, battery_voltage, battery_percent, pwm_value, pwm_percent, pwm_mode, cpu_load_1, cpu_load_5, cpu_load_15, mem_total_mb, mem_used_mb, mem_free_mb, disk_total_kb, disk_used_kb, disk_free_kb, uptime_seconds, hostname, create_ip ) VALUES ( :cpu_temp_c, :fan_rpm, :fan_efficiency, :rp1_temp_c, :cpu_voltage, :cpu_watts, :battery_voltage, :battery_percent, :pwm_value, :pwm_percent, :pwm_mode, :cpu_load_1, :cpu_load_5, :cpu_load_15, :mem_total_mb, :mem_used_mb, :mem_free_mb, :disk_total_kb, :disk_used_kb, :disk_free_kb, :uptime_seconds, :hostname, :create_ip ) "); $stmt->execute([ ':cpu_temp_c' => $r['cpu_temp_c'] ?? null, ':fan_rpm' => $r['fan_rpm'] ?? null, ':fan_efficiency' => $r['fan_efficiency'] ?? null, ':rp1_temp_c' => $r['rp1_temp_c'] ?? null, ':cpu_voltage' => $r['cpu_voltage'] ?? null, ':cpu_watts' => $r['cpu_watts'] ?? null, ':battery_voltage' => $r['battery_voltage'] ?? null, ':battery_percent' => $r['battery_percent'] ?? null, ':pwm_value' => $r['pwm_value'] ?? null, ':pwm_percent' => $r['pwm_percent'] ?? null, ':pwm_mode' => $r['pwm_mode'] ?? null, ':cpu_load_1' => $r['cpu_load_1'] ?? null, ':cpu_load_5' => $r['cpu_load_5'] ?? null, ':cpu_load_15' => $r['cpu_load_15'] ?? null, ':mem_total_mb' => $r['mem_total_mb'] ?? null, ':mem_used_mb' => $r['mem_used_mb'] ?? null, ':mem_free_mb' => $r['mem_free_mb'] ?? null, ':disk_total_kb' => $r['disk_total_kb'] ?? null, ':disk_used_kb' => $r['disk_used_kb'] ?? null, ':disk_free_kb' => $r['disk_free_kb'] ?? null, ':uptime_seconds' => $r['uptime_seconds'] ?? null, ':hostname' => $r['hostname'] ?? null, ':create_ip' => $_SERVER['REMOTE_ADDR'] ?? 'cli', ]); }