串行设备驱动程序实现

时间:2017-08-19 06:32:49

标签: c# serial-port

这里我试图开发一个好的模式来执行命令并通过COM端口接收响应。你对这个有什么看法,它有明显的缺陷吗?

public int COMTimeout { get; set; } = 5000; //ms
private SerialPort _serial;
public bool getLinkState()
    {
        if (_serial != null && _serial.IsOpen)
        {
            try
            {
                _serial.WriteLine("state");
                int time = 0;
                bool state = false;
                do
                {
                    Thread.Sleep(10);
                    time += 10;
                    if (_serial.BytesToRead > 0)
                    {
                        _readbuffer = _readbuffer + _serial.ReadLine();
                        int pos = _readbuffer.IndexOf("OK\r");
                        if (pos > -1 )
                        {
                            state = true;
                            _readbuffer = _readbuffer.Remove(pos, 3);
                        }
                    }
                } while (!state && time < COMTimeout);
                if (state)
                    return true;
                else
                {
                    OnCommandTimeout?.Invoke(this, new DEventArgs("state"));
                    return false;
                }
            }
            catch (TimeoutException) { OnCommandTimeout?.Invoke(this, new DEventArgs("state")); }
        }
        return false;
    }

另外,对于为成功执行而触发的每个命令实现单独的事件,您会怎么说?

0 个答案:

没有答案