Jak číst ESP32 NVS value do std::string

V našem předchozím postu jsme diskutovali Jak získat length / size of NVS value na ESP32. Na základě toho můžeme číst NVS value do std::string.

Strategie

  1. Určit size of value v NVS
  2. Alokovat temporary buffer určené size
  3. Číst value z NVS do temporary buffer
  4. Vytvořit std::string z value
  5. Cleanup temporary buffer

Utility function pro čtení NVS value jako std::string

V případě, že key neexistuje v NVS, tato function vrátí 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 of value in NVS
     *  2. Allocate temporary buffer of determined size
     *  3. Read value from NVS into temporary buffer
     *  4. Create std::string from value
     *  5. Cleanup
     */
    // Step 1: Get size of 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 to 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" has already been handled before, so this is an actual error.
        // We assume that the value did not change between reading the size (step 1) and now.
        // In case that assumption is value, this will fail with ESP_ERR_NVS_INVALID_LENGTH.
        // This is 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;
}

Příklad použití

To předpokládá, že jste setup myNvs jak jsme shown v našem předchozím postu Jak inicializovat NVS na ESP32

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

C++17 optimalizace

Počínaje C++17, můžete případně vytvořit std::string directly místo použití temporary buffer, protože existuje overload .data(), který vrací non-const pointer - takže můžete zapisovat directly do std::string’s buffer.

Nicméně, protože můj PlatformIO-based toolchain aktuálně nepodporuje to, nenapsal jsem tento code yet.


Podívejte se na podobné články podle kategorie: C/C++, ESP8266/ESP32