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.

80 lines
2.2 KiB

5 years ago
5 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. $res = $this->publish($order['template'], self::TOPIC, $order['to_client_id']);
  30. }
  31. }
  32. /**
  33. * @inheritDoc
  34. */
  35. public function publish(
  36. $message,
  37. $topic,
  38. $toClientId = '',
  39. $type = '',
  40. $payId = '',
  41. $curClientId = ''
  42. ) {
  43. $client = new MQTTClient(env('MQTT_HOST'), env('MQTT_PORT'));
  44. $client->setAuthentication(env('MQTT_NAME'), env('MQTT_PASS'));
  45. $client->setDebug(true);
  46. if (env('MQTT_CERT')) {
  47. $client->setEncryption(env('MQTT_CERT'));
  48. }
  49. $msgArr = [];
  50. if ( (empty($type)&&is_numeric($message)) || 'cash' === $type ) {
  51. $msgArr['cash'] = $message;
  52. $payId AND $msgArr['payid'] = $payId;
  53. } else {
  54. $msgArr['message'] = $message;
  55. }
  56. if (!empty($toClientId)) {
  57. $topic .= '/'.$toClientId;
  58. }
  59. $curClientId OR $curClientId = (string)rand(1,999999999);
  60. $success = $client->sendConnect($curClientId);
  61. if ($success) {
  62. $client->sendPublish($topic, json_encode($msgArr), MQTTClient::MQTT_QOS2);
  63. $client->sendDisconnect();
  64. }
  65. $client->close();
  66. }
  67. }