【20230308】Serial port receiving data packetization problem handling (Linux)

1 Problem background

A packet of data may be divided into several packets due to certain transmission reasons.
Please add image description

2 solutions

2.1 By setting the minimum read characters and read timeout time

You can use the termios structure to control the input and output of the terminal device. The reading of input can be controlled by combining the values ​​of VTIME and VMIN. Additionally, the two combined can control what happens when a program attempts to read a file descriptor associated with a terminal.

  1. VMIN = 0, VTIME = 0: In this case, read调用总是立刻返回. If there are characters waiting to be processed, read will return immediately; if there are no characters waiting to be processed, the read call returns 0 and no characters are read;
  2. VMIN = 0 and VTIME > 0: In this case, 只有有字符可以处理 or 经过VTIME个十分之一秒的时间间隔, the read call returns. If no characters are read due to timeout, read returns 0, otherwise read returns the number of characters read.
  3. VMIN > 0 and VTIME = 0: In this case, read调用将一直等待,直到有MIN个字符可以读取时才返回, the return value is the number of characters read. Returns 0 when the end of file is reached.
  4. VMIN > 0 and VTIME > 0: In this case, when read is called, it waits to receive a character. After the first character and each subsequent character are received, a character interval timer is started (restarting the timer if it is already running). 当有MIN个字符可读 or 两个字符之间的时间间隔超过TIME个十分之一秒时,read调用返回. This feature can be used to distinguish whether the Escape key was pressed alone or a functional key combination started by pressing an Escape key. But be aware that high network traffic or processor load will render a timer like this useless.

By setting a non-standard mode and using VMIN and VTIME values, a program can process input on a character-by-character basis.

/* 根据通讯协议设定最小接受字符和接收字符间超时间隔 */
  termAttr.c_cc[VMIN] = 12;                            // No minimal chars
  termAttr.c_cc[VTIME] = 1;                           // Wait 0.1 s for input
  tcsetattr(fd,TCSANOW,&termAttr);   // Save settings

2 Process according to frame header and data packet length

Reference 1: https://blog.csdn.net/junlon2006/article/details/78995650

Guess you like

Origin blog.csdn.net/Creationyang/article/details/129397046