Backup before error handling refactoring

This commit is contained in:
jkwoo
2026-07-13 17:10:02 +09:00
commit 04fc19b485
1132 changed files with 347840 additions and 0 deletions

View File

@@ -0,0 +1,59 @@
# 9번 셀 밸런싱 비동작 원인 분석 보고서 (회로도 및 하드웨어 연계 분석)
제공해주신 회로도 PDF [001 CPU.SchDoc] 및 [003 AFE.SchDoc] 문서를 면밀히 분석한 결과, **수동 밸런싱 테스트에서 9번 셀만 동작하지 않는 문제의 하드웨어적 원인과 소프트웨어적 해결 방법**을 명확히 규명하였습니다.
---
## 1. 회로도 분석 결과 (핀 매핑 확인)
* **회로도 상 연결**:
- [001 CPU] 페이지의 **U1 (STM32F103CBT6)** 핀 맵에서 9번 셀 밸런싱 제어 네트인 `MCU_EN9/S9`는 **Pin 6 (`PD1/OSC_OUT`)**에 정상적으로 연결되어 있습니다.
- 또한, [008 Enable Control] 페이지에서도 `MCU_EN9/S9` 신호가 9번 셀 밸런싱용 스위칭 FET인 `Q27 (AM2336N)`의 게이트(Gate)를 제어하고 있습니다.
- 회로 상에서는 연결에 문제가 없는 설계입니다.
* **클럭 발진 회로 구성**:
- [001 CPU] 페이지 하단에 16MHz 클럭 발진부인 **`Y1` (SCO-103 16MHz)**이 배치되어 있습니다.
- 이 소자는 2핀 크리스탈이 아닌, 전원을 받아 스스로 클럭을 출력하는 **4핀 액티브 오실레이터 (Active Oscillator)**입니다.
- `Y1`의 3번 출력 핀(`OUTPUT`)은 MCU의 **Pin 5 (`PD0/OSC_IN`)**에 단독으로 클럭을 주입하고 있으며, 피드백 출력 핀인 **Pin 6 (`PD1/OSC_OUT`)**은 비어 있는 상태로 일반 GPIO로 활용하도록 설계되었습니다.
---
## 2. 근본적인 오동작 원인 (두 가지 조건 불충족)
STM32F10x MCU에서 `PD0``PD1` 핀을 클럭 오실레이터가 아닌 일반 GPIO 포트로 사용하기 위해서는 **반드시 아래 2가지 설정이 동시에 활성화**되어야 합니다.
1. **HSE Bypass 모드 활성화 (클럭 점유 해제)**:
- 기본 설정인 **HSE Crystal 모드**가 활성화되면 MCU 내부의 발진 회로가 활성화되어 `PD0 (OSC_IN)``PD1 (OSC_OUT)` 두 핀을 모두 발진용으로 강제 점유합니다.
- 외부 액티브 오실레이터처럼 이미 주입되는 클럭이 있는 환경에서는 **HSE Bypass 모드**를 켜주어야 `PD1` 핀이 클럭 공급 기능에서 해방됩니다.
2. **AFIO PD0/PD1 리맵 설정 (GPIO 포트 전환)**:
- 하드웨어적으로 클럭 점유가 해제되더라도, AFIO(Alternative Function IO) 레지스터 상에서 `PD0``PD1` 핀을 일반 GPIO 포트로 사용하겠다고 맵핑을 직접 변경해주어야 합니다.
- 이 설정이 누락될 경우 핀이 GPIO 입력/출력 레지스터와 물리적으로 연결되지 않아 밸런싱 활성화 신호가 나가지 않습니다.
---
## 3. 해결 방안 (소프트웨어 조치 완료)
하드웨어 개조 없이 소프트웨어 설정 변경을 통해 버그 수정을 완료하였습니다.
### 단계 1: 시스템 클럭 설정 코드 수정 (`system_stm32f10x.c`)
시스템 클럭을 72MHz로 설정하는 `SetSysClockTo72()` 함수 내부에서 **HSE Bypass(Bypassed) 설정을 추가**하였습니다.
* **수정 내역**:
```c
/* Enable HSE Bypass and then enable HSE */
RCC->CR |= ((uint32_t)RCC_CR_HSEBYP); // <-- Bypass 활성화 추가
RCC->CR |= ((uint32_t)RCC_CR_HSEON);
```
### 단계 2: AFIO 클럭 활성화 및 PD0/PD1 리맵핑 추가 (`led.c`)
`led.c`의 GPIO 초기화 함수인 `DIO_Init()` 내부에서 AFIO 주변장치 클럭을 활성화하고, `GPIO_Remap_PD01` 리맵 설정을 추가하였습니다.
* **수정 내역**:
```c
/* GPIO clock enable */
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOC, ENABLE);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOD, ENABLE);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_AFIO, ENABLE); // <-- AFIO 클럭 추가
//Serial port 1 pins reuse maps
GPIO_PinRemapConfig(GPIO_Remap_SWJ_Disable, ENABLE);
GPIO_PinRemapConfig(GPIO_Remap_PD01, ENABLE); // <-- PD0/PD1 리맵 추가
```

View File

@@ -0,0 +1,39 @@
# Implementation Plan: 21S Active Balancing Firmware
## 1. Objective
Port the active balancing functionality from the 18S reference firmware to the current 21S project, ensuring correct hardware control and build stability.
## 2. Requirements
- Implement active balancing logic (Buck/Boost between adjacent cells).
- Map 20 balancing control channels to STM32 GPIOs based on schematic.
- Maintain compatibility with existing CAN communication and status reporting.
- Record all changes in `Revision History.txt`.
## 3. Implementation Steps
### Phase 1: Infrastructure and Data Structures (Completed)
- [x] Define `TBalanceEnable` union for 20 channels in `device_param.h`.
- [x] Add `balance_enable` field to `TDEVICE_STATUS`.
- [x] Update `ltc6813_comm.h` with new function prototypes.
- [x] Add `MP2642` control prototypes to `io.h`.
### Phase 2: Hardware Mapping (Completed)
- [x] Extract GPIO mapping for `MCU_EN1`~`MCU_EN20` from schematic.
- [x] Update `led.h` with accurate pin definitions.
- [x] Update `led.c` (`DIO_Init`) to initialize all balancing pins.
- [x] Implement `MP2642_Enable_Ctrl` and `MP2642_EnaDis_All` in `io.c`.
### Phase 3: Core Logic Porting (Completed)
- [x] Port `AutoBalancingActive`, `CalcBalancingVolt`, and `CheckCbRest` to `ltc6813_comm.c`.
- [x] Integrate `AutoBalancingActive` into `App_TaskBatt`.
- [x] Update manual balancing control to support active balancing FETs.
- [x] Fix undefined variable build errors (`ManualMdBalEnable`, `ManualMdBalMode`).
### Phase 4: Verification and Polish (Next Steps)
- [ ] Perform full build and verify zero errors/warnings.
- [ ] Verify `CB_Rest` rotation logic (Odd/Even channels) via debug logs or LEDs.
- [ ] Finalize `Revision History.txt` documentation.
## 4. Documentation Management
- All plans and design documents will be stored in the `/DOC` folder.
- `Revision History.txt` will be updated for every version change.

View File

@@ -0,0 +1,57 @@
# Project Improvement Suggestions: BMU 21S Application
Based on the analysis of the current codebase, the following improvements are suggested to enhance the system's stability, reliability, and maintainability.
## 1. Critical Reliability & Stability Improvements
### 1.1 Removal of Dynamic Memory Allocation (`malloc`/`free`)
- **Issue:** In `APP/battery_comm.c` (e.g., `ltc6813_wrcfg`, `ltc6813_rdcfg`), `malloc` and `free` are used inside functional calls.
- **Risk:** In an embedded RTOS environment, frequent dynamic allocation can lead to **heap fragmentation** and unpredictable `NULL` returns, potentially causing system crashes.
- **Recommendation:** Replace dynamic buffers with **static buffers** or **pre-allocated memory pools** since the maximum number of ICs in the daisy chain is typically constant.
### 1.2 Robust Error Handling for SPI/CAN Communication
- **Issue:** Many communication functions (e.g., `request_battery_voltage`) send commands but do not verify if the response is valid or if the hardware encountered an error.
- **Risk:** The system may process "garbage" data as valid cell voltages, leading to incorrect battery state estimation or failure to trigger alarms.
- **Recommendation:**
- Implement **return value checks** for all SPI/CAN read/write operations.
- Strictly enforce **PEC (Packet Error Code)** verification for every single packet received from LTC6813.
- Implement a **retry mechanism** (e.g., 3 attempts) before flagging a communication failure.
### 1.3 Improvement of `send_wakeup_signal` Logic
- **Issue:** `send_wakeup_signal` is called frequently (e.g., inside `App_TaskBatt` loop and multiple times in `request_battery_voltage`).
- **Risk:** Excessive wakeup signals may increase power consumption or interfere with the IC's internal state machine.
- **Recommendation:** Implement a **state-aware wakeup** mechanism that only sends the signal when the IC is actually in sleep mode or after a specific timeout.
## 2. Performance & Architecture Optimization
### 2.1 Task Priority Re-evaluation
- **Current State:**
- `BATT task` (Prio 3) $\rightarrow$ Highest
- `CAN Comm Task` (Prio 4)
- `Temp task` (Prio 5)
- `IO task` (Prio 6)
- **Analysis:** While battery monitoring is critical, CAN communication (handling requests and sending alarms) is also time-sensitive.
- **Recommendation:** Evaluate if `CAN Comm Task` needs a higher priority to ensure timely response to host commands, especially during critical fault conditions.
### 2.2 Use of DMA for Communication
- **Issue:** SPI and CAN operations currently appear to be synchronous/blocking (e.g., `SPI2_ReadWriteByte`).
- **Risk:** The CPU wastes cycles waiting for slow peripheral hardware, increasing CPU load.
- **Recommendation:** Implement **DMA (Direct Memory Access)** for SPI and CAN transfers to allow the CPU to perform other calculations while data is being moved.
## 3. Maintainability & Code Quality
### 3.1 Elimination of "Magic Numbers"
- **Issue:** Many hard-coded hex values are used for commands and PECs (e.g., `0x77D6`, `0xEA80` in `battery_comm.c`).
- **Recommendation:** Define these as **named constants** or macros in a header file (e.g., `#define LTC6813_CMD_RDCVA_PEC 0x77D6`) to improve readability and ease of modification.
### 3.2 Centralized Error Logging
- **Issue:** Debugging currently relies on `printf` and `NormalOutXY` scattered across the code.
- **Recommendation:** Implement a **centralized logging module** with different levels (`INFO`, `WARN`, `ERROR`) that can be routed to UART, CAN, or a diagnostic buffer.
## Summary of Priority
| Priority | Improvement | Impact |
| :--- | :--- | :--- |
| **Highest** | Remove `malloc`/`free` | System Stability |
| **High** | Strengthen PEC/Error Checking | Data Integrity |
| **Medium** | Implement DMA | CPU Efficiency |
| **Low** | Replace Magic Numbers | Maintainability |

View File

@@ -0,0 +1,42 @@
# Implementation Plan: Precise Alignment of Forced Balancing with Reference
## 1. Objective
Ensure that the `CanRspForcedBalancingCode` and manual balancing control logic precisely match the reference firmware's behavior and data format, while maintaining support for the 21-cell architecture.
## 2. Requirements
- Align `CanRspForcedBalancingCode` payload with the reference format.
- Support `ManualBalFlag == 2` for direct hardware actuation.
- Handle mode switching (Auto/Manual) exactly as the reference does.
- Maintain documentation in `Revision History.txt`.
## 3. Implementation Steps
### Step 1: Align CAN Response (`can_data_process.c`)
- [ ] Update `CanRspForcedBalancingCode`:
- Process `data->Data[0]` for mode switching.
- Process `data->Data[4]` for potential module balancing (even if currently unused).
- Construct the 8-byte response packet to match the reference:
- Byte 0: `ManualBalFlag`
- Byte 1: `ManualBalEnable` (LSB)
- Byte 2: `ManualBalMode` (LSB)
- Byte 3: 0
- Byte 4: `ManualMdBalMode` (Placeholder)
- Byte 5: `ManualMdBalEnable` (Placeholder)
- Byte 6: `AutoMdBalEnable` (Placeholder)
### Step 2: Refine Manual Control Logic (`ltc6813_comm.c`)
- [ ] Update `SetManualBalancing`:
- Implement logic for `ManualBalFlag == 2` to directly call `MP2642_Enable_Ctrl`.
- Maintain bitmask accumulation for `ManualBalFlag == 1`.
- [ ] Ensure `ManualCellBalancing` correctly handles the `ManualBalFlag` states (0, 1).
### Step 3: Version Update
- [ ] Update `APP_VER_COMPILE` to 4 in `app_ver.c`.
- [ ] Update `BD_MODEL` to "BMU-21S" in `app_ver.h`.
### Step 4: Documentation
- [ ] Update `Revision History.txt`.
## 4. Verification
- [ ] Perform full build.
- [ ] Confirm that CAN responses match the expected reference format.

View File

@@ -0,0 +1,22 @@
# Implementation Plan: CAN Balancing Status Transmission
## 1. Objective
Update the CAN communication logic to transmit the active balancing status of the 21-cell (20-channel) system, ensuring the host can monitor which cells are currently being balanced.
## 2. Requirements
- Report the current active balancing state via `CAN_RSP_BALANCING_CODE` (111).
- Use the `balance_enable` field from `TDEVICE_STATUS` which tracks the actual FET states.
- Maintain compatibility with the reference 8-byte response format.
## 3. Implementation Steps
### Step 1: Logic Update in `can_data_process.c`
- [x] Modify `CanRspBalancingCode` to send `device_status.balance_enable.value`.
- [x] Verify that `balance_enable.value` (32-bit) correctly maps to the 3-byte field (Bytes 4, 5, 6) in the CAN packet, covering all 20 balancing channels.
### Step 2: Documentation
- [x] Update `Revision History.txt` with the CAN reporting change.
## 4. Verification
- [ ] Perform build.
- [ ] (Optional/User) Verify CAN packet data on the host side while balancing is active.

View File

@@ -0,0 +1,24 @@
# Implementation Plan: Fix Build Post-Processing Scripts
## 1. Objective
Correct the post-build scripts (`CopyHex_Flash.bat` and `Hex2Bin_Flash.bat`) to use the latest build output from the `unify_builder` tool and update the output file name to match the new version (V1.0.0.4).
## 2. Requirements
- Ensure `CopyHex_Flash.bat` points to the correct source: `build\BMU_21S_APP\BMU_21S_APP.hex`.
- Update the output file name in both scripts to `BMU_21S_APP_V1004.hex`.
- Maintain synchronization between hex copying and binary generation.
## 3. Implementation Steps
### Step 1: Fix `CopyHex_Flash.bat`
- [x] Change the copy command to: `copy build\BMU_21S_APP\BMU_21S_APP.hex Flash\BMU_21S_APP_V1004.hex`.
### Step 2: Fix `Hex2Bin_Flash.bat`
- [x] Update the conversion command to: `hex2bin.exe -b .\FLASH\BMU_21S_APP_V1004.hex`.
### Step 3: Documentation
- [x] Update `Revision History.txt`.
## 4. Verification
- [ ] Run the build.
- [ ] Verify that `Flash\BMU_21S_APP_V1004.bin` is generated with the current timestamp.

View File

@@ -0,0 +1,36 @@
# Implementation Plan: Porting Forced Balancing and Manual Control
## 1. Objective
Port the manual control (Forced Balancing) logic from the reference firmware to allow explicit control over individual balancing channels and toggle between Auto and Manual balancing modes.
## 2. Requirements
- Implement `CAN_REQ_FORCED_BALANCING_CODE` (12) handling to:
- Toggle `ACB` (Auto Cell Balancing) mode.
- Set specific channels for manual balancing.
- Respond with the current manual control status.
- Update `SetManualBalancing` to process channel-specific commands.
- Update `ManualCellBalancing` to actuate FETs based on manual settings.
## 3. Implementation Steps
### Step 1: CAN Logic Update (`can_data_process.c`)
- [x] Modify `CanRspForcedBalancingCode`:
- If `data->Data[0] == 0`, set `device_status.battery_status.bit.ACB = 1` (Auto Mode).
- If `data->Data[0] == 1`, set `device_status.battery_status.bit.ACB = 0` (Manual Mode).
- Call `SetManualBalancing` with the received data.
- Construct and send `CAN_RSP_FORCED_BALANCING_CODE` (121) with current `ManualBal` flags and values.
### Step 2: Balancing Logic Update (`ltc6813_comm.c`)
- [x] Update `SetManualBalancing(uint8_t flag, uint8_t *data)`:
- Extract `ch`, `mode`, `enable` from `data[1]`, `data[2]`, `data[3]`.
- Update `ManualBalEnable` and `ManualBalMode` bitmasks accordingly.
- [x] Update `ManualCellBalancing`:
- If `ManualBalFlag == 1`, use `ManualBalEnable` to control `MP2642` FETs.
- If `ManualBalFlag == 0`, disable all FETs.
### Step 3: Documentation
- [x] Update `Revision History.txt`.
## 4. Verification
- [ ] Build the project and ensure no errors.
- [ ] Verify mode switching between Auto/Manual via CAN.

View File

@@ -0,0 +1,25 @@
# Implementation Plan: Porting STATUS5 CAN Transmission
## 1. Objective
Port the `CAN_RSP_STATUS5_CODE` (15) transmission logic from the reference firmware to provide the host with visibility into both the desired (`balance_enable`) and actual (`cellbalance`) balancing states.
## 2. Requirements
- Implement `Status #5` response in `CanRspStatusCode`.
- Transmit 8 bytes:
- Bytes 0-3: `device_status.balance_enable.value` (Current Operating Status - 20 bits).
- Bytes 4-7: `device_status.balance_enable.value` (Mirroring current status to ensure visibility in all modes).
- Ensure this value reflects both Auto and Manual balancing states.
## 3. Implementation Steps
### Step 1: Update `CanRspStatusCode` in `can_data_process.c`
- [ ] Add `delay_os_ms(1);` at the end of the current `CanRspStatusCode` function.
- [ ] Implement `Status #5` transmission using `CAN_RSP_STATUS5_CODE`.
- [ ] Map `balance_enable.value` and `cellbalance.value` to the 8-byte packet as specified.
### Step 2: Documentation
- [ ] Update `Revision History.txt`.
## 4. Verification
- [ ] Build the project and ensure no errors.
- [ ] Verify that 5 status messages (ID 211, 212, 213, 214, 215) are transmitted in sequence when requested.

View File

@@ -0,0 +1,26 @@
# Implementation Plan: Module Balancing Removal and Warning Fix
## 1. Objective
Remove the "Module Balancing" feature as it is not required for this project, and resolve compilation warnings identified in the latest build.
## 2. Requirements
- Remove all code related to `ManualMdBalEnable`, `ManualMdBalMode`, and `SetManualBalancingMd`.
- Fix implicit declaration warnings for `MP2642_Enable_Ctrl` and `MP2642_EnaDis_All`.
- Clean up unused variables to ensure a warning-free build.
## 3. Implementation Steps
### Step 1: Interface Cleanup
- [x] Remove `SetManualBalancingMd` prototype from `ltc6813_comm.h`.
### Step 2: Implementation Cleanup and Fixes
- [x] Remove `ManualMdBalEnable` and `ManualMdBalMode` from `ltc6813_comm.c`.
- [x] Remove `SetManualBalancingMd` implementation from `ltc6813_comm.c`.
- [x] Add `#include "io.h"` to `ltc6813_comm.c` to provide prototypes for `MP2642` control functions.
- [x] Remove unused `error` variable in `ReadCellVoltage` function in `ltc6813_comm.c`.
### Step 3: Documentation
- [x] Update `Revision History.txt`.
## 4. Verification
- [ ] Perform build and confirm 0 errors and 0 warnings (related to the changes).

63
DOC/project_analysis.md Normal file
View File

@@ -0,0 +1,63 @@
# Project Analysis: BMU 21S Application
## 1. Project Overview
This project is a firmware implementation for a **Battery Management Unit (BMU)**, specifically designed for a 21S (21 cells in series) configuration. It is built on an **STM32F10x** microcontroller platform and utilizes the **$\mu$C/OS-III** Real-Time Operating System (RTOS).
## 2. System Architecture
### 2.1 Hardware Abstraction & Drivers
- **MCU:** STM32F10x (Cortex-M3).
- **Communication Interfaces:**
- **CAN Bus:** Used for high-level communication (likely with a host controller).
- **SPI:** Used for communicating with battery monitoring ICs (LTC6813).
- **UART/Console:** Used for debugging and user interface.
- **Peripheral Drivers:** Standard STM32 peripheral drivers (`FWLIB`) are used for GPIO, SPI, CAN, etc.
### 2.2 Software Layers
- **Application Layer (`APP/`):** Contains the core business logic, including battery management, CAN communication, and task management.
- **Middleware/OS Layer (`UCOSIII/`):** $\mu$C/OS-III provides task scheduling, semaphores, mutexes, and message queues.
- **Hardware Abstraction Layer (`HARDWARE/`, `SYSTEM/`):** Provides low-level drivers for SPI, CAN, IWDG, LED, and system utilities (delay, usart).
- **Library Layer (`FWLIB/`):** STM32 Standard Peripheral Library.
## 3. Core Functional Modules
### 3.1 Battery Management (`APP/battery_comm.c`)
- **LTC6813 Interface:** Implements SPI communication to interact with LTC6813 battery monitoring ICs.
- **Cell Voltage Monitoring:** Functions like `request_battery_voltage_A/B/C/D` allow reading voltages from different cell groups.
- **Configuration:** Supports reading and writing configuration registers to the LTC6813 daisy chain.
- **Daisy Chain Support:** Handles multiple ICs connected in a daisy chain via SPI.
### 3.2 CAN Communication (`APP/can_comm.c`)
- **Task-Based:** Runs in a dedicated `can_comm_task`.
- **Packet Processing:**
- **Firmware Update:** Handles incoming packets for F/W updates (`FwUpdateProcess`).
- **Normal Communication:** Processes standard data packets (`CanRxDataProcess`).
- **Inventory Data:** Processes inventory-related packets (`CanRxInvDataProcess`).
- **Reliability:** Includes timeout checks (`CanCommFailCheck`) and error handling for the CAN peripheral.
### 3.3 Task Management & OS Integration
The system is highly multi-tasked, with tasks running at different priorities:
| Task Name | Priority | Description |
| :--- | :--- | :--- |
| `BATT task` | 3 | Battery monitoring and LTC6813 communication. |
| `CAN Comm Task` | 4 | CAN bus communication and packet processing. |
| `Temp task` | 5 | Temperature monitoring. |
| `IO task` | 6 | General I/O operations. |
| `Start Task` | 7 | Initialization and task creation. |
`APP/task_manager.c` manages Task Control Blocks (TCB) and provides debugging utilities to monitor task CPU usage and stack status.
## 4. Project Structure Summary
- `APP/`: High-level application logic.
- `CORE/`: Core startup and processor-specific code.
- `DOC/`: Documentation and analysis reports.
- `FWLIB/`: STM32 peripheral drivers.
- `HARDWARE/`: Low-level hardware drivers (SPI, CAN, etc.).
- `SYSTEM/`: System-level utilities (Delay, USART).
- `UCOSIII/`: $\mu$C/OS-III RTOS source and configuration.
- `USER/`: Main entry point (`main.c`), project configuration (Keil), and build artifacts.
## 5. Key Observations
- **Safety-Critical Design:** Use of an RTOS, watchdog (IWDG), and PEC (Packet Error Code) for SPI/CAN indicates a focus on reliability and safety.
- **Modular Design:** Clear separation between hardware drivers, OS, and application logic.
- **Daisy Chain Support:** Specifically designed to handle multiple battery monitoring chips in a sequence.