Skip to content

Instantly share code, notes, and snippets.

@akadlec
Created May 5, 2020 15:29
Show Gist options
  • Save akadlec/7ddc811d1a6929ff0a9f1aea3a796df2 to your computer and use it in GitHub Desktop.
Save akadlec/7ddc811d1a6929ff0a9f1aea3a796df2 to your computer and use it in GitHub Desktop.
<?php declare(strict_types = 1);
namespace App\Commands;
use IPub\MQTTClient;
use Nette;
use React\Promise;
use Symfony\Component\Console;
use Symfony\Component\Console\Input;
use Symfony\Component\Console\Output;
use Throwable;
/**
* MQTT client command
*
* @package FastyBird:MqttNode!
* @subpackage Commands
*
* @author Adam Kadlec <adam.kadlec@fastybird.com>
*/
class MqttClientCommand extends Console\Command\Command
{
use Nette\SmartObject;
/** @var MQTTClient\Client\IClient */
private $mqttClient;
public function __construct(
MQTTClient\Client\IClient $mqttClient,
?string $name = null
) {
parent::__construct($name);
$this->mqttClient = $mqttClient;
}
/**
* {@inheritDoc}
*/
protected function configure(): void
{
parent::configure();
$this
->setName('mqtt-node:client')
->setDescription('Start MQTT client.');
}
/**
* {@inheritDoc}
*/
protected function execute(
Input\InputInterface $input,
Output\OutputInterface $output
): int {
try {
// Prepare client connection
$this->mqttClient->connect()
->otherwise(function (Throwable $ex): void {
// Log error action reason
$this->logger->error('[ERROR] FB MQTT node - MQTT client', [
'exception' => [
'message' => $ex->getMessage(),
'code' => $ex->getCode(),
],
]);
$this->mqttClient->getLoop()->stop();
});
$this->mqttClient->getLoop()->run();
} catch (Throwable $ex) {
$this->mqttClient->getLoop()->stop();
return $ex->getCode();
}
return 0;
}
}
<?php declare(strict_types = 1);
namespace App\Events;
use BinSoul\Net\Mqtt;
use IPub\MQTTClient;
use Nette;
use Psr\Log;
class MqttClientOpenHandler
{
use Nette\SmartObject;
/** @var Log\LoggerInterface */
private $logger;
public function __construct(
Log\LoggerInterface $logger
) {
$this->logger = $logger;
}
/**
* @param Mqtt\Connection $connection
* @param MQTTClient\Client\IClient $client
*
* @return void
*/
public function __invoke(Mqtt\Connection $connection, MQTTClient\Client\IClient $client): void
{
// Network connection established
$this->logger->info(sprintf('[MQTT_CLIENT] Established connection to MQTT broker: %s', $client->getUri()), [
'server' => [
'uri' => $client->getUri(),
'port' => $client->getPort(),
],
'credentials' => [
'username' => $connection->getUsername(),
'clientId' => $connection->getClientID(),
],
]);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment