Home  >  Article  >  PHP Framework  >  About thinkphp using mqtt

About thinkphp using mqtt

藏色散人
藏色散人forward
2020-12-24 15:14:295806browse

The following is an introduction to thinkphp using mqtt from the thinkphp framework tutorial column. I hope it will be helpful to friends in need!

Recently I was working on a project using mqtt. I saw many examples on the Internet but I couldn’t quite understand it (probably because I’m stupid). But I solved it later and recorded it here so as not to forget it because I’m not very proficient. If you see any mistakes in writing, you can leave a message and give me some advice.

The first preparation is the environment and framework. You can also use the native one, which is almost the same.

Environment I am using contOs7 and installed it. The mqtt installation tutorial used in the mosquitto environment is here (remember to set the password, the relevant permissions have not been done yet, so this article has not been written)

Framework I am using the TP5.0 framework

Connect The following is the development process

1 Download the MQTT class and put it in the extend folder in the project root directory. I originally wanted to put it in csdn resources so that everyone can earn 1 point for hard work. Unexpectedly, the default is 5 points. If you are too lazy to go to Git and have too many points, please click on the resource address and give everyone the Git address. The Git address is: https://github.com/bluerhinos/phpMQTT,

2 Then Introducing the MQtt class

Next is the code block for publishing and subscribing. Regarding the MQTT information Qos level, if you are interested, you can search it

<?php
namespace app\index\model;
use Bluerhinos\phpMQTT;
use think\Model;
class Mqtt extends Model
{
    /**
     * MQTT发送信息
     * @param $id   发布消息的ID 订阅ID需要与发布ID一致才能接受信息 topic为发布给全部
     * @param $info 发布的信息
     */
    public function pus($id,$info){
        //使用require_once 引入 MQTT 的类
        require_once (EXTEND_PATH.&#39;/phpMQTT-master/phpMQTT.php&#39;);
        $host = "";     // change if necessary   IP
        $port = 1883;                     // change if necessary    端口默认1883
        $username = "";                   // set your username 用户名
        $password = "";                   // set your password 密码
        $message = $info; //要发送的消息
        //phpMQTT有四个参数:主机,端口,客户端id,证书。官网这里的案例没写证书,请参考phpMQT类
        //没有证书的时候只能连接1883端口,不能连接8883端口。
        //第三个参数为客户端ID 不可重复
        $mqtt = new phpMQTT($host, $port, "ClientID" . rand());
        //连接
        if ($mqtt->connect(true, NULL, $username, $password)) {

            //发送信息  第三个参数为Qos服务质量等级
            //Qos0   发送者只发送一次消息,不进行重试,Broker不会返回确认消息。在Qos0情况下,Broker可能没有接受到消息
            //Qos1   发送者最少发送一次消息,确保消息到达Broker,Broker需要返回确认消息PUBACK。在Qos1情况下,Broker可能接受到重复消息
            //Qos2   Qos2使用两阶段确认来保证消息的不丢失和不重复。在Qos2情况下,Broker肯定会收到消息,且只收到一次
            $mqtt->publish($id, $message, 0);
            $mqtt->close(); //关闭
        } else {
            echo "Fail or time out<br />";
        }
    }

    /**

     * 要使用命令行运行此方法!!!   

     *  think5.0 运行方法为 cd到Public 目录  然后  php index.php 模块/控制器/方法

     * 该类主要为订阅,建议订阅代码和发布代码不要写在同一个类中,避免修改造成不必要的误改。
     * 每次更新该类后需要重启mqtt订阅,否则新的改动不会生效。
     * 请在相应的位置放入phpMQTT的库
     * 库代码:https://github.com/bluerhinos/phpMQTT/blob/master/phpMQTT.php
     * 类库使用的时候注意命名空间,类名称命名要和thinkphp的保持一致,不然会报错
     */
    public function sub(){
        require_once (EXTEND_PATH.&#39;/phpMQTT-master/phpMQTT.php&#39;);
        $server = "";     // change if necessary 服务器IP
        $port = 1883;                     // change if necessary    端口 一般是1883
        $username = "";                   // set your username mosquitto设置的用户名
        $password = "";                   // set your password mosquitto设置的密码
        $client_id = "clientx9293670xxctr".rand(1213333123,123123333); //你的连接客户端id

        $mqtt = new phpMQTT($server, $port, $client_id);    //进行连接

        if(!$mqtt->connect(true, NULL, $username, $password)) {
            exit(&#39;error&#39;);   //连接失败
        } else {
            echo "success"; //连接成功
        }
        //topics["topic"]  为接受的主题名  需要和发送的主题名一致  否则会订阅不到
        //订阅信息 Qos为信息登记,需要和发送的等级一致
        $topics["topic"] = array("qos" => 0, "function" =>array($this,"onMessage"));

        $mqtt->subscribe($topics, 0);

        //死循环监听
        while($mqtt->proc()){

        }
        $mqtt->close();
    }
    /**
     * 在此处接MQtt的信息 进行业务处理
     * @param $topic
     * @param $msg
     */
    function onMessage($topic,$msg){
    	$msg = json_decode($msg,true);
        //我把数据传递到了另一个方法进行处理  可以在处理完逻辑业务之后 再次调用发布方法  去给订阅方发布消息
        $this->index($msg);   
    }
}

Remember to run it on the command line when using subscriptions , thinkphp execution example first cd to the public directory of the project and then execute php index.php module/controller/method

Return to sucess after execution If you want to test it, you can Use mqtt.fx software address is http://www.jensd.de/apps/mqttfx/ I am using 1.7.1. After clicking in, there is a windows link below and you can click to download. If you use it,

Configuration uses
to open the software. The interface is as shown below

About thinkphp using mqtt

Then select Edit Connection

About thinkphp using mqtt

and fill in the corresponding Profile Name , Broker Address and Broker Port (if modified, the default is 1883), Client ID can be automatically generated by clicking the Generate button. After editing, click Save to exit the editing interface.

About thinkphp using mqtt

After that, go to the drop-down box of the main interface and select the Profile Name just configured (172.16.0.121), and then click the Connect button to connect to the service. After the connection is successful, click the Subscribe option, select the topic in the drop-down box below (or create a topic yourself, such as i like mqtt), and then click the Subscribe button.

About thinkphp using mqtt

Go back to the Publish option and select a topic in the drop-down box (or create a topic the same as the Subscribe option). Now you can write the message you want to send in the input area below (such as wo ai mqtt, Chinese will be garbled on the subscriber's message display). The messages here support multiple formats, and then click the Publish button.

About thinkphp using mqtt

Finally, go back to the Subscribe option to check whether the message is received successfully. As shown in the figure, the message sent by the publisher (wo ai mqtt) has been successfully received.

About thinkphp using mqtt

You can also choose the corresponding message decoder (text format, JSON format, Base64 encoding, hexadecimal encoding, Sparkplug encoding)

The above is the detailed content of About thinkphp using mqtt. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete