<?php

namespace App\Services;

use Bluerhinos\phpMQTT;

class MqttService
{
    protected $mqtt;

    public function __construct()
    {
        $host = config('mqtt.host');
        $port = config('mqtt.port');
        $username = config('mqtt.username');
        $password = config('mqtt.password');
        $client_id = config('mqtt.client_id');

        $this->mqtt = new phpMQTT($host, $port, $client_id);

        if ($username && $password) {
            if (!$this->mqtt->connect(true, null, $username, $password)) {
                exit(1);
            }
        } else {
            if (!$this->mqtt->connect(true, null)) {
                exit(1);
            }
        }
    }

    public function subscribe($topic, $callback)
    {
        $this->mqtt->subscribe([$topic => ["qos" => 0, "function" => $callback]]);
        while ($this->mqtt->proc()) {}
        $this->mqtt->close();
    }
}
