logbook/class/core/log/clients/MQTT.class.php
linarphy a8aa60ae83
Fix following first run
The code 'works' as is
2025-04-15 21:03:44 +02:00

101 lines
2.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(\core\log\Tag $tag) : void
{
$hardcoded_configuration = \core\config\class\core\log\client\MqttSettings(
array(
'client_id' => 'php-mqtt-client',
'hostname' => 'localhost',
'port' => 1883,
'auth' => \core\config\class\core\log\client\MqttAuth(
'username' => null,
'password' => null,
),
),
);
$client_id = $hardcoded_configuration->get('client_id');
$hostname = $hardcoded_configuration->get('hostname');
$port = $hardcoded_configuration->get('port');
$username = $hardcoded_configuration->get('auth', 'username');
$password = $hardcoded_configuration->get('auth', 'password');
if (\core\config\GlobalConfiguration('class', 'core', 'log', 'client', 'settings'))
{
$configuration = \core\config\GlobalConfiguration::read('class', 'core', 'log', 'client', 'settings');
if ($configuration->exists('client-id'))
{
$client_id = $configuration->get('client_id'); # NOTE: check if we need to sanitize
}
if ($configuration->exists('hostname'))
{
$hostname = $configuration->get('hostname');
}
if ($configuration->exists('port'))
{
$port = $configuration->get('port');
}
if ($configuration->exists('auth'))
{
if ($configuration->exists('auth', 'username'))
{
$username = $configuration->get('auth', 'username');
}
if ($configuration->exists('auth', 'password'))
{
$password = $configuration->get('auth',' password');
}
}
}
$this->client = new \PhpMqtt\Client\MqttClient($hostname, $port, $client_id, \PhpMqtt\Client\MqttClient::MQTT_3_1, null);
$this->connection_settings = new \PhpMqtt\Client\ConnectionSettings();
if (!\is_null($username))
{
$this->connection_settings->setUsername($username);
}
if (!\is_null($passowrd))
{
$this->connection_settings->setPassword($password);
}
}
public function push(\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();
return $event;
}
}
?>