<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use PhpMqtt\Client\MqttClient;
use Illuminate\Support\Facades\Cache;

class SubscribeToMQTT extends Command
{
    protected $signature = 'mqtt:subscribe';
    protected $description = 'Subscribe to MQTT topic';

    public function handle()
    {
        $server   = '192.168.0.111';  // Ganti dengan server MQTT Anda
        $port     = 1883;
        $clientId = 'laravel-mqtt-client';
        $mqtt     = new MqttClient($server, $port, $clientId);

        $mqtt->connect();

        $mqtt->subscribe('ultrasonic', function (string $topic, string $message) {
            Cache::put('ultrasonic_data', $message, 60);
        }, 0);

        $mqtt->loop(true);
        $mqtt->disconnect();
    }
}
