Files
Verde-Web/app/Events/TruckLocationBroadcast.php

62 lines
1.8 KiB
PHP

<?php
namespace App\Events;
use App\Models\Trip;
use App\Models\Truck;
use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
class TruckLocationBroadcast implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public function __construct(
public readonly Truck $truck,
public readonly float $lat,
public readonly float $lng,
public readonly ?int $heading,
public readonly ?float $speedKmh,
public readonly ?Trip $trip,
public readonly \DateTimeInterface $recordedAt,
) {}
public function broadcastOn(): array
{
$channels = [new PrivateChannel('admin.live')];
// Resident-facing channel scoped to the team's service area, so only
// residents in the area receive position pings (less noise for users
// far from this truck).
$areaId = $this->truck->assignedTeam?->area_id;
if ($areaId) {
$channels[] = new Channel("area.{$areaId}.trucks");
}
return $channels;
}
public function broadcastAs(): string
{
return 'truck.location';
}
public function broadcastWith(): array
{
return [
'truck_id' => $this->truck->uuid,
'plate_number' => $this->truck->plate_number,
'lat' => $this->lat,
'lng' => $this->lng,
'heading_degrees' => $this->heading,
'speed_kmh' => $this->speedKmh,
'trip_id' => $this->trip?->uuid,
'recorded_at' => $this->recordedAt->format('c'),
];
}
}