在下面的代码中,当连接我的串口时(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");
}
}
}
答案 0 :(得分:2)
如果您尝试附加到字符串,我会推荐一个StringBuilder对象。
或者分辨率越低,使用+ =运算符
string s = "abcd";
s+="efgh";
Console.WriteLine(s); //s prints abcdefgh
答案 1 :(得分:0)
首先,你的变量(myReceivedLines和port)不是静态的。我不确定你是否希望它们是静态的,因为我看不到你如何使用SendToPrintComponent类。 你能解释DA.SetDataList(0,myReceivedLines);或者更好地包括代码,因为问题可能存在......