Paparazzi UAS v7.1_unstable
Paparazzi is a free software Unmanned Aircraft System.
Loading...
Searching...
No Matches
sdlog_chibios.c
Go to the documentation of this file.
1/*
2 * Copyright (C) 2013-2015 Gautier Hattenberger, Alexandre Bustico
3 *
4 * This file is part of paparazzi.
5 *
6 * paparazzi is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2, or (at your option)
9 * any later version.
10 *
11 * paparazzi is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with paparazzi; see the file COPYING. If not, write to
18 * the Free Software Foundation, 59 Temple Place - Suite 330,
19 * Boston, MA 02111-1307, USA.
20 */
21
22/*
23 * @file modules/loggers/sdlog_chibios.c
24 * @brief sdlog process with battery monitoring
25 *
26 */
27
28#include <ch.h>
29#include <hal.h>
35#include "mcu_periph/adc.h"
36#include "mcu.h"
37#include "led.h"
38
39// Delay before starting SD log
40#ifndef SDLOG_START_DELAY
41#if INS_EKF2_LOG_INPUTS
42/* the EKF2 only starts once the log is open to log all its inputs, don't wait long */
43#define SDLOG_START_DELAY 2
44#else
45#define SDLOG_START_DELAY 30
46#endif
47#endif
48#if INS_EKF2_LOG_INPUTS && SDLOG_START_DELAY > 5
49PRINT_CONFIG_MSG("INS_EKF2_LOG_INPUTS: the EKF2 only starts after the SD log is open (SDLOG_START_DELAY), set it low")
50#endif
51
52// Auto-flush period (in seconds)
53#ifndef SDLOG_AUTO_FLUSH_PERIOD
54#define SDLOG_AUTO_FLUSH_PERIOD 10
55#endif
56
57// Contiguous storage memory (in Mo)
58#ifndef SDLOG_CONTIGUOUS_STORAGE_MEM
59#define SDLOG_CONTIGUOUS_STORAGE_MEM 50
60#endif
61
62// Flush file on power loss
63#ifndef SDLOG_ENABLE_LOWBAT_FLUSH
64#define SDLOG_ENABLE_LOWBAT_FLUSH TRUE
65#endif
66
67
68#if (!defined USE_ADC_WATCHDOG) || (USE_ADC_WATCHDOG == 0)
69#error sdlog_chibios need USE_ADC_WATCHDOG in order to properly close files when power is unplugged
70#endif
71
72static const char PPRZ_LOG_NAME[] = "pprzlog_";
73static const char PPRZ_LOG_DIR[] = "PPRZ";
74
77#ifndef SDLOG_CONF
78#define SDLOG_CONF TRUE
79#endif
80#if SDLOG_CONF
81#include "generated/aircraft_conf.h"
82#endif
85// Error of the start step that failed, the storage status can be changed later by other calls
87static const char *sdlog_start_step = "";
88static volatile uint8_t sdlog_start_fatfs = 0;
89// Every switch into error is counted with its cause by the logger thread (it checks every second),
90// so the GCS report (every LOGGER_STATUS) misses none and gives the cause of that moment
91static volatile uint32_t sdlog_error_events = 0;
93
94/*
95 * Start log thread
96 */
97static IN_DMA_SECTION(THD_WORKING_AREA(wa_thd_startlog, 4096));
98static __attribute__((noreturn)) void thd_startlog(void *arg);
99
100bool sdOk = false;
101
103
105
106#if FLIGHTRECORDER_SDLOG
107static const char FLIGHTRECORDER_LOG_NAME[] = "fr_";
108static const char FR_LOG_DIR[] = "FLIGHT_RECORDER";
109FileDes flightRecorderLogFile = -1;
110#endif
111
114static enum {
119
123static char NO_FILE_NAME[] = "none";
124
125#if PREFLIGHT_CHECKS
126/* Preflight checks */
128static struct preflight_check_t sdlog_pfc;
129
130static void sdlog_preflight(struct preflight_result_t *result) {
132 const char *cause = (chibios_sdlog_status == SDLOG_STOPPED) ? "not started yet" :
134#ifdef SDLOG_PREFLIGHT_ERROR
135 preflight_error(result, "SD log not running: %s", cause);
136#else
137 preflight_warning(result, "SD log not running: %s", cause);
138#endif
139 } else {
140 preflight_success(result, "SDLogger running");
141 }
142}
143#endif // PREFLIGHT_CHECKS
144
145#if PERIODIC_TELEMETRY
152static void sdlog_report_status(struct transport_tx *trans, struct link_device *dev)
153{
154 static uint32_t reported_errors = 0;
155 static bool start_reported = false;
156 char msg[120];
157 const uint32_t errors = sdlog_error_events;
158 if (errors != reported_errors) {
159 // went into error (at the start or later) since the last report
160 reported_errors = errors;
161 const SdioError start_error = sdlog_start_error;
162 if (start_error != SDLOG_OK && sdlog_start_fatfs != 0) {
163 // the start failed: the failing step and its FatFS result tell why the card could not be used
164 chsnprintf(msg, sizeof(msg), "SD log error: %s (%s, FatFS %d)", sdlog_error_string(start_error),
166 } else if (start_error != SDLOG_OK) {
167 chsnprintf(msg, sizeof(msg), "SD log error: %s (%s)", sdlog_error_string(start_error), sdlog_start_step);
168 } else {
169 chsnprintf(msg, sizeof(msg), "SD log error: %s", sdlog_error_string(sdlog_error_cause));
170 }
171 } else if (!start_reported && chibios_sdlog_status != SDLOG_STOPPED) {
172 // started: only a configuration that could not be written is reported, a normal start is not
173 start_reported = true;
174 if (sdlog_conf_error == SDLOG_OK) {
175 return;
176 }
177 chsnprintf(msg, sizeof(msg), "SD log: configuration not written: %s", sdlog_error_string(sdlog_conf_error));
178 } else {
179 return;
180 }
181 pprz_msg_send_INFO_MSG(trans, dev, AC_ID, strlen(msg), msg);
182}
183
184static void send_sdlog_status(struct transport_tx *trans, struct link_device *dev)
185{
186 sdlog_report_status(trans, dev);
190 uint8_t size = strlen(chibios_sdlog_filenames);
191 char *filenames = chibios_sdlog_filenames;
192 if (size == 0) {
193 // when no file opened
194 filenames = NO_FILE_NAME;
195 size = strlen(filenames);
196 }
197 pprz_msg_send_LOGGER_STATUS(trans, dev, AC_ID, &status, &errno, &used, size, filenames);
198}
199#endif
200
201
202// Functions for the generic device API
203static int sdlog_check_free_space(struct chibios_sdlog *p __attribute__((unused)), long *fd, uint16_t len)
204{
205 SdLogBuffer *sdb;
206 SdioError status = sdLogAllocSDB(&sdb, len);
207 if (status != SDLOG_OK) {
208 return 0;
209 } else {
210 *fd = (long) sdb;
211 return 1;
212 }
213}
214
215static void sdlog_transmit(struct chibios_sdlog *p __attribute__((unused)), long fd, uint8_t byte)
216{
217 SdLogBuffer *sdb = (SdLogBuffer *) fd;
218 uint8_t *data = (uint8_t *) sdLogGetBufferFromSDB(sdb);
219 *data = byte;
220 sdLogSeekBufferFromSDB(sdb, 1);
221}
222
223static void sdlog_transmit_buffer(struct chibios_sdlog *p __attribute__((unused)), long fd, uint8_t *data, uint16_t len)
224{
225 SdLogBuffer *sdb = (SdLogBuffer *) fd;
226 memcpy(sdLogGetBufferFromSDB(sdb), data, len);
227 sdLogSeekBufferFromSDB(sdb, len);
228}
229
230static void sdlog_send(struct chibios_sdlog *p, long fd)
231{
232 SdLogBuffer *sdb = (SdLogBuffer *) fd;
233 sdLogWriteSDB(*(p->file), sdb);
234}
235
236static int null_function(struct chibios_sdlog *p __attribute__((unused))) { return 0; }
237static uint8_t null_byte_function(struct chibios_sdlog *p __attribute__((unused))) { return 0; }
238
239void chibios_sdlog_init(struct chibios_sdlog *sdlog, FileDes *file)
240{
241 // Store file descriptor
242 sdlog->file = file;
243 // Configure generic device
244 sdlog->device.periph = (void *)(sdlog);
245 sdlog->device.check_free_space = (check_free_space_t) sdlog_check_free_space;
246 sdlog->device.put_byte = (put_byte_t) sdlog_transmit;
247 sdlog->device.put_buffer = (put_buffer_t) sdlog_transmit_buffer;
248 sdlog->device.send_message = (send_message_t) sdlog_send;
249 sdlog->device.char_available = (char_available_t) null_function; // write only
250 sdlog->device.get_byte = (get_byte_t) null_byte_function; // write only
251
252}
253
255{
257#if PERIODIC_TELEMETRY
259#endif
260
261#if PREFLIGHT_CHECKS
262 preflight_check_register(&sdlog_pfc, sdlog_preflight);
263#endif
264
265 // Start polling on USB
267
268 // Start log thread
269 chThdCreateStatic(wa_thd_startlog, sizeof(wa_thd_startlog),
270 NORMALPRIO + 2, thd_startlog, NULL);
271}
272
273
274void sdlog_chibios_finish(const bool flush)
275{
276 if (pprzLogFile != -1) {
277 // if a FF_FS_REENTRANT is true, we can umount fs without closing
278 // file, fatfs lock will assure that umount is done after a write,
279 // and umount will close all open files cleanly. Thats the fatest
280 // way to umount cleanly filesystem.
281 //
282 // if FF_FS_REENTRANT is false,
283 // we have to flush and close files before unmounting filesystem
284#if FF_FS_REENTRANT == 0
285 sdLogCloseAllLogs(flush);
286#else
287 (void) flush;
288#endif
289
290 sdLogFinish();
291 pprzLogFile = -1;
292#if FLIGHTRECORDER_SDLOG
293 flightRecorderLogFile = -1;
294#endif
295 }
297}
298
299#if defined(SDLOG_BAT_ADC) && defined(SDLOG_BAT_CHAN)
300/*
301 * Bat survey thread
302 */
303#if SDLOG_ENABLE_LOWBAT_FLUSH
304static THD_WORKING_AREA(wa_thd_bat_survey, 1024);
305static __attribute__((noreturn)) void thd_bat_survey(void *arg);
306static void powerOutageIsr(void);
307event_source_t powerOutageSource;
308event_listener_t powerOutageListener;
309
310#define DefaultAdcOfVoltage(voltage) ((uint32_t) (voltage/(DefaultVoltageOfAdc(1))))
311static const uint16_t V_ALERT = DefaultAdcOfVoltage(5.5f);
312
313
314/*
315 powerOutageIsr is called within a lock zone from an isr, so no lock/unlock is needed
316*/
317static void powerOutageIsr(void)
318{
319 chEvtBroadcastI(&powerOutageSource);
320}
321
322static void thd_bat_survey(void *arg)
323{
324 (void)arg;
325 chRegSetThreadName("battery survey");
326 chEvtRegister(&powerOutageSource, &powerOutageListener, 1);
327 chThdSleepMilliseconds(2000);
328
329 register_adc_watchdog(&SDLOG_BAT_ADC, SDLOG_BAT_CHAN, V_ALERT, &powerOutageIsr);
330
331 chEvtWaitOne(EVENT_MASK(1));
332 // Only try to energy save is it is really a problem and not powered through USB
333 if (palReadPad(SDLOG_USB_VBUS_PORT, SDLOG_USB_VBUS_PIN) == PAL_LOW) {
334 // disable all required periph to save energy and maximize chance to flush files
335 // to mass storage and avoid infamous dirty bit on filesystem
337 }
338
339 // in case of powerloss, we should go fast and avoid to flush ram buffer
341
342 // Only put to deep sleep in case there is no power on the USB
343 if (palReadPad(SDLOG_USB_VBUS_PORT, SDLOG_USB_VBUS_PIN) == PAL_LOW) {
345 }
346 chThdExit(0);
347 while (true); // never goes here, only to avoid compiler warning: 'noreturn' function does return
348}
349#endif // SDLOG_ENABLE_LOWBAT_FLUSH
350#endif
351
353static void sdlog_start_failed(const char *step, SdioError err)
354{
355 if (sdOk) {
358 sdlog_start_error = err;
359 sdlog_error_cause = err;
360 }
361 sdOk = false;
362}
363
364static void thd_startlog(void *arg)
365{
366 (void) arg;
367 chRegSetThreadName("start log");
368 char tmpFilename[32];
369
370 // Wait before starting the log if needed
371 chThdSleepSeconds(SDLOG_START_DELAY);
372 // Check if we are already in USB Storage mode
373 if (usbStorageIsItRunning()) {
374 chThdSleepSeconds(20000); // stuck here for hours FIXME stop the thread ?
375 }
376
377 // Init sdlog struct
379
380 // Check for init errors
381 sdOk = true;
382
383 SdioError err = sdLogInit(NULL);
384 if (err != SDLOG_OK) {
385 sdlog_start_failed("init", err);
386 } else {
388 err = sdLogOpenLog(&pprzLogFile, PPRZ_LOG_DIR,
390 SDLOG_CONTIGUOUS_STORAGE_MEM, LOG_PREALLOCATION_DISABLED, tmpFilename, sizeof(tmpFilename));
391 if (err != SDLOG_OK) {
392 sdlog_start_failed("open log", err);
393 }
395#if FLIGHTRECORDER_SDLOG
396 removeEmptyLogs(FR_LOG_DIR, FLIGHTRECORDER_LOG_NAME, 50);
397 err = sdLogOpenLog(&flightRecorderLogFile, FR_LOG_DIR, FLIGHTRECORDER_LOG_NAME,
399 SDLOG_CONTIGUOUS_STORAGE_MEM, LOG_PREALLOCATION_DISABLED, tmpFilename, sizeof(tmpFilename));
400 if (err != SDLOG_OK) {
401 sdlog_start_failed("open flight recorder", err);
402 }
404#endif
405#if SDLOG_CONF
406 // once per configuration, a failure does not stop the logging
407 sdlog_conf_error = sdLogWriteFile(PPRZ_LOG_DIR, AIRCRAFT_CONF_NAME, aircraft_conf_gz, sizeof(aircraft_conf_gz));
408#endif
409 }
410
411 if (sdOk) {
412#if defined(SDLOG_BAT_ADC) && defined(SDLOG_BAT_CHAN) && SDLOG_ENABLE_LOWBAT_FLUSH
413 // Create Battery Survey Thread with event
414 chEvtObjectInit(&powerOutageSource);
415 chThdCreateStatic(wa_thd_bat_survey, sizeof(wa_thd_bat_survey),
416 NORMALPRIO + 2, thd_bat_survey, NULL);
417#endif
418
420 } else {
423 }
424
425 bool in_error = !sdOk;
426 while (true) {
427#ifdef SDLOG_LED
428 LED_TOGGLE(SDLOG_LED);
429#endif
430 // Blink faster if init has errors
431 chThdSleepMilliseconds(sdOk == true ? 1000 : 200);
432 const SdioError storage = sdLogGetStorageStatus();
433 if (storage != SDLOG_OK) {
434 if (!in_error) {
435 // a new error: keep its cause for the report
436 sdlog_error_cause = storage;
438 }
439 in_error = true;
441 sdOk = false;
442 } else {
443 // running again: a later error is not the start error anymore
444 in_error = false;
447 sdOk = true;
448 }
449
450
451 }
452}
453
454
456 uint8_t ac_id = pprzlink_get_DL_INFO_MSG_UP_ac_id(buf);
457 if(ac_id != AC_ID && ac_id != 0xFF) {
458 return;
459 }
460 uint8_t fd = pprzlink_get_DL_INFO_MSG_UP_fd(buf);
462 uint8_t len = pprzlink_get_INFO_MSG_UP_msg_length(buf);
463 uint8_t* msg = (uint8_t*) pprzlink_get_DL_INFO_MSG_UP_msg(buf);
464 sdLogWriteRaw(pprzLogFile, msg, len);
466 }
467}
468
arch independent ADC (Analog to Digital Converter) API
#define SDLOG_BAT_ADC
Definition board.h:523
#define SDLOG_USB_VBUS_PIN
Definition board.h:528
#define SDLOG_USB_VBUS_PORT
Definition board.h:527
#define SDLOG_BAT_CHAN
Definition board.h:524
static uint8_t status
#define LED_TOGGLE(i)
Definition led_hw.h:53
static THD_WORKING_AREA(wa_thd_spi1, SPI_THREAD_STACK_SIZE)
static struct uart_periph * dev
void chsnprintf(char *buffer, size_t size, const char *fmt,...)
Definition printf.c:377
void mcu_reboot(enum reboot_state_t reboot_state)
Reboot the MCU.
Definition mcu_arch.c:208
void mcu_energy_save(void)
Save energy for performing operations on shutdown Used for example to shutdown SD-card logging.
Definition mcu_arch.c:232
@ MCU_REBOOT_POWEROFF
Poweroff the device.
Definition mcu.h:45
static float p[2][2]
PRINT_CONFIG_MSG("USE_INS_NAV_INIT defaulting to TRUE")
arch independent LED (Light Emitting Diodes) API
static FILE * pprzLogFile
uint8_t step
Definition max7456.c:140
Arch independent mcu ( Micro Controller Unit ) utilities.
void preflight_error(struct preflight_result_t *result, const char *fmt,...)
Register a preflight error used inside the preflight checking functions.
void preflight_success(struct preflight_result_t *result, const char *fmt,...)
Register a preflight success used inside the preflight checking functions.
void preflight_warning(struct preflight_result_t *result, const char *fmt,...)
Register a preflight warning used inside the preflight checking functions.
void preflight_check_register(struct preflight_check_t *check, preflight_check_f func)
Register a preflight check and add it to the linked list.
Mini printf-like functionality.
#define IN_DMA_SECTION(var)
Definition ram_arch.h:87
SdioError sdLogFinish(void)
unmount filesystem
Definition sdLog.c:307
SdioError removeEmptyLogs(const char *directoryName, const char *prefix, const size_t sizeConsideredEmpty)
remove spurious log file left on sd
Definition sdLog.c:837
SdioError sdLogInit(uint32_t *freeSpaceInKo)
initialise sdLog
Definition sdLog.c:245
uint8_t sdLogGetFatfsResult(void)
Definition sdLog.c:227
SdioError sdLogWriteFile(const char *directoryName, const char *fileName, const uint8_t *data, const size_t len)
write a whole file, if it does not exist yet
Definition sdLog.c:882
struct _SdLogBuffer SdLogBuffer
Definition sdLog.h:127
int8_t FileDes
Definition sdLog.h:128
#define LOG_APPEND_TAG_AT_CLOSE_DISABLED
Definition sdLog.h:105
SdioError
Definition sdLog.h:111
@ SDLOG_OK
Definition sdLog.h:112
#define LOG_PREALLOCATION_DISABLED
Definition sdLog.h:103
static void sdlog_send(struct chibios_sdlog *p, long fd)
static int null_function(struct chibios_sdlog *p)
static enum @167037365353014241033154007315025330016177123070 chibios_sdlog_status
sdlog status
static volatile uint8_t sdlog_start_fatfs
static volatile SdioError sdlog_conf_error
Result of writing the configuration, reported to the GCS.
static void send_sdlog_status(struct transport_tx *trans, struct link_device *dev)
static volatile SdioError sdlog_start_error
static int sdlog_check_free_space(struct chibios_sdlog *p, long *fd, uint16_t len)
void logger_log_msg_up(uint8_t *buf)
static volatile uint32_t sdlog_error_events
static void thd_startlog(void *arg)
#define SDLOG_AUTO_FLUSH_PERIOD
static void sdlog_report_status(struct transport_tx *trans, struct link_device *dev)
Tell the GCS in words why the logger does not run (no SD card, card full, ...): at the start and ever...
static const char PPRZ_LOG_DIR[]
static volatile SdioError sdlog_error_cause
void sdlog_chibios_finish(const bool flush)
static void sdlog_transmit(struct chibios_sdlog *p, long fd, uint8_t byte)
static void sdlog_start_failed(const char *step, SdioError err)
Keep why the start failed (the first failing step only).
#define SDLOG_START_DELAY
@ SDLOG_STOPPED
@ SDLOG_ERROR
@ SDLOG_RUNNING
static char NO_FILE_NAME[]
static const char PPRZ_LOG_NAME[]
#define SDLOG_CONTIGUOUS_STORAGE_MEM
void chibios_sdlog_init(struct chibios_sdlog *sdlog, FileDes *file)
init chibios_sdlog structure
bool sdOk
static char chibios_sdlog_filenames[68]
sdlog filenames
static uint8_t null_byte_function(struct chibios_sdlog *p)
static void sdlog_transmit_buffer(struct chibios_sdlog *p, long fd, uint8_t *data, uint16_t len)
void sdlog_chibios_init(void)
static const char * sdlog_start_step
#define DEST_INFO_MSG_PPRZLOG
FileDes * file
#define DEST_INFO_MSG_ALL
struct link_device device
Generic device interface.
static const char * sdlog_error_string(SdioError error)
Human readable cause of a logger error, for the messages to the GCS.
chibios_sdlog structure
SdioError sdLogWriteByte(const FileDes fd, const uint8_t value)
SdioError sdLogGetStorageStatus(void)
SdioError sdLogWriteRaw(const FileDes fd, const uint8_t *buffer, const size_t len)
size_t sdLogGetNbBytesWrittenToStorage(void)
int fd
Definition serial.c:26
int16_t register_periodic_telemetry(struct periodic_telemetry *_pt, uint16_t _id, telemetry_cb _cb)
Register a telemetry callback function.
Definition telemetry.c:51
Periodic telemetry system header (includes downlink utility and generated code).
#define DefaultPeriodic
Set default periodic telemetry.
Definition telemetry.h:66
Dynamic memory allocation based on TLSF library.
void usbStorageStartPolling(void)
Definition usbStorage.c:76
bool usbStorageIsItRunning(void)
Definition usbStorage.c:163
unsigned short uint16_t
Typedef defining 16 bit unsigned short type.
unsigned int uint32_t
Typedef defining 32 bit unsigned int type.
unsigned char uint8_t
Typedef defining 8 bit unsigned char type.