中台MQTT
路径:/src/utils/MQTT.js
说明:此文件中两个类,MQTT为普通的mqtt的封装,不做说明。DataCenterMQTT为从中台获取连接MQTT的ClientID,用户名、密码等。
使用
调用DataCenterMQTT.getMQTT(),请求用户配置并返回MQTT实例。
this.mqtt = await DataCenterMQTT.getMQTT()
//连接成功后注册主题
this.mqtt.connect(e => {
this.mqtt.subscribe(topics)
})
// 收到数据后的回调
this.mqtt.onMessageArrived(message => {
const info = JSON.parse(message.payloadString)
console.log('onMessageArrived:', info)
this.onMessageArrived(info)
})
DataCenterMQTT代码示例
注意,1.dataCenterApi中的secret目前为写死,后期可能需要更新配置。2.http和https的配置有所不同,目前为了适配测试环境和正式环境所写的代码是临时的,需要根据将来的需求改动。
export class DataCenterMQTT {
constructor() {
return this
}
static getMQTT() {
if (typeof DataCenterMQTT.mqtt === 'object') {
return Promise.resolve(DataCenterMQTT.mqtt)
}
return new Promise((resolve, reject) => {
dataCenterApi
.getAuth('NjM1MjU5NTM1MzE4MzgwNTQ1', 'OUdsZVBwSTQ4ZjYzNTI1OTUzNTMxODM4MDU0Ng')
.request()
.then(
res => {
const data = res.data
const ws = data.ws[0]
const host = ws.split(':')[0]
const port = ws.split(':')[1]
var config = {
ClientID: data.clientId,
Username: data.username,
Password: data.password
}
if (window.location.href.indexOf('https') === 0) {
console.log('监测到是https,MQTT开启SSL')
config.Host = 'iot.acrel.cn'
config.Port = Number(443)
config.useSSL = true
} else {
config.Host = host
config.Port = Number(port)
config.useSSL = false
}
console.log('mqttConfig######:', config)
DataCenterMQTT.mqtt = new MQTT(config)
resolve(DataCenterMQTT.mqtt)
},
err => {
reject(err)
}
)
})
}
}