import mqtt from “mqtt”;
export default class mqttHandle {
constructor(subscribe) {
this.connect = {
endpoint: “/mqtt”,
host:‘123.249.38.211’,
port:‘8083’,
clean: true, // 清除会话
cleanSession: true,
connectTimeout: 7000, // 超时时间
reconnectPeriod: 7000, // 重连时间间隔
// 认证信息
clientId: ‘web’,
username: ‘web’,
password:‘piesat.com’
}
this.subscription = {
topic: subscribe, //需要传入数组的包含订阅的名称
qos: 2,
}
this.mqttClient = null;
}
/**
* 创建链接
* @returns client
*/
createConnect() {
//配置链接
const { …options } = this.connect;
const connectUrl = ws://${this.connect.host}:${this.connect.port}${this.connect.endpoint}
;
try {
this._client = mqtt.connect(connectUrl, options);
} catch (error) {
console.log("mqtt.connect error", error);
}
this._client.on("connect", () => {
console.log("Connection succeeded!");
});
this._client.on('reconnect', (error) => {
console.log('正在重连', error)
})
this._client.on("error", (error) => {
console.log("Connection failed", error);
});
//配置topic
// const { topic, qos } = this.subscription;
// this._client.subscribe(topic, { qos: qos }, (error, res) => {
// if (error) {
// console.log("Subscribe to topics error", error);
// return;
// }
// console.log("Subscribe to topics res", res);
// })
this.mqttClient = this._client;
return this.mqttClient;
}
/**
* @name:发布mqtt消息
* @msg:
* @param {*}
* @return {*}
*/
mqttPublish(isTopic) {
const topic = isTopic || this.subscription.topic;
this.client.publish(topic, JSON.stringify(this.message));
}
}
配置连接的时候非常频繁的处罚了重连回调,错误消息
Dashboard监控内容