private async Task<byte[]> BrickPiRx(int timeout, int cancelAfter = CancelAfter)
{
// clean token
if (ReadCancellationTokenSource == null)
ReadCancellationTokenSource = new CancellationTokenSource();
ReadCancellationTokenSource.CancelAfter(timeout + cancelAfter);
//read from the serial port
byte[] rx_buffer = await ReadAsync(timeout, ReadCancellationTokenSource.Token);
if (ReadCancellationTokenSource != null)
{
ReadCancellationTokenSource.Dispose();
ReadCancellationTokenSource = null;
}
// check if data are valids
if (rx_buffer == null)
return null;
if (rx_buffer.Length < 2)
return null;
if (rx_buffer.Length < (rx_buffer[1] + 2))
return null;
long CheckSum = (sum(1, rx_buffer.Length - 1, rx_buffer) % 256);
if (CheckSum != rx_buffer[0])
return null;
byte[] retval = new byte[rx_buffer.Length - 2];
//create the returned buffer, remove the message lenght and checksum
for (int i = 0; i < (rx_buffer.Length - 2); i++)
retval[i] = rx_buffer[i + 2];
return retval;
}