How 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.
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
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.
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 = 'mqtt {action}'; protected $description = 'PHP Server MQTT Client'; protected $client_id = 'php-server'; 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(); } }
.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
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
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
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

PHP is used to build dynamic websites, and its core functions include: 1. Generate dynamic content and generate web pages in real time by connecting with the database; 2. Process user interaction and form submissions, verify inputs and respond to operations; 3. Manage sessions and user authentication to provide a personalized experience; 4. Optimize performance and follow best practices to improve website efficiency and security.

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

The core benefits of PHP include ease of learning, strong web development support, rich libraries and frameworks, high performance and scalability, cross-platform compatibility, and cost-effectiveness. 1) Easy to learn and use, suitable for beginners; 2) Good integration with web servers and supports multiple databases; 3) Have powerful frameworks such as Laravel; 4) High performance can be achieved through optimization; 5) Support multiple operating systems; 6) Open source to reduce development costs.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

Laravel is a PHP framework for easy building of web applications. It provides a range of powerful features including: Installation: Install the Laravel CLI globally with Composer and create applications in the project directory. Routing: Define the relationship between the URL and the handler in routes/web.php. View: Create a view in resources/views to render the application's interface. Database Integration: Provides out-of-the-box integration with databases such as MySQL and uses migration to create and modify tables. Model and Controller: The model represents the database entity and the controller processes HTTP requests.

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

PHP is a server-side scripting language used for dynamic web development and server-side applications. 1.PHP is an interpreted language that does not require compilation and is suitable for rapid development. 2. PHP code is embedded in HTML, making it easy to develop web pages. 3. PHP processes server-side logic, generates HTML output, and supports user interaction and data processing. 4. PHP can interact with the database, process form submission, and execute server-side tasks.

PHP has shaped the network over the past few decades and will continue to play an important role in web development. 1) PHP originated in 1994 and has become the first choice for developers due to its ease of use and seamless integration with MySQL. 2) Its core functions include generating dynamic content and integrating with the database, allowing the website to be updated in real time and displayed in personalized manner. 3) The wide application and ecosystem of PHP have driven its long-term impact, but it also faces version updates and security challenges. 4) Performance improvements in recent years, such as the release of PHP7, enable it to compete with modern languages. 5) In the future, PHP needs to deal with new challenges such as containerization and microservices, but its flexibility and active community make it adaptable.
