我有一个设备连接到串行端口并等待使用 xmodem 协议传输文件。
我尝试使用 xmodem 格式构建消息并发送它,但是我没有得到预期的 ACK 传输。
下面是相关的代码位:
XMODEM 消息格式:
struct xmodem_packet
{
uint8_t start;
uint8_t block;
uint8_t block_neg;
uint8_t payload[128];
uint16_t crc;
};
打开和配置端口:
HANDLE portHandler = CreateFile(L"COM9", GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
DCB config = { 0 };
COMMTIMEOUTS timeout = { 0 };
// Configure
config.DCBlength = sizeof(config);
GetCommState(portHandler, &config);
config.BaudRate = CBR_115200;
config.ByteSize = 8;
config.StopBits = ONESTOPBIT;
config.Parity = NOPARITY;
SetCommState(portHandler, &config);
timeout.ReadIntervalTimeout = 50;
timeout.ReadTotalTimeoutConstant = 50;
timeout.ReadTotalTimeoutMultiplier = 50;
timeout.WriteTotalTimeoutConstant = 50;
timeout.WriteTotalTimeoutMultiplier = 10;
SetCommTimeouts(portHandler, &timeout);
为 XMODEM 传输准备模块:
DWORD toRead = 1;
DWORD wasWriten = 0;
DWORD wasRead = 0;
char responce = 0;
WriteFile(portHandler, "set load xmodem\n", 3+4+6+3, &wasWriten, NULL);
WriteFile(portHandler, "\n", 2, &wasWriten, NULL); // Doesn't work without this
构建XMODEM框架
xmodem_frame frame;
frame.start = SOH;
frame.block = 0;
frame.block_neg = 0;
memcpy(frame.payload, "test_data", 128);
swap16(crc16(frame.payload, sizeof(frame.payload)));
发送帧并寻找 ACK:
WriteFile(portHandler, &frame, sizeof(frame), &wasWriten, NULL);
ReadFile(portHandler, &responce, toRead, &wasRead, NULL);
if (responce == 6)
std::cout << "ACK was recieved";
else
std::cout << "ACK wasn't recieved";
我期待收到一个 ACK,但总是打印“ACK 未收到”。