You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

64 lines
1.8 KiB

  1. <?php
  2. declare(strict_types=1);
  3. namespace App\TaskWorker;
  4. use App\Libs\MQTTClient;
  5. use Hyperf\Task\Annotation\Task;
  6. class MQTTClientTask
  7. {
  8. protected $mqttClient = null;
  9. /**
  10. * @Task
  11. * @param string|number $message 消息内容
  12. * @param string $topic 发布消息到主题,主题名
  13. * @param string $type 消息类型,cash或tts
  14. * @param string $payId 支付方式,如“支付宝”、“微信”等
  15. * @param string $toClientId 终端id,如IMEI码
  16. * @param string $curClientId 当前客户端id
  17. */
  18. public function publish(
  19. $message,
  20. $topic,
  21. $toClientId = '',
  22. $type = '',
  23. $payId = '',
  24. $curClientId = ''
  25. ) {
  26. $this->getClient();
  27. $msgArr = [];
  28. if ( (empty($type)&&is_numeric($message)) || 'cash' === $type ) {
  29. $msgArr['cash'] = $message;
  30. $payId AND $msgArr['payid'] = $payId;
  31. } else {
  32. $msgArr['message'] = $message;
  33. }
  34. if (!empty($toClientId)) {
  35. $topic .= '/'.$toClientId;
  36. }
  37. $curClientId OR $curClientId = (string)rand(1,999999999);
  38. $success = $this->mqttClient->sendConnect($curClientId);
  39. if ($success) {
  40. $this->mqttClient->sendPublish($topic, json_encode($msgArr), MQTTClient::MQTT_QOS2);
  41. $this->mqttClient->sendDisconnect();
  42. }
  43. $this->mqttClient->close();
  44. }
  45. protected function getClient()
  46. {
  47. $this->mqttClient = new MQTTClient(env('MQTT_HOST'), env('MQTT_PORT'));
  48. $this->mqttClient->setAuthentication(env('MQTT_NAME'), env('MQTT_PASS'));
  49. if (env('MQTT_CERT')) {
  50. $this->mqttClient->setEncryption(env('MQTT_CERT'));
  51. }
  52. return $this->mqttClient;
  53. }
  54. }