123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176 |
- #pragma once
- #include <AP_HAL/AP_HAL.h>
- #if defined(STM32F1)
- #define AP_FLASHSTORAGE_MULTI_WRITE 0
- #else
- #define AP_FLASHSTORAGE_MULTI_WRITE 1
- #endif
- class AP_FlashStorage {
- private:
- static const uint8_t block_size = 8;
- static const uint16_t num_blocks = HAL_STORAGE_SIZE / block_size;
- static const uint8_t max_write = 64;
- public:
-
- FUNCTOR_TYPEDEF(FlashWrite, bool, uint8_t , uint32_t , const uint8_t *, uint16_t );
-
- FUNCTOR_TYPEDEF(FlashRead, bool, uint8_t , uint32_t , uint8_t *, uint16_t );
-
-
- FUNCTOR_TYPEDEF(FlashErase, bool, uint8_t );
-
- FUNCTOR_TYPEDEF(FlashEraseOK, bool);
-
-
- AP_FlashStorage(uint8_t *mem_buffer,
- uint32_t flash_sector_size,
- FlashWrite flash_write,
- FlashRead flash_read,
- FlashErase flash_erase,
- FlashEraseOK flash_erase_ok);
-
- bool init(void);
-
- bool re_initialise(void);
-
-
-
- bool switch_full_sector(void);
-
-
- bool write(uint16_t offset, uint16_t length);
-
- static const uint16_t storage_size = block_size * num_blocks;
-
- private:
- uint8_t *mem_buffer;
- const uint32_t flash_sector_size;
- FlashWrite flash_write;
- FlashRead flash_read;
- FlashErase flash_erase;
- FlashEraseOK flash_erase_ok;
- uint8_t current_sector;
- uint32_t write_offset;
- uint32_t reserved_space;
- bool write_error;
-
- #if AP_FLASHSTORAGE_MULTI_WRITE
- static const uint32_t signature = 0x51685B;
- #else
- static const uint32_t signature = 0x51;
- #endif
-
- enum SectorState {
- #if AP_FLASHSTORAGE_MULTI_WRITE
- SECTOR_STATE_AVAILABLE = 0xFF,
- SECTOR_STATE_IN_USE = 0xFE,
- SECTOR_STATE_FULL = 0xFC
- #else
- SECTOR_STATE_AVAILABLE = 0xFFFFFFFF,
- SECTOR_STATE_IN_USE = 0xFFFFFFF1,
- SECTOR_STATE_FULL = 0xFFF2FFF1,
- #endif
- };
-
- struct sector_header {
- #if AP_FLASHSTORAGE_MULTI_WRITE
- uint32_t state:8;
- uint32_t signature:24;
- #else
- uint32_t state:32;
- uint32_t signature:16;
- #endif
- };
- enum BlockState {
- BLOCK_STATE_AVAILABLE = 0x3,
- BLOCK_STATE_WRITING = 0x1,
- BLOCK_STATE_VALID = 0x0
- };
-
-
- struct block_header {
- uint16_t state:2;
- uint16_t block_num:11;
- uint16_t num_blocks_minus_one:3;
- };
-
- static const uint32_t reserve_size = (storage_size / max_write) * (sizeof(block_header) + max_write) + max_write;
-
-
- bool load_sector(uint8_t sector);
-
- bool erase_sector(uint8_t sector);
-
- bool erase_all();
-
- bool write_all();
-
- bool all_zero(uint16_t ofs, uint16_t size);
-
- bool switch_sectors(void);
- };
|