人间熙攘,好久不见

vuePress-theme-reco Magic    2017 - 2023
人间熙攘,好久不见 人间熙攘,好久不见

Choose mode

  • dark
  • auto
  • light
Home
Category
  • tools
  • Zsh
  • iTerm2
  • Front-end
  • 版本控制-Git
  • Rust
  • skia-safe
  • 第三方对接
  • MQTT
  • Powershell
  • python
  • MD5
  • SHA1
  • wsl2
Tags
TimeLine
GitHub
  • Github (opens new window)
  • Before (opens new window)
author-avatar

Magic

23

文章

15

标签

Home
Category
  • tools
  • Zsh
  • iTerm2
  • Front-end
  • 版本控制-Git
  • Rust
  • skia-safe
  • 第三方对接
  • MQTT
  • Powershell
  • python
  • MD5
  • SHA1
  • wsl2
Tags
TimeLine
GitHub
  • Github (opens new window)
  • Before (opens new window)

MQTT.js

vuePress-theme-reco Magic    2017 - 2023

MQTT.js

Magic 2023-04-17 MQTT

MQTT.js

# 官网

  • emqx MQTT (opens new window)
  • GitHub (opens new window)

# 注意事项

  • 开启 Client 放在全局入口处,只连接一次 (Vue):
  const onConnect = (cb?: () => void) => {
      if (!Vue.prototype.PahoMQTTClient) {
        let PahoMQTTClient = new window.mqtt.connect(`${WebSocket_URL}`, {
          // 超时时间
          connectTimeout: 4000,
          // 认证信息
          clientId,
          username: mqttUserName,
          password: mqttPassword,
          // 心跳时间
          keepalive: 60,
          clean: true,
        });
        PahoMQTTClient.on('connect', () => {
          console.log('MQTT onConnect--- success');
          if (timer) clearTimeout(timer);
          cb && cb();
        });
        PahoMQTTClient.on('reconnect', (err) => {
          console.log('MQTT onConnect--- reconnect', err)
        });
        PahoMQTTClient.on('error', (err) => {
          console.log('MQTT onConnect--- error', err);
          if (timer) clearTimeout(timer);
          PahoMQTTClient?.end(true);
          PahoMQTTClient = null;
          timer = setTimeout(() => {
            onConnect(cb);
          }, 2000);
        });
        Vue.prototype.PahoMQTTClient = PahoMQTTClient;
      } else {
        Vue.prototype.PahoMQTTClient.reconnect();
        Vue.prototype.PahoMQTTClient.on('connect', () => {
          console.log('MQTT onConnect--- success');
          if (timer) clearTimeout(timer);
          cb && cb();
        });
      }
    }
    onConnect();
    /** 全局注册 Mqtt 实例连接方法 */
    Vue.prototype.PahoMQTTClientConnect = onConnect;
  };
  • 避免重复监听
protected destroyed() {
    if (this.timer) clearTimeout(this.timer);
    try {
      this.PahoMQTTClient.removeAllListeners();
    } catch (e) {
      console.log("PahoMQTTClient.end_err", e);
    }
  }
  • 监听回调消息
let msg: string | null = null;
this.PahoMQTTClient.on('message', (topic, message, packet) => {
  // 根据 tipic 判断订阅调用不通方法
  msg = message.toString();
  console.log('订阅消息-RegisteredMqttCbMixin: registeringCb: ' + topic + ' : ' + msg);
  // 调用方法传递 json
  todo(JSON.parse(msg));
});
欢迎来到 人间熙攘,好久不见
看板娘