Search code examples
c#serial-portienumerablehandlergrasshopper

Getting an IEnumerable from a port.DataReceived Event and its subscriber method?


I am trying to read data received from a device but I get the following error with line DA.SetDataList(0, port.DataReceived);:

The best overloaded method match for Grasshopper.Kernel.IGH_DataAccess.SetDataList(int,System.Collections.IEnumerable) has some valid arguments.

The SetDataList(int32, IEnumerable) is part of the Grasshopper Kernel. port.DataReceived is an event and therefore not a valid IEnumerable argument, it stores a list of data in an output parameter during GH_Component.SolveInstance(). I have set up a subscriber method portdatareceived which gives me strings. How can I get an IEnumerable from this method?

  SerialPort port;

   protected override void SolveInstance(IGH_DataAccess DA)
    {
    string gcode = default(string);
    DA.GetData(0, ref gcode);

    port = new SerialPort(selectedportname, selectedbaudrate, Parity.None, 8, StopBits.One); 
    port.DtrEnable = true;   
    port.Open();            
    port.DataReceived += this.portdatareceived;

    if (gcode == null)
    {
        AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Specify a valid GCode");
        return;
    }
    else
    {
        DA.SetDataList(0, port.DataReceived);
    }    
    }

  private void portdatareceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
    {
       string line = port.ReadExisting();
    }

Solution

  • Making the line variable in the subscriber method a field and accessing it from the SetDataList method works:

    SerialPort port;
    string myReceivedLines;
    
       protected override void SolveInstance(IGH_DataAccess DA)
      {
    
        string gcode = default(string);
        DA.GetData(0, ref gcode);
    
        port = new SerialPort(selectedportname, selectedbaudrate, Parity.None, 8, StopBits.One);
        port.DtrEnable = true;   
        port.Open();            
        port.DataReceived += this.portdatareceived;
    
        if (gcode == null)
        {
            AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Specify a valid GCode");
            return;
        }
        else
        {
            DA.SetDataList(0,  myReceivedLines);
            port.WriteLine(gcode);
        }    
                  }
    
        private void portdatareceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
            myReceivedLines = port.ReadExisting();
        }