//安装PubSubClient库
//安装ArduinoJson库
//安装DHT11库  DHT sensor library

#include <WiFi.h>
#include <PubSubClient.h>
#include <DHT.h>
#include <ArduinoJson.h>

#define DHT_PIN 15
#define DHT_TYPE DHT11

DHT dht(DHT_PIN, DHT_TYPE);

// 配置信息
const char* ssid = "rehome";
const char* password = "Ruihong123";

const char* mqtt_server = "47.242.184.139";
const int mqtt_port = 1883;
const char* mqtt_user = "admin"; // 如果需要认证
const char* mqtt_password = "publish452131wW452131wW$";
const char* topic = "/device/esp8266/003";

WiFiClient espClient;
PubSubClient client(espClient);

unsigned long lastSensorRead = 0;
const long sensorInterval = 10000; // 10秒

void setup_wifi() {
  delay(10);
  Serial.println();
  Serial.print("正在连接: ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  Serial.println("");
  Serial.println("WiFi 连接成功");
  Serial.println("IP 地址: ");
  Serial.println(WiFi.localIP());
}

void callback(char* topic, byte* payload, unsigned int length) {
  Serial.print("收到消息 [");
  Serial.print(topic);
  Serial.print("]: ");
  
  for (int i = 0; i < length; i++) {
    Serial.print((char)payload[i]);
  }
  Serial.println();

Serial.println("-------------多主题处理------------ ");
  String message;
  for (int i = 0; i < length; i++) {
    message += (char)payload[i];
  }
  
  Serial.print("主题: ");
  Serial.print(topic);
  Serial.print(" | 消息: ");
  Serial.println(message);
  
  // 根据主题处理消息
  if (String(topic) == "esp32/status") {
    Serial.print("收到传感器数据: ");
    Serial.println(message);
  }
  if (String(topic) == "esp32/sensor/data") {
    Serial.print("收到json数据: ");
    Serial.println(message);
  }
  Serial.println("-------------多主题处理------------ ");
}

void reconnect() {
  while (!client.connected()) {
    Serial.print("尝试 MQTT 连接...");
    
    // 客户端 ID
    String clientId = "ESP32Client-";
    clientId += String(random(0xffff), HEX);
    
    // 尝试连接
    if (client.connect(clientId.c_str(), mqtt_user, mqtt_password)) {
      Serial.println("连接成功");
      
      // 订阅多个主题
      // 订阅主题
      //client.subscribe("esp32/status");
      //client.subscribe("esp32/sensor/data");
      client.subscribe(topic);
      
      
    } else {
      Serial.print("失败，错误代码: ");
      Serial.print(client.state());
      Serial.println(" 5秒后重试...");
      delay(5000);
    }
  }
}



void publishSensorData(float temperature,float humidity) {
  StaticJsonDocument<200> doc;
  doc["device"] = "ESP32_001";
  doc["temperature"] = String(temperature);
  doc["humidity"] = String(humidity);
  doc["timestamp"] = millis();
  
  String jsonString;
  serializeJson(doc, jsonString);
  //两个参数时  QoS 0 - 最多一次
  client.publish("esp32/sensor/data", jsonString.c_str());
  //三个参数时   QoS 1 - 至少一次
  //client.publish("esp32/sensor/data", jsonString.c_str(),true);
}

void readAndPublishSensorData() {
  float temperature = dht.readTemperature();
  float humidity = dht.readHumidity();
  
  if (!isnan(temperature) && !isnan(humidity)) {
    char tempStr[8];
    char humStr[8];
    
    dtostrf(temperature, 6, 2, tempStr);
    dtostrf(humidity, 6, 2, humStr);
    
    //client.publish("iot/sensor/temperature", tempStr);
    //client.publish("iot/sensor/humidity", humStr);
    
    Serial.printf("传感器数据已发布: 温度=%s°C, 湿度=%s%%\n", tempStr, humStr);

    String sendStr = String(temperature)+" "+String(humidity);
    //两个参数时  QoS 0 - 最多一次
    //client.publish("esp32/status", sendStr.c_str());
    client.publish(topic, sendStr.c_str());

    //topic
    //三个参数时   QoS 1 - 至少一次
    //client.publish("esp32/status", sendStr.c_str(),true);
    //发布json格式温湿度数据
    publishSensorData(temperature,humidity);
  }
}

void setup() {
  Serial.begin(115200);
  dht.begin();
  
  setup_wifi();
  client.setServer(mqtt_server, 1883);
  client.setCallback(callback);
  client.setKeepAlive(60);        // 保活时间
  client.setSocketTimeout(30);    // 套接字超时
  client.setBufferSize(1024);     // 缓冲区大小
}

void loop() {
  if(WiFi.status() != WL_CONNECTED){
    setup_wifi();
  }
  if (!client.connected()) {
    reconnect();
  }
  client.loop();
  
  // 定期读取传感器数据
  if (millis() - lastSensorRead > sensorInterval) {
    lastSensorRead = millis();
    readAndPublishSensorData();
  }
}