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.4 KiB

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