Git Product home page Git Product logo

mqttclient's Introduction

jesusslim/mqttclient

PHP mqtt client

usage

[English] Chinese

Install

Install:

composer require jesusslim/mqttclient

If your composer not allowed dev-master,add this config

"minimum-stability": "dev"

into your composer.json.

Require

swoole 2.0.8+(swoole.so)
mosquitto.so

Example

There's MqttClient we can use.One is based on swoole(see swoole example,deprecated),another is based on mosquitto(see mosquitto example).

The difference:

  • Requirements difference.
  • Swoole has package-separation bug and crash bug.We should handle this exception,for example,monitor the process id and restart when is crash or receive error package.
  • Swoole client can subscribe and publish in one client,use mosquitto we need two client.
  • Some grammar difference between swoole and mosquitto.

Example base on mosquitoo

define your logger:

class Logger implements \mqttclient\src\swoole\MqttLogInterface {

	public function log($type,$content,$params = []){
	        echo "$type : $content \r\n";
	 }
}

use Mqttclient

$host = '127.0.0.1';
$port = 1883;
$r = new \mqttclient\src\mosquitto\MqttClient($host,$port,10017);
$r->setAuth('username','password');
$r->setKeepAlive(60);
$r->setLogger(new Logger());
$r->setMaxReconnectTimesWhenError(360*12);
//reconnect interval
$r->setReconnectInterval(10);
//subscribe topics,callback's params can be any data we mapped into the container(IOC)
$r->setTopics(
[
    new \mqttclient\src\subscribe\Topic('test/slim',function($msg){
        echo "I receive:".$msg."\r\n";}),
    new \mqttclient\src\subscribe\Topic('test/slim3',function(\mqttclient\src\swoole\MqttClient $client,$msg){
        echo "I receive:".$msg." for slim3 \r\n";
        echo $client->getClientId();
    })
]
);
//set trigger
$r->on(\mqttclient\src\consts\ClientTriggers::SOCKET_CONNECT,function(){
    //do something
});
$r->start();

Sender:

$host = '127.0.0.1';
$port = 1883;
$r = new \mqttclient\src\mosquitto\MqttSender($host,$port,10017);
$r->setAuth('username','password');
$r->setKeepAlive(60);
$r->setLogger(new Logger());
$r->setMaxReconnectTimesWhenError(360*12);
//reconnect interval
$r->setReconnectInterval(10);
$r->setQueue(new Queue());
$r->start();

It need a queue implements mqttclient\src\mosquitto\MqttSendingQueue,to get msg that need to be sent in loop.

Example base on swoole(deprecated)

define your logger:

class Logger implements \mqttclient\src\swoole\MqttLogInterface {

	public function log($type,$content,$params = []){
	        echo "$type : $content \r\n";
	 }
}

define your tmp store (use Redis/Memory/...)

class Store implements \mqttclient\src\swoole\TmpStorageInterface{

	private $data = [];

    public function set($message_type, $key, $sub_key, $data, $expire = 3600)
    {
        $this->data[$message_type][$key][$sub_key] = $data;
    }

    public function get($message_type, $key, $sub_key)
    {
        return $this->data[$message_type][$key][$sub_key];
    }

    public function delete($message_type, $key, $sub_key)
    {
        if (!isset($this->data[$message_type][$key][$sub_key])){
            echo "storage not found:$message_type $key $sub_key";
        }
        unset($this->data[$message_type][$key][$sub_key]);
    }

}

use MqttClient

$host = '127.0.0.1';
$port = 1883;

$r = new \mqttclient\src\swoole\MqttClient($host,$port,10017);
$r->setAuth('username','password');
$r->setKeepAlive(60);
$r->setLogger(new Logger());
$r->setStore(new Store());
//dns lookup
$r->setDnsLookup(true);
//buffer size
$r->setSocketBufferSize(1024*1024*5);
//reconnect times when error
$r->setMaxReconnectTimesWhenError(360*12);
//reconnect interval
$r->setReconnectInterval(10000);
//subscribe topics,callback's params can be any data we mapped into the container(IOC)
$r->setTopics(
[
    new \mqttclient\src\subscribe\Topic('test/slim',function($msg){
        echo "I receive:".$msg."\r\n";}),
    new \mqttclient\src\subscribe\Topic('test/slim3',function(\mqttclient\src\swoole\MqttClient $client,$msg){
        echo "I receive:".$msg." for slim3 \r\n";
        echo $client->getClientId();
    })
]
);

//set trigger
$r->on(\mqttclient\src\consts\ClientTriggers::RECEIVE_SUBACK,function(\mqttclient\src\swoole\MqttClient $client){
	$client->publish('slim/echo','GGXX',\mqttclient\src\consts\Qos::ONE_TIME);
});

$r->connect();
$r->publish('test/slim','test qos',2);

Extends

You can also use own client extends MqttClient.

Example:

class Client extends MqttClient
{
    private $mysql_handler;
    private $mongo_handler;

    public function __construct($host,$port,$client_id,$mysql_conf,$mongo_conf)
    {
        $this->mysql_handler = new Mysqli($mysql_conf);
        $this->mongo_handler = new \MongoClient('mongodb://'.$mongo_conf['username'].':'.$mongo_conf['password'].'@'.$mongo_conf['host'].':'.$mongo_conf['port'].'/'.$mongo_conf['db']);
        parent::__construct($host,$port,$client_id);
    }

	 /**
     * override the produceContainer function and map your own class/data/closure to the injector,and they can be used in every publish receive handler
     * for exp: $client->setTopics([new Topic('test/own',function($mongo,$msg){ $result = $mongo->selectCollection('log_platform','test')->find(['sid' => ['$gte' => intval($msg)]]); })]);
     * @return Injector
     */
    protected function produceContainer()
    {
        $container = new Injector();
        $container->mapData(MqttClient::class,$this);
        $container->mapData(Client::class,$this);
        $container->mapData('mysqli',$this->mysql_handler);
        $container->mapData('mongo',$this->mongo_handler);
        return $container;
    }

}

mqttclient's People

Contributors

jesusslim avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

mqttclient's Issues

connect() does not authenticate

Using the example provided:
$r = new \mqttclient\src\swoole\MqttClient('127.0.0.1', 1883, 10017);
$r->setAuth('username','password');
...
$r->connect();

The 'username' and 'password' are never sent to the MQTT server. With using Wireshark, this can be confirmed. Message payload never has 'username' nor 'password' in it.

Mosquitto then reports on connect:

1525541579: New connection from 127.0.0.1 on port 1883.
1525541579: Socket error on client <unknown>, disconnecting.

Connecting with some other client does work when using same username and password. With Wireshark, username and password can be seen in the payload.

How can you authenticate using username and password?

请问有方法释放内存么,内存占用1天增加7%

image
4g的内存,这情况的话,基本上3天就得重启一次
image
调用代码如下:
`
public function handle()
{
$server = config('mqtt.host');
$port = config('mqtt.port');
$username = config('mqtt.username');
$password = config('mqtt.password');
$client_id = "backendService";
ini_set('memory_limit', '-1');

    $client = new Client($server, $port, $client_id);
    $client->setMqttVersion(MqttVersion::V311);
    $client->setAuth($username, $password);
    $client->setKeepAlive(60);
    $client->setStore(new Store());
    $client->setLogger(new Logger());
    $client->setMaxReconnectTimesWhenError(0);
    $client->setPackageMaxLength(1024*1024*256);

    $client->setTopics([
        new Topic('$sys/client/connect', function ($msg) {
            $this->clientConnect($msg);
        }, 1),

        new Topic('$sys/client/disconnect', function ($msg) {
            $this->clientDisconnect($msg);
        }, 1),

        new Topic('$sys/app/callback', function ($msg) use ($client) {
            $this->orderCallback($msg, $client);
        }, 0),
    ]);

    $client->setTimer(1000, function ($timer_id, $mqtt) {
        $this->publishOrderStartData($mqtt);
    });

    $client->setTimer(1100, function ($timer_id, $mqtt) {
        $this->publishOrderStopData($mqtt);
    });

    $client->setTimer(1, function ($timer_id, $mqtt) use ($client) {
        $client->on(ClientTriggers::SOCKET_FIRST_CLOSE, function () use ($client) {
            $this->resetAllDevice();
            Cache::forever('mqtt_server_is_connected', false);
            Log::debug('mqtt_server_is_connected', [cache('mqtt_server_is_connected')]);
        });
        $client->on(ClientTriggers::RECEIVE_CONNACK, function () use ($client) {
            Cache::forever('mqtt_server_is_connected', true);
            Log::debug('mqtt_server_is_connected', [cache('mqtt_server_is_connected')]);
        });
        $client->on(ClientTriggers::DISCONNECT, function () use ($client) {
            Cache::forever('mqtt_server_is_connected', false);
            Log::debug('mqtt_server_is_connected', [cache('mqtt_server_is_connected')]);
        });
        $client->on(ClientTriggers::RECEIVE_PINGRESP, function () {
            Cache::forever('mqtt_server_is_connected', true);
        });
    });

    $client->connect();
}`

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.