BWhelan
BWhelan

Reputation: 448

How to create a "DataReceived" Event for SerialDevice?

I am using the SerialDevice class to use RS-485 with my serial ports. It currently does not have an event for when data is received. And I currently have to poll a Listener with a DataReader which doesn't always capture all the data in its buffer.

I am looking for a way to create a receiver event for the SerialDevice class so that I don't have to poll and so that it can be triggered right when the correct data is received.

My current method:

async void Initialize()
{
        DeviceInformationCollection devices = await DeviceInformation.FindAllAsync();
        if (devices.Count > 0)
        {
            for (int i = 0; i < devices.Count; i++)
            {
                if (devices[i].Id.Contains("PNP0501#2"))
                {
                    GpioStatus = string.Format("Connecting... {0} found", devices[i].Id);
                    DeviceInformation deviceInfo = devices[i];
                    serialDevice = await SerialDevice.FromIdAsync(deviceInfo.Id);
                    serialDevice.BaudRate = 9600;
                    serialDevice.DataBits = 8;
                    serialDevice.StopBits = SerialStopBitCount.Two;
                    serialDevice.Parity = SerialParity.None;
                    serialDevice.Handshake = SerialHandshake.None;
                }
            }
        }
        Listen();
}


        Initialize();
        DataReader dataReader;
        SerialDevice serialDevice;
        CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
        const uint ReadBufferLength = 1024;

        async void Listen()
        {
            try
            {
                dataReader = new DataReader(serialDevice.InputStream);
                dataReader.InputStreamOptions = InputStreamOptions.Partial;

                while (true)
                {
                    await ReadAsync(cancellationTokenSource.Token);
                }
            }
            catch
            {
                GpioStatus = "Failed to listen";
            }
        }

        private async Task ReadAsync(CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();

            Task<UInt32> loadAsyncTask = dataReader.LoadAsync(ReadBufferLength).AsTask(cancellationToken);

            UInt32 bytesRead = await loadAsyncTask;
            GpioStatus = dataReader.ReadString(bytesRead);
        }

Any ideas would be much appreciated!

Upvotes: 0

Views: 758

Answers (1)

Neil
Neil

Reputation: 11919

As it's a serial protocol, you need to interpret as things come in. If the first thing expected is (say) a 4 byte length, followed by the rest of the packet, then:

while (dataReader.UnconsumedBufferLength > 0)
{
  // Note that the call to readString requires a length of "code units" 
  // to read. This is the reason each string is preceded by its length 
  // when "on the wire".
  uint bytesToRead = dataReader.ReadUInt32();
  receivedStrings += dataReader.ReadString(bytesToRead) + "\n";
}

Code snippet taken from : https://learn.microsoft.com/en-us/uwp/api/windows.storage.streams.datareader

Upvotes: 1

Related Questions