mqttHandler.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. import mqtt from "mqtt";
  2. import Vue from 'vue'
  3. var vm = new Vue();
  4. class mqttHandle {
  5. constructor(subscribe) {
  6. this.connect = {
  7. host: vm.mqttHost,
  8. port: vm.mqttPort,
  9. endpoint: "/mqtt",
  10. clean: true, // 保留会话
  11. cleanSession: true,
  12. connectTimeout: 7000, // 超时时间
  13. reconnectPeriod: 7000, // 重连时间间隔
  14. // 认证信息
  15. clientId: Number(new Date()).toString(),
  16. username: "emqx_t",
  17. password: "emqx_t",
  18. }
  19. this.subscription = {
  20. topic: subscribe, //需要传入数组的包含订阅的名称
  21. qos: 2,
  22. }
  23. this.mqttClient = null;
  24. }
  25. /**
  26. * 创建链接
  27. * @returns client
  28. */
  29. createConnect() {
  30. //配置链接
  31. const { host, port, endpoint, ...options } = this.connect;
  32. const connectUrl = `ws://13.229.167.76:1884/mqtt`;
  33. try {
  34. this._client = mqtt.connect(connectUrl, options);
  35. } catch (error) {
  36. console.log("mqtt.connect error", error);
  37. }
  38. this._client.on("connect", () => {
  39. console.log("Connection succeeded!");
  40. });
  41. this._client.on('reconnect', (error) => {
  42. console.log('正在重连', error)
  43. })
  44. this._client.on("error", (error) => {
  45. console.log("Connection failed", error);
  46. });
  47. //配置topic
  48. const { topic, qos } = this.subscription;
  49. this._client.subscribe(topic, { qos: qos }, (error, res) => {
  50. if (error) {
  51. console.log("Subscribe to topics error", error);
  52. return;
  53. }
  54. this.subscribeSuccess = true;
  55. // console.log("Subscribe to topics res", res[0].qos, res[0].topic);
  56. });
  57. this.mqttClient = this._client;
  58. return this.mqttClient;
  59. }
  60. }
  61. export default mqttHandle;