`#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <ArduinoJson.h>
#include <Wire.h>
#include <BH1750.h>
#include <SimpleDHT.h>
// WiFi设置
const char* ssid = "A1Q2";
const char* password = "a123456a";
// MQTT服务器设置
const char* mqtt_server = "dev.thingspanel.cn";
const int mqttPort = 1883;
const char* mqtt_user[] = {"user1", "user2", "user3", "user4"};
const char* mqtt_password[] = {"password1", "password2", "password3", "password4"};
const char* mqtt_topic[] = {"device/attributes", "device/attributes", "device/attributes", "device/attributes"};
WiFiClient espClient;
PubSubClient client(espClient);
// 定义传感器引脚
const int pinDHT11 = 1;
SimpleDHT11 dht11;
BH1750 lightMeter;
#define MQ7_ANALOG_PIN A0
#define MQ7_DIGITAL_PIN 16
const int pirPin = 3;
const int num_mqtt_servers = 4;
void setup() {
Serial.begin(115200);
delay(1000);
pinMode(pirPin, INPUT);
Wire.begin(4, 5);
lightMeter.begin();
connectToWiFi();
}
void loop() {
checkAndReconnect();
readAndSendSensorData();
client.loop();
}
void checkAndReconnect() {
if (!client.connected()) {
reconnectMQTT();
}
}
void reconnectMQTT() {
bool connected = false;
for (int i = 0; i < 4; i++) {
Serial.print("Attempting MQTT connection to ");
Serial.print(mqtt_server);
if (client.connect("ESP8266Client", mqtt_user[i], mqtt_password[i])) {
Serial.println(" - connected to server " + String(i));
connected = true;
break;
} else {
Serial.print(" - failed, rc=");
Serial.print(client.state());
Serial.println(" - try next server");
}
}
if (!connected) {
Serial.println("Failed to connect to any MQTT servers. Retrying in 10 seconds...");
delay(10000); // 延迟10秒后重新连接
}
}
void connectToWiFi() {
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());
}
void connectToMQTT() {
for (int i = 0; i < num_mqtt_servers; i++) {
client.setServer(mqtt_server, mqttPort);
}
reconnectMQTT();
}
void readAndSendSensorData() {
readAndSendDHT11Data();
readAndSendLightIntensity();
readAndSendMotionStatus();
}
void readAndSendDHT11Data() {
byte temperature = 0;
byte humidity = 0;
int err = SimpleDHTErrSuccess;
if ((err = dht11.read(pinDHT11, &temperature, &humidity, NULL)) != SimpleDHTErrSuccess) {
Serial.print("Read DHT11 failed, err=");
Serial.println(err);
delay(1000);
return;
}
StaticJsonDocument<100> doc;
doc["temperature"] = (int)temperature;
doc["humidity"] = (int)humidity;
char msg[100];
serializeJson(doc, msg);
client.publish(mqtt_topic[0], msg); // 使用 mqtt_topic[0]
}
void readAndSendLightIntensity() {
float lux = lightMeter.readLightLevel();
sendSensorDataToMQTT(lux, mqtt_topic[1], "LightIntensity");
}
void readAndSendMotionStatus() {
int pirState = digitalRead(pirPin);
sendSensorDataToMQTT(pirState, mqtt_topic[2], "MotionDetect"); // 使用正确的 mqtt_topic[2]
}
void sendSensorDataToMQTT(float value, const char* topic, const char* key) {
StaticJsonDocument<100> doc;
doc[key] = value;
char jsonBuffer[100];
serializeJson(doc, jsonBuffer);
client.publish(topic, jsonBuffer);
}
求解如何优化代码 😃
`