Skip to content

Instantly share code, notes, and snippets.

@pyaillet
Last active October 18, 2022 21:40
Show Gist options
  • Save pyaillet/cef47fd807218e1a5154853ebe8c99d9 to your computer and use it in GitHub Desktop.
Save pyaillet/cef47fd807218e1a5154853ebe8c99d9 to your computer and use it in GitHub Desktop.
esp-idf-rs storage example
use std::sync::Arc;
use embedded_svc::storage::{RawStorage, StorageBase};
use esp_idf_svc::{nvs::EspDefaultNvs, nvs_storage::EspNvsStorage};
use esp_idf_sys as _; // If using the `binstart` feature of `esp-idf-sys`, always keep this module imported
use log::*;
fn main() {
// Temporary. Will disappear once ESP-IDF 4.4 is released, but for now it is necessary to call this function once,
// or else some patches to the runtime implemented by esp-idf-sys might not link properly.
esp_idf_sys::link_patches();
// Bind the log crate to the ESP Logging facilities
esp_idf_svc::log::EspLogger::initialize_default();
#[allow(unused)]
let default_nvs = Arc::new(EspDefaultNvs::new().expect("Unable to initialize NVS"));
#[allow(unused)]
let mut storage = EspNvsStorage::new_default(default_nvs, "test", true)
.expect("Unable to initialize storage");
if !storage
.contains("test_key")
.expect("Unable to query storage")
{
info!("No key found about to create it");
storage
.put_raw("test_key", "Hello world".as_bytes())
.expect("Unable to persist value");
info!("key created");
}
info!("Key found, searching length");
let l = storage
.len("test_key")
.expect("Unable to get value length")
.unwrap_or(0);
if l == 0 {
info!("Length == 0");
storage
.put_raw("test_key", "Hello world".as_bytes())
.expect("Unable to persist value");
info!("key created");
}
info!("Length > 0");
let mut buf = vec![0; l];
storage
.get_raw("test_key", &mut buf)
.expect("Unable to get raw value");
info!("Key found, content: {buf:?}");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment