我有 WiiMote 连接
handle = CreateFile(didetail->DevicePath, GENERIC_READ|GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL);
if(handle != INVALID_HANDLE_VALUE) {
opened = true;
readReportEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
memset(&readOverlapped, 0, sizeof(readOverlapped));
readOverlapped.hEvent = readReportEvent;
readOverlapped.Offset = 0;
readOverlapped.OffsetHigh = 0;
writeReportEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
memset(&writeOverlapped, 0, sizeof(writeOverlapped));
writeOverlapped.hEvent = readReportEvent;
writeOverlapped.Offset = 0;
writeOverlapped.OffsetHigh = 0;
}
我有一个线程总是读取这个句柄来获取新消息:
while(opened && readThreadNextStatus){
memset (readBuff, 0, 22);
BYTE* ptrbuff = new BYTE[22];
int readfile = ReadFile(handle, readBuff, reportLength, NULL, &readOverlapped);
if(readfile == 0 && GetLastError() == ERROR_IO_PENDING){
DWORD waitError;
do
{
waitError = WaitForSingleObject(readReportEvent, timeout);
} while (waitError == WAIT_TIMEOUT && opened && readThreadNextStatus);
if(opened && readThreadNextStatus){
DWORD read = 0;
if(waitError == WAIT_OBJECT_0){
GetOverlappedResult(handle, &readOverlapped, &read, TRUE);
}
ResetEvent(readReportEvent);
memcpy(ptrbuff, readBuff, 22);
cout << "Read: ";
coutHex(ptrbuff);
}
}
}
我的写功能:
if(opened){
if(!WriteFile(handle, buff, reportLength, NULL, &writeOverlapped)){
if(GetLastError() != ERROR_IO_PENDING){
close();
}
}
WaitForSingleObject(writeReportEvent, timeout);
DWORD write = 0;
GetOverlappedResult(handle, &writeOverlapped, &write, TRUE);
ResetEvent(writeReportEvent);
}
cout << "Write: ";
coutHex(buff);
控制台输出:
Connection established
Write: 15- 0- 0- 0- 0- 0- 0- 0- 0- 0- 0- 0- 0- 0- 0- 0- 0- 0- 0- 0- 0- 0-
Read: 0- 0- 0- 0- 0- 0- 0- 0- 0- 0- 0- 0- 0- 0- 0- 0- 0- 0- 0- 0- 0- 0-
Read: 0- 0- 0- 0- 0- 0- 0- 0- 0- 0- 0- 0- 0- 0- 0- 0- 0- 0- 0- 0- 0- 0-
Write: 15- 0- 0- 0- 0- 0- 0- 0- 0- 0- 0- 0- 0- 0- 0- 0- 0- 0- 0- 0- 0- 0-
Read: 0- 0- 0- 0- 0- 0- 0- 0- 0- 0- 0- 0- 0- 0- 0- 0- 0- 0- 0- 0- 0- 0-
Write: 15- 0- 0- 0- 0- 0- 0- 0- 0- 0- 0- 0- 0- 0- 0- 0- 0- 0- 0- 0- 0- 0-
Read: 0- 0- 0- 0- 0- 0- 0- 0- 0- 0- 0- 0- 0- 0- 0- 0- 0- 0- 0- 0- 0- 0-
Read: 20- 0- 0-10- 0- 0-49-ff-ff-ff-ff-ff-ff-ff-ff-ff-ff-ff-ff-ff-ff-ff-
Write: 15- 0- 0- 0- 0- 0- 0- 0- 0- 0- 0- 0- 0- 0- 0- 0- 0- 0- 0- 0- 0- 0-
Read: 0- 0- 0- 0- 0- 0- 0- 0- 0- 0- 0- 0- 0- 0- 0- 0- 0- 0- 0- 0- 0- 0-
Write: 15- 0- 0- 0- 0- 0- 0- 0- 0- 0- 0- 0- 0- 0- 0- 0- 0- 0- 0- 0
Read: 0- 0-
0- 0-
- 0- 0- 0- 0- 0- 0- 0- 0- 0- 0- 0- 0- 0- 0- 0- 0- 0- 0- 0- 0-
coutHex 始终以十六进制格式打印接收到的数据。有时我得到正确的数据,但有时数组只加载了 00 00 00 00 00 00 00 00 00 ... 00 00
我经历过,当我进行写入时,我总是会返回一个报告,其中只包含 00,这出现在我的写入函数在控制台输出上写入之前。
我很绝望,所以我尝试了这个:
do
{
waitError = WaitForSingleObject(readReportEvent, timeout);
Sleep(500);
} while (waitError == WAIT_TIMEOUT && opened && readThreadNextStatus);
我不知道为什么,但现在它可以工作了(不好,因为它有 500 毫秒的延迟)。
你怎么看?也许 ReadFile 和 WriteFile 不能同时工作?
这是什么原因造成的?我错过了什么?