ESP32上手笔记 | 04 -通过MQTT对接腾讯云IoT Explorer物联网平台(PubSubClient)

一、WIFI库和ArduinoJson库

阅读文章:ESP32上手笔记 | 03 -通过HTTP获取天气信息(WiFi+HTTPClient+ArduinoJson)。

二、PubSubClient库

PubSubClient库是一个针对Arduino的MQTT客户端库,github仓库链接:Arduino Client for MQTT。

1. 安装库

git clone https://github.com/knolleary/pubsubclient

复制到platform工程的lib目录中。

2. 使用库

包含头文件:

#include "PubSubClient.h"

创建对象:

WiFiClient espClient;
PubSubClient mqttclient(espClient);

2.1. 连接MQTT服务器

设置mqtt服务器地址:

PubSubClient& setServer(IPAddress ip, uint16_t port);
PubSubClient& setServer(uint8_t * ip, uint16_t port);
PubSubClient& setServer(const char * domain, uint16_t port);

设置保活时间:

PubSubClient& PubSubClient::setKeepAlive(uint16_t keepAlive);

设置订阅回调函数:

PubSubClient& setCallback(MQTT_CALLBACK_SIGNATURE);

回调函数长这样:

#define MQTT_CALLBACK_SIGNATURE std::function callback

连接mqtt服务器:

boolean connect(const char* id);
boolean connect(const char* id, const char* user, const char* pass);
boolean connect(const char* id, const char* willTopic, uint8_t willQos, boolean willRetain, const char* willMessage);
boolean connect(const char* id, const char* user, const char* pass, const char* willTopic, uint8_t willQos, boolean willRetain, const char* willMessage);
boolean connect(const char* id, const char* user, const char* pass, const char* willTopic, uint8_t willQos, boolean willRetain, const char* willMessage, boolean cleanSession);

2.2. 发布消息

boolean publish(const char* topic, const char* payload);
boolean publish(const char* topic, const char* payload, boolean retained);
boolean publish(const char* topic, const uint8_t * payload, unsigned int plength);
boolean publish(const char* topic, const uint8_t * payload, unsigned int plength, boolean retained);
boolean publish_P(const char* topic, const char* payload, boolean retained);
boolean publish_P(const char* topic, const uint8_t * payload, unsigned int plength, boolean retained);

2.3. 订阅topic

boolean subscribe(const char* topic);
boolean subscribe(const char* topic, uint8_t qos);
boolean unsubscribe(const char* topic);

2.4. 断开连接

void disconnect();

2.5. mqtt主循环

该函数必须放在loop中调用,循环处理mqtt包:

boolean loop();

三、对接腾讯云IoT Explorer平台

1. 云端操作

参考:使用 TencentOS tiny 对接腾讯云IoT Explorer(以智能灯为例)。

2. 上云代码

#include 
#include 
#include "PubSubClient.h"

const char *ssid = "汇嘉阁15B";
const char *pwd  = "jiedian4001001111";
const char *mqtt_server = "106.55.124.154";
const char *mqtt_username = "FWR8PGACUSdev001;21010406;12365;4294967295";
const char *mqtt_userpwd  = "273f218b35f52900b8b85183d93c1fcc6b9c9444;hmacsha1";
const char *mqtt_clientid = "FWR8PGACUSdev001";
const char *mqtt_pub_topic = "$thing/up/property/FWR8PGACUS/dev001";
const char *mqtt_sub_topic = "$thing/down/property/FWR8PGACUS/dev001";

#define REPORT_DATA_TEMPLATE "{"method":"report","clientToken":"00000001","params":{"brightness":%d,"name":"bedroom"}}"

WiFiClient espClient;
PubSubClient mqttclient(espClient);
long lastMsg = 0;
int lightness = 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;ilength;i++) {
    Serial.print((char)payload[i]);
  }
  Serial.println();
}

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();

    // connect mqtt server
    mqttclient.setServer(mqtt_server, 1883);
    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] failn", mqtt_sub_topic);
    }
    Serial.printf("mqtt subscribe topic [%s] okn", 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, lightness);
        Serial.println(report_buf);
        if (++lightness > 100) {
            lightness = 0;
        }
        
        if (mqttclient.publish(mqtt_pub_topic, report_buf)) {
            Serial.printf("mqtt publish topic [%s] okn", mqtt_pub_topic);
        } else {
            Serial.printf("mqtt publish topic [%s] failn", mqtt_pub_topic);
        }
    }
}

3. 运行结果

ESP32上手笔记 | 04 -通过MQTT对接腾讯云IoT Explorer物联网平台(PubSubClient)

本文章来源于互联网,如有侵权,请联系删除!

相关推荐: 高通骁龙410e/APQ8016E嵌入式物联网应用处理器解决方案

高通骁龙410e/APQ8016E应用处理器是一种理想的物联网应用解决方案,它需要计算能力和集成Wi-Fi和蓝牙。 连接,比如连接家居、楼宇自动化、工业控制、数字标牌、智能监控等物联网设备。 410e/APQ8016E嵌入式平台专为物联网设备而设计,支持嵌入式…