int test_device(uint16_t vid, uint16_t pid) { libusb_device_handle *handle; libusb_device *dev; struct libusb_config_descriptor *conf_desc; const struct libusb_endpoint_descriptor *endpoint; int i, j, k, r; int iface, nb_ifaces; #ifdef OS_LINUX // Attaching/detaching the kernel driver is only relevant for Linux int iface_detached = -1; #endif bool test_scsi = false; struct libusb_device_descriptor dev_desc; char string[128]; uint8_t string_index[3]; // indexes of the string descriptors uint8_t endpoint_in = 0, endpoint_out = 0; // default IN and OUT endpoints printf("Opening device...\n"); handle = libusb_open_device_with_vid_pid(NULL, vid, pid); if (handle == NULL) { perr(" Failed.\n"); return -1; } dev = libusb_get_device(handle); printf("\nReading device descriptor:\n"); CALL_CHECK(libusb_get_device_descriptor(dev, &dev_desc)); printf(" length: %d\n", dev_desc.bLength); printf(" device class: %d\n", dev_desc.bDeviceClass); printf(" S/N: %d\n", dev_desc.iSerialNumber); printf(" VID:PID: %04X:%04X\n", dev_desc.idVendor, dev_desc.idProduct); printf(" bcdDevice: %04X\n", dev_desc.bcdDevice); printf(" iMan:iProd:iSer: %d:%d:%d\n", dev_desc.iManufacturer, dev_desc.iProduct, dev_desc.iSerialNumber); printf(" nb confs: %d\n", dev_desc.bNumConfigurations); // Copy the string descriptors for easier parsing string_index[0] = dev_desc.iManufacturer; string_index[1] = dev_desc.iProduct; string_index[2] = dev_desc.iSerialNumber; printf("\nReading configuration descriptors:\n"); CALL_CHECK(libusb_get_config_descriptor(dev, 0, &conf_desc)); nb_ifaces = conf_desc->bNumInterfaces; printf(" nb interfaces: %d\n", nb_ifaces); for (i=0; i<conf_desc->bNumInterfaces; i++) { for (j=0; j<conf_desc->usb_interface[i].num_altsetting; j++) { printf("interface[%d].altsetting[%d]: num endpoints = %d\n", i, j, conf_desc->usb_interface[i].altsetting[j].bNumEndpoints); printf(" Class.SubClass.Protocol: %02X.%02X.%02X\n", conf_desc->usb_interface[i].altsetting[j].bInterfaceClass, conf_desc->usb_interface[i].altsetting[j].bInterfaceSubClass, conf_desc->usb_interface[i].altsetting[j].bInterfaceProtocol); if ( (conf_desc->usb_interface[i].altsetting[j].bInterfaceClass == LIBUSB_CLASS_MASS_STORAGE) && ( (conf_desc->usb_interface[i].altsetting[j].bInterfaceSubClass == 0x01) || (conf_desc->usb_interface[i].altsetting[j].bInterfaceSubClass == 0x06) ) && (conf_desc->usb_interface[i].altsetting[j].bInterfaceProtocol == 0x50) ) { // Mass storage devices that can use basic SCSI commands test_scsi = true; } for (k=0; k<conf_desc->usb_interface[i].altsetting[j].bNumEndpoints; k++) { endpoint = &conf_desc->usb_interface[i].altsetting[j].endpoint[k]; printf(" endpoint[%d].address: %02X\n", k, endpoint->bEndpointAddress); // Use the last IN/OUT endpoints found as default for testing if (endpoint->bEndpointAddress & LIBUSB_ENDPOINT_IN) { endpoint_in = endpoint->bEndpointAddress; } else { endpoint_out = endpoint->bEndpointAddress; } printf(" max packet size: %04X\n", endpoint->wMaxPacketSize); printf(" polling interval: %02X\n", endpoint->bInterval); } } } libusb_free_config_descriptor(conf_desc); for (iface = 0; iface < nb_ifaces; iface++) { printf("\nClaiming interface %d...\n", iface); r = libusb_claim_interface(handle, iface); #ifdef OS_LINUX if ((r != LIBUSB_SUCCESS) && (iface == 0)) { // Maybe we need to detach the driver perr(" Failed. Trying to detach driver...\n"); libusb_detach_kernel_driver(handle, iface); iface_detached = iface; printf(" Claiming interface again...\n"); r = libusb_claim_interface(handle, iface); } #endif if (r != LIBUSB_SUCCESS) { perr(" Failed.\n"); } } printf("\nReading string descriptors:\n"); for (i=0; i<3; i++) { if (string_index[i] == 0) { continue; } if (libusb_get_string_descriptor_ascii(handle, string_index[i], string, 128) >= 0) { printf(" String (0x%02X): \"%s\"\n", string_index[i], string); } } switch(test_mode) { case USE_XBOX: CALL_CHECK(display_xbox_status(handle)); CALL_CHECK(set_xbox_actuators(handle, 128, 222)); msleep(2000); CALL_CHECK(set_xbox_actuators(handle, 0, 0)); break; case USE_HID: test_hid(handle, endpoint_in); break; default: break; } if (test_scsi) { CALL_CHECK(test_mass_storage(handle, endpoint_in, endpoint_out)); } printf("\n"); for (iface = 0; iface<nb_ifaces; iface++) { printf("Releasing interface %d...\n", iface); libusb_release_interface(handle, iface); } #ifdef OS_LINUX if (iface_detached >= 0) { printf("Re-attaching kernel driver...\n"); libusb_attach_kernel_driver(handle, iface_detached); } #endif printf("Closing device...\n"); libusb_close(handle); return 0; }
/* Configure CH341A, find the device and set the default interface. */ int32_t ch341Configure(uint16_t vid, uint16_t pid) { struct libusb_device *dev; int32_t ret; struct sigaction sa; uint8_t desc[0x12]; if (devHandle != NULL) { fprintf(stderr, "Call ch341Release before re-configure\n"); return -1; } ret = libusb_init(NULL); if(ret < 0) { fprintf(stderr, "Couldn't initialise libusb\n"); return -1; } libusb_set_option(NULL, LIBUSB_OPTION_LOG_LEVEL, LIBUSB_LOG_LEVEL_INFO); if(!(devHandle = libusb_open_device_with_vid_pid(NULL, vid, pid))) { fprintf(stderr, "Couldn't open device [%04x:%04x].\n", vid, pid); return -1; } if(!(dev = libusb_get_device(devHandle))) { fprintf(stderr, "Couldn't get bus number and address.\n"); goto close_handle; } if(libusb_kernel_driver_active(devHandle, 0)) { ret = libusb_detach_kernel_driver(devHandle, 0); if(ret) { fprintf(stderr, "Failed to detach kernel driver: '%s'\n", strerror(-ret)); goto close_handle; } } ret = libusb_claim_interface(devHandle, 0); if(ret) { fprintf(stderr, "Failed to claim interface 0: '%s'\n", strerror(-ret)); goto close_handle; } ret = libusb_get_descriptor(devHandle, LIBUSB_DT_DEVICE, 0x00, desc, 0x12); if(ret < 0) { fprintf(stderr, "Failed to get device descriptor: '%s'\n", strerror(-ret)); goto release_interface; } printf("Device reported its revision [%d.%02d]\n", desc[12], desc[13]); sa.sa_handler = &sig_int; sa.sa_flags = SA_RESTART; sigfillset(&sa.sa_mask); if (sigaction(SIGINT, &sa, &saold) == -1) { perror("Error: cannot handle SIGINT"); // Should not happen } return 0; release_interface: libusb_release_interface(devHandle, 0); close_handle: libusb_close(devHandle); devHandle = NULL; return -1; }
int cyusb_get_devaddr(cyusb_handle *h) { cyusb_device *tdev = libusb_get_device(h); return libusb_get_device_address( tdev ); }
static int test_device(uint16_t vid, uint16_t pid) { libusb_device_handle *handle; libusb_device *dev; uint8_t bus, port_path[8]; struct libusb_config_descriptor *conf_desc; const struct libusb_endpoint_descriptor *endpoint; int i, j, k, r; int iface, nb_ifaces, first_iface = -1; // For attaching/detaching the kernel driver, if needed int iface_detached = -1; struct libusb_device_descriptor dev_desc; const char* speed_name[5] = { "Unknown", "1.5 Mbit/s (USB LowSpeed)", "12 Mbit/s (USB FullSpeed)", "480 Mbit/s (USB HighSpeed)", "5000 Mbit/s (USB SuperSpeed)"}; char string[128]; uint8_t string_index[3]; // indexes of the string descriptors uint8_t endpoint_in = 0, endpoint_out = 0; // default IN and OUT endpoints printf("Opening device %04X:%04X...\n", vid, pid); handle = libusb_open_device_with_vid_pid(NULL, vid, pid); if (handle == NULL) { perr(" Failed.\n"); return -1; } dev = libusb_get_device(handle); bus = libusb_get_bus_number(dev); if (extra_info) { r = libusb_get_port_path(NULL, dev, port_path, sizeof(port_path)); if (r > 0) { printf("\nDevice properties:\n"); printf(" bus number: %d\n", bus); printf(" port path: %d", port_path[0]); for (i=1; i<r; i++) { printf("->%d", port_path[i]); } printf(" (from root hub)\n"); } r = libusb_get_device_speed(dev); if ((r<0) || (r>4)) r=0; printf(" speed: %s\n", speed_name[r]); } printf("\nReading device descriptor:\n"); CALL_CHECK(libusb_get_device_descriptor(dev, &dev_desc)); printf(" length: %d\n", dev_desc.bLength); printf(" device class: %d\n", dev_desc.bDeviceClass); printf(" S/N: %d\n", dev_desc.iSerialNumber); printf(" VID:PID: %04X:%04X\n", dev_desc.idVendor, dev_desc.idProduct); printf(" bcdDevice: %04X\n", dev_desc.bcdDevice); printf(" iMan:iProd:iSer: %d:%d:%d\n", dev_desc.iManufacturer, dev_desc.iProduct, dev_desc.iSerialNumber); printf(" nb confs: %d\n", dev_desc.bNumConfigurations); // Copy the string descriptors for easier parsing string_index[0] = dev_desc.iManufacturer; string_index[1] = dev_desc.iProduct; string_index[2] = dev_desc.iSerialNumber; printf("\nReading configuration descriptors:\n"); CALL_CHECK(libusb_get_config_descriptor(dev, 0, &conf_desc)); nb_ifaces = conf_desc->bNumInterfaces; printf(" nb interfaces: %d\n", nb_ifaces); if (nb_ifaces > 0) first_iface = conf_desc->usb_interface[0].altsetting[0].bInterfaceNumber; for (i=0; i<nb_ifaces; i++) { printf(" interface[%d]: id = %d\n", i, conf_desc->usb_interface[i].altsetting[0].bInterfaceNumber); for (j=0; j<conf_desc->usb_interface[i].num_altsetting; j++) { printf("interface[%d].altsetting[%d]: num endpoints = %d\n", i, j, conf_desc->usb_interface[i].altsetting[j].bNumEndpoints); printf(" Class.SubClass.Protocol: %02X.%02X.%02X\n", conf_desc->usb_interface[i].altsetting[j].bInterfaceClass, conf_desc->usb_interface[i].altsetting[j].bInterfaceSubClass, conf_desc->usb_interface[i].altsetting[j].bInterfaceProtocol); if ( (conf_desc->usb_interface[i].altsetting[j].bInterfaceClass == LIBUSB_CLASS_MASS_STORAGE) && ( (conf_desc->usb_interface[i].altsetting[j].bInterfaceSubClass == 0x01) || (conf_desc->usb_interface[i].altsetting[j].bInterfaceSubClass == 0x06) ) && (conf_desc->usb_interface[i].altsetting[j].bInterfaceProtocol == 0x50) ) { // Mass storage devices that can use basic SCSI commands test_mode = USE_SCSI; } for (k=0; k<conf_desc->usb_interface[i].altsetting[j].bNumEndpoints; k++) { endpoint = &conf_desc->usb_interface[i].altsetting[j].endpoint[k]; printf(" endpoint[%d].address: %02X\n", k, endpoint->bEndpointAddress); // Use the first interrupt or bulk IN/OUT endpoints as default for testing if ((endpoint->bmAttributes & LIBUSB_TRANSFER_TYPE_MASK) & (LIBUSB_TRANSFER_TYPE_BULK | LIBUSB_TRANSFER_TYPE_INTERRUPT)) { if (endpoint->bEndpointAddress & LIBUSB_ENDPOINT_IN) { if (!endpoint_in) endpoint_in = endpoint->bEndpointAddress; } else { if (!endpoint_out) endpoint_out = endpoint->bEndpointAddress; } } printf(" max packet size: %04X\n", endpoint->wMaxPacketSize); printf(" polling interval: %02X\n", endpoint->bInterval); } } } libusb_free_config_descriptor(conf_desc); for (iface = 0; iface < nb_ifaces; iface++) { printf("\nClaiming interface %d...\n", iface); r = libusb_claim_interface(handle, iface); if ((r != LIBUSB_SUCCESS) && libusb_has_capability(LIBUSB_CAP_SUPPORTS_DETACH_KERNEL_DRIVER) && (libusb_kernel_driver_active(handle, iface) > 0)) { // Try to detach the kernel driver perr(" A kernel driver is active, trying to detach it...\n"); r = libusb_detach_kernel_driver(handle, iface); if (r == LIBUSB_SUCCESS) { iface_detached = iface; printf(" Claiming interface again...\n"); r = libusb_claim_interface(handle, iface); } } if (r != LIBUSB_SUCCESS) { perr(" Failed.\n"); } } printf("\nReading string descriptors:\n"); for (i=0; i<3; i++) { if (string_index[i] == 0) { continue; } if (libusb_get_string_descriptor_ascii(handle, string_index[i], (unsigned char*)string, 128) >= 0) { printf(" String (0x%02X): \"%s\"\n", string_index[i], string); } } // Read the OS String Descriptor if (libusb_get_string_descriptor_ascii(handle, 0xEE, (unsigned char*)string, 128) >= 0) { printf(" String (0x%02X): \"%s\"\n", 0xEE, string); // If this is a Microsoft OS String Descriptor, // attempt to read the WinUSB extended Feature Descriptors if (strncmp(string, "MSFT100", 7) == 0) read_ms_winsub_feature_descriptors(handle, string[7], first_iface); } switch(test_mode) { case USE_PS3: CALL_CHECK(display_ps3_status(handle)); break; case USE_XBOX: CALL_CHECK(display_xbox_status(handle)); CALL_CHECK(set_xbox_actuators(handle, 128, 222)); msleep(2000); CALL_CHECK(set_xbox_actuators(handle, 0, 0)); break; case USE_HID: test_hid(handle, endpoint_in); break; case USE_SCSI: CALL_CHECK(test_mass_storage(handle, endpoint_in, endpoint_out)); case USE_GENERIC: break; } printf("\n"); for (iface = 0; iface<nb_ifaces; iface++) { printf("Releasing interface %d...\n", iface); libusb_release_interface(handle, iface); } if (iface_detached >= 0) { printf("Re-attaching kernel driver...\n"); libusb_attach_kernel_driver(handle, iface_detached); } printf("Closing device...\n"); libusb_close(handle); return 0; }
// Automatically uses the correct endpoint and transfer method (bulk or interrupt) static unsigned long LJUSB_SetupTransfer(HANDLE hDevice, BYTE *pBuff, unsigned long count, unsigned int timeout, enum LJUSB_TRANSFER_OPERATION operation) { libusb_device *dev = NULL; struct libusb_device_descriptor desc; bool isBulk = true; unsigned char endpoint = 0; int r = 0; #if LJ_DEBUG fprintf(stderr, "Calling LJUSB_SetupTransfer with count = %lu and operation = %d.\n", count, operation); #endif if (LJUSB_isNullHandle(hDevice)) { #if LJ_DEBUG fprintf(stderr, "LJUSB_SetupTransfer: returning 0. hDevice is NULL.\n"); #endif return 0; } //First determine the device from handle. dev = libusb_get_device(hDevice); r = libusb_get_device_descriptor(dev, &desc); if (r < 0) { LJUSB_libusbError(r); return 0; } switch (desc.idProduct) { /* These devices use bulk transfers */ case UE9_PRODUCT_ID: isBulk = true; switch (operation) { case LJUSB_WRITE: endpoint = UE9_PIPE_EP1_OUT; break; case LJUSB_READ: endpoint = UE9_PIPE_EP1_IN; break; case LJUSB_STREAM: endpoint = UE9_PIPE_EP2_IN; break; default: errno = EINVAL; return 0; } break; case U3_PRODUCT_ID: isBulk = true; switch (operation) { case LJUSB_WRITE: endpoint = U3_PIPE_EP1_OUT; break; case LJUSB_READ: endpoint = U3_PIPE_EP2_IN; break; case LJUSB_STREAM: endpoint = U3_PIPE_EP3_IN; break; default: errno = EINVAL; return 0; } break; case U6_PRODUCT_ID: isBulk = true; switch (operation) { case LJUSB_WRITE: endpoint = U6_PIPE_EP1_OUT; break; case LJUSB_READ: endpoint = U6_PIPE_EP2_IN; break; case LJUSB_STREAM: endpoint = U6_PIPE_EP3_IN; break; default: errno = EINVAL; return 0; } break; case BRIDGE_PRODUCT_ID: isBulk = true; switch (operation) { case LJUSB_WRITE: endpoint = BRIDGE_PIPE_EP1_OUT; break; case LJUSB_READ: endpoint = BRIDGE_PIPE_EP2_IN; break; case LJUSB_STREAM: endpoint = BRIDGE_PIPE_EP3_IN; break; default: errno = EINVAL; return 0; } break; case T7_PRODUCT_ID: isBulk = true; switch (operation) { case LJUSB_WRITE: endpoint = T7_PIPE_EP1_OUT; break; case LJUSB_READ: endpoint = T7_PIPE_EP2_IN; break; case LJUSB_STREAM: endpoint = T7_PIPE_EP3_IN; break; default: errno = EINVAL; return 0; } break; case DIGIT_PRODUCT_ID: isBulk = true; switch (operation) { case LJUSB_WRITE: endpoint = DIGIT_PIPE_EP1_OUT; break; case LJUSB_READ: endpoint = DIGIT_PIPE_EP2_IN; break; case LJUSB_STREAM: default: //No streaming interface errno = EINVAL; return 0; } break; /* These devices use interrupt transfers */ case U12_PRODUCT_ID: isBulk = false; switch (operation) { case LJUSB_READ: endpoint = U12_PIPE_EP1_IN; break; case LJUSB_WRITE: endpoint = U12_PIPE_EP2_OUT; break; case LJUSB_STREAM: endpoint = U12_PIPE_EP0; break; default: errno = EINVAL; return 0; } break; default: // Error, not a labjack device errno = EINVAL; return 0; } return LJUSB_DoTransfer(hDevice, endpoint, pBuff, count, timeout, isBulk); }
int usb_get_interface_endpoints(libusb_device_handle *device_handle, int interface_number, uint8_t *endpoint_in, uint8_t *endpoint_out) { int rc; libusb_device *device = libusb_get_device(device_handle); uint8_t bus_number = libusb_get_bus_number(device); uint8_t device_address = libusb_get_device_address(device); int i; struct libusb_config_descriptor *config_descriptor; const struct libusb_interface_descriptor *interface_descriptor; int k; const struct libusb_endpoint_descriptor *endpoint_descriptor; rc = libusb_get_config_descriptor(device, 0, &config_descriptor); if (rc < 0) { log_error("Could not get config descriptor for USB device (bus: %u, device: %u): %s (%d)", bus_number, device_address, usb_get_error_name(rc), rc); return -1; } if (config_descriptor->bNumInterfaces == 0) { log_error("Config descriptor for USB device (bus: %u, device: %u) contains no interfaces", bus_number, device_address); return -1; } for (i = 0; i < config_descriptor->bNumInterfaces; ++i) { if (config_descriptor->interface[i].num_altsetting < 1) { log_debug("Interface at index %d of USB device (bus: %u, device: %u) has no alt setting, ignoring it", i, bus_number, device_address); continue; } interface_descriptor = &config_descriptor->interface[i].altsetting[0]; if (interface_descriptor->bInterfaceNumber != interface_number) { continue; } if (interface_descriptor->bNumEndpoints != 2) { log_debug("Interface %d of USB device (bus: %u, device: %u) has %d endpoints, expecting 2, ignoring it", interface_descriptor->bInterfaceNumber, bus_number, device_address, interface_descriptor->bNumEndpoints); continue; } for (k = 0; k < interface_descriptor->bNumEndpoints; ++k) { endpoint_descriptor = &interface_descriptor->endpoint[k]; if (endpoint_descriptor->bEndpointAddress & LIBUSB_ENDPOINT_IN) { *endpoint_in = endpoint_descriptor->bEndpointAddress; } else { *endpoint_out = endpoint_descriptor->bEndpointAddress; } } libusb_free_config_descriptor(config_descriptor); return 0; } libusb_free_config_descriptor(config_descriptor); return -1; }
static GSList *hw_scan(GSList *options) { struct drv_context *drvc; struct dev_context *devc; struct sr_dev_inst *sdi; struct sr_usb_dev_inst *usb; struct sr_config *src; struct sr_probe *probe; libusb_device *dev; GSList *usb_devices, *devices, *l; int i; const char *conn; (void)options; drvc = di->priv; /* USB scan is always authoritative. */ clear_instances(); conn = NULL; for (l = options; l; l = l->next) { src = l->data; switch (src->key) { case SR_CONF_CONN: conn = src->value; break; } } if (!conn) conn = OSCI_VIDPID; devices = NULL; if ((usb_devices = sr_usb_find(drvc->sr_ctx->libusb_ctx, conn))) { for (l = usb_devices; l; l = l->next) { usb = l->data; if (!(sdi = sr_dev_inst_new(0, SR_ST_INACTIVE, OSCI_VENDOR, OSCI_MODEL, OSCI_VERSION))) return NULL; sdi->driver = di; for (i = 0; probe_names[i]; i++) { if (!(probe = sr_probe_new(i, SR_PROBE_ANALOG, TRUE, probe_names[i]))) return NULL; sdi->probes = g_slist_append(sdi->probes, probe); } if (!(devc = g_try_malloc0(sizeof(struct dev_context)))) return NULL; sdi->priv = devc; devc->usb = usb; if (strcmp(conn, OSCI_VIDPID)) { if (sr_usb_open(drvc->sr_ctx->libusb_ctx, usb) != SR_OK) break; dev = libusb_get_device(usb->devhdl); if (ezusb_upload_firmware(dev, 0, OSCI_FIRMWARE) == SR_OK) /* Remember when the firmware on this device was updated */ devc->fw_updated = g_get_monotonic_time(); else sr_err("Firmware upload failed for device " "at bus %d address %d.", usb->bus, usb->address); } drvc->instances = g_slist_append(drvc->instances, sdi); devices = g_slist_append(devices, sdi); } g_slist_free(usb_devices); } else g_slist_free_full(usb_devices, g_free); return devices; }
//-- private morpheus commands --- static bool morpheus_open_usb_device( MorpheusUSBContext *morpheus_context) { bool bSuccess = true; if (libusb_init(&morpheus_context->usb_context) == LIBUSB_SUCCESS) { libusb_set_debug(morpheus_context->usb_context, 3); } else { SERVER_LOG_ERROR("morpeus_open_usb_device") << "libusb context initialization failed!"; bSuccess = false; } if (bSuccess) { morpheus_context->usb_device_handle = libusb_open_device_with_vid_pid( morpheus_context->usb_context, MORPHEUS_VENDOR_ID, MORPHEUS_PRODUCT_ID); if (morpheus_context->usb_device_handle == nullptr) { SERVER_LOG_ERROR("morpeus_open_usb_device") << "Morpheus USB device not found!"; bSuccess = false; } } if (bSuccess) { libusb_device *device = libusb_get_device(morpheus_context->usb_device_handle); int result = libusb_get_config_descriptor_by_value( device, MORPHEUS_CONFIGURATION_PSVR, &morpheus_context->usb_device_descriptor); if (result != LIBUSB_SUCCESS) { SERVER_LOG_ERROR("morpeus_open_usb_device") << "Failed to retrieve Morpheus usb config descriptor"; bSuccess = false; } } for (int interface_index = 0; bSuccess && interface_index < morpheus_context->usb_device_descriptor->bNumInterfaces; interface_index++) { int mask = 1 << interface_index; if (MORPHEUS_USB_INTERFACES_MASK_TO_CLAIM & mask) { int result = 0; #ifndef _WIN32 result = libusb_kernel_driver_active(morpheus_context->usb_device_handle, interface_index); if (result < 0) { SERVER_LOG_ERROR("morpeus_open_usb_device") << "USB Interface #"<< interface_index <<" driver status failed"; bSuccess = false; } if (bSuccess && result == 1) { SERVER_LOG_ERROR("morpeus_open_usb_device") << "Detach kernel driver on interface #" << interface_index; result = libusb_detach_kernel_driver(morpheus_context->usb_device_handle, interface_index); if (result != LIBUSB_SUCCESS) { SERVER_LOG_ERROR("morpeus_open_usb_device") << "Interface #" << interface_index << " detach failed"; bSuccess = false; } } #endif //_WIN32 result = libusb_claim_interface(morpheus_context->usb_device_handle, interface_index); if (result == LIBUSB_SUCCESS) { morpheus_context->usb_claimed_interface_mask |= mask; } else { SERVER_LOG_ERROR("morpeus_open_usb_device") << "Interface #" << interface_index << " claim failed"; bSuccess = false; } } } if (!bSuccess) { morpheus_close_usb_device(morpheus_context); } return bSuccess; }
RESPONSECODE IFDHCreateChannel ( DWORD Lun, DWORD Channel ) { //RESPONSECODE IO_Create_Channel ( DWORD Channel ) { //DWORD Lun = 0; /* Lun - Logical Unit Number, use this for multiple card slots or multiple readers. 0xXXXXYYYY - XXXX multiple readers, YYYY multiple slots. The resource manager will set these automatically. By default the resource manager loads a new instance of the driver so if your reader does not have more than one smartcard slot then ignore the Lun in all the functions. Future versions of PC/SC might support loading multiple readers through one instance of the driver in which XXXX would be important to implement if you want this. */ /* Channel - Channel ID. This is denoted by the following: 0x000001 - /dev/pcsc/1 0x000002 - /dev/pcsc/2 0x000003 - /dev/pcsc/3 USB readers may choose to ignore this parameter and query the bus for the particular reader. */ /* This function is required to open a communications channel to the port listed by Channel. For example, the first serial reader on COM1 would link to /dev/pcsc/1 which would be a sym link to /dev/ttyS0 on some machines This is used to help with intermachine independance. Once the channel is opened the reader must be in a state in which it is possible to query IFDHICCPresence() for card status. returns: IFD_SUCCESS IFD_COMMUNICATION_ERROR */ syslog(LOG_INFO, "This is the Myson driver"); srand(time(0)); int readerNum = (Lun & 0xFFFF0000) >> 16; libusb_context *context; if(libusb_init(&context) != 0) //unable to initialize libusb { syslog(LOG_INFO, "Unable to initialize libusb"); return IFD_COMMUNICATION_ERROR; } rd[readerNum].context = context; rd[readerNum].handle = libusb_open_device_with_vid_pid(context, 0x04cf, 0x9920); syslog(LOG_INFO, "Success"); if(rd[readerNum].handle == NULL) { syslog(LOG_INFO, "Did you connect the Myson?"); return IFD_COMMUNICATION_ERROR; } libusb_device* dev = libusb_get_device(rd[readerNum].handle); //avoid conflict with an existing mass storage driver //this function, although it is in the documentation, is absent from libusb.h... //libusb_set_auto_detach_kernel_driver(rd[readerNum].handle,1); //we will claim the interface if(libusb_kernel_driver_active(rd[readerNum].handle,0) == 1) //then we free it { if(libusb_detach_kernel_driver(rd[readerNum].handle,0) != 0) //error when freeing? { syslog(LOG_INFO, "Unable to detach interface from kernel driver"); libusb_close(rd[readerNum].handle); libusb_exit(context); return IFD_COMMUNICATION_ERROR; } } if(libusb_claim_interface(rd[readerNum].handle, 0) != 0) { syslog(LOG_INFO, "Unable to claim interface"); libusb_close(rd[readerNum].handle); libusb_exit(context); return IFD_COMMUNICATION_ERROR; } syslog(LOG_INFO, "Myson successfully initialized"); int maxsize = libusb_get_max_packet_size(dev, IN_ENDPOINT); printf("Max IN packet size: %d\n", maxsize); maxsize = libusb_get_max_packet_size(dev, OUT_ENDPOINT); printf("Max OUT packet size: %d\n", maxsize); return IFD_SUCCESS; }
/* Initialize the audio path */ int mxuvc_audio_init(const char *backend, const char *options) { RECORD("\"%s\", \"%s\"", backend, options); struct libusb_device *dev = NULL; int ret=0, i, config; uint16_t vendor_id=0xdead, product_id=0xbeef; char *str=NULL, *opt, *value; int audio_sampling_rate; TRACE("Initializing the audio\n"); /* Check that the correct video backend was requested*/ if(strncmp(backend, "libusb-uac", 10)) { ERROR(-1, "The audio backend requested (%s) does not match " "the implemented one (libusb-uac)", backend); } /* Set init parameters to their default values */ packets_per_transfer = PACKETS_PER_TRANSFER_DEFAULT; num_transfers = NUM_TRANSFERS_DEFAULT; audio_duration_ms = AUDIO_DURATION_MS_DEFAULT; audio_sampling_rate = AUDIO_SAMPLING_RATE_DEFAULT; /* Copy the options string to a new buffer since next_opt() needs * non const strings and options could be a const string */ if(options != NULL) { str = (char*)malloc(strlen(options)+1); strncpy(str, options, strlen(options)); *(str + strlen(options)) = '\0'; } /* Get backend option from the option string */ ret = next_opt(str, &opt, &value); while(ret == 0) { if(strncmp(opt, "vid", 3) == 0) { vendor_id = (uint16_t) strtoul(value, NULL, 16); } else if(strncmp(opt, "pid", 3) == 0) { product_id = (uint16_t) strtoul(value, NULL, 16); } else if(strncmp(opt, "packets_per_transfer", 19) == 0) { packets_per_transfer = (unsigned int) strtoul(value, NULL, 10); } else if(strncmp(opt, "num_transfers", 12) == 0) { num_transfers = (unsigned int) strtoul(value, NULL, 10); } else if(strncmp(opt, "audio_duration_ms", 17) == 0) { audio_duration_ms = (unsigned int) strtoul(value, NULL, 10); } else if (strncmp (opt, "audio_sampling_rate", 19) == 0) { audio_sampling_rate = (unsigned int) strtoul (value, NULL, 10); } else { WARNING("Unrecognized option: '%s'", opt); } ret = next_opt(NULL, &opt, &value); } /* Display the values we are going to use */ TRACE("Using vid = 0x%x\n", vendor_id); TRACE("Using pid = 0x%x\n", product_id); TRACE("Using packets_per_transfer = %i\n", packets_per_transfer); TRACE("Using num_transfers = %i\n", num_transfers); TRACE("Using audio_duration_ms = %i\n", audio_duration_ms); TRACE("Using audio_sampling_rate = %i\n", audio_sampling_rate); /* Free the memory allocated to parse 'options' */ if(str) free(str); /* Initialize the backend */ aud_started = 0; audio_disconnected = 0; ret = init_libusb(&audio_ctx); if(ret < 0) return -1; audio_hdl = libusb_open_device_with_vid_pid(audio_ctx, vendor_id, product_id); CHECK_ERROR(audio_hdl == NULL, -1, "Could not open USB device " "%x:%x", vendor_id, product_id); dev = libusb_get_device(audio_hdl); if(dev == NULL) { printf("Unexpected error: libusb_get_device returned a NULL " "pointer."); mxuvc_audio_deinit(); return -1; } /* Get active USB configuration */ libusb_get_configuration(audio_hdl, &config); /* Parse USB decriptors from active USB configuration * to get all the UVC/UAC info needed */ ret = aparse_usb_config(dev, config); if(ret < 0){ mxuvc_audio_deinit(); return -1; } /* Initialize audio */ /* Claim audio control interface */ /* Check if a kernel driver is active on the audio control interface */ ret = libusb_kernel_driver_active(audio_hdl, aud_cfg.ctrlif); if(ret < 0) printf("Error: libusb_kernel_driver_active failed %d\n", ret); if(ret == 1) { TRACE("Detach the kernel driver...\n"); /* If kernel driver is active, detach it so that we can claim * the interface */ ret = libusb_detach_kernel_driver(audio_hdl, aud_cfg.ctrlif); if(ret < 0) printf("Error: libusb_detach_kernel_driver failed " "%d\n", ret); } /* Claim audio control interface */ ret = libusb_claim_interface(audio_hdl, aud_cfg.ctrlif); if(ret < 0) { printf("Error: libusb_claim_interface failed %d\n", ret); } /* Claim audio streaming interface */ /* Check if a kernel driver is active on the audio interface */ ret = libusb_kernel_driver_active(audio_hdl, aud_cfg.interface); if(ret < 0) printf("Error: libusb_kernel_driver_active failed %d\n", ret); if(ret == 1) { TRACE("Detach the kernel driver...\n"); /* If kernel driver is active, detach it so that we can claim * the interface */ ret = libusb_detach_kernel_driver(audio_hdl, aud_cfg.interface); if(ret < 0) printf("Error: libusb_detach_kernel_driver failed " "%d\n",ret); } /* Claim audio streaming interface */ ret = libusb_claim_interface(audio_hdl, aud_cfg.interface); if(ret < 0) { printf("Error: libusb_claim_interface failed %d\n",ret); } /* Select sampling rate */ for(i=0;i<MAX_AUD_FMTS;i++) { if(aud_cfg.format[i].samFr == audio_sampling_rate){ aud_cfg.fmt_idx = i; break; } CHECK_ERROR(i == MAX_AUD_FMTS-1, -1, "Unable to set the sampling rate to %i", audio_sampling_rate); } /* Map default UAC format to Audio format */ cur_aud_format = AUD_FORMAT_PCM_RAW; /* Get min, max and real unit id for ctrl */ AUDIO_CTRL *ctrl = uac_controls; int16_t min = 0, max = 0; uint16_t res = 0; while(ctrl->id != CTRL_NONE) { switch(ctrl->unit) { TRACE(">>>>>id:%d unit:%d\n", ctrl->id,ctrl->unit); case FEATURE: ctrl->unit = aud_cfg.ctrl_feature; break; default: ERROR(-1, "Unsupported control unit (%i) for " "audio control %i", ctrl->unit, ctrl->id); } if (ctrl->id == CTRL_MUTE) { ctrl++; continue; } ret = get_ctrl(ctrl->id, GET_MIN, (void*) &min); CHECK_ERROR(ret < 0, -1, "Unable to get min (GET_MIN) for audio " "control: id=%i, cs=%i, cn=%i.", ctrl->id, ctrl->cs, ctrl->cn); ctrl->min = min; ret = get_ctrl(ctrl->id, GET_MAX, (void*) &max); CHECK_ERROR(ret < 0, -1, "Unable to get max (GET_MAX) for audio " "control: id=%i, cs=%i, cn=%i.", ctrl->id, ctrl->cs, ctrl->cn); ctrl->max = max; ret = get_ctrl(ctrl->id, GET_RES, (void*) &res); CHECK_ERROR(ret < 0, -1, "Unable to get res (GET_RES) for audio " "control: id=%i, cs=%i, cn=%i.", ctrl->id, ctrl->cs, ctrl->cn); ctrl->res = res; ctrl++; } /* Register removal USB event*/ register_libusb_removal_cb((libusb_pollfd_removed_cb) audio_removed, audio_hdl); /* Start event thread/loop */ ret = start_libusb_events(); if(ret < 0) return -1; audio_initialized = 1; return 0; }
int main(int argc, char **argv) { libusb_context* m_context; int init_result= libusb_init(&m_context); if(init_result){ std::cerr << "USB init failed: "<< init_result << std::endl; exit(EXIT_FAILURE); } libusb_set_debug(m_context,3); // libusb_device** m_device_list; // libusb_device** actual_device_ptr; // // ssize_t num_devices=libusb_get_device_list(m_context, &m_device_list); // // actual_device_ptr=m_device_list; // // // iterate device list // while(*actual_device_ptr!=0){ // libusb_device_descriptor desc; // // if(int error=libusb_get_device_descriptor(*m_device_list,&desc)){ // // std::cerr << "Get device error: " << libusb_error_name(error) <<std::endl; // } // // std::cout << std::hex // << "VendorID: " << desc.idVendor << std::endl // << "ProductID: " << desc.idProduct << std::endl // << "USB Release: "<< desc.bcdUSB << std::endl // << "Serial number: " <<(int) desc.iSerialNumber << std::endl // // << std::dec; // // // // std::cout << "******************************************"<< std::endl; // // actual_device_ptr++; // } // // std::cout << "Devices found: "<< num_devices << std::endl; // // libusb_free_device_list(m_device_list,0); // #define VENDORID 0x19a2 #define PRODUCTID 0x5001 libusb_device_handle* m_usb_device_handle = libusb_open_device_with_vid_pid(m_context, VENDORID, PRODUCTID); // libusb_device_handle* m_device_handle = libusb_open_device_with_vid_pid(m_context, 0x05e3,0x1205); if( !m_usb_device_handle){ std::cerr << "Error open device:" << std::endl; }else{ libusb_device* m_device =libusb_get_device(m_usb_device_handle); printdev(m_device); std::cout << " Device Class 0: All Interfaces operate independently" << std::endl; std::cout << " Interface Number: 0" << std::endl; std::cout << " Two descriptors of type Endpoint" << std::endl; std::cout << " Endpoint Adresses 129 and 2, does thes mean we have Adress 2 with different directions? " << std::endl; // Our only available interface number int the_usb_interface_number=0; if(libusb_kernel_driver_active(m_usb_device_handle,the_usb_interface_number)){ std::cout << "Error: Kernel driver found" << std::endl; if (int error=libusb_detach_kernel_driver(m_usb_device_handle,the_usb_interface_number)){ std::cout << "Detaching Kernel Driver failed " << error << std::endl; exit(EXIT_FAILURE); } }else{ std::cout << " No Kernel driver for attached Device found, " "that's good, libusb handels the device" << std::endl; } // Now we claim the device int error = libusb_claim_interface(m_usb_device_handle,the_usb_interface_number); if(error){ std::cout << "Claiming interface failed " << error << std::endl; exit(EXIT_FAILURE); } static const uint8_t DATA_STX=2; //Start of text static const uint8_t DATA_ETX=3; // End of Text uint8_t start_one_scan[]={DATA_STX,'s','R','N',' ','L','M','D','s','c','a','n','d','a','t','a',DATA_ETX}; uint8_t start_continuous_scan[]={DATA_STX,'s','E','N',' ','L','M','D','s','c','a','n','d','a','t','a',' ','1',DATA_ETX}; uint8_t stop_continuous_scan[]={DATA_STX,'s','E','N',' ','L','M','D','s','c','a','n','d','a','t','a',' ','0',DATA_ETX}; uint8_t read_endpoint=129; uint8_t write_endpoint=2; unsigned int timeout_millis=10000; // std::cout << sizeof(start_one_scan) << std::endl; int transferred_data_size=0; uint8_t receive_buf[2049]; error =libusb_bulk_transfer( m_usb_device_handle, write_endpoint, // start_one_scan, // sizeof(start_one_scan), start_continuous_scan, sizeof(start_continuous_scan), &transferred_data_size, timeout_millis); if(error){ std::cout << "Write Bulk Transfer failed " << error << std::endl; exit(EXIT_FAILURE); } std::cout<< "Transfered Data written: " << transferred_data_size<< std::endl; // Receive acknoledge error =libusb_bulk_transfer( m_usb_device_handle, read_endpoint, receive_buf , sizeof(receive_buf)-1, // leave one for termination &transferred_data_size, timeout_millis); if(error){ std::cout << "Read Bulk Transfer failed " << error << std::endl; exit(EXIT_FAILURE); } // String terminierung receive_buf[transferred_data_size]=0; std::cout<< "Acknoledge: " << receive_buf<< std::endl; TiM3xx_Data_Parser mdp; for (int i = 0; i < 10; ++i) { error =libusb_bulk_transfer( m_usb_device_handle, read_endpoint, receive_buf , sizeof(receive_buf)-1, // leave one for termination &transferred_data_size, timeout_millis); if(error){ std::cout << "Read Bulk Transfer failed " << error << std::endl; exit(EXIT_FAILURE); } //std::cout<< "Transfered Data read: " << transferred_data_size<< std::endl; // String terminierung receive_buf[transferred_data_size]=0; if(receive_buf[0]!=DATA_STX){ // read from device buff until it is empty, and next data set starts with STX-Code std::cout << "."; }else{ // std::cout << receive_buf << std::endl; mdp.set_pointer_to_data_buf(receive_buf,transferred_data_size); mdp.parse_data(); mdp.print_data(); } } // end of for loop // Stop Measurment error =libusb_bulk_transfer( m_usb_device_handle, write_endpoint, stop_continuous_scan, sizeof(stop_continuous_scan), &transferred_data_size, timeout_millis); if(error){ std::cout << "Write Bulk Transfer failed " << error << std::endl; exit(EXIT_FAILURE); } std::cout<< "Transfered Data written: " << transferred_data_size<< std::endl; error =libusb_bulk_transfer( m_usb_device_handle, read_endpoint, receive_buf , sizeof(receive_buf)-1, // leave one for termination &transferred_data_size, timeout_millis); if(error){ std::cout << "Read Bulk Transfer failed " << error << std::endl; exit(EXIT_FAILURE); } std::cout<< "Transfered Data read: " << transferred_data_size<< std::endl; // String terminierung receive_buf[transferred_data_size]=0; std::cout << receive_buf << std::endl; error= libusb_release_interface(m_usb_device_handle,the_usb_interface_number); if(error){ std::cout << "Releasing interface failed " << error << std::endl; exit(EXIT_FAILURE); } // libusb_device_descriptor desc; // // libusb_get_device_descriptor(m_device,&desc); // uint8_t buff[2048]; // // for(int desc_index=1; desc_index<256;desc_index++){ // // int num_bytes_read=libusb_get_string_descriptor_ascii(m_device_handle,desc_index,buff,2048); // // // if(num_bytes_read>0){ // std::cout<< desc_index << ": " << num_bytes_read << ": " << buff << std::endl; // // if(libusb_kernel_driver_active(m_device_handle,0)){ // // std::cout << "Kernel driver found" << std::endl; // } // // // }else{ // std::cerr<< desc_index << ": " << libusb_error_name(num_bytes_read) << std::endl; // } // } // std::cout << "**********************************************" << std::endl; } if( m_usb_device_handle){ libusb_close(m_usb_device_handle); } libusb_exit(m_context); }
int main(int argc, char *argv[]) { int c; static struct option long_options[] = { {"manufacturer", 1, 0, 'm'}, {"product", 1, 0, 'p'}, {"serial", 1, 0, 's'}, {"verbose", 0, 0, 'v'}, {"help", 0, 0, 'h'}, {NULL, 0, NULL, 0} }; char orig_manufacturer[128]; char* manufacturer = NULL; char orig_product[128]; char* product = NULL; char orig_serial[128]; char* serial = NULL; int bus = -1; int device = -1; struct ftdi_context ftdi; int ires = 0; while ((c = getopt_long(argc, argv, "m:p:s:vh", long_options, &optind)) != -1) { switch (c) { case 'm': manufacturer = optarg; break; case 'p': product = optarg; break; case 's': serial = optarg; break; case 'v': verbose_mode = true; break; case 'h': print_help(argc, argv); return EXIT_SUCCESS; break; } } if (optind + 1 != argc) { print_help(argc, argv); return EXIT_FAILURE; } else { if (!parse_device_identifier(&bus, &device, argv[optind])) { fprintf(stderr, "Unable to parse `%s'\n", argv[optind]); return EXIT_FAILURE; } print_verbose("Using device %03d:%03d\n", bus, device); } libusb_init(NULL); libusb_device** usb_devices; ssize_t n_devices = libusb_get_device_list(NULL, &usb_devices); if (n_devices < 0) { fprintf(stderr, "ERROR: Unable to list USB devices [%zd]: %s\n", n_devices, libusb_strerror((enum libusb_error) n_devices)); return EXIT_FAILURE; } libusb_device* usb_device = NULL; for (int i = 0 ; i < n_devices ; i++) { if (libusb_get_bus_number(usb_devices[i]) == bus && libusb_get_device_address(usb_devices[i]) == device) { usb_device = usb_devices[i]; break; } } if (usb_device == NULL) { fprintf(stderr, "ERROR: Unable to find USB device at %03d:%03d\n", bus, device); return EXIT_FAILURE; } if ((ires = ftdi_init(&ftdi)) != 0) { fprintf(stderr, "ERROR: Unable to initialize libftdi (%d)\n", ires); return EXIT_FAILURE; } if ((ires = ftdi_usb_open_dev(&ftdi, usb_device)) != 0) { fprintf(stderr, "ERROR: Unable to open device (%d)\n", ires); fprintf(stderr, " Perhaps you don't have sufficient permissions (i.e., you aren't root)?\n"); return EXIT_FAILURE; } { struct libusb_device_descriptor desc; if ((ires = libusb_get_device_descriptor(libusb_get_device (ftdi.usb_dev), &desc)) < 0) { fprintf(stderr, "ERROR: Unable to retrieve device descriptor (%d): %s\n", ires, libusb_strerror((enum libusb_error) ires)); return EXIT_FAILURE; } if ((ires = libusb_get_string_descriptor_ascii(ftdi.usb_dev, desc.iManufacturer, (unsigned char*) orig_manufacturer, sizeof(orig_manufacturer))) < 0) { fprintf(stderr, "ERROR: Unable to retrieve manufacturer (%d): %s\n", ires, libusb_strerror((enum libusb_error) ires)); return EXIT_FAILURE; } print_verbose("Old manufacturer: %s\n", orig_manufacturer); if (manufacturer == NULL) manufacturer = orig_manufacturer; if ((ires = libusb_get_string_descriptor_ascii(ftdi.usb_dev, desc.iProduct, (unsigned char*) orig_product, sizeof(orig_product))) < 0) { fprintf(stderr, "ERROR: Unable to retrieve product (%d): %s\n", ires, libusb_strerror((enum libusb_error) ires)); return EXIT_FAILURE; } print_verbose("Old product: %s\n", orig_product); if (product == NULL) product = orig_product; if ((ires = libusb_get_string_descriptor_ascii(ftdi.usb_dev, desc.iSerialNumber, (unsigned char*) orig_serial, sizeof(orig_serial))) < 0) { fprintf(stderr, "ERROR: Unable to retrieve serial (%d): %s\n", ires, libusb_strerror((enum libusb_error) ires)); return EXIT_FAILURE; } print_verbose("Old serial: %s\n", orig_serial); if (serial == NULL) serial = orig_serial; } print_verbose("New manufacturer: %s\n", manufacturer); print_verbose("New product: %s\n", product); print_verbose("New serial: %s\n", serial); if ((ires = ftdi_eeprom_initdefaults (&ftdi, manufacturer, product, serial)) < 0) { fprintf(stderr, "Unable to set EEPROM defaults: %d\n", ires); return EXIT_FAILURE; } if ((ires = ftdi_eeprom_build (&ftdi)) < 0) { fprintf(stderr, "Unable to build EEPROM: %d\n", ires); return EXIT_FAILURE; } if ((ires = ftdi_write_eeprom (&ftdi)) < 0) { fprintf(stderr, "Unable to write EEPROM: %d\n", ires); return EXIT_FAILURE; } ftdi_deinit(&ftdi); return EXIT_SUCCESS; }
int main(int argc, char * argv[]) { COMMAND_ACTION[0] = (BITRATE << 3) + (REPEAT << 5); libusb_device_handle * handle; int i, ret; unsigned int level; unsigned char command[1], buf[8], channel; char param; //Arg Control if (argc == 1) { printf("Usage: %s --help\n", argv[0]); return -1; } if (strcmp (argv[1],"--help")==0) { printf("Usage: %s <command> <channel> [<level>|<RGB>]\n", argv[0]); printf(" <command>:\n"); printf(" --on - Turn channel ON\n"); printf(" --off - Turn channel OFF\n"); printf(" --switch - Switch channel ON/OFF\n"); printf(" --set - Set level for channel\n"); printf(" --bind - Bind channel\n"); printf(" --unbind - Unbind channel\n"); printf(" --load - Load preset channel\n"); printf(" --save - Save preset channel\n"); printf(" --stop - Stop changing level\n"); printf(" --color_roll - Rolling color\n"); printf(" --color_switch - Switch color\n"); printf(" --color - Set color R[0..255] G[0..255] B[0..255]\n"); printf(" --mode - Switch mode\n"); printf(" --mode_speed - Switch mode speed\n"); printf(" <channel> must be [1..32]\n"); printf(" <level> must be [0..100] - use with -set_ch\n"); printf(" <RGB> must be [0..255] [0..255] [0..255] - use with -set_color\n"); return -1; } if (argc >= 3) { if (strcmp (argv[1],"--on")==0) //Set cnannel ON { COMMAND_ACTION[1] = 2; } else if (strcmp(argv[1],"--off")==0) //Set channel OFF { COMMAND_ACTION[1] = 0; } else if (strcmp(argv[1],"--switch")==0) //Switch channel ON/OFF { COMMAND_ACTION[1] = 4; } else if (strcmp(argv[1],"--set")==0) //Set level on channel - needed arg "level" { COMMAND_ACTION[1] = 6; COMMAND_ACTION[2] = 1; // формат if (argc >= 4) { level = atoi(argv[3]); } else { printf("Missing brightness value. \nUsage: %s <command> <channel> [<level>]\n", argv[0]); return -1; } if (level>100) { level=100; } if (level<0) { level=0; } if (level>0) { level=(int)(34+(float)level*1.23); } COMMAND_ACTION[5]= level; } else if (strcmp(argv[1],"--bind")==0) //Привязать канал { COMMAND_ACTION[1] = 15; } else if (strcmp(argv[1],"--unbind")==0) //отвязать канал { COMMAND_ACTION[1] = 9; } else if (strcmp(argv[1],"--preset")==0) //Вызов записанного ранее в программе сценария освещения presetX, где X – номер сценария в программе (1…5) { // COMMAND_ACTION[1] = ?; // не реализовано } else if (strcmp(argv[1],"--load")==0) //Команда вызова записанного сценария из памяти силового блока для канала X { COMMAND_ACTION[1] = 7; } else if (strcmp(argv[1],"--save")==0) //Команда записи сценария в память силового блока для канала X { COMMAND_ACTION[1] = 8; } else if (strcmp(argv[1],"--stop")==0) //остановить регулировку { COMMAND_ACTION[1] = 10; } else if (strcmp(argv[1],"--color_roll")==0) //включение плавного перебора цвета, выключается командой 10. { COMMAND_ACTION[1] = 16; COMMAND_ACTION[2] = 4; // формат } else if (strcmp(argv[1],"--color_switch")==0) //переключение цвета { COMMAND_ACTION[1] = 17; COMMAND_ACTION[2] = 4; // формат } else if (strcmp(argv[1],"--mode")==0) //переключение режима работы { COMMAND_ACTION[1] = 18; COMMAND_ACTION[2] = 4; // формат } else if (strcmp(argv[1],"--mode_speed")==0) //переключение скорости эффекта в режиме работы { COMMAND_ACTION[1] = 19; COMMAND_ACTION[2] = 4; // формат } else if (strcmp(argv[1],"--color")==0) //Установка яркости на каждый канал независимо (R - 1, G - 2, B - 3). Уровень передается параметрами в формате 0…255 { COMMAND_ACTION[1] = 6; COMMAND_ACTION[2] = 3; // формат COMMAND_ACTION[5] = atoi(argv[3]); // R COMMAND_ACTION[6] = atoi(argv[4]); // G COMMAND_ACTION[7] = atoi(argv[5]); // B } else { printf("Command unknown\n"); return -1; } } else { printf("Unknown command.\nUsage: %s <command> <channel> [<level>]\n", argv[0]); return -1; } if (argc >= 3) { channel = atoi(argv[2]); channel--; COMMAND_ACTION[4] = channel; } else { printf("No channel number.\nUsage: %s <command> <channel> [<level>]\n", argv[0]); return -1; } //Prepare Command string libusb_init(NULL); libusb_set_debug(NULL, 3); handle = libusb_open_device_with_vid_pid(NULL, DEV_VID, DEV_PID); if (handle == NULL) { printf("No compatible devices were found.\n"); libusb_exit(NULL); return 0; } char str_desc[10]; struct libusb_device_descriptor desc; libusb_get_device_descriptor(libusb_get_device(handle), &desc); libusb_get_string_descriptor_ascii(handle, desc.iProduct, str_desc, 10); if ( (channel < 0) || (channel >= atoi(str_desc+4))) { printf("Channel number is out of range (1-%d for the %s transmitter you are using)\nUsage: %s <command> <channel> [<level>]\n", atoi(str_desc+4), str_desc, argv[0]); return -1; } if (libusb_kernel_driver_active(handle,DEV_INTF)) { libusb_detach_kernel_driver(handle, DEV_INTF); } if ((ret = libusb_set_configuration(handle, DEV_CONFIG)) < 0) { printf("USB configuration error %i.\n", ret); libusb_close(handle); libusb_exit(NULL); return 0; } if (libusb_claim_interface(handle, DEV_INTF) < 0) { printf("USB interface error.\n"); libusb_close(handle); libusb_exit(NULL); return 0; } //0x9 - номер запроса //0x300 - значение запроса - их надо получить из мониторинга if ((ret = libusb_control_transfer(handle, LIBUSB_REQUEST_TYPE_CLASS|LIBUSB_RECIPIENT_INTERFACE|LIBUSB_ENDPOINT_OUT, 0x9, 0x300, 0, COMMAND_ACTION, 8, 100)) < 0) { printf("USB data transfer error %i.\n", ret); } libusb_attach_kernel_driver(handle, DEV_INTF); libusb_close(handle); libusb_exit(NULL); return 0; }
int main(int argc, char * argv[]) { if (argc != 2 || argc == 2 && (strcasecmp(argv[1], "off") != 0) && (strcasecmp(argv[1], "on") != 0) && (strcasecmp(argv[1], "get") != 0)) goto usage; libusb_device_handle *handle; libusb_device *device; int ret; unsigned char buf[8]; unsigned char description[8]; struct libusb_device_descriptor desc; ret = libusb_init(NULL); if (ret < 0) { printf("failed to initialize libusb!\n"); goto exit; } libusb_set_debug(NULL, 3); handle = libusb_open_device_with_vid_pid(NULL, DEV_VID, DEV_PID); if (handle == NULL) { printf("no connected " DEV_NAME " found!\n"); libusb_exit(NULL); goto exit; } if (libusb_kernel_driver_active(handle,DEV_INTF)) libusb_detach_kernel_driver(handle, DEV_INTF); if ((ret = libusb_set_configuration(handle, DEV_CONFIG)) < 0) { printf(DEV_NAME "configuration failed!\n"); goto done; } if (libusb_claim_interface(handle, DEV_INTF) < 0) { printf(DEV_NAME " interface claim error!\n"); goto finish; } device = libusb_get_device(handle); ret = libusb_get_device_descriptor(device, &desc); if (ret < 0) { printf("failed to get " DEV_NAME " descriptor\n"); goto finish; } else { if (libusb_get_string_descriptor_ascii(handle, desc.iProduct, description, 8-1) <= 0 || strcmp(DEV_NAME, description) != 0 ) { printf("%s instead of " DEV_NAME " found!\n", description); ret = -1; goto finish; } } if (strcasecmp(argv[1], "on") == 0) { ret = libusb_control_transfer(handle, LIBUSB_REQUEST_TYPE_CLASS|LIBUSB_RECIPIENT_INTERFACE|LIBUSB_ENDPOINT_OUT, 0x9, 0x300, 0, COMMAND_1, 8, 1000); if (ret > 0) printf("OK\n"); else printf("FAIL\n"); } if (strcasecmp(argv[1], "off") == 0) { ret = libusb_control_transfer(handle, LIBUSB_REQUEST_TYPE_CLASS|LIBUSB_RECIPIENT_INTERFACE|LIBUSB_ENDPOINT_OUT, 0x9, 0x300, 0, COMMAND_2, 8, 1000); if (ret > 0) printf("OK\n"); else printf("FAIL\n"); } if (strcasecmp(argv[1], "get") == 0) { ret = libusb_control_transfer(handle, LIBUSB_REQUEST_TYPE_CLASS|LIBUSB_RECIPIENT_INTERFACE|LIBUSB_ENDPOINT_OUT, 0x9, 0x300, 0, COMMAND_3, 8, 1000); ret = libusb_control_transfer(handle, LIBUSB_REQUEST_TYPE_CLASS|LIBUSB_RECIPIENT_INTERFACE|LIBUSB_ENDPOINT_IN, 0x1, 0x300, 0, COMMAND_3, 8, 1000); if (ret > 0) printf("%d\n", COMMAND_3[1] == 0x19 ? 0 : 1); else printf("FAIL\n"); } finish: libusb_attach_kernel_driver(handle, DEV_INTF); done: libusb_close(handle); libusb_exit(NULL); if (ret > 0) exit(0); else goto exit; usage: printf("Invalid parameters!\n"); printf("Usage: mp709 <on|off|get>\n\n"); exit: exit(1); }
int main(int argc, char *argv[]) { std::string program_path(argv[0]); size_t executable_name_idx = program_path.rfind("Protonect"); std::string binpath = "/"; if(executable_name_idx != std::string::npos) { binpath = program_path.substr(0, executable_name_idx); } uint16_t vid = 0x045E; uint16_t pid = 0x02C4; uint16_t mi = 0x00; bool debug_mode = false; libusb_device_handle *handle; libusb_device *dev; uint8_t bus; const char* speed_name[5] = { "Unknown", "1.5 Mbit/s (USB LowSpeed)", "12 Mbit/s (USB FullSpeed)", "480 Mbit/s (USB HighSpeed)", "5000 Mbit/s (USB SuperSpeed)" }; int r; const struct libusb_version* version; version = libusb_get_version(); printf("Using libusbx v%d.%d.%d.%d\n\n", version->major, version->minor, version->micro, version->nano); r = libusb_init(NULL); if (r < 0) return r; libusb_set_debug(NULL, debug_mode ? LIBUSB_LOG_LEVEL_DEBUG : LIBUSB_LOG_LEVEL_INFO); printf("Opening device %04X:%04X...\n", vid, pid); handle = libusb_open_device_with_vid_pid(NULL, vid, pid); if (handle == NULL) { perr(" Failed.\n"); //system("PAUSE"); return -1; } dev = libusb_get_device(handle); bus = libusb_get_bus_number(dev); /* struct libusb_device_descriptor dev_desc; printf("\nReading device descriptor:\n"); CALL_CHECK(libusb_get_device_descriptor(dev, &dev_desc)); printf(" length: %d\n", dev_desc.bLength); printf(" device class: %d\n", dev_desc.bDeviceClass); printf(" S/N: %d\n", dev_desc.iSerialNumber); printf(" VID:PID: %04X:%04X\n", dev_desc.idVendor, dev_desc.idProduct); printf(" bcdDevice: %04X\n", dev_desc.bcdDevice); printf(" iMan:iProd:iSer: %d:%d:%d\n", dev_desc.iManufacturer, dev_desc.iProduct, dev_desc.iSerialNumber); printf(" nb confs: %d\n", dev_desc.bNumConfigurations); */ r = libusb_get_device_speed(dev); if ((r < 0) || (r > 4)) r = 0; printf(" speed: %s\n", speed_name[r]); int active_cfg = -5; r = libusb_get_configuration(handle, &active_cfg); printf("active configuration: %d, err: %d", active_cfg, r); int configId = 1; if (active_cfg != configId) { printf("Setting config: %d\n", configId); r = libusb_set_configuration(handle, configId); if (r != LIBUSB_SUCCESS) { perr(" Can't set configuration. Error code: %d (%s)\n", r, libusb_error_name(r)); } } int iface = 0; printf("\nClaiming interface %d...\n", iface); r = libusb_claim_interface(handle, iface); if (r != LIBUSB_SUCCESS) { perr(" Failed: %d.\n", r); } iface = 1; printf("\nClaiming interface %d...\n", iface); r = libusb_claim_interface(handle, iface); if (r != LIBUSB_SUCCESS) { perr(" Failed: %d.\n", r); } InitKinect(handle); // install signal handler now signal(SIGINT,sigint_handler); shutdown = false; libfreenect2::usb::EventLoop usb_loop; usb_loop.start(); libfreenect2::FrameMap frames; libfreenect2::FrameListener frame_listener(libfreenect2::Frame::Color | libfreenect2::Frame::Ir | libfreenect2::Frame::Depth); //libfreenect2::DumpRgbPacketProcessor rgb_processor; libfreenect2::TurboJpegRgbPacketProcessor rgb_processor; rgb_processor.setFrameListener(&frame_listener); libfreenect2::RgbPacketStreamParser rgb_packet_stream_parser(&rgb_processor); libfreenect2::usb::BulkTransferPool rgb_bulk_transfers(handle, 0x83); rgb_bulk_transfers.allocate(50, 0x4000); rgb_bulk_transfers.setCallback(&rgb_packet_stream_parser); rgb_bulk_transfers.enableSubmission(); libfreenect2::CpuDepthPacketProcessor depth_processor; depth_processor.setFrameListener(&frame_listener); depth_processor.load11To16LutFromFile((binpath + "../11to16.bin").c_str()); depth_processor.loadXTableFromFile((binpath + "../xTable.bin").c_str()); depth_processor.loadZTableFromFile((binpath + "../zTable.bin").c_str()); libfreenect2::DepthPacketStreamParser depth_packet_stream_parser(&depth_processor); size_t max_packet_size = libusb_get_max_iso_packet_size(dev, 0x84); std::cout << "iso max_packet_size: " << max_packet_size << std::endl; libfreenect2::usb::IsoTransferPool depth_iso_transfers(handle, 0x84); depth_iso_transfers.allocate(80, 8, max_packet_size); depth_iso_transfers.setCallback(&depth_packet_stream_parser); depth_iso_transfers.enableSubmission(); r = libusb_get_device_speed(dev); if ((r < 0) || (r > 4)) r = 0; printf(" speed: %s\n", speed_name[r]); RunKinect(handle, depth_processor); rgb_bulk_transfers.submit(10); depth_iso_transfers.submit(60); r = libusb_get_device_speed(dev); if ((r < 0) || (r > 4)) r = 0; printf(" speed: %s\n", speed_name[r]); while(!shutdown) { frame_listener.waitForNewFrame(frames); libfreenect2::Frame *rgb = frames[libfreenect2::Frame::Color]; libfreenect2::Frame *ir = frames[libfreenect2::Frame::Ir]; libfreenect2::Frame *depth = frames[libfreenect2::Frame::Depth]; cv::imshow("rgb", cv::Mat(rgb->height, rgb->width, CV_8UC3, rgb->data)); cv::imshow("ir", cv::Mat(ir->height, ir->width, CV_32FC1, ir->data) / 20000.0f); cv::imshow("depth", cv::Mat(depth->height, depth->width, CV_32FC1, depth->data) / 4500.0f); cv::waitKey(1); frame_listener.release(frames); } r = libusb_get_device_speed(dev); if ((r < 0) || (r > 4)) r = 0; printf(" speed: %s\n", speed_name[r]); rgb_bulk_transfers.disableSubmission(); depth_iso_transfers.disableSubmission(); CloseKinect(handle); rgb_bulk_transfers.cancel(); depth_iso_transfers.cancel(); // wait for all transfers to cancel // TODO: better implementation libfreenect2::this_thread::sleep_for(libfreenect2::chrono::seconds(2)); rgb_bulk_transfers.deallocate(); depth_iso_transfers.deallocate(); r = libusb_get_device_speed(dev); if ((r < 0) || (r > 4)) r = 0; printf(" speed: %s\n", speed_name[r]); iface = 0; printf("Releasing interface %d...\n", iface); libusb_release_interface(handle, iface); iface = 1; printf("Releasing interface %d...\n", iface); libusb_release_interface(handle, iface); printf("Closing device...\n"); libusb_close(handle); usb_loop.stop(); libusb_exit(NULL); //system("PAUSE"); return 0; }
FN_INTERNAL int fnusb_open_subdevices(freenect_device *dev, int index) { freenect_context *ctx = dev->parent; dev->device_does_motor_control_with_audio = 0; dev->motor_control_with_audio_enabled = 0; dev->usb_cam.parent = dev; dev->usb_cam.dev = NULL; dev->usb_motor.parent = dev; dev->usb_motor.dev = NULL; dev->usb_audio.parent = dev; dev->usb_audio.dev = NULL; libusb_device **devs; // pointer to pointer of device, used to retrieve a list of devices ssize_t cnt = libusb_get_device_list (dev->parent->usb.ctx, &devs); //get the list of devices if (cnt < 0) return -1; int i = 0, nr_cam = 0; int res; struct libusb_device_descriptor desc; for (i = 0; i < cnt; i++) { int r = libusb_get_device_descriptor (devs[i], &desc); if (r < 0) continue; if (desc.idVendor != VID_MICROSOFT) continue; res = 0; // Search for the camera if ((ctx->enabled_subdevices & FREENECT_DEVICE_CAMERA) && !dev->usb_cam.dev && (desc.idProduct == PID_NUI_CAMERA || desc.idProduct == PID_K4W_CAMERA)) { // If the index given by the user matches our camera index if (nr_cam == index) { dev->usb_cam.VID = desc.idVendor; dev->usb_cam.PID = desc.idProduct; res = libusb_open (devs[i], &dev->usb_cam.dev); if (res < 0 || !dev->usb_cam.dev) { FN_ERROR("Could not open camera: %d\n", res); dev->usb_cam.dev = NULL; break; } if (desc.idProduct == PID_K4W_CAMERA || desc.bcdDevice != fn_le32(267)) { freenect_device_flags requested_devices = ctx->enabled_subdevices; // Not the 1414 kinect so remove the motor flag, this should preserve the audio flag if set ctx->enabled_subdevices = (freenect_device_flags)(ctx->enabled_subdevices & ~FREENECT_DEVICE_MOTOR); ctx->zero_plane_res = 334; dev->device_does_motor_control_with_audio = 1; // set the LED for non 1414 devices to keep the camera alive for some systems which get freezes libusb_device * audioDevice = fnusb_find_connected_audio_device(devs[i], devs, cnt); if (audioDevice != NULL) { libusb_device_handle * audioHandle = NULL; res = libusb_open(audioDevice, &audioHandle); if (res != 0) { FN_ERROR("Failed to set the LED of K4W or 1473 device: %d\n", res); } else { // we need to do this as it is possible that the device was not closed properly in a previous session // if we don't do this and the device wasn't closed properly - it can cause infinite hangs on LED and TILT functions libusb_reset_device(audioHandle); libusb_close(audioHandle); res = libusb_open(audioDevice, &audioHandle); if (res == 0) { res = libusb_claim_interface(audioHandle, 0); if (res != 0) { FN_ERROR("Unable to claim interface %d\n", res); } else { fnusb_set_led_alt(audioHandle, ctx, LED_GREEN); libusb_release_interface(audioHandle, 0); } libusb_close(audioHandle); } } } // for newer devices we need to enable the audio device for motor control // we only do this though if motor has been requested. if ((requested_devices & FREENECT_DEVICE_MOTOR) && (requested_devices & FREENECT_DEVICE_AUDIO) == 0) { ctx->enabled_subdevices = (freenect_device_flags)(ctx->enabled_subdevices | FREENECT_DEVICE_AUDIO); } } else { // The good old kinect that tilts and tweets ctx->zero_plane_res = 322; } res = fnusb_claim_camera(dev); if (res < 0) { break; } } else { nr_cam++; } } } if (ctx->enabled_subdevices == FREENECT_DEVICE_CAMERA || res < 0) cnt = 0; //FIND MOTOR BASED ON PARENT HUB if( (ctx->enabled_subdevices & FREENECT_DEVICE_MOTOR) && dev->usb_cam.dev != NULL ) { libusb_device * camera = libusb_get_device( dev->usb_cam.dev ); libusb_device * cameraParent = libusb_get_parent( camera ); if( cameraParent != NULL ) { for(i = 0; i < cnt; i++) { // Match audio based on camera parent if( cameraParent == libusb_get_parent(devs[i]) ) { int r = libusb_get_device_descriptor (devs[i], &desc); if (r < 0) continue; if (desc.idVendor != VID_MICROSOFT) continue; // This has to be the device we are looking for as it is a Kinect motor device with the same parent as the camera if ( !dev->usb_motor.dev && desc.idProduct == PID_NUI_MOTOR) { dev->usb_motor.VID = desc.idVendor; dev->usb_motor.PID = desc.idProduct; res = libusb_open (devs[i], &dev->usb_motor.dev); if (res < 0 || !dev->usb_motor.dev) { FN_ERROR("Could not open motor: %d\n", res); dev->usb_motor.dev = NULL; break; } res = libusb_claim_interface (dev->usb_motor.dev, 0); if (res < 0) { FN_ERROR("Could not claim interface on motor: %d\n", res); libusb_close(dev->usb_motor.dev); dev->usb_motor.dev = NULL; break; } // This has to be the device we need, as it is matched by parent - so don't try any others break; } } } } } // FIND AUDIO BASED ON PARENT HUB if( (ctx->enabled_subdevices & FREENECT_DEVICE_AUDIO) && dev->usb_cam.dev != NULL ) { libusb_device * camera = libusb_get_device( dev->usb_cam.dev ); libusb_device * cameraParent = libusb_get_parent( camera ); if( cameraParent != NULL ) { for(i = 0; i < cnt; i++) { // Match audio based on camera parent if( cameraParent == libusb_get_parent(devs[i]) ) { int r = libusb_get_device_descriptor (devs[i], &desc); if (r < 0) continue; if (desc.idVendor != VID_MICROSOFT) continue; // This has to be the device we are looking for as it is a Kinect audio device with the same parent as the camera if ( !dev->usb_audio.dev && (desc.idProduct == PID_NUI_AUDIO || fnusb_is_pid_k4w_audio(desc.idProduct))) { dev->usb_audio.VID = desc.idVendor; dev->usb_audio.PID = desc.idProduct; res = libusb_open (devs[i], &dev->usb_audio.dev); if (res < 0 || !dev->usb_audio.dev) { FN_ERROR("Could not open audio: %d\n", res); dev->usb_audio.dev = NULL; break; } res = libusb_claim_interface (dev->usb_audio.dev, 0); if (res < 0) { FN_ERROR("Could not claim interface on audio: %d\n", res); libusb_close(dev->usb_audio.dev); dev->usb_audio.dev = NULL; break; } // Using the device handle that we've claimed, see if this // device has already uploaded firmware (has 2 interfaces). // If not, save the serial number (by reading the appropriate // descriptor), upload the firmware, and then enter a loop // waiting for a device with the same serial number to // reappear. int num_interfaces = fnusb_num_interfaces(&dev->usb_audio); if (num_interfaces >= 2) { if (dev->device_does_motor_control_with_audio) { dev->motor_control_with_audio_enabled = 1; } } else { // Read the serial number from the string descriptor and save it. unsigned char string_desc[256]; // String descriptors are at most 256 bytes res = libusb_get_string_descriptor_ascii(dev->usb_audio.dev, desc.iSerialNumber, string_desc, 256); if (res < 0) { FN_ERROR("Failed to retrieve serial number for audio device in bootloader state\n"); break; } char* audio_serial = strdup((char*)string_desc); FN_SPEW("Uploading firmware to audio device in bootloader state.\n"); // Check if we can load from memory - otherwise load from disk if (desc.idProduct == PID_NUI_AUDIO && ctx->fn_fw_nui_ptr && ctx->fn_fw_nui_size > 0) { FN_SPEW("loading firmware from memory\n"); res = upload_firmware_from_memory(&dev->usb_audio, ctx->fn_fw_nui_ptr, ctx->fn_fw_nui_size); } else if (desc.idProduct == PID_K4W_AUDIO && ctx->fn_fw_k4w_ptr && ctx->fn_fw_k4w_size > 0) { FN_SPEW("loading firmware from memory\n"); res = upload_firmware_from_memory(&dev->usb_audio, ctx->fn_fw_k4w_ptr, ctx->fn_fw_k4w_size); } else { res = upload_firmware(&dev->usb_audio, "audios.bin"); } if (res < 0) { FN_ERROR("upload_firmware failed: %d\n", res); break; } libusb_close(dev->usb_audio.dev); dev->usb_audio.dev = NULL; // Wait for the device to reappear. int loops = 0; for (loops = 0; loops < 10; loops++) { FN_SPEW("Try %d: Looking for new audio device matching serial %s\n", loops, audio_serial); // Scan devices. libusb_device **new_dev_list; int dev_index; ssize_t num_new_devs = libusb_get_device_list(ctx->usb.ctx, &new_dev_list); for (dev_index = 0; dev_index < num_new_devs; ++dev_index) { struct libusb_device_descriptor new_dev_desc; int r; r = libusb_get_device_descriptor (new_dev_list[dev_index], &new_dev_desc); if (r < 0) continue; // If this dev is a Kinect audio device, open device, read serial, and compare. if (new_dev_desc.idVendor == VID_MICROSOFT && (new_dev_desc.idProduct == PID_NUI_AUDIO || fnusb_is_pid_k4w_audio(desc.idProduct))) { FN_SPEW("Matched VID/PID!\n"); libusb_device_handle* new_dev_handle; // Open device r = libusb_open(new_dev_list[dev_index], &new_dev_handle); if (r < 0) continue; // Read serial r = libusb_get_string_descriptor_ascii(new_dev_handle, new_dev_desc.iSerialNumber, string_desc, 256); if (r < 0) { FN_SPEW("Lost new audio device while fetching serial number.\n"); libusb_close(new_dev_handle); continue; } // Compare to expected serial if (r == strlen(audio_serial) && strcmp((char*)string_desc, audio_serial) == 0) { // We found it! r = libusb_claim_interface(new_dev_handle, 0); if (r != 0) { // Ouch, found the device but couldn't claim the interface. FN_SPEW("Device with serial %s reappeared but couldn't claim interface 0\n", audio_serial); libusb_close(new_dev_handle); continue; } // Save the device handle. dev->usb_audio.dev = new_dev_handle; // Verify that we've actually found a device running the right firmware. num_interfaces = fnusb_num_interfaces(&dev->usb_audio); if (num_interfaces >= 2) { if (dev->device_does_motor_control_with_audio) { dev->motor_control_with_audio_enabled = 1; } } else { FN_SPEW("Opened audio with matching serial but too few interfaces.\n"); dev->usb_audio.dev = NULL; libusb_close(new_dev_handle); continue; } break; } else { FN_SPEW("Got serial %s, expected serial %s\n", (char*)string_desc, audio_serial); } } } libusb_free_device_list(new_dev_list, 1); // If we found the right device, break out of this loop. if (dev->usb_audio.dev) break; // Sleep for a second to give the device more time to reenumerate. sleep(1); } free(audio_serial); } // This has to be the device we need, as it is matched by parent - so don't try any others break; } } } } } libusb_free_device_list (devs, 1); // free the list, unref the devices in it if ((dev->usb_cam.dev || !(ctx->enabled_subdevices & FREENECT_DEVICE_CAMERA)) && (dev->usb_motor.dev || !(ctx->enabled_subdevices & FREENECT_DEVICE_MOTOR))) //&& (dev->usb_audio.dev || !(ctx->enabled_subdevices & FREENECT_DEVICE_AUDIO))) { // Each requested subdevice is open. // Except audio, which may fail if firmware is missing (or because it hates us). return 0; } if (dev->usb_cam.dev != NULL) { libusb_release_interface(dev->usb_cam.dev, 0); libusb_close(dev->usb_cam.dev); } else { FN_ERROR("Failed to open camera subdevice or it is not disabled."); } if (dev->usb_motor.dev != NULL) { libusb_release_interface(dev->usb_motor.dev, 0); libusb_close(dev->usb_motor.dev); } else { FN_ERROR("Failed to open motor subddevice or it is not disabled."); } if (dev->usb_audio.dev != NULL) { libusb_release_interface(dev->usb_audio.dev, 0); libusb_close(dev->usb_audio.dev); } else { FN_ERROR("Failed to open audio subdevice or it is not disabled."); } return -1; }
int main(int argc, char **argv) { struct libusb_device_descriptor desc; const struct t_pid *ppid = pidtab; ssize_t nr; int offset = 0, size = 0; uint16_t crc16; uint8_t flag = 0; char action; char *partname = NULL; info("rkflashtool v%d.%d\n", RKFLASHTOOL_VERSION_MAJOR, RKFLASHTOOL_VERSION_MINOR); NEXT; if (!argc) usage(); action = **argv; NEXT; switch(action) { case 'b': if (argc > 1) usage(); else if (argc == 1) flag = strtoul(argv[0], NULL, 0); break; case 'l': case 'L': if (argc) usage(); break; case 'e': case 'r': case 'w': if (argc < 1 || argc > 2) usage(); if (argc == 1) { partname = argv[0]; } else { offset = strtoul(argv[0], NULL, 0); size = strtoul(argv[1], NULL, 0); } break; case 'm': case 'M': case 'B': case 'i': if (argc != 2) usage(); offset = strtoul(argv[0], NULL, 0); size = strtoul(argv[1], NULL, 0); break; case 'n': case 'v': case 'p': case 'P': if (argc) usage(); offset = 0; size = 1024; break; default: usage(); } /* Initialize libusb */ if (libusb_init(&c)) fatal("cannot init libusb\n"); libusb_set_debug(c, 3); /* Detect connected RockChip device */ while ( !h && ppid->pid) { h = libusb_open_device_with_vid_pid(c, 0x2207, ppid->pid); if (h) { info("Detected %s...\n", ppid->name); break; } ppid++; } if (!h) fatal("cannot open device\n"); /* Connect to device */ if (libusb_kernel_driver_active(h, 0) == 1) { info("kernel driver active\n"); if (!libusb_detach_kernel_driver(h, 0)) info("driver detached\n"); } if (libusb_claim_interface(h, 0) < 0) fatal("cannot claim interface\n"); info("interface claimed\n"); if (libusb_get_device_descriptor(libusb_get_device(h), &desc) != 0) fatal("cannot get device descriptor\n"); if (desc.bcdUSB == 0x200) info("MASK ROM MODE\n"); switch(action) { case 'l': info("load DDR init\n"); crc16 = 0xffff; while ((nr = read(0, buf, 4096)) == 4096) { crc16 = rkcrc16(crc16, buf, nr); libusb_control_transfer(h, LIBUSB_REQUEST_TYPE_VENDOR, 12, 0, 1137, buf, nr, 0); } if (nr != -1) { crc16 = rkcrc16(crc16, buf, nr); buf[nr++] = crc16 >> 8; buf[nr++] = crc16 & 0xff; libusb_control_transfer(h, LIBUSB_REQUEST_TYPE_VENDOR, 12, 0, 1137, buf, nr, 0); } goto exit; case 'L': info("load USB loader\n"); crc16 = 0xffff; while ((nr = read(0, buf, 4096)) == 4096) { crc16 = rkcrc16(crc16, buf, nr); libusb_control_transfer(h, LIBUSB_REQUEST_TYPE_VENDOR, 12, 0, 1138, buf, nr, 0); } if (nr != -1) { crc16 = rkcrc16(crc16, buf, nr); buf[nr++] = crc16 >> 8; buf[nr++] = crc16 & 0xff; libusb_control_transfer(h, LIBUSB_REQUEST_TYPE_VENDOR, 12, 0, 1138, buf, nr, 0); }
transport_t::transport_t(const usb_context_ptr_t &ctx_, const device_ptr_t &dev, const notifier_t *terminator) : ctx_(ctx_), dev_(dev), terminator_(terminator), claimed_interface_(false), writer_termination_requested_(false), cur_consumed_(), read_window_size_() { stream_buffer_.resize(stream_buffer_size_); std::shared_ptr<libusb_device> dev_info(libusb_get_device(dev_.get()), [](libusb_device* d){libusb_unref_device(d);}); assert(dev_info); TA_TRACE() << "Retrieving USB configuration"; libusb_config_descriptor *config = 0; //We're always using the first configuration if (libusb_get_config_descriptor(dev_info.get(), 0, &config) != 0) throw std::runtime_error("Failed to get USB configuration"); ON_BLOCK_EXIT([=]{libusb_free_config_descriptor(config);}); uint8_t interface_id=0, endpoint_in=0, endpoint_out=0; bool endpoint_in_found = false, endpoint_out_found = false; int alt_setting_id=-1; for(interface_id=0; interface_id<config->bNumInterfaces; ++interface_id) { const libusb_interface *inter = &config->interface[interface_id]; for(int n=0; n<inter->num_altsetting; ++n) { endpoint_in_found = false; endpoint_out_found = false; const libusb_interface_descriptor *interdesc = &inter->altsetting[n]; alt_setting_id = interdesc->bAlternateSetting; for(int k=0; k<(int)interdesc->bNumEndpoints; k++) { const libusb_endpoint_descriptor *epdesc = &interdesc->endpoint[k]; if ((epdesc->bmAttributes & LIBUSB_TRANSFER_TYPE_MASK) != LIBUSB_TRANSFER_TYPE_BULK) continue; int dir = epdesc->bEndpointAddress & LIBUSB_ENDPOINT_DIR_MASK; if (dir == LIBUSB_ENDPOINT_IN) { endpoint_in = epdesc->bEndpointAddress; endpoint_in_found = true; //The read buffer size must be a multiply of wMaxPacketSize //to avoid buffer overruns. read_window_size_ = (stream_buffer_size_ - AA_PACKET_HEADER_SIZE); read_window_size_ -= (read_window_size_ % epdesc->wMaxPacketSize); } else { endpoint_out = epdesc->bEndpointAddress; endpoint_out_found = true; } } if (endpoint_in_found && endpoint_out_found) break; } if (endpoint_in_found && endpoint_out_found) break; } if (!endpoint_out || !endpoint_in) throw std::runtime_error("Failed to find bulk in/out endpoints on the ACC device"); TA_DEBUG() << "Found bulk endpoints: "<< (int)endpoint_in << " and " << (int)endpoint_out << ", config " << alt_setting_id << ", interface " << (int)interface_id; int ret = -1; for(int n = 0; n<10; ++n) { ret = libusb_claim_interface(dev.get(), interface_id); if (ret == 0) break; TA_DEBUG() << "Failed to claim USB interface, try " << n; terminator_->sleep(200); } if (ret != 0) { str_out_t p; p << "Failed to claim USB interface: " << libusb_error_name(ret); throw std::runtime_error(p); } TA_DEBUG() << "Claimed USB interface"; ret = libusb_set_interface_alt_setting(dev.get(), interface_id, alt_setting_id); if (ret != 0) { str_out_t p; p << "Failed to select configuration " << alt_setting_id; throw std::runtime_error(p); } TA_INFO() << "USB interface ready"; assert(read_window_size_); this->claimed_interface_ = true; this->endpoint_in_ = endpoint_in; this->endpoint_out_ = endpoint_out; this->interface_id_ = interface_id; this->writer_thread_ = std::thread([](transport_t *t){t->writer_loop();}, this); }
XN_C_API XnStatus xnUSBOpenEndPoint(XN_USB_DEV_HANDLE pDevHandle, XnUInt16 nEndPointID, XnUSBEndPointType nEPType, XnUSBDirectionType nDirType, XN_USB_EP_HANDLE* pEPHandlePtr) { // validate parameters XN_VALIDATE_USB_INIT(); XN_VALIDATE_DEVICE_HANDLE(pDevHandle); XN_VALIDATE_OUTPUT_PTR(pEPHandlePtr); // get the device from the handle libusb_device* pDevice = libusb_get_device(pDevHandle->hDevice); // get the configuration descriptor libusb_config_descriptor* pConfig; int rc = libusb_get_active_config_descriptor(pDevice, &pConfig); if (rc != 0) { return (XN_STATUS_USB_CONFIG_QUERY_FAILED); } // make sure configuration contains the interface we need if (pConfig->bNumInterfaces <= pDevHandle->nInterface) { libusb_free_config_descriptor(pConfig); return (XN_STATUS_USB_INTERFACE_QUERY_FAILED); } // take that interface const libusb_interface* pInterface = &pConfig->interface[pDevHandle->nInterface]; // make sure interface contains the alternate setting we work with if (pInterface->num_altsetting <= pDevHandle->nAltSetting) { libusb_free_config_descriptor(pConfig); return (XN_STATUS_USB_INTERFACE_QUERY_FAILED); } // take that setting const libusb_interface_descriptor* pInterfaceDesc = &pInterface->altsetting[pDevHandle->nAltSetting]; // search for the requested endpoint const libusb_endpoint_descriptor* pEndpointDesc = NULL; for (uint8_t i = 0; i < pInterfaceDesc->bNumEndpoints; ++i) { if (pInterfaceDesc->endpoint[i].bEndpointAddress == nEndPointID) { pEndpointDesc = &pInterfaceDesc->endpoint[i]; break; } } if (pEndpointDesc == NULL) { libusb_free_config_descriptor(pConfig); return (XN_STATUS_USB_ENDPOINT_NOT_FOUND); } libusb_transfer_type transfer_type = (libusb_transfer_type)(pEndpointDesc->bmAttributes & 0x3); // lower 2-bits // calculate max packet size // NOTE: we do not use libusb functions (libusb_get_max_packet_size/libusb_get_max_iso_packet_size) because // they hace a bug and does not consider alternative interface XnUInt32 nMaxPacketSize = 0; if (transfer_type == LIBUSB_TRANSFER_TYPE_ISOCHRONOUS) { XnUInt32 wMaxPacketSize = pEndpointDesc->wMaxPacketSize; // bits 11 and 12 mark the number of additional transactions, bits 0-10 mark the size XnUInt32 nAdditionalTransactions = wMaxPacketSize >> 11; XnUInt32 nPacketSize = wMaxPacketSize & 0x7FF; nMaxPacketSize = (nAdditionalTransactions + 1) * (nPacketSize); }
int main(int argc, char **argv) { const char *lua_init = "init.lua"; std::vector< std::pair< exec_type, std::string > > startup_cmds; // parse command line while(1) { static struct option long_options[] = { {"help", no_argument, 0, '?'}, {"quiet", no_argument, 0, 'q'}, {0, 0, 0, 0} }; int c = getopt_long(argc, argv, "?qi:e:f:", long_options, NULL); if(c == -1) break; switch(c) { case -1: break; case 'q': g_quiet = true; break; case '?': usage(); break; case 'i': lua_init = optarg; break; case 'e': startup_cmds.push_back(std::make_pair(exec_cmd, std::string(optarg))); break; case 'f': startup_cmds.push_back(std::make_pair(exec_file, std::string(optarg))); break; default: abort(); } } // load register descriptions std::vector< soc_t > socs; for(int i = optind; i < argc; i++) { socs.push_back(soc_t()); if(!soc_desc_parse_xml(argv[i], socs[socs.size() - 1])) { printf("Cannot load description '%s'\n", argv[i]); return 2; } } // create usb context libusb_context *ctx; libusb_init(&ctx); libusb_set_debug(ctx, 3); // look for device if(!g_quiet) printf("Looking for hwstub device ...\n"); // open first device libusb_device **list; ssize_t cnt = hwstub_get_device_list(ctx, &list); if(cnt <= 0) { printf("No device found\n"); return 1; } libusb_device_handle *handle; if(libusb_open(list[0], &handle) != 0) { printf("Cannot open device\n"); return 1; } libusb_free_device_list(list, 1); // admin stuff libusb_device *mydev = libusb_get_device(handle); if(!g_quiet) { printf("device found at %d:%d\n", libusb_get_bus_number(mydev), libusb_get_device_address(mydev)); } g_hwdev = hwstub_open(handle); if(g_hwdev == NULL) { printf("Cannot open device!\n"); return 1; } // get hwstub information int ret = hwstub_get_desc(g_hwdev, HWSTUB_DT_VERSION, &g_hwdev_ver, sizeof(g_hwdev_ver)); if(ret != sizeof(g_hwdev_ver)) { printf("Cannot get version!\n"); goto Lerr; } if(g_hwdev_ver.bMajor != HWSTUB_VERSION_MAJOR || g_hwdev_ver.bMinor < HWSTUB_VERSION_MINOR) { printf("Warning: this tool is possibly incompatible with your device:\n"); printf("Device version: %d.%d.%d\n", g_hwdev_ver.bMajor, g_hwdev_ver.bMinor, g_hwdev_ver.bRevision); printf("Host version: %d.%d\n", HWSTUB_VERSION_MAJOR, HWSTUB_VERSION_MINOR); } // get memory layout information ret = hwstub_get_desc(g_hwdev, HWSTUB_DT_LAYOUT, &g_hwdev_layout, sizeof(g_hwdev_layout)); if(ret != sizeof(g_hwdev_layout)) { printf("Cannot get layout: %d\n", ret); goto Lerr; } // get target ret = hwstub_get_desc(g_hwdev, HWSTUB_DT_TARGET, &g_hwdev_target, sizeof(g_hwdev_target)); if(ret != sizeof(g_hwdev_target)) { printf("Cannot get target: %d\n", ret); goto Lerr; } // get STMP specific information if(g_hwdev_target.dID == HWSTUB_TARGET_STMP) { ret = hwstub_get_desc(g_hwdev, HWSTUB_DT_STMP, &g_hwdev_stmp, sizeof(g_hwdev_stmp)); if(ret != sizeof(g_hwdev_stmp)) { printf("Cannot get stmp: %d\n", ret); goto Lerr; } } // get PP specific information if(g_hwdev_target.dID == HWSTUB_TARGET_PP) { ret = hwstub_get_desc(g_hwdev, HWSTUB_DT_PP, &g_hwdev_pp, sizeof(g_hwdev_pp)); if(ret != sizeof(g_hwdev_pp)) { printf("Cannot get pp: %d\n", ret); goto Lerr; } } /** Init lua */ // create lua state g_lua = luaL_newstate(); if(g_lua == NULL) { printf("Cannot create lua state\n"); return 1; } // import hwstub if(!my_lua_import_hwstub()) printf("Cannot import hwstub description into Lua context\n"); // open all standard libraires luaL_openlibs(g_lua); // import socs if(!my_lua_import_soc(socs)) printf("Cannot import SoC descriptions into Lua context\n"); if(luaL_dofile(g_lua, lua_init)) printf("error in init: %s\n", lua_tostring(g_lua, -1)); lua_pop(g_lua, lua_gettop(g_lua)); /** start interactive mode */ if(!g_quiet) printf("Starting interactive lua session. Type 'help()' to get some help\n"); /** run startup commands */ for(size_t i = 0; i < startup_cmds.size(); i++) { bool ret = false; if(!g_quiet) printf("Running '%s'...\n", startup_cmds[i].second.c_str()); if(startup_cmds[i].first == exec_file) ret = luaL_dofile(g_lua, startup_cmds[i].second.c_str()); else if(startup_cmds[i].first == exec_cmd) ret = luaL_dostring(g_lua, startup_cmds[i].second.c_str()); if(ret) printf("error: %s\n", lua_tostring(g_lua, -1)); } // use readline to provide some history and completion rl_bind_key('\t', rl_complete); while(!g_exit) { char *input = readline("> "); if(!input) break; add_history(input); // evaluate string if(luaL_dostring(g_lua, input)) printf("error: %s\n", lua_tostring(g_lua, -1)); // pop everything to start from a clean stack lua_pop(g_lua, lua_gettop(g_lua)); free(input); } Lerr: // display log if handled if(!g_quiet) printf("Device log:\n"); print_log(g_hwdev); hwstub_release(g_hwdev); return 1; }
/////////////////////////////////////////////////////////////////////////////// ///@author Nicolae Bodislav ///@brief Reads data from the USB device on bulk. ///@param [out]p_pData - Buffer to store output data ///@param [in]p_nLegth - Size of the output buffer ///@param [in]p_nMiliSec - How much to wait for data before abandoning the read operation ///@retval size of the data written in the output buffer or < 0 for error /////////////////////////////////////////////////////////////////////////////// int CUSBLink::ReadBulk(unsigned char* p_pData, uint32_t p_nLegth, unsigned int p_nMiliSec /*= 10*/ ) { m_nCb = 0; m_nTrasferedLength = 0; if(m_pDevh == NULL) { NLOG_ERR("[CUSBLink][ReadBulk] Device not open."); return -1; } int rez = libusb_claim_interface(m_pDevh, 0); if (rez < 0) { NLOG_ERR("[CUSBLink][ReadBulk] Couldn't claim interface."); return -1; } m_enumDealoc = CUSBLink::INTERFACE; m_pData_transfer = NULL; m_pData_transfer = libusb_alloc_transfer(0); if (!m_pData_transfer) { NLOG_ERR("[CUSBLink][ReadBulk] Transfer couldn't be allocated."); return -ENOMEM; } m_pDev = libusb_get_device(m_pDevh); int max_packet_size = libusb_get_max_packet_size(m_pDev, m_cReadEndpoint); libusb_fill_bulk_transfer(m_pData_transfer, m_pDevh, m_cReadEndpoint, m_pData, max_packet_size, Cb_TransferRead, this, p_nMiliSec); m_enumDealoc = CUSBLink::TRANSFER; rez = libusb_submit_transfer(m_pData_transfer); if (rez < 0) { NLOG_ERR("[CUSBLink][ReadBulk] Transfer couldn't be submitted."); libusb_cancel_transfer(m_pData_transfer); m_enumDealoc = CUSBLink::INTERFACE; while (!m_nCb) { rez = libusb_handle_events(m_pContex); if (rez < 0) { break; } } libusb_free_transfer(m_pData_transfer); return -1; } while (!m_nCb) { rez = libusb_handle_events(m_pContex); if (rez < 0) { libusb_free_transfer(m_pData_transfer); return -1; } } if(m_bHaveData) { if(m_nTrasferedLength > 0) { memcpy(p_pData, m_pData, m_nTrasferedLength); if (m_bRawLog) { NLOG_DBG_HEX("[CUSBLink][ReadBulk] Received packet:", m_pData, m_nTrasferedLength); } } else p_pData = NULL; } return m_nTrasferedLength; }
int main(int argc, char **argv) { bool quiet = false; struct hwstub_device_t *hwdev; enum image_type_t type = IT_DETECT; // parse command line while(1) { static struct option long_options[] = { {"help", no_argument, 0, '?'}, {"quiet", no_argument, 0, 'q'}, {"type", required_argument, 0, 't'}, {0, 0, 0, 0} }; int c = getopt_long(argc, argv, "?qt:", long_options, NULL); if(c == -1) break; switch(c) { case -1: break; case 'q': quiet = true; break; case '?': usage(); break; case 't': if(strcmp(optarg, "raw") == 0) type = IT_RAW; else if(strcmp(optarg, "rockbox") == 0) type = IT_ROCKBOX; else if(strcmp(optarg, "detect") == 0) type = IT_DETECT; else { fprintf(stderr, "Unknown file type '%s'\n", optarg); return 1; } break; default: abort(); } } if(optind + 2 != argc) usage(); char *end; unsigned long addr = strtoul(argv[optind], &end, 0); if(*end) { fprintf(stderr, "Invalid load address\n"); return 2; } FILE *f = fopen(argv[optind + 1], "rb"); if(f == NULL) { fprintf(stderr, "Cannot open file for reading: %m\n"); return 3; } fseek(f, 0, SEEK_END); size_t size = ftell(f); fseek(f, 0, SEEK_SET); unsigned char *buffer = (unsigned char*)malloc(size); fread(buffer, size, 1, f); fclose(f); if(type == IT_ROCKBOX || type == IT_DETECT) { enum image_type_t det = detect_type(buffer, size); if(type == IT_ROCKBOX && det != IT_ROCKBOX) { if(!could_be_rockbox(buffer, size)) fprintf(stderr, "This file does not appear to be valid rockbox image.\n"); return 4; } if(type == IT_DETECT && det == IT_RAW) could_be_rockbox(buffer, size); type = det; if(type == IT_ROCKBOX) { if(!quiet) printf("Rockox image is for player %s (%.4s)\n", get_player_name(buffer + 4), buffer + 4); memmove(buffer, buffer + 8, size - 8); size -= 8; } } if(!quiet) { if(type == IT_RAW) printf("Loading raw image at %#lx\n", addr); else printf("Loading rockbox image at %#lx\n", addr); } // create usb context libusb_context *ctx; libusb_init(&ctx); libusb_set_debug(ctx, 3); // look for device if(!quiet) printf("Looking for device %#04x:%#04x...\n", HWSTUB_USB_VID, HWSTUB_USB_PID); libusb_device_handle *handle = libusb_open_device_with_vid_pid(ctx, HWSTUB_USB_VID, HWSTUB_USB_PID); if(handle == NULL) { fprintf(stderr, "No device found\n"); return 1; } // admin stuff libusb_device *mydev = libusb_get_device(handle); if(!quiet) { printf("device found at %d:%d\n", libusb_get_bus_number(mydev), libusb_get_device_address(mydev)); } hwdev = hwstub_open(handle); if(hwdev == NULL) { fprintf(stderr, "Cannot probe device!\n"); return 1; } // get hwstub information struct hwstub_version_desc_t hwdev_ver; int ret = hwstub_get_desc(hwdev, HWSTUB_DT_VERSION, &hwdev_ver, sizeof(hwdev_ver)); if(ret != sizeof(hwdev_ver)) { fprintf(stderr, "Cannot get version!\n"); goto Lerr; } if(hwdev_ver.bMajor != HWSTUB_VERSION_MAJOR || hwdev_ver.bMinor < HWSTUB_VERSION_MINOR) { printf("Warning: this tool is possibly incompatible with your device:\n"); printf("Device version: %d.%d.%d\n", hwdev_ver.bMajor, hwdev_ver.bMinor, hwdev_ver.bRevision); printf("Host version: %d.%d\n", HWSTUB_VERSION_MAJOR, HWSTUB_VERSION_MINOR); } ret = hwstub_rw_mem(hwdev, 0, addr, buffer, size); if(ret != (int)size) { fprintf(stderr, "Image write failed: %d\n", ret); goto Lerr; } hwstub_jump(hwdev, addr); hwstub_release(hwdev); return 0; Lerr: // display log if handled fprintf(stderr, "Device log:\n"); do { char buffer[128]; int length = hwstub_get_log(hwdev, buffer, sizeof(buffer) - 1); if(length <= 0) break; buffer[length] = 0; fprintf(stderr, "%s", buffer); }while(1); hwstub_release(hwdev); return 1; }
void Context::set_usb_device(struct libusb_device_handle *dev) { ftdi_set_usbdev(d->ftdi, dev); d->dev = libusb_get_device(dev); }
int main (int argc, char **argv) { int c; int rc; unsigned char rbuf[10000]; int n; char filename[1000]; time_t t; struct tm tm; char cmd[1000]; if (0) { print_bank1 (bank1ref, sizeof bank1ref); exit (0); } while ((c = getopt (argc, argv, "xv")) != EOF) { switch (c) { case 'v': vflag = 1; break; case 'x': xflag = 1; break; default: usage (); } } if (optind < argc) intarg = atoi (argv[optind++]); if (optind != argc) usage (); signal (SIGALRM, intr); alarm (14 * 60); t = time (NULL); tm = *localtime (&t); sprintf (filename, "fitbit-log-%04d-%02d-%02d-%02d%02d%02d", tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec); if (libusb_init (&ctx) != 0) { fprintf (stderr, "libusb_init error\n"); exit (1); } libusb_set_debug (ctx, 3); dev = libusb_open_device_with_vid_pid (ctx, 0x10c4, 0x84c4); device = libusb_get_device (dev); if ((rc = libusb_get_device_descriptor (device, &desc)) != 0) die ("get_desc", rc); if (0) { printf ("bLength = %d\n", desc.bLength); printf ("bDescriptorType = %d\n", desc.bDescriptorType); /* 0x110 = USB 1.1 */ printf ("bcdUSB = 0x%x\n", desc.bcdUSB); /* class = 0 means class per interface */ printf ("bDeviceClass = %d\n", desc.bDeviceClass); printf ("bDeviceSubClass = %d\n", desc.bDeviceSubClass); printf ("bDeviceProtocol = %d\n", desc.bDeviceProtocol); printf ("bMaxPacketSize0 = %d\n", desc.bMaxPacketSize0); printf ("idVendor = 0x%x\n", desc.idVendor); printf ("idProduct = 0x%x\n", desc.idProduct); printf ("bcdDevice = 0x%x\n", desc.bcdDevice); printf ("iManufacturer = %d\n", desc.iManufacturer); printf ("iProduct = %d\n", desc.iProduct); printf ("iSerialNumber = %d\n", desc.iSerialNumber); printf ("bNumConfigurations = %d\n", desc.bNumConfigurations); } if ((rc = libusb_set_configuration (dev, -1)) != 0) die ("set_config", rc); if ((rc = libusb_set_configuration (dev, 1)) != 0) die ("set_config", rc); if ((rc = libusb_claim_interface (dev, 0)) != 0) die ("claim", rc); // try_requests (); dbg ("*** fitbit_ant_init\n"); fitbit_ant_init (); init_tracker_for_transfer (); get_tracker_info (); if ((outf = fopen (filename, "w")) == NULL) { fprintf (stderr, "can't create %s\n", filename); exit (1); } fprintf (outf, "%s\n", filename); n = run_data_bank_opcode (0, rbuf, sizeof rbuf); print_bank0 (rbuf, n); output_bank (0, rbuf, n); n = run_data_bank_opcode (1, rbuf, sizeof rbuf); print_bank1 (rbuf, n); output_bank (1, rbuf, n); n = run_data_bank_opcode (2, rbuf, sizeof rbuf); print_bank2 (rbuf, n); output_bank (2, rbuf, n); dbg ("resetting\n"); if ((rc = libusb_reset_device (dev)) != 0) die ("libusb_reset_device", rc); fclose (outf); sprintf (cmd, "./parsedata %s", filename); dbg ("running: %s\n", cmd); rc = system (cmd); if (rc) dbg ("error: 0x%x\n", rc); dbg ("ok\n"); return (0); }
// Tests based on setting and getting device configuration. // This primarily tests the "Get Configuration" and "Set Configuration" // requests. static void configuration_tests(void) { libusb_device *device; int i; unsigned int config_value; int r; struct libusb_device_descriptor device_info; struct libusb_config_descriptor *config_info; uint8_t buffer[64]; device = libusb_get_device(device_handle); if (libusb_get_device_descriptor(device, &device_info) != 0) { printf("ERROR: Could not get device descriptor\n"); exit(1); } // Go through all configs of device. -1 = unconfigured. for (i = -1; i < device_info.bNumConfigurations; i++) { if (i == -1) { config_value = 0; } else { if (libusb_get_config_descriptor(device, (uint8_t)i, &config_info) != 0) { printf("ERROR: Could not get configuration descriptor\n"); exit(1); } config_value = config_info->bConfigurationValue; libusb_free_config_descriptor(config_info); } // Set the configuration to some value, then get it and check that the // obtained value matches what was set. r = libusb_control_transfer(device_handle, 0x00, LIBUSB_REQUEST_SET_CONFIGURATION, config_value, 0, buffer, 0, TIMEOUT); if (r < 0) { printf("Set configuration for config_value = %u failed\n", config_value); tests_failed++; } else { tests_succeeded++; } r = libusb_control_transfer(device_handle, 0x80, LIBUSB_REQUEST_GET_CONFIGURATION, 0, 0, buffer, 1, TIMEOUT); if (r < 0) { printf("Get configuration for config_value = %u failed\n", config_value); tests_failed++; } else { tests_succeeded++; } if (buffer[0] != config_value) { printf("Get configuration data doesn't match config_value %u\n", config_value); tests_failed++; } else { tests_succeeded++; } } // end for (i = -1; i < device_info.bNumConfigurations; i++) // Try some invalid configuration values. r = libusb_control_transfer(device_handle, 0x00, LIBUSB_REQUEST_SET_CONFIGURATION, 0xff, 0, buffer, 0, TIMEOUT); if (r >= 0) { printf("Set configuration for config_value = 0xff succeeded\n"); tests_failed++; } else { tests_succeeded++; } r = libusb_control_transfer(device_handle, 0x00, LIBUSB_REQUEST_SET_CONFIGURATION, 0xffff, 0, buffer, 0, TIMEOUT); if (r >= 0) { printf("Set configuration for config_value = 0xffff succeeded\n"); tests_failed++; } else { tests_succeeded++; } // Current configuration should be unchanged. r = libusb_control_transfer(device_handle, 0x80, LIBUSB_REQUEST_GET_CONFIGURATION, 0, 0, buffer, 1, TIMEOUT); if ((r < 0) || (buffer[0] != config_value)) { printf("Invalid set configuration messes with configuration\n"); tests_failed++; } else { tests_succeeded++; } }
/* Helper to open a libusb device that matches vid, pid, product string and/or serial string. * Set any field to 0 as a wildcard. If the device is found true is returned, with ctx containing * the already opened handle. ctx->interface must be set to the desired interface (channel) number * prior to calling this function. */ static bool open_matching_device(struct mpsse_ctx *ctx, const uint16_t *vid, const uint16_t *pid, const char *product, const char *serial) { libusb_device **list; struct libusb_device_descriptor desc; struct libusb_config_descriptor *config0; int err; bool found = false; ssize_t cnt = libusb_get_device_list(ctx->usb_ctx, &list); if (cnt < 0) LOG_ERROR("libusb_get_device_list() failed with %zi", cnt); for (ssize_t i = 0; i < cnt; i++) { libusb_device *device = list[i]; err = libusb_get_device_descriptor(device, &desc); if (err != LIBUSB_SUCCESS) { LOG_ERROR("libusb_get_device_descriptor() failed with %d", err); continue; } if (vid && *vid != desc.idVendor) continue; if (pid && *pid != desc.idProduct) continue; err = libusb_open(device, &ctx->usb_dev); if (err != LIBUSB_SUCCESS) { LOG_ERROR("libusb_open() failed with %d", err); continue; } if (product && !string_descriptor_equal(ctx->usb_dev, desc.iProduct, product)) { libusb_close(ctx->usb_dev); continue; } if (serial && !string_descriptor_equal(ctx->usb_dev, desc.iSerialNumber, serial)) { libusb_close(ctx->usb_dev); continue; } found = true; break; } libusb_free_device_list(list, 1); if (!found) { LOG_ERROR("no device found"); return false; } err = libusb_get_config_descriptor(libusb_get_device(ctx->usb_dev), 0, &config0); if (err != LIBUSB_SUCCESS) { LOG_ERROR("libusb_get_config_descriptor() failed with %d", err); libusb_close(ctx->usb_dev); return false; } /* Make sure the first configuration is selected */ int cfg; err = libusb_get_configuration(ctx->usb_dev, &cfg); if (err != LIBUSB_SUCCESS) { LOG_ERROR("libusb_get_configuration() failed with %d", err); goto error; } if (desc.bNumConfigurations > 0 && cfg != config0->bConfigurationValue) { err = libusb_set_configuration(ctx->usb_dev, config0->bConfigurationValue); if (err != LIBUSB_SUCCESS) { LOG_ERROR("libusb_set_configuration() failed with %d", err); goto error; } } /* Try to detach ftdi_sio kernel module */ err = libusb_detach_kernel_driver(ctx->usb_dev, ctx->interface); if (err != LIBUSB_SUCCESS && err != LIBUSB_ERROR_NOT_FOUND && err != LIBUSB_ERROR_NOT_SUPPORTED) { LOG_ERROR("libusb_detach_kernel_driver() failed with %d", err); goto error; } err = libusb_claim_interface(ctx->usb_dev, ctx->interface); if (err != LIBUSB_SUCCESS) { LOG_ERROR("libusb_claim_interface() failed with %d", err); goto error; } /* Reset FTDI device */ err = libusb_control_transfer(ctx->usb_dev, FTDI_DEVICE_OUT_REQTYPE, SIO_RESET_REQUEST, SIO_RESET_SIO, ctx->index, NULL, 0, ctx->usb_write_timeout); if (err < 0) { LOG_ERROR("failed to reset FTDI device: %d", err); goto error; } switch (desc.bcdDevice) { case 0x500: ctx->type = TYPE_FT2232C; break; case 0x700: ctx->type = TYPE_FT2232H; break; case 0x800: ctx->type = TYPE_FT4232H; break; case 0x900: ctx->type = TYPE_FT232H; break; default: LOG_ERROR("unsupported FTDI chip type: 0x%04x", desc.bcdDevice); goto error; } /* Determine maximum packet size and endpoint addresses */ if (!(desc.bNumConfigurations > 0 && ctx->interface < config0->bNumInterfaces && config0->interface[ctx->interface].num_altsetting > 0)) goto desc_error; const struct libusb_interface_descriptor *descriptor; descriptor = &config0->interface[ctx->interface].altsetting[0]; if (descriptor->bNumEndpoints != 2) goto desc_error; ctx->in_ep = 0; ctx->out_ep = 0; for (int i = 0; i < descriptor->bNumEndpoints; i++) { if (descriptor->endpoint[i].bEndpointAddress & 0x80) { ctx->in_ep = descriptor->endpoint[i].bEndpointAddress; ctx->max_packet_size = descriptor->endpoint[i].wMaxPacketSize; } else { ctx->out_ep = descriptor->endpoint[i].bEndpointAddress; } } if (ctx->in_ep == 0 || ctx->out_ep == 0) goto desc_error; libusb_free_config_descriptor(config0); return true; desc_error: LOG_ERROR("unrecognized USB device descriptor"); error: libusb_free_config_descriptor(config0); libusb_close(ctx->usb_dev); return false; }
int cyusb_get_busnumber(cyusb_handle *h) { cyusb_device *tdev = libusb_get_device(h); return libusb_get_bus_number( tdev ); }
int main(int argc, char *argv[]) { int result; libusb_context *ctx; libusb_device_handle *usb_device; unsigned char *txbuf; int size; int retcode; int last_serial = -1; FILE *fp1, *fp2, *fp; char def1_inst[] = "/usr/share/rpiboot/usbbootcode.bin"; char def2_inst[] = "/usr/share/rpiboot/msd.elf"; char def3_inst[] = "/usr/share/rpiboot/buildroot.elf"; char def1_loc[] = "./usbbootcode.bin"; char def2_loc[] = "./msd.elf"; char def3_loc[] = "./buildroot.elf"; char *def1, *def2, *def3; char *stage1 = NULL, *stage2 = NULL; char *fatimage = NULL, *executable = NULL; int loop = 0; // if local file version exists use it else use installed if( access( def1_loc, F_OK ) != -1 ) { def1 = def1_loc; } else { def1 = def1_inst; } if( access( def2_loc, F_OK ) != -1 ) { def2 = def2_loc; } else { def2 = def2_inst; } if( access( def3_loc, F_OK ) != -1 ) { def3 = def3_loc; } else { def3 = def3_inst; } stage1 = def1; stage2 = def2; struct MESSAGE_S { int length; unsigned char signature[20]; } message; #if defined (__CYGWIN__) //printf("Running under Cygwin\n"); #else //exit if not run as sudo if(getuid() != 0) { printf("Must be run with sudo...\n"); exit(-1); } #endif // Skip the command name argv++; argc--; while(*argv) { if(strcmp(*argv, "-b") == 0) { argv++; argc--; if(argc < 1) usage(1); stage1 = def1; stage2 = def3; fatimage = *argv; } else if(strcmp(*argv, "-h") == 0 || strcmp(*argv, "--help") == 0) { usage(0); } else if(strcmp(*argv, "-x") == 0) { argv++; argc--; executable = *argv; } else if(strcmp(*argv, "-l") == 0) { loop = 1; } else if(strcmp(*argv, "-v") == 0) { verbose = 1; } else { usage(1); } argv++; argc--; } fp1 = fopen(stage1, "rb"); if (fp1 == NULL) { printf("Cannot open file %s\n", stage1); exit(-1); } fp2 = fopen(stage2, "rb"); if (fp2 == NULL) { printf("Cannot open file %s\n", stage2); exit(-1); } if(strcmp(stage2 + strlen(stage2) - 4, ".elf")) { printf("Third stage needs to be .elf format\n"); exit(-1); } int ret = libusb_init(&ctx); if (ret) { printf("Failed to initialise libUSB\n"); exit(-1); } libusb_set_debug(ctx, 0); do { FILE *fp_img = NULL; struct libusb_device_descriptor desc; printf("Waiting for BCM2835 ...\n"); // Wait for a device to get plugged in do { result = Initialize_Device(&ctx, &usb_device); if(result == 0) { libusb_get_device_descriptor(libusb_get_device (usb_device), &desc); // Make sure we've re-enumerated since the last time if(desc.iSerialNumber == last_serial) { result = -1; libusb_close(usb_device); } } if (result) { usleep(100); } } while (result); last_serial = desc.iSerialNumber; printf("Found serial = %d: writing file %s\n", desc.iSerialNumber, desc.iSerialNumber == 0 ? stage1 : stage2); fp = desc.iSerialNumber == 0 ? fp1 : fp2; fseek(fp, 0, SEEK_END); message.length = ftell(fp); fseek(fp, 0, SEEK_SET); if(desc.iSerialNumber == 1 && fatimage != NULL) { // Been given a filesystem image fp_img = fopen(fatimage, "rb"); if(fp_img == NULL) { printf("Failed to open image %s\n", fatimage); exit(-1); } fseek(fp_img, 0, SEEK_END); message.length += ftell(fp_img); if(verbose) printf("Adding %ld bytes of binary to end of elf\n", ftell(fp_img)); fseek(fp_img, 0, SEEK_SET); } txbuf = (unsigned char *)malloc(message.length); if (txbuf == NULL) { printf("Failed to allocate memory\n"); exit(-1); } size = fread(txbuf, 1, message.length, fp); if(fp_img) { size += fread(txbuf + size, 1, message.length - size, fp_img); } size = ep_write((unsigned char *)&message, sizeof(message), usb_device); if (size != sizeof(message)) { printf("Failed to write correct length, returned %d\n", size); exit(-1); } if(verbose) printf("Writing %d bytes\n", message.length); size = ep_write(txbuf, message.length, usb_device); if (size != message.length) { printf("Failed to read correct length, returned %d\n", size); exit(-1); } size = ep_read((unsigned char *)&retcode, sizeof(retcode), usb_device); if (retcode == 0) { if(verbose) printf("Successful\n"); if(fp == fp2 && executable) { system(executable); } } else printf("Failed : 0x%x", retcode); libusb_close(usb_device); } while(fp == fp1 || loop); libusb_exit(ctx); return 0; }
int cyusb_get_max_iso_packet_size(cyusb_handle *h, unsigned char endpoint) { cyusb_device *tdev = libusb_get_device(h); return ( libusb_get_max_iso_packet_size(tdev, endpoint) ); }
static int scpi_usbtmc_libusb_open(struct sr_scpi_dev_inst *scpi) { struct scpi_usbtmc_libusb *uscpi = scpi->priv; struct sr_usb_dev_inst *usb = uscpi->usb; struct libusb_device *dev; struct libusb_device_descriptor des; struct libusb_config_descriptor *confdes; const struct libusb_interface_descriptor *intfdes; const struct libusb_endpoint_descriptor *ep; int confidx, intfidx, epidx, config = 0, current_config; uint8_t capabilities[24]; int ret, found = 0; int do_reset; if (usb->devhdl) return SR_OK; if (sr_usb_open(uscpi->ctx->libusb_ctx, usb) != SR_OK) return SR_ERR; dev = libusb_get_device(usb->devhdl); libusb_get_device_descriptor(dev, &des); for (confidx = 0; confidx < des.bNumConfigurations; confidx++) { if ((ret = libusb_get_config_descriptor(dev, confidx, &confdes)) < 0) { if (ret != LIBUSB_ERROR_NOT_FOUND) sr_dbg("Failed to get configuration descriptor: %s, " "ignoring device.", libusb_error_name(ret)); continue; } for (intfidx = 0; intfidx < confdes->bNumInterfaces; intfidx++) { intfdes = confdes->interface[intfidx].altsetting; if (intfdes->bInterfaceClass != LIBUSB_CLASS_APPLICATION || intfdes->bInterfaceSubClass != SUBCLASS_USBTMC || intfdes->bInterfaceProtocol != USBTMC_USB488) continue; uscpi->interface = intfdes->bInterfaceNumber; config = confdes->bConfigurationValue; sr_dbg("Interface %d configuration %d.", uscpi->interface, config); for (epidx = 0; epidx < intfdes->bNumEndpoints; epidx++) { ep = &intfdes->endpoint[epidx]; if (ep->bmAttributes == LIBUSB_TRANSFER_TYPE_BULK && !(ep->bEndpointAddress & (LIBUSB_ENDPOINT_DIR_MASK))) { uscpi->bulk_out_ep = ep->bEndpointAddress; sr_dbg("Bulk OUT EP %d", uscpi->bulk_out_ep); } if (ep->bmAttributes == LIBUSB_TRANSFER_TYPE_BULK && ep->bEndpointAddress & (LIBUSB_ENDPOINT_DIR_MASK)) { uscpi->bulk_in_ep = ep->bEndpointAddress; sr_dbg("Bulk IN EP %d", uscpi->bulk_in_ep & 0x7f); } if (ep->bmAttributes == LIBUSB_TRANSFER_TYPE_INTERRUPT && ep->bEndpointAddress & (LIBUSB_ENDPOINT_DIR_MASK)) { uscpi->interrupt_ep = ep->bEndpointAddress; sr_dbg("Interrupt EP %d", uscpi->interrupt_ep & 0x7f); } } found = 1; } libusb_free_config_descriptor(confdes); if (found) break; } if (!found) { sr_err("Failed to find USBTMC interface."); return SR_ERR; } if (libusb_kernel_driver_active(usb->devhdl, uscpi->interface) == 1) { if ((ret = libusb_detach_kernel_driver(usb->devhdl, uscpi->interface)) < 0) { sr_err("Failed to detach kernel driver: %s.", libusb_error_name(ret)); return SR_ERR; } uscpi->detached_kernel_driver = 1; } if (libusb_get_configuration(usb->devhdl, ¤t_config) == 0 && current_config != config) { if ((ret = libusb_set_configuration(usb->devhdl, config)) < 0) { sr_err("Failed to set configuration: %s.", libusb_error_name(ret)); return SR_ERR; } } if ((ret = libusb_claim_interface(usb->devhdl, uscpi->interface)) < 0) { sr_err("Failed to claim interface: %s.", libusb_error_name(ret)); return SR_ERR; } /* Optionally reset the USB device. */ do_reset = check_usbtmc_blacklist(whitelist_usb_reset, des.idVendor, des.idProduct); if (do_reset) libusb_reset_device(usb->devhdl); /* Get capabilities. */ ret = libusb_control_transfer(usb->devhdl, LIBUSB_ENDPOINT_IN | LIBUSB_REQUEST_TYPE_CLASS | LIBUSB_RECIPIENT_INTERFACE, GET_CAPABILITIES, 0, uscpi->interface, capabilities, sizeof(capabilities), TRANSFER_TIMEOUT); if (ret == sizeof(capabilities)) { uscpi->usbtmc_int_cap = capabilities[ 4]; uscpi->usbtmc_dev_cap = capabilities[ 5]; uscpi->usb488_dev_cap = capabilities[15]; } sr_dbg("Device capabilities: %s%s%s%s%s, %s, %s", uscpi->usb488_dev_cap & USB488_DEV_CAP_SCPI ? "SCPI, " : "", uscpi->usbtmc_dev_cap & USBTMC_DEV_CAP_TERMCHAR ? "TermChar, ": "", uscpi->usbtmc_int_cap & USBTMC_INT_CAP_LISTEN_ONLY ? "L3, " : uscpi->usbtmc_int_cap & USBTMC_INT_CAP_TALK_ONLY ? "" : "L4, ", uscpi->usbtmc_int_cap & USBTMC_INT_CAP_TALK_ONLY ? "T5, " : uscpi->usbtmc_int_cap & USBTMC_INT_CAP_LISTEN_ONLY ? "" : "T6, ", uscpi->usb488_dev_cap & USB488_DEV_CAP_SR1 ? "SR1" : "SR0", uscpi->usb488_dev_cap & USB488_DEV_CAP_RL1 ? "RL1" : "RL0", uscpi->usb488_dev_cap & USB488_DEV_CAP_DT1 ? "DT1" : "DT0"); scpi_usbtmc_remote(uscpi); return SR_OK; }