libusb_submit_transfer例子
时间: 2023-09-03 12:12:21 浏览: 471
下面是一个示例,展示如何使用libusb_submit_transfer函数提交传输:
```c
#include <stdio.h>
#include <stdlib.h>
#include <libusb.h>
#define VENDOR_ID 0x0a5c
#define PRODUCT_ID 0x4503
#define ENDPOINT_IN 0x81
#define ENDPOINT_OUT 0x02
#define TRANSFER_SIZE 16
int main(void)
{
libusb_device_handle *dev_handle;
libusb_context *ctx = NULL;
int r;
// 初始化
r = libusb_init(&ctx);
if (r < 0)
{
fprintf(stderr, "libusb_init error: %d\n", r);
return EXIT_FAILURE;
}
// 打开设备
dev_handle = libusb_open_device_with_vid_pid(ctx, VENDOR_ID, PRODUCT_ID);
if (dev_handle == NULL)
{
fprintf(stderr, "libusb_open_device_with_vid_pid error\n");
libusb_exit(ctx);
return EXIT_FAILURE;
}
// 分配传输缓冲区
unsigned char *buffer = (unsigned char *)malloc(TRANSFER_SIZE);
if (buffer == NULL)
{
fprintf(stderr, "malloc error\n");
libusb_close(dev_handle);
libusb_exit(ctx);
return EXIT_FAILURE;
}
// 准备传输
libusb_transfer *transfer = libusb_alloc_transfer(0);
if (transfer == NULL)
{
fprintf(stderr, "libusb_alloc_transfer error\n");
free(buffer);
libusb_close(dev_handle);
libusb_exit(ctx);
return EXIT_FAILURE;
}
libusb_fill_bulk_transfer(transfer, dev_handle, ENDPOINT_OUT, buffer, TRANSFER_SIZE, NULL, NULL, 0);
// 提交传输
r = libusb_submit_transfer(transfer);
if (r < 0)
{
fprintf(stderr, "libusb_submit_transfer error: %d\n", r);
libusb_free_transfer(transfer);
free(buffer);
libusb_close(dev_handle);
libusb_exit(ctx);
return EXIT_FAILURE;
}
// 等待传输完成
r = libusb_handle_events(ctx);
if (r < 0)
{
fprintf(stderr, "libusb_handle_events error: %d\n", r);
libusb_cancel_transfer(transfer);
libusb_free_transfer(transfer);
free(buffer);
libusb_close(dev_handle);
libusb_exit(ctx);
return EXIT_FAILURE;
}
// 释放资源
libusb_free_transfer(transfer);
free(buffer);
libusb_close(dev_handle);
libusb_exit(ctx);
return EXIT_SUCCESS;
}
```
这个示例使用libusb_open_device_with_vid_pid函数打开一个特定的USB设备,然后使用libusb_alloc_transfer函数分配一个传输结构体。
接下来,使用libusb_fill_bulk_transfer函数填充传输结构体,指定设备句柄、端点地址、缓冲区和缓冲区大小。然后,使用libusb_submit_transfer函数提交传输。
最后,使用libusb_handle_events函数等待传输完成。如果传输失败,可以使用libusb_cancel_transfer函数取消传输。
阅读全文