laravel7 通过http协议控制mqtt并给mqtt协议发消息

想通过前端控制mqqt协议,但是必须通过后台去控制mqtt目前是后台是php框架用的laravel7

这里用到了 Workerman 官方文档

我这里会创建两个类 一个是发消息的 一个是接收消息的

发消息的 TestMqtt.php
收消息的 Subscribe.php

1.安装 Workerman

composer require workerman/workerman

2.安装 mqtt

composer require workerman/mqtt

3.通过 artisan 创建两个自定义的命令类

运行后就会在app\Console\Commands文件夹下生成一个自定义的类TestMqtt.php和Subscribe.php

php artisan make:command TestMqtt   //发消息的类
php artisan make:command Subscribe  //收消息的类

效果图

随后在app\Console\Kernel.php文件中$commands数组里添加一行刚刚生成的自定义类文件路径

   \App\Console\Commands\TestMqtt::class,
   \App\Console\Commands\Subscribe::class

效果图

4.首先我们编辑收消息的类 Subscribe.php

<?php

namespace App\Console\Commands;

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

class Subscribe extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'start:s';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'start subscribe';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $worker = new Worker();
        $worker->onWorkerStart = function () {
            $mqtt = new Client('mqtt://127.0.0.1:1883');
            $mqtt->onConnect = function ($mqtt) {
                $mqtt->subscribe('/result/out/hdl');
            };
            $mqtt->onMessage = function ($topic, $content) {
                $this->info('收到消息' . $content);
                $this->info("sub: $topic, $content");
            };
            $mqtt->connect();
        };
        Worker::runAll();
    }
}

5.编辑发消息的类 TestMqtt.php

<?php

namespace App\Console\Commands;

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

class TestMqtt extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'mqtt {start}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'mqtt start';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $worker = new Worker();
        $http_port = '8898';
        $worker->onWorkerStart = function ($worker) use ($http_port) {
            $ws_worker = new Worker('http://0.0.0.0:' . $http_port);
            $ws_worker->onMessage = function ($connection,  $request) {
                $id = $request->post('id') ?? 0;
                $topic = '/result/out/hdl';//监听的主题
                $port = '1883';//mqtt端口
                $mqtt_ip = '127.0.0.1';//mqttip
                //具体options参数可以到官网去查看 https://www.workerman.net/doc/workerman/components/workemran-mqtt.html
                $options = [
                    'username' => 'chunge',
                    'password' => '1234',
                    // 'debug' => true,
                ];
                $clicke = "mqtt://$mqtt_ip:$port";
                $mqtt = new Client($clicke, $options);
                $json_encode = json_encode(array('id' => $id));
                $mqtt->onConnect = function ($res) use ($json_encode, $topic, $mqtt, $connection) {
                    $this->info('http向mqqtt发送消息:' . $json_encode);
                    $res->publish($topic, $json_encode);
                    $mqtt->disconnect();
                    $message = tcpSuccess();
                    $connection->send($message);
                };
                $mqtt->connect();
                $mqtt->onError = function (\Exception $e) use ($mqtt, $connection) {
                    $this->error('请先启动mqtt服务:' . $e->getMessage());
                    $mqtt->disconnect();
                    $message = tcpError('请先启动mqtt服务:' . $e->getMessage());
                    $connection->send($message);
                };
                $mqtt->onClose = function () {
                    $this->error('断开连接');
                };
            };
            $worker->ws_worker = $ws_worker;
            $ws_worker->listen();
        };
        /**
         * http发送成功反馈
         */
        function tcpSuccess($message = 'ok')
        {
            $res = array(
                'status' => 0,
                'message' => $message,
                'data' => [],
                'attache' => []

            );
            return json_encode($res);
        }
        /**
         * http发送失败反馈
         */
        function tcpError($message = '账户或密码错误')
        {
            $res = array(
                'status' => 9001,
                'message' => $message,
                'data' => [],
                'attache' => []

            );
            return json_encode($res);
        }
        // 运行worker
        Worker::runAll();
    }
}

6.将两个类在项目的更目录打开cmd输入以下命令运行起来

//先启动收消息的类
php artisan start:s
//最后启动发消息的类 
php artisan mqtt start

7.那么接下来就是见证奇迹的时刻

通过postman 已post方式请求发送了id值为989
奇迹图

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

极客铁憨憨

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值