settings.cpp 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. #include "settings.h"
  2. using std::string;
  3. using std::map;
  4. namespace {
  5. typedef const char *const Key_t;
  6. template<class T>
  7. T read(const Key_t &key);
  8. struct Key {
  9. static constexpr Key_t NETWORK_SSID = "networkSSID";
  10. static constexpr Key_t NETWORK_PASSWORD = "networkPassword";
  11. static constexpr Key_t PAIRING_ID = "pairingId";
  12. static constexpr Key_t CALIBRATION_HIGH = "calibHigh";
  13. static constexpr Key_t CALIBRATION_LOW = "calibLow";
  14. };
  15. const map<string, uint64_t> defaultValuesInt = {
  16. {Key::CALIBRATION_LOW, 0},
  17. {Key::CALIBRATION_HIGH, 0}
  18. };
  19. const map<string, string> defaultValuesStr = {
  20. {Key::NETWORK_SSID, ""},
  21. {Key::NETWORK_PASSWORD, ""},
  22. {Key::PAIRING_ID, ""},
  23. };
  24. kbf::nvs::NVS *nvs;
  25. template<>
  26. bool read<bool>(Key_t const &key) {
  27. uint8_t value;
  28. if (!nvs->read(key, value)) {
  29. value = defaultValuesInt.at(key);
  30. }
  31. return value;
  32. }
  33. template<>
  34. int read<int>(Key_t const &key) {
  35. int value;
  36. if (!nvs->read(key, value)) {
  37. value = static_cast<bool>(defaultValuesInt.at(key));
  38. }
  39. return value;
  40. }
  41. template<>
  42. string read<string>(Key_t const &key) {
  43. string value;
  44. if (!nvs->read(key, value)) {
  45. value = defaultValuesStr.at(key);
  46. }
  47. return value;
  48. }
  49. }
  50. namespace dk::settings {
  51. void init() {
  52. delete nvs;
  53. nvs = new kbf::nvs::NVS("dk_settings");
  54. }
  55. Wifi wifi() {
  56. if (!nvs) init();
  57. return (Wifi) {.ssid = read<string>(Key::NETWORK_SSID), .password = read<string>(Key::NETWORK_PASSWORD)};
  58. }
  59. void setWifi(Wifi &value) {
  60. if (!nvs) init();
  61. nvs->write(Key::NETWORK_SSID, value.ssid);
  62. nvs->write(Key::NETWORK_PASSWORD, value.password);
  63. }
  64. string pairingId() {
  65. if (!nvs) init();
  66. return read<string>(Key::PAIRING_ID);
  67. }
  68. void setPairingId(string pairingId) {
  69. if (!nvs) init();
  70. nvs->write(Key::PAIRING_ID, pairingId);
  71. }
  72. Calibration calibration() {
  73. if (!nvs) init();
  74. return (Calibration) {.high = read<int>(Key::CALIBRATION_HIGH), .low = read<int>(Key::CALIBRATION_LOW)};
  75. }
  76. void setCalibration(Calibration &config) {
  77. if (!nvs) init();
  78. nvs->write(Key::CALIBRATION_HIGH, config.high);
  79. nvs->write(Key::CALIBRATION_LOW, config.low);
  80. }
  81. }