I am using the SerialPort.ReadLine() method to display the data received from a Serial Port (code below).
Previously the code looked like that and received data but it did not send data. Now it is the other way around:
Since I placed the port.DataReceived
event within the if(port==null)
statement and added SerialPort port;
as field, I don't receive data anymore. Can placing the event within an if statement change the way data is received and displayed? How can I fix that?
//Fields
List<string> myReceivedLines = new List<string>();
SerialPort port;
//subscriber method for the port.DataReceived Event
private void DataReceivedHandler(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
SerialPort sp = (SerialPort)sender;
while (sp.BytesToRead > 0)
{
try
{
myReceivedLines.Add(sp.ReadLine());
}
catch (TimeoutException)
{
break;
}
}
}
protected override void SolveInstance(IGH_DataAccess DA)
{
//Opening the port
if (port == null)
{
string selectedportname = default(string);
DA.GetData(1, ref selectedportname);
int selectedbaudrate = default(int);
DA.GetData(2, ref selectedbaudrate);
bool connecttodevice = default(bool);
DA.GetData(3, ref connecttodevice);
//Assigning an object to the field within the SolveInstance method()
port = new SerialPort(selectedportname, selectedbaudrate, Parity.None, 8, StopBits.One);
//Event Handling Method
if (connecttodevice == true)
{
port.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
DA.SetDataList(0, myReceivedLines);
}
//Enables the data terminal ready (dtr) signal during serial communication (handshaking)
port.DtrEnable = true;
port.Open();
}
//Displays if port if opened
if (port.IsOpen)
{
DA.SetData(1, "Port Open");
}
//If the port is open do all the rest
if (port.IsOpen)
{
//Assigning the input to variables for the code.
List<string> gcode = new List<string>();
DA.GetDataList(0, gcode);
bool sendtoprint = default(bool);
DA.GetData(4, ref sendtoprint);
bool homeall = default(bool);
DA.GetData(5, ref homeall);
//What happens when input is set
if (sendtoprint == true)
{
if (homeall == true)
{
port.Write("G28" + "\n");
}
}
else
{
DA.SetData(1, "Port Closed");
}
}