nvs_handle.hpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  1. #ifndef NVS_HANDLE_HPP_
  2. #define NVS_HANDLE_HPP_
  3. #include <string>
  4. #include <memory>
  5. #include <type_traits>
  6. #include "nvs.h"
  7. namespace nvs {
  8. /**
  9. * The possible blob types. This is a helper definition for template functions.
  10. */
  11. enum class ItemType : uint8_t {
  12. U8 = NVS_TYPE_U8,
  13. I8 = NVS_TYPE_I8,
  14. U16 = NVS_TYPE_U16,
  15. I16 = NVS_TYPE_I16,
  16. U32 = NVS_TYPE_U32,
  17. I32 = NVS_TYPE_I32,
  18. U64 = NVS_TYPE_U64,
  19. I64 = NVS_TYPE_I64,
  20. SZ = NVS_TYPE_STR,
  21. BLOB = 0x41,
  22. BLOB_DATA = NVS_TYPE_BLOB,
  23. BLOB_IDX = 0x48,
  24. ANY = NVS_TYPE_ANY
  25. };
  26. /**
  27. * @brief A handle allowing nvs-entry related operations on the NVS.
  28. *
  29. * @note The scope of this handle may vary depending on the implementation, but normally would be the namespace of
  30. * a particular partition. Outside that scope, nvs entries can't be accessed/altered.
  31. */
  32. class NVSHandle {
  33. public:
  34. virtual ~NVSHandle() { }
  35. /**
  36. * @brief set value for given key
  37. *
  38. * Sets value for key. Note that physical storage will not be updated until nvs_commit function is called.
  39. *
  40. * @param[in] key Key name. Maximal length is (NVS_KEY_NAME_MAX_SIZE-1) characters. Shouldn't be empty.
  41. * @param[in] value The value to set. Allowed types are the ones declared in ItemType as well as enums.
  42. * For strings, the maximum length (including null character) is
  43. * 4000 bytes, if there is one complete page free for writing.
  44. * This decreases, however, if the free space is fragmented.
  45. * Note that enums loose their type information when stored in NVS. Ensure that the correct
  46. * enum type is used during retrieval with \ref get_item!
  47. *
  48. * @return
  49. * - ESP_OK if value was set successfully
  50. * - ESP_ERR_NVS_READ_ONLY if storage handle was opened as read only
  51. * - ESP_ERR_NVS_INVALID_NAME if key name doesn't satisfy constraints
  52. * - ESP_ERR_NVS_NOT_ENOUGH_SPACE if there is not enough space in the
  53. * underlying storage to save the value
  54. * - ESP_ERR_NVS_REMOVE_FAILED if the value wasn't updated because flash
  55. * write operation has failed. The value was written however, and
  56. * update will be finished after re-initialization of nvs, provided that
  57. * flash operation doesn't fail again.
  58. * - ESP_ERR_NVS_VALUE_TOO_LONG if the string value is too long
  59. */
  60. template<typename T>
  61. esp_err_t set_item(const char *key, T value);
  62. virtual
  63. esp_err_t set_string(const char *key, const char* value) = 0;
  64. /**
  65. * @brief get value for given key
  66. *
  67. * These functions retrieve value for the key, given its name. If key does not
  68. * exist, or the requested variable type doesn't match the type which was used
  69. * when setting a value, an error is returned.
  70. *
  71. * In case of any error, out_value is not modified.
  72. *
  73. * @param[in] key Key name. Maximal length is (NVS_KEY_NAME_MAX_SIZE-1) characters. Shouldn't be empty.
  74. * @param value The output value. All integral types which are declared in ItemType as well as enums
  75. * are allowed. Note however that enums lost their type information when stored in NVS.
  76. * Ensure that the correct enum type is used during retrieval with \ref get_item!
  77. *
  78. * @return
  79. * - ESP_OK if the value was retrieved successfully
  80. * - ESP_ERR_NVS_NOT_FOUND if the requested key doesn't exist
  81. * - ESP_ERR_NVS_INVALID_NAME if key name doesn't satisfy constraints
  82. * - ESP_ERR_NVS_INVALID_LENGTH if length is not sufficient to store data
  83. */
  84. template<typename T>
  85. esp_err_t get_item(const char *key, T &value);
  86. /**
  87. * @brief set variable length binary value for given key
  88. *
  89. * This family of functions set value for the key, given its name. Note that
  90. * actual storage will not be updated until nvs_commit function is called.
  91. *
  92. * @param[in] key Key name. Maximal length is (NVS_KEY_NAME_MAX_SIZE-1) characters. Shouldn't be empty.
  93. * @param[in] blob The blob value to set.
  94. * @param[in] len length of binary value to set, in bytes; Maximum length is
  95. * 508000 bytes or (97.6% of the partition size - 4000) bytes
  96. * whichever is lower.
  97. *
  98. * @return
  99. * - ESP_OK if value was set successfully
  100. * - ESP_ERR_NVS_READ_ONLY if storage handle was opened as read only
  101. * - ESP_ERR_NVS_INVALID_NAME if key name doesn't satisfy constraints
  102. * - ESP_ERR_NVS_NOT_ENOUGH_SPACE if there is not enough space in the
  103. * underlying storage to save the value
  104. * - ESP_ERR_NVS_REMOVE_FAILED if the value wasn't updated because flash
  105. * write operation has failed. The value was written however, and
  106. * update will be finished after re-initialization of nvs, provided that
  107. * flash operation doesn't fail again.
  108. * - ESP_ERR_NVS_VALUE_TOO_LONG if the value is too long
  109. *
  110. * @note compare to \ref nvs_set_blob in nvs.h
  111. */
  112. virtual esp_err_t set_blob(const char *key, const void* blob, size_t len) = 0;
  113. /**
  114. * @brief get value for given key
  115. *
  116. * These functions retrieve the data of an entry, given its key. If key does not
  117. * exist, or the requested variable type doesn't match the type which was used
  118. * when setting a value, an error is returned.
  119. *
  120. * In case of any error, out_value is not modified.
  121. *
  122. * Both functions expect out_value to be a pointer to an already allocated variable
  123. * of the given type.
  124. *
  125. * It is suggested that nvs_get/set_str is used for zero-terminated short C strings, and
  126. * nvs_get/set_blob is used for arbitrary data structures and long C strings.
  127. *
  128. * @param[in] key Key name. Maximum length is (NVS_KEY_NAME_MAX_SIZE-1) characters. Shouldn't be empty.
  129. * @param out_str/ Pointer to the output value.
  130. * out_blob
  131. * @param[inout] len The length of the output buffer pointed to by out_str/out_blob.
  132. * Use \c get_item_size to query the size of the item beforehand.
  133. *
  134. * @return
  135. * - ESP_OK if the value was retrieved successfully
  136. * - ESP_ERR_NVS_NOT_FOUND if the requested key doesn't exist
  137. * - ESP_ERR_NVS_INVALID_NAME if key name doesn't satisfy constraints
  138. * - ESP_ERR_NVS_INVALID_LENGTH if length is not sufficient to store data
  139. */
  140. virtual esp_err_t get_string(const char *key, char* out_str, size_t len) = 0;
  141. virtual esp_err_t get_blob(const char *key, void* out_blob, size_t len) = 0;
  142. /**
  143. * @brief Look up the size of an entry's data.
  144. *
  145. * @param[in] datatype Data type to search for.
  146. * @param[in] key Key name. Maximum length is (NVS_KEY_NAME_MAX_SIZE-1) characters. Shouldn't be empty.
  147. * @param[out] size Size of the item, if it exists.
  148. * For strings, this size includes the zero terminator.
  149. *
  150. * @return - ESP_OK if the item with specified type and key exists. Its size will be returned via \c size.
  151. * - ESP_ERR_NVS_NOT_FOUND if an item with the requested key and type doesn't exist or any other
  152. * error occurs.
  153. */
  154. virtual esp_err_t get_item_size(ItemType datatype, const char *key, size_t &size) = 0;
  155. /**
  156. * @brief Erases an entry.
  157. */
  158. virtual esp_err_t erase_item(const char* key) = 0;
  159. /**
  160. * Erases all entries in the scope of this handle. The scope may vary, depending on the implementation.
  161. *
  162. * @not If you want to erase the whole nvs flash (partition), refer to \ref
  163. */
  164. virtual esp_err_t erase_all() = 0;
  165. /**
  166. * Commits all changes done through this handle so far.
  167. * Currently, NVS writes to storage right after the set and get functions,
  168. * but this is not guaranteed.
  169. */
  170. virtual esp_err_t commit() = 0;
  171. /**
  172. * @brief Calculate all entries in the scope of the handle.
  173. *
  174. * @param[out] used_entries Returns amount of used entries from a namespace on success.
  175. *
  176. *
  177. * @return
  178. * - ESP_OK if the changes have been written successfully.
  179. * Return param used_entries will be filled valid value.
  180. * - ESP_ERR_NVS_NOT_INITIALIZED if the storage driver is not initialized.
  181. * Return param used_entries will be filled 0.
  182. * - ESP_ERR_INVALID_ARG if nvs_stats equal to NULL.
  183. * - Other error codes from the underlying storage driver.
  184. * Return param used_entries will be filled 0.
  185. */
  186. virtual esp_err_t get_used_entry_count(size_t& usedEntries) = 0;
  187. protected:
  188. virtual esp_err_t set_typed_item(ItemType datatype, const char *key, const void* data, size_t dataSize) = 0;
  189. virtual esp_err_t get_typed_item(ItemType datatype, const char *key, void* data, size_t dataSize) = 0;
  190. };
  191. /**
  192. * @brief Opens non-volatile storage and returns a handle object.
  193. *
  194. * The handle is automatically closed on desctruction. The scope of the handle is the namespace ns_name
  195. * in a particular partition partition_name.
  196. * The parameters partition_name, ns_name and open_mode have the same meaning and restrictions as the parameters
  197. * part_name, name and open_mode in \ref nvs_open_from_partition, respectively.
  198. *
  199. * @param err an optional pointer to an esp_err_t result of the open operation, having the same meaning as the return
  200. * value in \ref nvs_open_from_partition:
  201. * - ESP_OK if storage handle was opened successfully
  202. * - ESP_ERR_NVS_NOT_INITIALIZED if the storage driver is not initialized
  203. * - ESP_ERR_NVS_PART_NOT_FOUND if the partition with label "nvs" is not found
  204. * - ESP_ERR_NVS_NOT_FOUND id namespace doesn't exist yet and
  205. * mode is NVS_READONLY
  206. * - ESP_ERR_NVS_INVALID_NAME if namespace name doesn't satisfy constraints
  207. * - other error codes from the underlying storage driver
  208. *
  209. * @return shared pointer of an nvs handle on success, an empty shared pointer otherwise
  210. */
  211. std::unique_ptr<NVSHandle> open_nvs_handle_from_partition(const char *partition_name,
  212. const char *ns_name,
  213. nvs_open_mode_t open_mode,
  214. esp_err_t *err = nullptr);
  215. /**
  216. * @brief This function does the same as \ref open_nvs_handle_from_partition but uses the default nvs partition
  217. * instead of a partition_name parameter.
  218. */
  219. std::unique_ptr<NVSHandle> open_nvs_handle(const char *ns_name,
  220. nvs_open_mode_t open_mode,
  221. esp_err_t *err = nullptr);
  222. // Helper functions for template usage
  223. /**
  224. * Help to translate all integral types into ItemType.
  225. */
  226. template<typename T, typename std::enable_if<std::is_integral<T>::value, void*>::type = nullptr>
  227. constexpr ItemType itemTypeOf()
  228. {
  229. return static_cast<ItemType>(((std::is_signed<T>::value)?0x10:0x00) | sizeof(T));
  230. }
  231. /**
  232. * Help to translate all enum types into integral ItemType.
  233. */
  234. template<typename T, typename std::enable_if<std::is_enum<T>::value, int>::type = 0>
  235. constexpr ItemType itemTypeOf()
  236. {
  237. return static_cast<ItemType>(((std::is_signed<T>::value)?0x10:0x00) | sizeof(T));
  238. }
  239. template<typename T>
  240. constexpr ItemType itemTypeOf(const T&)
  241. {
  242. return itemTypeOf<T>();
  243. }
  244. // Template Implementations
  245. template<typename T>
  246. esp_err_t NVSHandle::set_item(const char *key, T value) {
  247. return set_typed_item(itemTypeOf(value), key, &value, sizeof(value));
  248. }
  249. template<typename T>
  250. esp_err_t NVSHandle::get_item(const char *key, T &value) {
  251. return get_typed_item(itemTypeOf(value), key, &value, sizeof(value));
  252. }
  253. } // nvs
  254. #endif // NVS_HANDLE_HPP_