import mqtt from 'mqtt' import settings from '../settings.js' //全局属性 import store from '../store/index.js' export default { client: null, // mqtt连接 对象 host: settings.mqttHost, // mqtt服务器地址 options: { // mqtt服务器 参数配置 port: settings.mqttPort, connectTimeout: 3000, clientId: store.state.userInfo.topic_prefix, clean: true, keepalive: 60, username: settings.mqttUserName, password: settings.mqttPassword }, mqttConf, mqttDestroy, doSubscribe, publishFun } /** * @Description: mqtt对象初始化 */ function mqttConf() { if (!this.client) { // 链接mqtt this.client = mqtt.connect(this.host, this.options) // mqtt服务器中断 this.client.on('error', () => { console.warn('指令服务器异常中断') }) // 端口之后复连 this.client.on('reconnect', () => { console.warn('重新连接指令服务器') }) // 监听断开连接事件 this.client.on('offline', () => { console.warn('指令服务器异常中断') store.state.mqttState = false // 标记mqtt链接失败 掉线 }) } } /** * @description: 获取主题消息 * @param {string} topic 主题名称 * @param {fun} callBack 回调 传一个对象{topic订阅的主题,msg接收到主题的数据} 在父级给获取 */ function doSubscribe(topic, callBack) { // 订阅主题 this.client.on('connect', () => { // if (store.state.app.mqttState === false) { // console.log('成功连接指令服务器') // } // store.state.mqttState = true // 标记mqtt链接成功 在线 // 订阅一个主题 this.client.subscribe(topic, { qos: 2 }, err => { if (!err) { console.log(topic + '主题订阅成功') } else { console.warn(topic + '主题订阅失败') } }) }) // 获取订阅主题的消息 this.client.on('message', (topic, message) => { callBack({ topic: topic, msg: message.toString() }) }) } /** * @description: 向指定topic发送消息 * @param {*} topic 发送信息到的主题 不包括前缀 * @param {*} msg 要发送的信息 */ function publishFun(topic, msg) { // topic要保持一致 this.client.publish(topic, msg, { qos: 2 }) } /** * @Description: 销毁mqtt对象 */ function mqttDestroy() { if (this.client) { this.client.end() // 离开页面的时候 关闭mqtt连接 this.client = null } }