Fork of the excellent esp8266-react - https://github.com/rjwats/esp8266-react
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

76 lines
2.1 KiB

  1. #include <APSettingsService.h>
  2. APSettingsService::APSettingsService(AsyncWebServer* server, FS* fs, SecurityManager* securityManager) :
  3. _httpEndpoint(APSettings::serialize,
  4. APSettings::deserialize,
  5. this,
  6. server,
  7. AP_SETTINGS_SERVICE_PATH,
  8. securityManager),
  9. _fsPersistence(APSettings::serialize, APSettings::deserialize, this, fs, AP_SETTINGS_FILE),
  10. _dnsServer(nullptr),
  11. _lastManaged(0) {
  12. addUpdateHandler([&](const String& originId) { reconfigureAP(); }, false);
  13. }
  14. void APSettingsService::begin() {
  15. _fsPersistence.readFromFS();
  16. reconfigureAP();
  17. }
  18. void APSettingsService::reconfigureAP() {
  19. _lastManaged = millis() - MANAGE_NETWORK_DELAY;
  20. }
  21. void APSettingsService::loop() {
  22. unsigned long currentMillis = millis();
  23. unsigned long manageElapsed = (unsigned long)(currentMillis - _lastManaged);
  24. if (manageElapsed >= MANAGE_NETWORK_DELAY) {
  25. _lastManaged = currentMillis;
  26. manageAP();
  27. }
  28. handleDNS();
  29. }
  30. void APSettingsService::manageAP() {
  31. WiFiMode_t currentWiFiMode = WiFi.getMode();
  32. if (_state.provisionMode == AP_MODE_ALWAYS ||
  33. (_state.provisionMode == AP_MODE_DISCONNECTED && WiFi.status() != WL_CONNECTED)) {
  34. if (currentWiFiMode == WIFI_OFF || currentWiFiMode == WIFI_STA) {
  35. startAP();
  36. }
  37. } else {
  38. if (currentWiFiMode == WIFI_AP || currentWiFiMode == WIFI_AP_STA) {
  39. stopAP();
  40. }
  41. }
  42. }
  43. void APSettingsService::startAP() {
  44. Serial.println(F("Starting software access point"));
  45. WiFi.softAP(_state.ssid.c_str(), _state.password.c_str());
  46. if (!_dnsServer) {
  47. IPAddress apIp = WiFi.softAPIP();
  48. Serial.print(F("Starting captive portal on "));
  49. Serial.println(apIp);
  50. _dnsServer = new DNSServer;
  51. _dnsServer->start(DNS_PORT, "*", apIp);
  52. }
  53. }
  54. void APSettingsService::stopAP() {
  55. if (_dnsServer) {
  56. Serial.println(F("Stopping captive portal"));
  57. _dnsServer->stop();
  58. delete _dnsServer;
  59. _dnsServer = nullptr;
  60. }
  61. Serial.println(F("Stopping software access point"));
  62. WiFi.softAPdisconnect(true);
  63. }
  64. void APSettingsService::handleDNS() {
  65. if (_dnsServer) {
  66. _dnsServer->processNextRequest();
  67. }
  68. }