微信小程序学习记录(二)MQTT连接阿里云

准备

  1. 微信小程序开发工具
  2. MQTT.js库:https://unpkg.com/[email protected]/dist/mqtt.min.js点开链接,右击页面内容另存到电脑。

开始

  1. 将MQTT.js复制到utils目录中
  2. 勾选微信开发工具----->【不校验合法域名、web-view(业务域名)、TLS 版本以及 HTTPS 证书】
  3. 在微信公众平台的开发者后台socket 添加合法域名 为:wss://访问的IP
  4. 在测试页面的js文件:
var mqtt = require('../../utils/mqtt.min.js')
var client;

var topic_sub = '/a1YSkpQ02ky/设备名/get';
var host = 'wxs://a1YSkpQ02ky.iot-as-mqtt.cn-shanghai.aliyuncs.com';
var topic_pub = "/sys/a1YSkpQ02ky/设备名/thing/event/property/post";
var clientId = "esp8266|securemode=3,signmethod=hmacsha1|";
var username = "设备名&a1YSkpQ02ky";
var password = "AB856847D39E3301C8208152FD72F5198554BA4F";
var pub_message = "{\"id\":\"esp8266\",\"version\":\"1.0\",\"method\":\"thing.event.property.post\",\"params\":{\"led_G\":"


Page({
  data: {
    sub_message: "",
    connect_flag:false
  },

  sendInput: function (e) {
    var n = e.detail.value;
    if (this.data.connect_flag){
      if (!isNaN(n)) {
        client.publish(topic_pub, pub_message + n + "}}")
      }
    }else{
      wx.showToast({
        title: '未连接服务器',
        icon:'none'
      })
    }
  },

  bindConnect: function () {
    if (!this.data.connect_flag){
      this.doConnect()
    }else{
      wx.showToast({
        title: '不要重复连接',
        icon:'none'
    })
  },

  bindDisconnect: function () {
    client.end()
  },

  doConnect() {
    var that = this;

    const options = this.initMqttOptions();

    //mqtt连接
    client = mqtt.connect(host, options)
    client.on('connect', function () {
      console.log('连接服务器成功')
      that.setData({
        connect_flag : true
      })
      wx.showToast({
        title: '已连接服务器',
      })
      //订阅主题,(这里的主题,具体请查看后台设备Topic列表或使用自定义主题)
      client.subscribe(topic_sub, function (err) {
        if (!err) {
          console.log('订阅成功!');
        }
      })
    })

    //接收消息监听
    client.on('message', function (topic, message) {
      // message is Buffer
      console.log('收到消息:' + message.toString())
      that.setData({
        sub_message: (message.toString())
      });
    })

    // 监听断开连接事件(小程序不支持)
    client.on('close', function () {
      console.log("连接断开了!");
      that.setData({
        connect_flag: false
      })
      wx.showToast({
        title: '已断开服务器'
      })
    })
  },

  //IoT平台mqtt连接参数初始化
  initMqttOptions() {
    //CONNECT参数
    const options = {
      keepalive: 60, //60s
      clean: false, //cleanSession保持持久会话
      protocolVersion: 4 //MQTT v3.1.1
    }
    //1.生成clientId,username,password
    options.password = password;
    options.clientId = clientId;
    options.username = username;

    return options;
  }

})


参考链接

https://blog.csdn.net/ngl272/article/details/87887885为CSDN博主「我是一座离岛」的原创文章。

你可能感兴趣的:(小程序)