I'm creating a UWP application that will need to communicate with several modules (Arduino) over RS485.
At this time and for testing I created a small application that communicates with any of these modules without problems.
My problem is that my application will have more than one Page and to do these communications, I thought about creating a class to always keep the communications working.
The problem is that this way I can not keep the connection active, that is, after the communication starts, it loses its state.
Communications are initiated through this function:
private async Task initComm()
{
try
{
//cParam = PDB.getParameters();
string selectedPortID = null;
string aqs = SerialDevice.GetDeviceSelector();
deviceInformation = await DeviceInformation.FindAllAsync(aqs);
foreach (var devInfo in deviceInformation)
{
if (devInfo.Name == "USB-RS485 Cable")
{
selectedPortID = devInfo.Id;
}
}
serialPort = await SerialDevice.FromIdAsync(selectedPortID);
if (serialPort != null)
{
serialPort.ReadTimeout = TimeSpan.FromMilliseconds(1000);
serialPort.BaudRate = 9600;
serialPort.Parity = SerialParity.None;
serialPort.StopBits = SerialStopBitCount.One;
serialPort.DataBits = 8;
}
else
{
var status = DeviceAccessInformation.CreateFromId(selectedPortID).CurrentStatus;
// ELDB.attachEvent("E1002", "Starting Comunication Failed: " + status.ToString());
}
while (flagComm)
{
try
{
await Listen();
}
catch (Exception ex)
{
// ELDB.attachEvent("E2cC", ex.Message);
}
}
}
catch (Exception ex)
{
// ELDB.attachEvent("E1cC", ex.Message);
}
}
When I try to send something through this method:
private async void writeComm(string str2send)
{
try
{
using (var dataWriter = new DataWriter(serialPort.OutputStream))
{
dataWriter.WriteString(str2send);
await dataWriter.StoreAsync();
await dataWriter.FlushAsync();
dataWriter.DetachStream();
}
}
catch (Exception ex)
{
eventLog = ex.Message;
// ELDB.attachEvent("E6cC", ex.Message);
}
}
What happens is that it goes into an exception because the referenced object no longer exists ...
Asyoucanseeintheimage,"serialPort == null"
What I would like to know is if it is possible to keep this idea of having a class with the methods and only calling them when I want to send something, or if I have to change the thinking.
If it's the second, is there any idea for this to work as intended?