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.
 
 

81 lines
2.4 KiB

<?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()->select(['id','order_num','money', 'pay_type', 'store_id', 'type']);
if ($isMain) {
$orders = $orders->where(['order_main_id' => $orderId])->get()->toArray();
} else {
$orders = $orders->where(['id' => $orderId])->get()->toArray();
}
if(empty($orders)) return;
// 循环发送
foreach ($orders as $k => &$order) {
$order['template'] = $order['type']==OrderType::ONLINE ? "您有新的懒族外卖订单" : "微信到账".floatval($order['money'])."";
// 获取终端ID
$order['to_client_id'] = Store::query()->where(['id' => $order['store_id']])->value('loudspeaker_imei');
// 发布订阅消息
$res = $this->publish($order['template'], config('mqtt.topic'), $order['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();
}
}