[Internet of Things Development] - MQTT connection of WeChat applet, based on MQTT to realize device-server-mini-program message transmission

1. Pre-knowledge preparation

If you want to develop a WeChat applet, you must first have some basic knowledge: html, cs, js, json, etc. The knowledge framework used in the applet is roughly the same, and a page includes files in js, json, wxml, and wxss formats.

Since I have never been in contact with the development of small programs before, this article will analyze step by step how to use the WeChat small program to connect to the device through the MQTT server from the perspective of a novice Xiaobai. Including: how to apply for an MQTT server, how to use the WeChat developer tool to develop a small program, and let the device establish an MQTT connection with the server, subscribe to topics and publish messages, and realize the transmission of messages between the device-server-WeChat applet.

insert image description here

2. Small program development environment construction

1. Register WeChat Mini Program

https://mp.weixin.qq.com/cgi-bin/wx?token=&lang=zh_CN

  • Open the official link above and go to register for the WeChat Mini Program
  • As a login account, please fill in the email address that has not been registered on the WeChat public platform, has not been registered on the WeChat open platform, and has not been bound by a personal WeChat account
  • Email activation
  • information registration

After completing the above steps, you can log in to the background of the applet.

Why register a Mini Program account?

Because it will be debugged on the real machine, released and launched later, and the AppID of the applet must also be provided when using the WeChat developer platform to create a project, so this step is critical and indispensable.

2. Download the development software

There are several development software for WeChat applets. I use the original WeChat developer tool. The link is as follows, just download the stable version

https://developers.weixin.qq.com/miniprogram/dev/devtools/download.html

3. Create a new project

Project-New Project-fill in the project name, project storage directory, AppID, back-end service-not applicable cloud service, template selection-JavaScript, and confirm the creation of the applet.

4. Directory structure

The directory structure of the newly created applet is as follows.
insert image description here
The
JS script logic file is usually used to handle the interaction between this page and the user, such as the definition of data, the realization of function functions, etc.

JSON configuration file, json plays the role of static configuration in applets, the most commonly used file is app.json, which is used for global configuration

The wxml file is used to describe the structure of the current page, for example, the first component is a button, the second component is a text box, etc.

The wxss file is used to describe the style of the page, such as position, size, typesetting, etc.

The syntax of the specific framework can be read in detail in the official documentation at the link below

https://developers.weixin.qq.com/miniprogram/dev/reference/api/App.html

After creating the project, you can start the MQTT configuration

3. Configure MQTT service

1. What needs to be prepared

  1. The MQTT server is set up on the public network IP, and the IP is configured with a domain name, and the domain name has been filed with ICP
  2. A device capable of connecting to an MQTT server

Seeing this, do you feel that the difficulty is full at once? You have to learn so much extra, you have to build a server, and you have to install an operating system to configure a bunch of things... Don't worry, the road has been opened, and there is a server here that can be used directly, free and reliable! !

2. Special thanks

Here I would like to thank a conscientious up master who can provide this free MQTT server. I first learned how to build the small program MQTT and followed this up master step by step. If you pass by, you can give a one-click three-link support to this conscience blogger.
insert image description here
This blogger offers a website:

http://www.yoyolife.fun/

insert image description here

3. Register an account

One simple step to complete registration and login
insert image description here

4. Add equipment

insert image description here
Click on the device name of project management to perform device management

5. Manage equipment

insert image description here
At this point, the configuration of the server has been completed, and the device can connect to the MQTT server through the external network, but how to connect and how to observe the connection status of the device? This article uses the MQTTx client software as a device to subscribe topics and publish messages to the MQTT server .

Now there are two more nouns: subscribing to topics and publishing messages . As a novice, do you feel unfamiliar?

Subscribe to a topic: the device is bound to a specified topic, and when the server forwards the content under this topic, it will be pushed to all devices that subscribe to this topic;

发布消息:就是设备将消息绑定指定的主题,发到服务器,由服务器广播转发出去,只有绑定了(即订阅)该主题的设备才能收到服务器转发的该主题的消息。

通俗易懂地讲,设备订阅了一个主题,就能向订阅同样主题的设备发送消息,也能收到订阅了相同主题设备的消息。

四、使用MQTTx客户端创建设备

1、MQTTx下载链接

https://mqttx.app/zh

安装完MQTTx后准备对服务器进行连接

2、配置MQTT设备参数

名称可以随便填,ClientID和用户名必须填上面的设备ID,密码是在杰叔叔捣鼓提供的服务器创建设备ID时的密码,服务器地址和端口都是固定的,按照图片设置即可
insert image description here

3、连接MQTT服务器

可以看到这里订阅了两个主题,向服务器发送了消息以后,服务器将消息转发给订阅了该主题的设备,包括本设备,说明MQTT连接成功
insert image description here
我们可以看到,MQTT服务器显示设备在线,也说明MQTT连接成功
insert image description here
至此,MQTT服务器与单设备(MQTTx)的连接就调通了。

五、小程序端

1、修改微信开发者工具配置

详情-本地设置-取消勾选 “将JS编译成ES5”
insert image description here

2、登录小程序后台

开发管理-开发设置-服务器域名-修改,添加socket合法域名:wss://t.yoyolife.fun:8084

3、修改微信开发者工具代码

index.js文件

// index.js
// 获取应用实例
const app = getApp()
var mqtt = require('../../utils/mqtt.min')

Page({
    
    
  data: {
    
    
  },
  onLoad:function(options) {
    
    
    var that = this
    that.connectMqtt()
    // this.connectMqtt()
  },
  connectMqtt:function(){
    
    
    const options = {
    
    
      connectTimeout:4000,
      clientId:'5ddad3c8554e8f74fd3f96ff959dd894',
      port:8084,
      username:'5ddad3c8554e8f74fd3f96ff959dd894',
      password:'123456'
    }
    client = mqtt.connect('wxs://t.yoyolife.fun:8084/mqtt',options)
    client.on('connect',(e)=>
    {
    
    
      console.log('服务器连接成功')
      client.subscribe('/iot/2742/de',
      {
    
    
        qos:0, 
      },
      
      function(err)
      {
    
    
        if(!err)
        {
    
    
            console.log('订阅成功')
        }
      })
    })
    client.on('message',function(topic,message){
    
    
      console.log('收到'+message.toString())
    })
  },
  taphere(){
    
    
      console.log('helloworld');
  }
})

index.wxml

<!--index.wxml-->
<view class="container">
  <button type="primary" bindtap="taphere">helloworld</button>
</view>

值得注意的是,app.json文件中pages存放的是页面的路径,所以需要将logs文件夹删掉以后再修改app.json并保存

app.json

{
  "pages":[
    "pages/index/index"
  ],
  "window":{
    "backgroundTextStyle":"light",
    "navigationBarBackgroundColor": "#2b4b6b",
    "navigationBarTitleText": "物联网平台",
    "navigationBarTextStyle":"white"
  },
  "style": "v2",
  "sitemapLocation": "sitemap.json"
}

往utils添加mqtt.min.js文件

将下载链接的文件放进utils文件夹里,最后的目录结构将会是这样

下载链接:
https://pan.baidu.com/s/1lS6eDXgW107dA7HyxF8ZkA?pwd=n8jw 
提取码:n8jw 

insert image description here

总结

The clientId and username inside the applet must be the same. This ID is the ID of the IoT platform application provided by Uncle Jie. If you fill in the wrong one, you will not be able to access the MQTT server. The port is fixed at 8084. The password is the password when you apply for the ID. Subscribe The topic is currently /iot/2742/de

6. Compile the applet

1. Connect to the MQTT server

Click the compile button at the top, and the debug box will display "server connection successful" and "subscription successful", indicating that the applet is successfully connected to the MQTT server.
insert image description here

2. Send messages across devices

The applet can be used as a device, and MQTTx can create a device, use these two devices to subscribe to the same topic, and publish a message. After the MQTTx publishes the message, it will display the corresponding sent message in the applet debugging window. Let’s make a demonstration:
insert image description here
the function of the small program to publish messages is not yet perfect. At present, only the device can release messages, and the small program can display messages. It will be further improved in the future. However, as a platform for monitoring data, the small program can already meet some basic application scenarios. It only needs to realize that the received data is displayed on the small program page, and the small program can be officially launched and used.

So far, the device-server-applet message transmission based on MQTT has been realized

Code words are not easy, your one-click three-link is the greatest support for me~
All project codes are open source, welcome like-minded friends to discuss and improve together!
If there are deficiencies in the article, all seniors are welcome to criticize and correct.

This article project code download link:

Link: https://pan.baidu.com/s/1nYkcUG25VKTzmguYOAQXKA?pwd=bf95
Extraction code: bf95

Guess you like

Origin blog.csdn.net/weixin_46403492/article/details/129882782