#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
#include <ESP8266HTTPClient.h>
#include <Ticker.h>


Ticker myTicker;
WiFiClient wificlient;

//被读取的文件位置和名称
String flash_wifi = "/wifi.txt";
ESP8266WebServer ESP8266webServer;  // 创建网络服务器对象,HTTP服务的标准端口为：80
String ssid = "";
String passwd = "";
String html;

void setup(void) {
  Serial.begin(115200);
  delay(1000);
  if (FlashConnetWifi() == false) {
    HtmlSetWifi();
  }
}
void loop(void) {
}

void SetWifi() {
  ssid = ESP8266webServer.arg(0);
  passwd = ESP8266webServer.arg(1);
  String sp = ssid + "&" + passwd;
  Serial.println(sp);
  Serial.println("密码在前面");
  Serial.begin(115200);
  delay(500);
  const char* Ssid = ssid.c_str();
  const char* WifiPw = passwd.c_str();
  WiFi.begin(Ssid, WifiPw);
  WiFi.mode(WIFI_STA);
  delay(200);
  int ii = 0;
  for (ii; ii < 20; ii++) {
    delay(500);
    Serial.print(".");
    if (WiFi.status() == WL_CONNECTED) {
      ESP8266webServer.send(200, "text/plane", "Wifi密码正确,ESP准备重启");
      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(500);
      ESP.restart();
    }
  }
  ESP8266webServer.send(200, "text/plane", "Wifi密码错误,请重新输入");
}
//------- 展示页面-------
void handlejsonStr() {
  ESP8266webServer.send(500, "text/html", html);
}
void handleNotFound(void) {
  ESP8266webServer.send(404, "text/plain", "404-The page is not Found!");
}

void ApStart() {
  WiFi.disconnect();
  delay(500);
  Serial.begin(115200);
  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模式,并设置账号和密码
  WiFi.softAP("192.168.168.2", "nobiggie.cn");
}
void WebserverStart() {
  ESP8266webServer.begin(80);               // 启用网络服务
  ESP8266webServer.on("/", handlejsonStr);  // / 在HTTP中,表示请求首页服务,
  ESP8266webServer.on("/SetWifi", SetWifi);
  ESP8266webServer.onNotFound(handleNotFound);  // 当服务器没找到所需的服务,调用404函数
  Serial.println("webserver started");
}

void ForPing() {
  //定时时间到了,先取消定时状态
  myTicker.detach();
  delay(500);
  ESP.restart();
}

//扫描附件WIFI
void WifiScan() {
  Serial.begin(115200);
  WiFi.disconnect();
  WiFi.mode(WIFI_STA);
  delay(100);
  int n = WiFi.scanNetworks();
  if (n > 0) {
    Serial.println(n);
    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/>" + "<font color=\"red\">附近WiFi没有显示到自己的WIFI请重启或离信号源近点</font>" + "</body>" + "</html>";
    a = a + "</select>";
    html = HtmlStart + a + HtmlEnd;
  } else {
    html = "扫描不到网络";
    Serial.println("扫描不到网络");
  }
}
bool FlashConnetWifi() {
  Serial.begin(115200);
  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 = dateFile.readString();
  result.trim();
  Serial.println(result);
  int i = result.indexOf("&");
  String wifiname = result.substring(0, i);
  String wifipw = result.substring(i + 1);
  const char* Ssid = wifiname.c_str();
  const char* WifiPw = wifipw.c_str();
  WiFi.begin(Ssid, WifiPw);
  delay(500);
  WiFi.mode(WIFI_STA);
  Serial.println("FlashConnetWifi->connet");
  int ii = 0;
  for (ii; ii < 20; ii++) {
    delay(500);
    Serial.print(" . ");
    if (WiFi.status() == WL_CONNECTED) {
      Serial.println("FlashConnetWifi 闪存配置连接成功");
      return true;
    }
  }
  Serial.println("FlashConnetWifi->false");
  return false;
}

void HtmlSetWifi() {
  WifiScan();
  ApStart();
  delay(1000);
  Serial.println("启动网页");
  myTicker.detach();
  delay(200);
  //5分后重启 防止停电后复电,路由器连接WIFI速度慢于ESP导致ESP连接不到路由器进入无限AP模式,所以这里只让AP 激活5分钟后就重启
  myTicker.once(300, espReboot);
  delay(200);
  WebserverStart();
  while (1) {
    ESP8266webServer.handleClient();  // 检查网络服务请求并处理
  }
}
void espReboot() {
  ESP.restart();
}
