System.Timers.Timer用法

时间:2013-07-15 19:04:53

标签: c# timer serial-port

出于这个问题的目的,我将整整包括一类:

public class SerialPortConnection
{
    private SerialPort serialPort;
    private string ping;
    double failOut;
    bool isReceiving;

    public SerialPortConnection(string comPort = "Com1", int baud = 9600, System.IO.Ports.Parity parity = System.IO.Ports.Parity.None, int dataBits = 8, System.IO.Ports.StopBits stopBits = System.IO.Ports.StopBits.One, string ping = "*IDN?", double failOut = 2)
    {
        this.ping = ping;
        this.failOut = failOut * 1000;

        try
        {
            serialPort = new SerialPort(comPort, baud, parity, dataBits, stopBits);
        }
        catch (Exception e)
        {
            throw e;
        }
    }

    //Open Serial Connection. Returns False If Unable To Open.
    public bool OpenSerialConnection()
    {
        //Opens Initial Connection:
        try
        {
            serialPort.Open();
            serialPort.Write("REMOTE\r");
        }
        catch (Exception e)
        {
            throw e;
        }

        serialPort.Write(ping + "\r");
        var testReceived = "";
        isReceiving = true;

        Timer StopWatch = new Timer(failOut);
        StopWatch.Elapsed += new ElapsedEventHandler(OnTimedEvent);
        StopWatch.Interval = failOut;
        StopWatch.Enabled = true;

        while (isReceiving == true)
        {
            try
            {
                testReceived += serialPort.ReadExisting();
            }
            catch (Exception e)
            {
                throw e;
            }
        }

        StopWatch.Dispose();

        if (testReceived.Contains('>'))
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    public string WriteSerialConnection(string SerialCommand)
    {
        try
        {
            serialPort.Write(String.Format(SerialCommand + "\r"));
            var received = "";
            bool isReceiving = true;

            Timer StopWatch = new Timer(failOut);
            StopWatch.Elapsed += new ElapsedEventHandler(OnTimedEvent);
            StopWatch.Interval = failOut;
            StopWatch.Enabled = true;

            while (isReceiving == true)
            {
                try
                {
                    received += serialPort.ReadExisting();
                }
                catch (Exception e)
                {
                    throw e;
                }
            }

            if (received.Contains('>'))
            {
                return received;
            }
            else
            {
                received = "Error: No Data Received From Device";
                return received;
            }

            StopWatch.Dispose();
        }
        catch (Exception e)
        {
            throw e;
        }        
    }

    //Closes Serial Connection. Returns False If Unable To Close.
    public bool CloseSerialConnection()
    {
        try
        {
            serialPort.Write("LOCAL\r");
            serialPort.Close();
            return true;
        }
        catch (Exception e)
        {
            throw e;
        }
    }

    private void OnTimedEvent(object source, ElapsedEventArgs e)
    {
        isReceiving = false;
    }
}

我在这里尝试做的是保持循环运行一段时间(在这种情况下为2秒),因为连接到我正在使用的串行端口的设备是不可预测的。我不知道我将收到哪些数据,我不知道需要多长时间。这是无法修复的,是我必须要处理的事情。目前,我最好的选择是等待一段时间并检查我收到的结束令牌数据(“>”)。我甚至在课堂上尝试连接定时器,如下所示:

Timer StopWatch = new Timer(failOut * 1000);
StopWatch.Elapsed += new ElapsedEventHandler(OnTimedEvent);
StopWatch.Interval = failOut;
StopWatch.Enabled = true;

但它似乎不起作用。事件本身如此:

private void OnTimedEvent(object source, ElapsedEventArgs e)
{
    isReceiving = false;
}

我的目标是切断循环isReceiving与:

相关联
(while isReceiving == true)
{
    //Do Something
}

但它似乎不起作用。我假设我完全误解了计时器的功能,但我之前已经有了建议来实现它。我究竟做错了什么?如果我只是完全滥用它,我可以使用什么而不是计时器?正如我所说的,我别无选择,只能等待一段时间,检查我收到了什么。除了等待和希望得到一些东西之外,这是无法避免或处理的。

编辑:

也许我最好澄清一下。 OnTimedEvent事件正在触发,变量设置为false但它不会切断循环,因为isReceiving未设置为false。

编辑2:

先生。 Passant的回答很好地阻止了我遇到的一个奇怪的错误。因为我不相信这是他的答案中的一个问题,它更可能是一个硬件缺陷,或者其他一些奇怪和模糊不清的东西,我将他的答案标记为已接受。我建议任何选择实施他的答案的人也会查看我在这里提交的问题:

Apparent IO.Ports.SerialPort Flaw in C# or Possible Hardware Flaw

1 个答案:

答案 0 :(得分:3)

你自己太难了。只需将SerialPort.NewLine属性更改为“>”即可。并使用SerialPort.ReadLine()来读取响应。如果需要,您仍然可以使用超时,分配SerialPort.ReadTimeout属性并准备捕获TimeoutException。