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

Posted Mculover666

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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<void(char*, uint8_t*, unsigned int)> 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 <Arduino.h>
#include <WiFi.h>
#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;i<length;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] 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, lightness);
        Serial.println(report_buf);
        if (++lightness > 100) 
            lightness = 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);
        
    

3. 运行结果

以上是关于ESP32上手笔记 | 04 -通过MQTT对接腾讯云IoT Explorer物联网平台(PubSubClient)的主要内容,如果未能解决你的问题,请参考以下文章

ESP32-C3上手笔记 | 01 - ESP32 C3开发环境搭建(ESP-IDF)

ESP32上手笔记 | 06 -驱动1.3‘ ST7789 SPI屏幕(TFT_eSPI)

ESP32上手笔记 | 05 - 获取MPU6050数据进行姿态解算和展示(I2Cdev+MPU6050+Processing)

ESP32学习笔记 -- 使用 gitee 在 ubuntu 22.04 搭建 ESP-IDF 开发环境(新版本)

ESP32 单片机学习笔记 - 04 - ADC和定时器

esp32开发板上手micropython--windows环境