Пример #1
0
libusb_device_handle *
open_path(char const *path)
{
    return usb_executor->await([=] {
            libusb_device **devs = NULL;
            libusb_device *dev = NULL;
            libusb_device_handle *handle = NULL;
            int i = 0;

            libusb_get_device_list(NULL, &devs);
            while ((dev = devs[i++]) != NULL) {
                    char devpath[10];
                    snprintf(devpath, sizeof(devpath), "%04x:%04x",
                            libusb_get_bus_number(dev),
                            libusb_get_device_address(dev));
                    if (strncmp(devpath, path, sizeof(devpath)) == 0) {
                            if (libusb_open(dev, &handle) == 0) {
#if !defined(__FreeBSD__) || __FreeBSD_version >= 1100000
                                    libusb_set_auto_detach_kernel_driver(handle, 1);
#endif
                                    if (libusb_claim_interface(handle, 0)) {
                                            libusb_close(handle);
                                            handle = NULL;
                                    }
                            }
                            break;
                    }
            }
            libusb_free_device_list(devs, 1);
            return handle;
        });
}
Пример #2
0
static int open_device(libusb_device* device)
{
    int errno;
    errno = libusb_open(device, &device_handle);

    if (errno < 0)
    {
        fprintf(stderr, "Failed to open USB device %s\n", libusb_error_name(errno));
        return 1;
    }

    errno = libusb_set_auto_detach_kernel_driver(device_handle, 1);
    if (errno < 0)
    {
        printf("Failed to call auto detach USB device %s\n", libusb_error_name(errno));
        return 1;
    }

    errno = libusb_claim_interface(device_handle, 3);

    if (errno < 0)
    {
        printf("Failed to claim USB interface %s\n", libusb_error_name(errno));
        return 1;
    }

    return 0;
}
Пример #3
0
bool
claimInterface(struct libusb_device_handle *handle, int interface, bool autoconnect)
{
  int ret = 0;
  bool success = true;

  if (autoconnect == 0)
  {
    /* detach the kernel driver */
    if(libusb_kernel_driver_active(handle, interface) == 1)
    {
      log_info ("Kernel Driver Active.");
      if(libusb_detach_kernel_driver(handle, interface) == 0) //detach it
        log_info ("Kernel Driver Detached.");
    }
  }
  else
  {
    libusb_set_auto_detach_kernel_driver(handle, 1);
  }

  if (IS_LINUX)
  {
    ret = libusb_claim_interface(handle, interface);
    if (ret < 0)
    {
      log_err ("Unable to claim interface.");
      success = false;
    }
  }

  return success;
}
Пример #4
0
int main(void)
{
	libusb_device **devs;
	int r;
	ssize_t cnt;
	tablet_t tablet;
	xwrap_t xwrap;

	unsigned char data[10];
	int length = 10;
	int transferred = -1;

	signal(SIGINT, interrupt);

	r = libusb_init(NULL);
	if (r < 0)
		return r;

	cnt = libusb_get_device_list(NULL, &devs);
	if (cnt < 0)
		return (int) cnt;


	libusb_device* t_dev = tablet_get_device(devs);
	if (t_dev == NULL) {
		return 1;
	}
	libusb_device_handle* handle;
	if((r = libusb_open(t_dev, &handle))) {
		perror("Can't open device");
		return r;
	}

	tablet_init(&tablet);
	xwrap_init(&xwrap);
	if ((r = libusb_set_auto_detach_kernel_driver(handle, 1))) {
		perror("libusb_set_auto_detach_kernel_driver");
	}
	if ((r = libusb_claim_interface(handle, 0))) {
		perror("libusb_claim_interface");
		return r;
	}
	while(!interrupt_sent) {
		r = libusb_interrupt_transfer(handle, 0x81, data, length, &transferred, 0);
		tablet_parse_data(&tablet, data, &xwrap);
	}

	libusb_release_interface(handle, 0);
	libusb_close(handle);
	libusb_free_device_list(devs, 1);

	libusb_exit(NULL);
	return 0;
}
Пример #5
0
transport_ptr_t find_usb_transport(const usb_context_ptr_t &ctx, const notifier_t *notifier)
{
    device_ptr_t dev;
    TA_INFO() << "Enumerating USB devices";
    while (!dev)
    {
        dev = enumerate_devices(ctx);
        if (!dev || libusb_reset_device(dev.get()) != LIBUSB_SUCCESS)
            notifier->sleep(1000);
        TA_TRACE() << "ACC device not found, retrying";
    }
    TA_INFO() << "Found an ACC device.";
    // Always detach the kernel first
    libusb_set_auto_detach_kernel_driver(dev.get(), 1);

    return transport_ptr_t(new transport_t(ctx, dev, notifier));
}
Пример #6
0
int main()
{
  libusb_context *context;
  libusb_device_handle *handle;
  int configuration_value = 1, interface_number = 1, rv;

  rv = libusb_init(&context);
  if (rv != 0)
    {
      usbx_strerror(rv);
      return -1;
    }
  libusb_setlocale("zh");
  libusb_set_debug(context, LIBUSB_LOG_LEVEL_DEBUG);

  handle = libusb_open_device_with_vid_pid(context, 0x16C0, 0x06EA);
  if (!handle)
    {
      libusb_exit(context);
      return -1;
    }
  libusb_set_auto_detach_kernel_driver(handle, 1);

  rv = libusb_set_configuration(handle, configuration_value);
  if (rv != 0)
    {
      usbx_strerror(rv);
      libusb_close(handle);
      libusb_exit(context);
      return -1;
    }
  rv = libusb_claim_interface(handle, interface_number);
  if (rv != 0)
    {
      usbx_strerror(rv);
      libusb_close(handle);
      libusb_exit(context);
      return -1;
    }
  readcard(handle);

  libusb_release_interface(handle, interface_number);
  libusb_close(handle);
  libusb_exit(context);
  return 0;
}
Пример #7
0
int main(int argc, char *argv[])
{
  libusb_context* ctx = NULL;
  int ret = -1;
  int status;
  int i;

  if(read_file() < 0)
  {
    return -1;
  }

  if(libusb_init(&ctx))
  {
    fprintf(stderr, "Can't initialize libusb.\n");
    return -1;
  }

  //libusb_set_debug(ctx, 128);

  devh = libusb_open_device_with_vid_pid(ctx, VENDOR, PRODUCT);
  if(!devh)
  {
    fprintf(stderr, "No device found on USB busses.\n");
#ifdef WIN32
    Sleep(2000);
#else
    sleep(2);
#endif
    libusb_exit(ctx);
    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 > 0)
  {
    ret = libusb_detach_kernel_driver(devh, 0);
    if(ret < 0)
    {
      fprintf(stderr, "Can't detach kernel driver: %s.\n", libusb_strerror(ret));
      libusb_close(devh);
      libusb_exit(ctx);
      return -1;
    }
  }
#endif
#endif
  ret = libusb_claim_interface(devh, 0);
  if(ret < 0)
  {
    fprintf(stderr, "Can't claim interface: %s.\n", libusb_strerror(ret));
    libusb_close(devh);
    libusb_exit(ctx);
    return -1;
  }

  status = process_device(devh);

  process_transfer(&cleanup);

  ret = libusb_release_interface(devh, 0);
  if(ret < 0)
  {
    fprintf(stderr, "Can't release interface: %s.\n", libusb_strerror(ret));
  }

#if !defined(LIBUSB_API_VERSION) && !defined(LIBUSBX_API_VERSION)
#ifndef WIN32
  ret = libusb_attach_kernel_driver(devh, 0);
  if(ret < 0)
  {
    fprintf(stderr, "Can't attach kernel driver: %s.\n", libusb_strerror(ret));
  }
#endif
#endif

  free(transfers);

  libusb_close(devh);
  libusb_exit(ctx);

  return ret;

}
Пример #8
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;
}
Пример #9
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();
        }
    }
}
Пример #10
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;
}
Пример #11
0
void usbInit()
{
	int res, actualLen;
	libusb_device *usbRawDevice;
	libusb_device_descriptor usbDevDesc;
	libusb_config_descriptor *usbConfigDesc;
	const libusb_interface_descriptor *usbIface;
	const libusb_endpoint_descriptor *usbEndpointDesc;
	const usbIfaceAssoc *usbInterfaceAssoc;
	const usbCDCConfig *usbCDCDesc;

	if (libusb_init(&usbContext) != 0)
		die("Error: Could not initialise libusb-1.0\n");

	usbDevice = libusb_open_device_with_vid_pid(usbContext, 0x1CBE, 0x00FD);
	if (usbDevice == NULL)
	{
		libusb_exit(usbContext);
		die("Error: Could not find a Tiva C Launchpad to connect to\n");
	}
	usbRawDevice = libusb_get_device(usbDevice);

	if (libusb_get_device_descriptor(usbRawDevice, &usbDevDesc) != 0 || usbDevDesc.bNumConfigurations != 1)
	{
		usbInitCleanup();
		die("Error: libusb could not get the device descriptor for the Tiva C Launchpad\n");
	}

	if (libusb_get_config_descriptor(usbRawDevice, 0, &usbConfigDesc) != 0)
	{
		usbInitCleanup();
		die("Error: libusb could not get the configuration descriptor for the Tiva C Launchpad\n");
	}
	else if (usbConfigDesc->bLength != 9 || usbConfigDesc->bDescriptorType != 2 ||
		usbConfigDesc->bNumInterfaces != 4 || usbConfigDesc->extra_length != sizeof(usbIfaceAssoc))
	{
		libusb_free_config_descriptor(usbConfigDesc);
		usbInitCleanup();
		die("Error: The descriptor returned by the device claiming to be a Tiva C Launchpad is invalid\n");
	}

	usbInterfaceAssoc = (const usbIfaceAssoc *)usbConfigDesc->extra;
	if (usbInterfaceAssoc->bLength != 8 || usbInterfaceAssoc->bDescriptorType != 11 ||
		usbInterfaceAssoc->bInterfaceCount != 2 || usbInterfaceAssoc->bFirstInterface >= usbConfigDesc->bNumInterfaces)
	{
		libusb_free_config_descriptor(usbConfigDesc);
		usbInitCleanup();
		die("Error: The interface association returned by the device claiming to be the Tiva C Launchpad is invalid\n");
	}

	usbIface = usbConfigDesc->interface[usbInterfaceAssoc->bFirstInterface].altsetting;
	if (usbIface->bNumEndpoints != 1 || usbIface->extra_length != sizeof(usbCDCConfig))
	{
		libusb_free_config_descriptor(usbConfigDesc);
		usbInitCleanup();
		die("Error: The interface descriptor that is supposed to be for the control interface is invalid\n");
	}
	usbCDCDesc = (const usbCDCConfig *)usbIface->extra;
	if (usbCDCDesc->bHeaderLen != 5 || usbCDCDesc->bcdCDC != 0x0110 ||
		usbCDCDesc->bACMLen != 4 || usbCDCDesc->bUnionLen != 5 ||
		usbCDCDesc->bCallLen != 5)
	{
		libusb_free_config_descriptor(usbConfigDesc);
		usbInitCleanup();
		die("Error: The CDC descriptor that is provided by the control interface is invalid\n");
	}
	usbEndpointDesc = &usbIface->endpoint[0];
	ctrlEndpoint = usbEndpointDesc->bEndpointAddress;

	usbIface = usbConfigDesc->interface[usbCDCDesc->iDataInterface].altsetting;
	if (usbIface->bNumEndpoints != 2 || usbIface->extra_length != 0)
	{
		libusb_free_config_descriptor(usbConfigDesc);
		usbInitCleanup();
		die("Error: The interface descriptor that is supposed to be for the data interface is invalid\n");
	}
	usbEndpointDesc = &usbIface->endpoint[0];
	inEndpoint = usbEndpointDesc->bEndpointAddress;
	usbEndpointDesc = &usbIface->endpoint[1];
	outEndpoint = usbEndpointDesc->bEndpointAddress;

	ctrlInterface = usbInterfaceAssoc->bFirstInterface;
	dataInterface = usbCDCDesc->iDataInterface;
	libusb_set_configuration(usbDevice, usbConfigDesc->bConfigurationValue);
	libusb_free_config_descriptor(usbConfigDesc);

	libusb_set_auto_detach_kernel_driver(usbDevice, true);
	if (libusb_claim_interface(usbDevice, ctrlInterface) != 0 ||
		libusb_claim_interface(usbDevice, dataInterface) != 0)
	{
		usbDeinit();
		die("Error: Could not claim the Tiva C Launchpad virtual serial port interface\n");
	}

	/* Set the port baud rate */
	*((uint32_t *)ctrlData) = 115200;
	/* 1 stop bit, no parity, 8-bit */
	ctrlData[4] = 0;
	ctrlData[5] = 0;
	ctrlData[6] = 8;
	res = libusb_control_transfer(usbDevice, 0x21, CDC_SET_LINE_CODING, 0, ctrlInterface, ctrlData, 7, 10);
	if (res != 7)
	{
		usbDeinit();
		die("libusb returned %d: %s\n", res, libusb_strerror(res));
	}

	res = libusb_control_transfer(usbDevice, 0xA1, CDC_GET_LINE_CODING, 0, ctrlInterface, ctrlData, 7, 10);
	if (res != 7)
	{
		usbDeinit();
		die("libusb returned %d: %s\n", res, libusb_strerror(res));
	}

	res = libusb_control_transfer(usbDevice, 0x21, CDC_SET_CONTROL_LINE_STATE, 0, ctrlInterface, NULL, 0, 10);
	if (res != 0)
	{
		usbDeinit();
		die("libusb returned %d: %s\n", res, libusb_strerror(res));
	}
}
Пример #12
0
int main(int argc, char*argv[])
{
    fx_known_device known_device[] = FX_KNOWN_DEVICES;
    const char *path[] = { NULL, NULL };
    const char *device_id = NULL;
    const char *device_path = getenv("DEVICE");
    const char *type = NULL;
    const char *fx_name[FX_TYPE_MAX] = FX_TYPE_NAMES;
    const char *ext, *img_name[] = IMG_TYPE_NAMES;
    int fx_type = FX_TYPE_UNDEFINED, img_type[ARRAYSIZE(path)];
    int i, j, opt, status;
    unsigned vid = 0, pid = 0;
    unsigned busnum = 0, devaddr = 0, _busnum, _devaddr;
    libusb_device *dev, **devs;
    libusb_device_handle *device = NULL;
    struct libusb_device_descriptor desc;

    while ((opt = getopt(argc, argv, "qvV?hd:p:i:I:t:")) != EOF)
        switch (opt) {

        case 'd':
            device_id = optarg;
            if (sscanf(device_id, "%x:%x" , &vid, &pid) != 2 ) {
                fputs ("please specify VID & PID as \"vid:pid\" in hexadecimal format\n", stderr);
                return -1;
            }
            break;

        case 'p':
            device_path = optarg;
            if (sscanf(device_path, "%u,%u", &busnum, &devaddr) != 2 ) {
                fputs ("please specify bus number & device number as \"bus,dev\" in decimal format\n", stderr);
                return -1;
            }
            break;

        case 'i':
        case 'I':
            path[FIRMWARE] = optarg;
            break;

        case 'V':
            puts(FXLOAD_VERSION);
            return 0;

        case 't':
            type = optarg;
            break;

        case 'v':
            verbose++;
            break;

        case 'q':
            verbose--;
            break;

        case '?':
        case 'h':
        default:
            return print_usage(-1);

    }

    if (path[FIRMWARE] == NULL) {
        logerror("no firmware specified!\n");
        return print_usage(-1);
    }
    if ((device_id != NULL) && (device_path != NULL)) {
        logerror("only one of -d or -p can be specified\n");
        return print_usage(-1);
    }

    /* determine the target type */
    if (type != NULL) {
        for (i=0; i<FX_TYPE_MAX; i++) {
            if (strcmp(type, fx_name[i]) == 0) {
                fx_type = i;
                break;
            }
        }
        if (i >= FX_TYPE_MAX) {
            logerror("illegal microcontroller type: %s\n", type);
            return print_usage(-1);
        }
    }

    /* open the device using libusb */
    status = libusb_init(NULL);
    if (status < 0) {
        logerror("libusb_init() failed: %s\n", libusb_error_name(status));
        return -1;
    }
    libusb_set_debug(NULL, verbose);

    /* try to pick up missing parameters from known devices */
    if ((type == NULL) || (device_id == NULL) || (device_path != NULL))
    {
        if (libusb_get_device_list(NULL, &devs) < 0)
        {
            logerror("libusb_get_device_list() failed: %s\n", libusb_error_name(status));
            goto err;
        }
        for (i=0; (dev=devs[i]) != NULL; i++)
        {
            _busnum = libusb_get_bus_number(dev);
            _devaddr = libusb_get_device_address(dev);
            if ((type != NULL) && (device_path != NULL))
            {
                printf("Check Point 1\n");
                // if both a type and bus,addr were specified, we just need to find our match
                if ((libusb_get_bus_number(dev) == busnum) && (libusb_get_device_address(dev) == devaddr))
                {
                  printf("Check Point 2\n");
                    break;
                }
            }
            else
            {
                status = libusb_get_device_descriptor(dev, &desc);
                if (status >= 0)
                {
                    if (verbose >= 3)
                    {
                        logerror("examining %04x:%04x (%d,%d)\n",
                            desc.idVendor, desc.idProduct, _busnum, _devaddr);
                    }
                    for (j=0; j<ARRAYSIZE(known_device); j++)
                    {
                        if ((desc.idVendor == known_device[j].vid)
                            && (desc.idProduct == known_device[j].pid))
                            {
                            printf("Check Point 3\n");
                            if (// nothing was specified
                                ((type == NULL) && (device_id == NULL) && (device_path == NULL)) ||
                                // vid:pid was specified and we have a match
                                ((type == NULL) && (device_id != NULL) && (vid == desc.idVendor) && (pid == desc.idProduct)) ||
                                // bus,addr was specified and we have a match
                                ((type == NULL) && (device_path != NULL) && (busnum == _busnum) && (devaddr == _devaddr)) ||
                                // type was specified and we have a match
                                ((type != NULL) && (device_id == NULL) && (device_path == NULL) && (fx_type == known_device[j].type)) )
                              {
                                printf("Check Point 4\n");
                                fx_type = known_device[j].type;
                                vid = desc.idVendor;
                                pid = desc.idProduct;
                                busnum = _busnum;
                                devaddr = _devaddr;
                                break;
                              }
                            }
                            printf("Check Point 5\n");
                    }

                    if (j < ARRAYSIZE(known_device))
                    {
                      printf("Check Point 6\n");
                        if (verbose)
                            logerror("found device '%s' [%04x:%04x] (%d,%d)\n",
                                known_device[j].designation, vid, pid, busnum, devaddr);
                        break;
                    }
                }
            }
        }
        if (dev == NULL) {
            printf("Check Point 7\n");
            libusb_free_device_list(devs, 1);
            logerror("could not find a known device - please specify type and/or vid:pid and/or bus,dev\n");
            return print_usage(-1);
        }
        status = libusb_open(dev, &device);
        if (status < 0) {
            logerror("libusb_open() failed: %s\n", libusb_error_name(status));
            goto err;
        }
        libusb_free_device_list(devs, 1);
    } else if (device_id != NULL) {
        printf("Check Point 9\n");
        printf("Check Point 9  vid %d\n", pid);
        printf("Check Point 9  pid %d\n", vid);
        device = libusb_open_device_with_vid_pid(NULL, (uint16_t)vid, (uint16_t)pid);
        if (device == NULL) {
            logerror("libusb_open() failed\n");
            goto err;
        }
    }

    /* We need to claim the first interface */
    printf("Check Point 10\n");
    libusb_set_auto_detach_kernel_driver(device, 1);
    status = libusb_claim_interface(device, 0);
    if (status != LIBUSB_SUCCESS) {
        logerror("libusb_claim_interface failed: %s\n", libusb_error_name(status));
        goto err;
    }

    if (verbose)
        logerror("microcontroller type: %s\n", fx_name[fx_type]);

    for (i=0; i<ARRAYSIZE(path); i++) {
        if (path[i] != NULL) {
            ext = path[i] + strlen(path[i]) - 4;
            if ((_stricmp(ext, ".hex") == 0) || (strcmp(ext, ".ihx") == 0))
                img_type[i] = IMG_TYPE_HEX;
            else if (_stricmp(ext, ".iic") == 0)
                img_type[i] = IMG_TYPE_IIC;
            else if (_stricmp(ext, ".bix") == 0)
                img_type[i] = IMG_TYPE_BIX;
            else if (_stricmp(ext, ".img") == 0)
                img_type[i] = IMG_TYPE_IMG;
            else {
                logerror("%s is not a recognized image type\n", path[i]);
                goto err;
            }
        }
        if (verbose && path[i] != NULL)
            logerror("%s: type %s\n", path[i], img_name[img_type[i]]);
    }

    printf("Check Point 11\n");
    printf("Check Point 11  img_type[FIRMWARE]  %d\n", img_type[FIRMWARE]);
    printf("Check Point 11  fx_type  %d\n", fx_type);

    /* single stage, put into internal memory */
    if (verbose > 1)
        logerror("single stage: load on-chip memory\n");
    status = ezusb_load_ram(device, path[FIRMWARE], fx_type, img_type[FIRMWARE], 0);

    libusb_release_interface(device, 0);
    libusb_close(device);
    libusb_exit(NULL);
    return status;
err:
    libusb_exit(NULL);
    return -1;
}
Пример #13
0
int main(int argc, char *argv[])
{
	libusb_context *ctx;
	libusb_device_handle *handle;
	int ret;
	uint8_t buf[RAMSIZE], ram[RAMSIZE];
	int fd, i;

	if (argc != 2) {
		fprintf(stderr, "usage: %s binary\n", argv[0]);
		exit(2);
	}

	if ((ret = libusb_init(&ctx))) {
		fprintf(stderr, "%s: %s\n", libusb_error_name(ret),
		        libusb_strerror(ret));
		libusb_exit(ctx);
		exit(1);
	}

	if (!(handle = libusb_open_device_with_vid_pid(ctx, VID, PID))) {
		fprintf(stderr, "device 0x%x:0x%x not found!\n", VID, PID);
		libusb_exit(ctx);
		exit(1);
	}

	/* claim first interface on device so we can do IO */
	libusb_set_auto_detach_kernel_driver(handle, 1);
	if ((ret = libusb_claim_interface(handle, 0)) != 0) {
		fprintf(stderr, "%s: %s\n", libusb_error_name(ret),
		        libusb_strerror(ret));
		libusb_close(handle);
		libusb_exit(ctx);
		exit(1);
	}

	/* reset 8051
	 * bmRequest: 0x40 (Vendor Request OUT)
	 * bRequest : 0xa0 (Firmware Load)
	 * Address  : 0xe600 (CPUCS register) */
	buf[0] = 0x01;
	if ((ret = libusb_control_transfer(handle, 0x40, 0xa0, 0xe600, 0x00,
	                                   buf, 1, 1000)) != 1) {
		fprintf(stderr, "%s: %s\n", libusb_error_name(ret),
		        libusb_strerror(ret));
		libusb_release_interface(handle, 0);
		libusb_close(handle);
		libusb_exit(ctx);
		exit(1);
	}

	/* load 8051 binary from given file */
	memset(buf, 0, RAMSIZE);
	if ((fd = open(argv[1], O_RDONLY)) < 0) {
		fprintf(stderr, "file '%s' not found!\n", argv[1]);
		libusb_release_interface(handle, 0);
		libusb_close(handle);
		libusb_exit(ctx);
		exit(1);
	}
	read(fd, buf, RAMSIZE);
	close(fd);

	/* upload binary to 8051 RAM */
	for (i = 0; i < 4; ++i) {
		/* maximum data size for control transfer = 4 kiB */
		ret = libusb_control_transfer(handle, 0x40, 0xa0, i*4*1024,
		                              0x00, buf+i*4*1024, 4*1024, 1000);
		if (ret != 4*1024) {
			fprintf(stderr, "upload failed: %s (%s)\n",
		        libusb_error_name(ret),
		        libusb_strerror(ret));
			libusb_release_interface(handle, 0);
			libusb_close(handle);
			libusb_exit(ctx);
			exit(1);
		}
	}

	/* verify uploaded code */
	for (i = 0; i < 4; ++i) {
		ret = libusb_control_transfer(handle, 0xc0, 0xa0, i*4*1024,
		                              0x00, ram+i*4*1024, 4*1024, 1000);
		if (ret != 4*1024) {
			fprintf(stderr, "%s: %s\n", libusb_error_name(ret),
			        libusb_strerror(ret));
			libusb_release_interface(handle, 0);
			libusb_close(handle);
			libusb_exit(ctx);
			exit(1);
		}
	}
	for (i = 0; i < RAMSIZE; ++i) {
		if (ram[i] != buf[i]) {
			fprintf(stderr, "verify failed at address 0x%x: "\
			        "expected "\
			        "0x%x instead of 0x%x\n", i, buf[i], ram[i]);
			/*exit(1);*/
		}
	}

	/* run 8051 */
	buf[0] = 0x00;
	if ((ret = libusb_control_transfer(handle, 0x40, 0xa0, 0xe600, 0x00,
	                                   buf, 1, 1000)) != 1) {
		fprintf(stderr, "%s: %s\n", libusb_error_name(ret),
		        libusb_strerror(ret));
		libusb_release_interface(handle, 0);
		libusb_close(handle);
		libusb_exit(ctx);
		exit(1);
	}

	/* clean up */
	libusb_release_interface(handle, 0);
	libusb_close(handle);
	libusb_exit(ctx);
	return 0;
}
Пример #14
0
int main()
{
    libusb_context *context;
    libusb_device_handle *handle;
    int configuration_value = 1, interface_number = 0, rv;
    char *p;

    rv = libusb_init(&context);
    if (rv != 0)
    {
        usbx_strerror(rv);
        return -1;
    }
    libusb_setlocale("zh");
    libusb_set_debug(context, LIBUSB_LOG_LEVEL_DEBUG);

    handle = libusb_open_device_with_vid_pid(context, 0x04B8, 0x0005);
    if (!handle)
    {
        libusb_exit(context);
        return -1;
    }
    libusb_set_auto_detach_kernel_driver(handle, 1);

    rv = libusb_set_configuration(handle, configuration_value);
    if (rv != 0)
    {
        usbx_strerror(rv);
        libusb_close(handle);
        libusb_exit(context);
        return -1;
    }
    rv = libusb_claim_interface(handle, interface_number);
    if (rv != 0)
    {
        usbx_strerror(rv);
        libusb_close(handle);
        libusb_exit(context);
        return -1;
    }
    /*
    putstring(handle, (unsigned char*) "\x1B\x40", 2);
    putstring(handle, (unsigned char*) "\x1B\x4A\x10", 3);
    putstring(handle, (unsigned char*) "hello\n", 5);
    putstring(handle, (unsigned char*) "\x1B\x6A\x10", 3);
    */

    //putstring(handle, (unsigned char*) "\x1B\x194", 3);
    putstring(handle, (unsigned char*) "hello\n", 6);
    /*
    p = malloc(10000);
    memset(p, ' ', 10000);
    putstring(handle, p, 10000);
    */
    //getstring(handle);
    putstring(handle, (unsigned char*) "\x07", 1);
    //putstring(handle, (unsigned char*) "\x18", 1);
    putstring(handle, (unsigned char*) "\x0C", 1);
    //putstring(handle, (unsigned char*) "\x1B\x190", 3);
    //putstring(handle, (unsigned char*) "\x1B\x40", 2);
    //putstring(handle, (unsigned char*) "\x1B\x4F", 2);

    libusb_release_interface(handle, interface_number);
    libusb_close(handle);
    libusb_exit(context);
    return 0;
}