#include "BSP_SDLogger.h" #include "fatfs.h" #include "ulog.h" #include "stdio.h" #include "string.h" uint8_t block_buffer[512] = {0}; size_t block_buffer_index = 0; char file_name[20]; char ulog_buffer[ULOG_MAX_MESSAGE_LENGTH] = {0}; void BSP_SDLogger_ULOG(ulog_level_t level, char *msg) { uint32_t send_length = snprintf(ulog_buffer, ULOG_MAX_MESSAGE_LENGTH, "[%s] %s\n", ulog_level_name(level), msg); BSP_SDLogger_Write(ulog_buffer, send_length); } #include "cmsis_os2.h" // Define the mutex osMutexId_t logger_mutex; // init the logger buffer and the file // filename is generated based on the log number void BSP_SDLogger_Init(int log_number) { // create the file name sprintf(file_name, "log_%d.txt", log_number); // open the file FIL file; FRESULT res = f_open(&file, file_name, FA_CREATE_ALWAYS | FA_WRITE); if (res != FR_OK) { ULOG_ERROR("Failed to open file %s", file_name); } ULOG_SUBSCRIBE(BSP_SDLogger_ULOG, ULOG_DEBUG_LEVEL); // close the file f_close(&file); // Create the mutex logger_mutex = osMutexNew(NULL); } // this fuctions assumes you have the mutex void BSP_SDLogger_Flush_private() { // open the file FIL file; FRESULT res = f_open(&file, file_name, FA_OPEN_APPEND | FA_WRITE ); if (res != FR_OK) { ULOG_ERROR("Failed to open file %s", file_name); } // write the buffer to the file UINT bytes_written; res = f_write(&file, block_buffer, block_buffer_index, &bytes_written); if (res != FR_OK) { ULOG_ERROR("Failed to write to file %s", file_name); } // close the file f_close(&file); // reset the buffer index block_buffer_index = 0; } void BSP_SDLogger_Flush() { // Acquire the mutex osMutexAcquire(logger_mutex, osWaitForever); // flush the buffer BSP_SDLogger_Flush_private(); // Release the mutex osMutexRelease(logger_mutex); } // write data to the logger // data is only written to the buffer! // once the buffer is full, the data is written to the file void BSP_SDLogger_Write(char *data, size_t length) { // Acquire the mutex osMutexAcquire(logger_mutex, osWaitForever); size_t buffer_size = sizeof(block_buffer); size_t remaining_size = buffer_size - block_buffer_index; // if the data is larger than the remaining space in the buffer if (length > remaining_size) { // write the remaining space to the buffer memcpy(&block_buffer[block_buffer_index], data, remaining_size); block_buffer_index += remaining_size; // write the buffer to the file BSP_SDLogger_Flush_private(); // write the remaining data to the buffer memcpy(&block_buffer[block_buffer_index], &data[remaining_size], length - remaining_size); block_buffer_index = length - remaining_size; } else { // write the data to the buffer memcpy(&block_buffer[block_buffer_index], data, length); block_buffer_index += length; } // Release the mutex osMutexRelease(logger_mutex); }