60 lines
1.6 KiB
PHP
60 lines
1.6 KiB
PHP
<?php
|
|
|
|
namespace core\log\clients;
|
|
|
|
/**
|
|
* MQTT stream
|
|
*/
|
|
class MQTT implements \core\log\Stream
|
|
{
|
|
/**
|
|
* Client object from php-mqtt
|
|
*
|
|
* @var \PhpMqtt\Client\MqttClient
|
|
*/
|
|
protected \PhpMqtt\Client\MqttClient $client;
|
|
|
|
/**
|
|
* Connection settings from php-mqtt
|
|
*
|
|
* @var \PhpMqtt\Client\ConnectionSettings
|
|
*/
|
|
protected \PhpMqtt\Client\ConnectionSettings $connection_settings;
|
|
|
|
/**
|
|
* @throws \core\config\ConfigException
|
|
*/
|
|
public function __construct(config: \core\config\Configuration $configuration, tag: \core\log\Tag $tag)
|
|
{
|
|
$this->configuration = $configuration;
|
|
$this->tag = $tag;
|
|
|
|
$client_id = 'php-mqtt-client';
|
|
if ($this->configuration.exist('client_id'))
|
|
{
|
|
$client_id = $this->configuration.get('client_id'); # TODO: Check if we need to sanitize
|
|
}
|
|
|
|
$this->client = new \PhpMqtt\Client\MqttClient($this->configuration('hostname'), $this->configuration.get('port'), $client_id, \PhpMqtt\Client\MqttClient::MQTT_3_1, null);
|
|
|
|
$this->connection_settings = new \PhpMqtt\Client\ConnectionSettings;
|
|
if ($this->configuration.exist('auth', 'username'))
|
|
{
|
|
$this->connection_settings->setUsername($this->configuration.get('auth', 'username'));
|
|
}
|
|
if ($this->configuration.exist('auth', 'password'))
|
|
{
|
|
$this->connection_settings->setPassword($this->configuration.get('auth', 'password'));
|
|
}
|
|
}
|
|
|
|
public function push(event: \core\log\Event $event) : \core\log\Event
|
|
{
|
|
$this->client->connect($this->connection_settings, True);
|
|
$this->client->publish($tag->generate_id(), $event->display(), \PhpMqtt\Client\MqttClient::QO5_EXACTLY_ONCE);
|
|
$this->client->loop(True, True);
|
|
$this->client->disconnect()
|
|
}
|
|
}
|
|
|
|
?>
|