config.c 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721
  1. /*
  2. * Squeezelite for esp32
  3. *
  4. * (c) Sebastien 2019
  5. * Philippe G. 2019, philippe_44@outlook.com
  6. *
  7. * This program is free software: you can redistribute it and/or modify
  8. * it under the terms of the GNU General Public License as published by
  9. * the Free Software Foundation, either version 3 of the License, or
  10. * (at your option) any later version.
  11. *
  12. * This program is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU General Public License
  18. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  19. *
  20. */
  21. //#define LOG_LOCAL_LEVEL ESP_LOG_VERBOSE
  22. #include "config.h"
  23. #include "nvs_utilities.h"
  24. #include <stdio.h>
  25. #include <string.h>
  26. #include "esp_system.h"
  27. #include "esp_log.h"
  28. #include "esp_console.h"
  29. #include "esp_vfs_dev.h"
  30. #include "driver/uart.h"
  31. #include "linenoise/linenoise.h"
  32. #include "argtable3/argtable3.h"
  33. #include "esp_vfs_fat.h"
  34. #include "nvs.h"
  35. #include "nvs_flash.h"
  36. #include "nvs_utilities.h"
  37. #include "cJSON.h"
  38. #include "freertos/timers.h"
  39. #include "freertos/event_groups.h"
  40. #define CONFIG_COMMIT_DELAY 1000
  41. #define LOCK_MAX_WAIT 20*CONFIG_COMMIT_DELAY
  42. static const char * TAG = "config";
  43. static cJSON * nvs_json=NULL;
  44. static TimerHandle_t timer;
  45. static SemaphoreHandle_t config_mutex = NULL;
  46. static EventGroupHandle_t config_group;
  47. /* @brief indicate that the ESP32 is currently connected. */
  48. static const int CONFIG_NO_COMMIT_PENDING = BIT0;
  49. static const int CONFIG_LOAD_BIT = BIT1;
  50. bool config_lock(TickType_t xTicksToWait);
  51. void config_unlock();
  52. extern esp_err_t nvs_load_config();
  53. void config_raise_change(bool flag);
  54. cJSON_bool config_is_entry_changed(cJSON * entry);
  55. bool config_set_group_bit(int bit_num,bool flag);
  56. cJSON * config_set_value_safe(nvs_type_t nvs_type, const char *key, void * value);
  57. static void vCallbackFunction( TimerHandle_t xTimer );
  58. void config_set_entry_changed_flag(cJSON * entry, cJSON_bool flag);
  59. #define IMPLEMENT_SET_DEFAULT(t,nt) void config_set_default_## t (const char *key, t value){\
  60. void * pval = malloc(sizeof(value));\
  61. *((t *) pval) = value;\
  62. config_set_default(nt, key,pval,0);\
  63. free(pval); }
  64. #define IMPLEMENT_GET_NUM(t,nt) esp_err_t config_get_## t (const char *key, t * value){\
  65. void * pval = config_alloc_get(nt, key);\
  66. if(pval!=NULL){ *value = *(t * )pval; free(pval); return ESP_OK; }\
  67. return ESP_FAIL;}
  68. #if RECOVERY_APPLICATION==0
  69. static void * malloc_fn(size_t sz){
  70. void * ptr = heap_caps_malloc(sz, MALLOC_CAP_SPIRAM);
  71. if(ptr==NULL){
  72. ESP_LOGE(TAG,"malloc_fn: unable to allocate memory!");
  73. }
  74. return ptr;
  75. }
  76. /*
  77. static void * free_fn(void * ptr){
  78. if(ptr!=NULL){
  79. heap_caps_free(ptr);
  80. }
  81. else {
  82. ESP_LOGW(TAG,"free_fn: Cannot free null pointer!");
  83. }
  84. return NULL;
  85. }
  86. */
  87. #endif
  88. void init_cJSON(){
  89. static cJSON_Hooks hooks;
  90. // initialize cJSON hooks it uses SPIRAM memory
  91. // as opposed to IRAM
  92. #if RECOVERY_APPLICATION==0
  93. // In squeezelite mode, allocate memory from PSRAM. Otherwise allocate from internal RAM
  94. // as recovery will lock flash access when erasing FLASH or writing to OTA partition.
  95. hooks.malloc_fn=&malloc_fn;
  96. //hooks.free_fn=&free_fn;
  97. cJSON_InitHooks(&hooks);
  98. #endif
  99. }
  100. void config_init(){
  101. ESP_LOGD(TAG, "Creating mutex for Config");
  102. config_mutex = xSemaphoreCreateMutex();
  103. ESP_LOGD(TAG, "Creating event group");
  104. config_group = xEventGroupCreate();
  105. ESP_LOGD(TAG, "Loading config from nvs");
  106. init_cJSON();
  107. if(nvs_json !=NULL){
  108. cJSON_Delete(nvs_json);
  109. }
  110. nvs_json = cJSON_CreateObject();
  111. config_set_group_bit(CONFIG_LOAD_BIT,true);
  112. nvs_load_config();
  113. config_set_group_bit(CONFIG_LOAD_BIT,false);
  114. config_start_timer();
  115. }
  116. void config_start_timer(){
  117. ESP_LOGD(TAG, "Starting config timer");
  118. timer = xTimerCreate("configTimer", CONFIG_COMMIT_DELAY / portTICK_RATE_MS, pdFALSE, NULL, vCallbackFunction);
  119. if( xTimerStart( timer , CONFIG_COMMIT_DELAY/ portTICK_RATE_MS ) != pdPASS ) {
  120. ESP_LOGE(TAG, "config commitment timer failed to start.");
  121. }
  122. }
  123. nvs_type_t config_get_item_type(cJSON * entry){
  124. if(entry==NULL){
  125. ESP_LOGE(TAG,"null pointer received!");
  126. return true;
  127. }
  128. cJSON * item_type = cJSON_GetObjectItemCaseSensitive(entry, "type");
  129. if(item_type ==NULL ) {
  130. ESP_LOGE(TAG, "Item type not found! ");
  131. return 0;
  132. }
  133. ESP_LOGD(TAG,"Found item type %f",item_type->valuedouble);
  134. return item_type->valuedouble;
  135. }
  136. cJSON * config_set_value_safe(nvs_type_t nvs_type, const char *key, void * value){
  137. cJSON * entry = cJSON_CreateObject();
  138. double numvalue = 0;
  139. if(entry == NULL) {
  140. ESP_LOGE(TAG, "Unable to allocate memory for entry %s",key);
  141. return NULL;
  142. }
  143. cJSON * existing = cJSON_GetObjectItemCaseSensitive(nvs_json, key);
  144. if(existing !=NULL && nvs_type == NVS_TYPE_STR && config_get_item_type(existing) != NVS_TYPE_STR ) {
  145. ESP_LOGW(TAG, "Storing numeric value from string");
  146. numvalue = atof((char *)value);
  147. cJSON_AddNumberToObject(entry,"value", numvalue );
  148. nvs_type_t exist_type = config_get_item_type(existing);
  149. ESP_LOGW(TAG, "Stored value %f from string %s as type %d",numvalue, (char *)value,exist_type);
  150. cJSON_AddNumberToObject(entry,"type", exist_type);
  151. }
  152. else {
  153. cJSON_AddNumberToObject(entry,"type", nvs_type );
  154. switch (nvs_type) {
  155. case NVS_TYPE_I8:
  156. cJSON_AddNumberToObject(entry,"value", *(int8_t*)value );
  157. break;
  158. case NVS_TYPE_I16:
  159. cJSON_AddNumberToObject(entry,"value", *(int16_t*)value );
  160. break;
  161. case NVS_TYPE_I32:
  162. cJSON_AddNumberToObject(entry,"value", *(int32_t*)value );
  163. break;
  164. case NVS_TYPE_U8:
  165. cJSON_AddNumberToObject(entry,"value", *(uint8_t*)value );
  166. break;
  167. case NVS_TYPE_U16:
  168. cJSON_AddNumberToObject(entry,"value", *(uint16_t*)value );
  169. break;
  170. case NVS_TYPE_U32:
  171. cJSON_AddNumberToObject(entry,"value", *(uint32_t*)value );
  172. break;
  173. case NVS_TYPE_STR:
  174. cJSON_AddStringToObject(entry, "value", (char *)value);
  175. break;
  176. case NVS_TYPE_I64:
  177. case NVS_TYPE_U64:
  178. default:
  179. ESP_LOGE(TAG, "nvs type %u not supported", nvs_type);
  180. break;
  181. }
  182. }
  183. if(existing!=NULL ) {
  184. ESP_LOGV(TAG, "Changing existing entry [%s].", key);
  185. char * exist_str = cJSON_PrintUnformatted(existing);
  186. if(exist_str!=NULL){
  187. ESP_LOGV(TAG,"Existing entry: %s", exist_str);
  188. free(exist_str);
  189. }
  190. else {
  191. ESP_LOGV(TAG,"Failed to print existing entry");
  192. }
  193. // set commit flag as equal so we can compare
  194. cJSON_AddBoolToObject(entry,"chg",config_is_entry_changed(existing));
  195. if(!cJSON_Compare(entry,existing,false)){
  196. char * entry_str = cJSON_PrintUnformatted(entry);
  197. if(entry_str!=NULL){
  198. ESP_LOGD(TAG,"New config object: \n%s", entry_str );
  199. free(entry_str);
  200. }
  201. else {
  202. ESP_LOGD(TAG,"Failed to print entry");
  203. }
  204. ESP_LOGI(TAG, "Setting changed flag config [%s]", key);
  205. config_set_entry_changed_flag(entry,true);
  206. ESP_LOGI(TAG, "Updating config [%s]", key);
  207. cJSON_ReplaceItemInObject(nvs_json,key, entry);
  208. entry_str = cJSON_PrintUnformatted(entry);
  209. if(entry_str!=NULL){
  210. ESP_LOGD(TAG,"New config: %s", entry_str );
  211. free(entry_str);
  212. }
  213. else {
  214. ESP_LOGD(TAG,"Failed to print entry");
  215. }
  216. }
  217. else {
  218. ESP_LOGD(TAG, "Config not changed. ");
  219. cJSON_Delete(entry);
  220. entry = existing;
  221. }
  222. }
  223. else {
  224. // This is a new entry.
  225. config_set_entry_changed_flag(entry,true);
  226. cJSON_AddItemToObject(nvs_json, key, entry);
  227. }
  228. return entry;
  229. }
  230. nvs_type_t config_get_entry_type(cJSON * entry){
  231. if(entry==NULL){
  232. ESP_LOGE(TAG,"null pointer received!");
  233. return 0;
  234. }
  235. cJSON * entry_type = cJSON_GetObjectItemCaseSensitive(entry, "type");
  236. if(entry_type ==NULL ) {
  237. ESP_LOGE(TAG, "Entry type not found in nvs cache for existing setting.");
  238. return 0;
  239. }
  240. ESP_LOGV(TAG,"Found type %s",type_to_str(entry_type->valuedouble));
  241. return entry_type->valuedouble;
  242. }
  243. void config_set_entry_changed_flag(cJSON * entry, cJSON_bool flag){
  244. ESP_LOGV(TAG, "config_set_entry_changed_flag: begin");
  245. if(entry==NULL){
  246. ESP_LOGE(TAG,"null pointer received!");
  247. return;
  248. }
  249. bool bIsConfigLoading=((xEventGroupGetBits(config_group) & CONFIG_LOAD_BIT)!=0);
  250. bool changedFlag=bIsConfigLoading?false:flag;
  251. ESP_LOGV(TAG, "config_set_entry_changed_flag: retrieving chg flag from entry");
  252. cJSON * changed = cJSON_GetObjectItemCaseSensitive(entry, "chg");
  253. if(changed ==NULL ) {
  254. ESP_LOGV(TAG, "config_set_entry_changed_flag: chg flag not found. Adding. ");
  255. cJSON_AddBoolToObject(entry,"chg",changedFlag);
  256. }
  257. else {
  258. ESP_LOGV(TAG, "config_set_entry_changed_flag: Existing change flag found. ");
  259. if(cJSON_IsTrue(changed) && changedFlag){
  260. ESP_LOGW(TAG, "Commit flag not changed!");
  261. }
  262. else{
  263. ESP_LOGV(TAG, "config_set_entry_changed_flag: Updating change flag to %s",changedFlag?"TRUE":"FALSE");
  264. changed->type = changedFlag?cJSON_True:cJSON_False ;
  265. }
  266. }
  267. if(changedFlag) {
  268. ESP_LOGV(TAG, "config_set_entry_changed_flag: Calling config_raise_change. ");
  269. config_raise_change(true);
  270. }
  271. ESP_LOGV(TAG, "config_set_entry_changed_flag: done. ");
  272. }
  273. cJSON_bool config_is_entry_changed(cJSON * entry){
  274. if(entry==NULL){
  275. ESP_LOGE(TAG,"null pointer received!");
  276. return true;
  277. }
  278. cJSON * changed = cJSON_GetObjectItemCaseSensitive(entry, "chg");
  279. if(changed ==NULL ) {
  280. ESP_LOGE(TAG, "Change flag not found! ");
  281. return true;
  282. }
  283. return cJSON_IsTrue(changed);
  284. }
  285. void * config_safe_alloc_get_entry_value(nvs_type_t nvs_type, cJSON * entry){
  286. void * value=NULL;
  287. if(entry==NULL){
  288. ESP_LOGE(TAG,"null pointer received!");
  289. }
  290. ESP_LOGV(TAG, "getting config value type %s", type_to_str(nvs_type));
  291. cJSON * entry_value = cJSON_GetObjectItemCaseSensitive(entry, "value");
  292. if(entry_value==NULL ) {
  293. char * entry_str = cJSON_PrintUnformatted(entry);
  294. if(entry_str!=NULL){
  295. ESP_LOGE(TAG, "Missing config value!. Object: \n%s", entry_str);
  296. free(entry_str);
  297. }
  298. else{
  299. ESP_LOGE(TAG, "Missing config value");
  300. }
  301. return NULL;
  302. }
  303. nvs_type_t type = config_get_entry_type(entry);
  304. if(nvs_type != type){
  305. // requested value type different than the stored type
  306. char * entry_str = cJSON_PrintUnformatted(entry);
  307. if(entry_str!=NULL){
  308. ESP_LOGE(TAG, "Requested value type %s, found value type %s instead, Object: \n%s", type_to_str(nvs_type), type_to_str(type),entry_str);
  309. free(entry_str);
  310. }
  311. else{
  312. ESP_LOGE(TAG, "Requested value type %s, found value type %s instead", type_to_str(nvs_type), type_to_str(type));
  313. }
  314. return NULL;
  315. }
  316. if (nvs_type == NVS_TYPE_I8) {
  317. value=malloc(sizeof(int8_t));
  318. *(int8_t *)value = (int8_t)entry_value->valuedouble;
  319. } else if (nvs_type == NVS_TYPE_U8) {
  320. value=malloc(sizeof(uint8_t));
  321. *(uint8_t *)value = (uint8_t)entry_value->valuedouble;
  322. } else if (nvs_type == NVS_TYPE_I16) {
  323. value=malloc(sizeof(int16_t));
  324. *(int16_t *)value = (int16_t)entry_value->valuedouble;
  325. } else if (nvs_type == NVS_TYPE_U16) {
  326. value=malloc(sizeof(uint16_t));
  327. *(uint16_t *)value = (uint16_t)entry_value->valuedouble;
  328. } else if (nvs_type == NVS_TYPE_I32) {
  329. value=malloc(sizeof(int32_t));
  330. *(int32_t *)value = (int32_t)entry_value->valuedouble;
  331. } else if (nvs_type == NVS_TYPE_U32) {
  332. value=malloc(sizeof(uint32_t));
  333. *(uint32_t *)value = (uint32_t)entry_value->valuedouble;
  334. } else if (nvs_type == NVS_TYPE_I64) {
  335. value=malloc(sizeof(int64_t));
  336. *(int64_t *)value = (int64_t)entry_value->valuedouble;
  337. } else if (nvs_type == NVS_TYPE_U64) {
  338. value=malloc(sizeof(uint64_t));
  339. *(uint64_t *)value = (uint64_t)entry_value->valuedouble;
  340. } else if (nvs_type == NVS_TYPE_STR) {
  341. if(!cJSON_IsString(entry_value)){
  342. char * entry_str = cJSON_PrintUnformatted(entry);
  343. if(entry_str!=NULL){
  344. ESP_LOGE(TAG, "requested value type string, config type is different. key: %s, value: %s, type %d, Object: \n%s",
  345. entry_value->string,
  346. entry_value->valuestring,
  347. entry_value->type,
  348. entry_str);
  349. free(entry_str);
  350. }
  351. else {
  352. ESP_LOGE(TAG, "requested value type string, config type is different. key: %s, value: %s, type %d",
  353. entry_value->string,
  354. entry_value->valuestring,
  355. entry_value->type);
  356. }
  357. }
  358. else {
  359. value=(void *)strdup(cJSON_GetStringValue(entry_value));
  360. if(value==NULL){
  361. char * entry_str = cJSON_PrintUnformatted(entry);
  362. if(entry_str!=NULL){
  363. ESP_LOGE(TAG, "strdup failed on value for object \n%s",entry_str);
  364. free(entry_str);
  365. }
  366. else {
  367. ESP_LOGE(TAG, "strdup failed on value");
  368. }
  369. }
  370. }
  371. } else if (nvs_type == NVS_TYPE_BLOB) {
  372. ESP_LOGE(TAG, "Unsupported type NVS_TYPE_BLOB");
  373. }
  374. return value;
  375. }
  376. void config_commit_to_nvs(){
  377. ESP_LOGI(TAG,"Committing configuration to nvs. Locking config object.");
  378. ESP_LOGV(TAG,"config_commit_to_nvs. Locking config object.");
  379. if(!config_lock(LOCK_MAX_WAIT/portTICK_PERIOD_MS)){
  380. ESP_LOGE(TAG, "config_commit_to_nvs: Unable to lock config for commit ");
  381. return ;
  382. }
  383. if(nvs_json==NULL){
  384. ESP_LOGE(TAG, ": cJSON nvs cache object not set.");
  385. return;
  386. }
  387. ESP_LOGV(TAG,"config_commit_to_nvs. Config Locked!");
  388. cJSON * entry=nvs_json->child;
  389. while(entry!= NULL){
  390. char * entry_str = cJSON_PrintUnformatted(entry);
  391. if(entry_str!=NULL){
  392. ESP_LOGV(TAG,"config_commit_to_nvs processing item %s",entry_str);
  393. free(entry_str);
  394. }
  395. if(config_is_entry_changed(entry)){
  396. ESP_LOGD(TAG, "Committing entry %s value to nvs.",(entry->string==NULL)?"UNKNOWN":entry->string);
  397. nvs_type_t type = config_get_entry_type(entry);
  398. void * value = config_safe_alloc_get_entry_value(type, entry);
  399. if(value!=NULL){
  400. esp_err_t err = store_nvs_value(type,entry->string,value);
  401. free(value);
  402. if(err!=ESP_OK){
  403. char * entry_str = cJSON_PrintUnformatted(entry);
  404. if(entry_str!=NULL){
  405. ESP_LOGE(TAG, "Error comitting value to nvs for key %s, Object: \n%s",entry->string,entry_str);
  406. free(entry_str);
  407. }
  408. else {
  409. ESP_LOGE(TAG, "Error comitting value to nvs for key %s",entry->string);
  410. }
  411. }
  412. else {
  413. config_set_entry_changed_flag(entry, false);
  414. }
  415. }
  416. else {
  417. char * entry_str = cJSON_PrintUnformatted(entry);
  418. if(entry_str!=NULL){
  419. ESP_LOGE(TAG, "Unable to retrieve value. Error comitting value to nvs for key %s, Object: \n%s",entry->string,entry_str);
  420. free(entry_str);
  421. }
  422. else {
  423. ESP_LOGE(TAG, "Unable to retrieve value. Error comitting value to nvs for key %s",entry->string);
  424. }
  425. }
  426. }
  427. else {
  428. ESP_LOGV(TAG,"config_commit_to_nvs. Item already committed. Ignoring.");
  429. }
  430. taskYIELD(); /* allows the freeRTOS scheduler to take over if needed. */
  431. entry = entry->next;
  432. }
  433. ESP_LOGV(TAG,"config_commit_to_nvs. Resetting the global commit flag.");
  434. config_raise_change(false);
  435. ESP_LOGV(TAG,"config_commit_to_nvs. Releasing the lock object.");
  436. config_unlock();
  437. }
  438. bool config_has_changes(){
  439. return (xEventGroupGetBits(config_group) & CONFIG_NO_COMMIT_PENDING)==0;
  440. }
  441. bool wait_for_commit(){
  442. bool commit_pending=(xEventGroupGetBits(config_group) & CONFIG_NO_COMMIT_PENDING)==0;
  443. while (commit_pending){
  444. ESP_LOGW(TAG,"Waiting for config commit ...");
  445. commit_pending = (xEventGroupWaitBits(config_group, CONFIG_NO_COMMIT_PENDING,pdFALSE, pdTRUE, (CONFIG_COMMIT_DELAY*2) / portTICK_PERIOD_MS) & CONFIG_NO_COMMIT_PENDING)==0;
  446. if(commit_pending){
  447. ESP_LOGW(TAG,"Timeout waiting for config commit.");
  448. }
  449. else {
  450. ESP_LOGI(TAG,"Config committed!");
  451. }
  452. }
  453. return !commit_pending;
  454. }
  455. bool config_lock(TickType_t xTicksToWait) {
  456. ESP_LOGV(TAG, "Locking config json object");
  457. if( xSemaphoreTake( config_mutex, xTicksToWait ) == pdTRUE ) {
  458. ESP_LOGV(TAG, "config Json object locked!");
  459. return true;
  460. }
  461. else {
  462. ESP_LOGE(TAG, "Semaphore take failed. Unable to lock config Json object mutex");
  463. return false;
  464. }
  465. }
  466. void config_unlock() {
  467. ESP_LOGV(TAG, "Unlocking json buffer!");
  468. xSemaphoreGive( config_mutex );
  469. }
  470. static void vCallbackFunction( TimerHandle_t xTimer ) {
  471. static int cnt=0;
  472. if(config_has_changes()){
  473. ESP_LOGI(TAG, "configuration has some uncommitted entries");
  474. config_commit_to_nvs();
  475. }
  476. else{
  477. if(++cnt>=15){
  478. ESP_LOGV(TAG,"commit timer: commit flag not set");
  479. cnt=0;
  480. }
  481. }
  482. xTimerReset( xTimer, 10 );
  483. }
  484. void config_raise_change(bool change_found){
  485. if(config_set_group_bit(CONFIG_NO_COMMIT_PENDING,!change_found))
  486. {
  487. ESP_LOGD(TAG,"Config commit set to %s",change_found?"Pending Commit":"Committed");
  488. }
  489. }
  490. bool config_set_group_bit(int bit_num,bool flag){
  491. bool result = true;
  492. int curFlags=xEventGroupGetBits(config_group);
  493. if((curFlags & CONFIG_LOAD_BIT) && bit_num == CONFIG_NO_COMMIT_PENDING ){
  494. ESP_LOGD(TAG,"Loading config, ignoring changes");
  495. result = false;
  496. }
  497. if(result){
  498. bool curBit=(xEventGroupGetBits(config_group) & bit_num);
  499. if(curBit == flag){
  500. ESP_LOGV(TAG,"Flag %d already %s", bit_num, flag?"Set":"Cleared");
  501. result = false;
  502. }
  503. }
  504. if(result){
  505. ESP_LOGV(TAG,"%s Flag %d ", flag?"Setting":"Clearing",bit_num);
  506. if(!flag){
  507. xEventGroupClearBits(config_group, bit_num);
  508. }
  509. else {
  510. xEventGroupSetBits(config_group, bit_num);
  511. }
  512. }
  513. return result;
  514. }
  515. void config_set_default(nvs_type_t type, const char *key, void * default_value, size_t blob_size) {
  516. if(!config_lock(LOCK_MAX_WAIT/portTICK_PERIOD_MS)){
  517. ESP_LOGE(TAG, "Unable to lock config");
  518. return;
  519. }
  520. ESP_LOGV(TAG, "Checking if key %s exists in nvs cache for type %s.", key,type_to_str(type));
  521. cJSON * entry = cJSON_GetObjectItemCaseSensitive(nvs_json, key);
  522. if(entry !=NULL){
  523. ESP_LOGV(TAG, "Entry found.");
  524. }
  525. else {
  526. // Value was not found
  527. ESP_LOGW(TAG, "Adding default value for [%s].", key);
  528. entry=config_set_value_safe(type, key, default_value);
  529. if(entry == NULL){
  530. ESP_LOGE(TAG, "Failed to add value to cache!");
  531. }
  532. char * entry_str = cJSON_PrintUnformatted(entry);
  533. if(entry_str!=NULL){
  534. ESP_LOGD(TAG, "Value added to default for object: \n%s",entry_str);
  535. free(entry_str);
  536. }
  537. }
  538. config_unlock();
  539. }
  540. void config_delete_key(const char *key){
  541. nvs_handle nvs;
  542. ESP_LOGD(TAG, "Deleting nvs entry for [%s]", key);
  543. if(!config_lock(LOCK_MAX_WAIT/portTICK_PERIOD_MS)){
  544. ESP_LOGE(TAG, "Unable to lock config for delete");
  545. return false;
  546. }
  547. esp_err_t err = nvs_open_from_partition(settings_partition, current_namespace, NVS_READWRITE, &nvs);
  548. if (err == ESP_OK) {
  549. err = nvs_erase_key(nvs, key);
  550. if (err == ESP_OK) {
  551. ESP_LOGD(TAG, "key [%s] erased from nvs.",key);
  552. err = nvs_commit(nvs);
  553. if (err == ESP_OK) {
  554. ESP_LOGD(TAG, "nvs erase committed.");
  555. }
  556. else {
  557. ESP_LOGE(TAG, "Unable to commit nvs erase operation for key [%s]. %s.",key,esp_err_to_name(err));
  558. }
  559. }
  560. else {
  561. ESP_LOGE(TAG, "Unable to delete nvs key [%s]. %s. ",key, esp_err_to_name(err));
  562. }
  563. nvs_close(nvs);
  564. }
  565. else {
  566. ESP_LOGE(TAG, "Error opening nvs: %s. Unable to delete nvs key [%s].",esp_err_to_name(err),key);
  567. }
  568. char * struc_str = cJSON_PrintUnformatted(nvs_json);
  569. if(struc_str!=NULL){
  570. ESP_LOGV(TAG, "Structure before delete \n%s", struc_str);
  571. free(struc_str);
  572. }
  573. cJSON * entry = cJSON_DetachItemFromObjectCaseSensitive(nvs_json, key);
  574. if(entry !=NULL){
  575. ESP_LOGI(TAG, "Removing config key [%s]", entry->string);
  576. cJSON_Delete(entry);
  577. struc_str = cJSON_PrintUnformatted(nvs_json);
  578. if(struc_str!=NULL){
  579. ESP_LOGV(TAG, "Structure after delete \n%s", struc_str);
  580. free(struc_str);
  581. }
  582. }
  583. else {
  584. ESP_LOGW(TAG, "Unable to remove config key [%s]: not found.", key);
  585. }
  586. config_unlock();
  587. }
  588. void * config_alloc_get(nvs_type_t nvs_type, const char *key) {
  589. return config_alloc_get_default(nvs_type, key, NULL, 0);
  590. }
  591. void * config_alloc_get_default(nvs_type_t nvs_type, const char *key, void * default_value, size_t blob_size) {
  592. void * value = NULL;
  593. ESP_LOGV(TAG, "Retrieving key %s from nvs cache for type %s.", key,type_to_str(nvs_type));
  594. if(nvs_json==NULL){
  595. ESP_LOGE(TAG,"configuration not loaded!");
  596. return value;
  597. }
  598. if(!config_lock(LOCK_MAX_WAIT/portTICK_PERIOD_MS)){
  599. ESP_LOGE(TAG, "Unable to lock config");
  600. return value;
  601. }
  602. ESP_LOGD(TAG,"Getting config entry for key %s",key);
  603. cJSON * entry = cJSON_GetObjectItemCaseSensitive(nvs_json, key);
  604. if(entry !=NULL){
  605. ESP_LOGV(TAG, "Entry found, getting value.");
  606. value = config_safe_alloc_get_entry_value(nvs_type, entry);
  607. }
  608. else if(default_value!=NULL){
  609. // Value was not found
  610. ESP_LOGW(TAG, "Adding new config value for key [%s]",key);
  611. entry=config_set_value_safe(nvs_type, key, default_value);
  612. if(entry == NULL){
  613. ESP_LOGE(TAG, "Failed to add value to cache");
  614. }
  615. else {
  616. char * entry_str = cJSON_PrintUnformatted(entry);
  617. if(entry_str!=NULL){
  618. ESP_LOGV(TAG, "Value added configuration object for key [%s]: \n%s", entry->string,entry_str);
  619. free(entry_str);
  620. }
  621. else {
  622. ESP_LOGV(TAG, "Value added configuration object for key [%s]", entry->string);
  623. }
  624. value = config_safe_alloc_get_entry_value(nvs_type, entry);
  625. }
  626. }
  627. else{
  628. ESP_LOGW(TAG,"Value not found for key %s",key);
  629. }
  630. config_unlock();
  631. return value;
  632. }
  633. char * config_alloc_get_json(bool bFormatted){
  634. char * json_buffer = NULL;
  635. if(!config_lock(LOCK_MAX_WAIT/portTICK_PERIOD_MS)){
  636. ESP_LOGE(TAG, "Unable to lock config after %d ms",LOCK_MAX_WAIT);
  637. return strdup("{\"error\":\"Unable to lock configuration object.\"}");
  638. }
  639. if(bFormatted){
  640. json_buffer= cJSON_Print(nvs_json);
  641. }
  642. else {
  643. json_buffer= cJSON_PrintUnformatted(nvs_json);
  644. }
  645. config_unlock();
  646. return json_buffer;
  647. }
  648. esp_err_t config_set_value(nvs_type_t nvs_type, const char *key, void * value){
  649. esp_err_t result = ESP_OK;
  650. if(!config_lock(LOCK_MAX_WAIT/portTICK_PERIOD_MS)){
  651. ESP_LOGE(TAG, "Unable to lock config after %d ms",LOCK_MAX_WAIT);
  652. result = ESP_FAIL;
  653. }
  654. cJSON * entry = config_set_value_safe(nvs_type, key, value);
  655. if(entry == NULL){
  656. result = ESP_FAIL;
  657. }
  658. else{
  659. char * entry_str = cJSON_PrintUnformatted(entry);
  660. if(entry_str!=NULL){
  661. ESP_LOGV(TAG,"config_set_value result: \n%s",entry_str);
  662. free(entry_str);
  663. }
  664. else {
  665. ESP_LOGV(TAG,"config_set_value completed");
  666. }
  667. }
  668. config_unlock();
  669. return result;
  670. }
  671. IMPLEMENT_SET_DEFAULT(uint8_t,NVS_TYPE_U8);
  672. IMPLEMENT_SET_DEFAULT(int8_t,NVS_TYPE_I8);
  673. IMPLEMENT_SET_DEFAULT(uint16_t,NVS_TYPE_U16);
  674. IMPLEMENT_SET_DEFAULT(int16_t,NVS_TYPE_I16);
  675. IMPLEMENT_SET_DEFAULT(uint32_t,NVS_TYPE_U32);
  676. IMPLEMENT_SET_DEFAULT(int32_t,NVS_TYPE_I32);
  677. IMPLEMENT_GET_NUM(uint8_t,NVS_TYPE_U8);
  678. IMPLEMENT_GET_NUM(int8_t,NVS_TYPE_I8);
  679. IMPLEMENT_GET_NUM(uint16_t,NVS_TYPE_U16);
  680. IMPLEMENT_GET_NUM(int16_t,NVS_TYPE_I16);
  681. IMPLEMENT_GET_NUM(uint32_t,NVS_TYPE_U32);
  682. IMPLEMENT_GET_NUM(int32_t,NVS_TYPE_I32);