Exemplo n.º 1
0
FN_INTERNAL int fnusb_claim_camera(freenect_device* dev)
{
	freenect_context *ctx = dev->parent;

	int ret = 0;

#ifndef _WIN32 // todo: necessary?
	// Detach an existing kernel driver for the device
	ret = libusb_kernel_driver_active(dev->usb_cam.dev, 0);
	if (ret == 1)
	{
		ret = libusb_detach_kernel_driver(dev->usb_cam.dev, 0);
		if (ret < 0)
		{
			FN_ERROR("Failed to detach camera kernel driver: %s\n", libusb_error_name(ret));
			libusb_close(dev->usb_cam.dev);
			dev->usb_cam.dev = NULL;
			return ret;
		}
	}
#endif

	ret = libusb_claim_interface(dev->usb_cam.dev, 0);
	if (ret < 0)
	{
		FN_ERROR("Failed to claim camera interface: %s\n", libusb_error_name(ret));
		libusb_close(dev->usb_cam.dev);
		dev->usb_cam.dev = NULL;
		return ret;
	}

	if (dev->usb_cam.PID == PID_K4W_CAMERA)
	{
		ret = libusb_set_interface_alt_setting(dev->usb_cam.dev, 0, 1);
		if (ret != 0)
		{
			FN_ERROR("Failed to set alternate interface #1 for K4W: %s\n", libusb_error_name(ret));
			libusb_close(dev->usb_cam.dev);
			dev->usb_cam.dev = NULL;
			return ret;
		}
	}

	return ret;
}
Exemplo n.º 2
0
// Read the MS WinUSB Feature Descriptors, that are used on Windows 8 for automated driver installation
static void read_ms_winsub_feature_descriptors(libusb_device_handle *handle, uint8_t bRequest, int iface_number)
{
#define MAX_OS_FD_LENGTH 256
	int i, r;
	uint8_t os_desc[MAX_OS_FD_LENGTH];
	uint32_t length;
	void* le_type_punning_IS_fine;
	struct {
		const char* desc;
		uint16_t index;
		uint16_t header_size;
	} os_fd[2] = {
		{"Extended Compat ID", 0x0004, 0x10},
		{"Extended Properties", 0x0005, 0x0A}
	};

	if (iface_number < 0) return;

	for (i=0; i<2; i++) {
		printf("\nReading %s OS Feature Descriptor (wIndex = 0x%04d):\n", os_fd[i].desc, os_fd[i].index);

		// Read the header part
		r = libusb_control_transfer(handle, (uint8_t)(LIBUSB_ENDPOINT_IN|LIBUSB_REQUEST_TYPE_VENDOR|LIBUSB_RECIPIENT_DEVICE),
			bRequest, (uint16_t)(((iface_number)<< 8)|0x00), os_fd[i].index, os_desc, os_fd[i].header_size, 1000);
		if (r < os_fd[i].header_size) {
			perr("   Failed: %s", (r<0)?libusb_error_name((enum libusb_error)r):"header size is too small");
			return;
		}
		le_type_punning_IS_fine = (void*)os_desc;
		length = *((uint32_t*)le_type_punning_IS_fine);
		if (length > MAX_OS_FD_LENGTH) {
			length = MAX_OS_FD_LENGTH;
		}

		// Read the full feature descriptor
		r = libusb_control_transfer(handle, (uint8_t)(LIBUSB_ENDPOINT_IN|LIBUSB_REQUEST_TYPE_VENDOR|LIBUSB_RECIPIENT_DEVICE),
			bRequest, (uint16_t)(((iface_number)<< 8)|0x00), os_fd[i].index, os_desc, (uint16_t)length, 1000);
		if (r < 0) {
			perr("   Failed: %s", libusb_error_name((enum libusb_error)r));
			return;
		} else {
			display_buffer_hex(os_desc, r);
		}
	}
}
Exemplo n.º 3
0
Arquivo: aoa.cpp Projeto: jmgao/mimic
static bool aoa_initialize(libusb_device_handle* handle, AOAMode mode) {
  unsigned char aoa_version_buf[2] = {};
  int rc;

  // https://source.android.com/devices/accessories/aoa.html
  rc = libusb_control_transfer(handle, USB_DIR_IN | USB_TYPE_VENDOR, 51, 0, 0, aoa_version_buf,
                               sizeof(aoa_version_buf), 0);

  if (rc < 0) {
    error("failed to initialize AoA: %s", libusb_error_name(rc));
    return false;
  }

  uint16_t aoa_version;
  memcpy(&aoa_version, aoa_version_buf, sizeof(aoa_version_buf));
  if (aoa_version != 2) {
    error("unsupported AOA protocol version %u", aoa_version);
    return false;
  }

  auto sendString = [handle](int string_id, const std::string& string) {
    int rc = libusb_control_transfer(handle, USB_DIR_OUT | USB_TYPE_VENDOR, 52, 0, string_id,
                                     (unsigned char*)(string.c_str()), string.length() + 1, 0);
    if (rc < 0) {
      error("failed to send vendor string: %s", libusb_error_name(rc));
      return false;
    }
    return true;
  };

  // When not in accessory mode, don't send the manufacturer or model strings to avoid prompting.
  // https://source.android.com/devices/accessories/aoa2.html
  //
  // TODO: Make these strings configurable.
  if (!(sendString(AOA_STRING_DESCRIPTION, DESCRIPTION) && sendString(AOA_STRING_VERSION, VERSION) &&
        sendString(AOA_STRING_URI, URI) && sendString(AOA_STRING_SERIAL, SERIAL))) {
    return false;
  }

  if ((mode & AOAMode::accessory) == AOAMode::accessory) {
    return sendString(AOA_STRING_MANUFACTURER, MANUFACTURER) && sendString(AOA_STRING_MODEL, MODEL);
  }

  return true;
}
Exemplo n.º 4
0
static int lusb_open(void **driver,
                     struct bladerf_devinfo *info_in,
                     struct bladerf_devinfo *info_out)
{
    int status;
    struct bladerf_lusb *lusb = NULL;
    libusb_context *context;

    /* Initialize libusb for device tree walking */
    status = libusb_init(&context);
    if (status) {
        log_error("Could not initialize libusb: %s\n",
                  libusb_error_name(status));
        return error_conv(status);
    }

    /* We can only print this out when log output is enabled, or else we'll
     * get snagged by -Werror=unused-but-set-variable */
#   ifdef LOGGING_ENABLED
    {
        char buf[64];
        get_libusb_version(buf, sizeof(buf));
        log_verbose("Using libusb version: %s\n", buf);
    }
#   endif

    status = find_and_open_device(context, info_in, &lusb, info_out);
    if (status != 0) {
        libusb_exit(context);

        if (status == BLADERF_ERR_NODEV) {
            log_debug("No devices available on the libusb backend.\n");
        } else {
            log_debug("Failed to open bladeRF on libusb backend: %s\n",
                    bladerf_strerror(status));
        }
    } else {
        assert(lusb != NULL);

        /* Cosmin and Marian from Null Team (null.ro) and YateBTS(.com) found
         * that it is possible to recover from "Issue #95: Not enough bandwidth
         * for altsetting" by performing a USB port reset prior to actually
         * trying to use the device.
         */
#       if ENABLE_USB_DEV_RESET_ON_OPEN
        if (bladerf_usb_reset_device_on_open) {
            status = reset_and_reopen(context, &lusb, info_out);
        }
#       endif

        if (status == 0) {
            *driver = (void *) lusb;
        }
    }

    return status;
}
Exemplo n.º 5
0
void cmd_getter(struct libusb_device_handle* devh, int vendor_req,
				char *dataptr, int length) {
	int r;
	r = libusb_control_transfer(devh, CTRL_IN, vendor_req, 0, 0, dataptr,
								length, TIMEOUT);
	if (r < 0) {
		libusb_error_name(r);
	}
}
Exemplo n.º 6
0
unsigned char unixUsbDriver::usbIsoInit(void){
    int error;

    for(int n=0;n<NUM_FUTURE_CTX;n++){
        for (unsigned char k=0;k<NUM_ISO_ENDPOINTS;k++){
            isoCtx[k][n] = libusb_alloc_transfer(ISO_PACKETS_PER_CTX);
            transferCompleted[k][n].number = (k * ISO_PACKETS_PER_CTX) + n;
            transferCompleted[k][n].completed = false;
            libusb_fill_iso_transfer(isoCtx[k][n], handle, pipeID[k], dataBuffer[k][n], ISO_PACKET_SIZE*ISO_PACKETS_PER_CTX, ISO_PACKETS_PER_CTX, isoCallback, (void*)&transferCompleted[k][n], 4000);
            libusb_set_iso_packet_lengths(isoCtx[k][n], ISO_PACKET_SIZE);
        }
    }

    for(int n=0;n<NUM_FUTURE_CTX;n++){
        for (unsigned char k=0;k<NUM_ISO_ENDPOINTS;k++){
            error = libusb_submit_transfer(isoCtx[k][n]);
            if(error){
                qDebug() << "libusb_submit_transfer FAILED";
                qDebug() << "ERROR" << libusb_error_name(error);
            } else {
                if(n == 0){
                    qint64 t0;
                    qint64 t = QDateTime::currentMSecsSinceEpoch();
                    if(k==0){
                        t0 = t;
                    }
                    midBufferOffsets[k] = t0 - t;
                    qDebug() << "isoCtx submitted successfully!";
                    qDebug() << "[n, k] = " << n << k;
                    qDebug() << "t = " << t;
                    qDebug() << "Delay = " << 0;//midBufferOffsets[k];
                }
            }
        }
    }

    isoTimer = new QTimer();
    isoTimer->setTimerType(Qt::PreciseTimer);
    isoTimer->start(ISO_TIMER_PERIOD);
    connect(isoTimer, SIGNAL(timeout()), this, SLOT(isoTimerTick()));

    qDebug() << "Setup successful!";

    isoHandler = new worker();
    workerThread = new QThread();

    isoHandler->ctx = ctx;
    isoHandler->moveToThread(workerThread);
    connect(workerThread, SIGNAL(started()), isoHandler, SLOT(handle()));

    workerThread->start();

    qDebug() << "MAIN THREAD ID" << QThread::currentThreadId();
    //QThread::sleep(1);
    qDebug() << "Iso Stack initialised!";
    return 1;
}
Exemplo n.º 7
0
int atecard_driver_init_inner()
{
	int ret = libusb_init(NULL);
	if (ret < 0)
	{
		printf("libusb_init() failed: %s\r\n", libusb_error_name(ret));
		return -1;
	}

	if (libusb_get_device_list(NULL, &g_usbdevs) < 0)
	{
		printf("libusb_get_device_list() failed: %s\r\n", libusb_error_name(ret));
		libusb_exit(NULL);
		return -1;
	}

	return 0;
}
Exemplo n.º 8
0
static int scpi_usbtmc_remote(struct scpi_usbtmc_libusb *uscpi)
{
	struct sr_usb_dev_inst *usb = uscpi->usb;
	struct libusb_device *dev;
	struct libusb_device_descriptor des;
	int ret;
	uint8_t status;

	if (!(uscpi->usb488_dev_cap & USB488_DEV_CAP_RL1))
		return SR_OK;

	dev = libusb_get_device(usb->devhdl);
	libusb_get_device_descriptor(dev, &des);
	if (check_usbtmc_blacklist(blacklist_remote, des.idVendor, des.idProduct))
		return SR_OK;

	sr_dbg("Locking out local control.");
	ret = libusb_control_transfer(usb->devhdl, LIBUSB_ENDPOINT_IN |
		LIBUSB_REQUEST_TYPE_CLASS | LIBUSB_RECIPIENT_INTERFACE,
		REN_CONTROL, 1, uscpi->interface, &status, 1, TRANSFER_TIMEOUT);
	if (ret < 0 || status != USBTMC_STATUS_SUCCESS) {
		if (ret < 0)
			sr_dbg("Failed to enter REN state: %s.", libusb_error_name(ret));
		else
			sr_dbg("Failed to enter REN state: USBTMC status %d.", status);
		return SR_ERR;
	}

	ret = libusb_control_transfer(usb->devhdl, LIBUSB_ENDPOINT_IN |
		LIBUSB_REQUEST_TYPE_CLASS | LIBUSB_RECIPIENT_INTERFACE,
		LOCAL_LOCKOUT, 0, uscpi->interface, &status, 1,
		TRANSFER_TIMEOUT);
	if (ret < 0 || status != USBTMC_STATUS_SUCCESS) {
		if (ret < 0)
			sr_dbg("Failed to enter local lockout state: %s.",
					libusb_error_name(ret));
		else
			sr_dbg("Failed to enter local lockout state: USBTMC "
					"status %d.", status);
		return SR_ERR;
	}

	return SR_OK;
}
Exemplo n.º 9
0
SR_PRIV int sr_usb_open(libusb_context *usb_ctx, struct sr_usb_dev_inst *usb)
{
	struct libusb_device **devlist;
	struct libusb_device_descriptor des;
	int ret, r, cnt, i, a, b;

	sr_dbg("Trying to open USB device %d.%d.", usb->bus, usb->address);

	if ((cnt = libusb_get_device_list(usb_ctx, &devlist)) < 0) {
		sr_err("Failed to retrieve device list: %s.",
		       libusb_error_name(cnt));
		return SR_ERR;
	}

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

		b = libusb_get_bus_number(devlist[i]);
		a = libusb_get_device_address(devlist[i]);
		if (b != usb->bus || a != usb->address)
			continue;

		if ((r = libusb_open(devlist[i], &usb->devhdl)) < 0) {
			sr_err("Failed to open device: %s.",
			       libusb_error_name(r));
			break;
		}

		sr_dbg("Opened USB device (VID:PID = %04x:%04x, bus.address = "
		       "%d.%d).", des.idVendor, des.idProduct, b, a);

		ret = SR_OK;
		break;
	}

	libusb_free_device_list(devlist, 1);

	return ret;
}
Exemplo n.º 10
0
SR_PRIV int ezusb_upload_firmware(libusb_device *dev, int configuration,
				  const char *filename)
{
	struct libusb_device_handle *hdl;
	int ret;

	sr_info("uploading firmware to device on %d.%d",
		libusb_get_bus_number(dev), libusb_get_device_address(dev));

	if ((ret = libusb_open(dev, &hdl)) < 0) {
		sr_err("failed to open device: %s.", libusb_error_name(ret));
		return SR_ERR;
	}

/* Neither Windows/MinGW nor Darwin/Mac support these libusb-1.0 calls. */
#if !defined(_WIN32) && !defined(__APPLE__)
	if (libusb_kernel_driver_active(hdl, 0)) {
		if ((ret = libusb_detach_kernel_driver(hdl, 0)) < 0) {
			sr_err("failed to detach kernel driver: %s",
					libusb_error_name(ret));
			return SR_ERR;
		}
	}
#endif

	if ((ret = libusb_set_configuration(hdl, configuration)) < 0) {
		sr_err("Unable to set configuration: %s",
				libusb_error_name(ret));
		return SR_ERR;
	}

	if ((ezusb_reset(hdl, 1)) < 0)
		return SR_ERR;

	if (ezusb_install_firmware(hdl, filename) < 0)
		return SR_ERR;

	if ((ezusb_reset(hdl, 0)) < 0)
		return SR_ERR;

	libusb_close(hdl);

	return SR_OK;
}
Exemplo n.º 11
0
/**
 * \brief Get configuration by value.
 *
 * \param value	configuration value to search for.
 */
ConfigurationPtr	Device::configValue(uint8_t value) throw(USBError) {
	struct libusb_config_descriptor	*config;
	int	rc = libusb_get_config_descriptor_by_value(dev, value, &config);
	if (rc != LIBUSB_SUCCESS) {
		throw USBError(libusb_error_name(rc));
	}
	Configuration	*result = new Configuration(*this, config);
	libusb_free_config_descriptor(config);
	return ConfigurationPtr(result);
}
Exemplo n.º 12
0
static void write_to_usb(int resp_type,int resp_result)
{
	int err;
	usb_out_buf[0]=resp_type;
	usb_out_buf[1]=resp_result;
	err=libusb_interrupt_transfer(handle,0x02,usb_out_buf,USB_BUF_SIZE,&transferred,0);
	if(err)
		puts(libusb_error_name(err));
	
}
Exemplo n.º 13
0
int cmd_no_data(struct libusb_device_handle* devh, int vendor_req) {
	int r;
	r = libusb_control_transfer(devh, CTRL_OUT, vendor_req, 0, 0,
			NULL, 0, TIMEOUT);
	if (r < 0) {
		libusb_error_name(r);
		return r;
	}
	return 0;
}
Exemplo n.º 14
0
/**********************************************************
 * Function set_relay_conrad_4chan()
 * 
 * Description: Set new relay state
 * 
 * Parameters: portname (in)     - communication port
 *             relay (in)        - relay number
 *             relay_state (in)  - current relay state
 * 
 * Return:   o - success
 *          -1 - fail
 *********************************************************/
int set_relay_conrad_4chan(char* portname, uint8 relay, relay_state_t relay_state)
{
   struct libusb_device_handle *dev = NULL; 
   int r;  
   uint16 gpio=0;
   
   if (relay<FIRST_RELAY || relay>(FIRST_RELAY+CONRAD_4CHANNEL_USB_NUM_RELAYS-1))
   {  
      fprintf(stderr, "ERROR: Relay number out of range\n");
      return -1;      
   }
   
   libusb_init(NULL);
   
   /* Open USB device */
   //r = libusb_open(device, &dev);
   //if (r < 0)
   dev = libusb_open_device_with_vid_pid(NULL, VENDOR_ID, DEVICE_ID);
   if (dev == NULL)
   {
      fprintf(stderr, "unable to open CP2104 device\n");
      libusb_exit(NULL);
      return -2;
   }
   
   /* Set the relay state bit */
   relay = relay-1;
   if (relay_state == OFF) gpio = 0x0001<<(relay+RSTATES_BITOFFSET);
   
   /* Set the relay bit mask */
   gpio = gpio | (0x0001<<relay);

   /* Set relay state on the card */ 
   r = libusb_control_transfer (
                dev,                    // libusb_device_handle *  dev_handle,
                REQTYPE_HOST_TO_DEVICE, // uint8_t         bmRequestType,
                CP210X_VENDOR_SPECIFIC, // uint8_t         bRequest,
                CP210X_WRITE_LATCH,     // uint16_t        wValue,
                gpio,                   // uint16_t        wIndex,
                NULL,                   // unsigned char * data,
                0,                      // uint16_t        wLength,
                0);                     // unsigned int    timeout
   
   if (r < 0) 
   {
      fprintf(stderr, "libusb_control_transfer error (%s)\n", libusb_error_name(r));
      libusb_close(dev);
      libusb_exit(NULL);
      return -3;
   }

   libusb_close(dev);
   libusb_exit(NULL);
   return 0;
}
static int send_mass_storage_command(libusb_device_handle *handle, uint8_t endpoint, uint8_t lun,
	uint8_t *cdb, uint8_t direction, int data_length, uint32_t *ret_tag)
{
	static uint32_t tag = 1;
	uint8_t cdb_len;
	int i, r, size;
	struct command_block_wrapper cbw;

	if (cdb == NULL) {
		return -1;
	}

	if (endpoint & LIBUSB_ENDPOINT_IN) {
		perr("send_mass_storage_command: cannot send command on IN endpoint\n");
		return -1;
	}

	cdb_len = cdb_length[cdb[0]];
	if ((cdb_len == 0) || (cdb_len > sizeof(cbw.CBWCB))) {
		perr("send_mass_storage_command: don't know how to handle this command (%02X, length %d)\n",
			cdb[0], cdb_len);
		return -1;
	}

	memset(&cbw, 0, sizeof(cbw));
	cbw.dCBWSignature[0] = 'U';
	cbw.dCBWSignature[1] = 'S';
	cbw.dCBWSignature[2] = 'B';
	cbw.dCBWSignature[3] = 'C';
	*ret_tag = tag;
	cbw.dCBWTag = tag++;
	cbw.dCBWDataTransferLength = data_length;
	cbw.bmCBWFlags = direction;
	cbw.bCBWLUN = lun;
	// Subclass is 1 or 6 => cdb_len
	cbw.bCBWCBLength = cdb_len;
	memcpy(cbw.CBWCB, cdb, cdb_len);

	i = 0;
	do {
		// The transfer length must always be exactly 31 bytes.
		r = libusb_bulk_transfer(handle, endpoint, (unsigned char*)&cbw, 31, &size, 1000);
		if (r == LIBUSB_ERROR_PIPE) {
			libusb_clear_halt(handle, endpoint);
		}
		i++;
	} while ((r == LIBUSB_ERROR_PIPE) && (i<RETRY_MAX));
	if (r != LIBUSB_SUCCESS) {
		perr("   send_mass_storage_command: %s\n", libusb_error_name(r));
		return -1;
	}

	printf("   sent %d CDB bytes\n", cdb_len);
	return 0;
}
Exemplo n.º 16
0
/**
 * Queries a device instances' connection identifier.
 *
 * @param sdi Device instance to use. Must not be NULL.
 *
 * @return A copy of the connection id string or NULL. The caller is responsible
 *         for g_free()ing the string when it is no longer needed.
 */
SR_API const char *sr_dev_inst_connid_get(const struct sr_dev_inst *sdi)
{
#ifdef HAVE_LIBUSB_1_0
	struct drv_context *drvc;
	int cnt, i, a, b;
	char connection_id[64];
	struct sr_usb_dev_inst *usb;
	struct libusb_device **devlist;
#endif

	if (!sdi)
		return NULL;

#ifdef HAVE_LIBSERIALPORT
	struct sr_serial_dev_inst *serial;

	if ((!sdi->connection_id) && (sdi->inst_type == SR_INST_SERIAL)) {
		/* connection_id isn't populated, let's do that here. */

		serial = sdi->conn;
		((struct sr_dev_inst *)sdi)->connection_id = g_strdup(serial->port);
	}
#endif

#ifdef HAVE_LIBUSB_1_0
	if ((!sdi->connection_id) && (sdi->inst_type == SR_INST_USB)) {
		/* connection_id isn't populated, let's do that here. */

		drvc = sdi->driver->context;
		usb = sdi->conn;

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

		for (i = 0; i < cnt; i++) {
			/* Find the USB device by the logical address we know. */
			b = libusb_get_bus_number(devlist[i]);
			a = libusb_get_device_address(devlist[i]);
			if (b != usb->bus || a != usb->address)
				continue;

			usb_get_port_path(devlist[i], connection_id, sizeof(connection_id));
			((struct sr_dev_inst *)sdi)->connection_id = g_strdup(connection_id);
			break;
		}

		libusb_free_device_list(devlist, 1);
	}
#endif

	return sdi->connection_id;
}
	void GlobalTrainer::init() {
		int ecode = 0;
		usb_handle = libusb_open_device_with_vid_pid (usb_ctxt,
		                                              GLOBAL_TRAINER_VENDOR_ID,
		                                              GLOBAL_TRAINER_PRODUCT_ID);

		if (!usb_handle) {
			std::cerr << "Unable to open USB device" << std::endl;
			exit(EXIT_FAILURE);
		} 
		
		ecode = libusb_kernel_driver_active(usb_handle, 1);
		if (ecode == 1) {
			ecode = libusb_detach_kernel_driver(usb_handle, 1);
			if (ecode == 0)
				detached_kernel = true;
			else {
				std::cerr << "Libusb error detaching kernel driver: "
				          << libusb_error_name(ecode) << std::endl;
				exit(EXIT_FAILURE);
			}
		} else {
			switch (ecode) {
			case 0:
			case LIBUSB_ERROR_NOT_SUPPORTED:
				break;
			default:
				std::cerr << "Libusb error: "
				          << libusb_error_name(ecode) << std::endl;
				exit(EXIT_FAILURE);
			}
		}
		
		ecode = libusb_claim_interface(usb_handle, 1);
		if (ecode) {
			std::cerr << "Unable to claim USB interface: "
			          << libusb_error_name(ecode) << std::endl;
			exit(EXIT_FAILURE);
		} 
		interface_claimed = true;
		std::cout << "Claimed interface!" << std::endl;
	}
Exemplo n.º 18
0
void FX3Stream::init(unsigned short vid, unsigned short pid) {
    this->vid = vid;
    this->pid = pid;
    error = libusb_init(0);
    if( error < 0 ) {
        cerr << "Error initialising libusb: " << libusb_error_name(error) << endl;
        return;
    }
    if( FX3_DEBUG ) {
        libusb_set_debug(0,LIBUSB_LOG_LEVEL_WARNING);
    }
    devhandle = libusb_open_device_with_vid_pid(0, vid, pid);
    if( !devhandle ) {
        cerr << "Error opening the device" << endl;
        error = 1;
        return;
    }
    error = libusb_reset_device( devhandle );
    if( error < 0 ) {
        cerr << "Error resetting the device: " << libusb_error_name(error) << endl;
        return;
    }
    error = libusb_kernel_driver_active( devhandle, 1 );
    if( error < 0 ) {
        cerr << "Error checking for kernel driver: " << libusb_error_name(error) << endl;
        return;
    }
    else if( error == 1 ) {
        cerr << "Error: Kernel driver active." << endl;
        return;
    }
    error = libusb_set_configuration( devhandle, 1 );
    if( error < 0 ) {
        cerr << "Error setting the configuration: " << libusb_error_name(error) << endl;
        return;
    }
    error =  libusb_claim_interface( devhandle, 0 );
    if( error < 0 ) {
        cerr << "Error claiming the interface: " << libusb_error_name(error) << endl;
        return;
    }
    interfaceClaimed = true;
    inPktSize = libusb_get_max_packet_size( libusb_get_device(devhandle), FX3_IN_EP );
    if( inPktSize < 0 ) {
        cerr << "Error getting IN EP packet size: " << libusb_error_name(error) << endl;
        return;
    }
    outPktSize = libusb_get_max_packet_size( libusb_get_device(devhandle), FX3_OUT_EP );
    if( outPktSize < 0 ) {
        cerr << "Error getting OUT EP packet size: " << libusb_error_name(error) << endl;
        return;
    }
    if( FX3_DEBUG ) {
        cerr << "inPktSize: " << inPktSize << ", outPktSize: " << outPktSize << endl;
    }
    allocTransfers();
}
Exemplo n.º 19
0
static int gl_write_data(libusb_device_handle *devh, unsigned int val)
{
	unsigned char packet[8] = { val & 0xFF };
	int ret;

	ret = libusb_control_transfer(devh, CTRL_OUT, 0xc, REQ_WRITEDATA,
				      0, packet, 1, TIMEOUT);
	if (ret != 1)
		sr_err("%s: %s.", __func__, libusb_error_name(ret));
	return ret;
}
Exemplo n.º 20
0
static void resubmit_transfer(struct libusb_transfer *transfer)
{
	int ret;

	if ((ret = libusb_submit_transfer(transfer)) == LIBUSB_SUCCESS)
		return;

	sr_err("%s: %s", __func__, libusb_error_name(ret));
	free_transfer(transfer);

}
/**
 * \brief Submit a bulk transfer to the device.
 *
 * This method allocates and fills the bulk transfer, and submits it to
 * the libusb_submit_transfer function. It then starts to handle events,
 * and only returns when the complete flag is set.
 * \param dev_handle    the libusb device handle
 */
void	BulkTransfer::submit(libusb_device_handle *dev_handle) throw(USBError) {
	// allocate the transfer structure
	transfer = libusb_alloc_transfer(0);

	// fill the transfer
	libusb_fill_bulk_transfer(transfer, dev_handle,
		endpoint->bEndpointAddress(), data,
		length, bulktransfer_callback, this, timeout);

	// submit the transfer
	int	rc = libusb_submit_transfer(transfer);
	if (rc != LIBUSB_SUCCESS) {
		throw USBError(libusb_error_name(rc));
	}

	// handle events until the complete flag is set
	libusb_context  *ctx = getContext();
	while (!complete) {
		libusb_handle_events(ctx);
	}

	// at this point, the transfer has somehow completed, but we
	// don't know yet what happened.
	const char	*cause = NULL;
	switch (transfer->status) {
	case LIBUSB_TRANSFER_ERROR:
		cause = "transfer error";
		break;
	case LIBUSB_TRANSFER_TIMED_OUT:
		cause = "transfer timed out";
		break;
	case LIBUSB_TRANSFER_CANCELLED:
		cause = "transfer cancelled";
		break;
	case LIBUSB_TRANSFER_STALL:
		cause = "transfer stall";
		break;
	case LIBUSB_TRANSFER_NO_DEVICE:
		cause = "transfer no device";
		break;
	case LIBUSB_TRANSFER_OVERFLOW:
		cause = "transfer overflow";
		break;
	case LIBUSB_TRANSFER_COMPLETED:
		break;
	}
	if (NULL != cause) {
		debug(LOG_ERR, DEBUG_LOG, 0, "transfer failed: %s", cause);
		throw USBError(cause);
	} else {
		debug(LOG_DEBUG, DEBUG_LOG, 0, "transfer complete, %d bytes",
			transfer->actual_length);
	}
}
Exemplo n.º 22
0
static int gl_read_data(libusb_device_handle *devh)
{
	unsigned char packet[8] = { 0 };
	int ret;

	ret = libusb_control_transfer(devh, CTRL_IN, 0xc, REQ_READDATA,
				      0, packet, 1, TIMEOUT);
	if (ret != 1)
		sr_err("%s: %s, val=%hhx.", __func__,
		       libusb_error_name(ret), packet[0]);
	return (ret == 1) ? packet[0] : ret;
}
Exemplo n.º 23
0
SR_PRIV int gl_read_bulk(libusb_device_handle *devh, void *buffer,
			 unsigned int size)
{
	unsigned char packet[8] =
	    { 0, 0, 0, 0, size & 0xff, (size & 0xff00) >> 8,
	      (size & 0xff0000) >> 16, (size & 0xff000000) >> 24 };
	int ret, transferred = 0;

	ret = libusb_control_transfer(devh, CTRL_OUT, 0x4, REQ_READBULK,
				      0, packet, 8, TIMEOUT);
	if (ret != 8)
		sr_err("%s: libusb_control_transfer: %s.", __func__,
		       libusb_error_name(ret));

	ret = libusb_bulk_transfer(devh, EP1_BULK_IN, buffer, size,
				   &transferred, TIMEOUT);
	if (ret < 0)
		sr_err("%s: libusb_bulk_transfer: %s.", __func__,
		       libusb_error_name(ret));
	return transferred;
}
Exemplo n.º 24
0
void Usb::Initialize() throw (UsbException)
{
    if (!_isInitialized)
    {
        int returnedValue = libusb_init(&_context); // inicjalizacja biblioteki dla naszej sesji

        if (returnedValue < 0)
            throw new UsbException(libusb_error_name(returnedValue));

        _isInitialized = true;
    }
}
Exemplo n.º 25
0
DeviceDescriptorPtr	Device::descriptor() throw(USBError) {
	// get the device descriptor
	libusb_device_descriptor	d;
	int	rc = libusb_get_device_descriptor(dev, &d);
	if (rc != LIBUSB_SUCCESS) {
		throw USBError(libusb_error_name(rc));
	}

	// create a DeviceDescriptor object
	DeviceDescriptor	*devdesc = new DeviceDescriptor(*this, &d);
	return DeviceDescriptorPtr(devdesc);
}
Exemplo n.º 26
0
SR_PRIV int command_start_acquisition(libusb_device_handle *devhdl,
				      uint64_t samplerate, gboolean samplewide)
{
	struct cmd_start_acquisition cmd;
	int delay = 0, ret;

	/* Compute the sample rate. */
	if (samplewide && samplerate > MAX_16BIT_SAMPLE_RATE) {
		sr_err("Unable to sample at %" PRIu64 "Hz "
		       "when collecting 16-bit samples.", samplerate);
		return SR_ERR;
	}

	if ((SR_MHZ(48) % samplerate) == 0) {
		cmd.flags = CMD_START_FLAGS_CLK_48MHZ;
		delay = SR_MHZ(48) / samplerate - 1;
		if (delay > MAX_SAMPLE_DELAY)
			delay = 0;
	}

	if (delay == 0 && (SR_MHZ(30) % samplerate) == 0) {
		cmd.flags = CMD_START_FLAGS_CLK_30MHZ;
		delay = SR_MHZ(30) / samplerate - 1;
	}

	sr_info("GPIF delay = %d, clocksource = %sMHz.", delay,
		(cmd.flags & CMD_START_FLAGS_CLK_48MHZ) ? "48" : "30");

	if (delay <= 0 || delay > MAX_SAMPLE_DELAY) {
		sr_err("Unable to sample at %" PRIu64 "Hz.", samplerate);
		return SR_ERR;
	}

	cmd.sample_delay_h = (delay >> 8) & 0xff;
	cmd.sample_delay_l = delay & 0xff;

	/* Select the sampling width. */
	cmd.flags |= samplewide ? CMD_START_FLAGS_SAMPLE_16BIT :
		CMD_START_FLAGS_SAMPLE_8BIT;

	/* Send the control message. */
	ret = libusb_control_transfer(devhdl, LIBUSB_REQUEST_TYPE_VENDOR |
			LIBUSB_ENDPOINT_OUT, CMD_START, 0x0000, 0x0000,
			(unsigned char *)&cmd, sizeof(cmd), 100);
	if (ret < 0) {
		sr_err("Unable to send start command: %s.",
		       libusb_error_name(ret));
		return SR_ERR;
	}

	return SR_OK;
}
Exemplo n.º 27
0
static int find_device(struct cli_state *s,
                       libusb_context * context,
                       uint8_t bus, uint8_t addr,
                       libusb_device_handle **handle,
                       bool just_print)
{
    int status, i;
    libusb_device *dev, **devs;
    libusb_device *found_dev = NULL;
    ssize_t status_sz;
    size_t num_found = 0;

    status_sz = libusb_get_device_list(context, &devs);
    if (status_sz < 0) {
        cli_err(s, "Error", "libusb_get_device_list() failed: %d %s\n",
                status_sz, libusb_error_name((int)status_sz));

        return CMD_RET_UNKNOWN;
    }

    for (i = 0; (dev = devs[i]) != NULL && found_dev == NULL; i++) {

        if (just_print && is_bootloader_device(s, dev)) {
            if (num_found++ == 0) {
                printf("\n");
            }

            printf("  Bootloader @ bus=%d, addr=%d\n",
                   libusb_get_bus_number(dev), libusb_get_device_address(dev));

        } else if (is_bootloader_device(s, dev) &&
                   bus == libusb_get_bus_number(dev) &&
                   addr == libusb_get_device_address(dev)) {
            found_dev = dev;
        }
    }

    if (found_dev == NULL || (just_print && num_found == 0)) {
        s->last_lib_error =  BLADERF_ERR_NODEV;
        return CMD_RET_LIBBLADERF;
    } else if (!just_print) {
        status = libusb_open(found_dev, handle);

        if (status != 0) {
            s->last_lib_error = BLADERF_ERR_IO;
            return CMD_RET_LIBBLADERF;
        }
    }

    libusb_free_device_list(devs, 1);
    return 0;
}
Exemplo n.º 28
0
/* Returns true if the string descriptor indexed by str_index in device matches string */
static bool string_descriptor_equal(libusb_device_handle *device, uint8_t str_index,
	const char *string)
{
	int retval;
	char desc_string[256]; /* Max size of string descriptor */
	retval = libusb_get_string_descriptor_ascii(device, str_index, (unsigned char *)desc_string,
			sizeof(desc_string));
	if (retval < 0) {
		LOG_ERROR("libusb_get_string_descriptor_ascii() failed with %s", libusb_error_name(retval));
		return false;
	}
	return strncmp(string, desc_string, sizeof(desc_string)) == 0;
}
Exemplo n.º 29
0
void mpsse_purge(struct mpsse_ctx *ctx)
{
	int err;
	LOG_DEBUG("-");
	ctx->write_count = 0;
	ctx->read_count = 0;
	ctx->retval = ERROR_OK;
	bit_copy_discard(&ctx->read_queue);
	err = libusb_control_transfer(ctx->usb_dev, FTDI_DEVICE_OUT_REQTYPE, SIO_RESET_REQUEST,
			SIO_RESET_PURGE_RX, ctx->index, NULL, 0, ctx->usb_write_timeout);
	if (err < 0) {
		LOG_ERROR("unable to purge ftdi rx buffers: %s", libusb_error_name(err));
		return;
	}

	err = libusb_control_transfer(ctx->usb_dev, FTDI_DEVICE_OUT_REQTYPE, SIO_RESET_REQUEST,
			SIO_RESET_PURGE_TX, ctx->index, NULL, 0, ctx->usb_write_timeout);
	if (err < 0) {
		LOG_ERROR("unable to purge ftdi tx buffers: %s", libusb_error_name(err));
		return;
	}
}
Exemplo n.º 30
0
static void transfer_cb(struct libusb_transfer *xfr) {
    int rc = 0;
    int len = 0;
    unsigned int i;

    /* All packets are 192 bytes. */
    uint8_t* recv = malloc(PACKET_SIZE * xfr->num_iso_packets);
    uint8_t* recv_next = recv;

    for (i = 0; i < xfr->num_iso_packets; i++) {
        struct libusb_iso_packet_descriptor *pack = &xfr->iso_packet_desc[i];
        if (pack->status != LIBUSB_TRANSFER_COMPLETED) {
            LOGE("Error (status %d: %s)\n", pack->status,
                    libusb_error_name(pack->status));
            continue;
        }
        const uint8_t *data = libusb_get_iso_packet_buffer_simple(xfr, i);
        /* PACKET_SIZE == 192 == pack->length */
        memcpy(recv_next, data, PACKET_SIZE);
        recv_next += PACKET_SIZE;
        len += pack->length;
    }
    /* At this point, recv points to a buffer containing len bytes of audio. */
#if !defined(ANDROID)
    /* Lock around this write? */
    if ((rc = write(outfd, recv, len)) < 0) {
        perror("Unable to write to descriptor");
    }
#endif
    free(recv);
    /* Sanity check. If this is true, we've overflowed the recv buffer. */
    if (len > PACKET_SIZE * xfr->num_iso_packets) {
        LOGE("Error: incoming transfer had more data than we thought.\n");
        return;
    }
	if ((rc = libusb_submit_transfer(xfr)) < 0) {
		LOGE("libusb_submit_transfer: %s.\n", libusb_error_name(rc));
	}
}