Last active
May 25, 2020 23:24
-
-
Save elexisvenator/183c6db732f0b279f63c6725b2e063e9 to your computer and use it in GitHub Desktop.
Example workaround for serial port DataReceived events until events work as intended
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Threading; | |
using System.Threading.Tasks; | |
using Meadow.Hardware; | |
namespace Meadow.Foundation.Serial.Helper | |
{ | |
public class SerialEventPoller : IDisposable | |
{ | |
private readonly int _pollingIntervalMs; | |
private CancellationTokenSource _cancellationTokenSource; | |
public SerialEventPoller(ISerialPort serialPort, int pollingIntervalMs = 10) | |
{ | |
SerialPort = serialPort; | |
_pollingIntervalMs = pollingIntervalMs; | |
} | |
public ISerialPort SerialPort { get; } | |
public void Dispose() | |
{ | |
Stop(); | |
} | |
public void Start() | |
{ | |
Stop(); | |
_cancellationTokenSource = new CancellationTokenSource(); | |
var token = _cancellationTokenSource.Token; | |
Task.Factory.StartNew(() => PollForData(SerialPort, _pollingIntervalMs, token), token, | |
TaskCreationOptions.LongRunning, TaskScheduler.Default); | |
} | |
public void Stop() | |
{ | |
_cancellationTokenSource?.Cancel(); | |
} | |
private void PollForData(ISerialPort port, int intervalMs, CancellationToken token) | |
{ | |
while (true) | |
{ | |
if (port.IsOpen && port.BytesToRead > 0) | |
{ | |
var handler = Volatile.Read(ref DataReceived); | |
handler?.Invoke(this, new DataReceivedEventArgs {SerialPort = port}); | |
} | |
Thread.Sleep(intervalMs); | |
if (token.IsCancellationRequested) break; | |
} | |
} | |
public event DataReceivedEventHandler DataReceived = delegate { }; | |
} | |
public class DataReceivedEventArgs : EventArgs | |
{ | |
public ISerialPort SerialPort { get; set; } | |
} | |
public delegate void DataReceivedEventHandler(object sender, DataReceivedEventArgs e); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment