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.

85 lines
2.3 KiB

  1. #include <APSettingsService.h>
  2. APSettingsService::APSettingsService(FS* fs, SecurityManager* securityManager) : AdminSettingsService(fs, securityManager, AP_SETTINGS_SERVICE_PATH, AP_SETTINGS_FILE) {
  3. onConfigUpdated();
  4. }
  5. APSettingsService::~APSettingsService() {}
  6. void APSettingsService::loop() {
  7. unsigned long currentMillis = millis();
  8. unsigned long manageElapsed = (unsigned long)(currentMillis - _lastManaged);
  9. if (manageElapsed >= MANAGE_NETWORK_DELAY){
  10. _lastManaged = currentMillis;
  11. manageAP();
  12. }
  13. handleDNS();
  14. }
  15. void APSettingsService::manageAP() {
  16. WiFiMode_t currentWiFiMode = WiFi.getMode();
  17. if (_provisionMode == AP_MODE_ALWAYS || (_provisionMode == AP_MODE_DISCONNECTED && WiFi.status() != WL_CONNECTED)) {
  18. if (currentWiFiMode == WIFI_OFF || currentWiFiMode == WIFI_STA) {
  19. startAP();
  20. }
  21. } else {
  22. if (currentWiFiMode == WIFI_AP || currentWiFiMode == WIFI_AP_STA) {
  23. stopAP();
  24. }
  25. }
  26. }
  27. void APSettingsService::startAP() {
  28. Serial.println("Starting software access point");
  29. WiFi.softAP(_ssid.c_str(), _password.c_str());
  30. if (!_dnsServer) {
  31. IPAddress apIp = WiFi.softAPIP();
  32. Serial.print("Starting captive portal on ");
  33. Serial.println(apIp);
  34. _dnsServer = new DNSServer;
  35. _dnsServer->start(DNS_PORT, "*", apIp);
  36. }
  37. }
  38. void APSettingsService::stopAP() {
  39. if (_dnsServer) {
  40. Serial.println("Stopping captive portal");
  41. _dnsServer->stop();
  42. delete _dnsServer;
  43. _dnsServer = nullptr;
  44. }
  45. Serial.println("Stopping software access point");
  46. WiFi.softAPdisconnect(true);
  47. }
  48. void APSettingsService::handleDNS() {
  49. if (_dnsServer) {
  50. _dnsServer->processNextRequest();
  51. }
  52. }
  53. void APSettingsService::readFromJsonObject(JsonObject& root) {
  54. _provisionMode = root["provision_mode"] | AP_MODE_ALWAYS;
  55. switch (_provisionMode) {
  56. case AP_MODE_ALWAYS:
  57. case AP_MODE_DISCONNECTED:
  58. case AP_MODE_NEVER:
  59. break;
  60. default:
  61. _provisionMode = AP_MODE_ALWAYS;
  62. }
  63. _ssid = root["ssid"] | AP_DEFAULT_SSID;
  64. _password = root["password"] | AP_DEFAULT_PASSWORD;
  65. }
  66. void APSettingsService::writeToJsonObject(JsonObject& root) {
  67. root["provision_mode"] = _provisionMode;
  68. root["ssid"] = _ssid;
  69. root["password"] = _password;
  70. }
  71. void APSettingsService::onConfigUpdated() {
  72. _lastManaged = millis() - MANAGE_NETWORK_DELAY;
  73. // stop softAP - forces reconfiguration in loop()
  74. stopAP();
  75. }