AForge.Robotics.Lego.Internals.SerialCommunication.ReadMessage C# (CSharp) Method

ReadMessage() public method

Read message from NXT brick over the communication interface.
public ReadMessage ( byte buffer, int offset, int &length ) : bool
buffer byte Buffer to use for message reading.
offset int Offset in the buffer for message.
length int On successful return the variable keeps message length.
return bool
        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;
        }
    }

Same methods

SerialCommunication::ReadMessage ( byte buffer, int &length ) : bool