//安装PubSubClient库

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

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

// MQTT 配置
const char* mqtt_server = "47.242.184.139"; // 公共测试服务器
const int mqtt_port = 1883;
const char* mqtt_user = "admin"; // 如果需要认证
const char* mqtt_password = "publish452131wW452131wW$";

WiFiClient espClient;
PubSubClient client(espClient);

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();
}

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");
      
    } else {
      Serial.print("失败，错误代码: ");
      Serial.print(client.state());
      Serial.println(" 5秒后重试...");
      delay(5000);
    }
  }
}

void setup() {
  Serial.begin(115200);
  setup_wifi();
  
  client.setServer(mqtt_server, mqtt_port);
  client.setCallback(callback);
}

void loop() {
  if(WiFi.status() != WL_CONNECTED){
    setup_wifi();
  }
  if (!client.connected()) {
    reconnect();
  }
  client.loop();

  // 发布消息示例
  static unsigned long lastMsg = 0;
  if (millis() - lastMsg > 5000) {
    lastMsg = millis();
    
    String message = "Hello from ESP32 - " + String(millis());
    client.publish("esp32/status", message.c_str());
    
    Serial.println("消息已发布: " + message);
  }
}