<?php 

/**
 * Library used from https://github.com/php-mqtt/client
 * Multiple examples https://github.com/php-mqtt/client-examples
 */

namespace Libraries;

use \PhpMqtt\Client\MqttClient;
use \PhpMqtt\Client\ConnectionSettings;
use \PhpMqtt\Client\Exceptions\MqttClientException;

class MosquittoMqtt { 

    const KEEP_ALIVE_INTERVAL = 60;

    public $g_objMqttClient;
    public $g_objMqttLogger;
    public $g_objMqttConnectionSettings;
    public $g_boolIsCredentialsRequired;

    public function __construct() {
    
    }

    public function getMqttClient() {
        return $this->g_objMqttClient;
    }

    public function setMqttClient( $objMqttClient ) {
        $this->g_objMqttClient = $objMqttClient;
    }

    public function getConnection( $boolIsCredentialsRequired = false ) {

        $objMqttClient = new \PhpMqtt\Client\MqttClient( \getMosquittoBrokerServerIp(), ( int ) \getMosquittoBrokerTcpPort() );
        
        $this->g_boolIsCredentialsRequired = $boolIsCredentialsRequired;

        $objMqttClient->connect( $this->g_objMqttConnectionSettings );

        $this->setMqttClient( $objMqttClient );
        
        return $objMqttClient;

    }

    public function getConnectionSettings() {
        
        $this->g_objMqttConnectionSettings = new ConnectionSettings();
        
        $this->g_objMqttConnectionSettings->setConnectTimeout(3);
        $this->g_objMqttConnectionSettings->setKeepAliveInterval( self::KEEP_ALIVE_INTERVAL );

        if( true == $this->g_boolIsCredentialsRequired ) {
            $this->g_objMqttConnectionSettings->setUsername( MOSQUITTO_BROKER_USERNAME );
            $this->g_objMqttConnectionSettings->setPassword( MOSQUITTO_BROKER_PASSWORD );
        }
        
    }

    public function publish( $strTopic, $strPayload ) {
     
        $this->g_objMqttClient->publish( $strTopic, $strPayload, MqttClient::QOS_AT_LEAST_ONCE );
        
    }

    public function disconnectConnection() {
        $this->g_objMqttClient->disconnect();
    }

}


