public SbepMessage ReceiveSbep() { var i = 0; SbepMessage message = null; var sw = Stopwatch.StartNew(); while (sw.ElapsedMilliseconds < 1000 && i < _receiveBuffer.Length) { var avail = _port.BytesToRead; if (avail == 0) { Thread.Sleep(20); continue; //Don't restart stopwatch. } _port.Read(_receiveBuffer, i, avail); i += avail; message = new SbepMessage(_receiveBuffer, i); if (!message.Incomplete) { break; } sw.Restart(); //Give some more time for bytes } if (message == null || message.Incomplete || message.Invalid) { UpdateStatus("Timeout or Checksum Error"); } else { UpdateStatus("Received: " + String.Join(" ", Array.ConvertAll(message.Bytes.ToArray(), x => x.ToString("X2")))); } return(message); }
public void SendSbep(SbepMessage message) { int attempts = 0; while (true) { _port.DiscardInBuffer(); _port.DiscardOutBuffer(); var packetSize = message.Bytes.Length; UpdateStatus("Sending " + String.Join(" ", Array.ConvertAll(message.Bytes, x => x.ToString("X2")))); _port.Write(message.Bytes, 0, packetSize); //Every byte sent is echoed back since TX/RX lines are connected. //They have to be read back from the serial port before getting to a response packet. var sw = Stopwatch.StartNew(); byte[] echo = new byte[packetSize]; while (sw.ElapsedMilliseconds < 1000) { if (_port.BytesToRead < packetSize) { Thread.Sleep(10); continue; } _port.Read(echo, 0, packetSize); break; } //A check could be made to see if bytes matched what was sent. But it's kind of pointless //as it is not the radio echoing the bytes, it's just the computer hearing itself. if (echo.Max() == 0x00) { if (attempts == 4) { throw new Exception("RIB or interface cable does not appear to be connected to the computer. Did the cable to the computer come loose?"); } Thread.Sleep(500); attempts++; continue; } if (!message.ExpectAck) { return; } //Now look for actual response from the radio. sw = Stopwatch.StartNew(); int ack = 0; while (sw.ElapsedMilliseconds < 1000) { if (_port.BytesToRead < 1) { Thread.Sleep(10); continue; } ack = _port.ReadByte(); break; } if (ack == 0x50) { return; } if (attempts == 4) { throw new Exception("The radio failed to ackowledge command. Try power cycling the radio and running the operation again."); } Thread.Sleep(500); attempts++; } }