Home  >  Article  >  PHP Framework  >  How does Laravel cooperate with Workerman command line to monitor MQTT

How does Laravel cooperate with Workerman command line to monitor MQTT

青灯夜游
青灯夜游forward
2022-12-13 20:28:021792browse

Laravel WorkermanHow to monitor MQTT? The following article will introduce to you how Laravel cooperates with the Workerman command line to monitor MQTT. I hope it will be helpful to you.

How does Laravel cooperate with Workerman command line to monitor MQTT

The company is engaged in the Internet of Things. The server often communicates with the Internet of Things devices through PHP through the MQTT protocol. It happens that the PHP framework uses Laravel. I discovered it when I first came into contact with it. There is no comparable information. I have been exploring for a while and have already used it in several projects. I will post the relevant steps here for your own reference in the future and for the reference of friends with similar needs.

Written at the beginning

As we all know, PHP is a language designed specifically for the Web. Most of the time, it communicates with the Web Server and the back end. It is also used as a "front-end" in conjunction with other back-end languages. Its underlying design also limits its ability to do things on the Web that are more suitable for it. Therefore, if you want to use the server to monitor MQTT, you need other libraries to cooperate, as mentioned here. There are two main libraries, namely workerman and swoole. Currently (2019.08) in terms of the actual experience of using the server to monitor MQTT, they are as follows:

workerman:

  • Easy to install. It can be installed with one line of composer command [Related recommendation: "workerman Tutorial"]
  • MQTT library is used by many people, and the update date is more recent
  • Supports MQTT TLS/SSL Encryption
  • Document details

##swoole:

    The installation is more complicated than Workerman. Each operating environment must be installed separately and may need to be compiled. environment.
  • There are fewer people using MQTT and it has been updated for a long time.
  • There are few documents and there is less information that can be found.
  • Does not support TLS/SSL encryption. If encryption is required The environment may not be very friendly
To sum up, I finally chose workererman. This article uses workererman as the MQTT library for configuration and use.

Install Laravel, you can omit it if it is already installed

Composer should be essential for modern PHP development. Basically, larger frameworks will recommend using composer, so here Use composer to install Laravel, the command is as follows:

composer create-project --prefer-dist laravel/laravel workerman-mqtt '5.5.*'

Laravel specified version It is 5.5.x, which is the only LTS version currently (2019.08). Considering the stability and security of enterprise projects, LTS is still chosen. The project name is

workerman-mqtt, which is specially used to test MQTT.

If composer is too slow, you can consider using domestic composer sources such as Alibaba Cloud to speed up the installation.

Installing worker-mqtt

As mentioned above, it is very simple to install worker-mqtt with composer. It only requires one line of command:

➜  cd workerman-mqtt
➜  composer require workerman/mqtt
Using version ^1.0 for workerman/mqtt
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
Package operations: 2 installs, 0 updates, 0 removals
  - Installing workerman/workerman (v3.5.20): Loading from cache
  - Installing workerman/mqtt (v1.0): Loading from cache
workerman/workerman suggests installing ext-event (For better performance. )
Package phpunit/phpunit-mock-objects is abandoned, you should avoid using it. No replacement was suggested.
Writing lock file
Generating optimized autoload files
Carbon 1 is deprecated, see how to migrate to Carbon 2.
https://carbon.nesbot.com/docs/#api-carbon-2
    You can run './vendor/bin/upgrade-carbon' to get help in updating carbon and other frameworks and libraries that depend on it.
> Illuminate\Foundation\ComposerScripts::postAutoloadDump
> @php artisan package:discover
Discovered Package: fideloper/proxy
Discovered Package: laravel/tinker
Discovered Package: nesbot/carbon
Package manifest generated successfully.

Create a new artisan command

Since you are using Laravel with workerman to monitor MQTT, artisan is naturally the best choice. You can use Laravel components, and you can also use the artisan command to manage the listening process. Create the relevant command file:

➜  php artisan make:command mqtt
Console command created successfully.
Then edit the generated

workerman-mqtt/app/Console/Commands/mqtt.php file and change the file to the following content:

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Workerman\Worker;

class mqtt extends Command
{
    protected $signature = &#39;mqtt {action}&#39;;

    protected $description = &#39;PHP Server MQTT Client&#39;;

    protected $client_id = &#39;php-server&#39;;

    public function __construct()
    {
        parent::__construct();
    }

    public function handle()
    {
        global $argv;
        $arg = $this->argument('action');
        $argv [1] = $arg;

        $worker = new Worker();
        $worker->count = 1;
        $worker->onWorkerStart = function () {
            $mqtt = new \Workerman\Mqtt\Client("mqtt://" . env('MQTT_HOST') . ":" . env('MQTT_PORT'), array(
//                'ssl' => array(
//                    'local_cert' => base_path() . '/path/mqtt/client.crt',
//                    'local_pk' => base_path() . '/path/mqtt/client.key',
//                    'cafile' => base_path() . '/path/mqtt/ca.crt',
//                    'verify_peer' => false,
//                    'allow_self_signed' => true,
//                ),
//                $mqtt->transport = 'ssl';
                'username' => env('MQTT_USER'),
                'password' => env('MQTT_PASSWORD'),
                'debug' => env('MQTT_DEBUG'),
                'client_id' => $this->client_id . mt_rand(0, 999),
                'will' => [
                    'topic' => 'status/' . $this->client_id,
                    'content' => 0,
                    'qos' => 2,
                    'retain' => true,
                ]
            ));
            $mqtt->onConnect = function ($mqtt) {
                $mqtt->subscribe('/iot/#');
            };
            $mqtt->onMessage = function ($topic, $data, $mqtt) {
                                var_dump($topic);
                                var_dump($data);
                                //TODO 业务代码

                                //publish消息到topic
                                $mqtt->publish('test', 'hello workerman mqtt');
            };
            $mqtt->connect();
        };
        Worker::runAll();
    }
}
Then go to the

.env file under the project root directory and add the following items:

MQTT_HOST=mqtt-broker.test
MQTT_PORT=1883
MQTT_USER=username
MQTT_PASSWORD=password
MQTT_DEBUG=true
Among them,

subscribe in onConnect is followed by the topic that needs to be monitored. When it comes to new messages, topic in onMessage is the topic of the message, and data is the specific message information. With these two, we can write our business logic in onMessage, and of course we can also introduce it. Some components of the Laravel framework itself, such as databases, logs, etc., can also be used with other services such as Redis, message queue MQ, etc. to cache or use message queues.

Execute mqtt command

It is similar to other artisan commands, just run it directly from the command line:

➜  php artisan mqtt start
Workerman[artisan] start in DEBUG mode
------------------------------------- WORKERMAN --------------------------------------
Workerman version:3.5.20          PHP version:7.1.30
-------------------------------------- WORKERS ---------------------------------------
proto   user            worker          listen          processes    status
tcp     zoco            none            none            1             [OK]
--------------------------------------------------------------------------------------
Press Ctrl+C to stop. Start success.
-> Try to connect to mqtt://mqtt-broker.test:1883
-- Tcp connection established
-> Send CONNECT package client_id:php-server-superuser-subscribe95 username:username password:password clean_session:1 protocol_name:MQTT protocol_level:4
<- Recv CONNACK package, MQTT connect success
-> Send SUBSCRIBE package, topic:/iot/# message_id:1
<- Recv SUBACK package, message_id:1
Be careful not to forget the following

start, this is the startup parameter required by workererman itself.

Because the workerman setting is resident in memory, it is continuously monitoring under normal circumstances. Even if the program has a bug and is terminated, the workerman will automatically create a new process for processing.

If the production environment needs to monitor and process MQTT data for a long time, it is recommended to use commands such as systemctl for management.

Disadvantages

Although it is possible to monitor MQTT messages on the server as a client so far, there is a shortcoming here. I haven't found a way to call this library alone to publish messages to the specified topic when processing actual business logic.

Another point is that when using this library, you cannot run two artisan commands that use this library at the same time. There will be the following prompt:

➜  php artisan mqtt start
Workerman[artisan] start in DEBUG mode
Workerman[artisan] already running
I have searched the entire network and found this problem. There are solutions. Although the timing function can be added through the Timer class and solved by alternative methods, this is not the optimal solution when efficiency is required. If there are other solutions, it is recommended not to choose PHP as the server to handle MQTT-related businesses.

For more programming-related knowledge, please visit: Programming Teaching! !

The above is the detailed content of How does Laravel cooperate with Workerman command line to monitor MQTT. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete