Usually, when I create a Com port, it is a class level object that I initialize once at startup. I would move the initialization code from your method to a constructor or method that you can call once during startup. This should prevent you from trying to open it more than once and leave it available to respond to the Received Data.
I'm not sure about your architecture, it looks like you plan on having multiple ports, but to answer your question in the comments, everything you do to create a SerialPort. The minimum declaration for SerialPort must be a class level variable. Then you can check if there was nothing and create it for the first time.
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); SerialPort port = new SerialPort(selectedportname, selectedbaudrate, Parity.None, 8, StopBits.One); port.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler); DA.SetDataList(0, myReceivedLines); port.Open();
second option with a SerialPort class level. Try something like this:
protected override void SolveInstance(IGH_DataAccess DA) { 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); port = new SerialPort(selectedportname, selectedbaudrate, Parity.None, 8, StopBits.One); if (connecttodevice == true) { port.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler); DA.SetDataList(0, myReceivedLines); } port.DtrEnable = true; port.Open(); } bool homeall = default(bool); DA.GetData(5, ref homeall); if (homeall == true) { port.Write("g28"); } }
source share