Home >Backend Development >PHP Tutorial >Communication and control of the Internet of Things using PHP and MQTT

Communication and control of the Internet of Things using PHP and MQTT

WBOY
WBOYOriginal
2023-06-25 10:14:235068browse

With the development of Internet of Things technology, more and more devices and items are becoming connected to the Internet, and communication and control between these devices and items are required. This article will introduce how to use PHP and MQTT protocols to implement communication and control of the Internet of Things.

1. What is the MQTT protocol

MQTT (Message Queuing Telemetry Transport) is a lightweight message transmission protocol that is implemented based on the publish/subscribe model. The MQTT protocol can be used in low-bandwidth and unreliable network environments and is a protocol suitable for IoT devices.

The basic concepts of the MQTT protocol are:

  • Client: a device or application that can connect to the MQTT server and publish or subscribe to messages.
  • Server (Broker): MQTT message broker, responsible for receiving, storing and forwarding messages.
  • Topic: Represents the category or name of a message. Topics can consist of one or more words, separated by "/". For example, the topic "/sensor/humidity" represents data from a humidity sensor.
  • Message (Message): the information transmitted in communication. MQTT messages can contain topics and payloads, and the payload can be any binary data.

2. Use MQTT protocol to implement IoT communication

  1. Install MQTT server

First, you need to install the MQTT message proxy server on the server . Commonly used MQTT servers include Mosquitto and EMQX.

On Ubuntu systems, Mosquitto can be installed through the following command:

$ sudo apt-get update
$ sudo apt-get install mosquitto mosquitto-clients
  1. PHP can connect to the MQTT server

PHP can call the MQTT client library, To connect to the MQTT message broker server to implement the functions of publishing and subscribing messages. Commonly used MQTT client libraries include phpMQTT and MQTT.php.

Using the phpMQTT library, you can use the following code to connect to the MQTT server and publish messages:

<?php
require("phpMQTT.php");

$mqtt = new phpMQTT("example.com", 1883, "PHP MQTT Client");

if ($mqtt->connect()) {
    $mqtt->publish("/sensor/humidity", "25");
    $mqtt->close();
} else {
    echo "Connection failed!";
}
?>

In the above code, you need to provide the address and port number of the MQTT server, as well as the client's ID. The connect() method can be used to connect to the MQTT server, the publish() method is used to publish messages, and the close() method can close the MQTT connection.

  1. PHP subscribes to MQTT topics

In addition to publishing messages, PHP can also subscribe to MQTT topics and receive messages sent by the MQTT server.

Using the phpMQTT library, you can implement the functions of subscribing to topics and receiving messages through the following code:

<?php
require("phpMQTT.php");

function messageHandler($topic, $payload) {
    echo "Received message on topic: $topic
Payload: $payload

";
}

$mqtt = new phpMQTT("example.com", 1883, "PHP MQTT Client");

if ($mqtt->connect()) {
    $mqtt->subscribe("/sensor/temperature", "messageHandler");
    while ($mqtt->proc()) {}
    $mqtt->close();
} else {
    echo "Connection failed!";
}
?>

In the above code, use the subscribe() method to subscribe to the /mainstreet/topic topic, $payload parameter It is the message received by the callback function messageHandler(). code>while ($mqtt->proc()) {} loop can maintain the subscription state, receive and process messages from the MQTT server.

3. Use PHP and MQTT protocol to realize IoT control

MQTT protocol can not only be used to realize IoT communication, but also can be used to realize device control. The MQTT server can receive messages from clients and then send the messages to other clients that need to receive messages. In this way, control between devices can be achieved.

  1. Control LED lights

The following is a sample code for controlling LED lights using MQTT protocol and PHP:

<?php
require("phpMQTT.php");

function messageHandler($topic, $payload) {
    $pattern = '/^led=(on|off)$/';
    if (preg_match($pattern, $payload, $matches)) {
        if ($matches[1] == "on") {
            system("gpio write 0 1"); // Turn on LED
        } else {
            system("gpio write 0 0"); // Turn off LED
        }
    }
}

$mqtt = new phpMQTT("example.com", 1883, "PHP MQTT Client");

if ($mqtt->connect()) {
    $mqtt->subscribe("/devices/led", "messageHandler");
    while ($mqtt->proc()) {}
    $mqtt->close();
} else {
    echo "Connection failed!";
}
?>

In the above code, GPIO control is used LED light switch, when the message received by MQTT conforms to the "led=on" or "led=off" format, the LED light switch will be controlled.

  1. Control the motor

The following is a sample code for controlling the motor using the MQTT protocol and PHP:

<?php
require("phpMQTT.php");

function messageHandler($topic, $payload) {
    $pattern = '/^motor=(forward|backward|stop)$/';
    if (preg_match($pattern, $payload, $matches)) {
        if ($matches[1] == "forward") {
            // Turn motor forward
        } elseif ($matches[1] == "backward") {
            // Turn motor backward
        } else {
            // Stop motor
        }
    }
}

$mqtt = new phpMQTT("example.com", 1883, "PHP MQTT Client");

if ($mqtt->connect()) {
    $mqtt->subscribe("/devices/motor", "messageHandler");
    while ($mqtt->proc()) {}
    $mqtt->close();
} else {
    echo "Connection failed!";
}
?>

In the above code, regular expression matching is used If the content of the MQTT message conforms to the "motor=forward", "motor=backward" or "motor=stop" format, it will control the movement direction of the motor.

Summary

This article introduces how to use PHP and MQTT protocols to implement communication and control of the Internet of Things. Through the MQTT protocol, communication and control between devices can be achieved in low-bandwidth and unreliable network environments, which is the basis for IoT applications.

The above is the detailed content of Communication and control of the Internet of Things using PHP and MQTT. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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