ESP8266 RTOS使用NVS保存配置信息与取值

当wifi信息要保存时,不可能为了改一个信息就要重新烧固件,这时就要用到nvs来保存配置信息了
以下是nvs的存储功能部分,后面再实现配网部分。
user_nvs.c的内存如下:

#include<stdlib.h>
#include<string.h>
#include "nvs_flash.h"
#include "user_nvs.h"
static  nvs_handle handle_sys_info;

//初始化NVS内存
void user_nvs_init(void)
{
    nvs_flash_init();//初始化NVS内存
    nvs_open("wifi_sys_info", NVS_READWRITE, &handle_sys_info);
    user_nvs_init_status0 = nvs_initialized;
}
/**
 * @brief 返回字符串指针
 * @return 使用说明:
 *  char* ssid_str = user_nvs_getkey("ssid");
*/
char * user_nvs_getkey(char* key)
{
   if(user_nvs_init_status0==nvs_uninitialized)
   {
      user_nvs_init();
   }
   size_t buf_len;
   nvs_get_str(handle_sys_info,key,NULL,&buf_len); 
    char *tempkey_str = malloc(buf_len);
    nvs_get_str(handle_sys_info,key,tempkey_str,&buf_len);
    return tempkey_str;
}
//设置key
void user_nvs_setkey(char* key , char* value)
{
   if(user_nvs_init_status0==nvs_uninitialized)
   {
      user_nvs_init();
   }
   nvs_set_str(handle_sys_info, key, value);
}
void user_nvs_erase(void)
{
   if(user_nvs_init_status0==nvs_uninitialized)
   {
      user_nvs_init();
   }
   nvs_erase_all(handle_sys_info);//擦除名称空间中的所有键-值对
}
//反初始化
void  user_nvs_close(void)
{
   nvs_flash_deinit();
   nvs_close(handle_sys_info);//关闭
   user_nvs_init_status0=nvs_uninitialized;
}

头文件

#ifndef _USER_NVS_H_
#define _USER_NVS_H_
#include "nvs_flash.h"
typedef enum{
nvs_uninitialized =0x0,  /*驱动未初始化的状态*/
nvs_initialized =0x1     /*驱动已初始化的状态 */ 
}user_nvs_init_status;
user_nvs_init_status user_nvs_init_status0;
void user_nvs_init(void);
/*取值*/
char * user_nvs_getkey(char* key);
/*设置*/
void user_nvs_setkey(char* key , char* value);
/*关闭*/
void  user_nvs_close(void);
/*擦除*/
void user_nvs_erase(void);
#endif
posted @ 2020-05-19 15:09  天祈笨笨  阅读(985)  评论(0编辑  收藏  举报