MQTT message subscription and publishing practice in PHP development

WBOY
Release: 2023-07-08 14:04:01
Original
2294 people have browsed it

MQTT's practical message subscription and publishing in PHP development

Introduction:
With the development of the Internet of Things, the Message Queuing Telemetry Transport Protocol (MQTT) communicates between sensor devices and back-end applications plays an important role in. As a lightweight protocol, MQTT has the characteristics of low energy consumption, high reliability and scalability. In PHP development, MQTT is used to subscribe and publish messages, which can easily communicate with sensor devices and transmit data to the back-end application for processing and display. This article will introduce the practical application of MQTT in PHP development and provide relevant code examples.

1. Introduction to MQTT:
MQTT is a message queue transmission protocol based on the publish/subscribe model. It adopts a lightweight binary message format and is suitable for various hardware devices such as sensors and embedded systems. The MQTT protocol mainly contains two roles: message publisher and message subscriber. Publishers publish messages to a specific topic, while subscribers subscribe to topics of interest to receive relevant messages. The MQTT protocol also supports message QoS (Quality of Service) level settings to ensure data reliability.

2. Install MQTT server:
Before starting the actual MQTT in PHP development, we need to build an MQTT server first. The following are brief steps to build an MQTT server:

  1. Download and install an MQTT server, such as Mosquitto.
  2. Run the MQTT server, the default listening port is 1883.

3. Using MQTT in PHP:
The process of using MQTT for message subscription and publishing in PHP is as follows:

  1. Introduce the MQTT client library :
    First, you need to introduce the MQTT client library. Commonly used MQTT client libraries in PHP include phpMQTT and mosquitto-php. This article takes phpMQTT as an example, which can be installed through composer:

    composer require bluerhinos/phpmqttclient
    Copy after login
  2. MQTT client configuration:
    Before performing MQTT operations in PHP code, you need to configure the connection first, including the server Address, port number, QoS level, etc. The following is an example configuration:

    $mqttServer = 'localhost'; // MQTT服务器地址
    $mqttPort = 1883; // MQTT服务器端口
    $mqttClientId = 'php_script'; // 客户端ID
    $mqttUsername = ''; //用户名
    $mqttPassword = ''; // 密码
    Copy after login
  3. Subscription for MQTT messages:
    To subscribe to a topic in PHP, you can use the subscribe method. The following is an example:

    require('phpMQTT.php');
    $mqtt = new phpMQTT($mqttServer, $mqttPort, $mqttClientId);
    if($mqtt->connect(true, NULL, $mqttUsername, $mqttPassword)) {
      $topics['topic_name'] = array('qos' => 0, 'function' => 'dataCallback');
      $mqtt->subscribe($topics, 0);
      while($mqtt->proc()){
      }
      $mqtt->close();
    } else {
      echo "连接MQTT服务器失败!";
      exit(1);
    }
    function dataCallback($topic, $payload) {
      echo "收到消息:$payload";
    }
    Copy after login
  4. Publishing of MQTT messages:
    To publish a message in PHP, you can use the publish method. The following is an example:

    require('phpMQTT.php');
    $mqtt = new phpMQTT($mqttServer, $mqttPort, $mqttClientId);
    if($mqtt->connect(true, NULL, $mqttUsername, $mqttPassword)) {
      $mqtt->publish('topic_name', '消息内容', 0);
      $mqtt->close();
    } else {
      echo "连接MQTT服务器失败!";
      exit(1);
    }
    Copy after login

4. Practical application:
The following takes a simple real-life application as an example to demonstrate the practical application of using MQTT for message subscription and publishing in PHP .

  1. Scenario description:
    Suppose we have a temperature sensor device that publishes real-time temperature through the MQTT protocol to the channel with the topic temperature. Our PHP application needs to receive and process this temperature data in real time, and to do this, we will subscribe to this topic and display the real-time temperature through the web interface.
  2. PHP code example:
    Subscribe temperature data and display it on the Web interface:
require('phpMQTT.php');

$mqttServer = 'localhost'; // MQTT服务器地址
$mqttPort = 1883; // MQTT服务器端口
$mqttClientId = 'php_script'; // 客户端ID

$mqtt = new phpMQTT($mqttServer, $mqttPort, $mqttClientId);

if($mqtt->connect(true, NULL, NULL, NULL)) {
    $topics['temperature'] = array('qos' => 0, 'function' => 'temperatureCallback');
    $mqtt->subscribe($topics, 0);

    echo "开始订阅温度数据...
";

    while($mqtt->proc()){
    }

    $mqtt->close();
} else {
    echo "连接MQTT服务器失败!";
    exit(1);
}

function temperatureCallback($topic, $payload) {
    echo "收到温度消息:$payload
";
    // 在这里进行温度数据的处理,如存储到数据库或展示在Web界面上
}
Copy after login
  1. Web interface example:
    Display temperature data in real time through the Web interface The sample code is as follows:
<!DOCTYPE html>
<html>
<head>
    <title>温度监控</title>
</head>
<body>
    <h1>温度监控</h1>
    <div id="temperature"></div>

    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function() {
            var mqttServer = 'mqtt://localhost:1883';
            var clientId = 'web_client';
            var temperatureTopic = 'temperature';

            var client = mqtt.connect(mqttServer, { clientId: clientId });

            client.on('connect', function() {
                client.subscribe(temperatureTopic);
            });

            client.on('message', function(topic, message) {
                if (topic === temperatureTopic) {
                    var temperature = message.toString();
                    $('#temperature').text('当前温度:' + temperature + '℃');
                }
            });
        });
    </script>
</body>
</html>
Copy after login

The above sample code demonstrates the practical application of using MQTT for message subscription and publishing in PHP. By subscribing to temperature data, we can receive temperature data in real time for processing and display, and by publishing messages, we can send control instructions to sensor devices. In actual development, the code can be expanded and adjusted according to specific needs.

Conclusion:
This article introduces the practical application of MQTT message subscription and publishing in PHP development, and provides relevant code examples. By using the MQTT protocol, PHP applications can easily communicate with sensor devices and realize real-time data transmission and processing. In IoT application development, using MQTT for messaging can improve communication efficiency and reliability, and bring convenience to application development.

The above is the detailed content of MQTT message subscription and publishing practice in PHP development. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!