private Message SendAndWaitForResponse(BootloaderClient ep, Message request, int timeout, bool throw_timeout_exception = true, int retries = 3) { Debug.Assert(ep.BootloaderAddress == request.Address); MessageExtractor me = new MessageExtractor(); byte[] buffer = new byte[1024]; byte[] empty = new byte[128 + 4 + 5]; Message msg = null; while (retries-- >= 0) { // setup serial port ep.Port.DiscardInBuffer(); ep.Port.DiscardOutBuffer(); ep.Port.ReadTimeout = 200; // send data ep.Port.Write(request.Binary, 0, request.BinarySize); Thread.Sleep(0); //Debug.WriteLine("sent " + request.BinarySize.ToString()); // and wait for response DateTime start = DateTime.Now; do { int read = -1; try { read = ep.Port.Read(buffer, 0, buffer.Length); } catch (TimeoutException tex) { Debug.WriteLine("TO"); continue; // ignore timeouts } catch (Exception ex) { Debug.WriteLine("EX"); break; // shit happens } me.AddData(buffer, read); if (me.TryExtract(ref msg, request.Address, request.Type)) { break; // ok, got message! } } while ((DateTime.Now - start).TotalMilliseconds <= timeout && timeout != -1); // if message was correctly received then stop communication if (msg != null) { break; } Debug.WriteLine("RETRY"); } if (msg == null && throw_timeout_exception) { throw new TimeoutException(string.Format("No response from bootloader device 0x{0:X2} on {1}", ep.BootloaderAddress, ep.Port.PortName)); } return(msg); }