#include <stdio.h>
#include <stdlib.h>
#include <libusb-1.0/libusb.h>

libusb_device **list = NULL;
libusb_device_handle *handle = NULL;
ssize_t count;

void onexit(void) {
	if (handle) {
		libusb_close(handle);
		handle = NULL;
	}
	if (list) {
		libusb_free_device_list(list, 1);
		list = NULL;
	}
	libusb_exit(NULL);
}

int main(int argc, char *argv[]) {
	int err, len = 0;
	libusb_device **list = NULL;
	struct libusb_device_descriptor dev;
	ssize_t i;
	unsigned char buffer[256];
	if (argc < 3) {
		printf("Usage: %s VENDOR_ID PRODUCT_ID\n", argv[0]);
		return -1;
	}
	if ((err = libusb_init(NULL)) != 0) {
		printf("Init error\n");
		return err;
	}
	atexit(onexit);
	if ((count = libusb_get_device_list(NULL, &list)) < 0) {
		printf("No dev list\n");
		return err;
	}
	for(i = 0; i < count; i++) {
		libusb_get_device_descriptor(list[i], &dev);
		if ((strtol(argv[1], NULL, 0) == dev.idVendor) && (strtol(argv[2], NULL, 0) == dev.idProduct)) {
			if ((err = libusb_open(list[i], &handle)) < 0) {
				printf("Dev open error\n");
				return err;
			}
			if ((err = libusb_set_configuration(handle, 1)) < 0) {
				printf("Set config error\n");
//				return err;
			}
			len = libusb_get_string_descriptor_ascii(handle, 0, buffer, 255);
			buffer[255] = '\0';
			printf("ASCII Length: %3i; Text: %s\n", len, buffer);
			len = libusb_get_descriptor(handle, LIBUSB_DT_STRING, 0, buffer, 255);
			buffer[255] = '\0';
			printf("RAW   Length: %3i; Text: %s\n", len, buffer);
			return 0;
		}
	}
	printf("Device not found\n");
	return -1;
}

