Table of Contents
Written at the beginning
Home PHP Framework Workerman How does Laravel cooperate with Workerman command line to monitor MQTT

How does Laravel cooperate with Workerman command line to monitor MQTT

Dec 13, 2022 pm 08:28 PM
php laravel workerman

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.
Copy after login

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.
Copy after login
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();
    }
}
Copy after login
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
Copy after login
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
Copy after login
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
Copy after login
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 of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Laravel Eloquent ORM in Bangla partial model search) Laravel Eloquent ORM in Bangla partial model search) Apr 08, 2025 pm 02:06 PM

LaravelEloquent Model Retrieval: Easily obtaining database data EloquentORM provides a concise and easy-to-understand way to operate the database. This article will introduce various Eloquent model search techniques in detail to help you obtain data from the database efficiently. 1. Get all records. Use the all() method to get all records in the database table: useApp\Models\Post;$posts=Post::all(); This will return a collection. You can access data using foreach loop or other collection methods: foreach($postsas$post){echo$post->

The Future of PHP: Adaptations and Innovations The Future of PHP: Adaptations and Innovations Apr 11, 2025 am 12:01 AM

The future of PHP will be achieved by adapting to new technology trends and introducing innovative features: 1) Adapting to cloud computing, containerization and microservice architectures, supporting Docker and Kubernetes; 2) introducing JIT compilers and enumeration types to improve performance and data processing efficiency; 3) Continuously optimize performance and promote best practices.

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

Laravel's geospatial: Optimization of interactive maps and large amounts of data Laravel's geospatial: Optimization of interactive maps and large amounts of data Apr 08, 2025 pm 12:24 PM

Efficiently process 7 million records and create interactive maps with geospatial technology. This article explores how to efficiently process over 7 million records using Laravel and MySQL and convert them into interactive map visualizations. Initial challenge project requirements: Extract valuable insights using 7 million records in MySQL database. Many people first consider programming languages, but ignore the database itself: Can it meet the needs? Is data migration or structural adjustment required? Can MySQL withstand such a large data load? Preliminary analysis: Key filters and properties need to be identified. After analysis, it was found that only a few attributes were related to the solution. We verified the feasibility of the filter and set some restrictions to optimize the search. Map search based on city

PHP's Current Status: A Look at Web Development Trends PHP's Current Status: A Look at Web Development Trends Apr 13, 2025 am 12:20 AM

PHP remains important in modern web development, especially in content management and e-commerce platforms. 1) PHP has a rich ecosystem and strong framework support, such as Laravel and Symfony. 2) Performance optimization can be achieved through OPcache and Nginx. 3) PHP8.0 introduces JIT compiler to improve performance. 4) Cloud-native applications are deployed through Docker and Kubernetes to improve flexibility and scalability.

Laravel and the Backend: Powering Web Application Logic Laravel and the Backend: Powering Web Application Logic Apr 11, 2025 am 11:29 AM

How does Laravel play a role in backend logic? It simplifies and enhances backend development through routing systems, EloquentORM, authentication and authorization, event and listeners, and performance optimization. 1. The routing system allows the definition of URL structure and request processing logic. 2.EloquentORM simplifies database interaction. 3. The authentication and authorization system is convenient for user management. 4. The event and listener implement loosely coupled code structure. 5. Performance optimization improves application efficiency through caching and queueing.

PHP: The Foundation of Many Websites PHP: The Foundation of Many Websites Apr 13, 2025 am 12:07 AM

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

See all articles