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
+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);