writefile
我正在尝试使用andreadfile
函数通过串行端口连接发送和接收字符串。我必须异步执行此操作,因为要读取的字节数总是不同的,并且readfile
只会挂起或阻塞,直到它获得正确的字节数。现在我正在尝试异步执行此操作,我的writefile
函数将不会发送任何数据,并且我的readfile
函数似乎被跳过了,因为下一行开始执行此操作而没有读取任何字符。不确定我的重叠结构或超时是否有问题。但我此刻被困住了。
超时
void Serial::OpenPortRead()
{
HANDLE sSerial = CreateFile(L"COM3",GENERIC_READ|GENERIC_WRITE,0,0,OPEN_EXISTING,FILE_FLAG_OVERLAPPED,0);
//Timeout Settings
COMMTIMEOUTS CommTimeouts;
GetCommTimeouts(sSerial, &CommTimeouts);
CommTimeouts.ReadIntervalTimeout = 5000;
CommTimeouts.ReadTotalTimeoutMultiplier = 2;
CommTimeouts.ReadTotalTimeoutConstant = 10;
CommTimeouts.WriteTotalTimeoutMultiplier = 50;
CommTimeouts.WriteTotalTimeoutConstant = 500;
//Port Settings
DCB dcbSerialParams = {0};
dcbSerialParams.DCBlength=sizeof(dcbSerialParams);
dcbSerialParams.BaudRate=CBR_19200;
dcbSerialParams.ByteSize=8;
dcbSerialParams.StopBits=ONESTOPBIT;
dcbSerialParams.Parity=NOPARITY;
SetCommState(sSerial,&dcbSerialParams);//Apply Settings to Handle
}
写文件功能
void Serial::WritePort(CString buffer)
{
DWORD bytes;//pointer to hold number of bytes written
USES_CONVERSION;
CW2A buf((LPCWSTR)buffer);//Convert unicode to ascii
OpenPortRead();
OVERLAPPED overlapped_structure;
memset(&overlapped_structure, 0, sizeof(overlapped_structure));
overlapped_structure.Offset = 0;
overlapped_structure.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
WriteFile(sSerial, buf,strlen(buf),&bytes,&overlapped_structure);//Send string
}
读取文件功能
int Serial::ReadPort(CString buf){
OpenPortRead();// Open Serial Communication for reading
const int buffer_size = 10;
char buffer[10];//buffer to hold recieved string
memset (buffer, 0, buffer_size * sizeof (char));
int n, num,iTemp,i=0;
OVERLAPPED overlapped_structure;
memset(&overlapped_structure, 0, sizeof(overlapped_structure));
overlapped_structure.Offset = 0;
overlapped_structure.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
DWORD bytesRead;//pointer to number bytes read
ReadFile(sSerial,&buffer,buffer_size,&bytesRead,&overlapped_structure);// begin read
//Used this function because return would be filled with extra raw data characters
buffer[n] = StringLength(buffer, &n);//find length of string returned
num = n;