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

// WIFI相关
const char* ssid = "Wokwi-GUEST";
const char* password = "";
WiFiClient espClient;
String g_hostname = "esp32cam";

// MQTT相关
const char* g_mqtt_server = "119.23.217.2";
const int g_mqtt_port = 1883;
const char* g_mqtt_username = "demo";
const char* g_mqtt_password = "demo123456";
const char* g_mqtt_topic = "/solar/s/camera";

PubSubClient g_mqtt_client(espClient);
String g_mqtt_msg;
int g_mqtt_time_count = 0;

// HTTPClient相关
// HTTPClient http;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);

  // 初始化WIFI
  WiFi.begin(ssid, password);//连接Wifi
  while (WiFi.status() != WL_CONNECTED) {
    Serial.print("wifi connecting...");
    delay(1000);//等待WIfi连接成功
  }

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());

  // 初始化mqtt
  g_mqtt_client.setServer(g_mqtt_server, g_mqtt_port);
  // g_mqtt_client.setKeepAlive(65535);
  g_hostname += "--";
  g_hostname += String(WiFi.macAddress());// 拼接字符串

  while (!g_mqtt_client.connected()) {
    Serial.println("mqtt connecting");
    if (g_mqtt_client.connect(g_hostname.c_str(), g_mqtt_username, g_mqtt_password)) {
      break;
    }
    delay(1000);
  }// end while
  Serial.println("MQTT connected");
  g_mqtt_client.publish(g_mqtt_topic, "boot", true);

  // 下载并发送图片
  HTTPClient http;
  http.begin("https://www.baidu.com/img/flexible/logo/pc/result.png");
  int httpCode = http.GET();
  Serial.println(httpCode);
  if (httpCode == 200) {
    int contentLength = http.getSize(); // 获取内容长度
    if (contentLength > 0) {
      int receivedBytes = 0;
      while (http.connected() && (receivedBytes < contentLength || contentLength == -1)) {
        size_t len = http.getStream().available();
        receivedBytes += len;
        Serial.println(receivedBytes);
        uint8_t* buffer = new uint8_t[len];
        size_t bytesRead = http.getStream().readBytes(buffer, len);
        g_mqtt_client.publish(g_mqtt_topic, buffer, bytesRead, true);
        delete[] buffer; // 释放内存
      }
    }
  }
  Serial.println("image send success");
}

void loop() {
  g_mqtt_client.loop();
  checkMqttStatus();
  delay(10); // this speeds up the simulation
}

/*
  检查MQTT状态,掉线重连
*/
void checkMqttStatus(void) {
  while (!g_mqtt_client.connected()) {
    Serial.print("Attempting MQTT connection...");
    if (g_mqtt_client.connect(g_hostname.c_str(), g_mqtt_username, g_mqtt_password)) {
      Serial.println("mqtt connected");
    } else {
      Serial.print("mqtt reconnect failed, rc=");
      Serial.print(g_mqtt_client.state());
      Serial.println(" try again in 5 seconds");
      delay(5000);
    }
  }
}