【类 型】:feat

【主	题】:地面控制端增加发送mqtt功能函数 更改订单时向小程序端订阅的“更新订单主题” 发送信息
【描	述】:
	[原因]:小程序端可以实时刷新订单情况
	[过程]:发送小程序用户id对应的主题  订阅到订单有变更时 小程序端刷新订单
	[影响]:
【结	束】

# 类型 包含:
# feat:新功能(feature)
# fix:修补bug
# docs:文档(documentation)
# style: 格式(不影响代码运行的变动)
# refactor:重构(即不是新增功能,也不是修改bug的代码变动)
# test:增加测试
# chore:构建过程或辅助工具的变动
This commit is contained in:
tk 2024-06-12 17:59:16 +08:00
parent e8f9a1cb4d
commit c60e68348f
4 changed files with 45 additions and 6 deletions

View File

@ -9,7 +9,3 @@ function makeTopicPrefix($openid)
{
return substr(md5($openid . date("j")), 0, 8); //用户id+当天日 加密 截取前8位
}
function demo()
{
echo "hello";
}

View File

@ -8,7 +8,6 @@ class IndexController extends Controller
{
public function index()
{
demo();
$this->display();
}
}

View File

@ -5,6 +5,10 @@ namespace MpApi\Controller;
use Think\Image;
use Org\ImageController\ImageController;
use PhpMqtt\Client\MqttClient;
use PhpMqtt\Client\Exceptions\MqttClientException;
use PhpMqtt\Client\ConnectionSettings;
class PlaneController extends PublicController
{
public function index()
@ -571,7 +575,10 @@ class PlaneController extends PublicController
} elseif ($_REQUEST['state'] == 'back') {
$data['back'] = $_REQUEST['val']; //改变订单状态
}
if ($orderDb->where($where)->save($data)) {
if ($orderDb->where($where)->save($data)) { //修改数据
$topicPrefix = makeTopicPrefix($order['openid']); //小程序端用户订阅主题的前缀 ps:订单对应的用户的openid算出来的
// 提醒小程序端 刷新订单列表
$this->publish('refreshOrderList/' . $topicPrefix, 1);
echo json_encode(array('status' => 1, 'msg' => '订单修改成功'));
} else {
echo json_encode(array('status' => 0, 'msg' => '订单修改失败'));

View File

@ -6,6 +6,10 @@ use Think\Controller;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use PhpMqtt\Client\MqttClient;
use PhpMqtt\Client\Exceptions\MqttClientException;
use PhpMqtt\Client\ConnectionSettings;
class PublicController extends Controller
{
//****************
@ -148,4 +152,37 @@ class PublicController extends Controller
echo json_encode(array('status' => 0, 'msg' => '登录异常'));
}
}
/**
* @description: 连接mqtt服务器 并向指定主题发布信息
* @param string $topic mqtt主题
* @param string $msg 要发布的主题
*/
protected function publish($topic, $msg)
{
$server = C('mqtt')['server']; // MQTT 代理地址
$port = C('mqtt')['port']; // MQTT 代理端口
$clientId = C('mqtt')['client_id']; // 客户端 ID
$username = C('mqtt')['username']; // 用户名(如果需要)
$password = C('mqtt')['password']; // 密码(如果需要)
try {
// 创建连接设置对象
$settings = (new ConnectionSettings)->setUsername($username)->setPassword($password);
// 实例化 MQTT 客户端
$mqtt = new MqttClient($server, $port, $clientId);
// 连接到 MQTT 代理
$mqtt->connect($settings);
// 检查是否连接成功
if ($mqtt->isConnected()) {
// 发布消息到指定的主题 ps:主题 信息 qos
$mqtt->publish($topic, $msg, 0);
// 断开连接
$mqtt->disconnect();
} else {
echo "连接失败";
}
} catch (MqttClientException $e) { //连接失败
echo "Could not connect to MQTT broker: " . $e->getMessage();
}
}
}