ESP32是一款由乐鑫科技(Espressif Systems)推出的双核、低功耗、集成Wi-Fi和蓝牙的单芯片微控制器。它采用了Tensilica Xtensa LX6高性能处理器,具有大量的GPIO引脚、模数转换器、SPI、I2S、UART、PWM、I2C和SD卡接口等功能,可以满足各种物联网(IoT)应用的需求。由于其高度集成和低功耗特性,ESP32广泛应用于智能家居、智能城市、工业自动化、智能健康、车联网等领域。
1.1 准备
软件:Arduino IDE
硬件:esp32-dev-module
1.2 esp32_Arduino的MQTT库安装
esp32通过MQTT协议连接到物联网平台,我们需要一个mqtt client的库,帮助我们发布订阅相关的topic。我们还需要一个JSON库,帮我们解析JSON,用来序列化和反序列化物模型的JSON数据。
在工具>管理库中,查找PubSubclient、ArduinoJSON和EspMQTTclient,并安装。
1.3 MQTT连接腾讯云的相关配置
这里使用腾讯云平台,创建物联网公共实例。
(1)填写域名和端口
${productid}.iotcloud.tencentdevices.com:1883
(2)生成username和password
要注意的是username和password是在连接到云端mqtt broker的时候需要填入的,可以通过这个在线工具生成。Hmac签名算法选择【HMAC-SHA1】。
(3)填写订阅和发布的消息,可从云平台中获得。
发送的消息指令,具体数据格式可通过云端的调试功能发送一条消息进行测试。
1.4 编写代码
#include <Arduino.h>
#include <WiFi.h>
#include "PubSubClient.h"
#include <ArduinoJson.h>
DynamicJsonDocument doc(1024);
const char *ssid = "climbot";
const char *pwd = "climbot903B";
const char *mqtt_server = "E3TGIRQYNA.iotcloud.tencentdevices.com";
const char *mqtt_username = "E3TGIRQYNA01;12010126;CT9W4;1690882370";
const char *mqtt_userpwd = "72b711c5d7f7e1c76cfca1a785fbddfd3f744163;hmacsha1";
const char *mqtt_clientid = "E3TGIRQYNA01";
const char *mqtt_pub_topic = "$thing/up/property/E3TGIRQYNA/01";
const char *mqtt_sub_topic = "$thing/down/property/E3TGIRQYNA/01";
bool power_switch;
float longtitude;
float latitude;
int power_percent = 0;
#define REPORT_DATA_TEMPLATE "{\"method\":\"report\",\"clientToken\":\"00000001\",\"params\":{\"power_switch\":%d,\"GPS_Info\":{\"longtitude\":%f,\"latitude\":%f},\"_mesh_generic_power_percent\":%d}}"
WiFiClient espClient;
PubSubClient mqttclient(espClient);
long lastMsg = 0;
char report_buf[1024];
void callback(char* topic, byte* payload, unsigned int length)
{
Serial.print("--->Message arrived [");
Serial.print(topic);
Serial.print("] ");
Serial.println();
Serial.print("payload [");
for (int i=0;i<length;i++) {
Serial.print((char)payload[i]);
}
Serial.println();
//处理上位机的控制指令
DeserializationError error = deserializeJson(doc, payload);
// Test if parsing succeeds.
if (error) {
Serial.print("deserializeJson() failed: ");
Serial.println(error.f_str());
return;
}else{
if (doc["clientToken"]!="00000001") {
if (doc["params"]["power_switch"] == 1) {
Serial.print("Power On ");
power_switch=1;
} else {
Serial.print("Power Off ");
power_switch=0;
}
}
}
}
void setup_wifi()
{
Serial.printf("Connect to %s ", ssid);
WiFi.begin(ssid, pwd);
while (WiFi.status() != WL_CONNECTED) {
Serial.printf(".");
delay(500);
}
Serial.println("Connected!");
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
}
void setup() {
Serial.begin(115200);
setup_wifi();
mqttclient.setServer(mqtt_server, 1883);// connect mqtt server
mqttclient.setCallback(callback);
mqttclient.setKeepAlive(65535);
while (!mqttclient.connect(mqtt_clientid, mqtt_username, mqtt_userpwd)) {
Serial.println("mqtt connect fail, reconnect");
delay(2000);
}
Serial.println("mqtt connected!");
// sub topic
boolean ret = mqttclient.subscribe(mqtt_sub_topic);
if (ret != true) {
Serial.printf("mqtt subscribe topic [%s] fail\n", mqtt_sub_topic);
}
Serial.printf("mqtt subscribe topic [%s] ok\n", mqtt_sub_topic);
}
void loop() {
// client loop
mqttclient.loop();
// pub topic
long now = millis();
if (now - lastMsg > 10000) {
lastMsg = now;
memset(report_buf, 0, 1024);
sprintf(report_buf, REPORT_DATA_TEMPLATE, power_switch,longtitude,latitude,power_percent);
Serial.println(report_buf);
if (++power_percent > 100) {//模拟传感器数据
power_percent = 0;
}
if (++longtitude > 100) {
longtitude = 0;
}
if (++latitude > 100) {
latitude = 0;
}
if (mqttclient.publish(mqtt_pub_topic, report_buf)) {
Serial.printf("mqtt publish topic [%s] ok\n", mqtt_pub_topic);
} else {
Serial.printf("mqtt publish topic [%s] fail\n", mqtt_pub_topic);
}
}
}
1.5 烧录和测试
点击下载按钮,待下载完成后,打开串口监视器可看到打印的数据。打开腾讯云平台可查看设备在线状态。