/** * @file nvs_config.c * @brief Runtime configuration via NVS (Non-Volatile Storage). * * Checks NVS namespace "csi_cfg" for keys: ssid, password, target_ip, * target_port, node_id. Falls back to Kconfig defaults when absent. */ #include "nvs_config.h" #include #include "esp_log.h" #include "nvs_flash.h" #include "nvs.h" #include "sdkconfig.h" static const char *TAG = "nvs_config"; void nvs_config_load(nvs_config_t *cfg) { /* Start with Kconfig compiled defaults */ strncpy(cfg->wifi_ssid, CONFIG_CSI_WIFI_SSID, NVS_CFG_SSID_MAX - 1); cfg->wifi_ssid[NVS_CFG_SSID_MAX - 1] = '\0'; #ifdef CONFIG_CSI_WIFI_PASSWORD strncpy(cfg->wifi_password, CONFIG_CSI_WIFI_PASSWORD, NVS_CFG_PASS_MAX - 1); cfg->wifi_password[NVS_CFG_PASS_MAX - 1] = '\0'; #else cfg->wifi_password[0] = '\0'; #endif strncpy(cfg->target_ip, CONFIG_CSI_TARGET_IP, NVS_CFG_IP_MAX - 1); cfg->target_ip[NVS_CFG_IP_MAX - 1] = '\0'; cfg->target_port = (uint16_t)CONFIG_CSI_TARGET_PORT; cfg->node_id = (uint8_t)CONFIG_CSI_NODE_ID; /* Try to override from NVS */ nvs_handle_t handle; esp_err_t err = nvs_open("csi_cfg", NVS_READONLY, &handle); if (err != ESP_OK) { ESP_LOGI(TAG, "No NVS config found, using compiled defaults"); return; } size_t len; char buf[NVS_CFG_PASS_MAX]; /* WiFi SSID */ len = sizeof(buf); if (nvs_get_str(handle, "ssid", buf, &len) == ESP_OK && len > 1) { strncpy(cfg->wifi_ssid, buf, NVS_CFG_SSID_MAX - 1); cfg->wifi_ssid[NVS_CFG_SSID_MAX - 1] = '\0'; ESP_LOGI(TAG, "NVS override: ssid=%s", cfg->wifi_ssid); } /* WiFi password */ len = sizeof(buf); if (nvs_get_str(handle, "password", buf, &len) == ESP_OK) { strncpy(cfg->wifi_password, buf, NVS_CFG_PASS_MAX - 1); cfg->wifi_password[NVS_CFG_PASS_MAX - 1] = '\0'; ESP_LOGI(TAG, "NVS override: password=***"); } /* Target IP */ len = sizeof(buf); if (nvs_get_str(handle, "target_ip", buf, &len) == ESP_OK && len > 1) { strncpy(cfg->target_ip, buf, NVS_CFG_IP_MAX - 1); cfg->target_ip[NVS_CFG_IP_MAX - 1] = '\0'; ESP_LOGI(TAG, "NVS override: target_ip=%s", cfg->target_ip); } /* Target port */ uint16_t port_val; if (nvs_get_u16(handle, "target_port", &port_val) == ESP_OK) { cfg->target_port = port_val; ESP_LOGI(TAG, "NVS override: target_port=%u", cfg->target_port); } /* Node ID */ uint8_t node_val; if (nvs_get_u8(handle, "node_id", &node_val) == ESP_OK) { cfg->node_id = node_val; ESP_LOGI(TAG, "NVS override: node_id=%u", cfg->node_id); } nvs_close(handle); }