platform_config.c 23 KB

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