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

  1. #include <OTASettingsService.h>
  2. OTASettingsService::OTASettingsService(AsyncWebServer* server, FS* fs, SecurityManager* securityManager) :
  3. _httpEndpoint(OTASettings::serialize,
  4. OTASettings::deserialize,
  5. this,
  6. server,
  7. OTA_SETTINGS_SERVICE_PATH,
  8. securityManager),
  9. _fsPersistence(OTASettings::serialize, OTASettings::deserialize, this, fs, OTA_SETTINGS_FILE),
  10. _arduinoOTA(nullptr) {
  11. #ifdef ESP32
  12. WiFi.onEvent(std::bind(&OTASettingsService::onStationModeGotIP, this, std::placeholders::_1, std::placeholders::_2),
  13. WiFiEvent_t::SYSTEM_EVENT_STA_GOT_IP);
  14. #elif defined(ESP8266)
  15. _onStationModeGotIPHandler =
  16. WiFi.onStationModeGotIP(std::bind(&OTASettingsService::onStationModeGotIP, this, std::placeholders::_1));
  17. #endif
  18. addUpdateHandler([&](const String& originId) { configureArduinoOTA(); }, false);
  19. }
  20. void OTASettingsService::begin() {
  21. _fsPersistence.readFromFS();
  22. configureArduinoOTA();
  23. }
  24. void OTASettingsService::loop() {
  25. if (_state.enabled && _arduinoOTA) {
  26. _arduinoOTA->handle();
  27. }
  28. }
  29. void OTASettingsService::configureArduinoOTA() {
  30. if (_arduinoOTA) {
  31. #ifdef ESP32
  32. _arduinoOTA->end();
  33. #endif
  34. delete _arduinoOTA;
  35. _arduinoOTA = nullptr;
  36. }
  37. if (_state.enabled) {
  38. Serial.println(F("Starting OTA Update Service..."));
  39. _arduinoOTA = new ArduinoOTAClass;
  40. _arduinoOTA->setPort(_state.port);
  41. _arduinoOTA->setPassword(_state.password.c_str());
  42. _arduinoOTA->onStart([]() { Serial.println(F("Starting")); });
  43. _arduinoOTA->onEnd([]() { Serial.println(F("\r\nEnd")); });
  44. _arduinoOTA->onProgress([](unsigned int progress, unsigned int total) {
  45. Serial.printf_P(PSTR("Progress: %u%%\r\n"), (progress / (total / 100)));
  46. });
  47. _arduinoOTA->onError([](ota_error_t error) {
  48. Serial.printf("Error[%u]: ", error);
  49. if (error == OTA_AUTH_ERROR)
  50. Serial.println(F("Auth Failed"));
  51. else if (error == OTA_BEGIN_ERROR)
  52. Serial.println(F("Begin Failed"));
  53. else if (error == OTA_CONNECT_ERROR)
  54. Serial.println(F("Connect Failed"));
  55. else if (error == OTA_RECEIVE_ERROR)
  56. Serial.println(F("Receive Failed"));
  57. else if (error == OTA_END_ERROR)
  58. Serial.println(F("End Failed"));
  59. });
  60. _arduinoOTA->begin();
  61. }
  62. }
  63. #ifdef ESP32
  64. void OTASettingsService::onStationModeGotIP(WiFiEvent_t event, WiFiEventInfo_t info) {
  65. configureArduinoOTA();
  66. }
  67. #elif defined(ESP8266)
  68. void OTASettingsService::onStationModeGotIP(const WiFiEventStationModeGotIP& event) {
  69. configureArduinoOTA();
  70. }
  71. #endif