2017-06-20 83 views
0

我需要从使用rs232的温度控制器获取一些数据。 控制器在每个完整命令结束时向我发送每个字符的回显,它会返回'§'和'。'。如果命令是否成功应用。我的测试代码如下所示:C#串行端口读取缓冲区中有多个换行符

static string GetData(int memoryAddress) 
{ 
    if (!_session.IsOpen) 
     return "No Connection"; 

    string toSend = "*A_r_" + memoryAddress.ToString() + "_0" + (char)21; 

    foreach (char character in toSend) 
     _session.Write(character.ToString()); 

    Thread.Sleep(100); 
    return _session.ReadExisting(); 
} 

和返回是这样的:

*A_r_0_0§.250§ 

现在我还需要一些数据存储在控制器内,并想重新使用上半部分是有可能使用

ReadNewline (with Newline-Symbol §) 

只获取回声并验证它,这样我就可以在下一个函数中读取返回的数据(如果我选择读取someting)? 首先返回哪个值?最后一个还是最先到达的那个?

也会更好地使用ReadNewline而不是Thread.sleep(100)超时?

+1

更改换行属性,所以你可以使用的ReadLine(),或使用ReadTo()。切勿使用Sleep()来解决问题,强烈避免使用ReadExisting()。你只需要调用ReadTo()两次,首先得到回声并再次得到响应。你是否真的使用了这个回复取决于你。 –

回答

0

这是很好用 'DataReceived' 事件

private Object responseSignal = new object(); 
    private string portResponse; 
    _session.DataReceived += new SerialDataReceivedEventHandler(PortDataReceived); 

static string GetData(int memoryAddress) 
{ 
    if (!_session.IsOpen) 
    return "No Connection"; 

    string toSend = "*A_r_" + memoryAddress.ToString() + "_0" + (char)21; 

    foreach (char character in toSend) 
    _session.Write(character.ToString()); 

    if (System.Threading.Monitor.Wait(responseSignal, 10000)) // max time we want to wait to receive the response 
    { 
     // successful get 
    } 
    else 
    { 
     // failed to receive the response 
    } 
    return portResponse; 
    } 

    public void PortDataReceived(object sender, SerialDataReceivedEventArgs e) 
    { 
     try 
     { 
      lock (responseSignal) 
      { 
       string tmpPortResponse = _session.ReadExisting(); 
       portResponse += tmpPortResponse; 


       //Complete the response only when you get the end character 
       if (tmpPortResponse.Contains('.')) 
       { 
        // signal allows a waiting SendMessage method to proceed 
        System.Threading.Monitor.Pulse(responseSignal); 
       } 
      } 
     } 
     catch (Exception ex) 
     { 
      throw new Exception(ex.Message.ToString()); 
     } 
    } 
+0

在第一个回声(char)到达后不会调用它,所以我仍然需要等待其余的到达? – Darki

+0

是的。您可以存储接收到的数据,并在收到您正在查找的结束字符('。')时发出事件信号。用这种方法代替使用Thread.Sleep()是很好的做法 – JSR