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.
|
|
<?php
namespace App\Service\v3\Implementations;
use App\Constants\v3\OrderType;use App\Libs\MQTTClient;use App\Model\v3\Order;use App\Model\v3\Store;use Hyperf\Utils\ApplicationContext;use App\Service\v3\Interfaces\MqttServiceInterface;
class MqttService implements MqttServiceInterface{
/** * @inheritDoc */ public function speakToStore($orderId, $isMain = true) {
// 获取订单
$orders = Order::query() ->with('orderMain'); if ($isMain) { $orders = $orders->where(['order_main_id' => $orderId])->get(); } else { $orders = $orders->where(['id' => $orderId])->get(); }
if(empty($orders)) return;
// 循环发送
foreach ($orders as $k => &$order) { $template = $order->orderMain->type == OrderType::ONLINE ? "您有新的懒族外卖订单" : "微信到账".floatval($order->money)."元"; // 获取终端ID
$to_client_id = Store::query()->where(['id' => $order->store_id])->value('loudspeaker_imei'); // 发布订阅消息
$this->publish($template, config('mqtt.topic'), $to_client_id); } }
/** * @inheritDoc */ public function publish( $message, $topic, $toClientId = '', $type = '', $payId = '', $curClientId = '' ) {
$client = new MQTTClient(config('mqtt.host'), config('mqtt.port')); $client->setAuthentication(config('mqtt.name'), config('mqtt.pass')); $client->setDebug(true);
if (config('mqtt.cert')) { $client->setEncryption(config('mqtt.cert')); }
$msgArr = []; if ( (empty($type)&&is_numeric($message)) || 'cash' === $type ) { $msgArr['cash'] = $message; $payId AND $msgArr['payid'] = $payId; } else { $msgArr['message'] = $message; }
if (!empty($toClientId)) { $topic .= '/'.$toClientId; }
$curClientId OR $curClientId = (string)rand(1,999999999); $success = $client->sendConnect($curClientId); if ($success) { $client->sendPublish($topic, json_encode($msgArr), MQTTClient::MQTT_QOS2); $client->sendDisconnect(); } $client->close(); }}
|