#line 1 "c:\\Users\\32244\\Desktop\\BIlinkerAndHttpsOta\\httpslei.cpp"
#include <WiFi.h>
#include <freertos/FreeRTOSConfig.h>
#include "httpslei.h"
#include <Arduino.h>
#include <HTTPClient.h>
#include <WiFiClientSecure.h>
/*
 *    - ESP_OK: OTA data updated, next reboot will use specified partition.
 *    - ESP_FAIL: For generic failure.
 *    - ESP_ERR_INVALID_ARG: Invalid argument
 *    - ESP_ERR_OTA_VALIDATE_FAILED: Invalid app image
 *    - ESP_ERR_NO_MEM: Cannot allocate memory for OTA operation.
 *    - ESP_ERR_FLASH_OP_TIMEOUT or ESP_ERR_FLASH_OP_FAIL: Flash write failed.
 *    - For other return codes, refer OTA documentation in esp-idf's app_update component.
 */
static const char *url = "https://www.lshserver.com:9006/test/esp32-v1.bin"; //state url of your firmware image
String urls = "https://www.lshserver.com:9006/test/";
static const char *server_certificate =\
"-----BEGIN CERTIFICATE-----\n\
MIIDrzCCApegAwIBAgIQCDvgVpBCRrGhdWrJWZHHSjANBgkqhkiG9w0BAQUFADBh\n\
MQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3\n\
d3cuZGlnaWNlcnQuY29tMSAwHgYDVQQDExdEaWdpQ2VydCBHbG9iYWwgUm9vdCBD\n\
QTAeFw0wNjExMTAwMDAwMDBaFw0zMTExMTAwMDAwMDBaMGExCzAJBgNVBAYTAlVT\n\
MRUwEwYDVQQKEwxEaWdpQ2VydCBJbmMxGTAXBgNVBAsTEHd3dy5kaWdpY2VydC5j\n\
b20xIDAeBgNVBAMTF0RpZ2lDZXJ0IEdsb2JhbCBSb290IENBMIIBIjANBgkqhkiG\n\
9w0BAQEFAAOCAQ8AMIIBCgKCAQEA4jvhEXLeqKTTo1eqUKKPC3eQyaKl7hLOllsB\n\
CSDMAZOnTjC3U/dDxGkAV53ijSLdhwZAAIEJzs4bg7/fzTtxRuLWZscFs3YnFo97\n\
nh6Vfe63SKMI2tavegw5BmV/Sl0fvBf4q77uKNd0f3p4mVmFaG5cIzJLv07A6Fpt\n\
43C/dxC//AH2hdmoRBBYMql1GNXRor5H4idq9Joz+EkIYIvUX7Q6hL+hqkpMfT7P\n\
T19sdl6gSzeRntwi5m3OFBqOasv+zbMUZBfHWymeMr/y7vrTC0LUq7dBMtoM1O/4\n\
gdW7jVg/tRvoSSiicNoxBN33shbyTApOB6jtSj1etX+jkMOvJwIDAQABo2MwYTAO\n\
BgNVHQ8BAf8EBAMCAYYwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUA95QNVbR\n\
TLtm8KPiGxvDl7I90VUwHwYDVR0jBBgwFoAUA95QNVbRTLtm8KPiGxvDl7I90VUw\n\
DQYJKoZIhvcNAQEFBQADggEBAMucN6pIExIK+t1EnE9SsPTfrgT1eXkIoyQY/Esr\n\
hMAtudXH/vTBH1jLuG2cenTnmCmrEbXjcKChzUyImZOMkXDiqw8cvpOp/2PV5Adg\n\
06O/nVsJ8dWO41P0jmP6P6fbtGbfYmbW0W5BjfIttep3Sp+dWOIrWcBAI+0tKIJF\n\
PnlUkiaY4IBIqDfv8NZ5YBberOgOzW6sRBc4L0na4UU+Krk2U886UAb3LujEV0ls\n\
YSEY1QSteDwsOoBrp+uvFRTp2InBuThs4pFsiv9kuXclVzDAGySj4dzp30d8tbQk\n\
CAUw7C29C79Fv1C5qfPrmAESrciIxpg0X40KPMbp1ZWVbd4=\n\
-----END CERTIFICATE-----\n";

HttpsOTAStatus_t otastatus;
extern EventGroupHandle_t *ota_status_pointer;  // which is defined in C:\Users\32244\AppData\Local\Arduino15\packages\esp32\hardware\esp32\2.0.4\libraries\Update\src\HttpsOTAUpdate.cpp
void HttpEvent(HttpEvent_t *event)
{
    switch(event->event_id) {
        case HTTP_EVENT_ERROR:
            Serial.println("Http Event Error");
            break;
        case HTTP_EVENT_ON_CONNECTED:
            Serial.println("Http Event On Connected");
            break;
        case HTTP_EVENT_HEADER_SENT:
            Serial.println("Http Event Header Sent");
            break;
        case HTTP_EVENT_ON_HEADER:
            Serial.printf("Http Event On Header, key=%s, value=%s\n", event->header_key, event->header_value);
            break;
        case HTTP_EVENT_ON_DATA:
            break;
        case HTTP_EVENT_ON_FINISH:
            Serial.println("Http Event On Finish");
            break;
        case HTTP_EVENT_DISCONNECTED:
            Serial.println("Http Event Disconnected");
            break;
    }
}
void readStaus(void *p){
  printf("TaskMy running\n");
  for (; ; ) {
    otastatus = HttpsOTA.status();
    if(otastatus == HTTPS_OTA_SUCCESS) {
        Serial.println("Firmware written successfully");
        // otaSuccess();
        for(int i=10;i>0;i--){
          Serial.printf("Now to restart... %d\n",i);
          *ota_status_pointer = NULL;
          delay(500);
        }
        ESP.restart();
        delay(3000);
    } else if(otastatus == HTTPS_OTA_FAIL) {
        Serial.println("Firmware Upgrade Fail");
        *ota_status_pointer = NULL;
        vTaskDelete(NULL);
    }
    delay(1000);
  }
}
/***/
int checkNewOTA(const String version){
  WiFiClientSecure *client = new WiFiClientSecure;
  int httpCode = 0;
  if(client) {
    client -> setCACert(server_certificate);
    {
      // Add a scoping block for HTTPClient https to make sure it is destroyed before WiFiClientSecure *client is 
      HTTPClient https;
      Serial.print("[HTTPS_CHECK] begin "+urls+"esp32-"+version+".bin"+"\n");
      if (https.begin(*client,urls+"esp32-"+version+".bin")) {  // HTTPS
        Serial.print("[HTTPS_CHECK] GET...\n");
        // start connection and send HTTP header
        httpCode = https.GET();
        // httpCode will be negative on error
        if (httpCode > 0) {
          // HTTP header has been send and Server response header has been handled
          Serial.printf("[HTTPS_CHECK] GET... code: %d\n", httpCode);
          // file found at server
          if (httpCode == HTTP_CODE_OK || httpCode == HTTP_CODE_MOVED_PERMANENTLY) {
            Serial.println("file is ok");
          }
        } else {
          Serial.printf("[HTTPS_CHECK] GET... failed, error: %s\n", https.errorToString(httpCode).c_str());
        }
        https.end();
      } else {
        Serial.printf("[HTTPS_CHECK] Unable to connect\n");
      }
      // End extra scoping block
    }
    delete client;
  } else {
    Serial.println("Unable to create client");
  }
  return httpCode;
}
void httpsOtaStart(){
    HttpsOTA.onHttpEvent(HttpEvent); //启用https 调试信息
    HttpsOTA.begin(url,server_certificate);//开始升级
    xTaskCreate(readStaus,"readStaus",2048,NULL,2, NULL);//状态回调
}
void httpsOtaTurnOn(){
    
}
/* 
第一步：在setup中调用 httpsOtaTurnOn()
第二步：在需要升级的时候调用 httpsOtaStart();
*/