失眠网,内容丰富有趣,生活中的好帮手!
失眠网 > ESP32上手笔记 | 04 -通过MQTT对接腾讯云IoT Explorer物联网平台(PubSubClient)

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

时间:2020-01-05 01:05:35

相关推荐

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 /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 servermqttclient.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 topicboolean 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 loopmqttclient.loop();// pub topiclong 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)》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。