从EMQX模拟设备中发送数据到微信小程序

1、注册EMQX服务器

登录EMQX服务器官网EMQX Dashboard,注册自己的帐号和密码,点击“登录”。

2、找到WebSocket客户端

3、连接客户端

点击“连接”

4、复制自己的设置订阅主题“$thing/up/property/IQMPOB8BI9/temp/humi”,粘贴到EMQX的订阅和发布上

5、点击订阅

6、把以下代码复制到Payload

{ "temperture":"90","humidity":"90","longitude":"113.970473","latitude":"22.556992"}

7、点击发布

8、我们可以看到小程序收到了EMQX发送上来的数据了

这是我的代码,仅供参考:

const app = getApp()

var mqtt = require('../../utils/mqtt.min.js') //根据自己存放的路径修改

const appInstance = getApp();

Page({

  data: {

    motto: 'Hello World',

    userInfo: {},

    hasUserInfo: false,

    canIUse: wx.canIUse('button.open-type.getUserInfo'),

    canIUseGetUserProfile: false,

    canIUseOpenData: wx.canIUse('open-data.type.userAvatarUrl') && wx.canIUse('open-data.type.userNickName'), // 如需尝试获取用户信息可改为false

    temperture:'0',

    humidity:'0',

    angle:'0',

    wl:'0',

    gas:'0',

    longitude:'0',

    latitude:'0',

  },

  onLoad(){

    this.doConnect()

    if (wx.getUserProfile) {

      this.setData({

        canIUseGetUserProfile: true

      })

    }

    this.setData({

        nbTitle: '设备参数',

        nbLoading: false,

        nbFrontColor: '#ffffff',

        nbBackgroundColor: '#D53e37',

      })

  },

   doConnect(){

    //如果你服务器开了连接验证,这里的参数要自己加上username和password等

    const options = {

      keepalive: 60, //60s

      clean: true, //cleanSession不保持持久会话

      protocolVersion: 4 ,//MQTT v3.1.1

      clientId:Math.random().toString(36).substr(2)

    };

    let url = "wx://www.visionexpand.com.cn:8083/mqtt";//这个地址是emq官方的公开免费地址,请换成自己服务器的地址

    const client = mqtt.connect(url,options)

    client.on('connect', function () {

      console.log('连接emqx服务器成功')

      client.subscribe('$thing/up/property/IQMPOB8BI9/temp/humi',{qos:2},function(err){

        if(!err)

            {console.log('订阅成功')}

      })

    })

    //接收消息监听

    client.on('message', (topic, message) => { 

      let msg=message.toString();

      const data=JSON.parse(msg);

       const timestamp = new Date().toISOString().substr(0, 19).replace('T', ' ');  

      console.log('温度:', data.temperture, '湿度:', data.humidity,'纬度:',data.longitude,'经度',data.latitude); 

  // 设置数据

  this.setData({  

    temperture: data.temperture,  

    humidity: data.humidity,

    longitude:data.longitude,

    latitude:data.latitude

  });

  })

}

})

  • 19
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值