File manager - Edit - /var/www/html/portalHomolog/app/Http/Resources/Mobiangra/MobiangraResource.php
Back
<?php namespace App\Http\Resources\Mobiangra; use App\Http\Controllers\Controller; use App\Services\Mobiangra\MobiangraService; use Carbon\Carbon; use Illuminate\Support\Facades\Log; /** * Regras de negócio e orquestração do módulo MobiAngra. * * Responsável pelo mapeamento de IDs internos -> GTFS, * cálculo de serviços ativos e construção dos payloads do feed. */ class MobiangraResource extends Controller { public function __construct(private readonly MobiangraService $service) { } /** * Executa o fluxo completo: busca API -> processa -> salva .pb e JSON. * * @return array Resultado da execução com contagem de veículos. */ public function atualizarFeed(): array { $rawVehicles = $this->service->fetchVehiclePositions(); if ($rawVehicles === null) { $this->service->saveFeedStatus(0, false); return ['success' => false, 'count' => 0, 'message' => 'Falha ao consultar API']; } $feedEntities = $this->buildFeedEntities($rawVehicles); $livePayload = $this->buildLiveDataPayload($rawVehicles); $pbSaved = $this->service->saveProtobufFeed($feedEntities); $jsonSaved = $this->service->saveLiveDataJson($livePayload); $count = count($feedEntities); $success = $pbSaved && $jsonSaved; $this->service->saveFeedStatus($count, $success); return [ 'success' => $success, 'count' => $count, 'message' => $success ? "{$count} veículos processados" : 'Falha parcial ao salvar arquivos', ]; } /** * Mapeia um veículo da API para route_id e direction_id do GTFS. * * Lógica equivalente a get_gtfs_route() do generate_feed.py. * * @param array $veiculo Dados brutos de um veículo da API. * @return array [route_id, direction_id] */ public function resolveGtfsRoute(array $veiculo): array { $linha = trim((string) ($veiculo['Linha'] ?? '')); $rota = trim((string) ($veiculo['Rota'] ?? '')); $mapping = $this->service->getInternalToGtfs(); $key = "{$linha}_{$rota}"; if (isset($mapping[$key])) { return $mapping[$key]; } if (isset($mapping[$rota])) { return $mapping[$rota]; } return [$linha, 0]; } /** * Retorna os service_ids ativos para o dia atual. * * Lógica equivalente ao bloco de GTFS estático do generate_feed.py: * (Regulares + Adicionados) - Removidos. */ public function getActiveServiceIds(): array { try { $now = Carbon::now('America/Sao_Paulo'); $dayOfWeek = strtolower($now->englishDayOfWeek); $todayInt = (int) $now->format('Ymd'); $calendar = $this->service->readGtfsCsv('calendar.txt'); $calendarDates = $this->service->readGtfsCsv('calendar_dates.txt'); $regular = collect($calendar) ->filter(function ($row) use ($dayOfWeek, $todayInt) { return ($row[$dayOfWeek] ?? '0') == '1' && (int) ($row['start_date'] ?? 0) <= $todayInt && (int) ($row['end_date'] ?? 0) >= $todayInt; }) ->pluck('service_id') ->toArray(); $exceptions = collect($calendarDates) ->filter(fn ($row) => (int) ($row['date'] ?? 0) === $todayInt); $added = $exceptions ->filter(fn ($row) => ($row['exception_type'] ?? '') == '1') ->pluck('service_id') ->toArray(); $removed = $exceptions ->filter(fn ($row) => ($row['exception_type'] ?? '') == '2') ->pluck('service_id') ->toArray(); return array_values(array_diff( array_unique(array_merge($regular, $added)), $removed )); } catch (\Throwable $e) { Log::warning('Mobiangra: Falha ao calcular service_ids ativos - ' . $e->getMessage()); return []; } } /** * Transforma veículos da API em entidades prontas para o encoder Protobuf. * * @param array $rawVehicles Dados brutos da API Systemsatx. * @return array Veículos processados para o GtfsRealtimeEncoder. */ public function buildFeedEntities(array $rawVehicles): array { $entities = []; foreach ($rawVehicles as $v) { [$routeId, $directionId] = $this->resolveGtfsRoute($v); if (empty($routeId) || empty($v['Latitude'])) { continue; } $speed = 0.0; if (! empty($v['Velocidade'])) { $speed = (float) $v['Velocidade'] / 3.6; } $entities[] = [ 'entity_id' => (string) $v['Veiculo'], 'latitude' => (float) $v['Latitude'], 'longitude' => (float) $v['Longitude'], 'speed' => $speed, 'timestamp' => $this->convertToUnix($v['DataHora'] ?? ''), 'vehicle_id' => (string) $v['Veiculo'], 'route_id' => (string) $routeId, 'direction_id' => (int) $directionId, ]; } return $entities; } /** * Transforma veículos da API no payload JSON consumido pelo mapa. * * Equivalente a get_live_vehicle_data() do map_server.py. * * @param array $rawVehicles Dados brutos da API Systemsatx. * @return array Estrutura { timestamp, vehicles: [...] }. */ public function buildLiveDataPayload(array $rawVehicles): array { $routeNames = $this->service->getRouteNames(); $acVehicles = $this->service->getAcVehicles(); $headsigns = $this->service->getDirectionHeadsigns(); $vehicles = []; foreach ($rawVehicles as $v) { [$routeId, $directionId] = $this->resolveGtfsRoute($v); if (empty($routeId) || empty($v['Latitude'])) { continue; } $speedKmh = 0.0; if (! empty($v['Velocidade'])) { $speedKmh = (float) $v['Velocidade']; } $vehicleId = (string) $v['Veiculo']; $vidNormalized = ltrim($vehicleId, '0') ?: '0'; $vidPadded = str_pad($vidNormalized, 3, '0', STR_PAD_LEFT); $hasAc = in_array($vehicleId, $acVehicles, true) || in_array($vidNormalized, $acVehicles, true) || in_array($vidPadded, $acVehicles, true); $dirStr = (string) $directionId; $sentido = $headsigns[$routeId][$dirStr] ?? ($directionId === 0 ? 'Ida' : 'Volta'); $vehicles[] = [ 'id' => $vehicleId, 'linha' => (string) $routeId, 'linha_nome' => $routeNames[$routeId] ?? (string) $routeId, 'lat' => (float) $v['Latitude'], 'lon' => (float) $v['Longitude'], 'direction' => $directionId === 0 ? 'Ida' : 'Volta', 'sentido' => $sentido, 'horario_programado' => trim((string) ($v['HorarioProgramado'] ?? $v['Horario'] ?? '')), 'ar_condicionado' => $hasAc, 'speed_kmh' => round($speedKmh, 1), 'timestamp' => $this->convertToUnix($v['DataHora'] ?? ''), ]; } return [ 'timestamp' => time(), 'vehicles' => $vehicles, ]; } /** * Converte a string de data/hora da API para Unix Timestamp. * * Formato de entrada: 'MM-DD-YYYY HH:MM:SS'. */ private function convertToUnix(string $dateTimeStr): int { if (empty($dateTimeStr)) { return time(); } try { $dt = Carbon::createFromFormat('m-d-Y H:i:s', $dateTimeStr, 'America/Sao_Paulo'); return $dt ? $dt->timestamp : time(); } catch (\Throwable) { return time(); } } }
| ver. 1.4 |
Github
|
.
| PHP 8.3.28 | Generation time: 0.02 |
proxy
|
phpinfo
|
Settings