save a backup of storage file if we have microSD available. This is very handy for diagnostics, and for moving a copy of storage into SITL for testing */
| 126 | SITL for testing |
| 127 | */ |
| 128 | void Storage::_save_backup(void) |
| 129 | { |
| 130 | #ifdef USE_POSIX |
| 131 | // allow for fallback to microSD based storage |
| 132 | // create the backup directory if need be |
| 133 | int ret; |
| 134 | const char* _storage_bak_directory = HAL_STORAGE_BACKUP_FOLDER; |
| 135 | |
| 136 | if (hal.util->was_watchdog_armed()) { |
| 137 | // we are under watchdog reset |
| 138 | // ain't got no time... |
| 139 | return; |
| 140 | } |
| 141 | |
| 142 | EXPECT_DELAY_MS(3000); |
| 143 | |
| 144 | // We want to do this desperately, |
| 145 | // So we keep trying this for a second |
| 146 | uint32_t start_millis = AP_HAL::millis(); |
| 147 | while(!AP::FS().retry_mount() && (AP_HAL::millis() - start_millis) < 1000) { |
| 148 | hal.scheduler->delay(1); |
| 149 | } |
| 150 | |
| 151 | ret = AP::FS().mkdir(_storage_bak_directory); |
| 152 | if (ret == -1 && errno != EEXIST) { |
| 153 | return; |
| 154 | } |
| 155 | |
| 156 | char* fname = nullptr; |
| 157 | unsigned curr_bak = 0; |
| 158 | ret = asprintf(&fname, "%s/last_storage_bak", _storage_bak_directory); |
| 159 | if (fname == nullptr && (ret <= 0)) { |
| 160 | return; |
| 161 | } |
| 162 | int fd = AP::FS().open(fname, O_RDONLY); |
| 163 | if (fd != -1) { |
| 164 | char buf[10]; |
| 165 | memset(buf, 0, sizeof(buf)); |
| 166 | if (AP::FS().read(fd, buf, sizeof(buf)-1) > 0) { |
| 167 | //only record last HAL_STORAGE_BACKUP_COUNT backups |
| 168 | curr_bak = (strtol(buf, NULL, 10) + 1)%HAL_STORAGE_BACKUP_COUNT; |
| 169 | } |
| 170 | AP::FS().close(fd); |
| 171 | } |
| 172 | |
| 173 | fd = AP::FS().open(fname, O_WRONLY|O_CREAT|O_TRUNC); |
| 174 | free(fname); |
| 175 | fname = nullptr; |
| 176 | if (fd != -1) { |
| 177 | char buf[10]; |
| 178 | snprintf(buf, sizeof(buf), "%u\r\n", (unsigned)curr_bak); |
| 179 | const ssize_t to_write = strlen(buf); |
| 180 | const ssize_t written = AP::FS().write(fd, buf, to_write); |
| 181 | AP::FS().close(fd); |
| 182 | if (written < to_write) { |
| 183 | return; |
| 184 | } |
| 185 | } else { |
nothing calls this directly
no test coverage detected