mqtt使用方法

时间:2025-04-02 21:59:49
  • subscrib(topic) {
  • // topic = 'aibox/trash-ai-edge-02/event'
  • let that = this
  • let mqtt = require('mqtt')
  • let now = new Date()
  • let number = now.getTime()
  • let clientId = 'cid_' + number
  • //开启mqtt链接
  • this.client2 = mqtt.connect(this.mqtt.config.url, {
  • port: this.mqtt.config.port,
  • clientId: clientId,
  • username: this.mqtt.config.username,
  • password: this.mqtt.config.password,
  • clean: false
  • })
  • //监听是否连接成功
  • this.client2.on('connect', () => {
  • console.log('连接成功!')
  • })
  • //订阅后端给你发的字段 在on里面接收
  • that.client2.unsubscribe([topic])//先取消订阅,防止重复
  • that.client2.subscribe([topic], (error, res) => {
  • if (error) {
  • console.log('订阅失败', error)
  • }
  • console.log('订阅成功', res)
  • })
  • //接收消息
  • console.log('订阅topic是', topic)
  • let messagearr = []//该数组要在接收数据前定义,不然容易每次只有最新的数据
  • //监听订阅的消息,当有消息发过来,该函数便执行 ,回调函数中message则是收到的数据
  • that.client2.on('message', (topic, message) => {
  • // debugger
  • let messageitem = {}
  • messageitem = JSON.parse(message.toString())//收到的数据是一堆数字,要toString才能变成想要的样子,如果需要的是对象格式,记得
  • console.log('接收到的信息是', messageitem, message.toString())
  • //将收到的对象 处理message
  • messageitem.time = formatDate(new Date(messageitem.time), 'yyyy-MM-dd HH:mm:ss')
  • for (let i = 0; i < that.eventtypes.length; i++) {
  • if (that.eventtypes[i].event == messageitem.event[0]) {
  • messageitem.event = that.eventtypes[i].eventName
  • }
  • }
  • messagearr.push(messageitem)//由于数据是实时的,每次发过来一个对象,需将他们放入数组中使用
  • console.log('messageitem', messageitem, 'messagearr', messagearr)
  • console.log('arr', messagearr)
  • that.message = messagearr
  • })
  • },