Skip to content

Commit

Permalink
Merge pull request #11 from kayex/develop
Browse files Browse the repository at this point in the history
MQTT Authentication 🔒
  • Loading branch information
adsa95 authored Feb 13, 2017
2 parents ff07da6 + 0b84732 commit 68e78f7
Show file tree
Hide file tree
Showing 4 changed files with 38 additions and 8 deletions.
2 changes: 2 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ DB_PASSWORD=secret

MQTT_HOST=null
MQTT_PORT=1883
MQTT_USER=null
MQTT_PASS=null
MQTT_CLIENT_ID=sirius-api
MQTT_TOPIC=sirius

Expand Down
36 changes: 29 additions & 7 deletions app/Helpers/MQTT.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,20 +13,42 @@

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

public function __construct(
string $host,
string $port,
string $clientId,
$user = null,
$password = null
) {
$this->user = $user;
$this->password = $password;

public function __construct(string $host, string $port, string $clientId)
{
$this->conn = new MQTTClient($host, $port, $clientId);
}

if (!$this->conn->connect()) {
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;
}
}
6 changes: 5 additions & 1 deletion 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 All @@ -37,7 +39,9 @@ public function register()
$mqtt = new MQTT(
$config->get('mqtt.host'),
$config->get('mqtt.port'),
$config->get('mqtt.client_id')
$config->get('mqtt.client_id'),
$config->get('mqtt.user'),
$config->get('mqtt.password')
);

return new MQTTNotifier($mqtt, $config->get('mqtt.topic'));
Expand Down
2 changes: 2 additions & 0 deletions config/mqtt.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
return [
'host' => env('MQTT_HOST', null),
'port' => env('MQTT_PORT', 1883),
'user' => env('MQTT_USER', null),
'password' => env('MQTT_PASS', null),
'client_id' => env('MQTT_CLIENT_ID', 'sirius-api'),
'topic' => env('MQTT_TOPIC', 'sirius')
];

0 comments on commit 68e78f7

Please sign in to comment.