false, 'available' => false, 'message' => 'MQTT 모니터 설정이 없습니다.', ]; } try { $snapshot = self::cachedSnapshot($config); return self::summarize($snapshot, $config); } catch (Throwable $e) { return [ 'configured' => true, 'available' => false, 'message' => '차량 텔레메트리를 불러오지 못했습니다.', ]; } } public static function summarize(array $snapshot, array $config = []): array { $state = is_array($snapshot['state'] ?? null) ? $snapshot['state'] : []; $sampleEpoch = self::integer($state['_sample_epoch'] ?? ($snapshot['received_at'] ?? 0)); $age = $sampleEpoch > 0 ? max(0, time() - $sampleEpoch) : null; $staleAfter = max(10, (int)($config['stale_after'] ?? 20)); $online = (string)($snapshot['availability'] ?? '') === 'online'; $serviceTotal = 0; $serviceAvailable = 0; $serviceGroups = [ ['speed', 'gear_code', 'parked'], ['hev_ready', 'hev_battery_soc', 'total_distance_to_empty'], ['driver_door', 'driver_unlocked', 'trunk'], ['climate_on', 'driver_temperature', 'outside_temperature'], ]; foreach ($serviceGroups as $keys) { $serviceTotal++; foreach ($keys as $key) { if (array_key_exists($key, $state)) { $serviceAvailable++; break; } } } $keyMap = [ 'ignition' => ['ignition'], 'hev_ready' => ['hev_ready'], 'engine_running' => ['engine_running'], 'parking' => ['parked', 'gear_p_code'], 'gear' => ['gear_code', 'gear_p_code'], 'speed' => ['speed'], 'parking_brake' => ['parking_brake'], 'drive_mode' => ['drive_mode_code'], 'fuel_warning' => ['fuel_warning'], 'discharge_alert' => ['discharge_alert'], 'distance_to_empty' => ['total_distance_to_empty'], 'electric_distance_to_empty' => ['electric_distance_to_empty'], 'gas_distance_to_empty' => ['gas_distance_to_empty'], 'hev_battery_soc' => ['hev_battery_soc'], 'battery_soc_12v' => ['battery_soc_12v'], 'ldc_12v_charge' => ['ldc_12v_charge'], 'odometer' => ['odometer'], 'driver_unlock' => ['driver_unlocked'], 'passenger_unlock' => ['passenger_unlocked'], 'rear_left_unlock' => ['rear_left_unlocked'], 'rear_right_unlock' => ['rear_right_unlocked'], 'driver_door' => ['driver_door'], 'passenger_door' => ['passenger_door'], 'rear_left_door' => ['rear_left_door'], 'rear_right_door' => ['rear_right_door'], 'trunk' => ['trunk'], 'hood' => ['hood'], 'hazard' => ['hazard'], 'head_lamp' => ['head_lamp'], 'tail_lamp' => ['tail_lamp'], 'fog_lamp' => ['fog_lamp'], 'climate_on' => ['climate_on'], 'air_conditioner' => ['air_conditioner'], 'climate_auto' => ['climate_auto'], 'climate_dual' => ['climate_dual'], 'driver_temperature' => ['driver_temperature'], 'passenger_temperature' => ['passenger_temperature'], 'rear_temperature' => ['rear_temperature'], 'outside_temperature' => ['outside_temperature'], 'blower_level' => ['blower_level'], ]; $metrics = []; foreach ($keyMap as $name => $keys) { $value = null; foreach ($keys as $key) { if (array_key_exists($key, $state)) { $value = (string)$state[$key]; break; } } $metrics[$name] = [ 'value' => $value, 'supported' => $value !== null && !self::unsupported($value), ]; } $metricCount = count(array_filter($metrics, static fn(array $metric): bool => $metric['supported'])); return [ 'configured' => true, 'available' => $state !== [], 'online' => $online, 'stale' => !$online || $age === null || $age > $staleAfter, 'age_seconds' => $age, 'sample_epoch' => $sampleEpoch, 'metric_count' => $metricCount, 'services' => [ 'available' => $serviceAvailable, 'total' => $serviceTotal, ], 'cache' => [ 'received_at' => (int)($snapshot['received_at'] ?? 0), 'fallback' => !empty($snapshot['cache_fallback']), ], 'metrics' => $metrics, ]; } private static function config(): ?array { $path = getenv('NIRO_CAR_MQTT_CONFIG') ?: self::DEFAULT_CONFIG; if (!is_file($path) || is_link($path)) { return null; } $config = require $path; if (!is_array($config)) { return null; } foreach (['host', 'username', 'password'] as $required) { if (!isset($config[$required]) || trim((string)$config[$required]) === '') { return null; } } return $config; } private static function cachedSnapshot(array $config): array { $cachePath = (string)($config['cache_path'] ?? sys_get_temp_dir() . '/niro-car-mqtt-state.json'); $cacheTtl = max(1, min(15, (int)($config['cache_ttl'] ?? 4))); $cached = self::readCache($cachePath); if ($cached !== null && (time() - (int)($cached['received_at'] ?? 0)) <= $cacheTtl) { return $cached; } $lock = fopen($cachePath . '.lock', 'c'); if ($lock === false) { throw new RuntimeException('cache_lock_open_failed'); } try { if (!flock($lock, LOCK_EX)) { throw new RuntimeException('cache_lock_failed'); } $cached = self::readCache($cachePath); if ($cached !== null && (time() - (int)($cached['received_at'] ?? 0)) <= $cacheTtl) { return $cached; } try { $fresh = self::fetch($config); self::writeCache($cachePath, $fresh); return $fresh; } catch (Throwable $e) { if ($cached !== null) { $cached['cache_fallback'] = true; return $cached; } throw $e; } } finally { flock($lock, LOCK_UN); fclose($lock); } } private static function fetch(array $config): array { $host = trim((string)$config['host']); $port = max(1, min(65535, (int)($config['port'] ?? 1883))); $timeout = max(0.5, min(5.0, (float)($config['timeout'] ?? 2.0))); $stateTopic = (string)($config['state_topic'] ?? 'niro/gen5w/state'); $statePrefix = rtrim($stateTopic, '/') . '/'; $stateFilter = $statePrefix . '#'; $availabilityTopic = (string)($config['availability_topic'] ?? 'niro/gen5w/status'); $connection = self::openConnection($config, $host, $port, $timeout); $reader = $connection['reader']; $writer = $connection['writer']; try { $clientId = 'car-dashboard-' . getmypid() . '-' . bin2hex(random_bytes(4)); $variable = self::mqttString('MQTT') . chr(4) . chr(0xC2) . pack('n', 10); $payload = self::mqttString($clientId) . self::mqttString((string)$config['username']) . self::mqttString((string)$config['password']); self::writePacket($writer, 0x10, $variable . $payload); $connAck = self::readPacket($reader); if (($connAck['type'] ?? 0) !== 2 || strlen((string)$connAck['payload']) !== 2 || ord($connAck['payload'][1]) !== 0) { throw new RuntimeException('mqtt_connack_failed_' . (int)($connAck['type'] ?? 0) . '_' . bin2hex((string)($connAck['payload'] ?? ''))); } $subscribe = pack('n', 1) . self::mqttString($stateTopic) . chr(0) . self::mqttString($stateFilter) . chr(0) . self::mqttString($availabilityTopic) . chr(0); self::writePacket($writer, 0x82, $subscribe); $state = []; $availability = null; foreach (self::collectPackets($reader, $timeout) as $packet) { if (($packet['type'] ?? 0) !== 3) { continue; } [$topic, $body] = self::publishBody((string)$packet['payload'], (int)($packet['flags'] ?? 0)); if ($topic === $stateTopic) { $decoded = json_decode($body, true, 512, JSON_THROW_ON_ERROR); if (!is_array($decoded)) { throw new RuntimeException('mqtt_state_not_object'); } $state = $decoded; } elseif (str_starts_with($topic, $statePrefix)) { $entity = substr($topic, strlen($statePrefix)); if (preg_match('/^[a-z0-9_]+$/', $entity) !== 1) { continue; } if ($body === '') { unset($state[$entity]); } else { $state[$entity] = trim($body); } } elseif ($topic === $availabilityTopic) { $availability = trim($body); } } if ($state === []) { throw new RuntimeException('mqtt_state_missing'); } $state['_sample_epoch'] = time(); return [ 'received_at' => time(), 'availability' => $availability ?? 'unknown', 'state' => $state, ]; } finally { self::closeConnection($connection); } } private static function openConnection(array $config, string $host, int $port, float $timeout): array { $transport = (string)($config['transport'] ?? 'tcp'); if ($transport === 'tailscale_nc') { if (preg_match('/^[A-Za-z0-9._-]+$/', $host) !== 1) { throw new RuntimeException('tailscale_host_invalid'); } $binary = (string)($config['tailscale_binary'] ?? '/var/packages/Tailscale/target/bin/tailscale'); if (!is_file($binary) || !is_executable($binary)) { throw new RuntimeException('tailscale_binary_unavailable'); } $descriptors = [ 0 => ['pipe', 'r'], 1 => ['pipe', 'w'], 2 => ['file', '/dev/null', 'a'], ]; $pipes = []; $process = proc_open([$binary, 'nc', $host, (string)$port], $descriptors, $pipes, null, null, [ 'bypass_shell' => true, ]); if (!is_resource($process) || count($pipes) < 2) { throw new RuntimeException('tailscale_nc_failed'); } stream_set_timeout($pipes[0], (int)ceil($timeout)); stream_set_timeout($pipes[1], (int)ceil($timeout)); return [ 'reader' => $pipes[1], 'writer' => $pipes[0], 'process' => $process, 'pipes' => $pipes, ]; } if ($transport !== 'tcp') { throw new RuntimeException('mqtt_transport_invalid'); } $errno = 0; $errstr = ''; $socket = @stream_socket_client("tcp://{$host}:{$port}", $errno, $errstr, $timeout); if (!is_resource($socket)) { throw new RuntimeException('mqtt_connect_failed'); } stream_set_timeout($socket, (int)ceil($timeout)); return [ 'reader' => $socket, 'writer' => $socket, 'process' => null, 'pipes' => [$socket], ]; } private static function closeConnection(array $connection): void { $closed = []; foreach ((array)($connection['pipes'] ?? []) as $pipe) { if (!is_resource($pipe)) { continue; } $id = (int)$pipe; if (isset($closed[$id])) { continue; } fclose($pipe); $closed[$id] = true; } if (is_resource($connection['process'] ?? null)) { proc_terminate($connection['process']); proc_close($connection['process']); } } private static function publishBody(string $payload, int $flags): array { if (strlen($payload) < 2) { throw new RuntimeException('mqtt_publish_short'); } $topicLength = unpack('n', substr($payload, 0, 2))[1]; if ($topicLength < 1 || strlen($payload) < 2 + $topicLength) { throw new RuntimeException('mqtt_publish_topic_invalid'); } $offset = 2 + $topicLength; $qos = ($flags >> 1) & 0x03; if ($qos > 0) { $offset += 2; } if (strlen($payload) < $offset) { throw new RuntimeException('mqtt_publish_payload_invalid'); } return [substr($payload, 2, $topicLength), substr($payload, $offset)]; } private static function writePacket($socket, int $header, string $payload): void { $packet = chr($header) . self::remainingLength(strlen($payload)) . $payload; $written = 0; $length = strlen($packet); while ($written < $length) { $count = fwrite($socket, substr($packet, $written)); if ($count === false || $count === 0) { throw new RuntimeException('mqtt_write_failed'); } $written += $count; } } private static function readPacket($socket): array { $first = self::readExact($socket, 1); $remaining = 0; $multiplier = 1; do { $digit = ord(self::readExact($socket, 1)); $remaining += ($digit & 127) * $multiplier; $multiplier *= 128; if ($multiplier > 128 * 128 * 128 * 128) { throw new RuntimeException('mqtt_remaining_length_invalid'); } } while (($digit & 128) !== 0); if ($remaining > self::MAX_PACKET_BYTES) { throw new RuntimeException('mqtt_packet_too_large'); } $header = ord($first); return [ 'type' => $header >> 4, 'flags' => $header & 0x0f, 'payload' => self::readExact($socket, $remaining), ]; } /** @return list */ private static function collectPackets($socket, float $timeout): array { stream_set_blocking($socket, false); $packets = []; $buffer = ''; $deadline = microtime(true) + $timeout; $lastDataAt = null; while (microtime(true) < $deadline) { if ($lastDataAt !== null && microtime(true) - $lastDataAt >= 0.5) { break; } $remaining = max(0.0, min(0.1, $deadline - microtime(true))); $seconds = (int)$remaining; $microseconds = (int)(($remaining - $seconds) * 1000000); $read = [$socket]; $write = null; $except = null; $selected = @stream_select($read, $write, $except, $seconds, $microseconds); if ($selected === false) { throw new RuntimeException('mqtt_select_failed'); } if ($selected > 0) { $chunk = fread($socket, 65536); if ($chunk === false) { throw new RuntimeException('mqtt_read_failed'); } if ($chunk !== '') { $buffer .= $chunk; $lastDataAt = microtime(true); if (strlen($buffer) > self::MAX_PACKET_BYTES * 2) { throw new RuntimeException('mqtt_buffer_too_large'); } } elseif (feof($socket)) { break; } } while (strlen($buffer) >= 2) { $offset = 1; $packetLength = 0; $multiplier = 1; do { if (!isset($buffer[$offset])) { break 2; } $digit = ord($buffer[$offset]); $packetLength += ($digit & 127) * $multiplier; $multiplier *= 128; $offset++; if ($offset > 5) { throw new RuntimeException('mqtt_remaining_length_invalid'); } } while (($digit & 128) !== 0); if ($packetLength > self::MAX_PACKET_BYTES) { throw new RuntimeException('mqtt_packet_too_large'); } if (strlen($buffer) < $offset + $packetLength) { break; } $header = ord($buffer[0]); $packets[] = [ 'type' => $header >> 4, 'flags' => $header & 0x0f, 'payload' => substr($buffer, $offset, $packetLength), ]; $buffer = substr($buffer, $offset + $packetLength); } } return $packets; } private static function readExact($socket, int $length): string { $buffer = ''; while (strlen($buffer) < $length) { $chunk = fread($socket, $length - strlen($buffer)); if ($chunk === false || $chunk === '') { $meta = stream_get_meta_data($socket); throw new RuntimeException(!empty($meta['timed_out']) ? 'mqtt_read_timeout' : 'mqtt_read_failed'); } $buffer .= $chunk; } return $buffer; } private static function mqttString(string $value): string { if (strlen($value) > 65535) { throw new RuntimeException('mqtt_string_too_long'); } return pack('n', strlen($value)) . $value; } private static function remainingLength(int $length): string { $encoded = ''; do { $digit = $length % 128; $length = intdiv($length, 128); if ($length > 0) { $digit |= 128; } $encoded .= chr($digit); } while ($length > 0); return $encoded; } private static function readCache(string $path): ?array { if (!is_file($path) || filesize($path) > self::MAX_PACKET_BYTES * 2) { return null; } $decoded = json_decode((string)file_get_contents($path), true); return is_array($decoded) && is_array($decoded['state'] ?? null) ? $decoded : null; } private static function writeCache(string $path, array $snapshot): void { $json = json_encode($snapshot, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR); $temporary = $path . '.new.' . getmypid(); if (file_put_contents($temporary, $json, LOCK_EX) === false) { throw new RuntimeException('cache_write_failed'); } chmod($temporary, 0600); if (!rename($temporary, $path)) { @unlink($temporary); throw new RuntimeException('cache_replace_failed'); } } private static function unsupported(string $value): bool { return in_array(trim($value), ['-1', '255', '65535', '4294967295', '0xff', '0xffffffff'], true); } private static function integer(mixed $value): int { return is_numeric($value) ? (int)$value : 0; } }