vue 中ts实现mqtt封装

安装mqtt
npm i mqtt
untils/mqtt.ts
import mqtt from 'mqtt'

// 声明mqtt的options数据包类型
export interface MqttconnecOption extends mqtt.IClientOptions {}

// 为方便外部组件处理message,声明消息回调方法类型
export declare type OnMessageFun = (topic: string, payload: Buffer) => void

// 声明mqtt主题配置
interface Topic {
  topic: string
  qos: 0 | 1 | 2
}


export class Mqtt {
  mqclient!: mqtt.MqttClient //mq连接实例
  brokerHost: string //连接地址
  // brokerPort: number //这里可以自定义端口,看自己怎么定义
  subscribeTopics: Array<Topic> // 订阅的主题数组
  subscribeCallbacks: Map<string, OnMessageFun> //订阅消息的回调

  constructor(host?: string | any, port?: number | any) {
    this.brokerHost = host
    // this.brokerPort = port

    this.subscribeTopics = new Array<Topic>()
    this.subscribeCallbacks = new Map<string, OnMessageFun>()
  }

  /**
   * @description: 订阅主题
   * @param {*}
   * @return {*}
   */

  public subscribe(topic: string, qos: 0 | 1 | 2): void {
    this.subscribeTopics.push({ topic, qos })
    if (this.is_connect()) {
      this.mqclient.subscribe(topic, { qos: qos }, error => {
       if (!error) {
         console.log('success')
       } else {
         console.log('fail')
       }
     })
  }

  /**
   * @description: 判断是否已经连接mq
   * @param {*}
   * @return {*}
   */
  public is_connect(): boolean {
    return this.mqclient.connected === true
  }

  /**
   * @description: 消息数据回调方法
   * @param {*}
   * @return {*}
   */

  public message_callback(topicPatten: string, cb: OnMessageFun) {
    this.subscribeCallbacks.set(topicPatten, cb)
  }

  /**
   * @description: 连接方法
   * @param {MqttconnecOption} options:mqtt连接参数体
   * @return {*}
   */

  public connect(options: MqttconnecOption) {
    this.mqclient = mqtt.connect(`${this.brokerHost}`, options)

    // 连接
    this.mqclient.on('connect', () => {
      console.log('Connection succeeded!')
      for (let i = 0; i < this.subscribeTopics.length; i++) {
        const el = this.subscribeTopics[i]
        this.mqclient.subscribe(el.topic, { qos: el.qos },error => {
        	if (!error) {
            console.log('success')
	        } else {
	        console.log('fail')
	        }
        })
      }
    })
    // 消息
    this.mqclient.on('message', (topic: string, payload: Buffer) => {
      console.log('Connection message!')
      this.mqclient
      this.subscribeCallbacks.forEach((val, key) => {
        if (topic.indexOf(key) !== -1) {
          val(topic, payload)
        }
      })
    })

    // 重连
    this.mqclient.on('reconnect', () => {
      console.log('reconnect')
    })

    // 错误
    this.mqclient.on('error', (err: Error) => {
      console.log('Connection error!')
      console.log('错误信息' + err)
    })

    // 离线
    this.mqclient.on('offline', (err: Error) => {
      console.log('offline')
    })
  }
  /**
   * @description: 数据推送  我们数据推送采用http,因为中间要翻译
   * @param {string} topic
   * @param {string} message
   * @param {0} qos
   * @return {*}
   */
  // public publish(topic: string, message: string, qos: 0 | 1 | 2) {
  //   this.mqclient.publish(topic, message, { qos: qos, retain: false })
  // }
}
组件使用
  • 引入
import { Mqtt } from '@/utils/mqtt'
  • 定义mq队列
mqttList: new Array<Mqtt>() as Array<Mqtt>
  • 使用
 // 数据处理
      dealMessage(topic: string, payload: Buffer) {
        console.log(`data: ${topic}=>${payload.toString()}`)
      },

      // 数据包处理函数
      dealPackage(topic: string, payload: Buffer) {
        console.log(`rx: ${topic}=>${payload.toString()}`)
      },

      // 连接MQTT服务器
      connectMqtt(
        host: string,
        username: string,
        password: string,
        clean: boolean = true,
        id?: string
      ) {
        const mq = new Mqtt(host)
        mq.connect({
          username,
          password,
          clean,//离线时是否接收 QoS 1 和 2 的消息 false 为接收,true为不接收
          reconnectPeriod: 5000 //重连时间间隔
        })
        // 订阅主题 /topicName/#  #通配符  匹配以/gb212/开头的主题
        mq.subscribe('/topicName/#', 0)
        // 设置主题 /topicName/data 的消息回调
        mq.message_callback('/topicName/topic1', methods.dealMessage.bind(this))
        // 设置主题 /topicName/rx 的消息回调
        mq.message_callback('/topicName/topic2', methods.dealPackage.bind(this))
        // 将Mqtt变量mq放到Mqtt客户端列表中
        state.mqttList.push(mq)
      },
  • 在需要调用的地方调用连接方法初始化
  	methods.connectMqtt(mqUrl, mqUsername, mqPassword)
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值