diff --git a/libraries/AP_Filesystem/AP_Filesystem.h b/libraries/AP_Filesystem/AP_Filesystem.h index 97a3934551..d980132793 100644 --- a/libraries/AP_Filesystem/AP_Filesystem.h +++ b/libraries/AP_Filesystem/AP_Filesystem.h @@ -60,6 +60,9 @@ public: // return total disk space in bytes, -1 on error int64_t disk_space(const char *path); + + // set modification time on a file + bool set_mtime(const char *filename, const time_t mtime_sec); }; namespace AP { diff --git a/libraries/AP_Filesystem/AP_Filesystem_FATFS.cpp b/libraries/AP_Filesystem/AP_Filesystem_FATFS.cpp index ac481d3011..c5bd41ef5b 100644 --- a/libraries/AP_Filesystem/AP_Filesystem_FATFS.cpp +++ b/libraries/AP_Filesystem/AP_Filesystem_FATFS.cpp @@ -779,6 +779,39 @@ int64_t AP_Filesystem::disk_space(const char *path) return (int64_t)(tot_sect)*512; } +/* + convert unix time_t to FATFS timestamp + */ +static void unix_time_to_fat(time_t epoch, uint16_t &date, uint16_t &time) +{ + struct tm *t = gmtime((time_t *)&epoch); + + /* Pack date and time into a uint32_t variable */ + date = ((uint16_t)(t->tm_year - 80) << 9) + | (((uint16_t)t->tm_mon+1) << 5) + | (((uint16_t)t->tm_mday)); + + time = ((uint16_t)t->tm_hour << 11) + | ((uint16_t)t->tm_min << 5) + | ((uint16_t)t->tm_sec >> 1); +} + +/* + set mtime on a file + */ +bool AP_Filesystem::set_mtime(const char *filename, const time_t mtime_sec) +{ + FILINFO fno; + uint16_t fdate, ftime; + + unix_time_to_fat(mtime_sec, fdate, ftime); + + fno.fdate = fdate; + fno.ftime = ftime; + + return f_utime(filename, (FILINFO *)&fno) == FR_OK; +} + /* convert POSIX errno to text with user message. */ diff --git a/libraries/AP_Filesystem/AP_Filesystem_posix.cpp b/libraries/AP_Filesystem/AP_Filesystem_posix.cpp index a748f7c60c..b3dd3f7165 100644 --- a/libraries/AP_Filesystem/AP_Filesystem_posix.cpp +++ b/libraries/AP_Filesystem/AP_Filesystem_posix.cpp @@ -21,6 +21,7 @@ #if CONFIG_HAL_BOARD == HAL_BOARD_SITL || CONFIG_HAL_BOARD == HAL_BOARD_LINUX #include +#include extern const AP_HAL::HAL& hal; @@ -106,5 +107,17 @@ int64_t AP_Filesystem::disk_space(const char *path) } +/* + set mtime on a file + */ +bool AP_Filesystem::set_mtime(const char *filename, const time_t mtime_sec) +{ + struct utimbuf times {}; + times.actime = mtime_sec; + times.modtime = mtime_sec; + + return utime(filename, ×) == 0; +} + #endif // CONFIG_HAL_BOARD