From 0b8473203109f6dfed9961aef580e22f39aea530 Mon Sep 17 00:00:00 2001 From: Johan Vester Date: Mon, 13 Feb 2017 10:55:28 +0100 Subject: [PATCH] Implement lazy initialization of MQTT client --- app/Helpers/MQTT.php | 27 ++++++++++++++++++++++----- app/Providers/MQTTServiceProvider.php | 2 ++ 2 files changed, 24 insertions(+), 5 deletions(-) diff --git a/app/Helpers/MQTT.php b/app/Helpers/MQTT.php index 9ed45ef..483a6f7 100644 --- a/app/Helpers/MQTT.php +++ b/app/Helpers/MQTT.php @@ -13,7 +13,12 @@ class MQTT { + private $host; + private $port; + private $user; + private $password; private $conn; + private $connected = false; public function __construct( string $host, @@ -22,16 +27,28 @@ public function __construct( $user = null, $password = null ) { + $this->user = $user; + $this->password = $password; + $this->conn = new MQTTClient($host, $port, $clientId); + } - if (!$this->conn->connect(true, null, $user, $password)) { - throw MQTTException::connectionFailed($host, $port); + public function publish(string $topic, string $message) + { + if (!$this->connected) { + $this->connect(); } + + $this->conn->publish($topic, $message); + Log::debug("MQTT publish: $message"); } - public function publish(string $topic, string $message) + private function connect() { - $this->conn->publish($topic, $message); - Log::debug("MQTT publish: $message"); + if (!$this->conn->connect(true, null, $this->user, $this->password)) { + throw MQTTException::connectionFailed($this->host, $this->port); + } + + $this->connected = true; } } \ No newline at end of file diff --git a/app/Providers/MQTTServiceProvider.php b/app/Providers/MQTTServiceProvider.php index 0c5568c..723f59b 100644 --- a/app/Providers/MQTTServiceProvider.php +++ b/app/Providers/MQTTServiceProvider.php @@ -14,6 +14,8 @@ class MQTTServiceProvider extends ServiceProvider { + protected $defer = true; + /** * Bootstrap the application services. *