3 #include <ESPAsyncWebServer.h>
4 #include <StreamString.h>
7 bool isApEnabled = false;
8 bool isWebStarted = false;
10 bool pendingWiFi = false;
11 bool pendingAuth = false;
13 AsyncWebServer server(80);
14 AsyncEventSource events("/events");
21 void reportChange(const __FlashStringHelper* name) {
23 ConfigParameter* param = cfg.getParam(name);
25 switch (param->getType()) {
27 sprintf(buf,"{\"%s\":%s}", name, param->getBoolValue()?"true":"false");
30 sprintf(buf,"{\"%s\":%d}", name, param->getIntValue());
33 sprintf(buf,"{\"%s\":%f}", name, param->getFloatValue());
36 sprintf(buf,"{\"%s\":\"%s\"}", name, param->getCharValue());
39 events.send(buf,"update",millis());
43 void sendInitial(AsyncEventSourceClient *client) {
44 String mac = WiFi.macAddress();
46 sprintf(buf,"{\"_mac\":\"%s\",\"_weather\":\"%s\"}", mac.c_str(), weatherData);
47 client->send(buf,"keepalive",millis());
53 sprintf(buf,"{\"_weather\":\"%s\"}",weatherData);
54 events.send(buf,"keepalive",millis());
57 void sendKeepalive() {
58 static unsigned long lastMillis = 0;
59 static unsigned long uptimeCorrection = 0;
60 unsigned long currentMillis = millis();
61 unsigned long uptime = millis()/1000;
62 if (currentMillis < lastMillis) {
63 uptimeCorrection += lastMillis/1000;
65 lastMillis = millis();
66 uptime = uptime + uptimeCorrection;
67 int days = uptime / 86400;
68 uptime = uptime % 86400;
69 int hrs = uptime / 3600;
70 uptime = uptime % 3600;
71 int mins = uptime / 60;
73 int heap = ESP.getFreeHeap();
74 int rssi = WiFi.RSSI();
75 struct tm* timeinfo = localtime(&last_sync);
76 bool changed = cfg.getTimestamp() != 0;
77 char sync[16] = "--:--:--";
79 sprintf(sync, "%02d:%02d:%02d", timeinfo->tm_hour, timeinfo->tm_min, timeinfo->tm_sec);
83 sprintf(buf,"{\"_uptime\":\"%d д %d ч %d % м %d с\", \"_date\":\"%02d.%2d.%04d\", \"_time\":\"%02d:%02d\",\"_heap\":\"%d б\", \"_rssi\":\"%d\", \"_last_sync\":\"%s\", \"_changed\":%s}", days, hrs, mins, uptime, dd, mm, yy, hh, mi, heap, rssi, sync, changed?"true":"false");
85 sprintf(buf,"{\"_uptime\":\"%d ч %d % м %d с\", \"_date\":\"%02d.%2d.%04d\", \"_time\":\"%02d:%02d\",\"_heap\":\"%d б\", \"_rssi\":\"%d\", \"_last_sync\":\"%s\", \"_changed\":%s}", hrs, mins, uptime, dd, mm, yy, hh, mi, heap, rssi, sync, changed?"true":"false");
87 sprintf(buf,"{\"_uptime\":\"%d м %d с\", \"_date\":\"%02d.%2d.%04d\", \"_time\":\"%02d:%02d\",\"_heap\":\"%d б\", \"_rssi\":\"%d\", \"_last_sync\":\"%s\", \"_changed\":%s}", mins, uptime, dd, mm, yy, hh, mi, heap, rssi, sync, changed?"true":"false");
89 events.send(buf,"keepalive",millis());
92 void apply(const char* name) {
93 if (strcmp(name,"sta_ssid") == 0 || strcmp(name,"sta_psk") == 0) {
97 } else if (strcmp(name,"ap_ssid") == 0 || strcmp(name,"ap_psk") == 0) {
101 } else if (strcmp(name,"auth_user") == 0 || strcmp(name,"auth_pwd") == 0) {
103 } else if (strcmp(name,"ntp_server") == 0 || strcmp(name,"tz") == 0) {
105 } else if (strcmp(name,"pin_sda") == 0 || strcmp(name,"pin_scl") == 0 ||
106 strcmp(name,"i2c_speed") == 0 || strcmp(name,"enable_rtc") == 0 ||
107 strcmp(name,"enable_button") == 0 || strcmp(name,"button_pin") == 0 || strcmp(name,"button_inversed") == 0 ||
108 strcmp(name,"enable_buzzer") == 0 || strcmp(name,"buzzer_pin") == 0) {
110 } else if (strcmp(name,"pin_din") == 0 || strcmp(name,"pin_clk") == 0 ||
111 strcmp_P(name,"pin_cs") == 0 || strcmp(name,"led_modules") == 0){
113 } else if (strcmp(name,"panel_brightness_day") == 0 || strcmp_P(name,"panel_brightness_night") == 0 ||
114 strcmp_P(name,"day_from") == 0 || strcmp(name,"night_from") == 0){
115 setPanelBrightness();
119 char* actionScheduled = nullptr;
120 unsigned long millisScheduled = 0;
132 Serial.println("Setting authentication...");
133 strncpy(auth_user,cfg.getCharValue(F("auth_user")),31);
134 strncpy(auth_pwd,cfg.getCharValue(F("auth_pwd")),31);
136 server.on("/action", HTTP_GET, [](AsyncWebServerRequest* request) {
137 if (auth_user && auth_pwd && auth_user[0] && auth_pwd[0] && !request->authenticate(auth_user, auth_pwd)) {
138 return request-> requestAuthentication();
140 if(request->hasParam("name")) {
141 const char* action = request->getParam("name")->value().c_str();
142 if (strcmp(action,"restart") == 0) {
144 request->send(200,"application/json", "{\"result\":\"FAILED\",\"message\":\"Не применены настройки WiFi\", \"page\":\"wifi\"}");
145 } else if (pendingAuth) {
146 request->send(200,"application/json", "{\"result\":\"FAILED\",\"message\":\"Не применены настройки авторизации\", \"page\":\"system\"}");
148 request->send(200,"application/json", "{\"result\":\"OK\",\"message\":\"Перезагружаюсь\"}");
149 millisScheduled = millis();
150 actionScheduled = "restart";
152 } else if (strcmp(action,"wifi") == 0) {
154 request->send(200,"application/json", "{\"result\":\"FAILED\",\"message\":\"Не применены настройки авторизации\", \"page\":\"system\"}");
156 request->send(200,"application/json", "{\"result\":\"OK\",\"message\":\"Применяю настройки\"}");
157 millisScheduled = millis();
158 actionScheduled = "wifi";
160 } else if (strcmp(action,"auth") == 0) {
161 request->send(200,"application/json", "{\"result\":\"OK\",\"message\":\"Применяю настройки\"}");
162 millisScheduled = millis();
163 actionScheduled = "auth";
164 } else if (strcmp(action,"save") == 0) {
166 request->send(200,"application/json", "{\"result\":\"FAILED\",\"message\":\"Не применены настройки WiFi\", \"page\":\"wifi\"}");
167 } else if (pendingAuth) {
168 request->send(200,"application/json", "{\"result\":\"FAILED\",\"message\":\"Не применены настройки авторизации\", \"page\":\"system\"}");
170 request->send(200,"application/json", "{\"result\":\"OK\",\"message\":\"Сохраняю настройки\"}");
171 millisScheduled = millis();
172 actionScheduled = "save";
178 server.on("/wifi/scan", HTTP_GET, [](AsyncWebServerRequest* request) {
179 if (auth_user && auth_pwd && auth_user[0] && auth_pwd[0] && !request->authenticate(auth_user, auth_pwd)) {
180 return request-> requestAuthentication();
183 int n = WiFi.scanComplete();
185 WiFi.scanNetworks(true);
187 for (int i = 0; i < n; ++i) {
190 json += "\"rssi\":" + String(WiFi.RSSI(i));
191 json += ",\"ssid\":\"" + WiFi.SSID(i) + "\"";
192 json += ",\"bssid\":\"" + WiFi.BSSIDstr(i) + "\"";
193 json += ",\"channel\":" + String(WiFi.channel(i));
194 json += ",\"secure\":" + String(WiFi.encryptionType(i));
195 json += ",\"hidden\":" + String(WiFi.isHidden(i) ? "true" : "false");
199 if (WiFi.scanComplete() == -2) {
200 WiFi.scanNetworks(true);
204 request->send(200, "application/json", json);
208 server.on("/config/get", HTTP_GET, [](AsyncWebServerRequest* request) {
209 if (auth_user && auth_pwd && auth_user[0] && auth_pwd[0] && !request->authenticate(auth_user, auth_pwd)) {
210 return request-> requestAuthentication();
212 AsyncResponseStream* s = request->beginResponseStream("application/json");
214 for (int i = 0; i < cfg.getParametersCount(); i++) {
215 ConfigParameter* param = cfg.getParameter(i);
216 if (i) s->print(",");
218 s->print(param->getID());
220 switch (param->getType()) {
222 s->print(param->getBoolValue() ? "true" : "false");
225 s->print(param->getIntValue());
228 s->print(param->getFloatValue());
232 s->print(param->getCharValue());
241 server.on("/config/set", HTTP_GET, [](AsyncWebServerRequest* request) {
242 if (auth_user && auth_pwd && auth_user[0] && auth_pwd[0] && !request->authenticate(auth_user, auth_pwd)) {
243 return request-> requestAuthentication();
245 if(request->hasParam("name") && (request->hasParam("value"))) {
246 const char* name = request->getParam("name")->value().c_str();
247 const char* value = request->getParam("value")->value().c_str();
248 Serial.print(name); Serial.print(" = "); Serial.println(value);
250 ConfigParameter* param = cfg.getParam(name);
252 switch (param->getType()) {
254 cfg.setValue(name, strcmp(value, "true")==0);
255 sprintf(buf,"{\"%s\":%s}", name, param->getBoolValue()?"true":"false");
258 cfg.setValue(name, atoi(value));
259 sprintf(buf,"{\"%s\":%d}", name, param->getIntValue());
262 cfg.setValue(name, atof(value));
263 sprintf(buf,"{\"%s\":%f}", name, param->getFloatValue());
266 cfg.setValue(name, value);
267 sprintf(buf,"{\"%s\":\"%s\"}", name, param->getCharValue());
272 request->send(500, "text/plain", "Unknown parameter name");
275 request->send(200,"application/json",buf);
277 request->send(500, "text/plain", "Not all parameters set");
281 server.serveStatic("ui", LittleFS, "/ui.json").setAuthentication(auth_user,auth_pwd);
283 server.serveStatic("/", LittleFS, "/web/").setDefaultFile("index.html").setAuthentication(auth_user,auth_pwd);
285 server.onNotFound([](AsyncWebServerRequest *request){
286 request->send(404,"text/plain","Not found");
289 events.onConnect([](AsyncEventSourceClient *client){
293 events.setAuthentication(auth_user,auth_pwd);
295 server.addHandler(&events);
299 tKeepalive.attach(2, sendKeepalive);
303 #define CFG_AUTOSAVE 15
306 static char storedSSID[64];
307 static char storedPSK[64];
308 static bool connectInProgress = false;
309 static unsigned long connectMillis = 0;
310 if (actionScheduled && millis()>millisScheduled+300) {
311 Serial.print(F("Scheduled action ")); Serial.println(actionScheduled);
313 if (strcmp(actionScheduled,"restart") == 0) {
316 } else if (strcmp(actionScheduled,"auth") == 0) {
317 Serial.println("New authentication credentials");
318 strncpy(auth_user,cfg.getCharValue(F("auth_user")),31);
319 strncpy(auth_pwd,cfg.getCharValue(F("auth_pwd")),31);
321 } else if (strcmp(actionScheduled,"wifi") == 0) {
322 Serial.println("New wifi credentials");
323 strcpy(storedSSID,WiFi.SSID().c_str());
324 strcpy(storedPSK,WiFi.psk().c_str());
326 WiFi.begin(cfg.getCharValue("sta_ssid"),cfg.getCharValue("sta_psk"));
327 connectInProgress = true;
328 connectMillis = millis();
329 } else if (strcmp(actionScheduled,"save") == 0 && !pendingWiFi && !pendingAuth) {
332 actionScheduled = nullptr;
334 if (connectInProgress && (millis() > connectMillis + 1000)) {
335 if (WiFi.status() == WL_CONNECTED) {
337 sprintf(buf,"Подключен к %s, IP=%s", WiFi.SSID(), WiFi.localIP().toString().c_str());
341 connectInProgress = false;
342 } else if (WiFi.status() == WL_CONNECT_FAILED || WiFi.status() == WL_NO_SSID_AVAIL || ((WiFi.status() == WL_CONNECTION_LOST || WiFi.status() == WL_DISCONNECTED) && (millis()>connectMillis+1000*cfg.getIntValue("sta_wait")))) {
343 Serial.println(F("Подключение не удалось, возвращаю прежние настройки"));
344 message(F("Подключение не удалось, возвращаю прежние настройки"),1);
345 WiFi.begin(storedSSID, storedPSK);
346 connectInProgress = false;
350 if (!pendingWiFi && !pendingAuth && cfg.getTimestamp() && cfg.getTimestamp() < now - CFG_AUTOSAVE) {
352 Serial.println(F("Настройки сохранены"));