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.

88 lines
2.4 KiB

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