一、小程序下载mqtt
npm install mqtt@4.1.0
目前这个版本使用没有问题
二、封装
import mqtt from 'mqtt/dist/mqtt';
// import * as mqtt from 'mqtt/dist/mqtt'; // 直接使用 *
class MQTT {
constructor({ clientId, cleanSession = false, keepAlive = 60 }) {
this.url = 'wxs://mqtt.zh-zhsq.com:8084/mqtt'; // 写死的 URL
this.clientId = clientId;
this.username = ''; // 写死的用户名
this.password = ''; // 写死的密码
this.cleanSession = cleanSession; // 默认值
this.keepAlive = keepAlive; // 默认值
this.client = null;
}
// 初始化 MQTT
init() {
const options = {
clean: this.cleanSession, // 使用 cleanSession 设置
clientId: this.clientId,
username: this.username, // 使用写死的用户名
password: this.password, // 使用写死的密码
connectTimeout: 4000, // 超时时间
keepalive: this.keepAlive, // 使用 keepAlive 设置
};
this.client = mqtt.connect(this.url, options);
this.client.on('connect', () => {
console.log("连接成功",this.client);
});
this.client.on('error', (error) => {
console.error('MQTT连接错误:', error);
});
this.client.on('reconnect', (error) => {
console.log('正在重新连接:', error,this.client);
});
}
// 订阅主题
subscribe(topic) {
this.client.subscribe(topic, (error) => {
if (!error) {
console.log(`已订阅新主题111: ${topic}`);
} else {
console.log(`订阅失败: ${topic}`, error);
}
});
}
// 取消订阅
unsubscribe(topic) {
this.client.unsubscribe(topic, (error) => {
if (!error) {
console.log(`已取消订阅11111: ${topic}`);
} else {
console.log(`取消订阅失败: ${topic}`, error);
}
});
}
// 接收消息
get(callback) {
this.client.on('message', callback);
}
// 断开连接
over() {
if(this.client){
this.client.end();
console.log("断开mqtt连接");
}
}
}
export default MQTT;
三、使用
import MQTT from '../../pagesMy/utils/mqtt.js';
unsubscribeMqtt() {
if (this.mqttClient && this.elders && this.elders.length > 0) {
const privatekey = this.res.Ext.privatekey;
this.elders.forEach(elder => {
if (elder.id) {
const topic = `zh-ylgl/ypt/${privatekey}/${elder.id}`;
this.mqttClient.unsubscribe(topic);
}
});
}
},
reconnctmqtt() {
this.mqttClient = new MQTT({
clientId: "zhyl_" + this.res.Ext.privatekey,
});
this.mqttClient.init();
// 连接 MQTT 并订阅指定的主题
console.log(this.res.Ext.privatekey);
const privatekey = this.res.Ext.privatekey;
// 遍历所有老人,订阅他们各自的主题
if (this.elders && this.elders.length > 0) {
this.elders.forEach(elder => {
if (elder.id) {
const topic = `zh-ylgl/ypt/${privatekey}/${elder.id}`;
this.mqttClient.subscribe(topic);
}
});
} else {
console.warn("没有老人数据,无法订阅 MQTT 主题");
}
// 接收消息,使用回调函数处理
this.mqttClient.get((topic, message) => {
console.log(`收到来自 ${topic} 的消息:`, JSON.parse(message.toString()));
const message1 = JSON.parse(message.toString());
if (message1.type === "breathing_heart_rate") {
// 处理呼吸心率数据
}
});
}, onUnload() {
this.unsubscribeMqtt();
},
onHide() {
this.unsubscribeMqtt();
},
进页面mqtt连接订阅,出页面断开mqtt