web123456

How to use mqtt

  • 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
  • //Open mqtt link
  • 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
  • })
  • // Listen to whether the connection is successful
  • this.client2.on('connect', () => {
  • console.log('Connected successfully!')
  • })
  • //Subscribe to the fields sent to you by the backend and receive them in the on
  • that.client2.unsubscribe([topic])//Unsubscribe first to prevent duplication
  • that.client2.subscribe([topic], (error, res) => {
  • if (error) {
  • console.log('Subscription failed', error)
  • }
  • console.log('Subscription Successfully', res)
  • })
  • //Receive message
  • console.log('Subscribe to topic is', topic)
  • let messagearr = []//The array must be defined before receiving data, otherwise it will be easy to have only the latest data every time
  • // Listen to the subscribed message. When a message is sent, the function will be executed. The message in the callback function is the received data
  • that.client2.on('message', (topic, message) => {
  • // debugger
  • let messageitem = {}
  • messageitem = JSON.parse(message.toString())//The data received is a bunch of numbers. You need to toString to become what you want. If the object format is needed, remember
  • console.log('The information received is', messageitem, message.toString())
  • // Process the received object 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)// Since the data is real-time, each time an object is sent, they need to be put into the array to use
  • console.log('messageitem', messageitem, 'messagearr', messagearr)
  • console.log('arr', messagearr)
  • that.message = messagearr
  • })
  • },