Skip to content

ESP_ERR_NVS_NOT_FOUND not returned by nvs_open() IDFv6.1.0 (IDFGH-16839) #17912

@littleboot

Description

@littleboot

The nvs_open() function does not work as described.

esp_err_t nvs_open(const char *namespace_name, nvs_open_mode_t open_mode, nvs_handle_t *out_handle)

According to the API it should return ESP_ERR_NVS_NOT_FOUND when the the namespace is not found and the open_mode is NVS_READONLY:
ESP_ERR_NVS_NOT_FOUND id namespace doesn't exist yet and mode is NVS_READONLY

I want to use this to determine if the nvs contains my device settings or if I should initialize the nvs with my factory defaults. the code below should work but it doesn't nvs_open() on a non existing namespace in readonly mode return ESP_OK instead of ESP_ERR_NVS_NOT_FOUND
(i performed esptool erase-flash before flashing the test app)

esp_err_t settings_init(void)
{
    esp_err_t err = ESP_OK;
    nvs_handle_t handle = 0;
    char *buffer = NULL;
    cJSON *settings_default = NULL;

    // Initialize NVS
    err = nvs_flash_init();
    if (err == ESP_ERR_NVS_NO_FREE_PAGES || err == ESP_ERR_NVS_NEW_VERSION_FOUND)
    {
        ESP_ERROR_CHECK(nvs_flash_erase());
        err = nvs_flash_init();
    }
    if (err != ESP_OK)
    {
        ESP_LOGE(TAG, "NVS init failed");
        return err;
    }

    // Try opening read-only
    err = nvs_open(SETTINGS_NAMESPACE, NVS_READONLY, &handle);

    if (err == ESP_OK)
    {
        ESP_LOGI(TAG, "NVS open SETTINGS_NAMESPACE success, using current settings");
        // Namespace exists — nothing to do
        nvs_close(handle);
        return ESP_OK;
    }

    if (err != ESP_ERR_NVS_NOT_FOUND)
    {
        ESP_LOGE(TAG, "Failed to open NVS namespace: %s", esp_err_to_name(err));
        return err;
    }

    // Namespace missing → load defaults
    ESP_LOGW(TAG, "SETTINGS_NAMESPACE missing. Loading defaults...");

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions