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.4 KiB

6 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($orderId, $isMain = true)
  15. {
  16. // 获取订单
  17. $orders = Order::query()->select(['id','order_num','money', 'pay_type', 'store_id', 'type']);
  18. if ($isMain) {
  19. $orders = $orders->where(['order_main_id' => $orderId])->get()->toArray();
  20. } else {
  21. $orders = $orders->where(['id' => $orderId])->get()->toArray();
  22. }
  23. if(empty($orders)) return;
  24. // 循环发送
  25. foreach ($orders as $k => &$order) {
  26. $order['template'] = $order['type']==OrderType::ONLINE ? "您有新的懒族外卖订单" : "微信到账".floatval($order['money'])."";
  27. // 获取终端ID
  28. $order['to_client_id'] = Store::query()->where(['id' => $order['store_id']])->value('loudspeaker_imei');
  29. // 发布订阅消息
  30. $res = $this->publish($order['template'], config('mqtt.topic'), $order['to_client_id']);
  31. }
  32. }
  33. /**
  34. * @inheritDoc
  35. */
  36. public function publish(
  37. $message,
  38. $topic,
  39. $toClientId = '',
  40. $type = '',
  41. $payId = '',
  42. $curClientId = ''
  43. ) {
  44. $client = new MQTTClient(config('mqtt.host'), config('mqtt.port'));
  45. $client->setAuthentication(config('mqtt.name'), config('mqtt.pass'));
  46. $client->setDebug(true);
  47. if (config('mqtt.cert')) {
  48. $client->setEncryption(config('mqtt.cert'));
  49. }
  50. $msgArr = [];
  51. if ( (empty($type)&&is_numeric($message)) || 'cash' === $type ) {
  52. $msgArr['cash'] = $message;
  53. $payId AND $msgArr['payid'] = $payId;
  54. } else {
  55. $msgArr['message'] = $message;
  56. }
  57. if (!empty($toClientId)) {
  58. $topic .= '/'.$toClientId;
  59. }
  60. $curClientId OR $curClientId = (string)rand(1,999999999);
  61. $success = $client->sendConnect($curClientId);
  62. if ($success) {
  63. $client->sendPublish($topic, json_encode($msgArr), MQTTClient::MQTT_QOS2);
  64. $client->sendDisconnect();
  65. }
  66. $client->close();
  67. }
  68. }