jsy-app-static/utils/mqttUtil.js
2024-09-29 11:05:04 +08:00

106 lines
2.4 KiB
JavaScript
Raw Permalink 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.

import mqtt from "mqtt/dist/mqtt"
// import mqtt from "@/store/modules/mqtt.js"
import store from "@/store"
//封装一个类可直接cv
class MqttUtil {
//创建公共变量
static url //mqtt地址
static userId //userId
static clientId //clientId
static options //clientId
static client = null; //mqtt公共变量
//接收创建来的数据
constructor() {
this.url = import.meta.env.VITE_BASE_MQTT;
// this.userId = store.state.user.user.userId;
this.clientId = "mqtt_app_" + this.getUUID();
this.options = {
qos: 1, //QoS 级别
clean: false, // true: 清除会话, false: 保留会话
connectTimeout: 3000, // 超时时间
keepAlive: 60,
username: "app_client",
password: "app_client@2023",
clientId: this.clientId
}
}
//mqtt链接
link() {
if (this.client == null || this.client.connented == false) {
let client = mqtt.connect(this.url, this.options);
if (this.client == null) {
this.client = client;
this.client.on("connect", error => {
console.log("connect")
})
this.client.on("error", error => {
console.log("error")
})
this.client.on("reconnect", error => {
console.log("reconnect")
})
this.client.on("message", (topic, message) => {
console.log("message", message.toString())
})
}
}
}
//重新连接
reconnect() {
if (this.client.connected) {
this.client.end(); // 关闭当前连接
}
this.client.connect(this.options); // 重新连接
}
//结束链接
over() {
this.client.end();
this.client = null;
}
//订阅主题
subscribes(topic) {
this.client.subscribe(topic, error => {
if (error) {
console.error(`订阅主题失败:`, error)
} else {
console.log(`订阅主题成功`)
}
})
}
//取消订阅
unsubscribes(topic) {
this.client.unsubscribe(topic, error => {
if (!error) {
console.log("取消订阅成功")
} else {
console.log("取消订阅错误", topic)
}
})
}
//收到的消息
get() {
this.mqtt.client.on("message", (topic, message) => {
console.log("接受消息")
console.log("message", message.toString())
})
}
//发送消息
send(message) {
this.client.publish("test", JSON.stringify(message), res => {
console.log(res)
})
}
getUUID() {
function S4() {
return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
}
return (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4());
}
}
export default MqttUtil