Ejemplo n.º 1
0
        /// <summary>
        /// Attempt to connect to the first device that passes the filter of <paramref name="settings" />, and continue the attempt
        /// until
        /// cancellation token is triggered.
        /// </summary>
        public static async Task <BlePeripheralConnectionRequest> FindAndConnectToDevice(
            [NotNull] this IBluetoothLowEnergyAdapter adapter, ScanSettings settings, CancellationToken ct,
            IProgress <ConnectionProgress> progress = null)
        {
            if (settings.Filter == null)
            {
                throw new ArgumentNullException(
                          nameof(settings),
                          "Scan settings must have a non-null ScanFilter when calling FindAndConnectToDevice");
            }

            var cts = CancellationTokenSource.CreateLinkedTokenSource(ct);

            progress?.Report(ConnectionProgress.SearchingForDevice);
            var device = adapter.DiscoveredPeripherals.FirstOrDefault(p => settings.Filter.Passes(p.Advertisement));

            if (device == null)
            {
                await adapter.ScanForBroadcasts(
                    settings,
                    Observer.Create(
                        (Action <IBlePeripheral>)(p =>
                {
                    device = p;
                    cts.Cancel();
                })),
                    cts.Token).ConfigureAwait(false);
            }

            return(device == null
            ? ct.IsCancellationRequested
               ? new BlePeripheralConnectionRequest(ConnectionResult.ConnectionAttemptCancelled, null)
               : new BlePeripheralConnectionRequest(ConnectionResult.DeviceNotFound, null)
            : await adapter.ConnectToDevice(device, ct, progress).ConfigureAwait(false));
        }
Ejemplo n.º 2
0
        public async Task <bool> BLE_Connect(IBlePeripheral device)
        {
            // Get BLE device
            if ((null != g_BLEAdapterObj) && (null != device))
            {
                // Try connect to ble device
                BlePeripheralConnectionRequest connection = await g_BLEAdapterObj.ConnectToDevice(device, TimeSpan.FromSeconds(15));

                if (connection.IsSuccessful())
                {
                    // Invoke connection state callback
                    OnBLEConnection_StateChange(ConnectionState.Connected);

                    if (true == await SetupBLEConnection(connection))
                    {
                        return(true);
                    }
                    else
                    {
                        await connection.GattServer.Disconnect();
                    }
                }
            }

            return(false);
        }
Ejemplo n.º 3
0
 /// <summary>
 /// Connect to a discovered <see cref="IBlePeripheral" />. Timeout if the connection is not obtained in
 /// the provided time
 /// </summary>
 public static Task <BleDeviceConnection> ConnectToDevice(this IBluetoothLowEnergyAdapter adapter,
                                                          IBlePeripheral device, TimeSpan timeout,
                                                          IProgress <ConnectionProgress> progress = null)
 {
     Contract.Requires <ArgumentNullException>(adapter != null);
     // ReSharper disable once PossibleNullReferenceException
     return(adapter.ConnectToDevice(device, new CancellationTokenSource(timeout).Token, progress));
 }
        /// <summary>
        /// Attempt to find and connect to the given device by MAC address (6 bytes). Timeout if the connection is not obtained in
        /// the provided time
        /// </summary>
        public static Task <BlePeripheralConnectionRequest> ConnectToDevice(
            [NotNull] this IBluetoothLowEnergyAdapter adapter, Guid id, TimeSpan timeout,
            IProgress <ConnectionProgress> progress = null)
        {
            if (adapter == null)
            {
                throw new ArgumentNullException(nameof(adapter));
            }

            return(adapter.ConnectToDevice(id, new CancellationTokenSource(timeout).Token, progress));
        }
Ejemplo n.º 5
0
        public override async void OnAppearing()
        {
            // if we're budy or have a valid connection, then no-op
            if (IsBusy || (m_device != null && m_device.State != ConnectionState.Disconnected))
            {
                return;
            }

            IsBusy = true;
            CloseConnection();
            Log.Debug("Connecting to device. address={0}", m_peripheral.Address);
            m_device = await m_ble.ConnectToDevice(m_peripheral.Model);

            RaisePropertyChanged(nameof(DeviceConnectionState));
            m_device.Subscribe(
                Observer.Create(
                    ( ConnectionState c ) =>
            {
                Log.Info("Device state changed. address={0} status={1}", m_peripheral.Address, c);
                RaisePropertyChanged(nameof(DeviceConnectionState));
            }));
            Log.Debug("Connected to device. address={0} status={1}", m_peripheral.Address, m_device.State);
            if (m_device.State == ConnectionState.Connected || m_device.State == ConnectionState.Connecting)
            {
                var services = (await m_device.ListAllServices()).ToList();
                foreach (var serviceId in services)
                {
                    if (Services.Any(viewModel => viewModel.Guid.Equals(serviceId)))
                    {
                        continue;
                    }
                    Services.Add(new BleGattServiceViewModel(serviceId, m_device, m_dialog));
                }
                if (services.Count == 0)
                {
                    m_dialog.Toast("No services found");
                }
            }
            else
            {
                Log.Warn(
                    "Error connecting to device. address={0} state={1}",
                    m_device.Address.EncodeToBase16String(),
                    m_device.State);
                m_dialog.Toast("Error connecting to device");
            }
            Log.Debug("Read services. address={0} status={1}", m_peripheral.Address, m_device.State);
            IsBusy = false;
            RaisePropertyChanged(nameof(DeviceConnectionState));
        }
        public async Task OpenConnection()
        {
            // if we're busy or have a valid connection, then no-op
            if (IsBusy || m_gattServer != null && m_gattServer.State != ConnectionState.Disconnected)
            {
                //Log.Debug( "OnAppearing. state={0} isbusy={1}", m_gattServer?.State, IsBusy );
                return;
            }

            await CloseConnection();

            IsBusy = true;

            var connection = await m_bleAdapter.ConnectToDevice(
                device : m_peripheral.Model,
                timeout : TimeSpan.FromSeconds(CONNECTION_TIMEOUT_SECONDS),
                progress : progress => { Connection = progress.ToString(); });

            if (connection.IsSuccessful())
            {
                m_gattServer = connection.GattServer;
                Log.Debug("Connected to device. id={0} status={1}", m_peripheral.Id, m_gattServer.State);

                Settings.IsConnectedBLE = true;

                m_gattServer.Subscribe(
                    async c =>
                {
                    if (c == ConnectionState.Disconnected)
                    {
                        m_dialogManager.Toast("Device disconnected");
                        await CloseConnection();

                        //await OpenConnection();
                    }

                    Connection = c.ToString();
                });

                Connection = "Reading Services";
                try
                {
                    var services = (await m_gattServer.ListAllServices()).ToList();
                    foreach (var serviceId in services)
                    {
                        if (Services.Any(viewModel => viewModel.Guid.Equals(serviceId)))
                        {
                            continue;
                        }

                        Services.Add(new BleGattServiceViewModel(serviceId, m_gattServer, m_dialogManager));
                    }

                    if (Services.Count == 0)
                    {
                        m_dialogManager.Toast("No services found");
                    }

                    Connection = m_gattServer.State.ToString();
                }
                catch (GattException ex)
                {
                    Log.Warn(ex);
                    m_dialogManager.Toast(ex.Message, TimeSpan.FromSeconds(3));
                }
            }
            else
            {
                String errorMsg;
                if (connection.ConnectionResult == ConnectionResult.ConnectionAttemptCancelled)
                {
                    errorMsg = "Connection attempt cancelled after {0} seconds (see {1})".F(
                        CONNECTION_TIMEOUT_SECONDS,
                        GetType().Name + ".cs");
                }
                else
                {
                    errorMsg = "Error connecting to device: {0}".F(connection.ConnectionResult);
                }

                Settings.IsConnectedBLE = false;

                Log.Info(errorMsg);
                m_dialogManager.Toast(errorMsg, TimeSpan.FromSeconds(5));
            }

            IsBusy = false;
        }
Ejemplo n.º 7
0
 /// <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));
 }
Ejemplo n.º 8
0
        private async void Button_Clicked_1(object sender, EventArgs e)
        {
            var connection = await ble.ConnectToDevice(
                // The IBlePeripheral to connect to
                blePeripherals[0],
                // TimeSpan or CancellationToken to stop the
                // connection attempt.
                // If you omit this argument, it will use
                // BluetoothLowEnergyUtils.DefaultConnectionTimeout
                TimeSpan.FromSeconds(15),
                // Optional IProgress<ConnectionProgress>
                progress => Debug.WriteLine(progress)
                );

            /*
             * Connect to a specific device without manually scanning
             * In use-cases where you are not scanning for advertisements but rather looking to connect to a specific, known, device:
             */
            //var connection = await ble.FindAndConnectToDevice(
            //   new ScanFilter()
            //      .SetAdvertisedDeviceName("foo")
            //      .SetAdvertisedManufacturerCompanyId(0xffff)
            //      .AddAdvertisedService(guid),
            //   TimeSpan.FromSeconds(30));

            if (connection.IsSuccessful())
            {
                var gattServer = connection.GattServer;
                // ... do things with gattServer here... (see later examples...)

                /*
                 * See & Observe server connection Status
                 */
                Debug.WriteLine(gattServer.State); // e.g. ConnectionState.Connected
                                                   // the server implements IObservable<ConnectionState> so you can subscribe to its state
                gattServer.Subscribe(state =>
                {
                    if (state == ConnectionState.Disconnected)
                    {
                        Debug.WriteLine("Connection Lost");
                    }
                });

                var known = new KnownAttributes();

                foreach (var guid in await gattServer.ListAllServices())
                {
                    Debug.WriteLine($"service: {known.GetDescriptionOrGuid(guid)}");
                }

                //Debug.WriteLine($"service: {serviceGuid}");
                //foreach (var guid in await gattServer.ListServiceCharacteristics(serviceGuid))
                //{
                //    Debug.WriteLine($"characteristic: {known.GetDescriptionOrGuid(guid)}");
                //}

                //Be sure to disconnect when you are done:
                await gattServer.Disconnect();
            }
            else
            {
                // Do something to inform user or otherwise handle unsuccessful connection.
                Debug.WriteLine("Error connecting to device. result={0:g}", connection.ConnectionResult);
                // e.g., "Error connecting to device. result=ConnectionAttemptCancelled"
            }
        }