Como read ESP32 NVS value into std::string

En nuestro previous post, discutimos Como get el length / size de NVS value on ESP32. Based on eso, podemos read un NVS value into un std::string.

Strategy

  1. Determine size de value en NVS
  2. Allocate temporary buffer del determined size
  3. Read value from NVS into temporary buffer
  4. Create std::string from value
  5. Cleanup temporary buffer

Utility function para read NVS value as std::string

In case el key no exist en NVS, esta function returnara el empty string ("").

read_nvs_to_stdstring.cpp
#include <nvs.h>
#include <string>

std::string ReadNVSValueAsStdString(nvs_handle_t nvs, const char* key) {
    /**
     * Strategy:
     *  1. Determine size de value en NVS
     *  2. Allocate temporary buffer de determined size
     *  3. Read value from NVS into temporary buffer
     *  4. Create std::string from value
     *  5. Cleanup
     */
    // Step 1: Get size de key
    esp_err_t err;
    size_t value_size = 0;
    if((err = nvs_get_str(nvs, _key.c_str(), nullptr, &value_size)) != ESP_OK) {
        if(err == ESP_ERR_NVS_NOT_FOUND) {
            // Not found, no error
            return "";
        } else {
            printf("Failed to get size of NVS key %s: %s\r\n", key, esp_err_to_name(err));
            return;
        }
    }
    // Step 2: Allocate temporary buffer para read from
    char* buf = (char*)malloc(value_size);
    // Step 3: Read value into temporary buffer.
    esp_err_t err;
    if((err = nvs_get_str(nvs, _key.c_str(), buf, &value_size)) != ESP_OK) {
        // "Doesn't exist" ha already sido handled before, asi que esto es un actual error.
        // Asumimos que el value no change between reading el size (step 1) y now.
        // In case que esa assumption es value, esto failara con ESP_ERR_NVS_INVALID_LENGTH.
        // Esto es extremely unlikely in all usage scenarios, however.
        printf("Failed to read NVS key %s: %s\r\n", key, esp_err_to_name(err));
        free(buf);
        return "";
    }
    // Step 4: Make string
    std::string value = std::string(buf, value_size);
    // Step 5: cleanup
    free(buf);

    return value;
}

Usage example

Esto asume que has setup myNvs as hemos shown en nuestro previous post Como initialize NVS on ESP32

example_usage.cpp
std::string value = ReadNVSValueAsStdString(myNvs, "MyKey");

C++17 optimizations

Starting from C++17, puedes possibly create un std::string directly instead de usar el temporary buffer, since hay un overload de .data() que returns un non-const pointer - asi que puedes write directly al std::string’s buffer.

However, since my PlatformIO-based toolchain currently no support eso, no he written ese code yet.


Echa un vistazo a artículos similares por categoría: C/C++, ESP8266/ESP32