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.

83 lines
2.4 KiB

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
  1. <?php
  2. namespace App\Service\v3\Implementations;
  3. use App\Constants\v3\OrderType;
  4. use App\Libs\MQTTClient;
  5. use App\Model\v3\Order;
  6. use App\Model\v3\Store;
  7. use Hyperf\Utils\ApplicationContext;
  8. use App\Service\v3\Interfaces\MqttServiceInterface;
  9. class MqttService implements MqttServiceInterface
  10. {
  11. /**
  12. * @inheritDoc
  13. */
  14. public function speakToStore($globalOrderId, $isMain = true)
  15. {
  16. // 获取订单
  17. $orders = Order::query()
  18. ->with('orderMain');
  19. if ($isMain) {
  20. $orders = $orders->where(['order_main_id' => $globalOrderId])->get();
  21. } else {
  22. $orders = $orders->where(['id' => $globalOrderId])->get();
  23. }
  24. if(empty($orders)) return;
  25. // 循环发送
  26. foreach ($orders as $k => &$order) {
  27. $template = $order->orderMain->type == OrderType::ONLINE ? "懒族生活提示您:您有新的懒族外卖订单" : "微信到账".floatval($order->money)."";
  28. // 获取终端ID
  29. $to_client_id = Store::query()->where(['id' => $order->store_id])->value('loudspeaker_imei');
  30. // 发布订阅消息
  31. $this->publish($template, config('mqtt.topic'), $to_client_id);
  32. }
  33. return true;
  34. }
  35. /**
  36. * @inheritDoc
  37. */
  38. public function publish(
  39. $message,
  40. $topic,
  41. $toClientId = '',
  42. $type = '',
  43. $payId = '',
  44. $curClientId = ''
  45. ) {
  46. $client = new MQTTClient(config('mqtt.host'), config('mqtt.port'));
  47. $client->setAuthentication(config('mqtt.name'), config('mqtt.pass'));
  48. $client->setDebug(true);
  49. if (config('mqtt.cert')) {
  50. $client->setEncryption(config('mqtt.cert'));
  51. }
  52. $msgArr = [];
  53. if ( (empty($type)&&is_numeric($message)) || 'cash' === $type ) {
  54. $msgArr['cash'] = $message;
  55. $payId AND $msgArr['payid'] = $payId;
  56. } else {
  57. $msgArr['message'] = $message;
  58. }
  59. if (!empty($toClientId)) {
  60. $topic .= '/'.$toClientId;
  61. }
  62. $curClientId OR $curClientId = (string)rand(1,999999999);
  63. $success = $client->sendConnect($curClientId);
  64. if ($success) {
  65. $client->sendPublish($topic, json_encode($msgArr), MQTTClient::MQTT_QOS2);
  66. $client->sendDisconnect();
  67. }
  68. $client->close();
  69. }
  70. }