0
I am creating a UWP application that will need to communicate with multiple modules (Rduino) by 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 effect these communications I thought to create a class to always keep the communications working.
The problem is that this way I can’t keep the connection active, that is, after starting the communication, it loses the state of it.
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 enters into exception because the referenced object no longer exists...
As shown in the image, "serialPort == null"
What I would like to know is whether it is possible to maintain this idea of having a class with the methods and just call them when I want to send something, or if I have to change the thinking.
In case you’re the second, any idea how this works?
Could post a snippet of how you are making the calls to this class?
– Edney Batista da Silva
@Edneybatistadasilva Inside Mainpage I create a new object, initialize communications and then make the calls I need for the methods. It follows a passage. 

 public sealed partial class MainPage : Page
 {
 cComm cC = new cComm();

public MainPage()
 {
 InitializeComponent(); 
 cC.startSerialComm();
 } 

private void sendBtn_Click(Object Sender, Routedeventargs e) ' cc.sendComm(4); } }
– Nuno Santos