walkor / mqtt

Asynchronous MQTT client for PHP based on workerman.
207 stars 46 forks source link
mqtt mqtt-client php-mqtt

MQTT

Asynchronous MQTT client for PHP based on workerman.

Installation

composer require workerman/mqtt

文档

中文文档

Example

subscribe.php

<?php
require __DIR__ . '/vendor/autoload.php';
use Workerman\Worker;
$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 with command php subscribe.php start

publish.php

<?php
require __DIR__ . '/vendor/autoload.php';
use Workerman\Worker;
$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 with command php publish.php start

API


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

Create an instance by $address and $options.


connect()

Connect to broker specified by the given $address and $options in __construct($address, $options).


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

Publish a message to a topic


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

Subscribe to a topic or topics


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

Unsubscribe from a topic or topics


disconnect()

Send DISCONNECT package to broker and close the client.


close()

Close the client without DISCONNECT package.


callback onConnect(Client $mqtt)

Emitted on successful connection (CONNACK package received).


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

function (topic, message, client, properties) {}

Emitted when the client receives a publish packet


callback onError(\Exception $exception)

Emitted when something wrong for example the client cannot connect broker.


callback onClose()

Emitted when connection closed.


License

MIT