Unable to use SerialDevice.ReadTimeout in Windows 10 IoT

前端 未结 2 1512
温柔的废话
温柔的废话 2021-01-03 05:37

I\'m trying to implement a ModBus master on Windows 10 IoT on a Raspberry Pi 2. I\'m using an external USB to RS-232 adapter since the internal serial port

2条回答
  •  时光说笑
    2021-01-03 06:34

    Just spent a couple weeks fighting this and doing testing.

    1. ReadTimeout has no effect on the first byte of a read call. Read calls always wait forever for the first byte.

    2. ReadTimeout = 0ms causes read calls to wait forever for all subsequent bytes requested on a multi-byte read call.

    3. ReadTimeout = Greater than 0ms causes read calls to timeout after that time when waiting for any subsequent bytes after the first.

    4. ReadTimeout is a TimeSpan, which means the caller can specify a timeout value with more resolution than milliseconds. However, the underlying Windows calls only have a millisecond resolution.

    5. My experiments using a CancellationTokenSource with a timeout value seemed to result in the SerialDevice object becoming unstable after a timeout cancellation.

    I ended up creating a class derived from SerialDevice. The derived class launched a background task which simply issued read requests to the base SerialDevice class and stored the returned data in a queue. I set ReadTimeout to 1ms so my background task could issue large read requests, but then receive and store data into the queue as the data became available without waiting for the entire request.

    I created a circular queue for memory efficiency. .NET does not provide one standard. When dealing with high baud rates, copying read data to the queue will need to be very efficient. Meaning copying blocks of data. Not messing around with the data byte by byte.

    The derived class provided alternate read methods which would return data from the queue and could return immediately if no data was in the queue.

    With the SerialDevice reads occurring in the background task there was never any need to cancel the read requests and risk destabilize SerialDevice. The reads only had a CancellationToken for when the background task was being signaled to terminate because the derived class was closing SerialDevice and disposing.

提交回复
热议问题