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.

71 lines
2.5 KiB

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