private bool UpdateConnectOpen() { BluetoothUtils.UpdateClient(); try { BluetoothClient.Connect(CurrentBluetoothDeviceInfo.DeviceAddress, BluetoothService.SerialPort); } catch { return(false); } return(Open()); }
/// <summary> Connects to a serial port defined through the current settings. </summary> /// <returns> true if it succeeds, false if it fails. </returns> public bool Connect() { // Reconnecting to the same device seems to fail a lot of the time, so see // if we can remain connected if (_runningBluetoothDeviceInfo != null && _runningBluetoothDeviceInfo.DeviceAddress == CurrentBluetoothDeviceInfo.DeviceAddress && _lazyReconnect) { CurrentBluetoothDeviceInfo = _runningBluetoothDeviceInfo; } else { _runningBluetoothDeviceInfo = CurrentBluetoothDeviceInfo; //BluetoothClient.Close(); } // Closing serial port if it is open //_stream = null; // set pin of device to connect with // check if device is paired //CurrentBluetoothDeviceInfo.Refresh(); try { if (!CurrentBluetoothDeviceInfo.Authenticated) { //Console.WriteLine("Not authenticated"); _showAsConnected = false; return(_showAsConnected); } if (BluetoothClient.Connected && !LazyReconnect) { //Previously connected, setting up new connection" BluetoothUtils.UpdateClient(); } // synchronous connection method if (!BluetoothClient.Connected || !_lazyReconnect) { BluetoothClient.Connect(CurrentBluetoothDeviceInfo.DeviceAddress, BluetoothService.SerialPort); } if (!Open()) { // Desperate attempt: try full reset and open _showAsConnected = UpdateConnectOpen(); return(_showAsConnected); } // Check worker is not running as a precaution. This needs to be rechecked. if (!_worker.IsRunning) { _worker.Start(); } _showAsConnected = true; return(_showAsConnected); } catch (SocketException) { return(false); } catch (InvalidOperationException) { // Desperate attempt: try full reset and open _showAsConnected = UpdateConnectOpen(); return(_showAsConnected); } }