mqtt安装
npm install mqtt --save
import mqtt from 'mqtt'
interface ConfigOption {
clientId: string,
keepalive: number,
reconnectPeriod: number
}
export default class MQTT {
// 配置
private options: ConfigOption = {
clientId: 'mqttjs_' + Math.random().toString(16).substr(2, 8),
keepalive: 60,
reconnectPeriod: 600
}
// 实例
private mqttClient: any = '';
// 连接状态 成功true 掉线失败 false
private state: Boolean = false;
// 事件
private events: string[] = []
// 主题
private topicList: string[] = []
constructor(MQTT_URL = "ws://xxxxxxx") {
// 初始化配置
this.mqttClient = mqtt.connect(MQTT_URL, this.options);
// 连接状态
this.state = false;
// 事件
this.events = ["connect", "reconnect", "disconnect", "error"]
// 状态监听
this.on()
}
// 监听方法
on(success = () => {}, error = () => {}) {
let {events} = this;
for(let e of events) {
this.mqttClient.on(e, (event: any) => {
switch(e) {
case "connect": //连接成功
this.state = true;
success();
break;
case "reconnect": //重新连接
this.state = true;
success();
break;
case "disconnect": //断开连接
this.state = false;
console.error('mqtt断开连接', event)
error();
break;
case "error": // 连接出错
this.state = false;
console.error('连接出错', event)
error();
break;
}
})
}
}
// 接受消息通知
onMessage(topicValue: string, cb?: any) {
this.mqttClient.on("message", (topic: string, uint8Array: any) => {
if(topicValue == topic) {
const decoder = new TextDecoder();
const message = decoder.decode(uint8Array);
cb&&cb(message)
}
})
}
// 发布
publish(topic: string, message: string, cb?: any) {
if (!this.state) {
console.log('未连接')
return
}
this.mqttClient.publish(topic, message, {qos: 1},(err: any) => {
if(!err) {
console.log('主题'+ topic + "发布成功")
cb&&cb()
}
})
}
// 订阅
subscribe(topic: string, cb?: any) {
// 判断连接状态
let {topicList} = this;
if(this.state) {//成功
if(!topicList.includes(topic)) {//添加
this.mqttClient.subscribe([...topicList, topic], {}, (e: any) => {
cb&&cb(e)
this.topicList.push(topic);
console.log(`主题${topic}订阅成功!`)
})
} else {
console.log(`主题${topic}已订阅!`)
cb&&cb()
}
} else {//掉线状态
console.error('未连接,订阅失败')
}
}
// 取消订阅
unsubscribe(topic: string, cb?: any) {
// 判断连接状态
let {topicList} = this;
if(this.state) {//成功
let index = topicList.findIndex(item => item == topic) as number;
if(index !== -1) {
this.mqttClient.unsubscribe(topic, (e: any)=> {
console.log(`该主题${topic}取消订阅成功!`)
cb&&cb(e)
this.topicList.splice(index, 1);
})
} else {
console.log(`该主题${topic}暂未订阅!`)
}
} else {//掉线状态
console.error('未连接,取消订阅失败')
}
}
// 断开关闭
unconnect() {
if(!this.mqttClient) return
this.mqttClient.end()
this.topicList = []
this.state = false;
this.mqttClient = null
console.log('服务器已断开连接!')
}
}