//安装mqtt客户端 PubSubClient 库

#include <ESP8266WiFi.h>
#include <PubSubClient.h>

// WiFi settings
const char *ssid = "rehome";             // Replace with your WiFi name
const char *password = "Ruihong123";   // Replace with your WiFi password

// MQTT Broker settings
const char *mqtt_broker = "mqtt.fileview123.com";  // EMQX broker endpoint
const char *mqtt_topic = "/device/esp8266/+";     // MQTT topic
const char *mqtt_username = "admin";  // MQTT username for authentication
const char *mqtt_password = "publish452131wW452131wW$";  // MQTT password for authentication
const int mqtt_port = 1883;  // MQTT port (TCP)
const char *mqtt_topic_publish = "/device/esp8266/status";     // MQTT topic publish

WiFiClient espClient;
PubSubClient mqtt_client(espClient);

void connectToWiFi();

void connectToMQTTBroker();

void mqttCallback(char *topic, byte *payload, unsigned int length);

void setup() {
    Serial.begin(115200);
    connectToWiFi();
    mqtt_client.setServer(mqtt_broker, mqtt_port);
    mqtt_client.setCallback(mqttCallback);
    connectToMQTTBroker();
}

void connectToWiFi() {
    delay(10);
    Serial.println();
    Serial.print("正在连接: ");
    Serial.println(ssid);
    WiFi.begin(ssid, password);
    Serial.print("Connecting to WiFi");
    while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.print(".");
    }
    Serial.println("\nConnected to the WiFi network");
    Serial.println("");
    Serial.println("WiFi 连接成功");
    Serial.println("IP 地址: ");
    Serial.println(WiFi.localIP());
}

void connectToMQTTBroker() {
    while (!mqtt_client.connected()) {
        Serial.print("尝试 MQTT 连接...");
        //String client_id = "esp8266-client-" + String(WiFi.macAddress());
        String client_id = "esp8266-client-";
        client_id += String(random(0xffff), HEX);
        Serial.printf("Connecting to MQTT Broker as %s.....\n", client_id.c_str());
        if (mqtt_client.connect(client_id.c_str(), mqtt_username, mqtt_password)) {
            Serial.println("Connected to MQTT broker");
            Serial.println("连接成功");
            mqtt_client.subscribe(mqtt_topic);
            // Publish message upon successful connection
            //mqtt_client.publish(mqtt_topic, "Hi EMQX I'm ESP8266 ^^");
        } else {
            Serial.print("Failed to connect to MQTT broker, rc=");
            Serial.print(mqtt_client.state());
            Serial.println(" try again in 5 seconds");
            delay(5000);
        }
    }
}

void mqttCallback(char *topic, byte *payload, unsigned int length) {
    Serial.print("Message received on topic: ");
    Serial.println(topic);
    Serial.print("Message:");
    for (unsigned int i = 0; i < length; i++) {
        Serial.print((char) payload[i]);
    }
    Serial.println();
    Serial.println("-----------------------");
}

void loop() {
    if(WiFi.status() != WL_CONNECTED){
        connectToWiFi();
    }
    if (!mqtt_client.connected()) {
        connectToMQTTBroker();
    }
    mqtt_client.loop();
    
    // 发布消息示例
  static unsigned long lastMsg = 0;
  if (millis() - lastMsg > 5000) {
    lastMsg = millis();
    
    String message = "Hello from esp8266 - esp_connect_mqtt.ino_" + String(millis());
    mqtt_client.publish(mqtt_topic_publish, message.c_str());
    
    Serial.println("消息已发布: " + message);
  }
}
