workerman/mqtt

MQTT is a message transmission protocol based on the client-server architecture and the publish/subscribe pattern, which has become an important part of the Internet of Things. Its design philosophy is lightweight, open, simple, and standardized, and easy to implement. These characteristics make it a good choice for many scenarios, especially for constrained environments such as machine-to-machine communication (M2M) and the Internet of Things (IoT).

workerman\mqtt is an asynchronous MQTT client library based on workerman, which can be used to receive or send MQTT protocol messages. It supports QoS 0, QoS 1, QoS 2. It also supports MQTT versions 3.1, 3.1.1, and 5.

Project Address

https://github.com/walkor/mqtt

Installation

composer require workerman/mqtt

Examples

subscribe.php

<?php
use Workerman\Worker;
require_once __DIR__ . '/vendor/autoload.php';

$worker = new Worker();
$worker->onWorkerStart = function(){
    $mqtt = new Workerman\Mqtt\Client('mqtt://test.mosquitto.org:1883');
    $mqtt->onConnect = function($mqtt) {
        $mqtt->subscribe('test');
    };
    $mqtt->onMessage = function($topic, $content){
        var_dump($topic, $content);
    };
    $mqtt->connect();
};
Worker::runAll();

Run in the command line php subscribe.php start to start.

publish.php

<?php
use Workerman\Worker;
require_once __DIR__ . '/vendor/autoload.php';

$worker = new Worker();
$worker->onWorkerStart = function(){
    $mqtt = new Workerman\Mqtt\Client('mqtt://test.mosquitto.org:1883');
    $mqtt->onConnect = function($mqtt) {
       $mqtt->publish('test', 'hello workerman mqtt');
    };
    $mqtt->connect();
};
Worker::runAll();

Run in the command line php publish.php start to start.

workerman\mqtt\Client Interface


__construct (string $address, [array $options])

Creates an instance of the MQTT client.


connect()

Connects to the Broker.


publish(String $topic, String $content, [array $options], [callable $callback])

Publishes a message to a specific topic.


subscribe(mixed $topic, [array $options], [callable $callback])

Subscribes to one or multiple topics.


unsubscribe(mixed $topic, [callable $callback])

Unsubscribes from one or multiple topics.


disconnect()

Gracefully disconnects from the Broker. A DISCONNECT message will be sent to the Broker.


close()

Forcibly disconnects from the Broker without sending a DISCONNECT message.


callback onConnect(Client $mqtt)

Triggered when the connection to the Broker is established. At this point, the client has received the CONNACK message from the Broker.


callback onMessage(String $topic, String $content, Client $mqtt)

Triggered when the client receives a Publish message.


callback onError(\Exception $exception = null)

Triggered when a connection error occurs.


callback onClose()

Triggered when the connection is closed, either by the client or the server.