Home > Article > Backend Development > PHP and MQTT: Real-time monitoring of remote sensor data
PHP and MQTT: Real-time monitoring of remote sensor data
Introduction:
With the rapid development of the Internet of Things, we can monitor and control equipment and environments through remote sensors. MQTT (Message Queuing Telemetry Transport) is a lightweight message transmission protocol that is widely used in IoT applications to transmit sensor data. This article will introduce how to use PHP and MQTT to implement real-time monitoring of remote sensor data.
Install the phpMQTT library:
composer require bluerhinos/phpmqtt
The sample code to connect to the MQTT server is as follows:
<?php require("phpMQTT.php"); $mqtt = new phpMQTT("mqtt.example.com", 1883, "ClientID"); if(!$mqtt->connect()){ exit(1); } // MQTT订阅主题 $topics['sensors/data'] = array("qos" => 0, "function" => "handleSensorData"); $mqtt->subscribe($topics, 0); while($mqtt->proc()){ } $mqtt->close(); function handleSensorData($topic, $message){ echo "Received message: $message from topic: $topic "; } ?>
In the above sample code, we first introduce the phpMQTT library through the require statement. We then create an mqtt object and connect using the mqtt server's address (mqtt.example.com) and port number (1883). If the connection is successful, we can subscribe to one or more topics. In this example, we subscribe to a topic named "sensors/data" and specify the callback function handleSensorData to handle the received data. Finally, real-time monitoring is achieved by reading data in a loop. When new sensor data is received, the handleSensorData function is called for processing.
Publish sensor data:
Next, we will simulate a sensor and publish the sensor data to the MQTT server via PHP. The following is a simple example code:
<?php require("phpMQTT.php"); $mqtt = new phpMQTT("mqtt.example.com", 1883, "ClientID"); if(!$mqtt->connect()){ exit(1); } // MQTT发布主题 $topic = "sensors/data"; $message = "Sensor data: " . rand(1, 100); $mqtt->publish($topic, $message, 0); $mqtt->close(); ?>
In the above code, we create an mqtt object and use the address of the mqtt server (mqtt.example.com) and the port number ( 1883) to connect. We then specified the topic name (sensors/data) and sensor data to be published. Finally, the sensor data is published to the MQTT server by calling the publish method of the mqtt object.
However, this is just an example, and actual applications require more logic and processing. I hope this article can provide readers with basic ideas and code examples to further explore the potential of PHP and MQTT in IoT applications.
Reference materials:
The above is the detailed content of PHP and MQTT: Real-time monitoring of remote sensor data. For more information, please follow other related articles on the PHP Chinese website!