/// <summary>
        /// Connects to the GATT server hosted on the Bluetooth LE device.
        /// </summary>
        /// <param name="address"> The device address of the destination device.
        /// </param>
        /// <returns> Return true if the connection is initiated successfully. The connection result
        ///         is reported asynchronously through the
        ///         {@code BluetoothGattCallback#onConnectionStateChange(android.bluetooth.BluetoothGatt, int, int)}
        ///         callback. </returns>
        public virtual bool Connect(Context context, BluetoothDevice device)
        {
            if (device == null)
            {
                Debug.WriteLine(TAG, "Device not found. Unable to connect.");
                return(false);
            }

            // Previously connected device.  Try to reconnect.
            if (DeviceAddress != null && device.Address.Equals(DeviceAddress) && Gatt != null)
            {
                Debug.WriteLine(TAG, "Trying to use an existing mBluetoothGatt for connection.");
                if (Gatt.Connect())
                {
                    SetmConnectionState(STATE_CONNECTING);
                    return(true);
                }
                else
                {
                    return(false);
                }
            }

            // We want to directly connect to the device, so we are setting the autoConnect
            // parameter to false.
            Gatt = device.ConnectGatt(context, false, mGattCallback);
            RefreshDeviceCache(Gatt);
            Debug.WriteLine(TAG, "Trying to create a new connection.");
            DeviceAddress = device.Address;
            SetmConnectionState(STATE_CONNECTING);
            return(true);
        }
예제 #2
0
        public void connect(string deviceAddress)
        {
            if (gattConnection != null)
            {
                disconnect();
            }
            var device = devices.FirstOrDefault((dev) => dev.Address.ToUpper().Equals(deviceAddress.ToUpper()));

            if (device != null)
            {
                gattConnection = device.ConnectGatt(MainActivity.MainContext, false, bluetoothGattCallback);
                gattConnection.Connect();
            }
        }
예제 #3
0
        private void PerformConnectToDevice(IDevice device)
        {
            var bleDevice = device.NativeDevice as BluetoothDevice;

            if (bleDevice == null)
            {
                return;
            }

            var remoteDevice = _adapter.GetRemoteDevice(bleDevice.Address);

            if (remoteDevice == null)
            {
                return;
            }

            _gatt = remoteDevice.ConnectGatt(Android.App.Application.Context, false, _callback);
            _gatt.Connect();
        }
예제 #4
0
 private void PlatformConnect()
 {
     if (_gatt == null)
     {
         if (Build.VERSION.SdkInt >= BuildVersionCodes.M)
         {
             // 使用 LE 传输方式进行连接, 避免设备不支持 BR/EDR 方式时出现 133 连接失败
             _gatt = _device.ConnectGatt(Application.Context, false, _callback, BluetoothTransports.Le);
         }
         else
         {
             _gatt = _device.ConnectGatt(Application.Context, false, _callback);
         }
     }
     else
     {
         _gatt.Connect();
     }
 }
예제 #5
0
파일: BLEDevice.cs 프로젝트: poz1/Poz1.BLE
        public Task ConnectAsync()
        {
            connectTCS = new TaskCompletionSource <bool>();

            try
            {
                _gatt = _nativeDevice.ConnectGatt(Application.Context, false, this);
                var connectionState = _bluetoothManager.GetConnectionState(_nativeDevice, ProfileType.Gatt);

                if (connectionState != ProfileState.Connected)
                {
                    _gatt.Connect();
                }
            }
            catch (Exception e)
            {
                connectTCS.TrySetException(e);
            }

            return(connectTCS.Task);
        }
예제 #6
0
        /**
         * Connects to the GATT server hosted on the Bluetooth LE device.
         *
         * @param address The device address of the destination device.
         *
         * @return Return true if the connection is initiated successfully. The connection result
         *         is reported asynchronously through the
         *         {@code BluetoothGattCallback#onConnectionStateChange(android.bluetooth.BluetoothGatt, int, int)}
         *         callback.
         */
        public bool Connect(String address)
        {
            if (mBluetoothAdapter == null || address == null)
            {
                Log.Warn(TAG, "BluetoothAdapter not initialized or unspecified address.");
                return(false);
            }

            // Previously connected device.  Try to reconnect.
            if (mBluetoothDeviceAddress != null && address == mBluetoothDeviceAddress && mBluetoothGatt != null)
            {
                Log.Debug(TAG, "Trying to use an existing mBluetoothGatt for connection.");
                if (mBluetoothGatt.Connect())
                {
                    mConnectionState = State.Connecting;
                    return(true);
                }
                else
                {
                    return(false);
                }
            }

            BluetoothDevice device = mBluetoothAdapter.GetRemoteDevice(address);

            if (device == null)
            {
                Log.Warn(TAG, "Device not found.  Unable to connect.");
                return(false);
            }
            // We want to directly connect to the device, so we are setting the autoConnect
            // parameter to false.
            mBluetoothGatt = device.ConnectGatt(this, false, new BGattCallback(this));
            Log.Debug(TAG, "Trying to create a new connection.");
            mBluetoothDeviceAddress = address;
            mConnectionState        = State.Connecting;
            return(true);
        }
예제 #7
0
        public void Connect(ConnectParameters connectParameters, CancellationToken cancellationToken)
        {
            IsOperationRequested   = true;
            IsAutoConnectRequested = connectParameters.AutoConnect;

            if (connectParameters.ForceBleTransport)
            {
                ConnectToGattForceBleTransportAPI(connectParameters.AutoConnect, cancellationToken);
            }
            else
            {
                // If gatt is null then initiate the connection process by passing application context , connection parameters
                //and gattcallbacks.
                if (null == _gatt)
                {
                    _gatt = BluetoothDevice.ConnectGatt(Application.Context, connectParameters.AutoConnect, _gattCallback);
                }
                //else a valid gatt object is already exist.Just call connect. DO NOT craete new Gatt object by calling ConnectGatt.
                else
                {
                    _gatt.Connect();
                }
            }
        }
        protected override Task ConnectAsync()
        {
            if (bluetoothAdapter == null)
            {
                return(Task.FromException(new BluetoothLEException("BluetoothAdapter not initialized.")));
            }

            if (bluetoothGatt == null)
            {
                gattCallback = new GattCallbacks(
                    (gatt, status, newState) =>                     // onConnectionStateChange
                {
                    if (newState == ProfileState.Connected)
                    {
                        //intentAction = BluetoothLeService.ACTION_GATT_CONNECTED;
                        //BluetoothLeService.this.mConnectionState = 2;
                        //BluetoothLeService.this.broadcastUpdate(intentAction);
                        System.Diagnostics.Debug.WriteLine("Connected to GATT server.");
                        System.Diagnostics.Debug.WriteLine($"Attempting to start service discovery:{gatt?.DiscoverServices()}");
                    }
                    else if (newState == ProfileState.Disconnected)
                    {
                        //intentAction = BluetoothLeService.ACTION_GATT_DISCONNECTED;
                        //BluetoothLeService.this.mConnectionState = 0;
                        System.Diagnostics.Debug.WriteLine("Disconnected from GATT server.");
                        //BluetoothLeService.this.broadcastUpdate(intentAction);
                    }
                },
                    (gatt, status) =>                     // onServicesDiscovered
                {
                    if (status == GattStatus.Success)
                    {
                        //BluetoothLeService.this.broadcastUpdate(BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED);
                        foreach (var service in gatt.Services)
                        {
                            System.Diagnostics.Debug.WriteLine($"GattService, UUID=[{service.Uuid}]");
                        }

                        Services.AddRange(gatt.Services.Select(S => new BluetoothGattServiceAndroid(this, S)));
                        RaiseServicesUpdated();
                    }
                    else
                    {
                        System.Diagnostics.Debug.WriteLine($"onServicesDiscovered received: {status}");
                    }
                },
                    (gatt, characteristic, status) =>                     // onCharacteristicRead
                {
                    //BluetoothLeService.this.broadcastUpdate(BTConstants.responseMapMapLookup(status, "UnKown Response"), characteristic);
                },
                    (gatt, characteristic) =>                     // onCharacteristicChanged
                {
                    //BluetoothLeService.this.broadcastUpdate(BluetoothLeService.ACTION_CHAR_CHANGED, characteristic);
                },
                    (gatt, characteristic, status) =>                     // onCharacteristicWrite
                {
                    //BluetoothLeService.this.broadcastUpdate(BTConstants.responseMapMapLookup(status, "UnKown Response"), characteristic);
                },
                    (gatt, descriptor, status) =>                     // onDescriptorRead
                {
                    //BluetoothLeService.this.broadcastUpdate(BTConstants.responseMapMapLookup(status, "UnKown Response"), descriptor);
                },
                    (gatt, descriptor, status) =>                     // onDescriptorWrite
                {
                    //BluetoothLeService.this.broadcastUpdate(BTConstants.responseMapMapLookup(status, "UnKown Response"), descriptor);
                },
                    (gatt, status) =>                     //onReliableWriteCompleted
                {
                    //BluetoothLeService.this.broadcastUpdate(BTConstants.responseMapMapLookup(status, "UnKown Response"));
                },
                    (gatt, rssi, status) =>                     //onReadRemoteRssi
                {
                    //BluetoothLeService.this.broadcastUpdate(BTConstants.responseMapMapLookup(status, "UnKown Response"), rssi);
                });
                bluetoothGatt = device.ConnectGatt(Android.App.Application.Context, false, gattCallback);
                //Log.d(TAG, "Trying to create a new connection.");
                //this.mBluetoothDeviceAddress = address;
                //this.mConnectionState = 1;
                //return true;
                return(Task.CompletedTask);
            }
            else
            {
                //Log.d(TAG, "Trying to use an existing mBluetoothGatt for connection.");
                if (bluetoothGatt.Connect() != true)
                {
                    return(Task.FromException(new BluetoothLEException("BluetoothGatt connect fail.")));
                }
                else
                {
                    //this.mConnectionState = 1;
                    return(Task.CompletedTask);
                }
            }
        }