Skip to content

Instantly share code, notes, and snippets.

@elexisvenator
Last active May 25, 2020 23:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save elexisvenator/183c6db732f0b279f63c6725b2e063e9 to your computer and use it in GitHub Desktop.
Save elexisvenator/183c6db732f0b279f63c6725b2e063e9 to your computer and use it in GitHub Desktop.
Example workaround for serial port DataReceived events until events work as intended
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