I'm using an I2C sensor connected to a Raspberry Pi and need to collect and report continuous data from that bus and pass it along so that I can process the data and update the GUI with the sensor readings. I am using .NET Core so that I can be cross platform on linux and can't find resources on Async I2C collection on the Pi.
I currently have data being pulled from the I2C bus correctly and know how to implement/update the ViewModel, I just don't know how to pull the data continuously and on a new thread.
I have experience doing similar work in Windows with using System.IO.Ports
which already has DataReceivedEventHandlers
built in, but as I am staring from scratch here I have hit a bit of a road block. This is my first time diving into async tasks and event handlers which by themselves can be a bit confusing.
2 Main Issues so far: How to collect I2C data as async or on new thread? How to pass it to synchronous method on different thread?
The code below is what I have so far.
I2CInitialize.cs
public class I2CInitialize
{
public event EventHandler<I2CDataEventArgs> NewI2CDataRecieved;
///Need to call readingi2c in new thread and pass continuous i2c sensor data
public static string readingi2c()
{
int i = 0
while (true)
{
///Taking advantage of using's dispose feature so that memory isn't consumed on loop
using (var i2cBus = new I2CBus(bus))
{
///Driver to get I2C bytes from bus sits here. Returns bytes and converts to string
string result;
result = "I2CDataString";
return result;
}
}
}
///Calls readingi2c() and passes continuous string "data" to subscribers
public void I2C_DataRecieved()
{
string data = readingi2c();
if (NewI2CDataRecieved != null)
NewI2CDataRecieved(this, new I2CDataEventArgs(data));
}
public class I2CDataEventArgs : EventArgs
{
public I2CDataEventArgs(string dataInByteArray)
{
Data = dataInByteArray;
}
public string Data;
}
}
MainWindow.cs
public class MainWindow : Window
{
public void _NewI2CDataRecieved(object sender, I2CDataEventArgs e)
{
string RawStr = e.ToString();
///Update MainWindowViewModel with continuously passed I2C sensor data string "RawStr"
}
public MainWindow()
{
var _i2cInitialize = new I2CInitialize();
_i2cInitialize.NewI2CDataRecieved += new EventHandler<I2CDataEventArgs>(_NewI2CDataRecieved);
_i2cInitialize.I2C_DataRecieved();
}
}