public bool ReadMessage( byte[] buffer, int offset, out int length )
{
// check connection status
if ( !port.IsOpen )
{
throw new NullReferenceException( "Serial port is not opened" );
}
length = 0;
try
{
// read 2 bytes of message length
int lsb = port.ReadByte( );
int msb = port.ReadByte( );
int toRead = ( msb << 8 ) + lsb;
// check buffer size
if ( toRead > buffer.Length - offset )
{
// remove incomming message from the port
while ( toRead != 0 )
{
port.ReadByte( );
toRead--;
}
throw new ArgumentException( "Reply buffer is too small" );
}
// read the message
length = port.Read( buffer, offset, toRead );
while ( length < toRead )
{
buffer[offset + length] = (byte) port.ReadByte( );
length++;
}
}
catch
{
return false;
}
return true;
}
}