【发布时间】:2018-02-16 22:29:04
【问题描述】:
我正在使用 .NET 4.0 开发一个项目。我有一个通过串行端口连接的设备,我向它发送命令,然后等待响应。收到响应后,我会检查响应以确保其有效,然后发送下一条命令。
主要问题是我发送的命令有很大不同的响应时间。一个命令的响应可能需要 30 毫秒或 30 秒。因此,我实现了 TimerCallback 以每 500 毫秒检查一次来自串行端口的响应。我已经发布了下面的代码以及我得到的输出。
// From different class
private string SendCommandAwaitResponse(string command)
{
// Set timeout to 30 seconds.
this.port.ReadTimeout = 30000;
// Clears existing
this.port.ReadExisting();
this.port.Write(command);
var autoEvent = new AutoResetEvent(false);
var responseTimer = new ResponseTimer(port, command);
var timer = new Timer(responseTimer.GetResponse, autoEvent, 0, 500);
autoEvent.WaitOne();
Trace.WriteLine(string.Format("AutoEvent Set: {0}", command));
timer.Dispose();
return responseTimer.Response;
}
public class ResponseTimer
{
private ISerialPort serialPort;
private string command;
private bool isAttemptingRead;
public string Response
{
get { return this.response; }
set
{
if (this.response == value)
return;
this.response = value;
}
}
private string response;
public ResponseTimer(ISerialPort port, string command)
{
Trace.WriteLine("Constructor Created");
this.isAttemptingRead = false;
this.serialPort = port;
this.command = command;
Response= string.Empty;
}
public void GetResponse(Object stateInfo)
{
AutoResetEvent autoEvent = (AutoResetEvent)stateInfo;
try
{
if (!isAttemptingRead)
{
Trace.WriteLine("Initiating ReadLine");
Response= serialPort.ReadLine();
isAttemptingRead = true;
}
Trace.WriteLine("Try: " + Response);
}
catch (TimeoutException ex)
{
Trace.WriteLine(String.Format("EX: TIMED OUT: Response {0}", Response));
autoEvent.Set();
}
Trace.WriteLine(String.Format("CURRENT Response {0}", Response));
if (Response == command)
{
Trace.WriteLine(string.Format("COMMAND: {0}", command));
Trace.WriteLine(string.Format("Clearing Buffer: {0}", Response));
Response= string.Empty;
isAttemptingRead = false;
}
else if (!string.IsNullOrEmpty(Response))
{
Trace.WriteLine(String.Format("Got Response - {0}", Response));
autoEvent.Set();
}
else if (string.IsNullOrEmpty(Response))
Trace.WriteLine("Empty or Null read");
}
}
代码适用于较短的响应时间(30 毫秒),但是当它到达响应时间为 30 秒的命令时,我得到以下输出(大部分)。
WriteLine(#XSFCD)
- 已创建构造函数
- 启动 ReadLine
- 尝试:#XSFCD
- 当前响应 #XSFCD
- 命令:#XSFCD
- 清除缓冲区:#XSFCD
- 启动 Readline
- 启动 Readline
- 正在启动 Readline 等...
然后我通常只是结束程序。我是否缺少 TimerCallback 方法的某些内容?
【问题讨论】:
标签: c# serial-port