【发布时间】:2013-08-07 18:22:54
【问题描述】:
通过串口连接的设备的寿命状态。
大家好。
如何检查设备是否响应请求?我在谷歌上搜索了几天,也尝试了 SO 的许多解决方案,但没有给我预期的结果。经过多次尝试,我的观点如下所述。我想我已经很接近了,但现在我需要一点帮助,所以提前感谢每一个答案。
现状
我现在在做什么很简单。首先,我在应用程序的一开始就打开串行端口serialPort.Open()(数据接收几乎所有应用程序运行时间)。
由于这只是我表单中的一个示例,因此只有一个名为 labelStatus 和 labelStatus.Text = "Not connected" 的标签
接下来我要添加一个计时器,它是tick 方法,其中包含serialPort.Write() 的执行。如果重要的话,计时器间隔设置为 100。
private void timer_Tick(object sender, EventArgs e)
{
if (serialPort.IsOpen)
{
serialPort.WriteLine("r"); //I'm sending "r" message and device send data back
}
}
下一步是创建DataReceived 事件,如下所示(非常简化的版本,在我的应用程序中接收到的数据被解析为浮点数并存储在数组中,但这只是为了显示问题)
private void serialPort_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
string someVariable = serialPort.ReadLine();
labelStatus.Invoke((MethodInvoker)(() => labelStatus.Text = "Connected"));
//If i received something that means the device is plugged in and connection is correct (still very simplified)
}
最后一件事是创建ErrorReceived 方法。
private void serialPort_ErrorReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
labelStatus.Invoke((MethodInvoker)(() => labelStatus.Text = "Not connected"));
}
到目前为止,一切都很好。发送数据有效。 DataReceived 事件在发送数据时每 100 毫秒执行一次。我的数据被正确接收,没有问题。当我启动应用程序labelStatus 时,文本为“未连接”(未插入设备电缆)。当我插入设备 labelStatus 时,文本更改为“已连接”。 但是现在当我插入电缆时,ErrorReceived 事件没有执行,labelStatus 文本仍然是“已连接”。所以正如我之前问过的:如何检查设备是否仍连接到计算机? (或者也许:当数据没有接收到时,如何执行 ErrorReceived 事件?)。
注意:串口ReadTimeout设置为300毫秒。
我尝试了什么
我已经尝试了很多东西,但我脑海中的这个似乎应该有效但没有。
我已修改 DataReceived 事件并将 serialPort.ReadLine() 放入带有 TimeoutException 的 try/catch 块中,我尝试手动执行 ErrorReceived 方法,如下所示
private void serialPort_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
try
{
string someVariable = serialPort.ReadLine();
labelStatus.Invoke((MethodInvoker)(() => labelStatus.Text = "Connected"));
//If i received something that means the device is plugged in and connection is correct (still very simplified)
}
catch (TimeoutException)
{
serialPort_ErrorReceived(null, null);
}
}
我希望它会像我想要的那样工作。
顺便说一句。对不起我的英语不好。它并不完美,但我尽我所能。干杯!
【问题讨论】:
-
你在串行线上使用握手吗?也许我没有正确理解,但握手似乎是你想要实现的明显解决方案?没有它,串行通信是无连接的。
标签: c# serial-port status