问题
I’m working on with an embedded device that is connected to PC using rs232 (rs232 over USB).
I’m thinking about developing my own protocol:
<MAGIC><LENGTH><BINARY DATA><CRC>
but I don’t want to reinvent the wheel.
Please note that: I'm thinking about quite restricted device: 4kb of RAM, no kernel, nor standard C lib.
Can you think about a standard way to do this (maybe open source library)?
If you code your own solution do have any best practices?
- Do you use MAGIC bytes also at the end of packages?
- Maybe it is better to use time gaps instead of delimiters?
- How do you find the beginning of packages in a stream binary data?
- Maybe it is better to use text protocols?
UPDATE: Please re read the question. I shouldn't ask for library but for good practices.
回答1:
See this answer I gave to a very similar question regarding details of a simple protocol.
To respond to your specific points:
- "Magic" bytes at the end of packets don't do any harm, but they're redundant if you already know how long the packet is supposed to be, and have a CRC.
- It can be sensible to specifiy timeout times, so if there's too big a gap between bytes within one packet, then an error is flagged. Having used Modbus, I'm not convinced of the value of using time-based delimiters elsewhere.
- Do you mean, "how do you find the beginning of packets in a stream of binary data"? If so, maybe specify a minimum gap between packets, and/or require the recipient to acknolwedge after every packet.
- Makes it easier for debugging, and doesn't require any special software on the PC, but not very efficient. Of course, if usability is more important than efficiency, than a text-based system is entirely appropriate.
回答2:
For something like this by the time you get an existing solution to work on your device, it would have been easier just to reinvent the wheel.
void buffer_packet(unsigned char rx_byte)
{
static unsigned char byte_count = 0;
static unsigned char packet[8];
packet[byte_count++] = rx_byte;
if (byte_count == 8)
{
unsigned char crc = calculate_crc(packet, 8);
write_uart(0x55);
write_uart(8);
while (byte_count--)
{
write_uart(packet[7 - byte_count]);
}
write_uart(crc);
}
}
Or maybe I am underestimating your problem. If you're looking for how to generate the RS232 bits look in your microcontrollers datasheet.
回答3:
About the only thing there beyond your I/O primitives is going to be the CRC calculation. There's a nifty article, with code, here.
来源:https://stackoverflow.com/questions/815029/a-way-to-convert-byte-stream-to-packet-stream-in-c89-on-an-embedded-device