concept
MQTT
MQTT (Message Queuing Telemetry Transport) is a "lightweight" messaging protocol based on the publish/subscribe paradigm, published by IBM. MQTT can work on the TCP/IP protocol suite and is a publish/subscribe messaging protocol designed for remote devices with low hardware performance and poor network conditions. Therefore, the MQTT protocol is suitable for remote devices with low hardware performance and environments with poor network conditions, such as machine-to-machine (M2M) communication and the Internet of Things (IoT).
There are many other concepts about MQTT, such as subscription and publishing mechanisms, message service levels, heartbeat mechanisms, etc. Please understand the relevant knowledge before reading the article. Recommended learning addresses .
ESP8266
Espressif ESP8266 is a microcontroller with built-in WiFi function. It has high-performance wireless SOC characteristics and can provide wireless connection functions for mobile devices and IoT applications.
The characteristics of ESP8266 are as follows:
small package size, ultra-low power consumption, and supports multiple power modes.
Equipped with a high-performance UART-WiFi transparent transmission module, it can be directly connected to other microcontroller-based devices.
Supports three working modes: STA/AP/STA+AP, and can be used as a wireless access point or client.
Built-in TCP/IP protocol stack supports multiple TCP Client connections without adding any matching circuits.
Supports three types of antenna interfaces: onboard PCB antenna, IPEX interface and stamp hole interface.
It can be widely used in smart grid, smart transportation, smart furniture, handheld devices, industrial control and other fields.
It should be noted that although the information I provide is as accurate as possible, products may be constantly updated and changed. It is recommended to check the Espressif official website for the latest and most accurate information.
Build your own MQTT server
This article uses the EMQX official website address
. After purchasing your own server, use the following code to deploy it.
curl -s https://assets.emqx.com/scripts/install-emqx-rpm.sh | sudo bash
sudo yum install emqx -y
sudo systemctl start emqx
After the installation is complete, open the backend. http://你的IP地址/#/login?to=/websocket
The initial account admin password is public.
Burn ESP8266 code
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
// WiFi
const char *ssid = "mousse"; // Enter your WiFi name
const char *password = "qweqweqwe"; // Enter WiFi password
// MQTT Broker
const char *mqtt_broker = "broker.emqx.io";
const char *topic = "esp8266/test";
const char *mqtt_username = "emqx";
const char *mqtt_password = "public";
const int mqtt_port = 1883;
WiFiClient espClient;
PubSubClient client(espClient);
void setup() {
// Set software serial baud to 115200;
Serial.begin(115200);
// connecting to a WiFi network
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.println("Connecting to WiFi..");
}
Serial.println("Connected to the WiFi network");
//connecting to a mqtt broker
client.setServer(mqtt_broker, mqtt_port);
client.setCallback(callback);
while (!client.connected()) {
String client_id = "esp8266-client-";
client_id += String(WiFi.macAddress());
Serial.printf("The client %s connects to the public mqtt broker\n", client_id.c_str());
if (client.connect(client_id.c_str(), mqtt_username, mqtt_password)) {
Serial.println("Public emqx mqtt broker connected");
} else {
Serial.print("failed with state ");
Serial.print(client.state());
delay(2000);
}
}
// publish and subscribe
client.publish(topic, "hello emqx");
client.subscribe(topic);
}
void callback(char *topic, byte *payload, unsigned int length) {
Serial.print("Message arrived in topic: ");
Serial.println(topic);
Serial.print("Message:");
for (int i = 0; i < length; i++) {
Serial.print((char) payload[i]);
}
Serial.println();
Serial.println("-----------------------");
}
void loop() {
client.loop();
}
Change the above information to your own.
Pay attention to adding the PubSubClient library.
WeChat applet development
Official access tutorial
Create a WeChat applet project and add library files. This article uses MQTT.js. There are also related SDKs for different clients. The WeChat applet here uses JavaScript language, so this library is used.
EMQX requires WeChat applet to support instant communication through WebSocket. EMQX's MQTT Over WebSocket is fully compatible with WeChat applet.
Tip:
Due to the specification restrictions of the WeChat applet, EMQX needs to pay attention to the following points when using the WeChat applet to access: You must
use a domain name that has passed the domain name registration (opens new window) to access
the domain name, which needs to be in the applet management background (opens new window) The domain name/IP whitelist (Development->Development Settings->Server Domain Name->Socket Legal Domain Name)
only supports the WebSocket/TLS protocol, and a certificate issued by a trusted CA needs to be assigned to the domain name
. Due to the WeChat applet BUG, real Android phones must use TLS/443 port, otherwise the connection will fail (that is, the connection address cannot contain a port)
Download and import mqtt.mini.js
to test in the WeChat applet onLoad statement cycle.
onLoad(options) {
try {
console.log("开始链接");
const clientId = new Date().getTime();//mqtt的连接ID
app.globalData.client = mqtt.connect(`wxs://${
host}/mqtt`, {
username,
password,
reconnectPeriod,
connectTimeout,
clientId,
});
} catch (error) {
console.log("mqtt.connect error", error);
}
if (app.globalData.client) {
app.globalData.client.subscribe("test")
}
app.globalData.client.on("message", (topic, payload) => {
console.log(`收到消息 - Topic: ${
topic},Payload: ${
payload}`)
// app.globalData.currMsg = JSON.parse(payload);
// console.log(typeof payload)
});
}
The will message has been received here.
For more APIs such as subscription, publishing, and message callback, please check MQTT.js.