From 69663bc968d36805fd2e5262856bbaccf20c8480 Mon Sep 17 00:00:00 2001 From: rhetenor Date: Wed, 26 Aug 2026 20:47:17 +0000 Subject: [PATCH] card storage: make more robust, handle cards that are already seen, implement in nfc read --- src/bin/main.rs | 3 + src/storage/cardstore.rs | 160 +++++++++++++++++++++++++++++---------- 2 files changed, 122 insertions(+), 41 deletions(-) diff --git a/src/bin/main.rs b/src/bin/main.rs index 2110515..436a76d 100644 --- a/src/bin/main.rs +++ b/src/bin/main.rs @@ -22,6 +22,7 @@ use creaturedex::network::wifi::setup_wifi; use creaturedex::storage::cardstore::CardStore; use creaturedex::storage::store::Store; use embassy_executor::Spawner; +use embassy_time::Instant; use embedded_graphics::pixelcolor::BinaryColor; use embedded_graphics::{ mono_font::{MonoTextStyle, ascii::FONT_6X10}, @@ -29,6 +30,8 @@ use embedded_graphics::{ text::Text, }; use embedded_hal_bus::i2c::AtomicDevice; +use embedded_hal_bus::util::AtomicCell; +use esp_hal::Blocking; use esp_hal::clock::CpuClock; use esp_hal::gpio::{Input, InputConfig, Pull}; use esp_hal::timer::timg::TimerGroup; diff --git a/src/storage/cardstore.rs b/src/storage/cardstore.rs index 7b65372..8b69c54 100644 --- a/src/storage/cardstore.rs +++ b/src/storage/cardstore.rs @@ -1,24 +1,27 @@ -use alloc::collections::BTreeMap; +use alloc::collections::BTreeMap; use alloc::vec::Vec; -use binary_serde::{BinarySerde, Endianness, DeserializeError}; +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::{MemoryRegion,CARDSTORE_REGION}; +use crate::storage::{CARDSTORE_REGION, MemoryRegion}; const MAX_CARDS: usize = 20000; -const COUNT_REGION: MemoryRegion = MemoryRegion { offset: CARDSTORE_REGION.offset, size: size_of::()}; +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 + // this is the numeric offset of the AllocationTableEntry // as well as the card entry in flash memory // size_of::() * offset // size_of::() * offset @@ -26,7 +29,7 @@ pub struct AllocationTableEntry { creation_date: u64, last_read_date: u64, - + // how often a card has been read by nfc read_count: u32, @@ -38,96 +41,171 @@ pub struct AllocationTableEntry { 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] + 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 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()}; +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 + NoEntry, } -impl From for CardStoreError { - fn from(error: StoreError) -> CardStoreError { - CardStoreError::Store(error) +impl From for CardStoreError { + fn from(error: StoreError) -> CardStoreError { + CardStoreError::Store(error) } } -impl From for CardStoreError { - fn from(error: DeserializeError) -> CardStoreError { - CardStoreError::CorruptedEntry(error) +impl From for CardStoreError { + fn from(error: DeserializeError) -> CardStoreError { + CardStoreError::CorruptedEntry(error) } } pub struct CardStore { store: Store, count: u32, - pub allocation_table: BTreeMap + 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)?; + 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); + 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)?; + store.read( + ALLOCATION_TABLE_REGION.offset, + &mut allocation_table_entries, + )?; - let chunks = allocation_table_entries.into_chunks::<{ AllocationTableEntry::SERIALIZED_SIZE }>(); + 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)?; + 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 }) + 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 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)?) + Ok(RawCard::binary_deserialize( + raw_card.as_ref(), + Endianness::Little, + )?) } - pub fn save_raw_card(&mut self, raw_card: RawCard, timestamp: u64) -> Result<(), CardStoreError> { + 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); - let uuid: u32 = (u16::from_ne_bytes(raw_card.event_encoding) as u32) << 16 | (u16::from_ne_bytes(raw_card.card_uuid) as u32); - let entry = match self.allocation_table.values_mut().find(|entry| entry.deleted) { - Some(entry) => entry, - None => { - 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") + // 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; - 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)?; - - let mut serialized_entry: [u8; AllocationTableEntry::SERIALIZED_SIZE] = [0; AllocationTableEntry::SERIALIZED_SIZE]; + 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.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(()) } }