您当前的位置:首页 >> 头条 >  >> 
解决USB转串口数据拆包问题的方法!防止USB转串口数据拆包的技巧
来源: 豆ok3301      时间:2023-04-04 22:42:51

解决USB转串口数据拆包的问题的方法。在读回调函数中,定义了一个缓冲区来存储读取的数据。当数据可用时,将其添加到缓冲区中,同时检查缓冲区中是否存在完整的数据帧。如果存在完整的数据帧,则将其传递给tty驱动缓冲区。在传递完整的数据帧后,将其从缓冲区中删除,以便存储下一个数据帧。该方法可以确保数据不会被拆分,并且只有完整的数据帧会被传递给tty驱动缓冲区。


【资料图】

数据被拆分成多个部分,每个部分之间有明显的时间间隔。这可能是由于传输速率过慢,导致数据被拆成多个部分,或者是由于数据帧之间没有使用正确的分隔符。

为了将完整的数据传递给tty驱动缓冲区,您可以使用以下方法:

1、在读回调函数中定义一个缓冲区,用于存储读取的数据。

2、当数据可用时,将其添加到缓冲区中,同时检查缓冲区中是否存在完整的数据帧。

3、如果缓冲区中存在完整的数据帧,则将其传递给tty驱动缓冲区,使用tty_flip_buffer_push函数。

4、在传递完整的数据帧后,将其从缓冲区中删除,以便存储下一个数据帧。

以下是一个可能的实现示例:

#define MAX_BUFFER_SIZE 1024

static char buffer[MAX_BUFFER_SIZE];

static int buffer_pos = 0;

void usb_serial_generic_read_bulk_callback(struct urb *urb)

{

// Check for errors and handle them

if (urb->status) {

return;

}

// Get the received data and its length

char *data = urb->transfer_buffer;

int len = urb->actual_length;

// Add the received data to the buffer

memcpy(buffer + buffer_pos, data, len);

buffer_pos += len;

// Check if there is a complete data frame in the buffer

int i = 0;

while (i < buffer_pos) {

// Check for a complete data frame

if (buffer[i] == "<" && buffer[i + 7] == ">") {

// Copy the data frame to a new buffer

char frame[8];

memcpy(frame, buffer + i, 8);

// Pass the data frame to tty driver buffer

tty_flip_buffer_push(tty->port);

// Remove the data frame from the buffer

memmove(buffer, buffer + i + 8, buffer_pos - i - 8);

buffer_pos -= i + 8;

i = 0;

} else {

i++;

}

}

}

在这个示例中,假设数据帧以<开头,以>结尾,长度为8个字节。每当接收到一些数据时,它将添加到buffer中。然后,它将在buffer中查找完整的数据帧。如果找到了完整的数据帧,则将其传递给tty驱动缓冲区,并将其从buffer中删除。这将保证数据不会被拆分,并且只有完整的数据帧会被传递给tty驱动缓冲区。

标签:

X 关闭

X 关闭