Esempio n. 1
0
usb_dev_handle * usb_open_device_with_vid_pid(void* context, unsigned short vid, unsigned short pid) {

	usb_find_busses();
	usb_find_devices();

	struct usb_bus *busses;
	busses = usb_get_busses();

  struct usb_bus *bus;
	for (bus = busses; bus; bus = bus->next) {
		struct usb_device *dev;

		for (dev = bus->devices; dev; dev = dev->next) {
			/* Check if this device is a printer */
			if ((dev->descriptor.idVendor == vid) && (dev->descriptor.idProduct == pid)) {
				/* Open the device, claim the interface and do your processing */
        return usb_open(dev);
			}

		}
	}

  return NULL;
}
Esempio n. 2
0
/*
 * The "baud" parameter is meaningless for USB devices, so we reuse it
 * to pass the desired USB device ID.
 */
static int usbdev_open(char * port, union pinfo pinfo, union filedescriptor *fd)
{
  char string[256];
  char product[256];
  struct usb_bus *bus;
  struct usb_device *dev;
  usb_dev_handle *udev;
  char *serno, *cp2;
  int i;
  int iface;
  size_t x;

  /*
   * The syntax for usb devices is defined as:
   *
   * -P usb[:serialnumber]
   *
   * See if we've got a serial number passed here.  The serial number
   * might contain colons which we remove below, and we compare it
   * right-to-left, so only the least significant nibbles need to be
   * specified.
   */
  if ((serno = strchr(port, ':')) != NULL)
    {
      /* first, drop all colons there if any */
      cp2 = ++serno;

      while ((cp2 = strchr(cp2, ':')) != NULL)
	{
	  x = strlen(cp2) - 1;
	  memmove(cp2, cp2 + 1, x);
	  cp2[x] = '\0';
	}

      if (strlen(serno) > 12)
	{
	  avrdude_message(MSG_INFO, "%s: usbdev_open(): invalid serial number \"%s\"\n",
                          progname, serno);
	  return -1;
	}
    }

  if (fd->usb.max_xfer == 0)
    fd->usb.max_xfer = USBDEV_MAX_XFER_MKII;

  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 == pinfo.usbinfo.vid &&
	      dev->descriptor.idProduct == pinfo.usbinfo.pid)
	    {
	      udev = usb_open(dev);
	      if (udev)
		{
		  /* yeah, we found something */
		  if (usb_get_string_simple(udev,
					    dev->descriptor.iSerialNumber,
					    string, sizeof(string)) < 0)
		    {
		      avrdude_message(MSG_INFO, "%s: usb_open(): cannot read serial number \"%s\"\n",
                                      progname, usb_strerror());
		      /*
		       * On some systems, libusb appears to have
		       * problems sending control messages.  Catch the
		       * benign case where the user did not request a
		       * particular serial number, so we could
		       * continue anyway.
		       */
		      if (serno != NULL)
			return -1; /* no chance */
		      else
			strcpy(string, "[unknown]");
		    }

		  if (usb_get_string_simple(udev,
					    dev->descriptor.iProduct,
					    product, sizeof(product)) < 0)
		    {
		      avrdude_message(MSG_INFO, "%s: usb_open(): cannot read product name \"%s\"\n",
                                      progname, usb_strerror());
		      strcpy(product, "[unnamed product]");
		    }
		  /*
		   * The CMSIS-DAP specification mandates the string
		   * "CMSIS-DAP" must be present somewhere in the
		   * product name string for a device compliant to
		   * that protocol.  Use this for the decisision
		   * whether we have to search for a HID interface
		   * below.
		   */
		  if(strstr(product, "CMSIS-DAP") != NULL)
		  {
		      pinfo.usbinfo.flags |= PINFO_FL_USEHID;
		      /* The JTAGICE3 running the CMSIS-DAP firmware doesn't
		       * use a separate endpoint for event reception. */
		      fd->usb.eep = 0;
		  }

		  if(strstr(product, "mEDBG") != NULL)
		  {
		      /* The AVR Xplained Mini uses different endpoints. */
		      fd->usb.rep = 0x81;
		      fd->usb.wep = 0x02;
		  }

                  avrdude_message(MSG_NOTICE, "%s: usbdev_open(): Found %s, serno: %s\n",
                                    progname, product, string);
		  if (serno != NULL)
		    {
		      /*
		       * See if the serial number requested by the
		       * user matches what we found, matching
		       * right-to-left.
		       */
		      x = strlen(string) - strlen(serno);
		      if (strcasecmp(string + x, serno) != 0)
			{
                          avrdude_message(MSG_DEBUG, "%s: usbdev_open(): serial number doesn't match\n",
                                            progname);
			  usb_close(udev);
			      continue;
			}
		    }

		  if (dev->config == NULL)
		    {
		      avrdude_message(MSG_INFO, "%s: usbdev_open(): USB device has no configuration\n",
                                      progname);
		      goto trynext;
		    }

		  if (usb_set_configuration(udev, dev->config[0].bConfigurationValue))
		    {
		      avrdude_message(MSG_INFO, "%s: usbdev_open(): WARNING: failed to set configuration %d: %s\n",
                                      progname, dev->config[0].bConfigurationValue,
                                      usb_strerror());
		      /* let's hope it has already been configured */
		      // goto trynext;
		    }

		  for (iface = 0; iface < dev->config[0].bNumInterfaces; iface++)
		    {
		      usb_interface = dev->config[0].interface[iface].altsetting[0].bInterfaceNumber;
#ifdef LIBUSB_HAS_GET_DRIVER_NP
		      /*
		       * Many Linux systems attach the usbhid driver
		       * by default to any HID-class device.  On
		       * those, the driver needs to be detached before
		       * we can claim the interface.
		       */
		      (void)usb_detach_kernel_driver_np(udev, usb_interface);
#endif
		      if (usb_claim_interface(udev, usb_interface))
			{
			  avrdude_message(MSG_INFO, "%s: usbdev_open(): error claiming interface %d: %s\n",
                                          progname, usb_interface, usb_strerror());
			}
		      else
			{
			  if (pinfo.usbinfo.flags & PINFO_FL_USEHID)
			    {
			      /* only consider an interface that is of class HID */
			      if (dev->config[0].interface[iface].altsetting[0].bInterfaceClass !=
				  USB_CLASS_HID)
				continue;
			      fd->usb.use_interrupt_xfer = 1;
			    }
			  break;
			}
		    }
		  if (iface == dev->config[0].bNumInterfaces)
		    {
		      avrdude_message(MSG_INFO, "%s: usbdev_open(): no usable interface found\n",
                                      progname);
		      goto trynext;
		    }

		  fd->usb.handle = udev;
		  if (fd->usb.rep == 0)
		    {
		      /* Try finding out what our read endpoint is. */
		      for (i = 0; i < dev->config[0].interface[iface].altsetting[0].bNumEndpoints; i++)
			{
			  int possible_ep = dev->config[0].interface[iface].altsetting[0].
			  endpoint[i].bEndpointAddress;

			  if ((possible_ep & USB_ENDPOINT_DIR_MASK) != 0)
			    {
                              avrdude_message(MSG_NOTICE2, "%s: usbdev_open(): using read endpoint 0x%02x\n",
                                                  progname, possible_ep);
			      fd->usb.rep = possible_ep;
			      break;
			    }
			}
		      if (fd->usb.rep == 0)
			{
			  avrdude_message(MSG_INFO, "%s: usbdev_open(): cannot find a read endpoint, using 0x%02x\n",
                                          progname, USBDEV_BULK_EP_READ_MKII);
			  fd->usb.rep = USBDEV_BULK_EP_READ_MKII;
			}
		    }
		  for (i = 0; i < dev->config[0].interface[iface].altsetting[0].bNumEndpoints; i++)
		    {
		      if ((dev->config[0].interface[iface].altsetting[0].endpoint[i].bEndpointAddress == fd->usb.rep ||
			   dev->config[0].interface[iface].altsetting[0].endpoint[i].bEndpointAddress == fd->usb.wep) &&
			  dev->config[0].interface[iface].altsetting[0].endpoint[i].wMaxPacketSize < fd->usb.max_xfer)
			{
                          avrdude_message(MSG_NOTICE, "%s: max packet size expected %d, but found %d due to EP 0x%02x's wMaxPacketSize\n",
                                            progname,
                                            fd->usb.max_xfer,
                                            dev->config[0].interface[iface].altsetting[0].endpoint[i].wMaxPacketSize,
                                            dev->config[0].interface[iface].altsetting[0].endpoint[i].bEndpointAddress);
			  fd->usb.max_xfer = dev->config[0].interface[iface].altsetting[0].endpoint[i].wMaxPacketSize;
			}
		    }
		  if (pinfo.usbinfo.flags & PINFO_FL_USEHID)
		    {
		      if (usb_control_msg(udev, 0x21, 0x0a /* SET_IDLE */, 0, 0, NULL, 0, 100) < 0)
			avrdude_message(MSG_INFO, "%s: usbdev_open(): SET_IDLE failed\n", progname);
		    }
		  return 0;
		  trynext:
		  usb_close(udev);
		}
	      else
		avrdude_message(MSG_INFO, "%s: usbdev_open(): cannot open device: %s\n",
                                progname, usb_strerror());
	    }
	}
    }

  if ((pinfo.usbinfo.flags & PINFO_FL_SILENT) == 0)
      avrdude_message(MSG_NOTICE, "%s: usbdev_open(): did not find any%s USB device \"%s\" (0x%04x:0x%04x)\n",
	      progname, serno? " (matching)": "", port,
	      (unsigned)pinfo.usbinfo.vid, (unsigned)pinfo.usbinfo.pid);
  return -1;
}
Esempio n. 3
0
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;
}
Esempio n. 4
0
File: test.c Progetto: axlrose/cells
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;
}
Esempio n. 5
0
static void HPRescanUsbBus(void)
{
	int i, j;
	struct usb_bus *bus;
	struct usb_device *dev;
	char bus_device[BUS_DEVICE_STRSIZE];

	usb_find_busses();
	usb_find_devices();

	for (i=0; i < PCSCLITE_MAX_READERS_CONTEXTS; i++)
		/* clear rollcall */
		readerTracker[i].status = READER_ABSENT;

	/* For each USB bus */
	for (bus = usb_get_busses(); bus; bus = bus->next)
	{
		/* For each USB device */
		for (dev = bus->devices; dev; dev = dev->next)
		{
			/* check if the device is supported by one driver */
			for (i=0; i<driverSize; i++)
			{
				if (driverTracker[i].libraryPath != NULL &&
					dev->descriptor.idVendor == driverTracker[i].manuID &&
					dev->descriptor.idProduct == driverTracker[i].productID)
				{
					int newreader;

					/* A known device has been found */
					snprintf(bus_device, BUS_DEVICE_STRSIZE, "%s:%s",
						bus->dirname, dev->filename);
					bus_device[BUS_DEVICE_STRSIZE - 1] = '\0';
#ifdef DEBUG_HOTPLUG
					Log2(PCSC_LOG_DEBUG, "Found matching USB device: %s",
						bus_device);
#endif
					newreader = TRUE;

					/* Check if the reader is a new one */
					for (j=0; j<PCSCLITE_MAX_READERS_CONTEXTS; j++)
					{
						if (strncmp(readerTracker[j].bus_device,
							bus_device, BUS_DEVICE_STRSIZE) == 0)
						{
							/* The reader is already known */
							readerTracker[j].status = READER_PRESENT;
							newreader = FALSE;
#ifdef DEBUG_HOTPLUG
							Log2(PCSC_LOG_DEBUG, "Refresh USB device: %s",
								bus_device);
#endif
							break;
						}
					}

					/* New reader found */
					if (newreader)
						HPAddHotPluggable(dev, bus_device, &driverTracker[i]);
				}
			}
		} /* End of USB device for..loop */

	} /* End of USB bus for..loop */

	/*
	 * check if all the previously found readers are still present
	 */
	for (i=0; i<PCSCLITE_MAX_READERS_CONTEXTS; i++)
	{
#if defined(__NetBSD__) || defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__DragonFly__)
		int fd;
		char filename[BUS_DEVICE_STRSIZE];

		/*	BSD workaround:
		 *	ugenopen() in sys/dev/usb/ugen.c returns EBUSY
		 *	when the character device file is already open.
		 *	Because of this, open usb devices will not be
		 *	detected by usb_find_devices(), so we have to
		 *	check for this explicitly.
		 */
		if (readerTracker[i].status == READER_PRESENT ||
			 readerTracker[i].fullName == NULL)
			continue;

		sscanf(readerTracker[i].bus_device, "%*[^:]%*[:]%s", filename);
		fd = open(filename, O_RDONLY);
		if (fd == -1)
		{
			if (errno == EBUSY)
			{
				/* The device is present */
#ifdef DEBUG_HOTPLUG
				Log2(PCSC_LOG_DEBUG, "BSD: EBUSY on %s", filename);
#endif
				readerTracker[i].status = READER_PRESENT;
			}
#ifdef DEBUG_HOTPLUG
			else
				Log3(PCSC_LOG_DEBUG, "BSD: %s error: %s", filename,
					strerror(errno));
#endif
		}
		else
		{
#ifdef DEBUG_HOTPLUG
			Log2(PCSC_LOG_DEBUG, "BSD: %s still present", filename);
#endif
			readerTracker[i].status = READER_PRESENT;
			close(fd);
		}
#endif
		if ((readerTracker[i].status == READER_ABSENT) &&
			(readerTracker[i].fullName != NULL))
			HPRemoveHotPluggable(i);
	}

	if (AraKiriHotPlug)
	{
		int retval;

		for (i=0; i<driverSize; i++)
		{
			/* free strings allocated by strdup() */
			free(driverTracker[i].bundleName);
			free(driverTracker[i].libraryPath);
			free(driverTracker[i].readerName);
		}
		free(driverTracker);

		Log1(PCSC_LOG_INFO, "Hotplug stopped");
		pthread_exit(&retval);
	}
}
/**
 * Initialize the driver.
 * \param drvthis  Pointer to driver structure.
 * \retval 0       Success.
 * \retval -1      Error.
 */
int
hd_init_lcd2usb(Driver *drvthis)
{
	PrivateData *p = (PrivateData *) drvthis->private_data;

	struct usb_bus *bus;

	p->hd44780_functions->senddata = lcd2usb_HD44780_senddata;
	p->hd44780_functions->backlight = lcd2usb_HD44780_backlight;
	p->hd44780_functions->scankeypad = lcd2usb_HD44780_scankeypad;
	p->hd44780_functions->close = lcd2usb_HD44780_close;
	p->hd44780_functions->set_contrast = lcd2usb_HD44780_set_contrast;
	p->hd44780_functions->flush = lcd2usb_HD44780_flush;

	/* try to find USB device */
#if 0
	usb_debug = 2;
#endif

	usb_init();
	usb_find_busses();
	usb_find_devices();

	p->usbHandle = NULL;
	for (bus = usb_get_busses(); bus != NULL; bus = bus->next) {
		struct usb_device *dev;

		for (dev = bus->devices; dev != NULL; dev = dev->next) {

			/* Check if this device is a LCD2USB device */
			if ((dev->descriptor.idVendor == LCD2USB_VENDORID) &&
			 (dev->descriptor.idProduct == LCD2USB_PRODUCTID)) {

				/*
				 * LCD2USB device found; try to find its
				 * description
				 */
				p->usbHandle = usb_open(dev);
				if (p->usbHandle == NULL) {
					report(RPT_WARNING, "hd_init_lcd2usb: unable to open device");
				}
				else {
					/* read firmware version */
					unsigned char buffer[2];

					if (usb_control_msg(p->usbHandle, USB_TYPE_VENDOR | USB_RECIP_DEVICE | USB_ENDPOINT_IN,
							    LCD2USB_GET_FWVER, 0, 0, (char *)buffer, sizeof(buffer), 1000) == 2)
						report(RPT_INFO, "hd_init_lcd2usb: device with firmware version %d.%02d found", buffer[0], buffer[1]);
				}
			}
		}
	}

	if (p->usbHandle != NULL) {
		debug(RPT_DEBUG, "hd_init_lcd2usb: opening device succeeded");
	}
	else {
		report(RPT_ERR, "hd_init_lcd2usb: no (matching) LCD2USB device found");
		return -1;
	}

	/* allocate and initialize send buffer */
	if ((p->tx_buf.buffer = malloc(LCD2USB_MAX_CMD)) == NULL) {
		report(RPT_ERR, "hd_init_lcd2usb: could not allocate send buffer");
		lcd2usb_HD44780_close(p);
		return -1;
	}
	p->tx_buf.type = -1;
	p->tx_buf.use_count = 0;

	common_init(p, IF_4BIT);

	/* replace uPause with empty one after initialization */
	p->hd44780_functions->uPause = lcd2usb_HD44780_uPause;

	return 0;
}
Esempio n. 7
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;
	}
static int usbOpenDevice(usb_dev_handle **device, int vendor,
			 char *vendorName, int product, char *productName)
{
struct usb_bus       *bus;
struct usb_device    *dev;
usb_dev_handle       *handle = NULL;
int                  errorCode = USB_ERROR_NOTFOUND;
static int           didUsbInit = 0;

    if(!didUsbInit){
        didUsbInit = 1;
        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 == vendor &&
	       dev->descriptor.idProduct == product){
                char    string[256];
                int     len;
		/* we need to open the device in order to query strings */
                handle = usb_open(dev);
                if(!handle){
                    errorCode = USB_ERROR_ACCESS;
                    fprintf(stderr,
			    "%s: Warning: cannot open USB device: %s\n",
			    progname, usb_strerror());
                    continue;
                }
                if(vendorName == NULL && productName == NULL){
		    /* name does not matter */
                    break;
                }
                /* now check whether the names match: */
                len = usb_get_string_simple(handle, dev->descriptor.iManufacturer,
					    string, sizeof(string));
                if(len < 0){
                    errorCode = USB_ERROR_IO;
                    fprintf(stderr,
			    "%s: Warning: cannot query manufacturer for device: %s\n",
			    progname, usb_strerror());
                }else{
                    errorCode = USB_ERROR_NOTFOUND;
		    if (verbose > 1)
		        fprintf(stderr,
				"%s: seen device from vendor ->%s<-\n",
				progname, string);
                    if(strcmp(string, vendorName) == 0){
                        len = usb_get_string_simple(handle, dev->descriptor.iProduct,
						    string, sizeof(string));
                        if(len < 0){
                            errorCode = USB_ERROR_IO;
                            fprintf(stderr,
				    "%s: Warning: cannot query product for device: %s\n",
				    progname, usb_strerror());
                        }else{
                            errorCode = USB_ERROR_NOTFOUND;
			    if (verbose > 1)
			        fprintf(stderr,
					"%s: seen product ->%s<-\n",
					progname, string);
                            if(strcmp(string, productName) == 0)
                                break;
                        }
                    }
                }
                usb_close(handle);
                handle = NULL;
            }
        }
        if(handle)
            break;
    }
    if(handle != NULL){
        errorCode = 0;
        *device = handle;
    }
    return errorCode;
}
Esempio n. 9
0
UsbDevice *
usbFindDevice (UsbDeviceChooser *chooser, UsbChooseChannelData *data) {
  UsbDevice *device = NULL;
  int result;

  {
    static int initialized = 0;
    if (!initialized) {
      usb_init();
      initialized = 1;
    }
  }

  if ((result = usb_find_busses()) >= 0) {
    if ((result = usb_find_devices()) >= 0) {
      struct usb_bus *bus = usb_get_busses();

      if (bus) {
        struct usb_bus *bus0 = bus;

        do {
          struct usb_device *dev = bus->devices;

          if (dev) {
            struct usb_device *dev0 = dev;

            do {
              UsbDeviceExtension *devx;

              if ((devx = malloc(sizeof(*devx)))) {
                if ((devx->handle = usb_open(dev))) {
                  if ((device = usbTestDevice(devx, chooser, data))) return device;

                  usb_close(devx->handle);
                } else {
                  logMessage(LOG_ERR, "USB open error: vendor=%X product=%X",
                             getLittleEndian16(dev->descriptor.idVendor),
                             getLittleEndian16(dev->descriptor.idProduct));
                }

                free(devx);
              } else {
                logSystemError("USB device extension allocate");
              }

              if ((dev = dev->next) == dev0) dev = NULL;
            } while (dev);
          }

          if ((bus = bus->next) == bus0) bus = NULL;
        } while (bus);
      }
    } else {
      errno = -result;
      logSystemError("USB devices find");
    }
  } else {
    errno = -result;
    logSystemError("USB busses find");
  }

  return device;
}
Esempio n. 10
0
/**
 * Initialize the driver.
 * \param drvthis  Pointer to driver structure.
 * \retval 0       Success.
 * \retval -1      Error.
 */
int
hd_init_bwct_usb(Driver *drvthis)
{
  PrivateData *p = (PrivateData*) drvthis->private_data;

  struct usb_bus *bus;
  //char device_manufacturer[LCD_MAX_WIDTH+1] = "";
  char device_serial[LCD_MAX_WIDTH+1] = DEFAULT_SERIALNO;
  char serial[LCD_MAX_WIDTH+1] = DEFAULT_SERIALNO;

  p->hd44780_functions->senddata = bwct_usb_HD44780_senddata;
  p->hd44780_functions->close = bwct_usb_HD44780_close;
  p->hd44780_functions->set_contrast = bwct_usb_HD44780_set_contrast;

  /* Read config file's contents: serial number and contrast */

  strncpy(serial, drvthis->config_get_string(drvthis->name, "SerialNumber",
                                             0, DEFAULT_SERIALNO), sizeof(serial));
  serial[sizeof(serial)-1] = '\0';
  if (*serial != '\0') {
    report(RPT_INFO, "hd_init_bwct_usb: Using serial number: %s", serial);
  }

  /* try to find USB device */
#if 0
  usb_debug = 2;
#endif

  usb_init();
  usb_find_busses();
  usb_find_devices();

  p->usbHandle = NULL;
  p->usbIndex = 0;
  for (bus = usb_get_busses(); bus != NULL; bus = bus->next) {
    struct usb_device *dev;

    for (dev = bus->devices; dev != NULL; dev = dev->next) {
      int c;

      /* Check if this device is a BWCT device */
      if (dev->descriptor.idVendor != BWCT_USB_VENDORID) {
        continue;
      }
      /* Loop through all of the configurations */
      for (c = 0; c < dev->descriptor.bNumConfigurations; c++) {
        /* Loop through all of the interfaces */
        for (p->usbIndex = 0; p->usbIndex < dev->config[c].bNumInterfaces; p->usbIndex++) {
          int a;

          /* Loop through all of the alternate settings */
          for (a = 0; a < dev->config[c].interface[p->usbIndex].num_altsetting; a++) {
            /* Check if this interface is a BWCT lcd */
            if (((dev->config[c].interface[p->usbIndex].altsetting[a].bInterfaceClass == 0xFF) &&
                 (dev->config[c].interface[p->usbIndex].altsetting[a].bInterfaceSubClass == 0x01)) ||
                (dev->descriptor.idProduct == BWCT_USB_PRODUCTID)) {

              /* BWCT device found; try to find its description and serial number */
              p->usbHandle = usb_open(dev);
              if (p->usbHandle == NULL) {
                report(RPT_WARNING, "hd_init_bwct_usb: unable to open device");
                // return -1;                /* it's better to continue */
              }
              else {
                /* get device information & check for serial number */
                //if (usb_get_string_simple(p->usbHandle, dev->descriptor.iManufacturer,
                //                          manufacturer, LCD_MAX_WIDTH) <= 0)
                //  *manufacturer = '\0';
                //manufacturer[sizeof(manufacturer)-1] = '\0';

                //if (usb_get_string_simple(p->usbHandle, dev->descriptor.iProduct,
                //                          product, LCD_MAX_WIDTH) <= 0)
                //  *product = '\0';
                //product[sizeof(product)-1] = '\0';

                if (usb_get_string_simple(p->usbHandle, dev->descriptor.iSerialNumber,
                                          device_serial, LCD_MAX_WIDTH) <= 0)
                  *device_serial = '\0';
                device_serial[sizeof(device_serial)-1] = '\0';
                if ((*serial != '\0') && (*device_serial == '\0')) {
                  report(RPT_ERR, "hd_init_bwct_usb: unable to get device's serial number");
                  usb_close(p->usbHandle);
                  return -1;
                }

                /* succeed if no serial was given in the config or the 2 numbers match */
                if ((*serial == '\0') || (strcmp(serial, device_serial) == 0))
                  goto done;

                usb_close(p->usbHandle);
                p->usbHandle = NULL;
              }
            }
          }
        }
      }
    }
  }

  done:
  if (p->usbHandle != NULL) {
    debug(RPT_DEBUG, "hd_init_bwct_usb: opening device succeeded");

    errno = 0;
    if (usb_set_configuration(p->usbHandle, p->usbIndex) < 0) {
      report(RPT_WARNING, "hd_init_bwct_usb: unable to set configuration: %s",
             strerror(errno));
    }

    errno = 0;
    if (usb_claim_interface(p->usbHandle, p->usbIndex) < 0) {
#if defined(LIBUSB_HAS_DETACH_KERNEL_DRIVER_NP)
      report(RPT_WARNING, "hd_init_bwct_usb: interface may be claimed by "
                          "kernel driver, attempting to detach it");

      errno = 0;
      if ((usb_detach_kernel_driver_np(p->usbHandle, p->usbIndex) < 0) ||
          (usb_claim_interface(p->usbHandle, p->usbIndex) < 0)) {
        report(RPT_ERR, "hd_init_bwct_usb: unable to re-claim interface: %s",
	       strerror(errno));
        usb_close(p->usbHandle);
        return -1;
      }
#else
      report(RPT_ERR, "hd_init_bwct_usb: unable to claim interface: %s",
             strerror(errno));
      usb_close(p->usbHandle);
      return -1;
#endif
    }
  }
  else {
    report(RPT_ERR, "hd_init_bwct_usb: no (matching) BWCT device found");
    return -1;
  }

  common_init(p, IF_4BIT);

  return 0;
}
Esempio n. 11
0
int UHandler::openDevice (usb_dev_handle **device, int vendor, char *vendorName, int product, char *productName)
{

	fprintf (stderr, "UHandler: opening device.\n");
struct usb_bus      *bus;  // busses
struct usb_device   *dev;  // devices
usb_dev_handle      *handle = NULL; // handle for detected device
int                 errorCode = USB_ERROR_NOTFOUND; // error code %)
static int          didUsbInit = 0; // just an initialization indicator 

    if(!didUsbInit){  
        didUsbInit = 1;
        usb_init();
    }
    usb_find_busses();
    usb_find_devices();
    for(bus=usb_get_busses(); bus; bus=bus->next){ // looking among all busses and devices
        for(dev=bus->devices; dev; dev=dev->next){
            if(dev->descriptor.idVendor == vendor && dev->descriptor.idProduct == product){ // if vendor and id are matching needed ones
                char    string[256];
                int     len;
                handle = usb_open(dev); /* we need to open the device in order to query strings */
                if(!handle){
                    errorCode = USB_ERROR_ACCESS;
                    fprintf(stderr, "Warning: cannot open USB device: %s\n", usb_strerror());
                    continue;
                }
                if(vendorName == NULL && productName == NULL){  /* name does not matter */
                    break;
                }
                /* now check whether the names match: */
                len = getString (handle, dev->descriptor.iManufacturer, 0x0409, string, sizeof(string));
                if(len < 0){
                    errorCode = USB_ERROR_IO;
                    fprintf(stderr, "Warning: cannot query manufacturer for device: %s\n", usb_strerror());
                }else{
                    errorCode = USB_ERROR_NOTFOUND;
                    fprintf(stderr, "seen device from vendor ->%s<-\n", string);
                    if(strcmp(string, vendorName) == 0){
                        len = getString (handle, dev->descriptor.iProduct, 0x0409, string, sizeof(string));
                        if(len < 0){
                            errorCode = USB_ERROR_IO;
                            fprintf(stderr, "Warning: cannot query product for device: %s\n", usb_strerror());
                        }else{
                            errorCode = USB_ERROR_NOTFOUND;
                            fprintf(stderr, "seen product ->%s<-\n", string);
                            if(strcmp(string, productName) == 0)
                                break;
                        }
                    }
                }
                usb_close(handle);
                handle = NULL;
            }
        }
        if(handle)
            break;
    }
    if(handle != NULL){
        errorCode = 0;
        *device = handle;
    }
    return errorCode;
}
Esempio n. 12
0
File: libusb.c Progetto: alfh/nut
/* On success, fill in the curDevice structure and return the report
 * descriptor length. On failure, return -1.
 * Note: When callback is not NULL, the report descriptor will be
 * passed to this function together with the udev and USBDevice_t
 * information. This callback should return a value > 0 if the device
 * is accepted, or < 1 if not. If it isn't accepted, the next device
 * (if any) will be tried, until there are no more devices left.
 */
static int libusb_open(usb_dev_handle **udevp, USBDevice_t *curDevice, USBDeviceMatcher_t *matcher,
	int (*callback)(usb_dev_handle *udev, USBDevice_t *hd, unsigned char *rdbuf, int rdlen))
{
#ifdef HAVE_USB_DETACH_KERNEL_DRIVER_NP
	int retries;
#endif
	int rdlen1, rdlen2; /* report descriptor length, method 1+2 */
	USBDeviceMatcher_t *m;
	struct usb_device *dev;
	struct usb_bus *bus;
	usb_dev_handle *udev;
	struct usb_interface_descriptor *iface;

	int ret, res;
	unsigned char buf[20];
	unsigned char *p;
	char string[256];
	int i;

	/* report descriptor */
	unsigned char	rdbuf[MAX_REPORT_SIZE];
	int		rdlen;

	/* libusb base init */
	usb_init();
	usb_find_busses();
	usb_find_devices();

#ifndef __linux__ /* SUN_LIBUSB (confirmed to work on Solaris and FreeBSD) */
	/* Causes a double free corruption in linux if device is detached! */
	libusb_close(*udevp);
#endif

	for (bus = usb_busses; bus; bus = bus->next) {
		for (dev = bus->devices; dev; dev = dev->next) {
			upsdebugx(2, "Checking device (%04X/%04X) (%s/%s)", dev->descriptor.idVendor,
				dev->descriptor.idProduct, bus->dirname, dev->filename);

			/* supported vendors are now checked by the
			   supplied matcher */

			/* open the device */
			*udevp = udev = usb_open(dev);
			if (!udev) {
				upsdebugx(2, "Failed to open device, skipping. (%s)", usb_strerror());
				continue;
			}

			/* collect the identifying information of this
			   device. Note that this is safe, because
			   there's no need to claim an interface for
			   this (and therefore we do not yet need to
			   detach any kernel drivers). */

			free(curDevice->Vendor);
			free(curDevice->Product);
			free(curDevice->Serial);
			free(curDevice->Bus);
			memset(curDevice, '\0', sizeof(*curDevice));

			curDevice->VendorID = dev->descriptor.idVendor;
			curDevice->ProductID = dev->descriptor.idProduct;
			curDevice->Bus = strdup(bus->dirname);

			if (dev->descriptor.iManufacturer) {
				ret = usb_get_string_simple(udev, dev->descriptor.iManufacturer,
					string, sizeof(string));
				if (ret > 0) {
					curDevice->Vendor = strdup(string);
				}
			}

			if (dev->descriptor.iProduct) {
				ret = usb_get_string_simple(udev, dev->descriptor.iProduct,
					string, sizeof(string));
				if (ret > 0) {
					curDevice->Product = strdup(string);
				}
			}

			if (dev->descriptor.iSerialNumber) {
				ret = usb_get_string_simple(udev, dev->descriptor.iSerialNumber,
					string, sizeof(string));
				if (ret > 0) {
					curDevice->Serial = strdup(string);
				}
			}

			upsdebugx(2, "- VendorID: %04x", curDevice->VendorID);
			upsdebugx(2, "- ProductID: %04x", curDevice->ProductID);
			upsdebugx(2, "- Manufacturer: %s", curDevice->Vendor ? curDevice->Vendor : "unknown");
			upsdebugx(2, "- Product: %s", curDevice->Product ? curDevice->Product : "unknown");
			upsdebugx(2, "- Serial Number: %s", curDevice->Serial ? curDevice->Serial : "unknown");
			upsdebugx(2, "- Bus: %s", curDevice->Bus ? curDevice->Bus : "unknown");

			upsdebugx(2, "Trying to match device");
			for (m = matcher; m; m=m->next) {
				ret = matches(m, curDevice);
				if (ret==0) {
					upsdebugx(2, "Device does not match - skipping");
					goto next_device;
				} else if (ret==-1) {
					fatal_with_errno(EXIT_FAILURE, "matcher");
					goto next_device;
				} else if (ret==-2) {
					upsdebugx(2, "matcher: unspecified error");
					goto next_device;
				}
			}
			upsdebugx(2, "Device matches");

			/* Now we have matched the device we wanted. Claim it. */

#ifdef HAVE_USB_DETACH_KERNEL_DRIVER_NP
			/* this method requires at least libusb 0.1.8:
			 * it force device claiming by unbinding
			 * attached driver... From libhid */
			retries = 3;
			while (usb_claim_interface(udev, 0) < 0) {

				upsdebugx(2, "failed to claim USB device: %s", usb_strerror());

				if (usb_detach_kernel_driver_np(udev, 0) < 0) {
					upsdebugx(2, "failed to detach kernel driver from USB device: %s", usb_strerror());
				} else {
					upsdebugx(2, "detached kernel driver from USB device...");
				}

				if (retries-- > 0) {
					continue;
				}

				fatalx(EXIT_FAILURE, "Can't claim USB device [%04x:%04x]: %s", curDevice->VendorID, curDevice->ProductID, usb_strerror());
			}
#else
			if (usb_claim_interface(udev, 0) < 0) {
				fatalx(EXIT_FAILURE, "Can't claim USB device [%04x:%04x]: %s", curDevice->VendorID, curDevice->ProductID, usb_strerror());
			}
#endif

			/* set default interface */
			usb_set_altinterface(udev, 0);

			if (!callback) {
				return 1;
			}

			if (!dev->config) { /* ?? this should never happen */
				upsdebugx(2, "  Couldn't retrieve descriptors");
				goto next_device;
			}

			rdlen1 = -1;
			rdlen2 = -1;

			/* Get HID descriptor */

			/* FIRST METHOD: ask for HID descriptor directly. */
			/* res = usb_get_descriptor(udev, USB_DT_HID, 0, buf, 0x9); */
			res = usb_control_msg(udev, USB_ENDPOINT_IN+1, USB_REQ_GET_DESCRIPTOR,
					      (USB_DT_HID << 8) + 0, 0, buf, 0x9, USB_TIMEOUT);

			if (res < 0) {
				upsdebugx(2, "Unable to get HID descriptor (%s)", usb_strerror());
			} else if (res < 9) {
				upsdebugx(2, "HID descriptor too short (expected %d, got %d)", 8, res);
			} else {

				upsdebug_hex(3, "HID descriptor, method 1", buf, 9);

				rdlen1 = buf[7] | (buf[8] << 8);
			}

			if (rdlen1 < -1) {
				upsdebugx(2, "Warning: HID descriptor, method 1 failed");
			}

			/* SECOND METHOD: find HID descriptor among "extra" bytes of
			   interface descriptor, i.e., bytes tucked onto the end of
			   descriptor 2. */

			/* Note: on some broken UPS's (e.g. Tripp Lite Smart1000LCD),
				only this second method gives the correct result */

			/* for now, we always assume configuration 0, interface 0,
			   altsetting 0, as above. */
			iface = &dev->config[0].interface[0].altsetting[0];
			for (i=0; i<iface->extralen; i+=iface->extra[i]) {
				upsdebugx(4, "i=%d, extra[i]=%02x, extra[i+1]=%02x", i,
					iface->extra[i], iface->extra[i+1]);
				if (i+9 <= iface->extralen && iface->extra[i] >= 9 && iface->extra[i+1] == 0x21) {
					p = &iface->extra[i];
					upsdebug_hex(3, "HID descriptor, method 2", p, 9);
					rdlen2 = p[7] | (p[8] << 8);
					break;
				}
			}

			if (rdlen2 < -1) {
				upsdebugx(2, "Warning: HID descriptor, method 2 failed");
			}

			/* when available, always choose the second value, as it
				seems to be more reliable (it is the one reported e.g. by
				lsusb). Note: if the need arises, can change this to use
				the maximum of the two values instead. */
			rdlen = rdlen2 >= 0 ? rdlen2 : rdlen1;

			if (rdlen < 0) {
				upsdebugx(2, "Unable to retrieve any HID descriptor");
				goto next_device;
			}
			if (rdlen1 >= 0 && rdlen2 >= 0 && rdlen1 != rdlen2) {
				upsdebugx(2, "Warning: two different HID descriptors retrieved (Reportlen = %d vs. %d)", rdlen1, rdlen2);
			}

			upsdebugx(2, "HID descriptor length %d", rdlen);

			if (rdlen > (int)sizeof(rdbuf)) {
				upsdebugx(2, "HID descriptor too long %d (max %d)", rdlen, (int)sizeof(rdbuf));
				goto next_device;
			}

			/* res = usb_get_descriptor(udev, USB_DT_REPORT, 0, bigbuf, rdlen); */
			res = usb_control_msg(udev, USB_ENDPOINT_IN+1, USB_REQ_GET_DESCRIPTOR,
				(USB_DT_REPORT << 8) + 0, 0, rdbuf, rdlen, USB_TIMEOUT);

			if (res < 0)
			{
				upsdebug_with_errno(2, "Unable to get Report descriptor");
				goto next_device;
			}

			if (res < rdlen)
			{
				upsdebugx(2, "Warning: report descriptor too short (expected %d, got %d)", rdlen, res);
				rdlen = res; /* correct rdlen if necessary */
			}

			res = callback(udev, curDevice, rdbuf, rdlen);
			if (res < 1) {
				upsdebugx(2, "Caller doesn't like this device");
				goto next_device;
			}

			upsdebugx(2, "Report descriptor retrieved (Reportlen = %d)", rdlen);
			upsdebugx(2, "Found HID device");
			fflush(stdout);

			return rdlen;

		next_device:
			usb_close(udev);
		}
	}

	*udevp = NULL;
	upsdebugx(2, "No appropriate HID device found");
	fflush(stdout);

	return -1;
}
Esempio n. 13
0
int musb_open(MUSB_INTERFACE **musb_interface, int vendor, int product, int instance, int configuration, int usbinterface)
{
#if defined(HAVE_LIBUSB)
   
   struct usb_bus *bus;
   struct usb_device *dev;
   int count = 0;
   
   usb_init();
   usb_find_busses();
   usb_find_devices();
   usb_set_debug(3);
   
   for (bus = usb_get_busses(); bus; bus = bus->next)
      for (dev = bus->devices; dev; dev = dev->next)
         if (dev->descriptor.idVendor == vendor && dev->descriptor.idProduct == product) {
            if (count == instance) {
               int status;
               usb_dev_handle *udev;

               udev = usb_open(dev);
               if (!udev) {
                  fprintf(stderr, "musb_open: usb_open() error\n");
                  return MUSB_ACCESS_ERROR;
               }

               status = usb_set_configuration(udev, configuration);
               if (status < 0) {
                  fprintf(stderr, "musb_open: usb_set_configuration() error %d (%s)\n", status,
                     strerror(-status));
                  fprintf(stderr,
                     "musb_open: Found USB device 0x%04x:0x%04x instance %d, but cannot initialize it: please check permissions on \"/proc/bus/usb/%s/%s\" and \"/dev/bus/usb/%s/%s\"\n",
                     vendor, product, instance, bus->dirname, dev->filename, bus->dirname, dev->filename);
                  return MUSB_ACCESS_ERROR;
               }

               /* see if we have write access */
               status = usb_claim_interface(udev, usbinterface);
               if (status < 0) {
                  fprintf(stderr, "musb_open: usb_claim_interface() error %d (%s)\n", status,
                     strerror(-status));

#ifdef _MSC_VER
                  fprintf(stderr,
                     "musb_open: Found USB device 0x%04x:0x%04x instance %d, but cannot initialize it:\nDevice is probably used by another program\n",
                     vendor, product, instance);
#else
                  fprintf(stderr,
                     "musb_open: Found USB device 0x%04x:0x%04x instance %d, but cannot initialize it: please check permissions on \"/proc/bus/usb/%s/%s\"\n",
                     vendor, product, instance, bus->dirname, dev->filename);
#endif

                  return MUSB_ACCESS_ERROR;
               }

               *musb_interface = (MUSB_INTERFACE*)calloc(1, sizeof(MUSB_INTERFACE));
               (*musb_interface)->dev = udev;
               (*musb_interface)->usb_configuration = configuration;
               (*musb_interface)->usb_interface     = usbinterface;
               return MUSB_SUCCESS;
            }

            count++;
         }
   
   return MUSB_NOT_FOUND;
   
#elif defined(HAVE_LIBUSB10)
   
   static int first_call = 1;

   libusb_device **dev_list;
   libusb_device_handle *dev;
   struct libusb_device_descriptor desc;
   
   int status, i, n;
   int count = 0;
   
   if (first_call) {
      first_call = 0;
      libusb_init(NULL);
      // libusb_set_debug(NULL, 3);
   }
      
   n = libusb_get_device_list(NULL, &dev_list);
   
   for (i=0 ; i<n ; i++) {
      status = libusb_get_device_descriptor(dev_list[i], &desc);
      if (desc.idVendor == vendor && desc.idProduct == product) {
         if (count == instance) {
            status = libusb_open(dev_list[i], &dev);
            if (status < 0) {
               fprintf(stderr, "musb_open: libusb_open() error %d\n", status);
               return MUSB_ACCESS_ERROR;
            }

            status = libusb_set_configuration(dev, configuration);
            if (status < 0) {
               fprintf(stderr, "musb_open: usb_set_configuration() error %d\n", status);
               fprintf(stderr,
                       "musb_open: Found USB device 0x%04x:0x%04x instance %d, but cannot initialize it: please check permissions on \"/proc/bus/usb/%d/%d\" and \"/dev/bus/usb/%d/%d\"\n",
                       vendor, product, instance, libusb_get_bus_number(dev_list[i]), libusb_get_device_address(dev_list[i]), libusb_get_bus_number(dev_list[i]), libusb_get_device_address(dev_list[i]));
               return MUSB_ACCESS_ERROR;
            }
            
            /* see if we have write access */
            status = libusb_claim_interface(dev, usbinterface);
            if (status < 0) {
               fprintf(stderr, "musb_open: libusb_claim_interface() error %d\n", status);
               
#ifdef _MSC_VER
               fprintf(stderr,
                       "musb_open: Found USB device 0x%04x:0x%04x instance %d, but cannot initialize it:\nDevice is probably used by another program\n",
                       vendor, product, instance);
#else
               fprintf(stderr,
                       "musb_open: Found USB device 0x%04x:0x%04x instance %d, but cannot initialize it: please check permissions on \"/proc/bus/usb/%d/%d\"\n",
                       vendor, product, instance, libusb_get_bus_number(dev_list[i]), libusb_get_device_address(dev_list[i]));
#endif
               
               return MUSB_ACCESS_ERROR;
            }

            *musb_interface = (MUSB_INTERFACE*)calloc(1, sizeof(MUSB_INTERFACE));
            (*musb_interface)->dev = dev;
            (*musb_interface)->usb_configuration = configuration;
            (*musb_interface)->usb_interface     = usbinterface;
            return MUSB_SUCCESS;

         }
         count++;
      }
   }
   
   libusb_free_device_list(dev_list, 1);
   
   return MUSB_NOT_FOUND;
     
#elif defined(OS_DARWIN)
   
   kern_return_t status;
   io_iterator_t iter;
   io_service_t service;
   IOCFPlugInInterface **plugin;
   SInt32 score;
   IOUSBDeviceInterface **device;
   UInt16 xvendor, xproduct;
   int count = 0;

   *musb_interface = calloc(1, sizeof(MUSB_INTERFACE));
   
   status = IORegistryCreateIterator(kIOMasterPortDefault, kIOUSBPlane, kIORegistryIterateRecursively, &iter);
   assert(status == kIOReturnSuccess);

   while ((service = IOIteratorNext(iter))) {
      status =
          IOCreatePlugInInterfaceForService(service, kIOUSBDeviceUserClientTypeID, kIOCFPlugInInterfaceID,
                                            &plugin, &score);
      assert(status == kIOReturnSuccess);

      status = IOObjectRelease(service);
      assert(status == kIOReturnSuccess);

      status =
          (*plugin)->QueryInterface(plugin, CFUUIDGetUUIDBytes(kIOUSBDeviceInterfaceID), (void *) &device);
      assert(status == kIOReturnSuccess);

      status = (*plugin)->Release(plugin);

      status = (*device)->GetDeviceVendor(device, &xvendor);
      assert(status == kIOReturnSuccess);
      status = (*device)->GetDeviceProduct(device, &xproduct);
      assert(status == kIOReturnSuccess);

      //fprintf(stderr, "musb_open: Found USB device: vendor 0x%04x, product 0x%04x\n", xvendor, xproduct);

      if (xvendor == vendor && xproduct == product) {
         if (count == instance) {

            fprintf(stderr, "musb_open: Found USB device: vendor 0x%04x, product 0x%04x, instance %d\n", xvendor, xproduct, instance);

            status = (*device)->USBDeviceOpen(device);
            fprintf(stderr, "musb_open: USBDeviceOpen status 0x%x\n", status);

            assert(status == kIOReturnSuccess);

            (*musb_interface)->usb_configuration = configuration;
            (*musb_interface)->usb_interface     = usbinterface;
            (*musb_interface)->device = (void*)device;
            (*musb_interface)->interface = NULL;

            status = darwin_configure_device(*musb_interface);

            if (status == kIOReturnSuccess)
               return MUSB_SUCCESS;

            fprintf(stderr, "musb_open: USB device exists, but configuration fails!");
            return MUSB_NOT_FOUND;
         }

         count++;
      }

      (*device)->Release(device);
   }

   return MUSB_NOT_FOUND;
#elif defined(_MSC_VER)
   GUID guid;
   HDEVINFO hDevInfoList;
   SP_DEVICE_INTERFACE_DATA deviceInfoData;
   PSP_DEVICE_INTERFACE_DETAIL_DATA functionClassDeviceData;
   ULONG predictedLength, requiredLength;
   int status;
   char device_name[256], str[256];

   *musb_interface = (MUSB_INTERFACE *)calloc(1, sizeof(MUSB_INTERFACE));

   guid = GUID_CLASS_MSCB_BULK;

   // Retrieve device list for GUID that has been specified.
   hDevInfoList = SetupDiGetClassDevs(&guid, NULL, NULL, (DIGCF_PRESENT | DIGCF_DEVICEINTERFACE));

   status = FALSE;
   if (hDevInfoList != NULL) {

      // Clear data structure
      memset(&deviceInfoData, 0, sizeof(deviceInfoData));
      deviceInfoData.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA);

      // retrieves a context structure for a device interface of a device information set.
      if (SetupDiEnumDeviceInterfaces(hDevInfoList, 0, &guid, instance, &deviceInfoData)) {
         // Must get the detailed information in two steps
         // First get the length of the detailed information and allocate the buffer
         // retrieves detailed information about a specified device interface.
         functionClassDeviceData = NULL;

         predictedLength = requiredLength = 0;

         SetupDiGetDeviceInterfaceDetail(hDevInfoList, &deviceInfoData, NULL,   // Not yet allocated
                                         0,     // Set output buffer length to zero
                                         &requiredLength,       // Find out memory requirement
                                         NULL);

         predictedLength = requiredLength;
         functionClassDeviceData = (PSP_DEVICE_INTERFACE_DETAIL_DATA) malloc(predictedLength);
         functionClassDeviceData->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA);

         // Second, get the detailed information
         if (SetupDiGetDeviceInterfaceDetail(hDevInfoList,
                                             &deviceInfoData, functionClassDeviceData,
                                             predictedLength, &requiredLength, NULL)) {

            // Save the device name for subsequent pipe open calls
            strcpy(device_name, functionClassDeviceData->DevicePath);
            free(functionClassDeviceData);

            // Signal device found
            status = TRUE;
         } else
            free(functionClassDeviceData);
      }
   }
   // SetupDiDestroyDeviceInfoList() destroys a device information set
   // and frees all associated memory.
   SetupDiDestroyDeviceInfoList(hDevInfoList);

   if (status) {

      // Get the read handle
      sprintf(str, "%s\\PIPE00", device_name);
      (*musb_interface)->rhandle = CreateFile(str,
                                    GENERIC_WRITE | GENERIC_READ,
                                    FILE_SHARE_WRITE | FILE_SHARE_READ, NULL,
                                    OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL);

      if ((*musb_interface)->rhandle == INVALID_HANDLE_VALUE)
         return MUSB_ACCESS_ERROR;

      // Get the write handle
      sprintf(str, "%s\\PIPE01", device_name);
      (*musb_interface)->whandle = CreateFile(str,
                                    GENERIC_WRITE | GENERIC_READ,
                                    FILE_SHARE_WRITE | FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);

      if ((*musb_interface)->whandle == INVALID_HANDLE_VALUE)
         return MUSB_ACCESS_ERROR;

      return MUSB_SUCCESS;
   } 
     
   return MUSB_NOT_FOUND;
#endif
}
Esempio n. 14
0
usb_dev_handle* findProxmark(int verbose, unsigned int *iface)
{
  struct usb_bus *busses, *bus;
  usb_dev_handle *handle = NULL;
  struct prox_unit units[50];
  int iUnit = 0;

  usb_find_busses();
  usb_find_devices();

  busses = usb_get_busses();

  for (bus = busses; bus; bus = bus->next) {
    struct usb_device *dev;
    
    for (dev = bus->devices; dev; dev = dev->next) {
      struct usb_device_descriptor *desc = &(dev->descriptor);

      if ((desc->idProduct == 0x4b8f) && (desc->idVendor == 0x9ac4)) {
        handle = usb_open(dev);
        if (!handle) {
          if (verbose)
            fprintf(stderr, "open fabiled: %s!\n", usb_strerror());
          //return NULL;
          continue;
        }
        *iface = dev->config[0].interface[0].altsetting[0].bInterfaceNumber;

        struct prox_unit unit = {handle, {0}};
        usb_get_string_simple(handle, desc->iSerialNumber, unit.serial_number, sizeof(unit.serial_number));
        units[iUnit++] = unit;

        //return handle;
      }
    }
  }

  if (iUnit > 0) {
    int iSelection = 0;

    fprintf(stdout, "\nConnected units:\n");

    for (int i = 0; i < iUnit; i++) {
      struct usb_device * dev = usb_device(units[i].handle);
      fprintf(stdout, "\t%d. SN: %s [%s/%s]\n", i+1, units[i].serial_number, dev->bus->dirname, dev->filename);
    }
    if (iUnit > 1) {
      while (iSelection < 1 || iSelection > iUnit) {
        fprintf(stdout, "Which unit do you want to connect to? ");
        fscanf(stdin, "%d", &iSelection);
        }
      }
    else
      iSelection = 1;
    iSelection --;

    for (int i = 0; i < iUnit; i++) {
      if (iSelection == i) continue;
      usb_close(units[i].handle);
      units[i].handle = NULL;
    }

    return units[iSelection].handle;
  }

  return NULL;
}
Esempio n. 15
0
/** @brief detect devices based on usb pid / vid.
 *  @return list with usb VID / PID values.
 */
QMap<uint32_t, QString> System::listUsbDevices(void)
{
    QMap<uint32_t, QString> usbids;
    // usb pid detection
    LOG_INFO() << "Searching for USB devices";
#if defined(Q_OS_LINUX)
#if defined(LIBUSB1)
    libusb_device **devs;
    if(libusb_init(NULL) != 0) {
        LOG_ERROR() << "Initializing libusb-1 failed.";
        return usbids;
    }

    if(libusb_get_device_list(NULL, &devs) < 1) {
        LOG_ERROR() << "Error getting device list.";
        return usbids;
    }
    libusb_device *dev;
    int i = 0;
    while((dev = devs[i++]) != NULL) {
        QString name;
        unsigned char buf[256];
        uint32_t id;
        struct libusb_device_descriptor descriptor;
        if(libusb_get_device_descriptor(dev, &descriptor) == 0) {
            id = descriptor.idVendor << 16 | descriptor.idProduct;

            libusb_device_handle *dh;
            if(libusb_open(dev, &dh) == 0) {
                libusb_get_string_descriptor_ascii(dh, descriptor.iManufacturer, buf, 256);
                name += QString::fromLatin1((char*)buf) + " ";
                libusb_get_string_descriptor_ascii(dh, descriptor.iProduct, buf, 256);
                name += QString::fromLatin1((char*)buf);
                libusb_close(dh);
            }
            if(name.isEmpty())
                name = tr("(no description available)");
            if(id) {
                usbids.insertMulti(id, name);
                LOG_INFO("USB: 0x%08x, %s", id, name.toLocal8Bit().data());
            }
        }
    }

    libusb_free_device_list(devs, 1);
    libusb_exit(NULL);
#else
    usb_init();
    usb_find_busses();
    usb_find_devices();
    struct usb_bus *b;
    b = usb_busses;

    while(b) {
        if(b->devices) {
            struct usb_device *u;
            u = b->devices;
            while(u) {
                uint32_t id;
                id = u->descriptor.idVendor << 16 | u->descriptor.idProduct;
                // get identification strings
                usb_dev_handle *dev;
                QString name;
                char string[256];
                int res;
                dev = usb_open(u);
                if(dev) {
                    if(u->descriptor.iManufacturer) {
                        res = usb_get_string_simple(dev, u->descriptor.iManufacturer,
                                                    string, sizeof(string));
                        if(res > 0)
                            name += QString::fromLatin1(string) + " ";
                    }
                    if(u->descriptor.iProduct) {
                        res = usb_get_string_simple(dev, u->descriptor.iProduct,
                                                    string, sizeof(string));
                        if(res > 0)
                            name += QString::fromLatin1(string);
                    }
                    usb_close(dev);
                }
                if(name.isEmpty()) name = tr("(no description available)");

                if(id) {
                    usbids.insertMulti(id, name);
                    LOG_INFO() << "USB:" << QString("0x%1").arg(id, 8, 16) << name;
                }
                u = u->next;
            }
        }
        b = b->next;
    }
#endif
#endif

#if defined(Q_OS_MACX)
    kern_return_t result = KERN_FAILURE;
    CFMutableDictionaryRef usb_matching_dictionary;
    io_iterator_t usb_iterator = IO_OBJECT_NULL;
    usb_matching_dictionary = IOServiceMatching(kIOUSBDeviceClassName);
    result = IOServiceGetMatchingServices(kIOMasterPortDefault, usb_matching_dictionary,
                                          &usb_iterator);
    if(result) {
        LOG_ERROR() << "USB: IOKit: Could not get matching services.";
        return usbids;
    }

    io_object_t usbCurrentObj;
    while((usbCurrentObj = IOIteratorNext(usb_iterator))) {
        uint32_t id;
        QString name;
        /* get vendor ID */
        CFTypeRef vidref = NULL;
        int vid = 0;
        vidref = IORegistryEntryCreateCFProperty(usbCurrentObj, CFSTR("idVendor"),
                                kCFAllocatorDefault, 0);
        CFNumberGetValue((CFNumberRef)vidref, kCFNumberIntType, &vid);
        CFRelease(vidref);

        /* get product ID */
        CFTypeRef pidref = NULL;
        int pid = 0;
        pidref = IORegistryEntryCreateCFProperty(usbCurrentObj, CFSTR("idProduct"),
                                kCFAllocatorDefault, 0);
        CFNumberGetValue((CFNumberRef)pidref, kCFNumberIntType, &pid);
        CFRelease(pidref);
        id = vid << 16 | pid;

        /* get product vendor */
        char vendor_buf[256];
        CFIndex vendor_buflen = 256;
        CFTypeRef vendor_name_ref = NULL;

        vendor_name_ref = IORegistryEntrySearchCFProperty(usbCurrentObj,
                                 kIOServicePlane, CFSTR("USB Vendor Name"),
                                 kCFAllocatorDefault, 0);
        if(vendor_name_ref != NULL) {
            CFStringGetCString((CFStringRef)vendor_name_ref, vendor_buf, vendor_buflen,
                               kCFStringEncodingUTF8);
            name += QString::fromUtf8(vendor_buf) + " ";
            CFRelease(vendor_name_ref);
        }
        else {
            name += QObject::tr("(unknown vendor name) ");
        }

        /* get product name */
        char product_buf[256];
        CFIndex product_buflen = 256;
        CFTypeRef product_name_ref = NULL;

        product_name_ref = IORegistryEntrySearchCFProperty(usbCurrentObj,
                                kIOServicePlane, CFSTR("USB Product Name"),
                                kCFAllocatorDefault, 0);
        if(product_name_ref != NULL) {
            CFStringGetCString((CFStringRef)product_name_ref, product_buf, product_buflen,
                               kCFStringEncodingUTF8);
            name += QString::fromUtf8(product_buf);
            CFRelease(product_name_ref);
        }
        else {
            name += QObject::tr("(unknown product name)");
        }

        if(id) {
            usbids.insertMulti(id, name);
            LOG_INFO() << "USB:" << QString("0x%1").arg(id, 8, 16) << name;
        }

    }
    IOObjectRelease(usb_iterator);
#endif

#if defined(Q_OS_WIN32)
    HDEVINFO deviceInfo;
    SP_DEVINFO_DATA infoData;
    DWORD i;

    // Iterate over all devices
    // by doing it this way it's unneccessary to use GUIDs which might be not
    // present in current MinGW. It also seemed to be more reliably than using
    // a GUID.
    // See KB259695 for an example.
    deviceInfo = SetupDiGetClassDevs(NULL, NULL, NULL, DIGCF_ALLCLASSES | DIGCF_PRESENT);

    infoData.cbSize = sizeof(SP_DEVINFO_DATA);

    for(i = 0; SetupDiEnumDeviceInfo(deviceInfo, i, &infoData); i++) {
        DWORD data;
        LPTSTR buffer = NULL;
        DWORD buffersize = 0;
        QString description;

        // get device descriptor first
        // for some reason not doing so results in bad things (tm)
        while(!SetupDiGetDeviceRegistryProperty(deviceInfo, &infoData,
            SPDRP_DEVICEDESC, &data, (PBYTE)buffer, buffersize, &buffersize)) {
            if(GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
                if(buffer) free(buffer);
                // double buffer size to avoid problems as per KB888609
                buffer = (LPTSTR)malloc(buffersize * 2);
            }
            else {
                break;
            }
        }
        if(!buffer) {
            LOG_WARNING() << "Got no device description"
                          << "(SetupDiGetDeviceRegistryProperty), item" << i;
            continue;
        }
        description = QString::fromWCharArray(buffer);

        // now get the hardware id, which contains PID and VID.
        while(!SetupDiGetDeviceRegistryProperty(deviceInfo, &infoData,
            SPDRP_HARDWAREID, &data, (PBYTE)buffer, buffersize, &buffersize)) {
            if(GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
                if(buffer) free(buffer);
                // double buffer size to avoid problems as per KB888609
                buffer = (LPTSTR)malloc(buffersize * 2);
            }
            else {
                break;
            }
        }

        if(buffer) {
            // convert buffer text to upper case to avoid depending on the case of
            // the keys (W7 uses different casing than XP at least), in addition
            // XP may use "Vid_" and "Pid_".
            QString data = QString::fromWCharArray(buffer).toUpper();
            QRegExp rex("USB\\\\VID_([0-9A-F]{4})&PID_([0-9A-F]{4}).*");
            if(rex.indexIn(data) >= 0) {
                uint32_t id;
                id = rex.cap(1).toUInt(0, 16) << 16 | rex.cap(2).toUInt(0, 16);
                usbids.insert(id, description);
                LOG_INFO() << "USB:" << QString("0x%1").arg(id, 8, 16);
            }
            free(buffer);
        }
    }
    SetupDiDestroyDeviceInfoList(deviceInfo);

#endif
    return usbids;
}
/**
 * Initialize the driver.
 * \param drvthis  Pointer to driver structure.
 * \retval 0       Success.
 * \retval -1      Error.
 */
int
hd_init_usb4all(Driver *drvthis)
{
	PrivateData *p = (PrivateData *) drvthis->private_data;

	struct usb_bus *bus;

	p->hd44780_functions->senddata = usb4all_HD44780_senddata;
	p->hd44780_functions->close = usb4all_HD44780_close;

	p->hd44780_functions->set_contrast = usb4all_HD44780_set_contrast;
	p->hd44780_functions->backlight = usb4all_HD44780_backlight;
	p->hd44780_functions->readkeypad = usb4all_HD44780_readkeypad;

	/* try to find USB device */
	usb_init();
	usb_find_busses();
	usb_find_devices();

	p->usbHandle = NULL;
	for (bus = usb_get_busses(); bus != NULL; bus = bus->next) {
		struct usb_device *dev;

		for (dev = bus->devices; dev != NULL; dev = dev->next) {

			/* Check if this device is a usb4all device */
			if ((dev->descriptor.idVendor == USB4ALL_VENDORID) &&
			 (dev->descriptor.idProduct == USB4ALL_PRODUCTID)) {

				/* USB-4-all device found; try to open it */
				p->usbHandle = usb_open(dev);
				if (p->usbHandle == NULL) {
					report(RPT_WARNING, "hd_init_usb4all: unable to open device");
					/*
					 * Do not exit here because other
					 * (possibly working) devices may be
					 * connected.
					 */
				}
				else {
					report(RPT_INFO, "hd_init_usb4all: USB-4-all device found");
					usb4all_determine_usb_params(p, &dev->config[0].interface[0].altsetting[0]);
				}
			}
		}
	}

	/* No device found at all */
	if (p->usbHandle == NULL) {
		report(RPT_ERR, "hd_init_usb4all: no (matching) USB-4-all device found");
		return -1;
	}

	if (p->usbMode == -1) {
		report(RPT_ERR, "hd_init_usb4all: unknown usb mode");
		return -1;
	}

	/* allocate and initialize buffer */
	if ((p->tx_buf.buffer = malloc(USB4ALL_TX_MAX)) == NULL) {
		report(RPT_ERR, "hd_init_usb4all: could not allocate send buffer");
		usb4all_HD44780_close(p);
		return -1;
	}

	if ((p->rx_buf.buffer = malloc(USB4ALL_RX_MAX)) == NULL) {
		report(RPT_ERR, "hd_init_usb4all: could not allocate receive buffer");
		usb4all_HD44780_close(p);
		return -1;
	}

	common_init(p, IF_4BIT);

	/* replace uPause with empty one after initialization */
	p->hd44780_functions->uPause = usb4all_HD44780_uPause;

	/* initialize usb-4-all controller */
	usb4all_init(p);

	return 0;
}
Esempio n. 17
0
//  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;
}
Esempio n. 18
0
int APIENTRY WinMain(HINSTANCE instance, HINSTANCE prev_instance,
                     LPSTR cmd_line, int cmd_show)
{
  MSG msg;
  WNDCLASSEX win_class;
  DEV_BROADCAST_DEVICEINTERFACE dev_if;

  LoadLibrary("comctl32.dll");

  win_class.cbSize = sizeof(WNDCLASSEX); 
  
  win_class.style = CS_HREDRAW | CS_VREDRAW | CS_GLOBALCLASS ;
  win_class.lpfnWndProc = win_proc;
  win_class.cbClsExtra = 0;
  win_class.cbWndExtra = 0;
  win_class.hInstance = instance;
  win_class.hIcon = NULL;
  win_class.hCursor = LoadCursor(NULL, IDC_ARROW);
  win_class.hbrBackground = (HBRUSH)(COLOR_3DFACE + 1);
  win_class.lpszMenuName = NULL;
  win_class.lpszClassName = LIBUSB_WINDOW_CLASS;
  win_class.hIconSm = NULL;

  RegisterClassEx(&win_class);

  main_win = CreateWindowEx(WS_EX_APPWINDOW| WS_EX_CONTROLPARENT,
                            LIBUSB_WINDOW_CLASS, 
                            "TestLibUsb - Windows Version", 
                            WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN 
                            | WS_DLGFRAME,
                            CW_USEDEFAULT, 0, 500, 500, NULL, NULL, 
                            instance, NULL);
  if(!main_win) 
    {
      return FALSE;
    }


  exit_button = CreateWindow("BUTTON", "Exit",
                             WS_VISIBLE | WS_CHILD | BS_DEFPUSHBUTTON,
                             10, 10, 
                             LIBUSB_BUTTON_WIDTH, LIBUSB_BUTTON_HEIGHT, 
                             main_win, (HMENU) ID_EXIT, instance, NULL);

  refresh_button = CreateWindow("BUTTON", "Refresh",
                                WS_VISIBLE | WS_CHILD | BS_DEFPUSHBUTTON,
                                10, 100, 
                                LIBUSB_BUTTON_WIDTH, LIBUSB_BUTTON_HEIGHT, 
                                main_win, (HMENU) ID_REFRESH, instance, 
                                NULL);

  edit_box = CreateWindowEx(WS_EX_CLIENTEDGE, "EDIT", NULL,
                            WS_CHILD | WS_VISIBLE | WS_VSCROLL | 
                            ES_LEFT | ES_MULTILINE | ES_AUTOVSCROLL 
                            | ES_AUTOHSCROLL | ES_READONLY, 
                            CW_USEDEFAULT, CW_USEDEFAULT, 
                            CW_USEDEFAULT, CW_USEDEFAULT,
                            main_win, (HMENU) ID_EDIT, instance, NULL); 

  SendMessage(edit_box, WM_SETFONT, (WPARAM) CreateFont(13, 8, 0, 0,
                                                        400, 0, 0, 0,
                                                        0, 1, 2, 1,
                                                        49, "Courier"), 0);

  ShowWindow(main_win, cmd_show);
  UpdateWindow(main_win);
  BringWindowToTop(main_win);

  usb_set_debug(4);
  usb_init();
  usb_find_busses();

  on_refresh();

  dev_if.dbcc_size = sizeof(dev_if);
  dev_if.dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE;
  dev_if.dbcc_classguid = GUID_DEVINTERFACE_USB_HUB;

  notification_handle_hub = RegisterDeviceNotification(main_win, &dev_if, 0);

  dev_if.dbcc_classguid = GUID_DEVINTERFACE_USB_DEVICE;

  notification_handle_dev = RegisterDeviceNotification(main_win, &dev_if, 0);

  while(GetMessage(&msg, NULL, 0, 0) ) 
    {
      TranslateMessage(&msg);
      DispatchMessage(&msg);
    }

  DestroyWindow(main_win);
  UnregisterClass(LIBUSB_WINDOW_CLASS, instance);

  return 0;
}
Esempio n. 19
0
/**
 * 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;
}
Esempio n. 20
0
int usbOpenDevice(usbDevice_t **device, int vendor, char *vendorName, int product, char *productName, int _usesReportIDs)
{
struct usb_bus      *bus;
struct usb_device   *dev;
usb_dev_handle      *handle = NULL;
int                 errorCode = USB_ERROR_NOTFOUND;
static int          didUsbInit = 0;

    if(!didUsbInit){
        usb_init();
        didUsbInit = 1;
    }
    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 == vendor && dev->descriptor.idProduct == product){
                char    string[256];
                int     len;
                handle = usb_open(dev); /* we need to open the device in order to query strings */
                if(!handle){
                    errorCode = USB_ERROR_ACCESS;
                    fprintf(stderr, "Warning: cannot open USB device: %s\n", usb_strerror());
                    continue;
                }
                if(vendorName == NULL && productName == NULL){  /* name does not matter */
                    break;
                }
                /* now check whether the names match: */
                len = usbGetStringAscii(handle, dev->descriptor.iManufacturer, 0x0409, string, sizeof(string));
                if(len < 0){
                    errorCode = USB_ERROR_IO;
                    fprintf(stderr, "Warning: cannot query manufacturer for device: %s\n", usb_strerror());
                }else{
                    errorCode = USB_ERROR_NOTFOUND;
                    /* fprintf(stderr, "seen device from vendor ->%s<-\n", string); */
		    /* check product name , the is no vendor name*/
                    len = usbGetStringAscii(handle, dev->descriptor.iProduct, 0x0409, string, sizeof(string));
                    if(len < 0){
                          errorCode = USB_ERROR_IO;
                          fprintf(stderr, "Warning: cannot query product for device: %s\n", usb_strerror());
                    }else{
                          errorCode = USB_ERROR_NOTFOUND;
                          // fprintf(stderr, "seen product ->%s<-\n", string); 
                          if(strcmp(string, productName) == 0)
                              break;
                    }
                   
                }
                usb_close(handle);
                handle = NULL;
            }
        }
        if(handle)
            break;
    }
    if(handle != NULL){
        int rval, retries = 3;
        if(usb_set_configuration(handle, 1)){
            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((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){
                fprintf(stderr, "Warning: could not detach kernel HID driver: %s\n", usb_strerror());
            }
#endif
        }
#ifndef __APPLE__
        if(rval != 0)
            fprintf(stderr, "Warning: could not claim interface\n");
#endif
/* Continue anyway, even if we could not claim the interface. Control transfers
 * should still work.
 */
        errorCode = 0;
        *device = handle;
        usesReportIDs = _usesReportIDs;
    }
    return errorCode;
}
Esempio n. 21
0
int usbhidOpenDevice(usbDevice_t** device, int vendor, const char* vendorName, int product, const char* productName)
{
	struct usb_bus*     bus;
	struct usb_device*  dev;
	usb_dev_handle*     handle = NULL;
	int                 errorCode = USBOPEN_ERR_NOTFOUND;
	static int          didUsbInit = 0;

	if (!didUsbInit)
	{
		usb_init();
		didUsbInit = 1;
	}

	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 == vendor && dev->descriptor.idProduct == product)
			{
				char    string[256];
				int     len;
				handle = usb_open(dev); // we need to open the device in order to query strings
				if (!handle)
				{
					errorCode = USBOPEN_ERR_ACCESS;
					DEBUG_PRINT(("Warning: cannot open USB device: %s\n", usb_strerror()));
					continue;
				}

				if (vendorName == NULL && productName == NULL)  // name does not matter
					break;

				// now check whether the names match:
				len = usbhidGetStringAscii(handle, dev->descriptor.iManufacturer, string, sizeof(string));
				if (len < 0)
				{
					errorCode = USBOPEN_ERR_IO;
					DEBUG_PRINT(("Warning: cannot query manufacturer for device: %s\n", usb_strerror()));
				} else {
					errorCode = USBOPEN_ERR_NOTFOUND;
					if (strcmp(string, vendorName) == 0)
					{
						len = usbhidGetStringAscii(handle, dev->descriptor.iProduct, string, sizeof(string));
						if (len < 0)
						{
							errorCode = USBOPEN_ERR_IO;
							DEBUG_PRINT(("Warning: cannot query product for device: %s\n", usb_strerror()));
						} else {
							errorCode = USBOPEN_ERR_NOTFOUND;
							if (strcmp(string, productName) == 0)
								break;
						}
					}
				}
				usb_close(handle);
				handle = NULL;
			}
		}

		if (handle)
			break;
	}

	if (handle != NULL)
	{
		errorCode = USBOPEN_SUCCESS;
		*device = (usbDevice_t*)handle;
	}

	return errorCode;
}
Esempio n. 22
0
int usbOpenDevice(usb_dev_handle **device, int vendorID, char *vendorNamePattern, int productID, char *productNamePattern, char *serialNamePattern, FILE *printMatchingDevicesFp, FILE *warningsFp)
{
	struct usb_bus *bus;
	struct usb_device *dev;
	usb_dev_handle *handle = NULL;
	int errorCode = USBOPEN_ERR_NOTFOUND;

    usb_find_busses();
    usb_find_devices();
    for(bus = usb_get_busses(); bus; bus = bus->next)
	{
        for(dev = bus->devices; dev; dev = dev->next)
		{
            if((vendorID == 0 || dev->descriptor.idVendor == vendorID) && (productID == 0 || dev->descriptor.idProduct == productID))
			{
                char    vendor[256], product[256], serial[256];
                int     len;
                handle = usb_open(dev);
                
				if(!handle)
				{
                    errorCode = USBOPEN_ERR_ACCESS;
                    if(warningsFp != NULL)
					{
                        fprintf(warningsFp, "Warning: cannot open VID=0x%04x PID=0x%04x: %s\n", dev->descriptor.idVendor, dev->descriptor.idProduct, usb_strerror());
                    }
					continue;
                }

                len = vendor[0] = 0;
                if(dev->descriptor.iManufacturer > 0)
				{
                    len = usbGetStringAscii(handle, dev->descriptor.iManufacturer, vendor, sizeof(vendor));
                }
                if(len < 0)
				{
                    errorCode = USBOPEN_ERR_ACCESS;
                    if(warningsFp != NULL)
					{
                        fprintf(warningsFp, "Warning: cannot query manufacturer for VID=0x%04x PID=0x%04x: %s\n", dev->descriptor.idVendor, dev->descriptor.idProduct, usb_strerror());
					}
				}
				else
				{
                    errorCode = USBOPEN_ERR_NOTFOUND;

                    if(shellStyleMatch(vendor, vendorNamePattern))
					{
                        len = product[0] = 0;
                        if(dev->descriptor.iProduct > 0)
						{
                            len = usbGetStringAscii(handle, dev->descriptor.iProduct, product, sizeof(product));
                        }
                        if(len < 0)
						{
                            errorCode = USBOPEN_ERR_ACCESS;
                            if(warningsFp != NULL)
                                fprintf(warningsFp, "Warning: cannot query product for VID=0x%04x PID=0x%04x: %s\n", dev->descriptor.idVendor, dev->descriptor.idProduct, usb_strerror());
                        }
						else
						{
                            errorCode = USBOPEN_ERR_NOTFOUND;

                            if(shellStyleMatch(product, productNamePattern))
							{
                                len = serial[0] = 0;
                                if(dev->descriptor.iSerialNumber > 0)
								{
                                    len = usbGetStringAscii(handle, dev->descriptor.iSerialNumber, serial, sizeof(serial));
                                }
                                if(len < 0)
								{
                                    errorCode = USBOPEN_ERR_ACCESS;
                                    if(warningsFp != NULL)
                                        fprintf(warningsFp, "Warning: cannot query serial for VID=0x%04x PID=0x%04x: %s\n", dev->descriptor.idVendor, dev->descriptor.idProduct, usb_strerror());
                                }
                                if(shellStyleMatch(serial, serialNamePattern))
								{
                                    if(printMatchingDevicesFp != NULL)
									{
                                        if(serial[0] == 0)
										{
                                            fprintf(printMatchingDevicesFp, "VID=0x%04x PID=0x%04x vendor=\"%s\" product=\"%s\"\n", dev->descriptor.idVendor, dev->descriptor.idProduct, vendor, product);
                                        }
										else
										{
                                            fprintf(printMatchingDevicesFp, "VID=0x%04x PID=0x%04x vendor=\"%s\" product=\"%s\" serial=\"%s\"\n", dev->descriptor.idVendor, dev->descriptor.idProduct, vendor, product, serial);
                                        }
                                    }
									else
									{
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }
                usb_close(handle);
                handle = NULL;
            }
        }
		
        if(handle)
		{
            break;
		}
    }
	
    if(handle != NULL)
	{
        errorCode = 0;
        *device = handle;
    }
	
    if(printMatchingDevicesFp != NULL)
	{
        errorCode = 0;
	}
    return errorCode;
}
Esempio n. 23
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;
}
Esempio n. 24
0
/*****************************************************************************
 *
 *					OpenUSBByName
 *
 ****************************************************************************/
status_t OpenUSBByName(unsigned int reader_index, /*@null@*/ char *device)
{
	static struct usb_bus *busses = NULL;
	int alias = 0;
	struct usb_bus *bus;
	struct usb_dev_handle *dev_handle;
	char keyValue[TOKEN_MAX_VALUE_SIZE];
	unsigned int vendorID, productID;
	char infofile[FILENAME_MAX];
#ifndef __APPLE__
	unsigned int device_vendor, device_product;
#endif
	char *dirname = NULL, *filename = NULL;
	int interface_number = -1;
	static int previous_reader_index = -1;

	DEBUG_COMM3("Reader index: %X, Device: %s", reader_index, device);

#ifndef __APPLE__
	/* device name specified */
	if (device)
	{
		/* format: usb:%04x/%04x, vendor, product */
		if (strncmp("usb:", device, 4) != 0)
		{
			DEBUG_CRITICAL2("device name does not start with \"usb:\": %s",
				device);
			return STATUS_UNSUCCESSFUL;
		}

		if (sscanf(device, "usb:%x/%x", &device_vendor, &device_product) != 2)
		{
			DEBUG_CRITICAL2("device name can't be parsed: %s", device);
			return STATUS_UNSUCCESSFUL;
		}

		/* format usb:%04x/%04x:libusb:%s
		 * with %s set to %s:%s, dirname, filename */
		if ((dirname = strstr(device, "libusb:")) != NULL)
		{
			/* dirname points to the first char after libusb: */
			dirname += strlen("libusb:");

			/* search the : (separation) char */
			filename = strchr(dirname, ':');

			if (filename)
			{
				/* end the dirname string */
				*filename = '\0';

				/* filename points to the first char after : */
				filename++;
			}
			else
			{
				/* parse failed */
				dirname = NULL;

				DEBUG_CRITICAL2("can't parse using libusb scheme: %s", device);
			}
		}

		/* format usb:%04x/%04x:libhal:%s
		 * with %s set to
		 * /org/freedesktop/Hal/devices/usb_device_VID_PID_SERIAL_ifX
		 * VID is VendorID
		 * PID is ProductID
		 * SERIAL is device serial number
		 * X is the interface number
		 */
		if ((dirname = strstr(device, "libhal:")) != NULL)
		{
			const char *p;

#define HAL_HEADER "usb_device_"

			/* parse the hal string */
			if (
				/* search the last '/' char */
				(p = strrchr(dirname, '/'))

				/* if the string starts with "usb_device_" we continue */
				&& (0 == strncmp(++p, HAL_HEADER, sizeof(HAL_HEADER)-1))
				/* skip the HAL header */
				&& (p += sizeof(HAL_HEADER)-1)

				/* search the last '_' */
				&& (p = strrchr(++p, '_'))
				&& (0 == strncmp(++p, "if", 2))
			   )
			{
				/* convert the interface number */
				interface_number = atoi(p+2);
			}
			else
				DEBUG_CRITICAL2("can't parse using libhal scheme: %s", device);

			/* dirname was just a temporary variable */
			dirname = NULL;
		}
	}
#endif

	if (busses == NULL)
		usb_init();

	(void)usb_find_busses();
	(void)usb_find_devices();

	busses = usb_get_busses();

	if (busses == NULL)
	{
		DEBUG_CRITICAL("No USB busses found");
		return STATUS_UNSUCCESSFUL;
	}

	/* is the reader_index already used? */
	if (usbDevice[reader_index].handle != NULL)
	{
		DEBUG_CRITICAL2("USB driver with index %X already in use",
			reader_index);
		return STATUS_UNSUCCESSFUL;
	}

	/* Info.plist full patch filename */
	(void)snprintf(infofile, sizeof(infofile), "%s/%s/Contents/Info.plist",
		PCSCLITE_HP_DROPDIR, BUNDLE);

	/* general driver info */
	if (!LTPBundleFindValueWithKey(infofile, "ifdManufacturerString", keyValue, 0))
	{
		DEBUG_INFO2("Manufacturer: %s", keyValue);
	}
	else
	{
		DEBUG_INFO2("LTPBundleFindValueWithKey error. Can't find %s?",
			infofile);
		return STATUS_UNSUCCESSFUL;
	}
	if (!LTPBundleFindValueWithKey(infofile, "ifdProductString", keyValue, 0))
	{
		DEBUG_INFO2("ProductString: %s", keyValue);
	}
	else
		return STATUS_UNSUCCESSFUL;
	if (!LTPBundleFindValueWithKey(infofile, "Copyright", keyValue, 0))
	{
		DEBUG_INFO2("Copyright: %s", keyValue);
	}
	else
		return STATUS_UNSUCCESSFUL;
	vendorID = strlen(keyValue);
	alias = 0x1C;
	for (; vendorID--;)
		alias ^= keyValue[vendorID];

	/* for any supported reader */
	while (LTPBundleFindValueWithKey(infofile, PCSCLITE_MANUKEY_NAME, keyValue, alias) == 0)
	{
		vendorID = strtoul(keyValue, NULL, 0);

		if (LTPBundleFindValueWithKey(infofile, PCSCLITE_PRODKEY_NAME, keyValue, alias))
			goto end;
		productID = strtoul(keyValue, NULL, 0);

		if (LTPBundleFindValueWithKey(infofile, PCSCLITE_NAMEKEY_NAME, keyValue, alias))
			goto end;

		/* go to next supported reader for next round */
		alias++;

#ifndef __APPLE__
		/* the device was specified but is not the one we are trying to find */
		if (device
			&& (vendorID != device_vendor || productID != device_product))
			continue;
#else
		/* Leopard puts the friendlyname in the device argument */
		if (device && strcmp(device, keyValue))
			continue;
#endif

		/* on any USB buses */
		for (bus = busses; bus; bus = bus->next)
		{
			struct usb_device *dev;

			/* any device on this bus */
			for (dev = bus->devices; dev; dev = dev->next)
			{
				/* device defined by name? */
				if (dirname && (strcmp(dirname, bus->dirname)
					|| strcmp(filename, dev->filename)))
					continue;

				if (dev->descriptor.idVendor == vendorID
					&& dev->descriptor.idProduct == productID)
				{
					int r, already_used;
					struct usb_interface *usb_interface = NULL;
					int interface;
					int num = 0;

#ifdef USE_COMPOSITE_AS_MULTISLOT
					static int static_interface = 1;

					{
						/* simulate a composite device as when libhal is
						 * used */
						int readerID = (vendorID << 16) + productID;

						if ((GEMALTOPROXDU == readerID)
							|| (GEMALTOPROXSU == readerID))
						{
							if(interface_number >= 0)
							{
								DEBUG_CRITICAL("USE_COMPOSITE_AS_MULTISLOT can't be used with libhal");
								continue;
							}

							/* the CCID interfaces are 1 and 2 */
							interface_number = static_interface;
						}
					}
#endif
					/* is it already opened? */
					already_used = FALSE;

					DEBUG_COMM3("Checking device: %s/%s",
						bus->dirname, dev->filename);
					for (r=0; r<CCID_DRIVER_MAX_READERS; r++)
					{
						if (usbDevice[r].handle)
						{
							/* same busname, same filename */
							if (strcmp(usbDevice[r].dirname, bus->dirname) == 0 && strcmp(usbDevice[r].filename, dev->filename) == 0)
								already_used = TRUE;
						}
					}

					/* this reader is already managed by us */
					if (already_used)
					{
						if ((previous_reader_index != -1)
							&& usbDevice[previous_reader_index].handle
							&& (strcmp(usbDevice[previous_reader_index].dirname, bus->dirname)  == 0)
							&& (strcmp(usbDevice[previous_reader_index].filename, dev->filename) == 0)
							&& usbDevice[previous_reader_index].ccid.bCurrentSlotIndex < usbDevice[previous_reader_index].ccid.bMaxSlotIndex)
						{
							/* we reuse the same device
							 * and the reader is multi-slot */
							usbDevice[reader_index] = usbDevice[previous_reader_index];
							/* the other slots do not have the same data rates */
							if ((GEMCOREPOSPRO == usbDevice[reader_index].ccid.readerID)
								|| (GEMCORESIMPRO == usbDevice[reader_index].ccid.readerID))
							{
								usbDevice[reader_index].ccid.arrayOfSupportedDataRates = SerialCustomDataRates;
								usbDevice[reader_index].ccid.dwMaxDataRate = 125000;
							}

							*usbDevice[reader_index].nb_opened_slots += 1;
							usbDevice[reader_index].ccid.bCurrentSlotIndex++;
							usbDevice[reader_index].ccid.dwSlotStatus =
								IFD_ICC_PRESENT;
							DEBUG_INFO2("Opening slot: %d",
								usbDevice[reader_index].ccid.bCurrentSlotIndex);
							goto end;
						}
						else
						{
							/* if an interface number is given by HAL we
							 * continue with this device. */
							if (-1 == interface_number)
							{
								DEBUG_INFO3("USB device %s/%s already in use."
									" Checking next one.",
									bus->dirname, dev->filename);
								continue;
							}
						}
					}

					DEBUG_COMM3("Trying to open USB bus/device: %s/%s",
						 bus->dirname, dev->filename);

					dev_handle = usb_open(dev);
					if (dev_handle == NULL)
					{
						DEBUG_CRITICAL4("Can't usb_open(%s/%s): %s",
							bus->dirname, dev->filename, strerror(errno));

						continue;
					}

					/* now we found a free reader and we try to use it */
					if (dev->config == NULL)
					{
						(void)usb_close(dev_handle);
						DEBUG_CRITICAL3("No dev->config found for %s/%s",
							 bus->dirname, dev->filename);
						return STATUS_UNSUCCESSFUL;
					}

again:
					usb_interface = get_ccid_usb_interface(dev, &num);
					if (usb_interface == NULL)
					{
						(void)usb_close(dev_handle);
						if (0 == num)
							DEBUG_CRITICAL3("Can't find a CCID interface on %s/%s",
								bus->dirname, dev->filename);
						interface_number = -1;
						continue;
					}

					if (usb_interface->altsetting->extralen != 54)
					{
						(void)usb_close(dev_handle);
						DEBUG_CRITICAL4("Extra field for %s/%s has a wrong length: %d", bus->dirname, dev->filename, usb_interface->altsetting->extralen);
						return STATUS_UNSUCCESSFUL;
					}

					interface = usb_interface->altsetting->bInterfaceNumber;
					if (interface_number >= 0 && interface != interface_number)
					{
						/* an interface was specified and it is not the
						 * current one */
						DEBUG_INFO3("Wrong interface for USB device %s/%s."
							" Checking next one.", bus->dirname, dev->filename);

						/* check for another CCID interface on the same device */
						num++;

						goto again;
					}

					if (usb_claim_interface(dev_handle, interface) < 0)
					{
						(void)usb_close(dev_handle);
						DEBUG_CRITICAL4("Can't claim interface %s/%s: %s",
							bus->dirname, dev->filename, strerror(errno));
						interface_number = -1;
						continue;
					}

					DEBUG_INFO4("Found Vendor/Product: %04X/%04X (%s)",
						dev->descriptor.idVendor,
						dev->descriptor.idProduct, keyValue);
					DEBUG_INFO3("Using USB bus/device: %s/%s",
						 bus->dirname, dev->filename);

					/* check for firmware bugs */
					if (ccid_check_firmware(dev))
					{
						(void)usb_close(dev_handle);
						return STATUS_UNSUCCESSFUL;
					}

#ifdef USE_COMPOSITE_AS_MULTISLOT
					/* use the next interface for the next "slot" */
					static_interface++;

					/* reset for a next reader */
					if (static_interface > 2)
						static_interface = 1;
#endif

					/* Get Endpoints values*/
					(void)get_end_points(dev, &usbDevice[reader_index], num);

					/* store device information */
					usbDevice[reader_index].handle = dev_handle;
					usbDevice[reader_index].dirname = strdup(bus->dirname);
					usbDevice[reader_index].filename = strdup(dev->filename);
					usbDevice[reader_index].interface = interface;
					usbDevice[reader_index].real_nb_opened_slots = 1;
					usbDevice[reader_index].nb_opened_slots = &usbDevice[reader_index].real_nb_opened_slots;

					/* CCID common informations */
					usbDevice[reader_index].ccid.real_bSeq = 0;
					usbDevice[reader_index].ccid.pbSeq = &usbDevice[reader_index].ccid.real_bSeq;
					usbDevice[reader_index].ccid.readerID =
						(dev->descriptor.idVendor << 16) +
						dev->descriptor.idProduct;
					usbDevice[reader_index].ccid.dwFeatures = dw2i(usb_interface->altsetting->extra, 40);
					usbDevice[reader_index].ccid.wLcdLayout =
						(usb_interface->altsetting->extra[51] << 8) +
						usb_interface->altsetting->extra[50];
					usbDevice[reader_index].ccid.bPINSupport = usb_interface->altsetting->extra[52];
					usbDevice[reader_index].ccid.dwMaxCCIDMessageLength = dw2i(usb_interface->altsetting->extra, 44);
					usbDevice[reader_index].ccid.dwMaxIFSD = dw2i(usb_interface->altsetting->extra, 28);
					usbDevice[reader_index].ccid.dwDefaultClock = dw2i(usb_interface->altsetting->extra, 10);
					usbDevice[reader_index].ccid.dwMaxDataRate = dw2i(usb_interface->altsetting->extra, 23);
					usbDevice[reader_index].ccid.bMaxSlotIndex = usb_interface->altsetting->extra[4];
					usbDevice[reader_index].ccid.bCurrentSlotIndex = 0;
					usbDevice[reader_index].ccid.readTimeout = DEFAULT_COM_READ_TIMEOUT;
					usbDevice[reader_index].ccid.arrayOfSupportedDataRates = get_data_rates(reader_index, dev, num);
					usbDevice[reader_index].ccid.bInterfaceProtocol = usb_interface->altsetting->bInterfaceProtocol;
					usbDevice[reader_index].ccid.bNumEndpoints = usb_interface->altsetting->bNumEndpoints;
					usbDevice[reader_index].ccid.dwSlotStatus = IFD_ICC_PRESENT;
					usbDevice[reader_index].ccid.bVoltageSupport = usb_interface->altsetting->extra[5];
					goto end;
				}
			}
		}
	}
end:
	if (usbDevice[reader_index].handle == NULL)
		return STATUS_NO_SUCH_DEVICE;

	/* memorise the current reader_index so we can detect
	 * a new OpenUSBByName on a multi slot reader */
	previous_reader_index = reader_index;

	return STATUS_SUCCESS;
} /* OpenUSBByName */
Esempio n. 25
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;
}
Esempio n. 26
0
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;
}
Esempio n. 27
0
bool ns_usb_control::reset_device(int bus,int device_id){
	#ifdef _WIN32 
	return false;
	#else
	
	#ifdef USE_NEW_USB
	libusb_device **devices;
	int r;
	ssize_t cnt;
	ns_acquire_lock_for_scope lock(usb_context.libusb_lock,__FILE__,__LINE__);

	libusb_context * context = (libusb_context *)usb_context.get_context();
	try{
	  cnt = libusb_get_device_list(context, &devices);
	  if (cnt < 0)
	    throw ns_ex("ns_usb_control::Could not enumerate devices!");
	  try{
	    libusb_device *d;
	    libusb_device *requested_device(0);
	    int i = 0;
	    
	    while ((d= devices[i++]) != NULL) {
	      struct libusb_device_descriptor desc;
	      unsigned long bus_number(libusb_get_bus_number(d));
	      unsigned long device_address(libusb_get_device_address(d));
	      if (bus_number == bus && device_address == device_id){
		requested_device = d;
	      }
	      else
		libusb_unref_device(d);//don't hold onto devices that aren't used
	    }
	    
	    
	    if(requested_device==0){
	      libusb_free_device_list(devices,0);
	      lock.release();
	      return 0;
	    }
	    struct libusb_device_handle *device_handle;
	    int err = libusb_open(requested_device,&device_handle);
	    if (err != 0)
	      throw ns_ex("ns_usb_control::Could not open device: ") << err;
	    
	    err = libusb_reset_device(device_handle);
	    if (err){
	      libusb_close(device_handle);
	      libusb_unref_device(requested_device);
	      throw ns_ex("ns_usb::reset_device::Could not reset device: ") << err;
	    }
	    libusb_close(device_handle);
	    libusb_unref_device(requested_device);
	  }
	  catch(...){
	    //don't leak device name lists
	    libusb_free_device_list(devices, 0);
	    throw;
	  }
	}
	catch(...){
	  //release the context so that it can be reset
	  usb_context.release_context();
	  throw;
	}
	
	libusb_free_device_list(devices, 0);
	lock.release();
	return true;
#else
	
	ns_acquire_lock_for_scope lock(usb_context.libusb_lock,__FILE__,__LINE__);
	usb_find_busses();
	usb_find_devices();

	struct usb_device *device(0);
	ssize_t i = 0;
	int err = 0;

	for (struct usb_bus * cur_bus = usb_busses; cur_bus; cur_bus= cur_bus->next){
		int cur_bus_number(atoi(cur_bus->dirname));
		for (struct usb_device *dev = cur_bus->devices; dev; dev = dev->next){
			int cur_device_id(dev->devnum);
			//char * filename(dev->filename);

			if (cur_bus_number == bus && device_id == cur_device_id){
				device = dev;
				break;
			}
		}
	}
     

	if(!device){
		lock.release();
		return 0;
	}
	struct usb_dev_handle *handle;
	handle = usb_open(device);
	try{
		if (err)
			throw ns_ex("ns_usb::reset_device::Could not acquire handle for device");

		err = usb_reset(handle);
		//err2 = usb_reset(handle);
		if (err)
			throw ns_ex("ns_usb::reset_device::Could not reset device");
		usb_close(handle);
	}
	catch(...){
		usb_close(handle);
		throw;
	}
	lock.release();
	return true;
#endif
#endif
}
Esempio n. 28
0
static int usbOpenDevice(usb_dev_handle **device, int vendor, char *vendorName, int product, char *productName)
{
    struct usb_bus      *bus;
    struct usb_device   *dev;
    usb_dev_handle      *handle = NULL;
    int                 errorCode = USB_ERROR_NOTFOUND;
    static int          didUsbInit = 0;

    if(!didUsbInit) {
        didUsbInit = 1;
        usb_init();
    }
    usb_find_busses();
    usb_find_devices();
    for(bus=usb_get_busses(); bus; bus=bus->next) {											// iterate over busses
        for(dev=bus->devices; dev; dev=dev->next) {											// iterate over devices
            if(dev->descriptor.idVendor == vendor && dev->descriptor.idProduct == product) { // if we have found our device
                char    string[256];
                int     len;
                handle = usb_open(dev);														// open it
                if(!handle) {																// ooops
                    errorCode = USB_ERROR_ACCESS;
                    fprintf(stderr, "Warning: cannot open USB device: %s\n", usb_strerror());
                    continue;
                }
                if(vendorName == NULL && productName == NULL) { /* name does not matter */
                    break;
                }
                /* now check whether the names match: */
                len = usbGetStringAscii(handle, dev->descriptor.iManufacturer, 0x0409, string, sizeof(string));
                if(len < 0) {
                    errorCode = USB_ERROR_IO;
                    fprintf(stderr, "Warning: cannot query manufacturer for device: %s\n", usb_strerror());
                } else {
                    errorCode = USB_ERROR_NOTFOUND;
                    /* fprintf(stderr, "seen device from vendor ->%s<-\n", string); */
                    if(strcmp(string, vendorName) == 0) {
                        len = usbGetStringAscii(handle, dev->descriptor.iProduct, 0x0409, string, sizeof(string));
                        if(len < 0) {
                            errorCode = USB_ERROR_IO;
                            fprintf(stderr, "Warning: cannot query product for device: %s\n", usb_strerror());
                        } else {
                            errorCode = USB_ERROR_NOTFOUND;
                            /* fprintf(stderr, "seen product ->%s<-\n", string); */
                            if(strcmp(string, productName) == 0)
                                break;
                        }
                    }
                }
                usb_close(handle);
                handle = NULL;
            }
        }
        if(handle)
            break;
    }
    if(handle != NULL) {
        errorCode = 0;
        *device = handle;
    }
    return errorCode;
}
int main(int argc, char **argv) {
    int ret, vendor, product;
    struct usb_device *dev;
    char buf[65535], *endptr;
#if 0
    usb_urb *isourb;
    struct timeval isotv;
    char isobuf[32768];
#endif

    usb_init();
//    usb_set_debug(255);
    usb_find_busses();
    usb_find_devices();
/*
    if (argc!=3) {
	printf("usage: %s vendorID productID\n", argv[0]);
	printf("ID numbers of currently attached devices:\n");
	list_devices();
	exit(1);
    }
    vendor = strtol(argv[1], &endptr, 16);
    if (*endptr != '\0') {
	printf("invalid vendor id\n");
	exit(1);
    }
    product = strtol(argv[2], &endptr, 16);
    if (*endptr != '\0') {
	printf("invalid product id\n");
	exit(1);
    }
*/
    printf("Hladam HUAWEI E220 a prepnem na modem - bbo 06\n");
    vendor = 0x12d1;
    product = 0x1003;
    dev = find_device(vendor, product);
    assert(dev);

    devh = usb_open(dev);
    assert(devh);
    
    signal(SIGTERM, release_usb_device);

/*
    ret = usb_get_driver_np(devh, 0, buf, sizeof(buf));
    printf("usb_get_driver_np returned %d\n", ret);
    if (ret == 0) {
	printf("interface 0 already claimed by driver \"%s\", attempting to detach it\n", buf);
	ret = usb_detach_kernel_driver_np(devh, 0);
	printf("usb_detach_kernel_driver_np returned %d\n", ret);
    }
    ret = usb_claim_interface(devh, 0);
    if (ret != 0) {
	printf("claim failed with error %d\n", ret);
		exit(1);
    }
    
    ret = usb_set_altinterface(devh, 0);
    assert(ret >= 0);
*/
// BBO typ 1 = DEVICE
ret = usb_get_descriptor(devh, 0x0000001, 0x0000000, buf, 0x0000012);
//printf("1 get descriptor returned %d, bytes: ", ret);
//print_bytes(buf, ret);
//printf("\n");
usleep(1*1000);
// BBO typ 2 = CONFIGURATION
ret = usb_get_descriptor(devh, 0x0000002, 0x0000000, buf, 0x0000009);
//printf("2 get descriptor returned %d, bytes: ", ret);
//print_bytes(buf, ret);
//printf("\n");
usleep(1*1000);
// BBO typ 2 = CONFIGURATION
ret = usb_get_descriptor(devh, 0x0000002, 0x0000000, buf, 0x0000020);
//printf("3 get descriptor returned %d, bytes: ", ret);
//print_bytes(buf, ret);
//printf("\n");
usleep(1*1000);
/*
ret = usb_release_interface(devh, 0);
if (ret != 0) printf("failed to release interface before set_configuration: %d\n", ret);
ret = usb_set_configuration(devh, 0x0000001);
printf("4 set configuration returned %d\n", ret);
ret = usb_claim_interface(devh, 0);
if (ret != 0) printf("claim after set_configuration failed with error %d\n", ret);
ret = usb_set_altinterface(devh, 0);
printf("4 set alternate setting returned %d\n", ret);
usleep(50*1000);
ret = usb_set_altinterface(devh, 0);
printf("5 set alternate setting returned %d\n", ret);
usleep(62*1000);
*/
ret = usb_control_msg(devh, USB_TYPE_STANDARD + USB_RECIP_DEVICE, USB_REQ_SET_FEATURE, 00000001, 0, buf, 0, 1000);
printf("4 set feature request returned %d\n", ret);
/*
	ret = usb_release_interface(devh, 0);
	assert(ret == 0);
*/
	ret = usb_close(devh);
	assert(ret == 0);
	printf("Prepnute-OK, Mas ttyUSB0 ttyUSB1 (cez usbserial vendor=0x12d1 product=0x1004)\n");
	printf("pozri /proc/bus/usb/devices\n");
	return 0;
}
Esempio n. 30
0
int usbOpenDevice(usb_dev_handle ** device, int vendorID,
                  char *vendorNamePattern, int productID,
                  char *productNamePattern, char *serialNamePattern,
                  FILE * printMatchingDevicesFp, FILE * warningsFp)
{
    struct usb_bus *bus;
    struct usb_device *dev;
    usb_dev_handle *handle = NULL;
    int errorCode = USBOPEN_ERR_NOTFOUND;

    usb_find_busses();
    usb_find_devices();
    for (bus = usb_get_busses(); bus; bus = bus->next) {
        for (dev = bus->devices; dev; dev = dev->next) {        /* iterate over 
                                                                 * all devices
                                                                 * on all
                                                                 * busses */
            if ((vendorID == 0 || dev->descriptor.idVendor == vendorID)
                && (productID == 0 || dev->descriptor.idProduct == productID)) {
                char vendor[256],
                 product[256],
                 serial[256];
                int len;
                handle = usb_open(dev); /* we need to open the device in order
                                         * to query strings */
                if (!handle) {
                    errorCode = USBOPEN_ERR_ACCESS;
                    if (warningsFp != NULL)
                        fprintf(warningsFp,
                                "Warning: cannot open VID=0x%04x PID=0x%04x: %s\n",
                                dev->descriptor.idVendor,
                                dev->descriptor.idProduct, usb_strerror());
                    continue;
                }
                /*
                 * now check whether the names match: 
                 */
                len = vendor[0] = 0;
                if (dev->descriptor.iManufacturer > 0) {
                    len =
                        usbGetStringAscii(handle, dev->descriptor.iManufacturer,
                                          vendor, sizeof(vendor));
                }
                if (len < 0) {
                    errorCode = USBOPEN_ERR_ACCESS;
                    if (warningsFp != NULL)
                        fprintf(warningsFp,
                                "Warning: cannot query manufacturer for VID=0x%04x PID=0x%04x: %s\n",
                                dev->descriptor.idVendor,
                                dev->descriptor.idProduct, usb_strerror());
                } else {
                    errorCode = USBOPEN_ERR_NOTFOUND;
                    /*
                     * printf("seen device from vendor ->%s<-\n", vendor); 
                     */
                    if (shellStyleMatch(vendor, vendorNamePattern)) {
                        len = product[0] = 0;
                        if (dev->descriptor.iProduct > 0) {
                            len =
                                usbGetStringAscii(handle,
                                                  dev->descriptor.iProduct,
                                                  product, sizeof(product));
                        }
                        if (len < 0) {
                            errorCode = USBOPEN_ERR_ACCESS;
                            if (warningsFp != NULL)
                                fprintf(warningsFp,
                                        "Warning: cannot query product for VID=0x%04x PID=0x%04x: %s\n",
                                        dev->descriptor.idVendor,
                                        dev->descriptor.idProduct,
                                        usb_strerror());
                        } else {
                            errorCode = USBOPEN_ERR_NOTFOUND;
                            /*
                             * printf("seen product ->%s<-\n", product); 
                             */
                            if (shellStyleMatch(product, productNamePattern)) {
                                len = serial[0] = 0;
                                if (dev->descriptor.iSerialNumber > 0) {
                                    len =
                                        usbGetStringAscii(handle,
                                                          dev->descriptor.
                                                          iSerialNumber, serial,
                                                          sizeof(serial));
                                }
                                if (len < 0) {
                                    errorCode = USBOPEN_ERR_ACCESS;
                                    if (warningsFp != NULL)
                                        fprintf(warningsFp,
                                                "Warning: cannot query serial for VID=0x%04x PID=0x%04x: %s\n",
                                                dev->descriptor.idVendor,
                                                dev->descriptor.idProduct,
                                                usb_strerror());
                                }
                                if (shellStyleMatch(serial, serialNamePattern)) {
                                    if (printMatchingDevicesFp != NULL) {
                                        if (serial[0] == 0) {
                                            fprintf(printMatchingDevicesFp,
                                                    "VID=0x%04x PID=0x%04x vendor=\"%s\" product=\"%s\"\n",
                                                    dev->descriptor.idVendor,
                                                    dev->descriptor.idProduct,
                                                    vendor, product);
                                        } else {
                                            fprintf(printMatchingDevicesFp,
                                                    "VID=0x%04x PID=0x%04x vendor=\"%s\" product=\"%s\" serial=\"%s\"\n",
                                                    dev->descriptor.idVendor,
                                                    dev->descriptor.idProduct,
                                                    vendor, product, serial);
                                        }
                                    } else {
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }
                usb_close(handle);
                handle = NULL;
            }
        }
        if (handle)             /* we have found a deice */
            break;
    }
    if (handle != NULL) {
        errorCode = 0;
        *device = handle;
    }
    if (printMatchingDevicesFp != NULL) /* never return an error for listing
                                         * only */
        errorCode = 0;
    return errorCode;
}