public async void SubscribeAndHandleDeviceAsync(IBacGenericDevice device) { //check if we chose the same device if (ConnectedDevice == device) { return; } if (ConnectedDevice != null) { //unsubsribe from connection events. Devices could potentially persist. ConnectedDevice.ConnectionStateChanged -= Device_ConnectionStateChanged; //Disconnect if choosing new device. if (ConnectedDevice.ConnectionState != BACConnectionState.DISCONNECTED) { await ConnectedDevice.Disconnect(); } } ConnectedDevice = device; if (ConnectedDevice != null) { ConnectedDevice.ConnectionStateChanged += Device_ConnectionStateChanged; Application.Current.Properties["device"] = ConnectedDevice.Guid; } // HandleConnectionState(); }
/// <summary> /// Start an auto-connection sequence /// </summary> private async void StartAutoConnectionRoutine() { Console.WriteLine("Started auto connect !!"); if (ConnectedDevice != null) { await ConnectedDevice.Disconnect(); ConnectedDevice = null; } while (ConnectedDevice == null && List.Count > 0) { ConnectedDevice = await BacCommunication.CurrentRepository.StartBluetoothLeAutoConnection(List); if (ConnectedDevice != null) { var wheelDiameter = await ConnectedDevice.Read(227); if (Math.Abs(wheelDiameter - 279.4) > 0.1) { try { await ConnectedDevice.Write(227, (short)279.4); } catch (Exception exception) { Console.WriteLine(exception); UnsubscribeToDevice(); HandleConnectionState(); } } var gearRatio = await ConnectedDevice.Read(226) / 256; if (gearRatio != 1) { try { await ConnectedDevice.Write(226, 1); } catch (Exception exception) { Console.WriteLine(exception); UnsubscribeToDevice(); HandleConnectionState(); } } } } if (ConnectedDevice == null) { return; } App.LocalDevice = ConnectedDevice; HandleConnectionState(); SubscribeToConnectedDevice(); }
private async void ConnectController() { if (ConnectedDevice != null) { switch (ConnectedDevice.ConnectionState) { case BACConnectionState.DISCONNECTED when !Application.Current.Properties.ContainsKey("device"): await _pageService.PushAsync(new ListOfDevices(this)); break; case BACConnectionState.DISCONNECTED: StartAutoConnectionRoutine(); break; case BACConnectionState.CONNECTED: await ConnectedDevice.Disconnect(); List.Remove(Application.Current.Properties["device"].ToString()); ConnectedDevice = null; break; case BACConnectionState.CONNECTING: break; case BACConnectionState.DISCONNECTING: break; case BACConnectionState.ERROR_STATE: break; default: throw new ArgumentOutOfRangeException(); } } else { if (!Application.Current.Properties.ContainsKey("device")) { await _pageService.PushAsync(new ListOfDevices(this)); } SetupCommunications(); } }