非tarbar页面使用MQTT协议订阅主题,但只能发布不能接收?
发布于 6 年前 作者 xiulanxiong 4755 次浏览 来自 官方Issues
我从tarbar页面输入账号密码验证通过后跳转至控制页面,控制页面中按钮可正常点击发送数值到mqtt服务器,但HumdValue那里一直接收不到信息,如果编译模式选择单index的话,console.log还可以输出connected callback ,并且可正常收到HumdValue数据,但是若是普通编译情况下,跳转至控制页面后,没有输出connected callback,并且收不到mqtt服务器端发来的信息,接收信息是使用一个MessageProcess的方法,这个方法与之前输出conneed callback的方法一同放在onLoad下,望大家能给予意见以及建议,谢谢大家,以下是index.js代码
import mqtt from './../../utils/mqtt.js';

//获取应用实例
const app = getApp();

Page({
  data: {
    client: null,
    topic: {
      LEDcontrolTopic: 'control_led',
      NumTopic:'num_car',
    },
    value: {
      Humdlogo: '/pages/images/humd.png',
      HumdValue: 0,
    },
    LEDValue: [{
      LEDlogo: '/pages/images/LED_gray.png',
      ButtonValue: '第一个门开启',
      ButtonFlag: true,
    }],

  onLoad: function() {
    console.log("onload");
    var that = this;
    this.data.client = app.globalData.client;
    that.data.client.on('connect', that.ConnectCallback);
    that.data.client.on("message", that.MessageProcess);
    that.data.client.on("error", that.ConnectError);
    that.data.client.on("reconnect", that.ClientReconnect);
    that.data.client.on("offline", that.ClientOffline);
  },

  onShow: function() {
    console.log("on show"); 
  },

  onHide: function() {
    console.log("on hide");
  },

  onUnload: function() {
    console.log("on unload");
  },

  LedControl: function(e) {
    var that = this;
    
    if (that.data.LEDValue[0].ButtonFlag) {
        that.setData({
          'LEDValue[0].ButtonValue': '第一个门关闭',
          'LEDValue[0].ButtonFlag': false,
          "LEDValue[0].LEDlogo": './../images/LED_red.png',
        })
      that.data.client.publish(that.data.topic.LEDcontrolTopic, "4",{
        qos: 1
      });
    } else {
          that.setData({
            'LEDValue[0].ButtonValue': '第一个门开启',
            'LEDValue[0].ButtonFlag': true,
            "LEDValue[0].LEDlogo": './../images/LED_gray.png',
          })
      that.data.client.publish(that.data.topic.LEDcontrolTopic, "7",{
        qos: 1
      });
    }
  },
  
  MessageProcess: function(topic, payload) {
    var that = this;
    var payload_string = payload.toString();
    if (topic == that.data.topic.NumTopic) {
      that.setData({
        'value.HumdValue': payload_string
      })
      }
  },

  ConnectCallback: function(connack) {
    var that = this;
    console.log("connect callback ");
    for (var v in that.data.topic) {
      that.data.client.subscribe(that.data.topic[v], {
        qos: 1
      });
    }
  },

  ConnectError: function(error) {
    console.log(error)
  },

  ClientReconnect: function() {
    console.log("Client Reconnect")
  },

  ClientOffline: function() {
    console.log("Client Offline")
  }

})
回到顶部