83 lines
2.4 KiB
JavaScript
83 lines
2.4 KiB
JavaScript
import mqtt from "mqtt";
|
|
import Vue from 'vue'
|
|
var vm = new Vue();
|
|
// var ip = window.location.host.split(":")[0];
|
|
// console.log("ip",ip)
|
|
class mqttHandle {
|
|
constructor() {
|
|
this.connect = {
|
|
// host: vm.mqttHost,
|
|
// port: vm.mqttPort,
|
|
endpoint: "/mqtt",
|
|
clean: true, // 保留会话
|
|
cleanSession: true,
|
|
connectTimeout: 7000, // 超时时间
|
|
reconnectPeriod: 7000, // 重连时间间隔
|
|
host: '138.227.111.141',
|
|
port: '8083',
|
|
// 认证信息
|
|
clientId: Number(new Date()).toString(),
|
|
// clientId: 'JBFY',
|
|
username: "admin",
|
|
password: "123456",
|
|
}
|
|
// this.subscription = {
|
|
// topic: subscribe, //需要传入数组的包含订阅的名称
|
|
// qos: 0,
|
|
// }
|
|
this.mqttClient = null;
|
|
}
|
|
/**
|
|
* 创建链接
|
|
* @returns client
|
|
*/
|
|
createConnect(onConnected) {
|
|
//配置链接
|
|
// console.log("connectUrl",connectUrl)
|
|
const { host, port, endpoint, ...options } = this.connect;
|
|
console.log("this.connect.host", this.connect.host)
|
|
const connectUrl = 'ws://138.227.208.100:1884/mqtt';
|
|
//const connectUrl = 'ws://172.16.1.253:1884/mqtt';
|
|
if (this.mqttClient == undefined) {
|
|
this.mqttClient = mqtt.connect(connectUrl, options);
|
|
this.mqttClient.on("connect", () => {
|
|
console.log("Connection succeeded!");
|
|
onConnected();
|
|
});
|
|
this.mqttClient.on('reconnect', (error) => {
|
|
console.log('正在重连')
|
|
})
|
|
this.mqttClient.on("error", (error) => {
|
|
console.log("Connection failed");
|
|
});
|
|
|
|
}
|
|
|
|
return this.mqttClient;
|
|
|
|
// try {
|
|
|
|
|
|
// } catch (error) {
|
|
// console.log("mqtt.connect error", error);
|
|
// }
|
|
|
|
}
|
|
|
|
MySub(subscriptions) {
|
|
this.mqttClient.subscribe(subscriptions, { qos: 0 }, (err) => {
|
|
if (!err) {
|
|
console.log("订阅成功:" + subscriptions);
|
|
|
|
} else {
|
|
console.log('消息订阅失败!' + subscriptions)
|
|
}
|
|
});
|
|
}
|
|
|
|
|
|
MyUnSub(subscription) {
|
|
|
|
}
|
|
}
|
|
export default mqttHandle; |