Example #1
0
int main()
{

    int i=0, cnt=0;
    unsigned short VID = 0x045e; //vendor id
    unsigned short PID = 0x00f7; //product id
//    unsigned char EP_out = 0x82; // write into usb  end point
//    unsigned char EP_in  = 0x01; // read from usb end point

//    unsigned char TX[] = {0xC1, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00}; //reqwest
//    unsigned char RX[521]; //answer

    struct libusb_device_descriptor desc; //description of device structure

    libusb_device_handle *dev_handle = NULL;    //a device handle
    libusb_context       *ctx = NULL;           //a libusb session
    libusb_device        *dev = NULL;           //pointer to device
    libusb_device        **devs = NULL;         //pointer to pointer of device
    int r;
//    ssize_t cnt;                                //holding number of devices in list


    //init libusb
    r =  libusb_init(&ctx);
    if(r < 0) {
        printf("Init Error %d\n", r);           // Ошибка инициализации сессии libusb
        return 1;
    }
    libusb_set_debug(ctx, 3);

    // get device list
    cnt = libusb_get_device_list(ctx, &devs);   //get the list of devices
    printf("Количество устройств: %d\n", cnt);

    //get need device descriptor and number
    while ((dev = devs[i++]) != NULL)           //take all connected device one by one
        {
            cnt = libusb_get_device_descriptor(dev, &desc); // look in deckritption of current device
            if(cnt == 0)
                printf("\tУстройство = VID:%04x, PID:%04x, Конф:%04x\n", desc.idVendor, desc.idProduct, desc.bNumConfigurations);

            //test device vendor and product identify
            if( desc.idVendor == VID && desc.idProduct == PID ) // if VID & PID is positive
            {
                // open device
                cnt = libusb_open(dev, &dev_handle);
                if(cnt == 0)
                printf("Открываем наше устройство:\n");
                break;
            }
        }

        // Очищаем список устройств, убрираем ссылки на устройства в нем
        libusb_free_device_list(devs, 1);

        // test to enable device
        if ( dev_handle == NULL )
        {
            printf("Устройство не найдено\n");

            //exit work with usb
            libusb_exit(ctx);
                printf("Закрываем libusb\n");

            return 0;
        }

        // test to device to grubed by kernel
        if(libusb_kernel_driver_active(dev_handle, 0) == 1)
            if(libusb_detach_kernel_driver(dev_handle, 0) == 0) //detach it
                printf("Отсоединяем устройство от драйвера ядра\n");

        // config  device
            cnt = libusb_set_configuration(dev_handle, 1);
            if(cnt == 0)
                printf("Устанавливаем конфигурацию\n");

        // claim interface
            cnt = libusb_claim_interface(dev_handle, 0);
            if( cnt == 0 )
                printf("Запрос %d интерфейса\n", cnt);

//        uint8_t index = valreg[0][1];
//            uint8_t *buff;

//            cnt = sn9c102_write_reg(dev_handle, index, 1);
//            libusb_control_transfer(dev_handle, 0x41, 0x08, index, 0, buff, 1, TIMEOUT);
//        cnt = libusb_control_transfer(dev_handle,
 //                                     0x41,
   //                                   0x08, index, 0,
     //                                 buff, 1, TIMEOUT);
//                    (udev, usb_sndctrlpipe(udev, 0), 0x08, 0x41, index, 0, data, len, SN9C102_CTRL_TIMEOUT);
//        printf("Read from device.\n\tReturn value = %d\n\tAccept bytes = %d\n",cnt);

//static int sn9c102_usb_probe(struct usb_interface* intf, const struct usb_device_id* id)
//{
//    struct libusb_device *dev =
//}

//int sn9c102_write_regs(struct sn9c102_device* cam, const uint8_t valreg[][2], int count)
//{
//    struct libusb_d
//}
        // send data block to device
//        cnt = libusb_bulk_transfer(dev_handle, EP_in, TX, sizeof(TX), &bTransfer, TIMEOUT);
//        printf("Write to device.\n\tReturn value = %d\n\tSend bytes = %s\n",cnt,buff);

        // read answer
//        cnt = libusb_bulk_transfer(dev_handle, EP_out, RX, sizeof(RX), &bTransfer, TIMEOUT);
//        printf("Read from device.\n\tReturn value = %d\n\tAccept bytes = %s\n",cnt,buff);

        //release the claimed interface
        cnt = libusb_release_interface(dev_handle, 0);
        if( cnt == 0 )
            printf("Release 0 interface\n");

        // close usb device
        libusb_close(dev_handle);
            printf("Close device\n");

        //exit work with usb
        libusb_exit(ctx);
            printf("Exit libusb\n");

        //erase dev_handle
        dev_handle = NULL;

        return 0;
}
Example #2
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 #3
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 #4
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 #5
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;

}
Example #6
0
int main(int argc, char** argv) {
	libusb_device_handle * handle = NULL;
	libusb_context * ctx = NULL;
	uint16_t vid = 0x18d1;
	uint16_t pid = 0x4e22;
	int r;
	
	if (SIG_ERR == signal(SIGINT, &sig_handler)) {
		std::cerr << "can not catch SIGINT\n";
	}
	signal(SIGTERM, &sig_handler);
	signal(SIGKILL, &sig_handler);
	
	r = libusb_init(&ctx);
	if (r != LIBUSB_SUCCESS) {
		std::cerr << "libusb init fail. " << libusb_error_name(r) << std::endl;
		exit(r);
	}
	
	////////////////////////////////////////////////////////////////////////////////////////////////
	// Switch to aoap mode
	////////////////////////////////////////////////////////////////////////////////////////////////
	handle = libusb_open_device_with_vid_pid(ctx, vid, pid);
	if (handle == NULL) {
		std::cerr << "open device " << vid << ":" << pid << " error. " << libusb_error_name(errno) << std::endl;
		// exit(errno);
	} else {
		libusb_device * dev = NULL;
		dev = libusb_get_device(handle);
		dev = libusb_ref_device(dev);
	
		print_dev("", dev);
	
		{
			// 1. Get AOA Protocol on phone
			if (GetProtocol(handle) == false) {
				std::cerr << "Get AOA Protocol error\n";
				libusb_unref_device(dev);
				libusb_exit(ctx);
				exit(-1);
			}
			// 2. send accessory information
			if (SendAccessoryInfos(handle) == false) {
				std::cerr << "Send Accessory infos error\n";
				libusb_unref_device(dev);
				libusb_exit(ctx);
				exit(-2);
			}
			// 3. send reset command
			if (SendResetCommand(handle) == false) {
				std::cerr << "Send Reset command error\n";
				libusb_unref_device(dev);
				libusb_exit(ctx);
				exit(-3);
			}
		}
		
		std::cout << "phone reset to aoa mode\n";
	
		libusb_unref_device(dev);
	}
	std::cout << std::endl;
	std::cout << "===========================================================================\n";
	// list_devices(ctx);
	
	std::cout << "===========================================================================\n";
	// open aoa phone
	pid = 0x2D01;
	handle = NULL;
	int cnt = 60;
	while (handle == NULL) {
		handle = libusb_open_device_with_vid_pid(ctx, vid, pid);
		if (handle != NULL) {
			break;
		}
		sleep(1);
		if (--cnt < 0) {
			break;
		}
	}
	if (handle == NULL) {
		std::cerr << "open device " << vid << ":" << pid << " error. " << libusb_error_name(errno) << std::endl;
		// exit(errno);
	} else {
		for (int i = 0; i < 15; i++) {
			sleep(1);
			std::cout << "." << std::flush;
		}
		std::cout << std::endl;
		std::cout << "open device " << vid << ":" << pid << " success." << std::endl;
		libusb_device * dev = NULL;
		dev = libusb_get_device(handle);
		dev = libusb_ref_device(dev);
	
		print_dev("", dev);
		
		std::cout << std::endl;
		int interface = 0;
		unsigned char endpoint_in = 0, endpoint_out = 0;
		GetCommunicationEndpoint(handle, dev, interface, endpoint_in, endpoint_out);
		std::cout << std::endl;
		std::cout << "Get interface : " << (int)interface << std::endl;
		std::cout << "Get input endpoint address : 0x" << std::hex << (int)endpoint_in << std::endl;
		std::cout << "Get output endpoint address : 0x" << (int)endpoint_out << std::dec << std::endl;
	
		// 1. check whether kernel use this device or not
		int active = libusb_kernel_driver_active(handle, interface);
		std::cout << "interface [" << interface << "] active = " << active << std::endl;
		if (active == 1) {
			r = libusb_detach_kernel_driver(handle, interface);
			if (r != LIBUSB_SUCCESS) {
				std::cerr << "detach kernel drive error. " << libusb_error_name(r) << std::endl;
			}
		} else if (active != 0) {// 0 means no kernel drive active 
			std::cerr << "query kernel drive active fail. " << libusb_error_name(active) << std::endl;
		} 
		
		// 2. claim interface
		r = libusb_claim_interface(handle, interface);
		if (r != LIBUSB_SUCCESS) {
			std::cerr << "claim interface error. " << libusb_error_name(r) << std::endl;
		} else {
			std::cout << "claim interface[" << interface << "] success\n";
		}
		
		{
		// TODO
		// communication
		// int LIBUSB_CALL libusb_bulk_transfer(libusb_device_handle *dev_handle,
		//		unsigned char endpoint, unsigned char *data, int length,
		//		int *actual_length, unsigned int timeout);
		char buf[1024];
		memset(buf, 0, sizeof(buf));
		const char * info = "USB accessory [Ubuntu 12.04 host]";
		//const char * info = "Telenav USB accessory";
		//const char * info = "brad.shi";
		strncpy(buf, info, sizeof(buf));
		int actual_transfer_bytes = 0;
		int timeout = 1000;
		
		r = libusb_bulk_transfer(handle, endpoint_out, (unsigned char*)&buf[0], strlen(buf) + 1, &actual_transfer_bytes, timeout);
		if (r != LIBUSB_SUCCESS) {
			std::cerr << "bulk transfer error [hu -> phone]. " << libusb_error_name(r) << std::endl;
		} else {
			std::cout << "WOW, bulk transfer success [hu -> phone]. " << actual_transfer_bytes << " bytes transfered." << std::endl;
		}
				
		memset(buf, 0, sizeof(buf));
		timeout = 5 * 1000;
		r = libusb_bulk_transfer(handle, endpoint_in, (unsigned char*)&buf[0], sizeof(buf), &actual_transfer_bytes, timeout);
		if (r != LIBUSB_SUCCESS) {
			std::cerr << "bulk transfer error [phone -> hu]. " << libusb_error_name(r) << std::endl;
		} else {
			std::cout << "WOW, bulk transfer success [phone -> hu]. " << actual_transfer_bytes << " bytes transfered." << std::endl;
			std::cout << "RECEIVE : " << buf << std::endl;
		}
		
		} // end communication
		
		{ // async io
			const char * msg = "test usb async io.";
			//char buf[1024];
			char * buf;
			int timeout = 2000;
			buf = (char*)malloc(strlen(msg) + 1);
			memset(buf, 0, strlen(msg) + 1);
			strncpy(buf, msg, strlen(msg));
			std::cout << "buf : " << buf << std::endl;
			std::cout << "strlen(buf) = " << strlen(buf) << std::endl;
			// char readBuf[1024] = {0};		// if this cause crash issue, declare it as global variable
			// struct libusb_transfer inTransfer = {0};	// if this cause crash issue, use , answer : this will cause unexpect result
														// struct libusb_transfer * inTransfer = libusb_alloc_transfer(0);
			// struct libusb_transfer outTransfer = {0};
			struct libusb_transfer * pOutTransfer = libusb_alloc_transfer(0);	// should free it by calling libusb_free_transfer(libusb_transfer *)
			struct libusb_transfer & outTransfer = *pOutTransfer;
			std::cout << "fill out transfer" << std::endl;
			libusb_fill_bulk_transfer(&outTransfer	// struct libusb_transfer*
				, handle					// libusb_device_handle *
				, endpoint_out				// address of the endpoint where this transfer will be sent
				, (unsigned char*)&buf[0]	// data buffer
				, strlen(buf) + 1			// length of data buffer
				, &usbSendComplete			// callback fn, libusb_transfer_cb_fn
				, NULL						// user data to pass to callback function
				, timeout);					// timeout for the transfer in milliseconds
			std::cout << "submit out transfer" << std::endl;
			r = libusb_submit_transfer(&outTransfer);
			if (r != LIBUSB_SUCCESS) {
				std::cout << "r = " << r << ". " << libusb_error_name(r) << std::endl;
			}
			std::cout << "fill in transfer" << std::endl;
			
			struct libusb_transfer * pInTransfer = libusb_alloc_transfer(0);
			struct libusb_transfer & inTransfer = *pInTransfer;
			libusb_fill_bulk_transfer(&inTransfer	// struct libusb_transfer *
				, handle
				, endpoint_in
				, (unsigned char*)&readBuf[0]
				, sizeof(readBuf) - 1
				, &usbRecvComplete			// callback fn, libusb_transfer_cb_fn
				, NULL
				, timeout);
			std::cout << "submit in transfer" << std::endl;
			r = libusb_submit_transfer(&inTransfer);
			if (r != LIBUSB_SUCCESS) {
				std::cout << "r = " << r << ". " << libusb_error_name(r) << std::endl;
			}
		
			for (int i = 0; i < 10; i++) {
				struct timeval tv;
				tv.tv_sec  = 1;     // seconds
				tv.tv_usec = 0;		// milliseconds  ( .1 sec)
				r = libusb_handle_events_timeout(ctx, &tv); 
				sleep(1);
				std::cout << '.';
			}
			std::cout << std::endl;
			
			// release libusb_transfer
			std::cout << "LIBUSB_ERROR_NOT_FOUND if the transfer is already complete or cancelled." << std::endl;
			if (pOutTransfer) {
				r = libusb_cancel_transfer(pOutTransfer);
				if (LIBUSB_SUCCESS == r){
					std::cout << "pOutTransfer successfully cancelled\n";
				} else {
					std::cerr << "can out transfer error : " << libusb_error_name(r) << std::endl;
				}
				libusb_free_transfer(pOutTransfer);
				pOutTransfer = NULL;
			}
			if (pInTransfer) {
				r = libusb_cancel_transfer(pInTransfer);
				if (LIBUSB_SUCCESS == r){
					std::cout << "pInTransfer successfully cancelled\n";
				} else {
					std::cerr << "can in transfer error : " << libusb_error_name(r) << std::endl;
				}
				libusb_free_transfer(pInTransfer);
				pInTransfer = NULL;
			}
			free(buf);
		}
		
		std::cout << "releasing interface..." << std::endl;
		// -2. release interface
		r = libusb_release_interface(handle, interface);
		if (r != LIBUSB_SUCCESS) {
			std::cerr << "release interface error. " << libusb_error_name(r) << std::endl;
		} else {
			std::cout << "release interface[" << interface << "] success\n";
		}
		
		// ??? reset aoa ???
		// SendResetCommand(handle);
		// libusb_reset_device(handle);
		GetProtocol(handle);
		
		// -1. reactive kernel driver?
		if (active == 1) {
			r = libusb_attach_kernel_driver(handle, interface);
			if (r != LIBUSB_SUCCESS) {
				std::cerr << "attach kenel drive error. " << libusb_error_name(r) << std::endl;
			}
		}
			
		libusb_unref_device(dev);
	}
	
	libusb_exit(ctx);
	std::cout << "===========================================================================\n" << std::flush;
	cnt = 5;
	while(g_quit == false) {
		if (cnt < 0) {
			std::cout << "extends 60s. quit*\n";
			break;
		}
		sleep(1);
		cnt--;
	}
	
	
	return 0;
}
Example #7
0
int main(int argc, char **argv)
{
	int expected_size = 0;
	unsigned int transfer_size = 0;
	enum mode mode = MODE_NONE;
	struct dfu_status status;
	libusb_context *ctx;
	struct dfu_file file;
	char *end;
	int final_reset = 0;
  int detach_unsupported = 0;
	int ret;
	int dfuse_device = 0;
	int fd;
	const char *dfuse_options = NULL;
	int detach_delay = 5;
	uint16_t runtime_vendor;
	uint16_t runtime_product;

	memset(&file, 0, sizeof(file));

	/* make sure all prints are flushed */
	setvbuf(stdout, NULL, _IONBF, 0);

	while (1) {
		int c, option_index = 0;
		c = getopt_long(argc, argv, "hVvlenE:d:p:c:i:a:S:t:U:D:Rs:Z:", opts,
				&option_index);
		if (c == -1)
			break;

		switch (c) {
		case 'h':
			help();
			break;
		case 'V':
			mode = MODE_VERSION;
			break;
		case 'v':
			verbose++;
			break;
		case 'l':
			mode = MODE_LIST;
			break;
		case 'e':
			mode = MODE_DETACH;
			match_iface_alt_index = 0;
			match_iface_index = 0;
			break;
		case 'E':
			detach_delay = atoi(optarg);
			break;
    case 'n':
      detach_unsupported = 1;
      break;
		case 'd':
			parse_vendprod(optarg);
			break;
		case 'p':
			/* Parse device path */
			ret = resolve_device_path(optarg);
			if (ret < 0)
				errx(EX_SOFTWARE, "Unable to parse '%s'", optarg);
			if (!ret)
				errx(EX_SOFTWARE, "Cannot find '%s'", optarg);
			break;
		case 'c':
			/* Configuration */
			match_config_index = atoi(optarg);
			break;
		case 'i':
			/* Interface */
			match_iface_index = atoi(optarg);
			break;
		case 'a':
			/* Interface Alternate Setting */
			match_iface_alt_index = strtoul(optarg, &end, 0);
			if (*end) {
				match_iface_alt_name = optarg;
				match_iface_alt_index = -1;
			}
			break;
		case 'S':
			parse_serial(optarg);
			break;
		case 't':
			transfer_size = atoi(optarg);
			break;
		case 'U':
			mode = MODE_UPLOAD;
			file.name = optarg;
			break;
		case 'Z':
			expected_size = atoi(optarg);
			break;
		case 'D':
			mode = MODE_DOWNLOAD;
			file.name = optarg;
			break;
		case 'R':
			final_reset = 1;
			break;
		case 's':
			dfuse_options = optarg;
			break;
		default:
			help();
			break;
		}
	}

	print_version();
	if (mode == MODE_VERSION) {
		exit(0);
	}

	if (mode == MODE_NONE) {
		fprintf(stderr, "You need to specify one of -D or -U\n");
		help();
	}

	if (match_config_index == 0) {
		/* Handle "-c 0" (unconfigured device) as don't care */
		match_config_index = -1;
	}

	if (mode == MODE_DOWNLOAD) {
		dfu_load_file(&file, MAYBE_SUFFIX, MAYBE_PREFIX);
		/* If the user didn't specify product and/or vendor IDs to match,
		 * use any IDs from the file suffix for device matching */
		if (match_vendor < 0 && file.idVendor != 0xffff) {
			match_vendor = file.idVendor;
			printf("Match vendor ID from file: %04x\n", match_vendor);
		}
		if (match_product < 0 && file.idProduct != 0xffff) {
			match_product = file.idProduct;
			printf("Match product ID from file: %04x\n", match_product);
		}
	}

	ret = libusb_init(&ctx);
	if (ret)
		errx(EX_IOERR, "unable to initialize libusb: %i", ret);

	if (verbose > 2) {
		libusb_set_debug(ctx, 255);
	}

	probe_devices(ctx);

	if (mode == MODE_LIST) {
		list_dfu_interfaces();
		exit(0);
	}

	if (dfu_root == NULL) {
		errx(EX_IOERR, "No DFU capable USB device available");
	} else if (dfu_root->next != NULL) {
		/* We cannot safely support more than one DFU capable device
		 * with same vendor/product ID, since during DFU we need to do
		 * a USB bus reset, after which the target device will get a
		 * new address */
		errx(EX_IOERR, "More than one DFU capable USB device found! "
		       "Try `--list' and specify the serial number "
		       "or disconnect all but one device\n");
	}

	/* We have exactly one device. Its libusb_device is now in dfu_root->dev */

	printf("Opening DFU capable USB device...\n");
	ret = libusb_open(dfu_root->dev, &dfu_root->dev_handle);
	if (ret || !dfu_root->dev_handle)
		errx(EX_IOERR, "Cannot open device");

	printf("ID %04x:%04x\n", dfu_root->vendor, dfu_root->product);

	printf("Run-time device DFU version %04x\n",
	       libusb_le16_to_cpu(dfu_root->func_dfu.bcdDFUVersion));

	/* Transition from run-Time mode to DFU mode */
	if (!(dfu_root->flags & DFU_IFF_DFU)) {
		int err;
		/* In the 'first round' during runtime mode, there can only be one
		* DFU Interface descriptor according to the DFU Spec. */

		/* FIXME: check if the selected device really has only one */

		runtime_vendor = dfu_root->vendor;
		runtime_product = dfu_root->product;

		printf("Claiming USB DFU Runtime Interface...\n");
		if (libusb_claim_interface(dfu_root->dev_handle, dfu_root->interface) < 0) {
			errx(EX_IOERR, "Cannot claim interface %d",
				dfu_root->interface);
		}

		if (libusb_set_interface_alt_setting(dfu_root->dev_handle, dfu_root->interface, 0) < 0) {
			errx(EX_IOERR, "Cannot set alt interface zero");
		}

		printf("Determining device status: ");

		err = dfu_get_status(dfu_root, &status);
		if (err == LIBUSB_ERROR_PIPE) {
			printf("Device does not implement get_status, assuming appIDLE\n");
			status.bStatus = DFU_STATUS_OK;
			status.bwPollTimeout = 0;
			status.bState  = DFU_STATE_appIDLE;
			status.iString = 0;
		} else if (err < 0) {
			errx(EX_IOERR, "error get_status");
		} else {
			printf("state = %s, status = %d\n",
			       dfu_state_to_string(status.bState), status.bStatus);
		}
		milli_sleep(status.bwPollTimeout);

		switch (status.bState) {
		case DFU_STATE_appIDLE:
		case DFU_STATE_appDETACH:
      if (!detach_unsupported) {
        printf("Device really in Runtime Mode, send DFU "
               "detach request...\n");
        if (dfu_detach(dfu_root->dev_handle,
                 dfu_root->interface, 1000) < 0) {
          warnx("error detaching");
        }
      }
			if (dfu_root->func_dfu.bmAttributes & USB_DFU_WILL_DETACH) {
				printf("Device will detach and reattach...\n");
			} else {
				printf("Resetting USB...\n");
				ret = libusb_reset_device(dfu_root->dev_handle);
				if (ret < 0 && ret != LIBUSB_ERROR_NOT_FOUND)
					errx(EX_IOERR, "error resetting "
						"after detach");
			}
			break;
		case DFU_STATE_dfuERROR:
			printf("dfuERROR, clearing status\n");
			if (dfu_clear_status(dfu_root->dev_handle,
					     dfu_root->interface) < 0) {
				errx(EX_IOERR, "error clear_status");
			}
			/* fall through */
		default:
			warnx("WARNING: Runtime device already in DFU state ?!?");
			libusb_release_interface(dfu_root->dev_handle,
			    dfu_root->interface);
			goto dfustate;
		}
		libusb_release_interface(dfu_root->dev_handle,
					 dfu_root->interface);
		libusb_close(dfu_root->dev_handle);
		dfu_root->dev_handle = NULL;

		if (mode == MODE_DETACH) {
			libusb_exit(ctx);
			exit(0);
		}

		/* keeping handles open might prevent re-enumeration */
		disconnect_devices();

		milli_sleep(detach_delay * 1000);

		/* Change match vendor and product to impossible values to force
		 * only DFU mode matches in the following probe */
		match_vendor = match_product = 0x10000;

		probe_devices(ctx);

		if (dfu_root == NULL) {
			errx(EX_IOERR, "Lost device after RESET?");
		} else if (dfu_root->next != NULL) {
			errx(EX_IOERR, "More than one DFU capable USB device found! "
				"Try `--list' and specify the serial number "
				"or disconnect all but one device");
		}

		/* Check for DFU mode device */
		if (!(dfu_root->flags | DFU_IFF_DFU))
			errx(EX_SOFTWARE, "Device is not in DFU mode");

		printf("Opening DFU USB Device...\n");
		ret = libusb_open(dfu_root->dev, &dfu_root->dev_handle);
		if (ret || !dfu_root->dev_handle) {
			errx(EX_IOERR, "Cannot open device");
		}
	} else {
		/* we're already in DFU mode, so we can skip the detach/reset
		 * procedure */
		/* If a match vendor/product was specified, use that as the runtime
		 * vendor/product, otherwise use the DFU mode vendor/product */
		runtime_vendor = match_vendor < 0 ? dfu_root->vendor : match_vendor;
		runtime_product = match_product < 0 ? dfu_root->product : match_product;
	}

dfustate:
#if 0
	printf("Setting Configuration %u...\n", dfu_root->configuration);
	if (libusb_set_configuration(dfu_root->dev_handle, dfu_root->configuration) < 0) {
		errx(EX_IOERR, "Cannot set configuration");
	}
#endif
	printf("Claiming USB DFU Interface...\n");
	if (libusb_claim_interface(dfu_root->dev_handle, dfu_root->interface) < 0) {
		errx(EX_IOERR, "Cannot claim interface");
	}

	printf("Setting Alternate Setting #%d ...\n", dfu_root->altsetting);
	if (libusb_set_interface_alt_setting(dfu_root->dev_handle, dfu_root->interface, dfu_root->altsetting) < 0) {
		errx(EX_IOERR, "Cannot set alternate interface");
	}

status_again:
	printf("Determining device status: ");
	if (dfu_get_status(dfu_root, &status ) < 0) {
		errx(EX_IOERR, "error get_status");
	}
	printf("state = %s, status = %d\n",
	       dfu_state_to_string(status.bState), status.bStatus);

	milli_sleep(status.bwPollTimeout);

	switch (status.bState) {
	case DFU_STATE_appIDLE:
	case DFU_STATE_appDETACH:
		errx(EX_IOERR, "Device still in Runtime Mode!");
		break;
	case DFU_STATE_dfuERROR:
		printf("dfuERROR, clearing status\n");
		if (dfu_clear_status(dfu_root->dev_handle, dfu_root->interface) < 0) {
			errx(EX_IOERR, "error clear_status");
		}
		goto status_again;
		break;
	case DFU_STATE_dfuDNLOAD_IDLE:
	case DFU_STATE_dfuUPLOAD_IDLE:
		printf("aborting previous incomplete transfer\n");
		if (dfu_abort(dfu_root->dev_handle, dfu_root->interface) < 0) {
			errx(EX_IOERR, "can't send DFU_ABORT");
		}
		goto status_again;
		break;
	case DFU_STATE_dfuIDLE:
		printf("dfuIDLE, continuing\n");
		break;
	default:
		break;
	}

	if (DFU_STATUS_OK != status.bStatus ) {
		printf("WARNING: DFU Status: '%s'\n",
			dfu_status_to_string(status.bStatus));
		/* Clear our status & try again. */
		if (dfu_clear_status(dfu_root->dev_handle, dfu_root->interface) < 0)
			errx(EX_IOERR, "USB communication error");
		if (dfu_get_status(dfu_root, &status) < 0)
			errx(EX_IOERR, "USB communication error");
		if (DFU_STATUS_OK != status.bStatus)
			errx(EX_SOFTWARE, "Status is not OK: %d", status.bStatus);

		milli_sleep(status.bwPollTimeout);
	}

	printf("DFU mode device DFU version %04x\n",
	       libusb_le16_to_cpu(dfu_root->func_dfu.bcdDFUVersion));

	if (dfu_root->func_dfu.bcdDFUVersion == libusb_cpu_to_le16(0x11a))
		dfuse_device = 1;

	/* If not overridden by the user */
	if (!transfer_size) {
		transfer_size = libusb_le16_to_cpu(
		    dfu_root->func_dfu.wTransferSize);
		if (transfer_size) {
			printf("Device returned transfer size %i\n",
			       transfer_size);
		} else {
			errx(EX_IOERR, "Transfer size must be specified");
		}
	}

#ifdef HAVE_GETPAGESIZE
/* autotools lie when cross-compiling for Windows using mingw32/64 */
#ifndef __MINGW32__
	/* limitation of Linux usbdevio */
	if ((int)transfer_size > getpagesize()) {
		transfer_size = getpagesize();
		printf("Limited transfer size to %i\n", transfer_size);
	}
#endif /* __MINGW32__ */
#endif /* HAVE_GETPAGESIZE */

	if (transfer_size < dfu_root->bMaxPacketSize0) {
		transfer_size = dfu_root->bMaxPacketSize0;
		printf("Adjusted transfer size to %i\n", transfer_size);
	}

	switch (mode) {
	case MODE_UPLOAD:
		/* open for "exclusive" writing */
		fd = open(file.name, O_WRONLY | O_BINARY | O_CREAT | O_EXCL | O_TRUNC, 0666);
		if (fd < 0)
			err(EX_IOERR, "Cannot open file %s for writing", file.name);

		if (dfuse_device || dfuse_options) {
		    if (dfuse_do_upload(dfu_root, transfer_size, fd,
					dfuse_options) < 0)
			exit(1);
		} else {
		    if (dfuload_do_upload(dfu_root, transfer_size,
			expected_size, fd) < 0) {
			exit(1);
		    }
		}
		close(fd);
		break;

	case MODE_DOWNLOAD:
		if (((file.idVendor  != 0xffff && file.idVendor  != runtime_vendor) ||
		     (file.idProduct != 0xffff && file.idProduct != runtime_product)) &&
		    ((file.idVendor  != 0xffff && file.idVendor  != dfu_root->vendor) ||
		     (file.idProduct != 0xffff && file.idProduct != dfu_root->product))) {
			errx(EX_IOERR, "Error: File ID %04x:%04x does "
				"not match device (%04x:%04x or %04x:%04x)",
				file.idVendor, file.idProduct,
				runtime_vendor, runtime_product,
				dfu_root->vendor, dfu_root->product);
		}
		if (dfuse_device || dfuse_options || file.bcdDFU == 0x11a) {
		        if (dfuse_do_dnload(dfu_root, transfer_size, &file,
							dfuse_options) < 0)
				exit(1);
		} else {
			if (dfuload_do_dnload(dfu_root, transfer_size, &file) < 0)
				exit(1);
	 	}
		break;
	case MODE_DETACH:
    if (detach_unsupported)
      break;
    ret = dfu_detach(dfu_root->dev_handle, dfu_root->interface, 1000);
		if (ret < 0) {
			warnx("can't detach");
		}
		break;
	default:
		errx(EX_IOERR, "Unsupported mode: %u", mode);
		break;
	}

	if (final_reset) {
    if (detach_unsupported) {
      // STM32 DFU devices dont support DFU_DETACH
      // Instead, force the device into STATE_DFU_MANIFEST_WAIT_RESET
      // by sending a download request of size 0 and checking the state
      if (dfu_download(dfu_root->dev_handle, dfu_root->interface, 0x0, 0x0, NULL)) {
        warnx("Failure forcing a manifest");
      } else {
        if (dfu_get_status(dfu_root, &status) < 0) {
          warnx("Unable to check status after manifest");
        } else {
          printf("state = %s, status = %d\n",
                 dfu_state_to_string(status.bState), status.bStatus);
          if (status.bState != STATE_DFU_MANIFEST) {
            warnx("Device should be in manifest state");
          }
        }
      }
    } else {
      if (dfu_detach(dfu_root->dev_handle, dfu_root->interface, 1000) < 0) {
        /* Even if detach failed, just carry on to leave the
                             device in a known state */
      	warnx("can't detach");
      }
    }

		printf("Resetting USB to switch back to runtime mode\n");
		ret = libusb_reset_device(dfu_root->dev_handle);
		if (ret < 0 && ret != LIBUSB_ERROR_NOT_FOUND) {
			errx(EX_IOERR, "error resetting after download");
		}
	}

	libusb_close(dfu_root->dev_handle);
	dfu_root->dev_handle = NULL;
	libusb_exit(ctx);

	return (0);
}
Example #8
0
void lxc_close(libusb_device_handle *dev) {
	libusb_release_interface(dev, LXC_USB_INTERFACE);
	libusb_close(dev);
}
Example #9
0
static const blissbox_pad_type_t* input_autoconfigure_get_blissbox_pad_type_libusb(int vid, int pid)
{
#ifdef HAVE_LIBUSB
   unsigned i;
   unsigned char answer[USB_PACKET_CTRL_LEN] = {0};
   int ret                                   = libusb_init(NULL);

   if (ret < 0)
   {
      RARCH_ERR("[Autoconf]: Could not initialize libusb.\n");
      return NULL;
   }

   autoconfig_libusb_handle = libusb_open_device_with_vid_pid(NULL, vid, pid);

   if (!autoconfig_libusb_handle)
   {
      RARCH_ERR("[Autoconf]: Could not find or open libusb device %d:%d.\n", vid, pid);
      goto error;
   }

#ifdef __linux__
   libusb_detach_kernel_driver(autoconfig_libusb_handle, 0);
#endif

   ret = libusb_set_configuration(autoconfig_libusb_handle, 1);

   if (ret < 0)
   {
      RARCH_ERR("[Autoconf]: Error during libusb_set_configuration.\n");
      goto error;
   }

   ret = libusb_claim_interface(autoconfig_libusb_handle, 0);

   if (ret < 0)
   {
      RARCH_ERR("[Autoconf]: Error during libusb_claim_interface.\n");
      goto error;
   }

   ret = libusb_control_transfer(autoconfig_libusb_handle, USB_CTRL_IN, USB_HID_GET_REPORT, BLISSBOX_USB_FEATURE_REPORT_ID, 0, answer, USB_PACKET_CTRL_LEN, USB_TIMEOUT);

   if (ret < 0)
      RARCH_ERR("[Autoconf]: Error during libusb_control_transfer.\n");

   libusb_release_interface(autoconfig_libusb_handle, 0);

#ifdef __linux__
   libusb_attach_kernel_driver(autoconfig_libusb_handle, 0);
#endif

   libusb_close(autoconfig_libusb_handle);
   libusb_exit(NULL);

   for (i = 0; i < sizeof(blissbox_pad_types) / sizeof(blissbox_pad_types[0]); i++)
   {
      const blissbox_pad_type_t *pad = &blissbox_pad_types[i];

      if (!pad || string_is_empty(pad->name))
         continue;

      if (pad->index == answer[0])
         return pad;
   }

   RARCH_LOG("[Autoconf]: Could not find connected pad in Bliss-Box port#%d.\n", pid - BLISSBOX_PID);

   return NULL;

error:
   libusb_close(autoconfig_libusb_handle);
   libusb_exit(NULL);
#endif

   return NULL;
}
Example #10
0
/*! \brief Close the USB communication port.
	\returns XRV_OK if the port was closed successfully
	\note Linux:\n
	If a kernel driver was detached when communication with the device started,
	attach it again. No guarantee is given that udev will pick up on it though.
*/
XsResultValue UsbInterface::closeUsb(void)
{
	//lint --e{534}
#ifdef LOG_RX_TX
	if (d->rx_log != NULL)
		fclose(d->rx_log);
	if (d->tx_log != NULL)
		fclose(d->tx_log);
	d->rx_log = NULL;
	d->tx_log = NULL;
#endif
	if (!isOpen())
		return d->m_lastResult = XRV_NOPORTOPEN;

	d->m_lastResult = XRV_OK;
#ifdef USE_WINUSB
	if (d->m_threadHandle != INVALID_HANDLE_VALUE)
	{
		while (d->m_running)
		{
			::SetEvent(d->m_quitEvent);
			XsTime::msleep(10);
		}
		::CloseHandle(d->m_threadHandle);
	}

	flushData();
	if(d->m_usbHandle[0]) {
		WinUsb_Free(d->m_usbHandle[0]);
		d->m_usbHandle[0] = NULL;
	}
	if(d->m_usbHandle[1]) {
		WinUsb_Free(d->m_usbHandle[1]);
		d->m_usbHandle[1] = NULL;
	}
	if (d->m_deviceHandle) {
		CloseHandle(d->m_deviceHandle);
		d->m_deviceHandle = NULL;
	}
#else
	flushData();
	libusb_device *dev = libusb_get_device(d->m_deviceHandle);
	for (int i = 0; i < d->m_interfaceCount; i++) {
		int result = LIBUSB_ERROR_OTHER;
		while (result != LIBUSB_SUCCESS) {
			result = libusb_release_interface(d->m_deviceHandle, i);
			if (result == LIBUSB_SUCCESS) {
				libusb_attach_kernel_driver(d->m_deviceHandle, i);
			}
		}
	}

	libusb_close(d->m_deviceHandle);
	d->m_deviceHandle = NULL;

	libusb_unref_device(dev);
	d->m_interface = -1;
	d->m_dataInEndPoint = -1;
	d->m_dataOutEndPoint = -1;
#endif
	d->m_endTime = 0;

	return d->m_lastResult;
}
Example #11
0
/*! \brief Open a communcation channel to the given USB port name. */
XsResultValue UsbInterface::open(const XsPortInfo &portInfo, uint32_t, uint32_t)
{
	d->m_endTime = 0;

#ifdef USE_WINUSB
	JLDEBUG(gJournal, "Open usb port " << portInfo.portName().toStdString());
#else
	JLDEBUG(gJournal, "Open usb port " << portInfo.usbBus() << ":" << portInfo.usbAddress());
#endif

	if (isOpen())
	{
		JLALERT(gJournal, "Port " << portInfo.portName().toStdString() << " already open");
		return (d->m_lastResult = XRV_ALREADYOPEN);
	}

#ifdef USE_WINUSB
	d->m_deviceHandle = CreateFileA(portInfo.portName().c_str(),
		GENERIC_WRITE | GENERIC_READ,
		FILE_SHARE_WRITE | FILE_SHARE_READ,
		NULL,
		OPEN_EXISTING,
		FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED,
		NULL);

	if (d->m_deviceHandle == INVALID_HANDLE_VALUE)
	{
		d->m_deviceHandle = NULL;
		return (d->m_lastResult = XRV_PORTNOTFOUND);
	}

	BOOL result = FALSE;
	UCHAR speed = 0;
	ULONG length = 0;
	USB_INTERFACE_DESCRIPTOR interfaceDescriptor = {0,0,0,0,0,0,0,0,0};
	WINUSB_PIPE_INFORMATION pipeInfo;

	result = WinUsb_Initialize(d->m_deviceHandle, &d->m_usbHandle[0]);
	if (result)
	{
		result = WinUsb_GetAssociatedInterface(d->m_usbHandle[0],0,&d->m_usbHandle[1]);
	}
	else
	{
#ifdef XSENS_DEBUG
		DWORD err = GetLastError();
		assert(result);
#endif
		return (d->m_lastResult = XRV_ERROR);
	}

	for (int k = 0; k<2;k++)
	{
		if(result)
		{
			assert(d->m_usbHandle[k] != 0);
			length = sizeof(UCHAR);
			result = WinUsb_QueryDeviceInformation(d->m_usbHandle[k],
				DEVICE_SPEED,
				&length,
				&speed);
		}

		if(result)
		{
			d->m_deviceSpeed = speed;
			result = WinUsb_QueryInterfaceSettings(d->m_usbHandle[k],
				0,
				&interfaceDescriptor);
		}
		if(result)
		{
			for(int i=0;i<interfaceDescriptor.bNumEndpoints;i++)
			{
				result = WinUsb_QueryPipe(d->m_usbHandle[k],
					0,
					(UCHAR) i,
					&pipeInfo);

				if(pipeInfo.PipeType == UsbdPipeTypeBulk &&
					USB_ENDPOINT_DIRECTION_IN(pipeInfo.PipeId))
				{
					d->m_bulkInPipe = pipeInfo.PipeId;
					d->m_bulkInPipePacketSize =
						pipeInfo.MaximumPacketSize;
				}
				else if(pipeInfo.PipeType == UsbdPipeTypeBulk &&
					USB_ENDPOINT_DIRECTION_OUT(pipeInfo.PipeId))
				{
					d->m_bulkOutPipe = pipeInfo.PipeId;
				}
				else if(pipeInfo.PipeType == UsbdPipeTypeInterrupt)
				{
					d->m_interruptPipe = pipeInfo.PipeId;
				}
				else
				{
					result = FALSE;
					break;
				}
			}
		}
	}

	setTimeout(0);	//lint !e534
	flushData();	//lint !e534

	sprintf(d->m_portname, "%s", portInfo.portName().c_str());

//	d->m_offset = 0;
	::ResetEvent(&d->m_quitEvent);	//lint !e534
	d->m_threadHandle = xsStartThread(usbReadThreadFunc, d, &d->m_threadId);
	if (d->m_threadHandle == XSENS_INVALID_THREAD)
	{
#ifdef XSENS_DEBUG
		assert(0);
#endif
		return (d->m_lastResult = XRV_ERROR);
	}

#else // !USE_WINUSB
	static UsbInterfacePrivate::UsbContext  contextManager; //m_contextManager;

	libusb_device **deviceList;
	ssize_t listLength = libusb_get_device_list(contextManager.m_usbContext /*d->m_contextManager.m_usbContext*/, &deviceList);
	if (listLength < 0)
		return d->m_lastResult = d->libusbErrorToXrv((int)listLength);

	// "USBxxx:yyy"
	uint8_t bus = XsPortInfo_usbBus(&portInfo);
	uint8_t address = XsPortInfo_usbAddress(&portInfo);

	XsResultValue xrv = XRV_OK;
	int result;
	libusb_device *device = NULL;
	for (int i = 0; i < listLength && device == NULL; ++i) {
		libusb_device *dev = deviceList[i];
		if (libusb_get_bus_number(dev) != bus || libusb_get_device_address(dev) != address)
			continue;

		libusb_device_descriptor desc;
		result = libusb_get_device_descriptor(dev, &desc);
		if (result != LIBUSB_SUCCESS)
			break;

		libusb_config_descriptor *configDesc;
		result = libusb_get_active_config_descriptor(dev, &configDesc);
		if (result != LIBUSB_SUCCESS)
			break;

		d->m_interface = -1;
		d->m_interfaceCount = configDesc->bNumInterfaces;
		// find the bulk transfer endpoints
		for (uint8_t ifCount = 0; ifCount < configDesc->bNumInterfaces && d->m_interface == -1; ++ifCount) {
			for (uint8_t altsettingCount = 0; altsettingCount < configDesc->interface[ifCount].num_altsetting; altsettingCount++) {
				const libusb_endpoint_descriptor *endpoints = configDesc->interface[ifCount].altsetting[altsettingCount].endpoint;
				int inEndpoint = -1, outEndpoint = -1;
				for (uint8_t i = 0; i < configDesc->interface[ifCount].altsetting[altsettingCount].bNumEndpoints; i++) {
					if ((endpoints[i].bmAttributes&LIBUSB_TRANSFER_TYPE_MASK) != LIBUSB_TRANSFER_TYPE_BULK)
						continue;

					switch (endpoints[i].bEndpointAddress&LIBUSB_ENDPOINT_DIR_MASK) {
					case LIBUSB_ENDPOINT_IN:
						inEndpoint = endpoints[i].bEndpointAddress&LIBUSB_ENDPOINT_ADDRESS_MASK;
						break;

					case LIBUSB_ENDPOINT_OUT:
						outEndpoint = endpoints[i].bEndpointAddress&LIBUSB_ENDPOINT_ADDRESS_MASK;
						break;
					}

				}

				if (outEndpoint == -1 || inEndpoint == -1)
					continue;

				d->m_interface = ifCount;
				d->m_dataOutEndPoint = outEndpoint;
				d->m_dataInEndPoint = inEndpoint;
			}
		}
		if (d->m_interface == -1) {
			xrv = XRV_INPUTCANNOTBEOPENED;
			break;
		}

		libusb_free_config_descriptor(configDesc);
		libusb_ref_device(dev);
		device = dev;
		result = LIBUSB_SUCCESS;
	}

	libusb_free_device_list(deviceList, 1);
	if (result != LIBUSB_SUCCESS) {
		libusb_unref_device(device);
		return d->m_lastResult = d->libusbErrorToXrv(result);
	}

	if (xrv != XRV_OK) {
		libusb_unref_device(device);
		return d->m_lastResult = xrv;
	}

	libusb_device_handle *handle;
	result = libusb_open(device, &handle);
	if (result != LIBUSB_SUCCESS) {
		libusb_unref_device(device);
		return d->m_lastResult = d->libusbErrorToXrv(result);
	}

	// be rude and claim all interfaces
	for (int i = 0; i < d->m_interfaceCount; i++) {
		result = libusb_kernel_driver_active(handle, i);
		if (result > 0)
			result = libusb_detach_kernel_driver(handle, i);
		if (result == LIBUSB_SUCCESS)
			result = libusb_claim_interface(handle, i);
		if (result != LIBUSB_SUCCESS) {
			for (int j = 0; j < i; j++) {
				while (result != LIBUSB_SUCCESS) {
					result = libusb_release_interface(handle, j);
					libusb_attach_kernel_driver(handle, j);
				}
			}

			libusb_close(handle);
			libusb_unref_device(device);
			return d->m_lastResult = d->libusbErrorToXrv(result);
		}
	}

	d->m_deviceHandle = handle;
	sprintf(d->m_portname, "%s", portInfo.portName().c_str());

	flushData();

#endif // !USE_WINUSB
	JLDEBUG(gJournal, "USB Port opened");
	return (d->m_lastResult = XRV_OK);
}
Example #12
0
int musb_close(MUSB_INTERFACE *musb_interface)
{
#if defined(HAVE_LIBUSB)

   int status;
   status = usb_release_interface(musb_interface->dev, musb_interface->usb_interface);
   if (status < 0)
      fprintf(stderr, "musb_close: usb_release_interface() error %d\n", status);
   
#ifdef OS_LINUX   // linux wants a reset, otherwise the device cannot be accessed next time
   musb_reset(musb_interface);
#endif

   status = usb_close(musb_interface->dev);
   if (status < 0)
      fprintf(stderr, "musb_close: usb_close() error %d\n", status);
   
#elif defined(HAVE_LIBUSB10)   

   int status;
   status = libusb_release_interface(musb_interface->dev, musb_interface->usb_interface);
   if (status < 0)
      fprintf(stderr, "musb_close: libusb_release_interface() error %d\n", status);
   
#ifdef OS_LINUX   // linux wants a reset, otherwise the device cannot be accessed next time
   musb_reset(musb_interface);
#endif
   
   libusb_close(musb_interface->dev);

#elif defined(OS_DARWIN)

   IOReturn status;
   IOUSBInterfaceInterface **interface = (IOUSBInterfaceInterface **)musb_interface->interface;

   status = (*interface)->USBInterfaceClose(interface);
   if (status != kIOReturnSuccess)
      fprintf(stderr, "musb_close: USBInterfaceClose() status %d 0x%x\n", status, status);

   status = (*interface)->Release(interface);
   if (status != kIOReturnSuccess)
      fprintf(stderr, "musb_close: USB Interface Release() status %d 0x%x\n", status, status);

   IOUSBDeviceInterface **device = (IOUSBDeviceInterface**)musb_interface->device;
   status = (*device)->USBDeviceClose(device);
   if (status != kIOReturnSuccess)
      fprintf(stderr, "musb_close: USBDeviceClose() status %d 0x%x\n", status, status);

   status = (*device)->Release(device);
   if (status != kIOReturnSuccess)
      fprintf(stderr, "musb_close: USB Device Release() status %d 0x%x\n", status, status);

#elif defined(_MSC_VER)

   CloseHandle(musb_interface->rhandle);
   CloseHandle(musb_interface->whandle);

#else
   assert(!"musb_close() is not implemented");
#endif

   /* free memory allocated in musb_open() */
   free(musb_interface);
   return 0;
}
Example #13
0
int fnusb_open_subdevices(freenect_device *dev, int index)
{
	freenect_context *ctx = dev->parent;

	dev->usb_cam.parent = dev;
	dev->usb_cam.dev = NULL;
	dev->usb_motor.parent = dev;
	dev->usb_motor.dev = NULL;

	libusb_device **devs; //pointer to pointer of device, used to retrieve a list of devices
	ssize_t cnt = libusb_get_device_list (dev->parent->usb.ctx, &devs); //get the list of devices
	if (cnt < 0)
		return -1;

	int i = 0, nr_cam = 0, nr_mot = 0;
	int res;
	struct libusb_device_descriptor desc;

	for (i = 0; i < cnt; i++) {
		int r = libusb_get_device_descriptor (devs[i], &desc);
		if (r < 0)
			continue;

		if (desc.idVendor != VID_MICROSOFT)
			continue;

		// Search for the camera
		if (!dev->usb_cam.dev && desc.idProduct == PID_NUI_CAMERA) {
			// If the index given by the user matches our camera index
			if (nr_cam == index) {
				res = libusb_open (devs[i], &dev->usb_cam.dev);
				if (res < 0 || !dev->usb_cam.dev) {
					FN_ERROR("Could not open camera: %d\n", res);
					dev->usb_cam.dev = NULL;
					break;
				}
				res = libusb_claim_interface (dev->usb_cam.dev, 0);
				if (res < 0) {
					FN_ERROR("Could not claim interface on camera: %d\n", res);
					libusb_close(dev->usb_cam.dev);
					dev->usb_cam.dev = NULL;
					break;
				}
			} else {
				nr_cam++;
			}
		}

		// Search for the motor
		if (!dev->usb_motor.dev && desc.idProduct == PID_NUI_MOTOR) {
			// If the index given by the user matches our camera index
			if (nr_mot == index) {
				res = libusb_open (devs[i], &dev->usb_motor.dev);
				if (res < 0 || !dev->usb_motor.dev) {
					FN_ERROR("Could not open motor: %d\n", res);
					dev->usb_motor.dev = NULL;
					break;
				}
				res = libusb_claim_interface (dev->usb_motor.dev, 0);
				if (res < 0) {
					FN_ERROR("Could not claim interface on motor: %d\n", res);
					libusb_close(dev->usb_motor.dev);
					dev->usb_motor.dev = NULL;
					break;
				}
			} else {
				nr_mot++;
			}
		}
	}

	libusb_free_device_list (devs, 1);  // free the list, unref the devices in it

	if (dev->usb_cam.dev && dev->usb_motor.dev) {
		return 0;
	} else {
		if (dev->usb_cam.dev) {
			libusb_release_interface(dev->usb_cam.dev, 0);
			libusb_close(dev->usb_cam.dev);
		}
		if (dev->usb_motor.dev) {
			libusb_release_interface(dev->usb_motor.dev, 0);
			libusb_close(dev->usb_motor.dev);
		}
		return -1;
	}
}
Example #14
0
/*****************************************************************************
 *
 *					CloseUSB
 *
 ****************************************************************************/
status_t CloseUSB(unsigned int reader_index)
{
	/* device not opened */
	if (usbDevice[reader_index].dev_handle == NULL)
		return STATUS_UNSUCCESSFUL;

	DEBUG_COMM3("Closing USB device: %d/%d",
		usbDevice[reader_index].bus_number,
		usbDevice[reader_index].device_address);

	/* one slot closed */
	(*usbDevice[reader_index].nb_opened_slots)--;

	/* release the allocated ressources for the last slot only */
	if (0 == *usbDevice[reader_index].nb_opened_slots)
	{
		struct usbDevice_MultiSlot_Extension *msExt;

		DEBUG_COMM("Last slot closed. Release resources");

		msExt = usbDevice[reader_index].multislot_extension;
		/* If this is a multislot reader, close using the multislot stuff */
		if (msExt)
		{
			/* terminate the interrupt waiter thread */
			Multi_PollingTerminate(msExt);

			/* wait for the thread to actually terminate */
			pthread_join(msExt->thread_proc, NULL);

			/* release the shared objects */
			pthread_cond_destroy(&msExt->condition);
			pthread_mutex_destroy(&msExt->mutex);

			/* Deallocate the extension itself */
			free(msExt);

			/* Stop the slot */
			usbDevice[reader_index].multislot_extension = NULL;
		}

		if (usbDevice[reader_index].ccid.gemalto_firmware_features)
			free(usbDevice[reader_index].ccid.gemalto_firmware_features);

		if (usbDevice[reader_index].ccid.sIFD_serial_number)
			free(usbDevice[reader_index].ccid.sIFD_serial_number);

		if (usbDevice[reader_index].ccid.sIFD_iManufacturer)
			free(usbDevice[reader_index].ccid.sIFD_iManufacturer);

		if (usbDevice[reader_index].ccid.arrayOfSupportedDataRates)
			free(usbDevice[reader_index].ccid.arrayOfSupportedDataRates);

		(void)libusb_release_interface(usbDevice[reader_index].dev_handle,
			usbDevice[reader_index].interface);
		(void)libusb_close(usbDevice[reader_index].dev_handle);
	}

	/* mark the resource unused */
	usbDevice[reader_index].dev_handle = NULL;
	usbDevice[reader_index].interface = 0;

	close_libusb_if_needed();

	return STATUS_SUCCESS;
} /* CloseUSB */
Example #15
0
void closeDongleHid(libusb_device_handle *handle) {	
	libusb_release_interface(handle, 0);
	libusb_attach_kernel_driver(handle, 0);
	libusb_close(handle);
}
Example #16
0
static void dev_deinit(struct fp_img_dev *dev)
{
	g_free(dev->priv);
	libusb_release_interface(dev->udev, 0);
	fpi_imgdev_close_complete(dev);
}
int main(void)
{
  // libusb_device **devices;
  // int response;
  // ssize_t i;
  
  libusb_device_handle *lpcdevice;
  unsigned char buffer[64];
  int transferred = 0;
  int bulk_out_magic_number = 0;

  /* Initialise libusbx */
  if(libusb_init(NULL))
  {
		printf("Failed to initialise libusbx\n");
    return -1;
  }
  
  //  /* Get a list of USB devices */
  //  i = libusb_get_device_list(NULL, &devices);
  //  if (i < 0)
  //  {
  //		printf("Failed getting the USB device list (Error: %d)\n", response);
  //    return (int)i;
  //  }
  //
  //  /* Show a list of connected devices */
  //	list_devices(devices);
  
  /* Try to connect to 0x1FC9, 0x2020 (LPC board) */
  lpcdevice = libusb_open_device_with_vid_pid(NULL, 0x1FC9, 0x2020);
  if (NULL == lpcdevice)
  {
    printf("Unable to open VID:0x1FC9 PID:0x2020\n");
    libusb_exit(NULL);
    return -1;
  }

  /* We need to claim the interface before we can do any IO */
  if(libusb_claim_interface(lpcdevice, 0))
  {
    printf("Unable to claim the device interface for VID:0x1FC9 PID:0x2020\n");
    libusb_exit(NULL);
    return -1;
  }  

  /* Transfer some data! */
  /*
  printf("Transferring data to 0x1FC9/0x2020\n");
  uint8_t counter = 0;
  uint32_t c;
  for( c=0; c < 1000; c++ )
  {
    buffer[0] = counter++;
    buffer[1] = 0xAA; 
    buffer[2] = 0xBB; 
    buffer[3] = 0xCC; 
    buffer[4] = 0xDD; 
    buffer[5] = 0xEE; 
    libusb_bulk_transfer(lpcdevice, 0x04, buffer, 6, &transferred, 0); 
  }
  printf("Done!\n");
  */
  
  
  /* Read incoming data! */
  while(1)
  {
    memset(buffer, 0, sizeof(buffer));
    if(libusb_bulk_transfer(lpcdevice, 0x81, buffer, 64, &transferred, 0))
    {
      printf("\nError in read! received = %d\n", transferred);    
      return -1;    
    }
    else
    {
      printf("\nReceived %d bytes\n", transferred);    
      printf("%d", buffer[0]);
    }
    
    memset(buffer, 0, sizeof(buffer));
    buffer[0] = bulk_out_magic_number++;
    if(libusb_bulk_transfer(lpcdevice, 0x04, buffer, 64, &transferred, 0))
    {
      printf("\nError in sending! sent = %d\n", transferred);
    }else
    {
      printf("\nSent %d bytes, 1st byte = %d\n", transferred, buffer[0]);    
    }
  }

  /* Free up the device list and close libusbx */
	// libusb_free_device_list(devices, 1);
  libusb_release_interface(lpcdevice, 0);
	libusb_exit(NULL);
  
	return 0;
}
Example #18
0
int
main (int argc, char *argv[])
{
	struct options options = { 0 };
	struct sensei_config new_config = { 0 };

	parse_options (argc, argv, &options, &new_config);

	int result, status = 0;

	result = libusb_init (NULL);
	if (result)
		ERROR (error_0, "libusb initialisation failed: %s\n",
			libusb_error_name (result));

	static const int products[] =
	{
		USB_PRODUCT_STEELSERIES_SENSEI_RAW,
		USB_PRODUCT_STEELSERIES_COD_BO2
	};

	result = 0;
	libusb_device_handle *device = find_device_list (USB_VENDOR_STEELSERIES,
		products, sizeof products / sizeof products[0], &result);
	if (!device)
	{
		if (result)
			ERROR (error_1, "couldn't open device: %s\n",
				libusb_error_name (result));
		else
			ERROR (error_1, "no suitable device found\n");
	}

	bool reattach_driver = false;

	result = libusb_kernel_driver_active (device, SENSEI_CTL_IFACE);
	switch (result)
	{
	case 0:
	case LIBUSB_ERROR_NOT_SUPPORTED:
		break;
	case 1:
		reattach_driver = true;
		result = libusb_detach_kernel_driver (device, SENSEI_CTL_IFACE);
		if (result)
			ERROR (error_2, "couldn't detach kernel driver: %s\n",
				libusb_error_name (result));
		break;
	default:
		ERROR (error_2, "coudn't detect kernel driver presence: %s\n",
			libusb_error_name (result));
	}

	result = libusb_claim_interface (device, SENSEI_CTL_IFACE);
	if (result)
		ERROR (error_3, "couldn't claim interface: %s\n",
			libusb_error_name (result));

	result = apply_options (device, &options, &new_config);
	if (result)
		ERROR (error_4, "operation failed: %s\n",
			libusb_error_name (result));

error_4:
	result = libusb_release_interface (device, SENSEI_CTL_IFACE);
	if (result)
		ERROR (error_3, "couldn't release interface: %s\n",
			libusb_error_name (result));

error_3:
	if (reattach_driver)
	{
		result = libusb_attach_kernel_driver (device, SENSEI_CTL_IFACE);
		if (result)
			ERROR (error_2, "couldn't reattach kernel driver: %s\n",
				libusb_error_name (result));
	}

error_2:
	libusb_close (device);
error_1:
	libusb_exit (NULL);
error_0:
	return status;
}
Example #19
0
int main(void)
{
	struct sigaction sigact;
	int r = 1;

	r = libusb_init(NULL);
	if (r < 0) {
		fprintf(stderr, "failed to initialise libusb\n");
		exit(1);
	}

	r = find_dpfp_device();
	if (r < 0) {
		fprintf(stderr, "Could not find/open device\n");
		goto out;
	}

	r = libusb_claim_interface(devh, 0);
	if (r < 0) {
		fprintf(stderr, "usb_claim_interface error %d %s\n", r, strerror(-r));
		goto out;
	}
	printf("claimed interface\n");

	r = print_f0_data();
	if (r < 0)
		goto out_release;

	r = do_init();
	if (r < 0)
		goto out_deinit;

	/* async from here onwards */

	sigact.sa_handler = sighandler;
	sigemptyset(&sigact.sa_mask);
	sigact.sa_flags = 0;
	sigaction(SIGINT, &sigact, NULL);
	sigaction(SIGTERM, &sigact, NULL);
	sigaction(SIGQUIT, &sigact, NULL);

	r = pthread_create(&poll_thread, NULL, poll_thread_main, NULL);
	if (r)
		goto out_deinit;

	r = alloc_transfers();
	if (r < 0) {
		request_exit(1);
		pthread_join(poll_thread, NULL);
		goto out_deinit;
	}

	r = init_capture();
	if (r < 0) {
		request_exit(1);
		pthread_join(poll_thread, NULL);
		goto out_deinit;
	}

	while (!do_exit) {
		pthread_mutex_lock(&exit_cond_lock);
		pthread_cond_wait(&exit_cond, &exit_cond_lock);
		pthread_mutex_unlock(&exit_cond_lock);
	}

	printf("shutting down...\n");
	pthread_join(poll_thread, NULL);

	r = libusb_cancel_transfer(irq_transfer);
	if (r < 0) {
		request_exit(1);
		goto out_deinit;
	}

	r = libusb_cancel_transfer(img_transfer);
	if (r < 0) {
		request_exit(1);
		goto out_deinit;
	}

	while (img_transfer || irq_transfer)
		if (libusb_handle_events(NULL) < 0)
			break;

	if (do_exit == 1)
		r = 0;
	else
		r = 1;

out_deinit:
	libusb_free_transfer(img_transfer);
	libusb_free_transfer(irq_transfer);
	set_mode(0);
	set_hwstat(0x80);
out_release:
	libusb_release_interface(devh, 0);
out:
	libusb_close(devh);
	libusb_exit(NULL);
	return r >= 0 ? r : -r;
}
Example #20
0
int main( int argc, char **argv )
{
    static const char *progname = PACKAGE;
    int retval = SUCCESS;
    int status;
    dfu_device_t dfu_device;
    struct programmer_arguments args;
#ifdef HAVE_LIBUSB_1_0
    struct libusb_device *device = NULL;
#else
    struct usb_device *device = NULL;
#endif

    memset( &args, 0, sizeof(args) );
    memset( &dfu_device, 0, sizeof(dfu_device) );

    status = parse_arguments(&args, argc, argv);
    if( status < 0 ) {
        /* Exit with an error. */
        return ARGUMENT_ERROR;
    } else if (status > 0) {
        /* It was handled by parse_arguments. */
        return SUCCESS;
    }

#ifdef HAVE_LIBUSB_1_0
    if (libusb_init(&usbcontext)) {
        fprintf( stderr, "%s: can't init libusb.\n", progname );
        return DEVICE_ACCESS_ERROR;
    }
#else
    usb_init();
#endif

    if( debug >= 200 ) {
#ifdef HAVE_LIBUSB_1_0
        libusb_set_debug(usbcontext, debug );
#else
        usb_set_debug( debug );
#endif
    }

    if( !(args.command == com_bin2hex || args.command == com_hex2bin) ) {
        device = dfu_device_init( args.vendor_id, args.chip_id,
                                  args.bus_id, args.device_address,
                                  &dfu_device,
                                  args.initial_abort,
                                  args.honor_interfaceclass );

        if( NULL == device ) {
            fprintf( stderr, "%s: no device present.\n", progname );
            retval = DEVICE_ACCESS_ERROR;
            goto error;
        }
    }

    if( 0 != (retval = execute_command(&dfu_device, &args)) ) {
        /* command issued a specific diagnostic already */
        goto error;
    }

error:
    if( NULL != dfu_device.handle ) {
        int rv;

#ifdef HAVE_LIBUSB_1_0
        rv = libusb_release_interface( dfu_device.handle, dfu_device.interface );
#else
        rv = usb_release_interface( dfu_device.handle, dfu_device.interface );
#endif
        /* The RESET command sometimes causes the usb_release_interface command to fail.
           It is not obvious why this happens but it may be a glitch due to the hardware
           reset in the attached device. In any event, since reset causes a USB detach
           this should not matter, so there is no point in raising an alarm.
        */
        if( 0 != rv && !(com_launch == args.command &&
                args.com_launch_config.noreset == 0) ) {
            fprintf( stderr, "%s: failed to release interface %d.\n",
                             progname, dfu_device.interface );
            retval = DEVICE_ACCESS_ERROR;
        }
    }

    if( NULL != dfu_device.handle ) {
#ifdef HAVE_LIBUSB_1_0
        libusb_close(dfu_device.handle);
#else
        if( 0 != usb_close(dfu_device.handle) ) {
            fprintf( stderr, "%s: failed to close the handle.\n", progname );
            retval = DEVICE_ACCESS_ERROR;
        }
#endif
    }

#ifdef HAVE_LIBUSB_1_0
    libusb_exit(usbcontext);
#endif

    return retval;
}
Example #21
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 #22
0
int test_device(uint16_t vid, uint16_t pid)
{
	libusb_device_handle *handle;
	libusb_device *dev;
	uint8_t bus, port_path[8];
	struct libusb_config_descriptor *conf_desc;
	const struct libusb_endpoint_descriptor *endpoint;
	int i, j, k, r;
	int iface, nb_ifaces;
#if defined(__linux)
	// Attaching/detaching the kernel driver is only relevant for Linux
	int iface_detached = -1;
#endif
	struct libusb_device_descriptor dev_desc;
	char string[128];
	uint8_t string_index[3];	// indexes of the string descriptors
	uint8_t endpoint_in = 0, endpoint_out = 0;	// default IN and OUT endpoints

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

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

	dev = libusb_get_device(handle);
	bus = libusb_get_bus_number(dev);
	r = libusb_get_port_path(NULL, dev, port_path, sizeof(port_path));
	if (r > 0) {
		printf("bus: %d, port path from HCD: %d", bus, port_path[0]);
		for (i=1; i<r; i++) {
			printf("->%d", port_path[i]);
		}
		printf("\n");
	}

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

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

	for (iface = 0; iface < nb_ifaces; iface++)
	{
		printf("\nClaiming interface %d...\n", iface);
		r = libusb_claim_interface(handle, iface);
#if defined(__linux)
		if ((r != LIBUSB_SUCCESS) && (iface == 0)) {
			// Maybe we need to detach the driver
			perr("   Failed. Trying to detach driver...\n");
			libusb_detach_kernel_driver(handle, iface);
			iface_detached = iface;
			printf("   Claiming interface again...\n");
			r = libusb_claim_interface(handle, iface);
		}
#endif
		if (r != LIBUSB_SUCCESS) {
			perr("   Failed.\n");
		}
	}

	printf("\nReading string descriptors:\n");
	for (i=0; i<3; i++) {
		if (string_index[i] == 0) {
			continue;
		}
		if (libusb_get_string_descriptor_ascii(handle, string_index[i], string, 128) >= 0) {
			printf("   String (0x%02X): \"%s\"\n", string_index[i], string);
		}
	}

	switch(test_mode) {
	case USE_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_SCSI:
		CALL_CHECK(test_mass_storage(handle, endpoint_in, endpoint_out));
	default:
		break;
	}

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

#if defined(__linux)
	if (iface_detached >= 0) {
		printf("Re-attaching kernel driver...\n");
		libusb_attach_kernel_driver(handle, iface_detached);
	}
#endif

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

	return 0;
}
//TODO: get the deletion shutdown of objects ordered right
int Protonect::closeKinect(){

 if( bOpened ){

    bOpened = false;
    shutdown = true;
    
    rgb_bulk_transfers->disableSubmission();
    depth_iso_transfers->disableSubmission();

    rgb_bulk_transfers->cancel();
    depth_iso_transfers->cancel();
    

    CloseKinect(handle);

    // wait for all transfers to cancel
    // TODO: better implementation
    libfreenect2::this_thread::sleep_for(libfreenect2::chrono::seconds(2));

    rgb_bulk_transfers->deallocate();
    depth_iso_transfers->deallocate();

    int iface = 0;
    printf("Releasing interface %d...\n", iface);
    libusb_release_interface(handle, iface);

    iface = 1;
    printf("Releasing interface %d...\n", iface);
    libusb_release_interface(handle, iface);

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

    usb_loop.stop();

    libusb_exit(NULL);
    
    
    if(frame_listener != NULL){
        delete frame_listener;
        frame_listener = NULL;
    }
    
    if(rgb_bulk_transfers != NULL){
        delete rgb_bulk_transfers;
        rgb_bulk_transfers = NULL;
    }
    
    if(depth_iso_transfers != NULL){
        delete depth_iso_transfers;
        depth_iso_transfers = NULL;
    }
    
    if(depth_processor != NULL){
        delete depth_processor;
        depth_processor = NULL;
    }

   // if(rgb_processor != NULL){
   //     delete rgb_processor;
   //     rgb_processor = NULL;
   // }
    
    if(rgb_packet_stream_parser != NULL){
        delete rgb_packet_stream_parser;
        rgb_packet_stream_parser = NULL;
    }
    
    if(depth_packet_stream_parser != NULL){
        delete depth_packet_stream_parser;
        depth_packet_stream_parser = NULL;
    }
    
    
     
  }
  return 0;
}
Example #24
0
int main(int argc, const char * argv[])
{
    libusb_device ** devs;
    int r = libusb_init(NULL);
    if(r < 0) {
        fprintf(stderr, "libusb_init() returned error %d\n", r);
        return r;
    }
    
    ssize_t cnt = libusb_get_device_list(NULL, &devs);
    if(cnt < 0) {
        fprintf(stderr, "libusb_get_device_list() returned error %d\n", r);
        return cnt;
    }
    
    // for(libusb_device ** dev = devs; *dev != NULL; dev++)
    //     print_dev(*dev);
    libusb_device * lpcdev = find_lpc(devs);
    if(lpcdev)
    {
        printf("Found device:\n");
        print_dev(lpcdev);
        
        libusb_device_handle * lpchand;
        r = libusb_open(lpcdev, &lpchand);
        if(r < 0) {
            fprintf(stderr, "libusb_open() returned error %d\n", r);
            exit(r);
        }
        
        r = libusb_set_configuration(lpchand, 1);
        if(r < 0) {
            fprintf(stderr, "libusb_set_configuration() returned error %d\n", r);
            libusb_close(lpchand);
            exit(r);
        }
        
        int interface = 1;
        
        r = libusb_claim_interface(lpchand, interface);
        if(r < 0) {
            fprintf(stderr, "libusb_claim_interface() returned error %d\n", r);
            libusb_close(lpchand);
            exit(r);
        }
        
        // uint8_t endpoint = 0x82;
        uint8_t endpoint = 0x02;
        uint8_t data[256];
        char * chdata = (char *)data;
        int length, actualLength;
        
        // data[0] = 100;
        strcpy(chdata, "USB MESSAGE     ");
        length = 16;
        r = libusb_bulk_transfer(lpchand, endpoint, data, length, &actualLength, 1000);
        if(r < 0) {
            fprintf(stderr, "libusb_bulk_transfer() returned error %d\n", r);
            libusb_release_interface(lpchand, interface);
            libusb_close(lpchand);
            exit(r);
        }
        fprintf(stderr, "libusb_bulk_transfer() returned %d\n", r);
        printf("Bytes transferred: %d\n", actualLength);
        
        r = libusb_release_interface(lpchand, interface);
        if(r < 0) {
            fprintf(stderr, "libusb_release_interface() returned error %d\n", r);
            libusb_close(lpchand);
            exit(r);
        }
        
        libusb_close(lpchand);
    }
    else
    {
        printf("Device not found\n");
    }
    
    libusb_free_device_list(devs, 1);
    libusb_exit(NULL);
    
    return EXIT_SUCCESS;
}
Example #25
0
int main(int argc, char * const argv[])
{
	struct sdp_dev *p_id;
	struct mach_id *mach;
	libusb_device **devs;
	libusb_device *dev;
	int r;
	int err;
	ssize_t cnt;
	libusb_device_handle *h = NULL;
	int config = 0;
	int verify = 0;
	struct sdp_work *curr;
	struct sdp_work *cmd_head = NULL;
	char const *conf;
	char const *base_path = get_base_path(argv[0]);
	char const *conf_path = "/etc/imx-loader.d/";

	err = parse_opts(argc, argv, &conf_path, &verify, &cmd_head);
	if (err < 0)
		return -1;

	// Get list of machines...
	conf = conf_file_name("imx_usb.conf", base_path, conf_path);
	if (conf == NULL)
		return -1;

	struct mach_id *list = parse_imx_conf(conf);
	if (!list)
		return -1;

	r = libusb_init(NULL);
	if (r < 0)
		goto out;

	cnt = libusb_get_device_list(NULL, &devs);
	if (cnt < 0)
		goto out;

//	print_devs(devs);
	dev = find_imx_dev(devs, &mach, list);
	if (dev) {
		err = libusb_open(dev, &h);
		if (err)
			printf("%s:Could not open device vid=0x%x pid=0x%x err=%d\n", __func__, mach->vid, mach->pid, err);
	}
	libusb_free_device_list(devs, 1);

	if (!h)
		goto out;

	// Get machine specific configuration file..
	conf = conf_file_name(mach->file_name, base_path, conf_path);
	if (conf == NULL)
		goto out;

	p_id = parse_conf(conf);
	if (!p_id)
		goto out;

	if (p_id->mode == MODE_HID)
		p_id->transfer = &transfer_hid;
	if (p_id->mode == MODE_BULK)
		p_id->transfer = &transfer_bulk;

	// USB private pointer is libusb device handle...
	p_id->priv = h;

	libusb_get_configuration(h, &config);
	printf("%04x:%04x(%s) bConfigurationValue =%x\n",
			mach->vid, mach->pid, p_id->name, config);

	if (libusb_kernel_driver_active(h, 0))
		 libusb_detach_kernel_driver(h, 0);

	err = libusb_claim_interface(h, 0);
	if (err) {
		printf("Claim failed\n");
		goto out;
	}
	printf("Interface 0 claimed\n");
	err = do_status(p_id);
	if (err) {
		printf("status failed\n");
		goto out;
	}

	// By default, use work from config file...
	curr = p_id->work;

	if (cmd_head != NULL)
		curr = cmd_head;

	if (curr == NULL) {
		printf("no job found\n"); 
		goto out;
	}

	while (curr) {
		if (curr->mem)
			perform_mem_work(p_id, curr->mem);
//		printf("jump_mode %x\n", curr->jump_mode);
		if (curr->filename[0]) {
			err = DoIRomDownload(p_id, curr, verify);
		}
		if (err) {
			err = do_status(p_id);
			break;
		}
		if (!curr->next && (!curr->plug || curr != cmd_head))
			break;
		err = do_status(p_id);
		printf("jump_mode %x plug=%i err=%i\n", curr->jump_mode, curr->plug, err);
		if (err) {
			int retry;
			/* Rediscovers device */
			libusb_release_interface(h, 0);
			libusb_close(h);
			libusb_exit(NULL);
			for (retry = 0; retry < 10; retry++) {
				printf("sleeping\n");
				sleep(3);
				printf("done sleeping\n");
				h = open_vid_pid(mach, p_id);
				if (h)
					break;
			}
			if (!h)
				goto out;
		}
		if (curr == cmd_head && curr->plug) {
			curr->plug = 0;
			continue;
		}
		curr = curr->next;
	}

exit:
	libusb_release_interface(h, 0);
out:
	if (h)
		libusb_close(h);
	libusb_exit(NULL);
	return 0;
}
Example #26
0
//*****************************************************************************
//
//! Initializes the sample API.
//!
//! This function prepares the sample API for use by the application.
//!
//! \return None.
//
//*****************************************************************************
int
main(int argc, char *argv[])
{
    int rc;
    unsigned int iDev, iCfg, iIf, iAlt, iEndp;
    ssize_t nDevs;

    libusb_device        **pDevices;
    libusb_device        *pDev;

    struct libusb_config_descriptor *pdCfg;
    struct libusb_device_descriptor dDev;

    rc = libusb_init(&pCtx);
    ASSERT(rc == 0);

    // libusb_set_debug(pCtx, 5);


    nDevs = libusb_get_device_list(pCtx, &pDevices);
    TRACE(0, "nDevs = %d\n", (int)nDevs);
    ASSERT(nDevs >= 0);

    pDev = NULL;
    for (iDev = 0; iDev < nDevs; iDev++)
    {
        TRACE(0, "Considering device %d\n", iDev);
        //
        // Get the device descriptor so we know how many configurations there are
        //
        rc = libusb_get_device_descriptor(pDevices[iDev], &dDev);
        ASSERT(rc == 0);
        if ((dDev.idVendor == LMICDI_VID) &&
            (dDev.idProduct == LMICDI_PID))
        {
            pDev = pDevices[iDev];
            TRACE(1, "Found device with matching VID and PID.  pDev = %p\n", pDev);
            break;
        }
    }
    ASSERT(pDev != NULL);

    rc = libusb_open(pDev, &phDev);
    if (rc != 0)
    {
        TRACE(ALWAYS, "Failed to open device.  rc = %d\n", rc);
    }

    //
    // NOTE: If/When we get here dDev should still be valid
    //

    // For each configuration... 
    //   for each interface...
    //     for each alternate config for the interface...
    //        for each endpoint...
    //
    for (iCfg = 0; iCfg < dDev.bNumConfigurations; iCfg++)
    {
        TRACE(1, D0 "iCfg = %d\n", iCfg);

        rc = libusb_get_config_descriptor(pDev, iCfg, &pdCfg);
        ASSERT(rc == 0);

        //
        // It seems as though we need to detach the kernel before we can read
        // strings for ourselves.
        //
#if 0
        for (iIf = 0; iIf < pdCfg->bNumInterfaces; iIf++)
        {
            rc = libusb_kernel_driver_active(phDev, iIf);
            TRACE(1, D1 "kernel_driver_active(if%d) = %d\n",
                  iIf, rc);
            if (rc)
            {
                TRACE(1, D1 "Attempting to detach...");
                rc = libusb_detach_kernel_driver(phDev, iIf);
                if (rc)
                {
                    TRACE(1, " failed (%d)\n", rc);
                }
                else
                {
                    bKernel[iIf] = 1;

                    TRACE(1, " OK\n");
                }
            }
        }
#endif
        //
        // if the MFGr string is coming back as 0 then the device is wedged.
        //
        if (dDev.iManufacturer == 0) exit(EXIT_FAILURE);

        //
        // TODO: Figure out why some string indexes are coming back as 0
        //
        // _dump_cfg_strings(phDev, pdCfg, D0);
        // _dump_dev_strings(phDev, &dDev, D0);

        for (iIf = 0; iIf < pdCfg->bNumInterfaces; iIf++)
        {
            const struct libusb_interface *pIf = &pdCfg->interface[iIf];
            TRACE(1, D1 "iIf = %d\n", iIf);

            for (iAlt = 0; iAlt < pIf->num_altsetting; iAlt++)
            {
                const struct libusb_interface_descriptor *pdIf = 
                    &pIf->altsetting[iAlt];

                TRACE(1, D2 "iAlt = %d\n", iAlt);
                _dump_if_strings(phDev, pdIf, D2);

                //
                // The "correct" thing to do would be to identify the 
                // interface based on its name and string index but, at 
                // the moment, the iInterface is coming back as 0. 
                // Instead, we'll grab the interface that uses the
                // VENDOR_SPECIFIC class 
                //
                if (pdIf->bInterfaceClass != LIBUSB_CLASS_VENDOR_SPEC)
                {
                    continue;
                }
                
                // 
                // The interface we're interested in should have two endpoints
                //
                if (pdIf->bNumEndpoints != 2)
                {
                    continue;
                }

                rc = libusb_claim_interface(phDev, iIf);
                ASSERT(rc == 0);
                
                for (iEndp = 0; iEndp < pdIf->bNumEndpoints; iEndp++)
                {
                    const struct libusb_endpoint_descriptor *pdEndp = 
                        &pdIf->endpoint[iEndp];

                    TRACE(1, D3 "iEndp = %d\n", iEndp);
                   if ((pdEndp->bmAttributes & 0x3) != 
                            LIBUSB_TRANSFER_TYPE_BULK)
                    {
                        continue;
                    }

                    if ((pdEndp->bEndpointAddress & LIBUSB_ENDPOINT_DIR_MASK) == 
                            LIBUSB_ENDPOINT_IN)
                    {
                        TRACE(1, D3 "Found ENDPOINT_IN\n");
                        pdEndpIn = pdEndp;
                        continue;
                    }

                    if ((pdEndp->bEndpointAddress & LIBUSB_ENDPOINT_DIR_MASK) == 
                            LIBUSB_ENDPOINT_OUT)
                    {
                        TRACE(1, D3 "Found ENDPOINT_OUT\n");
                        pdEndpOut = pdEndp;
                        continue;
                    }

                    //
                    // We should never get here.  An endpoint has to be either 
                    // in or out
                    //
                    TRACE(ALWAYS, "%s[%d]: Unexpected error\n", __FILE__, __LINE__);
                    ASSERT(0);
                }
                goto found;
            }    
        }
    }

found:
    libusb_free_device_list(pDevices, 1);

    //
    // EXPERIMENT:  Can we kick of an async receive and then do a 
    // synchronous transmit? ANSWER:  YES!
    //
    pTrans = libusb_alloc_transfer(0);
    ASSERT(pTrans != NULL);
    
    //
    // Set up a pending receive...
    //
    pTrans->dev_handle = phDev;
    pTrans->flags = 0;              // no auto-freeing of transfers
    pTrans->endpoint = pdEndpIn->bEndpointAddress;
    pTrans->type = LIBUSB_TRANSFER_TYPE_BULK;
    pTrans->timeout = 0;           // no timeout
    pTrans->buffer = pResp;
    pTrans->length = sizeof(pResp);
    pTrans->callback = usb_callback;
    pTrans->num_iso_packets = 0;
    pTrans->user_data = &gdbUsbCtx;

    //
    // And wait for a RX operation to complete...
    //
    rc = libusb_submit_transfer(pTrans);
    if (rc != 0)
    {
        TRACE(ALWAYS, "%s: ERROR: submit_transfer rc = %d\n", __FUNCTION__, rc);
    }

    SocketIO(PORT, phDev);

    TRACE(1, "%s: libusb_release_interface\n", __FUNCTION__);
    libusb_release_interface(phDev, iIf);

    TRACE(1, "%s: libusb_close(phDev)\n", __FUNCTION__);
    libusb_close(phDev);

    TRACE(1, "%s: libusb_exit\n", __FUNCTION__);
    libusb_exit(pCtx);

    return(EXIT_SUCCESS);
}
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 #28
0
/*
 * This function applys changes to the device.
 *
 * New settings are in port->settings_pending and the old ones
 * are in port->settings. Compare them first and only call
 * usb_set_configuration() and usb_set_altinterface() if needed
 * since some USB devices does not like it if this is done
 * more than necessary (Canon Digital IXUS 300 for one).
 *
 */
static int
gp_libusb1_update (GPPort *port)
{
	int ifacereleased = FALSE, changedone = FALSE;

	C_PARAMS (port && port->pl && port->pl->ctx);

	GP_LOG_D ("(old int=%d, conf=%d, alt=%d) port %s, (new int=%d, conf=%d, alt=%d) port %s",
		port->settings.usb.interface,
		port->settings.usb.config,
		port->settings.usb.altsetting,
		port->settings.usb.port,
		port->settings_pending.usb.interface,
		port->settings_pending.usb.config,
		port->settings_pending.usb.altsetting,
		port->settings_pending.usb.port
	);

/* do not overwrite it ... we need to set it.
	if (port->pl->interface == -1) port->pl->interface = port->settings.usb.interface;
	if (port->pl->config == -1) port->pl->config = port->settings.usb.config;
	if (port->pl->altsetting == -1) port->pl->altsetting = port->settings.usb.altsetting;
*/

	/* The portname can also be changed with the device still fully closed. */
	memcpy(&port->settings.usb.port, &port->settings_pending.usb.port,
		sizeof(port->settings.usb.port));

	if (!port->pl->dh) {
		GP_LOG_D("lowlevel libusb1 port not yet opened, no need for libusb changes");
		return GP_OK; /* the port might not be opened, yet. that is ok */
	}

	memcpy(&port->settings.usb, &port->settings_pending.usb,
		sizeof(port->settings.usb));

	/* The interface changed. release the old, claim the new ... */
	if (port->settings.usb.interface != port->pl->interface) {
		GP_LOG_D ("changing interface %d -> %d", port->pl->interface, port->settings.usb.interface);
		if (LOG_ON_LIBUSB_E (libusb_release_interface (port->pl->dh, port->pl->interface))) {
			/* Not a hard error for now. -Marcus */
		} else {
			GP_LOG_D ("claiming interface %d", port->settings.usb.interface);
			C_LIBUSB (libusb_claim_interface (port->pl->dh, port->settings.usb.interface),
				  GP_ERROR_IO_USB_CLAIM);
			port->pl->interface = port->settings.usb.interface;
		}
		changedone = TRUE;
	}
	if (port->settings.usb.config != port->pl->config) {
		GP_LOG_D ("changing config %d -> %d", port->pl->config, port->settings.usb.config);
		/* This can only be changed with the interface released. 
		 * This is a hard requirement since 2.6.12.
		 */
		if (LOG_ON_LIBUSB_E (libusb_release_interface (port->pl->dh, port->settings.usb.interface))) {
			ifacereleased = FALSE;
		} else {
			ifacereleased = TRUE;
		}
		if (LOG_ON_LIBUSB_E (libusb_set_configuration(port->pl->dh, port->settings.usb.config))) {
#if 0 /* setting the configuration failure is not fatal */
			int saved_errno = errno;
			gp_port_set_error (port,
					   _("Could not set config %d/%d (%s)"),
					   port->settings.usb.interface,
					   port->settings.usb.config,
					   strerror(saved_errno));
			return GP_ERROR_IO_UPDATE;	
#endif
			GP_LOG_E ("setting configuration from %d to %d failed, but continuing...", port->pl->config, port->settings.usb.config);
		}

		GP_LOG_D ("Changed usb.config from %d to %d", port->pl->config, port->settings.usb.config);

		if (ifacereleased) {
			GP_LOG_D ("claiming interface %d", port->settings.usb.interface);
			LOG_ON_LIBUSB_E (libusb_claim_interface (port->pl->dh, port->settings.usb.interface));
		}
		/*
		 * Copy at once if something else fails so that this
		 * does not get re-applied
		 */
		port->pl->config = port->settings.usb.config;
		changedone = TRUE;
	}

	/* This can be changed with interface claimed. (And I think it must be claimed.) */
	if (port->settings.usb.altsetting != port->pl->altsetting) {
		if (LOG_ON_LIBUSB_E (libusb_set_interface_alt_setting (port->pl->dh,
					port->settings.usb.interface, port->settings.usb.altsetting))) {
			int saved_errno = errno;
			gp_port_set_error (port,
					   _("Could not set altsetting from %d "
					     "to %d (%s)"),
					   port->pl->altsetting,
					   port->settings.usb.altsetting,
					   strerror(saved_errno));
			return GP_ERROR_IO_UPDATE;
		}

		GP_LOG_D ("Changed usb.altsetting from %d to %d", port->pl->altsetting, port->settings.usb.altsetting);
		port->pl->altsetting = port->settings.usb.altsetting;
		changedone = TRUE;
	}

	/* requeue the interrupts */
	if (changedone)
		gp_libusb1_queue_interrupt_urbs (port);
	return GP_OK;
}
Example #29
0
int main(int UNUSED argc, const char UNUSED * argv[]) {
    int actual;
    int result;
    int r;

    ssize_t fullSize = sizeof(bootp_packet) + sizeof(udp_t) +
                       sizeof(struct iphdr) + sizeof(struct ethhdr) +
                       sizeof(rndis_hdr);
    ssize_t rndisSize = sizeof(rndis_hdr);
    ssize_t etherSize = sizeof(struct ethhdr);
    ssize_t arpSize = sizeof(arp_hdr);
    ssize_t ipSize = sizeof(struct iphdr);
    ssize_t udpSize = sizeof(udp_t);
    ssize_t bootpSize = sizeof(bootp_packet);
    ssize_t tftpSize = sizeof(tftp_data);

    unsigned char *data = (unsigned char*)calloc(1, 1000);
    unsigned char *buffer = (unsigned char*)malloc(450 *
                            sizeof(unsigned char));

    FILE *send;

    libusb_device **devs = NULL;
    libusb_device_handle *dev_handle = NULL;
    libusb_context *ctx = NULL;

    r = libusb_init(&ctx);
    if (r < 0) {
        printf("Init error!\n");
        exit(1);
    }
    libusb_set_debug(ctx, 3);

    while (dev_handle == NULL) {
        r = libusb_get_device_list(ctx, &devs);
        if (r < 0) {
            printf("Cannot get device list.\n");
        }
        dev_handle = libusb_open_device_with_vid_pid(ctx,
                     ROMVID, ROMPID);
        libusb_free_device_list(devs, 1);
    }


    if (libusb_kernel_driver_active(dev_handle, 0) == 1) {
        libusb_detach_kernel_driver(dev_handle, 0);
    }

    r = libusb_claim_interface(dev_handle, 1);
    if (r < 0) {
        printf("Cannot Claim Interface!\n");
        exit(1);
    }

    r = libusb_bulk_transfer(dev_handle, (129 | LIBUSB_ENDPOINT_IN),
                             buffer, 450, &actual, 0);

    rndis_hdr *rndis = (rndis_hdr*)calloc(1, rndisSize);
    make_rndis(rndis, fullSize - rndisSize);

    struct ethhdr *ether = (struct ethhdr*)(buffer+rndisSize);
    struct ethhdr *eth2 = (struct ethhdr*)calloc(1, etherSize);
    make_ether2(eth2, ether->h_source, (unsigned char*)my_hwaddr);

    struct iphdr *ip = (struct iphdr*)calloc(1, ipSize);
    make_ipv4(ip, server_ip, BBB_ip, IPUDP, 0, ipSize + udpSize +
              bootpSize);

    udp_t *udp = (udp_t*)calloc(1, udpSize);
    make_udp(udp, bootpSize, BOOTPS, BOOTPC);

    bootp_packet *breq = (bootp_packet*)calloc(1, bootpSize);
    make_bootp(servername, filename, breq, 1, ether->h_source);

    memcpy(data, rndis, rndisSize);
    memcpy(data + rndisSize, eth2, etherSize);
    memcpy(data + rndisSize + etherSize, ip, ipSize);
    memcpy(data + rndisSize + etherSize + ipSize, udp, udpSize);
    memcpy(data + rndisSize + etherSize + ipSize + udpSize,
           breq, bootpSize);

    r = libusb_bulk_transfer(dev_handle, (2 | LIBUSB_ENDPOINT_OUT),
                             data, fullSize, &actual, 0);
    r = libusb_bulk_transfer(dev_handle, (129 | LIBUSB_ENDPOINT_IN),
                             buffer, 450, &actual, 0);

    arp_hdr *receivedArp = (arp_hdr*)(buffer + rndisSize + etherSize);
    arp_hdr *arpResponse = (arp_hdr*)calloc(1, arpSize);

    make_arp(arpResponse, 2, my_hwaddr, &receivedArp->ip_dest,
             (const uint8_t*)&receivedArp->hw_source,
             &receivedArp->ip_source);

    memset(data, 0, fullSize);

    make_rndis(rndis, etherSize + arpSize);
    eth2->h_proto = htons(ETHARPP);
    memcpy(data, rndis, rndisSize);
    memcpy(data + rndisSize, eth2, etherSize);
    memcpy(data + rndisSize + etherSize, arpResponse, arpSize);

    r = libusb_bulk_transfer(dev_handle, (2 | LIBUSB_ENDPOINT_OUT),
                             data, rndisSize + etherSize + arpSize,
                             &actual, 0);

    memset(buffer, 0, 450);

    r = libusb_bulk_transfer(dev_handle, (129 | LIBUSB_ENDPOINT_IN),
                             buffer, 450, &actual, 0);

    udp_t *udpSPL = (udp_t*)(buffer + rndisSize + etherSize + ipSize);
    tftp_data *tftp = (tftp_data*)calloc(1, sizeof(tftp_data));
    eth2->h_proto = htons(ETHIPP);
    int blk_number = 1;

    send = fopen("spl", "rb");

    if (send == NULL) {
        perror("Cannot open spl binary");
    }

    char *reader = (char*)malloc(512 * sizeof(char));

    while (!feof(send)) {
        memset(reader, 0, 512);
        memset(data, 0, fullSize);
        memset(rndis, 0, rndisSize);
        memset(ip, 0, ipSize);
        memset(udp, 0, udpSize);
        result = fread(reader, sizeof(char), 512, send);

        make_rndis(rndis, etherSize + ipSize +
                   udpSize + tftpSize + result);
        make_ipv4(ip, server_ip, BBB_ip, IPUDP, 0, ipSize + udpSize +
                  tftpSize + result);
        make_udp(udp, tftpSize + result, ntohs(udpSPL->udpDst),
                 ntohs(udpSPL->udpSrc));
        make_tftp_data(tftp, 3, blk_number);

        memcpy(data, rndis, rndisSize);
        memcpy(data + rndisSize, eth2, etherSize);
        memcpy(data + rndisSize + etherSize, ip, ipSize);
        memcpy(data + rndisSize + etherSize + ipSize, udp, udpSize);
        memcpy(data + rndisSize + etherSize + ipSize + udpSize,
               tftp, tftpSize);
        memcpy(data + rndisSize + etherSize + ipSize + udpSize +
               tftpSize, reader, result);

        r = libusb_bulk_transfer(dev_handle, (2 | LIBUSB_ENDPOINT_OUT),
                                 data, rndisSize + etherSize + ipSize +
                                 udpSize + tftpSize + result,
                                 &actual, 0);

        memset(buffer, 0, 450);

        r = libusb_bulk_transfer(dev_handle,
                                 (129 | LIBUSB_ENDPOINT_IN), buffer,
                                 450, &actual, 0);

        blk_number++;
    }

    fclose(send);
    libusb_close(dev_handle);

    sleep(1.5);

    libusb_get_device_list(ctx, &devs);
    dev_handle = libusb_open_device_with_vid_pid(ctx, SPLVID, SPLPID);

    while (dev_handle == NULL) {
        libusb_get_device_list(ctx, &devs);
        dev_handle = libusb_open_device_with_vid_pid(ctx, SPLVID,
                     SPLPID);
        libusb_free_device_list(devs, 1);
    }

    if (dev_handle == NULL) {
        printf("Error! Cannot open SPL device!\n");
        return -1;
    }

    libusb_free_device_list(devs, 1);

    if (libusb_kernel_driver_active(dev_handle, 0) == 1) {
        libusb_detach_kernel_driver(dev_handle, 0);
    }

    r = libusb_claim_interface(dev_handle, 1);

    printf("SPL has started!\n\n");

    memset(buffer, 0, 450);
    memset(data, 0, 1000);
    memset(rndis, 0, rndisSize);
    memset(eth2, 0, etherSize);
    memset(ip, 0, ipSize);
    memset(udp, 0, udpSize);
    memset(breq, 0, bootpSize);

    r = libusb_bulk_transfer(dev_handle, (129 | LIBUSB_ENDPOINT_IN),
                             buffer, 450, &actual, 0);

    make_rndis(rndis, fullSize - rndisSize);
    eth2->h_proto = htons(ETHIPP);
    make_ipv4(ip, server_ip, BBB_ip, IPUDP, 0, ipSize +
              udpSize + bootpSize);
    make_udp(udp, bootpSize, ntohs(((udp_t*)(buffer + rndisSize +
                                    etherSize + ipSize))->udpDst),
             ntohs(((udp_t*)(buffer + rndisSize +
                             etherSize + ipSize))->udpSrc));
    make_bootp(servername, uboot, breq, ntohl(((bootp_packet*)(buffer +
               rndisSize + etherSize + ipSize + udpSize))->xid),
               ether->h_source);

    memcpy(data, rndis, rndisSize);
    memcpy(data + rndisSize, eth2, etherSize);
    memcpy(data + rndisSize + etherSize, ip, ipSize);
    memcpy(data + rndisSize + etherSize + ipSize, udp, udpSize);
    memcpy(data + rndisSize + etherSize + ipSize + udpSize,
           breq, bootpSize);

    r = libusb_bulk_transfer(dev_handle, (1 | LIBUSB_ENDPOINT_OUT),
                             data, fullSize, &actual, 0);

    r = libusb_bulk_transfer(dev_handle, (129 | LIBUSB_ENDPOINT_IN),
                             buffer, 450, &actual, 0);

    memset(data, 0 , fullSize);
    memset(rndis, 0, rndisSize);

    make_rndis(rndis, etherSize + arpSize);
    eth2->h_proto = htons(ETHARPP);
    memcpy(data, rndis, rndisSize);
    memcpy(data + rndisSize, eth2, etherSize);
    memcpy(data +rndisSize + etherSize, arpResponse, arpSize);

    r = libusb_bulk_transfer(dev_handle, (1 | LIBUSB_ENDPOINT_OUT),
                             data, rndisSize + etherSize +arpSize,
                             &actual, 0);

    r = libusb_bulk_transfer(dev_handle, (129 | LIBUSB_ENDPOINT_IN),
                             buffer, 450, &actual, 0);

    udp_t *received = (udp_t*)(buffer + rndisSize + etherSize + ipSize);
    eth2->h_proto = htons(ETHIPP);

    blk_number = 1;
    send = fopen("uboot", "rb");

    if (send == NULL) {
        perror("Cannot open uboot binary");
    }

    memset(reader, 0, 512);

    while (!feof(send)) {
        memset(data, 0, fullSize);
        memset(rndis, 0, rndisSize);
        memset(ip, 0, ipSize);
        memset(udp, 0, udpSize);

        result = fread(reader, sizeof(char), 512, send);

        make_rndis(rndis, etherSize + ipSize +
                   udpSize + tftpSize + result);
        make_ipv4(ip, server_ip, BBB_ip, IPUDP, 0, ipSize + udpSize +
                  tftpSize + result);
        make_udp(udp, tftpSize + result, ntohs(received->udpDst),
                 ntohs(received->udpSrc));
        make_tftp_data(tftp, 3, blk_number);

        memcpy(data, rndis, rndisSize);
        memcpy(data + rndisSize, eth2, etherSize);
        memcpy(data + rndisSize + etherSize, ip, ipSize);
        memcpy(data + rndisSize + etherSize + ipSize, udp, udpSize);
        memcpy(data + rndisSize + etherSize + ipSize + udpSize,
               tftp, tftpSize);
        memcpy(data + rndisSize + etherSize + ipSize + udpSize +
               tftpSize, reader, result);

        r = libusb_bulk_transfer(dev_handle, (1 | LIBUSB_ENDPOINT_OUT),
                                 data, rndisSize + etherSize + ipSize +
                                 udpSize + tftpSize + result,
                                 &actual, 0);

        memset(buffer, 0, 450);

        r = libusb_bulk_transfer(dev_handle,
                                 (129 | LIBUSB_ENDPOINT_IN),
                                 buffer, 450, &actual, 0);

        blk_number++;
    }

    fclose(send);

    r = libusb_release_interface(dev_handle, 1);
    if (r < 0) {
        printf("Cannot release interface!\n");
        exit(1);
    }
    libusb_close(dev_handle);

    sleep(3);

    dev_handle = NULL;

    while (dev_handle == NULL) {
        r = libusb_get_device_list(ctx, &devs);
        if (r < 0) {
            printf("Cannot get device list\n");
            exit (1);
        }
        dev_handle = libusb_open_device_with_vid_pid(ctx,
                     UBOOTVID, UBOOTPID);
        libusb_free_device_list(devs, 1);
    }

    if (libusb_kernel_driver_active(dev_handle, 0) == 1) {
        libusb_detach_kernel_driver(dev_handle, 0);
    }

    r = libusb_claim_interface(dev_handle, 1);

    printf("U-Boot has started! Sending now the FIT image!\n\n");

    memset(data, 0, fullSize);
    make_rndis(rndis, etherSize + arpSize);
    eth2->h_proto = htons(ETHARPP);
    memcpy(data, rndis, rndisSize);
    memcpy(data + rndisSize, eth2, etherSize);
    memcpy(data + rndisSize + etherSize, arpResponse, arpSize);

    r = libusb_bulk_transfer(dev_handle, (1 | LIBUSB_ENDPOINT_OUT),
                             data, rndisSize + etherSize +
                             arpSize, &actual, 0);
    memset(buffer, 0, 450);

    r = libusb_bulk_transfer(dev_handle, (129 | LIBUSB_ENDPOINT_IN),
                             buffer, 450, &actual, 0);

    eth2->h_proto = htons(ETHIPP);
    blk_number = 1;
    send = fopen("fit", "rb");

    if (send == NULL) {
        perror("Cannot open fit binary");
        exit(1);
    }

    memset(reader, 0, 512);

    while (!feof(send)) {
        memset(data, 0, fullSize);
        memset(rndis, 0, rndisSize);
        memset(ip, 0, ipSize);
        memset(udp, 0, udpSize);

        result = fread(reader, sizeof(char), 512, send);
        make_rndis(rndis, etherSize + ipSize +
                   udpSize + tftpSize + result);
        make_ipv4(ip, server_ip, BBB_ip, IPUDP, 0, ipSize + udpSize +
                  tftpSize + result);
        make_udp(udp, tftpSize + result, ntohs(received->udpDst),
                 ntohs(received->udpSrc));
        make_tftp_data(tftp, 3, blk_number);

        memcpy(data, rndis, rndisSize);
        memcpy(data + rndisSize, eth2, etherSize);
        memcpy(data + rndisSize + etherSize, ip, ipSize);
        memcpy(data + rndisSize + etherSize + ipSize, udp, udpSize);
        memcpy(data + rndisSize + etherSize + ipSize +
               udpSize, tftp, tftpSize);
        memcpy(data + rndisSize + etherSize + ipSize + udpSize +
               tftpSize, reader, result);

        r = libusb_bulk_transfer(dev_handle, (1 | LIBUSB_ENDPOINT_OUT),
                                 data, rndisSize + etherSize + ipSize +
                                 udpSize + tftpSize + result,
                                 &actual, 0);

        memset(buffer, 0, 450);

        r = libusb_bulk_transfer(dev_handle,
                                 (129 | LIBUSB_ENDPOINT_IN),
                                 buffer, 450, &actual, 0);

        blk_number++;
    }

    fclose(send);

    libusb_close(dev_handle);
    libusb_exit(ctx);

    /* Freeing used structures */
    free(rndis);
    free(ip);
    free(udp);
    free(arpResponse);
    free(breq);
    free(tftp);
    free(eth2);

    /* Freeing data buffers */
    free(data);
    free(buffer);
    free(reader);

    return 0;
}
Example #30
0
int cyusb_release_interface(cyusb_handle *h, int interface)
{
	return ( libusb_release_interface(h, interface) );
}