libusb介紹及簡單使用

libusb是一個開源的用C實現的,應用程序與用戶的USB設備進行通信的庫。它是可移植的,對外使用統一的API,支持Windows、macOS、Linux、Android。它是用戶模式(user-mode),應用程序與USB設備通信不需要高權限,但是在Android下好像有些接口需要root權限才能調用成功。它支持所有版本的USB協議。它的License是LGPL,源碼地址在https://github.com/libusb/libusb,最新發布版本爲1.0.23。

libusb特性:

(1).支持所有的傳輸類型(control/bulk/interrupt/isochronous)。

(2).傳輸接口包括同步和異步。

(3).線程安全。

(4).在一些平臺上支持熱插拔(Hotplug)。

libusb中的接口通常在成功時返回0,在失敗時返回負值。

libusb使用stderr記錄所有日誌(log)。默認情況下,日誌記錄設置爲NONE,將不產生任何輸出。除非在編譯源碼時禁用了日誌記錄,否則任何應用程序對libusb_set_option(ctx, LIBUSB_OPTION_LOG_LEVEL, level)的調用或在應用程序外部對環境變量LIBUSB_DEBUG的設置都可能生成日誌記錄。log消息是非結構化的,它與調用接口返回的錯誤碼沒有一一對應的關係。

在Windows上編譯步驟:在源碼的msvc目錄下有各種版本的vs工程,2013、2017等等。這裏以vs2013爲例,打開libusb_2013.sln,然後點擊”重新生成解決方案”,便會生成動態庫、靜態庫、及一些二進制文件。仿照原工程所需文件及配置,這裏在OpenCV_Test的基礎上新加一個libusb工程,編譯生成libusb靜態庫。

在Linux上編譯步驟:執行以下命令即可:

./autogen.sh
make

以下爲獲取PC機上usb設備信息的測試代碼:

#include "funset.hpp"
#include <libusb.h>

int test_libusb_get_devices_list()
{
	// reference: examples/listdevs.c
	int ret = libusb_init(nullptr);
	if (ret != 0) {
		fprintf(stderr, "fail to init: %d\n", ret);
		return -1;
	}

	libusb_device** devs = nullptr;
	ssize_t count = libusb_get_device_list(nullptr, &devs);
	if (count < 0) {
		fprintf(stderr, "fail to get device list: %d\n", count);
		libusb_exit(nullptr);
		return -1;
	}

	libusb_device* dev = nullptr;
	int i = 0;

	while ((dev = devs[i++]) != nullptr) {
		struct libusb_device_descriptor desc;
		ret = libusb_get_device_descriptor(dev, &desc);
		if (ret < 0) {
			fprintf(stderr, "fail to get device descriptor: %d\n", ret);
			return -1;
		}

		fprintf(stdout, "%04x:%04x (bus: %d, device: %d) ",
			desc.idVendor, desc.idProduct, libusb_get_bus_number(dev), libusb_get_device_address(dev));

		uint8_t path[8];
		ret = libusb_get_port_numbers(dev, path, sizeof(path));
		if (ret > 0) {
			fprintf(stdout, "path: %d", path[0]);
			for (int j = 1; j < ret; ++j)
				fprintf(stdout, ".%d", path[j]);
		}
		fprintf(stdout, "\n");
	}

	libusb_free_device_list(devs, 1);
	libusb_exit(nullptr);

	return 0;
}

Windows上執行結果如下:

Linux上執行結果如下:

GitHubhttps://github.com//fengbingchun/OpenCV_Test

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章