串口AT与数据的混杂接收处理

linux串口AT与数据的混杂接收处理;
fdcom_rs232为串口句柄
conf.rs232.baudrate为实际使用的波特率
buf_rs232 为串口数据缓存数组
buf_rs232_len 为串口数据缓存实际长度
LOG_ERROR 为自定义错误打印宏

void recv_at_rs232(void)
{
	char buf[1024];//根据实际需要分配大小
	int len = 0;

	if (fdcom_rs232 <= 0) {
		usleep(100 * 1000);
		return;
	}
	memset(buf, 0, sizeof(buf));
	len = PortRecv(fdcom_rs232, buf, sizeof(buf_rs232), conf.rs232.baudrate);

	if (len > 0) {
		memcpy(buf_rs232 + buf_rs232_len, buf, len);
		buf_rs232_len += len;
	}




	char *head = strstr(buf_rs232, "AT");
	char *end = strstr(buf_rs232, "\r\n");
	//开始分别取出AT和数据
	while(buf_rs232_len > 4 && head != NULL && end != NULL && (int)(end - head) > 2){
		char atbuf[128] = {0};//根据实际需要分配大小
		
		//检查AT之类之前是否有数据,有数据则将该部分数据取出发送
		int hd_len = (int)(head - buf_rs232);
		if(hd_len > 0){
			//do you want
			memcpy(data.rs232.data, buf_rs232, hd_len);


			memmove(buf_rs232, buf_rs232 + hd_len, buf_rs232_len - hd_len);
			buf_rs232_len -= hd_len;
		}
		//取出AT		
		int at_len = ((int)(end - head)) + 2;
		//防呆
		if(at_len > 128){
			LOG_ERROR("collect", __FILE__, __LINE__, "not right at!");
		}
		else{
			//do you want for at
			memcpy(at_buf, buf_rs232, at_len);

			
			memmove(buf_rs232, buf_rs232 + at_len, buf_rs232_len - at_len);
			buf_rs232_len -= at_len;
		}
		//防呆,防止AT指令后有多个0D0A
		while (buf_rs232_len >2 && buf_rs232[0] == '\r' && buf_rs232[1] == '\n')
		{
			memmove(buf_rs232, buf_rs232 + 2, buf_rs232_len - 2);
			buf_rs232_len -= 2;
		}
		head = strstr(buf_rs232, "AT");
		end = strstr(buf_rs232, "\r\n"); 		
	}
	//剩余部分为数据,直接发送
	if (buf_rs232_len > 0) {
		//do you want


		memset(buf_rs232, 0, sizeof(buf_rs232));
		buf_rs232_len = 0;
	}
}
posted @ 2023-07-22 09:23  bitwoods  阅读(35)  评论(0编辑  收藏  举报