To use MQTT in a Laravel project, you can create a command that runs in the background and listens for incoming messages. Here's an example:
- Create a new command using the
make:commandArtisan command:
php artisan make:command MqttListener
- Open the
app/Console/Commands/MqttListener.phpfile and replace thehandlemethod with the following code:
public function handle()
{
$server = 'xxx.com';
$port = 8883;
$clientId = 'xxx';
$username = 'xxx';
$password = 'xxx';
$clean_session = true;
$mqtt_version = MqttClient::MQTT_3_1;
$connectionSettings = (new ConnectionSettings)
->setConnectTimeout(10)
->setUsername($username)
->setPassword($password)
->setUseTls(true)
->setTlsSelfSignedAllowed(true)
->setKeepAliveInterval(60);
$mqtt = new MqttClient($server, $port, $clientId, $mqtt_version);
$mqtt->connect($connectionSettings, $clean_session);
printf("client connected\n");
$mqtt->subscribe('#', function ($topic, $message) {
printf("Received message on topic [%s]: %s\n", $topic, $message);
// Save the message to the database
}, 0);
$mqtt->loop(true);
}
-
Replace the MQTT connection settings with your own.
-
In the
subscribecallback function, you can save the received message to the database using Laravel's Eloquent ORM or any other database library. -
To run the command in the background, you can use a process manager like Supervisor or systemd. Here's an example configuration for Supervisor:
[program:mqtt-listener]
command=php /path/to/artisan mqtt:listen
autostart=true
autorestart=true
user=www-data
redirect_stderr=true
stdout_logfile=/path/to/logs/mqtt-listener.log
- Start the Supervisor process:
sudo supervisorctl reread
sudo supervisorctl update
sudo supervisorctl start mqtt-listener
Now the mqtt:listen command will run in the background and listen for incoming messages.