import mqtt from "mqtt"; import Vue from 'vue' var vm = new Vue(); class mqttHandle { constructor() { this.connect = { // host: vm.mqttHost, // port: vm.mqttPort, endpoint: "/mqtt", clean: true, // 保留会话 cleanSession: true, connectTimeout: 7000, // 超时时间 reconnectPeriod: 7000, // 重连时间间隔 host:'172.16.1.51', port: '7788', // 认证信息 clientId: Number(new Date()).toString(), // clientId: newName, 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://175.27.191.156:10083/mgtt'; // 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._client.subscribe('img'+this.number, { qos: 0 }); // this._client.subscribe('stream'+this.number, { qos: 0 }); // this._client.subscribe('trajectory'+this.number, { qos: 0 }); // this._client.subscribe('detection'+this.number, { qos: 0 }); // this._client.subscribe('img0', { qos: 0 }); // this._client.subscribe('stream0', { qos: 0 }); // this._client.subscribe('trajectory0', { qos: 0 }); // this._client.subscribe('detection0', { qos: 0 }); }); 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) { //['hert','img0','img1','img2','img3','img4','img5','img6','img7'] this.mqttClient.subscribe(subscriptions, { qos: 0 }, (err)=> { if (!err) { console.log("订阅成功:"+subscriptions); } else { console.log('消息订阅失败!'+subscriptions) } }); } MyUnSub(subscription) { } } export default mqttHandle;