working Communication, Database, Logger (w/out CDC)

This commit is contained in:
2026-08-18 19:53:02 +03:00
parent 880be76f0e
commit 844f53a12b
58 changed files with 11196 additions and 129 deletions
+28
View File
@@ -0,0 +1,28 @@
add_library(KPI_Rover STATIC
KPIRover.c
)
target_include_directories(KPI_Rover PRIVATE
${CMAKE_CURRENT_SOURCE_DIR}
)
set(KPIROVER_COMPONENTS
Communication
Database
Logger
#Storage
)
foreach(comp ${KPIROVER_COMPONENTS})
add_subdirectory(${comp})
target_link_libraries(KPI_Rover PRIVATE
KPI_Rover_${comp}
KPI_Rover_${comp}_H
)
endforeach()
add_library(KPI_Rover_H INTERFACE)
target_include_directories(KPI_Rover_H INTERFACE
${CMAKE_CURRENT_SOURCE_DIR}
)
+32
View File
@@ -0,0 +1,32 @@
set(KPI_Rover_Communication_Inc
${CMAKE_CURRENT_SOURCE_DIR}
)
set(KPI_Rover_Communication_Src
${CMAKE_CURRENT_SOURCE_DIR}/hwUSART3.c
${CMAKE_CURRENT_SOURCE_DIR}/crc16.c
${CMAKE_CURRENT_SOURCE_DIR}/drvUart.c
${CMAKE_CURRENT_SOURCE_DIR}/UARTTransport.c
${CMAKE_CURRENT_SOURCE_DIR}/ProtocolHandler.c
)
add_library(KPI_Rover_Communication STATIC)
target_include_directories(KPI_Rover_Communication PRIVATE
${KPI_Rover_Communication_Inc}
)
target_sources(KPI_Rover_Communication PRIVATE
${KPI_Rover_Communication_Src}
)
target_link_libraries(KPI_Rover_Communication PRIVATE
FREERTOS_H
HAL_H
KPI_Rover_Database_H
)
add_library(KPI_Rover_Communication_H INTERFACE)
target_include_directories(KPI_Rover_Communication_H INTERFACE
${CMAKE_CURRENT_SOURCE_DIR}
)
+204
View File
@@ -0,0 +1,204 @@
#include "UARTTransport.h"
#include <string.h>
#include <stdint.h>
#include "cmsis_os2.h"
#include "ulDatabase.h"
#define SEND_BUFFER_SIZE 64
#define RECV_BUFFER_SIZE 32
#define LEN(x) ( sizeof(x) / sizeof((x)[0]) )
static uint8_t sendBuffer[SEND_BUFFER_SIZE];
static uint8_t recvBuffer[RECV_BUFFER_SIZE];
static uint8_t recvSize;
static osThreadAttr_t ta = {
.stack_size = 256 * 4
};
static int32_t switch_endianness_int32(const uint8_t * const address)
{
return (int32_t) ((((uint32_t)address[0]) << 24) + (((uint32_t)address[1]) << 16) + (((uint32_t)address[2]) << 8) + ((uint32_t)address[3]));
}
static void dispatch_not_a_command(void) {}
static void dispatch_get_api_version(void)
{
sendBuffer[0] = 0x01;
sendBuffer[1] = 0x01;
UARTTransport_send(sendBuffer, 2);
}
static void dispatch_set_motor_speed(void)
{
sendBuffer[0] = 0x02;
sendBuffer[1] = 0x00;
static int32_t target_value;
target_value = switch_endianness_int32(&(recvBuffer[2])); // big (network) to little (host)
target_value /= 100;
switch (recvBuffer[1]) {
case 0:
ulDatabase_setInt32(MOTOR_FL_SETPOINT, target_value);
break;
case 1:
ulDatabase_setInt32(MOTOR_RL_SETPOINT, target_value);
break;
case 2:
ulDatabase_setInt32(MOTOR_FR_SETPOINT, target_value);
break;
case 3:
ulDatabase_setInt32(MOTOR_RR_SETPOINT, target_value);
break;
default:
sendBuffer[1] = 0x01;
break;
}
UARTTransport_send(sendBuffer, 2);
}
static void dispatch_set_all_motors_speed(void)
{
static int32_t target_value_fl, target_value_rl, target_value_fr, target_value_rr;
target_value_fl = switch_endianness_int32(&(recvBuffer[1]));
target_value_rl = switch_endianness_int32(&(recvBuffer[5]));
target_value_fr = switch_endianness_int32(&(recvBuffer[9]));
target_value_rr = switch_endianness_int32(&(recvBuffer[13]));
ulDatabase_setInt32(MOTOR_FL_SETPOINT, target_value_fl / 100);
ulDatabase_setInt32(MOTOR_RL_SETPOINT, target_value_rl / 100);
ulDatabase_setInt32(MOTOR_FR_SETPOINT, target_value_fr / 100);
ulDatabase_setInt32(MOTOR_RR_SETPOINT, target_value_rr / 100);
sendBuffer[0] = 0x03;
sendBuffer[1] = 0x00;
UARTTransport_send(sendBuffer, 2);
}
static void dispatch_get_encoder(void)
{
sendBuffer[0] = 0x04;
static int32_t source_value;
switch (recvBuffer[1]) {
case 0:
ulDatabase_getInt32(MOTOR_FL_RPM, &source_value);
break;
case 1:
ulDatabase_getInt32(MOTOR_RL_RPM, &source_value);
break;
case 2:
ulDatabase_getInt32(MOTOR_FR_RPM, &source_value);
break;
case 3:
ulDatabase_getInt32(MOTOR_RR_RPM, &source_value);
break;
default:
// failure is not an option in the protocol
break;
}
source_value = switch_endianness_int32((uint8_t *) &source_value); // little (host) to big (network)
memcpy(&(sendBuffer[1]), &source_value, sizeof(source_value));
UARTTransport_send(sendBuffer, 5);
}
static void dispatch_get_all_encoders(void)
{
static int32_t source_value_fl, source_value_rl, source_value_fr, source_value_rr;
ulDatabase_getInt32(MOTOR_FL_RPM, &source_value_fl);
ulDatabase_getInt32(MOTOR_RL_RPM, &source_value_rl);
ulDatabase_getInt32(MOTOR_FR_RPM, &source_value_fr);
ulDatabase_getInt32(MOTOR_RR_RPM, &source_value_rr);
source_value_fl = switch_endianness_int32((uint8_t *) &source_value_fl);
source_value_rl = switch_endianness_int32((uint8_t *) &source_value_rl);
source_value_fr = switch_endianness_int32((uint8_t *) &source_value_fr);
source_value_rr = switch_endianness_int32((uint8_t *) &source_value_rr);
sendBuffer[0] = 0x05;
memcpy(&(sendBuffer[1]), &source_value_fl, sizeof(source_value_fl));
memcpy(&(sendBuffer[5]), &source_value_rl, sizeof(source_value_rl));
memcpy(&(sendBuffer[9]), &source_value_fr, sizeof(source_value_fr));
memcpy(&(sendBuffer[13]), &source_value_rr, sizeof(source_value_rr));
UARTTransport_send(sendBuffer, 17);
}
static void dispatch_get_imu(void)
{
sendBuffer[0] = 0x06;
ulDatabase_getFloat(IMU_ACCEL_X, (float *) (sendBuffer + 1));
ulDatabase_getFloat(IMU_ACCEL_Y, (float *) (sendBuffer + 5));
ulDatabase_getFloat(IMU_ACCEL_Z, (float *) (sendBuffer + 9));
ulDatabase_getFloat(IMU_GYRO_X, (float *) (sendBuffer + 13));
ulDatabase_getFloat(IMU_GYRO_Y, (float *) (sendBuffer + 17));
ulDatabase_getFloat(IMU_GYRO_Z, (float *) (sendBuffer + 21));
ulDatabase_getFloat(IMU_MAG_X, (float *) (sendBuffer + 25));
ulDatabase_getFloat(IMU_MAG_Y, (float *) (sendBuffer + 29));
ulDatabase_getFloat(IMU_MAG_Z, (float *) (sendBuffer + 33));
ulDatabase_getFloat(IMU_QUAT_X, (float *) (sendBuffer + 37));
ulDatabase_getFloat(IMU_QUAT_X, (float *) (sendBuffer + 41));
ulDatabase_getFloat(IMU_QUAT_Y, (float *) (sendBuffer + 45));
ulDatabase_getFloat(IMU_QUAT_Z, (float *) (sendBuffer + 49));
UARTTransport_send(sendBuffer, 53);
}
static void ProtocolHandler_emergencyStop(void)
{
ulDatabase_setInt32(MOTOR_FL_SETPOINT, 0);
ulDatabase_setInt32(MOTOR_RL_SETPOINT, 0);
ulDatabase_setInt32(MOTOR_FR_SETPOINT, 0);
ulDatabase_setInt32(MOTOR_RR_SETPOINT, 0);
}
static const void (*dispatch_table[])(void) = {
(const void (*)(void)) dispatch_not_a_command,
(const void (*)(void)) dispatch_get_api_version,
(const void (*)(void)) dispatch_set_motor_speed,
(const void (*)(void)) dispatch_set_all_motors_speed,
(const void (*)(void)) dispatch_get_encoder,
(const void (*)(void)) dispatch_get_all_encoders,
(const void (*)(void)) dispatch_get_imu,
};
void ProtocolHandler_processTask(void *d)
{
(void) d;
UARTTransport_init();
for ( ; ; ) {
if (!UARTTransport_receive(recvBuffer, &recvSize))
{
ProtocolHandler_emergencyStop();
continue;
}
if (recvBuffer[0] >= LEN(dispatch_table))
continue;
dispatch_table[recvBuffer[0]]();
}
}
void ProtocolHandler_init(void)
{
(void) osThreadNew(ProtocolHandler_processTask, NULL, &ta);
}
@@ -0,0 +1,8 @@
#ifndef __PROTOCOL_HANDLER_H
#define __PROTOCOL_HANDLER_H
void ProtocolHandler_init(void);
#endif /* __PROTOCOL_HANDLER_H */
+113
View File
@@ -0,0 +1,113 @@
#include <string.h>
#include "UARTTransport.h"
#include "cmsis_os2.h"
#include "drvUart.h"
#define FLAG_TRANSMIT_FINISH 0x1
static osMessageQueueId_t sendQ;
static osMessageQueueId_t recvQ;
static osEventFlagsId_t ef;
static osThreadAttr_t ta = {
.stack_size = 64 * 4
};
void UARTTransport_sendTask(void *d)
{
(void) d;
static uint8_t sendMessageBuffer[UART_TRANSPORT_SEND_BUFFER_SIZE];
for ( ; ; ) {
if (osMessageQueueGet(sendQ, sendMessageBuffer, NULL, osWaitForever))
continue;
drvUart_send(sendMessageBuffer);
osEventFlagsWait(ef, FLAG_TRANSMIT_FINISH, 0, osWaitForever);
}
}
void UARTTransport_onRxCplt(const uint8_t * const buffer)
{
(void) osMessageQueuePut(recvQ, buffer, 0, 0);
}
void UARTTransport_onTxCplt(void)
{
(void) osEventFlagsSet(ef, FLAG_TRANSMIT_FINISH);
}
void UARTTransport_init(void)
{
(void) drvUart_set_on_rx_cplt(UARTTransport_onRxCplt);
(void) drvUart_set_on_tx_cplt(UARTTransport_onTxCplt);
(void) drvUart_start();
ef = osEventFlagsNew(NULL);
sendQ = osMessageQueueNew(16, UART_TRANSPORT_SEND_BUFFER_SIZE, NULL);
recvQ = osMessageQueueNew(16, UART_TRANSPORT_RECV_BUFFER_SIZE, NULL);
(void) osThreadNew(UARTTransport_sendTask, NULL, &ta);
}
bool UARTTransport_receive(uint8_t * const buf, uint8_t * const size)
{
static uint8_t recvBuffer[UART_TRANSPORT_RECV_BUFFER_SIZE];
//for ( ; osMessageQueueGet(recvQ, recvBuffer, NULL, 50) != osOK; drvUart_restart_receiver());
if (osMessageQueueGet(recvQ, recvBuffer, NULL, 50) != osOK)
{
drvUart_restart_receiver();
return false;
}
else
{
*size = recvBuffer[0] - 1;
memcpy(buf, recvBuffer + 1, *size);
return true;
}
/*
static osStatus_t r;
for ( ; ; )
{
r = osMessageQueueGet(recvQ, recvBuffer, NULL, 100);
if (r == osOK)
{
break;
}
else
{
drvUart_restart_receiver();
}
}
*/
/*
*size = recvBuffer[0] - 1;
memcpy(buf, recvBuffer + 1, *size);
return true;
*/
}
void UARTTransport_send(const uint8_t * const buf, const uint8_t size)
{
static uint8_t sendEncodingBuffer[UART_TRANSPORT_SEND_BUFFER_SIZE];
sendEncodingBuffer[0] = size + 1;
memcpy(sendEncodingBuffer + 1, buf, size);
(void) osMessageQueuePut(sendQ, sendEncodingBuffer, 0, osWaitForever);
}
+14
View File
@@ -0,0 +1,14 @@
#ifndef __UART_TRANSPORT_H
#define __UART_TRANSPORT_H
#include <stdint.h>
#include <stdbool.h>
#define UART_TRANSPORT_RECV_BUFFER_SIZE 32
#define UART_TRANSPORT_SEND_BUFFER_SIZE 64
void UARTTransport_init(void);
bool UARTTransport_receive(uint8_t * const buf, uint8_t * const size);
void UARTTransport_send(const uint8_t * const buf, const uint8_t size);
#endif /* __UART_TRANSPORT_H */
+27
View File
@@ -0,0 +1,27 @@
#include "crc16.h"
uint16_t crc16(uint8_t const *data, size_t size)
{
uint16_t crc = 0xFFFF;
char i = 0;
while(size--)
{
crc ^= (*data++);
for(i = 0; i < 8; i++)
{
if( crc & 1 )
{
crc >>= 1;
crc ^= 0xA001;
}
else
{
crc >>= 1;
}
}
}
return crc;
}
+9
View File
@@ -0,0 +1,9 @@
#ifndef COMMUNICATION_CRC16_H_
#define COMMUNICATION_CRC16_H_
#include <stdint.h>
#include <stddef.h>
uint16_t crc16(uint8_t const *data, size_t size);
#endif /* COMMUNICATION_CRC16_H_ */
+202
View File
@@ -0,0 +1,202 @@
#include "main.h"
#include <stdbool.h>
#include <string.h>
#include "hwUSART3.h"
#include "drvUart.h"
#include "crc16.h"
extern UART_HandleTypeDef huart3;
static uint8_t *activeReceiveBuffer;
static uint8_t *sideReceiveBuffer;
static uint8_t receiveBuffer1[DRV_UART_RECEIVE_BUFFER_SIZE];
static uint8_t receiveBuffer2[DRV_UART_RECEIVE_BUFFER_SIZE];
static uint8_t transmitBuffer[DRV_UART_TRANSMIT_BUFFER_SIZE];
static void (*on_rx_cplt)(const uint8_t * const buffer);
static void (*on_tx_cplt)(void);
#if 0
extern DMA_HandleTypeDef hdma_usart3_rx;
extern DMA_HandleTypeDef hdma_usart3_tx;
static void drvUart_configureDMA(void)
{
/* DMA controller clock enable */
__HAL_RCC_DMA1_CLK_ENABLE();
/* DMA interrupt init */
/* DMA1_Stream1_IRQn interrupt configuration */
HAL_NVIC_SetPriority(DMA1_Stream1_IRQn, 10, 0);
HAL_NVIC_EnableIRQ(DMA1_Stream1_IRQn);
/* DMA1_Stream3_IRQn interrupt configuration */
HAL_NVIC_SetPriority(DMA1_Stream3_IRQn, 10, 0);
HAL_NVIC_EnableIRQ(DMA1_Stream3_IRQn);
/* USART3 DMA Init */
/* USART3_RX Init */
hdma_usart3_rx.Instance = DMA1_Stream1;
hdma_usart3_rx.Init.Channel = DMA_CHANNEL_4;
hdma_usart3_rx.Init.Direction = DMA_PERIPH_TO_MEMORY;
hdma_usart3_rx.Init.PeriphInc = DMA_PINC_DISABLE;
hdma_usart3_rx.Init.MemInc = DMA_MINC_ENABLE;
hdma_usart3_rx.Init.PeriphDataAlignment = DMA_PDATAALIGN_BYTE;
hdma_usart3_rx.Init.MemDataAlignment = DMA_MDATAALIGN_BYTE;
hdma_usart3_rx.Init.Mode = DMA_NORMAL;
hdma_usart3_rx.Init.Priority = DMA_PRIORITY_LOW;
hdma_usart3_rx.Init.FIFOMode = DMA_FIFOMODE_ENABLE;
hdma_usart3_rx.Init.FIFOThreshold = DMA_FIFO_THRESHOLD_FULL;
hdma_usart3_rx.Init.MemBurst = DMA_MBURST_SINGLE;
hdma_usart3_rx.Init.PeriphBurst = DMA_PBURST_SINGLE;
if (HAL_DMA_Init(&hdma_usart3_rx) != HAL_OK)
{
Error_Handler();
}
__HAL_LINKDMA(&huart3, hdmarx, hdma_usart3_rx);
/* USART3_TX Init */
hdma_usart3_tx.Instance = DMA1_Stream3;
hdma_usart3_tx.Init.Channel = DMA_CHANNEL_4;
hdma_usart3_tx.Init.Direction = DMA_MEMORY_TO_PERIPH;
hdma_usart3_tx.Init.PeriphInc = DMA_PINC_DISABLE;
hdma_usart3_tx.Init.MemInc = DMA_MINC_ENABLE;
hdma_usart3_tx.Init.PeriphDataAlignment = DMA_PDATAALIGN_BYTE;
hdma_usart3_tx.Init.MemDataAlignment = DMA_MDATAALIGN_BYTE;
hdma_usart3_tx.Init.Mode = DMA_NORMAL;
hdma_usart3_tx.Init.Priority = DMA_PRIORITY_LOW;
hdma_usart3_tx.Init.FIFOMode = DMA_FIFOMODE_ENABLE;
hdma_usart3_tx.Init.FIFOThreshold = DMA_FIFO_THRESHOLD_FULL;
hdma_usart3_tx.Init.MemBurst = DMA_MBURST_SINGLE;
hdma_usart3_tx.Init.PeriphBurst = DMA_PBURST_SINGLE;
if (HAL_DMA_Init(&hdma_usart3_tx) != HAL_OK)
{
Error_Handler();
}
__HAL_LINKDMA(&huart3, hdmatx, hdma_usart3_tx);
/* USART3 interrupt Init */
HAL_NVIC_SetPriority(USART3_IRQn, 10, 0);
HAL_NVIC_EnableIRQ(USART3_IRQn);
}
#endif
bool drvUart_start(void)
{
activeReceiveBuffer = receiveBuffer1;
sideReceiveBuffer = receiveBuffer2;
transmitBuffer[0] = 0xAA;
//drvUart_configureDMA();
HW_USART3_Init();
HAL_UARTEx_ReceiveToIdle_DMA(&huart3, activeReceiveBuffer, DRV_UART_RECEIVE_BUFFER_SIZE);
return true;
}
bool drvUart_set_on_rx_cplt(void (*f)(const uint8_t * const buffer))
{
on_rx_cplt = f;
return true;
}
bool drvUart_set_on_tx_cplt(void (*f)(void))
{
on_tx_cplt = f;
return true;
}
bool drvUart_send(uint8_t * const buf)
{
memcpy(transmitBuffer + 1, buf, buf[0]);
transmitBuffer[1] += 2; // add size of CRC16
uint16_t crc = crc16(transmitBuffer + 1, buf[0]);
transmitBuffer[1 + buf[0]] = (uint8_t) crc;
transmitBuffer[1 + buf[0] + 1] = (uint8_t) (crc >> 8);
HAL_UART_Transmit_DMA(&huart3, transmitBuffer, buf[0] + 3);
return true;
}
void drvUart_restart_receiver(void)
{
if (huart3.RxState != HAL_UART_STATE_BUSY_RX)
{
// at this point callback has swapped the buffer pointers
(void) HAL_UARTEx_ReceiveToIdle_DMA(&huart3, activeReceiveBuffer, DRV_UART_RECEIVE_BUFFER_SIZE);
}
}
void HAL_UARTEx_RxEventCallback(UART_HandleTypeDef *huart, uint16_t Size)
{
// first, relaunch hardware DMA reception on the other buffer
(void) HAL_UARTEx_ReceiveToIdle_DMA(&huart3, sideReceiveBuffer, DRV_UART_RECEIVE_BUFFER_SIZE);
// then update local references
{
// restrict symbol visibility, but use static allocation for performance
static uint8_t *tmp;
tmp = sideReceiveBuffer;
sideReceiveBuffer = activeReceiveBuffer;
activeReceiveBuffer = tmp;
}
if (on_rx_cplt == NULL)
{
return;
}
// then process every received packet
{
static uint16_t offset;
for (offset = 0; offset < Size; offset += 3 + sideReceiveBuffer[1 + offset]) {
// verify packet is not too short (1 byte for size, 1+ byte(s) for command and 2 bytes for CRC16)
if (sideReceiveBuffer[1 + offset] < 4)
{
// drop ALL remaining packets on failure
return;
}
// verify packet length does not overflow received frame size
if (1 + offset + sideReceiveBuffer[1 + offset] > Size)
{
return;
}
// verify packet is not corrupted
if (crc16(sideReceiveBuffer + 1 + offset, sideReceiveBuffer[1 + offset]))
{
return;
}
// exclude size of CRC16
sideReceiveBuffer[1 + offset] -= 2;
// then call the callback (stripping 0xAA from the data)
on_rx_cplt(sideReceiveBuffer + 1 + offset);
}
}
}
void HAL_UART_TxCpltCallback(UART_HandleTypeDef *huart)
{
if (on_tx_cplt == NULL)
{
return;
}
on_tx_cplt();
}
+16
View File
@@ -0,0 +1,16 @@
#ifndef __DRV_UART_H
#define __DRV_UART_H
#include <stdbool.h>
#define DRV_UART_RECEIVE_BUFFER_SIZE 256
#define DRV_UART_TRANSMIT_BUFFER_SIZE 256
bool drvUart_start(void);
bool drvUart_set_on_rx_cplt(void (*f)(const uint8_t * const buffer));
bool drvUart_set_on_tx_cplt(void (*f)(void));
bool drvUart_send(uint8_t *buf);
void drvUart_restart_receiver(void);
#endif /* __DRV_UART_H */
+185
View File
@@ -0,0 +1,185 @@
#include "main.h"
#include "hwUSART3.h"
extern UART_HandleTypeDef huart3;
extern DMA_HandleTypeDef hdma_usart3_rx;
extern DMA_HandleTypeDef hdma_usart3_tx;
void HW_USART3_Init(void)
{
__HAL_RCC_DMA1_CLK_ENABLE();
__HAL_RCC_USART3_CLK_ENABLE();
__HAL_RCC_GPIOD_CLK_ENABLE();
__HAL_RCC_GPIOC_CLK_ENABLE();
huart3.Instance = USART3;
huart3.Init.BaudRate = 115200;
huart3.Init.WordLength = UART_WORDLENGTH_8B;
huart3.Init.StopBits = UART_STOPBITS_1;
huart3.Init.Parity = UART_PARITY_NONE;
huart3.Init.Mode = UART_MODE_TX_RX;
huart3.Init.HwFlowCtl = UART_HWCONTROL_NONE;
huart3.Init.OverSampling = UART_OVERSAMPLING_16;
if (HAL_UART_Init(&huart3) != HAL_OK)
{
Error_Handler();
}
#if 0
GPIO_InitTypeDef GPIO_InitStruct = {0};
GPIO_InitStruct.Pin = GPIO_PIN_9;
GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_VERY_HIGH;
GPIO_InitStruct.Alternate = GPIO_AF7_USART3;
HAL_GPIO_Init(GPIOD, &GPIO_InitStruct);
GPIO_InitStruct.Pin = GPIO_PIN_10;
GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_VERY_HIGH;
GPIO_InitStruct.Alternate = GPIO_AF7_USART3;
HAL_GPIO_Init(GPIOC, &GPIO_InitStruct);
hdma_usart3_rx.Instance = DMA1_Stream1;
hdma_usart3_rx.Init.Channel = DMA_CHANNEL_4;
hdma_usart3_rx.Init.Direction = DMA_PERIPH_TO_MEMORY;
hdma_usart3_rx.Init.PeriphInc = DMA_PINC_DISABLE;
hdma_usart3_rx.Init.MemInc = DMA_MINC_ENABLE;
hdma_usart3_rx.Init.PeriphDataAlignment = DMA_PDATAALIGN_BYTE;
hdma_usart3_rx.Init.MemDataAlignment = DMA_MDATAALIGN_BYTE;
hdma_usart3_rx.Init.Mode = DMA_NORMAL;
hdma_usart3_rx.Init.Priority = DMA_PRIORITY_LOW;
hdma_usart3_rx.Init.FIFOMode = DMA_FIFOMODE_DISABLE;
if (HAL_DMA_Init(&hdma_usart3_rx) != HAL_OK)
{
Error_Handler();
}
__HAL_LINKDMA(&huart3, hdmarx, hdma_usart3_rx);
hdma_usart3_tx.Instance = DMA1_Stream3;
hdma_usart3_tx.Init.Channel = DMA_CHANNEL_4;
hdma_usart3_tx.Init.Direction = DMA_MEMORY_TO_PERIPH;
hdma_usart3_tx.Init.PeriphInc = DMA_PINC_DISABLE;
hdma_usart3_tx.Init.MemInc = DMA_MINC_ENABLE;
hdma_usart3_tx.Init.PeriphDataAlignment = DMA_PDATAALIGN_BYTE;
hdma_usart3_tx.Init.MemDataAlignment = DMA_MDATAALIGN_BYTE;
hdma_usart3_tx.Init.Mode = DMA_NORMAL;
hdma_usart3_tx.Init.Priority = DMA_PRIORITY_LOW;
hdma_usart3_tx.Init.FIFOMode = DMA_FIFOMODE_DISABLE;
if (HAL_DMA_Init(&hdma_usart3_tx) != HAL_OK)
{
Error_Handler();
}
__HAL_LINKDMA(&huart3, hdmatx, hdma_usart3_tx);
#endif
HAL_NVIC_SetPriority(DMA1_Stream1_IRQn, 10, 0);
HAL_NVIC_EnableIRQ(DMA1_Stream1_IRQn);
HAL_NVIC_SetPriority(DMA1_Stream3_IRQn, 10, 0);
HAL_NVIC_EnableIRQ(DMA1_Stream3_IRQn);
HAL_NVIC_SetPriority(USART3_IRQn, 10, 0);
HAL_NVIC_EnableIRQ(USART3_IRQn);
}
void HAL_UART_MspInit(UART_HandleTypeDef* uartHandle)
{
GPIO_InitTypeDef GPIO_InitStruct = {0};
if(uartHandle->Instance==USART2)
{
__HAL_RCC_USART2_CLK_ENABLE();
__HAL_RCC_GPIOD_CLK_ENABLE();
GPIO_InitStruct.Pin = GPIO_PIN_5|GPIO_PIN_6;
GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_VERY_HIGH;
GPIO_InitStruct.Alternate = GPIO_AF7_USART2;
HAL_GPIO_Init(GPIOD, &GPIO_InitStruct);
}
else if(uartHandle->Instance==USART3)
{
__HAL_RCC_USART3_CLK_ENABLE();
__HAL_RCC_GPIOD_CLK_ENABLE();
__HAL_RCC_GPIOC_CLK_ENABLE();
GPIO_InitStruct.Pin = GPIO_PIN_9;
GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_VERY_HIGH;
GPIO_InitStruct.Alternate = GPIO_AF7_USART3;
HAL_GPIO_Init(GPIOD, &GPIO_InitStruct);
GPIO_InitStruct.Pin = GPIO_PIN_10;
GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_VERY_HIGH;
GPIO_InitStruct.Alternate = GPIO_AF7_USART3;
HAL_GPIO_Init(GPIOC, &GPIO_InitStruct);
hdma_usart3_rx.Instance = DMA1_Stream1;
hdma_usart3_rx.Init.Channel = DMA_CHANNEL_4;
hdma_usart3_rx.Init.Direction = DMA_PERIPH_TO_MEMORY;
hdma_usart3_rx.Init.PeriphInc = DMA_PINC_DISABLE;
hdma_usart3_rx.Init.MemInc = DMA_MINC_ENABLE;
hdma_usart3_rx.Init.PeriphDataAlignment = DMA_PDATAALIGN_BYTE;
hdma_usart3_rx.Init.MemDataAlignment = DMA_MDATAALIGN_BYTE;
hdma_usart3_rx.Init.Mode = DMA_NORMAL;
hdma_usart3_rx.Init.Priority = DMA_PRIORITY_LOW;
hdma_usart3_rx.Init.FIFOMode = DMA_FIFOMODE_DISABLE;
if (HAL_DMA_Init(&hdma_usart3_rx) != HAL_OK)
{
Error_Handler();
}
__HAL_LINKDMA(uartHandle,hdmarx,hdma_usart3_rx);
hdma_usart3_tx.Instance = DMA1_Stream3;
hdma_usart3_tx.Init.Channel = DMA_CHANNEL_4;
hdma_usart3_tx.Init.Direction = DMA_MEMORY_TO_PERIPH;
hdma_usart3_tx.Init.PeriphInc = DMA_PINC_DISABLE;
hdma_usart3_tx.Init.MemInc = DMA_MINC_ENABLE;
hdma_usart3_tx.Init.PeriphDataAlignment = DMA_PDATAALIGN_BYTE;
hdma_usart3_tx.Init.MemDataAlignment = DMA_MDATAALIGN_BYTE;
hdma_usart3_tx.Init.Mode = DMA_NORMAL;
hdma_usart3_tx.Init.Priority = DMA_PRIORITY_LOW;
hdma_usart3_tx.Init.FIFOMode = DMA_FIFOMODE_DISABLE;
if (HAL_DMA_Init(&hdma_usart3_tx) != HAL_OK)
{
Error_Handler();
}
__HAL_LINKDMA(uartHandle,hdmatx,hdma_usart3_tx);
}
}
void HAL_UART_MspDeInit(UART_HandleTypeDef* uartHandle)
{
if(uartHandle->Instance==USART2)
{
__HAL_RCC_USART2_CLK_DISABLE();
HAL_GPIO_DeInit(GPIOD, GPIO_PIN_5|GPIO_PIN_6);
}
else if(uartHandle->Instance==USART3)
{
__HAL_RCC_USART3_CLK_DISABLE();
HAL_GPIO_DeInit(GPIOD, GPIO_PIN_9);
HAL_GPIO_DeInit(GPIOC, GPIO_PIN_10);
HAL_DMA_DeInit(uartHandle->hdmarx);
HAL_DMA_DeInit(uartHandle->hdmatx);
}
}
+6
View File
@@ -0,0 +1,6 @@
#ifndef __HW_USART3_H
#define __HW_USART3_H
void HW_USART3_Init(void);
#endif /* __HW_USART3_H */
+17
View File
@@ -0,0 +1,17 @@
set(KPI_Rover_Database_Inc
#${PROJECT_KPIROVER_DIR}
${CMAKE_CURRENT_SOURCE_DIR}
)
set(KPI_Rover_Database_Src
${CMAKE_CURRENT_SOURCE_DIR}/ulDatabase.c
)
add_library(KPI_Rover_Database STATIC)
target_include_directories(KPI_Rover_Database PRIVATE ${KPI_Rover_Database_Inc})
target_sources(KPI_Rover_Database PRIVATE ${KPI_Rover_Database_Src})
target_link_libraries(KPI_Rover_Database PRIVATE FREERTOS_H KPI_Rover_Logger_H)
add_library(KPI_Rover_Database_H INTERFACE)
target_include_directories(KPI_Rover_Database_H INTERFACE ${CMAKE_CURRENT_SOURCE_DIR})
+218
View File
@@ -0,0 +1,218 @@
#!/bin/python3
from pathlib import Path
lines = open(Path(__file__).parent / "../../KPIRover.c").read().split('\n')
decoder_active = False
params = []
def log(text):
types = {"ERROR": True,
"WARN": True,
"INFO": True,
"DEBUG": True}
if len(text) == 0 or text[0] != "[":
print(text)
return
msg_type = text.split("]", 1)[0][1:]
if msg_type not in types:
print(f'[INTERNAL ERROR] msg_type "{msg_type}" does not exist')
exit(2)
if types[msg_type]:
print(text)
def process_offset(v):
global params
offset = int(v)
if offset != 0:
log("[WARN] Offsets are overridden by the database and should be kept as 0 in the metadata")
return False
params[-1]["offset"] = int(v)
return True
def process_type(v):
global params
if v not in ["INT8", "UINT8", "INT16", "UINT16", "INT32", "UINT32", "FLOAT"]:
log(f'[ERROR] Invalid type: "{v}"')
return False
params[-1]["type"] = v
return True
def process_persistent(v):
global params
if v not in ["true", "false"]:
log(f"[ERROR] Invalid boolean value: {v}")
return False
params[-1]["persistent"] = True if v == "true" else False
if len(params) > 1:
if params[-1]["persistent"] and not params[-2]["persistent"]:
log("[ERROR] Persistent parameters must come before the non-persistent ones")
return False
return True
def process_defaultValue(v):
if params[-1]["type"] == "FLOAT":
try:
params[-1]["defaultValue"] = float(v.strip("fF"))
except:
log(f"[ERROR] Invalid floating-point value: {v}")
return False
else:
try:
params[-1]["defaultValue"] = int(v)
except:
log(f"[ERROR] Invalid integer value: {v}")
return False
''' unfinished and broken, no reason to fix right now
elif params[-1]["type"] == "INT32":
try:
params[-1]["defaultValue"] = int(v)
if params[-1]["defaultValue"] > 0x7fffffff:
print(f"[WARN] defaultValue overflows it's data type: {v} ({hex(params[-1]['defaultValue'])}) > 0x7fffffff")
elif params[-1]["defaultValue"] < -0x80000000:
print(f"[WARN] defaultValue overflows it's data type: {v} ({hex(params[-1]['defaultValue'] % 0x100000000)}) < -0x80000000")
except:
log(f"[ERROR] Invalid floating-point value: {v}")
return False
'''
return True
for l in lines:
log("> " + l)
if 'struct ulDatabase_ParamMetadata ulDatabase_params[]' in l:
log("[DEBUG] Starting to read metadata")
decoder_active = True
continue
if ('}' in l) and ('{' not in l):
log("[DEBUG] End of metadata")
break
if not decoder_active:
continue
metadata = [i.strip() for i in l.split('}')[0].split('{')[1].split(',')]
name = l.split("//")[1].strip().strip(",")
params.append({'name': name})
metadata_item_pool = [
{
"name": "offset",
"func": process_offset
},
{
"name": "type",
"func": process_type
},
{
"name": "persistent",
"func": process_persistent
},
{
"name": "defaultValue",
"func": process_defaultValue
}
]
for i, v in enumerate(metadata_item_pool):
v["position"] = i
for c, t in enumerate(metadata):
index = -1
result = False
value = ""
if '=' in t:
item, value = [i.strip() for i in t.split("=")]
try:
index = [i['name'] for i in metadata_item_pool].index(item)
except ValueError:
log(f'[ERROR] {i}: "{item}": no such metadata key')
else:
index = 0
value = t
if index != -1:
result = metadata_item_pool.pop(index)['func'](value)
if not result:
unwrapped_l = l.replace("\t", " " * 8)
log(f"[ERROR] > {unwrapped_l}")
arrow_offset = unwrapped_l.index("{") + 1
ll = unwrapped_l[arrow_offset:]
for _ in range(c):
arrow_offset += ll.index(",") + 1
ll = unwrapped_l[arrow_offset:]
while unwrapped_l[arrow_offset] == ' ':
arrow_offset += 1
underline_len = len(t) - 1
while unwrapped_l[arrow_offset + underline_len] == ' ':
underline_len -= 1
log("[ERROR] > " + " " * arrow_offset + "^" + "~" * underline_len)
log("[ERROR] Error detected, not continuing")
exit(1)
log("[INFO] Result:")
for i in params:
print("[INFO] " + i["name"])
log("[INFO] Patching ulDatabase.h...")
ulDatabase_h = open(Path(__file__).parent / "../ulDatabase.h").read().split('\n')
while ulDatabase_h[-1] == "":
del ulDatabase_h[-1]
enum_since = [i.startswith("enum ulDatabase_ParamId {") for i in ulDatabase_h].index(True) + 1
enum_len = [i.startswith("};") for i in ulDatabase_h[enum_since:]].index(True)
log("[DEBUG]: Removing old enum data:")
for i, l in enumerate(ulDatabase_h):
if enum_since <= i < enum_since + enum_len:
log("[DEBUG] -" + l)
else:
log("[DEBUG] " + l)
del ulDatabase_h[enum_since:enum_since+enum_len]
ulDatabase_h.insert(enum_since, "\tPARAM_COUNT")
for i in params[::-1]:
ulDatabase_h.insert(enum_since, f"\t{i['name']},")
log("[DEBUG] Writing new ulDatabase.h...")
with open(Path(__file__).parent / "../ulDatabase.h", "w") as f:
for i in ulDatabase_h:
print(i + '\n', end = '')
f.write(i + '\n')
log("[DEBUG] ulDatabase.h closed")
+432
View File
@@ -0,0 +1,432 @@
#include <string.h>
#include "ulDatabase.h"
//#include "FreeRTOS.h"
//#include "cmsis_os2.h"
#include "ulog.h"
#define DB_LOCK() // osMutexAcquire(ulDatabase_mutex, osWaitForever)
#define DB_FREE() // osMutexRelease(ulDatabase_mutex)
union TypeHolder {
uint8_t u8;
int8_t i8;
uint16_t u16;
int16_t i16;
uint32_t u32;
int32_t i32;
float f;
};
//static osMutexId_t ulDatabase_mutex;
//StaticSemaphore_t *ulDatabase_mutex_cb;
static struct ulDatabase db;
bool ulDatabase_init(struct ulDatabase_ParamMetadata * const metadataTable, const uint16_t metadataCount)
{
ULOG_DEBUG("Database init start");
// calculate DB size and assign correct offsets
uint16_t db_size = 0;
for (size_t i = 0; i < metadataCount; i++) {
metadataTable[i].offset = db_size;
switch (metadataTable[i].type) {
case UINT8:
case INT8:
db_size += 1;
break;
case UINT16:
case INT16:
db_size += 2;
break;
case UINT32:
case INT32:
case FLOAT:
db_size += 4;
break;
}
}
// allocate memory for DB
if (db_size) {
ULOG_INFO("Allocating %hu for database storage", db_size);
void *db_mem = malloc(db_size);
if (db_mem == NULL) {
ULOG_ERROR("Failed to allocate memory for database storage: allocator returned NULL");
return false;
}
db.dataArray = (uint8_t *) db_mem;
} else {
ULOG_INFO("Not allocating memory for an empty database");
db.dataArray = NULL;
}
// create global database lock (mutex) for the entire database
#if 0
{
ulDatabase_mutex_cb = malloc(sizeof(StaticSemaphore_t));
if (ulDatabase_mutex_cb == NULL) {
ULOG_ERROR("Failed to allocate memory for database mutex: allocator returned NULL");
return false;
}
osMutexAttr_t mutex_attrs = {NULL, 0, ulDatabase_mutex_cb, sizeof(StaticSemaphore_t)};
if (NULL == (ulDatabase_mutex = osMutexNew(&mutex_attrs))) {
ULOG_ERROR("Failed to initialize mutex: OS error");
return false;
}
}
#endif
// save metadata for allocated db + metadata size
db.dataArraySize = db_size;
db.metadataCount = metadataCount;
// save metadata table location
db.metadataTable = metadataTable;
// fill db memory with default values
for (uint16_t i = 0; i < metadataCount; i++)
ulDatabase_reset(i);
ULOG_DEBUG("Database init finish [success]");
return true;
}
bool ulDatabase_setUint8(uint16_t id, uint8_t value)
{
struct ulDatabase_ParamMetadata *p = ulDatabase_getMetadata(id);
if (p == NULL)
return false;
if (p->type != UINT8)
return false;
DB_LOCK();
memcpy(&(db.dataArray[p->offset]), &value, 1);
DB_FREE();
return true;
}
bool ulDatabase_getUint8(uint16_t id, uint8_t *value)
{
struct ulDatabase_ParamMetadata *p = ulDatabase_getMetadata(id);
if (p == NULL)
return false;
if (p->type != UINT8)
return false;
DB_LOCK();
memcpy(value, &(db.dataArray[p->offset]), 1);
DB_FREE();
return true;
}
bool ulDatabase_setInt8(uint16_t id, int8_t value)
{
struct ulDatabase_ParamMetadata *p = ulDatabase_getMetadata(id);
if (p == NULL)
return false;
if (p->type != INT8)
return false;
DB_LOCK();
memcpy(&(db.dataArray[p->offset]), &value, 1);
DB_FREE();
return true;
}
bool ulDatabase_getInt8(uint16_t id, int8_t *value)
{
struct ulDatabase_ParamMetadata *p = ulDatabase_getMetadata(id);
if (p == NULL)
return false;
if (p->type != INT8)
return false;
DB_LOCK();
memcpy(value, &(db.dataArray[p->offset]), 1);
DB_FREE();
return true;
}
bool ulDatabase_setUint16(uint16_t id, uint16_t value)
{
struct ulDatabase_ParamMetadata *p = ulDatabase_getMetadata(id);
if (p == NULL)
return false;
if (p->type != UINT16)
return false;
DB_LOCK();
memcpy(&(db.dataArray[p->offset]), &value, 2);
DB_FREE();
return true;
}
bool ulDatabase_getUint16(uint16_t id, uint16_t *value)
{
struct ulDatabase_ParamMetadata *p = ulDatabase_getMetadata(id);
if (p == NULL)
return false;
if (p->type != UINT16)
return false;
DB_LOCK();
memcpy(value, &(db.dataArray[p->offset]), 2);
DB_FREE();
return true;
}
bool ulDatabase_setInt16(uint16_t id, int16_t value)
{
struct ulDatabase_ParamMetadata *p = ulDatabase_getMetadata(id);
if (p == NULL)
return false;
if (p->type != INT16)
return false;
DB_LOCK();
memcpy(&(db.dataArray[p->offset]), &value, 2);
DB_FREE();
return true;
}
bool ulDatabase_getInt16(uint16_t id, int16_t *value)
{
struct ulDatabase_ParamMetadata *p = ulDatabase_getMetadata(id);
if (p == NULL)
return false;
if (p->type != INT16)
return false;
DB_LOCK();
memcpy(value, &(db.dataArray[p->offset]), 2);
DB_FREE();
return true;
}
bool ulDatabase_setUint32(uint16_t id, uint32_t value)
{
struct ulDatabase_ParamMetadata *p = ulDatabase_getMetadata(id);
if (p == NULL)
return false;
if (p->type != UINT32)
return false;
DB_LOCK();
memcpy(&(db.dataArray[p->offset]), &value, 4);
DB_FREE();
return true;
}
bool ulDatabase_getUint32(uint16_t id, uint32_t *value)
{
struct ulDatabase_ParamMetadata *p = ulDatabase_getMetadata(id);
if (p == NULL)
return false;
if (p->type != UINT32)
return false;
DB_LOCK();
memcpy(value, &(db.dataArray[p->offset]), 4);
DB_FREE();
return true;
}
bool ulDatabase_setInt32(uint16_t id, int32_t value)
{
struct ulDatabase_ParamMetadata *p = ulDatabase_getMetadata(id);
if (p == NULL)
return false;
if (p->type != INT32)
return false;
DB_LOCK();
memcpy(&(db.dataArray[p->offset]), &value, 4);
DB_FREE();
return true;
}
bool ulDatabase_getInt32(uint16_t id, int32_t *value)
{
struct ulDatabase_ParamMetadata *p = ulDatabase_getMetadata(id);
if (p == NULL)
return false;
if (p->type != INT32)
return false;
DB_LOCK();
memcpy(value, &(db.dataArray[p->offset]), 4);
DB_FREE();
return true;
}
bool ulDatabase_setFloat(uint16_t id, float value)
{
struct ulDatabase_ParamMetadata *p = ulDatabase_getMetadata(id);
if (p == NULL)
return false;
if (p->type != FLOAT)
return false;
DB_LOCK();
memcpy(&(db.dataArray[p->offset]), &value, 4);
DB_FREE();
return true;
}
bool ulDatabase_getFloat(uint16_t id, float *value)
{
struct ulDatabase_ParamMetadata *p = ulDatabase_getMetadata(id);
if (p == NULL)
return false;
if (p->type != FLOAT)
return false;
DB_LOCK();
memcpy(value, &(db.dataArray[p->offset]), 4);
DB_FREE();
return true;
}
bool ulDatabase_reset(uint16_t id)
{
struct ulDatabase_ParamMetadata *p = ulDatabase_getMetadata(id);
if (p == NULL)
return false;
union TypeHolder new_value;
DB_LOCK();
switch (p->type) {
case UINT8:
new_value.u8 = (uint8_t) p->defaultValue;
break;
case INT8:
new_value.i8 = (int8_t) p->defaultValue;
break;
case UINT16:
new_value.u16 = (uint16_t) p->defaultValue;
break;
case INT16:
new_value.i16 = (int16_t) p->defaultValue;
break;
case UINT32:
new_value.u32 = (uint32_t) p->defaultValue;
break;
case INT32:
new_value.i32 = (int32_t) p->defaultValue;
break;
case FLOAT:
new_value.f = (float) p->defaultValue;
break;
}
switch (p->type) {
case UINT8:
memcpy(&(db.dataArray[p->offset]), &(new_value.u8), sizeof(new_value.u8));
break;
case INT8:
memcpy(&(db.dataArray[p->offset]), &(new_value.i8), sizeof(new_value.i8));
break;
case UINT16:
memcpy(&(db.dataArray[p->offset]), &(new_value.u16), sizeof(new_value.u16));
break;
case INT16:
memcpy(&(db.dataArray[p->offset]), &(new_value.i16), sizeof(new_value.i16));
break;
case UINT32:
memcpy(&(db.dataArray[p->offset]), &(new_value.u32), sizeof(new_value.u32));
break;
case INT32:
memcpy(&(db.dataArray[p->offset]), &(new_value.i32), sizeof(new_value.i32));
break;
case FLOAT:
memcpy(&(db.dataArray[p->offset]), &(new_value.f), sizeof(new_value.f));
break;
}
DB_FREE();
return true;
}
uint8_t *ulDatabase_freeze(void)
{
DB_LOCK();
return db.dataArray;
}
void ulDatabase_unfreeze(void)
{
DB_FREE();
}
struct ulDatabase_ParamMetadata *ulDatabase_getMetadata(uint16_t id)
{
if (!ulDatabase_validateId(id))
return NULL;
return &(db.metadataTable[id]);
}
bool ulDatabase_validateId(uint16_t id)
{
return db.metadataCount > id;
}
+105
View File
@@ -0,0 +1,105 @@
#include <stddef.h>
#include <stdint.h>
#include <stdbool.h>
#include <stdlib.h>
//#include "cmsis_os2.h"
enum ulDatabase_ParamType {
UINT8,
INT8,
UINT16,
INT16,
UINT32,
INT32,
FLOAT
};
enum ulDatabase_ParamId {
ENCODER_CONTROL_PERIOD_MS,
ENCODER_TICKS_PER_REVOLUTION,
MOTOR_FL_KP,
MOTOR_FL_KI,
MOTOR_FL_KD,
MOTOR_FR_KP,
MOTOR_FR_KI,
MOTOR_FR_KD,
MOTOR_RL_KP,
MOTOR_RL_KI,
MOTOR_RL_KD,
MOTOR_RR_KP,
MOTOR_RR_KI,
MOTOR_RR_KD,
ADC_CAL_CH_11_OFFSET,
ADC_CAL_CH_TEMP_OFFSET,
ADC_CAL_CH_11_SCALE,
ADC_CAL_CH_TEMP_SCALE,
MOTOR_FL_SETPOINT,
MOTOR_RL_SETPOINT,
MOTOR_FR_SETPOINT,
MOTOR_RR_SETPOINT,
MOTOR_FL_RPM,
MOTOR_RL_RPM,
MOTOR_FR_RPM,
MOTOR_RR_RPM,
IMU_ACCEL_X,
IMU_ACCEL_Y,
IMU_ACCEL_Z,
IMU_GYRO_X,
IMU_GYRO_Y,
IMU_GYRO_Z,
IMU_MAG_X,
IMU_MAG_Y,
IMU_MAG_Z,
IMU_QUAT_W,
IMU_QUAT_X,
IMU_QUAT_Y,
IMU_QUAT_Z,
IMU_CALIB_CMD,
IMU_CALIB_STATUS,
IMU_IS_CALIBRATED,
ADC_CALIBRATION_START,
ADC_CALIBRATION_POINT,
ADC_CALIBRATION_POINT_VALUE,
ADC_CALIBRATION_CHANNEL_ID,
PARAM_BATTERY_VOLTAGE,
PARAM_MCU_TEMPERATURE,
UART_LINE_ERROR_COUNT,
PARAM_COUNT
};
struct ulDatabase_ParamMetadata {
uint16_t offset;
enum ulDatabase_ParamType type;
bool persistent;
float defaultValue;
};
struct ulDatabase {
uint8_t *dataArray;
struct ulDatabase_ParamMetadata *metadataTable;
uint16_t metadataCount;
uint16_t dataArraySize;
};
bool ulDatabase_init(struct ulDatabase_ParamMetadata * const metadataTable, const uint16_t metadataCount);
bool ulDatabase_setUint8(uint16_t id, uint8_t value);
bool ulDatabase_getUint8(uint16_t id, uint8_t *value);
bool ulDatabase_setInt8(uint16_t id, int8_t value);
bool ulDatabase_getInt8(uint16_t id, int8_t *value);
bool ulDatabase_setUint16(uint16_t id, uint16_t value);
bool ulDatabase_getUint16(uint16_t id, uint16_t *value);
bool ulDatabase_setInt16(uint16_t id, int16_t value);
bool ulDatabase_getInt16(uint16_t id, int16_t *value);
bool ulDatabase_setUint32(uint16_t id, uint32_t value);
bool ulDatabase_getUint32(uint16_t id, uint32_t *value);
bool ulDatabase_setInt32(uint16_t id, int32_t value);
bool ulDatabase_getInt32(uint16_t id, int32_t *value);
bool ulDatabase_setFloat(uint16_t id, float value);
bool ulDatabase_getFloat(uint16_t id, float *value);
bool ulDatabase_reset(uint16_t id);
uint8_t *ulDatabase_freeze(void);
void ulDatabase_unfreeze(void);
struct ulDatabase_ParamMetadata *ulDatabase_getMetadata(uint16_t id);
bool ulDatabase_validateId(uint16_t id);
+95
View File
@@ -0,0 +1,95 @@
#include "KPIRover.h"
//#include "ADC/ulAdc.h"
#include "Communication/ProtocolHandler.h"
#include "Database/ulDatabase.h"
//#include "Encoders/ulEncoder.h"
//#include "IMU/ulImu.h"
//#include "Motors/ulMotorsController.h"
//#include "Storage/ulStorage.h"
#include "ulog.h"
#include "ulUlog.h"
//#include "cmsis_os.h"
static struct ulDatabase_ParamMetadata ulDatabase_params[] = {
{0, UINT16, true, 5}, // ENCODER_CONTROL_PERIOD_MS,
{0, FLOAT, true, 820.0f}, // ENCODER_TICKS_PER_REVOLUTION,
{0, FLOAT, true, 0.046f}, // MOTOR_FL_KP
{0, FLOAT, true, 0.013f}, // MOTOR_FL_KI
{0, FLOAT, true, 0.0001f}, // MOTOR_FL_KD
{0, FLOAT, true, 0.046f}, // MOTOR_FR_KP
{0, FLOAT, true, 0.013f}, // MOTOR_FR_KI
{0, FLOAT, true, 0.0001f}, // MOTOR_FR_KD
{0, FLOAT, true, 0.046f}, // MOTOR_RL_KP
{0, FLOAT, true, 0.013f}, // MOTOR_RL_KI
{0, FLOAT, true, 0.0001f}, // MOTOR_RL_KD
{0, FLOAT, true, 0.046f}, // MOTOR_RR_KP
{0, FLOAT, true, 0.013f}, // MOTOR_RR_KI
{0, FLOAT, true, 0.0001f}, // MOTOR_RR_KD
{0, INT32, true, 0}, // ADC_CAL_CH_11_OFFSET,
{0, INT32, true, 0}, // ADC_CAL_CH_TEMP_OFFSET,
{0, FLOAT, true, 0.0f}, // ADC_CAL_CH_11_SCALE,
{0, FLOAT, true, 0.0f}, // ADC_CAL_CH_TEMP_SCALE,
{0, INT32, false, 0}, // MOTOR_FL_SETPOINT,
{0, INT32, false, 0}, // MOTOR_RL_SETPOINT,
{0, INT32, false, 0}, // MOTOR_FR_SETPOINT,
{0, INT32, false, 0}, // MOTOR_RR_SETPOINT,
{0, INT32, false, 0}, // MOTOR_FL_RPM,
{0, INT32, false, 0}, // MOTOR_RL_RPM,
{0, INT32, false, 0}, // MOTOR_FR_RPM,
{0, INT32, false, 0}, // MOTOR_RR_RPM,
{0, FLOAT, false, 0.0f}, // IMU_ACCEL_X
{0, FLOAT, false, 0.0f}, // IMU_ACCEL_Y
{0, FLOAT, false, 0.0f}, // IMU_ACCEL_Z
{0, FLOAT, false, 0.0f}, // IMU_GYRO_X
{0, FLOAT, false, 0.0f}, // IMU_GYRO_Y
{0, FLOAT, false, 0.0f}, // IMU_GYRO_Z
{0, FLOAT, false, 0.0f}, // IMU_MAG_X
{0, FLOAT, false, 0.0f}, // IMU_MAG_Y
{0, FLOAT, false, 0.0f}, // IMU_MAG_Z
{0, FLOAT, false, 0.0f}, // IMU_QUAT_W
{0, FLOAT, false, 0.0f}, // IMU_QUAT_X
{0, FLOAT, false, 0.0f}, // IMU_QUAT_Y
{0, FLOAT, false, 0.0f}, // IMU_QUAT_Z
{0, UINT8, false, 0}, // IMU_CALIB_CMD
{0, UINT8, false, 0}, // IMU_CALIB_STATUS
{0, UINT8, false, 0}, // IMU_IS_CALIBRATED
{0, UINT8, false, 0}, // ADC_CALIBRATION_START,
{0, UINT8, false, 0}, // ADC_CALIBRATION_POINT,
{0, FLOAT, false, 0}, // ADC_CALIBRATION_POINT_VALUE,
{0, UINT8, false, 0}, // ADC_CALIBRATION_CHANNEL_ID
{0, FLOAT, false, 0}, // PARAM_BATTERY_VOLTAGE,
{0, FLOAT, false, 0}, // PARAM_MCU_TEMPERATURE
{0, UINT32, false, 0}, // UART_LINE_ERROR_COUNT
};
//extern I2C_HandleTypeDef hi2c3;
void KPIRover_Init(void) {
ULOG_INIT();
ULOG_SUBSCRIBE(ul_ulog_send, ULOG_DEBUG_LEVEL);
ulDatabase_init(ulDatabase_params, sizeof(ulDatabase_params) / sizeof(struct ulDatabase_ParamMetadata));
ProtocolHandler_init();
#if 0
ulStorage_init();
ulEncoder_Init();
//ulImu_Init(&hi2c3);
static const osThreadAttr_t MotorsCtrlTask_attributes = {
.name = "MotorsCtrlTask",
.priority = (osPriority_t) osPriorityNormal,
.stack_size = 1024 * 4
};
(void) osThreadNew(ulMotorsController_Task, NULL, &MotorsCtrlTask_attributes);
// ADC
const osThreadAttr_t adcTask_attributes = {
.name = "adcTask",
.priority = (osPriority_t) osPriorityNormal,
.stack_size = 256 * 4
};
(void) osThreadNew(ulAdc_task, NULL, &adcTask_attributes);
#endif
}
+6
View File
@@ -0,0 +1,6 @@
#ifndef KPIROVER_H
#define KPIROVER_H
void KPIRover_Init(void);
#endif // KPIROVER_H
+29
View File
@@ -0,0 +1,29 @@
set(KPI_Rover_Logger_Inc
#${PROJECT_KPIROVER_DIR}
${CMAKE_CURRENT_SOURCE_DIR}
)
set(KPI_Rover_Logger_Src
${CMAKE_CURRENT_SOURCE_DIR}/ulUlog.c
${CMAKE_CURRENT_SOURCE_DIR}/ulog.c
)
add_library(KPI_Rover_Logger STATIC)
target_include_directories(KPI_Rover_Logger PRIVATE
${KPI_Rover_Logger_Inc}
)
target_sources(KPI_Rover_Logger PRIVATE
${KPI_Rover_Logger_Src}
)
target_link_libraries(KPI_Rover_Logger PRIVATE
FREERTOS_H
HAL_H
)
add_library(KPI_Rover_Logger_H INTERFACE)
target_include_directories(KPI_Rover_Logger_H INTERFACE
${CMAKE_CURRENT_SOURCE_DIR}
)
+50
View File
@@ -0,0 +1,50 @@
# uLog Logger
A lightweight logging system for the KPI Rover ECU software that provides structured logging with multiple log levels and configurable output destinations. Integrated with FreeRTOS for thread-safe operation across multiple tasks.
## Usage Example
Once initialized, you can use logging macros throughout your application:
```c
#include "ulog.h"
void StartDefaultTask(void *argument)
{
uint32_t count = 0;
ULOG_INFO("Default task started");
for(;;)
{
ULOG_DEBUG("Hello from default task %d", count++);
vTaskDelay(pdMS_TO_TICKS(101)); // Wait for ~100ms
}
}
```
## Available Log Levels
The logger supports multiple log levels in order of increasing severity:
| Level | Macro | Numeric Value | Description |
|-------|-------|---------------|-------------|
| **TRACE** | `ULOG_TRACE()` | 100 | Very detailed information for tracing program flow |
| **DEBUG** | `ULOG_DEBUG()` | 101 | Detailed information for diagnosing problems |
| **INFO** | `ULOG_INFO()` | 102 | General information about program execution |
| **WARNING** | `ULOG_WARNING()` | 103 | Something unexpected happened, but software still works |
| **ERROR** | `ULOG_ERROR()` | 104 | Serious problem occurred, some function failed |
| **CRITICAL** | `ULOG_CRITICAL()` | 105 | Very serious error, program may be unable to continue |
| **ALWAYS** | `ULOG_ALWAYS()` | 106 | Messages that should always be logged |
### Example Output
When properly configured, the logger produces formatted output like this:
```
[20301][DEBUG][main.c] Hello from default task 201
[21302][INFO][sensor_task.c] Temperature: 23.5°C
[22303][WARNING][sensor_task.c] High temperature detected: 81.2°C
[23304][ERROR][can_driver.c] CAN transmission failed, error code: 0x42
```
+177
View File
@@ -0,0 +1,177 @@
/*
* MIT License
*
* Copyright (c) 2024 KPI Rover Project
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include "ulUlog.h"
#include "FreeRTOS.h"
#include "task.h"
#include "queue.h"
#include "cmsis_os2.h"
//#include "usbd_cdc_if.h"
//#include "usbd_def.h"
#include "main.h"
#include "portable.h"
#include <string.h>
#include <stdio.h>
#include <string.h>
#define LOG_QUEUE_LENGTH 20
#define MAX_LOG_MESSAGE_SIZE 256
static void ulogTask(void *argument);
static osThreadId_t ulogTaskHandle;
static StaticQueue_t xUlogQueueBuffer;
static uint8_t ucUlogQueueStorage[LOG_QUEUE_LENGTH * MAX_LOG_MESSAGE_SIZE];
static QueueHandle_t xULogQueue = NULL;
volatile uint32_t ulogUsbIsEstablished;
osEventFlagsId_t ulogFlags;
#define ULOG_CDC_TRANSMIT_FINISH_FLAG 0x1
#define ULOG_DEV_CONNECTED_WAKEUP_FLAG 0x2
static StaticSemaphore_t ulUlog_mutex_storage;
#define ULOG_LOCK() // osMutexAcquire(&ulUlog_mutex_storage, osWaitForever)
#define ULOG_UNLOCK() // osMutexRelease(&ulUlog_mutex_storage)
static const osThreadAttr_t ulogTask_attributes = {
.name = "ulogTask",
.stack_size = 128 * 4,
.priority = (osPriority_t) osPriorityNormal,
};
void ul_ulog_init()
{
xULogQueue = xQueueCreateStatic(LOG_QUEUE_LENGTH, MAX_LOG_MESSAGE_SIZE,
ucUlogQueueStorage, &xUlogQueueBuffer);
if (xULogQueue == NULL)
{
Error_Handler();
}
ulogTaskHandle = osThreadNew(ulogTask, NULL, &ulogTask_attributes);
if (ulogTaskHandle == NULL)
{
Error_Handler();
}
ulogFlags = osEventFlagsNew(NULL);
ulogUsbIsEstablished = 0;
{
const static osMutexAttr_t mutex_attrs = {NULL, 0, &ulUlog_mutex_storage, sizeof(ulUlog_mutex_storage)};
(void) osMutexNew(&mutex_attrs);
}
}
static inline void ul_ulog_send_critical(ulog_level_t level, const char *filename, char *msg)
{
if (xULogQueue == NULL || msg == NULL)
{
return;
}
static char logBuffer[MAX_LOG_MESSAGE_SIZE];
int len;
size_t msg_len = strlen(msg);
// Extract just the filename from the full path
const char *fbasename = strrchr(filename, '/');
if (fbasename) {
fbasename++; // Skip the '/'
} else {
fbasename = filename; // No path separator found
}
// Truncate message if too long, leaving space for timestamp, level, and filename
if (msg_len > (MAX_LOG_MESSAGE_SIZE - 60))
{
msg_len = MAX_LOG_MESSAGE_SIZE - 60;
}
TickType_t currentTime = xTaskGetTickCount();
len = snprintf(logBuffer, sizeof(logBuffer), "[%lu][%s][%s] %.*s\r\n",
(unsigned long)currentTime,
ulog_level_name(level),
fbasename,
(int)msg_len, msg);
// Ensure buffer is always null-terminated
if (len < 0)
{
// snprintf failed
return;
}
if (len >= sizeof(logBuffer))
{
logBuffer[sizeof(logBuffer) - 1] = '\0';
}
BaseType_t xHigherPriorityTaskWoken = pdFALSE;
if (uxQueueSpacesAvailable(xULogQueue))
{
if (xPortIsInsideInterrupt())
{
xQueueSendFromISR(xULogQueue, logBuffer, &xHigherPriorityTaskWoken);
portYIELD_FROM_ISR(xHigherPriorityTaskWoken);
}
else
{
xQueueSend(xULogQueue, logBuffer, pdMS_TO_TICKS(10));
}
}
}
void ul_ulog_send(ulog_level_t level, const char *filename, char *msg)
{
ULOG_LOCK();
ul_ulog_send_critical(level, filename, msg);
ULOG_UNLOCK();
}
static void ulogTask(void *argument)
{
for (;;)
{
static char logMessage[MAX_LOG_MESSAGE_SIZE];
BaseType_t result = xQueueReceive(xULogQueue, logMessage, portMAX_DELAY);
if (result == pdTRUE)
{
logMessage[MAX_LOG_MESSAGE_SIZE - 1] = '\0';
#if 0
while (ulogUsbIsEstablished != 1)
{
osEventFlagsWait(ulogFlags, ULOG_DEV_CONNECTED_WAKEUP_FLAG, 0, osWaitForever);
osDelay(2000);
}
CDC_Transmit_FS((uint8_t *)logMessage, strlen(logMessage));
osEventFlagsWait(ulogFlags, ULOG_CDC_TRANSMIT_FINISH_FLAG, 0, 100);
#endif
}
}
}
+41
View File
@@ -0,0 +1,41 @@
/*
* MIT License
*
* Copyright (c) 2024 KPI Rover Project
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#ifndef ULOG_TASK_H_
#define UL_ULOG_H_
#ifdef __cplusplus
extern "C" {
#endif
#include "ulog.h"
void ul_ulog_init();
void ul_ulog_send(ulog_level_t level, const char *filename, char *msg);
#ifdef __cplusplus
}
#endif
#endif /* UL_ULOG_H_ */
+159
View File
@@ -0,0 +1,159 @@
/**
MIT License
Copyright (c) 2024 KPI Rover Project
This file contains modifications and extensions to the original uLog library.
Original uLog library:
Copyright (c) 2019 R. Dunbar Poor <rdpoor@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
/**
* \file ulog.c
*
* \brief uLog: lightweight logging for embedded systems
*
* See ulog.h for sparse documentation.
*/
#include "ulog.h"
#ifdef ULOG_ENABLED // whole file...
#include <stdio.h>
#include <string.h>
#include <stdarg.h>
// =============================================================================
// types and definitions
typedef struct {
ulog_function_t fn;
ulog_level_t threshold;
} subscriber_t;
static ulog_level_t ulog_lowest_log_level();
// =============================================================================
// local storage
static subscriber_t s_subscribers[ULOG_MAX_SUBSCRIBERS];
static char s_message[ULOG_MAX_MESSAGE_LENGTH];
static ulog_level_t s_lowest_log_level;
// =============================================================================
// user-visible code
void ulog_init() {
memset(s_subscribers, 0, sizeof(s_subscribers));
s_lowest_log_level = ulog_lowest_log_level();
}
// search the s_subscribers table to install or update fn
ulog_err_t ulog_subscribe(ulog_function_t fn, ulog_level_t threshold) {
int available_slot = -1;
int i;
for (i=0; i<ULOG_MAX_SUBSCRIBERS; i++) {
if (s_subscribers[i].fn == fn) {
// already subscribed: update threshold and return immediately.
s_subscribers[i].threshold = threshold;
return ULOG_ERR_NONE;
} else if (s_subscribers[i].fn == NULL) {
// found a free slot
available_slot = i;
}
}
// fn is not yet a subscriber. assign if possible.
if (available_slot == -1) {
return ULOG_ERR_SUBSCRIBERS_EXCEEDED;
}
s_subscribers[available_slot].fn = fn;
s_subscribers[available_slot].threshold = threshold;
s_lowest_log_level = ulog_lowest_log_level(); // Update lowest log level
return ULOG_ERR_NONE;
}
// search the s_subscribers table to remove
ulog_err_t ulog_unsubscribe(ulog_function_t fn) {
int i;
for (i=0; i<ULOG_MAX_SUBSCRIBERS; i++) {
if (s_subscribers[i].fn == fn) {
s_subscribers[i].fn = NULL; // mark as empty
s_lowest_log_level = ulog_lowest_log_level(); // Update lowest log level
return ULOG_ERR_NONE;
}
}
return ULOG_ERR_NOT_SUBSCRIBED;
}
const char *ulog_level_name(ulog_level_t severity) {
switch(severity) {
case ULOG_TRACE_LEVEL: return "TRACE";
case ULOG_DEBUG_LEVEL: return "DEBUG";
case ULOG_INFO_LEVEL: return "INFO";
case ULOG_WARNING_LEVEL: return "WARNING";
case ULOG_ERROR_LEVEL: return "ERROR";
case ULOG_CRITICAL_LEVEL: return "CRITICAL";
case ULOG_ALWAYS_LEVEL: return "ALWAYS";
default: return "UNKNOWN";
}
}
void ulog_message(const char *filename, ulog_level_t severity, const char *fmt, ...) {
// Do not evaluate the log message if it will never be logged
if (severity < s_lowest_log_level){
return;
}
va_list ap;
int i;
va_start(ap, fmt);
vsnprintf(s_message, ULOG_MAX_MESSAGE_LENGTH, fmt, ap);
va_end(ap);
for (i=0; i<ULOG_MAX_SUBSCRIBERS; i++) {
if (s_subscribers[i].fn != NULL) {
if (severity >= s_subscribers[i].threshold) {
s_subscribers[i].fn(severity, filename, s_message);
}
}
}
}
// =============================================================================
// private code
static ulog_level_t ulog_lowest_log_level(){
ulog_level_t lowest_log_level = ULOG_ALWAYS_LEVEL;
int i;
for (i=0; i<ULOG_MAX_SUBSCRIBERS; i++) {
if (s_subscribers[i].fn != NULL){
if (s_subscribers[i].threshold < lowest_log_level) {
lowest_log_level = s_subscribers[i].threshold;
}
}
}
return lowest_log_level;
}
#endif // #ifdef ULOG_ENABLED
+155
View File
@@ -0,0 +1,155 @@
/**
MIT License
Copyright (c) 2024 KPI Rover Project
This file contains modifications and extensions to the original uLog library.
Original uLog library:
Copyright (c) 2019 R. Dunbar Poor <rdpoor@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
/**
* \file
*
* \brief uLog: lightweight logging for embedded systems
*
* A quick intro by example:
*
* #include "ulog.h"
*
* // To use uLog, you must define a function to process logging messages.
* // It can write the messages to a console, to a file, to an in-memory
* // buffer: the choice is yours. And you get to choose the format of
* // the message. This example prints to the console. One caveat: msg
* // is a static string and will be over-written at the next call to ULOG.
* // You may print it or copy it, but saving a pointer to it will lead to
* // confusion and astonishment.
* //
* void my_console_logger(ulog_level_t level, const char *msg) {
* printf("%s [%s]: %s\n",
* get_timestamp(),
* ulog_level_name(level),
* msg);
* }
*
* int main() {
* ULOG_INIT();
*
* // log to the console messages that are WARNING or more severe. You
* // can re-subscribe at any point to change the severity level.
* ULOG_SUBSCRIBE(my_console_logger, ULOG_WARNING);
*
* // log to a file messages that are DEBUG or more severe
* ULOG_SUBSCRIBE(my_file_logger, ULOG_DEBUG);
*
* int arg = 42;
* ULOG_INFO("Arg is %d", arg); // logs to file but not console
* }
*/
#ifndef ULOG_H_
#define ULOG_H_
#ifdef __cplusplus
extern "C" {
#endif
typedef enum {
ULOG_TRACE_LEVEL=100,
ULOG_DEBUG_LEVEL,
ULOG_INFO_LEVEL,
ULOG_WARNING_LEVEL,
ULOG_ERROR_LEVEL,
ULOG_CRITICAL_LEVEL,
ULOG_ALWAYS_LEVEL
} ulog_level_t;
// The following macros enable or disable uLog. If `ULOG_ENABLED` is
// defined at compile time, a macro such as `ULOG_INFO(...)` expands
// into `ulog_message(ULOG_INFO_LEVEL, ...)`. If `ULOG_ENABLED` is not
// defined, then the same macro expands into `do {} while(0)` and will
// not generate any code at all.
//
// There are two ways to enable uLog: you can uncomment the following
// line, or -- if it is commented out -- you can add -DULOG_ENABLED to
// your compiler switches.
#ifndef ULOG_ENABLED
#define ULOG_ENABLED
#endif
#ifdef ULOG_ENABLED
#define ULOG_INIT() ulog_init()
#define ULOG_SUBSCRIBE(a, b) ulog_subscribe(a, b)
#define ULOG_UNSUBSCRIBE(a) ulog_unsubscribe(a)
#define ULOG_LEVEL_NAME(a) ulog_level_name(a)
#define ULOG(...) ulog_message(__FILE__, __VA_ARGS__)
#define ULOG_TRACE(...) ulog_message(__FILE__, ULOG_TRACE_LEVEL, __VA_ARGS__)
#define ULOG_DEBUG(...) ulog_message(__FILE__, ULOG_DEBUG_LEVEL, __VA_ARGS__)
#define ULOG_INFO(...) ulog_message(__FILE__, ULOG_INFO_LEVEL, __VA_ARGS__)
#define ULOG_WARNING(...) ulog_message(__FILE__, ULOG_WARNING_LEVEL, __VA_ARGS__)
#define ULOG_ERROR(...) ulog_message(__FILE__, ULOG_ERROR_LEVEL, __VA_ARGS__)
#define ULOG_CRITICAL(...) ulog_message(__FILE__, ULOG_CRITICAL_LEVEL, __VA_ARGS__)
#define ULOG_ALWAYS(...) ulog_message(__FILE__, ULOG_ALWAYS_LEVEL, __VA_ARGS__)
#else
// uLog vanishes when disabled at compile time...
#define ULOG_INIT() do {} while(0)
#define ULOG_SUBSCRIBE(a, b) do {} while(0)
#define ULOG_UNSUBSCRIBE(a) do {} while(0)
#define ULOG_LEVEL_NAME(a) do {} while(0)
#define ULOG(s, f, ...) do {} while(0)
#define ULOG_TRACE(f, ...) do {} while(0)
#define ULOG_DEBUG(f, ...) do {} while(0)
#define ULOG_INFO(f, ...) do {} while(0)
#define ULOG_WARNING(f, ...) do {} while(0)
#define ULOG_ERROR(f, ...) do {} while(0)
#define ULOG_CRITICAL(f, ...) do {} while(0)
#define ULOG_ALWAYS(f, ...) do {} while(0)
#endif
typedef enum {
ULOG_ERR_NONE = 0,
ULOG_ERR_SUBSCRIBERS_EXCEEDED,
ULOG_ERR_NOT_SUBSCRIBED,
} ulog_err_t;
// define the maximum number of concurrent subscribers
#ifndef ULOG_MAX_SUBSCRIBERS
#define ULOG_MAX_SUBSCRIBERS 6
#endif
// maximum length of formatted log message
#ifndef ULOG_MAX_MESSAGE_LENGTH
#define ULOG_MAX_MESSAGE_LENGTH 120
#endif
/**
* @brief: prototype for uLog subscribers.
*/
typedef void (*ulog_function_t)(ulog_level_t severity, const char *filename, char *msg);
void ulog_init(void);
ulog_err_t ulog_subscribe(ulog_function_t fn, ulog_level_t threshold);
ulog_err_t ulog_unsubscribe(ulog_function_t fn);
const char *ulog_level_name(ulog_level_t level);
void ulog_message(const char *filename, ulog_level_t severity, const char *fmt, ...);
#ifdef __cplusplus
}
#endif
#endif /* ULOG_H_ */
+416
View File
@@ -0,0 +1,416 @@
#include <string.h>
#include "ulDatabase.h"
#include "ulStorage.h"
#include "ulog.h"
extern char _sccmram[]; // value exported by linker script
#define PAGE_START _sccmram // CCM RAM (to protect actual flash memory)
#define PAGE_SIZE 0x4000 // model 16KiB FLASH memory
#define MARKER_SAVE_BEGIN 0xAA
static uint32_t persistent_db_field_size;
// flash emulation section start
static bool flash_unlocked;
static void HAL_FLASH_Unlock(void)
{
flash_unlocked = 1;
}
static void HAL_FLASH_Lock(void)
{
flash_unlocked = 0;
}
enum Size {
FLASH_TYPEPROGRAM_BYTE
};
static void HAL_FLASH_Erase(void)
{
if (!flash_unlocked) {
ULOG_WARNING("Erase command on locked flash");
return;
}
memset((void *) PAGE_START, 0xFF, PAGE_SIZE);
}
static void HAL_FLASH_Program(enum Size s, const void * const addr, const uint64_t value)
{
(void) s;
if (!flash_unlocked) {
ULOG_WARNING("Write command on locked flash: %p <- 0x%02hhx", addr, (uint8_t) value);
return;
}
if ((addr >= (void *) (PAGE_START + PAGE_SIZE)) || (addr < (void *) PAGE_START)) {
ULOG_CRITICAL("OUT OF BOUNDS FLASH WRITE GENERATED");
ULOG_CRITICAL("TRIED TO WRITE VALUE 0x%02hhx TO ADDRESS %p", (uint8_t) value, addr);
return;
}
*(uint8_t *) addr = (uint8_t) value;
}
// flash emulation section finish
static uint32_t crc32(const uint8_t * const data, const uint32_t data_size, const uint32_t remainder)
{
register uint32_t reg_a = 0,
reg_b = 0;
static const uint32_t divisor = 0x04C11DB7;
uint32_t read_offset = 0;
uint32_t xor_ready = 0;
while ((data_size - read_offset) >= 4) {
reg_b = *(uint32_t *) &(data[read_offset]);
read_offset += 4;
for (unsigned int i = 0; i < 32; i++) {
// check if XOR can be done yet
xor_ready = reg_a & 0x80000000;
// shift in
reg_a <<= 1;
if (reg_b & 0x80000000)
reg_a |= 0x1;
reg_b <<= 1;
// XOR if ready
if (xor_ready)
reg_a ^= divisor;
}
}
if (data_size - read_offset != 0) {
// fill reg_b
for (unsigned int i = 0; i < (data_size - read_offset); i++) {
reg_b |= data[read_offset + i];
reg_b <<= 8;
}
reg_b <<= 8 * (3 - (data_size - read_offset));
// finish calculating main part
for (unsigned int i = 0; i < 8 * (data_size - read_offset); i++) {
// check if XOR can be done yet
xor_ready = reg_a & 0x80000000;
// shift in
reg_a <<= 1;
if (reg_b & 0x80000000)
reg_a |= 0x1;
reg_b <<= 1;
// XOR if ready
if (xor_ready)
reg_a ^= divisor;
}
}
// now finish with 32 bits of the remainder
reg_b = remainder;
// finish calculating main part
for (unsigned int i = 0; i < 32; i++) {
// check if XOR can be done yet
xor_ready = reg_a & 0x80000000;
// shift in
reg_a <<= 1;
if (reg_b & 0x80000000)
reg_a |= 0x1;
reg_b <<= 1;
// XOR if ready
if (xor_ready)
reg_a ^= divisor;
}
return reg_a;
}
static uint32_t crc32_calculate(const uint8_t * const data, const uint32_t data_size)
{
return crc32(data, data_size, 0);
}
static uint32_t crc32_verify(const uint8_t * const data, const uint32_t data_size, const uint32_t remainder)
{
return crc32(data, data_size, remainder);
}
static uint32_t ulStorage_get_save_size(void)
{
uint32_t persistent_fields_len = 0;
for (uint16_t i = 0; i < PARAM_COUNT; i++) {
struct ulDatabase_ParamMetadata *p = ulDatabase_getMetadata(i);
if (p == NULL) {
ULOG_ERROR("p == NULL, but parameter should exist (i = %hu, PARAM_COUNT = %hu); this is not possible, disabling ulStorage to prevent further damage",
i, (uint16_t) PARAM_COUNT);
return 0;
}
if (!p->persistent)
break;
switch (p->type) {
case INT8:
case UINT8:
persistent_fields_len += 1;
break;
case INT16:
case UINT16:
persistent_fields_len += 2;
break;
case INT32:
case UINT32:
case FLOAT:
persistent_fields_len += 4;
break;
}
}
return persistent_fields_len;
}
static bool ulStorage_verify_sector_header(void)
{
uint32_t sector_header = *(uint32_t *) PAGE_START;
// verify the sector is erased
if (sector_header & 0x80) {
ULOG_WARNING("Sector is not formatted: ERASED flag is 1");
return false;
}
// verify no invalid flags are present
if ((sector_header & 0x2F) != 0x2F) {
ULOG_WARNING("Sector is not formatted: garbage flags found");
return false;
}
// verify save size matches current persistent field size
if ((sector_header >> 20) != persistent_db_field_size) {
ULOG_WARNING("Save size does not match with current size");
return false;
}
// verify hash is not there yet
if ((sector_header & 0x000FFF00) != 0x000FFF00) {
ULOG_WARNING("Garbage found in HASH header field");
return false;
}
return true;
}
static uint8_t *ulStorage_find_first_free_block(void)
{
uint8_t *seek_head;
for (
seek_head = (uint8_t *) PAGE_START + 4;
(seek_head < (uint8_t *) (PAGE_START + PAGE_SIZE)) && (*seek_head != 0xFF);
seek_head += 1 + persistent_db_field_size + 4);
return seek_head;
}
static bool ulStorage_find_last_save(uint8_t **buffer)
{
if (!ulStorage_verify_sector_header())
return false;
uint8_t *seek_head = ulStorage_find_first_free_block();
// finding last valid save data
uint32_t save_checksum = 0xFFFFFFFF;
while ((seek_head > (uint8_t *) PAGE_START + 4) && save_checksum) {
seek_head -= 1 + persistent_db_field_size + 4;
ULOG_DEBUG("Verifying save hash for %p", seek_head);
save_checksum = crc32_verify(seek_head + 1, persistent_db_field_size, *(uint32_t *)(seek_head + 1 + persistent_db_field_size));
ULOG_DEBUG("Result: 0x%08X", save_checksum);
}
// if none found, stop
if (save_checksum) {
ULOG_WARNING("No valid saves found");
return false;
}
// otherwise set the correct pointer
*buffer = seek_head + 1;
return true;
}
static bool ulStorage_find_new_save_block(uint8_t ** block)
{
if (!ulStorage_verify_sector_header())
return false;
uint8_t *new_block = ulStorage_find_first_free_block();
if ((new_block + 1 + persistent_db_field_size + 4) >= (uint8_t *) (PAGE_START + PAGE_SIZE))
return false;
*block = new_block;
return true;
}
static void ulStorage_format_sector(void)
{
uint32_t new_header = 0xFFFFFFFF;
// mark ERASED bit
new_header &= 0xFFFFFF7F;
// mark save size
new_header &= (persistent_db_field_size << 20) | (0x000FFFFF);
// --- ENTER UNSAFE ZONE ---
HAL_FLASH_Unlock();
HAL_FLASH_Erase();
// write header to flash
HAL_FLASH_Program(FLASH_TYPEPROGRAM_BYTE, (void *) (PAGE_START + 0), (new_header >> 0) & 0xFF);
HAL_FLASH_Program(FLASH_TYPEPROGRAM_BYTE, (void *) (PAGE_START + 1), (new_header >> 8) & 0xFF);
HAL_FLASH_Program(FLASH_TYPEPROGRAM_BYTE, (void *) (PAGE_START + 2), (new_header >> 16) & 0xFF);
HAL_FLASH_Program(FLASH_TYPEPROGRAM_BYTE, (void *) (PAGE_START + 3), (new_header >> 24) & 0xFF);
HAL_FLASH_Lock();
// --- LEAVE UNSAFE ZONE ---
}
static void ulStorage_write_save(uint8_t * const write_at, const uint8_t * const save_data)
{
uint32_t checksum = crc32_calculate(save_data, persistent_db_field_size);
// --- ENTER UNSAFE ZONE ---
HAL_FLASH_Unlock();
HAL_FLASH_Program(FLASH_TYPEPROGRAM_BYTE, write_at, MARKER_SAVE_BEGIN);
for (uint32_t i = 0; i < persistent_db_field_size; i++)
HAL_FLASH_Program(FLASH_TYPEPROGRAM_BYTE, write_at + 1 + i, save_data[i]);
for (uint32_t i = 0; i < 4; i++)
HAL_FLASH_Program(FLASH_TYPEPROGRAM_BYTE, write_at + 1 + persistent_db_field_size + i, (checksum >> (8 * i)) & 0xFF);
HAL_FLASH_Lock();
// --- LEAVE UNSAFE ZONE ---
}
bool ulStorage_init(void)
{
persistent_db_field_size = ulStorage_get_save_size();
bool r = ulStorage_load();
if (r) {
ULOG_INFO("Loaded save from storage");
} else {
ULOG_INFO("Loading save from storage has failed");
}
return true;
}
bool ulStorage_load(void)
{
if (!persistent_db_field_size)
return true;
uint8_t *buffer;
if (!ulStorage_find_last_save(&buffer))
return false;
uint8_t *db_data = ulDatabase_freeze();
memcpy(db_data, buffer, persistent_db_field_size);
ulDatabase_unfreeze();
return true;
}
bool ulStorage_save(void)
{
if (!persistent_db_field_size)
return true;
// get a copy of persistent fields
uint8_t new_save_data[persistent_db_field_size];
uint8_t *db_data = ulDatabase_freeze();
memcpy(new_save_data, db_data, persistent_db_field_size);
ulDatabase_unfreeze();
// try to load last save
uint8_t *last_save_data;
if (ulStorage_find_last_save(&last_save_data))
if (!memcmp(new_save_data, last_save_data, persistent_db_field_size)) {
ULOG_INFO("Old save is valid and identical to a new one; not writing another block");
return true;
}
// write a new save
uint8_t *new_save_address;
if (!ulStorage_find_new_save_block(&new_save_address)) {
// the storage is not formatted or is full - either way needs formatting
ULOG_INFO("Sector is full or not formatted; formatting the sector and writing new save");
ulStorage_format_sector();
ulStorage_write_save((uint8_t *) (PAGE_START + 4), new_save_data);
} else {
ULOG_INFO("Writing new save to %p", new_save_address);
ulStorage_write_save(new_save_address, new_save_data);
}
return true;
}
bool ulStorage_erase(void)
{
if (!persistent_db_field_size)
return true;
ulStorage_format_sector();
return true;
}
bool ulStorage_factoryReset(void)
{
for (uint16_t i = 0; ulDatabase_reset(i); i++);
if (!persistent_db_field_size)
return true;
ulStorage_format_sector();
return true;
}
+12
View File
@@ -0,0 +1,12 @@
#ifndef __ULSTORAGE_H
#define __ULSTORAGE_H
#include <stdbool.h>
bool ulStorage_init(void);
bool ulStorage_load(void);
bool ulStorage_save(void);
bool ulStorage_erase(void);
bool ulStorage_factoryReset(void);
#endif /* __ULSTORAGE_H */