#include <Arduino.h>
#include <WiFi.h>
#include <HTTPClient.h>
#include <HTTPUpdate.h>
WiFiClient wificlient;
String ssid="webserver";
String wifipwd="www.360xyz.cn";
void setup() {
  Serial.begin(115200);
  WiFi.begin(ssid.c_str(), wifipwd.c_str());
  delay(500);
  WiFi.mode(WIFI_STA);
  Serial.println("wifiConnet...");
  while (1) {
    delay(500);
    Serial.print(" . ");
    if (WiFi.status() == WL_CONNECTED) {
      Serial.println("wifi connet success");
      break;
    }
  }
  delay(500);
  String re = esp32post();
  Serial.println(re);
  re.trim();
  if (re.length()>10) {
    while (1) {
      httpUpdate.onStart(update_started);
      httpUpdate.onEnd(update_finished);
      httpUpdate.onProgress(update_progress);
      httpUpdate.onError(update_error);
      t_httpUpdate_return ret = httpUpdate.update(wificlient, re);
      //t_httpUpdate_return ret = httpUpdate.update(wificlient, "server", 80, "/file.bin");
      switch (ret) {
        case HTTP_UPDATE_FAILED:
          Serial.printf("HTTP_UPDATE_FAILED Error (%d): %s\n", httpUpdate.getLastError(), httpUpdate.getLastErrorString().c_str());
          break;
        case HTTP_UPDATE_NO_UPDATES:
          Serial.println("HTTP_UPDATE_NO_UPDATES");
          break;
        case HTTP_UPDATE_OK:
          Serial.println("HTTP_UPDATE_OK");
          break;
      }
    }
  }
}

void loop() {
  // put your main code here, to run repeatedly:
  delay(5000);
  Serial.println("123");
}
void update_started() {
  Serial.println("CALLBACK:  HTTP update process started");
}

void update_finished() {
  Serial.println("CALLBACK:  HTTP update process finished");
}

void update_progress(int cur, int total) {
  Serial.printf("CALLBACK:  HTTP update process at %d of %d bytes...\n", cur, total);
}

void update_error(int err) {
  Serial.printf("CALLBACK:  HTTP update fatal error code %d\n", err);
}

String esp32post() {
  HTTPClient http;
  String url = "http://jyan.nobiggie.cn/query/vs";
  http.begin(wificlient, url);
  http.setTimeout(3000);
  String postStr = "version=nodemcuesp32s01";
  char dataBuff[postStr.length()];
  strcpy(dataBuff, postStr.c_str());
  http.addHeader("Content-Type", "application/x-www-form-urlencoded");
  int httpResponseCode = http.POST(dataBuff);
  if (httpResponseCode > 0) {
    String response = http.getString();
    return response;
  }
  return "";
}