AP_Logger_SITL.cpp 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. /*
  2. backend for SITL emulation of block logging
  3. */
  4. #include "AP_Logger_SITL.h"
  5. #include <AP_HAL/AP_HAL.h>
  6. #if CONFIG_HAL_BOARD == HAL_BOARD_SITL
  7. #include <unistd.h>
  8. #include <stdlib.h>
  9. #include <sys/types.h>
  10. #include <sys/stat.h>
  11. #include <fcntl.h>
  12. #include <assert.h>
  13. #include <stdio.h>
  14. #define DF_PAGE_SIZE 256UL
  15. #define DF_PAGE_PER_SECTOR 16 // 4k sectors
  16. #define DF_NUM_PAGES 65536UL
  17. #define ERASE_TIME_MS 10000
  18. extern const AP_HAL::HAL& hal;
  19. void AP_Logger_SITL::Init()
  20. {
  21. if (flash_fd == 0) {
  22. flash_fd = open(filename, O_RDWR|O_CLOEXEC, 0777);
  23. if (flash_fd == -1) {
  24. flash_fd = open(filename, O_RDWR | O_CREAT | O_CLOEXEC, 0777);
  25. StartErase();
  26. erase_started_ms = 0;
  27. }
  28. if (ftruncate(flash_fd, DF_PAGE_SIZE*uint32_t(DF_NUM_PAGES)) != 0) {
  29. AP_HAL::panic("Failed to create %s", filename);
  30. }
  31. }
  32. df_PageSize = DF_PAGE_SIZE;
  33. df_PagePerSector = DF_PAGE_PER_SECTOR;
  34. df_NumPages = DF_NUM_PAGES;
  35. AP_Logger_Block::Init();
  36. }
  37. bool AP_Logger_SITL::CardInserted(void) const
  38. {
  39. return df_NumPages > 0;
  40. }
  41. void AP_Logger_SITL::PageToBuffer(uint32_t PageAdr)
  42. {
  43. assert(PageAdr>0 && PageAdr <= df_NumPages+1);
  44. if (pread(flash_fd, buffer, DF_PAGE_SIZE, (PageAdr-1)*DF_PAGE_SIZE) != DF_PAGE_SIZE) {
  45. printf("Failed flash read");
  46. }
  47. }
  48. void AP_Logger_SITL::BufferToPage(uint32_t PageAdr)
  49. {
  50. assert(PageAdr>0 && PageAdr <= df_NumPages+1);
  51. if (pwrite(flash_fd, buffer, DF_PAGE_SIZE, (PageAdr-1)*DF_PAGE_SIZE) != DF_PAGE_SIZE) {
  52. printf("Failed flash write");
  53. }
  54. }
  55. void AP_Logger_SITL::SectorErase(uint32_t SectorAdr)
  56. {
  57. uint8_t fill[DF_PAGE_SIZE*DF_PAGE_PER_SECTOR];
  58. memset(fill, 0xFF, sizeof(fill));
  59. if (pwrite(flash_fd, fill, sizeof(fill), SectorAdr*DF_PAGE_PER_SECTOR*DF_PAGE_SIZE) != sizeof(fill)) {
  60. printf("Failed sector erase");
  61. }
  62. }
  63. void AP_Logger_SITL::StartErase()
  64. {
  65. for (uint32_t i=0; i<DF_NUM_PAGES/DF_PAGE_PER_SECTOR; i++) {
  66. SectorErase(i);
  67. }
  68. erase_started_ms = AP_HAL::millis();
  69. }
  70. bool AP_Logger_SITL::InErase()
  71. {
  72. if (erase_started_ms == 0) {
  73. return false;
  74. }
  75. uint32_t now = AP_HAL::millis();
  76. if (now - erase_started_ms < ERASE_TIME_MS) {
  77. return true;
  78. }
  79. erase_started_ms = 0;
  80. return false;
  81. }
  82. #endif // HAL_BOARD_SITL