c语言 - 二进制包中的转义字符 (0x1b/27) 不会通过 Wi-Fi 发送,并且在传输过程中消息损坏



我正在嵌入式系统(STM32F4)上进行开发,我试图将一些数据发送到PC端的一个简单的Windows Forms客户端程序。当我使用基于字符的字符串格式时,一切都很好,但当我改用二进制包来提高性能时,我遇到了转义字符的问题。

我正在使用nanopb实现Googles协议缓冲区进行传输,我观察到在5%的包中,我在客户端程序中收到异常,告诉我我的包已损坏。

我在WireShark中进行了调试,发现在这个损坏的包中,大小比原始包的大小小2-4个字节。在进一步检查后,我发现损坏的包总是包含二进制值27,而其他包从未包含此值。我搜索了一下,发现这个值代表了一个转义字符,这可能会导致问题。

我正在使用的Wi-Fi模块的技术文档(Gainspan GSM2100)提到,命令前面有一个转义符,所以我认为我需要在包中去掉这些值。

我找不到解决问题的方法,所以如果有更有经验的人能引导我找到正确的方法来解决这个问题,我将不胜感激。

如何发送数据?您是在使用库还是在发送原始字节?根据手册,您的数据命令应该以转义序列开始,但也要指定数据长度

// Each escape sequence starts with the ASCII character 27 (0x1B),
// the equivalent to the ESC key. The contents of < > are a byte or byte stream.
// - Cid is connection id (udp, tcp, etc)
// - Data Length is 4 ASCII char represents decimal value
//   i.e. 1400 bytes would be '1' '4' '0' '0' (0x31 0x34 0x30 0x30).
// - Data size must match with specified length. 
//   Ignore all command or esc sequence in between data pay load.
<Esc>Z<Cid><Data Length xxxx 4 ascii char><data>

请注意有关数据大小的备注:"忽略数据付费加载之间的所有命令或esc序列"

例如,GSCore.cpp中的GSCore::writeData函数如下所示:

// Including a trailing 0 that snprintf insists to write
uint8_t header[8]; 
// Prepare header: <esc> Z <cid> <ascii length>
snprintf((char*)header, sizeof(header), "x1bZ%x%04d", cid, len);
// First, write the escape sequence up to the cid. After this, the
// module responds with <ESC>O or <ESC>F.
writeRaw(header, 3);
if (!readDataResponse()) {
    if (GS_LOG_ERRORS && this->error)
        this->error->println("Sending bulk data frame failed");
    return false;
}
// Then, write the rest of the escape sequence (-1 to not write the
// trailing 0)
writeRaw(header + 3, sizeof(header) - 1 - 3);+
// And write the actual data
writeRaw(buf, len);

这很可能会奏效。或者,一个肮脏的破解可能是在发送之前"转义符",即在发送之前用两个字符(0x27 0x27)替换每个0x27-但这只是一个猜测,我认为你应该查看手册。

相关内容

最新更新