Hi,
What are you using to send command to be read by this code? Without knowing this it is hard to judge what might be going wrong here... However there are a few potential problems....
It is not a good idea to use the available() call this way... The contract for available is...
Returns an estimate of the number of bytes that can be read (or skipped over) from this input stream without blocking by the next invocation of a method for this input stream. The next invocation might be the same thread or another thread. A single read or skip of this many bytes will not block, but may read or skip fewer bytes.
Note that this is just an estimate and that (for instance) an implementation would be correct to always return 0.
The problem here is that for some Bluetooth stacks the only way to check for new data is to issue a blocking read. The available method is not allowed to block and so it is not possible to check for new data that has arrived, instead it simply returns the amount of data that is still remaining from in the buffers from a previous read. So data may be available to be read even if available() returns 0.
In particular this is true of the PC side of leJOS you cannot use available() in this way with our PC side code. The only safe way is to call a read function (which may block). On the NXT currently you can do this (because we have non blocking reads available to check if data is present). However this may change in the future and so you should avoid using available in this way.
The second problem is that you are not checking the return value of read. A blocking read will always return at least one byte (or an error), however it may not block until all of the bytes that you have requested have been read. So sometimes you may end up reading 1,2,3 bytes rather than the 4 that you have requested. You are using packet mode (you set the IO mode to 0), so you may get away with this because in this mode read will block until the entire packet is available, but without seeing how the data has been sent it is hard to be sure.
The third problem is that your byte to integer code will fail for large integers (because of the division by 256), with your current code this is probably not an issue, but it is easy to fix, simply change the code to...
- Code: Select all
private int byteArrayToInt(byte[] b)
{
int value = 0;
for(int index = 0;index<b.length;index++)
{
value <<= 8;
value |= b[index] & 0xFF;
}
return value;
}
Andy