Skip to main content
RKTK API Docs RKTK Home Repo

rktk/config/storage/
read.rs

1use core::fmt::Debug;
2use kmsm::interface::state::config::StateConfig;
3use postcard::experimental::max_size::MaxSize as _;
4
5use crate::{config::keymap::Layer, drivers::interface::storage::StorageDriver};
6
7use super::{ConfigKey, StorageConfigManager};
8
9#[derive(Debug)]
10pub enum ConfigReadError<E: Debug> {
11    ReadError(E),
12    DecodeError(postcard::Error),
13}
14
15impl<E: Debug> From<E> for ConfigReadError<E> {
16    fn from(e: E) -> Self {
17        ConfigReadError::ReadError(e)
18    }
19}
20
21impl<S: StorageDriver> StorageConfigManager<S> {
22    pub async fn read_version(&self) -> Result<u16, ConfigReadError<S::Error>> {
23        let mut buf = [0; 2];
24        let key = u64::from_le_bytes([ConfigKey::Version as u8, 0, 0, 0, 0, 0, 0, 0]);
25        self.storage.read::<2>(key, &mut buf).await?;
26        Ok(u16::from_le_bytes(buf))
27    }
28
29    pub async fn read_state_config(&self) -> Result<StateConfig, ConfigReadError<S::Error>> {
30        let mut buf = [0; StateConfig::POSTCARD_MAX_SIZE];
31        let key = u64::from_le_bytes([ConfigKey::StateConfig as u8, 0, 0, 0, 0, 0, 0, 0]);
32        self.storage.read::<{ StateConfig::POSTCARD_MAX_SIZE }>(key, &mut buf).await?;
33        let res = postcard::from_bytes(&buf).map_err(ConfigReadError::DecodeError)?;
34        Ok(res)
35    }
36
37    pub async fn read_keymap(&self, layer: u8) -> Result<Layer, ConfigReadError<S::Error>> {
38        let mut buf = [0; Layer::POSTCARD_MAX_SIZE];
39        let key = u64::from_le_bytes([ConfigKey::StateKeymap as u8, layer, 0, 0, 0, 0, 0, 0]);
40        self.storage.read::<{ Layer::POSTCARD_MAX_SIZE }>(key, &mut buf).await?;
41        let res = postcard::from_bytes(&buf).map_err(ConfigReadError::DecodeError)?;
42        Ok(res)
43    }
44
45    pub async fn read_calibration<const N: usize>(
46        &self,
47        buf: &mut [u8],
48    ) -> Result<(), ConfigReadError<S::Error>> {
49        let key = u64::from_le_bytes([ConfigKey::Calibration as u8, 0, 0, 0, 0, 0, 0, 0]);
50        self.storage.read::<N>(key, buf).await?;
51        Ok(())
52    }
53}