javascript 连接 mqtt 通过 paho-mqtt
Paho JavaScript Client是使用Javascript编写的基于MQTT浏览器的客户端库,该库使用WebSockets连接到MQTT Broker。
通过node 安装
npm install paho-mqtt
initMqtt(params) {
const t = {}
t.i = params.msgTopicName
t.c = 0
t.t = 3
t.p = 1
const state = {}
const message = new Paho.Message(JSON.stringify(t))
message.destinationName = params.willTopicName // willTopicName
const connectOptions = {}
// connectParams.timeout = this.globalData.connectParams.connectionTimeout; 默认30s
connectOptions.userName = process.env.VUE_APP_MQTT_USER//连接mqtt用户名
connectOptions.password = process.env.VUE_APP_MQTT_PASS//连接mqtt密码
console.log(connectOptions, 'connectOptions')
connectOptions.willMessage = message //遗嘱消息
connectOptions.keepAliveInterval = 10//this.globalData.connectParams.keepAliveInterval; //心跳保持时间
connectOptions.cleanSession = params.cleanSession //断开连接时是否要清除session
connectOptions.reconnect = false //设置如果连接丢失,客户端是否自动尝试重新连接到服务器
//连接成功回调
connectOptions.onSuccess = e => {
console.log('mqtt连接成功 - onConnect')
state.mqtt.isconnect = true
state.mqtt.limit = 0
state.client.subscribe(params.msgTopicName) //pt_1234
// var t = '上线';
const t = {}
t.i = params.msgTopicName
t.c = 0
t.t = 0
t.p = 1
const message = new Paho.Message(JSON.stringify(t))
message.destinationName = params.statusTopicName // statusTopicName
//发送上线消息
state.client.send(message)
}
//连接失败回调
connectOptions.onFailure = e => {
state.mqtt.isconnect = false
console.log('mqtt - disConnect', e)
if (e.errorCode === 8) {
clearTimeout(state.mqtt.timer)
if (state.mqtt.limit < 12) {
state.mqtt.timer = setTimeout(() => {
dispatch('mqtt/initMqtt', params)
}, 3000)
state.mqtt.limit++
}
}
}
const url = 'ws://' + params.host + (params.port ? (':' + params.port) : '') + '/mqtt'
state.client = new Paho.Client(url, params.clientId)
console.log(url, params.clientId)
state.client.onConnectionLost = responseObject => {
// wx.closeSocket();
state.mqtt.isconnect = false
console.log('mqtt失去连接 - responseObject:' + responseObject, state.client)
if (responseObject.errorCode !== 0) {
console.log('onConnectionLost:' + responseObject.errorMessage)
}
}
state.client.onMessageArrived = message => {
console.log('mqtt消息到达 - onMessageArrived:' + message.payloadString, message)
const _message = JSON.parse(message.payloadString)
//会话结束消息
if (_message.c === 1 && _message.t === 1) {
} else {
// var chatkey = this.globalData.connectParams.msgTopicName + '_' + message.from.id
}
_message.update = true
}
console.log(connectOptions, 'connectOptions')
state.client.connect(connectOptions)
}