Skip to content

Commit

Permalink
Merge pull request #31 from felHR85/ftdi_sync
Browse files Browse the repository at this point in the history
Ftdi sync
  • Loading branch information
felHR85 committed Feb 28, 2016
2 parents c434492 + 6da1eed commit 36fd71b
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 31 deletions.
52 changes: 52 additions & 0 deletions usbserial/src/main/java/com/felhr/usbserial/FTDISerialDevice.java
Original file line number Diff line number Diff line change
Expand Up @@ -566,4 +566,56 @@ private void copyData(byte[] src, byte[] dst)
}
}

@Override
public int syncRead(byte[] buffer, int timeout)
{
long beginTime = System.currentTimeMillis();
long stopTime = beginTime + timeout;

if(asyncMode)
{
return -1;
}

if(buffer == null)
{
return 0;
}

int n = buffer.length / 62;
if(buffer.length % 62 != 0)
{
n++;
}

byte[] tempBuffer = new byte[buffer.length + n * 2];

int readen = 0;

do
{
int timeLeft = (int) (stopTime - System.currentTimeMillis());
if(timeLeft <= 0)
{
break;
}

int numberBytes = connection.bulkTransfer(inEndpoint, tempBuffer, tempBuffer.length, timeLeft);

if(numberBytes > 2) // Data received
{
byte[] newBuffer = this.ftdiUtilities.adaptArray(tempBuffer);
System.arraycopy(newBuffer, 0, buffer, 0, buffer.length);

int p = numberBytes / 64;
if(numberBytes % 64 != 0)
{
p++;
}
readen = numberBytes - p * 2;
}
}while(readen <= 0);

return readen;
}
}
37 changes: 6 additions & 31 deletions usbserial/src/main/java/com/felhr/usbserial/UsbSerialDevice.java
Original file line number Diff line number Diff line change
Expand Up @@ -140,40 +140,15 @@ public int syncWrite(byte[] buffer, int timeout)
@Override
public int syncRead(byte[] buffer, int timeout)
{
if(!asyncMode)
{
if(buffer == null)
return 0;
if(!isFTDIDevice())
{
return connection.bulkTransfer(inEndpoint, buffer, buffer.length, timeout);
}else // FTDI devices need special treatment
{
int n = buffer.length / 62;
if(buffer.length % 62 != 0)
n++;

byte[] tempBuffer = new byte[buffer.length + n * 2];
int numberBytes = connection.bulkTransfer(inEndpoint, tempBuffer, tempBuffer.length, timeout);

if(numberBytes > 2) // Data received
{
byte[] newBuffer = ((FTDISerialDevice) this).ftdiUtilities.adaptArray(tempBuffer);
System.arraycopy(newBuffer, 0, buffer, 0, buffer.length);

int p = numberBytes / 64;
if(numberBytes % 64 != 0)
p++;
return numberBytes - p * 2;
}else
{
return 0;
}
}
}else
if(asyncMode)
{
return -1;
}

if (buffer == null)
return 0;

return connection.bulkTransfer(inEndpoint, buffer, buffer.length, timeout);
}

// Serial port configuration
Expand Down

0 comments on commit 36fd71b

Please sign in to comment.