{
//检查mqtt链接是否正常
if (!client.connected()) {
reconnect();
}
client.loop(); //检查调用回调函数
//延迟采集设置,目前延迟时间为2000毫秒
if (read_time == 0 || (millis() - read_time) >= 2000)
{
read_time = millis();
float h = dht.readHumidity(); //读取湿度
float t = dht.readTemperature(); //读取温度
if (isnan(h) || isnan(t)) { //判断温湿度值是否正常,不正常则跳出循环
return;
}
float hic = dht.computeHeatIndex(t, h, false);
humi = h;
temp = t;
snprintf (msg, 75, "{\"datetime\":\"2018-7-2 20:30\",\"temp\":%ld,\"humi\":%ld}", temp,humi);
Serial.print("Publish message: ");
Serial.println(msg);
client.publish("hmdata", msg);
}
}
//链接wifi函数
void setup_wifi() {
delay(10);
// We start by connecting to a WiFi network
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
//mqtt回调函数
void callback(char* topic, byte* payload, unsigned int length) { //回调函数
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
for (int i = 0; i < length; i++) {
Serial.print((char)payload[i]);
}
Serial.println();
// Switch on the LED if an 1 was received as first character
if (length>2){
if ((char)payload[length-2] == '1') {
digitalWrite(ledpin, LOW); // Turn the LED on (Note that LOW is the voltage level
// but actually the LED is on; this is because
// it is acive low on the ESP-01)
} else {
digitalWrite(ledpin, HIGH); // Turn the LED off by making the voltage HIGH
}
}
}
void reconnect() { //每次发布mqtt信息时,需检查链接
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Attempt to connect
if (client.connect("ID_ESP32Client")) {
Serial.println("connected");
// Once connected, publish an announcement...
client.publish("hmdata", "{\"datetime\":\"2018-7-1 19:30\",\"temp\":25,\"humi\":100}"); //发布json格式
// ... and resubscribe
client.subscribe("hmdata"); //订阅
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}