Esempio n. 1
0
        public override void OnServicesDiscovered(BluetoothGatt gatt, GattStatus status)
        {
            if (ValidateServices())
            {
                if (!gatt.SetCharacteristicNotification(readCharacteristic, true))
                {
                    Log.E(this, "Failed to set rigado read characteristic to notify");
                    Disconnect();
                    return;
                }

                if (!readCharacteristicDescriptor.SetValue(new List <byte>(BluetoothGattDescriptor.EnableNotificationValue).ToArray()))
                {
                    Log.E(this, "Failed to set notification to read descriptor");
                    Disconnect();
                    return;
                }

                if (!gatt.WriteDescriptor(readCharacteristicDescriptor))
                {
                    Log.E(this, "Failed to write read notification descriptor");
                    Disconnect();
                    return;
                }
            }
        }
Esempio n. 2
0
        private Boolean SetNotifyEnable(bool enable)
        {
            if (gatt == null || characteristic == null)
            {
                return(false);
            }

            bool isSuccess = gatt.SetCharacteristicNotification(characteristic, enable);

            if (!isSuccess)
            {
                return(false);
            }

            BluetoothGattDescriptor descriptor = characteristic.GetDescriptor(UUID.FromString("00002902-0000-1000-8000-00805f9b34fb"));

            byte[] value = new byte[BluetoothGattDescriptor.EnableNotificationValue.Count];

            for (int i = 0; i < BluetoothGattDescriptor.EnableNotificationValue.Count; i++)
            {
                value[i] = BluetoothGattDescriptor.EnableNotificationValue[i];
            }

            descriptor.SetValue(value);

            isSuccess = gatt.WriteDescriptor(descriptor);

            return(isSuccess);
        }
Esempio n. 3
0
        public Task <bool> UnsubscribeCharacteristic(string serviceGUID, string characteristicGUID, string descriptorGUID)
        {
            unsubscribeCharacteristicTCS = new TaskCompletionSource <bool>();

            try
            {
                if (_gatt == null)
                {
                    Debug.WriteLine("Connect to Bluetooth Device first");
                    unsubscribeCharacteristicTCS.TrySetException(new Exception("Connect to Bluetooth Device first"));
                }

                BluetoothGattCharacteristic chara = _gatt.GetService(UUID.FromString(serviceGUID)).GetCharacteristic(UUID.FromString(characteristicGUID));
                if (null == chara)
                {
                    subscribeCharacteristicTCS.TrySetException(new Exception("Characteristic Id: " + characteristicGUID + " Not Found in Service: " + serviceGUID));
                }

                _gatt.SetCharacteristicNotification(chara, false);

                BluetoothGattDescriptor descriptor = chara.GetDescriptor(UUID.FromString(descriptorGUID));
                descriptor.SetValue(BluetoothGattDescriptor.DisableNotificationValue.ToArray());
                _gatt.WriteDescriptor(descriptor);
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.Message);
                unsubscribeCharacteristicTCS.TrySetException(new Exception(e.Message));
            }

            return(unsubscribeCharacteristicTCS.Task);
        }
Esempio n. 4
0
        /**
         * Enables or disables notification on a give characteristic.
         *
         * @param characteristic Characteristic to act on.
         * @param enabled If true, enable notification.  False otherwise.
         */
        internal void SetCharacteristicNotification(BluetoothGattCharacteristic characteristic, bool enabled)
        {
            if (bluetoothAdapter == null || bluetoothGatt == null)
            {
                logger.TraceWarning("BluetoothAdapter not initialized");
                return;
            }

            if (characteristic.Uuid.Equals(UUID.FromString(SampleGattAttributes.PRESSURE_NOTIFICATION_HANDLE)))
            {
                bluetoothGatt.SetCharacteristicNotification(characteristic, enabled);
                logger.TraceInformation("Setting notification: Pressure Characteristic detected ");

                BluetoothGattDescriptor descriptor = characteristic.GetDescriptor(UUID.FromString("00002902-0000-1000-8000-00805F9B34FB"));
                if (descriptor != null)
                {
                    logger.TraceInformation("Setting notification: Pressure Descriptor Found");
                    descriptor.SetValue(BluetoothGattDescriptor.EnableNotificationValue.ToArray <byte>());
                    bluetoothGatt.WriteDescriptor(descriptor);
                    logger.TraceInformation("Setting notification: Write Pressure Descriptor");
                }
                else
                {
                    logger.TraceWarning("NOTIFICATION SET UP IGNORED");
                }
            }
        }
Esempio n. 5
0
        Task DoWriteValue(byte[] value)
        {
            _descriptor.SetValue(value);
            bool written = Characteristic.Service.Device.Gatt.NativeGatt.WriteDescriptor(_descriptor);

            Characteristic.Service.Device.Gatt.WaitForDescriptorWrite();
            return(Task.CompletedTask);
        }
Esempio n. 6
0
        //public void StartUpdates()
        //{
        //    Task.Run(() =>
        //    {
        //        while (true)
        //        {
        //            if (!_gatt.SetCharacteristicNotification(_nativeCharacteristic, true))
        //            {
        //                // In order to subscribe to notifications on a given characteristic, you must first set the Notifications Enabled bit
        //                // in its Client Characteristic Configuration Descriptor. See https://developer.bluetooth.org/gatt/descriptors/Pages/DescriptorsHomePage.aspx and
        //                // https://developer.bluetooth.org/gatt/descriptors/Pages/DescriptorViewer.aspx?u=org.bluetooth.descriptor.gatt.client_characteristic_configuration.xml
        //                // for details.

        //                if (_nativeCharacteristic.Descriptors.Count > 0)
        //                {
        //                    var descriptors = _nativeCharacteristic.Descriptors;
        //                    var descriptor = descriptors[0];
        //                    if (descriptor != null && Properties.HasFlag(CharacteristicPropertyType.Indicate))
        //                    {
        //                        if (!descriptor.SetValue(BluetoothGattDescriptor.EnableIndicationValue.ToArray()))
        //                        {
        //                        }
        //                        if (!_gatt.WriteDescriptor(descriptor))
        //                        {
        //                        }
        //                    }
        //                    if (descriptor != null && Properties.HasFlag(CharacteristicPropertyType.Notify))
        //                    {
        //                        if (!descriptor.SetValue(BluetoothGattDescriptor.EnableNotificationValue.ToArray()))
        //                        {
        //                        }
        //                        if (!_gatt.WriteDescriptor(descriptor))
        //                        {
        //                        }
        //                    }
        //                    break;
        //                }
        //                else
        //                {
        //                }
        //            }
        //            else
        //            {
        //            }
        //            Thread.Sleep(1000);
        //        }
        //    });
        //}

        public void StartUpdates()
        {
            Task.Run(() =>
            {//on andorid this NEEDS to be in a different thread. when you await each command it stops it from responding and unblocking.
                while (!_gatt.ReadCharacteristic(_nativeCharacteristic))
                {
                    Thread.Sleep(100);
                }
                while (!_gatt.SetCharacteristicNotification(_nativeCharacteristic, true))
                {
                    Thread.Sleep(100);
                }
                // [TO20131211@1634] It seems that setting the notification above isn't enough. You have to set the NOTIFY
                // descriptor as well, otherwise the receiver will never get the updates. I just grabbed the first (and only)
                // descriptor that is associated with the characteristic, which is the NOTIFY descriptor. This seems like a really
                // odd way to do things to me, but I'm a Bluetooth newbie. Google has a example here (but no real explaination as
                // to what is going on):
                if (_nativeCharacteristic.Descriptors.Count > 0)
                {
                    Thread.Sleep(100);
                    BluetoothGattDescriptor descriptor = _nativeCharacteristic.Descriptors[0];
                    while (!descriptor.SetValue(BluetoothGattDescriptor.EnableIndicationValue.ToArray()))
                    {
                        Console.WriteLine("Descriptor Setvalue loop");
                        Thread.Sleep(100);
                    }
                    while (!_gatt.WriteDescriptor(descriptor))
                    {
                        Console.WriteLine(" Write Descriptor loop");
                        Thread.Sleep(100);
                    }
                    Thread.Sleep(100);
                    while (!descriptor.SetValue(BluetoothGattDescriptor.EnableNotificationValue.ToArray()))
                    {
                        Console.WriteLine("Descriptor Setvalue loop");
                        Thread.Sleep(100);
                    }
                    while (!_gatt.WriteDescriptor(descriptor))
                    {
                        Console.WriteLine(" Write Descriptor loop");
                        Thread.Sleep(100);
                    }
                }
            });
        }
Esempio n. 7
0
        public void StartUpdates()
        {
            Console.WriteLine("Enabling indication/notification...");
            BluetoothGattDescriptor descriptor = _nativeCharacteristic.GetDescriptor(UUID.FromString("00002902-0000-1000-8000-00805f9b34fb"));

            Console.WriteLine("Descriptor UUID: " + descriptor.Uuid.ToString());
            if ((_nativeCharacteristic.Properties & GattProperty.Indicate) == GattProperty.Indicate)
            {
                Console.WriteLine("Enabling indication");
                descriptor.SetValue(BluetoothGattDescriptor.EnableIndicationValue.ToArray());
            }

            if ((_nativeCharacteristic.Properties & GattProperty.Notify) == GattProperty.Notify)
            {
                Console.WriteLine("Enabling notification");
                descriptor.SetValue(BluetoothGattDescriptor.EnableNotificationValue.ToArray());
            }
            _gatt.WriteDescriptor(descriptor);
        }
 private void EnableGlucoseContextNotification(BluetoothGatt gatt)
 {
     if (_glucoseMeasurementContextCharacteristic != null)
     {
         gatt.SetCharacteristicNotification(_glucoseMeasurementContextCharacteristic, true);
         BluetoothGattDescriptor descriptor =
             _glucoseMeasurementContextCharacteristic.GetDescriptor(BLEHelpers.BLE_DESCRIPTOR);
         descriptor.SetValue(BluetoothGattDescriptor.EnableNotificationValue.ToArray());
         gatt.WriteDescriptor(descriptor);
     }
 }
Esempio n. 9
0
 private void PlatformWrite(byte[] data)
 {
     if (!_descriptor.SetValue(data))
     {
         RaiseWriteFailed(BLEErrorCode.InternalError);
         return;
     }
     if (!_gatt.WriteDescriptor(_descriptor))
     {
         RaiseWriteFailed(BLEErrorCode.InternalError);
     }
 }
        private void EnableTimeSyncIndication(BluetoothGatt gatt)
        {
            if (_customTimeCharacteristic == null)
            {
                return;
            }
            gatt.SetCharacteristicNotification(_customTimeCharacteristic, true);
            BluetoothGattDescriptor descriptor = _customTimeCharacteristic.GetDescriptor(BLEHelpers.BLE_DESCRIPTOR);

            descriptor.SetValue(BluetoothGattDescriptor.EnableNotificationValue.ToArray());
            gatt.WriteDescriptor(descriptor);
        }
        private void EnableRecordAccessControlPointIndication(BluetoothGatt gatt)
        {
            if (_racpCharacteristic == null)
            {
                return;
            }
            gatt.SetCharacteristicNotification(_racpCharacteristic, true);
            BluetoothGattDescriptor descriptor = _racpCharacteristic.GetDescriptor(BLEHelpers.BLE_DESCRIPTOR);

            descriptor.SetValue(BluetoothGattDescriptor.EnableIndicationValue.ToArray());
            gatt.WriteDescriptor(descriptor);
        }
Esempio n. 12
0
        private void InternalWrite(byte[] data)
        {
            if (!_nativeDescriptor.SetValue(data))
            {
                throw new Exception("GATT: SET descriptor value failed");
            }

            if (!_gatt.WriteDescriptor(_nativeDescriptor))
            {
                throw new Exception("GATT: WRITE descriptor value failed");
            }
        }
        public override bool EnableNotifications(object characteristic, bool enabled)
        {
            bool result = gatt.SetCharacteristicNotification((BluetoothGattCharacteristic)characteristic, enabled);

            if (result == true)
            {
                BluetoothGattDescriptor descriptor = ((BluetoothGattCharacteristic)characteristic).GetDescriptor(CLIENT_CHARACTERISTIC_CONFIG_UUID);
                if (enabled)
                {
                    result = descriptor.SetValue(BluetoothGattDescriptor.EnableNotificationValue.ToArray());
                }
                else
                {
                    result = descriptor.SetValue(BluetoothGattDescriptor.DisableNotificationValue.ToArray());
                }
                if (result == true)
                {
                    gatt.WriteDescriptor(descriptor);
                }
            }
            return(result);
        }
        private static void SetCharacteristicNotification_private(BluetoothGatt gatt, UUID serviceUuid, UUID characteristicUuid)
        {
            try {
                BluetoothGattCharacteristic characteristic = gatt.GetService(serviceUuid).GetCharacteristic(characteristicUuid);
                gatt.SetCharacteristicNotification(characteristic, true);
                BluetoothGattDescriptor descriptor = characteristic.GetDescriptor(BLEHelpers.ClientCharacteristicConfig);
                bool indication = (Convert.ToInt32(characteristic.Properties) & 32) != 0;
                descriptor.SetValue(indication
                    ? BluetoothGattDescriptor.EnableIndicationValue.ToArray()
                    : BluetoothGattDescriptor.EnableNotificationValue.ToArray());

                gatt.WriteDescriptor(descriptor);
            } catch (Exception e) {
                Log.Error("BloodPressureGattCallbackerror", e.Message);
            }
        }
Esempio n. 15
0
        /// <summary>
        ///
        /// </summary>
        public virtual void EnableTXNotification()
        {
            if (m_Gatt == null)
            {
                Log.e("BleSerialPort", "No BluetoothGatt to EnableTXNotification!!!");
                return;
            }

            // Get the service.
            BluetoothGattService RxService = m_Gatt
                                             .GetService(m_UuidServ);

            if (RxService == null)
            {
                Log.e("BleSerialPort", "RxService==null");
                return;
            }

            // Get the characteristic.
            BluetoothGattCharacteristic txChar = RxService
                                                 .GetCharacteristic(m_UuidTx);

            if (txChar == null)
            {
                Log.e("BleSerialPort", "txChar==null");
                return;
            }

            // Set the characteristic notification.
            bool result = m_Gatt.SetCharacteristicNotification(txChar, true);

            if (!result)
            {
                Log.e("BleSerialPort", "m_Gatt.SetCharacteristicNotification(txChar,true) failed!!!");
            }

            // (Set the characteristic notification ???).
            BluetoothGattDescriptor descriptor = txChar
                                                 .GetDescriptor(m_UuidCCCD);

            descriptor.SetValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
            m_Gatt.WriteDescriptor(descriptor);

            Log.i("BleSerialPort", "EnableTXNotification successfully.");
        }
Esempio n. 16
0
        /**
         * Enables or disables notification on a give characteristic.
         *
         * @param characteristic Characteristic to act on.
         * @param enabled If true, enable notification.  False otherwise.
         */
        public void SetCharacteristicNotification(BluetoothGattCharacteristic characteristic, bool enabled)
        {
            if (mBluetoothAdapter == null || mBluetoothGatt == null)
            {
                Log.Warn(TAG, "BluetoothAdapter not initialized");
                return;
            }
            mBluetoothGatt.SetCharacteristicNotification(characteristic, enabled);

            // This is specific to Heart Rate Measurement.
            if (UUID_HEART_RATE_MEASUREMENT == characteristic.Uuid)
            {
                BluetoothGattDescriptor descriptor = characteristic.GetDescriptor(
                    UUID.FromString(SampleGattAttributes.CLIENT_CHARACTERISTIC_CONFIG));
                descriptor.SetValue(BluetoothGattDescriptor.EnableNotificationValue.ToArray());
                mBluetoothGatt.WriteDescriptor(descriptor);
            }
        }
Esempio n. 17
0
        public void StartUpdates()
        {
            // TODO: should be bool RequestValue? compare iOS API for commonality
            bool successful = false;

            if (CanRead)
            {
                Console.WriteLine("Characteristic.RequestValue, PropertyType = Read, requesting updates");
                successful = this._gatt.ReadCharacteristic(_nativeCharacteristic);
            }
            if (CanUpdate)
            {
                Console.WriteLine("Characteristic.RequestValue, PropertyType = Notify, requesting updates");

                successful = _gatt.SetCharacteristicNotification(this._nativeCharacteristic, true);

                // [TO20131211@1634] It seems that setting the notification above isn't enough. You
                // have to set the NOTIFY descriptor as well, otherwise the receiver will never get
                // the updates. I just grabbed the first (and only) descriptor that is associated
                // with the characteristic, which is the NOTIFY descriptor. This seems like a really
                // odd way to do things to me, but I'm a Bluetooth newbie. Google has a example here
                // (but ono real explaination as to what is going on):
                // http://developer.android.com/guide/topics/connectivity/bluetooth-le.html#notification
                //
                // HACK: further detail, in the Forms client this only seems to work with a
                // breakpoint on it (ie. it probably needs to wait until the above
                // 'SetCharacteristicNofication' is done before doing this...?????? [CD]
                System.Threading.Thread.Sleep(100); // HACK: did i mention this was a hack?????????? [CD] 50ms was too short, 100ms seems to work

                if (_nativeCharacteristic.Descriptors.Count > 0)
                {
                    BluetoothGattDescriptor descriptor = _nativeCharacteristic.Descriptors[0];
                    descriptor.SetValue(BluetoothGattDescriptor.EnableNotificationValue.ToArray());
                    _gatt.WriteDescriptor(descriptor);
                }
                else
                {
                    Console.WriteLine("RequestValue, FAILED: _nativeCharacteristic.Descriptors was empty, not sure why");
                }
            }

            Console.WriteLine("RequestValue, Succesful: " + successful.ToString());
        }
Esempio n. 18
0
            public override void OnServicesDiscovered(BluetoothGatt gatt, [GeneratedEnum] GattStatus status)
            {
                base.OnServicesDiscovered(gatt, status);

                foreach (BluetoothGattService service in gatt.Services)
                {
                    string uuid = service.Uuid.ToString().ToUpper();

                    if (uuid != "")
                    {
                        foreach (BluetoothGattCharacteristic characteristic in service.Characteristics)
                        {
                            string c_uuid = characteristic.Uuid.ToString().ToUpper();

                            if (c_uuid != "")
                            {
                                gatt.SetCharacteristicNotification(characteristic, true);

                                BluetoothGattDescriptor descriptor = new BluetoothGattDescriptor(UUID.FromString("00002A25-0000-1000-8000-00805F9B34FB"), GattDescriptorPermission.Read | GattDescriptorPermission.Write);
                                characteristic.AddDescriptor(descriptor);
                                gatt.SetCharacteristicNotification(characteristic, true);
                                gatt.ReadDescriptor(descriptor);
                                byte[] data = descriptor.GetValue();
                                descriptor.SetValue(data);
                                gatt.WriteDescriptor(descriptor);
                                byte[] chara = characteristic.GetValue();

                                if (data != null)
                                {
                                    Log.Debug(tag, "VALOR AQUI: " + data.ToString());
                                    Log.Debug(tag, "Chara: " + chara[0].ToString());
                                }
                                Log.Debug(tag, "Chara: " + chara[0].ToString());
                                Log.Debug(tag, "VALOR AQUI: " + data.ToString());


                                //Log.Debug(tag, "VALOR AQUI: " + data.ToString());
                            }
                        }
                    }
                }
            }
        public void SetCharacteristicNotification(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, string UUIDClient)
        {
            //Servizi trovati e compatibili
            //Attiva richiesta notifiche
            thread = new Thread(new ThreadStart(() =>
            {
                bool notificationState = false;

                for (int i = 0; i < 3; i++)
                {
                    gatt.SetCharacteristicNotification(characteristic, true);
                    BluetoothGattDescriptor descriptor = new BluetoothGattDescriptor(Java.Util.UUID.FromString(UUIDClient), GattDescriptorPermission.Write | GattDescriptorPermission.Read);
                    characteristic.AddDescriptor(descriptor);
                    descriptor.SetValue(BluetoothGattDescriptor.EnableNotificationValue.ToArray());
                    gatt.WriteDescriptor(descriptor);

                    /*
                     * BluetoothGattDescriptor desc = characteristic.GetDescriptor(UUID.FromString(UUIDClient));
                     * desc.SetValue(BluetoothGattDescriptor.EnableNotificationValue.ToArray<Byte>());
                     * gatt.WriteDescriptor(desc);
                     * gatt.SetCharacteristicNotification(characteristic, true);
                     */
                    if (WaitCharRecive.WaitOne(5000))
                    {
                        notificationState = true;
                        if (Notification_Event != null)
                        {
                            Notification_Event(true);
                        }
                        break;
                    }
                }
                if (notificationState == false)
                {
                    if (Notification_Event != null)
                    {
                        Notification_Event(false);
                    }
                }
            }));
            thread.Start();
        }
            public override void OnServicesDiscovered(BluetoothGatt gatt, GattStatus status)
            {
                if (status == GattStatus.Success)
                {
                    Debug.WriteLine(TAG, "mBluetoothGatt = " + Service.Gatt);
                    BluetoothGattCharacteristic TxChar;
                    BluetoothGattService        RxService = Service.Gatt.GetService(RX_SERVICE_UUID2);
                    if (RxService == null)
                    {
                        Service.ShowMessage("mBluetoothGatt null" + Service.Gatt);
                        Service.ShowMessage("Rx service not found!");
                        Service.BroadcastUpdate(DEVICE_DOES_NOT_SUPPORT_UART);
                        return;
                    }
                    TxChar = RxService.GetCharacteristic(TX_CHAR_UUID2);
                    if (TxChar == null)
                    {
                        Service.ShowMessage("Rx charateristic not found!");
                        Service.BroadcastUpdate(DEVICE_DOES_NOT_SUPPORT_UART);
                        return;
                    }
                    Debug.WriteLine(TAG, "RxChar = " + TX_CHAR_UUID2.ToString());
                    Service.Gatt.SetCharacteristicNotification(TxChar, true);

                    BluetoothGattDescriptor descriptor = TxChar.GetDescriptor(CCCD);
                    var ilistValue = BluetoothGattDescriptor.EnableNotificationValue;
                    var arrayValue = new byte[ilistValue.Count];
                    for (int index = 0; index < arrayValue.Length; index++)
                    {
                        arrayValue[index] = ilistValue[index];
                    }
                    descriptor.SetValue(arrayValue);
                    Service.Gatt.WriteDescriptor(descriptor);

                    Service.BroadcastUpdate(ACTION_GATT_SERVICES_DISCOVERED);
                }
                else
                {
                    Debug.WriteLine(TAG, "onServicesDiscovered received: " + status);
                }
            }
        private static void SetCharacteristicNotification_private(BluetoothGatt gatt, UUID serviceUuid,
                                                                  UUID characteristicUuid)
        {
            try {
                bool indication;
                BluetoothGattCharacteristic characteristic =
                    gatt.GetService(serviceUuid).GetCharacteristic(characteristicUuid);
                gatt.SetCharacteristicNotification(characteristic, true);
                BluetoothGattDescriptor descriptor =
                    characteristic.GetDescriptor(BLEHelpers.ClientCharacteristicConfig);
                indication = (Convert.ToInt32(characteristic.Properties) & 32) != 0;
                Log.Error("Indication", indication.ToString());
                descriptor.SetValue(indication
                                        ? BluetoothGattDescriptor.EnableIndicationValue.ToArray()
                                        : BluetoothGattDescriptor.EnableNotificationValue.ToArray());

                gatt.WriteDescriptor(descriptor);
            } catch (Exception e) {
                e.PrintStackTrace();
            }
        }
Esempio n. 22
0
        /// <summary>
        /// Process a callback from the Gatt for device services discovered while we're connecting
        /// </summary>
        private void GattCallback_ServicesDiscovered(object sender, EventArgs e)
        {
            Debug.WriteLineIf(sw.TraceInfo, "++> GattCallback_ServicesDiscovered");
            _service = _gatt.GetService(uuidService);
            _TX      = _service.GetCharacteristic(uuidTX);
            _RX      = _service.GetCharacteristic(uuidRX);
            BluetoothGattDescriptor config = _RX.GetDescriptor(uuidCharacteristicConfig);

            if (config == null)
            {
                Debug.WriteLineIf(sw.TraceError, "--> _RX.GetDescriptor failed");
                ErrorMessage = "RX.GetDescriptor failed";
                Disconnect();
                return;
            }
            bool b = _gatt.SetCharacteristicNotification(_RX, true);

            b = config.SetValue(BluetoothGattDescriptor.EnableNotificationValue.ToArray());
            b = _gatt.WriteDescriptor(config);
            // now that services are connected, we're ready to go
            State = BlueState.Connected;
        }
        // Overridden from BaseLeConnection
        protected override bool OnConnectionSuccess()
        {
            if (!gatt.SetCharacteristicNotification(readCharacteristic, true))
            {
                Log.E(this, "Failed to set rigado read characteristic to notify");
                return(false);
            }

            if (!readCharacteristicDescriptor.SetValue(new List <byte>(BluetoothGattDescriptor.EnableNotificationValue).ToArray()))
            {
                Log.E(this, "Failed to set notification to read descriptor");
                return(false);
            }

            if (!gatt.WriteDescriptor(readCharacteristicDescriptor))
            {
                Log.E(this, "Failed to write read notification descriptor");
                return(false);
            }

            return(base.OnConnectionSuccess());
        }
        internal static void process_queue_entry(Bluetooth_CMD btc)
        {
            if (GlucoseGattCallback.mBluetoothGatt == null)
            {
                Debug.WriteLine("Bluetooth Gatt not initialized");
                return;
            }

            BluetoothGattService        service = null;
            BluetoothGattCharacteristic characteristic;

            if (btc.service != null)
            {
                service = GlucoseGattCallback.mBluetoothGatt.GetService(btc.service);
            }
            if ((service != null) || (btc.service == null))
            {
                if ((service != null) && (btc.characteristic != null))
                {
                    characteristic = service.GetCharacteristic(btc.characteristic);
                }
                else
                {
                    characteristic = null;
                }
                if (characteristic != null)
                {
                    switch (btc.cmd)
                    {
                    case "W":
                        characteristic.SetValue(btc.data);
                        if ((characteristic.GetValue().Length > 1))
                        {
                            GlucoseGattCallback.AwaitingAck  = true;
                            GlucoseGattCallback.AwaitingData = true;
                            if (GlucoseGattCallback.Debug)
                            {
                                Debug.WriteLine("Setting await ack blocker 1");
                            }
                        }


                        Task.Run(() =>
                        {
                            try
                            {
                                if (!GlucoseGattCallback.mBluetoothGatt.WriteCharacteristic(characteristic))
                                {
                                    Debug.WriteLine("Failed in write characteristic");
                                    System.Threading.Thread.Sleep(150);
                                    if (!GlucoseGattCallback.mBluetoothGatt.WriteCharacteristic(characteristic))
                                    {
                                        Debug.WriteLine("Failed second time in write charactersitic");
                                    }
                                }
                            }
                            catch (NullPointerException e)
                            {
                                Debug.WriteLine(
                                    "Got null pointer exception writing characteristic - probably temporary failure");
                            }
                        });



                        break;

                    case "R":
                        GlucoseGattCallback.mBluetoothGatt.ReadCharacteristic(characteristic);
                        break;

                    case "N":
                        GlucoseGattCallback.mBluetoothGatt.SetCharacteristicNotification(characteristic, true);
                        System.Threading.Thread.Sleep(100);
                        poll_queue();     // we don't get an event from this
                        break;

                    case "U":
                        GlucoseGattCallback.mBluetoothGatt.SetCharacteristicNotification(characteristic, false);
                        break;

                    case "D":
                        BluetoothGattDescriptor descriptor = characteristic.GetDescriptor(
                            GattMapper.UuidForType <ClientCharacteristicConfiguration>());
                        descriptor.SetValue(btc.data);
                        GlucoseGattCallback.mBluetoothGatt.WriteDescriptor(descriptor);
                        break;

                    default:
                        Debug.WriteLine("Unknown queue cmd: " + btc.cmd);
                        break;
                    } // end switch
                }
                else
                {
                    Debug.WriteLine("Characteristic was null!!!!");
                }
            }
            else
            {
                Debug.WriteLine("Got null service error on: " + btc.service);
            }
        }
Esempio n. 25
0
            public override void OnServicesDiscovered(BluetoothGatt gatt, GattStatus status)
            {
                base.OnServicesDiscovered(gatt, status);

                try
                {
                    foreach (var bluetoothGattService in gatt.Services)
                    {
                        Log.Info(TAG, $"Service Discovered => {bluetoothGattService.Uuid}");
                        foreach (var bluetoothGattCharacteristic in bluetoothGattService.Characteristics)
                        {
                            Log.Info(TAG, $"Characteristic Discovered => {bluetoothGattCharacteristic.Uuid}");
                        }
                    }



                    WriteCharacteristic = gatt.GetService(DEX_SERVICE_SPP)
                                          .GetCharacteristic(DEX_CHARACTERISTIC_DATAWRITE);


                    Log.Info(TAG, $"WriteCharacteristic Properties => {WriteCharacteristic.Properties.ToString()}");


                    DeviceCharacteristic = gatt.GetService(DEX_SERVICE).GetCharacteristic(DEVICE_SETTINGS);


                    Log.Info(TAG, $"DeviceCharacteristic Properties => {DeviceCharacteristic.Properties.ToString()}");


                    StatusCharacteristic = gatt.GetService(DEX_SERVICE_SPP)
                                           .GetCharacteristic(DEX_CHARACTERISTIC_STATUS);


                    Log.Info(TAG, $"StatusCharacteristic Properties => {StatusCharacteristic.Properties.ToString()}");


                    gatt.SetCharacteristicNotification(DeviceCharacteristic, true);

                    var descDevice = DeviceCharacteristic.GetDescriptor(CLIENT_CHARACTERISTIC_CONFIG);

                    Log.Info(TAG, $"descDevice Permissions => {descDevice.Permissions.ToString()}");


                    descDevice.SetValue(BluetoothGattDescriptor.EnableNotificationValue.ToArray());
                    gatt.WriteDescriptor(descDevice);
                    descDevice.SetValue(BluetoothGattDescriptor.EnableIndicationValue.ToArray());
                    gatt.WriteDescriptor(descDevice);


                    if (gatt.SetCharacteristicNotification(WriteCharacteristic, true))
                    {
                        MainActivity.RunOnUiThread(() =>
                        {
                            Log.Info(TAG + DexService.Operation, "Set Write Characteristic succeeded");
                        });
                        DexService.LogMessage2("Set Write Characteristic succeeded", false);
                    }
                    else
                    {
                        MainActivity.RunOnUiThread(() => { Log.Info(TAG + DexService.Operation, "Set Write Characteristic failed"); });
                    }

                    BluetoothGattDescriptor descWrite = WriteCharacteristic.GetDescriptor(CLIENT_CHARACTERISTIC_CONFIG);

                    Log.Info(TAG, $"descWrite Permissions => {descWrite.Permissions.ToString()}");



                    descWrite.SetValue(BluetoothGattDescriptor.EnableNotificationValue.ToArray());
                    gatt.WriteDescriptor(descWrite);
                    descWrite.SetValue(BluetoothGattDescriptor.EnableIndicationValue.ToArray());
                    gatt.WriteDescriptor(descWrite);
                    DexService.Connected = true;
                    DexService.LogMessage2("Device Connected", false);
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                    throw;
                }
            }
Esempio n. 26
0
        /// <summary>
        /// Connets the service and enable notifications for the chars we need
        /// </summary>
        /// <param name="gatt">Gatt.</param>
        public void connectToService(BluetoothGatt gatt)
        {
            try
            {
                if (handle == null)
                {
                    handle = new SensorHandler(deviceDetails, AppConfig.UserID);
                }

                BluetoothDevice d = gatt.Device;

                // Getting Char/services UUIDS
                UUID serviceUUID = null;
                UUID charUUID    = null;
                UUID ccdUUID     = UUID.FromString(BluetoothConstants.CCD_UUID);

                // Can add other ones later or maybe swap out config files?
                if (gatt.Device.Name.StartsWith("MVSS", StringComparison.CurrentCulture))
                {
                    serviceUUID = UUID.FromString(BluetoothConstants.MVSS_SERVICE);
                    charUUID    = UUID.FromString(BluetoothConstants.MVSS_CHAR);
                }

                if (gatt.Device.Name.StartsWith("Zephyr", StringComparison.CurrentCulture))
                {
                    serviceUUID = UUID.FromString(BluetoothConstants.HEART_RATE_SERVICE);
                    charUUID    = UUID.FromString(BluetoothConstants.HEART_RATE_CHAR);
                }


                /*	if (serviceUUID == null || charUUID == null || ccdUUID == null)
                 *  {
                 *      // dont continue
                 *      // throw error?
                 *  }*/

                notifyChars.Add(serviceUUID.ToString());
                notifyChars.Add(charUUID.ToString());

                // Getting Service
                BluetoothGattService ser = gatt.GetService(serviceUUID);

                // Getting custom characteristic and enabling the notifications for it
                BluetoothGattCharacteristic cha = ser.GetCharacteristic(charUUID);

                // Getting Descriptor from characteristic
                BluetoothGattDescriptor ds = cha.GetDescriptor(ccdUUID);

                // Setting desc to notify
                ds.SetValue(BluetoothGattDescriptor.EnableNotificationValue.ToArray());
                //ds.SetValue(BluetoothGattDescriptor.EnableIndicationValue.ToArray());
                gatt.WriteDescriptor(ds);

                // Enabling the notifications
                gatt.SetCharacteristicNotification(cha, true);
            }
            catch (NullReferenceException e)
            {
                // Service could not be reached
                // How to get this back to the user?
                string t = e.ToString();
            }
        }
Esempio n. 27
0
        public bool ConnectLeGattDevice(Context context, BluetoothDevice device)
        {
            try
            {
                BtGattDisconnect();

                _gattConnectionState    = State.Connecting;
                _gattServicesDiscovered = false;
                _btGattSppInStream      = new MemoryQueueBufferStream(true);
                _btGattSppOutStream     = new BGattOutputStream(this);
                _bluetoothGatt          = device.ConnectGatt(context, false, new BGattCallback(this));
                if (_bluetoothGatt == null)
                {
                    LogString("*** ConnectGatt failed");
                    return(false);
                }

                _btGattConnectEvent.WaitOne(2000, false);
                if (_gattConnectionState != State.Connected)
                {
                    LogString("*** GATT connection timeout");
                    return(false);
                }

                _btGattDiscoveredEvent.WaitOne(2000, false);
                if (!_gattServicesDiscovered)
                {
                    LogString("*** GATT service discovery timeout");
                    return(false);
                }

                IList <BluetoothGattService> services = _bluetoothGatt.Services;
                if (services == null)
                {
                    LogString("*** No GATT services found");
                    return(false);
                }

#if DEBUG
                foreach (BluetoothGattService gattService in services)
                {
                    if (gattService.Uuid == null || gattService.Characteristics == null)
                    {
                        continue;
                    }

                    Android.Util.Log.Info(Tag, string.Format("GATT service: {0}", gattService.Uuid));
                    foreach (BluetoothGattCharacteristic gattCharacteristic in gattService.Characteristics)
                    {
                        if (gattCharacteristic.Uuid == null)
                        {
                            continue;
                        }

                        Android.Util.Log.Info(Tag, string.Format("GATT characteristic: {0}", gattCharacteristic.Uuid));
                        Android.Util.Log.Info(Tag, string.Format("GATT properties: {0}", gattCharacteristic.Properties));
                    }
                }
#endif

                _gattCharacteristicSppRead      = null;
                _gattCharacteristicSppWrite     = null;
                _gattCharacteristicUuidSppRead  = null;
                _gattCharacteristicUuidSppWrite = null;

                BluetoothGattService        gattServiceSpp        = _bluetoothGatt.GetService(GattServiceCarlySpp);
                BluetoothGattCharacteristic gattCharacteristicSpp = gattServiceSpp?.GetCharacteristic(GattCharacteristicCarlySpp);
                if (gattCharacteristicSpp != null)
                {
                    if ((gattCharacteristicSpp.Properties & (GattProperty.Read | GattProperty.Write | GattProperty.Notify)) ==
                        (GattProperty.Read | GattProperty.Write | GattProperty.Notify))
                    {
                        _gattCharacteristicSppRead      = gattCharacteristicSpp;
                        _gattCharacteristicSppWrite     = gattCharacteristicSpp;
                        _gattCharacteristicUuidSppRead  = GattCharacteristicCarlySpp;
                        _gattCharacteristicUuidSppWrite = GattCharacteristicCarlySpp;
#if DEBUG
                        Android.Util.Log.Info(Tag, "SPP characteristic Carly found");
#endif
                    }
                }
                else
                {
                    gattServiceSpp = _bluetoothGatt.GetService(GattServiceWgSoftSpp);
                    BluetoothGattCharacteristic gattCharacteristicSppRead  = gattServiceSpp?.GetCharacteristic(GattCharacteristicWgSoftSppRead);
                    BluetoothGattCharacteristic gattCharacteristicSppWrite = gattServiceSpp?.GetCharacteristic(GattCharacteristicWgSoftSppWrite);
                    if (gattCharacteristicSppRead != null && gattCharacteristicSppWrite != null)
                    {
                        if (((gattCharacteristicSppRead.Properties & (GattProperty.Read | GattProperty.Notify)) == (GattProperty.Read | GattProperty.Notify)) &&
                            ((gattCharacteristicSppWrite.Properties & (GattProperty.Write)) == (GattProperty.Write)))
                        {
                            _gattCharacteristicSppRead      = gattCharacteristicSppRead;
                            _gattCharacteristicSppWrite     = gattCharacteristicSppWrite;
                            _gattCharacteristicUuidSppRead  = GattCharacteristicWgSoftSppRead;
                            _gattCharacteristicUuidSppWrite = GattCharacteristicWgSoftSppWrite;
                        }
#if DEBUG
                        Android.Util.Log.Info(Tag, "SPP characteristic WgSoft found");
#endif
                    }
                }

                if (_gattCharacteristicSppRead == null || _gattCharacteristicSppWrite == null)
                {
                    LogString("*** No GATT SPP characteristic found");
                    return(false);
                }

                if (!_bluetoothGatt.SetCharacteristicNotification(_gattCharacteristicSppRead, true))
                {
                    LogString("*** GATT SPP enable notification failed");
                    return(false);
                }

                BluetoothGattDescriptor descriptor = _gattCharacteristicSppRead.GetDescriptor(GattCharacteristicConfig);
                if (descriptor == null)
                {
                    LogString("*** GATT SPP config descriptor not found");
                    return(false);
                }

                if (BluetoothGattDescriptor.EnableNotificationValue == null)
                {
                    LogString("*** GATT SPP EnableNotificationValue not present");
                    return(false);
                }

                _gattWriteStatus = GattStatus.Failure;
                descriptor.SetValue(BluetoothGattDescriptor.EnableNotificationValue.ToArray());
                if (!_bluetoothGatt.WriteDescriptor(descriptor))
                {
                    LogString("*** GATT SPP write config descriptor failed");
                    return(false);
                }

                if (!_btGattWriteEvent.WaitOne(2000))
                {
                    LogString("*** GATT SPP write config descriptor timeout");
                    return(false);
                }

                if (_gattWriteStatus != GattStatus.Success)
                {
                    LogString("*** GATT SPP write config descriptor status failure");
                    return(false);
                }

#if false
                byte[] sendData = Encoding.UTF8.GetBytes("ATI\r");
                _btGattSppOutStream.Write(sendData, 0, sendData.Length);

                while (_btGattReceivedEvent.WaitOne(2000, false))
                {
#if DEBUG
                    Android.Util.Log.Info(Tag, "GATT SPP data received");
#endif
                }

                while (_btGattSppInStream.HasData())
                {
                    int data = _btGattSppInStream.ReadByteAsync();
                    if (data < 0)
                    {
                        break;
                    }
#if DEBUG
                    Android.Util.Log.Info(Tag, string.Format("GATT SPP byte: {0:X02}", data));
#endif
                }
#endif
                return(true);
            }
            catch (Exception)
            {
                _gattConnectionState    = State.Disconnected;
                _gattServicesDiscovered = false;
                return(false);
            }
        }