Wechat Mini program is an application launched by Tencent on January 9, 2017 that can be used on wechat platform without download and installation. Users can open the application by scanning or searching it. It also embodies the concept of “use it and go”, so users don’t have to worry about installing too many apps. Applications will be everywhere, ready to use, but not installed or uninstalled. For developers, the threshold of small program development is relatively low, less difficult than APP, can meet the simple basic application, for users, can save the use of time cost and mobile phone memory space, for developers can also save the development and promotion cost.

This paper mainly introduces how to use MQTT in wechat applet project to realize the connection, subscription, sending and receiving messages, unsubscription and other functions between the applet client and MQTT cloud service.

MQTT is a lightweight Internet of Things messaging protocol based on publish/subscribe mode, which can provide real-time and reliable messaging services for networked devices with very little code and bandwidth. It is widely used in the Internet of Things, mobile Internet, intelligent hardware, Internet of vehicles, power energy and other industries.

Project initialization

preparation

Register a wechat mini program account and download the wechat developer tools. Because wechat applet has high security requirements, HTTPS or WSS protocol must be used to communicate with the background server. Therefore, a domain name server should be set up in the background of wechat applet.

Wechat applets only support instant communication through WebSocket, EMQ X MQTT Over WebSocket can be fully compatible with the use of wechat applets. However, due to the specification limitations of wechat applets, EMQ X needs to pay attention to the following points when using wechat applets:

  • Access using a domain name that has been registered

  • Domain name You need to add the configuration server domain name under the server domain name on the main page after logging in to the wechat public platform

  • Only WebSocket or TLS is supported. A certificate issued by a trusted CA must be assigned to the domain name

  • Due to wechat small program BUG, Android real machine must use TLS/443 port, otherwise the connection will fail (that is, the connection address can not have port)

IO/WSS :// Broker.emqx. IO/WSS ://broker.emqx. IO/WSS :// Emqx. IO/WSS :// Emqx. IO

After the addition, we are allowed to communicate and interact with the server under the domain name address during the development of wechat small program.

New project

After finishing the work related to network communication in the early stage, we opened the downloaded wechat developer tool and clicked on the page to create a small program, as shown in the picture below:

After clicking ok, the wechat developer tool will automatically initialize the project and we can start developing.

Install the MQTT client library

Because the applets are developed in JavaScript, mqTT.js can be used as the MQTT client library.

Starting with applets Base library version 2.2.1 or above and developer tool 1.02.1808300 or above, applets support installing third-party packages using NPM. If interested readers can view the official documentation of small program NPM support to operate and use, this article to simplify the operation process, will not use the WAY of NPM installation. We will create a new mqtt.js file under the utils folder, and we will directly fetch the packaged and built source copy mqtt.js file on the MQtt.js CDN.

Mqtt.js CDN address: unpkg.com/[email protected]/… You can view it through the browser.

Note: as of the current version of MQtt.js v4.2.8, the use of small programs will report net.createconnection undefined error, need to be backtracked and use version 4.0.1.

After that, we can import from the index.js main page:

import mqtt from '.. /.. /utils/mqtt'
Copy the code

Use MQTT

In this paper, the free public MQTT server provided by EMQ X Cloud will be used as the ADDRESS of the MQTT server for this test. The server access information is as follows:

  • Broker: broker.emqx.io
  • TCP Port: 1883
  • SSL/TLS Port: 8883

For more details, visit the EMQ X Cloud website or view the EMQ X Cloud documentation.

Connection code

Wechat applet uses WebSocket to connect to MQTT server, but please use WXS protocol name in the URL address of connection, and key codes of connection and initialization data:

Page({
  data: {
    client: null.host: 'broker.emqx.io:8084'.topic: 'testtopic/miniprogram'.msg: 'Hello! I am from WeChat miniprogram'.mqttOptions: {
      protocolVersion: 4.//MQTT connection protocol version
      clientId: 'emqx_cloud_miniprogram'.clean: true.password: ' '.username: ' '.reconnectPeriod: 1000.// 1000 ms, the interval between two reconnections
      connectTimeout: 30 * 1000.// 1000 ms, the interval between two reconnections
      resubscribe: true // If the connection is disconnected and reconnected, subscribed topics are automatically subscribed again (default true)}},connect() {
    this.data.client = mqtt.connect(`wxs://The ${this.data.host}/mqtt`.this.data.mqttOptions)
    this.data.client.on('connect'.() = > {
      wx.showToast({
        title: 'Connection successful'})})}})Copy the code

Subscribe to the topic

subscribe() {
  this.data.client.subscribe(this.data.topic)
  wx.showToast({
    title: 'Topic subscribed successfully'})},Copy the code

unsubscribe

unsubscribe() {
  this.data.client.unsubscribe(this.data.topic)
  wx.showToast({
    title: 'Unsubscribe succeeded'})},Copy the code

News release

publish() {
  this.data.client.publish(this.data.topic, this.data.msg)
},
Copy the code

disconnect

disconnect() {
  this.data.client.end()
  wx.showToast({
    title: 'Disconnection succeeded'})},Copy the code

test

We have simply written the following application interface in the small program, the application has: create a connection, subscribe to the topic, send and receive messages, cancel subscription, disconnect and other functions.

Full project example code: github.com/emqx/MQTT-C…

Use MQTT 5.0 client tool – MQTT X as another client for messaging tests.

You can see that MQTT X normally receives messages sent from the applet, and you can also see that the applet normally receives a message sent to the topic using MQTT X.

conclusion

To sum up, we implemented the creation of an MQTT connection in an applet project, simulating a scenario where an applet client subscrires, sends and receives messages, unsubscrires, and disconnects from an MQTT server.

Copyright: EMQ

Original link: www.emqx.com/zh/blog/how…

Technical support: If you have any questions about this article or EMQ related products, please visit askemq.com to ask questions. We will respond to you in time.

More technical dry goods, welcome to our official account [EMQ Chinese community].