Set blackbox file handler to NULL after closing file
[inav.git] / src / main / fc / firmware_update_common.c
blob2d3370b78f729c72f9d200b1a91155489c0f2be5
2 #include <stdbool.h>
3 #include <stdint.h>
5 #include "platform.h"
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
19 #endif
21 #ifdef USE_SDCARD
22 static afatfsFilePtr_t metaFile = NULL;
24 static void metaFileOpenCallback(afatfsFilePtr_t file)
26 metaFile = file;
28 #endif
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))) {
36 return false;
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))) {
47 return false;
50 #endif
52 return true;
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))) {
63 return false;
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));
82 #endif
84 return true;
87 #endif