Example #1
0
/*-----------------------------------------------------------------------------
 * Name      :  usb_list_ports
 * Purpose   :  List available USB ports
 * Inputs    :  p   : array of port structures
 *              max : maximum number of ports in list
 * Outputs   :  <>
 * Return    :  Number of ports or error code
 * -----------------------------------------------------------------------------*/
int usb_list_ports(aps_port_t **p,int max)
{
	const char *usbfs = USBFS;
	int n;
	int i;
	int total;
	libusb_device * dev;


	if (libusb_ctx == 0)
	{
		init_libusb();
	}

	/*list connected devices*/
	n = devcnt;

	if (n <= 0) {
		return 0;
	}

	/*build ports from APS devices*/
	total = 0;

	i = 0;
	while (total < max && (dev = devs[i]) != NULL)
	{
		struct libusb_device_descriptor desc;
		int r;

		r = libusb_get_device_descriptor(dev, &desc);
		if (r < 0)
		{
			fprintf(stderr, "ERROR: failed to get device descriptor");
			libusb_free_device_list(devs, 1);
			libusb_exit(NULL);
			devs = 0;
			devcnt = 0;
			libusb_ctx = 0;
			return APS_USB_DEVICE_NOT_FOUND;
		}

		if (desc.idVendor == APS_VENDOR_ID || desc.idVendor == APS_VENDOR_ID0)
		{
#ifdef DEBUG
			fprintf(stderr, "DEBUG: ok, aps printer found...\n");
#endif
			*p = calloc(1, sizeof(aps_class_t));
			usb_custom(*p);
			(*p)->set.usb.pdev = dev;
			p ++;
			total ++;
		}
		i ++;
	}

#if 0
	for (i=0; i<n && total<max; i++) {
		libusb_device *dev = devs + i;

		if (dev->vendor_id==APS_VENDOR_ID || dev->vendor_id==APS_VENDOR_ID0) {
			*p = aps_create_usb_port_from_address(usbfs,dev->busnum,dev->devnum);

			if (*p!=NULL) {
				p++;
				total++;
			}
		}
	}
#endif

	return total;
}
Example #2
0
static GSList *scan(struct sr_dev_driver *di, GSList *options)
{
	struct drv_context *drvc;
	struct dev_context *devc;
	struct sr_dev_inst *sdi;
	struct sr_usb_dev_inst *usb;
	struct sr_config *src;
	const struct hantek_6xxx_profile *prof;
	GSList *l, *devices, *conn_devices;
	struct libusb_device_descriptor des;
	libusb_device **devlist;
	int i, j;
	const char *conn;
	char connection_id[64];

	drvc = di->context;

	devices = 0;

	conn = NULL;
	for (l = options; l; l = l->next) {
		src = l->data;
		if (src->key == SR_CONF_CONN) {
			conn = g_variant_get_string(src->data, NULL);
			break;
		}
	}
	if (conn)
		conn_devices = sr_usb_find(drvc->sr_ctx->libusb_ctx, conn);
	else
		conn_devices = NULL;

	/* Find all Hantek 60xx devices and upload firmware to all of them. */
	libusb_get_device_list(drvc->sr_ctx->libusb_ctx, &devlist);
	for (i = 0; devlist[i]; i++) {
		if (conn) {
			usb = NULL;
			for (l = conn_devices; l; l = l->next) {
				usb = l->data;
				if (usb->bus == libusb_get_bus_number(devlist[i])
					&& usb->address == libusb_get_device_address(devlist[i]))
					break;
			}
			if (!l)
				/* This device matched none of the ones that
				 * matched the conn specification. */
				continue;
		}

		libusb_get_device_descriptor(devlist[i], &des);

		usb_get_port_path(devlist[i], connection_id, sizeof(connection_id));

		prof = NULL;
		for (j = 0; j < (int)ARRAY_SIZE(dev_profiles); j++) {
			if (des.idVendor == dev_profiles[j].orig_vid
				&& des.idProduct == dev_profiles[j].orig_pid) {
				/* Device matches the pre-firmware profile. */
				prof = &dev_profiles[j];
				sr_dbg("Found a %s %s.", prof->vendor, prof->model);
				sdi = hantek_6xxx_dev_new(prof);
				sdi->connection_id = g_strdup(connection_id);
				devices = g_slist_append(devices, sdi);
				devc = sdi->priv;
				if (ezusb_upload_firmware(drvc->sr_ctx, devlist[i],
						USB_CONFIGURATION, prof->firmware) == SR_OK)
					/* Remember when the firmware on this device was updated. */
					devc->fw_updated = g_get_monotonic_time();
				else
					sr_err("Firmware upload failed.");
				/* Dummy USB address of 0xff will get overwritten later. */
				sdi->conn = sr_usb_dev_inst_new(
						libusb_get_bus_number(devlist[i]), 0xff, NULL);
				break;
			} else if (des.idVendor == dev_profiles[j].fw_vid
				&& des.idProduct == dev_profiles[j].fw_pid) {
				/* Device matches the post-firmware profile. */
				prof = &dev_profiles[j];
				sr_dbg("Found a %s %s.", prof->vendor, prof->model);
				sdi = hantek_6xxx_dev_new(prof);
				sdi->connection_id = g_strdup(connection_id);
				sdi->status = SR_ST_INACTIVE;
				devices = g_slist_append(devices, sdi);
				sdi->inst_type = SR_INST_USB;
				sdi->conn = sr_usb_dev_inst_new(
						libusb_get_bus_number(devlist[i]),
						libusb_get_device_address(devlist[i]), NULL);
				break;
			}
		}
		if (!prof)
			/* Not a supported VID/PID. */
			continue;
	}
	libusb_free_device_list(devlist, 1);

	return devices;
}
Example #3
0
static void *libusb_hid_init(void)
{
   unsigned i, count;
   int ret;
   struct libusb_device **devices;
   libusb_hid_t *hid = (libusb_hid_t*)calloc(1, sizeof(*hid));

   if (!hid)
      goto error;

   ret = libusb_init(&hid->ctx);

   if (ret < 0)
      goto error;

   if (!libusb_has_capability(LIBUSB_CAP_HAS_HOTPLUG))
      goto error;

   hid->slots = pad_connection_init(MAX_USERS);

   if (!hid->slots)
      goto error;

   count = libusb_get_device_list(hid->ctx, &devices);

   for (i = 0; i < count; i++)
   {
      struct libusb_device_descriptor desc;
      libusb_get_device_descriptor(devices[i], &desc);

      if (desc.idVendor > 0 && desc.idProduct > 0)
         add_adapter(hid, devices[i]);
   }

   if (count > 0)
      libusb_free_device_list(devices, 1);

   ret = libusb_hotplug_register_callback(
         hid->ctx,
         (libusb_hotplug_event)(LIBUSB_HOTPLUG_EVENT_DEVICE_ARRIVED |
         LIBUSB_HOTPLUG_EVENT_DEVICE_LEFT),
         (libusb_hotplug_flag)LIBUSB_HOTPLUG_ENUMERATE,
         LIBUSB_HOTPLUG_MATCH_ANY,
         LIBUSB_HOTPLUG_MATCH_ANY,
         LIBUSB_HOTPLUG_MATCH_ANY,
         libusb_hid_hotplug_callback,
         hid,
         &hid->hp);

   if (ret != LIBUSB_SUCCESS)
   {
      RARCH_ERR("Error creating a hotplug callback.\n");
      goto error;
   }

   hid->poll_thread = sthread_create(poll_thread, hid);

   if (!hid->poll_thread)
   {
      RARCH_ERR("Error creating polling thread");
      goto error;
   }

   return hid;

error:
   if (hid)
      libusb_hid_free(hid);
   return NULL;
}
Example #4
0
static libusb_device_handle *hmcfgusb_find(int vid, int pid, char *serial) {
	libusb_device_handle *devh = NULL;
	libusb_device **list;
	ssize_t cnt;
	ssize_t i;
	int err;

	cnt = libusb_get_device_list(NULL, &list);
	if (cnt < 0) {
		fprintf(stderr, "Can't get USB device list: %d\n", (int)cnt);
		return NULL;
	}

	for (i = 0; i < cnt; i++){
		struct libusb_device_descriptor desc;

		err = libusb_get_device_descriptor(list[i], &desc);
		if (err)
			continue;

		if ((desc.idVendor == vid) && (desc.idProduct == pid)) {
			libusb_device *dev = list[i];

			err = libusb_open(dev, &devh);
			if (err) {
				fprintf(stderr, "Can't open device: %s\n", usb_strerror(err));
				libusb_free_device_list(list, 1);
				return NULL;
			}

			if (serial) {
				if (desc.iSerialNumber > 0) {
					uint8_t devSerial[256];
					err = libusb_get_string_descriptor_ascii(devh, desc.iSerialNumber, devSerial, sizeof(devSerial));
					if (err < 0) {
						fprintf(stderr, "Can't read serial-number: %s\n", usb_strerror(err));
						libusb_close(devh);
						libusb_free_device_list(list, 1);
						return NULL;
					}
					if (strcmp((char*)devSerial, (char*)serial)) {
						libusb_close(devh);
						continue;
					}
				} else {
					libusb_close(devh);
					continue;
				}
			}

			err = libusb_detach_kernel_driver(devh, INTERFACE);
			if ((err != 0) && (err != LIBUSB_ERROR_NOT_FOUND)) {
				fprintf(stderr, "Can't detach kernel driver: %s\n", usb_strerror(err));
				libusb_close(devh);
				libusb_free_device_list(list, 1);
				return NULL;
			}

			err = libusb_claim_interface(devh, INTERFACE);
			if ((err != 0)) {
				fprintf(stderr, "Can't claim interface: %s\n", usb_strerror(err));
				libusb_close(devh);
				libusb_free_device_list(list, 1);
				return NULL;
			}

			libusb_free_device_list(list, 0);
			return devh;
		}

	}

	libusb_free_device_list(list, 1);
	return NULL;
}
Example #5
0
static GSList *scan(GSList *options)
{
	struct sr_dev_inst *sdi;
	struct sr_channel *ch;
	struct drv_context *drvc;
	struct dev_context *devc;
	const struct zp_model *prof;
	struct libusb_device_descriptor des;
	libusb_device **devlist;
	GSList *devices;
	int ret, devcnt, i, j;

	(void)options;

	drvc = di->priv;

	devices = NULL;

	/* Find all ZEROPLUS analyzers and add them to device list. */
	devcnt = 0;
	libusb_get_device_list(drvc->sr_ctx->libusb_ctx, &devlist); /* TODO: Errors. */

	for (i = 0; devlist[i]; i++) {
		ret = libusb_get_device_descriptor(devlist[i], &des);
		if (ret != 0) {
			sr_err("Failed to get device descriptor: %s.",
			       libusb_error_name(ret));
			continue;
		}

		prof = NULL;
		for (j = 0; j < zeroplus_models[j].vid; j++) {
			if (des.idVendor == zeroplus_models[j].vid &&
				des.idProduct == zeroplus_models[j].pid) {
				prof = &zeroplus_models[j];
			}
		}
		/* Skip if the device was not found. */
		if (!prof)
			continue;
		sr_info("Found ZEROPLUS %s.", prof->model_name);

		/* Register the device with libsigrok. */
		if (!(sdi = sr_dev_inst_new(devcnt, SR_ST_INACTIVE,
				VENDOR_NAME, prof->model_name, NULL))) {
			sr_err("%s: sr_dev_inst_new failed", __func__);
			return NULL;
		}
		sdi->driver = di;

		/* Allocate memory for our private driver context. */
		if (!(devc = g_try_malloc0(sizeof(struct dev_context)))) {
			sr_err("Device context malloc failed.");
			return NULL;
		}

		sdi->priv = devc;
		devc->prof = prof;
		devc->num_channels = prof->channels;
#ifdef ZP_EXPERIMENTAL
		devc->max_sample_depth = 128 * 1024;
		devc->max_samplerate = 200;
#else
		devc->max_sample_depth = prof->sample_depth * 1024;
		devc->max_samplerate = prof->max_sampling_freq;
#endif
		devc->max_samplerate *= SR_MHZ(1);
		devc->memory_size = MEMORY_SIZE_8K;
		// memset(devc->trigger_buffer, 0, NUM_TRIGGER_STAGES);

		/* Fill in channellist according to this device's profile. */
		for (j = 0; j < devc->num_channels; j++) {
			if (!(ch = sr_channel_new(j, SR_CHANNEL_LOGIC, TRUE,
					channel_names[j])))
				return NULL;
			sdi->channels = g_slist_append(sdi->channels, ch);
		}

		devices = g_slist_append(devices, sdi);
		drvc->instances = g_slist_append(drvc->instances, sdi);
		sdi->inst_type = SR_INST_USB;
		sdi->conn = sr_usb_dev_inst_new(
			libusb_get_bus_number(devlist[i]),
			libusb_get_device_address(devlist[i]), NULL);
		devcnt++;

	}
	libusb_free_device_list(devlist, 1);

	return devices;
}
int main(int argc, char **argv) {

   printf("Arguments: %i\n",argc);
   int arg;
   for (arg = 0 ; arg < argc ; arg++)
      printf("  %i: %s;\n", arg,argv[arg]);
   if ((argc > 1) && argv[1][0] == '1') {
      test = 1;
      printf("Set test\n");
   }

   libusb_device **list;
   //libusb_device *accel;
   libusb_context *ctx = NULL;


   libusb_init(&ctx);
   libusb_set_debug(ctx,3);
   names_init("./usb.ids");

   ssize_t cnt = libusb_get_device_list(ctx,&list);

   ssize_t i = 0;
   int err = 0;

   if (cnt < 0) {
      printf("Error getting usb device list\n");
      exit(1);
   }

   for (i = 0 ; i < cnt ; i++) {
      libusb_device *device = list[i];
      struct libusb_device_descriptor desc;
      err = libusb_get_device_descriptor(device,&desc);
      if (err < 0)
         printf("Error getting device descriptor: %i\n",err);
      else {
         if (desc.idVendor == VENDOR_ID && desc.idProduct == PRODUCT_ID) {
            printf("Device Found: idVendor = %xh, idProduct = %xh\n",desc.idVendor, desc.idProduct);
            printdev(device);
            int reattach = 0;
            libusb_device_handle *handle;
            int r = libusb_open(device,&handle);
            if (r < 0){
               printf("Error opening device: %i\n",r);
               exit(1);
            }

            if (libusb_kernel_driver_active(handle,0)) {
               printf("Device already has a kernel driver\n");
               r = libusb_detach_kernel_driver(handle,0);
               if (r < 0) {
                  printf("Unable to detach kernel driver: %i\n",r);
                  goto CLOSE;
               }
               reattach = 1;
            }

            if (libusb_claim_interface(handle,0) == 0) {
               printf("Claimed Device\n");
               dump_hid(device,handle);

               if (test) {
                  printf("Beginning report testing\n");
                  test_report(handle);
               }
            }
CLOSE:

            libusb_release_interface(handle, 0);
            if (reattach) {
               r = libusb_attach_kernel_driver(handle,0);
               if (r < 0) {
                  printf("Failed to reattach kernel driver: %i\n",r);
                  switch (-1) {
                     case LIBUSB_ERROR_IO: 
                        printf("I/O error\n");
                        break;
                     case LIBUSB_ERROR_ACCESS:
                        printf("Access Denied\n");
                        break;
                     case LIBUSB_ERROR_NOT_FOUND:
                        printf("Kernel driver wasn't active\n");
                        break;
                     case LIBUSB_ERROR_INVALID_PARAM:
                        printf("Interface doesn't exist\n");
                        break;
                     case LIBUSB_ERROR_NO_DEVICE:
                        printf("Device was disconnected\n");
                        break;
                     case LIBUSB_ERROR_BUSY:
                        printf("Interface is still claimed\n");
                        break;
                     case LIBUSB_ERROR_TIMEOUT:
                        printf("Operation timed out\n");
                        break;
                     case LIBUSB_ERROR_OVERFLOW:
                        printf("Overflow\n");
                        break;
                     case LIBUSB_ERROR_PIPE:
                        printf("Pipe Error\n");
                        break;
                     case LIBUSB_ERROR_INTERRUPTED:
                        printf("System call interrupted\n");
                        break;
                     case LIBUSB_ERROR_NO_MEM:
                        printf("Insufficient Memory\n");
                        break;
                     case LIBUSB_ERROR_NOT_SUPPORTED:
                        printf("Operation not supported\n");
                        break;
                     default:
                        printf("Some other error occured\n");
                        break;
                  }
               }
            }
            libusb_close(handle);
         }
      }
   }
   libusb_free_device_list(list,1);
   libusb_exit(ctx);
   exit(err);
}
Example #7
0
struct hid_device_info  HID_API_EXPORT *hid_enumerate(unsigned short vendor_id, unsigned short product_id)
{
    libusb_device **devs;
    libusb_device *dev;
    libusb_device_handle *handle;
    ssize_t num_devs;
    int i = 0;

    struct hid_device_info *root = NULL; // return object
    struct hid_device_info *cur_dev = NULL;

    setlocale(LC_ALL,"");

    if (!initialized)
	hid_init();

    num_devs = libusb_get_device_list(NULL, &devs);

    if (num_devs < 0)
	return NULL;
    while ((dev = devs[i++]) != NULL) {
	struct libusb_device_descriptor desc;
	struct libusb_config_descriptor *conf_desc = NULL;
	int j, k;
	int interface_num = 0;

	int res = libusb_get_device_descriptor(dev, &desc);
	unsigned short dev_vid = desc.idVendor;
	unsigned short dev_pid = desc.idProduct;

	/* HID's are defined at the interface level. */
	if (desc.bDeviceClass != LIBUSB_CLASS_PER_INTERFACE)
	    continue;

	res = libusb_get_active_config_descriptor(dev, &conf_desc);

	if (res < 0)
	    libusb_get_config_descriptor(dev, 0, &conf_desc);
	if (conf_desc) {
	    for (j = 0; j < conf_desc->bNumInterfaces; j++) {
		const struct libusb_interface *intf = &conf_desc->interface[j];
		for (k = 0; k < intf->num_altsetting; k++) {
		    const struct libusb_interface_descriptor *intf_desc;
		    intf_desc = &intf->altsetting[k];
		    if (intf_desc->bInterfaceClass == LIBUSB_CLASS_HID) {
			interface_num = intf_desc->bInterfaceNumber;

			/* Check the VID/PID against the arguments */
			if ((vendor_id == 0x0 && product_id == 0x0) ||
				(vendor_id == dev_vid && product_id == dev_pid)) {
			    struct hid_device_info *tmp;

			    /* VID/PID match. Create the record. */
			    tmp = calloc(1, sizeof(struct hid_device_info));
			    if (cur_dev) {
				cur_dev->next = tmp;
			    }
			    else {
				root = tmp;
			    }
			    cur_dev = tmp;

			    /* Fill out the record */
			    cur_dev->next = NULL;
			    cur_dev->path = make_path(dev, interface_num);
			    
			    res = libusb_open(dev, &handle);
			    
			    if (res >= 0) { 
				/* Serial Number */
				if (desc.iSerialNumber > 0)
				    cur_dev->serial_number =
					get_usb_string(handle, desc.iSerialNumber);

				/* Manufacturer and Product strings */
				if (desc.iManufacturer > 0)
				    cur_dev->manufacturer_string =
					get_usb_string(handle, desc.iManufacturer);
				if (desc.iProduct > 0)
				    cur_dev->product_string =
					get_usb_string(handle, desc.iProduct);

#ifdef INVASIVE_GET_USAGE
				/*
				   This section is removed because it is too
				   invasive on the system. Getting a Usage Page
				   and Usage requires parsing the HID Report
				   descriptor. Getting a HID Report descriptor
				   involves claiming the interface. Claiming the
				   interface involves detaching the kernel driver.
				   Detaching the kernel driver is hard on the system
				   because it will unclaim interfaces (if another
				   app has them claimed) and the re-attachment of
				   the driver will sometimes change /dev entry names.
				   It is for these reasons that this section is
#if 0. For composite devices, use the interface
field in the hid_device_info struct to distinguish
between interfaces. */
				int detached = 0;
				unsigned char data[256];

				/* Usage Page and Usage */
				res = libusb_kernel_driver_active(handle, interface_num);
				if (res == 1) {
				    res = libusb_detach_kernel_driver(handle, interface_num);
				    if (res < 0)
					LOG("Couldn't detach kernel driver, even though a kernel driver was attached.");
				    else
					detached = 1;
				}
				res = libusb_claim_interface(handle, interface_num);
				if (res >= 0) {
				    /* Get the HID Report Descriptor. */
				    res = libusb_control_transfer(handle, LIBUSB_ENDPOINT_IN|LIBUSB_RECIPIENT_INTERFACE, LIBUSB_REQUEST_GET_DESCRIPTOR, (LIBUSB_DT_REPORT << 8)|interface_num, 0, data, sizeof(data), 5000);
				    if (res >= 0) {
					unsigned short page=0, usage=0;
					/* Parse the usage and usage page
					   out of the report descriptor. */
					get_usage(data, res,  &page, &usage);
					cur_dev->usage_page = page;
					cur_dev->usage = usage;
				    }
				    else
					LOG("libusb_control_transfer() for getting the HID report failed with %d\n", res);

				    /* Release the interface */
				    res = libusb_release_interface(handle, interface_num);
				    if (res < 0)
					LOG("Can't release the interface.\n");
				}
				else
				    LOG("Can't claim interface %d\n", res);

				/* Re-attach kernel driver if necessary. */
				if (detached) {
				    res = libusb_attach_kernel_driver(handle, interface_num);
				    if (res < 0)
					LOG("Couldn't re-attach kernel driver.\n");
				}
#endif /*******************/

				libusb_close(handle);
			    }
			    /* VID/PID */
			    cur_dev->vendor_id = dev_vid;
			    cur_dev->product_id = dev_pid;

			    /* Release Number */
			    cur_dev->release_number = desc.bcdDevice;

			    /* Interface Number */
			    cur_dev->interface_number = interface_num;
			}
		    }
		} /* altsettings */
	    } /* interfaces */
	    libusb_free_config_descriptor(conf_desc);
	}
    }

    libusb_free_device_list(devs, 1);

    return root;
}
Example #8
0
static GSList *scan(struct sr_dev_driver *di, GSList *options)
{
	struct sr_dev_inst *sdi;
	struct drv_context *drvc;
	struct dev_context *devc;
	const struct zp_model *prof;
	struct libusb_device_descriptor des;
	struct libusb_device_handle *hdl;
	libusb_device **devlist;
	GSList *devices;
	int ret, i, j;
	char serial_num[64], connection_id[64];

	(void)options;

	drvc = di->priv;

	devices = NULL;

	/* Find all ZEROPLUS analyzers and add them to device list. */
	libusb_get_device_list(drvc->sr_ctx->libusb_ctx, &devlist); /* TODO: Errors. */

	for (i = 0; devlist[i]; i++) {
		ret = libusb_get_device_descriptor(devlist[i], &des);
		if (ret != 0) {
			sr_err("Failed to get device descriptor: %s.",
			       libusb_error_name(ret));
			continue;
		}

		if ((ret = libusb_open(devlist[i], &hdl)) < 0)
			continue;

		if (des.iSerialNumber == 0) {
			serial_num[0] = '\0';
		} else if ((ret = libusb_get_string_descriptor_ascii(hdl,
				des.iSerialNumber, (unsigned char *) serial_num,
				sizeof(serial_num))) < 0) {
			sr_warn("Failed to get serial number string descriptor: %s.",
				libusb_error_name(ret));
			continue;
		}

		libusb_close(hdl);

		usb_get_port_path(devlist[i], connection_id, sizeof(connection_id));

		prof = NULL;
		for (j = 0; j < zeroplus_models[j].vid; j++) {
			if (des.idVendor == zeroplus_models[j].vid &&
				des.idProduct == zeroplus_models[j].pid) {
				prof = &zeroplus_models[j];
			}
		}
		/* Skip if the device was not found. */
		if (!prof)
			continue;
		sr_info("Found ZEROPLUS %s.", prof->model_name);

		/* Register the device with libsigrok. */
		sdi = g_malloc0(sizeof(struct sr_dev_inst));
		sdi->status = SR_ST_INACTIVE;
		sdi->vendor = g_strdup(VENDOR_NAME);
		sdi->model = g_strdup(prof->model_name);
		sdi->driver = di;
		sdi->serial_num = g_strdup(serial_num);
		sdi->connection_id = g_strdup(connection_id);

		/* Allocate memory for our private driver context. */
		devc = g_malloc0(sizeof(struct dev_context));
		sdi->priv = devc;
		devc->prof = prof;
		devc->num_channels = prof->channels;
#ifdef ZP_EXPERIMENTAL
		devc->max_sample_depth = 128 * 1024;
		devc->max_samplerate = 200;
#else
		devc->max_sample_depth = prof->sample_depth * 1024;
		devc->max_samplerate = prof->max_sampling_freq;
#endif
		devc->max_samplerate *= SR_MHZ(1);
		devc->memory_size = MEMORY_SIZE_8K;
		// memset(devc->trigger_buffer, 0, NUM_TRIGGER_STAGES);

		/* Fill in channellist according to this device's profile. */
		for (j = 0; j < devc->num_channels; j++)
			sr_channel_new(sdi, j, SR_CHANNEL_LOGIC, TRUE,
					channel_names[j]);

		devices = g_slist_append(devices, sdi);
		drvc->instances = g_slist_append(drvc->instances, sdi);
		sdi->inst_type = SR_INST_USB;
		sdi->conn = sr_usb_dev_inst_new(
			libusb_get_bus_number(devlist[i]),
			libusb_get_device_address(devlist[i]), NULL);
	}
	libusb_free_device_list(devlist, 1);

	return devices;
}
Example #9
0
static int test_device(uint16_t vid, uint16_t pid)
{
	libusb_device_handle *handle;
	libusb_device *dev;
	uint8_t bus, port_path[8];
	struct libusb_bos_descriptor *bos_desc;
	struct libusb_config_descriptor *conf_desc;
	const struct libusb_endpoint_descriptor *endpoint;
	int i, j, k, r;
	int iface, nb_ifaces, first_iface = -1;
	struct libusb_device_descriptor dev_desc;
	const char* speed_name[5] = { "Unknown", "1.5 Mbit/s (USB LowSpeed)", "12 Mbit/s (USB FullSpeed)",
		"480 Mbit/s (USB HighSpeed)", "5000 Mbit/s (USB SuperSpeed)"};
	char string[128];
	uint8_t string_index[3];	// indexes of the string descriptors
	uint8_t endpoint_in = 0, endpoint_out = 0;	// default IN and OUT endpoints

	printf("Opening device %04X:%04X...\n", vid, pid);
	handle = libusb_open_device_with_vid_pid(NULL, vid, pid);

	if (handle == NULL) {
		perr("  Failed.\n");
		return -1;
	}

	dev = libusb_get_device(handle);
	bus = libusb_get_bus_number(dev);
	if (extra_info) {
		r = libusb_get_port_numbers(dev, port_path, sizeof(port_path));
		if (r > 0) {
			printf("\nDevice properties:\n");
			printf("        bus number: %d\n", bus);
			printf("         port path: %d", port_path[0]);
			for (i=1; i<r; i++) {
				printf("->%d", port_path[i]);
			}
			printf(" (from root hub)\n");
		}
		r = libusb_get_device_speed(dev);
		if ((r<0) || (r>4)) r=0;
		printf("             speed: %s\n", speed_name[r]);
	}

	printf("\nReading device descriptor:\n");
	CALL_CHECK(libusb_get_device_descriptor(dev, &dev_desc));
	printf("            length: %d\n", dev_desc.bLength);
	printf("      device class: %d\n", dev_desc.bDeviceClass);
	printf("               S/N: %d\n", dev_desc.iSerialNumber);
	printf("           VID:PID: %04X:%04X\n", dev_desc.idVendor, dev_desc.idProduct);
	printf("         bcdDevice: %04X\n", dev_desc.bcdDevice);
	printf("   iMan:iProd:iSer: %d:%d:%d\n", dev_desc.iManufacturer, dev_desc.iProduct, dev_desc.iSerialNumber);
	printf("          nb confs: %d\n", dev_desc.bNumConfigurations);
	// Copy the string descriptors for easier parsing
	string_index[0] = dev_desc.iManufacturer;
	string_index[1] = dev_desc.iProduct;
	string_index[2] = dev_desc.iSerialNumber;

	printf("\nReading BOS descriptor: ");
	if (libusb_get_bos_descriptor(handle, &bos_desc) == LIBUSB_SUCCESS) {
		printf("%d caps\n", bos_desc->bNumDeviceCaps);
		for (i = 0; i < bos_desc->bNumDeviceCaps; i++)
			print_device_cap(bos_desc->dev_capability[i]);
		libusb_free_bos_descriptor(bos_desc);
	} else {
		printf("no descriptor\n");
	}

	printf("\nReading first configuration descriptor:\n");
	CALL_CHECK(libusb_get_config_descriptor(dev, 0, &conf_desc));
	nb_ifaces = conf_desc->bNumInterfaces;
	printf("             nb interfaces: %d\n", nb_ifaces);
	if (nb_ifaces > 0)
		first_iface = conf_desc->usb_interface[0].altsetting[0].bInterfaceNumber;
	for (i=0; i<nb_ifaces; i++) {
		printf("              interface[%d]: id = %d\n", i,
			conf_desc->usb_interface[i].altsetting[0].bInterfaceNumber);
		for (j=0; j<conf_desc->usb_interface[i].num_altsetting; j++) {
			printf("interface[%d].altsetting[%d]: num endpoints = %d\n",
				i, j, conf_desc->usb_interface[i].altsetting[j].bNumEndpoints);
			printf("   Class.SubClass.Protocol: %02X.%02X.%02X\n",
				conf_desc->usb_interface[i].altsetting[j].bInterfaceClass,
				conf_desc->usb_interface[i].altsetting[j].bInterfaceSubClass,
				conf_desc->usb_interface[i].altsetting[j].bInterfaceProtocol);
			if ( (conf_desc->usb_interface[i].altsetting[j].bInterfaceClass == LIBUSB_CLASS_MASS_STORAGE)
			  && ( (conf_desc->usb_interface[i].altsetting[j].bInterfaceSubClass == 0x01)
			  || (conf_desc->usb_interface[i].altsetting[j].bInterfaceSubClass == 0x06) )
			  && (conf_desc->usb_interface[i].altsetting[j].bInterfaceProtocol == 0x50) ) {
				// Mass storage devices that can use basic SCSI commands
				test_mode = USE_SCSI;
			}
			for (k=0; k<conf_desc->usb_interface[i].altsetting[j].bNumEndpoints; k++) {
				struct libusb_ss_endpoint_companion_descriptor *ep_comp = NULL;
				endpoint = &conf_desc->usb_interface[i].altsetting[j].endpoint[k];
				printf("       endpoint[%d].address: %02X\n", k, endpoint->bEndpointAddress);
				// Use the first interrupt or bulk IN/OUT endpoints as default for testing
				if ((endpoint->bmAttributes & LIBUSB_TRANSFER_TYPE_MASK) & (LIBUSB_TRANSFER_TYPE_BULK | LIBUSB_TRANSFER_TYPE_INTERRUPT)) {
					if (endpoint->bEndpointAddress & LIBUSB_ENDPOINT_IN) {
						if (!endpoint_in)
							endpoint_in = endpoint->bEndpointAddress;
					} else {
						if (!endpoint_out)
							endpoint_out = endpoint->bEndpointAddress;
					}
				}
				printf("           max packet size: %04X\n", endpoint->wMaxPacketSize);
				printf("          polling interval: %02X\n", endpoint->bInterval);
				libusb_get_ss_endpoint_companion_descriptor(NULL, endpoint, &ep_comp);
				if (ep_comp) {
					printf("                 max burst: %02X   (USB 3.0)\n", ep_comp->bMaxBurst);
					printf("        bytes per interval: %04X (USB 3.0)\n", ep_comp->wBytesPerInterval);
					libusb_free_ss_endpoint_companion_descriptor(ep_comp);
				}
			}
		}
	}
	libusb_free_config_descriptor(conf_desc);

	libusb_set_auto_detach_kernel_driver(handle, 1);
	for (iface = 0; iface < nb_ifaces; iface++)
	{
		printf("\nClaiming interface %d...\n", iface);
		r = libusb_claim_interface(handle, iface);
		if (r != LIBUSB_SUCCESS) {
			perr("   Failed.\n");
		}
	}

	printf("\nReading string descriptors:\n");
	for (i=0; i<3; i++) {
		if (string_index[i] == 0) {
			continue;
		}
		if (libusb_get_string_descriptor_ascii(handle, string_index[i], (unsigned char*)string, 128) >= 0) {
			printf("   String (0x%02X): \"%s\"\n", string_index[i], string);
		}
	}
	// Read the OS String Descriptor
	if (libusb_get_string_descriptor_ascii(handle, 0xEE, (unsigned char*)string, 128) >= 0) {
		printf("   String (0x%02X): \"%s\"\n", 0xEE, string);
		// If this is a Microsoft OS String Descriptor,
		// attempt to read the WinUSB extended Feature Descriptors
		if (strncmp(string, "MSFT100", 7) == 0)
			read_ms_winsub_feature_descriptors(handle, string[7], first_iface);
	}

	switch(test_mode) {
	case USE_PS3:
		CALL_CHECK(display_ps3_status(handle));
		break;
	case USE_XBOX:
		CALL_CHECK(display_xbox_status(handle));
		CALL_CHECK(set_xbox_actuators(handle, 128, 222));
		msleep(2000);
		CALL_CHECK(set_xbox_actuators(handle, 0, 0));
		break;
	case USE_HID:
		test_hid(handle, endpoint_in);
		break;
	case USE_SCSI:
		CALL_CHECK(test_mass_storage(handle, endpoint_in, endpoint_out));
	case USE_GENERIC:
		break;
	}

	printf("\n");
	for (iface = 0; iface<nb_ifaces; iface++) {
		printf("Releasing interface %d...\n", iface);
		libusb_release_interface(handle, iface);
	}

	printf("Closing device...\n");
	libusb_close(handle);

	return 0;
}
Example #10
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;
	}
Example #11
0
int Command(AlienFxHandle_t *fx, char **cmdv) 
{
    int cmdc = CommandCount(cmdv); // cmdv[cmdc] == (char*)0
	if(debug)
		fprintf(stderr, "command %s with cmdc %d\n", *cmdv, cmdc);
    if( ! strcmp("color", cmdv[0])) {
        if(cmdc < 4) {
            fputs("error: too few arguments to command \"color\"\n", stderr);
            return 0;
        } else {
            int block = BLOCK_AC_POWER; // int block = BLOCK_LOAD_ON_BOOT 
			char *all[] = { "all", 0 };
			unsigned int region = LightMask(fx, all);
            int r = 0, g = 0, b = 0;
            if(   (1 == sscanf(cmdv[1], "%d", &r))
               && (1 == sscanf(cmdv[2], "%d", &g))
               && (1 == sscanf(cmdv[3], "%d", &b)))
            {
                if(cmdc > 4)
					region = LightMask(fx, & cmdv[4]);
				if(debug)
					fprintf(stderr, "command: color %d %d %d %x\n",
							r,g,b, region);
                Reset(fx->usb_handle, RESET_ALL_LIGHTS_ON);
				/* apparently some types may need a brief pause here */
				usleep(fx->info->post_reset_delay);
                ColorSet(fx->usb_handle, block, region, r, g, b); 
                Loop(fx->usb_handle);       
                SendAndExec(fx->usb_handle);
            }
        }
	} else if( ! strcmp("info", cmdv[0])) {
		if(verbose) {
			printf("  idVendor  %#6x \n", fx->info->idVendor);
			printf("  idProduct %#6x %s\n",
				   fx->info->idProduct, fx->info->name);
		}
		unsigned int i;
		unsigned int primitives = 0;
		unsigned int composites = 0;
		for(i = 0 ; i < fx->info->lightsCount ; ++i)
			if(fx->info->lights[i].is_composite)
				++composites;
			else
				++primitives;
		printf("  light primitives %d\n", primitives);
		printf("  light composites %d\n", composites);
		printf("  region type      name\n");
		printf("  ------ --------- ----\n");
		for(i = 0 ; i < fx->info->lightsCount ; ++i)
			printf("  %#6x %s %s\n",
				   fx->info->lights[i].id,
				   fx->info->lights[i].is_composite ? "composite" : "primitive",
				   fx->info->lights[i].name);
		if(debug) {
			struct libusb_device *usb_dev = 0;
			struct libusb_device_descriptor usb_desc;
			if(   (usb_dev = libusb_get_device(fx->usb_handle))
			   && (0 == libusb_get_device_descriptor(usb_dev, & usb_desc)))
			{
				printf("  bLength %d\n",            usb_desc.bLength);
				printf("  bDescriptorType %d\n",    usb_desc.bDescriptorType);
				printf("  bcdUSB %d\n",             usb_desc.bcdUSB);
				printf("  bDeviceClass %d\n",       usb_desc.bDeviceClass);
				printf("  bDeviceSubClass %d\n",    usb_desc.bDeviceSubClass);
				printf("  bDeviceProtocol %d\n",    usb_desc.bDeviceProtocol);
				printf("  bMaxPacketSize0 %d\n",    usb_desc.bMaxPacketSize0);
				printf("  idVendor %#x\n",          usb_desc.idVendor);
				printf("  idProduct %#x\n",         usb_desc.idProduct);
				printf("  bcdDevice %d\n",          usb_desc.bcdDevice);
				printf("  iManufacturer %#x\n",     usb_desc.iManufacturer);
				printf("  iProduct %#x\n",          usb_desc.iProduct);
				printf("  iSerialNumber %#x\n",     usb_desc.iSerialNumber);
				printf("  bNumConfigurations %d\n", usb_desc.bNumConfigurations);
			}
		}
    } else {
		fprintf(stderr, "unrecognized command \"%s\"\n", cmdv[0]);
		Syntax(stderr);
	}
    return 1;
}
Example #12
0
// Find the device, and set up to read it periodically, then send 
// the data out stdout so another process can pick it up and do
// something reasonable with it.
// 
int main(int argc, char **argv)
{
    char *usage = {"usage: %s -u -n\n"};
    int libusbDebug = 0; //This will turn on the DEBUG for libusb
    int noisy = 0;       //This will print the packets as they come in
    libusb_device **devs;
    int r, err, c;
    ssize_t cnt;
    
    while ((c = getopt (argc, argv, "unh")) != -1)
        switch (c){
            case 'u':
                libusbDebug = 1;
                break;
            case 'n':
                noisy = 1;
                break;
            case 'h':
                fprintf(stderr, usage, argv[0]);
            case '?':
                exit(1);
            default:
                exit(1);
       }
    fprintf(stderr,"%s Starting ... ",argv[0]);
    fprintf(stderr,"libusbDebug = %d, noisy = %d\n", libusbDebug, noisy);
    // The Pi linker can give you fits.  If you get a linker error on
    // the next line, set LD_LIBRARY_PATH to /usr/local/lib 
    fprintf(stderr,"This is not an error!! Checking linker, %s\n", libusb_strerror(0));

    if (signal(SIGINT, sig_handler) == SIG_ERR)
        fprintf(stderr,"Couldn't set up signal handler\n"); 
    err = libusb_init(NULL);
    if (err < 0){
        fprintf(stderr,"Couldn't init usblib, %s\n", libusb_strerror(err));
        exit(1);
    }
    // This is where you can get debug output from libusb.
    // just set it to LIBUSB_LOG_LEVEL_DEBUG
    if (libusbDebug)
        libusb_set_debug(NULL, LIBUSB_LOG_LEVEL_DEBUG);
    else
        libusb_set_debug(NULL, LIBUSB_LOG_LEVEL_INFO);

    
    cnt = libusb_get_device_list(NULL, &devs);
    if (cnt < 0){
        fprintf(stderr,"Couldn't get device list, %s\n", libusb_strerror(err));
        exit(1);
    }
    // go get the device; the device handle is saved in weatherStation struct.
    if (!findDevice(devs)){
        fprintf(stderr,"Couldn't find the device\n");
        exit(1);
    }
    // Now I've found the weather station and can start to try stuff
    // So, I'll get the device descriptor
    struct libusb_device_descriptor deviceDesc;
    err = libusb_get_device_descriptor(weatherStation.device, &deviceDesc);
    if (err){
        fprintf(stderr,"Couldn't get device descriptor, %s\n", libusb_strerror(err));
        exit(1);
    }
    fprintf(stderr,"got the device descriptor back\n");
    
    // Open the device and save the handle in the weatherStation struct
    err = libusb_open(weatherStation.device, &weatherStation.handle);
    if (err){
        fprintf(stderr,"Open failed, %s\n", libusb_strerror(err));
        closeUpAndLeave();    }
    fprintf(stderr,"I was able to open it\n");
    // Now that it's opened, I can free the list of all devices
    libusb_free_device_list(devs, 1); // Documentation says to get rid of the list
                                      // Once I have the device I need
    fprintf(stderr,"Released the device list\n");
    err = libusb_set_auto_detach_kernel_driver(weatherStation.handle, 1);
    if(err){
        fprintf(stderr,"Some problem with detach %s\n", libusb_strerror(err));
        closeUpAndLeave();
    }
    int activeConfig;
    err =libusb_get_configuration(weatherStation.handle, &activeConfig);
    if (err){
        fprintf(stderr,"Can't get current active configuration, %s\n", libusb_strerror(err));;
        closeUpAndLeave();
    }
    fprintf(stderr,"Currently active configuration is %d\n", activeConfig);
    if(activeConfig != 1){
        err = libusb_set_configuration  (weatherStation.handle, 1);
        if (err){
            fprintf(stderr,"Cannot set configuration, %s\n", libusb_strerror(err));;
        closeUpAndLeave();
        }
        fprintf(stderr,"Just did the set configuration\n");
    }
    
    err = libusb_claim_interface(weatherStation.handle, 0); //claim interface 0 (the first) of device (mine had just 1)
    if(err) {
        fprintf(stderr,"Cannot claim interface, %s\n", libusb_strerror(err));
        closeUpAndLeave();
    }
    fprintf(stderr,"Claimed Interface\n");
    // I don't want to just hang up and read the reports as fast as I can, so
    // I'll space them out a bit.  It's weather, and it doesn't change very fast.
    sleep(1);
    fprintf(stderr,"Setting the device 'idle' before starting reads\n");
    err = libusb_control_transfer(weatherStation.handle, 
        0x21, 0x0a, 0, 0, 0, 0, 1000);
    sleep(1);
    int tickcounter= 0;
    fprintf(stderr,"Starting reads\n");
    while(1){
        sleep(1);
        if(tickcounter++ % 10 == 0){
            getit(1, noisy);
        }
        if(tickcounter % 30 == 0){
            getit(2, noisy);
        }
        if (tickcounter % 15 == 0){
            showit();
        }
    }
}
Example #13
0
int usb_init(int usb_number, e_controller_type type)
{
  int ret = -1;
  int dev_i;

  struct usb_state* state = usb_states+usb_number;

  if(!controller[type].vendor || !controller[type].product)
  {
    gprintf(_("no pass-through device is needed\n"));
    return 0;
  }

  usb_state_indexes[usb_number] = usb_number;

  memset(state, 0x00, sizeof(*state));
  state->joystick_id = -1;
  state->type = type;
  state->ack = 1;

  if(!ctx)
  {
    ret = libusb_init(&ctx);
    if(ret != LIBUSB_SUCCESS)
    {
      fprintf(stderr, "libusb_init: %s.\n", libusb_strerror(ret));
      return -1;
    }
  }

  if(!devs)
  {
    cnt = libusb_get_device_list(ctx, &devs);
    if(cnt < 0)
    {
      fprintf(stderr, "libusb_get_device_list: %s.\n", libusb_strerror(cnt));
      return -1;
    }
  }

  for(dev_i=0; dev_i<cnt; ++dev_i)
  {
    struct libusb_device_descriptor desc;
    ret = libusb_get_device_descriptor(devs[dev_i], &desc);
    if(!ret)
    {
      if(desc.idVendor == controller[type].vendor && desc.idProduct == controller[type].product)
      {
        libusb_device_handle* devh;
        ret = libusb_open(devs[dev_i], &devh);
        if(ret != LIBUSB_SUCCESS)
        {
          fprintf(stderr, "libusb_open: %s.\n", libusb_strerror(ret));
          return -1;
        }
        else
        {
          ret = libusb_reset_device(devh);
          if(ret != LIBUSB_SUCCESS)
          {
            fprintf(stderr, "libusb_reset_device: %s.\n", libusb_strerror(ret));
            libusb_close(devh);
            return -1;
          }

#if defined(LIBUSB_API_VERSION) || defined(LIBUSBX_API_VERSION)
          libusb_set_auto_detach_kernel_driver(devh, 1);
#else
#ifndef WIN32
          ret = libusb_kernel_driver_active(devh, 0);
          if(ret == 1)
          {
            ret = libusb_detach_kernel_driver(devh, 0);
            if(ret != LIBUSB_SUCCESS)
            {
              fprintf(stderr, "libusb_detach_kernel_driver: %s.\n", libusb_strerror(ret));
              libusb_close(devh);
              return -1;
            }
          }
          else if(ret != LIBUSB_SUCCESS)
          {
            fprintf(stderr, "libusb_kernel_driver_active: %s.\n", libusb_strerror(ret));
            libusb_close(devh);
            return -1;
          }
#endif
#endif

          int config;

          ret = libusb_get_configuration(devh, &config);
          if(ret != LIBUSB_SUCCESS)
          {
            fprintf(stderr, "libusb_get_configuration: %s.\n", libusb_strerror(ret));
            libusb_close(devh);
            return -1;
          }

          if(config != controller[state->type].configuration)
          {
            ret = libusb_set_configuration(devh, controller[state->type].configuration);
            if(ret != LIBUSB_SUCCESS)
            {
              fprintf(stderr, "libusb_set_configuration: %s.\n", libusb_strerror(ret));
              libusb_close(devh);
              return -1;
            }
          }

          ret = libusb_claim_interface(devh, controller[state->type].interface);
          if(ret != LIBUSB_SUCCESS)
          {
            fprintf(stderr, "libusb_claim_interface: %s.\n", libusb_strerror(ret));
            libusb_close(devh);
          }
          else
          {
            state->devh = devh;
            ++nb_opened;

#ifndef WIN32
            const struct libusb_pollfd** pfd_usb = libusb_get_pollfds(ctx);

            int poll_i;
            for (poll_i=0; pfd_usb[poll_i] != NULL; ++poll_i)
            {
              GE_AddSource(pfd_usb[poll_i]->fd, usb_number, usb_handle_events, usb_handle_events, usb_close);
            }

            free(pfd_usb);
#endif

            if(state->type == C_TYPE_XONE_PAD && adapter_get(usb_number)->status)
            {
              //if the authentication was already performed, activate the controller

              //warning: make sure not to make any libusb async io before this!

              unsigned char activate[] = { 0x05, 0x20, 0x00, 0x01, 0x00 };
              usb_send_interrupt_out_sync(usb_number, activate, sizeof(activate));

              unsigned char activate_rumble[] = { 0x09, 0x00, 0x00, 0x09, 0x00, 0x0f, 0x00, 0x00, 0x00, 0x00, 0xff, 0x00, 0x00 };
              usb_send_interrupt_out_sync(usb_number, activate_rumble, sizeof(activate_rumble));
            }

            // register joystick
            state->joystick_id = GE_RegisterJoystick(controller[state->type].name, NULL);

            int i;
            for(i = 0; i < controller[state->type].endpoints.in.reports.nb; ++i)
            {
              usb_states[usb_number].reports[i].report_id = controller[state->type].endpoints.in.reports.elements[i].report_id;
            }

            return 0;
          }
        }
      }
    }
  }

  return -1;
}
Example #14
0
/*-----------------------------------------------------------------------------
 * Name      :  usb_open
 * Purpose   :  Open USB port
 * Inputs    :  p : port structure
 * Outputs   :  <>
 * Return    :  APS_OK or error code
 * -----------------------------------------------------------------------------*/
int usb_open(aps_port_t *p)
{
	libusb_device * dev;
	libusb_device_handle * h;
	int r;
	ssize_t cnt;
	int i;
	const char *vidstr;
	const char *pidstr;
#ifdef DEBUG
	fprintf(stderr, "DEBUG: in %s()\n", __func__);
#endif
	if (devcnt == 0)
	{
		return APS_USB_DEVICE_NOT_FOUND;
	}

	i = 0;
	while ((dev = devs[i]) != NULL)
	{
		struct libusb_device_descriptor desc;

		r = libusb_get_device_descriptor(dev, &desc);
		if (r < 0)
		{
			fprintf(stderr, "ERROR: failed to get device descriptor");
			libusb_free_device_list(devs, 1);
			libusb_exit(NULL);
			return APS_USB_DEVICE_NOT_FOUND;
		}

		/* shopov(04072011) - modified */
		//if (desc.idVendor == APS_VENDOR_ID || desc.idVendor == APS_VENDOR_ID0)
		if (libusb_get_bus_number(dev) == p->set.usb.busnum
				&& p->set.usb.devaddr == libusb_get_device_address(dev))
		{
#ifdef DEBUG
			fprintf(stderr, "DEBUG: ok, printer found...\n");
#endif
			break;
		}
		/* shopov(04072011) - end modified */
		i ++;
	}

	if (dev == 0)
	{
#ifdef DEBUG
		fprintf(stderr, "DEBUG: aps printer not found, exiting\n");
#endif
		libusb_free_device_list(devs, 1);
		libusb_exit(NULL);
		devs = 0;
		devcnt = 0;
		return APS_USB_DEVICE_NOT_FOUND;
	}
#ifdef DEBUG
	fprintf(stderr, "DEBUG: printer at bus: %i\n", libusb_get_bus_number(dev));
	fprintf(stderr, "DEBUG: printer at address: %i\n", libusb_get_device_address(dev));
#endif
	if (libusb_open(dev, &h))
	{
#ifdef DEBUG
		fprintf(stderr, "DEBUG: aps printer not found, exiting\n");
#endif
		libusb_free_device_list(devs, 1);
		libusb_exit(NULL);
		devs = 0;
		devcnt = 0;
		return APS_USB_DEVICE_NOT_FOUND;
	}
	r = libusb_kernel_driver_active(h, 0);
	if (r != 0 && r != 1)
	{
close_and_return:		
		libusb_close(h);
#ifdef DEBUG
		fprintf(stderr, "DEBUG: aps printer not found, exiting\n");
#endif
		libusb_free_device_list(devs, 1);
		libusb_exit(NULL);
		devs = 0;
		devcnt = 0;
		return APS_IO_ERROR;
	}
	p->set.usb.was_kernel_driver_attached = r;
	if (r)
	{
		r = libusb_detach_kernel_driver(h, 0);
		if (r != 0)
			goto close_and_return;
	}
	r = libusb_claim_interface(h, 0);
	if (r != 0)
		goto close_and_return;

	p->set.usb.pdev = dev;
	p->set.usb.hdev = h;

	return APS_OK;
}
Example #15
0
//------------------------------------------------------------------------------
int ttwatch_open_device(libusb_device *device, const char *serial_or_name, TTWATCH **watch)
{
    struct libusb_device_descriptor desc;
    int result;
    libusb_device_handle *handle;
    char serial[64];
    char name[64];
    int count;
    int attempts = 0;

    // get the device descriptor
    libusb_get_device_descriptor(device, &desc);

    // ignore any non-TomTom devices
    // PID 0x7474 is Multisport and Multisport Cardio
    if ((desc.idVendor  != TOMTOM_VENDOR_ID) ||
        ((desc.idProduct != TOMTOM_MULTISPORT_PRODUCT_ID) &&
         !IS_SPARK(desc.idProduct)))
    {
        *watch = 0;
        return TTWATCH_NotAWatch;
    }

    // open the device so we can read the serial number
    if (libusb_open(device, &handle))
    {
        *watch = 0;
        return TTWATCH_UnableToOpenDevice;
    }

    *watch = (TTWATCH*)malloc(sizeof(TTWATCH));
    memset(*watch, 0, sizeof(TTWATCH));
    (*watch)->device = handle;
    (*watch)->usb_product_id = desc.idProduct;

    // Claim the device interface. If the device is busy (such as opened
    // by a daemon), wait up to 60 seconds for it to become available
    while (attempts++ < 60)
    {
        // detach the kernel HID driver, otherwise we can't do anything
        if (libusb_kernel_driver_active(handle, 0))
        {
            if (!libusb_detach_kernel_driver(handle, 0))
                (*watch)->attach_kernel_driver = 1;
        }
        if ((result = libusb_claim_interface(handle, 0)) != 0)
        {
            if (result == LIBUSB_ERROR_BUSY)
                sleep(1);
            else
            {
                ttwatch_close(*watch);
                *watch = 0;
                return TTWATCH_UnableToOpenDevice;
            }
        }
        else
            break;
    }
    // if we have finished the attempts and it's still busy, abort
    if (result)
    {
        ttwatch_close(*watch);
        *watch = 0;
        return TTWATCH_UnableToOpenDevice;
    }

    // get the watch serial number
    count = libusb_get_string_descriptor_ascii(handle, desc.iSerialNumber,
        (unsigned char*)(*watch)->serial_number, sizeof((*watch)->serial_number));
    if (count > 0)
        ((char*)(*watch)->serial_number)[count] = 0;

    RETURN_ERROR(ttwatch_send_startup_message_group(*watch));

    // get the watch name
    if (ttwatch_get_watch_name(*watch, name, sizeof(name)) != TTWATCH_NoError)
        name[0] = 0;

    // see if we can match the watch serial number or name
    if (!serial_or_name ||
        (strcasecmp(serial_or_name, serial) == 0) ||
        (strcasecmp(serial_or_name, name) == 0))
    {
        ttwatch_get_product_id(*watch, &(*watch)->product_id);
        ttwatch_get_firmware_version(*watch, &(*watch)->firmware_version);
        ttwatch_get_ble_version(*watch, &(*watch)->ble_version);

        return TTWATCH_NoError;
    }
    else
    {
        ttwatch_close(*watch);
        *watch = 0;
        return TTWATCH_NoMatchingWatch;
    }
}
Example #16
0
SR_PRIV int hantek_6xxx_open(struct sr_dev_inst *sdi)
{
	struct dev_context *devc;
	struct drv_context *drvc = sdi->driver->context;
	struct sr_usb_dev_inst *usb;
	struct libusb_device_descriptor des;
	libusb_device **devlist;
	int err, i;
	char connection_id[64];

	devc = sdi->priv;
	usb = sdi->conn;

	if (sdi->status == SR_ST_ACTIVE)
		/* Already in use. */
		return SR_ERR;

	libusb_get_device_list(drvc->sr_ctx->libusb_ctx, &devlist);
	for (i = 0; devlist[i]; i++) {
		libusb_get_device_descriptor(devlist[i], &des);

		if (des.idVendor != devc->profile->fw_vid
		    || des.idProduct != devc->profile->fw_pid)
			continue;

		if ((sdi->status == SR_ST_INITIALIZING) ||
				(sdi->status == SR_ST_INACTIVE)) {
			/*
			 * Check device by its physical USB bus/port address.
			 */
			usb_get_port_path(devlist[i], connection_id, sizeof(connection_id));
			if (strcmp(sdi->connection_id, connection_id))
				/* This is not the one. */
				continue;
		}

		if (!(err = libusb_open(devlist[i], &usb->devhdl))) {
			if (usb->address == 0xff) {
				/*
				 * First time we touch this device after firmware upload,
				 * so we don't know the address yet.
				 */
				usb->address = libusb_get_device_address(devlist[i]);
			}

			sdi->status = SR_ST_ACTIVE;
			sr_info("Opened device on %d.%d (logical) / "
					"%s (physical) interface %d.",
				usb->bus, usb->address,
				sdi->connection_id, USB_INTERFACE);
		} else {
			sr_err("Failed to open device: %s.",
			       libusb_error_name(err));
		}

		/* If we made it here, we handled the device (somehow). */
		break;
	}

	libusb_free_device_list(devlist, 1);

	if (sdi->status != SR_ST_ACTIVE)
		return SR_ERR;

	return SR_OK;
}
Example #17
0
///////////////////////////////////////////////////////////////////////////////
// searchDevice() -  Search for AOA support device in the all USB devices
///////////////////////////////////////////////////////////////////////////////
//argument
// ctx      : libusb_context
// idVendor : return buffer for USB Vendor ID
// idProduc : return buffer for USB Product ID
//
//return
// -1 : AOA device not found
// 0> : AOA Version
//
int AOA::searchDevice(libusb_context *ctx, uint16_t *idVendor, uint16_t *idProduct)
{
    int res;
    int i;
    libusb_device **devs;
    libusb_device *dev;
    struct libusb_device_descriptor desc;
    ssize_t devcount;

    *idVendor = *idProduct = 0;
    res = -1;
    devcount = libusb_get_device_list(ctx, &devs);
    if(devcount <= 0){
       printf("Get device error.\n");
       return -1;
    }

    //enumerate USB deivces
    for(i=0; i<devcount; i++){
        dev = devs[i];
        libusb_get_device_descriptor(dev, &desc);
#ifdef DEBUG
        printf("VID:%04X, PID:%04X Class:%02X\n", desc.idVendor, desc.idProduct, desc.bDeviceClass);
#endif
        //Ignore non target device
        if( desc.bDeviceClass != 0 ){
            continue;
        }

        //Already AOA mode ?
        if(desc.idVendor == USB_ACCESSORY_VENDOR_ID &&
            (desc.idProduct >= USB_ACCESSORY_PRODUCT_ID &&
             desc.idProduct <= USB_ACCESSORY_AUDIO_ADB_PRODUCT_ID)
        ){
#ifdef DEBUG
            printf("already in accessory mode.\n");
#endif
            res = 0;
            break;
        }

        //Checking the AOA capability.
        if((handle = libusb_open_device_with_vid_pid(ctx, desc.idVendor,  desc.idProduct)) == NULL) {
               printf("Device open error.\n");
        } else {
                libusb_claim_interface(handle, 0);
                res = getProtocol();
                libusb_release_interface (handle, 0);
                libusb_close(handle);
                handle = NULL;
                if( res != -1 ){
#ifdef DEBUG
    printf("AOA protocol version: %d\n", verProtocol);
#endif
                    break; //AOA found.
                }
        }
    }

    // find end point number
    if( findEndPoint(dev) < 0 ){
        printf("Endpoint not found.\n");
        res = -1;
    }
    *idVendor = desc.idVendor;
    *idProduct = desc.idProduct;
#ifdef DEBUG
    printf("VID:%04X, PID:%04X\n", *idVendor, *idProduct);
#endif
    return res;
}
Example #18
0
static void
_open_usb_device (ArvUvDevice *uv_device)
{
	libusb_device **devices;
	unsigned i, j, k;
	ssize_t count;

	count = libusb_get_device_list (uv_device->priv->usb, &devices);
	if (count < 0) {
		arv_warning_device ("[[UvDevice::_open_usb_device] Failed to get USB device list: %s",
				    libusb_error_name (count));
		return;
	}

	for (i = 0; i < count && uv_device->priv->usb_device == NULL; i++) {
		libusb_device_handle *usb_device;
		struct libusb_device_descriptor desc;

		if (libusb_get_device_descriptor (devices[i], &desc) >= 0 &&
		    libusb_open (devices[i], &usb_device) == LIBUSB_SUCCESS) {
			unsigned char *manufacturer;
			unsigned char *product;
			unsigned char *serial_nbr;
			int index;

			manufacturer = g_malloc0 (256);
			product = g_malloc0 (256);
			serial_nbr = g_malloc0 (256);

			index = desc.iManufacturer;
			if (index > 0)
				libusb_get_string_descriptor_ascii (usb_device, index, manufacturer, 256);
			index = desc.iProduct;
			if (index > 0)
				libusb_get_string_descriptor_ascii (usb_device, index, product, 256);
			index = desc.iSerialNumber;
			if (index > 0)
				libusb_get_string_descriptor_ascii (usb_device, index, serial_nbr, 256);

			if (g_strcmp0 ((char * ) manufacturer, uv_device->priv->vendor) == 0 &&
			    g_strcmp0 ((char * ) product, uv_device->priv->product) == 0 &&
			    g_strcmp0 ((char * ) serial_nbr, uv_device->priv->serial_nbr) == 0) {
				struct libusb_config_descriptor *config;
				struct libusb_endpoint_descriptor endpoint;
				const struct libusb_interface *inter;
				const struct libusb_interface_descriptor *interdesc;

				uv_device->priv->usb_device = usb_device;

				libusb_get_config_descriptor (devices[i], 0, &config);
				for (j = 0; j < (int) config->bNumInterfaces; j++) {
					inter = &config->interface[j];
					for (k = 0; k < inter->num_altsetting; k++) {
						interdesc = &inter->altsetting[k];
						if (interdesc->bInterfaceClass == ARV_UV_INTERFACE_INTERFACE_CLASS &&
						    interdesc->bInterfaceSubClass == ARV_UV_INTERFACE_INTERFACE_SUBCLASS) {
							if (interdesc->bInterfaceProtocol == ARV_UV_INTERFACE_CONTROL_PROTOCOL) {
								endpoint = interdesc->endpoint[0];
								uv_device->priv->control_endpoint = endpoint.bEndpointAddress & 0x0f;
								uv_device->priv->control_interface = interdesc->bInterfaceNumber;
							}
							if (interdesc->bInterfaceProtocol == ARV_UV_INTERFACE_DATA_PROTOCOL) {
								endpoint = interdesc->endpoint[0];
								uv_device->priv->data_endpoint = endpoint.bEndpointAddress & 0x0f;
								uv_device->priv->data_interface = interdesc->bInterfaceNumber;
							}
						}
					}
				}
				libusb_free_config_descriptor (config);
			} else
				libusb_close (usb_device);

			g_free (manufacturer);
			g_free (product);
			g_free (serial_nbr);
		}
	}

	libusb_free_device_list (devices, 1);
}
Example #19
0
irecv_error_t irecv_open(irecv_client_t* pclient) {
#ifndef WIN32
	int i = 0;
	struct libusb_device* usb_device = NULL;
	struct libusb_device** usb_device_list = NULL;
	struct libusb_device_handle* usb_handle = NULL;
	struct libusb_device_descriptor usb_descriptor;

	*pclient = NULL;
	if(libirecovery_debug) {
		irecv_set_debug_level(libirecovery_debug);
	}

	irecv_error_t error = IRECV_E_SUCCESS;
	int usb_device_count = libusb_get_device_list(libirecovery_context, &usb_device_list);
	for (i = 0; i < usb_device_count; i++) {
		usb_device = usb_device_list[i];
		libusb_get_device_descriptor(usb_device, &usb_descriptor);
		if (usb_descriptor.idVendor == APPLE_VENDOR_ID) {
			/* verify this device is in a mode we understand */
			if (usb_descriptor.idProduct == kRecoveryMode1 ||
				usb_descriptor.idProduct == kRecoveryMode2 ||
				usb_descriptor.idProduct == kRecoveryMode3 ||
				usb_descriptor.idProduct == kRecoveryMode4 ||
				usb_descriptor.idProduct == kDfuMode) {

				debug("opening device %04x:%04x...\n", usb_descriptor.idVendor, usb_descriptor.idProduct);

				libusb_open(usb_device, &usb_handle);
				if (usb_handle == NULL) {
					libusb_free_device_list(usb_device_list, 1);
					libusb_close(usb_handle);
					libusb_exit(libirecovery_context);
					return IRECV_E_UNABLE_TO_CONNECT;
				}
				libusb_free_device_list(usb_device_list, 1);

				irecv_client_t client = (irecv_client_t) malloc(sizeof(struct irecv_client));
				if (client == NULL) {
					libusb_close(usb_handle);
					libusb_exit(libirecovery_context);
					return IRECV_E_OUT_OF_MEMORY;
				}

				memset(client, '\0', sizeof(struct irecv_client));
				client->interface = 0;
				client->handle = usb_handle;
				client->mode = usb_descriptor.idProduct;
				

				error = irecv_set_configuration(client, 1);
				if (error != IRECV_E_SUCCESS) {
					return error;
				}
				
				if (client->mode != kDfuMode) {
					error = irecv_set_interface(client, 0, 0);
					error = irecv_set_interface(client, 1, 1);
				} else {
					error = irecv_set_interface(client, 0, 0);
				}

				if (error != IRECV_E_SUCCESS) {
					return error;
				}

				/* cache usb serial */
				irecv_get_string_descriptor_ascii(client, usb_descriptor.iSerialNumber, (unsigned char*) client->serial, 255);
				
				*pclient = client;
				return IRECV_E_SUCCESS;
			}
		}
	}

	return IRECV_E_UNABLE_TO_CONNECT;
#else
	int ret = mobiledevice_connect(pclient);
	if (ret == IRECV_E_SUCCESS) {
		irecv_get_string_descriptor_ascii(*pclient, 3, (unsigned char*) (*pclient)->serial, 255);
	}
	return ret;
#endif
}
Example #20
0
int main(void)
{
    libusb_context *ctx;
    libusb_init(&ctx);
    libusb_set_debug(ctx, 3);

    /* Look at the keyboard based on vendor and device id */
    libusb_device_handle *device_handle = libusb_open_device_with_vid_pid(ctx, 0x046d, 0xc52b);

    fprintf(stderr, "Found keyboard 0x%p\n", device_handle);

    libusb_device *device = libusb_get_device(device_handle);

    struct libusb_device_descriptor desc;

    libusb_get_device_descriptor(device, &desc);

    for(uint8_t config_index = 0; config_index < desc.bNumConfigurations; config_index++)
    {
        struct libusb_config_descriptor *config;

        libusb_get_config_descriptor(device, config_index, &config);

        /* We know we want interface 2 */
        int iface_index = 2;
        const struct libusb_interface *iface = &config->interface[iface_index];

        for (int altsetting_index = 0; altsetting_index < iface->num_altsetting; altsetting_index++)
        {
            const struct libusb_interface_descriptor *iface_desc = &iface->altsetting[altsetting_index];

            if (iface_desc->bInterfaceClass == LIBUSB_CLASS_HID)
            {
                libusb_detach_kernel_driver(device_handle, iface_index);
                libusb_claim_interface(device_handle, iface_index);

                unsigned char ret[65535];

                unsigned char payload[] = "\x10\x02\x09\x03\x78\x01\x00";

                if(libusb_control_transfer(device_handle,
                            LIBUSB_REQUEST_TYPE_CLASS | LIBUSB_RECIPIENT_INTERFACE,
                            HID_REQ_SET_REPORT,
                            0x0210, iface_index, payload, sizeof(payload) - 1, 10000))
                {
                    int actual_length = 0;

                    while(actual_length != 20 || strncmp((const char *) &ret[9], "GOOD", 4))
                        libusb_interrupt_transfer(device_handle,
                                iface_desc->endpoint[0].bEndpointAddress,
                                ret, sizeof(ret), &actual_length, 100000);

                    uint16_t lux = ret[5] << 8 | ret[6];

                    fprintf(stderr, "Charge: %d %%\nLight: %d lux\n", ret[4], lux);
                }

                libusb_release_interface(device_handle, iface_index);
                libusb_attach_kernel_driver(device_handle, iface_index);
            }
        }
    }

    libusb_close(device_handle);
    libusb_exit(ctx);
}
Example #21
0
hid_device * HID_API_EXPORT hid_open_path(const char *path)
{
	hid_device *dev = NULL;

	dev = new_hid_device();

	libusb_device **devs;
	libusb_device *usb_dev;
	int res;
	int d = 0;
	int good_open = 0;
	
	setlocale(LC_ALL,"");
	
	if (!initialized)
		hid_init();
	libusb_get_device_list(NULL, &devs);
	while ((usb_dev = devs[d++]) != NULL) {
		struct libusb_device_descriptor desc;
		struct libusb_config_descriptor *conf_desc = NULL;
		int i,j,k;
		libusb_get_device_descriptor(usb_dev, &desc);

		if (libusb_get_active_config_descriptor(usb_dev, &conf_desc) < 0)
			continue;
		for (j = 0; j < conf_desc->bNumInterfaces; j++) {
			const struct libusb_interface *intf = &conf_desc->interface[j];
			for (k = 0; k < intf->num_altsetting; k++) {
				const struct libusb_interface_descriptor *intf_desc;
				intf_desc = &intf->altsetting[k];
				if (intf_desc->bInterfaceClass == LIBUSB_CLASS_HID) {
					char *dev_path = make_path(usb_dev, intf_desc->bInterfaceNumber);
					if (!strcmp(dev_path, path)) {
						/* Matched Paths. Open this device */

						// OPEN HERE //
						res = libusb_open(usb_dev, &dev->device_handle);
						if (res < 0) {
							LOG("can't open device\n");
							free(dev_path);
 							break;
						}
						good_open = 1;
						
						/* Detach the kernel driver, but only if the
						   device is managed by the kernel */
						if (libusb_kernel_driver_active(dev->device_handle, intf_desc->bInterfaceNumber) == 1) {
							res = libusb_detach_kernel_driver(dev->device_handle, intf_desc->bInterfaceNumber);
							if (res < 0) {
								libusb_close(dev->device_handle);
								LOG("Unable to detach Kernel Driver\n");
								free(dev_path);
								good_open = 0;
								break;
							}
						}
						
						res = libusb_claim_interface(dev->device_handle, intf_desc->bInterfaceNumber);
						if (res < 0) {
							LOG("can't claim interface %d: %d\n", intf_desc->bInterfaceNumber, res);
							free(dev_path);
							libusb_close(dev->device_handle);
							good_open = 0;
							break;
						}

						/* Store off the string descriptor indexes */
						dev->manufacturer_index = desc.iManufacturer;
						dev->product_index      = desc.iProduct;
						dev->serial_index       = desc.iSerialNumber;

						/* Store off the interface number */
						dev->interface = intf_desc->bInterfaceNumber;
												
						/* Find the INPUT and OUTPUT endpoints. An
						   OUTPUT endpoint is not required. */
						for (i = 0; i < intf_desc->bNumEndpoints; i++) {
							const struct libusb_endpoint_descriptor *ep
								= &intf_desc->endpoint[i];

							/* Determine the type and direction of this
							   endpoint. */
							int is_interrupt =
								(ep->bmAttributes & LIBUSB_TRANSFER_TYPE_MASK)
							      == LIBUSB_TRANSFER_TYPE_INTERRUPT;
							int is_output = 
								(ep->bEndpointAddress & LIBUSB_ENDPOINT_DIR_MASK)
							      == LIBUSB_ENDPOINT_OUT;
							int is_input = 
								(ep->bEndpointAddress & LIBUSB_ENDPOINT_DIR_MASK)
							      == LIBUSB_ENDPOINT_IN;

							/* Decide whether to use it for intput or output. */
							if (dev->input_endpoint == 0 &&
							    is_interrupt && is_input) {
								/* Use this endpoint for INPUT */
								dev->input_endpoint = ep->bEndpointAddress;
								dev->input_ep_max_packet_size = ep->wMaxPacketSize;
							}
							if (dev->output_endpoint == 0 &&
							    is_interrupt && is_output) {
								/* Use this endpoint for OUTPUT */
								dev->output_endpoint = ep->bEndpointAddress;
							}
						}
						
						pthread_create(&dev->thread, NULL, read_thread, dev);
						
						// Wait here for the read thread to be initialized.
						pthread_barrier_wait(&dev->barrier);
						
					}
					free(dev_path);
				}
			}
		}
		libusb_free_config_descriptor(conf_desc);

	}

	libusb_free_device_list(devs, 1);
	
	// If we have a good handle, return it.
	if (good_open) {
		return dev;
	}
	else {
		// Unable to open any devices.
		free_hid_device(dev);
		return NULL;
	}
}
Example #22
0
static int
usb_find_hubs (int listing, int verbose, int busnum, int devnum, int hub)
{

	struct libusb_device **devs;
	struct libusb_device *dev;
	int i = 0;
	int r;
	number_of_hubs_with_feature = 0;

	if (libusb_get_device_list( ctx, &devs ) < 0){
		perror ("failed to access USB");
		return 0;
	}

	while ( (dev = devs[i++]) != NULL) {
		struct libusb_device_descriptor desc;
		unsigned short dev_vid, dev_pid, dev_bcd;

		r = libusb_get_device_descriptor(dev, &desc);
		if (r < 0) {
			continue;
		}
		dev_vid = libusb_le16_to_cpu(desc.idVendor);
		dev_pid = libusb_le16_to_cpu(desc.idProduct);
		dev_bcd = libusb_le16_to_cpu(desc.bcdUSB);
		//wmlog_msg(1, "Bus %03d Device %03d: ID %04x:%04x", libusb_get_bus_number(dev), libusb_get_device_address(dev), dev_vid, dev_pid);

		libusb_device_handle *uh;
		int print = 0;
		int usb3 = (dev_bcd >= 0x0300);

		//printf("found dev %d\n", dev->descriptor.bDeviceClass);
		if (desc.bDeviceClass != LIBUSB_CLASS_HUB)
			continue;


		if (listing
			|| (verbose ))
			//		  && ((atoi (bus->dirname) == busnum && dev->devnum == devnum)
			//		      || hub == number_of_hubs_with_feature)))
			print = 1;

		if( libusb_open (dev, &uh) != 0 )
			continue;

/*		if(libusb_detach_kernel_driver( uh, 0 ))
			perror("libusb_detach_kernel_driver");

		if(libusb_claim_interface( uh, 0 ))
			perror("libusb_claim_interface");*/

		if ( uh != NULL )
		{	    

			if (print)
				printf ("Hub #%d at \tBUS:DEV\t\t%03d:%03d\n\t\tUSB VEND:PROD: \t%04x:%04x\n",
				number_of_hubs_with_feature,
				libusb_get_bus_number( dev ), 
				libusb_get_device_address( dev ),
				dev_vid, dev_pid
				);

			char buf[ sizeof(struct usb_hub_descriptor) + 2*4 ];
			int len;
			int nport;
			struct usb_hub_descriptor *uhd = (struct usb_hub_descriptor *)buf;

			if ( (len = libusb_control_transfer ( uh,
				LIBUSB_ENDPOINT_IN | USB_RT_HUB,
				LIBUSB_REQUEST_GET_DESCRIPTOR,
				(usb3 ? LIBUSB_DT_SUPERSPEED_HUB : LIBUSB_DT_HUB)<<8, 0,
				buf, (int)sizeof ( buf ),
				CTRL_TIMEOUT ) )
//			if( libusb_get_descriptor( uh, LIBUSB_DT_HUB, 0, buf, sizeof(buf) )
			    >(int)sizeof (struct usb_hub_descriptor) )
			{
				if (!(!(uhd->wHubCharacteristics[0] & HUB_CHAR_PORTIND)
					&& (uhd->wHubCharacteristics[0] & HUB_CHAR_LPSM) >= 2)){

						switch ((uhd->wHubCharacteristics[0] & HUB_CHAR_LPSM))
						{
						case 0:
							if (print)
								fprintf (stderr, " INFO: ganged switching.\n");
							break;
						case 1:
							if (print)
								fprintf (stderr, " INFO: individual power switching.\n");
							break;
						case 2:
						case 3:
							if (print)
								fprintf (stderr, " WARN: No power switching.\n");
							break;
						}

						if (print
							&& !(uhd->wHubCharacteristics[0] & HUB_CHAR_PORTIND))
							fprintf (stderr, " WARN: Port indicators are NOT supported.\n");
				}
			}
			else
			{
				perror ("Can't get hub descriptor.");
				printf( "%d\n",len );
			}

			if( len > 0 )
			{
				nport = buf[2];
				hubs[number_of_hubs_with_feature].busnum = libusb_get_bus_number( dev );
				hubs[number_of_hubs_with_feature].devnum = libusb_get_device_address( dev );
				hubs[number_of_hubs_with_feature].dev = dev;
				hubs[number_of_hubs_with_feature].indicator_support =
					(uhd->wHubCharacteristics[0] & HUB_CHAR_PORTIND)? 1 : 0;
				hubs[number_of_hubs_with_feature].nport = nport;
				hubs[number_of_hubs_with_feature].usb3 = usb3;

				number_of_hubs_with_feature++;

				if (verbose)
					hub_port_status (uh, nport, usb3);
			}
/*
			libusb_release_interface( uh,0 );
			libusb_attach_kernel_driver( uh, 0); */

			libusb_close (uh);
		}
	}
	libusb_free_device_list( devs, 1 );


	return number_of_hubs_with_feature;
}
static bool usb_open()
{
	printf("%s\n", __PRETTY_FUNCTION__);

	if(m_pContext) {
		// open済み
		//printf("already opened\n");
		return true;
	}

	int r;

	printf("--init...%p\n", m_pContext);
	r = libusb_init(&m_pContext);
	if (r < 0) {
		LOGE("cannot init\n");
		return false;
	}
	printf("  ==> done!\n");

	//libusb_set_debug(NULL, 3);

#if 1
	libusb_device **devs;
	ssize_t cnt = libusb_get_device_list(m_pContext, &devs);
	if (cnt < 0) {
		LOGE("cannot list\n");
		close();
		return false;
	}

	libusb_device *dev;
	int i = 0;

	while ((dev = devs[i++]) != NULL) {
		struct libusb_device_descriptor desc;
		int r = libusb_get_device_descriptor(dev, &desc);
		if (r < 0) {
			LOGE("failed to get device descriptor\n");
			i = -1;
			break;
		}
		if((desc.idVendor == VID) && (desc.idProduct == PID)) {
			i = 0;
			break;
		}
	}
	if(i != 0) {
		LOGE("cannot find\n");
		close();
		return false;
	}
	r = libusb_open(dev, &m_pHandle);
	if(r != 0) {
		LOGE("cannot open : %d\n", r);
		close();
		return false;
	}
	libusb_free_device_list(devs, 1);

#else
	printf("--open...\n");
	m_pHandle = libusb_open_device_with_vid_pid(NULL, VID, PID);
	if(m_pHandle == NULL) {
		LOGE("cannot open\n");
		close();
		return false;
	}
	printf("  ==>done!\n");
	
	libusb_device *dev;
	dev = libusb_get_device(m_pHandle);
#endif

	struct libusb_config_descriptor* pConfig;
	r = libusb_get_config_descriptor(dev, 0, &pConfig);
	if(r != 0) {
		LOGE("cannot getdesc : %d\n", r);
		close();
		return false;
	}
	
	printf("--find\n");
	int inf;
	int alt;
	int desc;
	for(inf = 0; inf < pConfig->bNumInterfaces; inf++) {
		const struct libusb_interface* inter = &pConfig->interface[inf];
		for(alt = 0; alt < inter->num_altsetting; alt++) {
			const struct libusb_interface_descriptor* idesc = &(inter->altsetting[alt]);
			for(desc = 0; desc < idesc->bNumEndpoints; desc++) {
				const struct libusb_endpoint_descriptor* EndPnt = &(idesc->endpoint[desc]);
				if(EndPnt->bEndpointAddress & LIBUSB_ENDPOINT_IN) {
					printf("find IN\n");
					m_EndPntIn = EndPnt->bEndpointAddress;
				}
				else {
					printf("find OUT\n");
					m_EndPntOut = EndPnt->bEndpointAddress;
				}
			}
		}
	}

	r = libusb_claim_interface(m_pHandle, 0);
	if(r != 0) {
		LOGE("cannot claim\n");
		close();
		return false;
	}

	//Debug Out
	//libusb_set_debug(m_pContext, 3);

	printf("open!\n");
	return true;
}
Example #24
0
SR_PRIV int fx2lafw_dev_open(struct sr_dev_inst *sdi, struct sr_dev_driver *di)
{
	libusb_device **devlist;
	struct sr_usb_dev_inst *usb;
	struct libusb_device_descriptor des;
	struct dev_context *devc;
	struct drv_context *drvc;
	struct version_info vi;
	int ret, i, device_count;
	uint8_t revid;
	char connection_id[64];

	drvc = di->context;
	devc = sdi->priv;
	usb = sdi->conn;

	if (sdi->status == SR_ST_ACTIVE)
		/* Device is already in use. */
		return SR_ERR;

	device_count = libusb_get_device_list(drvc->sr_ctx->libusb_ctx, &devlist);
	if (device_count < 0) {
		sr_err("Failed to get device list: %s.",
		       libusb_error_name(device_count));
		return SR_ERR;
	}

	for (i = 0; i < device_count; i++) {
		libusb_get_device_descriptor(devlist[i], &des);

		if (des.idVendor != devc->profile->vid
		    || des.idProduct != devc->profile->pid)
			continue;

		if ((sdi->status == SR_ST_INITIALIZING) ||
				(sdi->status == SR_ST_INACTIVE)) {
			/*
			 * Check device by its physical USB bus/port address.
			 */
			usb_get_port_path(devlist[i], connection_id, sizeof(connection_id));
			if (strcmp(sdi->connection_id, connection_id))
				/* This is not the one. */
				continue;
		}

		if (!(ret = libusb_open(devlist[i], &usb->devhdl))) {
			if (usb->address == 0xff)
				/*
				 * First time we touch this device after FW
				 * upload, so we don't know the address yet.
				 */
				usb->address = libusb_get_device_address(devlist[i]);
		} else {
			sr_err("Failed to open device: %s.",
			       libusb_error_name(ret));
			break;
		}

		if (libusb_has_capability(LIBUSB_CAP_SUPPORTS_DETACH_KERNEL_DRIVER)) {
			if (libusb_kernel_driver_active(usb->devhdl, USB_INTERFACE) == 1) {
				if ((ret = libusb_detach_kernel_driver(usb->devhdl, USB_INTERFACE)) < 0) {
					sr_err("Failed to detach kernel driver: %s.",
						libusb_error_name(ret));
					return SR_ERR;
				}
			}
		}

		ret = command_get_fw_version(usb->devhdl, &vi);
		if (ret != SR_OK) {
			sr_err("Failed to get firmware version.");
			break;
		}

		ret = command_get_revid_version(sdi, &revid);
		if (ret != SR_OK) {
			sr_err("Failed to get REVID.");
			break;
		}

		/*
		 * Changes in major version mean incompatible/API changes, so
		 * bail out if we encounter an incompatible version.
		 * Different minor versions are OK, they should be compatible.
		 */
		if (vi.major != FX2LAFW_REQUIRED_VERSION_MAJOR) {
			sr_err("Expected firmware version %d.x, "
			       "got %d.%d.", FX2LAFW_REQUIRED_VERSION_MAJOR,
			       vi.major, vi.minor);
			break;
		}

		sdi->status = SR_ST_ACTIVE;
		sr_info("Opened device on %d.%d (logical) / %s (physical), "
			"interface %d, firmware %d.%d.",
			usb->bus, usb->address, connection_id,
			USB_INTERFACE, vi.major, vi.minor);

		sr_info("Detected REVID=%d, it's a Cypress CY7C68013%s.",
			revid, (revid != 1) ? " (FX2)" : "A (FX2LP)");

		break;
	}
	libusb_free_device_list(devlist, 1);

	if (sdi->status != SR_ST_ACTIVE)
		return SR_ERR;

	return SR_OK;
}
Example #25
0
static int dev_open(struct sr_dev_inst *sdi)
{
	struct dev_context *devc;
	struct drv_context *drvc;
	struct sr_usb_dev_inst *usb;
	libusb_device **devlist, *dev;
	struct libusb_device_descriptor des;
	int device_count, ret, i;

	drvc = di->priv;
	usb = sdi->conn;

	if (!(devc = sdi->priv)) {
		sr_err("%s: sdi->priv was NULL", __func__);
		return SR_ERR_ARG;
	}

	device_count = libusb_get_device_list(drvc->sr_ctx->libusb_ctx,
					      &devlist);
	if (device_count < 0) {
		sr_err("Failed to retrieve device list.");
		return SR_ERR;
	}

	dev = NULL;
	for (i = 0; i < device_count; i++) {
		if ((ret = libusb_get_device_descriptor(devlist[i], &des))) {
			sr_err("Failed to get device descriptor: %s.",
			       libusb_error_name(ret));
			continue;
		}
		if (libusb_get_bus_number(devlist[i]) == usb->bus
		    && libusb_get_device_address(devlist[i]) == usb->address) {
			dev = devlist[i];
			break;
		}
	}
	if (!dev) {
		sr_err("Device on bus %d address %d disappeared!",
		       usb->bus, usb->address);
		return SR_ERR;
	}

	if (!(ret = libusb_open(dev, &(usb->devhdl)))) {
		sdi->status = SR_ST_ACTIVE;
		sr_info("Opened device %d on %d.%d interface %d.",
			sdi->index, usb->bus, usb->address, USB_INTERFACE);
	} else {
		sr_err("Failed to open device: %s.", libusb_error_name(ret));
		return SR_ERR;
	}

	ret = libusb_set_configuration(usb->devhdl, USB_CONFIGURATION);
	if (ret < 0) {
		sr_err("Unable to set USB configuration %d: %s.",
		       USB_CONFIGURATION, libusb_error_name(ret));
		return SR_ERR;
	}

	ret = libusb_claim_interface(usb->devhdl, USB_INTERFACE);
	if (ret != 0) {
		sr_err("Unable to claim interface: %s.",
		       libusb_error_name(ret));
		return SR_ERR;
	}

	/* Set default configuration after power on. */
	if (analyzer_read_status(usb->devhdl) == 0)
		analyzer_configure(usb->devhdl);

	analyzer_reset(usb->devhdl);
	analyzer_initialize(usb->devhdl);

	//analyzer_set_memory_size(MEMORY_SIZE_512K);
	// analyzer_set_freq(g_freq, g_freq_scale);
	analyzer_set_trigger_count(1);
	// analyzer_set_ramsize_trigger_address((((100 - g_pre_trigger)
	// * get_memory_size(g_memory_size)) / 100) >> 2);

#if 0
	if (g_double_mode == 1)
		analyzer_set_compression(COMPRESSION_DOUBLE);
	else if (g_compression == 1)
		analyzer_set_compression(COMPRESSION_ENABLE);
	else
#endif
	analyzer_set_compression(COMPRESSION_NONE);

	if (devc->cur_samplerate == 0) {
		/* Samplerate hasn't been set. Default to 1MHz. */
		analyzer_set_freq(1, FREQ_SCALE_MHZ);
		devc->cur_samplerate = SR_MHZ(1);
	}

	if (devc->cur_threshold == 0)
		set_voltage_threshold(devc, 1.5);

	return SR_OK;
}
Example #26
0
int test_init(struct test_state *state)
{
	int i, ret;
	ssize_t cnt;
	libusb_device **list;

	state->found = NULL;
	state->ctx = NULL;
	state->handle = NULL;
	state->attached = 0;

	ret = libusb_init(&state->ctx);
	if (ret) {
		printf("cannot init libusb: %s\n", libusb_error_name(ret));
		return 1;
	}

	cnt = libusb_get_device_list(state->ctx, &list);
	if (cnt <= 0) {
		printf("no devices found\n");
		goto error1;
	}

	for (i = 0; i < cnt; ++i) {
		libusb_device *dev = list[i];
		struct libusb_device_descriptor desc;
		ret = libusb_get_device_descriptor(dev, &desc);
		if (ret) {
			printf("unable to get device descriptor: %s\n",
			       libusb_error_name(ret));
			goto error2;
		}
		if (desc.idVendor == VENDOR && desc.idProduct == PRODUCT) {
			state->found = dev;
			break;
		}
	}

	if (!state->found) {
		printf("no devices found\n");
		goto error2;
	}

	ret = libusb_open(state->found, &state->handle);
	if (ret) {
		printf("cannot open device: %s\n", libusb_error_name(ret));
		goto error2;
	}

	if (libusb_claim_interface(state->handle, 0)) {
		ret = libusb_detach_kernel_driver(state->handle, 0);
		if (ret) {
			printf("unable to detach kernel driver: %s\n",
			       libusb_error_name(ret));
			goto error3;
		}
		state->attached = 1;
		ret = libusb_claim_interface(state->handle, 0);
		if (ret) {
			printf("cannot claim interface: %s\n",
			       libusb_error_name(ret));
			goto error4;
		}
	}

	return 0;

error4:
	if (state->attached == 1)
		libusb_attach_kernel_driver(state->handle, 0);

error3:
	libusb_close(state->handle);

error2:
	libusb_free_device_list(list, 1);

error1:
	libusb_exit(state->ctx);
	return 1;
}
Example #27
0
static int add_adapter(void *data, struct libusb_device *dev)
{
   int rc;
   struct libusb_device_descriptor desc;
   const char *device_name         = NULL;
   struct libusb_adapter *old_head = NULL;
   struct libusb_hid          *hid = (struct libusb_hid*)data;
   struct libusb_adapter *adapter  = (struct libusb_adapter*)
      calloc(1, sizeof(struct libusb_adapter));

   if (!adapter)
      return -1;

   if (!hid)
   {
      free(adapter);
      RARCH_ERR("Allocation of adapter failed.\n");
      return -1;
   }

   rc = libusb_get_device_descriptor(dev, &desc);

   if (rc != LIBUSB_SUCCESS)
   {
      RARCH_ERR("Error getting device descriptor.\n");
      goto error;
   }

   adapter->device = dev;

   libusb_get_description(adapter->device, adapter);

   if (adapter->endpoint_in == 0)
   {
      RARCH_ERR("Could not find HID config for device.\n");
      goto error;
   }

   rc = libusb_open (adapter->device, &adapter->handle);

   if (rc != LIBUSB_SUCCESS)
   {
      RARCH_ERR("Error opening device 0x%p (VID/PID: %04x:%04x).\n",
            (void*)adapter->device, desc.idVendor, desc.idProduct);
      goto error;
   }

   if (desc.iManufacturer)
   {
      libusb_get_string_descriptor_ascii(adapter->handle,
            desc.iManufacturer, adapter->manufacturer_name,
            sizeof(adapter->manufacturer_name));
#if 0
      RARCH_ERR(" Adapter Manufacturer name: %s\n",
            adapter->manufacturer_name);
#endif
   }

   if (desc.iProduct)
   {
      libusb_get_string_descriptor_ascii(adapter->handle,
            desc.iProduct, adapter->name,
            sizeof(adapter->name));
#if 0
      RARCH_ERR(" Adapter name: %s\n", adapter->name);
#endif
   }

   device_name   = (const char*)adapter->name;

   if (string_is_empty((const char*)adapter->name))
      goto error;

   adapter->send_control_lock = slock_new();
   adapter->send_control_buffer = fifo_new(4096);

   if (!adapter->send_control_lock || !adapter->send_control_buffer)
   {
      RARCH_ERR("Error creating send control buffer.\n");
      goto error;
   }

   adapter->slot = pad_connection_pad_init(hid->slots,
         device_name, desc.idVendor, desc.idProduct,
         adapter, &libusb_hid_device_send_control);

   if (adapter->slot == -1)
      goto error;

   if (!pad_connection_has_interface(hid->slots, adapter->slot))
   {
      RARCH_ERR(" Interface not found (%s).\n", adapter->name);
      goto error;
   }

   RARCH_LOG("Interface found: [%s].\n", adapter->name);

   if (libusb_kernel_driver_active(adapter->handle, 0) == 1
         && libusb_detach_kernel_driver(adapter->handle, 0))
   {
      RARCH_ERR("Error detaching handle 0x%p from kernel.\n", adapter->handle);
      goto error;
   }

   rc = libusb_claim_interface(adapter->handle, adapter->interface_number);

   if (rc != LIBUSB_SUCCESS)
   {
      RARCH_ERR("Error claiming interface %d .\n", adapter->interface_number);
      goto error;
   }

   RARCH_LOG("Device 0x%p attached (VID/PID: %04x:%04x).\n",
         adapter->device, desc.idVendor, desc.idProduct);

   libusb_hid_device_add_autodetect(adapter->slot,
         device_name, libusb_hid.ident, desc.idVendor, desc.idProduct);

   adapter->hid = hid;
   adapter->thread = sthread_create(adapter_thread, adapter);

   if (!adapter->thread)
   {
      RARCH_ERR("Error initializing adapter thread.\n");
      goto error;
   }

   old_head      = adapters.next;
   adapters.next = adapter;
   adapter->next = old_head;

   return 0;

error:
   if (adapter->thread)
      sthread_join(adapter->thread);
   if (adapter->send_control_lock)
      slock_free(adapter->send_control_lock);
   if (adapter->send_control_buffer)
      fifo_free(adapter->send_control_buffer);
   if (adapter)
      free(adapter);
   return -1;
}
Example #28
0
/* Helper to open a libusb device that matches vid, pid, product string and/or serial string.
 * Set any field to 0 as a wildcard. If the device is found true is returned, with ctx containing
 * the already opened handle. ctx->interface must be set to the desired interface (channel) number
 * prior to calling this function. */
static bool open_matching_device(struct mpsse_ctx *ctx, const uint16_t *vid, const uint16_t *pid,
	const char *product, const char *serial, const char *location)
{
	libusb_device **list;
	struct libusb_device_descriptor desc;
	struct libusb_config_descriptor *config0;
	int err;
	bool found = false;
	ssize_t cnt = libusb_get_device_list(ctx->usb_ctx, &list);
	if (cnt < 0)
		LOG_ERROR("libusb_get_device_list() failed with %s", libusb_error_name(cnt));

	for (ssize_t i = 0; i < cnt; i++) {
		libusb_device *device = list[i];

		err = libusb_get_device_descriptor(device, &desc);
		if (err != LIBUSB_SUCCESS) {
			LOG_ERROR("libusb_get_device_descriptor() failed with %s", libusb_error_name(err));
			continue;
		}

		if (vid && *vid != desc.idVendor)
			continue;
		if (pid && *pid != desc.idProduct)
			continue;

		err = libusb_open(device, &ctx->usb_dev);
		if (err != LIBUSB_SUCCESS) {
			LOG_ERROR("libusb_open() failed with %s",
				  libusb_error_name(err));
			continue;
		}

		if (location && !device_location_equal(device, location)) {
			libusb_close(ctx->usb_dev);
			continue;
		}

		if (product && !string_descriptor_equal(ctx->usb_dev, desc.iProduct, product)) {
			libusb_close(ctx->usb_dev);
			continue;
		}

		if (serial && !string_descriptor_equal(ctx->usb_dev, desc.iSerialNumber, serial)) {
			libusb_close(ctx->usb_dev);
			continue;
		}

		found = true;
		break;
	}

	libusb_free_device_list(list, 1);

	if (!found) {
		LOG_ERROR("no device found");
		return false;
	}

	err = libusb_get_config_descriptor(libusb_get_device(ctx->usb_dev), 0, &config0);
	if (err != LIBUSB_SUCCESS) {
		LOG_ERROR("libusb_get_config_descriptor() failed with %s", libusb_error_name(err));
		libusb_close(ctx->usb_dev);
		return false;
	}

	/* Make sure the first configuration is selected */
	int cfg;
	err = libusb_get_configuration(ctx->usb_dev, &cfg);
	if (err != LIBUSB_SUCCESS) {
		LOG_ERROR("libusb_get_configuration() failed with %s", libusb_error_name(err));
		goto error;
	}

	if (desc.bNumConfigurations > 0 && cfg != config0->bConfigurationValue) {
		err = libusb_set_configuration(ctx->usb_dev, config0->bConfigurationValue);
		if (err != LIBUSB_SUCCESS) {
			LOG_ERROR("libusb_set_configuration() failed with %s", libusb_error_name(err));
			goto error;
		}
	}

	/* Try to detach ftdi_sio kernel module */
	err = libusb_detach_kernel_driver(ctx->usb_dev, ctx->interface);
	if (err != LIBUSB_SUCCESS && err != LIBUSB_ERROR_NOT_FOUND
			&& err != LIBUSB_ERROR_NOT_SUPPORTED) {
		LOG_ERROR("libusb_detach_kernel_driver() failed with %s", libusb_error_name(err));
		goto error;
	}

	err = libusb_claim_interface(ctx->usb_dev, ctx->interface);
	if (err != LIBUSB_SUCCESS) {
		LOG_ERROR("libusb_claim_interface() failed with %s", libusb_error_name(err));
		goto error;
	}

	/* Reset FTDI device */
	err = libusb_control_transfer(ctx->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
			SIO_RESET_REQUEST, SIO_RESET_SIO,
			ctx->index, NULL, 0, ctx->usb_write_timeout);
	if (err < 0) {
		LOG_ERROR("failed to reset FTDI device: %s", libusb_error_name(err));
		goto error;
	}

	switch (desc.bcdDevice) {
	case 0x500:
		ctx->type = TYPE_FT2232C;
		break;
	case 0x700:
		ctx->type = TYPE_FT2232H;
		break;
	case 0x800:
		ctx->type = TYPE_FT4232H;
		break;
	case 0x900:
		ctx->type = TYPE_FT232H;
		break;
	default:
		LOG_ERROR("unsupported FTDI chip type: 0x%04x", desc.bcdDevice);
		goto error;
	}

	/* Determine maximum packet size and endpoint addresses */
	if (!(desc.bNumConfigurations > 0 && ctx->interface < config0->bNumInterfaces
			&& config0->interface[ctx->interface].num_altsetting > 0))
		goto desc_error;

	const struct libusb_interface_descriptor *descriptor;
	descriptor = &config0->interface[ctx->interface].altsetting[0];
	if (descriptor->bNumEndpoints != 2)
		goto desc_error;

	ctx->in_ep = 0;
	ctx->out_ep = 0;
	for (int i = 0; i < descriptor->bNumEndpoints; i++) {
		if (descriptor->endpoint[i].bEndpointAddress & 0x80) {
			ctx->in_ep = descriptor->endpoint[i].bEndpointAddress;
			ctx->max_packet_size =
					descriptor->endpoint[i].wMaxPacketSize;
		} else {
			ctx->out_ep = descriptor->endpoint[i].bEndpointAddress;
		}
	}

	if (ctx->in_ep == 0 || ctx->out_ep == 0)
		goto desc_error;

	libusb_free_config_descriptor(config0);
	return true;

desc_error:
	LOG_ERROR("unrecognized USB device descriptor");
error:
	libusb_free_config_descriptor(config0);
	libusb_close(ctx->usb_dev);
	return false;
}
Example #29
0
static int scpi_usbtmc_libusb_open(void *priv)
{
	struct scpi_usbtmc_libusb *uscpi = priv;
	struct sr_usb_dev_inst *usb = uscpi->usb;
	struct libusb_device *dev;
	struct libusb_device_descriptor des;
	struct libusb_config_descriptor *confdes;
	const struct libusb_interface_descriptor *intfdes;
	const struct libusb_endpoint_descriptor *ep;
	int confidx, intfidx, epidx, config = 0;
	uint8_t capabilities[24];
	int ret, found = 0;

	if (usb->devhdl)
		return SR_OK;

	if (sr_usb_open(uscpi->ctx->libusb_ctx, usb) != SR_OK)
		return SR_ERR;

	dev = libusb_get_device(usb->devhdl);
	if ((ret = libusb_get_device_descriptor(dev, &des))) {
		sr_err("Failed to get device descriptor: %s.",
		       libusb_error_name(ret));
		return SR_ERR;
	}

	for (confidx = 0; confidx < des.bNumConfigurations; confidx++) {
		if (libusb_get_config_descriptor(dev, confidx, &confdes) != 0) {
			sr_err("Failed to get configuration descriptor: %s.",
			       libusb_error_name(ret));
			continue;
		}
		for (intfidx = 0; intfidx < confdes->bNumInterfaces; intfidx++) {
			intfdes = confdes->interface[intfidx].altsetting;
			if (intfdes->bInterfaceClass    != LIBUSB_CLASS_APPLICATION ||
			    intfdes->bInterfaceSubClass != SUBCLASS_USBTMC          ||
			    intfdes->bInterfaceProtocol != USBTMC_USB488)
				continue;
			uscpi->interface = intfdes->bInterfaceNumber;
			sr_dbg("Interface %d", uscpi->interface);
			config = confdes->bConfigurationValue;
			sr_dbg("Configuration %d", config);
			for (epidx = 0; epidx < intfdes->bNumEndpoints; epidx++) {
				ep = &intfdes->endpoint[epidx];
				if (ep->bmAttributes == LIBUSB_TRANSFER_TYPE_BULK &&
				    !(ep->bEndpointAddress & (LIBUSB_ENDPOINT_DIR_MASK))) {
					uscpi->bulk_out_ep = ep->bEndpointAddress;
					sr_dbg("Bulk OUT EP %d", uscpi->bulk_out_ep);
				}
				if (ep->bmAttributes == LIBUSB_TRANSFER_TYPE_BULK &&
				    ep->bEndpointAddress & (LIBUSB_ENDPOINT_DIR_MASK)) {
					uscpi->bulk_in_ep = ep->bEndpointAddress;
					sr_dbg("Bulk IN EP %d", uscpi->bulk_in_ep);
				}
				if (ep->bmAttributes == LIBUSB_TRANSFER_TYPE_INTERRUPT &&
				    ep->bEndpointAddress & (LIBUSB_ENDPOINT_DIR_MASK)) {
					uscpi->interrupt_ep = ep->bEndpointAddress;
					sr_dbg("Interrupt EP %d", uscpi->interrupt_ep);
				}
			}
			found = 1;
		}
		libusb_free_config_descriptor(confdes);
		if (found)
			break;
	}

	if (!found) {
		sr_err("Failed to find USBTMC interface.");
		return SR_ERR;
	}

	if (libusb_kernel_driver_active(usb->devhdl, uscpi->interface) == 1) {
		if ((ret = libusb_detach_kernel_driver(usb->devhdl,
		                                       uscpi->interface)) < 0) {
			sr_err("Failed to detach kernel driver: %s.",
			       libusb_error_name(ret));
			return SR_ERR;
		}
		uscpi->detached_kernel_driver = 1;
	}

	if ((ret = libusb_set_configuration(usb->devhdl, config))) {
		sr_err("Failed to set configuration: %s.",
		       libusb_error_name(ret));
		return SR_ERR;
	}

	if ((ret = libusb_claim_interface(usb->devhdl, uscpi->interface))) {
		sr_err("Failed to claim interface: %s.",
		       libusb_error_name(ret));
		return SR_ERR;
	}

	if ((ret = libusb_clear_halt(usb->devhdl, uscpi->bulk_in_ep)) < 0) {
		sr_err("Failed to clear halt/stall condition for EP %d: %s.",
		       uscpi->bulk_in_ep, libusb_error_name(ret));
		return SR_ERR;
	}
	if ((ret = libusb_clear_halt(usb->devhdl, uscpi->bulk_out_ep)) < 0) {
		sr_err("Failed to clear halt/stall condition for EP %d: %s.",
		       uscpi->bulk_out_ep, libusb_error_name(ret));
		return SR_ERR;
	}
	if ((ret = libusb_clear_halt(usb->devhdl, uscpi->interrupt_ep)) < 0) {
		sr_err("Failed to clear halt/stall condition for EP %d: %s.",
		       uscpi->interrupt_ep, libusb_error_name(ret));
		return SR_ERR;
	}

	/* Get capabilities. */
	ret = libusb_control_transfer(usb->devhdl,
	                              LIBUSB_ENDPOINT_IN         |
	                              LIBUSB_REQUEST_TYPE_CLASS  |
	                              LIBUSB_RECIPIENT_INTERFACE,
	                              GET_CAPABILITIES, 0,
	                              uscpi->interface,
	                              capabilities, sizeof(capabilities),
	                              TRANSFER_TIMEOUT);
	if (ret == sizeof(capabilities)) {
		uscpi->usbtmc_int_cap = capabilities[ 4];
		uscpi->usbtmc_dev_cap = capabilities[ 5];
		uscpi->usb488_dev_cap = capabilities[15];
	}
	sr_dbg("Device capabilities: %s%s%s%s%s, %s, %s",
	       uscpi->usb488_dev_cap & USB488_DEV_CAP_SCPI       ? "SCPI, "    : "",
	       uscpi->usbtmc_dev_cap & USBTMC_DEV_CAP_TERMCHAR   ? "TermChar, ": "",
	       uscpi->usbtmc_int_cap & USBTMC_INT_CAP_LISTEN_ONLY? "L3, " :
	       uscpi->usbtmc_int_cap & USBTMC_INT_CAP_TALK_ONLY  ? ""     : "L4, ",
	       uscpi->usbtmc_int_cap & USBTMC_INT_CAP_TALK_ONLY  ? "T5, " :
	       uscpi->usbtmc_int_cap & USBTMC_INT_CAP_LISTEN_ONLY? ""     : "T6, ",
	       uscpi->usb488_dev_cap & USB488_DEV_CAP_SR1        ? "SR1"  : "SR0",
	       uscpi->usb488_dev_cap & USB488_DEV_CAP_RL1        ? "RL1"  : "RL0",
	       uscpi->usb488_dev_cap & USB488_DEV_CAP_DT1        ? "DT1"  : "DT0");

	return SR_OK;
}
Example #30
0
/*-----------------------------------------------------------------------------
 * Name      :  usb_create_from_uri
 * Purpose   :  Create USB port from URI string
 * Inputs    :  p   : port structure
 *              uri : URI string
 * Outputs   :  <>
 * Return    :  APS_OK or error code
 * -----------------------------------------------------------------------------*/
int usb_create_from_uri(aps_port_t *p,struct aps_uri *su)
{
	libusb_device * dev;
	libusb_device_handle * h;
	int r;
	ssize_t cnt;
	int i;
	const char *vidstr;
	const char *pidstr;
	int vid, pid;

	p->set.usb.busnum = 0;
	p->set.usb.devaddr = 0;

	vidstr = uri_get_opt(su,"vid");
	pidstr = uri_get_opt(su,"pid");

#ifdef DEBUG
	fprintf(stderr, "DEBUG: in %s()\n", __func__);
#endif
	if (devcnt == 0)
	{
		return APS_USB_DEVICE_NOT_FOUND;
	}

	if (vidstr == 0 || pidstr == 0)
	{
		return APS_INVALID_URI;
	}

	if (sscanf(vidstr,"%i",&vid)!=1) {
		return APS_INVALID_URI;
	}
	if (sscanf(pidstr,"%i",&pid)!=1) {
		return APS_INVALID_URI;
	}

	i = 0;
	while ((dev = devs[i]) != NULL)
	{
		struct libusb_device_descriptor desc;

		r = libusb_get_device_descriptor(dev, &desc);
		if (r < 0)
		{
			fprintf(stderr, "ERROR: failed to get device descriptor");
			libusb_free_device_list(devs, 1);
			libusb_exit(NULL);
			return APS_USB_DEVICE_NOT_FOUND;
		}

		//if (desc.idVendor == APS_VENDOR_ID || desc.idVendor == APS_VENDOR_ID0)
		if (desc.idVendor == vid && desc.idProduct == pid)
		{
#ifdef DEBUG
			fprintf(stderr, "DEBUG: ok, aps printer found...\n");
#endif
			break;
		}
		i ++;
	}

	if (dev == 0)
	{
#ifdef DEBUG
		fprintf(stderr, "DEBUG: aps printer not found, exiting\n");
#endif
		libusb_free_device_list(devs, 1);
		libusb_exit(NULL);
		devs = 0;
		devcnt = 0;
		return APS_USB_DEVICE_NOT_FOUND;
	}
#ifdef DEBUG
	fprintf(stderr, "DEBUG: printer at bus: %i\n", libusb_get_bus_number(dev));
	fprintf(stderr, "DEBUG: printer at address: %i\n", libusb_get_device_address(dev));
#endif
	/* shopov(04072011) - added */
	p->set.usb.busnum = libusb_get_bus_number(dev);
	p->set.usb.devaddr = libusb_get_device_address(dev);
	return APS_OK;
	/* shopov(04072011) - end added */
#if 0	

	if (libusb_open(dev, &h))
	{
		fprintf(stderr, "DEBUG: aps printer not found, exiting\n");
		libusb_free_device_list(devs, 1);
		libusb_exit(NULL);
		devs = 0;
		devcnt = 0;
		return APS_USB_DEVICE_NOT_FOUND;
	}
	r = libusb_kernel_driver_active(h, 0);
	if (r != 0 && r != 1)
	{
close_and_return:		
		libusb_close(h);
		fprintf(stderr, "DEBUG: aps printer not found, exiting\n");
		libusb_free_device_list(devs, 1);
		libusb_exit(NULL);
		devs = 0;
		devcnt = 0;
		return APS_IO_ERROR;
	}
	p->set.usb.was_kernel_driver_attached = r;
	if (r)
	{
		r = libusb_detach_kernel_driver(h, 0);
		if (r != 0)
			goto close_and_return;
	}
	r = libusb_claim_interface(h, 0);
	if (r != 0)
		goto close_and_return;

	p->set.usb.pdev = dev;
	p->set.usb.hdev = h;

	return APS_OK;
#endif


#if 0
	struct stat st;
	const char *device;
	const char *usbfs;
	const char *path;
	const char *vidstr;
	const char *pidstr;

	/*get device name*/
	device = uri_get_device(su);

	printf("Device:%s\n",device);

	if (stat(device,&st)<0) {
		return APS_IO_ERROR;
	}

	printf("stats ok!:\n");

	if (S_ISCHR(st.st_mode)) {
		printf("S_ISCHR =============ok!:\n");
		/*build connection path from device name*/
		return usb_create(p,device);
	}
	else if (S_ISDIR(st.st_mode)) {
		printf("S_ISDIR ok!:\n");
		usbfs = device;
	}
	else {
		printf("Ke dall !  ok!:\n");
		return APS_INVALID_URI;
	}

	/*get path, vendor ID and product ID parameters*/
	path = uri_get_opt(su,"path");
	vidstr = uri_get_opt(su,"vid");
	pidstr = uri_get_opt(su,"pid");

	if (path!=NULL) {
		/*create USB port from connection path*/
		/*just copy path into port structure*/

		/*set usbfs parameter*/
		if (strlen(usbfs)>sizeof(p->set.usb.usbfs)-1) {
			return APS_NAME_TOO_LONG;
		}
		else {
			strcpy(p->set.usb.usbfs,usbfs);
		}

		/*copy connection path*/
		if (strlen(path)>sizeof(p->set.usb.path)-1) {
			return APS_NAME_TOO_LONG;
		}
		else {
			strcpy(p->set.usb.path,path);
		}
	}
	else if (vidstr!=NULL && pidstr!=NULL) {
		/*create USB port from (vendor ID,product ID) pair*/
		/*build connection path*/

		int vid;
		int pid;

		if (sscanf(vidstr,"%i",&vid)!=1) {
			return APS_INVALID_URI;
		}
		if (sscanf(pidstr,"%i",&pid)!=1) {
			return APS_INVALID_URI;
		}

		return usb_create_from_id(p,usbfs,vid,pid);
	}
	else {
		return APS_INVALID_URI;
	}

	return APS_OK;
#endif
	return APS_OK;
}