# DiagCore **Repository Path**: ivanchain/DiagCore ## Basic Information - **Project Name**: DiagCore - **Description**: No description available - **Primary Language**: Unknown - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2026-11-12 - **Last Updated**: 2026-11-12 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # FreeRTOS APP Layer UDS Stack 这是一个运行在 APP 层的 ISO 14229 UDS 诊断协议栈骨架。协议栈不直接绑定 CAN、CAN FD、DoIP、ISO-TP、NVM 或 Flash 驱动,ECU/OEM 相关行为通过回调和表配置接入。 ## 文件 - `include/uds.h` / `src/uds.c`: UDS 服务分发、正负响应、会话、安全访问、传输流程和默认状态机。 - `include/uds_did_mgr.h` / `src/uds_did_mgr.c`: 表驱动 DID 管理,支持固定数据、RAM 数据和自定义 read/write/io-control handler。 - `include/uds_dtc_mgr.h` / `src/uds_dtc_mgr.c`: 表驱动 DTC 管理,支持状态管理、清除、按状态掩码查询、快照和扩展数据 handler。 - `include/uds_default_tables.h` / `src/uds_default_tables.c`: 常用 DID/DTC 默认表,可直接初始化 DID/DTC 管理器。 - `include/uds_service_cfg.h` / `src/uds_service_cfg.c`: 服务 ID 支持矩阵,配置 SID 是否支持、允许会话和安全等级。 - `include/uds_log.h` / `src/uds_log.c`: 可选 debug 日志输出,使用宏控制是否编译。 ## 已覆盖服务 内置处理常用服务: - `0x10` DiagnosticSessionControl - `0x11` ECUReset - `0x14` ClearDiagnosticInformation - `0x19` ReadDTCInformation - `0x22` ReadDataByIdentifier - `0x27` SecurityAccess - `0x2E` WriteDataByIdentifier - `0x2F` InputOutputControlByIdentifier - `0x31` RoutineControl - `0x34` RequestDownload - `0x35` RequestUpload - `0x36` TransferData - `0x37` RequestTransferExit - `0x3E` TesterPresent 差异较大的服务通过 `generic_service` 回调接管,例如 `0x23/0x24/0x28/0x29/0x2A/0x2C/0x38/0x3D/0x83/0x84/0x85/0x86/0x87`。 ## FreeRTOS 接入 ISO-TP 或 DoIP 完成分段重组后,把完整诊断请求 PDU 投递到诊断任务;诊断任务调用 `Uds_OnRequest()`;UDS 响应通过 `transmit` 回调交给下层发送。 ```c #include "uds.h" #include "uds_did_mgr.h" #include "uds_dtc_mgr.h" #include "uds_default_tables.h" #include "uds_service_cfg.h" #include "uds_storage.h" static uint8_t uds_tx_buffer[4096]; static Uds_Context uds_ctx; static Uds_DidManager did_mgr; static Uds_DtcManager dtc_mgr; static Uds_ServiceConfig service_cfg; static Uds_StorageContext storage_ctx; static bool did_dirty[32]; static uint8_t storage_work_buffer[128]; static void UdsTx(const uint8_t *data, size_t len, Uds_AddressingType addressing) { (void)addressing; /* IsoTp_Send(data, len); */ } static Uds_AppResult ReadDid(uint16_t did, uint8_t *data, size_t capacity, size_t *len, Uds_NegativeResponseCode *nrc) { return Uds_DidManager_Read(&did_mgr, did, data, capacity, len, nrc); } static Uds_AppResult WriteDid(uint16_t did, const uint8_t *data, size_t len, Uds_NegativeResponseCode *nrc) { return Uds_DidManager_Write(&did_mgr, did, data, len, nrc); } static Uds_AppResult ClearDtc(uint8_t sub_function, const uint8_t *request, size_t request_len, uint8_t *response, size_t capacity, size_t *response_len, Uds_NegativeResponseCode *nrc) { return Uds_DtcManager_Clear(&dtc_mgr, sub_function, request, request_len, response, capacity, response_len, nrc); } static Uds_AppResult ReadDtc(uint8_t sub_function, const uint8_t *request, size_t request_len, uint8_t *response, size_t capacity, size_t *response_len, Uds_NegativeResponseCode *nrc) { return Uds_DtcManager_Read(&dtc_mgr, sub_function, request, request_len, response, capacity, response_len, nrc); } static bool ServiceAllowed(uint8_t sid, Uds_Session session, Uds_SecurityLevel security) { return Uds_ServiceConfig_IsSupported(&service_cfg, sid, session, security); } void Uds_AppInit(void) { Uds_StorageConfig storage_cfg = { .read_block = NvReadBlock, .write_block = NvWriteBlock, .driver_user_data = NULL, .work_buffer = storage_work_buffer, .work_buffer_len = sizeof(storage_work_buffer), .periodic_save_ms = 5000u, .restore_did_on_init = true, .restore_dtc_on_init = true, .save_did = true, .save_dtc = true, }; Uds_Config cfg = { .tx_buffer = uds_tx_buffer, .tx_buffer_len = sizeof(uds_tx_buffer), .timing = { .p2_ms = 50u, .p2_star_ms = 5000u, .s3_ms = 5000u, .response_pending_period_ms = 1000u, .security_delay_ms = 5000u, .max_security_attempts = 3u, .max_transfer_block_len = 4095u, }, .callbacks = { .transmit = UdsTx, .read_did = ReadDid, .write_did = WriteDid, .clear_dtc = ClearDtc, .read_dtc = ReadDtc, .service_allowed = ServiceAllowed, }, }; Uds_DefaultTables_Init(&did_mgr, &dtc_mgr); Uds_DefaultServiceConfig_Init(&service_cfg); Uds_Storage_Init(&storage_ctx, &did_mgr, &dtc_mgr, &storage_cfg, did_dirty, sizeof(did_dirty) / sizeof(did_dirty[0])); Uds_Init(&uds_ctx, &cfg); } ``` ## 默认 DID 表 `uds_default_tables` 提供常用 DID,早期集成可直接使用,量产时应按 ECU/OEM 规范替换默认值和访问权限。 - `0xF180` Boot Software Identification - `0xF181` Application Software Identification - `0xF182` Application Data Identification - `0xF183` Boot Software Fingerprint - `0xF186` Active Diagnostic Session - `0xF187` Spare Part Number - `0xF188` ECU Software Number - `0xF189` ECU Software Version - `0xF18A` System Supplier Identifier - `0xF18B` ECU Manufacturing Date - `0xF18C` ECU Serial Number - `0xF190` VIN - `0xF191` ECU Hardware Number - `0xF192` ECU Hardware Version - `0xF193` Supplier ECU Software Version - `0xF198` Repair Shop Code - `0xF199` Programming Date ## 默认 DTC 表 默认 DTC 使用项目内部示例编码。实际项目中 DTC 编码通常由 OEM 诊断规范定义。 - `UDS_DTC_SUPPLY_VOLTAGE_TOO_LOW` - `UDS_DTC_SUPPLY_VOLTAGE_TOO_HIGH` - `UDS_DTC_INTERNAL_ECU_FAULT` - `UDS_DTC_NVM_CHECKSUM_FAULT` - `UDS_DTC_FLASH_PROGRAMMING_FAULT` - `UDS_DTC_CAN_BUS_OFF` - `UDS_DTC_CAN_MESSAGE_TIMEOUT` - `UDS_DTC_LOST_COMMUNICATION_WITH_GATEWAY` - `UDS_DTC_SENSOR_SUPPLY_SHORT_TO_GROUND` - `UDS_DTC_SENSOR_SIGNAL_OPEN_CIRCUIT` - `UDS_DTC_ACTUATOR_OPEN_CIRCUIT` - `UDS_DTC_ACTUATOR_SHORT_TO_BATTERY` - `UDS_DTC_TEMPERATURE_TOO_HIGH` ## 服务 ID 支持表 `uds_service_cfg` 用表格控制服务是否支持,以及在哪些会话和安全等级下允许访问。默认表关闭了高风险或 OEM 差异较大的服务,例如 `ReadMemoryByAddress`、`WriteMemoryByAddress`、`RequestFileTransfer`。 表项格式: ```c typedef struct { uint8_t sid; bool supported; uint8_t session_mask; uint8_t security_mask; } Uds_ServiceConfigEntry; ``` 自定义示例: ```c static const Uds_ServiceConfigEntry app_services[] = { {UDS_SVC_DIAGNOSTIC_SESSION_CONTROL, true, UDS_SESSION_ALL_MASK, UDS_SECURITY_ALL_MASK}, {UDS_SVC_READ_DATA_BY_IDENTIFIER, true, UDS_SESSION_ALL_MASK, UDS_SECURITY_ALL_MASK}, {UDS_SVC_WRITE_DATA_BY_IDENTIFIER, true, UDS_SESSION_EXTENDED_MASK, UDS_SECURITY_LEVEL_1_MASK}, {UDS_SVC_REQUEST_DOWNLOAD, false, UDS_SESSION_PROGRAMMING_MASK, UDS_SECURITY_LEVEL_2_MASK}, }; Uds_ServiceConfig_Init(&service_cfg, app_services, sizeof(app_services) / sizeof(app_services[0]), false); ``` `default_supported = false` 表示表里没有列出的 SID 默认不支持;量产项目建议保持这个策略。 ## 业务侧访问 业务逻辑不需要构造 UDS 报文,可直接读写 DID 和维护 DTC 状态。 ```c uint8_t value[17] = "L1234567890123456"; size_t value_len = 0u; uint8_t dtc_status = 0u; (void)Uds_DidManager_BusinessSet(&did_mgr, UDS_DID_VIN, value, 17u); if (Uds_DidManager_BusinessRead(&did_mgr, UDS_DID_VIN, value, sizeof(value), &value_len) == UDS_APP_OK) { /* 使用 value/value_len */ } (void)Uds_DtcManager_SetStatusBits(&dtc_mgr, UDS_DTC_SUPPLY_VOLTAGE_TOO_LOW, UDS_DTC_STATUS_TEST_FAILED | UDS_DTC_STATUS_CONFIRMED_DTC); (void)Uds_DtcManager_ClearStatusBits(&dtc_mgr, UDS_DTC_SUPPLY_VOLTAGE_TOO_LOW, UDS_DTC_STATUS_TEST_FAILED); if (Uds_DtcManager_ReadStatus(&dtc_mgr, UDS_DTC_SUPPLY_VOLTAGE_TOO_LOW, &dtc_status)) { /* 使用 dtc_status */ } ``` ## NVM/Flash 持久化 `uds_storage` 提供类似 AUTOSAR NvM 的使用模型:上电读取全部块,运行时 RAM mirror 变化后置 dirty,下电保存全部块,任务周期保存 dirty 块。底层可以接 EEPROM、Flash EEPROM emulation、AUTOSAR NvM 或自研 Flash block driver。 底层只需要实现两个 block 接口: ```c static Uds_StorageResult NvReadBlock(uint32_t block_id, uint8_t *data, size_t len, void *user_data) { (void)user_data; /* 读取 block_id 对应的 NVM/Flash 数据到 data */ return UDS_STORAGE_OK; } static Uds_StorageResult NvWriteBlock(uint32_t block_id, const uint8_t *data, size_t len, void *user_data) { (void)user_data; /* 将 data 写入 block_id 对应的 NVM/Flash 块 */ return UDS_STORAGE_OK; } ``` 推荐调用点: ```c /* 上电初始化:Uds_Storage_Init 内部可根据配置自动 ReadAll,也可以显式调用 PowerOnRead */ Uds_Storage_Init(&storage_ctx, &did_mgr, &dtc_mgr, &storage_cfg, did_dirty, did_dirty_count); (void)Uds_Storage_PowerOnRead(&storage_ctx); /* 10ms 或 100ms 任务周期调用,用于定时保存 dirty 数据 */ Uds_Storage_MainFunction(&storage_ctx, elapsed_ms); /* KL15 off、MCU sleep 前、下电保持窗口内调用 */ (void)Uds_Storage_PowerDownSave(&storage_ctx); ``` Block ID 规则: - DID block: `UDS_STORAGE_DID_BLOCK_BASE | did`,例如 VIN `0x0001F190`。 - DTC status block: `UDS_STORAGE_DTC_STATUS_BLOCK_ID`。 DID 默认按每个可持久化 RAM DID 一个 block 保存;DTC 状态统一保存为一个状态 block。这个策略写放大较低,且便于把 DID 和 DTC 映射到不同 Flash sector 或 NvM block。 ## UDS 超时机制 UDS 栈内部维护以下应用层定时器: - `S3`: 非默认会话下,超过 `s3_ms` 未收到请求则回到默认会话,并锁定安全等级。 - `SecurityDelay`: 安全访问失败达到阈值后,`security_delay_ms` 内拒绝新的 seed 请求。 - `P2/P2*`: 服务回调返回 `UDS_APP_PENDING` 时立即发送 `0x7F SID 0x78`,随后由 `Uds_MainFunction()` 按 `response_pending_period_ms` 周期继续发送 `0x78`,直到业务完成或 `p2_star_ms` 超时取消。 - `BusyRepeat`: pending 未完成时收到新请求,UDS 返回 `0x21 busyRepeatRequest`。 异步服务调用方式: ```c static Uds_AppResult StartLongRoutine(uint8_t routine_control_type, uint16_t routine_id, const uint8_t *data, size_t len, uint8_t *response, size_t capacity, size_t *response_len, Uds_NegativeResponseCode *nrc) { (void)routine_control_type; (void)routine_id; (void)data; (void)len; (void)response; (void)capacity; (void)response_len; (void)nrc; /* 启动耗时任务,稍后由业务任务调用 Uds_CompletePendingPositive/Negative */ return UDS_APP_PENDING; } void LongRoutine_Done(void) { uint8_t payload[] = {0x01u, 0x12u, 0x34u}; /* routineControlType + routineId */ (void)Uds_CompletePendingPositive(&uds_ctx, payload, sizeof(payload)); } void LongRoutine_Failed(void) { (void)Uds_CompletePendingNegative(&uds_ctx, UDS_NRC_GENERAL_PROGRAMMING_FAILURE); } ``` `Uds_MainFunction()` 必须周期调用,建议 5ms 或 10ms: ```c Uds_MainFunction(&uds_ctx, elapsed_ms); ``` ## Debug 日志 日志默认不编译,不增加运行时代码。开启方式: ```powershell cmake -S . -B .tools\build-log -G "MinGW Makefiles" -DUDS_LOG_ENABLE=ON cmake --build .tools\build-log ``` 或直接给编译器传宏: ```c -DUDS_LOG_ENABLE=1 ``` 应用层绑定串口输出: ```c #include "uds_log.h" static void UartLogOutput(const char *text, void *user_data) { (void)user_data; Uart_Send((const uint8_t *)text, strlen(text)); Uart_Send((const uint8_t *)"\r\n", 2u); } void App_Init(void) { Uds_LogSetOutput(UartLogOutput, NULL); } ``` 日志覆盖关键路径: - UDS 收发 PDU、负响应、pending 开始/结束、P2* 超时、S3 超时。 - DID 读取、写入、业务设置。 - DTC 状态置位、清位、清除。 - NVM/Flash DID/DTC block 读写结果。 日志接口不直接依赖 UART,实际串口发送由 `Uds_LogOutput` 回调完成。 ## PC 上位机模拟测试 工程提供一个简易上位机模拟程序 `uds_host_sim`,直接向 UDS Server 输入完整诊断 PDU,并打印响应。它不包含 CAN/ISO-TP 分段,只用于验证 UDS 应用层行为。 构建: ```powershell cmake --build .tools\build ``` 运行内置测试: ```powershell .\.tools\build\uds_host_sim.exe --test ``` 交互模式: ```powershell .\.tools\build\uds_host_sim.exe ``` 输入示例: ```text UDS> 10 03 UDS> 22 F1 90 UDS> 19 02 FF UDS> 14 FF FF FF UDS> quit ``` 当前内置用例覆盖: - `0x10` 会话切换 - `0x3E` TesterPresent - `0x22` 读取 VIN - `0x2E` 写入 VIN 后再读取 - `0x19` 查询 DTC 数量和列表 - `0x14` 清除 DTC - 不支持 SID 的负响应 - `0x31` RoutineControl pending、busyRepeat、周期 `0x78`、最终正响应 ## 集成建议 - `Uds_OnRequest()` 输入必须是完整应用层诊断 PDU,不包含 CAN ID、ISO-TP PCI 或 DoIP 头。 - 多任务调用时配置 `lock` / `unlock` 回调,内部可用 FreeRTOS mutex 或 critical section。 - `service_allowed` 用于实现不同会话和安全等级下的服务矩阵。 - 安全访问 seed/key 算法只在应用回调中实现,协议栈只管理请求序列、失败次数和延时。 - 下载上传服务只管理 `0x34/0x35 -> 0x36 -> 0x37` 流程和块序号,Flash 擦写、CRC、分区权限应在回调中实现。