我从 UART 获取字符串数据并将其转换为十六进制。转换为 hex 后,我有两个唯一的分隔符“06”和“07”。我想获取这两个分隔符之间的数据。我试图根据我所说的构建下面的代码。但是在收到 6-7 个输出后,我得到了分段错误错误。
std::string sub_between(std::string start,std::string stop,std::string input)
{
auto start_index = input.find(start);
if (start_index != std::string::npos)
{
auto stop_index = input.find(stop,start_index+start.size());
if (stop_index != std::string::npos)
{
return {input.begin() + start_index+start.size(), input.begin() + stop_index};
}
}
// return empty string
return {};
}
int main(int argc, char ** argv)
{
int uart0_filestream = -1;
int uart2_filestream = -1;
unsigned char rx_buffer[1024];
memset(&rx_buffer[0], 0, 1023);
unsigned char tx_buffer[1024];
memset(&tx_buffer[0], 0, 1023);
std::stringstream ss;
if(uart0_filestream == -1)
{
uart0_filestream = open("/dev/ttyS0", O_RDWR | O_NOCTTY | O_NDELAY);
//uart0_filestream = open("/dev/ttyS0", O_NOCTTY );
if(uart0_filestream == -1)
{
std::cout << "UARTListener::Start Unable to open UART" << std::endl;
}
else
{
struct termios options;
tcgetattr(uart0_filestream, &options);
options.c_cflag = B115200 | CS8 | CLOCAL | CREAD; //<Set baud rate
options.c_iflag = IGNPAR;
options.c_oflag = 0;
options.c_lflag = 0;
//options.c_line = '\n';
//options.c_cc[VEOL] = 0;
tcflush(uart0_filestream, TCIFLUSH);
tcsetattr(uart0_filestream, TCSANOW, &options);
}
}
while(true)
{
memset(&rx_buffer[0], 0, 1024);
int rx_length = read(uart0_filestream, (void*) rx_buffer, 1023);
if(rx_length > 0)
{
rx_buffer[rx_length] = '\0';
//std::string txt = std::string((char*) rx_buffer);
for (int i = 0; i < rx_length ; i++)
{
ss << std::setfill('0') << std::setw(2)<< std::hex << (int)rx_buffer[i];
//ss << std::hex << (int)rx_buffer[i];
}
std::string startDEL = "06";
std::string stopDEL = "07";
std::string concat = std::accumulate(std::begin(ss.str()),std::end(ss.str()),std::string(""));
std::cout << "Pulled Data : " << ss.str() << std::endl;
std::cout << "String : " << sub_between(startDEL,stopDEL,concat) << std::endl;
//std::cout << txt << std::endl;
}
}
return 0;
}
- 输出 -
Pulled Data : 42
String :
Pulled Data : 426561636f6e
String :
Pulled Data : 426561636f6e283229
String :
Pulled Data : 426561636f6e28322920466f756e
String :
Pulled Data : 426561636f6e28322920466f756e645b355d
String :
Segmentation fault