Search code examples
c#exceptionmethodsserial-portgrasshopper

SerialPort.ReadExisting Method not displaying received data


The following code is building without errors but when I run the program, the received data does not show in the output. When I place a breakpoint on the myReceivedLines = port.ReadExisting(); I get:

System.InvalidOperationException.

In the program itself, after restarting my computer it says:

Access to COM5 is denied

What can I do to fix this?

Code:

//Fields
SerialPort port;
string myReceivedLines;

   protected override void SolveInstance(IGH_DataAccess DA)
  {

    List<string> gcode = new List<string>();
    DA.GetDataList(0, gcode);
    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);
    bool sendtoprint= default(bool);
    DA.GetData(4, ref sendtoprint);


    if (!DA.GetDataList(0, gcode)) return;
    if (!DA.GetData(1, ref selectedportname)) return;
    if (!DA.GetData(2, ref selectedbaudrate)) return;
    if (!DA.GetData(3, ref connecttodevice)) return;
    if (!DA.GetData(4, ref sendtoprint)) return;


    port = new SerialPort(selectedportname, selectedbaudrate, Parity.None, 8, StopBits.One); //Create the serial port
    port.DtrEnable = true;   //enables the Data Terminal Ready (DTR) signal during serial communication (Handshaking)
    port.Open();             //Open the port
    port.DataReceived += this.portdatareceived;


    if (gcode == null)
    {
        AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Specify a valid GCode");
        return;
    }

    if (connecttodevice == true)
    {
        DA.SetDataList(0, myReceivedLines);
    }

        if (sendtoprint == true)
        {
            foreach (String s in gcode)
            {
                port.WriteLine(s);
            }
        }

              }


    //subscriber method for the port.DataReceived Event
    private void portdatareceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
    {
            myReceivedLines = port.ReadExisting();
    }

Solution

  • The SerialPort's DataReceived Event operates on a different thread than the UI thread. You will need to do something like the MSDN Page for The DataReceived Event suggests. The reason why you get the access denied error is because the port is still open, reboot your computer to correct restarting your program is not enough.

    i.e. from above link

    private static void DataReceivedHandler( object sender, SerialDataReceivedEventArgs e)
    {
        SerialPort sp = (SerialPort)sender;
        string indata = sp.ReadExisting();
    }