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) { //配置链接 const { host, port, endpoint, ...options } = this.connect; console.log("this.connect.host", this.connect.host) const connectUrl = 'ws://138.227.111.141:8083/mqtt'; // const connectUrl = `ws://${this.connect.host}:${this.connect.port}`; // if (!client.connected) { // client.on('connect', function () { // console.log('连接成功') // }) // } else { // client.publish('test/clientE', ms, {'qos': 2}, function (err) { // if (err) { // console.log(err) // } // }) // } 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"); }); //配置topic // const { topic, qos } = this.subscription; // console.log(topic, qos,'topic, qos'); // this._client.subscribe(topic, { qos: qos }, (error, res) => { // if (error) { // console.log("Subscribe to topics error", error); // return; // } // this.subscribeSuccess = true; // console.log("Subscribe to topics res", res[0].qos, res[0].topic); // }); } 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;