#include <ESP8266WiFi.h>
#include <ArduinoJson.h>

// Wi-Fi 连接信息
const char *ssid = "Xiaomi_3A40";
const char *password = "112233ww";

// 服务器信息
const char *serverIP = "192.168.31.184";        // 服务器 IP 地址
const int serverPort = 80;                      // 端口号
const char *requestPath = "/ESP01/getData.php"; // 请求路径

#define Sleep_Pin 2

void setup()
{
  Serial.begin(115200);
  WiFi.begin(ssid, password);

  // 连接到 Wi-Fi
  Serial.print("Connecting to Wi-Fi");
  while (WiFi.status() != WL_CONNECTED)
  {
    delay(1000);
    Serial.print(".");
  }
  Serial.println("\nWi-Fi connected!");

  pinMode(Sleep_Pin, OUTPUT);
  digitalWrite(Sleep_Pin, LOW);
}

void loop()
{
  // 确保 Wi-Fi 连接正常
  if (WiFi.status() != WL_CONNECTED)
  {
    Serial.println("Wi-Fi disconnected, reconnecting...");
    WiFi.begin(ssid, password);
    while (WiFi.status() != WL_CONNECTED)
    {
      delay(1000);
      Serial.print(".");
    }
    Serial.println("\nReconnected to Wi-Fi!");
  }

  // 创建客户端
  WiFiClient client;

  if (client.connect(serverIP, serverPort))
  {
    Serial.println("Connected to server");

    // 发送 GET 请求
    client.println(String("GET ") + requestPath + " HTTP/1.1");
    client.println(String("Host: ") + serverIP);
    client.println("Connection: close");
    client.println();

    // 等待响应
    while (client.connected() || client.available())
    {
      if (client.available())
      {
        String line = client.readStringUntil('\n');
        if (line == "\r")
        {
          break; // 头部结束
        }
      }
    }

    // 读取 JSON 数据
    String jsonData;
    while (client.available())
    {
      jsonData += client.readString();
    }

    // 打印获取到的 JSON 数据
    Serial.println("Received JSON:");
    Serial.println(jsonData);

    // 解析 JSON 数据
    StaticJsonDocument<512> doc;
    DeserializationError error = deserializeJson(doc, jsonData);
    if (error)
    {
      Serial.print("Failed to parse JSON: ");
      Serial.println(error.c_str());
      return;
    }

    // 提取 JSON 数据
    if (doc.containsKey("standby"))
    {
      String standby = doc["standby"];
      Serial.print("Standby mode: ");
      Serial.println(standby);
      if (standby == "1")
      {
        Serial.println("Standby mode");
        digitalWrite(Sleep_Pin, HIGH); // 打开休眠模式
      }
      else
      {
        Serial.println("Normal mode");
        digitalWrite(Sleep_Pin, LOW); // 关闭休眠模式
      }
    }
    else
    {
      Serial.println("Key 'standby' not found in JSON data");
    }
  }
  else
  {
    Serial.println("Failed to connect to server");
  }

  // 延时一段时间再发送下一次请求
  delay(100);
}
