This commit is contained in:
Iruka 2024-09-30 12:30:11 +08:00
parent c1f5e127b5
commit ec0e061cc9

View File

@ -16,7 +16,6 @@ import {
} from "@/uni_modules/zy-mqtt"; } from "@/uni_modules/zy-mqtt";
// #endif // #endif
//封装一个类可直接cv //封装一个类可直接cv
class MqttUtil { class MqttUtil {
//创建公共变量 //创建公共变量
@ -27,10 +26,10 @@ class MqttUtil {
static reconnectCount = 0; static reconnectCount = 0;
//接收创建来的数据 //接收创建来的数据
constructor(eventHandler) { constructor(messageEvent) {
this.eventHandler = eventHandler; this.messageEvent = messageEvent;
const url = import.meta.env.VITE_BASE_MQTT;
const url = import.meta.env.VITE_BASE_MQTT;
// #ifdef H5 // #ifdef H5
this.url = `mqtt://${url}`; this.url = `mqtt://${url}`;
// #endif // #endif
@ -40,14 +39,15 @@ class MqttUtil {
} }
//初始化参数 //初始化参数
init(userId) { init(userId) {
let clientId = `mqtt_app_${userId}_${this.getUUID()}`; this.userId = userId;
// let clientId = this.getClientId();
let username = "app_client"; let username = "app_client";
let password = "app_client@2023"; let password = "app_client@2023";
let keepalive = 10; //保持连接的心跳间隔,单位为秒。 let keepalive = 10; //保持连接的心跳间隔,单位为秒。
let connectTimeout = 30; //接超时的时间,单位为秒。 let connectTimeout = 30; //接超时的时间,单位为秒。
// #ifdef H5 // #ifdef H5
this.options = { this.options = {
clientId: clientId, // string 客户端的唯一标识符。 clientId: null, // string 客户端的唯一标识符。
username: username, // string 连接时的用户名。 username: username, // string 连接时的用户名。
password: password, // string 连接时的密码。 password: password, // string 连接时的密码。
keepalive: keepalive, // number 60 保持连接的心跳间隔,单位为秒。 keepalive: keepalive, // number 60 保持连接的心跳间隔,单位为秒。
@ -69,7 +69,7 @@ class MqttUtil {
// #ifdef APP-PLUS // #ifdef APP-PLUS
this.options = { this.options = {
host: this.url, // 主机ip host: this.url, // 主机ip
clientId: clientId, // 客户端id clientId: null, // 客户端id
userName: username, // 用户名 userName: username, // 用户名
password: password, // 密码 password: password, // 密码
heartBeat: keepalive, // 可选,默认60秒, 心跳 heartBeat: keepalive, // 可选,默认60秒, 心跳
@ -82,18 +82,27 @@ class MqttUtil {
}; };
// #endif // #endif
} }
//监听消息回调 //获取clientId
onEventHandler(topic, data) { getClientId() {
console.error("topic", topic);
console.error("data", data);
this.eventHandler(topic, data);
}
getUUID() {
function S4() { function S4() {
return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1); return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
} }
return (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4()); let UUID = (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4());
return `mqtt_app_${this.userId}_${UUID}`;
} }
//清理连接信息
cleanClient() {
// this.options.clientId = null;
this.client = null;
this.connected = false;
this.reconnectCount = 0;
}
//监听消息回调
onMessageEvent(topic, data) {
this.messageEvent(topic, data);
}
// #ifdef H5 // #ifdef H5
//mqtt链接 //mqtt链接
@ -101,19 +110,22 @@ class MqttUtil {
if (!this.options) { if (!this.options) {
this.init(userId); this.init(userId);
} }
this.client = mqtt.connect(this.url, this.options); if (this.connected) {
return;
}
if (!this.options.clientId) {
this.options.clientId = this.getClientId();
}
this.client = mqtt.connect(this.url, this.options);
this.client.on("connect", error => { this.client.on("connect", error => {
this.connected = this.client.connected && !this.client.reconnecting; this.connected = this.client.connected;
this.reconnectCount = 0; this.reconnectCount = 0;
console.log("connect:", this.client) console.log("connect:", this.client)
console.log("connect:", this.connected) console.log("connect:", this.connected)
}) })
this.client.on("reconnect", error => { this.client.on("reconnect", error => {
this.connected = this.client.connected && !this.client.reconnecting;
this.reconnectCount++; this.reconnectCount++;
console.log("reconnect:", this.client)
console.log(`reconnect_${this.reconnectCount}:`, this.connected)
}) })
this.client.on("error", error => { this.client.on("error", error => {
console.log("error", error) console.log("error", error)
@ -121,22 +133,23 @@ class MqttUtil {
this.client.on("message", (topic, message) => { this.client.on("message", (topic, message) => {
console.log("接受消息") console.log("接受消息")
console.log("message", message.toString()) console.log("message", message.toString())
this.onEventHandler(topic, message); this.onMessageEvent(topic, message);
}) })
this.client.on("close", () => { this.client.on("close", () => {
console.log("已断开连接1") console.log("已断开连接1")
this.client = null;
this.connected = false; this.connected = false;
this.reconnectCount = 0;
}); });
} }
//结束链接 //结束链接
over() { over() {
this.client.end(false, null, () => {}); this.client.end(false, null, () => {
console.log("over")
this.cleanClient();
});
} }
//订阅主题 //订阅主题
subscribes(topics) { subscribes(topics) {
if (!this.client || !this.connected) { if (!this.connected) {
return; return;
} }
console.log("subscribes", topics) console.log("subscribes", topics)
@ -150,7 +163,7 @@ class MqttUtil {
} }
//取消订阅 //取消订阅
unsubscribes(topics) { unsubscribes(topics) {
if (!this.client || !this.connected) { if (!this.connected) {
return; return;
} }
console.log("unsubscribes", topics) console.log("unsubscribes", topics)
@ -176,6 +189,13 @@ class MqttUtil {
if (!this.options) { if (!this.options) {
this.init(userId); this.init(userId);
} }
if (this.connected) {
return;
}
if (!this.options.clientId) {
this.options.clientId = this.getClientId();
}
// 先连接mqtt // 先连接mqtt
connect(this.options, (res) => { connect(this.options, (res) => {
console.log("connect", res); console.log("connect", res);
@ -192,10 +212,7 @@ class MqttUtil {
}) })
// 监听自动重新连接函数 // 监听自动重新连接函数
onReconnect((res) => { onReconnect((res) => {
console.log("onReconnect", res);
this.connected = isConnected();
this.reconnectCount++; this.reconnectCount++;
console.log("onConnectLost_${this.reconnectCount}:", this.connected)
}) })
} }
//结束链接 //结束链接
@ -204,16 +221,15 @@ class MqttUtil {
return; return;
} }
disConnect((res) => { disConnect((res) => {
console.log("接受消息:", res) console.log("disConnect:", res)
if (res.code == 200) { if (res.code == 200) {
this.reconnectCount = 0; this.cleanClient();
this.connected = isConnected();
} }
}) })
} }
//订阅主题 //订阅主题
subscribes(topics) { subscribes(topics) {
if (!isConnected()) { if (!this.connected) {
return; return;
} }
console.log("subscribes", topics) console.log("subscribes", topics)
@ -229,7 +245,7 @@ class MqttUtil {
} }
//取消订阅 //取消订阅
unsubscribes(topics) { unsubscribes(topics) {
if (!isConnected()) { if (!this.connected) {
return; return;
} }
console.log("unsubscribes", topics) console.log("unsubscribes", topics)