我具有用于从串行端口读取字节的代码,但是对于客户端设备,消息"No enough information"
显示,并且他说串行端口中有足够的信息,但是此消息被展示。
int SuccessfulRead(unsigned char * s , DWORD bytesRead){
if( bytesRead == 2 ){
//...
return 1;
}
return 0;
}
//Reading
int i=1 , breakWhile=0 ;
while(!breakWhile)
{
DWORD dwRead;
BOOL fWaitingOnRead = FALSE; //overlapped
OVERLAPPED osReader = {0};
unsigned char lpBuf[2];
osReader.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
if (osReader.hEvent == NULL){
MessageBox( NULL , L"Unable to create event" , L"Error" , MB_OK);
breakWhile=1;
}
if (!fWaitingOnRead) {
// Issue read operation.
if (!ReadFile(hPort2, lpBuf, 2, &dwRead,&osReader)) {
if (GetLastError() != ERROR_IO_PENDING){
MessageBox(NULL , L"Error in communication" , L"ERROR" , MB_OK);
break;
}
else
fWaitingOnRead = TRUE;
}
else {
// read completed immediately
int res=SuccessfulRead(lpBuf,dwRead);
if( !res){
MessageBox(NULL , L"No enough information" , L"" , MB_OK);
break;
}
}
}
#define READ_TIMEOUT 2000 // milliseconds
DWORD dwRes=0;
if (fWaitingOnRead) {
dwRes = WaitForSingleObject(osReader.hEvent,READ_TIMEOUT);
switch(dwRes)
{
// Read completed.
case WAIT_OBJECT_0:{
if (!GetOverlappedResult(hPort2, &osReader, &dwRead,FALSE))
MessageBox(NULL , L"Error in GetOverlappedResult" , L"Error" , MB_OK);
else{
// Read completed successfully.
int res=SuccessfulRead(lpBuf,dwRead);
if(!res){//less than two bytes read that is one byte readed
MessageBox(NULL , L"No enough information" , L"" , MB_OK);
breakWhile=1;//exit loop
}
//Reset flag so that another opertion can be issued.
fWaitingOnRead = FALSE;
}
break;
case WAIT_TIMEOUT:
if( i==1){//failed in first try
MessageBox(NULL , L"There is no data please try again", L"" , MB_OK);
}
breakWhile=1;//exit loop
break;
}
}
}
CloseHandle(osReader.hEvent);
i++;
}
由于ReadFile(hPort2, lpBuf, 2, &dwRead,&osReader)
,它每次必须读取2个字节,但是它第一次读取1个字节,因此它意味着串行端口中的字节数不超过1个。但是似乎code vision
读取了这些字节,为什么当程序多于2个字节时,此程序只读取1个字节?当在ReadFile()
中时,要读取的字节为2。
为什么不起作用以及如何使其起作用?
与timeout
值有关吗?
谢谢
这里:
int res=SuccessfulRead(lpBuf,dwRead);
if(!res){//less than two bytes read that is one byte readed
该注释建议您期望> =两个字节,但是SuccessfulRead()
仅在读取确切地两个字节时才返回非零:
if( bytesRead == 2 ){ // EXACTLY two bytes!!!
//...
return 1;
}
您需要:
if( bytesRead <= 2 ){ // AT LEAST two bytes
...
为了使评论正确。