platform_config.c 22 KB

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