C#串口发送等待接收

时间:2013-08-27 07:24:24

标签: c# .net serial-port

我有一些命令存储在列表中。我需要进入thrue列表,发送命令并等待特定时间的回复(时间也在列表中)。

这是我的代码:

SerialPort myPort = new SerialPort("COM1", 9600, Parity.None, 8, StopBits.One);

bool _doSend;
string _inSensor;
int _threadWait;

Thread myThread = new Thread(myStartingMethod);

checkPortStatus();

private void checkPortStatus()
{
    if (!(myPort.IsOpen == true))
        {
            myPort.Open();
            myPort.DataReceived += new SerialDataReceivedEventHandler(myPort_DataReceived);
            _doSend = true;
            myThread.Start();
        }
        else
        {
            _doSend = false;
            myPort.Close();
            myThread.Abort();
        }
}

public void myStartingMethod()
    {
        //Create list of commands
        List<List<String>> atCommands = new List<List<string>>();

        //Create list of time to wait for informaition (recieve on setial port)
        List<List<String>> thSleep = new List<List<string>>();

        thSleep.Add(new List<string> { "1", "1000" }); //{"Sensor ID", "Time to wait for replay"}
        thSleep.Add(new List<string> { "2", "5000" });

        atCommands.Add(new List<string> { "1", "A111", "B111"});  //{"Sensor ID", "command 1", "command 2"}
        atCommands.Add(new List<string> { "2", "C222", "D222"});
        atCommands.Add(new List<string> { "1", "A111", "B111", "E111", "F111"});  
        atCommands.Add(new List<string> { "2", "D111"});

        while(_doSend)
        {
            foreach (var _subList in thSleep)
            {
                _inSensor = _subList.ElementAt(0);
                _threadWait = Convert.ToInt32(_subList.ElementAt(1));

                foreach(var subCommands in atCommands)
                {
                     if(_inSensor == subCommand.AlementAt(0)
                     {
                        foreach (string command in subCommands.Skip(1))
                        {
                            myPort.Write(command + "\r\n");

                            Thread.Sleep(_threadWait);
                        }
                     }
                }
            }

        }
    }
void myPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
    {
        //Do something with data and save to Database
    }

我的问题是:如何100%确定我收到了我发送的命令的回复。如果在给定时间内没有回复,我需要继续执行其他命令。在“myPort_DataReceived”中,我想将最后发送的命令和收到的数据存储到mySql数据库中。 我知道如何连接到数据库,但我遇到了等待响应的问题。

0 个答案:

没有答案