使用WinUSB读写USB设备
2021-10-15
3904
0
Windows为WinUSB设备提供了API,主要通过以下几个步骤访问设备。
通过扩展描述符中的GUID查看接口的路径
用接口的路径作为参数,调用CreateFile打开接口
使用WinUsb_Initialize得到WinUSB句柄
通过WinUsb_WritePipe和WinUsb_ReadPipe对接口进行读写操作
// ensure data size is not multiple of endpoint Max Packet size or we will send a zero length packet
UCHAR test_data_out[256-1];
UCHAR test_data_in[1024];
int main()
{
const TCHAR* path = get_first_interface_device_path(_T("{1D4B2365-4749-48EA-B38A-7C6FDDDD7E23}"));
if (path == NULL) {
printf("device not found\n");
return 0;
}
_tprintf(_T("Got device interface %s\n"), path);
HANDLE hDev = CreateFile(path,
GENERIC_WRITE | GENERIC_READ,
FILE_SHARE_WRITE | FILE_SHARE_READ,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED,
NULL);
if (INVALID_HANDLE_VALUE == hDev) {
printf("fail to open device, last error %d\n", GetLastError());
return 0;
}
WINUSB_INTERFACE_HANDLE hWinusb;
BOOL bResult = WinUsb_Initialize(hDev, &hWinusb);
if (!bResult) {
CloseHandle(hDev);
printf("Fail to invoke WinUsb_Initialize, last error %d\n", GetLastError());
return 0;
}
ULONG transferred;
for (int i = 0; i<sizeof(test_data_out); i++) {
test_data_out[i] = i;
}
bResult = WinUsb_WritePipe(hWinusb, 0x01, test_data_out, sizeof(test_data_out), &transferred, NULL);
if (!bResult) {
printf("Fail to invoke WinUsb_WritePipe, last error %d\n", GetLastError());
goto error;
}
printf("Write %d bytes data\n", transferred);
bResult = WinUsb_ReadPipe(hWinusb, 0x81, test_data_in, sizeof(test_data_in), &transferred, NULL);
if (!bResult) {
printf("Fail to invoke WinUsb_WritePipe, last error %d\n", GetLastError());
goto error;
}
printf("Read back %d bytes data\n", transferred);
error:
WinUsb_Free(hWinusb);
CloseHandle(hDev);
exit(0);
}
HID人机交互QQ群:564808376
UAC音频QQ群:218581009
UVC相机QQ群:331552032
BOT&UASP大容量存储QQ群:258159197
STC-USB单片机QQ群:315457461
USB技术交流QQ群2:580684376
USB技术交流QQ群:952873936