ota_component.h 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. #pragma once
  2. #include "esphome/core/component.h"
  3. #include "esphome/core/preferences.h"
  4. #include <WiFiServer.h>
  5. #include <WiFiClient.h>
  6. namespace esphome {
  7. namespace ota {
  8. enum OTAResponseTypes {
  9. OTA_RESPONSE_OK = 0,
  10. OTA_RESPONSE_REQUEST_AUTH = 1,
  11. OTA_RESPONSE_HEADER_OK = 64,
  12. OTA_RESPONSE_AUTH_OK = 65,
  13. OTA_RESPONSE_UPDATE_PREPARE_OK = 66,
  14. OTA_RESPONSE_BIN_MD5_OK = 67,
  15. OTA_RESPONSE_RECEIVE_OK = 68,
  16. OTA_RESPONSE_UPDATE_END_OK = 69,
  17. OTA_RESPONSE_ERROR_MAGIC = 128,
  18. OTA_RESPONSE_ERROR_UPDATE_PREPARE = 129,
  19. OTA_RESPONSE_ERROR_AUTH_INVALID = 130,
  20. OTA_RESPONSE_ERROR_WRITING_FLASH = 131,
  21. OTA_RESPONSE_ERROR_UPDATE_END = 132,
  22. OTA_RESPONSE_ERROR_INVALID_BOOTSTRAPPING = 133,
  23. OTA_RESPONSE_ERROR_WRONG_CURRENT_FLASH_CONFIG = 134,
  24. OTA_RESPONSE_ERROR_WRONG_NEW_FLASH_CONFIG = 135,
  25. OTA_RESPONSE_ERROR_ESP8266_NOT_ENOUGH_SPACE = 136,
  26. OTA_RESPONSE_ERROR_ESP32_NOT_ENOUGH_SPACE = 137,
  27. OTA_RESPONSE_ERROR_UNKNOWN = 255,
  28. };
  29. /// OTAComponent provides a simple way to integrate Over-the-Air updates into your app using ArduinoOTA.
  30. class OTAComponent : public Component {
  31. public:
  32. /** Set a plaintext password that OTA will use for authentication.
  33. *
  34. * Warning: This password will be stored in plaintext in the ROM and can be read
  35. * by intruders.
  36. *
  37. * @param password The plaintext password.
  38. */
  39. void set_auth_password(const std::string &password);
  40. /// Manually set the port OTA should listen on.
  41. void set_port(uint16_t port);
  42. bool should_enter_safe_mode(uint8_t num_attempts, uint32_t enable_time);
  43. // ========== INTERNAL METHODS ==========
  44. // (In most use cases you won't need these)
  45. void setup() override;
  46. void dump_config() override;
  47. float get_setup_priority() const override;
  48. void loop() override;
  49. uint16_t get_port() const;
  50. void clean_rtc();
  51. void on_safe_shutdown() override;
  52. protected:
  53. void write_rtc_(uint32_t val);
  54. uint32_t read_rtc_();
  55. void handle_();
  56. size_t wait_receive_(uint8_t *buf, size_t bytes, bool check_disconnected = true);
  57. std::string password_;
  58. uint16_t port_;
  59. WiFiServer *server_{nullptr};
  60. WiFiClient client_{};
  61. bool has_safe_mode_{false}; ///< stores whether safe mode can be enabled.
  62. uint32_t safe_mode_start_time_; ///< stores when safe mode was enabled.
  63. uint32_t safe_mode_enable_time_{60000}; ///< The time safe mode should be on for.
  64. uint32_t safe_mode_rtc_value_;
  65. uint8_t safe_mode_num_attempts_;
  66. ESPPreferenceObject rtc_;
  67. };
  68. } // namespace ota
  69. } // namespace esphome