36 Commits

Author SHA1 Message Date
93870fb725 fixed binfile hole 2024-08-13 05:14:01 +02:00
207b91460d update proto with display messages 2024-08-13 05:09:12 +02:00
6094e7b0e7 added display messages 2024-08-13 05:07:40 +02:00
b02f4af38d using LPUART to forward Bluetooth messages ! 2024-08-10 03:28:37 +02:00
8e3b1526aa new lpuart config for Bluetooth RX 2024-08-06 00:05:05 +02:00
8c209ac6aa added glasm 2024-06-04 18:59:05 +02:00
9925b7a686 moved config file for CI 2024-06-04 13:38:34 +02:00
68193b096c Add MLZR_GLASM submodule to Application 2024-06-04 03:23:35 +02:00
1e0fd80f5c added MLZR_Comm 2024-06-03 22:04:46 +02:00
41cc7a9ff6 display current ambientlight 2024-06-02 02:26:33 +02:00
f263896cbf update proto 2024-06-02 02:10:45 +02:00
d8e27df3fe added a way to readout the current value 2024-06-02 02:05:31 +02:00
be0ce6dee5 now using cls-build container for faster builds 2024-05-30 04:04:57 +02:00
0798ec40c1 added ambient light to can bus 2024-05-29 04:01:55 +02:00
4724da0455 new version 2024-05-29 03:36:18 +02:00
13002071d7 added passthouth off headlight settings messages 2024-05-29 03:28:16 +02:00
8d02489b16 fix CI compile 2024-05-28 04:56:24 +02:00
452246951b fixed error on can parsing 2024-05-28 04:55:31 +02:00
eb5733da97 added new signal 2024-05-28 04:21:39 +02:00
766d5e9ca8 refactor Functions to group everything connected to the vehicle to a central location 2024-05-28 03:52:03 +02:00
9c489c1a25 disable_sd_log 2024-05-24 16:08:01 +02:00
d0544576a3 Master is now using the same FW_Update Methode as the Slaves 2024-05-24 01:58:53 +02:00
66e04c6e06 adjusted dimming only when deadlight is on 2024-05-23 23:08:29 +02:00
9b49028c20 fixed issue during provisoning 2024-05-23 21:40:00 +02:00
13c6a71af6 added more CarCan Messages 2024-05-23 14:00:56 +02:00
c7d6ba78d5 issue hardfault try 2024-05-23 02:15:36 +02:00
804c4c8c69 Using RAM_D3 start as flag for system_bootloader 2024-05-23 00:10:06 +02:00
a91fdc9311 update proto 2024-05-22 21:41:26 +02:00
fd3757b6a1 added jump_to_systembootloader 2024-05-22 21:37:25 +02:00
2b12ea9602 trying to improve stabiltiy 2024-05-22 02:39:18 +02:00
e892a21f97 addded missing requests 2024-05-21 23:30:27 +02:00
1a1e4bbee4 fixed missing header 2024-05-21 23:00:14 +02:00
c3322ed571 fixed sd_logger 2024-05-21 22:51:32 +02:00
bd8779b5aa added loggint to SD card 2024-05-21 22:18:05 +02:00
04c5eb047e Locking the car will shutdown the system 2024-05-21 22:17:47 +02:00
1d7ad7dc31 fixed bug not going to standby correctly 2024-05-21 22:17:03 +02:00
61 changed files with 1709 additions and 264 deletions

View File

@@ -23,7 +23,7 @@
<option id="com.st.stm32cube.ide.mcu.gnu.managedbuild.option.fpu.116246094" name="Floating-point unit" superClass="com.st.stm32cube.ide.mcu.gnu.managedbuild.option.fpu" value="com.st.stm32cube.ide.mcu.gnu.managedbuild.option.fpu.value.fpv5-d16" valueType="enumerated"/>
<option id="com.st.stm32cube.ide.mcu.gnu.managedbuild.option.floatabi.1041462468" name="Floating-point ABI" superClass="com.st.stm32cube.ide.mcu.gnu.managedbuild.option.floatabi" value="com.st.stm32cube.ide.mcu.gnu.managedbuild.option.floatabi.value.hard" valueType="enumerated"/>
<option id="com.st.stm32cube.ide.mcu.gnu.managedbuild.option.target_board.1294249446" name="Board" superClass="com.st.stm32cube.ide.mcu.gnu.managedbuild.option.target_board" value="genericBoard" valueType="string"/>
<option id="com.st.stm32cube.ide.mcu.gnu.managedbuild.option.defaults.19322524" name="Defaults" superClass="com.st.stm32cube.ide.mcu.gnu.managedbuild.option.defaults" value="com.st.stm32cube.ide.common.services.build.inputs.revA.1.0.6 || Debug || true || Executable || com.st.stm32cube.ide.mcu.gnu.managedbuild.option.toolchain.value.workspace || STM32H723VGTx || 0 || 0 || arm-none-eabi- || ${gnu_tools_for_stm32_compiler_path} || ../Core/Inc | ../FATFS/Target | ../FATFS/App | ../USB_DEVICE/App | ../USB_DEVICE/Target | ../Drivers/STM32H7xx_HAL_Driver/Inc | ../Drivers/STM32H7xx_HAL_Driver/Inc/Legacy | ../Middlewares/Third_Party/FreeRTOS/Source/include | ../Middlewares/Third_Party/FreeRTOS/Source/CMSIS_RTOS_V2 | ../Middlewares/Third_Party/FreeRTOS/Source/portable/GCC/ARM_CM4F | ../Middlewares/Third_Party/FatFs/src | ../Middlewares/ST/STM32_USB_Device_Library/Core/Inc | ../Middlewares/ST/STM32_USB_Device_Library/Class/CDC/Inc | ../Drivers/CMSIS/Device/ST/STM32H7xx/Include | ../Drivers/CMSIS/Include || || || USE_FULL_LL_DRIVER | USE_HAL_DRIVER | STM32H723xx || || EEPROM | Drivers | Core/Startup | Middlewares | Core | FATFS | USB_DEVICE || || || ${workspace_loc:/${ProjName}/STM32H723VGTX_FLASH.ld} || true || NonSecure || || secure_nsclib.o || || None || || || " valueType="string"/>
<option id="com.st.stm32cube.ide.mcu.gnu.managedbuild.option.defaults.19322524" name="Defaults" superClass="com.st.stm32cube.ide.mcu.gnu.managedbuild.option.defaults" value="com.st.stm32cube.ide.common.services.build.inputs.revA.1.0.6 || Debug || true || Executable || com.st.stm32cube.ide.mcu.gnu.managedbuild.option.toolchain.value.workspace || STM32H723VGTx || 0 || 0 || arm-none-eabi- || ${gnu_tools_for_stm32_compiler_path} || ../Core/Inc | ../FATFS/Target | ../FATFS/App | ../USB_DEVICE/App | ../USB_DEVICE/Target | ../Drivers/STM32H7xx_HAL_Driver/Inc | ../Drivers/STM32H7xx_HAL_Driver/Inc/Legacy | ../Middlewares/Third_Party/FreeRTOS/Source/include | ../Middlewares/Third_Party/FreeRTOS/Source/CMSIS_RTOS_V2 | ../Middlewares/Third_Party/FreeRTOS/Source/portable/GCC/ARM_CM4F | ../Middlewares/Third_Party/FatFs/src | ../Middlewares/ST/STM32_USB_Device_Library/Core/Inc | ../Middlewares/ST/STM32_USB_Device_Library/Class/CDC/Inc | ../Drivers/CMSIS/Device/ST/STM32H7xx/Include | ../Drivers/CMSIS/Include || || || USE_FULL_LL_DRIVER | USE_HAL_DRIVER | STM32H723xx || || Drivers | Core/Startup | Middlewares | Core | FATFS | USB_DEVICE || || || ${workspace_loc:/${ProjName}/STM32H723VGTX_FLASH.ld} || true || NonSecure || || secure_nsclib.o || || None || || || " valueType="string"/>
<option id="com.st.stm32cube.ide.mcu.debug.option.cpuclock.784195808" superClass="com.st.stm32cube.ide.mcu.debug.option.cpuclock" value="275" valueType="string"/>
<targetPlatform archList="all" binaryParser="org.eclipse.cdt.core.ELF" id="com.st.stm32cube.ide.mcu.gnu.managedbuild.targetplatform.550567667" isAbstract="false" osList="all" superClass="com.st.stm32cube.ide.mcu.gnu.managedbuild.targetplatform"/>
<builder buildPath="${workspace_loc:/CLS_Master}/Debug" id="com.st.stm32cube.ide.mcu.gnu.managedbuild.builder.1667139540" keepEnvironmentInBuildfile="false" managedBuildOn="true" name="Gnu Make Builder" parallelBuildOn="true" parallelizationNumber="optimal" superClass="com.st.stm32cube.ide.mcu.gnu.managedbuild.builder"/>
@@ -85,7 +85,6 @@
</toolChain>
</folderInfo>
<sourceEntries>
<entry flags="VALUE_WORKSPACE_PATH|RESOLVED" kind="sourcePath" name="EEPROM"/>
<entry flags="VALUE_WORKSPACE_PATH|RESOLVED" kind="sourcePath" name="Core"/>
<entry flags="VALUE_WORKSPACE_PATH|RESOLVED" kind="sourcePath" name="FATFS"/>
<entry flags="VALUE_WORKSPACE_PATH|RESOLVED" kind="sourcePath" name="Middlewares"/>
@@ -118,7 +117,7 @@
<option id="com.st.stm32cube.ide.mcu.gnu.managedbuild.option.fpu.315263605" superClass="com.st.stm32cube.ide.mcu.gnu.managedbuild.option.fpu" value="com.st.stm32cube.ide.mcu.gnu.managedbuild.option.fpu.value.fpv5-d16" valueType="enumerated"/>
<option id="com.st.stm32cube.ide.mcu.gnu.managedbuild.option.floatabi.861723814" superClass="com.st.stm32cube.ide.mcu.gnu.managedbuild.option.floatabi" value="com.st.stm32cube.ide.mcu.gnu.managedbuild.option.floatabi.value.hard" valueType="enumerated"/>
<option id="com.st.stm32cube.ide.mcu.gnu.managedbuild.option.target_board.575901382" superClass="com.st.stm32cube.ide.mcu.gnu.managedbuild.option.target_board" value="genericBoard" valueType="string"/>
<option id="com.st.stm32cube.ide.mcu.gnu.managedbuild.option.defaults.41596049" superClass="com.st.stm32cube.ide.mcu.gnu.managedbuild.option.defaults" value="com.st.stm32cube.ide.common.services.build.inputs.revA.1.0.6 || Release || false || Executable || com.st.stm32cube.ide.mcu.gnu.managedbuild.option.toolchain.value.workspace || STM32H723VGTx || 0 || 0 || arm-none-eabi- || ${gnu_tools_for_stm32_compiler_path} || ../Core/Inc | ../FATFS/Target | ../FATFS/App | ../USB_DEVICE/App | ../USB_DEVICE/Target | ../Drivers/STM32H7xx_HAL_Driver/Inc | ../Drivers/STM32H7xx_HAL_Driver/Inc/Legacy | ../Middlewares/Third_Party/FreeRTOS/Source/include | ../Middlewares/Third_Party/FreeRTOS/Source/CMSIS_RTOS_V2 | ../Middlewares/Third_Party/FreeRTOS/Source/portable/GCC/ARM_CM4F | ../Middlewares/Third_Party/FatFs/src | ../Middlewares/ST/STM32_USB_Device_Library/Core/Inc | ../Middlewares/ST/STM32_USB_Device_Library/Class/CDC/Inc | ../Drivers/CMSIS/Device/ST/STM32H7xx/Include | ../Drivers/CMSIS/Include || || || USE_FULL_LL_DRIVER | USE_HAL_DRIVER | STM32H723xx || || EEPROM | Drivers | Core/Startup | Middlewares | Core | FATFS | USB_DEVICE || || || ${workspace_loc:/${ProjName}/STM32H723VGTX_FLASH.ld} || true || NonSecure || || secure_nsclib.o || || None || || || " valueType="string"/>
<option id="com.st.stm32cube.ide.mcu.gnu.managedbuild.option.defaults.41596049" superClass="com.st.stm32cube.ide.mcu.gnu.managedbuild.option.defaults" value="com.st.stm32cube.ide.common.services.build.inputs.revA.1.0.6 || Release || false || Executable || com.st.stm32cube.ide.mcu.gnu.managedbuild.option.toolchain.value.workspace || STM32H723VGTx || 0 || 0 || arm-none-eabi- || ${gnu_tools_for_stm32_compiler_path} || ../Core/Inc | ../FATFS/Target | ../FATFS/App | ../USB_DEVICE/App | ../USB_DEVICE/Target | ../Drivers/STM32H7xx_HAL_Driver/Inc | ../Drivers/STM32H7xx_HAL_Driver/Inc/Legacy | ../Middlewares/Third_Party/FreeRTOS/Source/include | ../Middlewares/Third_Party/FreeRTOS/Source/CMSIS_RTOS_V2 | ../Middlewares/Third_Party/FreeRTOS/Source/portable/GCC/ARM_CM4F | ../Middlewares/Third_Party/FatFs/src | ../Middlewares/ST/STM32_USB_Device_Library/Core/Inc | ../Middlewares/ST/STM32_USB_Device_Library/Class/CDC/Inc | ../Drivers/CMSIS/Device/ST/STM32H7xx/Include | ../Drivers/CMSIS/Include || || || USE_FULL_LL_DRIVER | USE_HAL_DRIVER | STM32H723xx || || Drivers | Core/Startup | Middlewares | Core | FATFS | USB_DEVICE || || || ${workspace_loc:/${ProjName}/STM32H723VGTX_FLASH.ld} || true || NonSecure || || secure_nsclib.o || || None || || || " valueType="string"/>
<option id="com.st.stm32cube.ide.mcu.debug.option.cpuclock.669660917" superClass="com.st.stm32cube.ide.mcu.debug.option.cpuclock" value="275" valueType="string"/>
<targetPlatform archList="all" binaryParser="org.eclipse.cdt.core.ELF" id="com.st.stm32cube.ide.mcu.gnu.managedbuild.targetplatform.62262984" isAbstract="false" osList="all" superClass="com.st.stm32cube.ide.mcu.gnu.managedbuild.targetplatform"/>
<builder buildPath="${workspace_loc:/CLS_Master}/Release" id="com.st.stm32cube.ide.mcu.gnu.managedbuild.builder.1586300933" managedBuildOn="true" name="Gnu Make Builder.Release" parallelBuildOn="true" parallelizationNumber="optimal" superClass="com.st.stm32cube.ide.mcu.gnu.managedbuild.builder"/>
@@ -176,7 +175,6 @@
</toolChain>
</folderInfo>
<sourceEntries>
<entry flags="VALUE_WORKSPACE_PATH|RESOLVED" kind="sourcePath" name="EEPROM"/>
<entry flags="VALUE_WORKSPACE_PATH|RESOLVED" kind="sourcePath" name="Core"/>
<entry flags="VALUE_WORKSPACE_PATH|RESOLVED" kind="sourcePath" name="FATFS"/>
<entry flags="VALUE_WORKSPACE_PATH|RESOLVED" kind="sourcePath" name="Middlewares"/>

View File

@@ -4,11 +4,11 @@ on: [push]
jobs:
Build-Release:
runs-on: ubuntu-latest
runs-on: cls-build
steps:
- name: Install dependencies
run: apt-get update && apt-get install -y gcc-arm-none-eabi binutils-arm-none-eabi ninja-build cmake protobuf-compiler python3 python3-grpcio python3-protobuf python3-pkg-resources
#- name: Install dependencies
# run: apt-get update && apt-get install -y gcc-arm-none-eabi binutils-arm-none-eabi ninja-build cmake protobuf-compiler python3 python3-grpcio python3-protobuf python3-pkg-resources python3-requests
# run: pip install setuptools
- name: Check out repository code
uses: actions/checkout@v4
@@ -31,4 +31,9 @@ jobs:
name: firmware
path: |
build/*.hex
build/*.bin
build/*.bin
- name: Upload Firmware
env:
SERVER_KEY: ${{ secrets.SERVER_KEY }}
run: python3 tools/upload_firmware.py $SERVER_KEY

9
.gitmodules vendored
View File

@@ -19,3 +19,12 @@
[submodule "proto"]
path = proto
url = git@git.lan:oliver/cls-proto.git
[submodule "lib/TinyFrame"]
path = lib/TinyFrame
url = https://github.com/MightyPork/TinyFrame.git
[submodule "Application/MLZR_Comm"]
path = Application/MLZR_Comm
url = git@git.lan:ODDIY/MLZR_Comm.git
[submodule "Application/MLZR_GLASM"]
path = Application/MLZR_GLASM
url = git@git.lan:ODDIY/MLZR_GLASM.git

File diff suppressed because one or more lines are too long

27
.vscode/launch.json vendored
View File

@@ -44,6 +44,33 @@
//"armToolchainPath": "c:\\ST\\STM32CubeIDE_1.7.0\\STM32CubeIDE\\plugins\\com.st.stm32cube.ide.mcu.externaltools.gnu-tools-for-stm32.9-2020-q2-update.win32_2.0.0.202105311346\\tools\\bin",
//"stm32cubeprogrammer": "c:\\Program Files\\STMicroelectronics\\STM32Cube\\STM32CubeProgrammer\\bin",
/* If you use external loader, add additional arguments */
//"serverArgs": ["--extload", "path/to/ext/loader.stldr"],
},
{
"name": "Attach Microcontroller - ST-Link",
"cwd": "${workspaceFolder}",
"type": "cortex-debug",
"executable": "${command:cmake.launchTargetPath}", //or fixed file path: build/stm32h735g-dk-led.elf
"request": "attach", //Use "attach" to connect to target w/o elf download
"servertype": "stlink",
"device": "STM32H723VGT", //MCU used, ex. "STM32H735IG"
"interface": "swd",
"serialNumber": "002800223232511939353236", //Set ST-Link ID if you use multiple at the same time
"runToEntryPoint": "main",
"svdFile": "STM32H723.svd", //Path to SVD file to see registers
"v1": false,
"showDevDebugOutput": "both",
"liveWatch": {
"enabled": true,
"samplesPerSecond": 4
}
/* Will get automatically detected if STM32CubeIDE is installed to default directory
or it can be manually provided if necessary.. */
//"serverpath": "c:\\ST\\STM32CubeIDE_1.7.0\\STM32CubeIDE\\plugins\\com.st.stm32cube.ide.mcu.externaltools.stlink-gdb-server.win32_2.0.100.202109301221\\tools\\bin\\ST-LINK_gdbserver.exe",
//"armToolchainPath": "c:\\ST\\STM32CubeIDE_1.7.0\\STM32CubeIDE\\plugins\\com.st.stm32cube.ide.mcu.externaltools.gnu-tools-for-stm32.9-2020-q2-update.win32_2.0.0.202105311346\\tools\\bin",
//"stm32cubeprogrammer": "c:\\Program Files\\STMicroelectronics\\STM32Cube\\STM32CubeProgrammer\\bin",
/* If you use external loader, add additional arguments */
//"serverArgs": ["--extload", "path/to/ext/loader.stldr"],
}

View File

@@ -47,7 +47,7 @@ void BSP_ADC_Start()
void HAL_ADC_ConvHalfCpltCallback(ADC_HandleTypeDef* hadc)
{
/* Invalidate Data Cache to get the updated content of the SRAM on the first half of the ADC converted data buffer: 32 bytes */
SCB_InvalidateDCache_by_Addr((uint32_t *) &aADCxConvertedData[0], ADC_CONVERTED_DATA_BUFFER_SIZE);
//SCB_InvalidateDCache_by_Addr((uint32_t *) &aADCxConvertedData[0], ADC_CONVERTED_DATA_BUFFER_SIZE);
}
/**
@@ -58,7 +58,7 @@ void HAL_ADC_ConvHalfCpltCallback(ADC_HandleTypeDef* hadc)
void HAL_ADC_ConvCpltCallback(ADC_HandleTypeDef* hadc)
{
/* Invalidate Data Cache to get the updated content of the SRAM on the second half of the ADC converted data buffer: 32 bytes */
SCB_InvalidateDCache_by_Addr((uint32_t *) &aADCxConvertedData[ADC_CONVERTED_DATA_BUFFER_SIZE/2], ADC_CONVERTED_DATA_BUFFER_SIZE);
//SCB_InvalidateDCache_by_Addr((uint32_t *) &aADCxConvertedData[ADC_CONVERTED_DATA_BUFFER_SIZE/2], ADC_CONVERTED_DATA_BUFFER_SIZE);
}

View File

@@ -10,12 +10,14 @@
#include "cmsis_os2.h"
#include "BSP_GPIO.h"
#include "BSP_ADC.h"
#include "BSP_SDLogger.h"
#define LPTIM_CLK 500 // Hz
#define SLEEP_TICK_TIME 1 // seconds to wait
#define STAY_AWAKE_TIME 60 // seconds to stay awake without K15
bool CanDataTask_CarCanActive();
// Start the sleep counter check
void BSP_POWER_Init() {
@@ -52,6 +54,15 @@ void BSP_POWER_WakeUp() {
*/
void BSP_POWER_EnterStandby() {
// if there is still communication on the CAN bus, we should not go to standby
// intstead we should reset the system, because the CAN bus would wake us up again
if (CanDataTask_CarCanActive()) {
NVIC_SystemReset();
}
// stop the sytem interrupts
__disable_irq();
// We need to disable all Periperals to minimize parasitic currents
HAL_I2C_DeInit(&hi2c1);
HAL_I2C_MspDeInit(&hi2c1);
@@ -108,6 +119,13 @@ void BSP_POWER_EnterStandby() {
/* Enter the Standby mode */
HAL_PWR_EnterSTANDBYMode();
while (1)
{
// if we are here, something went wrong
NVIC_SystemReset();
Error_Handler();
}
}
uint32_t sec_without_k15 = 0;

View File

@@ -0,0 +1,110 @@
#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);
}

View File

@@ -1,4 +1,14 @@
// SD logger steam is logged to sd card
// buffernd logger collect logs until some amount of data is collected.
// needs to be flushed before shutdown
// used with ULOG
// used with ULOG
#include <stdint.h>
#include <stddef.h>
void BSP_SDLogger_Init(int log_number);
void BSP_SDLogger_Write(char *data, size_t length);
void BSP_SDLogger_Flush();

View File

@@ -5,6 +5,7 @@ BSP_INA.c
BSP_POWER.c
BSP_GPIO.c
BSP_ADC.c
BSP_SDLogger.c
)
target_include_directories(BSP PUBLIC ./)

View File

@@ -1,4 +1,5 @@
#include "CLS_BSP.h"
#include "CLSAddress.h"
#ifdef CLS_BSP_FDCAN
@@ -25,6 +26,31 @@ HAL_StatusTypeDef CLS_BSP_CAN_SetUniversalFilter(const CLS_BSP_CAN_UniversalFilt
#endif
uint8_t CLS_BSP_DLC_ToBytes(uint32_t dlc) {
switch (dlc) {
case CLS_BSP_DLC_BYTES_1:
return 1;
case CLS_BSP_DLC_BYTES_2:
return 2;
case CLS_BSP_DLC_BYTES_3:
return 3;
case CLS_BSP_DLC_BYTES_4:
return 4;
case CLS_BSP_DLC_BYTES_5:
return 5;
case CLS_BSP_DLC_BYTES_6:
return 6;
case CLS_BSP_DLC_BYTES_7:
return 7;
case CLS_BSP_DLC_BYTES_8:
return 8;
default:
return 0;
}
}
CLS_Type_t CLS_BSP_GetDeviceType(void) {
return cls_device_Type_MASTER;
@@ -42,4 +68,9 @@ CLS_Position_t CLS_BSP_GetPosition(void) {
}
void CLS_BSP_SetPosition(CLS_Position_t position) {
}
}
#include "BSP_GPIO.h"

View File

@@ -30,6 +30,9 @@ typedef FDCAN_TxHeaderTypeDef CLS_BSP_TxHeaderType;
#define CLS_BSP_DLC_BYTES_7 FDCAN_DLC_BYTES_7
#define CLS_BSP_DLC_BYTES_8 FDCAN_DLC_BYTES_8
// function to convert DLC to bytes
uint8_t CLS_BSP_DLC_ToBytes(uint32_t dlc);
#define CLS_CAN_FILTER_DISABLE FDCAN_FILTER_DISABLE
#define CLS_CAN_FILTER_TO_RXFIFO0 FDCAN_FILTER_TO_RXFIFO0
#define CLS_CAN_FILTER_TO_RXFIFO1 FDCAN_FILTER_TO_RXFIFO1

View File

@@ -12,4 +12,4 @@ target_sources(${PROJECT_NAME}
)
target_include_directories(${PROJECT_NAME} PUBLIC ${CMAKE_CURRENT_LIST_DIR})
target_link_libraries(${PROJECT_NAME} PRIVATE CLS)
target_link_libraries(${PROJECT_NAME} PRIVATE CLS BSP Vehicle)

View File

@@ -1,4 +1,10 @@
include_directories(MLZR_Comm_Conf)
add_subdirectory(Tasks)
add_subdirectory(CLS)
add_subdirectory(CLS_BSP)
add_subdirectory(BSP)
add_subdirectory(BSP)
add_subdirectory(ram_loader)
add_subdirectory(MLZR_GLASM)
add_subdirectory(MLZR_Comm)
add_subdirectory(Vehicle)

1
Application/MLZR_Comm Submodule

Submodule Application/MLZR_Comm added at baa031e9c3

View File

@@ -0,0 +1,14 @@
// Define macros for UART and DMA configurations
#define MAIN_UART USART1
#define MAIN_DMA_RX 1
#define MAIN_DMA_RX_CHANNEL 0
#define MAIN_DMA_TX 1
#define MAIN_DMA_TX_CHANNEL 1
#define HALF_UART USART3
#define HALF_DMA_RX 1
#define HALF_DMA_RX_CHANNEL 2
#define HALF_DMA_TX 1
#define HALF_DMA_TX_CHANNEL 3
#define DMA_MEM_ATTR __attribute__((section(".data")))

View File

@@ -12,6 +12,9 @@ target_sources(${PROJECT_NAME}
${CMAKE_CURRENT_LIST_DIR}/FirmwareUpdate.c
${CMAKE_CURRENT_LIST_DIR}/LightTask.c
${CMAKE_CURRENT_LIST_DIR}/LightState.c
${CMAKE_CURRENT_LIST_DIR}/Headlight_can.c
${CMAKE_CURRENT_LIST_DIR}/DisplayComm.c
INTERFACE
${CMAKE_CURRENT_LIST_DIR}/UsbDataHandler.h
${CMAKE_CURRENT_LIST_DIR}/CanDataTask.h
@@ -22,4 +25,4 @@ target_sources(${PROJECT_NAME}
target_include_directories(${PROJECT_NAME} INTERFACE ${CMAKE_CURRENT_LIST_DIR})
target_link_libraries(${PROJECT_NAME} PUBLIC PROTOS CLS)
target_link_libraries(${PROJECT_NAME} PRIVATE Revision CLS_BSP BSP ulog)
target_link_libraries(${PROJECT_NAME} PRIVATE Revision CLS_BSP BSP ulog Vehicle ram_loader mlzr_comm TinyFrame)

View File

@@ -9,6 +9,9 @@
#include "usb.pb.h"
#include "version_info.h"
#include "ulog.h"
#include "BSP_POWER.h"
#include "BSP_GPIO.h"
#include "Vehicle.h"
// Define thread flags
#define FLAG_FDCAN_RX_FIFO0 (1<<0)
#define FLAG_FDCAN_RX_FIFO1 (1<<1)
@@ -31,7 +34,7 @@ const osThreadAttr_t CanDataTask_attr = {
// Memory for the task
StaticTask_t CarCanTask_cb;
uint32_t CarCanTask_stk[256];
uint32_t CarCanTask_stk[512];
// Attributes for the task
osThreadId_t CarCanTask_id;
const osThreadAttr_t CarCanTask_attr = {
@@ -44,7 +47,7 @@ const osThreadAttr_t CarCanTask_attr = {
.priority = osPriorityNormal,
};
static uint64_t last_car_message_time = 0;
uint32_t dlcDecode(uint32_t dlcCode) {
switch(dlcCode) {
@@ -128,7 +131,6 @@ void CanDataTask_func(void *argument) {
}
}
static uint64_t last_car_message_time = UINT64_MAX;
// convert byte to 2 hex characters
void byteToHex(uint8_t byte, char * hex) {
@@ -137,13 +139,22 @@ void byteToHex(uint8_t byte, char * hex) {
hex[1] = hexLookup[byte & 0x0F];
}
static FDCAN_RxHeaderTypeDef RxHeader = {0};
static uint8_t RxData[8] = {0};
void CarCanTask_func(void *argument) {
// for testing accept all messages from the car can bus
// put unkown messages in fifo 0
if (HAL_FDCAN_ConfigGlobalFilter(&hfdcan2, FDCAN_ACCEPT_IN_RX_FIFO0, FDCAN_ACCEPT_IN_RX_FIFO0, FDCAN_REJECT_REMOTE, FDCAN_REJECT_REMOTE) != HAL_OK) {
Error_Handler();
}
Vehicle_Setup_CAN();
/* Start the FDCAN module */
if (HAL_FDCAN_Start(&hfdcan2) != HAL_OK){
Error_Handler();
@@ -153,8 +164,7 @@ void CarCanTask_func(void *argument) {
Error_Handler();
}
FDCAN_RxHeaderTypeDef RxHeader;
uint8_t RxData[8];
for(;;) {
// wait for interrupt event on any fifo
@@ -166,7 +176,7 @@ void CarCanTask_func(void *argument) {
} else {
// do something with the can data
last_car_message_time = osKernelGetTickCount();
//last_car_message_time = osKernelGetTickCount();
char msg[17] = {0};
switch (RxHeader.DataLength)
@@ -230,7 +240,7 @@ void CarCanTask_func(void *argument) {
break;
}
ULOG_DEBUG("Car MSG: %x, %d %s", RxHeader.Identifier, RxHeader.DataLength, msg);
//ULOG_DEBUG("Car MSG: %x, %d %s", RxHeader.Identifier,CLS_BSP_DLC_ToBytes(RxHeader.DataLength) , msg);
}
}
@@ -239,9 +249,9 @@ void CarCanTask_func(void *argument) {
Error_Handler();
} else {
// do something with the can data
last_car_message_time = osKernelGetTickCount();
Vehicle_Receive_CAN(RxHeader, RxData);
//ULOG_DEBUG("Used Car MSG: %x, %d %s", RxHeader.Identifier, CLS_BSP_DLC_ToBytes(RxHeader.DataLength), msg );
}
}
}
@@ -253,10 +263,18 @@ void CarCanTask_func(void *argument) {
* @return true if a car can message has been received
* @return false if no car can message has been received
*/
bool CanDataTask_gotCarCanMessage() {
return last_car_message_time != UINT64_MAX;
bool CanDataTask_CarCanActive() {
if (last_car_message_time == 0) {
return false;
}
return osKernelGetTickCount() - last_car_message_time < 1000;
}
void HAL_FDCAN_RxFifo0Callback(FDCAN_HandleTypeDef *hfdcan, uint32_t RxFifo0ITs) {
// Notify the thread
if(hfdcan == &hfdcan1) {
@@ -264,8 +282,15 @@ void HAL_FDCAN_RxFifo0Callback(FDCAN_HandleTypeDef *hfdcan, uint32_t RxFifo0ITs)
}
if(hfdcan == &hfdcan2) {
osThreadFlagsSet(CarCanTask_id, FLAG_FDCAN_RX_FIFO0);
last_car_message_time = osKernelGetTickCount();
while (HAL_FDCAN_GetRxFifoFillLevel(&hfdcan2, FDCAN_RX_FIFO0) > 0 ) {
FDCAN_RxHeaderTypeDef RxHeader;
uint8_t RxData[8];
HAL_FDCAN_GetRxMessage(&hfdcan2, FDCAN_RX_FIFO0, &RxHeader, RxData);
//ignore the message for now
}
//osThreadFlagsSet(CarCanTask_id, FLAG_FDCAN_RX_FIFO0);
}
}
@@ -276,6 +301,7 @@ void HAL_FDCAN_RxFifo1Callback(FDCAN_HandleTypeDef *hfdcan, uint32_t RxFifo1ITs)
}
if(hfdcan == &hfdcan2) {
last_car_message_time = osKernelGetTickCount();
osThreadFlagsSet(CarCanTask_id, FLAG_FDCAN_RX_FIFO1);
}
}
@@ -292,10 +318,9 @@ extern uint8_t gCLS_DEVICE_ADDRESS;
void DataClbk_cls_device_RequestList(void* msg, uint32_t length) {
memset(&list,0,sizeof(list));
// add yourself
CLS_Position_t position = CLS_BSP_GetPosition();
CLS_Type_t type = CLS_BSP_GetDeviceType();
list.devices[list.devices_count].available = true;
list.devices[list.devices_count].canid = GENERATE_CLS_ADDRESS(CLS_CODE_STATUS, gCLS_DEVICE_ADDRESS, CLS_CH_STA_HEATBEAT);
list.devices[list.devices_count].device = gCLS_DEVICE_ADDRESS;
@@ -307,7 +332,21 @@ void DataClbk_cls_device_RequestList(void* msg, uint32_t length) {
list.devices[list.devices_count].fw_version[1] = VERSION_INFO.patch;
list.devices[list.devices_count].fw_version[2] = VERSION_INFO.minor;
list.devices[list.devices_count].fw_version[3] = VERSION_INFO.major;
list.devices_count++;
//add display
list.devices[list.devices_count].available = true;
list.devices[list.devices_count].canid = GENERATE_CLS_ADDRESS(CLS_CODE_STATUS, gCLS_DEVICE_ADDRESS+1, CLS_CH_STA_HEATBEAT);
list.devices[list.devices_count].device = gCLS_DEVICE_ADDRESS+1;
list.devices[list.devices_count].type = cls_device_Type_DISPLAY; // enum to uint
list.devices[list.devices_count].position[0] = position.p0;
list.devices[list.devices_count].position[1] = position.p1;
list.devices[list.devices_count].position_count = 2;
list.devices[list.devices_count].fw_version[0] = 0;
list.devices[list.devices_count].fw_version[1] = 0;
list.devices[list.devices_count].fw_version[2] = 0;
list.devices[list.devices_count].fw_version[3] = 0;
list.devices_count++;
for (size_t i = 0; i < 16; i++)

View File

@@ -1,6 +1,14 @@
#pragma once
#include "stdbool.h"
void CanDataTask_start();
bool CanDataTask_gotCarCanMessage();
bool CanDataTask_gotCarCanMessage();
bool CanDataTask_CarCanActive();
uint8_t CanDataTask_CarCanBrightness();
float CanDataTask_CarCanSpeed();
int CanDataTask_CarCanDirectionIsForward();

View File

@@ -0,0 +1,16 @@
#include "main.h"
#include "UsbDataHandler.h"
#include "stdint.h"
#include "mlzr_comm.h"
#include "pb_decode.h"
#include "display.pb.h"
static cls_display_SetLayout msg_cls_display_SetLayout;
void DataClbk_cls_display_SetLayout(void* msg, uint32_t length) {
DATA_CLBK_SETUP(cls_display_SetLayout);
uint8_t num = (uint8_t)msg_cls_display_SetLayout.layout;
TF_SendSimple(tf_fallback,0x0F, &num, sizeof(num));
}

View File

@@ -10,6 +10,9 @@
#include "crc.h"
#include "FirmwareUpdate.h"
#include "stdbool.h"
#include "CLS.h"
#include "stdbool.h"
#include "ram_loader.h"
// static memory only for decoding messages
static cls_firmware_Start msg_cls_firmware_Start;
@@ -58,19 +61,15 @@ void DataSend_FirmwareFileCheck(uint32_t crc, uint32_t device_id, bool ready_for
#define CHUNK_SIZE 256 // Change this to the size of chunks you want to read
static uint8_t crc_buffer[CHUNK_SIZE];
void DataClbk_cls_firmware_Start(void *msg, uint32_t length) {
DATA_CLBK_SETUP(cls_firmware_Start);
fwStartTime = osKernelGetSysTimerCount();
fwPackageCounter = 0;
void fw_Start_Slave( cls_firmware_Start * msg) {
uint32_t crc = 0;
UINT totalRead = 0;
UINT bytesRead = 0;
if(FileOpen) {
f_close(&FwFile);
}
// Check if file already exists
if(f_open(&FwFile, msg_cls_firmware_Start.name, FA_READ) == FR_OK) {
if(f_open(&FwFile, msg->name, FA_READ) == FR_OK) {
__HAL_CRC_DR_RESET(&hcrc);
do {
@@ -80,16 +79,38 @@ void DataClbk_cls_firmware_Start(void *msg, uint32_t length) {
} while(bytesRead == CHUNK_SIZE);
f_close(&FwFile);
if(crc == msg_cls_firmware_Start.crc_fw) {
if(crc == msg->crc_fw) {
// CRC matches, no need for transfer
DataSend_FirmwareFileCheck(crc, msg_cls_firmware_Start.device_id, false, totalRead, msg_cls_firmware_Start.name);
DataSend_FirmwareFileCheck(crc, msg->device_id, false, totalRead, msg->name);
return;
}
}
fresult_open = f_open(&FwFile, msg_cls_firmware_Start.name, FA_CREATE_ALWAYS | FA_WRITE);
fresult_open = f_open(&FwFile, msg->name, FA_CREATE_ALWAYS | FA_WRITE);
FileOpen=true;
DataSend_FirmwareFileCheck(crc, msg_cls_firmware_Start.device_id, fresult_open==FR_OK, totalRead, msg_cls_firmware_Start.name);
DataSend_FirmwareFileCheck(crc, msg->device_id, fresult_open==FR_OK, totalRead, msg->name);
}
void fw_Start_Master( cls_firmware_Start * msg) {
fresult_open = f_open(&FwFile, "firm.bin", FA_CREATE_ALWAYS | FA_WRITE);
FileOpen=true;
DataSend_FirmwareFileCheck(0, msg->device_id, fresult_open==FR_OK, 0, msg->name);
}
void DataClbk_cls_firmware_Start(void *msg, uint32_t length) {
DATA_CLBK_SETUP(cls_firmware_Start);
fwStartTime = osKernelGetSysTimerCount();
fwPackageCounter = 0;
if(FileOpen) {
f_close(&FwFile);
}
if(msg_cls_firmware_Start.device_id == gCLS_DEVICE_ADDRESS) {
fw_Start_Master(&msg_cls_firmware_Start);
} else {
fw_Start_Slave(&msg_cls_firmware_Start);
}
}
@@ -133,10 +154,19 @@ void DataClbk_cls_firmware_Done(void *msg, uint32_t length) {
fresult_open = 0xFF;
FileOpen=false;
FirmwareUpdateArgs args;
args.device = msg_cls_firmware_Done.device_id;
memcpy(args.name, msg_cls_firmware_Start.name, sizeof(args.name));
if(msg_cls_firmware_Done.device_id == gCLS_DEVICE_ADDRESS) {
RamLoader_LoadApplication();
} else if (msg_cls_firmware_Done.device_id == gCLS_DEVICE_ADDRESS +1) {
// send fw to display
// todo !
FirmwareUpdateTask_start(args);
} {
// send fw to slave
FirmwareUpdateArgs args;
args.device = msg_cls_firmware_Done.device_id;
memcpy(args.name, msg_cls_firmware_Start.name, sizeof(args.name));
FirmwareUpdateTask_start(args);
}
}

View File

@@ -160,7 +160,6 @@ void FirmwareUpdateTask_start(FirmwareUpdateArgs args) {
}
}
UsbDataPacket buffer;
void CLSFirmwareUpdateTask_func(void *argument) {
FirmwareUpdateArgs args;
osStatus_t status;

View File

@@ -0,0 +1,116 @@
#include "UsbDataHandler.h"
#include "headlight.pb.h"
#include "CanDataHandler.h"
#include "stdint.h"
#include "cmsis_os2.h"
#include "CLS.h"
#include "CLS_BSP.h"
#include "CLSAddress.h"
#include "ulog.h"
#include "Vehicle.h"
cls_headlight_RequestSettings msg_cls_headlight_RequestSettings;
cls_headlight_Settings msg_cls_headlight_Settings;
cls_headlight_SaveSettings msg_cls_headlight_SaveSettings;
typedef struct Headlight_Control_Setting {
float alpha;
uint16_t on_threshold;
uint16_t off_threshold;
} Headlight_Control_Setting_t;
uint16_t headlight_amblight = 0;
void CanData_ambilight(CanDataId canid, uint8_t* data, uint8_t len) {
if(len == 2) {
headlight_amblight = (data[1] << 8) | data[0];
}
ULOG_INFO("Ambilight: %d", headlight_amblight);
}
void AddHeadlightMessages() {
CanData_regEventMsg(GENERATE_CLS_ADDRESS(CLS_CODE_STATUS, 0, CLS_CH_STA_AMBIENTLIGHT), CanData_ambilight);
}
// whan a message is received, this function is called
void DataClbk_cls_headlight_Settings(void* msg, uint32_t length) {
DATA_CLBK_SETUP(cls_headlight_Settings);
uint8_t device = msg_cls_headlight_Settings.deviceId;
uint16_t msg_light_setting = GENERATE_CLS_ADDRESS(CLS_CODE_CONFIG, device, 0);
CLS_BSP_TxHeaderType can_header = CREATE_BSP_CAN_HEADER(msg_light_setting, CLS_BSP_DLC_BYTES_8);
Headlight_Control_Setting_t data = {0};
data.alpha = msg_cls_headlight_Settings.alpha;
data.on_threshold = msg_cls_headlight_Settings.on_threshold;
data.off_threshold = msg_cls_headlight_Settings.off_threshold;
CLS_BSP_CAN_AddMessageToSend(&can_header, (uint8_t*)&data);
}
void DataClbk_cls_headlight_SaveSettings(void* msg, uint32_t length) {
DATA_CLBK_SETUP(cls_headlight_SaveSettings);
uint8_t device = msg_cls_headlight_SaveSettings.deviceId;
uint16_t msg_light_setting = GENERATE_CLS_ADDRESS(CLS_CODE_CONFIG, device, 4);
CLS_BSP_TxHeaderType can_header = CREATE_BSP_CAN_HEADER(msg_light_setting, CLS_BSP_DLC_BYTES_1);
CLS_BSP_CAN_AddMessageToSend(&can_header, (uint8_t*)"X");
}
static Headlight_Control_Setting_t response_theme = {0};
static cls_headlight_Settings headligh_settings = {0};
void CanData_responseHeadlightSetting(CanDataId canid, uint8_t* data, uint8_t len) {
if(len == 8) {
memcpy(&response_theme, data, 8);
headligh_settings.alpha = response_theme.alpha;
headligh_settings.on_threshold = response_theme.on_threshold;
headligh_settings.off_threshold = response_theme.off_threshold;
headligh_settings.deviceId = (canid >> 3) & 0x1F;
USBDataResonse(&headligh_settings,cls_headlight_Settings_fields, cls_usb_PackageType_HEADLIGHT_SETTINGS);
}
CanData_removeEvent(canid);
}
void DataClbk_cls_headlight_RequestSettings(void* msg, uint32_t length) {
DATA_CLBK_SETUP(cls_headlight_RequestSettings);
uint8_t device = msg_cls_headlight_RequestSettings.deviceId;
uint8_t data = 0;
uint16_t msg_light_setting = GENERATE_CLS_ADDRESS(CLS_CODE_CONFIG, device, 7);
CLS_BSP_TxHeaderType can_header = CREATE_BSP_CAN_HEADER(msg_light_setting, CLS_BSP_DLC_BYTES_1);
CanData_regEventMsg(msg_light_setting,CanData_responseHeadlightSetting);
CLS_BSP_CAN_AddMessageToSend(&can_header, (uint8_t*)&data);
}
void DataClbk_cls_headlight_RequestBrightness(void* msg, uint32_t length) {
cls_headlight_RequestBrightness msg_cls_headlight_RequestBrightness;
memcpy(&msg_cls_headlight_RequestBrightness, msg, sizeof(cls_headlight_RequestBrightness));
cls_headlight_Brightness msg_cls_headlight_Brightness;
msg_cls_headlight_Brightness.brightness = headlight_amblight;
USBDataResonse(&msg_cls_headlight_Brightness,cls_headlight_Brightness_fields, cls_usb_PackageType_HEADLIGHT_BRIGHTNESS);
}

View File

@@ -4,12 +4,14 @@
#include "BSP_ADC.h"
#include "LightTask.h"
#include "ulog.h"
#include "stdbool.h"
#include "Vehicle.h"
// Create the task with a specific priority and stack size
osThreadAttr_t task_attr = {
.name = "LightStateTask",
.priority = osPriorityNormal,
.stack_size = 1024
.stack_size = 2048
};
// Function prototype for the task function
@@ -23,89 +25,15 @@ void LightStateTask_start(void)
// Check if K15 is on for switching the light state
static bool isK15On()
{
return BSP_GPIO_K15isSet();
}
// Define the threshold voltage for engine running
#define ENGINE_RUNNING_THRESHOLD 13.3 // 13.5V
// Define thresholds with hysteresis
#define ENGINE_RUNNING_THRESHOLD_HIGH (ENGINE_RUNNING_THRESHOLD + 0.125)
#define ENGINE_RUNNING_THRESHOLD_LOW (ENGINE_RUNNING_THRESHOLD - 0.125)
// Global variable to store the current engine state
static bool engineRunning = false;
// Function to initialize the engine state based on the initial voltage
static void initializeEngineState()
{
float initialVoltage = BSP_ADC_ReadBusValue();
if (initialVoltage > ENGINE_RUNNING_THRESHOLD)
{
engineRunning = true;
}
else
{
engineRunning = false;
}
}
// Ensure the engine state is initialized once
static bool isEngineInitialized = false;
static bool isEngineRunning()
{
if (!isEngineInitialized)
{
initializeEngineState();
isEngineInitialized = true;
}
float voltage = BSP_ADC_ReadBusValue();
if (engineRunning)
{
// If engine is currently running, use the lower threshold to turn it off
if (voltage < ENGINE_RUNNING_THRESHOLD_LOW)
{
engineRunning = false;
}
}
else
{
// If engine is currently off, use the higher threshold to turn it on
if (voltage > ENGINE_RUNNING_THRESHOLD_HIGH)
{
engineRunning = true;
}
}
return engineRunning;
}
// check if the headlight is on and the engine is running to switch the light state
// we can check the headlight using the GPIO functions
static bool isHeadlightOn()
{
return BSP_GPIO_HeadLightIsSet();
}
// Function to determine the next state of the light
// return 1 as default state
// return 2 if the engine is running
// return 3 if the headlight and engine is running
static int determineNextState()
{
if (isHeadlightOn() && isEngineRunning()) {
if (Vehicle_isHeadlightOn() && Vehicle_isEngineRunning()) {
return 2;
} else if (isEngineRunning()) {
} else if (Vehicle_isEngineRunning()) {
return 1;
} else {
return 0;

View File

@@ -8,6 +8,10 @@
#include "BSP_EE24.h"
#include "LightTask.h"
#include "CanDataHandler.h"
#include "BSP_GPIO.h"
#include "CanDataTask.h"
#include "Vehicle.h"
#include "BSP_ADC.h"
#define DIMM_DEADZONE_VOLTAGE 0.7
@@ -76,22 +80,35 @@ void LightTask_func(void *argument) {
// calculate the brightness to send
uint8_t brightness = lightSettings.brightness;
// Read ADC battery voltage and dimmer voltage
float v_bus = BSP_ADC_ReadBusValue() - DIMM_DEADZONE_VOLTAGE;
float v_dimm = BSP_ADC_ReadDimmerValue();
// calculate the dimmfactor based on the battery voltage and the dimmer voltage
// the dimmfactor shoudl be 0 if the dimmer voltage is 4V.
// the dimmfactor should be 1 if the dimmer voltage is the same as the battery voltage
float dimmfactor;
if (v_dimm >= v_bus) {
dimmfactor = 1.0;
} else if (v_dimm <= 4.0) {
dimmfactor = 0.0;
} else {
dimmfactor = (v_dimm - 4.0) / (v_bus - 4.0);
}
uint8_t adjustedBrightness = (uint8_t)(brightness * dimmfactor);
uint8_t dimm = 255;
// currenlty not working
// only dimm if the headlight is on
//if (Vehicle_isHeadlightOn()) {
// new version over CAN
//dimm = Vehicle_Brightness();
// old version over ADC
// calculate the dimmfactor based on the battery voltage and the dimmer voltage
// the dimmfactor shoudl be 0 if the dimmer voltage is 4V.
// the dimmfactor should be 1 if the dimmer voltage is the same as the battery voltage
// float v_bus = BSP_ADC_ReadBusValue() - DIMM_DEADZONE_VOLTAGE;
// float v_dimm = BSP_ADC_ReadDimmerValue();
//if (v_dimm >= v_bus) {
// dimmfactor = 1.0;
//} else if (v_dimm <= 4.0) {
// dimmfactor = 0.0;
//} else {
// dimmfactor = (v_dimm - 4.0) / (v_bus - 4.0);
//}
//}
uint8_t adjustedBrightness = (brightness * dimm)/ 255;
lightSettings_dimmed.brightness = adjustedBrightness;
lightSettings_dimmed.theme = lightSettings.theme;

View File

@@ -3,10 +3,12 @@
#include "FreeRTOS.h"
#include "firmware.pb.h"
#include "light.pb.h"
#include "headlight.pb.h"
#include "usb_device.h"
#include <pb_decode.h>
#include "cls_device.pb.h"
#include "usb.pb.h"
#include "display.pb.h"
#include "stdbool.h"
/* Declare the thread function */
@@ -61,7 +63,12 @@ union {
cls_light_ThemeSettings msg_cls_light_ThemeSettings;
cls_light_SaveThemeSettings msg_cls_light_SaveThemeSettings;
cls_light_RequestThemeSetting msg_cls_light_RequestThemeSetting;
cls_usb_JumpToBootloader msg_cls_usb_JumpToBootloader;
cls_headlight_Settings msg_cls_headlight_Settings;
cls_headlight_SaveSettings msg_cls_headlight_SaveSettings;
cls_headlight_RequestSettings msg_cls_headlight_RequestSettings;
cls_headlight_RequestBrightness msg_cls_headlight_RequestBrightness;
cls_display_SetLayout msg_cls_display_SetLayout;
} mem_msg_decode;
@@ -119,6 +126,12 @@ message_handler_t message_handlers[] = {
MESSAGE_HANDLER(cls_usb_PackageType_LIGHT_SETTING_THEME, cls_light_ThemeSettings),
MESSAGE_HANDLER(cls_usb_PackageType_LIGHT_SETTING_THEME_SAVE, cls_light_SaveThemeSettings),
MESSAGE_HANDLER(cls_usb_PackageType_LIGHT_REQUEST_THEME, cls_light_RequestThemeSetting),
MESSAGE_HANDLER(cls_usb_PackageType_JUMP_TO_BOOTLOADER, cls_usb_JumpToBootloader),
MESSAGE_HANDLER(cls_usb_PackageType_HEADLIGHT_SETTINGS, cls_headlight_Settings),
MESSAGE_HANDLER(cls_usb_PackageType_HEADLIGHT_SAVE_SETTINGS, cls_headlight_SaveSettings),
MESSAGE_HANDLER(cls_usb_PackageType_HEADLIGHT_REQUEST_SETTINGS, cls_headlight_RequestSettings),
MESSAGE_HANDLER(cls_usb_PackageType_HEADLIGHT_REQUEST_BRIGHTNESS, cls_headlight_RequestBrightness),
MESSAGE_HANDLER(cls_usb_PackageType_DISPLAY_SET_LAYOUT, cls_display_SetLayout),
};

View File

@@ -122,6 +122,7 @@ void UsbDataHandler_Runner();
*/
int UsbDataHandler_RxCallback(uint8_t* Buf, uint32_t Len);
void DataClbk_cls_usb_JumpToBootloader(void* msg, uint32_t length);
void DataClbk_cls_firmware_Start(void* msg, uint32_t length);
void DataClbk_cls_firmware_Package(void* msg, uint32_t length);
@@ -135,6 +136,11 @@ void DataClbk_cls_light_GlobalTheme(void* msg, uint32_t length);
void DataClbk_cls_light_ThemeSettings(void* msg, uint32_t length);
void DataClbk_cls_light_SaveThemeSettings(void* msg, uint32_t length);
void DataClbk_cls_light_RequestThemeSetting(void* msg, uint32_t length);
void DataClbk_cls_headlight_Settings(void* msg, uint32_t length);
void DataClbk_cls_headlight_SaveSettings(void* msg, uint32_t length);
void DataClbk_cls_headlight_RequestSettings(void* msg, uint32_t length);
void DataClbk_cls_headlight_RequestBrightness(void* msg, uint32_t length);
void DataClbk_cls_display_SetLayout(void* msg, uint32_t length);
#include "usb.pb.h"
void USBDataResonse(void * msg, const pb_msgdesc_t *fields, cls_usb_PackageType typeid);

View File

@@ -0,0 +1,32 @@
# Set the minimum required CMake version
cmake_minimum_required(VERSION 3.12)
# Set the project name
project(Vehicle)
# Add the source files for the library
set(SOURCES
Vehicle.c
Vehicle_can.c
)
# Add the header files for the library
set(HEADERS
Vehicle.h
)
# Create the library target
add_library(Vehicle ${SOURCES} ${HEADERS})
# Set the include directories for the library
target_include_directories(Vehicle PUBLIC ./)
# Set any additional compiler flags or options
# target_compile_options(Vehicle PRIVATE ...)
# Set any additional linker flags or options
# target_link_options(Vehicle PRIVATE ...)
# Specify any dependencies for the library
target_link_libraries(Vehicle BSP CLS CLS_BSP)

View File

@@ -0,0 +1,82 @@
#include "Vehicle.h"
#include "BSP_GPIO.h"
#include "stdbool.h"
#include "BSP_ADC.h"
// Define the threshold voltage for engine running
#define ENGINE_RUNNING_THRESHOLD 13.0 // 13.5V
// Define thresholds with hysteresis
#define ENGINE_RUNNING_THRESHOLD_HIGH (ENGINE_RUNNING_THRESHOLD + 0.225)
#define ENGINE_RUNNING_THRESHOLD_LOW (ENGINE_RUNNING_THRESHOLD - 0.225)
// Global variable to store the current engine state
static bool engineRunning = false;
void Vehicle_Init() {
engineRunning = false;
}
bool Vehicle_isHeadlightOn()
{
return BSP_GPIO_HeadLightIsSet();
}
bool Vehicle_isEngineRunning() {
float voltage = BSP_ADC_ReadBusValue();
if (engineRunning)
{
// If engine is currently running, use the lower threshold to turn it off
if (voltage < ENGINE_RUNNING_THRESHOLD_LOW)
{
engineRunning = false;
}
}
else
{
// If engine is currently off, use the higher threshold to turn it on
if (voltage > ENGINE_RUNNING_THRESHOLD_HIGH)
{
engineRunning = true;
}
}
return engineRunning;
}
bool Vehicle_isK15On() {
return BSP_GPIO_K15isSet();
}
#include "CLS.h"
#include "CLS_BSP.h"
#include "CLSAddress.h"
static CLS_VehicleStatus_t status = {0};
_Static_assert(sizeof(status) == 8, "CLS_HeatbeatData_t is not 8 bytes");
void CLS_VehicleHeatbeat(void *argument) {
CLS_BSP_TxHeaderType cls_vehicle_header = CREATE_BSP_CAN_HEADER(GENERATE_CLS_ADDRESS(CLS_CODE_STATUS,0,CLS_CH_STA_VEHICLE), CLS_BSP_DLC_BYTES_8);
status.k15 = Vehicle_isK15On();
status.headlight = Vehicle_isHeadlightOn();
status.engine = Vehicle_isEngineRunning();
status.speed = (uint8_t)Vehicle_Speed();
status.unlocked = Vehicle_UnlockedSignal();
CLS_BSP_CAN_AddMessageToSend(&cls_vehicle_header, (uint8_t*)&status);
}

View File

@@ -0,0 +1,24 @@
#include "fdcan.h"
#include "stdint.h"
#include "stdbool.h"
void Vehicle_Init();
bool Vehicle_isHeadlightOn();
bool Vehicle_isEngineRunning();
bool Vehicle_isK15On();
void Vehicle_Setup_CAN();
void Vehicle_Receive_CAN( FDCAN_RxHeaderTypeDef header, uint8_t* data);
bool Vehicle_gotUnlockMessage();
uint8_t Vehicle_Brightness();
float Vehicle_Speed();
int Vehicle_DirectionIsForward();
bool Vehicle_UnlockedSignal();

View File

@@ -0,0 +1,149 @@
#include "Vehicle.h"
#include "fdcan.h"
#include "CLS.h"
#include "CLS_BSP.h"
#include "BSP_GPIO.h"
#include "cmsis_os2.h"
static uint64_t last_unlock_message_time = UINT64_MAX;
static uint8_t car_can_brightness = 255;
static float car_can_speed = 0;
static int car_can_direction = 0;
void Vehicle_Setup_CAN() {
FDCAN_FilterTypeDef sFilterConfig;
sFilterConfig.IdType = FDCAN_STANDARD_ID;
sFilterConfig.FilterIndex = 0;
sFilterConfig.FilterType = CLS_BSP_CAN_FILTER_LIST;
sFilterConfig.FilterConfig = FDCAN_FILTER_TO_RXFIFO1;
sFilterConfig.FilterID1 = 0x391;
sFilterConfig.FilterID2 = 0x395;
HAL_FDCAN_ConfigFilter(&hfdcan2, &sFilterConfig);
sFilterConfig.FilterIndex = 1;
sFilterConfig.FilterID1 = 0x351;
sFilterConfig.FilterID2 = 0x635;
HAL_FDCAN_ConfigFilter(&hfdcan2, &sFilterConfig);
}
static void rx_unlock_key(uint8_t * RxData ) {
if (RxData[1] == 0x04)
{
// car was unlocked
last_unlock_message_time = osKernelGetTickCount();
}
else if (RxData[1] ==0x80)
{
// car was locked
if (!BSP_GPIO_K15isSet()) {
NVIC_SystemReset();
}
}
}
static void rx_unlock_secure(uint8_t * RxData ) {
if ((RxData[0] & 0x0F) == 0x01) {
// car was unlocked
last_unlock_message_time = osKernelGetTickCount();
} else if ((RxData[0] & 0x0F) == 0x02) {
// car was locked
if (!BSP_GPIO_K15isSet()) {
NVIC_SystemReset();
}
}
}
static void rx_speed(uint8_t * RxData) {
// speed signal
// AA BB XX YY 00 00 00 00
// Speed (XX*(2^8)+(YY-1))/190
// direction AA = 0x00 forward, 0x02 backward
uint16_t speed = (RxData[2] << 8) + RxData[3];
float speed_kmh = (speed - 1) / 190.0;
car_can_speed = speed_kmh;
car_can_direction = RxData[0];
//ULOG_DEBUG("Speed: %f, Direction: %d", car_can_speed, car_can_direction);
}
static void rx_brightness(uint8_t* RxData) {
// scale the brightness to 0 - 255 only using integer math
car_can_brightness = ((uint32_t)RxData[0] * 255) / 100;
//ULOG_DEBUG("Brightness: %d", car_can_brightness);
}
void Vehicle_Receive_CAN( FDCAN_RxHeaderTypeDef RxHeader, uint8_t* RxData) {
if(RxHeader.Identifier == 0x391) {
rx_unlock_key(RxData);
}
if (RxHeader.Identifier == 0x395) {
rx_unlock_secure(RxData);
}
if (RxHeader.Identifier == 0x351) {
rx_speed(RxData);
}
// brightness knob in 0 - 100
if (RxHeader.Identifier == 0x635) {
rx_brightness(RxData);
}
}
bool Vehicle_gotUnlockMessage() {
return last_unlock_message_time != UINT64_MAX;
}
uint8_t Vehicle_Brightness() {
return car_can_brightness;
}
float Vehicle_Speed() {
return car_can_speed;
}
int Vehicle_DirectionIsForward() {
return car_can_direction == 0;
}
static bool unlocked = false;
bool Vehicle_UnlockedSignal() {
if (unlocked) {
if(Vehicle_isK15On()) {
unlocked = false;
last_unlock_message_time = UINT64_MAX;
}
}
if (!unlocked) {
if (Vehicle_gotUnlockMessage()) {
unlocked = true;
}
}
return unlocked;
}

View File

@@ -0,0 +1,34 @@
# Set the minimum required CMake version
cmake_minimum_required(VERSION 3.12)
# Set the project name
project(ram_loader)
# Add the source files for the library
set(SOURCES
ram_loader.c
)
# Add the header files for the library
set(HEADERS
ram_loader.h
)
# Create the library target
add_library(ram_loader ${SOURCES} ${HEADERS})
# Set the include directories for the library
target_include_directories(ram_loader PUBLIC ./)
# Set any additional compiler flags or options
# target_compile_options(${PROJECT_NAME} PRIVATE ...)
# Set any additional linker flags or options
# target_link_options(${PROJECT_NAME} PRIVATE ...)
# Specify any dependencies for the library
# target_link_libraries(${PROJECT_NAME} <dependency1> <dependency2> ...)
# Optionally, add an executable target for testing
# add_executable(test_ram_loader test/test_ram_loader.cpp)
# target_link_libraries(test_ram_loader ${PROJECT_NAME})

View File

@@ -0,0 +1,110 @@
#include "fatfs.h"
#include "string.h"
#define RAM_LOADER_BUFFER_SIZE 15*1024
#define RAM_LOADER_ADDRESS 0x38000000
#define APP_START_ADDRESS RAM_LOADER_ADDRESS
uint8_t * ram_loader_buffer = (uint8_t *) RAM_LOADER_ADDRESS;
void _app_start(void)
{
__disable_irq();
// Reset USB
//De-init all peripherals
//HAL_ADC_DeInit(&hadc1);
// Disable Systick
SysTick->CTRL = 0;
SysTick->LOAD = 0;
SysTick->VAL = 0;
// Reset clock to default
HAL_RCC_DeInit();
// Clear all interrupt bits
for (uint8_t i = 0; i < sizeof(NVIC->ICER) / sizeof(NVIC->ICER[0]); i++)
{
NVIC->ICER[i] = 0xFFFFFFFF;
NVIC->ICPR[i] = 0xFFFFFFFF;
}
__enable_irq();
// set the vector table offset register
SCB->VTOR = APP_START_ADDRESS;
// get the application stack pointer
__set_MSP(((uint32_t *)APP_START_ADDRESS)[0]);
// jump to the application
((void (*)(void))((uint32_t *)APP_START_ADDRESS)[1])();
// the application should never return
// ULOG_ERROR("Failed to start application");
while (1) {}
}
static uint8_t buffer[512];
void RamLoader_LoadApplication()
{
// check if the file "load.bin" exists
FIL file;
FRESULT res = f_open(&file, "load.bin", FA_READ);
if (res != FR_OK) {
// ULOG_ERROR("Failed to open file load.bin");
return;
}
UINT size = f_size(&file);
// ensure the file is not larger than the buffer
if (size > RAM_LOADER_BUFFER_SIZE ) {
// ULOG_ERROR("File load.bin is too large");
return;
}
// read the file into the buffer
UINT bytes_read;
uint32_t remaining_bytes = size;
uint8_t *destination_ptr = ram_loader_buffer;
uint8_t *buffer_ptr = buffer;
while (remaining_bytes > 0) {
UINT read_size = remaining_bytes > 512 ? 512 : remaining_bytes;
res = f_read(&file, buffer_ptr, read_size, &bytes_read);
if (res != FR_OK) {
// ULOG_ERROR("Failed to read file load.bin");
return;
}
if (bytes_read != read_size) {
// ULOG_ERROR("Failed to read file load.bin completely");
return;
}
memcpy(destination_ptr, buffer_ptr, read_size);
remaining_bytes -= read_size;
destination_ptr += read_size;
}
// close the file
f_close(&file);
// check that the file to flash exists ("firm.bin")
res = f_open(&file, "firm.bin", FA_READ);
if (res != FR_OK) {
// ULOG_ERROR("Failed to open file firm.bin");
return;
}
//close the file
f_close(&file);
_app_start();
}

View File

@@ -0,0 +1,3 @@
#pragma once
void RamLoader_LoadApplication();

View File

@@ -26,6 +26,43 @@ ADC1.SamplingTime-2\#ChannelRegularConversion=ADC_SAMPLETIME_32CYCLES_5
ADC1.SamplingTime-3\#ChannelRegularConversion=ADC_SAMPLETIME_32CYCLES_5
ADC1.SamplingTime-4\#ChannelRegularConversion=ADC_SAMPLETIME_32CYCLES_5
ADC1.master=1
Bdma.LPUART1_RX.0.Direction=DMA_PERIPH_TO_MEMORY
Bdma.LPUART1_RX.0.EventEnable=DISABLE
Bdma.LPUART1_RX.0.Instance=BDMA_Channel0
Bdma.LPUART1_RX.0.MemDataAlignment=DMA_MDATAALIGN_BYTE
Bdma.LPUART1_RX.0.MemInc=DMA_MINC_ENABLE
Bdma.LPUART1_RX.0.Mode=DMA_NORMAL
Bdma.LPUART1_RX.0.PeriphDataAlignment=DMA_PDATAALIGN_BYTE
Bdma.LPUART1_RX.0.PeriphInc=DMA_PINC_DISABLE
Bdma.LPUART1_RX.0.Polarity=HAL_DMAMUX_REQ_GEN_RISING
Bdma.LPUART1_RX.0.Priority=DMA_PRIORITY_LOW
Bdma.LPUART1_RX.0.RequestNumber=1
Bdma.LPUART1_RX.0.RequestParameters=Instance,Direction,PeriphInc,MemInc,PeriphDataAlignment,MemDataAlignment,Mode,Priority,SignalID,Polarity,RequestNumber,SyncSignalID,SyncPolarity,SyncEnable,EventEnable,SyncRequestNumber
Bdma.LPUART1_RX.0.SignalID=NONE
Bdma.LPUART1_RX.0.SyncEnable=DISABLE
Bdma.LPUART1_RX.0.SyncPolarity=HAL_DMAMUX_SYNC_NO_EVENT
Bdma.LPUART1_RX.0.SyncRequestNumber=1
Bdma.LPUART1_RX.0.SyncSignalID=NONE
Bdma.LPUART1_TX.1.Direction=DMA_MEMORY_TO_PERIPH
Bdma.LPUART1_TX.1.EventEnable=DISABLE
Bdma.LPUART1_TX.1.Instance=BDMA_Channel1
Bdma.LPUART1_TX.1.MemDataAlignment=DMA_MDATAALIGN_BYTE
Bdma.LPUART1_TX.1.MemInc=DMA_MINC_ENABLE
Bdma.LPUART1_TX.1.Mode=DMA_NORMAL
Bdma.LPUART1_TX.1.PeriphDataAlignment=DMA_PDATAALIGN_BYTE
Bdma.LPUART1_TX.1.PeriphInc=DMA_PINC_DISABLE
Bdma.LPUART1_TX.1.Polarity=HAL_DMAMUX_REQ_GEN_RISING
Bdma.LPUART1_TX.1.Priority=DMA_PRIORITY_LOW
Bdma.LPUART1_TX.1.RequestNumber=1
Bdma.LPUART1_TX.1.RequestParameters=Instance,Direction,PeriphInc,MemInc,PeriphDataAlignment,MemDataAlignment,Mode,Priority,SignalID,Polarity,RequestNumber,SyncSignalID,SyncPolarity,SyncEnable,EventEnable,SyncRequestNumber
Bdma.LPUART1_TX.1.SignalID=NONE
Bdma.LPUART1_TX.1.SyncEnable=DISABLE
Bdma.LPUART1_TX.1.SyncPolarity=HAL_DMAMUX_SYNC_NO_EVENT
Bdma.LPUART1_TX.1.SyncRequestNumber=1
Bdma.LPUART1_TX.1.SyncSignalID=NONE
Bdma.Request0=LPUART1_RX
Bdma.Request1=LPUART1_TX
Bdma.RequestsNb=2
CAD.formats=
CAD.pinconfig=
CAD.provider=
@@ -198,36 +235,38 @@ I2C2.Timing=0x00D0D8FF
KeepUserPlacement=false
LPTIM4.ClockPrescaler=LPTIM_PRESCALER_DIV64
LPTIM4.IPParameters=ClockPrescaler
LPUART1.BaudRate=2000000
LPUART1.IPParameters=BaudRate
LPUART1.BaudRate=1000000
LPUART1.FIFOMode=UART_FIFOMODE_DISABLE
LPUART1.IPParameters=BaudRate,FIFOMode
Mcu.CPN=STM32H723VGT6
Mcu.Family=STM32H7
Mcu.IP0=ADC1
Mcu.IP1=CORTEX_M7
Mcu.IP10=I2C2
Mcu.IP11=LPTIM4
Mcu.IP12=LPUART1
Mcu.IP13=NVIC
Mcu.IP14=PWR
Mcu.IP15=RCC
Mcu.IP16=RNG
Mcu.IP17=RTC
Mcu.IP18=SDMMC1
Mcu.IP19=SYS
Mcu.IP2=CRC
Mcu.IP20=TIM2
Mcu.IP21=USART1
Mcu.IP22=USART3
Mcu.IP23=USB_DEVICE
Mcu.IP24=USB_OTG_HS
Mcu.IP3=DEBUG
Mcu.IP4=DMA
Mcu.IP5=FATFS
Mcu.IP6=FDCAN1
Mcu.IP7=FDCAN2
Mcu.IP8=FREERTOS
Mcu.IP9=I2C1
Mcu.IPNb=25
Mcu.IP1=BDMA
Mcu.IP10=I2C1
Mcu.IP11=I2C2
Mcu.IP12=LPTIM4
Mcu.IP13=LPUART1
Mcu.IP14=NVIC
Mcu.IP15=PWR
Mcu.IP16=RCC
Mcu.IP17=RNG
Mcu.IP18=RTC
Mcu.IP19=SDMMC1
Mcu.IP2=CORTEX_M7
Mcu.IP20=SYS
Mcu.IP21=TIM2
Mcu.IP22=USART1
Mcu.IP23=USART3
Mcu.IP24=USB_DEVICE
Mcu.IP25=USB_OTG_HS
Mcu.IP3=CRC
Mcu.IP4=DEBUG
Mcu.IP5=DMA
Mcu.IP6=FATFS
Mcu.IP7=FDCAN1
Mcu.IP8=FDCAN2
Mcu.IP9=FREERTOS
Mcu.IPNb=26
Mcu.Name=STM32H723VGTx
Mcu.Package=LQFP100
Mcu.Pin0=PE2
@@ -302,6 +341,8 @@ Mcu.UserName=STM32H723VGTx
MxCube.Version=6.9.2
MxDb.Version=DB.6.0.92
NVIC.ADC_IRQn=true\:5\:0\:false\:false\:true\:true\:true\:true\:true
NVIC.BDMA_Channel0_IRQn=true\:5\:0\:false\:false\:true\:true\:false\:true\:true
NVIC.BDMA_Channel1_IRQn=true\:5\:0\:false\:false\:true\:true\:false\:true\:true
NVIC.BusFault_IRQn=true\:0\:0\:false\:false\:true\:false\:false\:false\:false
NVIC.DMA1_Stream0_IRQn=true\:5\:0\:false\:false\:true\:true\:false\:true\:true
NVIC.DMA1_Stream1_IRQn=true\:5\:0\:false\:false\:true\:true\:false\:true\:true
@@ -317,6 +358,7 @@ NVIC.FDCAN2_IT1_IRQn=true\:5\:0\:false\:false\:true\:true\:true\:true\:true
NVIC.ForceEnableDMAVector=true
NVIC.HardFault_IRQn=true\:0\:0\:false\:false\:true\:false\:false\:false\:false
NVIC.LPTIM4_IRQn=true\:5\:0\:false\:false\:true\:true\:true\:true\:true
NVIC.LPUART1_IRQn=true\:5\:0\:false\:false\:true\:true\:true\:true\:true
NVIC.MemoryManagement_IRQn=true\:0\:0\:false\:false\:true\:false\:false\:false\:false
NVIC.NonMaskableInt_IRQn=true\:0\:0\:false\:false\:true\:false\:false\:false\:false
NVIC.OTG_HS_EP1_IN_IRQn=true\:5\:0\:false\:false\:true\:true\:false\:true\:true
@@ -540,7 +582,7 @@ ProjectManager.ToolChainLocation=
ProjectManager.UAScriptAfterPath=
ProjectManager.UAScriptBeforePath=
ProjectManager.UnderRoot=true
ProjectManager.functionlistsort=1-SystemClock_Config-RCC-false-HAL-false,2-MX_GPIO_Init-GPIO-false-HAL-true,3-MX_DMA_Init-DMA-false-HAL-true,4-MX_I2C2_Init-I2C2-false-HAL-true,5-MX_LPUART1_UART_Init-LPUART1-false-HAL-true,6-MX_USART1_UART_Init-USART1-false-LL-true,7-MX_USART3_UART_Init-USART3-false-LL-true,8-MX_RTC_Init-RTC-false-HAL-true,9-MX_SDMMC1_SD_Init-SDMMC1-false-HAL-true,10-MX_FATFS_Init-FATFS-false-HAL-false,11-MX_ADC1_Init-ADC1-false-HAL-true,12-MX_FDCAN1_Init-FDCAN1-false-HAL-true,13-MX_USB_DEVICE_Init-USB_DEVICE-false-HAL-false,14-MX_FDCAN2_Init-FDCAN2-false-HAL-true,15-MX_I2C1_Init-I2C1-false-HAL-true,16-MX_CRC_Init-CRC-false-HAL-true,17-MX_RNG_Init-RNG-false-HAL-true,18-MX_TIM2_Init-TIM2-false-HAL-true,19-MX_LPTIM4_Init-LPTIM4-false-HAL-true,0-MX_CORTEX_M7_Init-CORTEX_M7-false-HAL-true,0-MX_VREFBUF_Init-VREFBUF-false-HAL-true,0-MX_PWR_Init-PWR-false-HAL-true
ProjectManager.functionlistsort=1-SystemClock_Config-RCC-false-HAL-false,2-MX_GPIO_Init-GPIO-false-HAL-true,3-MX_DMA_Init-DMA-false-HAL-true,4-MX_BDMA_Init-BDMA-false-HAL-true,5-MX_I2C2_Init-I2C2-false-HAL-true,6-MX_LPUART1_UART_Init-LPUART1-false-HAL-true,7-MX_USART1_UART_Init-USART1-false-LL-true,8-MX_USART3_UART_Init-USART3-false-LL-true,9-MX_RTC_Init-RTC-false-HAL-true,10-MX_SDMMC1_SD_Init-SDMMC1-false-HAL-true,11-MX_FATFS_Init-FATFS-false-HAL-false,12-MX_ADC1_Init-ADC1-false-HAL-true,13-MX_FDCAN1_Init-FDCAN1-false-HAL-true,14-MX_USB_DEVICE_Init-USB_DEVICE-false-HAL-false,15-MX_FDCAN2_Init-FDCAN2-false-HAL-true,16-MX_I2C1_Init-I2C1-false-HAL-true,17-MX_CRC_Init-CRC-false-HAL-true,18-MX_RNG_Init-RNG-false-HAL-true,19-MX_LPTIM4_Init-LPTIM4-false-HAL-true,20-MX_TIM2_Init-TIM2-false-HAL-true,0-MX_CORTEX_M7_Init-CORTEX_M7-false-HAL-true,0-MX_PWR_Init-PWR-false-HAL-true
RCC.ADCFreq_Value=96000000
RCC.AHB12Freq_Value=275000000
RCC.AHB4Freq_Value=275000000

View File

@@ -124,6 +124,8 @@ nanopb_generate_cpp(PROTO_SRCS PROTO_HDRS RELPATH proto
proto/cls_device.proto
proto/light.proto
proto/usb.proto
proto/headlight.proto
proto/display.proto
)
add_library(PROTOS ${PROTO_SRCS} ${PROTO_HDRS})
target_include_directories(PROTOS PUBLIC ${NANOPB_INCLUDE_DIRS} ${PROJECT_BINARY_DIR})
@@ -140,9 +142,9 @@ add_subdirectory("Application")
add_executable(${CMAKE_PROJECT_NAME})
target_sources(${CMAKE_PROJECT_NAME} PUBLIC ${sources_SRCS})
target_link_libraries(${CMAKE_PROJECT_NAME} PUBLIC Tasks CLS CLS_BSP BSP EE24 INA219 ulog)
target_link_libraries(${CMAKE_PROJECT_NAME} PUBLIC Tasks CLS CLS_BSP BSP EE24 INA219 ulog ram_loader Vehicle)
#target_link_libraries(${CMAKE_PROJECT_NAME} PUBLIC PROTOS)
target_link_libraries(${CMAKE_PROJECT_NAME} PUBLIC uart_driver)
target_link_libraries(${CMAKE_PROJECT_NAME} PUBLIC mlzr_comm TinyFrame uart_driver mlzr_glasm)
#target_link_libraries(${CMAKE_PROJECT_NAME} PUBLIC lwrb)
target_compile_options(${CMAKE_PROJECT_NAME} PRIVATE

52
Core/Inc/bdma.h Normal file
View File

@@ -0,0 +1,52 @@
/* USER CODE BEGIN Header */
/**
******************************************************************************
* @file bdma.h
* @brief This file contains all the function prototypes for
* the bdma.c file
******************************************************************************
* @attention
*
* Copyright (c) 2024 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in the LICENSE file
* in the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
******************************************************************************
*/
/* USER CODE END Header */
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef __BDMA_H__
#define __BDMA_H__
#ifdef __cplusplus
extern "C" {
#endif
/* Includes ------------------------------------------------------------------*/
#include "main.h"
/* DMA memory to memory transfer handles -------------------------------------*/
/* USER CODE BEGIN Includes */
/* USER CODE END Includes */
/* USER CODE BEGIN Private defines */
/* USER CODE END Private defines */
void MX_BDMA_Init(void);
/* USER CODE BEGIN Prototypes */
/* USER CODE END Prototypes */
#ifdef __cplusplus
}
#endif
#endif /* __BDMA_H__ */

View File

@@ -72,7 +72,10 @@ void SDMMC1_IRQHandler(void);
void OTG_HS_EP1_OUT_IRQHandler(void);
void OTG_HS_EP1_IN_IRQHandler(void);
void OTG_HS_IRQHandler(void);
void BDMA_Channel0_IRQHandler(void);
void BDMA_Channel1_IRQHandler(void);
void LPTIM4_IRQHandler(void);
void LPUART1_IRQHandler(void);
/* USER CODE BEGIN EFP */
/* USER CODE END EFP */

58
Core/Src/bdma.c Normal file
View File

@@ -0,0 +1,58 @@
/* USER CODE BEGIN Header */
/**
******************************************************************************
* @file bdma.c
* @brief This file provides code for the configuration
* of all the requested memory to memory DMA transfers.
******************************************************************************
* @attention
*
* Copyright (c) 2024 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in the LICENSE file
* in the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
******************************************************************************
*/
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "bdma.h"
/* USER CODE BEGIN 0 */
/* USER CODE END 0 */
/*----------------------------------------------------------------------------*/
/* Configure DMA */
/*----------------------------------------------------------------------------*/
/* USER CODE BEGIN 1 */
/* USER CODE END 1 */
/**
* Enable DMA controller clock
*/
void MX_BDMA_Init(void)
{
/* DMA controller clock enable */
__HAL_RCC_BDMA_CLK_ENABLE();
/* DMA interrupt init */
/* BDMA_Channel0_IRQn interrupt configuration */
HAL_NVIC_SetPriority(BDMA_Channel0_IRQn, 5, 0);
HAL_NVIC_EnableIRQ(BDMA_Channel0_IRQn);
/* BDMA_Channel1_IRQn interrupt configuration */
HAL_NVIC_SetPriority(BDMA_Channel1_IRQn, 5, 0);
HAL_NVIC_EnableIRQ(BDMA_Channel1_IRQn);
}
/* USER CODE BEGIN 2 */
/* USER CODE END 2 */

View File

@@ -39,6 +39,9 @@
#include "LightState.h"
#include "BSP_GPIO.h"
#include "BSP_ADC.h"
#include "BSP_SDLogger.h"
#include "Vehicle.h"
/* USER CODE END Includes */
/* Private typedef -----------------------------------------------------------*/
@@ -71,7 +74,7 @@ const osThreadAttr_t defaultTask_attributes = {
osThreadId_t waitForStartConfirmHandle;
const osThreadAttr_t waitForStartConfirm_attributes = {
.name = "waitForStartConfirm",
.stack_size = 256 * 4,
.stack_size = 512 * 4,
.priority = (osPriority_t) osPriorityNormal,
};
@@ -149,6 +152,8 @@ void MX_FREERTOS_Init(void) {
}
/* USER CODE BEGIN Header_StartDefaultTask */
void AddHeadlightMessages();
/**
* @brief Function implementing the defaultTask thread.
* @param argument: Not used
@@ -157,6 +162,8 @@ void MX_FREERTOS_Init(void) {
#include "CLS_BSP.h"
#include "CLSAddress.h"
#include "mlzr_comm.h"
#include "glasm.h"
/* USER CODE END Header_StartDefaultTask */
void StartDefaultTask(void *argument)
{
@@ -166,6 +173,10 @@ void StartDefaultTask(void *argument)
BSP_EE24_Init();
BSP_INA_Init();
MLZR_INIT();
GLASM_Init();
retSD = f_mount(&SDFatFS,SDPath,0);
retSD = f_open(&SDFile, "counter.bin", FA_READ);
@@ -186,6 +197,9 @@ void StartDefaultTask(void *argument)
ULOG_INFO(output);
}
BSP_SDLogger_Init(counter);
AddHeadlightMessages();
char INA_LOG[72];
/* Infinite loop */
@@ -233,7 +247,7 @@ void WaitForStartConfirm_Task(void *argument) {
while(1) {
osDelayUntil(tick);
tick += delayTime;
if(BSP_GPIO_K15isSet() || CanDataTask_gotCarCanMessage()) {
if(BSP_GPIO_K15isSet() || Vehicle_gotUnlockMessage()) {
BSP_POWER_FullPowerMode();
ULOG_INFO("Power systems started");
osThreadExit();
@@ -247,13 +261,13 @@ void WaitForStartConfirm_Task(void *argument) {
}
if(tick > maxDelayTime) {
BSP_POWER_EnterStandby();
ULOG_INFO("System in standby mode");
osThreadExit();
while (1)
{
osDelay(1000);
ULOG_INFO("System in standby mode");
BSP_POWER_EnterStandby();
NVIC_SystemReset();
}
osThreadExit();
}
}
}

View File

@@ -20,6 +20,7 @@
#include "main.h"
#include "cmsis_os.h"
#include "adc.h"
#include "bdma.h"
#include "crc.h"
#include "dma.h"
#include "fatfs.h"
@@ -41,11 +42,15 @@
#include "BSP_POWER.h"
#include "BSP_GPIO.h"
#include "BSP_ADC.h"
#include "ram_loader.h"
#include "AsyncComm.h"
/* USER CODE END Includes */
/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */
extern uart_desc_t uart_half;
__attribute__((__section__(".dma_buffer"))) uint8_t lp_buffer[2][2048] = {0};
uint8_t swap_index = 0;
/* USER CODE END PTD */
/* Private define ------------------------------------------------------------*/
@@ -72,6 +77,7 @@ static void MPU_Config(void);
void MX_FREERTOS_Init(void);
/* USER CODE BEGIN PFP */
void ULOG_SendLPUART(ulog_level_t level, char *msg);
/* USER CODE END PFP */
/* Private user code ---------------------------------------------------------*/
@@ -87,6 +93,7 @@ int main(void)
{
/* USER CODE BEGIN 1 */
/* USER CODE END 1 */
/* Enable I-Cache---------------------------------------------------------*/
@@ -117,6 +124,7 @@ int main(void)
/* Initialize all configured peripherals */
MX_GPIO_Init();
MX_DMA_Init();
MX_BDMA_Init();
MX_I2C2_Init();
MX_LPUART1_UART_Init();
MX_USART1_UART_Init();
@@ -129,8 +137,8 @@ int main(void)
MX_I2C1_Init();
MX_CRC_Init();
MX_RNG_Init();
MX_TIM2_Init();
MX_LPTIM4_Init();
MX_TIM2_Init();
/* USER CODE BEGIN 2 */
BSP_GPIO_PeriperalsOn();
@@ -141,6 +149,14 @@ int main(void)
gCLS_DEVICE_ADDRESS = 0x11; // Address is set to master
ULOG_DEBUG("Setting Global CLS address to 0b10001");
ULOG_DEBUG("Init Kernel and start schedule");
//HAL_UART_Receive(&hlpuart1, lp_buffer[swap_index], 10, 10000);
HAL_StatusTypeDef status = HAL_UARTEx_ReceiveToIdle_DMA(&hlpuart1, lp_buffer[swap_index], 2048);
if(status != HAL_OK){
ULOG_ERROR("Failed to start DMA");
Error_Handler();
}
/* USER CODE END 2 */
@@ -164,6 +180,37 @@ int main(void)
/* USER CODE END 3 */
}
void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart){
if(huart->Instance ==LPUART1){
uint8_t new_index = (swap_index + 1) % 2;
HAL_UARTEx_ReceiveToIdle_DMA(&hlpuart1, lp_buffer[new_index], 2048);
usart_send_data(&uart_half, lp_buffer[swap_index], 2048);
swap_index = new_index;
}
}
void HAL_UARTEx_RxEventCallback(UART_HandleTypeDef *huart, uint16_t Size){
//restarts the DMA listening of the UART rx (next 247 bytes)
if(huart->Instance ==LPUART1){
uint8_t new_index = (swap_index + 1) % 2;
HAL_UARTEx_ReceiveToIdle_DMA(&hlpuart1, lp_buffer[new_index], 2048);
usart_send_data(&uart_half, lp_buffer[swap_index], Size);
swap_index = new_index;
}
return;
}
void HAL_UART_ErrorCallback(UART_HandleTypeDef *huart)
{
/* Prevent unused argument(s) compilation warning */
if(huart->Instance ==LPUART1){
swap_index = (swap_index + 1) % 2;
HAL_UARTEx_ReceiveToIdle_DMA(&hlpuart1, lp_buffer[swap_index], 2048);
}
}
/**
* @brief System Clock Configuration
* @retval None
@@ -285,6 +332,9 @@ void ULOG_SendLPUART(ulog_level_t level, char *msg) {
HAL_UART_Transmit(&hlpuart1, (const uint8_t*)ulog_send_buffer, send_length, LOG_TIMEOUT);
}
void DataClbk_cls_usb_JumpToBootloader(void* msg, uint32_t length) {
RamLoader_LoadApplication();
}
/* USER CODE END 4 */
/* MPU Configuration */

View File

@@ -22,6 +22,7 @@
#include "stm32h7xx_it.h"
/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include "AsyncComm.h"
/* USER CODE END Includes */
/* Private typedef -----------------------------------------------------------*/
@@ -41,7 +42,8 @@
/* Private variables ---------------------------------------------------------*/
/* USER CODE BEGIN PV */
extern uart_desc_t uart_duplex;
extern uart_desc_t uart_half;
/* USER CODE END PV */
/* Private function prototypes -----------------------------------------------*/
@@ -61,6 +63,9 @@ extern ADC_HandleTypeDef hadc1;
extern FDCAN_HandleTypeDef hfdcan1;
extern FDCAN_HandleTypeDef hfdcan2;
extern LPTIM_HandleTypeDef hlptim4;
extern DMA_HandleTypeDef hdma_lpuart1_rx;
extern DMA_HandleTypeDef hdma_lpuart1_tx;
extern UART_HandleTypeDef hlpuart1;
extern RTC_HandleTypeDef hrtc;
extern SD_HandleTypeDef hsd1;
extern TIM_HandleTypeDef htim2;
@@ -99,6 +104,21 @@ void HardFault_Handler(void)
while (1)
{
/* USER CODE BEGIN W1_HardFault_IRQn 0 */
HAL_GPIO_TogglePin(DIO12_L2_GPIO_Port, DIO12_L2_Pin);
for (size_t i = 0; i < 10000000; i++)
{
__NOP();
__NOP();
__NOP();
__NOP();
__NOP();
__NOP();
__NOP();
}
/* USER CODE END W1_HardFault_IRQn 0 */
}
}
@@ -114,6 +134,18 @@ void MemManage_Handler(void)
while (1)
{
/* USER CODE BEGIN W1_MemoryManagement_IRQn 0 */
HAL_GPIO_TogglePin(DIO12_L2_GPIO_Port, DIO12_L2_Pin);
for (size_t i = 0; i < 30000000; i++)
{
__NOP();
__NOP();
__NOP();
__NOP();
__NOP();
__NOP();
__NOP();
}
/* USER CODE END W1_MemoryManagement_IRQn 0 */
}
}
@@ -206,7 +238,7 @@ void DMA1_Stream0_IRQHandler(void)
/* USER CODE END DMA1_Stream0_IRQn 0 */
/* USER CODE BEGIN DMA1_Stream0_IRQn 1 */
usart_dma_irq_handler(&uart_duplex);
/* USER CODE END DMA1_Stream0_IRQn 1 */
}
@@ -220,7 +252,7 @@ void DMA1_Stream1_IRQHandler(void)
/* USER CODE END DMA1_Stream1_IRQn 0 */
/* USER CODE BEGIN DMA1_Stream1_IRQn 1 */
usart_dma_irq_handler_tx(&uart_duplex);
/* USER CODE END DMA1_Stream1_IRQn 1 */
}
@@ -234,7 +266,7 @@ void DMA1_Stream2_IRQHandler(void)
/* USER CODE END DMA1_Stream2_IRQn 0 */
/* USER CODE BEGIN DMA1_Stream2_IRQn 1 */
usart_dma_irq_handler(&uart_half);
/* USER CODE END DMA1_Stream2_IRQn 1 */
}
@@ -248,7 +280,7 @@ void DMA1_Stream3_IRQHandler(void)
/* USER CODE END DMA1_Stream3_IRQn 0 */
/* USER CODE BEGIN DMA1_Stream3_IRQn 1 */
usart_dma_irq_handler_tx(&uart_half);
/* USER CODE END DMA1_Stream3_IRQn 1 */
}
@@ -373,7 +405,7 @@ void USART1_IRQHandler(void)
/* USER CODE END USART1_IRQn 0 */
/* USER CODE BEGIN USART1_IRQn 1 */
usart_irq_handler(&uart_duplex);
/* USER CODE END USART1_IRQn 1 */
}
@@ -386,7 +418,7 @@ void USART3_IRQHandler(void)
/* USER CODE END USART3_IRQn 0 */
/* USER CODE BEGIN USART3_IRQn 1 */
usart_irq_handler(&uart_half);
/* USER CODE END USART3_IRQn 1 */
}
@@ -446,6 +478,34 @@ void OTG_HS_IRQHandler(void)
/* USER CODE END OTG_HS_IRQn 1 */
}
/**
* @brief This function handles BDMA channel0 global interrupt.
*/
void BDMA_Channel0_IRQHandler(void)
{
/* USER CODE BEGIN BDMA_Channel0_IRQn 0 */
/* USER CODE END BDMA_Channel0_IRQn 0 */
HAL_DMA_IRQHandler(&hdma_lpuart1_rx);
/* USER CODE BEGIN BDMA_Channel0_IRQn 1 */
/* USER CODE END BDMA_Channel0_IRQn 1 */
}
/**
* @brief This function handles BDMA channel1 global interrupt.
*/
void BDMA_Channel1_IRQHandler(void)
{
/* USER CODE BEGIN BDMA_Channel1_IRQn 0 */
/* USER CODE END BDMA_Channel1_IRQn 0 */
HAL_DMA_IRQHandler(&hdma_lpuart1_tx);
/* USER CODE BEGIN BDMA_Channel1_IRQn 1 */
/* USER CODE END BDMA_Channel1_IRQn 1 */
}
/**
* @brief This function handles LPTIM4 global interrupt.
*/
@@ -460,6 +520,22 @@ void LPTIM4_IRQHandler(void)
/* USER CODE END LPTIM4_IRQn 1 */
}
/**
* @brief This function handles LPUART1 global interrupt.
*/
void LPUART1_IRQHandler(void)
{
/* USER CODE BEGIN LPUART1_IRQn 0 */
/* USER CODE END LPUART1_IRQn 0 */
HAL_UART_IRQHandler(&hlpuart1);
/* USER CODE BEGIN LPUART1_IRQn 1 */
/* USER CODE END LPUART1_IRQn 1 */
}
/* USER CODE BEGIN 1 */
/* USER CODE END 1 */

View File

@@ -25,6 +25,8 @@
/* USER CODE END 0 */
UART_HandleTypeDef hlpuart1;
DMA_HandleTypeDef hdma_lpuart1_rx;
DMA_HandleTypeDef hdma_lpuart1_tx;
/* LPUART1 init function */
@@ -39,7 +41,7 @@ void MX_LPUART1_UART_Init(void)
/* USER CODE END LPUART1_Init 1 */
hlpuart1.Instance = LPUART1;
hlpuart1.Init.BaudRate = 2000000;
hlpuart1.Init.BaudRate = 3000000;
hlpuart1.Init.WordLength = UART_WORDLENGTH_8B;
hlpuart1.Init.StopBits = UART_STOPBITS_1;
hlpuart1.Init.Parity = UART_PARITY_NONE;
@@ -157,7 +159,7 @@ void MX_USART1_UART_Init(void)
/* USER CODE END USART1_Init 1 */
USART_InitStruct.PrescalerValue = LL_USART_PRESCALER_DIV1;
USART_InitStruct.BaudRate = 1000000;
USART_InitStruct.BaudRate = 2000000;
USART_InitStruct.DataWidth = LL_USART_DATAWIDTH_8B;
USART_InitStruct.StopBits = LL_USART_STOPBITS_1;
USART_InitStruct.Parity = LL_USART_PARITY_NONE;
@@ -273,7 +275,7 @@ void MX_USART3_UART_Init(void)
/* USER CODE END USART3_Init 1 */
USART_InitStruct.PrescalerValue = LL_USART_PRESCALER_DIV1;
USART_InitStruct.BaudRate = 1000000;
USART_InitStruct.BaudRate = 2000000;
USART_InitStruct.DataWidth = LL_USART_DATAWIDTH_8B;
USART_InitStruct.StopBits = LL_USART_STOPBITS_1;
USART_InitStruct.Parity = LL_USART_PARITY_NONE;
@@ -340,6 +342,44 @@ void HAL_UART_MspInit(UART_HandleTypeDef* uartHandle)
GPIO_InitStruct.Alternate = GPIO_AF8_LPUART;
HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);
/* LPUART1 DMA Init */
/* LPUART1_RX Init */
hdma_lpuart1_rx.Instance = BDMA_Channel0;
hdma_lpuart1_rx.Init.Request = BDMA_REQUEST_LPUART1_RX;
hdma_lpuart1_rx.Init.Direction = DMA_PERIPH_TO_MEMORY;
hdma_lpuart1_rx.Init.PeriphInc = DMA_PINC_DISABLE;
hdma_lpuart1_rx.Init.MemInc = DMA_MINC_ENABLE;
hdma_lpuart1_rx.Init.PeriphDataAlignment = DMA_PDATAALIGN_BYTE;
hdma_lpuart1_rx.Init.MemDataAlignment = DMA_MDATAALIGN_BYTE;
hdma_lpuart1_rx.Init.Mode = DMA_NORMAL;
hdma_lpuart1_rx.Init.Priority = DMA_PRIORITY_LOW;
if (HAL_DMA_Init(&hdma_lpuart1_rx) != HAL_OK)
{
Error_Handler();
}
__HAL_LINKDMA(uartHandle,hdmarx,hdma_lpuart1_rx);
/* LPUART1_TX Init */
hdma_lpuart1_tx.Instance = BDMA_Channel1;
hdma_lpuart1_tx.Init.Request = BDMA_REQUEST_LPUART1_TX;
hdma_lpuart1_tx.Init.Direction = DMA_MEMORY_TO_PERIPH;
hdma_lpuart1_tx.Init.PeriphInc = DMA_PINC_DISABLE;
hdma_lpuart1_tx.Init.MemInc = DMA_MINC_ENABLE;
hdma_lpuart1_tx.Init.PeriphDataAlignment = DMA_PDATAALIGN_BYTE;
hdma_lpuart1_tx.Init.MemDataAlignment = DMA_MDATAALIGN_BYTE;
hdma_lpuart1_tx.Init.Mode = DMA_NORMAL;
hdma_lpuart1_tx.Init.Priority = DMA_PRIORITY_LOW;
if (HAL_DMA_Init(&hdma_lpuart1_tx) != HAL_OK)
{
Error_Handler();
}
__HAL_LINKDMA(uartHandle,hdmatx,hdma_lpuart1_tx);
/* LPUART1 interrupt Init */
HAL_NVIC_SetPriority(LPUART1_IRQn, 5, 0);
HAL_NVIC_EnableIRQ(LPUART1_IRQn);
/* USER CODE BEGIN LPUART1_MspInit 1 */
/* USER CODE END LPUART1_MspInit 1 */
@@ -365,6 +405,12 @@ void HAL_UART_MspDeInit(UART_HandleTypeDef* uartHandle)
HAL_GPIO_DeInit(GPIOB, GPIO_PIN_6);
/* LPUART1 DMA DeInit */
HAL_DMA_DeInit(uartHandle->hdmarx);
HAL_DMA_DeInit(uartHandle->hdmatx);
/* LPUART1 interrupt Deinit */
HAL_NVIC_DisableIRQ(LPUART1_IRQn);
/* USER CODE BEGIN LPUART1_MspDeInit 1 */
/* USER CODE END LPUART1_MspDeInit 1 */

View File

@@ -171,6 +171,17 @@ SECTIONS
. = ALIGN(8);
} >RAM_D1
.dma_buffer (NOLOAD):
{
/*_framebuffer =.; */
/*__framebuffer_start__ = _framebuffer; */
*(.dma_buffer)
*(.dma_buffer*)
} >RAM_D3
/* Remove information from the standard libraries */
/DISCARD/ :
{

View File

@@ -43,8 +43,9 @@ _Min_Stack_Size = 0x400; /* required amount of stack */
/* Specify the memory areas */
MEMORY
{
RAM_EXEC (xrw) : ORIGIN = 0x24000000, LENGTH = 320K
DTCMRAM (xrw) : ORIGIN = 0x20000000, LENGTH = 128K
RAM_EXEC (xrw) : ORIGIN = 0x24000000, LENGTH = 319K
RAM_NOINIT(xrw) : ORIGIN = 0x2404fc00, LENGTH = 1K
DTCMRAM (xrw) : ORIGIN = 0x20000000, LENGTH = 127K
ITCMRAM (xrw) : ORIGIN = 0x00000000, LENGTH = 64K
RAM_D2 (xrw) : ORIGIN = 0x30000000, LENGTH = 32K
RAM_D3 (xrw) : ORIGIN = 0x38000000, LENGTH = 16K
@@ -161,6 +162,12 @@ SECTIONS
. = ALIGN(8);
} >DTCMRAM
.noinit :
{
KEEP(*(.noinitdata))
} >DTCMRAM2
/* Remove information from the standard libraries */
/DISCARD/ :
{

View File

@@ -22,6 +22,7 @@ set(sources_SRCS ${sources_SRCS}
${CMAKE_CURRENT_SOURCE_DIR}/Core/Src/adc.c
${CMAKE_CURRENT_SOURCE_DIR}/Core/Src/crc.c
${CMAKE_CURRENT_SOURCE_DIR}/Core/Src/dma.c
${CMAKE_CURRENT_SOURCE_DIR}/Core/Src/bdma.c
${CMAKE_CURRENT_SOURCE_DIR}/Core/Src/fdcan.c
${CMAKE_CURRENT_SOURCE_DIR}/Core/Src/gpio.c
${CMAKE_CURRENT_SOURCE_DIR}/Core/Src/i2c.c

View File

@@ -4,5 +4,10 @@ add_subdirectory(nanopb)
add_subdirectory(ulog)
add_subdirectory(ina219)
add_library(EE24 STATIC "ee24/ee24.c")
target_include_directories(EE24 PUBLIC "ee24")
target_include_directories(EE24 PUBLIC "ee24")
add_library(TinyFrame STATIC "TinyFrame/TinyFrame.c")
target_include_directories(TinyFrame PUBLIC "./TinyFrame" "./TinyFrameConf")

1
lib/TinyFrame Submodule

Submodule lib/TinyFrame added at a29167a69f

View File

@@ -0,0 +1,81 @@
//
// TinyFrame configuration file.
//
// Rename to TF_Config.h
//
#ifndef TF_CONFIG_H
#define TF_CONFIG_H
#include <stdint.h>
#include <stdio.h> // used by the TF_Error() macro defined below
//#include <esp8266.h> // when using with esphttpd
//----------------------------- FRAME FORMAT ---------------------------------
// The format can be adjusted to fit your particular application needs
// If the connection is reliable, you can disable the SOF byte and checksums.
// That can save up to 9 bytes of overhead.
// ,-----+-----+-----+------+------------+- - - -+-------------,
// | SOF | ID | LEN | TYPE | HEAD_CKSUM | DATA | DATA_CKSUM |
// | 0-1 | 1-4 | 1-4 | 1-4 | 0-4 | ... | 0-4 | <- size (bytes)
// '-----+-----+-----+------+------------+- - - -+-------------'
// !!! BOTH PEERS MUST USE THE SAME SETTINGS !!!
// Adjust sizes as desired (1,2,4)
#define TF_ID_BYTES 2
#define TF_LEN_BYTES 2
#define TF_TYPE_BYTES 2
// Checksum type. Options:
// TF_CKSUM_NONE, TF_CKSUM_XOR, TF_CKSUM_CRC8, TF_CKSUM_CRC16, TF_CKSUM_CRC32
// TF_CKSUM_CUSTOM8, TF_CKSUM_CUSTOM16, TF_CKSUM_CUSTOM32
// Custom checksums require you to implement checksum functions (see TinyFrame.h)
#define TF_CKSUM_TYPE TF_CKSUM_CRC16
// Use a SOF byte to mark the start of a frame
#define TF_USE_SOF_BYTE 1
// Value of the SOF byte (if TF_USE_SOF_BYTE == 1)
#define TF_SOF_BYTE 0x55
//----------------------- PLATFORM COMPATIBILITY ----------------------------
// used for timeout tick counters - should be large enough for all used timeouts
typedef uint16_t TF_TICKS;
// used in loops iterating over listeners
typedef uint8_t TF_COUNT;
//----------------------------- PARAMETERS ----------------------------------
// Maximum received payload size (static buffer)
// Larger payloads will be rejected.
#define TF_MAX_PAYLOAD_RX 1024
// Size of the sending buffer. Larger payloads will be split to pieces and sent
// in multiple calls to the write function. This can be lowered to reduce RAM usage.
#define TF_SENDBUF_LEN 1024
// --- Listener counts - determine sizes of the static slot tables ---
// Frame ID listeners (wait for response / multi-part message)
#define TF_MAX_ID_LST 50
// Frame Type listeners (wait for frame with a specific first payload byte)
#define TF_MAX_TYPE_LST 5
// Generic listeners (fallback if no other listener catches it)
#define TF_MAX_GEN_LST 5
// Timeout for receiving & parsing a frame
// ticks = number of calls to TF_Tick()
#define TF_PARSER_TIMEOUT_TICKS 10
// Whether to use mutex - requires you to implement TF_ClaimTx() and TF_ReleaseTx()
#define TF_USE_MUTEX 1
// Error reporting function. To disable debug, change to empty define
#define TF_Error(format, ...) printf("[TF] " format "\n", ##__VA_ARGS__)
//------------------------- End of user config ------------------------------
#endif //TF_CONFIG_H

2
proto

Submodule proto updated: 30e74889a2...c46afcd594

View File

@@ -6,6 +6,8 @@ ${PROTO_SRC_DIR}/firmware.proto
${PROTO_SRC_DIR}/light.proto
${PROTO_SRC_DIR}/usb.proto
${PROTO_SRC_DIR}/cls_device.proto
${PROTO_SRC_DIR}/headlight.proto
${PROTO_SRC_DIR}/display.proto
)
# Specify where you want to generate the python code

13
tools/bootloader.py Normal file
View File

@@ -0,0 +1,13 @@
from usb_pb2 import PackageType, JumpToBootloader
from vcp_driver import *
if __name__ == "__main__":
ser = setup_connection()
# Create a message
request = JumpToBootloader()
request.magic = 0xdeadbeef
# Serialize the request to a bytearray
request_data = request.SerializeToString()
# Send the request
send_package(PackageType.JUMP_TO_BOOTLOADER, request_data, ser)

41
tools/display_test.py Normal file
View File

@@ -0,0 +1,41 @@
import serial
import struct
from google.protobuf.message import DecodeError
from serial.tools import list_ports
from display_pb2 import SetLayout
from usb_pb2 import PackageType
from vcp_driver import *
if __name__ == "__main__":
ser = setup_connection()
# Create a message
#request = GlobalBrightness()
#request.brightness = 100
# Serialize the request to a bytearray
#request_data = request.SerializeToString()
# Send the request
#send_package(PackageType.LIGHT_GLOBAL_BRIGHT, request_data, ser)
#request = GlobalTheme()
#request.theme = 1
#request_data = request.SerializeToString()
#send_package(PackageType.LIGHT_GLOBAL_THEME, request_data, ser)
# request = ThemeSettings()
# request.deviceId = 1
# request.theme = 1
# request.rgb = 0x00f000f0
# request.brightness = 255
# request.animation = 2
# request_data = request.SerializeToString()
# send_package(PackageType.LIGHT_SETTING_THEME, request_data, ser)
request = SetLayout()
request.layout = 2
request_data = request.SerializeToString()
send_package(PackageType.DISPLAY_SET_LAYOUT, request_data, ser)

View File

@@ -4,25 +4,26 @@ from google.protobuf.message import DecodeError
from serial.tools import list_ports
from light_pb2 import GlobalBrightness, Theme, GlobalTheme, ThemeSettings
from headlight_pb2 import Settings, RequestSettings
from usb_pb2 import PackageType
from vcp_driver import *
if __name__ == "__main__":
ser = setup_connection()
# Create a message
request = GlobalBrightness()
request.brightness = 100
#request = GlobalBrightness()
#request.brightness = 100
# Serialize the request to a bytearray
request_data = request.SerializeToString()
#request_data = request.SerializeToString()
# Send the request
send_package(PackageType.LIGHT_GLOBAL_BRIGHT, request_data, ser)
#send_package(PackageType.LIGHT_GLOBAL_BRIGHT, request_data, ser)
request = GlobalTheme()
request.theme = 1
request_data = request.SerializeToString()
send_package(PackageType.LIGHT_GLOBAL_THEME, request_data, ser)
#request = GlobalTheme()
#request.theme = 1
#request_data = request.SerializeToString()
#send_package(PackageType.LIGHT_GLOBAL_THEME, request_data, ser)
# request = ThemeSettings()
@@ -33,3 +34,14 @@ if __name__ == "__main__":
# request.animation = 2
# request_data = request.SerializeToString()
# send_package(PackageType.LIGHT_SETTING_THEME, request_data, ser)
request = Settings()
request.deviceId = 1
request.alpha = 0.001
request.on_threshold = 600
request.off_threshold = 400
request.on_time = 100
request.input_invert = False
request_data = request.SerializeToString()
send_package(PackageType.HEADLIGHT_SETTINGS, request_data, ser)

View File

@@ -30,7 +30,7 @@ def make_header(typeid: PackageType, length: int) -> bytearray:
struct_format = '<HHB' # '<' for little-endian, 'H' for uint16_t, 'B' for uint8_t
# Calculate the check byte as the sum of length and type
typeidint = int(typeid)
check = (length & 0xFF) + ((length >> 8) & 0xFF) + (typeidint & 0xFF) + ((typeidint >> 8) & 0xFF)
check = ((length & 0xFF) + ((length >> 8) & 0xFF) + (typeidint & 0xFF) + ((typeidint >> 8) & 0xFF) ) & 0xff
packed_data = struct.pack(struct_format, length, typeid, check)
return packed_data

View File

@@ -6,10 +6,10 @@ if __name__ == "__main__":
ser = setup_connection()
# Create a message
request = UpdateDeviceSettings()
request.device = 1
request.type = Type.LIGHT
request.position.append(Position.RIGHT)
request.position.append(Position.FLOOR)
request.device = 0
request.type = Type.COMMING_HOME
request.position.append(Position.LEFT)
request.position.append(Position.CENTER)
# Serialize the request to a bytearray
request_data = request.SerializeToString()

View File

@@ -3,21 +3,20 @@ import struct
from google.protobuf.message import DecodeError
from serial.tools import list_ports
from light_pb2 import RequestThemeSetting, Theme, ThemeSettings
from headlight_pb2 import Settings, RequestSettings
from usb_pb2 import PackageType
from vcp_driver import *
if __name__ == "__main__":
ser = setup_connection()
request = RequestThemeSetting()
request.deviceId = 0
request.theme = 1
request = RequestSettings()
request.deviceId = 1
print("send request")
print(request)
request_data = request.SerializeToString()
send_package(PackageType.LIGHT_REQUEST_THEME, request_data, ser)
send_package(PackageType.HEADLIGHT_REQUEST_SETTINGS, request_data, ser)
print("wait for response")
@@ -30,13 +29,13 @@ if __name__ == "__main__":
print(length, typeid, check)
# Check if the type is RESPONSE_DEVICE_LIST
if typeid == PackageType.LIGHT_SETTING_THEME:
if typeid == PackageType.HEADLIGHT_SETTINGS:
# Read the response data from the serial port
response_data = ser.read(length)
# Try to parse the data as a ResponseDeviceList message
try:
response = ThemeSettings.FromString(response_data)
response = Settings.FromString(response_data)
except DecodeError:
# If we get a DecodeError, it means the data we read is not a valid

13
tools/uart_in_test.py Normal file
View File

@@ -0,0 +1,13 @@
import serial
# Open the serial port
ser = serial.Serial('/dev/ttyACM1', baudrate=1000000)
# Send 10 bytes of data
data = b'01234567890123456789012345678901234567890123456789'
for i in range(10):
ser.write(data)
# Close the serial port
ser.close()

71
tools/upload_firmware.py Normal file
View File

@@ -0,0 +1,71 @@
import hmac
import hashlib
import sys
from pathlib import Path
import requests
import subprocess
import base64
def load_secret_key(keyb64: str):
# Decode the base64 encoded key
decoded_key = base64.b64decode(keyb64)
return decoded_key
def compute_hmac(file_path, secret_key):
"""Compute the HMAC of a file using HMAC-SHA256."""
hmac_obj = hmac.new(secret_key, digestmod=hashlib.sha256)
with open(file_path, 'rb') as f:
while chunk := f.read(4096):
hmac_obj.update(chunk)
return hmac_obj.hexdigest()
def upload_file(url, file_path, secret_key):
"""Upload a file to the server with an HMAC signature."""
# Compute HMAC of the file
signature = compute_hmac(file_path, secret_key)
print(signature)
# Prepare headers
headers = {'X-Signature': signature}
# Read file and prepare files dictionary for request
with open(file_path, 'rb') as f:
files = {'file': (Path(file_path).name, f)}
response = requests.post(url, files=files, headers=headers)
return response
def get_short_git_commit_hash():
try:
# Run the Git command to get the short commit hash
result = subprocess.run(['git', 'rev-parse', '--short', 'HEAD'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, check=True)
# Extract and return the commit hash
return result.stdout.strip()
except subprocess.CalledProcessError as e:
print(f"Error getting Git commit hash: {e}")
return None
if __name__ == "__main__":
url = "https://fw.revwal.de/master/upload" # Adjust this to your server's URL
fw_path = "build/CLS_Master.bin" # Path to the file you want to upload
# Get the Git commit hash
commit_hash = get_short_git_commit_hash()
if commit_hash is None:
print("Error: Could not get Git commit hash")
sys.exit(1)
# replace the file name with the commit hash
file_path = fw_path.replace("CLS_Master", commit_hash)
# copy the file to the new name
subprocess.run(['cp', fw_path, file_path])
secret_key = load_secret_key(sys.argv[1])
response = upload_file(url, file_path, secret_key)
print(f"Server response: {response.text}")