Files
movecheck/src/utils/sendMqtt.js
2025-09-27 14:59:48 +08:00

162 lines
4.0 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// MQTT工具包 - 兼容H5、App、微信小程序
// 参考https://blogs.seecsdn.cn/online/2025-09-27/0ecf1401e23b25be5f8c7e4377d8b5dd.html
let mqtturl;
// #ifdef H5
mqtturl = "ws://122.51.194.184:8083/mqtt";
import * as mqtt from "mqtt/dist/mqtt.min.js";
// #endif
// #ifdef APP-PLUS || MP-WEIXIN
mqtturl = "wx://122.51.194.184:8083/mqtt";
import * as mqtt from "mqtt/dist/mqtt.min.js";
//#endif
// #ifdef MP-ALIPAY
mqtturl = "alis://122.51.194.184:8083/mqtt";
import * as mqtt from "@/utils/mqtt.min.js";
//#endif
function messageid2() {
// 2位随机数
return Math.floor(Math.random() * (99 - 10)) + 10;
}
var client;
// 创建MQTT连接
const createMqtt = () => {
let options = {
keepalive: 30,
clientId: `mobile-inspection-system-${messageid2()}`, // 客户端ID
protocolId: 'MQTT',
username: "dmbroker",
password: "qwer1234",
protocolVersion: 4,
clean: true,
reconnectPeriod: 1000, // reconnectPeriod为1000毫秒这意味着在连接丢失之后客户端将在1秒后尝试重新连接。
connectTimeout: 5000, // 5s超时时间 意味着mqtt-reconnect函数5秒钟触发一次
topic: "HDYDCJ_01_DOWN",
rejectUnauthorized: false,
// #ifdef MP-ALIPAY
my: my,//注意这里的my
//#endif
}
try {
if (!client) {
console.log('🔧 开始创建MQTT连接...');
console.log('🔧 MQTT URL:', mqtturl);
console.log('🔧 连接选项:', options);
client = mqtt.connect(mqtturl, options);
initEventHandleMqtt(options.topic);
}
} catch (e) {
console.error('❌ MQTT连接创建失败:', e);
}
};
//建立连接
const initEventHandleMqtt = (topicUrl) => {
// 当连接成功时触发
client.on("connect", function() {
uni.hideLoading();
console.log("✅ MQTT连接成功");
//订阅主题
client.subscribe(topicUrl, function(err) {
if (err) {
console.error("❌ MQTT订阅主题失败:", err);
} else {
console.log("✅ MQTT订阅主题成功:", topicUrl);
}
});
});
//如果mqttws订阅主题成功那么这里就是当接收到自己订阅主题的处理逻辑
client.on("message", function(topic, message) {
try {
console.log('📨 收到MQTT消息:');
console.log('主题:', topic);
console.log('消息内容:', message.toString());
// 获取信息
const mqttData = JSON.parse(message.toString());
console.log('📋 解析后的数据:', mqttData);
// 传递信息
uni.$emit("mqttData", mqttData);
} catch (error) {
console.error('❌ 处理MQTT消息失败:', error);
console.error('原始消息:', message.toString());
}
});
// 当断开连接后,经过重连间隔时间重新自动连接到 Broker 时触发
client.on('reconnect', function() {
console.log('🔄 MQTT重新连接中...');
uni.showLoading({
title: "重新连接"
});
});
// 当客户端无法成功连接时或发生解析错误时触发,参数 error 为错误信息
client.on("error", function(err) {
console.error('❌ MQTT连接错误:', err);
uni.showToast({
title: 'MQTT连接错误',
icon: 'error',
duration: 3000
});
});
// 在收到 Broker 发送过来的断开连接的报文时触发
client.on('disconnect', function() {
console.log('⚠️ MQTT连接断开');
});
// 在断开连接以后触发
client.on("close", function() {
console.log('🔌 MQTT连接关闭');
});
// 当客户端下线时触发
client.on("offline", function() {
console.log('📴 MQTT客户端离线');
});
};
//强制断开Mqtt
const closeMqtt = () => {
if (client) {
console.log('🔌 强制断开MQTT连接');
client.end();
client = null;
}
};
// 使用pingResp心跳判断客户端和服务端是否还在连接着
const judgeBeat = () => {
if (client && client.pingResp === false) {
console.log('💔 MQTT心跳停止准备重连');
uni.showLoading({
title: "心跳停止,等待重连..."
});
closeMqtt();
createMqtt();
}
};
// 获取连接状态
const getConnectionStatus = () => {
return client && client.connected;
};
export {
createMqtt,
closeMqtt,
judgeBeat,
getConnectionStatus,
client,
}