add bleJoystick as a button event (#2842)
[ExpressLRS.git] / src / lib / WIFI / devWIFI.cpp
blob5fda5bac7bf43c2c15c6262b97cf176534150862
1 #include "device.h"
3 #if defined(PLATFORM_ESP8266) || defined(PLATFORM_ESP32)
5 #include "deferred.h"
7 #include <AsyncJson.h>
8 #include <ArduinoJson.h>
9 #if defined(PLATFORM_ESP8266)
10 #include <FS.h>
11 #else
12 #include <SPIFFS.h>
13 #endif
15 #if defined(PLATFORM_ESP32)
16 #include <WiFi.h>
17 #include <ESPmDNS.h>
18 #include <Update.h>
19 #include <esp_partition.h>
20 #include <esp_ota_ops.h>
21 #include <soc/uart_pins.h>
22 #else
23 #include <ESP8266WiFi.h>
24 #include <ESP8266mDNS.h>
25 #define wifi_mode_t WiFiMode_t
26 #endif
27 #include <DNSServer.h>
29 #include <set>
30 #include <StreamString.h>
32 #include <ESPAsyncWebServer.h>
33 #include "AsyncJson.h"
34 #include "ArduinoJson.h"
36 #include "common.h"
37 #include "POWERMGNT.h"
38 #include "FHSS.h"
39 #include "hwTimer.h"
40 #include "logging.h"
41 #include "options.h"
42 #include "helpers.h"
43 #include "devVTXSPI.h"
44 #include "devButton.h"
46 #include "WebContent.h"
48 #include "config.h"
50 #if defined(TARGET_TX)
52 #include "wifiJoystick.h"
54 extern TxConfig config;
55 extern void setButtonColors(uint8_t b1, uint8_t b2);
56 #else
57 extern RxConfig config;
58 #endif
60 extern unsigned long rebootTime;
62 static char station_ssid[33];
63 static char station_password[65];
65 static bool wifiStarted = false;
66 bool webserverPreventAutoStart = false;
68 static wl_status_t laststatus = WL_IDLE_STATUS;
69 volatile WiFiMode_t wifiMode = WIFI_OFF;
70 static volatile WiFiMode_t changeMode = WIFI_OFF;
71 static volatile unsigned long changeTime = 0;
73 static const byte DNS_PORT = 53;
74 static IPAddress netMsk(255, 255, 255, 0);
75 static DNSServer dnsServer;
76 static IPAddress ipAddress;
78 #if defined(USE_MSP_WIFI) && defined(TARGET_RX) //MSP2WIFI in enabled only for RX only at the moment
79 #include "crsf2msp.h"
80 #include "msp2crsf.h"
82 #include "tcpsocket.h"
83 TCPSOCKET wifi2tcp(5761); //port 5761 as used by BF configurator
84 #endif
86 #if defined(PLATFORM_ESP8266)
87 static bool scanComplete = false;
88 #endif
90 static AsyncWebServer server(80);
91 static bool servicesStarted = false;
92 static constexpr uint32_t STALE_WIFI_SCAN = 20000;
93 static uint32_t lastScanTimeMS = 0;
95 static bool target_seen = false;
96 static uint8_t target_pos = 0;
97 static String target_found;
98 static bool target_complete = false;
99 static bool force_update = false;
100 static uint32_t totalSize;
102 void setWifiUpdateMode()
104 // No need to ExitBindingMode(), the radio will be stopped stopped when start the Wifi service.
105 // Need to change this before the mode change event so the LED is updated
106 InBindingMode = false;
107 connectionState = wifiUpdate;
110 /** Is this an IP? */
111 static boolean isIp(String str)
113 for (size_t i = 0; i < str.length(); i++)
115 int c = str.charAt(i);
116 if (c != '.' && (c < '0' || c > '9'))
118 return false;
121 return true;
124 /** IP to String? */
125 static String toStringIp(IPAddress ip)
127 String res = "";
128 for (int i = 0; i < 3; i++)
130 res += String((ip >> (8 * i)) & 0xFF) + ".";
132 res += String(((ip >> 8 * 3)) & 0xFF);
133 return res;
136 static bool captivePortal(AsyncWebServerRequest *request)
138 extern const char *wifi_hostname;
140 if (!isIp(request->host()) && request->host() != (String(wifi_hostname) + ".local"))
142 DBGLN("Request redirected to captive portal");
143 request->redirect(String("http://") + toStringIp(request->client()->localIP()));
144 return true;
146 return false;
149 static struct {
150 const char *url;
151 const char *contentType;
152 const uint8_t* content;
153 const size_t size;
154 } files[] = {
155 {"/scan.js", "text/javascript", (uint8_t *)SCAN_JS, sizeof(SCAN_JS)},
156 {"/mui.js", "text/javascript", (uint8_t *)MUI_JS, sizeof(MUI_JS)},
157 {"/elrs.css", "text/css", (uint8_t *)ELRS_CSS, sizeof(ELRS_CSS)},
158 {"/hardware.html", "text/html", (uint8_t *)HARDWARE_HTML, sizeof(HARDWARE_HTML)},
159 {"/hardware.js", "text/javascript", (uint8_t *)HARDWARE_JS, sizeof(HARDWARE_JS)},
160 {"/cw.html", "text/html", (uint8_t *)CW_HTML, sizeof(CW_HTML)},
161 {"/cw.js", "text/javascript", (uint8_t *)CW_JS, sizeof(CW_JS)},
164 static void WebUpdateSendContent(AsyncWebServerRequest *request)
166 for (size_t i=0 ; i<ARRAY_SIZE(files) ; i++) {
167 if (request->url().equals(files[i].url)) {
168 AsyncWebServerResponse *response = request->beginResponse_P(200, files[i].contentType, files[i].content, files[i].size);
169 response->addHeader("Content-Encoding", "gzip");
170 request->send(response);
171 return;
174 request->send(404, "text/plain", "File not found");
177 static void WebUpdateHandleRoot(AsyncWebServerRequest *request)
179 if (captivePortal(request))
180 { // If captive portal redirect instead of displaying the page.
181 return;
183 force_update = request->hasArg("force");
184 AsyncWebServerResponse *response;
185 if (connectionState == hardwareUndefined)
187 response = request->beginResponse_P(200, "text/html", (uint8_t*)HARDWARE_HTML, sizeof(HARDWARE_HTML));
189 else
191 response = request->beginResponse_P(200, "text/html", (uint8_t*)INDEX_HTML, sizeof(INDEX_HTML));
193 response->addHeader("Content-Encoding", "gzip");
194 response->addHeader("Cache-Control", "no-cache, no-store, must-revalidate");
195 response->addHeader("Pragma", "no-cache");
196 response->addHeader("Expires", "-1");
197 request->send(response);
200 static void putFile(AsyncWebServerRequest *request, uint8_t *data, size_t len, size_t index, size_t total)
202 static File file;
203 static size_t bytes;
204 if (!file || request->url() != file.name()) {
205 file = SPIFFS.open(request->url(), "w");
206 bytes = 0;
208 file.write(data, len);
209 bytes += len;
210 if (bytes == total) {
211 file.close();
215 static void getFile(AsyncWebServerRequest *request)
217 if (request->url() == "/options.json") {
218 request->send(200, "application/json", getOptions());
219 } else if (request->url() == "/hardware.json") {
220 request->send(200, "application/json", getHardware());
221 } else {
222 request->send(SPIFFS, request->url().c_str(), "text/plain", true);
226 static void HandleReboot(AsyncWebServerRequest *request)
228 AsyncWebServerResponse *response = request->beginResponse(200, "application/json", "Kill -9, no more CPU time!");
229 response->addHeader("Connection", "close");
230 request->send(response);
231 request->client()->close();
232 rebootTime = millis() + 100;
235 static void HandleReset(AsyncWebServerRequest *request)
237 if (request->hasArg("hardware")) {
238 SPIFFS.remove("/hardware.json");
240 if (request->hasArg("options")) {
241 SPIFFS.remove("/options.json");
243 if (request->hasArg("model") || request->hasArg("config")) {
244 config.SetDefaults(true);
246 AsyncWebServerResponse *response = request->beginResponse(200, "application/json", "Reset complete, rebooting...");
247 response->addHeader("Connection", "close");
248 request->send(response);
249 request->client()->close();
250 rebootTime = millis() + 100;
253 static void UpdateSettings(AsyncWebServerRequest *request, JsonVariant &json)
255 if (firmwareOptions.flash_discriminator != json["flash-discriminator"].as<uint32_t>()) {
256 request->send(409, "text/plain", "Mismatched device identifier, refresh the page and try again.");
257 return;
260 File file = SPIFFS.open("/options.json", "w");
261 serializeJson(json, file);
262 request->send(200);
265 static const char *GetConfigUidType(const JsonObject json)
267 #if defined(TARGET_RX)
268 if (config.GetBindStorage() == BINDSTORAGE_VOLATILE)
269 return "Volatile";
270 if (config.GetBindStorage() == BINDSTORAGE_RETURNABLE && config.IsOnLoan())
271 return "Loaned";
272 if (config.GetIsBound())
273 return "Bound";
274 return "Not Bound";
275 #else
276 if (firmwareOptions.hasUID)
278 if (json["options"]["customised"] | false)
279 return "Overridden";
280 else
281 return "Flashed";
283 return "Not set (using MAC address)";
284 #endif
287 static void GetConfiguration(AsyncWebServerRequest *request)
289 bool exportMode = request->hasArg("export");
290 AsyncJsonResponse *response = new AsyncJsonResponse();
291 JsonObject json = response->getRoot();
293 if (!exportMode)
295 JsonDocument options;
296 deserializeJson(options, getOptions());
297 json["options"] = options;
300 JsonArray uid = json["config"]["uid"].to<JsonArray>();
301 copyArray(UID, UID_LEN, uid);
303 #if defined(TARGET_TX)
304 int button_count = 0;
305 if (GPIO_PIN_BUTTON != UNDEF_PIN)
306 button_count = 1;
307 if (GPIO_PIN_BUTTON2 != UNDEF_PIN)
308 button_count = 2;
309 for (int button=0 ; button<button_count ; button++)
311 const tx_button_color_t *buttonColor = config.GetButtonActions(button);
312 if (hardware_int(button == 0 ? HARDWARE_button_led_index : HARDWARE_button2_led_index) != -1) {
313 json["config"]["button-actions"][button]["color"] = buttonColor->val.color;
315 for (int pos=0 ; pos<button_GetActionCnt() ; pos++)
317 json["config"]["button-actions"][button]["action"][pos]["is-long-press"] = buttonColor->val.actions[pos].pressType ? true : false;
318 json["config"]["button-actions"][button]["action"][pos]["count"] = buttonColor->val.actions[pos].count;
319 json["config"]["button-actions"][button]["action"][pos]["action"] = buttonColor->val.actions[pos].action;
322 if (exportMode)
324 json["config"]["fan-mode"] = config.GetFanMode();
325 json["config"]["power-fan-threshold"] = config.GetPowerFanThreshold();
327 json["config"]["motion-mode"] = config.GetMotionMode();
329 json["config"]["vtx-admin"]["band"] = config.GetVtxBand();
330 json["config"]["vtx-admin"]["channel"] = config.GetVtxChannel();
331 json["config"]["vtx-admin"]["pitmode"] = config.GetVtxPitmode();
332 json["config"]["vtx-admin"]["power"] = config.GetVtxPower();
333 json["config"]["backpack"]["dvr-start-delay"] = config.GetDvrStartDelay();
334 json["config"]["backpack"]["dvr-stop-delay"] = config.GetDvrStopDelay();
335 json["config"]["backpack"]["dvr-aux-channel"] = config.GetDvrAux();
337 for (int model = 0 ; model < CONFIG_TX_MODEL_CNT ; model++)
339 const model_config_t &modelConfig = config.GetModelConfig(model);
340 String strModel(model);
341 JsonObject modelJson = json["config"]["model"][strModel].to<JsonObject>();
342 modelJson["packet-rate"] = modelConfig.rate;
343 modelJson["telemetry-ratio"] = modelConfig.tlm;
344 modelJson["switch-mode"] = modelConfig.switchMode;
345 modelJson["power"]["max-power"] = modelConfig.power;
346 modelJson["power"]["dynamic-power"] = modelConfig.dynamicPower;
347 modelJson["power"]["boost-channel"] = modelConfig.boostChannel;
348 modelJson["model-match"] = modelConfig.modelMatch;
349 modelJson["tx-antenna"] = modelConfig.txAntenna;
352 #endif /* TARGET_TX */
354 if (!exportMode)
356 json["config"]["ssid"] = station_ssid;
357 json["config"]["mode"] = wifiMode == WIFI_STA ? "STA" : "AP";
358 #if defined(TARGET_RX)
359 json["config"]["serial-protocol"] = config.GetSerialProtocol();
360 #if defined(PLATFORM_ESP32)
361 json["config"]["serial1-protocol"] = config.GetSerial1Protocol();
362 #endif
363 json["config"]["sbus-failsafe"] = config.GetFailsafeMode();
364 json["config"]["modelid"] = config.GetModelId();
365 json["config"]["force-tlm"] = config.GetForceTlmOff();
366 json["config"]["vbind"] = config.GetBindStorage();
367 #if defined(GPIO_PIN_PWM_OUTPUTS)
368 for (int ch=0; ch<GPIO_PIN_PWM_OUTPUTS_COUNT; ++ch)
370 json["config"]["pwm"][ch]["config"] = config.GetPwmChannel(ch)->raw;
371 json["config"]["pwm"][ch]["pin"] = GPIO_PIN_PWM_OUTPUTS[ch];
372 uint8_t features = 0;
373 auto pin = GPIO_PIN_PWM_OUTPUTS[ch];
374 if (pin == U0TXD_GPIO_NUM) features |= 1; // SerialTX supported
375 else if (pin == U0RXD_GPIO_NUM) features |= 2; // SerialRX supported
376 else if (pin == GPIO_PIN_SCL) features |= 4; // I2C SCL supported (only on this pin)
377 else if (pin == GPIO_PIN_SDA) features |= 8; // I2C SCL supported (only on this pin)
378 else if (GPIO_PIN_SCL == UNDEF_PIN || GPIO_PIN_SDA == UNDEF_PIN) features |= 12; // Both I2C SCL/SDA supported (on any pin)
379 #if defined(PLATFORM_ESP32)
380 if (pin != 0) features |= 16; // DShot supported on all pins but GPIO0
381 if (pin == GPIO_PIN_SERIAL1_RX) features |= 32; // SERIAL1 RX supported (only on this pin)
382 else if (pin == GPIO_PIN_SERIAL1_TX) features |= 64; // SERIAL1 TX supported (only on this pin)
383 else if ((GPIO_PIN_SERIAL1_RX == UNDEF_PIN || GPIO_PIN_SERIAL1_TX == UNDEF_PIN) &&
384 (!(features & 1) && !(features & 2))) features |= 96; // Both Serial1 RX/TX supported (on any pin if not already featured for Serial 1)
385 #endif
386 json["config"]["pwm"][ch]["features"] = features;
388 #endif
389 #endif
390 json["config"]["product_name"] = product_name;
391 json["config"]["lua_name"] = device_name;
392 json["config"]["reg_domain"] = FHSSgetRegulatoryDomain();
393 json["config"]["has-highpower"] = (MaxPower != HighPower);
394 json["config"]["uidtype"] = GetConfigUidType(json);
397 response->setLength();
398 request->send(response);
401 #if defined(TARGET_TX)
402 static void UpdateConfiguration(AsyncWebServerRequest *request, JsonVariant &json)
404 if (json.containsKey("button-actions")) {
405 const JsonArray &array = json["button-actions"].as<JsonArray>();
406 for (size_t button=0 ; button<array.size() ; button++)
408 tx_button_color_t action;
409 for (int pos=0 ; pos<button_GetActionCnt() ; pos++)
411 action.val.actions[pos].pressType = array[button]["action"][pos]["is-long-press"];
412 action.val.actions[pos].count = array[button]["action"][pos]["count"];
413 action.val.actions[pos].action = array[button]["action"][pos]["action"];
415 action.val.color = array[button]["color"];
416 config.SetButtonActions(button, &action);
419 config.Commit();
420 request->send(200, "text/plain", "Import/update complete");
423 static void ImportConfiguration(AsyncWebServerRequest *request, JsonVariant &json)
425 if (json.containsKey("config"))
427 json = json["config"];
430 if (json.containsKey("fan-mode")) config.SetFanMode(json["fan-mode"]);
431 if (json.containsKey("power-fan-threshold")) config.SetPowerFanThreshold(json["power-fan-threshold"]);
432 if (json.containsKey("motion-mode")) config.SetMotionMode(json["motion-mode"]);
434 if (json.containsKey("vtx-admin"))
436 if (json["vtx-admin"].containsKey("band")) config.SetVtxBand(json["vtx-admin"]["band"]);
437 if (json["vtx-admin"].containsKey("channel")) config.SetVtxChannel(json["vtx-admin"]["channel"]);
438 if (json["vtx-admin"].containsKey("pitmode")) config.SetVtxPitmode(json["vtx-admin"]["pitmode"]);
439 if (json["vtx-admin"].containsKey("power")) config.SetVtxPower(json["vtx-admin"]["power"]);
442 if (json.containsKey("backpack"))
444 if (json["backpack"].containsKey("dvr-start-delay")) config.SetDvrStartDelay(json["backpack"]["dvr-start-delay"]);
445 if (json["backpack"].containsKey("dvr-stop-delay")) config.SetDvrStopDelay(json["backpack"]["dvr-stop-delay"]);
446 if (json["backpack"].containsKey("dvr-aux-channel")) config.SetDvrAux(json["backpack"]["dvr-aux-channel"]);
449 if (json.containsKey("model"))
451 for(JsonPair kv : json["model"].as<JsonObject>())
453 uint8_t model = atoi(kv.key().c_str());
454 JsonObject modelJson = kv.value();
456 config.SetModelId(model);
457 if (modelJson.containsKey("packet-rate")) config.SetRate(modelJson["packet-rate"]);
458 if (modelJson.containsKey("telemetry-ratio")) config.SetTlm(modelJson["telemetry-ratio"]);
459 if (modelJson.containsKey("switch-mode")) config.SetSwitchMode(modelJson["switch-mode"]);
460 if (modelJson.containsKey("power"))
462 if (modelJson["power"].containsKey("max-power")) config.SetPower(modelJson["power"]["max-power"]);
463 if (modelJson["power"].containsKey("dynamic-power")) config.SetDynamicPower(modelJson["power"]["dynamic-power"]);
464 if (modelJson["power"].containsKey("boost-channel")) config.SetBoostChannel(modelJson["power"]["boost-channel"]);
466 if (modelJson.containsKey("model-match")) config.SetModelMatch(modelJson["model-match"]);
467 // if (modelJson.containsKey("tx-antenna")) config.SetTxAntenna(modelJson["tx-antenna"]);
468 // have to commmit after each model is updated
469 config.Commit();
473 UpdateConfiguration(request, json);
476 static void WebUpdateButtonColors(AsyncWebServerRequest *request, JsonVariant &json)
478 int button1Color = json[0].as<int>();
479 int button2Color = json[1].as<int>();
480 DBGLN("%d %d", button1Color, button2Color);
481 setButtonColors(button1Color, button2Color);
482 request->send(200);
484 #else
486 * @brief: Copy uid to config if changed
488 static void JsonUidToConfig(JsonVariant &json)
490 JsonArray juid = json["uid"].as<JsonArray>();
491 size_t juidLen = constrain(juid.size(), 0, UID_LEN);
492 uint8_t newUid[UID_LEN] = { 0 };
494 // Copy only as many bytes as were included, right-justified
495 // This supports 6-digit UID as well as 4-digit (OTA bound) UID
496 copyArray(juid, &newUid[UID_LEN-juidLen], juidLen);
498 if (memcmp(newUid, config.GetUID(), UID_LEN) != 0)
500 config.SetUID(newUid);
501 config.Commit();
502 // Also copy it to the global UID in case the page is reloaded
503 memcpy(UID, newUid, UID_LEN);
506 static void UpdateConfiguration(AsyncWebServerRequest *request, JsonVariant &json)
508 uint8_t protocol = json["serial-protocol"] | 0;
509 config.SetSerialProtocol((eSerialProtocol)protocol);
511 #if defined(PLATFORM_ESP32)
512 uint8_t protocol1 = json["serial1-protocol"] | 0;
513 config.SetSerial1Protocol((eSerial1Protocol)protocol1);
514 #endif
516 uint8_t failsafe = json["sbus-failsafe"] | 0;
517 config.SetFailsafeMode((eFailsafeMode)failsafe);
519 long modelid = json["modelid"] | 255;
520 if (modelid < 0 || modelid > 63) modelid = 255;
521 config.SetModelId((uint8_t)modelid);
523 long forceTlm = json["force-tlm"] | 0;
524 config.SetForceTlmOff(forceTlm != 0);
526 config.SetBindStorage((rx_config_bindstorage_t)(json["vbind"] | 0));
527 JsonUidToConfig(json);
529 #if defined(GPIO_PIN_PWM_OUTPUTS)
530 JsonArray pwm = json["pwm"].as<JsonArray>();
531 for(uint32_t channel = 0 ; channel < pwm.size() ; channel++)
533 uint32_t val = pwm[channel];
534 //DBGLN("PWMch(%u)=%u", channel, val);
535 config.SetPwmChannelRaw(channel, val);
537 #endif
539 config.Commit();
540 request->send(200, "text/plain", "Configuration updated");
542 #endif
544 static void WebUpdateGetTarget(AsyncWebServerRequest *request)
546 JsonDocument json;
547 json["target"] = &target_name[4];
548 json["version"] = VERSION;
549 json["product_name"] = product_name;
550 json["lua_name"] = device_name;
551 json["reg_domain"] = FHSSgetRegulatoryDomain();
552 json["git-commit"] = commit;
553 #if defined(TARGET_TX)
554 json["module-type"] = "TX";
555 #endif
556 #if defined(TARGET_RX)
557 json["module-type"] = "RX";
558 #endif
559 #if defined(RADIO_SX128X)
560 json["radio-type"] = "SX128X";
561 json["has-sub-ghz"] = false;
562 #endif
563 #if defined(RADIO_SX127X)
564 json["radio-type"] = "SX127X";
565 json["has-sub-ghz"] = true;
566 #endif
567 #if defined(RADIO_LR1121)
568 json["radio-type"] = "LR1121";
569 json["has-sub-ghz"] = true;
570 #endif
572 AsyncResponseStream *response = request->beginResponseStream("application/json");
573 serializeJson(json, *response);
574 request->send(response);
577 static void WebUpdateSendNetworks(AsyncWebServerRequest *request)
579 int numNetworks = WiFi.scanComplete();
580 if (numNetworks >= 0 && millis() - lastScanTimeMS < STALE_WIFI_SCAN) {
581 DBGLN("Found %d networks", numNetworks);
582 std::set<String> vs;
583 String s="[";
584 for(int i=0 ; i<numNetworks ; i++) {
585 String w = WiFi.SSID(i);
586 DBGLN("found %s", w.c_str());
587 if (vs.find(w)==vs.end() && w.length()>0) {
588 if (!vs.empty()) s += ",";
589 s += "\"" + w + "\"";
590 vs.insert(w);
593 s+="]";
594 request->send(200, "application/json", s);
595 } else {
596 if (WiFi.scanComplete() != WIFI_SCAN_RUNNING)
598 #if defined(PLATFORM_ESP8266)
599 scanComplete = false;
600 WiFi.scanNetworksAsync([](int){
601 scanComplete = true;
603 #else
604 WiFi.scanNetworks(true);
605 #endif
606 lastScanTimeMS = millis();
608 request->send(204, "application/json", "[]");
612 static void sendResponse(AsyncWebServerRequest *request, const String &msg, WiFiMode_t mode) {
613 AsyncWebServerResponse *response = request->beginResponse(200, "text/plain", msg);
614 response->addHeader("Connection", "close");
615 request->send(response);
616 request->client()->close();
617 changeTime = millis();
618 changeMode = mode;
621 static void WebUpdateAccessPoint(AsyncWebServerRequest *request)
623 DBGLN("Starting Access Point");
624 String msg = String("Access Point starting, please connect to access point '") + wifi_ap_ssid + "' with password '" + wifi_ap_password + "'";
625 sendResponse(request, msg, WIFI_AP);
628 static void WebUpdateConnect(AsyncWebServerRequest *request)
630 DBGLN("Connecting to network");
631 String msg = String("Connecting to network '") + station_ssid + "', connect to http://" +
632 wifi_hostname + ".local from a browser on that network";
633 sendResponse(request, msg, WIFI_STA);
636 static void WebUpdateSetHome(AsyncWebServerRequest *request)
638 String ssid = request->arg("network");
639 String password = request->arg("password");
641 DBGLN("Setting network %s", ssid.c_str());
642 strcpy(station_ssid, ssid.c_str());
643 strcpy(station_password, password.c_str());
644 if (request->hasArg("save")) {
645 strlcpy(firmwareOptions.home_wifi_ssid, ssid.c_str(), sizeof(firmwareOptions.home_wifi_ssid));
646 strlcpy(firmwareOptions.home_wifi_password, password.c_str(), sizeof(firmwareOptions.home_wifi_password));
647 saveOptions();
649 WebUpdateConnect(request);
652 static void WebUpdateForget(AsyncWebServerRequest *request)
654 DBGLN("Forget network");
655 firmwareOptions.home_wifi_ssid[0] = 0;
656 firmwareOptions.home_wifi_password[0] = 0;
657 saveOptions();
658 station_ssid[0] = 0;
659 station_password[0] = 0;
660 String msg = String("Home network forgotten, please connect to access point '") + wifi_ap_ssid + "' with password '" + wifi_ap_password + "'";
661 sendResponse(request, msg, WIFI_AP);
664 static void WebUpdateHandleNotFound(AsyncWebServerRequest *request)
666 if (captivePortal(request))
667 { // If captive portal redirect instead of displaying the error page.
668 return;
670 String message = F("File Not Found\n\n");
671 message += F("URI: ");
672 message += request->url();
673 message += F("\nMethod: ");
674 message += (request->method() == HTTP_GET) ? "GET" : "POST";
675 message += F("\nArguments: ");
676 message += request->args();
677 message += F("\n");
679 for (uint8_t i = 0; i < request->args(); i++)
681 message += String(F(" ")) + request->argName(i) + F(": ") + request->arg(i) + F("\n");
683 AsyncWebServerResponse *response = request->beginResponse(404, "text/plain", message);
684 response->addHeader("Cache-Control", "no-cache, no-store, must-revalidate");
685 response->addHeader("Pragma", "no-cache");
686 response->addHeader("Expires", "-1");
687 request->send(response);
690 static void corsPreflightResponse(AsyncWebServerRequest *request) {
691 AsyncWebServerResponse *response = request->beginResponse(204, "text/plain");
692 request->send(response);
695 static void WebUploadResponseHandler(AsyncWebServerRequest *request) {
696 if (target_seen || Update.hasError()) {
697 String msg;
698 if (!Update.hasError() && Update.end()) {
699 DBGLN("Update complete, rebooting");
700 msg = String("{\"status\": \"ok\", \"msg\": \"Update complete. ");
701 #if defined(TARGET_RX)
702 msg += "Please wait for the LED to resume blinking before disconnecting power.\"}";
703 #else
704 msg += "Please wait for a few seconds while the device reboots.\"}";
705 #endif
706 rebootTime = millis() + 200;
707 } else {
708 StreamString p = StreamString();
709 if (Update.hasError()) {
710 Update.printError(p);
711 } else {
712 p.println("Not enough data uploaded!");
714 p.trim();
715 DBGLN("Failed to upload firmware: %s", p.c_str());
716 msg = String("{\"status\": \"error\", \"msg\": \"") + p + "\"}";
718 AsyncWebServerResponse *response = request->beginResponse(200, "application/json", msg);
719 response->addHeader("Connection", "close");
720 request->send(response);
721 request->client()->close();
722 } else {
723 String message = String("{\"status\": \"mismatch\", \"msg\": \"<b>Current target:</b> ") + (const char *)&target_name[4] + ".<br>";
724 if (target_found.length() != 0) {
725 message += "<b>Uploaded image:</b> " + target_found + ".<br/>";
727 message += "<br/>It looks like you are flashing firmware with a different name to the current firmware. This sometimes happens because the hardware was flashed from the factory with an early version that has a different name. Or it may have even changed between major releases.";
728 message += "<br/><br/>Please double check you are uploading the correct target, then proceed with 'Flash Anyway'.\"}";
729 request->send(200, "application/json", message);
733 static void WebUploadDataHandler(AsyncWebServerRequest *request, const String& filename, size_t index, uint8_t *data, size_t len, bool final) {
734 force_update = force_update || request->hasArg("force");
735 if (index == 0) {
736 #ifdef HAS_WIFI_JOYSTICK
737 WifiJoystick::StopJoystickService();
738 #endif
740 size_t filesize = request->header("X-FileSize").toInt();
741 DBGLN("Update: '%s' size %u", filename.c_str(), filesize);
742 #if defined(PLATFORM_ESP8266)
743 Update.runAsync(true);
744 uint32_t maxSketchSpace = (ESP.getFreeSketchSpace() - 0x1000) & 0xFFFFF000;
745 DBGLN("Free space = %u", maxSketchSpace);
746 UNUSED(maxSketchSpace); // for warning
747 #endif
748 if (!Update.begin(filesize, U_FLASH)) { // pass the size provided
749 Update.printError(LOGGING_UART);
751 target_seen = false;
752 target_found.clear();
753 target_complete = false;
754 target_pos = 0;
755 totalSize = 0;
757 if (len) {
758 DBGVLN("writing %d", len);
759 if (Update.write(data, len) == len) {
760 if (force_update || (totalSize == 0 && *data == 0x1F))
761 target_seen = true;
762 if (!target_seen) {
763 for (size_t i=0 ; i<len ;i++) {
764 if (!target_complete && (target_pos >= 4 || target_found.length() > 0)) {
765 if (target_pos == 4) {
766 target_found.clear();
768 if (data[i] == 0 || target_found.length() > 50) {
769 target_complete = true;
771 else {
772 target_found += (char)data[i];
775 if (data[i] == target_name[target_pos]) {
776 ++target_pos;
777 if (target_pos >= target_name_size) {
778 target_seen = true;
781 else {
782 target_pos = 0; // Startover
786 totalSize += len;
787 } else {
788 DBGLN("write failed to write %d", len);
793 static void WebUploadForceUpdateHandler(AsyncWebServerRequest *request) {
794 target_seen = true;
795 if (request->arg("action").equals("confirm")) {
796 WebUploadResponseHandler(request);
797 } else {
798 #if defined(PLATFORM_ESP32)
799 Update.abort();
800 #endif
801 request->send(200, "application/json", "{\"status\": \"ok\", \"msg\": \"Update cancelled\"}");
805 #ifdef HAS_WIFI_JOYSTICK
806 static void WebUdpControl(AsyncWebServerRequest *request)
808 const String &action = request->arg("action");
809 if (action.equals("joystick_begin"))
811 WifiJoystick::StartSending(request->client()->remoteIP(),
812 request->arg("interval").toInt(), request->arg("channels").toInt());
813 request->send(200, "text/plain", "ok");
815 else if (action.equals("joystick_end"))
817 WifiJoystick::StopSending();
818 request->send(200, "text/plain", "ok");
821 #endif
823 static size_t firmwareOffset = 0;
824 static size_t getFirmwareChunk(uint8_t *data, size_t len, size_t pos)
826 uint8_t *dst;
827 uint8_t alignedBuffer[7];
828 if ((uintptr_t)data % 4 != 0)
830 // If data is not aligned, read aligned byes using the local buffer and hope the next call will be aligned
831 dst = (uint8_t *)((uint32_t)alignedBuffer / 4 * 4);
832 len = 4;
834 else
836 // Otherwise just make sure len is a multiple of 4 and smaller than a sector
837 dst = data;
838 len = constrain((len / 4) * 4, 4, SPI_FLASH_SEC_SIZE);
841 ESP.flashRead(firmwareOffset + pos, (uint32_t *)dst, len);
843 // If using local stack buffer, move the 4 bytes into the passed buffer
844 // data is known to not be aligned so it is moved byte-by-byte instead of as uint32_t*
845 if ((void *)dst != (void *)data)
847 for (unsigned b=len; b>0; --b)
848 *data++ = *dst++;
850 return len;
853 static void WebUpdateGetFirmware(AsyncWebServerRequest *request) {
854 #if defined(PLATFORM_ESP32)
855 const esp_partition_t *running = esp_ota_get_running_partition();
856 if (running) {
857 firmwareOffset = running->address;
859 #endif
860 const size_t firmwareTrailerSize = 4096; // max number of bytes for the options/hardware layout json
861 AsyncWebServerResponse *response = request->beginResponse("application/octet-stream", (size_t)ESP.getSketchSize() + firmwareTrailerSize, &getFirmwareChunk);
862 String filename = String("attachment; filename=\"") + (const char *)&target_name[4] + "_" + VERSION + ".bin\"";
863 response->addHeader("Content-Disposition", filename);
864 request->send(response);
867 static void HandleContinuousWave(AsyncWebServerRequest *request) {
868 if (request->hasArg("radio")) {
869 SX12XX_Radio_Number_t radio = request->arg("radio").toInt() == 1 ? SX12XX_Radio_1 : SX12XX_Radio_2;
871 bool setSubGHz = false;
872 #if defined(RADIO_LR1121)
873 setSubGHz = request->arg("subGHz").toInt() == 1;
874 #endif
876 AsyncWebServerResponse *response = request->beginResponse(204);
877 response->addHeader("Connection", "close");
878 request->send(response);
879 request->client()->close();
881 Radio.TXdoneCallback = [](){};
882 Radio.Begin(FHSSgetMinimumFreq(), FHSSgetMaximumFreq());
884 POWERMGNT::init();
885 POWERMGNT::setPower(POWERMGNT::getMinPower());
887 #if defined(RADIO_LR1121)
888 Radio.startCWTest(setSubGHz ? FHSSconfig->freq_center : FHSSconfigDualBand->freq_center, radio);
889 #else
890 Radio.startCWTest(FHSSconfig->freq_center, radio);
891 #if defined(RADIO_SX127X)
892 deferExecutionMillis(50, [radio](){ Radio.cwRepeat(radio); });
893 #endif
894 #endif
895 } else {
896 int radios = (GPIO_PIN_NSS_2 == UNDEF_PIN) ? 1 : 2;
897 request->send(200, "application/json", String("{\"radios\": ") + radios + ", \"center\": "+ FHSSconfig->freq_center +
898 #if defined(RADIO_LR1121)
899 ", \"center2\": "+ FHSSconfigDualBand->freq_center +
900 #endif
901 "}");
905 static void initialize()
907 wifiStarted = false;
908 WiFi.disconnect(true);
909 WiFi.mode(WIFI_OFF);
910 #if defined(PLATFORM_ESP8266)
911 WiFi.forceSleepBegin();
912 #endif
913 registerButtonFunction(ACTION_START_WIFI, [](){
914 setWifiUpdateMode();
918 static void startWiFi(unsigned long now)
920 if (wifiStarted) {
921 return;
924 if (connectionState < FAILURE_STATES) {
925 hwTimer::stop();
927 #ifdef HAS_VTX_SPI
928 disableVTxSpi();
929 #endif
931 // Set transmit power to minimum
932 POWERMGNT::setPower(MinPower);
934 setWifiUpdateMode();
936 DBGLN("Stopping Radio");
937 Radio.End();
940 DBGLN("Begin Webupdater");
942 WiFi.persistent(false);
943 WiFi.disconnect();
944 WiFi.mode(WIFI_OFF);
945 strcpy(station_ssid, firmwareOptions.home_wifi_ssid);
946 strcpy(station_password, firmwareOptions.home_wifi_password);
947 if (station_ssid[0] == 0) {
948 changeTime = now;
949 changeMode = WIFI_AP;
951 else {
952 changeTime = now;
953 changeMode = WIFI_STA;
955 laststatus = WL_DISCONNECTED;
956 wifiStarted = true;
959 static void startMDNS()
961 if (!MDNS.begin(wifi_hostname))
963 DBGLN("Error starting mDNS");
964 return;
967 String options = "-DAUTO_WIFI_ON_INTERVAL=" + String(firmwareOptions.wifi_auto_on_interval / 1000);
969 #ifdef TARGET_TX
970 if (firmwareOptions.unlock_higher_power)
972 options += " -DUNLOCK_HIGHER_POWER";
974 options += " -DTLM_REPORT_INTERVAL_MS=" + String(firmwareOptions.tlm_report_interval);
975 options += " -DFAN_MIN_RUNTIME=" + String(firmwareOptions.fan_min_runtime);
976 #endif
978 #ifdef TARGET_RX
979 if (firmwareOptions.lock_on_first_connection)
981 options += " -DLOCK_ON_FIRST_CONNECTION";
983 options += " -DRCVR_UART_BAUD=" + String(firmwareOptions.uart_baud);
984 #endif
986 String instance = String(wifi_hostname) + "_" + WiFi.macAddress();
987 instance.replace(":", "");
988 #ifdef PLATFORM_ESP8266
989 // We have to do it differently on ESP8266 as setInstanceName has the side-effect of chainging the hostname!
990 MDNS.setInstanceName(wifi_hostname);
991 MDNSResponder::hMDNSService service = MDNS.addService(instance.c_str(), "http", "tcp", 80);
992 MDNS.addServiceTxt(service, "vendor", "elrs");
993 MDNS.addServiceTxt(service, "target", (const char *)&target_name[4]);
994 MDNS.addServiceTxt(service, "device", (const char *)device_name);
995 MDNS.addServiceTxt(service, "product", (const char *)product_name);
996 MDNS.addServiceTxt(service, "version", VERSION);
997 MDNS.addServiceTxt(service, "options", options.c_str());
998 MDNS.addServiceTxt(service, "type", "rx");
999 // If the probe result fails because there is another device on the network with the same name
1000 // use our unique instance name as the hostname. A better way to do this would be to use
1001 // MDNSResponder::indexDomain and change wifi_hostname as well.
1002 MDNS.setHostProbeResultCallback([instance](const char* p_pcDomainName, bool p_bProbeResult) {
1003 if (!p_bProbeResult) {
1004 WiFi.hostname(instance);
1005 MDNS.setInstanceName(instance);
1008 #else
1009 MDNS.setInstanceName(instance);
1010 MDNS.addService("http", "tcp", 80);
1011 MDNS.addServiceTxt("http", "tcp", "vendor", "elrs");
1012 MDNS.addServiceTxt("http", "tcp", "target", (const char *)&target_name[4]);
1013 MDNS.addServiceTxt("http", "tcp", "device", (const char *)device_name);
1014 MDNS.addServiceTxt("http", "tcp", "product", (const char *)product_name);
1015 MDNS.addServiceTxt("http", "tcp", "version", VERSION);
1016 MDNS.addServiceTxt("http", "tcp", "options", options.c_str());
1017 #ifdef TARGET_TX
1018 MDNS.addServiceTxt("http", "tcp", "type", "tx");
1019 #else
1020 MDNS.addServiceTxt("http", "tcp", "type", "rx");
1021 #endif
1022 #endif
1024 #ifdef HAS_WIFI_JOYSTICK
1025 MDNS.addService("elrs", "udp", JOYSTICK_PORT);
1026 MDNS.addServiceTxt("elrs", "udp", "device", (const char *)device_name);
1027 MDNS.addServiceTxt("elrs", "udp", "version", String(JOYSTICK_VERSION).c_str());
1028 #endif
1031 static void addCaptivePortalHandlers()
1033 // windows 11 captive portal workaround
1034 server.on("/connecttest.txt", [](AsyncWebServerRequest *request) { request->redirect("http://logout.net"); });
1035 // A 404 stops win 10 keep calling this repeatedly and panicking the esp32
1036 server.on("/wpad.dat", [](AsyncWebServerRequest *request) { request->send(404); });
1038 server.on("/generate_204", WebUpdateHandleRoot); // Android
1039 server.on("/gen_204", WebUpdateHandleRoot); // Android
1040 server.on("/library/test/success.html", WebUpdateHandleRoot); // apple call home
1041 server.on("/hotspot-detect.html", WebUpdateHandleRoot); // apple call home
1042 server.on("/connectivity-check.html", WebUpdateHandleRoot); // ubuntu
1043 server.on("/check_network_status.txt", WebUpdateHandleRoot); // ubuntu
1044 server.on("/ncsi.txt", WebUpdateHandleRoot); // windows call home
1045 server.on("/canonical.html", WebUpdateHandleRoot); // firefox captive portal call home
1046 server.on("/fwlink", WebUpdateHandleRoot);
1047 server.on("/redirect", WebUpdateHandleRoot); // microsoft redirect
1048 server.on("/success.txt", [](AsyncWebServerRequest *request) { request->send(200); }); // firefox captive portal call home
1051 static void startServices()
1053 if (servicesStarted) {
1054 #if defined(PLATFORM_ESP32)
1055 MDNS.end();
1056 startMDNS();
1057 #endif
1058 return;
1061 server.on("/", WebUpdateHandleRoot);
1062 server.on("/elrs.css", WebUpdateSendContent);
1063 server.on("/mui.js", WebUpdateSendContent);
1064 server.on("/scan.js", WebUpdateSendContent);
1065 server.on("/networks.json", WebUpdateSendNetworks);
1066 server.on("/sethome", WebUpdateSetHome);
1067 server.on("/forget", WebUpdateForget);
1068 server.on("/connect", WebUpdateConnect);
1069 server.on("/config", HTTP_GET, GetConfiguration);
1070 server.on("/access", WebUpdateAccessPoint);
1071 server.on("/target", WebUpdateGetTarget);
1072 server.on("/firmware.bin", WebUpdateGetFirmware);
1074 server.on("/update", HTTP_POST, WebUploadResponseHandler, WebUploadDataHandler);
1075 server.on("/update", HTTP_OPTIONS, corsPreflightResponse);
1076 server.on("/forceupdate", WebUploadForceUpdateHandler);
1077 server.on("/forceupdate", HTTP_OPTIONS, corsPreflightResponse);
1078 server.on("/cw.html", WebUpdateSendContent);
1079 server.on("/cw.js", WebUpdateSendContent);
1080 server.on("/cw", HandleContinuousWave);
1082 DefaultHeaders::Instance().addHeader("Access-Control-Allow-Origin", "*");
1083 DefaultHeaders::Instance().addHeader("Access-Control-Max-Age", "600");
1084 DefaultHeaders::Instance().addHeader("Access-Control-Allow-Methods", "POST,GET,OPTIONS");
1085 DefaultHeaders::Instance().addHeader("Access-Control-Allow-Headers", "*");
1087 server.on("/hardware.html", WebUpdateSendContent);
1088 server.on("/hardware.js", WebUpdateSendContent);
1089 server.on("/hardware.json", getFile).onBody(putFile);
1090 server.on("/options.json", HTTP_GET, getFile);
1091 server.on("/reboot", HandleReboot);
1092 server.on("/reset", HandleReset);
1093 #ifdef HAS_WIFI_JOYSTICK
1094 server.on("/udpcontrol", HTTP_POST, WebUdpControl);
1095 #endif
1097 server.addHandler(new AsyncCallbackJsonWebHandler("/config", UpdateConfiguration));
1098 server.addHandler(new AsyncCallbackJsonWebHandler("/options.json", UpdateSettings));
1099 #if defined(TARGET_TX)
1100 server.addHandler(new AsyncCallbackJsonWebHandler("/buttons", WebUpdateButtonColors));
1101 server.addHandler(new AsyncCallbackJsonWebHandler("/import", ImportConfiguration, 32768U));
1102 #endif
1104 addCaptivePortalHandlers();
1106 server.onNotFound(WebUpdateHandleNotFound);
1108 server.begin();
1110 dnsServer.start(DNS_PORT, "*", ipAddress);
1111 dnsServer.setErrorReplyCode(DNSReplyCode::NoError);
1113 startMDNS();
1115 #ifdef HAS_WIFI_JOYSTICK
1116 WifiJoystick::StartJoystickService();
1117 #endif
1119 servicesStarted = true;
1120 DBGLN("HTTPUpdateServer ready! Open http://%s.local in your browser", wifi_hostname);
1121 #if defined(USE_MSP_WIFI) && defined(TARGET_RX)
1122 wifi2tcp.begin();
1123 #endif
1126 static void HandleWebUpdate()
1128 unsigned long now = millis();
1129 wl_status_t status = WiFi.status();
1131 if (status != laststatus && wifiMode == WIFI_STA) {
1132 DBGLN("WiFi status %d", status);
1133 switch(status) {
1134 case WL_NO_SSID_AVAIL:
1135 case WL_CONNECT_FAILED:
1136 case WL_CONNECTION_LOST:
1137 changeTime = now;
1138 changeMode = WIFI_AP;
1139 break;
1140 case WL_DISCONNECTED: // try reconnection
1141 changeTime = now;
1142 break;
1143 default:
1144 break;
1146 laststatus = status;
1148 if (status != WL_CONNECTED && wifiMode == WIFI_STA && (now - changeTime) > 30000) {
1149 changeTime = now;
1150 changeMode = WIFI_AP;
1151 DBGLN("Connection failed %d", status);
1153 if (changeMode != wifiMode && changeMode != WIFI_OFF && (now - changeTime) > 500) {
1154 switch(changeMode) {
1155 case WIFI_AP:
1156 DBGLN("Changing to AP mode");
1157 WiFi.disconnect();
1158 wifiMode = WIFI_AP;
1159 #if defined(PLATFORM_ESP32)
1160 WiFi.setHostname(wifi_hostname); // hostname must be set before the mode is set to STA
1161 #endif
1162 WiFi.mode(wifiMode);
1163 #if defined(PLATFORM_ESP8266)
1164 WiFi.setHostname(wifi_hostname); // hostname must be set before the mode is set to STA
1165 #endif
1166 changeTime = now;
1167 #if defined(PLATFORM_ESP8266)
1168 WiFi.setOutputPower(20.5);
1169 WiFi.setPhyMode(WIFI_PHY_MODE_11N);
1170 #elif defined(PLATFORM_ESP32)
1171 WiFi.setTxPower(WIFI_POWER_19_5dBm);
1172 #endif
1173 WiFi.softAPConfig(ipAddress, ipAddress, netMsk);
1174 WiFi.softAP(wifi_ap_ssid, wifi_ap_password);
1175 startServices();
1176 break;
1177 case WIFI_STA:
1178 DBGLN("Connecting to network '%s'", station_ssid);
1179 wifiMode = WIFI_STA;
1180 #if defined(PLATFORM_ESP32)
1181 WiFi.setHostname(wifi_hostname); // hostname must be set before the mode is set to STA
1182 #endif
1183 WiFi.mode(wifiMode);
1184 #if defined(PLATFORM_ESP8266)
1185 WiFi.setHostname(wifi_hostname); // hostname must be set after the mode is set to STA
1186 #endif
1187 changeTime = now;
1188 #if defined(PLATFORM_ESP8266)
1189 WiFi.setOutputPower(20.5);
1190 WiFi.setPhyMode(WIFI_PHY_MODE_11N);
1191 #elif defined(PLATFORM_ESP32)
1192 WiFi.setTxPower(WIFI_POWER_19_5dBm);
1193 WiFi.setSortMethod(WIFI_CONNECT_AP_BY_SIGNAL);
1194 WiFi.setScanMethod(WIFI_ALL_CHANNEL_SCAN);
1195 #endif
1196 WiFi.begin(station_ssid, station_password);
1197 startServices();
1198 default:
1199 break;
1201 #if defined(PLATFORM_ESP8266)
1202 MDNS.notifyAPChange();
1203 #endif
1204 changeMode = WIFI_OFF;
1207 #if defined(PLATFORM_ESP8266)
1208 if (scanComplete)
1210 WiFi.mode(wifiMode);
1211 scanComplete = false;
1213 #endif
1215 if (servicesStarted)
1217 dnsServer.processNextRequest();
1218 #if defined(PLATFORM_ESP8266)
1219 MDNS.update();
1220 #endif
1222 #ifdef HAS_WIFI_JOYSTICK
1223 WifiJoystick::Loop(now);
1224 #endif
1228 void HandleMSP2WIFI()
1230 #if defined(USE_MSP_WIFI) && defined(TARGET_RX)
1231 // check is there is any data to write out
1232 if (crsf2msp.FIFOout.peekSize() > 0)
1234 const uint16_t len = crsf2msp.FIFOout.popSize();
1235 uint8_t data[len];
1236 crsf2msp.FIFOout.popBytes(data, len);
1237 wifi2tcp.write(data, len);
1240 // check if there is any data to read in
1241 const uint16_t bytesReady = wifi2tcp.bytesReady();
1242 if (bytesReady > 0)
1244 uint8_t data[bytesReady];
1245 wifi2tcp.read(data);
1246 msp2crsf.parse(data, bytesReady);
1249 wifi2tcp.handle();
1250 #endif
1253 static int start()
1255 ipAddress.fromString(wifi_ap_address);
1256 return firmwareOptions.wifi_auto_on_interval;
1259 static int event()
1261 if (connectionState == wifiUpdate || connectionState > FAILURE_STATES)
1263 if (!wifiStarted) {
1264 startWiFi(millis());
1265 return DURATION_IMMEDIATELY;
1268 else if (wifiStarted)
1270 wifiStarted = false;
1271 WiFi.disconnect(true);
1272 WiFi.mode(WIFI_OFF);
1273 #if defined(PLATFORM_ESP8266)
1274 WiFi.forceSleepBegin();
1275 #endif
1277 return DURATION_IGNORE;
1280 static int timeout()
1282 if (wifiStarted)
1284 HandleWebUpdate();
1285 HandleMSP2WIFI();
1286 #if defined(PLATFORM_ESP8266)
1287 // When in STA mode, a small delay reduces power use from 90mA to 30mA when idle
1288 // In AP mode, it doesn't seem to make a measurable difference, but does not hurt
1289 // Only done on 8266 as the ESP32 runs a throttled task
1290 if (!Update.isRunning())
1291 delay(1);
1292 return DURATION_IMMEDIATELY;
1293 #else
1294 // All the web traffic is async apart from changing modes and MSP2WIFI
1295 // No need to run balls-to-the-wall; the wifi runs on this core too (0)
1296 return 2;
1297 #endif
1300 #if defined(TARGET_TX)
1301 // if webupdate was requested before or .wifi_auto_on_interval has elapsed but uart is not detected
1302 // start webupdate, there might be wrong configuration flashed.
1303 if(firmwareOptions.wifi_auto_on_interval != -1 && webserverPreventAutoStart == false && connectionState < wifiUpdate && !wifiStarted){
1304 DBGLN("No CRSF ever detected, starting WiFi");
1305 setWifiUpdateMode();
1306 return DURATION_IMMEDIATELY;
1308 #elif defined(TARGET_RX)
1309 if (firmwareOptions.wifi_auto_on_interval != -1 && !webserverPreventAutoStart && (connectionState == disconnected))
1311 static bool pastAutoInterval = false;
1312 // If InBindingMode then wait at least 60 seconds before going into wifi,
1313 // regardless of if .wifi_auto_on_interval is set to less
1314 if (!InBindingMode || firmwareOptions.wifi_auto_on_interval >= 60000 || pastAutoInterval)
1316 setWifiUpdateMode();
1317 return DURATION_IMMEDIATELY;
1319 pastAutoInterval = true;
1320 return (60000 - firmwareOptions.wifi_auto_on_interval);
1322 #endif
1323 return DURATION_NEVER;
1326 device_t WIFI_device = {
1327 .initialize = initialize,
1328 .start = start,
1329 .event = event,
1330 .timeout = timeout
1333 #endif