rktk_drivers_common/storage/
flash_sequential_map.rs1use core::fmt::Debug;
4use embedded_storage_async::nor_flash::{MultiwriteNorFlash, NorFlash, ReadNorFlash};
5use rktk::{
6 drivers::interface::{Error, storage::StorageDriver},
7 utils::Mutex,
8};
9pub use sequential_storage;
10use sequential_storage::{
11 cache::NoCache,
12 map::{MapConfig, MapStorage},
13};
14
15#[derive(Debug)]
18#[cfg_attr(feature = "defmt", derive(defmt::Format))]
19pub enum FlashSequentialMapStorageError<E: Debug> {
20 Storage(#[cfg_attr(feature = "defmt", defmt(Debug2Format))] sequential_storage::Error<E>),
21 NotFound,
22}
23impl<E: Debug> Error for FlashSequentialMapStorageError<E> {}
24
25impl<E: Debug> From<sequential_storage::Error<E>> for FlashSequentialMapStorageError<E> {
26 fn from(e: sequential_storage::Error<E>) -> Self {
27 Self::Storage(e)
28 }
29}
30
31pub struct FlashSequentialMapStorage<F: NorFlash + ReadNorFlash + MultiwriteNorFlash> {
34 storage: Mutex<MapStorage<u64, F, NoCache>>,
35}
36
37impl<F: NorFlash + ReadNorFlash + MultiwriteNorFlash> FlashSequentialMapStorage<F> {
38 pub fn new(flash: F, start_address: u32, storage_size: u32) -> Self {
39 let storage = MapStorage::new(
40 flash,
41 MapConfig::new(start_address..start_address + storage_size),
42 NoCache,
43 );
44 Self { storage: Mutex::new(storage) }
45 }
46}
47
48impl<F: NorFlash + ReadNorFlash + MultiwriteNorFlash> StorageDriver
49 for FlashSequentialMapStorage<F>
50{
51 type Error = FlashSequentialMapStorageError<F::Error>;
52
53 async fn format(&self) -> Result<(), Self::Error> {
54 let mut storage = self.storage.lock().await;
55 storage.remove_all_items(&mut [0; 1024]).await?;
56 Ok(())
57 }
58
59 async fn read<const N: usize>(&self, key: u64, buf: &mut [u8]) -> Result<(), Self::Error> {
60 let mut storage = self.storage.lock().await;
61 let val: [u8; N] = storage
62 .fetch_item(&mut [0; 1024], &key)
63 .await?
64 .ok_or(FlashSequentialMapStorageError::NotFound)?;
65 buf.copy_from_slice(&val);
66 Ok(())
67 }
68
69 async fn write<const N: usize>(&self, key: u64, item_buf: &[u8]) -> Result<(), Self::Error> {
70 let mut storage = self.storage.lock().await;
71 storage.store_item(&mut [0; 1024], &key, &item_buf).await?;
72 Ok(())
73 }
74}