Skip to content

Commit

Permalink
Implement lazy initialization of MQTT client
Browse files Browse the repository at this point in the history
  • Loading branch information
Johan Vester committed Feb 13, 2017
1 parent a6c35c4 commit 0b84732
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 5 deletions.
27 changes: 22 additions & 5 deletions app/Helpers/MQTT.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,12 @@

class MQTT
{
private $host;
private $port;
private $user;
private $password;
private $conn;
private $connected = false;

public function __construct(
string $host,
Expand All @@ -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;
}
}
2 changes: 2 additions & 0 deletions app/Providers/MQTTServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@

class MQTTServiceProvider extends ServiceProvider
{
protected $defer = true;

/**
* Bootstrap the application services.
*
Expand Down

0 comments on commit 0b84732

Please sign in to comment.