#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
#include <ESP8266HTTPClient.h>
#include <FS.h>
int v = 0;
float val11;
float val2;
//被读取的文件位置和名称
String flash_wifi = "/wifi.txt";
ESP8266WebServer ESP8266webServer(80);  // 创建网络服务器对象，HTTP服务的标准端口为：80
String ssid = "";
String passwd = "";
String html = String("") + "<!DOCTYPE html>" +
              "<html>" +
              "<head>" +
              "<meta charset='utf-8'>" +
              "<meta name='viewport' content='width=device-width,initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no' />" +
              "<title>设置WiFi</title>" +
              "<link rel='stylesheet' href=''>" +
              "</head>" +
              "<script>" +
              "onload  = function() {" +
              "document.getElementById('up').onclick = function(){" +
              "var ssid=document.getElementsByTagName('input')[0].value;" +
              "var passwd=document.getElementsByTagName('input')[1].value;" +
              "xhr = new XMLHttpRequest();" +
              "xhr.open('POST','./set_wifi',true);" +
              "var posts = ('ssid='+ssid+'&passwd='+ passwd);" +
              "xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');" +
              "xhr.send(posts);" +
              "xhr.onreadystatechange = function(){" +
              " if(this.readyState == 4 && this.status == 200){" +
              "alert(this.responseText);" +
              " }" +
              " }" +
              "}" +
              "}" +
              "</script>" +
              "<body>" +
              "<p>WiFi帐号<input type='text' name='ssid'></p>" +
              "<p>WiFi密码<input type='text' name='passwd'></p>" +
              "<input type='submit' id='up' value='设置'>" +
              "<div>连接成功AP热点退出转WIFI_STA</div>" +
              "</body>" +
              "</html>";
int d5 = 14;
String flash_sql = "/sql.txt";
//连网状态
bool wifibool = false;
void setup(void) {
  pinMode(d5, INPUT_PULLUP);//默认是高电平
  bool wifibool = wifi_bool();
  if (wifibool == false) {
    ap_start();
    delay(1000);
    Serial.println("bei wang");
    webserver_start();
    while (1) {
      ESP8266webServer.handleClient();   // 检查网络服务请求并处理
    }
  }
  SPIFFS.remove(flash_sql);
}
void loop(void) {
  // put your main code here, to run repeatedly:
  float temp;
  val11 = analogRead(v);
  temp = val11 / 6.492;
  //val11=(int)temp;//
  val2 = temp * 0.1;
  Serial.println(val2);
  SPIFFS.begin();
  //网络是否连通
  for (int i = 0; i < 10; i++) {
    if (http_get("http://www.360xyz.cn/server/ping_websocket") != "") {
      wifibool = true;
      break;
    }
    delay(500);
  }
  //追加内容 可读可写
  File dataFile = SPIFFS.open(flash_sql, "a+");

  //给D5对地短接 表示要发送消息到服务器
  if (digitalRead(d5) == LOW) {
    if (wifibool == false) {
      WiFi.disconnect();
      delay(500);
      //连接WIFI
      wifibool = wifi_bool();
    }
    //连接成功
    if (wifibool == true) {
      String result = dataFile.readString();
      Serial.println(result);
      if (result.length() > 10) {
        http_post("http://www.360xyz.cn/internet/RuestEspData", "user=Taurus_Feb&data=" + result);
        Serial.println("发送");
      }
    }
    //发送完毕，清除文件
    SPIFFS.remove(flash_sql);
  }
  //把数据存到 flash闪存里
  String result = dataFile.readString();
  Serial.println(result);
  if (val2 > 0) {
    String aabb = "|" + String(val2);
    dataFile.print(aabb);
    delay(200);

    dataFile.close();
  }

  delay(60000);
}
void set_wifi() {
  ssid = ESP8266webServer.arg(0);
  passwd = ESP8266webServer.arg(1);
  String sp = ssid + "&" + passwd;
  Serial.println(sp);
  Serial.begin(19200);
  delay(500);
  WiFi.begin(ssid, passwd);
  WiFi.mode(WIFI_STA);
  delay(200);
  Serial.println("wifi_connet");
  int ii = 0;
  for (ii; ii < 30; ii++) {
    delay(500);
    Serial.print(".");
    if (WiFi.status() == WL_CONNECTED) {
      ESP8266webServer.close();
      delay(500);
      WiFi.disconnect();
      delay(500);
      //写入数据
      SPIFFS.format();
      delay(500);
      SPIFFS.begin();
      File dataFile = SPIFFS.open(flash_wifi, "w");
      dataFile.println(sp);
      dataFile.close();
      Serial.println("HTML连接成功");
      delay(1000);
      ESP.reset();
    }
  }

}
//------- 展示页面-------
void handleRoot() {
  ESP8266webServer.send(300, "text/html", html);
}
void handleNotFound(void) {
  ESP8266webServer.send(404, "text/plain", "404-The page is not Found!");
}


void ap_start() {
  Serial.begin(19200);
  WiFi.mode(WIFI_AP);
  IPAddress local_IP(192, 168, 168, 2);
  IPAddress gateway(192, 168, 168, 1);
  IPAddress subnet(255, 255, 255, 0);
  WiFi.softAPConfig(local_IP, gateway, subnet) ;

  //启动AP模式，并设置账号和密码
  boolean result = WiFi.softAP("192.168.168.2", "192.168.168.2");
  if (result) {
    //输出 soft-ap ip地址
    //Serial.println(String("Soft-AP IP address = ") + WiFi.softAPIP());
  }
}
void webserver_start() {
  //-----------------启动webserver网络服务--------------------
  ESP8266webServer.begin(); // 启用网络服务
  ESP8266webServer.on("/", handleRoot);   // / 在HTTP中，表示请求首页服务，
  ESP8266webServer.on("/set_wifi", set_wifi);
  ESP8266webServer.onNotFound(handleNotFound);    // 当服务器没找到所需的服务，调用404函数
  Serial.println("webserver started");
}
bool wifi_bool() {
  Serial.begin(19200);
  delay(500);
  //是否存在数据
  SPIFFS.begin();
  if (SPIFFS.exists(flash_wifi) == false) {
    Serial.print(flash_wifi);
    Serial.println(" NOT FOUND");
    return false;
  }

  File dateFile = SPIFFS.open(flash_wifi, "r");
  String result;
  for (int i = 0; i < dateFile.size(); i++) {
    //Serial.print((char)dateFile.read());
    result += (char)dateFile.read();
  }
  //去除前后空格
  result.trim();
  Serial.println(result);
  int i = result.indexOf("&");
  String wifiname = result.substring(0, i);
  String wifipw = result.substring(i + 1);
  Serial.println(wifiname);
  Serial.println(wifipw);
  WiFi.begin(wifiname, wifipw);
  delay(500);
  WiFi.mode(WIFI_STA);
  Serial.println("wifi_bool->connet");
  int ii = 0;
  for (ii; ii < 300; ii++) {
    delay(500);
    Serial.print(" . ");
    if (WiFi.status() == WL_CONNECTED) {
      Serial.println("wifi_bool 闪存配置连接成功");
      return true;
    }
  }
  Serial.println("wifi_bool->false");
  return false;
}
String http_post(String url, String postStr) {
  HTTPClient http;
  String response;
  http.begin(url);
  http.setTimeout(3000);
  //需要传输的数据
  char dataBuff[postStr.length()];
  strcpy(dataBuff, postStr.c_str());
  //头信息，需要的反注释就可以
  //http.addHeader("Content-Type", "application/json;charset=utf-8");
  http.addHeader("Content-Type", "application/x-www-form-urlencoded");
  int httpCode = http.POST(dataBuff);
  if (httpCode == 200) {
    response = http.getString();
    //Serial.println(response);
    return response;
  }
  http.end();
}
String http_get(String string) {
  HTTPClient http;
  String response;
  http.begin(string);
  http.setTimeout(3000);
  int httpCode = http.GET();
  if (httpCode == 200) {
    //读取响应内容
    response = http.getString();
    //Serial.println(response);
    http.end();
    return response;
  }
  http.end();
  return "";
}