system_reset.cc 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. #include "system_reset.h"
  2. #include <esp_log.h>
  3. #include <nvs_flash.h>
  4. #include <driver/gpio.h>
  5. #include <esp_partition.h>
  6. #include <esp_system.h>
  7. #include <freertos/FreeRTOS.h>
  8. #define TAG "SystemReset"
  9. SystemReset::SystemReset(gpio_num_t reset_nvs_pin, gpio_num_t reset_factory_pin) : reset_nvs_pin_(reset_nvs_pin), reset_factory_pin_(reset_factory_pin) {
  10. // Configure GPIO1, GPIO2 as INPUT, reset NVS flash if the button is pressed
  11. gpio_config_t io_conf;
  12. io_conf.intr_type = GPIO_INTR_DISABLE;
  13. io_conf.mode = GPIO_MODE_INPUT;
  14. io_conf.pin_bit_mask = (1ULL << reset_nvs_pin_) | (1ULL << reset_factory_pin_);
  15. io_conf.pull_down_en = GPIO_PULLDOWN_DISABLE;
  16. io_conf.pull_up_en = GPIO_PULLUP_ENABLE;
  17. gpio_config(&io_conf);
  18. }
  19. void SystemReset::CheckButtons() {
  20. if (gpio_get_level(reset_factory_pin_) == 0) {
  21. ESP_LOGI(TAG, "Button is pressed, reset to factory");
  22. ResetNvsFlash();
  23. ResetToFactory();
  24. }
  25. if (gpio_get_level(reset_nvs_pin_) == 0) {
  26. ESP_LOGI(TAG, "Button is pressed, reset NVS flash");
  27. ResetNvsFlash();
  28. }
  29. }
  30. void SystemReset::ResetNvsFlash() {
  31. ESP_LOGI(TAG, "Resetting NVS flash");
  32. esp_err_t ret = nvs_flash_erase();
  33. if (ret != ESP_OK) {
  34. ESP_LOGE(TAG, "Failed to erase NVS flash");
  35. }
  36. ret = nvs_flash_init();
  37. if (ret != ESP_OK) {
  38. ESP_LOGE(TAG, "Failed to initialize NVS flash");
  39. }
  40. }
  41. void SystemReset::ResetToFactory() {
  42. ESP_LOGI(TAG, "Resetting to factory");
  43. // Erase otadata partition
  44. const esp_partition_t* partition = esp_partition_find_first(ESP_PARTITION_TYPE_DATA, ESP_PARTITION_SUBTYPE_DATA_OTA, NULL);
  45. if (partition == NULL) {
  46. ESP_LOGE(TAG, "Failed to find otadata partition");
  47. return;
  48. }
  49. esp_partition_erase_range(partition, 0, partition->size);
  50. ESP_LOGI(TAG, "Erased otadata partition");
  51. // Reboot in 3 seconds
  52. RestartInSeconds(3);
  53. }
  54. void SystemReset::RestartInSeconds(int seconds) {
  55. for (int i = seconds; i > 0; i--) {
  56. ESP_LOGI(TAG, "Resetting in %d seconds", i);
  57. vTaskDelay(1000 / portTICK_PERIOD_MS);
  58. }
  59. esp_restart();
  60. }