Watts SDK Protocol specification - Sample code for
reading message
package [Link];
import [Link];
import [Link];
public class SdkCommunicationsUtil
{
// -------------------------- STATIC METHODS --------------------------
/**
* Reads one message from the stream. Returns the the full message including
* header and payload
*
* @param inputStream the stream to read from
* @return an array of bytes representing a full framing of a message
*/
public static byte[] readMessage( DataInputStream inputStream )
{
int msglen;
int msglen1 = readUnsignedByte( inputStream );
int msglen2 = readUnsignedByte( inputStream );
int msglen3 = readUnsignedByte( inputStream );
int msglen4 = readUnsignedByte( inputStream );
if (msglen4 == 0)
{
msglen = (msglen1 * 256) + msglen2;
}
else if (msglen4 == 1)
{
msglen = (msglen1 * 256 * 256) + (msglen2 * 256) + msglen3;
}
else
{
throw new RuntimeException( "Protocol-length version not correct in first 4 bytes:
" + msglen1 + "," + msglen2 + "," + msglen3 + "," + msglen4 );
}
// for robustness store the message in a bytebuffer before continuing
byte[] bytes = new byte[msglen + 2];
bytes[0] = (byte)msglen1;
bytes[1] = (byte)msglen2;
bytes[2] = (byte)msglen3;
bytes[3] = (byte)msglen4;
try
{
int bytesLeft = msglen - 2;
while (bytesLeft > 0)
{ // keep reading until everything is read
int res = [Link]( bytes, 2 + msglen - bytesLeft, bytesLeft );
if (res != -1)
{
bytesLeft -= res;
}
else
{
throw new RuntimeException( "Error reading Socket InStream" );
}
}
}
catch (IOException e)
{
throw new RuntimeException( e );
}
return bytes;
}
/**
* reads an unsigned byte from the stream
*
* @param inputStream the stream to read from
* @return an unsigned byte
*/
private static short readUnsignedByte( DataInputStream inputStream )
{
try
{
return toUnsigned( [Link]() );
}
catch (IOException e)
{
throw new RuntimeException( e );
}
}
/**
* Interprets the bits of a byte as a unsigned byte. eg. 52->52, -126 -> 130
*
* @param b the byte
* @return a short containing the value of the unsigned byte
*/
private static short toUnsigned( byte b )
{
return b < 0 ? (short)(b + 256) : b;
}
/**
* convert the bytes to an integer. When more that 4 bytes are given, only the first
four bytes are taken into account
*
* @param bytes The bytes to be converted. Most significant byte first.
* @return A long represented by the byte array
*/
private static long toUnsigned( byte... bytes )
{
long result = 0;
final int length = [Link]( 4, [Link] );
for (int i = 0; i < length; i++)
{
result += toUnsigned( bytes[i] ) << ((length - 1 - i) * 8);
}
return result;
}
/**
* This function is needed because DataInputStream does not support readUnsignedInt
*
* @param dataInputStream the input stream
* @return unsigned int value
* @throws [Link] due to error while reading stream
*/
private static long readUnsignedInt( DataInputStream dataInputStream ) throws
IOException
{
byte[] bytes = new byte[4];
[Link]( bytes );
return toUnsigned( bytes );
}
}