settings.cc 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. #include "settings.h"
  2. #include <esp_log.h>
  3. #include <nvs_flash.h>
  4. #define TAG "Settings"
  5. Settings::Settings(const std::string& ns, bool read_write) : ns_(ns), read_write_(read_write) {
  6. nvs_open(ns.c_str(), read_write_ ? NVS_READWRITE : NVS_READONLY, &nvs_handle_);
  7. }
  8. Settings::~Settings() {
  9. if (nvs_handle_ != 0) {
  10. if (read_write_ && dirty_) {
  11. ESP_ERROR_CHECK(nvs_commit(nvs_handle_));
  12. }
  13. nvs_close(nvs_handle_);
  14. }
  15. }
  16. std::string Settings::GetString(const std::string& key, const std::string& default_value) {
  17. if (nvs_handle_ == 0) {
  18. return default_value;
  19. }
  20. size_t length = 0;
  21. if (nvs_get_str(nvs_handle_, key.c_str(), nullptr, &length) != ESP_OK) {
  22. return default_value;
  23. }
  24. std::string value;
  25. value.resize(length);
  26. ESP_ERROR_CHECK(nvs_get_str(nvs_handle_, key.c_str(), value.data(), &length));
  27. while (!value.empty() && value.back() == '\0') {
  28. value.pop_back();
  29. }
  30. return value;
  31. }
  32. void Settings::SetString(const std::string& key, const std::string& value) {
  33. if (read_write_) {
  34. ESP_ERROR_CHECK(nvs_set_str(nvs_handle_, key.c_str(), value.c_str()));
  35. dirty_ = true;
  36. } else {
  37. ESP_LOGW(TAG, "Namespace %s is not open for writing", ns_.c_str());
  38. }
  39. }
  40. int32_t Settings::GetInt(const std::string& key, int32_t default_value) {
  41. if (nvs_handle_ == 0) {
  42. return default_value;
  43. }
  44. int32_t value;
  45. if (nvs_get_i32(nvs_handle_, key.c_str(), &value) != ESP_OK) {
  46. return default_value;
  47. }
  48. return value;
  49. }
  50. void Settings::SetInt(const std::string& key, int32_t value) {
  51. if (read_write_) {
  52. ESP_ERROR_CHECK(nvs_set_i32(nvs_handle_, key.c_str(), value));
  53. dirty_ = true;
  54. } else {
  55. ESP_LOGW(TAG, "Namespace %s is not open for writing", ns_.c_str());
  56. }
  57. }
  58. void Settings::EraseKey(const std::string& key) {
  59. if (read_write_) {
  60. auto ret = nvs_erase_key(nvs_handle_, key.c_str());
  61. if (ret != ESP_ERR_NVS_NOT_FOUND) {
  62. ESP_ERROR_CHECK(ret);
  63. }
  64. } else {
  65. ESP_LOGW(TAG, "Namespace %s is not open for writing", ns_.c_str());
  66. }
  67. }
  68. void Settings::EraseAll() {
  69. if (read_write_) {
  70. ESP_ERROR_CHECK(nvs_erase_all(nvs_handle_));
  71. } else {
  72. ESP_LOGW(TAG, "Namespace %s is not open for writing", ns_.c_str());
  73. }
  74. }