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

<?php
namespace App\Service;
use App\Libs\MQTTClient;
use App\Model\Order;
use App\Model\Store;
use Hyperf\Utils\ApplicationContext;
class MqttSpeakerService implements MqttServiceInterface
{
const TOPIC = 'test01';
/**
* @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'] = "懒族支付到账".floatval($order['money'])."";
// 获取终端ID
$order['to_client_id'] = Store::query()->where(['id' => $order['store_id']])->value('loudspeaker_imei');
// 发布订阅消息
$res = $this->publish($order['template'], self::TOPIC, $order['to_client_id']);
}
}
/**
* @inheritDoc
*/
public function publish(
$message,
$topic,
$toClientId = '',
$type = '',
$payId = '',
$curClientId = ''
) {
$client = new MQTTClient(env('MQTT_HOST'), env('MQTT_PORT'));
$client->setAuthentication(env('MQTT_NAME'), env('MQTT_PASS'));
$client->setDebug(true);
if (env('MQTT_CERT')) {
$client->setEncryption(env('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();
}
}