esp32 mqtt 连接thingsboard 的代码
时间: 2024-12-09 22:02:55 浏览: 34
ESP32连接到ThingsBoard服务器并使用MQTT协议通信的代码示例会在物联网开发中经常遇到。这里是一个基本的步骤:
```c
#include <WiFi.h>
#include <PubSubClient.h>
const char* ssid = "your_SSID";
const char* password = "your_PASSWORD";
const char* mqtt_server = "your_THINGSBOARD_HOST";
const int mqtt_port = 1883;
const char* client_id = "esp32_client";
char device_name[] = "esp32_device";
WiFiClient wifiClient;
PubSubClient client(wifiClient);
void connectToWiFi() {
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("Connected to WiFi!");
}
void reconnect() {
while (!client.connected()) {
if (client.connect(client_id, device_name)) {
Serial.println("Connected to MQTT server");
client.subscribe("$SYS/#"); // Subscribe to system topics
} else {
Serial.print("Failed to connect, retrying in 5 seconds...");
delay(5000);
}
}
}
void publishData() {
String data = "temperature=25, humidity=60"; // Example payload
client.publish("devices/" + device_name + "/ telemetry", data.c_str());
}
void setup() {
Serial.begin(115200);
connectToWiFi();
client.setServer(mqtt_server, mqtt_port);
reconnect();
}
void loop() {
if (!client.connected()) {
reconnect();
}
publishData(); // Publish your sensor readings here
client.loop();
}
```
在这个例子中,你需要替换`ssid`, `password`, 和`mqtt_server`为实际的网络信息。在`loop()`函数中,你可以根据你的硬件设备实时收集数据,并将其发送到ThingsBoard指定的设备主题(`"devices/esp32_device/telemetry"`)。
阅读全文