用Laravel配合Workerman命令行监听MQTT的方法教程来了,PHP语言的绝大部分时间都是在与Web Server通信,再后端一点,也是与别的后端语言配合做“前端”,其底层设计也限制了其本身更适合做Web那些事,所以如果想要用来服务端监听MQTT,就需要别的库来配合,这里说的库主要就两个,分别是workerman及swooleLaravel本文给大家分享workerman命令行监听MQTT的方法,下面就来看看具体如何操作。
用Laravel配合Workerman命令行监听MQTT的方法
安装workerman-mqtt
用composer安装workerman-mqtt很简单,只需要一行命令:
➜ 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.
新建artisan命令
既然是使用Laravel配合workerman监听MQTT,那artisan自然是不二的选择了,能使用Laravel的组件,还能使用artisan命令管理监听进程。创建相关命令文件:
➜ php artisan make:command mqtt
Console command created successfully.
然后编辑生成的workerman-mqtt/app/Console/Commands/mqtt.php文件,将文件改成如下内容:
<?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文件添加下面几项:
MQTT_HOST=mqtt-broker.test
MQTT_PORT=1883
MQTT_USER=username
MQTT_PASSWORD=password
MQTT_DEBUG=true
其中,onConnect里面的subscribe后面是需要监听的topic,当收到新消息的时候,onMessage里面的topic是消息的topic,data就是具体的消息信息了,有了这两个,我们可以在onMessage里面写我们的业务逻辑,当然也可以引入Laravel框架本身的一些组件,比如数据库、日志等,也可以与别的服务比如说Redis、消息队列MQ等配合进行缓存或者使用消息队列等。
执行mqtt命令
和别的artisan命令差不多,直接命令行运行就好了:
➜ 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,这是workerman本身需要的启动参数。
因为workerman设定是常驻内存,正常情况下是在持续在监听的,即使程序有bug被终止,workerman也会自动新建一个进程进行处理。
如果生产环境需要长期监听处理MQTT数据,建议使用systemctl等命令来管理。
用Laravel配合Workerman命令行监听MQTT的方法解析就到这里,翼速应用平台内有更多相关资讯,欢迎查阅!
我来说两句