예제 #1
0
        /// <summary>
        /// 发送Hex字符串,比如7E 48 53 44
        /// </summary>
        /// <param name="str"></param>
        public DataResult WriteHexString(string str, int timeOut)
        {
            if (!Monitor.TryEnter(_flag))
            {
                throw new Exception("串口正在执行命令,请稍后");
            }
            lock (_flag)
            {
                _dataRecv = null;
                if (null != _port && _port.IsOpen)
                {
                    _port.WriteHexString(str);
                    Console.WriteLine($"发送数据:{str}");
                }
                else
                {
                    throw new Exception("请先打开串口");
                }

                var index = 1;
                while (index < timeOut)
                {
                    Thread.Sleep(1);
                    index++;
                    if (null != _dataRecv && _dataRecv.Length > 1)
                    {
                        var newBuffer = new byte[_dataRecv.Length];
                        Array.Copy(_dataRecv, 0, newBuffer, 0, _dataRecv.Length);
                        //接受到应答数据
                        Console.WriteLine($"接受到应答数据:{GetHexString(newBuffer)}");
                        //对接受到的数据进行解析
                        if (!CommandFactory.ValidateData(newBuffer))
                        {
                            throw new Exception("接受到的数据校验失败");
                        }
                        return(new DataResult(newBuffer));
                    }
                }

                throw new Exception("执行命令超时");
            }
        }