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.

85 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. var_dump('speaker-orderid', $orderId);
  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. var_dump('speaker-orders', $orders);
  24. if(empty($orders)) return;
  25. // 循环发送
  26. foreach ($orders as $k => &$order) {
  27. $order['template'] = "懒族支付到账".floatval($order['money'])."";
  28. // 获取终端ID
  29. $order['to_client_id'] = Store::query()->where(['id' => $order['store_id']])->value('loudspeaker_imei');
  30. var_dump('speaker-$order', $order);
  31. // 发布订阅消息
  32. $res = $this->publish($order['template'], self::TOPIC, $order['to_client_id']);
  33. var_dump('speaker-$res', $res);
  34. }
  35. }
  36. /**
  37. * @inheritDoc
  38. */
  39. public function publish(
  40. $message,
  41. $topic,
  42. $toClientId = '',
  43. $type = '',
  44. $payId = '',
  45. $curClientId = ''
  46. ) {
  47. $client = new MQTTClient(env('MQTT_HOST'), env('MQTT_PORT'));
  48. $client->setAuthentication(env('MQTT_NAME'), env('MQTT_PASS'));
  49. $client->setDebug(true);
  50. if (env('MQTT_CERT')) {
  51. $client->setEncryption(env('MQTT_CERT'));
  52. }
  53. $msgArr = [];
  54. if ( (empty($type)&&is_numeric($message)) || 'cash' === $type ) {
  55. $msgArr['cash'] = $message;
  56. $payId AND $msgArr['payid'] = $payId;
  57. } else {
  58. $msgArr['message'] = $message;
  59. }
  60. if (!empty($toClientId)) {
  61. $topic .= '/'.$toClientId;
  62. }
  63. $curClientId OR $curClientId = (string)rand(1,999999999);
  64. $success = $client->sendConnect($curClientId);
  65. var_dump('$success', $success);
  66. if ($success) {
  67. $client->sendPublish($topic, json_encode($msgArr), MQTTClient::MQTT_QOS2);
  68. $client->sendDisconnect();
  69. }
  70. $client->close();
  71. }
  72. }