64 lines
1.3 KiB
C
64 lines
1.3 KiB
C
#include "include/cmd_parser.h"
|
|
|
|
// 定义协议中的常量
|
|
#define HEADER_BYTE1 0xEF
|
|
#define HEADER_BYTE2 0xEF
|
|
|
|
// 校验函数:简单求和校验
|
|
uint8_t calculate_checksum(const uint8_t *data, uint8_t len)
|
|
{
|
|
uint8_t checksum = 0;
|
|
for (uint8_t i = 0; i < len; ++i)
|
|
{
|
|
checksum += data[i];
|
|
}
|
|
return checksum;
|
|
}
|
|
|
|
// 串口指令解析函数
|
|
int8_t parse_serial_command(const uint8_t *buffer, uint8_t length)
|
|
{
|
|
if (length < 7)
|
|
{
|
|
// 长度不足以包含最小协议帧
|
|
return -1;
|
|
}
|
|
|
|
// 检查头部
|
|
if (buffer[0] != HEADER_BYTE1 || buffer[1] != HEADER_BYTE2)
|
|
{
|
|
// 头部不匹配
|
|
return -2;
|
|
}
|
|
|
|
// 读取长度
|
|
uint8_t len = buffer[2];
|
|
|
|
// 读取地址
|
|
uint8_t addr = buffer[3];
|
|
|
|
// 读取指令
|
|
const uint8_t cmd = buffer[4];
|
|
// 读取数据
|
|
const uint8_t *data = &buffer[5];
|
|
|
|
// 读取校验
|
|
uint8_t received_checksum = buffer[2 + len];
|
|
|
|
// 计算校验
|
|
uint8_t calculated_checksum = calculate_checksum(buffer, 2 + len);
|
|
|
|
// 校验验证
|
|
if (received_checksum != calculated_checksum)
|
|
{
|
|
// 校验失败
|
|
return -4;
|
|
}
|
|
else
|
|
{
|
|
// printf("check success!\n");
|
|
}
|
|
|
|
// 返回指令
|
|
return cmd;
|
|
} |