Watts SDK Protocol Specification - Sample Code For Reading Message
Watts SDK Protocol Specification - Sample Code For Reading Message
reading message
package com.traficon.util;
import java.io.DataInputStream;
import java.io.IOException;
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 );
}
try
{
int bytesLeft = msglen - 2;
while (bytesLeft > 0)
{ // keep reading until everything is read
int res = inputStream.read( 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( inputStream.readByte() );
}
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 = Math.min( 4, bytes.length );
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 java.io.IOException due to error while reading stream
*/
private static long readUnsignedInt( DataInputStream dataInputStream ) throws
IOException
{
byte[] bytes = new byte[4];
dataInputStream.readFully( bytes );
return toUnsigned( bytes );
}
}