Exemple #1
0
/* Initialize CM19A so it recognizes signals from the CR12A or CR14A remote */
int LibUSButils::ahpInit(usb_dev_handle* handle)
{
    int ret;

    // Send this out on the control pipe
    char write_ok[] = { 0x20, 0x34, (char)0xcb, 0x58, (char)0xa7 };
    char init1[]    = { (char)0x80, 0x01, 0x00, 0x20, 0x14 };
    char init2[]    = { (char)0x80, 0x01, 0x00, 0x00, 0x14, 0x24, 0x20, 0x20 };

    ret = usb_interrupt_write(handle, EP2, write_ok, 5, 5000);
    Logger::Log(DEBUG, "Write_Ok : Wrote (%d) bytes", ret);

    sleep(1);

    ret = usb_interrupt_write(handle, EP2, init1, 5, 5000);
    Logger::Log(DEBUG, "Init1    : Wrote (%d) bytes", ret);

    sleep(1);

    ret = usb_interrupt_write(handle, EP2, init2, 8, 5000);
    Logger::Log(DEBUG, "Init2    : Wrote (%d) bytes", ret);

    sleep(1);

    return ret;
}
Exemple #2
0
void
write_usb_device(struct usb_device* dev, int interface, int endpoint)
{
  struct usb_dev_handle* handle = usb_open(dev);
  if (!handle)
    {
      std::cout << "Error opening usb device" << std::endl;
    }
  else
    {
      if (usb_claim_interface(handle, interface) != 0)
        {
          std::cout << "Error claiming the interface: " << usb_strerror() << std::endl;
          if (usb_detach_kernel_driver_np(handle, interface) < 0)
            {
              std::cout << "Failure to kick kernel driver: " << usb_strerror() << std::endl;
              exit(EXIT_FAILURE);              
            }

          if (usb_claim_interface(handle, interface) != 0)
            {
              std::cout << "Error claiming the interface: " << usb_strerror() << std::endl;
              exit(EXIT_FAILURE);
            }
        }

      bool quit = false;

      while(!quit)
        {
          uint8_t data[32];
          
          if (1)
            {
              int ret = fread(data, sizeof(char), sizeof(data), stdin);

              std::cout << ret << std::endl;
              usb_interrupt_write(handle, endpoint, (char*)data, ret, 0);

            }
          else
            {
              int ret = sizeof(data);
              for(int i = 0; i < ret ; ++i)
                {
                  data[i] = int(127 * sin(float(i) / ret * M_PI*2)) + 127;
                  std::cout << ret << std::endl;
                }
              std::cout << ret << std::endl;
              usb_interrupt_write(handle, endpoint, (char*)data, ret, 0);

            }
        }
    }   
}
void
Xbox360UsbThread::set_rumble(uint8_t big, uint8_t small)
{
  // Should be ok without mutex lock
  char rumblecmd[] = { 0x00, 0x08, 0x00, big, small, 0x00, 0x00, 0x00 };
  usb_interrupt_write(handle, 2, rumblecmd, 8, 0);
}
Exemple #4
0
int LibUsb::write(char *buf, int bytes, int timeout)
{

    // check it isn't closed
    if (!device) return -1;

    int rc;
    if (OperatingSystem == WINDOWS) {
        rc = usb_interrupt_write(device, writeEndpoint, buf, bytes, 1000);
    } else {
        // we use a non-interrupted write on Linux/Mac since the interrupt
        // write block size is incorrectly implemented in the version of
        // libusb we build with. It is no less efficient.
        rc = usb_bulk_write(device, writeEndpoint, buf, bytes, timeout);
    }

    if (rc < 0)
    {
        // Report timeouts - previously we ignored -110 errors. This masked a serious
        // problem with write on Linux/Mac, the USB stick needed a reset to avoid
        // these error messages, so we DO report them now
        qDebug()<<"usb_interrupt_write Error writing ["<<rc<<"]: "<< usb_strerror();
    }

    return rc;
}
Exemple #5
0
void sendBuffer(char* buffer, size_t size) {
	OpenIBootCmd cmd;

	pthread_mutex_lock(&sendLock);

	if(!ready)
		pthread_cond_wait(&readyCond, &sendLock);

	amtToWrite = size;
	dataToWrite = buffer;

	cmd.command = OPENIBOOTCMD_SENDCOMMAND;
	cmd.dataLen = size;

	if(usb_interrupt_write(device, 4, (char*) (&cmd), sizeof(OpenIBootCmd), 1000) < 0)
	{
		oibc_log("failed to send command.\n");
		pthread_mutex_unlock(&sendLock);
		return;
	}

	pthread_cond_wait(&sendCond, &sendLock);
	
	pthread_mutex_unlock(&sendLock);
}
Exemple #6
0
/*
 void test_control_transfer(usb_dev_handle *dev)
 {
//   usb_set_altinterface(dev, 0);
   usb_release_interface(dev, 0);
 }
*/
 void test_interrupt_transfer(usb_dev_handle *dev)
 {
   int r,i;
   char answer[reqIntLen];
   char question[reqIntLen];
   for (i=0;i<reqIntLen; i++) question[i]=i;
   r = usb_interrupt_write(dev, endpoint_Int_out, question, reqIntLen, timeout);
   if( r < 0 )
   {
	  perror("USB interrupt write"); bad("USB write failed"); 
   }
   r = usb_interrupt_read(dev, endpoint_Int_in, answer, reqIntLen, timeout);
   if( r != reqIntLen )
   {
	  perror("USB interrupt read"); bad("USB read failed"); 
   }
//   for (i=0;i<reqIntLen; i++) printf("%i, %i, \n",question[i],answer[i]);
	for(i = 0;i < reqIntLen; i++) {
		if(i%8 == 0)
			printf("\n");
		printf("%02x, %02x; ",question[i],answer[i]);
	}
	printf("\n");

//   usb_set_altinterface(dev, 0);
   usb_release_interface(dev, 0);
 }
Exemple #7
0
void sendBuffer(char* buffer, size_t size) {
	OpenIBootCmd cmd;

	cmd.command = OPENIBOOTCMD_SENDCOMMAND;
	cmd.dataLen = size;

	usb_interrupt_write(device, 4, (char*) (&cmd), sizeof(OpenIBootCmd), 1000);

	while(1) {
		usb_interrupt_read(device, 3, (char*) (&cmd), sizeof(OpenIBootCmd), 1000);
		if(cmd.command == OPENIBOOTCMD_SENDCOMMAND_GOAHEAD)
			break;
	}

	int toSend = 0;
	while(size > 0) {
		if(size <= MAX_TO_SEND)
			toSend = size;
		else
			toSend = MAX_TO_SEND;

		usb_bulk_write(device, 2, buffer, toSend, 1000);
		buffer += toSend;
		size -= toSend;
	}
}
Exemple #8
0
static int pickit2_shutdown(void *data)
{
	/* Set all pins to float and turn voltages off */
	uint8_t command[CMD_LENGTH] = {
		CMD_EXEC_SCRIPT,
		8,
		SCR_SET_PINS,
		3, /* Bit-0=1(PDC In), Bit-1=1(PGD In), Bit-2=0(PDC LL), Bit-3=0(PGD LL) */
		SCR_SET_AUX,
		1, /* Bit-0=1(Aux In), Bit-1=0(Aux LL) */
		SCR_MCLR_GND_OFF,
		SCR_VPP_OFF,
		SCR_VDD_OFF,
		SCR_BUSY_LED_OFF,
		CMD_END_OF_BUFFER
	};

	int ret = usb_interrupt_write(pickit2_handle, ENDPOINT_OUT, (char *)command, CMD_LENGTH, DFLT_TIMEOUT);

	if (ret != CMD_LENGTH) {
		msg_perr("Command Shutdown failed (%s)!\n", usb_strerror());
		ret = 1;
	}
	if (usb_release_interface(pickit2_handle, 0) != 0) {
		msg_perr("Could not release USB interface!\n");
		ret = 1;
	}
	if (usb_close(pickit2_handle) != 0) {
		msg_perr("Could not close USB device!\n");
		ret = 1;
	}
	return ret;
}
Exemple #9
0
uint8_t *hw_usbeesx_get_samples(struct flosslogic_context *ctx,
		uint64_t numsamples, uint64_t samplerate, int timeout)
{
	int ret, bufsize;
	uint64_t i;
	char cmdbuf[2];
	uint8_t *sample_buffer;

	cmdbuf[0] = 0x01;
	/* TODO: Error handling. */
	ret = usb_interrupt_write(ctx->devhandle, 0x81, cmdbuf, 1, timeout);

	cmdbuf[0] = 0x55;
	/* TODO: Error handling. */
	ret = usb_interrupt_write(ctx->devhandle, 0x81, cmdbuf, 1, timeout);

	/* TODO */

	cmdbuf[0] = 0x01;
	cmdbuf[1] = samplerate_config_value(samplerate); /* TODO: Error h. */
	if (cmdbuf[1] == (char)0xff) {
		/* Handle hw_usbeesx_shutdown() errors. */
		hw_usbeesx_shutdown(ctx);
		/* TODO: Set error code. */
		return NULL;
	}
	/* TODO: Error handling. */
	ret = usb_interrupt_write(ctx->devhandle, 0x01, cmdbuf, 2, timeout);

	bufsize = numsamples * (ctx->la->numchannels / 8);
	sample_buffer = malloc(bufsize);
	/* TODO: Better error handling? */
	if (sample_buffer == NULL)
		return NULL;

	for (i = 0; (int)i < bufsize; i += 512) {
		/* 0x86 == EP 6, IN direction */
		usb_block_read(ctx->devhandle, 0x86,
			       (char *)(sample_buffer + i), 512, timeout);
	}

	/* TODO: Shutdown command? */

	return sample_buffer;
}
Exemple #10
0
/*
 * Class:     ch_ntb_usb_LibusbJava
 * Method:    usb_interrupt_write
 * Signature: (JI[BII)I
 */
JNIEXPORT jint JNICALL Java_ch_ntb_usb_LibusbJava_usb_1interrupt_1write
  (JNIEnv *env, jclass obj, jlong dev_handle, jint ep, jbyteArray jbytes, jint size, jint timeout)
  {
  	clearLibusbJavaError();
  	jbyte *bytes = (*env)->GetByteArrayElements(env, jbytes, NULL);
  	int num_bytes = usb_interrupt_write( (usb_dev_handle *) dev_handle, ep, (char *) bytes, size, timeout);
 	(*env)->ReleaseByteArrayElements(env, jbytes, bytes, 0);
 	return num_bytes;
  }
Exemple #11
0
int INDI::USBDevice::WriteInterrupt(char *buf,int c,int timeout)
{
	int rc;

	//printf("Writing %02x to endpoint %d\n",buf[0],OutputEndpoint);
	rc=usb_interrupt_write(usb_handle,OutputEndpoint,buf,c,timeout);
	return rc;

}
void vibrate(int leftTriggerVal, int rightTriggerVal, int leftVal, int rightVal, int dwUserIndex)
{
	// Motors are 0 - 255
	unsigned char data[] = { 9, 0, 0, 9, 0, 15, leftTriggerVal, rightTriggerVal, leftVal, rightVal, 255, 0, 0 };
	if (usb_interrupt_write(controllerHandler[dwUserIndex]->handle, endpointOut, (char*)data, sizeof(data), timeout) < 0)
	{
		std::cout << "usb_interrupt_write (" << usb_strerror() << ")." << std::endl;
	}
}
static int usbdev_send(union filedescriptor *fd, const unsigned char *bp, size_t mlen)
{
  usb_dev_handle *udev = (usb_dev_handle *)fd->usb.handle;
  int rv;
  int i = mlen;
  const unsigned char * p = bp;
  int tx_size;

  if (udev == NULL)
    return -1;

  /*
   * Split the frame into multiple packets.  It's important to make
   * sure we finish with a short packet, or else the device won't know
   * the frame is finished.  For example, if we need to send 64 bytes,
   * we must send a packet of length 64 followed by a packet of length
   * 0.
   */
  do {
    tx_size = (mlen < fd->usb.max_xfer)? mlen: fd->usb.max_xfer;
    if (fd->usb.use_interrupt_xfer)
      rv = usb_interrupt_write(udev, fd->usb.wep, (char *)bp, tx_size, 10000);
    else
      rv = usb_bulk_write(udev, fd->usb.wep, (char *)bp, tx_size, 10000);
    if (rv != tx_size)
    {
        avrdude_message(MSG_INFO, "%s: usbdev_send(): wrote %d out of %d bytes, err = %s\n",
                progname, rv, tx_size, usb_strerror());
        return -1;
    }
    bp += tx_size;
    mlen -= tx_size;
  } while (mlen > 0);

  if (verbose > 3)
  {
      avrdude_message(MSG_TRACE, "%s: Sent: ", progname);

      while (i) {
        unsigned char c = *p;
        if (isprint(c)) {
          avrdude_message(MSG_TRACE, "%c ", c);
        }
        else {
          avrdude_message(MSG_TRACE, ". ");
        }
        avrdude_message(MSG_TRACE, "[%02x] ", c);

        p++;
        i--;
      }
      avrdude_message(MSG_TRACE, "\n");
  }
  return 0;
}
/**
 * Send a command with data to usb4all controller and reads the answer.
 * Even if some inputs should be read a command to do this has to send before.
 * \param p            pointer to private data structure
 * \param data_out     pointer to data send to controller
 * \param data_in      pointer to buffer where read in data is stored
 * \return             number of bytes read in
 */
int
usb4all_data_io(PrivateData *p, tx_buffer * data_out, tx_buffer * data_in)
{
	int res;

	if (p->usbMode == MODE_BULK) {
		res = usb_bulk_write(p->usbHandle,
				     p->usbEpOut,
				     (char *)data_out->buffer,
				     data_out->use_count,
				     TIMEOUT_WRITE);
	}
	else {
		res = usb_interrupt_write(p->usbHandle,
					  p->usbEpOut,
					  (char *)data_out->buffer,
					  data_out->use_count,
					  TIMEOUT_WRITE);
	}

	if (res < 0) {
		p->hd44780_functions->drv_report(RPT_WARNING,
		   "usb4all_data_io: unable to send, result = %d ...", res);
		return -1;
	}

	/* if a reset command is send the usb4all controller doesn't answer */
	if (data_out->buffer[0] == USB4ALL_RESET) {
		return 0;
	}

	if (res != data_out->use_count) {
		p->hd44780_functions->drv_report(RPT_WARNING,
						 "usb4all_data_io: Want to send %d bytes but currently only %d bytes was send!?",
						 data_out->use_count, res);
		return -1;
	}

	if (p->usbMode == MODE_BULK) {
		res = usb_bulk_read(p->usbHandle,
				    p->usbEpIn,
				    (char *)data_in->buffer,
				    USB4ALL_RX_MAX,
				    TIMEOUT_READ);
	}
	else {
		res = usb_interrupt_read(p->usbHandle,
					 p->usbEpIn,
					 (char *)data_in->buffer,
					 USB4ALL_RX_MAX,
					 TIMEOUT_READ);
	}

	return res;
}
Exemple #15
0
int HID_API_EXPORT hid_write(hid_device *dev, const unsigned char *data, size_t length)
{
    int res;
    int report_number = data[0];
    int skipped_report_id = 0;

    if (report_number == 0x0)
    {
        data++;
        length--;
        skipped_report_id = 1;
    }


    if (dev->output_endpoint <= 0)
    {
        /* No interrput out endpoint. Use the Control Endpoint */
        res = usb_control_msg(dev->device_handle,
                                      USB_TYPE_CLASS|USB_RECIP_INTERFACE,
                                      0x09/*HID Set_Report*/,
                                      (2/*HID output*/ << 8) | report_number,
                                      dev->interface,
                                      (unsigned char *)data, length,
                                      1000/*timeout millis*/);

        if (res < 0)
            return -1;

        if (skipped_report_id)
            length++;

        return length;
    }
    else
    {
#if 0
        /* Use the interrupt out endpoint */
        int actual_length;
        res = usb_interrupt_write(dev->device_handle,
                                        dev->output_endpoint,
                                        (unsigned char*)data,
                                        length,
                                        &actual_length, 1000);

        if (res < 0)
            return -1;

        if (skipped_report_id)
            actual_length++;

        return actual_length;
#endif
    }
}
int send_command(usb_dev_handle *handle, cmdstruct command ) {
    if (command.numCmds == 0) {
        printf( "send_command: Empty command provided! Not sending anything...\n");
        return 0;
    }

    int stat;
    stat = usb_detach_kernel_driver_np(handle, 0);
    if ((stat < 0 ) || verbose_flag) perror("Detach kernel driver");

    stat = usb_claim_interface( handle, 0 );
    if ( (stat < 0) || verbose_flag) perror("Claiming USB interface");

    int transferred = 0;

    // send all command strings provided in command
    int cmdCount;
    for (cmdCount=0; cmdCount < command.numCmds; cmdCount++) {
        if (verbose_flag) {
            char raw_string[255];
            print_cmd(raw_string, command.cmds[cmdCount]);
            printf("\tSending string:   \"%s\"\n", raw_string);
        }
        stat = usb_interrupt_write( handle, 1, (const char*)command.cmds[cmdCount], sizeof( command.cmds[cmdCount] ), TRANSFER_WAIT_TIMEOUT_MS );
        transferred = (stat>0)?stat:0;
        if ( (stat < 0) || verbose_flag) perror("Sending USB command");
    }

    /* In case the command just sent caused the device to switch from restricted mode to native mode
     * the following two commands will fail due to invalid device handle (because the device changed
     * its pid on the USB bus).
     * So it is not possible anymore to release the interface and re-attach kernel driver.
     * I am not sure if this produces a memory leak within libusb, but i do not think there is another
     * solution possible...
     */
    stat = usb_release_interface(handle, 0 );
/*FIXME:
    if (stat != usb_ERROR_NO_DEVICE) { // silently ignore "No such device" error due to reasons explained above.
        if ( (stat < 0) || verbose_flag) {
            perror("Releasing USB interface.");
        }
    }
*/

//FIXME: Not portable?!    stat = usb_attach_kernel_driver_np( handle, 0);
/*FIXME:
    if (stat != usb_ERROR_NO_DEVICE) { // silently ignore "No such device" error due to reasons explained above.
        if ( (stat < 0) || verbose_flag) {
            perror("Reattaching kernel driver");
        }
    }
*/
    return 0;
}
Exemple #17
0
static int
write_command (usb_dev_handle *handle,
	       char cmd,
	       const char *in,
	       int in_size,
	       char *out,
	       int out_size)
{
	char buffer[64];
	int rc;
	int ret = -1;

	/* setup write packet */
	memset (buffer, 0x00, sizeof (buffer));
	buffer[0] = cmd;
	if (in != NULL)
		memcpy (buffer + 1, in, in_size);

	/* write to device */
	rc = usb_interrupt_write (handle, 0x01, buffer, 64, 5000);
	if (rc < 0) {
		printf ("Failed to write, got %s\n", usb_strerror ());
		goto out;
	}
	if (rc < 64) {
		printf ("Failed to write stream, only wrote %i\n", rc);
		goto out;
	}

	/* read status */
	rc = usb_interrupt_read (handle, 0x81, buffer, 64, 5000);
	if (rc != 2 + out_size && rc != 64) {
		printf ("Failed to read, got %i bytes\n", rc);
		goto out;
	}
	if (buffer[0] != 0x00) {
		printf ("Failed to get valid command status %i\n", buffer[0]);
		goto out;
	}
	if (buffer[1] != cmd) {
		printf ("Failed to get valid command value %i\n", buffer[1]);
		goto out;
	}

	/* copy data out of buffer */
	if (out != NULL)
		memcpy (out, buffer + 2, out_size);

	/* success */
	ret = 0;
out:
	return ret;
}
Exemple #18
0
/*
 *	HIDデバイスに HID Report を送信する.
 *	送信バッファの先頭の1バイトにReportID を入れる処理は
 *	この関数内で行うので、先頭1バイトを予約しておくこと.
 *
 *	id と Length の組はデバイス側で定義されたものでなければならない.
 *
 *	戻り値はHidD_SetFeatureの戻り値( 0 = 失敗 )
 *
 */
static int hidWrite(char *buf, int Length, int id)
{
	int rc;
	buf[0] = id;
	rc = usb_interrupt_write(usb_dev, EP_OUT , buf+1 , Length -1 , 5000);
//	rc = HidD_SetFeature(h, buf, Length);

#if	DEBUG_PKTDUMP
	memdump("WR", buf, Length);
#endif
	return rc;
}
Exemple #19
0
//  rawhid_send - send a packet
//    Inputs:
//	num = device to transmit to (zero based)
//	buf = buffer containing packet to send
//	len = number of bytes to transmit
//	timeout = time to wait, in milliseconds
//    Output:
//	number of bytes sent, or -1 on error
//
int rawhid_send(int num, void *buf, int len, int timeout)
{
	hid_t *hid;

	hid = get_hid(num);
	if (!hid || !hid->open) return -1;
	if (hid->ep_out) {
		return usb_interrupt_write(hid->usb, hid->ep_out, buf, len, timeout);
	} else {
		return usb_control_msg(hid->usb, 0x21, 9, 0, hid->iface, buf, len, timeout);
	}
}
Exemple #20
0
int PMD_SendOutputReport(HIDInterface* hid, __u8 reportID, __u8* vals, int num_vals, int delay)
{
  int ret;

  if (reportID == 0) { // use interrupt endpoint 1 
    ret = usb_interrupt_write(hid->dev_handle, USB_ENDPOINT_OUT | 1, (char *) vals, num_vals, delay);
    if (ret != num_vals) { // try one more time:
      ret = usb_interrupt_write(hid->dev_handle, USB_ENDPOINT_OUT | 1, (char *) vals, num_vals, delay);
    }
  } else { // use the control endpoint (Some FS devices use this)
    ret = usb_control_msg(hid->dev_handle,
			  (USB_TYPE_CLASS| USB_RECIP_INTERFACE),
			  SET_REPORT,
			  (OUTPUT_REPORT | reportID),
			  0,
			  (char *) vals,
			  num_vals,
			  delay);
  }
  return ret;    
}
void vibrate(int leftTriggerVal, int rightTriggerVal, int leftVal, int rightVal, int dwUserIndex)
{
	writeLog("vibrate", "start leftTriggerVal = %d rightTriggerVal = %d leftVal = %d rightVal = %d dwUserIndex = %d \n", leftTriggerVal, rightTriggerVal, leftVal, rightVal, dwUserIndex);
	// Motors are 0 - 255
	unsigned char data[] = { 9, 0, 0, 9, 0, 15, leftTriggerVal, rightTriggerVal, leftVal, rightVal, 255, 0, 0 };
	int dwWaitResult = WaitForSingleObject(XboxOneControllerMutex[dwUserIndex], INFINITE);
	if (dwWaitResult == WAIT_OBJECT_0)
	{
		usb_interrupt_write(controllerHandler[dwUserIndex]->handle, endpointOut, (char*)data, sizeof(data), 500);
		ReleaseMutex(XboxOneControllerMutex[dwUserIndex]);
	}
	writeLog("vibrate", "stop\n");
}
Exemple #22
0
int writeUSB ( ubyte *data , int numBytes )
{
    int nSent;
    
    //  printf ( "%s: writing [%d] bytes " , ProgName , numBytes );
    //  for ( int b = 0; b < numBytes; b++ ) printf ( "[%d]" , data[b] );
    //  printf ( "n" );
    
    // write the data
    
    nSent = usb_interrupt_write (udev, 1, (char *) data, numBytes, 200);
    
    if ( nSent != numBytes ) {
        
        printf ( "Error writing %d bytes: \n" , numBytes);
        int b;
        for ( b = 0; b < numBytes; b++ ) {
            printf ( "[%d]" , data[b] );
        }
        printf ( "\n[%d] bytes written\n", nSent );

        // Trying another time
        
        nSent = usb_interrupt_write (udev, 1, (char *) data, numBytes, 200);

        printf("Trying another time... ");
        if (nSent != numBytes) {
            printf("FAILED [%d]", nSent);
            return ( 0 );
        }
        else {
            printf("OK!");
        }
    }
    
    return ( 1 );
    
}
Exemple #23
0
uint8_t *hw_usbeesx_get_samples_init(struct flosslogic_context *ctx,
		uint64_t numsamples, uint64_t samplerate, int timeout)
{
	int ret, bufsize;
	char cmdbuf[2];
	uint8_t *sample_buffer;

	cmdbuf[0] = 0x01;
	/* TODO: Error handling. */
	ret = usb_interrupt_write(ctx->devhandle, 0x81, cmdbuf, 1, timeout);

	cmdbuf[0] = 0x55;
	/* TODO: Error handling. */
	ret = usb_interrupt_write(ctx->devhandle, 0x81, cmdbuf, 1, timeout);

	/* TODO */

	cmdbuf[0] = 0x01;
	cmdbuf[1] = samplerate_config_value(samplerate); /* TODO: Error h. */
	if (cmdbuf[1] == (char)0xff) {
		/* Handle hw_usbeesx_shutdown() errors. */
		hw_usbeesx_shutdown(ctx);
		/* TODO: Set error code. */
		return NULL;
	}
	/* TODO: Error handling. */
	ret = usb_interrupt_write(ctx->devhandle, 0x01, cmdbuf, 2, timeout);

	bufsize = numsamples * (ctx->la->numchannels / 8);
	sample_buffer = malloc(bufsize);
	/* TODO: Better error handling? */
	if (sample_buffer == NULL)
		return NULL;

	return sample_buffer;
}
Exemple #24
0
static int pickit2_get_firmware_version(void)
{
	int ret;
	uint8_t command[CMD_LENGTH] = {CMD_GET_VERSION, CMD_END_OF_BUFFER};

	ret = usb_interrupt_write(pickit2_handle, ENDPOINT_OUT, (char *)command, CMD_LENGTH, DFLT_TIMEOUT);
	ret = usb_interrupt_read(pickit2_handle, ENDPOINT_IN, (char *)command, CMD_LENGTH, DFLT_TIMEOUT);
	
	msg_pdbg("PICkit2 Firmware Version: %d.%d\n", (int)command[0], (int)command[1]);
	if (ret != CMD_LENGTH) {
		msg_perr("Command Get Firmware Version failed (%s)!\n", usb_strerror());
		return 1;
	}

	return 0;
}
Exemple #25
0
static int pickit2_set_spi_voltage(int millivolt)
{
	double voltage_selector;
	switch (millivolt) {
	case 0:
		/* Admittedly this one is an assumption. */
		voltage_selector = 0;
		break;
	case 1800:
		voltage_selector = 1.8;
		break;
	case 2500:
		voltage_selector = 2.5;
		break;
	case 3500:
		voltage_selector = 3.5;
		break;
	default:
		msg_perr("Unknown voltage %i mV! Aborting.\n", millivolt);
		return 1;
	}
	msg_pdbg("Setting SPI voltage to %u.%03u V\n", millivolt / 1000,
		 millivolt % 1000);

	uint8_t command[CMD_LENGTH] = {
		CMD_SET_VDD,
		voltage_selector * 2048 + 672,
		(voltage_selector * 2048 + 672) / 256,
		voltage_selector * 36,
		CMD_SET_VPP,
		0x40,
		voltage_selector * 18.61,
		voltage_selector * 13,
		CMD_END_OF_BUFFER
	};

	int ret = usb_interrupt_write(pickit2_handle, ENDPOINT_OUT, (char *)command, CMD_LENGTH, DFLT_TIMEOUT);

	if (ret != CMD_LENGTH) {
		msg_perr("Command Set Voltage failed (%s)!\n", usb_strerror());
		return 1;
	}

	return 0;
}
Exemple #26
0
static int l_usb_interrupt_write(lua_State *L) {
	struct usb_dev_handle * dev_handle = lua_touserdata(L, 1);  
	int ep = lua_tonumber(L, 2);  
	const char *bytes = lua_tostring (L, 3);
	int size = lua_strlen (L, 3);
	int timeout = lua_tonumber (L, 4);
	
	int ret = usb_interrupt_write(dev_handle, ep, (char*)bytes, size, timeout);
	
	if( ret < 0 ) {
		lua_pushnil (L);
		lua_pushnumber (L, ret);
		return 2; /* number of results */   
	} else{
		lua_pushnumber (L, ret);
		return 1; /* number of results */   
	}	
}
void 
USBDevice_internalFlush(LPSKYETEK_DEVICE device, unsigned char lockSendBuffer)
{
	LPUSB_DEVICE usbDevice;
	unsigned char sendBuffer[64];
	int result;
	
	if((device == NULL) || (device->user == NULL))
		return;
	
	usbDevice = (LPUSB_DEVICE)device->user;

#ifdef HAVE_PTHREAD
	if(lockSendBuffer)
		pthread_mutex_lock(&usbDevice->sendBufferMutex);
#endif

	if(usbDevice->sendBufferWritePtr == usbDevice->sendBuffer)
		goto end;

	sendBuffer[0] = (usbDevice->sendBufferWritePtr - usbDevice->sendBuffer);
	memcpy((sendBuffer + 1), usbDevice->sendBuffer, sendBuffer[0]);

	/*printf("Writing - %d\r\n", sendBuffer[0]);
	for(size_t ix = 0; ix < sendBuffer[0]; ix++)
		printf("%02x", sendBuffer[ix]);
	printf("\r\n");*/

	
	if((result = usb_interrupt_write(usbDevice->usbDevHandle, 1, sendBuffer, 64, 100)) < 0)		
	{
		/*printf("usb_interrupt_write failed: %d \r\n", result);*/
	}
	else
		usbDevice->packetParity++;
	
	usbDevice->sendBufferWritePtr = usbDevice->sendBuffer;

end:
#ifdef HAVE_PTHREAD
	if(lockSendBuffer)
		pthread_mutex_unlock(&usbDevice->sendBufferMutex);
#endif
}
Exemple #28
0
int do_receiveBuffer(size_t totalLen)
{
	OpenIBootCmd cmd;
	char* buffer;

	if(totalLen > 0)
	{
		buffer = (char*) malloc(totalLen + 1);

		cmd.command = OPENIBOOTCMD_DUMPBUFFER_GOAHEAD;
		cmd.dataLen = totalLen;
		usb_interrupt_write(device, 4, (char*)&cmd, sizeof(OpenIBootCmd), 1000);

		int read = 0;
		while(read < totalLen) {
			int left = (totalLen - read);
			size_t toRead = (left > USB_BYTES_AT_A_TIME) ? USB_BYTES_AT_A_TIME : left;
			int hasRead;
			hasRead = usb_bulk_read(device, 1, buffer + read, toRead, 1000);
			read += hasRead;
		}

		int discarded = 0;
		if(readIntoOutput > 0) {
			if(readIntoOutput <= read) {
				fwrite(buffer, 1, readIntoOutput, outputFile);
				discarded += readIntoOutput;
				readIntoOutput = 0;
				fclose(outputFile);
			} else {
				fwrite(buffer, 1, read, outputFile);
				discarded += read;
				readIntoOutput -= read;
			}
		}

		*(buffer + read) = '\0';
		printf("%s", buffer + discarded); fflush(stdout);

		free(buffer);
	}

	return 0;
}
Exemple #29
0
ssize_t
usbWriteEndpoint (
  UsbDevice *device,
  unsigned char endpointNumber,
  const void *buffer,
  size_t length,
  int timeout
) {
  UsbDeviceExtension *devx = device->extension;
  UsbEndpoint *endpoint;

  if ((endpoint = usbGetOutputEndpoint(device, endpointNumber))) {
    const UsbEndpointDescriptor *descriptor = endpoint->descriptor;
    UsbEndpointTransfer transfer = USB_ENDPOINT_TRANSFER(descriptor);
    int result = -1;

    usbLogEndpointData(endpoint, "output", buffer, length);

    switch (transfer) {
      case UsbEndpointTransfer_Bulk:
        result = usb_bulk_write(devx->handle, descriptor->bEndpointAddress,
                                (char *)buffer, length, timeout);
        break;

      case UsbEndpointTransfer_Interrupt:
        result = usb_interrupt_write(devx->handle, descriptor->bEndpointAddress,
                                     (char *)buffer, length, timeout);
        break;

      default:
        logMessage(LOG_ERR, "USB endpoint output transfer not supported: 0X%02X", transfer);
        result = -ENOSYS;
        break;
    }

    if (result >= 0) return result;
    errno = -result;
  }

  logSystemError("USB endpoint write");
  return -1;
}
Exemple #30
0
/* USB::DevHandle#usb_interrupt_write(endpoint, bytes, timeout) */
static VALUE
rusb_interrupt_write(
  VALUE v,
  VALUE vep,
  VALUE vbytes,
  VALUE vtimeout)
{
  usb_dev_handle *p = get_usb_devhandle(v);
  int ep = NUM2INT(vep);
  int timeout = NUM2INT(vtimeout);
  char *bytes;
  int size;
  int ret;
  StringValue(vbytes);
  bytes = RSTRING_PTR(vbytes);
  size = RSTRING_LEN(vbytes);
  ret = usb_interrupt_write(p, ep, bytes, size, timeout);
  check_usb_error("usb_interrupt_write", ret);
  return INT2NUM(ret);
}