private void ExcuteCmd(CommandBase cmd, out RxPackage pkg, int TimeOut = 1000) { ExcuteCmd(cmd); pkg = new RxPackage() { PackageSize = cmd.ExpectResultLength, }; var StartTime = DateTime.Now.Ticks; while (true) { int len = Comport.BytesToRead; for (int i = 0; i < len; i++) { pkg.AddByte((byte)Comport.ReadByte()); } if (TimeSpan.FromTicks((DateTime.Now.Ticks - StartTime)).TotalSeconds >= (TimeOut / 1000.0)) { throw new Exception("time for waiting result"); } if (pkg.IsPackageFind) { cmd.FromByteArray(pkg.RawData); break; } } }
/// <summary> /// Read package from UART port synchronously with specified timeout value. /// </summary> /// <param name="cancellationToken"></param> /// <param name="timeout"></param> /// <param name="package"></param> /// <returns></returns> private void Read(out RxPackage package, CancellationToken cancellationToken, int timeout = DEFAULT_READ_TIMEOUT) { package = new RxPackage(); var start = DateTime.Now; while (true) { var span = DateTime.Now - start; if (span.TotalMilliseconds > timeout) { throw new TimeoutException("timeout to read package from the serial port."); } if (cancellationToken != CancellationToken.None && cancellationToken.IsCancellationRequested) { throw new OperationCanceledException("operation has cancelled."); } // if one or more bytes are received, push to RxPackageParser. var len = _port.BytesToRead; if (len <= 0) { continue; } var data = new byte[len]; _port.Read(data, 0, len); foreach (var t in data) { package.AddData(t); if (package.IsPackageFound) { break; } } if (package.IsPackageFound) { break; } } if (package.IsPassCRC == false) { throw new Exception("the CRC of the package is error."); } }
/// <summary> /// Read package from UART port synchronously with specified timeout value. /// </summary> /// <param name="Timeout"></param> /// <param name="Package"></param> /// <returns></returns> public void Read(out RxPackage Package, CancellationToken cancellationToken, int Timeout = DEFAULT_READ_TIMEOUT) { Package = new RxPackage(); DateTime start = DateTime.Now; while (true) { var span = DateTime.Now - start; if (span.TotalMilliseconds > Timeout) { throw new TimeoutException("timeout to read package from the serial port."); } if (cancellationToken != CancellationToken.None && cancellationToken.IsCancellationRequested) { throw new OperationCanceledException("operation has cancelled."); } // if one or more bytes are received, push to RxPackageParser. if (port.BytesToRead > 0) { var data = (byte)port.ReadByte(); Package.AddData(data); if (Package.IsPackageFound) { break; } } } if (Package.IsPassCRC == false) { throw new Exception("incorrect CRC value."); } }