Example #1
0
//
// Open the serial port.
// Initialise ftdi_context and use it to open the device
static dc_status_t serial_ftdi_open (void **userdata, const char* name)
{
	// Allocate memory.
	ftdi_serial_t *device = (ftdi_serial_t *) malloc (sizeof (ftdi_serial_t));
	if (device == NULL) {
		SYSERROR (context, errno);
		return DC_STATUS_NOMEMORY;
	}

	struct ftdi_context *ftdi_ctx = ftdi_new();
	if (ftdi_ctx == NULL) {
		free(device);
		SYSERROR (context, errno);
		return DC_STATUS_NOMEMORY;
	}

	// Library context.
	//device->context = context;

	// Default to blocking reads.
	device->timeout = -1;

	// Default to full-duplex.
	device->halfduplex = 0;
	device->baudrate = 0;
	device->nbits = 0;

	// Initialize device ftdi context
	ftdi_init(ftdi_ctx);

	if (ftdi_set_interface(ftdi_ctx,INTERFACE_ANY)) {
		free(device);
		ERROR (context, "%s", ftdi_get_error_string(ftdi_ctx));
		return DC_STATUS_IO;
	}

	if (serial_ftdi_open_device(ftdi_ctx) < 0) {
		free(device);
		ERROR (context, "%s", ftdi_get_error_string(ftdi_ctx));
		return DC_STATUS_IO;
	}

	if (ftdi_usb_reset(ftdi_ctx)) {
		free(device);
		ERROR (context, "%s", ftdi_get_error_string(ftdi_ctx));
		return DC_STATUS_IO;
	}

	if (ftdi_usb_purge_buffers(ftdi_ctx)) {
		free(device);
		ERROR (context, "%s", ftdi_get_error_string(ftdi_ctx));
		return DC_STATUS_IO;
	}

	device->ftdi_ctx = ftdi_ctx;

	*userdata = device;

	return DC_STATUS_SUCCESS;
}
Example #2
0
/*
 * use libftdi and libusb to send command
 * no kernel driver needed
 */
int usbWriteFtdi(char *cmdstr)
{
    struct ftdi_context ctx;
    int device=0x0c30, vendor=0x1781;

    if (ftdi_init( &ctx )) {
        fprintf(stderr,  "usb - init error !\n");
        return 1;
    }

    if (ftdi_usb_open(&ctx, vendor, device)) {
        fprintf(stderr,  "usb - open error (cannot find?) !\n");
        ftdi_deinit( &ctx );
        return 2;
    }

    if (ftdi_usb_reset( &ctx )) {
        fprintf(stderr,  "usb - reset error !\n");
        ftdi_usb_close( &ctx );
        ftdi_deinit( &ctx );
        return 3;
    }

    ftdi_disable_bitbang( &ctx );
    ftdi_set_baudrate(&ctx, BAUD);

    ftdi_write_data( &ctx, cmdstr, strlen(cmdstr) );
    sleep(1); /* just for sure */
    ftdi_usb_close( &ctx );
    ftdi_deinit( &ctx );

    return 0;
}
/**
 * Close the USB port and reset the sequencer logic.
 *
 * @param devc The struct containing private per-device-instance data.
 *
 * @return SR_OK upon success, SR_ERR_ARG upon invalid arguments.
 */
static int close_usb_reset_sequencer(struct dev_context *devc)
{
	/* Magic sequence of bytes for resetting the sequencer logic. */
	uint8_t buf[8] = {0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01};
	int ret;

	/* Note: Caller checked that devc and devc->ftdic != NULL. */

	if (devc->ftdic->usb_dev) {
		/* Reset the sequencer logic, then wait 100ms. */
		sr_dbg("Resetting sequencer logic.");
		(void) cv_write(devc, buf, 8); /* Ignore errors. */
		g_usleep(100 * 1000);

		/* Purge FTDI buffers, then reset and close the FTDI device. */
		sr_dbg("Purging buffers, resetting+closing FTDI device.");

		/* Log errors, but ignore them (i.e., don't abort). */
		if ((ret = ftdi_usb_purge_buffers(devc->ftdic)) < 0)
			sr_err("Failed to purge FTDI buffers (%d): %s.",
			       ret, ftdi_get_error_string(devc->ftdic));
		if ((ret = ftdi_usb_reset(devc->ftdic)) < 0)
			sr_err("Failed to reset FTDI device (%d): %s.",
			       ret, ftdi_get_error_string(devc->ftdic));
		if ((ret = ftdi_usb_close(devc->ftdic)) < 0)
			sr_err("Failed to close FTDI device (%d): %s.",
			       ret, ftdi_get_error_string(devc->ftdic));
	}

	/* Close USB device, deinitialize and free the FTDI context. */
	ftdi_free(devc->ftdic);
	devc->ftdic = NULL;

	return SR_OK;
}
Example #4
0
static int ublast_ftdi_init(struct ublast_lowlevel *low)
{
	uint8_t latency_timer;
	struct ftdi_context *ftdic = ublast_getftdic(low);

	LOG_INFO("usb blaster interface using libftdi");
	if (ftdi_init(ftdic) < 0)
		return ERROR_JTAG_INIT_FAILED;

	/* context, vendor id, product id */
	if (ftdi_usb_open(ftdic, low->ublast_vid, low->ublast_pid) < 0)	{
		LOG_ERROR("unable to open ftdi device: %s", ftdic->error_str);
		return ERROR_JTAG_INIT_FAILED;
	}

	if (ftdi_usb_reset(ftdic) < 0) {
		LOG_ERROR("unable to reset ftdi device");
		return ERROR_JTAG_INIT_FAILED;
	}

	if (ftdi_set_latency_timer(ftdic, 2) < 0) {
		LOG_ERROR("unable to set latency timer");
		return ERROR_JTAG_INIT_FAILED;
	}

	if (ftdi_get_latency_timer(ftdic, &latency_timer) < 0) {
		LOG_ERROR("unable to get latency timer");
		return ERROR_JTAG_INIT_FAILED;
	}
	LOG_DEBUG("current latency timer: %u", latency_timer);

	ftdi_disable_bitbang(ftdic);
	return ERROR_OK;
}
	bool FalconCommLibFTDI::setFirmwareMode()
	{
		unsigned int bytes_written, bytes_read;
		unsigned char check_msg_1_send[3] = {0x0a, 0x43, 0x0d};
		unsigned char check_msg_1_recv[4] = {0x0a, 0x44, 0x2c, 0x0d};
		unsigned char check_msg_2[1] = {0x41};
		unsigned char send_buf[128], receive_buf[128];
		int k;
	
		if(!m_isCommOpen)
		{
			m_errorCode = FALCON_COMM_DEVICE_NOT_VALID_ERROR;
			return false;
		}

		//Save ourselves having to reset this on every error
		m_errorCode = FALCON_COMM_DEVICE_ERROR;
		
		//Clear out current buffers to make sure we have a fresh start
		if((m_deviceErrorCode = ftdi_usb_purge_buffers((m_falconDevice))) < 0) return false;

		//Reset the device
		if((m_deviceErrorCode = ftdi_usb_reset((m_falconDevice))) < 0) return false;

		//Make sure our latency timer is at 16ms, otherwise firmware checks tend to always fail
		if((m_deviceErrorCode = ftdi_set_latency_timer((m_falconDevice), 16)) < 0) return false;
	
		//Set to:
		// 9600 baud
		// 8n1
		// No Flow Control
		// RTS Low
		// DTR High	
		if((m_deviceErrorCode = ftdi_set_baudrate((m_falconDevice), 9600)) < 0) return false;
		if((m_deviceErrorCode = ftdi_set_line_property((m_falconDevice), BITS_8, STOP_BIT_1, NONE)) < 0) return false;
		if((m_deviceErrorCode = ftdi_setflowctrl((m_falconDevice), SIO_DISABLE_FLOW_CTRL)) < 0) return false;
		if((m_deviceErrorCode = ftdi_setrts((m_falconDevice), 0)) < 0) return false;
		if((m_deviceErrorCode = ftdi_setdtr((m_falconDevice), 0)) < 0) return false;
		if((m_deviceErrorCode = ftdi_setdtr((m_falconDevice), 1)) < 0) return false;

		//Send 3 bytes: 0x0a 0x43 0x0d
		if(!write(check_msg_1_send, 3)) return false;
		if(!read(receive_buf, 4)) return false;
	
		//Set to:
		// DTR Low
		// 140000 baud (0x15 clock ticks per signal)
		if((m_deviceErrorCode = ftdi_setdtr((m_falconDevice),0)) < 0) return false;
		if((m_deviceErrorCode = ftdi_set_baudrate((m_falconDevice), 140000)) < 0) return false;

		//Send "A" character
		if(!write(check_msg_2, 1)) return false;

		//Expect back 2 bytes:
		// 0x13 0x41
		if(!read(receive_buf, 2)) return false;
		m_errorCode = 0;
		return true;
	}
Example #6
0
File: vcc.c Project: koheik/vcctool
void begin(struct ftdi_context *ftdi)
{
	ftdi_usb_reset(ftdi);
	ftdi_usb_purge_rx_buffer(ftdi);
	ftdi_usb_purge_tx_buffer(ftdi);

	ftdi_setrts(ftdi, 1);
}
Example #7
0
static int jtagkey_init(unsigned short vid, unsigned short pid) {
	int ret = 0;
	unsigned char c;

	if ((ret = ftdi_init(&ftdic)) != 0) {
		fprintf(stderr, "unable to initialise libftdi: %d (%s)\n", ret, ftdi_get_error_string(&ftdic));
		return ret;
	}
	
	if ((ret = ftdi_usb_open(&ftdic, vid, pid)) != 0) {
		fprintf(stderr, "unable to open ftdi device: %d (%s)\n", ret, ftdi_get_error_string(&ftdic));
		return ret;
	}

	if ((ret = ftdi_usb_reset(&ftdic)) != 0) {
		fprintf(stderr, "unable reset device: %d (%s)\n", ret, ftdi_get_error_string(&ftdic));
		return ret;
	}

	if ((ret = ftdi_set_interface(&ftdic, INTERFACE_A)) != 0) {
		fprintf(stderr, "unable to set interface: %d (%s)\n", ret, ftdi_get_error_string(&ftdic));
		return ret;
	}

	if ((ret = ftdi_write_data_set_chunksize(&ftdic, USBBUFSIZE))  != 0) {
		fprintf(stderr, "unable to set write chunksize: %d (%s)\n", ret, ftdi_get_error_string(&ftdic));
		return ret;
	}

	if ((ret = ftdi_read_data_set_chunksize(&ftdic, USBBUFSIZE))  != 0) {
		fprintf(stderr, "unable to set read chunksize: %d (%s)\n", ret, ftdi_get_error_string(&ftdic));
		return ret;
	}

	if ((ret = jtagkey_latency(OTHER_LATENCY)) != 0)
		return ret;

	c = 0x00;
	ftdi_write_data(&ftdic, &c, 1);

	if ((ret = ftdi_set_bitmode(&ftdic, JTAGKEY_TCK|JTAGKEY_TDI|JTAGKEY_TMS|JTAGKEY_OEn, BITMODE_SYNCBB))  != 0) {
		fprintf(stderr, "unable to enable bitbang mode: %d (%s)\n", ret, ftdi_get_error_string(&ftdic));
		return ret;
	}

	if ((ret = ftdi_set_baudrate(&ftdic, JTAG_SPEED))  != 0) {
		fprintf(stderr, "unable to set baudrate: %d (%s)\n", ret, ftdi_get_error_string(&ftdic));
		return ret;
	}

	if ((ret = ftdi_usb_purge_buffers(&ftdic))  != 0) {
		fprintf(stderr, "unable to purge buffers: %d (%s)\n", ret, ftdi_get_error_string(&ftdic));
		return ret;
	}

	return ret;
}
Example #8
0
bool EnttecDMXUSBOpen::open()
{
	if (isOpen() == false)
	{
		if (ftdi_usb_open_desc(&m_context, EnttecDMXUSBWidget::VID,
						   EnttecDMXUSBWidget::PID,
						   name().toAscii(),
						   serial().toAscii()) < 0)
		{
			qWarning() << "Unable to open" << uniqueName()
				   << ":" << ftdi_get_error_string(&m_context);
			return false;
		}

		if (ftdi_usb_reset(&m_context) < 0)
		{
			qWarning() << "Unable to reset" << uniqueName()
				   << ":" << ftdi_get_error_string(&m_context);
			return close();
		}

		if (ftdi_set_line_property(&m_context, BITS_8, STOP_BIT_2, NONE) < 0)
		{
			qWarning() << "Unable to set 8N2 serial properties to"
				   << uniqueName()
				   << ":" << ftdi_get_error_string(&m_context);
			return close();
		}

		if (ftdi_set_baudrate(&m_context, 250000) < 0)
		{
			qWarning() << "Unable to set 250kbps baudrate for"
				   << uniqueName()
				   << ":" << ftdi_get_error_string(&m_context);
			return close();
		}

		if (ftdi_setrts(&m_context, 0) < 0)
		{
			qWarning() << "Unable to set RTS line to 0 for"
				   << uniqueName()
				   << ":" << ftdi_get_error_string(&m_context);
			return close();
		}

		if (isRunning() == false)
			start();

		return true;
	}
	else
	{
		/* Already open */
		return true;
	}
}
Example #9
0
QString LibFTDIInterface::readLabel(uchar label, int *ESTA_code)
{
    if (ftdi_usb_open_desc(&m_handle, DMXInterface::FTDIVID, DMXInterface::FTDIPID,
                           name().toLatin1().data(), serial().toLatin1().data()) < 0)

        return QString();

    if (ftdi_usb_reset(&m_handle) < 0)
        return QString();

    if (ftdi_set_baudrate(&m_handle, 250000) < 0)
        return QString();

    if (ftdi_set_line_property(&m_handle, BITS_8, STOP_BIT_2, NONE) < 0)
        return QString();

    if (ftdi_setflowctrl(&m_handle, SIO_DISABLE_FLOW_CTRL) < 0)
        return QString();

    QByteArray request;
    request.append(ENTTEC_PRO_START_OF_MSG);
    request.append(label);
    request.append(ENTTEC_PRO_DMX_ZERO); // data length LSB
    request.append(ENTTEC_PRO_DMX_ZERO); // data length MSB
    request.append(ENTTEC_PRO_END_OF_MSG);

    if (ftdi_write_data(&m_handle, (uchar*) request.data(), request.size()) < 0)
    {
        qDebug() << Q_FUNC_INFO << "Cannot write data to device";
        return QString();
    }

    uchar *buffer = (uchar*) malloc(sizeof(uchar) * 40);
    Q_ASSERT(buffer != NULL);

    QByteArray array;
    usleep(300000); // give some time to the device to respond
    int read = ftdi_read_data(&m_handle, buffer, 40);
    //qDebug() << Q_FUNC_INFO << "Data read: " << read;
    array = QByteArray::fromRawData((char*) buffer, read);

    if (array[0] != ENTTEC_PRO_START_OF_MSG)
        qDebug() << Q_FUNC_INFO << "Reply message wrong start code: " << QString::number(array[0], 16);
    *ESTA_code = (array[5] << 8) | array[4];
    array.remove(0, 6); // 4 bytes of Enttec protocol + 2 of ESTA ID
    array.replace(ENTTEC_PRO_END_OF_MSG, '\0'); // replace Enttec termination with string termination

    //for (int i = 0; i < array.size(); i++)
    //    qDebug() << "-Data: " << array[i];
    ftdi_usb_close(&m_handle);

    return QString(array);
}
Example #10
0
bool QLCFTDI::reset()
{
    if (ftdi_usb_reset(&m_handle) < 0)
    {
        qWarning() << Q_FUNC_INFO << name() << ftdi_get_error_string(&m_handle);
        return false;
    }
    else
    {
        return true;
    }
}
Example #11
0
struct ftdi_context *
bub_init(unsigned int baud_rate,
	 unsigned char latency,
	 unsigned int tx_buf_size,
	 unsigned int rx_buf_size) {

	int ret = 0;

	struct ftdi_context *ftdic;
	
	ftdic = malloc(sizeof(struct ftdi_context));
   
	if(ftdic == NULL) {
		perror("malloc");
		return(NULL);
	}

	ret = ftdi_init(ftdic);
	if (ret < 0) {
		fprintf(stderr, "ftdi_init failed: %d.\n", ret);
		return(NULL);
	}

	ftdi_set_interface(ftdic, INTERFACE_ANY);

	ret = ftdi_usb_open(ftdic, 0x0403, 0x6001); // FIXME make nice defines
	if(ret < 0) {
		fprintf(stderr, "unable to open ftdi device: %d (%s)\n", 
			ret, ftdi_get_error_string(ftdic));
		return(NULL);
	}

	if(ftdi_usb_reset(ftdic) != 0)
		fprintf(stderr, "WARN: ftdi_usb_reset failed!\n");

	ftdi_disable_bitbang(ftdic);

	if (ftdi_set_baudrate(ftdic, baud_rate) < 0) {
		fprintf(stderr, "Unable to set baudrate: (%s)\n", 
			ftdi_get_error_string(ftdic));
		return(NULL);
	} 

	ftdi_set_latency_timer(ftdic, latency);

	if(tx_buf_size > 0)
		ftdi_write_data_set_chunksize(ftdic, tx_buf_size);
	if(rx_buf_size > 0)
		ftdi_read_data_set_chunksize(ftdic, rx_buf_size);

	return(ftdic);
}
Example #12
0
bool FTDIDevice::connect (int baudrate) throw ()
{
#ifdef FOUND_ftdi

  int ret, i;
  disconnect();

  ftdi_init (&_ftdic);
  while ((ret = ftdi_usb_open(&_ftdic, 0x0403, 0x6001)) < 0)
    FTDERROR("unable to open ftdi device: " << ret << " (" << ftdi_get_error_string(&_ftdic) << ")");

  for (i=0, ret=-1; i<10 && ret!=0; i++)
    ret = ftdi_usb_reset(&_ftdic);
  if (ret != 0) {
    FTDERROR("unable to reset ftdi device.");
    return false;
  }

  for (i=0, ret=-1; i<10 && ret!=0; i++)
    ret = ftdi_set_baudrate(&_ftdic, baudrate);
  if (ret != 0) {
    FTDERROR("unable to set baud rate.");
    return false;
  }

  if (_latency > 0) for (i=0, ret=-1; i<10 && ret!=0; i++)
      ret = ftdi_set_latency_timer(&_ftdic, _latency);
  if (ret != 0) {
    FTDERROR("unable to set latency timer.");
    return false;
  }

  for (i=0, ret=-1; i<10 && ret!=0; i++)
    ret = ftdi_usb_purge_buffers(&_ftdic);
  if (ret != 0) {
    FTDERROR("unable to purge buffers.");
    return false;
  }

  _initialized = true;
  FTDLOG("Connection successful.");
  return true;

#else

  _initialized = false;
  FTDERROR("cannot connect FTDI device: compiled without required libraries");
  return false;

#endif
}
Example #13
0
int hftdi::ftdi_usb_open()
{
//    struct

    if(m_usb->claim_interface(m_ftdi->interface) < 0)
        return  -1;
    if(ftdi_usb_reset() != 0)
        return  -6;
    m_ftdi->type = TYPE_232H;

    if(ftdi_set_baudrate(9600) != 0)
        return  -7;

    return  0;
}
Example #14
0
int main(void) {


	snd_rawmidi_open(&midi_in, &midi_out, "virtual", SND_RAWMIDI_NONBLOCK);
	//snd_rawmidi_open(&midi_in, &midi_out, "virtual", 0);


	if (ftdi_init( &ftdi )) {
		fprintf(stderr,  "usb - init error !\n");
		return 1;
	}

	if (ftdi_usb_open(&ftdi, 0x0403, 0x6001)) {
		fprintf(stderr,  "usb - open error (cannot find?) !\n");
		fprintf(stderr, "ftdi_usb_open failed, error (%s)\n", ftdi_get_error_string(&ftdi));
		ftdi_deinit( &ftdi );
		return 2;
	}

	if (ftdi_usb_reset( &ftdi )) {
		fprintf(stderr,  "usb - reset error !\n");
		ftdi_usb_close( &ftdi );
		ftdi_deinit( &ftdi );
		return 3;
	}

	ftdi_disable_bitbang( &ftdi );
	ftdi_set_baudrate(&ftdi, BAUD);

	unsigned char buf[BUFFER_SIZE];
	int ret;
	while(1) {
		//FTDI2MIDI
		ret = ftdi_read_data(&ftdi, buf, BUFFER_SIZE);
		if(ret < 0) break;
		if(ret > 0) snd_rawmidi_write(midi_out, buf, BUFFER_SIZE);

		//MIDI2FTDI
		/*
		ret = snd_rawmidi_read(midi_in, buf,BUFFER_SIZE);
		if(ret < 0 && ret != -EAGAIN) break;
		if(ret > 0) ftdi_write_data(&ftdi, buf,BUFFER_SIZE);
		*/
		usleep(LATENCY);
	}
	exit(0);
}
Example #15
0
int sys_init()
{
	int ret, i;
	struct ftdi_device_list *devlist, *curdev;
	char manufacturer[128], description[128], serialno[128];

	if (ftdi_init(&ux400_ftdic) < 0)
	{
		fprintf(stderr, "ftdi_init failed\n");
		return EXIT_FAILURE;
	}

	if((ret = ftdi_usb_open_desc(&ux400_ftdic, UX400VENDOR, UX400PRODUCT, UX400DES, UX400_LOCAL_SN)) < 0)
	{
	    fprintf(stderr, "ftdi_usb_open_desc failed: %d (%s)\n", ret, ftdi_get_error_string(&ux400_ftdic));
	    return EXIT_FAILURE;
	}

	if((ret = ftdi_usb_reset(&ux400_ftdic)) < 0)
	{
	    fprintf(stderr, "ftdi_usb_reset failed: %d (%s)\n", ret, ftdi_get_error_string(&ux400_ftdic));
	    return EXIT_FAILURE;
	}

	if((ret = ftdi_set_baudrate(&ux400_ftdic, 9600)) < 0)
	{
	    fprintf(stderr, "ftdi_set_baudrate failed: %d (%s)\n", ret, ftdi_get_error_string(&ux400_ftdic));
	    return EXIT_FAILURE;
	}

	if((ret = ftdi_set_bitmode(&ux400_ftdic, 0x00, BITMODE_RESET)) < 0)
	{
	    fprintf(stderr, "ftdi_set_bitmode failed: %d (%s)\n", ret, ftdi_get_error_string(&ux400_ftdic));
	    return EXIT_FAILURE;
	}

	usleep(10000);

	if((ret = ftdi_set_bitmode(&ux400_ftdic, 0x00, BITMODE_MCU)) < 0)
	{
	    fprintf(stderr, "ftdi_set_bitmode failed: %d (%s)\n", ret, ftdi_get_error_string(&ux400_ftdic));
	    return EXIT_FAILURE;
	}

	return 0;
}
Example #16
0
/**
 * Close the ChronoVu LA8 USB port and reset the LA8 sequencer logic.
 *
 * @param devc The struct containing private per-device-instance data.
 * @return SR_OK upon success, SR_ERR_ARG upon invalid arguments.
 */
SR_PRIV int la8_close_usb_reset_sequencer(struct dev_context *devc)
{
	/* Magic sequence of bytes for resetting the LA8 sequencer logic. */
	uint8_t buf[8] = {0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01};
	int ret;

	if (!devc) {
		sr_err("%s: devc was NULL.", __func__);
		return SR_ERR_ARG;
	}

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

	if (devc->ftdic->usb_dev) {
		/* Reset the LA8 sequencer logic, then wait 100ms. */
		sr_dbg("Resetting sequencer logic.");
		(void) la8_write(devc, buf, 8); /* Ignore errors. */
		g_usleep(100 * 1000);

		/* Purge FTDI buffers, then reset and close the FTDI device. */
		sr_dbg("Purging buffers, resetting+closing FTDI device.");

		/* Log errors, but ignore them (i.e., don't abort). */
		if ((ret = ftdi_usb_purge_buffers(devc->ftdic)) < 0)
			sr_err("%s: ftdi_usb_purge_buffers: (%d) %s.",
			    __func__, ret, ftdi_get_error_string(devc->ftdic));
		if ((ret = ftdi_usb_reset(devc->ftdic)) < 0)
			sr_err("%s: ftdi_usb_reset: (%d) %s.", __func__,
			       ret, ftdi_get_error_string(devc->ftdic));
		if ((ret = ftdi_usb_close(devc->ftdic)) < 0)
			sr_err("%s: ftdi_usb_close: (%d) %s.", __func__,
			       ret, ftdi_get_error_string(devc->ftdic));
	}

	/* Close USB device, deinitialize and free the FTDI context. */
	ftdi_free(devc->ftdic); /* Returns void. */
	devc->ftdic = NULL;

	return SR_OK;
}
Example #17
0
static dc_status_t serial_ftdi_purge (void *io, dc_direction_t queue)
{
	ftdi_serial_t *device = io;

	if (device == NULL)
		return DC_STATUS_INVALIDARGS;

	size_t input;
	serial_ftdi_get_received (io, &input);
	INFO (device->context, "Flush: queue=%u, input=%lu, output=%i", queue, input,
	      serial_ftdi_get_transmitted (device));

	switch (queue) {
	case DC_DIRECTION_INPUT:  /**< Input direction */
		if (ftdi_usb_purge_tx_buffer(device->ftdi_ctx)) {
			ERROR (device->context, "%s", ftdi_get_error_string(device->ftdi_ctx));
			return DC_STATUS_IO;
		}
		break;
	case DC_DIRECTION_OUTPUT: /**< Output direction */
		if (ftdi_usb_purge_rx_buffer(device->ftdi_ctx)) {
			ERROR (device->context, "%s", ftdi_get_error_string(device->ftdi_ctx));
			return DC_STATUS_IO;
		}
		break;
	case DC_DIRECTION_ALL: /**< All directions */
	default:
		if (ftdi_usb_reset(device->ftdi_ctx)) {
			ERROR (device->context, "%s", ftdi_get_error_string(device->ftdi_ctx));
			return DC_STATUS_IO;
		}
		break;
	}

	return DC_STATUS_SUCCESS;
}
Example #18
0
Ft245sync::Ft245sync(unsigned int chunkSizeRead,
                     unsigned int chunkSizeWrite,
                     uint8_t gpio,
                     struct ftdi_context * vftdic, 
                     struct ftdi_context * vftdic2)
{
    if(vftdic == NULL)
    {
        this->ftdic = static_cast<struct ftdi_context*>(malloc(sizeof(struct ftdi_context)));
    }
    else
    {
        this->ftdic = vftdic;
    }
    if(vftdic2 == NULL)
    {
        this->ftdic2 = static_cast<struct ftdi_context*>(malloc(sizeof(struct ftdi_context)));
    }
    else
    {
        this->ftdic2 = vftdic2;
    }
    int f;
    // Init 1. channel
    if (ftdi_init(ftdic) < 0)
    {
        throw Exception("ftdi_init failure\n");
    }
    ftdi_set_interface(ftdic, INTERFACE_A);
    f = ftdi_usb_open(ftdic, 0x0403, PID);
    if (f < 0 && f != -5)
    {
        throw Exception("Unable to open FTDI device, channel A\n");
    }
    
    // Init 2. channel
    if (ftdi_init(ftdic2) < 0)
    {
        throw Exception("ftdi_init failure\n");
    }
    ftdi_usb_reset(ftdic);
    ftdi_usb_reset(ftdic2);
    ftdi_set_interface(ftdic2, INTERFACE_B);
    f = ftdi_usb_open(ftdic2, 0x0403, PID);
    if (f < 0 && f != -5)
    {
        throw Exception("Unable to open FTDI device, channel B\n");
    }
    
    ftdi_write_data_set_chunksize(ftdic2, 512);
    ftdi_set_interface(ftdic2, INTERFACE_B);
    ftdi_usb_reset(ftdic2);
    ftdi_set_latency_timer(ftdic2, 2);
    ftdi_setflowctrl(ftdic2, SIO_RTS_CTS_HS);
    ftdi_set_bitmode(ftdic2, 0, BBMODE_SPI);
    
    uint8_t buf[3];
    buf[0] = SET_BITS_LOW;
    buf[1] = 8;
    buf[2] = BIT_DIR; //holding programming of FPGA*/
    ftdi_write_data(ftdic2, buf, 3);
    buf[0] = SET_BITS_HIGH;
    buf[1] = 0xFF; //lighting leds
    buf[2] = BIT_DIR;
    ftdi_write_data(ftdic2, buf, 3);
    buf[0] = SET_BITS_HIGH;
    buf[1] = 0x00; //lighting leds
    buf[2] = BIT_DIR;
    ftdi_write_data(ftdic2, buf, 3);
    buf[0] = SET_BITS_LOW;
    buf[1] = gpio;
    buf[2] = BIT_DIR; //releasing programming of FPGA
    ftdi_write_data(ftdic2, buf, 3);
    sleep(1);
    buf[0] = SET_BITS_LOW;
    buf[1] = 0xFF; //reseting design in FPGA
    buf[2] = BIT_DIR;
    ftdi_write_data(ftdic2, buf, 3);
    sleep(1);
    buf[0] = SET_BITS_LOW;
    buf[1] = 0xDD; //releasing reset
    buf[2] = BIT_DIR;
    ftdi_write_data(ftdic2, buf, 3);
    sleep(1);
    buf[0] = SET_BITS_HIGH;
    buf[1] = 0xFF; //lighting leds
    buf[2] = BIT_DIR;
    ftdi_write_data(ftdic2, buf, 3);
    
    if (ftdi_usb_purge_buffers(ftdic2))
    {
        throw Exception("Purging buffers failed\n");
    }
    ftdi_usb_close(ftdic2); // close channel 2
    ftdi_deinit(ftdic2); // close channel 2
    ftdic->usb_read_timeout = READ_TIMEOUT;
    ftdic->usb_write_timeout = WRITE_TIMEOUT;
    ftdi_read_data_set_chunksize(ftdic, chunkSizeRead);
    ftdi_write_data_set_chunksize(ftdic, chunkSizeWrite);
    
    if (ftdi_usb_reset(ftdic))
    {
        throw Exception("Reset failed\n");
    }
    usleep(1000);
    
    if(ftdi_usb_purge_buffers(ftdic) < 0)
    {
       throw Exception("Setting FT2232 synchronous bitmode failed\n");
    }
    if(ftdi_set_bitmode(ftdic, 0xFF, 0x00) < 0)
    {
       throw Exception("Setting FT2232 synchronous bitmode failed\n");
    }
    if(ftdi_set_bitmode(ftdic, 0xFF, 0x40) < 0) 
    {
        throw Exception("Setting FT2232 synchronous bitmode failed\n");
    }
    if (ftdi_set_latency_timer(ftdic, 2)) /* AN_130 */
    {
        throw Exception("Set latency failed failed\n");
    }
    //SetUSBParameters(ftHandle,0x10000, 0x10000);
    if (ftdi_setflowctrl(ftdic, SIO_RTS_CTS_HS)) // AN_130 
    {
        throw Exception("Set RTS_CTS failed\n");
    }
    /*if(ftdi_usb_purge_buffers(ftdic) < 0)
    {
        throw Exception("Setting FT2232 synchronous bitmode failed\n");
    }*/
    //fixes unalignment of first read (should be fixed in cleaner manner)
    usleep(400);
    unsigned char cleanup[10] = { 0xBB, 0xBB, 0xBB, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA };
    ftdi_write_data(ftdic, cleanup, 10);
    unsigned char recvbuf[4000];
    read(recvbuf);
}
Example #19
0
int sys_init()
{
	int ret, i;
	struct ftdi_device_list *devlist, *curdev;
	char manufacturer[128], description[128], serialno[128];

	if (ftdi_init(&ux400_ftdic) < 0)
	{
		fprintf(stderr, "ftdi_init failed\n");
		return EXIT_FAILURE;
	}

#if 0
	if ((ret = ftdi_usb_find_all(&ux400_ftdic, &devlist, UX400VENDOR, UX400PRODUCT)) < 0)
	{
		fprintf(stderr, "ftdi_usb_find_all failed: %d (%s)\n", ret, ftdi_get_error_string(&ux400_ftdic));
		return EXIT_FAILURE;
	}

	printf("Number of FTDI devices found: %d\n", ret);

	i = 0;
	for (curdev = devlist; curdev != NULL; i++)
	{
		printf("Checking device: %d\n", i);
		if ((ret = ftdi_usb_get_strings(&ux400_ftdic, curdev->dev, manufacturer, 128, description, 128, serialno, 128)) < 0)
		{
		    fprintf(stderr, "ftdi_usb_get_strings failed: %d (%s)\n", ret, ftdi_get_error_string(&ux400_ftdic));
		    return EXIT_FAILURE;
		}
		printf("Manufacturer: %s, Description: %s, Serial number: %s\n\n", manufacturer, description, serialno);
		curdev = curdev->next;
	}

	ftdi_list_free(&devlist);
#endif

	if((ret = ftdi_usb_open_desc(&ux400_ftdic, UX400VENDOR, UX400PRODUCT, UX400DES, UX400_LOCAL_SN)) < 0)
	{
	    fprintf(stderr, "ftdi_usb_open_desc failed: %d (%s)\n", ret, ftdi_get_error_string(&ux400_ftdic));
	    return EXIT_FAILURE;
	}

	if((ret = ftdi_usb_reset(&ux400_ftdic)) < 0)
	{
	    fprintf(stderr, "ftdi_usb_reset failed: %d (%s)\n", ret, ftdi_get_error_string(&ux400_ftdic));
	    return EXIT_FAILURE;
	}

	if((ret = ftdi_set_baudrate(&ux400_ftdic, 9600)) < 0)
	{
	    fprintf(stderr, "ftdi_set_baudrate failed: %d (%s)\n", ret, ftdi_get_error_string(&ux400_ftdic));
	    return EXIT_FAILURE;
	}

	if((ret = ftdi_set_bitmode(&ux400_ftdic, 0x00, BITMODE_RESET)) < 0)
	{
	    fprintf(stderr, "ftdi_set_bitmode failed: %d (%s)\n", ret, ftdi_get_error_string(&ux400_ftdic));
	    return EXIT_FAILURE;
	}

	usleep(10000);

	if((ret = ftdi_set_bitmode(&ux400_ftdic, 0x00, BITMODE_MCU)) < 0)
	{
	    fprintf(stderr, "ftdi_set_bitmode failed: %d (%s)\n", ret, ftdi_get_error_string(&ux400_ftdic));
	    return EXIT_FAILURE;
	}

	return 0;
}
Example #20
0
int FtdiDevice::reset() const
{
	return ( context_ != 0 ) ? ftdi_usb_reset( context_ ) : 0;
}
Example #21
0
File: spi.c Project: z80/bt-board
int spi_open(int nport)
{
    LOG(DEBUG, "(%d) spi_dev_open=%d", nport, spi_dev_open);

    if (spi_dev_open > 0) {
        LOG(WARN, "Superfluos call to spi_open()");
        return 0;
    }

    if (spi_nports == 0 || nport < spi_nports - 1) {
        SPI_ERR("No FTDI device found");
        goto open_err;
    }

#ifdef SPI_STATS
    memset(&spi_stats, 0, sizeof(spi_stats));
    if (gettimeofday(&spi_stats.tv_open_begin, NULL) < 0)
        LOG(WARN, "gettimeofday failed: %s", strerror(errno));
#endif

    /*ftdi_set_interface(&ftdic, INTERFACE_A);*/ /* XXX for multichannel chips */

    if (ftdi_usb_open_desc(&ftdic, spi_ports[nport].vid, spi_ports[nport].pid,
                NULL, spi_ports[nport].serial) < 0)
    {
        SPI_ERR("FTDI: ftdi_usb_open_desc() failed: %s", ftdi_get_error_string(&ftdic));
        goto open_err;
    }

    spi_dev_open++;

    LOG(INFO, "FTDI: using FTDI device: \"%s\"", spi_ports[nport].name);

    if (ftdi_usb_reset(&ftdic) < 0) {
        SPI_ERR("FTDI: reset failed: %s", ftdi_get_error_string(&ftdic));
        goto open_err;
    }

    if (ftdi_usb_purge_buffers(&ftdic) < 0) {
        SPI_ERR("FTDI: purge buffers failed: %s", ftdi_get_error_string(&ftdic));
        goto open_err;
    }

    /* Set 1 ms latency timer, see FTDI AN232B-04 */
    if (ftdi_set_latency_timer(&ftdic, 1) < 0) {
        SPI_ERR("FTDI: setting latency timer failed: %s", ftdi_get_error_string(&ftdic));
        goto open_err;
    }

    if (ftdi_set_bitmode(&ftdic, 0, BITMODE_RESET) < 0) {
        SPI_ERR("FTDI: reset bitmode failed: %s", ftdi_get_error_string(&ftdic));
        goto open_err;
    }

    if (ftdi_set_bitmode(&ftdic, PINS_OUTPUT, BITMODE_SYNCBB) < 0) {
        SPI_ERR("FTDI: set synchronous bitbang mode failed: %s", ftdi_get_error_string(&ftdic));
        goto open_err;
    }

    /*
     * Note on buffer sizes:
     *
     * FT232R has 256 byte receive buffer and 128 byte transmit buffer. It works
     * like 384 byte buffer. See:
     * http://developer.intra2net.com/mailarchive/html/libftdi/2011/msg00410.html
     * http://developer.intra2net.com/mailarchive/html/libftdi/2011/msg00413.html
     * http://jdelfes.blogspot.ru/2014/03/ft232r-bitbang-spi-part-2.html
     *
     * FT2232C has 128 byte TX and 384 byte RX buffers per channel.
     * FT2232H has 4kB RX and TX buffers per channel.
     * FT4232H has 2kB RX and TX buffers per channel.
     * FT232H has 1 kB RX and TX buffers.
     * FT230X has 512 byte TX and RX buffers.
     */
    switch (ftdic.type) {
        case TYPE_AM:
            ftdi_type_str = "FT232AM";
            SPI_ERR("This chip type is not supported: %s", ftdi_type_str);
            goto open_err;
            break;
        case TYPE_BM:
            ftdi_type_str = "FT232BM";
            SPI_ERR("This chip type is not supported: %s", ftdi_type_str);
            goto open_err;
            break;
        case TYPE_2232C:
            ftdi_type_str = "FT2232C/D";
            ftdi_buf_size = 512;
            break;
        case TYPE_R:
            ftdi_type_str = "FT232R";
            ftdi_buf_size = 384;
            break;
        case TYPE_2232H:
            ftdi_type_str = "FT2232H";
            ftdi_buf_size = 8192;
            break;
        case TYPE_4232H:
            ftdi_type_str = "FT4232H";
            ftdi_buf_size = 4096;
            break;
        case TYPE_232H:
            ftdi_type_str = "FT232H";
            ftdi_buf_size = 2048;
            break;
        /* TYPE_230X is supported since libftdi1-1.2 */
        /*case TYPE_230X:
            ftdi_type_str = "FT230X";
            ftdi_buf_size = 1024;
            break;
        */
        default:
            LOG(WARN, "Unknown FTDI chip type, assuming FT232R");
            ftdi_type_str = "Unknown";
            ftdi_buf_size = 384;
            break;
    }

    LOG(INFO, "Detected %s type programmer chip, buffer size: %u",
            ftdi_type_str, ftdi_buf_size);

    /* Initialize xfer buffer */
    ftdi_buf = malloc(ftdi_buf_size);
    if (ftdi_buf == NULL) {
        SPI_ERR("Not enough memory");
        goto open_err;
    }
    ftdi_buf_write_offset = 0;

    ftdi_pin_state = PINS_INIT;
    ftdi_buf[ftdi_buf_write_offset++] = ftdi_pin_state;

    return 0;

open_err:
    if (spi_dev_open > 0)
        ftdi_usb_close(&ftdic);
    spi_dev_open = 0;

    return -1;
}
Example #22
0
QList <DMXUSBWidget*> QLCFTDI::widgets()
{
    QList <DMXUSBWidget*> widgetList;
    quint32 input_id = 0;

    struct ftdi_context ftdi;

    ftdi_init(&ftdi);

#ifdef LIBFTDI1
    libusb_device *dev;
    libusb_device **devs;
    int i = 0;

    if (libusb_get_device_list(ftdi->usb_ctx, &devs) < 0)
    {
        qDebug() << "usb_find_devices() failed";
        ftdi_error_return(-5, "libusb_get_device_list() failed");
    }

    while ((dev = devs[i++]) != NULL)
    {
#else
    struct usb_bus *bus;
    struct usb_device *dev;

    usb_init();

    if (usb_find_busses() < 0)
    {
        qDebug() << "usb_find_busses() failed";
        return widgetList;
    }
    if (usb_find_devices() < 0)
    {
        qDebug() << "usb_find_devices() failed";
        return widgetList;
    }

    for (bus = usb_get_busses(); bus; bus = bus->next)
    {
      for (dev = bus->devices; dev; dev = dev->next)
      {
#endif
        Q_ASSERT(dev != NULL);

        // Skip non wanted devices
        if (dev->descriptor.idVendor != QLCFTDI::FTDIVID &&
            dev->descriptor.idVendor != QLCFTDI::ATMELVID)
                continue;

        if (dev->descriptor.idProduct != QLCFTDI::FTDIPID &&
            dev->descriptor.idProduct != QLCFTDI::DMX4ALLPID &&
            dev->descriptor.idProduct != QLCFTDI::NANODMXPID)
                continue;

        char ser[256];
        char nme[256];
        char vend[256];

        ftdi_usb_get_strings(&ftdi, dev, vend, 256, nme, 256, ser, 256);

        QString serial(ser);
        QString name(nme);
        QString vendor(vend);

        QMap <QString,QVariant> types(typeMap());

        qDebug() << Q_FUNC_INFO << "DMX USB VID:" << QString::number(dev->descriptor.idVendor, 16) <<
                    "PID:" << QString::number(dev->descriptor.idProduct, 16);
        qDebug() << Q_FUNC_INFO << "DMX USB serial: " << serial << "name:" << name << "vendor:" << vendor;

        if (types.contains(serial) == true)
        {
            // Force a widget with a specific serial to either type
            DMXUSBWidget::Type type = (DMXUSBWidget::Type) types[serial].toInt();
            switch (type)
            {
            case DMXUSBWidget::OpenTX:
                widgetList << new EnttecDMXUSBOpen(serial, name, vendor);
                break;
            case DMXUSBWidget::ProRX:
            {
                EnttecDMXUSBProRX* prorx = new EnttecDMXUSBProRX(serial, name, vendor, input_id++);
                widgetList << prorx;
                break;
            }
            case DMXUSBWidget::ProMk2:
            {
                EnttecDMXUSBProTX* protx = new EnttecDMXUSBProTX(serial, name, vendor, 1);
                widgetList << protx;
                widgetList << new EnttecDMXUSBProTX(serial, name, vendor, 2, protx->ftdi());
                EnttecDMXUSBProRX* prorx = new EnttecDMXUSBProRX(serial, name, vendor, input_id++, protx->ftdi());
                widgetList << prorx;
                break;
            }
            case DMXUSBWidget::UltraProTx:
            {
                UltraDMXUSBProTx* protx = new UltraDMXUSBProTx(serial, name, vendor, 1);
                widgetList << protx;
                widgetList << new UltraDMXUSBProTx(serial, name, vendor, 2, protx->ftdi());
                EnttecDMXUSBProRX* prorx = new EnttecDMXUSBProRX(serial, name, vendor, input_id++, protx->ftdi());
                widgetList << prorx;
                break;
            }
            case DMXUSBWidget::VinceTX:
                widgetList << new VinceUSBDMX512TX(serial, name, vendor);
                break;
            default:
            case DMXUSBWidget::ProTX:
                widgetList << new EnttecDMXUSBProTX(serial, name, vendor);
                break;
            }
        }
        else if (name.toUpper().contains("PRO MK2") == true)
        {
            EnttecDMXUSBProTX* protx = new EnttecDMXUSBProTX(serial, name, vendor, 1);
            widgetList << protx;
            widgetList << new EnttecDMXUSBProTX(serial, name, vendor, 2, protx->ftdi());
            EnttecDMXUSBProRX* prorx = new EnttecDMXUSBProRX(serial, name, vendor, input_id++, protx->ftdi());
            widgetList << prorx;
        }
        else if (name.toUpper().contains("DMX USB PRO"))
        {
            /** Check if the device responds to label 77 and 78, so it might be a DMXking adapter */
            int ESTAID = 0;
            int DEVID = 0;
            QString manName = readLabel(&ftdi, name.toLatin1().data(), serial.toLatin1().data(),
                                        USB_DEVICE_MANUFACTURER, &ESTAID);
            qDebug() << "--------> Device Manufacturer: " << manName;
            QString devName = readLabel(&ftdi, name.toLatin1().data(), serial.toLatin1().data(),
                                        USB_DEVICE_NAME, &DEVID);
            qDebug() << "--------> Device Name: " << devName;
            qDebug() << "--------> ESTA Code: " << QString::number(ESTAID, 16) << ", Device ID: " << QString::number(DEVID, 16);
            if (ESTAID == DMXKING_ESTA_ID)
            {
                if (DEVID == ULTRADMX_PRO_DEV_ID)
                {
                    UltraDMXUSBProTx* protxP1 = new UltraDMXUSBProTx(serial, name, vendor, 1);
                    protxP1->setRealName(devName);
                    widgetList << protxP1;
                    UltraDMXUSBProTx* protxP2 = new UltraDMXUSBProTx(serial, name, vendor, 2, protxP1->ftdi());
                    protxP2->setRealName(devName);
                    widgetList << protxP2;
                    EnttecDMXUSBProRX* prorx = new EnttecDMXUSBProRX(serial, name, vendor, input_id++, protxP1->ftdi());
                    prorx->setRealName(devName);
                    widgetList << prorx;
                }
                else
                {
                    EnttecDMXUSBProTX* protx = new EnttecDMXUSBProTX(serial, name, vendor);
                    protx->setRealName(devName);
                    widgetList << protx;
                }
            }
            else
            {
                /* This is probably a Enttec DMX USB Pro widget */
                EnttecDMXUSBProTX* protx = new EnttecDMXUSBProTX(serial, name, vendor);
                widgetList << protx;
                EnttecDMXUSBProRX* prorx = new EnttecDMXUSBProRX(serial, name, vendor, input_id++, protx->ftdi());
                widgetList << prorx;
            }
        }
        else if (name.toUpper().contains("USB-DMX512 CONVERTER") == true)
        {
            widgetList << new VinceUSBDMX512TX(serial, name, vendor);
        }
        else if (dev->descriptor.idVendor == QLCFTDI::FTDIVID &&
                 dev->descriptor.idProduct == QLCFTDI::DMX4ALLPID)
        {
            widgetList << new Stageprofi(serial, name, vendor);
        }
#if defined(Q_WS_X11) || defined(Q_OS_LINUX)
        else if (dev->descriptor.idVendor == QLCFTDI::ATMELVID &&
                 dev->descriptor.idProduct == QLCFTDI::NANODMXPID)
        {
            widgetList << new NanoDMX(serial, name, vendor);
        }
#endif
        else
        {
            /* This is probably an Open DMX USB widget */
            widgetList << new EnttecDMXUSBOpen(serial, name, vendor, 0);
        }
#ifndef LIBFTDI1
      }
#endif
    }

#ifdef LIBFTDI1
    libusb_free_device_list(devs, 1);
#endif

    ftdi_deinit(&ftdi);
    return widgetList;
}

bool QLCFTDI::open()
{
    if (m_openCount < m_refCount)
        m_openCount++;

    if (isOpen() == true)
        return true;

    if (ftdi_usb_open_desc(&m_handle, QLCFTDI::FTDIVID, QLCFTDI::FTDIPID,
                           name().toLatin1(), serial().toLatin1()) < 0)
    {
        qWarning() << Q_FUNC_INFO << name() << ftdi_get_error_string(&m_handle);
        return false;
    }
    else
    {
        return true;
    }
}

bool QLCFTDI::openByPID(const int PID)
{
    if (m_openCount < m_refCount)
        m_openCount++;

    if (isOpen() == true)
        return true;

    if (ftdi_usb_open(&m_handle, QLCFTDI::FTDIVID, PID) < 0)
    {
        qWarning() << Q_FUNC_INFO << name() << ftdi_get_error_string(&m_handle);
        return false;
    }
    else
    {
        return true;
    }
}

bool QLCFTDI::close()
{
    if (m_openCount > 1)
    {
        m_openCount--;
        return true;
    }

    if (ftdi_usb_close(&m_handle) < 0)
    {
        qWarning() << Q_FUNC_INFO << name() << ftdi_get_error_string(&m_handle);
        return false;
    }
    else
    {
        return true;
    }
}

bool QLCFTDI::isOpen() const
{
    return (m_handle.usb_dev != NULL) ? true : false;
}

bool QLCFTDI::reset()
{
    if (ftdi_usb_reset(&m_handle) < 0)
    {
        qWarning() << Q_FUNC_INFO << name() << ftdi_get_error_string(&m_handle);
        return false;
    }
    else
    {
        return true;
    }
}

bool QLCFTDI::setLineProperties()
{
    if (ftdi_set_line_property(&m_handle, BITS_8, STOP_BIT_2, NONE) < 0)
    {
        qWarning() << Q_FUNC_INFO << name() << ftdi_get_error_string(&m_handle);
        return false;
    }
    else
    {
        return true;
    }
}

bool QLCFTDI::setBaudRate()
{
    if (ftdi_set_baudrate(&m_handle, 250000) < 0)
    {
        qWarning() << Q_FUNC_INFO << name() << ftdi_get_error_string(&m_handle);
        return false;
    }
    else
    {
        return true;
    }
}

bool QLCFTDI::setFlowControl()
{
    if (ftdi_setflowctrl(&m_handle, SIO_DISABLE_FLOW_CTRL) < 0)
    {
        qWarning() << Q_FUNC_INFO << name() << ftdi_get_error_string(&m_handle);
        return false;
    }
    else
    {
        return true;
    }
}

bool QLCFTDI::clearRts()
{
    if (ftdi_setrts(&m_handle, 0) < 0)
    {
        qWarning() << Q_FUNC_INFO << name() << ftdi_get_error_string(&m_handle);
        return false;
    }
    else
    {
        return true;
    }
}

bool QLCFTDI::purgeBuffers()
{
    if (ftdi_usb_purge_buffers(&m_handle) < 0)
    {
        qWarning() << Q_FUNC_INFO << name() << ftdi_get_error_string(&m_handle);
        return false;
    }
    else
    {
        return true;
    }
}

bool QLCFTDI::setBreak(bool on)
{
    ftdi_break_type type;
    if (on == true)
        type = BREAK_ON;
    else
        type = BREAK_OFF;

    if (ftdi_set_line_property2(&m_handle, BITS_8, STOP_BIT_2, NONE, type) < 0)
    {
        qWarning() << Q_FUNC_INFO << name() << ftdi_get_error_string(&m_handle);
        return false;
    }
    else
    {
        return true;
    }
}
Example #23
0
static int presto_open_libftdi(char *req_serial)
{
	uint8_t presto_data;

	LOG_DEBUG("searching for PRESTO using libftdi");

	/* initialize FTDI context structure */
	if (ftdi_init(&presto->ftdic) < 0) {
		LOG_ERROR("unable to init libftdi: %s", presto->ftdic.error_str);
		return ERROR_JTAG_DEVICE_ERROR;
	}

	/* context, vendor id, product id */
	if (ftdi_usb_open_desc(&presto->ftdic, PRESTO_VID, PRESTO_PID, NULL, req_serial) < 0) {
		LOG_ERROR("unable to open PRESTO: %s", presto->ftdic.error_str);
		return ERROR_JTAG_DEVICE_ERROR;
	}

	if (ftdi_usb_reset(&presto->ftdic) < 0) {
		LOG_ERROR("unable to reset PRESTO device");
		return ERROR_JTAG_DEVICE_ERROR;
	}

	if (ftdi_set_latency_timer(&presto->ftdic, 1) < 0) {
		LOG_ERROR("unable to set latency timer");
		return ERROR_JTAG_DEVICE_ERROR;
	}

	if (ftdi_usb_purge_buffers(&presto->ftdic) < 0) {
		LOG_ERROR("unable to purge PRESTO buffers");
		return ERROR_JTAG_DEVICE_ERROR;
	}

	presto_data = 0xD0;
	if (presto_write(&presto_data, 1) != ERROR_OK) {
		LOG_ERROR("error writing to PRESTO");
		return ERROR_JTAG_DEVICE_ERROR;
	}

	if (presto_read(&presto_data, 1) != ERROR_OK) {
		LOG_DEBUG("no response from PRESTO, retrying");

		if (ftdi_usb_purge_buffers(&presto->ftdic) < 0)
			return ERROR_JTAG_DEVICE_ERROR;

		presto_data = 0xD0;
		if (presto_write(&presto_data, 1) != ERROR_OK)
			return ERROR_JTAG_DEVICE_ERROR;

		if (presto_read(&presto_data, 1) != ERROR_OK) {
			LOG_ERROR("no response from PRESTO, giving up");
			return ERROR_JTAG_DEVICE_ERROR;
		}
	}

	if (presto_write(presto_init_seq, sizeof(presto_init_seq)) != ERROR_OK) {
		LOG_ERROR("error writing PRESTO init sequence");
		return ERROR_JTAG_DEVICE_ERROR;
	}

	return ERROR_OK;
}
Example #24
0
int Dionysus::reset(){
  if (this->debug) printf ("Dionysus: Reset FTDI\n");
  return ftdi_usb_reset(this->ftdi);
}
Example #25
0
int nifalcon_load_firmware(falcon_device* dev, const char* firmware_filename)
{
	unsigned int bytes_written, bytes_read;
	unsigned char check_msg_1_send[3] = {0x0a, 0x43, 0x0d};
	unsigned char check_msg_1_recv[4] = {0x0a, 0x44, 0x2c, 0x0d};
	unsigned char check_msg_2[1] = {0x41};
	unsigned char send_buf[128], receive_buf[128];
	FILE* firmware_file;
	int k;
	if(!dev->is_initialized) nifalcon_error_return(NIFALCON_DEVICE_NOT_VALID_ERROR, "tried to load firmware on an uninitialized device");
	if(!dev->is_open) nifalcon_error_return(NIFALCON_DEVICE_NOT_FOUND_ERROR, "tried to load firmware on an unopened device");
  
	//Clear out current buffers to make sure we have a fresh start
	if((dev->falcon_status_code = ftdi_usb_purge_buffers(&(dev->falcon))) < 0) return dev->falcon_status_code;

	//Reset the device
	if((dev->falcon_status_code = ftdi_usb_reset(&(dev->falcon))) < 0) return dev->falcon_status_code;

	//Make sure our latency timer is at 16ms, otherwise firmware checks tend to always fail
	if((dev->falcon_status_code = ftdi_set_latency_timer(&(dev->falcon), 16)) < 0) return dev->falcon_status_code;
	
	//Set to:
	// 9600 baud
	// 8n1
	// No Flow Control
	// RTS Low
	// DTR High	
	if((dev->falcon_status_code = ftdi_set_baudrate(&(dev->falcon), 9600)) < 0) return dev->falcon_status_code;
	if((dev->falcon_status_code = ftdi_set_line_property(&(dev->falcon), BITS_8, STOP_BIT_1, NONE)) < 0) return dev->falcon_status_code;
	if((dev->falcon_status_code = ftdi_setflowctrl(&(dev->falcon), SIO_DISABLE_FLOW_CTRL)) < 0) return dev->falcon_status_code;
	if((dev->falcon_status_code = ftdi_setrts(&(dev->falcon), 0)) < 0) return dev->falcon_status_code;
	if((dev->falcon_status_code = ftdi_setdtr(&(dev->falcon), 0)) < 0) return dev->falcon_status_code;
	if((dev->falcon_status_code = ftdi_setdtr(&(dev->falcon), 1)) < 0) return dev->falcon_status_code;
	//Send 3 bytes: 0x0a 0x43 0x0d

	if((dev->falcon_status_code = nifalcon_write(dev, check_msg_1_send, 3)) < 0) return dev->falcon_status_code;
	if((dev->falcon_status_code = nifalcon_read(dev, receive_buf, 4, 1000)) < 0) return dev->falcon_status_code;
	
	//Set to:
	// DTR Low
	// 140000 baud (0x15 clock ticks per signal)
	if((dev->falcon_status_code = ftdi_setdtr(&(dev->falcon),0)) < 0) return dev->falcon_status_code;
	if((dev->falcon_status_code = ftdi_set_baudrate(&(dev->falcon), 140000)) < 0) return dev->falcon_status_code;

	//Send "A" character
	if((dev->falcon_status_code = nifalcon_write(dev, check_msg_2, 1)) < 0) return dev->falcon_status_code;

	//Expect back 2 bytes:
	// 0x13 0x41
	if((dev->falcon_status_code = nifalcon_read(dev, receive_buf, 2, 1000)) < 0) return dev->falcon_status_code;
	
	firmware_file = fopen(firmware_filename, "rb");

	if(!firmware_file)
	{
		nifalcon_error_return(NIFALCON_FIRMWARE_NOT_FOUND_ERROR, "cannot find falcon firmware file");
	}

	while(!feof(firmware_file))
	{
		int firmware_bytes_read;
		int i;
		firmware_bytes_read = fread(send_buf, 1, 128, firmware_file);
		if((dev->falcon_status_code = nifalcon_write(dev, send_buf, firmware_bytes_read)) < 0) return dev->falcon_status_code;
		if((dev->falcon_status_code = nifalcon_read(dev, receive_buf, firmware_bytes_read, 1000)) < firmware_bytes_read)
		{			
			nifalcon_error_return(NIFALCON_FIRMWARE_CHECKSUM_ERROR, "error sending firmware (firmware send step, 128 byte reply not received)");
		}
		for(i = 0; i < firmware_bytes_read; ++i)
		{
			if(send_buf[i] != receive_buf[i])
			{
				nifalcon_error_return(NIFALCON_FIRMWARE_CHECKSUM_ERROR, "error sending firmware (firmware send step, checksum does not match)");
			}
		}
		if(firmware_bytes_read < 128) break;
	}
	fclose(firmware_file);

	//VERY IMPORTANT
	//If we do not reset latency to 1ms, then we either have to fill the FTDI butter (64bytes) or wait 16ms
	//to get any data back. This is what was causing massive slowness in pre-1.0 releases
	if((dev->falcon_status_code = ftdi_set_latency_timer(&(dev->falcon), 1)) < 0) return dev->falcon_status_code;

	//Shift to full speed
	if((dev->falcon_status_code = ftdi_set_baudrate(&(dev->falcon), 1456312)) < 0) return dev->falcon_status_code;

	return 0;
}
Example #26
0
int Context::reset()
{
    return ftdi_usb_reset(d->ftdi);
}
Example #27
0
//
// Open the serial port.
// Initialise ftdi_context and use it to open the device
static dc_status_t serial_ftdi_open (void **io, dc_context_t *context)
{
	INFO(0, "serial_ftdi_open called");
	// Allocate memory.
	ftdi_serial_t *device = (ftdi_serial_t *) malloc (sizeof (ftdi_serial_t));
	if (device == NULL) {
		INFO(0, "couldn't allocate memory");
		SYSERROR (context, errno);
		return DC_STATUS_NOMEMORY;
	}
	INFO(0, "setting up ftdi_ctx");
	struct ftdi_context *ftdi_ctx = ftdi_new();
	if (ftdi_ctx == NULL) {
		INFO(0, "failed ftdi_new()");
		free(device);
		SYSERROR (context, errno);
		return DC_STATUS_NOMEMORY;
	}

	// Library context.
	//device->context = context;

	// Default to blocking reads.
	device->timeout = -1;

	// Default to full-duplex.
	device->baudrate = 0;
	device->nbits = 0;
	device->databits = 0;
	device->stopbits = 0;
	device->parity = 0;

	// Initialize device ftdi context
	INFO(0, "initialize ftdi_ctx");
	ftdi_init(ftdi_ctx);

	if (ftdi_set_interface(ftdi_ctx,INTERFACE_ANY)) {
		free(device);
		ERROR (context, "%s", ftdi_get_error_string(ftdi_ctx));
		return DC_STATUS_IO;
	}

	INFO(0, "call serial_ftdi_open_device");
	if (serial_ftdi_open_device(ftdi_ctx) < 0) {
		free(device);
		ERROR (context, "%s", ftdi_get_error_string(ftdi_ctx));
		return DC_STATUS_IO;
	}

	if (ftdi_usb_reset(ftdi_ctx)) {
		free(device);
		ERROR (context, "%s", ftdi_get_error_string(ftdi_ctx));
		return DC_STATUS_IO;
	}

	if (ftdi_usb_purge_buffers(ftdi_ctx)) {
		free(device);
		ERROR (context, "%s", ftdi_get_error_string(ftdi_ctx));
		return DC_STATUS_IO;
	}

	device->ftdi_ctx = ftdi_ctx;

	*io = device;

	return DC_STATUS_SUCCESS;
}
Example #28
0
QList<DMXInterface *> LibFTDIInterface::interfaces(QList<DMXInterface *> discoveredList)
{
    QList <DMXInterface*> interfacesList;
    int id = 0;

    struct ftdi_context ftdi;

    ftdi_init(&ftdi);

#ifdef LIBFTDI1
    libusb_device *dev;
    libusb_device **devs;
    struct libusb_device_descriptor dev_descriptor;
    int i = 0;

    if (libusb_get_device_list(ftdi.usb_ctx, &devs) < 0)
    {
        qDebug() << "usb_find_devices() failed";
        return interfacesList;
    }

    while ((dev = devs[i++]) != NULL)
    {
        libusb_get_device_descriptor(dev, &dev_descriptor);
#else
    struct usb_bus *bus;
    struct usb_device *dev;
    struct usb_device_descriptor dev_descriptor;

    usb_init();

    if (usb_find_busses() < 0)
    {
        qDebug() << "usb_find_busses() failed";
        return interfacesList;
    }
    if (usb_find_devices() < 0)
    {
        qDebug() << "usb_find_devices() failed";
        return interfacesList;
    }

    for (bus = usb_get_busses(); bus; bus = bus->next)
    {
      for (dev = bus->devices; dev; dev = dev->next)
      {
        dev_descriptor = dev->descriptor;
#endif
        Q_ASSERT(dev != NULL);

        // Skip non wanted devices
        if (validInterface(dev_descriptor.idVendor, dev_descriptor.idProduct) == false)
            continue;

        char ser[256];
        memset(ser, 0, 256);
        char nme[256];
        char vend[256];

        ftdi_usb_get_strings(&ftdi, dev, vend, 256, nme, 256, ser, 256);

        QString serial(ser);
        QString name(nme);
        QString vendor(vend);

        qDebug() << Q_FUNC_INFO << "DMX USB VID:" << QString::number(dev_descriptor.idVendor, 16) <<
                    "PID:" << QString::number(dev_descriptor.idProduct, 16);
        qDebug() << Q_FUNC_INFO << "DMX USB serial: " << serial << "name:" << name << "vendor:" << vendor;

        bool found = false;
        for (int c = 0; c < discoveredList.count(); c++)
        {
            if (discoveredList.at(c)->checkInfo(serial, name, vendor) == true)
            {
                found = true;
                break;
            }
        }
        if (found == false)
        {
            LibFTDIInterface *iface = new LibFTDIInterface(serial, name, vendor, dev_descriptor.idVendor,
                                                           dev_descriptor.idProduct, id++);
#ifdef LIBFTDI1
            iface->setBusLocation(libusb_get_port_number(dev));
#else
            iface->setBusLocation(dev->bus->location);
#endif
            interfacesList << iface;
        }

#ifndef LIBFTDI1
      }
#endif
    }

#ifdef LIBFTDI1
    libusb_free_device_list(devs, 1);
#endif

    ftdi_deinit(&ftdi);

    return interfacesList;
}

bool LibFTDIInterface::open()
{
    if (isOpen() == true)
        return true;

    QByteArray sba = serial().toLatin1();
    const char *ser = NULL;
    if (serial().isEmpty() == false)
        ser = (const char *)sba.data();

    if (ftdi_usb_open_desc(&m_handle, vendorID(), productID(),
                           name().toLatin1(), ser) < 0)
    {
        qWarning() << Q_FUNC_INFO << name() << ftdi_get_error_string(&m_handle);
        return false;
    }
    else
    {
        return true;
    }
}

bool LibFTDIInterface::openByPID(const int PID)
{
    if (isOpen() == true)
        return true;

    if (ftdi_usb_open(&m_handle, DMXInterface::FTDIVID, PID) < 0)
    {
        qWarning() << Q_FUNC_INFO << name() << ftdi_get_error_string(&m_handle);
        return false;
    }
    else
    {
        return true;
    }
}

bool LibFTDIInterface::close()
{
    if (ftdi_usb_close(&m_handle) < 0)
    {
        qWarning() << Q_FUNC_INFO << name() << ftdi_get_error_string(&m_handle);
        return false;
    }
    else
    {
        return true;
    }
}

bool LibFTDIInterface::isOpen() const
{
    return (m_handle.usb_dev != NULL) ? true : false;
}

bool LibFTDIInterface::reset()
{
    if (ftdi_usb_reset(&m_handle) < 0)
    {
        qWarning() << Q_FUNC_INFO << name() << ftdi_get_error_string(&m_handle);
        return false;
    }
    else
    {
        return true;
    }
}

bool LibFTDIInterface::setLineProperties()
{
    if (ftdi_set_line_property(&m_handle, BITS_8, STOP_BIT_2, NONE) < 0)
    {
        qWarning() << Q_FUNC_INFO << name() << ftdi_get_error_string(&m_handle);
        return false;
    }
    else
    {
        return true;
    }
}

bool LibFTDIInterface::setBaudRate()
{
    if (ftdi_set_baudrate(&m_handle, 250000) < 0)
    {
        qWarning() << Q_FUNC_INFO << name() << ftdi_get_error_string(&m_handle);
        return false;
    }
    else
    {
        return true;
    }
}

bool LibFTDIInterface::setFlowControl()
{
    if (ftdi_setflowctrl(&m_handle, SIO_DISABLE_FLOW_CTRL) < 0)
    {
        qWarning() << Q_FUNC_INFO << name() << ftdi_get_error_string(&m_handle);
        return false;
    }
    else
    {
        return true;
    }
}

bool LibFTDIInterface::clearRts()
{
    if (ftdi_setrts(&m_handle, 0) < 0)
    {
        qWarning() << Q_FUNC_INFO << name() << ftdi_get_error_string(&m_handle);
        return false;
    }
    else
    {
        return true;
    }
}

bool LibFTDIInterface::purgeBuffers()
{
    if (ftdi_usb_purge_buffers(&m_handle) < 0)
    {
        qWarning() << Q_FUNC_INFO << name() << ftdi_get_error_string(&m_handle);
        return false;
    }
    else
    {
        return true;
    }
}

bool LibFTDIInterface::setBreak(bool on)
{
    ftdi_break_type type;
    if (on == true)
        type = BREAK_ON;
    else
        type = BREAK_OFF;

    if (ftdi_set_line_property2(&m_handle, BITS_8, STOP_BIT_2, NONE, type) < 0)
    {
        qWarning() << Q_FUNC_INFO << name() << ftdi_get_error_string(&m_handle);
        return false;
    }
    else
    {
        return true;
    }
}
Example #29
0
int main(int argc, char **argv)
{
	struct ftdi_context ftdi;
	uint8_t buf[4];
	uint8_t conf_buf[] = {SET_BITS_LOW,  0x08, 0x0b,
			      SET_BITS_HIGH, 0x00, 0x00,
			      TCK_DIVISOR,   0x00, 0x00,
			      LOOPBACK_END};

	if (argc < 2) {
		usage(argv[0]);
		return 1;
	}

	if (strcmp (argv[1], "idcode") && strcmp (argv[1], "reset") &&
	    strcmp (argv[1], "load")  && strcmp (argv[1], "readreg") &&
	    strcmp (argv[1], "read") && strcmp (argv[1], "write")
		) {
		usage(argv[0]);
		return 1;
	}

	/* Init */
	ftdi_init(&ftdi);
	if (ftdi_usb_open_desc(&ftdi, VENDOR, PRODUCT, 0, 0) < 0) {
		fprintf(stderr,
			"Can't open device %04x:%04x\n", VENDOR, PRODUCT);
		return 1;
	}
	ftdi_usb_reset(&ftdi);
	ftdi_set_interface(&ftdi, INTERFACE_A);
	ftdi_set_latency_timer(&ftdi, 1);
	ftdi_set_bitmode(&ftdi, 0xfb, BITMODE_MPSSE);
	if (ftdi_write_data(&ftdi, conf_buf, 10) != 10) {
		fprintf(stderr,
			"Can't configure device %04x:%04x\n", VENDOR, PRODUCT);
		return 1;
	}

	buf[0] = GET_BITS_LOW;
	buf[1] = SEND_IMMEDIATE;

	if (ftdi_write_data(&ftdi, buf, 2) != 2) {
		fprintf(stderr,
			"Can't send command to device\n");
		return 1;
	}
	ftdi_read_data(&ftdi, &buf[2], 1);
	if (!(buf[2] & 0x10)) {
		fprintf(stderr,
			"Vref not detected. Please power on target board\n");
		return 1;
	}

	if (!strcmp(argv[1], "idcode")) {
		uint8_t out[4];
		tap_reset_rti(&ftdi);
		tap_shift_dr_bits(&ftdi, NULL, 32, out);
		rev_dump(out, 4);
		printf("\n");
	}

	if (!strcmp (argv[1], "reset"))
		brd_reset(&ftdi);

	if (!strcmp (argv[1], "load")) {
		int i;
		struct load_bits *bs;
		FILE *fp;
		uint8_t *dr_data;
		uint32_t u;

		if(argc < 3) {
			usage(argv[0]);
			goto exit;
		}

		if (!strcmp(argv[2], "-"))
			fp = stdin;
		else {
			fp = fopen(argv[2], "r");
			if (!fp) {
				perror("Unable to open file");
				goto exit;
			}
		}

		bs = calloc(1, sizeof(*bs));
		if (!bs) {
			perror("memory allocation failed");
			goto exit;
		}

		if (load_bits(fp, bs) != 0) {
			fprintf(stderr, "%s not supported\n", argv[2]);
			goto free_bs;
		}

		printf("Bitstream information:\n");
		printf("\tDesign: %s\n", bs->design);
		printf("\tPart name: %s\n", bs->part_name);
		printf("\tDate: %s\n", bs->date);
		printf("\tTime: %s\n", bs->time);
		printf("\tBitstream length: %d\n", bs->length);

		/* copy data into shift register */
		dr_data = calloc(1, bs->length);
		if (!dr_data) {
			perror("memory allocation failed");
			goto free_bs;
		}

		for (u = 0; u < bs->length; u++)
			dr_data[u] = rev8(bs->data[u]);

		brd_reset(&ftdi);

		tap_shift_ir(&ftdi, CFG_IN);
		tap_shift_dr_bits(&ftdi, dr_data, bs->length * 8, NULL);

		/* ug380.pdf
		 * P161: a minimum of 16 clock cycles to the TCK */
		tap_shift_ir(&ftdi, JSTART);
		for (i = 0; i < 32; i++)
			tap_tms(&ftdi, 0, 0);

		tap_reset_rti(&ftdi);

		free(dr_data);
	free_bs:
		bits_free(bs);
		fclose(fp);
	}

	if (!strcmp(argv[1], "readreg") && argc == 3) {
		int i;
		char *err;
		uint8_t reg;
		uint8_t out[2];
		uint8_t dr_in[14];

		uint8_t in[14] = {
			0xaa, 0x99, 0x55, 0x66,
			0x00, 0x00, 0x20, 0x00,
			0x20, 0x00, 0x20, 0x00,
			0x20, 0x00
		};

		uint16_t cmd = 0x2801;	/* type 1 packet (word count = 1) */

		reg = strtol(argv[2], &err, 0);
		if((*err != 0x00) || (reg < 0) || (reg > 0x22)) {
			fprintf(stderr,
				"Invalid register, use a decimal or hexadecimal(0x...) number between 0x0 and 0x22\n");
			goto exit;
		}

		cmd |= ((reg & 0x3f) << 5);
		in[4] = (cmd & 0xff00) >> 8;
		in[5] = cmd & 0xff;

		tap_reset_rti(&ftdi);

		tap_tms(&ftdi, 1, 0);
		tap_tms(&ftdi, 1, 0);
		tap_tms(&ftdi, 0, 0);
		tap_tms(&ftdi, 0, 0);	/* Goto shift IR */

		tap_shift_ir_only(&ftdi, CFG_IN);

		tap_tms(&ftdi, 1, 0);
		tap_tms(&ftdi, 1, 0);
		tap_tms(&ftdi, 0, 0);
		tap_tms(&ftdi, 0, 0);	/* Goto SHIFT-DR */

		for (i = 0; i < 14; i++)
			dr_in[i] = rev8(in[i]);

		tap_shift_dr_bits_only(&ftdi, dr_in, 14 * 8, NULL);

		tap_tms(&ftdi, 1, 0);
		tap_tms(&ftdi, 1, 0);
		tap_tms(&ftdi, 1, 0);	/* Goto SELECT-IR */
		tap_tms(&ftdi, 0, 0);
		tap_tms(&ftdi, 0, 0);	/* Goto SHIFT-IR */

		tap_shift_ir_only(&ftdi, CFG_OUT);

		tap_tms(&ftdi, 1, 0);
		tap_tms(&ftdi, 1, 0);
		tap_tms(&ftdi, 0, 0);
		tap_tms(&ftdi, 0, 0);	/* Goto SHIFT-IR */

		tap_shift_dr_bits_only(&ftdi, NULL, 2 * 8, out);

		tap_tms(&ftdi, 1, 0);
		tap_tms(&ftdi, 1, 0);
		tap_tms(&ftdi, 1, 0);	/* Goto SELECT-IR */
		tap_tms(&ftdi, 0, 0);
		tap_tms(&ftdi, 0, 0);	/* Goto SHIFT-IR */

		tap_reset_rti(&ftdi);

		out[0] = rev8(out[0]);
		out[1] = rev8(out[1]);

		printf("REG[%d]: 0x%02x%02x\n", reg, out[0], out[1]);
	}
Example #30
0
// init serial communication device
bool CPlatform::initSerial(char*cPort, unsigned int baudrate)
{
// Windows
#ifdef WIN32
    if(hSerialPort != INVALID_HANDLE_VALUE) {
        CloseHandle(hSerialPort);
    }

    if(cPort == NULL) {
        cPort = STDSERIALWINDOWS;
    }

    hSerialPort = ::CreateFile(cPort, GENERIC_READ|GENERIC_WRITE, 0, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);

    if(hSerialPort == INVALID_HANDLE_VALUE) {
        CUtil::cout("initSerial: CreateFile() failed.\n", TEXT_ERROR);
        return false;
    }
    else {
        CUtil::cout("initSerial: Connected!\n", TEXT_ERROR);
    }

    COMMTIMEOUTS timeouts;
    GetCommTimeouts(hSerialPort, &timeouts);

    int a = 40; //40
    timeouts.ReadIntervalTimeout = a;
    timeouts.ReadTotalTimeoutMultiplier = 20;
    timeouts.ReadTotalTimeoutConstant = a;
    timeouts.WriteTotalTimeoutMultiplier = 20;
    timeouts.WriteTotalTimeoutConstant = a;

    SetCommTimeouts(hSerialPort, &timeouts);

    DCB dcb = {0};
    dcb.DCBlength = sizeof(DCB);

    if(!::GetCommState(hSerialPort, &dcb) ) {
        CUtil::cout("initSerial: GetCommState() failed.\n", TEXT_ERROR);
    }
    else {
        // 8bit, no parity, one stopbit
        dcb.BaudRate  = baudrate;
        dcb.ByteSize = 8;
        dcb.Parity = 0;
        dcb.StopBits = 0;

        if(!::SetCommState(hSerialPort, &dcb) ) {
            CUtil::cout("initSerial: SetCommState() failed.\n", TEXT_ERROR);
        }
    }

    return true;

// LINUX
#else
    if(cPort == NULL) {
        cPort = (char *)STDSERIALLINUX;
    }

#ifdef USE_FTDI

    /* Still testing */

    unsigned char  buf [1000];

    int a;
    int rsize;
    if (ftdi_init(&ftdi) < 0 )
        return false;
    int ret;

    if((ret = ftdi_usb_open(&ftdi, 0x0403, 0x6001)) < 0) {
        printf( "unable to open ftdi device: %d (%s)\n", ret, ftdi_get_error_string(&ftdi));
        return EXIT_FAILURE;
    }

    // Read out FTDIChip-ID of R type chips
    if (ftdi.type == TYPE_R) {
        unsigned int chipid;
        printf("ftdi_read_chipid: %d\n", ftdi_read_chipid(&ftdi, &chipid));
        printf("FTDI chipid: %X\n", chipid);
    }
    ftdi_read_data_set_chunksize(&ftdi, 4096);
    ftdi_write_data_set_chunksize(&ftdi, 4096);
    ftdi_set_line_property2(&ftdi, BITS_8, STOP_BIT_1, NONE, BREAK_OFF);
    ftdi_usb_reset (&ftdi);
    printf("baudrate: %d\n", ftdi_set_baudrate (&ftdi, baudrate));
    ftdi_setflowctrl(&ftdi, SIO_DISABLE_FLOW_CTRL);
    ftdi_set_latency_timer(&ftdi, 1);
    ftdi_usb_purge_buffers (&ftdi);

    printf (" Err : %s \n", ftdi.error_str);

    unsigned char nix[150];
    int j = 0;
    int cr;
    for (j = 0; j < 10; j++) {
        cr = ftdi_read_data (&ftdi, &nix[0], 100);
        printf (" %i \n", cr);
    }


    printf ("Typ: %d\n", ftdi.type);
    printf ("usb_read_timeout: %d\n", ftdi.usb_read_timeout);
    printf ("usb_write_timeout: %d\n",
            ftdi.usb_write_timeout);
    printf ("baudrate: %d\n",  ftdi.baudrate);
    printf ("bitbang_enabled: %x\n", ftdi.bitbang_enabled);
    printf ("bitbang_mode: %x\n", ftdi.bitbang_mode);

    return true;

    /* close handles */
    ftdi_usb_close(&ftdi);
    ftdi_deinit(&ftdi);
    return false;
#endif
    //system("stty -F /dev/ttyS0 speed 115200 raw cs8");

    fdSerialPort = open(cPort, O_RDWR | O_NOCTTY | O_NDELAY);// | O_NONBLOCK | O_NDELAY);
    if(fdSerialPort == -1) {
        CUtil::cout("initSerial: open() failed.\n", TEXT_ERROR);
        return false;
    }
    else {
        CUtil::cout("initSerial: Connected.\n", TEXT_ERROR);
    }

    clearLine();


#ifndef SERIALDONTINIT


    //fcntl(fdSerialPort, F_SETFL, FNDELAY);

    struct termios options;

    if(tcgetattr(fdSerialPort, &options) == -1) {
        CUtil::cout("initSerial: tvgetattr() failed.\n", TEXT_ERROR);
    }
    else {
        options.c_iflag = 0;
        options.c_oflag = 0;
        options.c_cflag = 0;
        options.c_lflag = 0;

        cfsetispeed(&options, getSpeedConstant(baudrate) );
        cfsetospeed(&options, getSpeedConstant(baudrate) );
        cfmakeraw(&options);

        options.c_cflag |= (CLOCAL | CREAD);

        // 8 bit, no parity, 1 stopbit
        options.c_cflag |= CS8;

        options.c_cflag &= ~CRTSCTS;
        options.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);


        // wait for 1 characters
        options.c_cc[VMIN]  = 1;
        // timeout 1 seconds
        options.c_cc[VTIME] = 1;

        /*
           cfsetispeed(&options, getSpeedConstant(baudrate));
           cfsetospeed(&options, getSpeedConstant(baudrate));

           //options.c_cflag = 0;
           options.c_cflag |= (getSpeedConstant(baudrate) | CLOCAL | CREAD);

           // 8 bit, no parity, 1 stopbit
           options.c_cflag |= CS8;

           options.c_cflag &= ~CRTSCTS;

           //options.c_lflag = 0;
           options.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);*/
        // testing -->

        // <-- testing

        /*
           // baudrate >> 1152000

           struct serial_struct nuts;
           int arby;
           if(ioctl(fdSerialPort, TIOCGSERIAL, &nuts) == -1)
           CUtil::cout( "Serial: ioctl(*,TIOCGSERIAL,*) failed.\n");

           nuts.custom_divisor = nuts.baud_base / 500000;

           if (!(nuts.custom_divisor))
           nuts.custom_divisor = 1;

           arby = nuts.baud_base / nuts.custom_divisor;
           nuts.flags &= ~ASYNC_SPD_MASK;
           nuts.flags |= ASYNC_SPD_CUST;

           if (ioctl(fdSerialPort, TIOCSSERIAL, &nuts) == -1)
           CUtil::cout("Serial: ioctl(*, TIOCSSERIAL, *) failed.\n");
           options.c_cflag |= B38400;

           // wait for 1 characters
           options.c_cc[VMIN]  = 1;
           // timeout 1 seconds
           options.c_cc[VTIME] = 1;
         */


        if(tcsetattr(fdSerialPort, TCSANOW, &options) != 0) {
            CUtil::cout("initSerial: tcsetattr() failed.\n", TEXT_ERROR);
        }
    }
#endif
    return true;

#endif
}