/// <summary> /// Asynchronously gets the requested service /// </summary> public static Task<IDevice> ConnectAsync(this IAdapter adapter, IDevice device) { if (device.State == DeviceState.Connected) return Task.FromResult<IDevice>(device); var tcs = new TaskCompletionSource<IDevice>(); EventHandler<DeviceConnectionEventArgs> h = null; EventHandler<DeviceConnectionEventArgs> he = null; h = (sender, e) => { Mvx.TaggedTrace("ConnectAsync", "Connected: {0} {1}", e.Device.ID, e.Device.Name); if (e.Device.ID == device.ID) { adapter.DeviceConnected -= h; adapter.DeviceConnectionError -= he; tcs.TrySetResult(e.Device); } }; he = (sender, e) => { // Would be nice to use C#6.0 null-conditional operators like e.Device?.ID Mvx.TaggedWarning("ConnectAsync", "Connection Error: {0} {1}", (e.Device != null ? e.Device.ID.ToString() : ""), (e.Device != null ? e.Device.Name : "")); if(e.Device.ID == device.ID) { adapter.DeviceConnectionError -= he; adapter.DeviceConnected -= h; tcs.TrySetException(new Exception("Connect operation exception")); } }; adapter.DeviceConnected += h; adapter.DeviceConnectionError += he; adapter.ConnectToDevice(device); return tcs.Task; }
/// <summary> /// Asynchronously gets the requested service /// </summary> public static Task<IDevice> ConnectAsync(this IAdapter adapter, IDevice device) { if (device.State == DeviceState.Connected) return Task.FromResult<IDevice> (null); var tcs = new TaskCompletionSource<IDevice> (); EventHandler<DeviceConnectionEventArgs> h = null; h = (sender, e) => { Debug.WriteLine ("CCC: " + e.Device.ID + " " + e.Device.State); if (e.Device.ID == device.ID) { adapter.DeviceConnected -= h; tcs.SetResult (e.Device); } }; adapter.DeviceConnected += h; adapter.ConnectToDevice (device); return tcs.Task; }
/// <summary> /// Connect to a discovered <see cref="IBlePeripheral" />. Timeout if the connection is not obtained in /// the provided time /// </summary> public static Task<IBleGattServer> ConnectToDevice( this IBluetoothLowEnergyAdapter adapter, IBlePeripheral device, TimeSpan timeout ) { return adapter.ConnectToDevice( device, new CancellationTokenSource( timeout ).Token ); }