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.

88 lines
2.4 KiB

6 years ago
  1. <?php
  2. namespace App\Service;
  3. use App\Libs\MQTTClient;
  4. use App\Model\Order;
  5. use App\Model\Store;
  6. use Hyperf\Utils\ApplicationContext;
  7. class MqttSpeakerService implements MqttServiceInterface
  8. {
  9. const TOPIC = 'test01';
  10. /**
  11. * @inheritDoc
  12. */
  13. public function speakToStore($orderId, $isMain = true)
  14. {
  15. // 获取订单
  16. $orders = Order::query()->select(['id','order_num','money', 'pay_type', 'store_id', 'type']);
  17. if ($isMain) {
  18. $orders = $orders->where(['order_main_id' => $orderId])->get()->toArray();
  19. } else {
  20. $orders = $orders->where(['id' => $orderId])->get()->toArray();
  21. }
  22. if(empty($orders)) return;
  23. // 循环发送
  24. foreach ($orders as $k => &$order) {
  25. $order['template'] = "懒族生活支付到账".floatval($order['money'])."";
  26. // 获取终端ID
  27. $order['to_client_id'] = Store::query()->where(['id' => $order['store_id']])->value('loudspeaker_imei');
  28. // 发布订阅消息
  29. $this->pubToMqtt($order['template'], self::TOPIC, $order['to_client_id']);
  30. }
  31. }
  32. /**
  33. * @inheritDoc
  34. */
  35. public function pubToMqtt($message, $topic, $toClientId)
  36. {
  37. $this->publish($message, $topic, $toClientId);
  38. }
  39. /**
  40. * @inheritDoc
  41. */
  42. public function publish(
  43. $message,
  44. $topic,
  45. $toClientId = '',
  46. $type = '',
  47. $payId = '',
  48. $curClientId = ''
  49. ) {
  50. $client = new MQTTClient(env('MQTT_HOST'), env('MQTT_PORT'));
  51. $client->setAuthentication(env('MQTT_NAME'), env('MQTT_PASS'));
  52. if (env('MQTT_CERT')) {
  53. $client->setEncryption(env('MQTT_CERT'));
  54. }
  55. $msgArr = [];
  56. if ( (empty($type)&&is_numeric($message)) || 'cash' === $type ) {
  57. $msgArr['cash'] = $message;
  58. $payId AND $msgArr['payid'] = $payId;
  59. } else {
  60. $msgArr['message'] = $message;
  61. }
  62. if (!empty($toClientId)) {
  63. $topic .= '/'.$toClientId;
  64. }
  65. $curClientId OR $curClientId = (string)rand(1,999999999);
  66. $success = $client->sendConnect($curClientId);
  67. if ($success) {
  68. $client->sendPublish($topic, json_encode($msgArr), MQTTClient::MQTT_QOS2);
  69. $client->sendDisconnect();
  70. }
  71. $client->close();
  72. }
  73. }