fix flash initialization by erasing flash before writing

This commit is contained in:
2026-08-29 15:01:48 +00:00
parent b63195b943
commit e65162249d
2 changed files with 17 additions and 7 deletions
+2 -2
View File
@@ -183,7 +183,7 @@ impl CardStore {
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(
self.store.write_erase(
CARDS_REGION.offset + entry.offset * RawCard::SERIALIZED_SIZE as u32,
&mut serialized_card,
)?;
@@ -198,7 +198,7 @@ impl CardStore {
let mut serialized_entry: [u8; AllocationTableEntry::SERIALIZED_SIZE] =
[0; AllocationTableEntry::SERIALIZED_SIZE];
entry.binary_serialize(&mut serialized_entry, Endianness::Little);
self.store.write(
self.store.write_erase(
ALLOCATION_TABLE_REGION.offset
+ entry.offset * AllocationTableEntry::SERIALIZED_SIZE as u32,
&mut serialized_entry,
+15 -5
View File
@@ -3,13 +3,12 @@ use embedded_storage::nor_flash::ReadNorFlash;
use esp_storage::{FlashStorage, FlashStorageError};
use crate::storage::MAGIC_REGION;
use crate::storage::cardstore::COUNT_REGION;
pub type StoreError = FlashStorageError;
const FLASH_ADDR: u32 = 0x9000;
const INITIALIZATION_SIZE: usize = COUNT_REGION.end();
const INITIALIZATION_SIZE: usize = 0x1000;
const FLASH_INITIALIZE_MAGIC: u32 = 0xde6de6de;
pub struct Store {
@@ -43,7 +42,17 @@ impl Store {
self.storage.write(FLASH_ADDR + offset, bytes)
}
fn has_magic_bytes(storage: &mut FlashStorage) -> Result<bool, StoreError> {
pub fn write_erase(&mut self, offset: u32, bytes: &mut [u8]) -> Result<(), StoreError> {
log::debug!(
"Erasing and Writing {} bytes at offset 0x{offset:08x}",
bytes.len()
);
self.storage
.erase(FLASH_ADDR + offset, FLASH_ADDR + bytes.len() as u32)?;
self.storage.write(FLASH_ADDR + offset, bytes)
}
pub fn has_magic_bytes(storage: &mut FlashStorage) -> Result<bool, StoreError> {
let mut magic: [u8; 4] = [0, 0, 0, 0];
storage.read(FLASH_ADDR + MAGIC_REGION.offset, &mut magic)?;
log::debug!("Magic bytes are {magic:?}");
@@ -51,9 +60,10 @@ impl Store {
Ok(u32::from_ne_bytes(magic) == FLASH_INITIALIZE_MAGIC)
}
fn initialize_flash(storage: &mut FlashStorage) -> Result<(), StoreError> {
pub fn initialize_flash(storage: &mut FlashStorage) -> Result<(), StoreError> {
storage.erase(FLASH_ADDR, FLASH_ADDR + INITIALIZATION_SIZE as u32)?;
let zeros: [u8; INITIALIZATION_SIZE] = [0; INITIALIZATION_SIZE];
storage.write(FLASH_ADDR, &zeros)?;
storage.write(FLASH_ADDR + MAGIC_REGION.end() as u32, &zeros)?;
storage.write(
FLASH_ADDR + MAGIC_REGION.offset,
&FLASH_INITIALIZE_MAGIC.to_ne_bytes(),