myReceivedLines
在下面的代码中,当与我的串行端口连接时(当connecttodevice
为真时)出现在其中接收到的字符串。但是,当我启动另一个命令时它们会消失(何时homeall
为真)。
我添加了myReceivedLines
在类中调用的字段,以便我可以使用该方法String.Add()
接收到的所有反馈和发送的命令(就像程序中的控制台一样)。
为什么发送命令后反馈消失?如何确保所有字符串都保留在变量中myReceivedLines
?字符串是否会myReceivedLine
因为它们发生在订阅者方法中而消失?我该如何解决?
注意:GH_DataAccess.SetDataList(Int32, IEnumerable) 是来自内核的一种方法,一个名为Grasshopper的软件将值分配给输出(它必须在也来自这个内核的 GH_Component.SolveInstance() 方法中使用),我是使用它来可视化 myReceivedLines。
代码:
public class SendToPrintComponent : GH_Component
{
//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);
//Assigning an object to the field within the SolveInstance method()
port = new SerialPort(selectedportname, selectedbaudrate, Parity.None, 8, StopBits.One);
//Enables the data terminal ready (dtr) signal during serial communication (handshaking)
port.DtrEnable = true;
port.WriteTimeout = 500;
port.ReadTimeout = 500;
}
//Event Handling Method
bool connecttodevice = default(bool);
DA.GetData(3, ref connecttodevice);
**if (connecttodevice == true)**
{
if (!port.IsOpen)
{
port.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
DA.SetDataList(0, myReceivedLines);
port.Open();
}
}
else
if (port.IsOpen)
{
port.DataReceived -= new SerialDataReceivedEventHandler(DataReceivedHandler);
port.Close();
}
if (port.IsOpen)
{
DA.SetData(1, "Port Open");
}
//If the port is open do all the rest
if (port.IsOpen)
{
bool homeall = default(bool);
DA.GetData(5, ref homeall);
//Home all sends all the axis to the origin
**if (homeall == true)**
{
port.Write("G28" + "\n");
myReceivedLines.Add("G28" + "\n");
DA.SetDataList(2, myReceivedLines);
}
}
else
{
DA.SetData(1, "Port Closed");
}
}
}