public DecompressieKamer(int maxTries = 3) { AreValuesUpToDate = false; _SerialPort = new SerialPort(); //RP6 default config 38400,8N1 _SerialPort.BaudRate = 38400; _SerialPort.DataBits = 8; _SerialPort.Parity = Parity.None; _SerialPort.StopBits = StopBits.One; if (!SearchForDecompressionDevice(maxTries)) { _SerialPort.Dispose(); throw new NoDeviceFoundException(); } _Message = new Message(_SerialPort); _LastTimeAlive = DateTime.Now; _LastUpdateTime = DateTime.Now; }
/// <summary> /// Automatically check existing devices and see if they are a decompression chamber by trial and error /// </summary> /// <param name="maxTries"></param> /// <returns>true if found false if not</returns> private bool SearchForDecompressionDevice(int maxTries) { if (_SerialPort == null) { return false; } bool found = false; int tries = 0; Thread.Sleep(1000); while (!found && tries < maxTries) { foreach (string port in SerialPort.GetPortNames()) { if (_SerialPort.IsOpen) { try { _SerialPort.Close(); } catch (Exception) { /*We just want to disconnect and continue searching*/ } } try { _SerialPort.PortName = port; _SerialPort.Open(); Message message = new Message(_SerialPort); message.BeginWrite(); message.Action = (byte)Actions.CHECK_FOR_DECOMPRESSION_DEVICE; message.Write_byte((byte)MsgStruct.MS_DataBegin); message.Send(); Stopwatch watch = new Stopwatch(); watch.Start(); while (message.Receive() != 6 && watch.ElapsedMilliseconds < 150) { } if (message.DataLength == 1 && !message.IsCorrupt) { byte output = 0; if (message.Action == (byte)Actions.HERE_IS_A_DECOMPRESSION_DEVICE && message.Read_byte(ref output)) { if (output == (byte)MsgStruct.MS_DataEnd) { //found decompression device return true; } } } } catch (Exception) { continue; } } ++tries; Thread.Sleep(1); } return false; }