Coroutine MQTT Client Integration With Hyperf Framework
This library uses simps/mqtt, please see https://mqtt.simps.io/#/en/ for compatibility
composer require nashgao/mqtt
publish config
php bin/hyperf.php vendor:publish nashgao/mqtt
Shared Subscription is a new feature introduced by MQTT 5. It allows multiple subscribers to subscribe a same topic while only one of them receives the message at a time
[subscriber1] got msg1
msg1, msg2, msg3 /
[publisher] ----------------> "$share/g/topic" -- [subscriber2] got msg2
\
[subscriber3] got msg3
As the Chart demonstrated, subscriber 1,2,3 belongs to the same group g
under topic
, where $share
is the constant prefix of the topic.
While msg 1,2,3 is published gradually, only one of the subscriber within the group will receive the message instead of all of them (queue topic
is special case for shared subscription, with group g
became a constant string as $queue
).
In order to make the subscription easier, this library was designed and integrated with Hyperf framework. The library uses simps/mqtt which is the first php mqtt library that support MQTT 5 for basic mqtt broker interaction.
-
Subscribe
- Auto subscribe:
- For each topic defined under your
config/autoload/mqtt.php
, if theauto_subscribe
is enabled as true, the mentioned topic will be subscribed once the hyperf server is started. - If the
queue topic
is enabled as true, then it would short circuit the shared topic options - option
enable_multi_sub
is enabled as true, thenmulti_sub
numbers of client will be created to subscribe corresponding topic - option
group_name
represents to theg
option mentioned above it the design purpose section
- For each topic defined under your
- Manual subscribe (in these cases, the shared subscription needs to be handled manually)
- dispatch
Nashgao\MQTT\Event\SubscribeEvent
eventuse Hyperf\Context\ApplicationContext; use Nashgao\MQTT\Config\TopicConfig; use Nashgao\MQTT\Event\SubscribeEvent; use Psr\EventDispatcher\EventDispatcherInterface; $event = new SubscribeEvent(topicConfigs: [ new TopicConfig([ 'topic' => 'topic/test', 'qos' => 2 ]) ]); $dispatcher = ApplicationContext::getContainer()->get(EventDispatcherInterface::class); $dispatcher->dispatch($event);
- call
Nashgao\MQTT\Client
directlyuse Nashgao\MQTT\Client; $client = make(Client::class); $client->subscribe([ 'topic/test' => [ 'qos' => 2 ] ]);
- dispatch
- Auto subscribe:
-
Publish
- dispatch
Nashgao\MQTT\Event\PublishEvent
use Hyperf\Event\EventDispatcher; use Hyperf\Context\ApplicationContext; use Nashgao\MQTT\Event\PublishEvent; use Psr\EventDispatcher\EventDispatcherInterface; $dispatcher = ApplicationContext::getContainer()->get(EventDispatcherInterface::class); $dispatcher->dispatch(new PublishEvent('topic/test', 'hi mqtt', 2));
- call
Nashgao\MQTT\Client
directly
use Nashgao\MQTT\Client; $client = make(Client::class); $client->publish('topic/test', 'hi_mqtt', 2);
- dispatch