首先使用mqttx注册设备:
温度传感器配置(包括设备信息)
{
"unique_id": "esp32_temperature_sensor1",
"name": "温度传感器1",
"state_topic": "home/esp32/temperature1",
"unit_of_measurement": "°C",
"device_class": "temperature",
"value_template": "{{ value_json.temperature }}",
"device": {
"identifiers": ["esp32_unique_identifier"],
"name": "ESP32环境传感器",
"manufacturer": "自定义制造商",
"model": "ESP32-DHT11",
"sw_version": "1.0"
}
}
湿度传感器配置
{
"unique_id": "esp32_humidity_sensor1",
"name": "湿度传感器1",
"state_topic": "home/esp32/humidity1",
"unit_of_measurement": "%",
"device_class": "humidity",
"value_template": "{{ value_json.humidity }}",
"device": {
"identifiers": ["esp32_unique_identifier"],
"name": "ESP32环境传感器",
"manufacturer": "自定义制造商",
"model": "ESP32-DHT11",
"sw_version": "1.0"
}
}
esp32代码:
#include <WiFi.h>
#include <PubSubClient.h>
#include "DHT.h"
#define DHTPIN 2
#define DHTTYPE DHT11
#define WIFI_SSID "sunk"
#define WIFI_PASSWORD "915471697"
#define MQTT_SERVER "192.168.1.140"
DHT dht(DHTPIN, DHTTYPE);
WiFiClient wifiClient;
PubSubClient mqttClient(wifiClient);
// 定义变量来存储上次的温度和湿度值
float lastTemperature = NAN;
float lastHumidity = NAN;
void connectWifi() {
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
}
}
void connectMQTT() {
mqttClient.setServer(MQTT_SERVER, 1883);
while (!mqttClient.connected()) {
if (mqttClient.connect("ESP32Client")) {
// 连接成功
} else {
delay(5000); // 如果连接失败,等待5秒后重试
}
}
}
void setup() {
dht.begin();
connectWifi();
connectMQTT();
}
void loop() {
if (!mqttClient.connected()) {
connectMQTT();
}
mqttClient.loop();
float humidity = dht.readHumidity();
float temperature = dht.readTemperature();
if (!isnan(humidity) && !isnan(temperature)) {
// 单独检查温度变化
if (temperature != lastTemperature) {
String tempPayload = "{\"temperature\":" + String(temperature) + "}";
mqttClient.publish("home/esp32/temperature1", tempPayload.c_str());
lastTemperature = temperature; // 更新存储的温度值
}
// 单独检查湿度变化
if (humidity != lastHumidity) {
String humPayload = "{\"humidity\":" + String(humidity) + "}";
mqttClient.publish("home/esp32/humidity1", humPayload.c_str());
lastHumidity = humidity; // 更新存储的湿度值
}
}
delay(100); // 简单的延时,减少消息发送频率 作者:__AEEE__ https://www.bilibili.com/read/cv32760502/ 出处:bilibili