nvs_handle.hpp 12 KB

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