Exemplo n.º 1
0
// Read up to the specified number of bytes, return bytes actually read
u32 ser_read( int id, u8* dest, u32 maxsize )
{
  DWORD dwRxSize;
  FT_STATUS	ftStatus;
  DWORD dwBytesRead;

  if( ser_timeout == SER_INF_TIMEOUT ) {
    printf( "infinite timeout selected.\n" );
    FT_SetTimeouts(ftHandle[id], 10000000, 10000000); // a couple hours to timeout...
    dwRxSize = 0;
    ftStatus = FT_OK;
    while ((dwRxSize < maxsize) && (ftStatus == FT_OK)) {
      ftStatus = FT_GetQueueStatus(ftHandle[id], &dwRxSize);
    }

    if(ftStatus == FT_OK) {
      if((ftStatus = FT_Read(ftHandle[id], dest, maxsize, &dwBytesRead)) != FT_OK) {
	printf("Error FT_Read(%d)\n", ftStatus);
      }
      else {
	if( ser_dbg )
	  printf("FT_Read = %d\n", dwBytesRead);
      }
    }
    else {
      printf("Error FT_GetQueueStatus(%d)\n", ftStatus);
      return 0;
    }
    return (u32) dwBytesRead;
  }
  else
  {
  //  fd_set readfs;
  //  struct timeval tv;
  //  int retval;

    if( ser_timeout == 0 )
      ser_timeout = 1;
    //fprintf(stderr,"setting timeout to %u\n", ser_timeout );
    //fprintf(stderr,"read size: %d\n",maxsize);
    //fprintf(stderr,"id: %d\n",id);
    FT_SetTimeouts(ftHandle[id], ser_timeout, ser_timeout);

    if((ftStatus = FT_Read(ftHandle[id], dest, maxsize, &dwBytesRead)) != FT_OK) {
     // fprintf(stderr,"Error FT_Read(%d)\n", ftStatus);
    }
    else {
      ftStatus = FT_GetQueueStatus(ftHandle[id], &dwRxSize);

  	//  fprintf(stderr,"  - ser_read [%d | %02x] . %d\n", dwBytesRead, *dest & 0xFF, dwRxSize);
    }

    //fprintf(stderr,"read: %u\n",dwBytesRead);
    return (u32) dwBytesRead;
  }
}
Exemplo n.º 2
0
FT_STATUS ftdimut_init() {
  FT_STATUS ftStatus; 
  unsigned char buf[4];
  unsigned int bytesRead = 0;

  if(ftdimut_getData(0x17) != 0) {
    return FT_OK;
  }

  printf("Sending 0x00 at 5 baud\n");

  printf("Break on......\n");
  ftStatus = FT_SetBreakOn(ftHandle);
  if(ftStatus != FT_OK) return ftStatus;
  usleep(1800 * 1000);
  printf("Break off......\n");
  ftStatus = FT_SetBreakOff(ftHandle);
  if(ftStatus != FT_OK) return ftStatus;

  ftStatus = FT_Read(ftHandle, buf, 4, &bytesRead);
  if(ftStatus != FT_OK) return ftStatus;

  if(bytesRead == 4) {
    return FT_OK;
  }
  return FT_OTHER_ERROR;
}
Exemplo n.º 3
0
/*
 * Class:     kinetic_Kinetic1090Puck
 * Method:    puckRead
 * Signature: ()[I
 */
JNIEXPORT jintArray JNICALL Java_kinetic_Kinetic1090Puck_puckRead(JNIEnv *env, jobject obj)
{
    DWORD rxBytes;
    DWORD txBytes;
    DWORD eventDWord;
    DWORD bytesReturned;

	FT_STATUS ftStatus = FT_GetStatus(ftHandle, &rxBytes, &txBytes, &eventDWord);
	if(ftStatus != FT_OK) {
	    return (*env)->NewIntArray(env,0);
	}
	if(rxBytes == 0) {
	    return (*env)->NewIntArray(env,0);
	}

	if(rxBytes > 1024) {
	    rxBytes = 1024;
	}
	ftStatus = FT_Read(ftHandle, rxBuffer, rxBytes, &bytesReturned);

	jintArray outputArray = (*env)->NewIntArray(env, bytesReturned);
	jint *outputBody = (*env)->GetIntArrayElements(env, outputArray, 0);
	for(int i=0;i<bytesReturned;i++) {
	    outputBody[i] = (int)(rxBuffer[i]);
	}
    (*env)->ReleaseIntArrayElements(env, outputArray, outputBody, 0);

	return outputArray;
}
Exemplo n.º 4
0
void* ReadData(void* ptr)
{
	DeviceParams_t* device = (DeviceParams_t*)ptr;
	DWORD RxBytes;
	FT_STATUS status;

	printf("Thread Started\r\n");
	
	while(true)
	{
		WaitForData(device);

		status = FT_GetQueueStatus(device->handle, &RxBytes);
		if(status != FT_OK)
        {
            fprintf(stderr, "Can't read from ftdi device: %d\n", status);
            return NULL;
        }

        //printf("RX %s [%d]\r\n", device->serial, RxBytes);
        if(RxBytes > 0)
        {
        	DWORD BytesReceived;
        	char* data = new char[RxBytes];
        	
        	FT_Read(device->handle, data, RxBytes, &BytesReceived);
			
			fprintf(stderr, "%d Bytes Read\n", BytesReceived);
			delete[] data;
        }
	}

	return NULL;
} 
Exemplo n.º 5
0
bool CMmcUsbHndlBase::Read(void *pDataBuffer, unsigned int dNumberOfBytesToRead, unsigned int *pdNumberOfBytesRead)
{

	if( !AreLibraryFunctionsLoaded() )
    {
		perror("Library not loaded");
        return false;
    }

	FT_STATUS ftStatus = FT_Read(m_Handle, pDataBuffer, dNumberOfBytesToRead, (DWORD*)pdNumberOfBytesRead);

	if( ftStatus != FT_OK )
	{
		std::string errormsg = GetFtStatusDescription(ftStatus);
		errormsg += ":FT_Read";
		perror(errormsg.c_str());
		return false;
	}

	if( *pdNumberOfBytesRead <= 0 )
	{
		//perror("Read processed successfully, but number of read bytes is 0");
		return false;
	}

	return true;
}
Exemplo n.º 6
0
void FT232R_SPI::ftdi_spi_rw(unsigned char *write, unsigned char *read, int size){

    unsigned char * buffWrite = (unsigned char *)malloc((size+2)*((8*3)+3));
    unsigned char * buffRead = (unsigned char *)malloc((size+2)*((8*3)+3));
    int index = 0;


    state &= ~CSN;
    buffWrite[index++] = state;

    for(int i = 0; i < size; i++){
        index += ftdi_byte_encode(buffWrite+index, write[i]);
    }

    state |= CSN;
    buffWrite[index++] = state;


#ifdef _WIN32
    DWORD written = 0;
    FT_Write(ftHandle,(void*)buffWrite, index, &written);
    written = 0;
    FT_Read(ftHandle, (void*) buffRead, index, &written);
#elif __linux__
    unsigned int written = 0;
    written = ftdi_write_data(ftdi, (unsigned char*)buffWrite, index);
    ftdi_read_data(ftdi, (unsigned char*) buffRead, index);
#endif

    ftdi_spi_decode(buffRead, written, read);

    free(buffWrite);
    free(buffRead);

}
Exemplo n.º 7
0
void getSerialNumber( FT_HANDLE ftHandle )
{
  FT_STATUS status;
  char buf[80];
  char c;
  char *p;
  unsigned long nBytesWritten;
  unsigned long eventStatus;
  unsigned long nRxCnt;// Number of characters in receive queue
  unsigned long nTxCnt;// Number of characters in transmit queue

  memset( buf, 0, sizeof( buf ) );
  printf("Get serial number.\n");
  printf("==================\n");

  FT_Purge( ftHandle, FT_PURGE_RX | FT_PURGE_TX );

  sprintf( buf, "N\r" );
  if ( FT_OK != ( status = FT_Write( ftHandle, buf, strlen( buf ), &nBytesWritten ) ) ) {
    printf("Error: Failed to write command. return code = %d\n", status );
    return;
  }
  
  // Check if there is something to receive
  while ( 1 ){

    if ( FT_OK == FT_GetStatus( ftHandle, &nRxCnt, &nTxCnt, &eventStatus ) ) {
      
      // If there are characters to receive
      if ( nRxCnt ) {
	
	if ( FT_OK != ( status = FT_Read( ftHandle, buf, nRxCnt, &nBytesWritten ) ) ) {
	  printf("Error: Failed to read data. return code = %d\n", status );
	  return;
	}
	
	p = buf;
	while ( *p ) {
	  if ( 0x0d == *p ) {
	    *p = 0;
	    break;
	  }
	  p++;
	}
      
	printf( "Serial = %s \n", buf  );
	break;
	
      }
      
    }
    else {
      printf("Error: Failed to get status. return code = %d\n", status );
      return;
    }

  }
  
}
Exemplo n.º 8
0
extern "C" BOOL	ReadByteEx (BYTE *data, int timeout, BOOL warn)
{
	if(data == NULL)
		return FALSE;
	if (ParPort == -1)
	{
		DWORD BytesReceived = 0;
		FT_SetTimeouts(ftHandleA,timeout*1000,0);
		ftStatus = FT_Read(ftHandleA,RxBuffer,1,&BytesReceived);
		if (ftStatus == FT_OK)
		{
			if (BytesReceived == 1)
			{
				// FT_Read OK
				*data = RxBuffer[0];
				return TRUE;
			}
			else
			{
				// FT_Read Timeout
				if (warn)
					MessageBox(topHWnd, "USB Error: Read Timeout", "ReadByteEx", MB_OK | MB_ICONERROR);
				return FALSE;
			}
		}
		else
		{
			// FT_Read Failed
			if (warn)
				MessageBox(topHWnd, "USB Error: Read Failed", "ReadByteEx", MB_OK | MB_ICONERROR);
			return FALSE;
		}
	}
	else
	{
		BYTE a, b;
		time_t starttime = time(NULL);
		shadow |= 0x20;
		pwControl(shadow);	// set port to input mode
		b = prStatus();		// wait for ACK
		while (!((b ^ c) & 0x20))
		{
			b = prStatus();
			if (time(NULL) > starttime + (time_t)timeout)
			{
				if (warn)
					MessageBox(topHWnd, "Timeout on data transfer!", "ReadByte", MB_OK | MB_ICONERROR);
				return FALSE;
			}
		}
		c = b;
		a = prData();		// read data
		shadow ^= 0x02;
		pwControl(shadow);	// signal byte received
		*data = a;
		return TRUE;
	}
}
Exemplo n.º 9
0
/**
 *  Чтение данных с устройства
 */
int FtdiDevices::readData( char *data, DWORD size, unsigned int *rcnt ) {
  FT_STATUS ftStatus;
  DWORD     BytesReceived;

  QString msg = QString(" Исполнение операции чтения (READ)."\
                        " Дескриптор устройства = %1"\
                        " Размер = %2").arg( ( int )m_ftHandleA ).arg( size );

  /* Запись в лог сообщения */
  appLogger.sendDataToViewer( appLogger.INFO_MSG_TYPE, msg, appLogger.SYSTEM_LOGGER  );

  ftStatus = FT_SetTimeouts( m_ftHandleA, 100, 100 );
  if ( ftStatus != FT_OK ) {
    /* Запись в лог сообщения */
    appLogger.sendDataToViewer( appLogger.ERROR_MSG_TYPE,
                                                 " Операция установки таймаута не выполнена! ",
                                                 appLogger.SYSTEM_LOGGER );
  }
  else {
    /* Запись в лог сообщения */
    appLogger.sendDataToViewer( appLogger.INFO_MSG_TYPE,
                                                 " Операция установки таймаута выполнена! ",
                                                 appLogger.SYSTEM_LOGGER );
  }

  ftStatus = FT_Read( m_ftHandleA, data, size, &BytesReceived );

  /* Запись дампа пакета в лог */
  if ( BytesReceived != 0) {
    appLogger.sendDataToViewer( appLogger.INFO_MSG_TYPE, "Дамп ответа: ", appLogger.PROTOCOL_LOGGER );
    QString dump = "";
    for ( unsigned int i = 0; i < BytesReceived; i++ ) {
      dump += QString(" 0x%1 ").arg( (unsigned char)data[i], 0, 16 );
    }
    appLogger.sendDataToViewer( appLogger.INFO_MSG_TYPE, dump, appLogger.PROTOCOL_LOGGER );
  }
  *rcnt = BytesReceived;

  if ( ftStatus == FT_OK ) {
    if ( BytesReceived == size ) {
      /* Запись в лог сообщения */
        appLogger.sendDataToViewer( appLogger.INFO_MSG_TYPE,QString(" Все данные получены успешно! "), appLogger.SYSTEM_LOGGER );
      }
    else {
      /* Запись в лог сообщения */
        appLogger.sendDataToViewer( appLogger.WARNING_MSG_TYPE,QString(" Не все данные получены успешно! "), appLogger.SYSTEM_LOGGER );
        return FT_ERROR;
      }
    }
  else {
    /* Запись в лог сообщения */
      appLogger.sendDataToViewer( appLogger.ERROR_MSG_TYPE, QString(" Read выполнился с ошибкой! "), appLogger.SYSTEM_LOGGER );
      return FT_ERROR;
    }

  return FT_SUCCESSFUL;
}
Exemplo n.º 10
0
QString FTD2XXInterface::readLabel(uchar label, int *ESTA_code)
{
    FT_HANDLE ftdi = NULL;

    if (FT_Open(id(), &ftdi) != FT_OK)
        return QString();

    if(FT_ResetDevice(ftdi) != FT_OK)
        return QString();

    if(FT_SetBaudRate(ftdi, 250000) != FT_OK)
        return QString();

    if(FT_SetDataCharacteristics(ftdi, FT_BITS_8, FT_STOP_BITS_2, FT_PARITY_NONE) != FT_OK)
        return QString();

    if(FT_SetFlowControl(ftdi, 0, 0, 0) != FT_OK)
        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);

    DWORD written = 0;
    if (FT_Write(ftdi, (char*) request.data(), request.size(), &written) != FT_OK)
        return QString();

    if (written == 0)
    {
        qDebug() << Q_FUNC_INFO << "Cannot write data to device";
        return QString();
    }

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

    int read = 0;
    QByteArray array;
    FT_SetTimeouts(ftdi, 500,0);
    FT_Read(ftdi, buffer, 40, (LPDWORD) &read);
    qDebug() << Q_FUNC_INFO << "----- Read: " << read << " ------";
    for (int i = 0; i < read; i++)
        array.append((char) buffer[i]);

    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

    FT_Close(ftdi);
    return QString(array);
}
Exemplo n.º 11
0
int D2xxSerial::read(unsigned char *buffer, int length) {
	DWORD BytesReceived = 0;
	FT_STATUS err = FT_Read(handle,buffer, length,&BytesReceived);
	if (err != FT_OK) {
		printf("Error reading: %s\n", getError(err));
		return 0;
	}
	return BytesReceived;
	
}
Exemplo n.º 12
0
UCHAR ReadBits(void) {
	UCHAR Value;
	DWORD BytesRead;
	FT_Status = FT_Read(FT_Handle, &Value, 1, &BytesRead);
	if (FT_Status != FT_OK) {
		printf("\nFT_Read error (%d), Cable disconnected?\n", FT_Status);
		Idle(2000);		// Display error message for 2 seconds
		Quit();
		}
	return ~Value;
	}
Exemplo n.º 13
0
NDI_DECL1 unsigned int NDI_DECL2 LinkRead( void *pData, unsigned int uSize )
{
	DWORD	dwRead;

	if( s_hndl )
	{
		if( FT_Read( s_hndl, pData, uSize, &dwRead ) == FT_OK )
			return dwRead;
	} /* if */
	return 0;
}
Exemplo n.º 14
0
static int pm_read(struct pm_context *pm, char *buffer, unsigned int count)
{
	FT_STATUS ftstat;
	DWORD bytes_read;

	ftstat = FT_Read(pm->handle, buffer, count, &bytes_read);

	if (ftstat == FT_OK && count == bytes_read)
		return bytes_read;

	return -1;
}
Exemplo n.º 15
0
unsigned char ftdimut_getData(unsigned char request) {
  unsigned int bytesRead, bytesWrote;
  unsigned char buf[2];
  FT_Write(ftHandle, &request, 1, &bytesWrote);
  if(bytesWrote != 1) {
    return 0;
  }
  FT_Read(ftHandle, buf, 2, &bytesRead);
  if(bytesRead != 2) {
    return 0;
  }

  return buf[1];
}
Exemplo n.º 16
0
Arquivo: main.c Projeto: 0x6a77/JD2XX
int main(int argc, char *argv[])
{
	char * pcBufRead;
	DWORD dwBytesRead;
	FILE * fh;
	FT_HANDLE ftHandle;
	FT_STATUS ftStatus;
	int iport;
	
	if(argc > 1) {
		sscanf(argv[1], "%d", &iport);
	}
	else {
		iport = 0;
	}
	
	fh = fopen("target.bin", "wb+");
	if(fh == NULL) {
		printf("Cant open source file\n");
		return 1;
	}
		
	ftStatus = FT_Open(iport, &ftHandle);
	if(ftStatus != FT_OK) {
		/* 
			This can fail if the ftdi_sio driver is loaded
		 	use lsmod to check this and rmmod ftdi_sio to remove
			also rmmod usbserial
		 */
		printf("FT_Open(%d) failed\n", iport);
		return 1;
	}

	pcBufRead = (char *)malloc(BUF_SIZE);
	FT_ResetDevice(ftHandle);
	FT_SetBaudRate(ftHandle, 115200);
	FT_SetDtr(ftHandle);
	FT_SetRts(ftHandle);
	FT_SetFlowControl(ftHandle, FT_FLOW_RTS_CTS, 0, 0);
	FT_SetTimeouts(ftHandle, 0, 0);				// infinite timeouts	
	FT_SetBitMode(ftHandle, 0xFF, 0x01);
	FT_Read(ftHandle, pcBufRead, BUF_SIZE, &dwBytesRead);

	fwrite(pcBufRead, 1, dwBytesRead, fh);
	fclose(fh);
	free(pcBufRead);
	FT_Close(ftHandle);
	
	return 0;
}
Exemplo n.º 17
0
static int
usbconn_ftd2xx_read (urj_usbconn_t *conn, uint8_t *buf, int len)
{
    ftd2xx_param_t *p = conn->params;
    int cpy_len;
    FT_STATUS status = FT_OK;
    DWORD recvd = 0;

    urj_log (URJ_LOG_LEVEL_COMM, "%sread begin: len %d\n", module, len);

    if (!p->fc)
        return -1;

    /* flush send buffer to get all scheduled receive bytes */
    if (usbconn_ftd2xx_flush (p) < 0)
        return -1;

    if (len == 0)
        return 0;

    /* check for number of remaining bytes in receive buffer */
    cpy_len = p->recv_write_idx - p->recv_read_idx;
    if (cpy_len > len)
        cpy_len = len;
    len -= cpy_len;

    if (cpy_len > 0)
    {
        /* get data from the receive buffer */
        memcpy (buf, &p->recv_buf[p->recv_read_idx], cpy_len);
        p->recv_read_idx += cpy_len;
        if (p->recv_read_idx == p->recv_write_idx)
            p->recv_read_idx = p->recv_write_idx = 0;
    }

    if (len > 0)
    {
        /* need to get more data directly from the device */
        while (recvd == 0)
            if ((status =
                 FT_Read (p->fc, &buf[cpy_len], len, &recvd)) != FT_OK)
                urj_error_set (URJ_ERROR_FTD, _("Error from FT_Read(): %s"),
                               ftd2xx_status_string(status));
    }

    urj_log (URJ_LOG_LEVEL_COMM, "%sread end  : status %ld, length %d\n",
             module, status, cpy_len + len);

    return status != FT_OK ? -1 : cpy_len + len;
}
Exemplo n.º 18
0
static int ft245r_recv(PROGRAMMER * pgm, char * buf, size_t len)
{
  FT_STATUS r;
  DWORD rlen;

  r = FT_Read(handle, buf, len, &rlen);

  if (r != FT_OK || len != rlen) {
    fprintf(stderr,
	    "%s: ft245r_recv(): programmer is not responding\n",
	    progname);
    exit(1);
  }
  return 0;
}
Exemplo n.º 19
0
int APSRack::raw_read(int deviceID, FPGASELECT fpga) {
	DWORD bytesRead, bytesWritten;
	UCHAR dataBuffer[2];
	USHORT transferSize = 1;
	int Command = APS_FPGA_IO;

	//Send the read command byte
	UCHAR commandPacket = 0x80 | Command | (fpga<<2) | transferSize;
    FT_Write(APSs_[deviceID].handle_, &commandPacket, 1, &bytesWritten);

	//Look for the data
	FT_Read(APSs_[deviceID].handle_, dataBuffer, 2, &bytesRead);
	FILE_LOG(logDEBUG2) << "Read " << bytesRead << " bytes with value" << myhex << ((dataBuffer[0] << 8) | dataBuffer[1]);
	return int((dataBuffer[0] << 8) | dataBuffer[1]);
}
Exemplo n.º 20
0
int gecko_readbyte(LPVOID lpBuffer, DWORD dwBytesToRead, LPDWORD lpdwBytesReturned)
{
        // read data based on FTDI D2XX USB 2.0 API
        status = FT_Read(fthandle, lpBuffer, dwBytesToRead, lpdwBytesReturned);

        if (status == FT_OK) {
                if(*lpdwBytesReturned != dwBytesToRead)
                        return 2;
        } else {
                eprintf("Error: Read Error. Closing\n");
                status = FT_Close(fthandle);
                return 0;
        }
        return 1;

}
Exemplo n.º 21
0
static int ublast_ftd2xx_read(struct ublast_lowlevel *low, uint8_t *buf,
			     unsigned size, uint32_t *bytes_read)
{
	DWORD dw_bytes_read;
	FT_STATUS status;
	FT_HANDLE *ftdih = ublast_getftdih(low);

	status = FT_Read(*ftdih, buf, size, &dw_bytes_read);
	if (status != FT_OK) {
		*bytes_read = dw_bytes_read;
		LOG_ERROR("FT_Read returned: %s", ftd2xx_status_string(status));
		return ERROR_JTAG_DEVICE_ERROR;
	}
	*bytes_read = dw_bytes_read;
	return ERROR_OK;
}
Exemplo n.º 22
0
int dxl_hal_rx( unsigned char *pPacket, int numPacket )
{
	FT_STATUS ft_status;
	DWORD dwNumToRead;
	DWORD dwNumRead = 0;

	ft_status = FT_GetQueueStatus( ghFt_Handle, &dwNumToRead );
	if( ft_status != FT_OK )
		return 0;

	if( dwNumToRead > 0 )
	{
		ft_status = FT_Read( ghFt_Handle, (LPVOID)pPacket, dwNumToRead, &dwNumRead );
		if( ft_status == FT_IO_ERROR )
			return 0;
	}

	return (int)dwNumRead;
}
Exemplo n.º 23
0
Arquivo: main.c Projeto: 0x6a77/JD2XX
int main(int argc, char *argv[])
{
	char cBufRead[BUF_SIZE];
	DWORD dwBytesRead;
	FT_STATUS ftStatus;
	FT_HANDLE ftHandle;
	int iport;
	int i;
	
	if(argc > 1) {
		sscanf(argv[1], "%d", &iport);
	}
	else {
		iport = 0;
	}
	
	ftStatus = FT_Open(iport, &ftHandle);
	if(ftStatus != FT_OK) {
		/* 
			This can fail if the ftdi_sio driver is loaded
		 	use lsmod to check this and rmmod ftdi_sio to remove
			also rmmod usbserial
		 */
		printf("FT_Open(%d) failed, with error %d.\n", iport, (int)ftStatus);
		printf("Use lsmod to check if ftdi_sio (and usbserial) are present.\n");
		printf("If so, unload them using rmmod, as they conflict with ftd2xx.\n");
		return 1;
	}

	FT_SetTimeouts(ftHandle, 3000, 3000);	// 3 second read timeout
	
	for(i = 0; i < 10 ; i++) {
		FT_Read(ftHandle, cBufRead, BUF_SIZE, &dwBytesRead);
		if(dwBytesRead != BUF_SIZE)
			printf("Timeout %d\n", i);
		else
			printf("Read %d\n", (int)dwBytesRead);
	}
		
		
	FT_Close(ftHandle);
	return 0;
}
Exemplo n.º 24
0
uint32_t Marmote_GetFrequency(FT_HANDLE ftHandle)
{
	uint32_t freq;

	uint8_t dummy;
	uint8_t rxBuffer[150];
	PktHdr_t* pkt;

	DWORD bytesRequested;
	DWORD bytesReceived;
	FT_STATUS ftStatus;

	sendMsg(ftHandle, SDR, GET_FREQUENCY, &dummy, 0);
	bytesRequested = sizeof(rxBuffer);
	ftStatus = FT_Read(ftHandle, rxBuffer, bytesRequested, &bytesReceived);
	if (ftStatus != FT_OK)
	{
		printf("readReg(): FT_Read failed\n");
		return -1;
	}

	pkt = NULL;
	printf("Read  %4d chars: ", bytesReceived);
	for (DWORD i = 0; i < bytesReceived; i++)
	{
		if (rxBuffer[i] == SYNC_CHAR_1)
		{
			pkt = (PktHdr_t*)(rxBuffer+i);
		}
	}
	printf("\n");

	if (!pkt)
	{
		// ERROR
		return 0;
	}
	
	freq = *(uint32_t*)pkt->payload;
	
	return freq;
}
Exemplo n.º 25
0
static int presto_read(uint8_t *buf, uint32_t size)
{
#if BUILD_PRESTO_FTD2XX == 1
	DWORD ftbytes;
	presto->status = FT_Read(presto->handle, buf, size, &ftbytes);
	if (presto->status != FT_OK) {
		LOG_ERROR("FT_Read returned: %s", ftd2xx_status_string(presto->status));
		return ERROR_JTAG_DEVICE_ERROR;
	}

#elif BUILD_PRESTO_LIBFTDI == 1
	uint32_t ftbytes = 0;

	struct timeval timeout, now;
	gettimeofday(&timeout, NULL);
	timeval_add_time(&timeout, 1, 0);	/* one second timeout */

	while (ftbytes < size) {
		presto->retval = ftdi_read_data(&presto->ftdic, buf + ftbytes, size - ftbytes);
		if (presto->retval < 0) {
			LOG_ERROR("ftdi_read_data: %s", ftdi_get_error_string(&presto->ftdic));
			return ERROR_JTAG_DEVICE_ERROR;
		}
		ftbytes += presto->retval;

		gettimeofday(&now, NULL);
		if ((now.tv_sec > timeout.tv_sec) ||
				((now.tv_sec == timeout.tv_sec) && (now.tv_usec > timeout.tv_usec)))
			break;
	}
#endif

	if (ftbytes != size) {
		/* this is just a warning, there might have been timeout when detecting PRESTO,
		 *which is not fatal */
		LOG_WARNING("couldn't read the requested number of bytes from PRESTO (%u < %u)",
			(unsigned)ftbytes, (unsigned)size);
		return ERROR_JTAG_DEVICE_ERROR;
	}

	return ERROR_OK;
}
Exemplo n.º 26
0
/* returns -1 for timeout, else 0..255 */
int
serial_read(void)
{
  struct timeval tv1, tv2;
  long et, oet;
  DWORD rv, stat;
  unsigned char buf;

  gettimeofday(&tv1, 0);
  do {
    stat = FT_Read (handle, &buf, 1, &rv);
    if (rv == 0)
      usleep (10);
    gettimeofday(&tv2, 0);
    et = tv2.tv_usec - tv1.tv_usec;
    et += (tv2.tv_sec - tv1.tv_sec) * 1000000;
    et /= 1000;
    oet = et;
  } while (stat == FT_OK
	   && rv == 0
	   && et < timeout_val);

  if (stat != FT_OK)
    {
      printf("[read failed? %ld]", stat);
      return -1;
    }
  if (rv == 0)
    {
      dprintf("[T]");
      return -1;
    }
  if (verbose > 1)
    {
      if (isgraph(buf))
	printf("\033[31m%c\033[0m", buf);
      //else
	printf("\033[35m%02x\033[0m ", buf);
      fflush(stdout);
    }
  return buf;
}
Exemplo n.º 27
0
/* Read buffer USB*/
quint16 ftdiChip::Read(QByteArray &buff)
{
FT_STATUS ftStatus;
DWORD  numout,RxBytes;// RxBuf=NULL, TxBuf=NULL, EventStat;

//ftStatus=FT_GetStatus(hdUSB,&RxBuf,&TxBuf, &EventStat);
//do{
  ftStatus=FT_GetQueueStatus(hdUSB,&RxBytes);
  if(ftStatus==FT_OK){
    if(RxBytes>0){ //чтение только если в приёмном буфере что то есть
      QByteArray tmpbuff(RxBytes,0x00);
      ftStatus=FT_Read(hdUSB,tmpbuff.data(),RxBytes,&numout);
      if(ftStatus!=FT_OK)return retErr;
      buff.append(tmpbuff);
      }
      else return retBusyDevice;
    }else return retErr;
  //}while(RxBytes);
return retOk;
}
Exemplo n.º 28
0
//Just wraps the FT_Read function in a QueueStatus call so we don't block on reads
int nifalcon_read(falcon_device* dev, unsigned char* str, unsigned int size, unsigned int timeout_ms)
{
	unsigned long bytes_rx, bytes_read = 0;
	clock_t timeout = (clock_t)(((double)timeout_ms * .001) * (double)CLOCKS_PER_SEC) + clock();		
	
	if(!dev->is_open) nifalcon_error_return(NIFALCON_DEVICE_NOT_FOUND_ERROR, "tried to read from an unopened device");
	
	while(bytes_read < size)
	{
		if((dev->falcon_status_code = FT_GetQueueStatus(dev->falcon, &bytes_rx)) != FT_OK) return -dev->falcon_status_code;
		if(bytes_rx > size) bytes_rx = size - bytes_read;
		if(bytes_rx > 0)
		{
			if((dev->falcon_status_code = FT_Read(dev->falcon, str, bytes_rx, &bytes_read)) != FT_OK) return -dev->falcon_status_code;
			bytes_read += bytes_rx;
		}
		if (clock() > timeout) return bytes_read;
	}
	return bytes_read;
}
Exemplo n.º 29
0
bool CMmcUsbHndlBase::ReadByte( unsigned char *pData, unsigned int *pDataRead)
{

	if( !AreLibraryFunctionsLoaded() )
    {
		perror("Library not loaded");
        return false;
    }

	FT_STATUS ftStatus = FT_Read(m_Handle, pData, 1, (DWORD*)pDataRead);

	if( ftStatus != FT_OK )
	{
		std::string errormsg = GetFtStatusDescription(ftStatus);
		errormsg += ":FT_SetUSBParameters";
		perror(errormsg.c_str());
	}

	return (FT_OK == ftStatus);
}
Exemplo n.º 30
0
int CKMotionIO::ReadBytesAvailable(char *RxBuffer, int maxbytes, DWORD *BytesReceived, int timeout_ms)
{
	FT_STATUS ftStatus;
	DWORD EventDWord;
	DWORD RxBytes;
	DWORD TxBytes;

	Mutex->Lock();
	ftStatus=FT_GetStatus(ftHandle,&RxBytes,&TxBytes,&EventDWord);

	if (ftStatus != FT_OK)
	{
		Failed();
		Mutex->Unlock();
		return 1;
	}

	if ((int)RxBytes > maxbytes) RxBytes = maxbytes-1; // leave room for null

	RxBuffer[0]=0;  // set buf empty initially
	*BytesReceived=0;

	if (RxBytes > 0) 
	{
		ftStatus = FT_Read(ftHandle,RxBuffer,RxBytes,BytesReceived);
		if (ftStatus == FT_OK) 
		{
			RxBuffer[*BytesReceived]=0;  // null terminate
		}
		else 
		{
			Failed();
			Mutex->Unlock();
			return 1;
		}
	}

	Mutex->Unlock();
	return 0;
}