安装mqtt
npm i mqtt
untils/mqtt.ts
import mqtt from 'mqtt'
export interface MqttconnecOption extends mqtt.IClientOptions {}
export declare type OnMessageFun = (topic: string, payload: Buffer) => void
interface Topic {
topic: string
qos: 0 | 1 | 2
}
export class Mqtt {
mqclient!: mqtt.MqttClient
brokerHost: string
subscribeTopics: Array<Topic>
subscribeCallbacks: Map<string, OnMessageFun>
constructor(host?: string | any, port?: number | any) {
this.brokerHost = host
this.subscribeTopics = new Array<Topic>()
this.subscribeCallbacks = new Map<string, OnMessageFun>()
}
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')
}
})
}
public is_connect(): boolean {
return this.mqclient.connected === true
}
public message_callback(topicPatten: string, cb: OnMessageFun) {
this.subscribeCallbacks.set(topicPatten, cb)
}
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')
})
}
}
组件使用
import { Mqtt } from '@/utils/mqtt'
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()}`)
},
connectMqtt(
host: string,
username: string,
password: string,
clean: boolean = true,
id?: string
) {
const mq = new Mqtt(host)
mq.connect({
username,
password,
clean,
reconnectPeriod: 5000
})
mq.subscribe('/topicName/#', 0)
mq.message_callback('/topicName/topic1', methods.dealMessage.bind(this))
mq.message_callback('/topicName/topic2', methods.dealPackage.bind(this))
state.mqttList.push(mq)
},
methods.connectMqtt(mqUrl, mqUsername, mqPassword)