MqttMessageClient.php 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. <?php
  2. namespace app\admin\services;
  3. use PhpMqtt\Client\MqttClient;
  4. use PhpMqtt\Client\ConnectionSettings;
  5. use PhpMqtt\Client\Exceptions\ProtocolNotSupportedException;
  6. use think\Env;
  7. class MqttMessageClient
  8. {
  9. protected static $instance = null;
  10. protected $client = null;
  11. /**
  12. * 功能:实例化mqtt
  13. * @throws ProtocolNotSupportedException
  14. * @throws \PhpMqtt\Client\Exceptions\ConfigurationInvalidException
  15. * @throws \PhpMqtt\Client\Exceptions\ConnectingToBrokerFailedException
  16. */
  17. protected function __construct()
  18. {
  19. // $protocol = Env::get("mqtt.protocol");
  20. $clientId = Env::get("mqtt.client_id");
  21. $hostname = Env::get("mqtt.hostname");
  22. $port = Env::get("mqtt.port");
  23. $username = Env::get("mqtt.username");
  24. $password = Env::get("mqtt.password");
  25. $mqtt = new MqttClient($hostname, $port, $clientId, MqttClient::MQTT_3_1_1);
  26. $connectionSettings = (new ConnectionSettings());
  27. if ($username !== null) {
  28. $connectionSettings = $connectionSettings->setUsername($username);
  29. }
  30. if ($password !== null) {
  31. $connectionSettings = $connectionSettings->setPassword($password);
  32. }
  33. $this->client = $mqtt;
  34. $mqtt->connect($connectionSettings);
  35. }
  36. protected function __clone()
  37. {
  38. }
  39. public static function getInstance()
  40. {
  41. if (static::$instance == null) {
  42. static::$instance = new static();
  43. }
  44. return static::$instance;
  45. }
  46. public function subscribe($topic, $callback)
  47. {
  48. $this->client->subscribe($topic, $callback);
  49. }
  50. public function publish(string $topic, string $message, int $qos = 0, bool $retain = false)
  51. {
  52. $this->client->publish($topic, $message, $qos, $retain);
  53. }
  54. public function loop(bool $keepAlive = true): void
  55. {
  56. $this->client->loop($keepAlive);
  57. }
  58. }