void *lothar_usb_new(uint16_t vendor, uint16_t product) { struct usb_bus *bus; usb_dev_handle *result = NULL; static int init = 0; static int interface = 0; if(!init) { usb_init(); usb_find_busses(); usb_find_devices(); init = 1; } for(bus = usb_get_busses(); bus; bus = bus->next) { struct usb_device *dev = NULL; for(dev = bus->devices; dev; dev = dev->next) { if(dev->descriptor.idVendor == vendor && dev->descriptor.idProduct == product) { result = usb_open(dev); break; } } if(result) // break out of nested loop break; } if(!result || usb_claim_interface(result, interface++)) // nothing found, or error claiming { LOTHAR_ERROR(LOTHAR_ERROR_USB_CANNOT_CREATE); return NULL; } return result; }
usb_dev_handle *dpf_usb_open(int index) { struct usb_device *d; usb_dev_handle *usb_dev; usb_init(); usb_find_busses(); usb_find_devices(); d = find_dev(index); if (!d) { handle_error("No matching USB device found!"); return NULL; } usb_dev = usb_open(d); if (usb_dev == NULL) { handle_error("Failed to open usb device!"); return NULL; } usb_claim_interface(usb_dev, 0); return usb_dev; }
int claim_interface(int num){ int claimed = -1; //do stuff claimed = usb_claim_interface(launcher, num); printf("Interface %d claimed with %d\n", num, claimed); //usb_detach_kernel_driver_np(launcher, 1); //usb_detach_kernel_driver_np(launcher, 0); printf("%d <= 0: %s\n", claimed, claimed <= 0); if (claimed <= 0) { printf("Preparing to release interface %d\n", num); usb_release_interface(launcher, num); printf("Couldn't claim interface %d \n", num); usb_close(launcher); return 1; } else if (claimed > 0){ printf("Claimed interface %d \n", num); } return 0; }
void process_device(int argc, char **argv, struct usb_device *dev, struct usb_config_descriptor *cfg, int itfnum) { int mac[6], have_mac=0; usb_dev_handle *devh = usb_open(dev); if ( ! devh ) fatal("usb_open"); usb_detach_kernel_driver_np(devh, itfnum); int res = usb_claim_interface(devh, itfnum); if ( res < 0 ) fatal("usb_claim_interface"); show_master(devh, itfnum); if ( argc >= 2 ) { if ( sscanf(argv[1], "%x:%x:%x:%x:%x:%x", &mac[0],&mac[1],&mac[2],&mac[3],&mac[4],&mac[5]) != 6 ) { printf("usage: %s [<bd_addr of master>]\n", argv[0]); exit(1); } } else { FILE *f = popen("hcitool dev", "r"); if ( !f || fscanf(f, "%*s\n%*s %x:%x:%x:%x:%x:%x", &mac[0],&mac[1],&mac[2],&mac[3],&mac[4],&mac[5]) != 6 ) { printf("Unable to retrieve local bd_addr from `hcitool dev`.\n"); printf("Please enable Bluetooth or specify an address manually.\n"); exit(1); } pclose(f); } set_master(devh, itfnum, mac); usb_close(devh); }
static int switch_babel(struct device_info *devinfo, int argc, char *argv[]) { char buf[3]; struct usb_dev_handle *udev; int err; memset(buf, 0, sizeof(buf)); buf[0] = 0x00; buf[1] = 0x06; buf[2] = 0x00; udev = usb_open(devinfo->dev); if (!udev) return -errno; if (usb_claim_interface(udev, 0) < 0) { err = -errno; usb_close(udev); return err; } err = usb_bulk_write(udev, 0x02, buf, sizeof(buf), 10000); if (err == 0) { err = -1; errno = EALREADY; } else { if (errno == ETIMEDOUT) err = 0; } usb_release_interface(udev, 0); usb_close(udev); return err; }
uint8_t open_usb(usb_dev_handle **handle) { uint16_t vid = USB_VID; uint16_t pid = USB_PID; char vendor[256]; char product[256]; struct usb_bus *bus; struct usb_device *dev; usb_dev_handle *target = NULL; usb_init(); usb_find_busses(); usb_find_devices(); for (bus=usb_get_busses(); bus; bus=bus->next) { for (dev=bus->devices; dev; dev=dev->next) { if (dev->descriptor.idVendor == vid && dev->descriptor.idProduct == pid) { target = usb_open(dev); if (target) { usb_get_string_simple(target, dev->descriptor.iManufacturer, vendor, sizeof(vendor)); usb_get_string_simple(target, dev->descriptor.iProduct, product, sizeof(product)); if (strcmp(vendor, V_NAME) == 0 && strcmp(product, P_NAME) == 0) { /* we found our device */ break; } } usb_close(target); target = NULL; } } } if (target != NULL) { usb_claim_interface(target, 0); *handle = target; return 1; } else { return 0; } }
VScope* openVScope() { unsigned char located = 0; struct usb_bus *bus; struct usb_device *dev; VScope *tmp = (VScope*)malloc(sizeof(VScope)); tmp->vscope_handle=0; //usb_set_debug(2); usb_init(); usb_find_busses(); usb_find_devices(); for (bus = usb_busses; bus; bus = bus->next) { for (dev = bus->devices; dev; dev = dev->next) { if (dev->descriptor.idVendor == 0x0400) { located++; tmp->vscope_handle = usb_open(dev); } } } if (tmp->vscope_handle==0) return (0); else { //printf("found\n"); usb_set_configuration(tmp->vscope_handle,1); usb_claim_interface(tmp->vscope_handle,0); usb_set_altinterface(tmp->vscope_handle,0); return (tmp); } }
/* * Under most circustances it's better to use listen_for_interrupts than use * this methods (just because it ensure that the device is closed when you're * done. But this starts a device listening, and from there you can use * next_interrupt to get the data. You must call interrupt_close if you call * interrupt_open */ VALUE endpoint_start_listening(VALUE self) { struct usb_endpoint_descriptor* e; Data_Get_Struct(self, struct usb_endpoint_descriptor, e); struct usb_interface_descriptor* interface; Data_Get_Struct(rb_iv_get(self,"@interface"), struct usb_interface_descriptor, interface); struct interrupt_result_list* list; if(rb_iv_get(self, "@result_list") == Qnil) { // this initializes the structure the thread will use to communicate list = malloc(sizeof(struct interrupt_result_list)); list->head = NULL; list->tail = NULL; pthread_mutex_init(&list->mutex, 0); rb_iv_set(self, "@result_list", Data_Wrap_Struct(rb_cObject, NULL, free_interrupt_list, list)); } else { Data_Get_Struct(rb_iv_get(self,"@result_list"), struct interrupt_result_list, list); } Data_Get_Struct(rb_iv_get(self,"@interface"), struct usb_interface_descriptor, interface); ENSURE_OPEN_BEGIN(rb_iv_get(self, "@device")); if(usb_claim_interface(handle, interface->bInterfaceNumber) < 0) { ENSURE_OPEN_END; raise_usb_error(); } pthread_t* thread1 = malloc(sizeof(pthread_t)); int ret; struct interrupt_thread_parameters* thread_params = malloc(sizeof(struct interrupt_thread_parameters)); thread_params->bEndpointAddress = e->bEndpointAddress; thread_params->wMaxPacketSize = e->wMaxPacketSize; thread_params->handle = handle; thread_params->list = list; ret = pthread_create(thread1, NULL, test_thread, thread_params); rb_iv_set(self, "@thread", Data_Wrap_Struct(rb_cObject, NULL, NULL, thread1)); rb_iv_set(rb_iv_get(self, "@interface"), "@claimed", Qtrue); return Qnil; }
static int drv_UL_open(void) { struct usb_bus *busses, *bus; struct usb_device *dev; lcd = NULL; info("%s: scanning for USBLCD...", Name); usb_set_debug(0); usb_init(); usb_find_busses(); usb_find_devices(); busses = usb_get_busses(); for (bus = busses; bus; bus = bus->next) { for (dev = bus->devices; dev; dev = dev->next) { if (((dev->descriptor.idVendor == USBLCD_VENDOR) || (dev->descriptor.idVendor == USBLCD_VENDOR2)) && (dev->descriptor.idProduct == USBLCD_DEVICE)) { unsigned int v = dev->descriptor.bcdDevice; info("%s: found USBLCD V%1d%1d.%1d%1d on bus %s device %s", Name, (v & 0xF000) >> 12, (v & 0xF00) >> 8, (v & 0xF0) >> 4, (v & 0xF), bus->dirname, dev->filename); interface = 0; lcd = usb_open(dev); if (usb_claim_interface(lcd, interface) < 0) { error("%s: usb_claim_interface() failed!", Name); error("%s: maybe you have the usblcd module loaded?", Name); return -1; } return 0; } } }
usb_dev_handle* OpenProxmark(int verbose) { int ret; usb_dev_handle *handle = NULL; unsigned int iface; handle = findProxmark(verbose, &iface); if (!handle) return NULL; #ifdef __linux__ /* detach kernel driver first */ ret = usb_detach_kernel_driver_np(handle, iface); /* don't complain if no driver attached */ if (ret<0 && ret != -61 && verbose) fprintf(stderr, "detach kernel driver failed: (%d) %s!\n", ret, usb_strerror()); #endif // Needed for Windows. Optional for Mac OS and Linux ret = usb_set_configuration(handle, 1); if (ret < 0) { if (verbose) fprintf(stderr, "configuration set failed: %s!\n", usb_strerror()); return NULL; } ret = usb_claim_interface(handle, iface); if (ret < 0) { if (verbose) fprintf(stderr, "claim failed: %s!\n", usb_strerror()); return NULL; } claimed_iface = iface; devh = handle; return handle; }
GenericUSBController::GenericUSBController(libusb_device* dev, int interface, int endpoint, bool try_detach) : USBController(dev), m_interface(interface), m_endpoint(endpoint) { struct libusb_config_descriptor* config; if (libusb_get_active_config_descriptor(dev, &config) != LIBUSB_SUCCESS) { raise_exception(std::runtime_error, "failed to get config descriptor"); } else { if (config->bNumInterfaces == 0) { raise_exception(std::runtime_error, "no interfaces available"); } if (config->interface[0].num_altsetting == 0) { raise_exception(std::runtime_error, "no interface descriptors available"); } if (config->interface[0].altsetting[0].bNumEndpoints <= m_endpoint) { raise_exception(std::runtime_error, "endpoint not available"); } uint16_t wMaxPacketSize = config->interface[0].altsetting[0].endpoint[m_endpoint].wMaxPacketSize; log_debug("wMaxPacketSize: " << wMaxPacketSize); usb_claim_interface(m_interface, try_detach); usb_submit_read(m_endpoint, wMaxPacketSize); } }
/* * Callback that is called by usb_device_open() that handles USB device * settings prior to accepting the devide. At the very least claim the * device here. Detaching the kernel driver will be handled by the * caller, don't do this here. Return < 0 on error, 0 or higher on * success. */ static int driver_callback(usb_dev_handle *handle, USBDevice_t *device) { if (usb_set_configuration(handle, 1) < 0) { upsdebugx(5, "Can't set USB configuration"); return -1; } if (usb_claim_interface(handle, 0) < 0) { upsdebugx(5, "Can't claim USB interface"); return -1; } if (usb_set_altinterface(handle, 0) < 0) { upsdebugx(5, "Can't set USB alternate interface"); return -1; } if (usb_clear_halt(handle, 0x81) < 0) { upsdebugx(5, "Can't reset USB endpoint"); return -1; } return 1; }
usb_dev_handle* setup_libusb_access() { usb_dev_handle *lvr_winusb; usb_set_debug(0); usb_init(); usb_find_busses(); usb_find_devices(); if(!(lvr_winusb = find_lvr_winusb())) { return NULL; } /* Linux*/ usb_detach_kernel_driver_np(lvr_winusb,0); if (usb_set_configuration(lvr_winusb, 1) < 0) { printf("Could not set configuration 1 : \n"); return NULL; } if (usb_claim_interface(lvr_winusb, INTFACE) < 0) { printf("Could not claim interface: \n"); return NULL; } return lvr_winusb; }
static int drv_TF_open(void) { struct usb_bus *busses, *bus; struct usb_device *dev; lcd = NULL; info("%s: scanning USB for TREFON LCD...", Name); usb_set_debug(0); usb_init(); usb_find_busses(); usb_find_devices(); busses = usb_get_busses(); for (bus = busses; bus; bus = bus->next) { for (dev = bus->devices; dev; dev = dev->next) { if ((dev->descriptor.idVendor == LCD_USB_VENDOR) && (dev->descriptor.idProduct == LCD_USB_DEVICE)) { info("%s: found TREFON USB LCD on bus %s device %s", Name, bus->dirname, dev->filename); lcd = usb_open(dev); if (usb_set_configuration(lcd, 1) < 0) { error("%s: usb_set_configuration() failed!", Name); return -1; } interface = 0; if (usb_claim_interface(lcd, interface) < 0) { error("%s: usb_claim_interface() failed!", Name); return -1; } return 0; } } } return -1; }
int _ykusb_write(void *dev, int report_type, int report_number, char *buffer, int size) { int rc = usb_claim_interface((usb_dev_handle *)dev, 0); if (rc >= 0) { int rc2; rc = usb_control_msg((usb_dev_handle *)dev, USB_TYPE_CLASS | USB_RECIP_INTERFACE | USB_ENDPOINT_OUT, HID_SET_REPORT, report_type << 8 | report_number, 0, buffer, size, 1000); /* preserve a control message error over an interface release one */ rc2 = usb_release_interface((usb_dev_handle *)dev, 0); if (rc >= 0 && rc2 < 0) rc = rc2; } if (rc >= 0) return 1; yk_errno = YK_EUSBERR; return 0; }
int xusb_claim_interface(struct xusb *xusb) { const struct usb_device_descriptor *dev_desc; int ret; assert(xusb); xusb_open(xusb); /* If it's not open yet... */ if(usb_claim_interface(xusb->handle, xusb->interface_num) != 0) { ERR("usb_claim_interface %d in '%s': %s\n", xusb->interface_num, xusb->devpath_tail, usb_strerror()); return 0; } xusb->is_claimed = 1; xusb_fill_strings(xusb); dev_desc = &xusb->dev->descriptor; DBG("ID=%04X:%04X Manufacturer=[%s] Product=[%s] SerialNumber=[%s] Interface=[%s]\n", dev_desc->idVendor, dev_desc->idProduct, xusb->iManufacturer, xusb->iProduct, xusb->iSerialNumber, xusb->iInterface); if(usb_clear_halt(xusb->handle, EP_OUT(xusb)) != 0) { ERR("Clearing output endpoint: %s\n", usb_strerror()); return 0; } if(usb_clear_halt(xusb->handle, EP_IN(xusb)) != 0) { ERR("Clearing input endpoint: %s\n", usb_strerror()); return 0; } if((ret = xusb_flushread(xusb)) < 0) { ERR("xusb_flushread failed: %d\n", ret); return 0; } return 1; }
struct simpleport* simpleport_open() { struct usb_bus *busses; struct usb_dev_handle* usb_handle; struct usb_bus *bus; struct usb_device *dev; struct simpleport * tmp; tmp = (struct simpleport*)malloc(sizeof(struct simpleport)); usb_init(); usb_find_busses(); usb_find_devices(); busses = usb_get_busses(); /* find simpleport device in usb bus */ for (bus = busses; bus; bus = bus->next){ for (dev = bus->devices; dev; dev = dev->next){ /* condition for sucessfully hit (too bad, I only check the vendor id)*/ if (dev->descriptor.idVendor == VID && dev->descriptor.idProduct == PID) { tmp->usb_handle = usb_open(dev); usb_set_configuration (tmp->usb_handle,dev->config[0].bConfigurationValue); usb_claim_interface(tmp->usb_handle, 0); usb_set_altinterface(tmp->usb_handle,0); return tmp; } } } return 0; }
nxt_error_t nxt_open(nxt_t *nxt) { char buf[2]; int ret; nxt->hdl = usb_open(nxt->dev); ret = usb_set_configuration(nxt->hdl, 1); if (ret < 0) { usb_close(nxt->hdl); return NXT_CONFIGURATION_ERROR; } ret = usb_claim_interface(nxt->hdl, 1); if (ret < 0) { usb_close(nxt->hdl); return NXT_IN_USE; } /* NXT handshake */ nxt_send_str(nxt, "N#"); nxt_recv_buf(nxt, buf, 2); if (memcmp(buf, "\n\r", 2) != 0) { usb_release_interface(nxt->hdl, 1); usb_close(nxt->hdl); return NXT_HANDSHAKE_FAILED; } return NXT_OK; }
int main(int argc, char *argv[]) { struct usb_bus *bus; struct usb_device *dev, *mydev; usb_dev_handle *handle; unsigned char bytes[64]; int ret; int i; for (ret = 0; ret < 64; ret++) { bytes[ret] = 0; } bytes[0] = 0; bytes[1] = 0; bytes[2] = 0; bytes[3] = 0; bytes[4] = 0; bytes[5] = 0; bytes[6] = 0x01; bytes[7] = 0xbb; usb_init(); usb_find_busses(); usb_find_devices(); for (bus = usb_busses; bus; bus = bus->next) { for (dev = bus->devices; dev; dev = dev->next) { if (dev->descriptor.idVendor == 0x1130 && dev->descriptor.idProduct == 0x6807) { printf("find my device\n"); mydev = dev; break; } } } handle = usb_open(mydev); printf("handle = %d\n", handle); //usb_get_driver_np(handle, 0, bytes, 64); //fprintf(stderr, "return usb_get_driver name is %s\n", bytes); #if 1 ret = usb_detach_kernel_driver_np(handle, 1); fprintf(stderr, "usb_detach_kernel_driver_np return %d\n", ret); ret = usb_claim_interface(handle, 1); printf("claim interface return %d\n", ret); #endif #if 1 ret = usb_detach_kernel_driver_np(handle, 0); fprintf(stderr, "return usb_detach_kernel_driver_np is %d\n", ret); ret = usb_claim_interface(handle, 0); printf("claim interface return %d\n", ret); #endif ret = usb_control_msg(handle, 0x21, 0x09, 0x0200, 1, bytes, 0x0008, 1000); printf("usb_control_msg return %d\n", ret); sleep(1); ret = usb_interrupt_read(handle, 3, bytes, 64, 1000); printf("usb_interrupt_read return %d\n", ret); for (i = 0; i < 64; i++) { printf("0x%02x ", bytes[i]); } printf("\n"); usb_release_interface(handle, 0); usb_release_interface(handle, 1); usb_close(handle); return 0; }
/** * API: Initialize glcd2usb connection type. */ int glcd2usb_init(Driver *drvthis) { PrivateData *p = (PrivateData *)drvthis->private_data; CT_glcd2usb_data *ctd; static int didUsbInit = 0; struct usb_bus *bus; struct usb_device *dev; usb_dev_handle *handle = NULL; int err = 0; int rval, retries = 3; int len; /* Set up connection type low-level functions */ p->glcd_functions->blit = glcd2usb_blit; p->glcd_functions->close = glcd2usb_close; p->glcd_functions->set_backlight = glcd2usb_backlight; p->glcd_functions->poll_keys = glcd2usb_poll_keys; /* Allocate memory structures */ ctd = (CT_glcd2usb_data *) calloc(1, sizeof(CT_glcd2usb_data)); if (ctd == NULL) { report(RPT_ERR, "%s/glcd2usb: error allocating connection data", drvthis->name); return -1; } p->ct_data = ctd; /* * Try to find and open a device. Only the first device found will be * recognized. */ if (!didUsbInit) { usb_init(); didUsbInit = 1; } usb_find_busses(); usb_find_devices(); for (bus = usb_get_busses(); bus != NULL; bus = bus->next) { for (dev = bus->devices; dev != NULL; dev = dev->next) { if (dev->descriptor.idVendor == GLCD2USB_VID && dev->descriptor.idProduct == GLCD2USB_PID) { handle = usb_open(dev); if (!handle) { report(RPT_WARNING, "%s/glcd2usb: cannot open USB device: %s", drvthis->name, usb_strerror()); continue; } else { goto found_dev; } } } } found_dev: if (handle) { debug(RPT_DEBUG, "%s/glcd2usb: opening device succeeded", drvthis->name); } else { report(RPT_ERR, "%s/glcd2usb: no GLCD2USB device found", drvthis->name); goto err_out; } if (usb_set_configuration(handle, 1)) report(RPT_WARNING, "%s/glcd2usb: could not set configuration: %s", drvthis->name, usb_strerror()); /* * now try to claim the interface and detach the kernel HID driver on * Linux and other operating systems which support the call. */ while ((rval = usb_claim_interface(handle, 0)) != 0 && retries-- > 0) { #ifdef LIBUSB_HAS_DETACH_KERNEL_DRIVER_NP if (usb_detach_kernel_driver_np(handle, 0) < 0) { report(RPT_WARNING, "%s/glcd2usb: could not detach kernel HID driver: %s", drvthis->name, usb_strerror()); } #endif } if (rval != 0) report(RPT_WARNING, "%s/glcd2usb: could not claim interface", drvthis->name); /* * Continue anyway, even if we could not claim the interface. Control * transfers should still work. */ ctd->device = handle; /* Query device */ memset(&(ctd->tx_buffer), 0, sizeof(ctd->tx_buffer)); len = sizeof(display_info_t); if ((err = usbGetReport(ctd->device, USB_HID_REPORT_TYPE_FEATURE, GLCD2USB_RID_GET_INFO, ctd->tx_buffer.bytes, &len)) != 0) { report(RPT_ERR, "%s/glcd2usb: query display parameters: %s", drvthis->name, usbErrorMessage(err)); goto err_out; } if (len < (int)sizeof(ctd->tx_buffer.display_info)) { report(RPT_ERR, "%s/glcd2usb: incomplete display info report (%d instead of %d)", drvthis->name, len, (int)sizeof(ctd->tx_buffer.display_info)); goto err_out; } if (!(ctd->tx_buffer.display_info.flags & FLAG_VERTICAL_UNITS)) { report(RPT_ERR, "%s/glcd2usb: unsupported display layout", drvthis->name); goto err_out; } if (ctd->tx_buffer.display_info.width > GLCD_MAX_WIDTH || ctd->tx_buffer.display_info.width <= 0 || ctd->tx_buffer.display_info.height > GLCD_MAX_HEIGHT || ctd->tx_buffer.display_info.height <= 0) { report(RPT_ERR, "%s/glcd2usb: display size out of range: %dx%d", drvthis->name, ctd->tx_buffer.display_info.width, ctd->tx_buffer.display_info.height); goto err_out; } p->framebuf.layout = FB_TYPE_VPAGED; p->framebuf.px_width = ctd->tx_buffer.display_info.width; p->framebuf.px_height = ctd->tx_buffer.display_info.height; p->framebuf.size = (p->framebuf.px_height + 7) / 8 * p->framebuf.px_width; report(RPT_INFO, "%s/glcd2usb: using display size %dx%d", drvthis->name, ctd->tx_buffer.display_info.width, ctd->tx_buffer.display_info.height); ctd->paged_buffer = malloc(p->framebuf.size); if (ctd->paged_buffer == NULL) { report(RPT_ERR, "%s/glcd2usb: cannot allocate memory", drvthis->name); goto err_out; } memset(ctd->paged_buffer, 0x55, p->framebuf.size); ctd->dirty_buffer = malloc(p->framebuf.size); if (ctd->dirty_buffer == NULL) { report(RPT_ERR, "%s/glcd2usb: cannot allocate memory", drvthis->name); goto err_out; } /* Allocate the display (turn off the 'whirl') */ ctd->tx_buffer.bytes[0] = GLCD2USB_RID_SET_ALLOC; ctd->tx_buffer.bytes[1] = 1; if ((err = usbSetReport(ctd->device, USB_HID_REPORT_TYPE_FEATURE, ctd->tx_buffer.bytes, 2)) != 0) { report(RPT_ERR, "%s/glcd2usb: Error allocating display: %s", drvthis->name, usbErrorMessage(err)); goto err_out; } return 0; err_out: glcd2usb_close(p); return -1; }
int pickit2_spi_init(void) { unsigned int usedevice = 0; // FIXME: allow to select one of multiple devices uint8_t buf[CMD_LENGTH] = { CMD_EXEC_SCRIPT, 10, /* Script length */ SCR_SET_PINS, 2, /* Bit-0=0(PDC Out), Bit-1=1(PGD In), Bit-2=0(PDC LL), Bit-3=0(PGD LL) */ SCR_SET_AUX, 0, /* Bit-0=0(Aux Out), Bit-1=0(Aux LL) */ SCR_VDD_ON, SCR_MCLR_GND_OFF, /* Let CS# float */ SCR_VPP_PWM_ON, SCR_VPP_ON, /* Pull CS# high */ SCR_BUSY_LED_ON, CMD_CLR_DLOAD_BUFF, CMD_CLR_ULOAD_BUFF, CMD_END_OF_BUFFER }; int spispeed_idx = 0; char *spispeed = extract_programmer_param("spispeed"); if (spispeed != NULL) { int i = 0; for (; spispeeds[i].name; i++) { if (strcasecmp(spispeeds[i].name, spispeed) == 0) { spispeed_idx = i; break; } } if (spispeeds[i].name == NULL) { msg_perr("Error: Invalid 'spispeed' value.\n"); free(spispeed); return 1; } free(spispeed); } int millivolt = 3500; char *voltage = extract_programmer_param("voltage"); if (voltage != NULL) { millivolt = parse_voltage(voltage); free(voltage); if (millivolt < 0) return 1; } /* Here comes the USB stuff */ usb_init(); (void)usb_find_busses(); (void)usb_find_devices(); struct usb_device *dev = get_device_by_vid_pid(PICKIT2_VID, PICKIT2_PID, usedevice); if (dev == NULL) { msg_perr("Could not find a PICkit2 on USB!\n"); return 1; } msg_pdbg("Found USB device (%04x:%04x).\n", dev->descriptor.idVendor, dev->descriptor.idProduct); pickit2_handle = usb_open(dev); int ret = usb_set_configuration(pickit2_handle, 1); if (ret != 0) { msg_perr("Could not set USB device configuration: %i %s\n", ret, usb_strerror()); if (usb_close(pickit2_handle) != 0) msg_perr("Could not close USB device!\n"); return 1; } ret = usb_claim_interface(pickit2_handle, 0); if (ret != 0) { msg_perr("Could not claim USB device interface %i: %i %s\n", 0, ret, usb_strerror()); if (usb_close(pickit2_handle) != 0) msg_perr("Could not close USB device!\n"); return 1; } if (register_shutdown(pickit2_shutdown, NULL) != 0) { return 1; } if (pickit2_get_firmware_version()) { return 1; } /* Command Set SPI Speed */ if (pickit2_set_spi_speed(spispeed_idx)) { return 1; } /* Command Set SPI Voltage */ msg_pdbg("Setting voltage to %i mV.\n", millivolt); if (pickit2_set_spi_voltage(millivolt) != 0) { return 1; } /* Perform basic setup. * Configure pin directions and logic levels, turn Vdd on, turn busy LED on and clear buffers. */ ret = usb_interrupt_write(pickit2_handle, ENDPOINT_OUT, (char *)buf, CMD_LENGTH, DFLT_TIMEOUT); if (ret != CMD_LENGTH) { msg_perr("Command Setup failed (%s)!\n", usb_strerror()); return 1; } register_spi_master(&spi_master_pickit2); return 0; }
int main(int argc, char **argv) { usb_dev_handle *handle = NULL; const unsigned char rawVid[2] = {USB_CFG_VENDOR_ID}, rawPid[2] = {USB_CFG_DEVICE_ID}; char vendor[] = "Atmel", product[] = "JTAGICE mkII"; char buffer[1000]; int cnt, vid, pid; usb_init(); /* compute VID/PID from usbconfig.h so that there is a central source of information */ vid = rawVid[1] * 256 + rawVid[0]; pid = rawPid[1] * 256 + rawPid[0]; /* The following function is in opendevice.c: */ if(usbOpenDevice(&handle, vid, vendor, pid, product, NULL, NULL, NULL) != 0) { fprintf(stderr, "Could not find USB device \"%s\" with vid=0x%x pid=0x%x\n", product, vid, pid); system("pause"); exit(1); } try{ usb_set_configuration(handle, 1); usb_claim_interface(handle, 0); int i, count=0, total=0; DWORD time = GetTickCount(); char send[] = "1234567890abcdef"; char recv[256]; //ComPort com; int res; for(i = 0; i < 1000; i++) { //if(!com.WriteBuffer(send, 16)) //{ // std::cout << "Com write error" << std::endl; //} std::cout << i << std::endl; res = usb_bulk_read(handle, 0x82, recv, 128, 500); if(res < 0) { std::cout << "bulk = " << res << std::endl << usb_strerror() << std::endl; } else { recv[res]=0; std::cout << "res = " << res << " \t" << recv << std::endl; total+=res; } //Sleep(100); } time = GetTickCount() - time; std::cout << "transfer compleate:\n"; std::cout << total << " bytes in " << (float)time/1000.f << "seconds" << std::endl; std::cout << (float)total/(float)time*1000.f << "bytes per second" << std::endl; } catch(std::exception &e) { std::cout << e.what()<< std::endl; } usb_close(handle); system("pause"); return 0; }
int main(int argc, char** argv) { struct BENCHMARK_TEST_PARAM Test; struct BENCHMARK_TRANSFER_PARAM* ReadTest = NULL; struct BENCHMARK_TRANSFER_PARAM* WriteTest = NULL; int key; if (argc == 1) { ShowHelp(); return -1; } ShowCopyright(); // NOTE: This is the log level for the benchmark application. // #if defined __ERROR_H__ usb_log_set_level(255); #endif SetTestDefaults(&Test); // Load the command line arguments. if (ParseBenchmarkArgs(&Test, argc, argv) < 0) return -1; // Initialize the critical section used for locking // the volatile members of the transfer params in order // to update/modify the running statistics. // InitializeCriticalSection(&DisplayCriticalSection); // Initialize the library. usb_init(); // Find all busses. usb_find_busses(); // Find all connected devices. usb_find_devices(); if (Test.UseList) { if (GetTestDeviceFromList(&Test) < 0) goto Done; } else { // Open a benchmark device. see Bench_Open(). Test.DeviceHandle = Bench_Open(Test.Vid, Test.Pid, Test.Intf, Test.Altf, &Test.Device); } if (!Test.DeviceHandle || !Test.Device) { CONERR("device %04X:%04X not found!\n",Test.Vid, Test.Pid); goto Done; } // If "NoTestSelect" appears in the command line then don't send the control // messages for selecting the test type. // if (!Test.NoTestSelect) { if (Bench_SetTestType(Test.DeviceHandle, Test.TestType, Test.Intf) != 1) { CONERR("setting bechmark test type #%d!\n%s\n", Test.TestType, usb_strerror()); goto Done; } } CONMSG("Benchmark device %04X:%04X opened..\n",Test.Vid, Test.Pid); // If reading from the device create the read transfer param. This will also create // a thread in a suspended state. // if (Test.TestType & TestTypeRead) { ReadTest = CreateTransferParam(&Test, Test.Ep | USB_ENDPOINT_DIR_MASK); if (!ReadTest) goto Done; } // If writing to the device create the write transfer param. This will also create // a thread in a suspended state. // if (Test.TestType & TestTypeWrite) { WriteTest = CreateTransferParam(&Test, Test.Ep); if (!WriteTest) goto Done; } // Set configuration #1. if (usb_set_configuration(Test.DeviceHandle, 1) < 0) { CONERR("setting configuration #%d!\n%s\n",1,usb_strerror()); goto Done; } // Claim_interface Test.Intf (Default is #0) if (usb_claim_interface(Test.DeviceHandle, Test.Intf) < 0) { CONERR("claiming interface #%d!\n%s\n", Test.Intf, usb_strerror()); goto Done; } // Set the alternate setting (Default is #0) if (usb_set_altinterface(Test.DeviceHandle, Test.Altf) < 0) { CONERR("selecting alternate setting #%d on interface #%d!\n%s\n", Test.Altf, Test.Intf, usb_strerror()); goto Done; } else { if (Test.Altf > 0) { CONDBG("selected alternate setting #%d on interface #%d\n",Test.Altf, Test.Intf); } } if (Test.Verify) { if (ReadTest && WriteTest) { if (CreateVerifyBuffer(&Test, WriteTest->Ep.wMaxPacketSize) < 0) goto Done; } else if (ReadTest) { if (CreateVerifyBuffer(&Test, ReadTest->Ep.wMaxPacketSize) < 0) goto Done; } } ShowTestInfo(&Test); ShowTransferInfo(ReadTest); ShowTransferInfo(WriteTest); CONMSG0("\nWhile the test is running:\n"); CONMSG0("Press 'Q' to quit\n"); CONMSG0("Press 'T' for test details\n"); CONMSG0("Press 'I' for status information\n"); CONMSG0("Press 'R' to reset averages\n"); CONMSG0("\nPress 'Q' to exit, any other key to begin.."); key = _getch(); CONMSG0("\n"); if (key=='Q' || key=='q') goto Done; // Set the thread priority and start it. if (ReadTest) { SetThreadPriority(ReadTest->ThreadHandle, Test.Priority); ResumeThread(ReadTest->ThreadHandle); } // Set the thread priority and start it. if (WriteTest) { SetThreadPriority(WriteTest->ThreadHandle, Test.Priority); ResumeThread(WriteTest->ThreadHandle); } while (!Test.IsCancelled) { Sleep(Test.Refresh); if (_kbhit()) { // A key was pressed. key = _getch(); switch (key) { case 'Q': case 'q': Test.IsUserAborted = TRUE; Test.IsCancelled = TRUE; break; case 'T': case 't': ShowTestInfo(&Test); break; case 'I': case 'i': // LOCK the display critical section EnterCriticalSection(&DisplayCriticalSection); // Print benchmark test details. ShowTransferInfo(ReadTest); ShowTransferInfo(WriteTest); // UNLOCK the display critical section LeaveCriticalSection(&DisplayCriticalSection); break; case 'R': case 'r': // LOCK the display critical section EnterCriticalSection(&DisplayCriticalSection); // Reset the running status. ResetRunningStatus(ReadTest); ResetRunningStatus(WriteTest); // UNLOCK the display critical section LeaveCriticalSection(&DisplayCriticalSection); break; } // Only one key at a time. while (_kbhit()) _getch(); } // If the read test should be running and it isn't, cancel the test. if ((ReadTest) && !ReadTest->IsRunning) { Test.IsCancelled = TRUE; break; } // If the write test should be running and it isn't, cancel the test. if ((WriteTest) && !WriteTest->IsRunning) { Test.IsCancelled = TRUE; break; } // Print benchmark stats if (ReadTest) ShowRunningStatus(ReadTest); else ShowRunningStatus(WriteTest); } // Wait for the transfer threads to complete gracefully if it // can be done in 10ms. All of the code from this point to // WaitForTestTransfer() is not required. It is here only to // improve response time when the test is cancelled. // Sleep(10); // If the thread is still running, abort and reset the endpoint. if ((ReadTest) && ReadTest->IsRunning) usb_resetep(Test.DeviceHandle, ReadTest->Ep.bEndpointAddress); // If the thread is still running, abort and reset the endpoint. if ((WriteTest) && WriteTest->IsRunning) usb_resetep(Test.DeviceHandle, WriteTest->Ep.bEndpointAddress); // Small delay incase usb_resetep() was called. Sleep(10); // WaitForTestTransfer will not return until the thread // has exited. WaitForTestTransfer(ReadTest); WaitForTestTransfer(WriteTest); // Print benchmark detailed stats ShowTestInfo(&Test); if (ReadTest) ShowTransferInfo(ReadTest); if (WriteTest) ShowTransferInfo(WriteTest); Done: if (Test.DeviceHandle) { usb_close(Test.DeviceHandle); Test.DeviceHandle = NULL; } if (Test.VerifyBuffer) { free(Test.VerifyBuffer); Test.VerifyBuffer = NULL; } FreeTransferParam(&ReadTest); FreeTransferParam(&WriteTest); DeleteCriticalSection(&DisplayCriticalSection); CONMSG0("Press any key to exit.."); _getch(); CONMSG0("\n"); return 0; }
int main(int argc, char **argv) { usb_dev_handle *handle = NULL; const unsigned char rawVid[2] = {USB_CFG_VENDOR_ID}, rawPid[2] = {USB_CFG_DEVICE_ID}; char vendor[] = {USB_CFG_VENDOR_NAME, 0}; char product[] = {USB_CFG_DEVICE_NAME, 0}; int cnt, vid, pid; usb_init(); if(argc < 1){ /* we need at least one argument */ usage("set-lcd"); exit(1); } else if (argc >= 2 && (strcmp(argv[1], "-h") == 0)) { usage(argv[0]); exit(0); } /* compute VID/PID from usbconfig.h so that there is a central source of information */ vid = rawVid[1] * 256 + rawVid[0]; pid = rawPid[1] * 256 + rawPid[0]; /* The following function is in opendevice.c: */ if(usbOpenDevice(&handle, vid, vendor, pid, product, NULL, NULL, NULL) != 0){ fprintf(stderr, "Could not find USB device \"%s\" with vid=0x%x pid=0x%x\n", product, vid, pid); exit(1); } /* Since we use only control endpoint 0, we don't need to choose a * configuration and interface. Reading device descriptor and setting a * configuration and interface is done through endpoint 0 after all. * However, newer versions of Linux require that we claim an interface * even for endpoint 0. Enable the following code if your operating system * needs it: */ #if 0 int retries = 1, usbConfiguration = 1, usbInterface = 0; if(usb_set_configuration(handle, usbConfiguration) && showWarnings){ fprintf(stderr, "Warning: could not set configuration: %s\n", usb_strerror()); } /* now try to claim the interface and detach the kernel HID driver on * Linux and other operating systems which support the call. */ while((len = usb_claim_interface(handle, usbInterface)) != 0 && retries-- > 0){ #ifdef LIBUSB_HAS_DETACH_KERNEL_DRIVER_NP if(usb_detach_kernel_driver_np(handle, 0) < 0 && showWarnings){ fprintf(stderr, "Warning: could not detach kernel driver: %s\n", usb_strerror()); } #endif } #endif if(argc > 1) { int size = getSizeOfDisplayArgs(argc, argv); char* allargs = malloc(size); buildConcatenatedDisplayArgString(allargs, argc, argv); fprintf(stderr, "Setting LCD text to: %s\n", allargs); cnt = usb_control_msg(handle, USB_TYPE_VENDOR | USB_RECIP_DEVICE | USB_ENDPOINT_OUT, CUSTOM_RQ_SHOW_MSG, size - 1, 0, allargs, size - 1, 5000); free(allargs); if(cnt < 0){ fprintf(stderr, "USB error: %s\n", usb_strerror()); } }else{ fprintf(stderr, "Clearing LCD\n"); cnt = usb_control_msg(handle, USB_TYPE_VENDOR | USB_RECIP_DEVICE | USB_ENDPOINT_OUT, CUSTOM_RQ_CLEAR, 0, 0, NULL, 0, 5000); if(cnt < 0){ fprintf(stderr, "USB error: %s\n", usb_strerror()); } } usb_close(handle); return 0; }
/// \brief Search for compatible devices. /// \return A string with the result of the search. QString Device::search() { if(this->error) return tr("Can't search for Hantek oscilloscopes: %1").arg(Helper::libUsbErrorString(this->error)); QString message; QString deviceAddress; int errorCode = LIBUSB_SUCCESS; #if LIBUSB_VERSION == 0 errorCode = usb_find_busses(); if(errorCode >= 0) errorCode = usb_find_devices(); if(errorCode < 0) return tr("Failed to get device list: %1").arg(Helper::libUsbErrorString(errorCode)); struct usb_device *device = NULL; // Iterate through all usb devices for(struct usb_bus *bus = usb_busses; bus; bus = bus->next) { for(device = bus->devices; device; device = device->next) { // Check VID and PID if(device->descriptor.idVendor == HANTEK_VENDOR_ID) { this->model = (Model) this->modelIds.indexOf(device->descriptor.idProduct); if(this->model >= 0) break; // Found a compatible device, ignore others } } if(this->model >= 0) { deviceAddress = QString("%1:%2").arg(bus->dirname).arg(device->filename); break; // Found a compatible device, ignore other busses } } if(this->model >= 0) { // Open device deviceAddress = QString("%1:%2").arg(device->bus->location, 3, 10, QLatin1Char('0')).arg(device->devnum, 3, 10, QLatin1Char('0')); this->handle = usb_open(device); if(this->handle) { struct usb_config_descriptor *configDescriptor = device->config; struct usb_interface *interface; struct usb_interface_descriptor *interfaceDescriptor; for(int interfaceIndex = 0; interfaceIndex < configDescriptor->bNumInterfaces; ++interfaceIndex) { interface = &configDescriptor->interface[interfaceIndex]; if(interface->num_altsetting < 1) continue; interfaceDescriptor = &interface->altsetting[0]; if(interfaceDescriptor->bInterfaceClass == USB_CLASS_VENDOR_SPEC && interfaceDescriptor->bInterfaceSubClass == 0 && interfaceDescriptor->bInterfaceProtocol == 0 && interfaceDescriptor->bNumEndpoints == 2) { // That's the interface we need, claim it errorCode = usb_claim_interface(this->handle, interfaceDescriptor->bInterfaceNumber); if(errorCode < 0) { usb_close(this->handle); this->handle = 0; message = tr("Failed to claim interface %1 of device %2: %3").arg(QString::number(interfaceDescriptor->bInterfaceNumber), deviceAddress, Helper::libUsbErrorString(errorCode)); } else { this->interface = interfaceDescriptor->bInterfaceNumber; // Check the maximum endpoint packet size usb_endpoint_descriptor *endpointDescriptor; this->outPacketLength = 0; this->inPacketLength = 0; for (int endpoint = 0; endpoint < interfaceDescriptor->bNumEndpoints; ++endpoint) { endpointDescriptor = &interfaceDescriptor->endpoint[endpoint]; switch(endpointDescriptor->bEndpointAddress) { case HANTEK_EP_OUT: this->outPacketLength = endpointDescriptor->wMaxPacketSize; break; case HANTEK_EP_IN: this->inPacketLength = endpointDescriptor->wMaxPacketSize; break; } } message = tr("Device found: Hantek %1 (%2)").arg(this->modelStrings[this->model], deviceAddress); emit connected(); } } } } else message = tr("Couldn't open device %1").arg(deviceAddress); } else message = tr("No Hantek oscilloscope found"); #else libusb_device **deviceList; libusb_device *device; if(this->handle) libusb_close(this->handle); ssize_t deviceCount = libusb_get_device_list(this->context, &deviceList); if(deviceCount < 0) return tr("Failed to get device list: %1").arg(Helper::libUsbErrorString(errorCode)); // Iterate through all usb devices this->model = MODEL_UNKNOWN; for(ssize_t deviceIterator = 0; deviceIterator < deviceCount; ++deviceIterator) { device = deviceList[deviceIterator]; // Get device descriptor if(libusb_get_device_descriptor(device, &(this->descriptor)) < 0) continue; // Check VID and PID if(this->descriptor.idVendor == HANTEK_VENDOR_ID) { this->model = (Model) this->modelIds.indexOf(this->descriptor.idProduct); if(this->model >= 0) break; // Found a compatible device, ignore others } } if(this->model >= 0) { // Open device deviceAddress = QString("%1:%2").arg(libusb_get_bus_number(device), 3, 10, QLatin1Char('0')).arg(libusb_get_device_address(device), 3, 10, QLatin1Char('0')); errorCode = libusb_open(device, &(this->handle)); if(errorCode == LIBUSB_SUCCESS) { libusb_config_descriptor *configDescriptor; const libusb_interface *interface; const libusb_interface_descriptor *interfaceDescriptor; // Search for the needed interface libusb_get_config_descriptor(device, 0, &configDescriptor); for(int interfaceIndex = 0; interfaceIndex < (int) configDescriptor->bNumInterfaces; ++interfaceIndex) { interface = &configDescriptor->interface[interfaceIndex]; if(interface->num_altsetting < 1) continue; interfaceDescriptor = &interface->altsetting[0]; if(interfaceDescriptor->bInterfaceClass == LIBUSB_CLASS_VENDOR_SPEC && interfaceDescriptor->bInterfaceSubClass == 0 && interfaceDescriptor->bInterfaceProtocol == 0 && interfaceDescriptor->bNumEndpoints == 2) { // That's the interface we need, claim it errorCode = libusb_claim_interface(this->handle, interfaceDescriptor->bInterfaceNumber); if(errorCode < 0) { libusb_close(this->handle); this->handle = 0; message = tr("Failed to claim interface %1 of device %2: %3").arg(QString::number(interfaceDescriptor->bInterfaceNumber), deviceAddress, Helper::libUsbErrorString(errorCode)); } else { this->interface = interfaceDescriptor->bInterfaceNumber; // Check the maximum endpoint packet size const libusb_endpoint_descriptor *endpointDescriptor; this->outPacketLength = 0; this->inPacketLength = 0; for (int endpoint = 0; endpoint < interfaceDescriptor->bNumEndpoints; ++endpoint) { endpointDescriptor = &(interfaceDescriptor->endpoint[endpoint]); switch(endpointDescriptor->bEndpointAddress) { case HANTEK_EP_OUT: this->outPacketLength = endpointDescriptor->wMaxPacketSize; break; case HANTEK_EP_IN: this->inPacketLength = endpointDescriptor->wMaxPacketSize; break; } } message = tr("Device found: Hantek %1 (%2)").arg(this->modelStrings[this->model], deviceAddress); emit connected(); } } } libusb_free_config_descriptor(configDescriptor); } else { this->handle = 0; message = tr("Couldn't open device %1: %2").arg(deviceAddress, Helper::libUsbErrorString(errorCode)); } } else message = tr("No Hantek oscilloscope found"); libusb_free_device_list(deviceList, true); #endif return message; }
/** * initialize hardware */ static NftResult _usb_init(void *privdata, const char *id) { Niftylino *n = privdata; struct usb_bus *bus; struct usb_device *dev; struct usb_dev_handle *h; /* save id */ strncpy(n->id, id, sizeof(n->id)); /* get our chain */ LedChain *chain = led_hardware_get_chain(n->hw); /* pixel-format of our chain */ LedPixelFormat *format = led_chain_get_format(chain); /* pixelformat supported? */ NiftylinoValueWidth vw; switch (led_pixel_format_get_bytes_per_pixel(format) / led_pixel_format_get_n_components(format)) { /* 8 bit values */ case 1: { vw = NIFTYLINO_8BIT_VALUES; break; } /* 16 bit values */ case 2: { vw = NIFTYLINO_16BIT_VALUES; break; } /* unsupported format */ default: { NFT_LOG(L_ERROR, "Unsupported format requested: %d bytes-per-pixel, %d components-per-pixel", led_pixel_format_get_bytes_per_pixel(format), led_pixel_format_get_n_components(format)); return NFT_FAILURE; } } /* find (new) busses */ usb_find_busses(); /* find (new) devices */ usb_find_devices(); /* open niftylino usb-device */ char serial[255]; /* walk all busses */ for(bus = usb_get_busses(); bus; bus = bus->next) { /* walk all devices on bus */ for(dev = bus->devices; dev; dev = dev->next) { /* found niftylino? */ if((dev->descriptor.idVendor != VENDOR_ID) || (dev->descriptor.idProduct != PRODUCT_ID)) { continue; } /* try to open */ if(!(h = usb_open(dev))) /* device allready open or other error */ continue; /* interface already claimed by driver? */ char driver[1024]; if(!(usb_get_driver_np(h, 0, driver, sizeof(driver)))) { // NFT_LOG(L_ERROR, "Device already claimed by // \"%s\"", driver); continue; } /* reset device */ usb_reset(h); usb_close(h); // ~ if(usb_reset(h) < 0) // ~ { // ~ /* reset failed */ // ~ usb_close(h); // ~ continue; // ~ } /* re-open */ if(!(h = usb_open(dev))) /* device allready open or other error */ continue; /* clear any previous halt status */ // usb_clear_halt(h, 0); /* claim interface */ if(usb_claim_interface(h, 0) < 0) { /* device claim failed */ usb_close(h); continue; } /* receive string-descriptor (serial number) */ if(usb_get_string_simple(h, 3, serial, sizeof(serial)) < 0) { usb_release_interface(h, 0); usb_close(h); continue; } /* device id == requested id? (or wildcard id * requested? */ if(strlen(n->id) == 0 || strncmp(n->id, serial, sizeof(serial)) == 0 || strncmp(n->id, "*", 1) == 0) { /* serial-number... */ strncpy(n->id, serial, sizeof(n->id)); /* usb device handle */ n->usb_handle = h; /* set format */ NFT_LOG(L_INFO, "Setting bitwidth to %d bit", (vw == NIFTYLINO_8BIT_VALUES ? 8 : 16)); if(!_set_format(privdata, vw)) { NFT_LOG(L_ERROR, "Failed to set greyscale format to %s.", vw == NIFTYLINO_8BIT_VALUES ? "u8" : "u16"); return NFT_FAILURE; } return NFT_SUCCESS; } /* close this adapter */ usb_release_interface(h, 0); usb_close(h); } } return NFT_FAILURE; }
static int read_one_sensor (struct usb_device *dev, uint16_t &value) { int ret; struct usb_dev_handle *devh; char driver_name[DRIVER_NAME_LEN] = ""; char usb_io_buf[USB_BUF_LEN] = "\x40\x68\x2a\x54" "\x52\x0a\x40\x40" "\x40\x40\x40\x40" "\x40\x40\x40\x40"; /* Open USB device. */ devh = usb_open (dev); if (! dev) { fprintf (stderr, "Failed to usb_open(%p)\n", (void *) dev); ret = -1; goto out; } /* Ensure that the device isn't claimed. */ ret = usb_get_driver_np (devh, 0/*intrf*/, driver_name, sizeof (driver_name)); if (! ret) { _log.Log(LOG_ERROR,"Voltcraft CO-20: Warning: device is claimed by driver %s, trying to unbind it.", driver_name); ret = usb_detach_kernel_driver_np (devh, 0/*intrf*/); if (ret) { _log.Log(LOG_ERROR,"Voltcraft CO-20: Warning: Failed to detatch kernel driver."); ret = -2; goto out; } } /* Claim device. */ ret = usb_claim_interface (devh, 0/*intrf*/); if (ret) { _log.Log(LOG_ERROR,"Voltcraft CO-20: usb_claim_interface() failed with error %d=%s", ret, strerror (-ret)); ret = -3; goto out; } /* Send query command. */ ret = usb_interrupt_write(devh, 0x0002/*endpoint*/, usb_io_buf, 0x10/*len*/, 1000/*msec*/); if (ret < 0) { _log.Log(LOG_ERROR,"Voltcraft CO-20: Failed to usb_interrupt_write() the initial buffer, ret = %d", ret); ret = -4; goto out_unlock; } /* Read answer. */ ret = usb_interrupt_read(devh, 0x0081/*endpoint*/, usb_io_buf, 0x10/*len*/, 1000/*msec*/); if (ret < 0) { _log.Log(LOG_ERROR,"Voltcraft CO-20: Failed to usb_interrupt_read() #1"); ret = -5; goto out_unlock; } /* On empty read, read again. */ if (ret == 0) { ret = usb_interrupt_read(devh, 0x0081/*endpoint*/, usb_io_buf, 0x10/*len*/, 1000/*msec*/); if (ret == 0) { //give up! goto out_unlock; } } /* Prepare value from first read. */ value = ((unsigned char *)usb_io_buf)[3] << 8 | ((unsigned char *)usb_io_buf)[2] << 0; /* Dummy read. */ usb_interrupt_read(devh, 0x0081/*endpoint*/, usb_io_buf, 0x10/*len*/, 1000/*msec*/); out_unlock: ret = usb_release_interface(devh, 0/*intrf*/); if (ret) { fprintf(stderr, "Failed to usb_release_interface()\n"); ret = -5; } out: if (devh) usb_close (devh); return ret; }
// rawhid_open - open 1 or more devices // // Inputs: // max = maximum number of devices to open // vid = Vendor ID, or -1 if any // pid = Product ID, or -1 if any // usage_page = top level usage page, or -1 if any // usage = top level usage number, or -1 if any // Output: // actual number of devices opened // int rawhid_open(int max, int vid, int pid, int usage_page, int usage) { struct usb_bus *bus; struct usb_device *dev; struct usb_interface *iface; struct usb_interface_descriptor *desc; struct usb_endpoint_descriptor *ep; usb_dev_handle *u; uint8_t buf[1024], *p; int i, n, len, tag, ep_in, ep_out, count=0, claimed; uint32_t val=0, parsed_usage, parsed_usage_page; hid_t *hid; if (first_hid) free_all_hid(); printf("rawhid_open, max=%d\n", max); if (max < 1) return 0; usb_init(); usb_find_busses(); usb_find_devices(); for (bus = usb_get_busses(); bus; bus = bus->next) { for (dev = bus->devices; dev; dev = dev->next) { if (vid > 0 && dev->descriptor.idVendor != vid) continue; if (pid > 0 && dev->descriptor.idProduct != pid) continue; if (!dev->config) continue; if (dev->config->bNumInterfaces < 1) continue; printf("device: vid=%04X, pic=%04X, with %d iface\n", dev->descriptor.idVendor, dev->descriptor.idProduct, dev->config->bNumInterfaces); iface = dev->config->interface; u = NULL; claimed = 0; for (i=0; i<dev->config->bNumInterfaces && iface; i++, iface++) { desc = iface->altsetting; if (!desc) continue; printf(" type %d, %d, %d\n", desc->bInterfaceClass, desc->bInterfaceSubClass, desc->bInterfaceProtocol); if (desc->bInterfaceClass != 3) continue; if (desc->bInterfaceSubClass != 0) continue; if (desc->bInterfaceProtocol != 0) continue; ep = desc->endpoint; ep_in = ep_out = 0; for (n = 0; n < desc->bNumEndpoints; n++, ep++) { if (ep->bEndpointAddress & 0x80) { if (!ep_in) ep_in = ep->bEndpointAddress & 0x7F; printf(" IN endpoint %d\n", ep_in); } else { if (!ep_out) ep_out = ep->bEndpointAddress; printf(" OUT endpoint %d\n", ep_out); } } if (!ep_in) continue; if (!u) { u = usb_open(dev); if (!u) { printf(" unable to open device\n"); break; } } printf(" hid interface (generic)\n"); if (usb_get_driver_np(u, i, (char *)buf, sizeof(buf)) >= 0) { printf(" in use by driver \"%s\"\n", buf); if (usb_detach_kernel_driver_np(u, i) < 0) { printf(" unable to detach from kernel\n"); continue; } } if (usb_claim_interface(u, i) < 0) { printf(" unable claim interface %d\n", i); continue; } len = usb_control_msg(u, 0x81, 6, 0x2200, i, (char *)buf, sizeof(buf), 250); printf(" descriptor, len=%d\n", len); if (len < 2) { usb_release_interface(u, i); continue; } p = buf; parsed_usage_page = parsed_usage = 0; while ((tag = hid_parse_item(&val, &p, buf + len)) >= 0) { printf(" tag: %X, val %X\n", tag, val); if (tag == 4) parsed_usage_page = val; if (tag == 8) parsed_usage = val; if (parsed_usage_page && parsed_usage) break; } if ((!parsed_usage_page) || (!parsed_usage) || (usage_page > 0 && parsed_usage_page != usage_page) || (usage > 0 && parsed_usage != usage)) { usb_release_interface(u, i); continue; } hid = (struct hid_struct *)malloc(sizeof(struct hid_struct)); if (!hid) { usb_release_interface(u, i); continue; } hid->usb = u; hid->iface = i; hid->ep_in = ep_in; hid->ep_out = ep_out; hid->open = 1; add_hid(hid); claimed++; count++; if (count >= max) return count; } if (u && !claimed) usb_close(u); } } return count; }
static int drv_MOGX_open(void) { struct usb_bus *busses, *bus; struct usb_device *dev; char driver[1024]; char product[1024]; char manufacturer[1024]; char serialnumber[1024]; int ret; lcd_dev = NULL; info("%s: scanning for Matrix Orbital GX Series LCD...", Name); usb_set_debug(0); usb_init(); usb_find_busses(); usb_find_devices(); busses = usb_get_busses(); for (bus = busses; bus; bus = bus->next) { for (dev = bus->devices; dev; dev = dev->next) { if ((dev->descriptor.idVendor == MatrixOrbitalGX_VENDOR) && ((dev->descriptor.idProduct == MatrixOrbitalGX_DEVICE_1) || (dev->descriptor.idProduct == MatrixOrbitalGX_DEVICE_2) || (dev->descriptor.idProduct == MatrixOrbitalGX_DEVICE_3))) { /* At the moment, I have information for only this LCD */ if (dev->descriptor.idProduct == MatrixOrbitalGX_DEVICE_2) backlight_RGB = 0; info("%s: found Matrix Orbital GX Series LCD on bus %s device %s", Name, bus->dirname, dev->filename); lcd_dev = usb_open(dev); ret = usb_get_driver_np(lcd_dev, 0, driver, sizeof(driver)); if (ret == 0) { info("%s: interface 0 already claimed by '%s'", Name, driver); info("%s: attempting to detach driver...", Name); if (usb_detach_kernel_driver_np(lcd_dev, 0) < 0) { error("%s: usb_detach_kernel_driver_np() failed!", Name); return -1; } } usb_set_configuration(lcd_dev, 1); usleep(100); if (usb_claim_interface(lcd_dev, 0) < 0) { error("%s: usb_claim_interface() failed!", Name); return -1; } usb_set_altinterface(lcd_dev, 0); usb_get_string_simple(lcd_dev, dev->descriptor.iProduct, product, sizeof(product)); usb_get_string_simple(lcd_dev, dev->descriptor.iManufacturer, manufacturer, sizeof(manufacturer)); usb_get_string_simple(lcd_dev, dev->descriptor.iSerialNumber, serialnumber, sizeof(serialnumber)); info("%s: Manufacturer='%s' Product='%s' SerialNumber='%s'", Name, manufacturer, product, serialnumber); return 0; } } } error("%s: could not find a Matrix Orbital GX Series LCD", Name); return -1; }
int main(int argc, char **argv) { usb_dev_handle *handle = NULL; const unsigned char rawVid[2] = {USB_CFG_VENDOR_ID}, rawPid[2] = {USB_CFG_DEVICE_ID}; char vendor[] = {USB_CFG_VENDOR_NAME, 0}, product[] = {USB_CFG_DEVICE_NAME, 0}; char buffer[4]; int cnt, vid, pid, isOn; usb_init(); if(argc < 2){ /* we need at least one argument */ usage(argv[0]); exit(1); } /* compute VID/PID from usbconfig.h so that there is a central source of information */ vid = rawVid[1] * 256 + rawVid[0]; pid = rawPid[1] * 256 + rawPid[0]; /* The following function is in opendevice.c: */ if(usbOpenDevice(&handle, vid, vendor, pid, product, NULL, NULL, NULL) != 0){ fprintf(stderr, "Could not find USB device \"%s\" with vid=0x%x pid=0x%x\n", product, vid, pid); exit(1); } /* Since we use only control endpoint 0, we don't need to choose a * configuration and interface. Reading device descriptor and setting a * configuration and interface is done through endpoint 0 after all. * However, newer versions of Linux require that we claim an interface * even for endpoint 0. Enable the following code if your operating system * needs it: */ #if 0 int retries = 1, usbConfiguration = 1, usbInterface = 0; if(usb_set_configuration(handle, usbConfiguration) && showWarnings){ fprintf(stderr, "Warning: could not set configuration: %s\n", usb_strerror()); } /* now try to claim the interface and detach the kernel HID driver on * Linux and other operating systems which support the call. */ while((len = usb_claim_interface(handle, usbInterface)) != 0 && retries-- > 0){ #ifdef LIBUSB_HAS_DETACH_KERNEL_DRIVER_NP if(usb_detach_kernel_driver_np(handle, 0) < 0 && showWarnings){ fprintf(stderr, "Warning: could not detach kernel driver: %s\n", usb_strerror()); } #endif } #endif if(strcasecmp(argv[1], "status") == 0){ cnt = usb_control_msg(handle, USB_TYPE_VENDOR | USB_RECIP_DEVICE | USB_ENDPOINT_IN, CUSTOM_RQ_GET_LED_STATUS, 0, 0, buffer, sizeof(buffer), 5000); if(cnt < 1){ if(cnt < 0){ fprintf(stderr, "USB error: %s\n", usb_strerror()); }else{ fprintf(stderr, "only %d bytes received.\n", cnt); } }else{ printf("LED is %s\n", buffer[0] ? "on" : "off"); } }else if((isOn = (strcasecmp(argv[1], "on") == 0)) || strcasecmp(argv[1], "off") == 0){ cnt = usb_control_msg(handle, USB_TYPE_VENDOR | USB_RECIP_DEVICE | USB_ENDPOINT_OUT, CUSTOM_RQ_SET_LED_STATUS, isOn, 0, buffer, 0, 5000); if(cnt < 0){ fprintf(stderr, "USB error: %s\n", usb_strerror()); } #if ENABLE_TEST }else if(strcasecmp(argv[1], "test") == 0){ int i; srandomdev(); for(i = 0; i < 50000; i++){ int value = random() & 0xffff, index = random() & 0xffff; int rxValue, rxIndex; if((i+1) % 100 == 0){ fprintf(stderr, "\r%05d", i+1); fflush(stderr); } cnt = usb_control_msg(handle, USB_TYPE_VENDOR | USB_RECIP_DEVICE | USB_ENDPOINT_IN, CUSTOM_RQ_LED_ECHO, value, index, buffer, sizeof(buffer), 5000); if(cnt < 0){ fprintf(stderr, "\nUSB error in iteration %d: %s\n", i, usb_strerror()); break; }else if(cnt != 4){ fprintf(stderr, "\nerror in iteration %d: %d bytes received instead of 4\n", i, cnt); break; } rxValue = ((int)buffer[0] & 0xff) | (((int)buffer[1] & 0xff) << 8); rxIndex = ((int)buffer[2] & 0xff) | (((int)buffer[3] & 0xff) << 8); if(rxValue != value || rxIndex != index){ fprintf(stderr, "\ndata error in iteration %d:\n", i); fprintf(stderr, "rxValue = 0x%04x value = 0x%04x\n", rxValue, value); fprintf(stderr, "rxIndex = 0x%04x index = 0x%04x\n", rxIndex, index); } } fprintf(stderr, "\nTest completed.\n"); #endif /* ENABLE_TEST */ }else{ usage(argv[0]); exit(1); } usb_close(handle); return 0; }