It seems easy to receive and parse data from the serial port. In fact, when the Protocol becomes complex, poor processing or imperfect consideration may lead to many problems.
Generally, each data packet transmitted through the serial port is not too large. Otherwise, data will be overwritten. For big data transmitted through the serial port, the processing method is to split into multiple small data packets. The possible cause is that the received data is not synchronized with the read data. The received data must be read multiple times, one part of a single data packet or the second half of a data packet and the first half of a data packet. Another possibility is that excess data is added to the data stream during transmission through Bluetooth or infrared technology. When the transmission channel becomes unreliable, some redundancy and mechanisms need to be introduced to ensure the correctness of the Upper-layer data.
The first step in data parsing is to extract a complete data packet from the byte stream. Here I just want to figure out how to capture a complete data packet and parse and record it.
For a complete data packet, a recognizable part is required. The common identification method is to determine the prefix, suffix, and data structure. Generally, prefixes are well recognized, while suffixes may be identified by combining data structures.
The following describes how to use a queue to store intermediate data:
1. If the queue is not empty;
Extract the data in the queue and combine it with the new data. The data is processed as null in the queue.
2. If the queue is empty;
Scan byte streams:
If the prefix is found, the system checks whether the data starting with the prefix is a complete data packet. If yes, the packet is processed and the end of the packet is used as the new scanning start point. If the prefix is not found, all data from the starting point of the scan is pushed to the queue.