7 #include "common/log.h"
9 #include "drivers/flash.h"
11 #include "fc/firmware_update_common.h"
13 #include "io/asyncfatfs/asyncfatfs.h"
15 #ifdef MSP_FIRMWARE_UPDATE
17 #if !(defined(USE_FLASHFS) || defined(USE_SDCARD))
18 #error No storage backend available
22 static afatfsFilePtr_t metaFile
= NULL
;
24 static void metaFileOpenCallback(afatfsFilePtr_t file
)
30 bool firmwareUpdateMetadataRead(firmwareUpdateMetadata_t
*updateMetadata
)
32 #if defined(USE_SDCARD)
33 if ((afatfs_getFilesystemState() != AFATFS_FILESYSTEM_STATE_READY
)
34 || !afatfs_fopen(FIRMWARE_UPDATE_META_FILENAME
, "r", metaFileOpenCallback
)
35 || (afatfs_freadSync(metaFile
, (uint8_t *)updateMetadata
, sizeof(*updateMetadata
)) != sizeof(*updateMetadata
))) {
39 #elif defined(USE_FLASHFS)
40 flashPartition_t
*flashPartition
= flashPartitionFindByType(FLASH_PARTITION_TYPE_FIRMWARE_UPDATE_META
);
41 if (!flashPartition
) return false;
43 const flashGeometry_t
*flashGeometry
= flashGetGeometry();
44 uint32_t flashAddress
= flashPartition
->startSector
* flashGeometry
->sectorSize
;
46 if (!flashReadBytes(flashAddress
, (uint8_t *)updateMetadata
, sizeof(*updateMetadata
))) {
55 bool firmwareUpdateMetadataWrite(firmwareUpdateMetadata_t
*updateMetadata
)
57 updateMetadata
->magic
= FIRMWARE_UPDATE_METADATA_MAGIC
;
59 #if defined(USE_SDCARD)
60 if ((afatfs_getFilesystemState() != AFATFS_FILESYSTEM_STATE_READY
)
61 || !afatfs_fopen(FIRMWARE_UPDATE_META_FILENAME
, "w+", metaFileOpenCallback
)
62 || (afatfs_fwriteSync(metaFile
, (uint8_t *)updateMetadata
, sizeof(*updateMetadata
)) != sizeof(*updateMetadata
))) {
66 afatfs_fcloseSync(metaFile
);
68 #elif defined(USE_FLASHFS)
69 flashPartition_t
*flashPartition
= flashPartitionFindByType(FLASH_PARTITION_TYPE_FIRMWARE_UPDATE_META
);
70 if (!flashPartition
) return false;
72 const flashGeometry_t
*flashGeometry
= flashGetGeometry();
73 const uint32_t flashPartitionSize
= (flashPartition
->endSector
- flashPartition
->startSector
+ 1) * flashGeometry
->sectorSize
;
74 uint32_t flashAddress
= flashPartition
->startSector
* flashGeometry
->sectorSize
;
76 if (flashPartitionSize
< sizeof(*updateMetadata
)) return false;
78 flashEraseSector(flashAddress
);
79 flashWaitForReady(1000);
80 flashPageProgram(flashAddress
, (uint8_t *)updateMetadata
, sizeof(*updateMetadata
));