use alloc::collections::BTreeMap; use alloc::vec::Vec; use binary_serde::{BinarySerde, DeserializeError, Endianness}; //use crate::card::model::Nfcraw_card; use crate::card::model::RawCard; use crate::storage::store::{Store, StoreError}; use crate::storage::{CARDSTORE_REGION, MemoryRegion}; const MAX_CARDS: usize = 20000; const COUNT_REGION: MemoryRegion = MemoryRegion { offset: CARDSTORE_REGION.offset, size: size_of::(), }; #[derive(Debug, BinarySerde, PartialEq, Eq, Clone)] #[repr(C)] pub struct AllocationTableEntry { uuid: u32, // this is the numeric offset of the AllocationTableEntry // as well as the card entry in flash memory // size_of::() * offset // size_of::() * offset offset: u32, creation_date: u64, last_read_date: u64, // how often a card has been read by nfc read_count: u32, deleted: bool, reserved: [u64; 4], } impl AllocationTableEntry { fn new(uuid: u32, offset: u32, timestamp: u64) -> Self { Self { uuid, offset, creation_date: timestamp, last_read_date: timestamp, read_count: 0, deleted: true, reserved: [0; 4], } } } const ALLOCATION_TABLE_REGION: MemoryRegion = MemoryRegion { offset: COUNT_REGION.end() as u32, size: MAX_CARDS * AllocationTableEntry::SERIALIZED_SIZE, }; const CARDS_REGION: MemoryRegion = MemoryRegion { offset: ALLOCATION_TABLE_REGION.end() as u32, size: CARDSTORE_REGION.size - ALLOCATION_TABLE_REGION.end(), }; #[derive(Debug)] pub enum CardStoreError { Store(StoreError), CorruptedEntry(DeserializeError), NoEntry, } impl From for CardStoreError { fn from(error: StoreError) -> CardStoreError { CardStoreError::Store(error) } } impl From for CardStoreError { fn from(error: DeserializeError) -> CardStoreError { CardStoreError::CorruptedEntry(error) } } pub struct CardStore { store: Store, count: u32, pub allocation_table: BTreeMap, } impl CardStore { pub fn new(mut store: Store) -> Result { let mut count_bytes: [u8; COUNT_REGION.size] = [0; COUNT_REGION.size]; store.read(COUNT_REGION.offset, &mut count_bytes)?; let count: u32 = u32::from_ne_bytes(count_bytes); let mut allocation_table_entries: Vec = Vec::with_capacity(AllocationTableEntry::SERIALIZED_SIZE * count as usize); store.read( ALLOCATION_TABLE_REGION.offset, &mut allocation_table_entries, )?; let chunks = allocation_table_entries.into_chunks::<{ AllocationTableEntry::SERIALIZED_SIZE }>(); let mut allocation_table = BTreeMap::::new(); for chunk in chunks { let allocation_table_entry = AllocationTableEntry::binary_deserialize(chunk.as_ref(), Endianness::Little)?; allocation_table.insert(allocation_table_entry.uuid, allocation_table_entry); } Ok(Self { store, count, allocation_table, }) } pub fn get_card_by_uuid(&mut self, uuid: u32) -> Result { let entry = self .allocation_table .get(&uuid) .ok_or(CardStoreError::NoEntry)?; let mut raw_card: [u8; size_of::()] = [0; size_of::()]; self.store.read(entry.offset, &mut raw_card)?; Ok(RawCard::binary_deserialize( raw_card.as_ref(), Endianness::Little, )?) } pub fn save_raw_card( &mut self, raw_card: RawCard, timestamp: u64, ) -> Result<(), CardStoreError> { let uuid: u32 = (u16::from_ne_bytes(raw_card.event_encoding) as u32) << 16 | (u16::from_ne_bytes(raw_card.card_uuid) as u32); log::info!("Saving card with uuid {:x}", uuid); // check if we already got the card // if not find the next deleted entry, // if none create a new one at the end let (entry, is_new) = match self.allocation_table.get_mut(&uuid) { Some(entry) => { log::debug!("old entry"); (entry, false) } None => match self .allocation_table .values_mut() .find(|entry| entry.deleted) { Some(entry) => { log::debug!("deleted entry"); (entry, true) } None => { log::debug!("new entry"); let entry = AllocationTableEntry::new(uuid, self.count + 1, timestamp); self.allocation_table.insert(uuid, entry); ( self.allocation_table .get_mut(&uuid) .expect("entry was just inserted"), true, ) } }, }; // only write card data if it is new. else it is already written in flash if is_new { log::debug!("writing RawCard to flash"); let mut serialized_card: [u8; RawCard::SERIALIZED_SIZE] = [0; RawCard::SERIALIZED_SIZE]; raw_card.binary_serialize(&mut serialized_card, Endianness::Little); self.store.write( CARDS_REGION.offset + entry.offset * RawCard::SERIALIZED_SIZE as u32, &mut serialized_card, )?; } else { entry.last_read_date = timestamp; entry.read_count += 1; } entry.deleted = false; log::debug!("writing AllocationTableEntry to flash"); let mut serialized_entry: [u8; AllocationTableEntry::SERIALIZED_SIZE] = [0; AllocationTableEntry::SERIALIZED_SIZE]; entry.binary_serialize(&mut serialized_entry, Endianness::Little); self.store.write( ALLOCATION_TABLE_REGION.offset + entry.offset * AllocationTableEntry::SERIALIZED_SIZE as u32, &mut serialized_entry, )?; self.count += 1; log::debug!("writing card count to flash"); let mut serialized_count: [u8; 4] = self.count.to_le_bytes(); self.store .write(COUNT_REGION.offset, serialized_count.as_mut_slice())?; Ok(()) } }