#include <PubSubClient.h>
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ArduinoJson.h>
#include <DHTesp.h>
//参数配置
const char* ssid = "******";
const char* password = "*******";
const int mqttPort = 1883;
const char* mqttUser = "***";
const char* mqttPassword = "********";
const char* mqttServer = "********";
// json dht
long lastMsg = 0;
int value = 0;
char msg[300]; //存放json数据
char msg1[300];
char msg2[100];
float humidity;
float temperature;
DHTesp dht;
WiFiClient espClient;
PubSubClient client(espClient);
// mqtt 消息回调
void callback(char *topic, byte* payload, int length) {
Serial.print("Messageved in topic: ");
Serial.println(topic);
Serial.println();
char receivedChar[100];
for (int i = 0; i < length; i++) {
receivedChar[i] = (char)payload[i];
}
Serial.print("meaasge: ");
Serial.println(receivedChar);
// if (strcmp(receivedChar, "ON") == 0) {
// led_open();
// } else if (strcmp(receivedChar, "OFF") == 0) {
// led_close();
// }
Serial.println();
}
// 链接mqtt wifi
void connect_wifi_mqtt() {
// 连接wifi
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.println();
Serial.println("Connecting WiFi...");
}
Serial.println("Connect to the WiFi network success!");
// 连接mqtt服务器
// 设置服务器与回调函数
client.setServer(mqttServer, mqttPort);
client.setCallback(callback);
while (!client.connected()) {
Serial.println("Connecting to MQTT...");
if (client.connect("ESP8266Client", mqttUser, mqttPassword ))
{
Serial.println("Connect to the mqtt server success!");
} else {
Serial.println("failed state ");
Serial.println(client.state());
delay(2000);
}
}
if (client.connect("ESP8266Client", mqttUser, mqttPassword)) {
Serial.println("connected");
} else {
Serial.print("failed state");
Serial.print(client.state());
delay(2000);
}
}
// mqtt掉线重连
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Attempt to connect
if (client.connect("ESP8266 Client")) {
Serial.println("connected");
// ******************************
// ... and subscribe to topic
// ***************************************
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println("try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
// JSON编码
void encodeJson() {
DynamicJsonBuffer jsonBuffer;
JsonObject& root1 = jsonBuffer.createObject();
JsonObject& root2 = jsonBuffer.createObject();
JsonObject& root3 = jsonBuffer.createObject();
root1["device_class"] = "sensor";
root1["name"] = "Temperature";
root1["state_topic"] = "homeassistant/sensor/sensorBedroom/state";
root1["unit_of_measurement"] = "°C";
root1["value_template"] = "{{ value_json.temperature}}";
// root1.prettyPrintTo(Serial);
root1.printTo(msg);
root2["device_class"] = "sensor";
root2["name"] = "Humidity";
root2["state_topic"] = "homeassistant/sensor/sensorBedroom/state";
root2["unit_of_measurement"] = "%";
root2["value_template"] = "{{ value_json.humidity}}";
root2.printTo(msg1);
root3["humidity"] = humidity;
root3["temperature"] = temperature;
// root3.prettyPrintTo(Serial);
root3.printTo(msg2);
}
//JSON解码
//void decodeJson(char msg[100]){
// DynamicJsonBuffer jsonBuffer;
// JsonObject& root = jsonBuffer.parseObject(msg);
// float temp = root["Temperature"];
// float hum = root["Humidity"];
//
// Serial.println(temp);
// Serial.println(hum);
//}
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
connect_wifi_mqtt();
dht.setup(4, DHTesp::DHT11);
// 订阅节点
// client.subscribe("LED");
// pinMode(pinLED, OUTPUT);
}
void loop() {
// put your main code here, to run repeatedly:
delay(dht.getMinimumSamplingPeriod());
humidity = dht.getHumidity();
temperature = dht.getTemperature();
if (!client.connected()) {
reconnect();
}
client.loop();
encodeJson();
long now = millis();//记录当前时间
if (now - lastMsg > 1000) {//每隔1000毫秒秒发一次数据
encodeJson();
client.publish("homeassistant/sensor/sensorBedroomT/config", msg);
client.publish("homeassistant/sensor/sensorBedroomH/config", msg1);
// Serial.println(msg);
if (isnan(humidity)) {
return;
} else {
client.publish("homeassistant/sensor/sensorBedroom/state", msg2);
client.publish("test", "ttt");
// Serial.println(msg2);
lastMsg = now;
}
}
}
but dht data can publish, who can tell me why? thanks