Home PHP Framework ThinkPHP About thinkphp using mqtt

About thinkphp using mqtt

Dec 24, 2020 pm 03:14 PM
mqtt thinkphp

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);   
    }
}
Copy after login

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 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)

How to run thinkphp project How to run thinkphp project Apr 09, 2024 pm 05:33 PM

To run the ThinkPHP project, you need to: install Composer; use Composer to create the project; enter the project directory and execute php bin/console serve; visit http://localhost:8000 to view the welcome page.

There are several versions of thinkphp There are several versions of thinkphp Apr 09, 2024 pm 06:09 PM

ThinkPHP has multiple versions designed for different PHP versions. Major versions include 3.2, 5.0, 5.1, and 6.0, while minor versions are used to fix bugs and provide new features. The latest stable version is ThinkPHP 6.0.16. When choosing a version, consider the PHP version, feature requirements, and community support. It is recommended to use the latest stable version for best performance and support.

How to run thinkphp How to run thinkphp Apr 09, 2024 pm 05:39 PM

Steps to run ThinkPHP Framework locally: Download and unzip ThinkPHP Framework to a local directory. Create a virtual host (optional) pointing to the ThinkPHP root directory. Configure database connection parameters. Start the web server. Initialize the ThinkPHP application. Access the ThinkPHP application URL and run it.

PHP MQTT Client Development Guide PHP MQTT Client Development Guide Mar 27, 2024 am 09:21 AM

MQTT (MessageQueuingTelemetryTransport) is a lightweight message transmission protocol commonly used for communication between IoT devices. PHP is a commonly used server-side programming language that can be used to develop MQTT clients. This article will introduce how to use PHP to develop an MQTT client and include the following content: Basic concepts of the MQTT protocol Selection and usage examples of the PHPMQTT client library: Using the PHPMQTT client to publish and

Which one is better, laravel or thinkphp? Which one is better, laravel or thinkphp? Apr 09, 2024 pm 03:18 PM

Performance comparison of Laravel and ThinkPHP frameworks: ThinkPHP generally performs better than Laravel, focusing on optimization and caching. Laravel performs well, but for complex applications, ThinkPHP may be a better fit.

Development suggestions: How to use the ThinkPHP framework to implement asynchronous tasks Development suggestions: How to use the ThinkPHP framework to implement asynchronous tasks Nov 22, 2023 pm 12:01 PM

"Development Suggestions: How to Use the ThinkPHP Framework to Implement Asynchronous Tasks" With the rapid development of Internet technology, Web applications have increasingly higher requirements for handling a large number of concurrent requests and complex business logic. In order to improve system performance and user experience, developers often consider using asynchronous tasks to perform some time-consuming operations, such as sending emails, processing file uploads, generating reports, etc. In the field of PHP, the ThinkPHP framework, as a popular development framework, provides some convenient ways to implement asynchronous tasks.

How to install thinkphp How to install thinkphp Apr 09, 2024 pm 05:42 PM

ThinkPHP installation steps: Prepare PHP, Composer, and MySQL environments. Create projects using Composer. Install the ThinkPHP framework and dependencies. Configure database connection. Generate application code. Launch the application and visit http://localhost:8000.

How is the performance of thinkphp? How is the performance of thinkphp? Apr 09, 2024 pm 05:24 PM

ThinkPHP is a high-performance PHP framework with advantages such as caching mechanism, code optimization, parallel processing and database optimization. Official performance tests show that it can handle more than 10,000 requests per second and is widely used in large-scale websites and enterprise systems such as JD.com and Ctrip in actual applications.

See all articles