search
HomePHP FrameworkWorkermanHow does Laravel cooperate with Workerman command line to monitor MQTT

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
 Send SUBSCRIBE package, topic:/iot/# message_id:1
Be careful not to forget the following <p>start<strong>, this is the startup parameter required by workererman itself. </strong></p>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. <p></p>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. <p></p><h2>Disadvantages<strong></strong>
</h2>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. <p></p>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: <p></p><pre class="brush:php;toolbar:false">➜  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. If there is any infringement, please contact admin@php.cn delete
What Are the Key Features of Workerman's Built-in WebSocket Client?What Are the Key Features of Workerman's Built-in WebSocket Client?Mar 18, 2025 pm 04:20 PM

Workerman's WebSocket client enhances real-time communication with features like asynchronous communication, high performance, scalability, and security, easily integrating with existing systems.

How to Use Workerman for Building Real-Time Collaboration Tools?How to Use Workerman for Building Real-Time Collaboration Tools?Mar 18, 2025 pm 04:15 PM

The article discusses using Workerman, a high-performance PHP server, to build real-time collaboration tools. It covers installation, server setup, real-time feature implementation, and integration with existing systems, emphasizing Workerman's key f

What Are the Best Ways to Optimize Workerman for Low-Latency Applications?What Are the Best Ways to Optimize Workerman for Low-Latency Applications?Mar 18, 2025 pm 04:14 PM

The article discusses optimizing Workerman for low-latency applications, focusing on asynchronous programming, network configuration, resource management, data transfer minimization, load balancing, and regular updates.

How to Implement Real-Time Data Synchronization with Workerman and MySQL?How to Implement Real-Time Data Synchronization with Workerman and MySQL?Mar 18, 2025 pm 04:13 PM

The article discusses implementing real-time data synchronization using Workerman and MySQL, focusing on setup, best practices, ensuring data consistency, and addressing common challenges.

What Are the Key Considerations for Using Workerman in a Serverless Architecture?What Are the Key Considerations for Using Workerman in a Serverless Architecture?Mar 18, 2025 pm 04:12 PM

The article discusses integrating Workerman into serverless architectures, focusing on scalability, statelessness, cold starts, resource management, and integration complexity. Workerman enhances performance through high concurrency, reduced cold sta

How to Build a High-Performance E-Commerce Platform with Workerman?How to Build a High-Performance E-Commerce Platform with Workerman?Mar 18, 2025 pm 04:11 PM

The article discusses building a high-performance e-commerce platform using Workerman, focusing on its features like WebSocket support and scalability to enhance real-time interactions and efficiency.

What Are the Advanced Features of Workerman's WebSocket Server?What Are the Advanced Features of Workerman's WebSocket Server?Mar 18, 2025 pm 04:08 PM

Workerman's WebSocket server enhances real-time communication with features like scalability, low latency, and security measures against common threats.

How to Use Workerman for Building Real-Time Analytics Dashboards?How to Use Workerman for Building Real-Time Analytics Dashboards?Mar 18, 2025 pm 04:07 PM

The article discusses using Workerman, a high-performance PHP server, to build real-time analytics dashboards. It covers installation, server setup, data processing, and frontend integration with frameworks like React, Vue.js, and Angular. Key featur

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.