uniapp+小程序+mqtt封装+完整代码

一、小程序下载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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值