#include <WiFi.h>
#include <WebServer.h>
#include <HTTPClient.h>
#include <FS.h>
#include "SPIFFS.h"
#include "ESPmDNS.h"
#include <Ticker.h>

Ticker myTicker;
String flashWifi = "/wifi.txt";  //wifi密码存放文件
WebServer webServer;
String ssid;
String passwd;
String html;
#define baudRate 115200
void setup(void) {
  if (FlashConnetWifi() == false) {
    HtmlSetWifi();
  }
}

void loop(void) {
}

void HtmlSetWifi() {
  WifiScan();
  apStart();
  delay(1000);
  Serial.println("start webserver");
  //5分后重启 防止停电后复电，路由器连接WIFI速度慢于ESP导致ESP连接不到路由器进入无限AP模式，所以这里只让AP激活5分钟后就重启
  myTicker.once(300, espReboot);
  delay(200);
  webserverStart();
  while (1) {
    webServer.handleClient();  //检查网络服务请求并处理
  }
}
void espReboot() {
  ESP.restart();
}
//扫描附件WIFI
void WifiScan() {
  WiFi.disconnect();
  Serial.begin(baudRate);
  WiFi.mode(WIFI_STA);
  delay(100);
  int n = WiFi.scanNetworks();
  if (n > 0) {
    String a = "附近WiFi <select id=\"ssid\">";
    for (int i = 0; i < n; i++) {
      Serial.println(WiFi.SSID(i));
      a = a + "<option value=\"" + WiFi.SSID(i) + "\">" + WiFi.SSID(i) + "</option>";
      delay(50);
    }
    String HtmlStart = 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 ssida=document.getElementById(\"ssid\").value;" + "var ssid=ssida.replace(/\\s+/g, \" \");" + "var passwda=document.getElementsByTagName('input')[0].value;" + "var passwd=passwda.replace(/\\s+/g, \" \");" + "xhr = new XMLHttpRequest();" + "xhr.open(\"POST\",\"./setWifi\",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>";
    String HtmlEnd = String("") + "<p>WiFi密码<input type=\"text\" id=\"passwd\"></p>" + "<input type=\"submit\" id=\"up\" value=\"设 置\">" + "<hr/>" + "<div>如果附近WiFi没有显示到自己的WIFI<div>" + "<div>请重启或离信号近点</div>" + "<div>连接成功AP热点退出转WIFI_STA</div>" + "</body>" + "</html>";
    a = a + "</select>";
    html = HtmlStart + a + HtmlEnd;
  } else {
    html = "扫描不到网络";
  }
}
void setWifi() {
  ssid = webServer.arg(0);
  passwd = webServer.arg(1);
  const char* Ssid = ssid.c_str();
  const char* Passwd = passwd.c_str();
  String sp = ssid + "&" + passwd;
  Serial.println(sp);
  Serial.begin(baudRate);
  delay(500);
  WiFi.begin(Ssid, Passwd);
  WiFi.mode(WIFI_STA);
  delay(200);
  Serial.println("wifi_connet");
  int ii = 0;
  for (ii; ii < 20; ii++) {
    delay(500);
    Serial.print(".");
    if (WiFi.status() == WL_CONNECTED) {
      webServer.send(200, "text/plane", "Wifi密码正确,ESP准备重启");
      webServer.close();
      delay(500);
      WiFi.disconnect();
      delay(500);
      //写入数据
      SPIFFS.format();
      delay(500);
      SPIFFS.begin();
      File dataFile = SPIFFS.open(flashWifi, "w");
      dataFile.println(sp);
      dataFile.close();
      Serial.println("HTML设置网络连接成功");
      delay(500);
      ESP.restart();
    }
  }
  webServer.send(200, "text/plane", "Wifi密码错误,请重新输入");
}
//------- 展示页面-------
void handleRoot() {
  webServer.send(500, "text/html", html);
}
void handleNotFound(void) {
  webServer.send(404, "text/plain", "404-The page is not Found!");
}
void apStart() {
  Serial.begin(baudRate);
  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", "nobiggie.cn");
  if (result) {
    Serial.println(String("Soft-AP IP address = ") + WiFi.softAPIP());
  }
}
void webserverStart() {
  webServer.begin(80);            // 启用网络服务
  webServer.on("/", handleRoot);  // / 在HTTP中，表示请求首页服务，
  webServer.on("/setWifi", setWifi);
  webServer.onNotFound(handleNotFound);  // 当服务器没找到所需的服务，调用404函数
  Serial.println("webserver started");
}
bool FlashConnetWifi() {
  Serial.begin(baudRate);
  delay(200);
  SPIFFS.begin();
  if (SPIFFS.exists(flashWifi) == false) {
    Serial.println("NOT FOUND");
    return false;
  }

  File dateFile = SPIFFS.open(flashWifi, "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);
  const char* WifiName = wifiname.c_str();
  const char* WifiPw = wifipw.c_str();
  Serial.println(WifiName);
  Serial.println(WifiPw);
  WiFi.begin(WifiName, WifiPw);
  delay(500);
  WiFi.mode(WIFI_STA);
  Serial.println("FlashConnet...");
  int ii = 0;
  for (ii; ii < 20; ii++) {
    delay(500);
    Serial.print(" . ");
    if (WiFi.status() == WL_CONNECTED) {
      Serial.println("flash connet success");
      return true;
    }
  }
  Serial.println("flash read error");
  return false;
}