#include <stdint.h>
#include <stdbool.h>
#include <string.h>
#define SBL_DEFAULT_RETRY_COUNT 3
#define SBL_PORT_ERROR 1
#define SBL_TIMEOUT_ERROR 2
#define SBL_SUCCESS 0
#define SBL_ERROR 3
typedef struct {
// … 其他成员
ComType* m_pCom;
} SblDevice;
typedef struct {
// … 其他成员
} ComType;
// 其他相关的函数声明
uint8_t generateCheckSum(uint32_t cmd, char* data, uint32_t dataLen);
bool isInitiated(ComType* com);
void setState(uint32_t state, const char* message, …);
uint32_t readBytes(ComType* com, unsigned char* buffer, uint32_t length);
void flushBuffers(ComType* com);
uint32_t getResponseData(SblDevice* device, char* pcData, uint32_t* ui32MaxLen, uint32_t ui32MaxRetries)
{
uint32_t numBytes = 0;
uint32_t retry = 0;
unsigned char pcHdr[2];
uint32_t numPayloadBytes;
uint8_t hdrChecksum, dataChecksum;
uint32_t bytesRecv = 0;
setState(SBL_SUCCESS);
if (!isInitiated(device->m_pCom))
{
setState(SBL_PORT_ERROR, "COM port not initiated.\n");
return SBL_PORT_ERROR;
}
memset(pcHdr, 0, 2);
do
{
bytesRecv += readBytes(device->m_pCom, &pcHdr[bytesRecv], (2 - bytesRecv));
retry++;
} while ((bytesRecv < 2) && retry < ui32MaxRetries);
if (bytesRecv < 2)
{
setState(SBL_TIMEOUT_ERROR, "Timed out waiting for data header from device.\n");
return SBL_TIMEOUT_ERROR;
}
numPayloadBytes = pcHdr[0] - 2;
hdrChecksum = pcHdr[1];
if (numPayloadBytes > *ui32MaxLen)
{
setState(SBL_ERROR, "Error: Device sending more data than expected. \nMax expected was %d, sent was %d.\n", *ui32MaxLen, (numPayloadBytes + 2));
flushBuffers(device->m_pCom);
return SBL_ERROR;
}
bytesRecv = 0;
do
{
bytesRecv += readBytes(device->m_pCom, &pcData[bytesRecv], (numPayloadBytes - bytesRecv));
retry++;
} while (bytesRecv < numPayloadBytes && retry < ui32MaxRetries);
if (bytesRecv < numPayloadBytes)
{
*ui32MaxLen = bytesRecv;
setState(SBL_TIMEOUT_ERROR, "Timed out waiting for data from device.\n");
return SBL_TIMEOUT_ERROR;
}
dataChecksum = generateCheckSum(0, pcData, numPayloadBytes);
if (dataChecksum != hdrChecksum)
{
setState(SBL_ERROR, "Checksum verification error. Expected 0x%02X, got 0x%02X.\n", hdrChecksum, dataChecksum);
return SBL_ERROR;
}
*ui32MaxLen = bytesRecv;
return SBL_SUCCESS;
}
代码功能解释
包含头文件和宏定义: 包含了必要的头文件和定义了一些宏,这些宏用于表示不同的错误代码。
结构体定义: 定义了两个结构体SblDevice和ComType来模拟您的原始代码中的类。
辅助函数声明: 定义了一些辅助函数的声明,它们将被用于这段代码。
函数定义:
参数修改: 将 uint32_t &ui32MaxLen 更改为 uint32_t* ui32MaxLen 来适应C语言的语法。
初始化变量: 初始化了一些必要的局部变量用于之后的逻辑。
COM端口检查: 检查COM端口是否已初始化,如果没有,它将返回一个错误。
数据头接收: 在一个do-while循环中,它尝试读取2字节的数据头,包含负载长度和校验和。
负载长度和校验和检查: 检查接收到的负载长度和校验和是否合法。
负载数据接收: 在一个新的do-while循环中,它尝试读取负载数据。
校验和验证: 验证接收到的数据的校验和是否与数据头中的校验和匹配。
返回: 最后,如果一切顺利,它将更新ui32MaxLen的值并返回SBL_SUCCESS。
注意:我假设了一些函数的存在和它们的参数,你需要根据实际情况调整它们。同时,您需要将C++类中的函数和成员变量转换为C语言的函数和结构体成员变量。