#include "WS_WIFI.h"
const char *ssid = STASSID; // Name of the WIFI you want to connect to
const char *password = STAPSK; // The WIFI password to connect to
WebServer server(80); // Declare the WebServer object
char ipStr[16];
bool WIFI_Connection = 0;
void handleRoot() {
String myhtmlPage =
String("") +
""+
"
"+
" "+
"
"+
" "+
" "+
" "+
"
"+
"
"+
" "+
" "+
" "+
"
"+
"
"+
" "+
" "+
" "+
"
"+
"
"+
" "+
" "+
" "+
"
"+
"
"+
" "+
" "+
" "+
"
"+
"
"+
" "+
" "+
" "+
"
"+
"
"+
" "+
" "+
"
"+
"
"+
"
Please refresh the page
"+
"
Chinese:请刷新页面
"+
"
"+
"
"+
""+
"";
server.send(200, "text/html", myhtmlPage);
printf("The user visited the home page\r\n");
}
void handleGetData() {
String json = "[";
for (int i = 0; i < sizeof(Relay_Flag) / sizeof(Relay_Flag[0]); i++) {
json += String(Relay_Flag[i]);
if (i < sizeof(Relay_Flag) / sizeof(Relay_Flag[0]) - 1) {
json += ",";
}
}
json += "]";
server.send(200, "application/json", json);
}
void handleSwitch(int ledNumber) {
uint8_t Data[1]={0};
Data[0]=ledNumber+48;
Relay_Analysis(Data,WIFI_Mode);
server.send(200, "text/plain", "OK");
}
void handleSwitch1() { handleSwitch(1); }
void handleSwitch2() { handleSwitch(2); }
void handleSwitch3() { handleSwitch(3); }
void handleSwitch4() { handleSwitch(4); }
void handleSwitch5() { handleSwitch(5); }
void handleSwitch6() { handleSwitch(6); }
void handleSwitch7() { handleSwitch(7); }
void handleSwitch8() { handleSwitch(8); }
void WIFI_Init()
{
uint8_t Count = 0;
WiFi.mode(WIFI_STA);
WiFi.setSleep(true);
WiFi.begin(ssid, password); // Connect to the specified Wi-Fi network
while (WiFi.status() != WL_CONNECTED)
{
Count++;
delay(500);
printf(".\r\n");
if(Count % 2 == 0 && Count != 0){
RGB_Light(60, 0, 0);
delay(1000);
RGB_Light(0, 0, 0);
}
if(Count % 10 == 0){ // 10 attempts failed to connect, cancel the connection, try again
WiFi.disconnect();
delay(100);
WiFi.mode(WIFI_OFF);
delay(100);
WiFi.mode(WIFI_STA);
delay(100);
WiFi.begin(ssid, password);
}
if(Count > 22){ // connection fail
break;
}
}
delay(100);
if(Count < 23){
WIFI_Connection = 1;
RGB_Light(0, 60, 0);
delay(1000);
RGB_Light(0, 0, 0);
IPAddress myIP = WiFi.localIP();
printf("IP Address: ");
sprintf(ipStr, "%d.%d.%d.%d", myIP[0], myIP[1], myIP[2], myIP[3]);
printf("%s\r\n", ipStr);
// 注册回调函数
server.on("/", handleRoot);
server.on("/getData", handleGetData);
server.on("/Switch1", handleSwitch1);
server.on("/Switch2", handleSwitch2);
server.on("/Switch3", handleSwitch3);
server.on("/Switch4", handleSwitch4);
server.on("/Switch5", handleSwitch5);
server.on("/Switch6", handleSwitch6);
server.on("/AllOn" , handleSwitch7);
server.on("/AllOff" , handleSwitch8);
server.begin(); //启动服务器
printf("Web server started\r\n");
}
else{
WIFI_Connection = 0;
printf("WIFI connection fails, you can use the Bluetooth debugging Assistant to control the device.\r\n");
RGB_Light(60, 0, 0);
}
}
void WIFI_Loop()
{
if(WIFI_Connection == 1)
server.handleClient(); // Processing requests from clients
}