예제 #1
0
파일: BLEDevice.cs 프로젝트: poz1/Poz1.BLE
        public Task <bool> SubscribeCharacteristic(string serviceGUID, string characteristicGUID, string descriptorGUID)
        {
            subscribeCharacteristicTCS = new TaskCompletionSource <bool>();

            try
            {
                if (_gatt == null)
                {
                    Debug.WriteLine("Connect to Bluetooth Device first");
                    subscribeCharacteristicTCS.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, true);

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

            return(subscribeCharacteristicTCS.Task);
        }
예제 #2
0
        private void SetUpdateValue(bool enable)
        {
            var success = _gatt.SetCharacteristicNotification(_nativeCharacteristic, enable);

            if (!success)
            {
                NotificationStateChanged?.Invoke(this, new CharacteristicNotificationStateEventArgs(this, false));
            }

            if (_nativeCharacteristic.Descriptors.Count > 0)
            {
                const string descriptorId = "00002902-0000-1000-8000-00805f9b34fb";
                var          value        = enable ? BluetoothGattDescriptor.EnableNotificationValue : BluetoothGattDescriptor.DisableNotificationValue;
                var          descriptor   = _nativeCharacteristic.Descriptors.FirstOrDefault(x => x.Uuid.ToString() == descriptorId);
                if (descriptor != null && !descriptor.SetValue(value.ToArray()))
                {
                    throw new Exception("Unable to set the notification value on the descriptor");
                }
                var dSuccess = _gatt.WriteDescriptor(descriptor);
                if (!dSuccess)
                {
                    //NotificationStateChanged?.Invoke(this, new CharacteristicNotificationStateEventArgs(this, false));
                }
            }
            _isUpdating = enable;
        }
예제 #3
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);
        }
예제 #4
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;
                }
            }
        }
예제 #5
0
        public Task <bool> EnableNotificationAsync(IGattCharacteristic characteristic, CancellationToken token)
        {
            lock (_lock)
            {
                if (_bluetoothGatt == null || State != BluetoothLEDeviceState.Connected)
                {
                    return(Task.FromResult(false));
                }

                var nativeCharacteristic = ((GattCharacteristic)characteristic).BluetoothGattCharacteristic;
                if (!_bluetoothGatt.SetCharacteristicNotification(nativeCharacteristic, true))
                {
                    return(Task.FromResult(false));
                }

                var descriptor = nativeCharacteristic.GetDescriptor(ClientCharacteristicConfigurationUUID);
                if (descriptor == null)
                {
                    return(Task.FromResult(false));
                }

                if (!descriptor.SetValue(BluetoothGattDescriptor.EnableNotificationValue.ToArray()))
                {
                    return(Task.FromResult(false));
                }

                var result = _bluetoothGatt.WriteDescriptor(descriptor);
                return(Task.FromResult(result));
            }
        }
예제 #6
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");
                }
            }
        }
예제 #7
0
        private void PlatformSetNotification(bool enabled)
        {
            if (!_gatt.SetCharacteristicNotification(_characteristic, enabled))
            {
                RaiseSetNotificationFailed(BLEErrorCode.InternalError);
                return;
            }
            using (var uuid = Java.Util.UUID.FromString(BLEConstants.CLIENT_CHARACTERISTIC_CONFIGURATION))
            {
                var descriptor = _characteristic.GetDescriptor(uuid);
                if (!descriptor.SetValue(BluetoothGattDescriptor.EnableNotificationValue.ToArray()))
                {
                    RaiseSetNotificationFailed(BLEErrorCode.InternalError);
                    return;
                }
                if (!_gatt.WriteDescriptor(descriptor))
                {
                    RaiseSetNotificationFailed(BLEErrorCode.InternalError);
                    return;
                }
            }

            PlatformIsNotifying = enabled;
            RaiseNotificationSet();
        }
예제 #8
0
        public override void OnServicesDiscovered(BluetoothGatt gatt, GattStatus status)
        {
            if (ValidateServices())
            {
                var d = readCharacteristic.Descriptors[0];

                if (!gatt.SetCharacteristicNotification(readCharacteristic, true))
                {
                    Log.E(this, "Failed to set the read characteristic to notify.");
                    Disconnect();
                    return;
                }

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

                NotifyConnectionState();
                vrcMeasurement = Units.Vacuum.MICRON.OfScalar(600000);
                rigAngle       = Units.Angle.DEGREE.OfScalar(90);
            }
        }
        public override void OnCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic)
        {
            if (characteristic.Uuid.Equals(DT1WatchDogService.DT1WatchdogDataCharacteristicUUID))
            {
                log.Debug("Watchdog data characteristic changed.");

                // we got data - fine we disconnect and wait for the next alarm

                var CLIENT_CHARACTERISTIC_CONFIG        = Java.Util.UUID.FromString("00002902-0000-1000-8000-00805f9b34fb");
                var clientCharacteristiConfigDescriptor = characteristic.GetDescriptor(CLIENT_CHARACTERISTIC_CONFIG);
                clientCharacteristiConfigDescriptor.SetValue(BluetoothGattDescriptor.DisableNotificationValue.ToArray());
                gatt.WriteDescriptor(clientCharacteristiConfigDescriptor);

                gatt.Disconnect();

                var data    = characteristic.GetValue();
                var reading = GlucoseReading.ParseRawCharacteristicData(data);

                // fill in source
                reading.Source = gatt.Device.Name;

                dataService.PersistReading(reading);

                if (reading.ErrorCode == GlucoseReading.ReadingErrorCode.NoError)
                {
                    dataService.LastValidReading = DateTimeOffset.UtcNow;
                    EvaluateReading(reading);
                }

                var dataIntent = new Intent(DT1WatchDogService.IntentIncommingData);
                service.SendBroadcast(dataIntent);
            }
        }
예제 #10
0
            private void EnableNotification()
            {
                _gatt.SetCharacteristicNotification(_characteristic, true);
                var descriptor = _characteristic.GetDescriptor(UUID.FromString(NotifyDescriptorUuid));

                descriptor.SetValue(BluetoothGattDescriptor.EnableNotificationValue.ToArray());
                _gatt.WriteDescriptor(descriptor);
            }
예제 #11
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);
                    }
                }
            });
        }
        private void SubscribeCharacteristic(BluetoothGattCharacteristic characteristic)
        {
            _gatt.SetCharacteristicNotification(characteristic, true);

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

            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);
     }
 }
예제 #14
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);
        }
예제 #17
0
        public void ConfigureGyroscopeNotification(BluetoothGatt gatt)
        {
            ConfigurationStep = ConfigurationStep.GyroscopeNotification;
            var gyroscopeData         = gatt.GetService(BluetoothSensorAttributes.GyroscopeService).GetCharacteristic(BluetoothSensorAttributes.GyroscopeData);
            var gyroscopeNotification = gyroscopeData.GetDescriptor(BluetoothSensorAttributes.GyroscopeNotification);


            gyroscopeNotification.SetValue(new byte[] { 1, 0 });

            gatt.SetCharacteristicNotification(gyroscopeData, true);
            gatt.WriteDescriptor(gyroscopeNotification);
        }
예제 #18
0
        public void ConfigureAccelerometerNotification(BluetoothGatt gatt)
        {
            ConfigurationStep = ConfigurationStep.AccelerometerNotification;
            var accelerometerData         = gatt.GetService(BluetoothSensorAttributes.AccelerometerService).GetCharacteristic(BluetoothSensorAttributes.AccelerometerData);
            var accelerometerNotification = accelerometerData.GetDescriptor(BluetoothSensorAttributes.AccelerometerNotification);


            accelerometerNotification.SetValue(new byte[] { 1, 0 });

            gatt.SetCharacteristicNotification(accelerometerData, true);
            gatt.WriteDescriptor(accelerometerNotification);
        }
예제 #19
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");
            }
        }
예제 #20
0
        public void StartUpdates()
        {
            // TODO: should be bool RequestValue? compare iOS API for commonality
            var successful = false;

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

            if (CanUpdate)
            {
                Console.WriteLine("Characteristic.RequestValue, PropertyType = Notify, requesting updates");

                if (_gattCallback != null)
                {
                    // wire up the characteristic value updating on the gattcallback for event forwarding
                    _gattCallback.CharacteristicValueUpdated += OnCharacteristicValueChanged;
                }

                successful = _gatt.SetCharacteristicNotification(_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]
                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)
                {
                    var descriptor = _nativeCharacteristic.Descriptors[0];
                    descriptor.SetValue(BluetoothGattDescriptor.EnableNotificationValue.ToArray());
                    successful &= _gatt.WriteDescriptor(descriptor);
                }
                else
                {
                    Console.WriteLine("RequestValue, FAILED: _nativeCharacteristic.Descriptors was empty, not sure why");
                }
            }

            Mvx.TaggedTrace("StartUpdates", "RequestValue, Succesful: {0}", successful);
        }
        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);
            }
        }
예제 #22
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.");
        }
예제 #23
0
        protected override async void StartUpdatesNative()
        {
            // wire up the characteristic value updating on the gattcallback for event forwarding
            _gattCallback.CharacteristicValueUpdated += OnCharacteristicValueChanged;

            var successful = _gatt.SetCharacteristicNotification(_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

            await Task.Delay(100);

            //ToDo is this still needed?
            // HACK: did i mention this was a hack?????????? [CD] 50ms was too short, 100ms seems to work

            if (_nativeCharacteristic.Descriptors.Count > 0)
            {
                var descriptor = _nativeCharacteristic.Descriptors[0];

                //has to have one of these (either indicate or notify)
                if (Properties.HasFlag(CharacteristicPropertyType.Indicate))
                {
                    descriptor.SetValue(BluetoothGattDescriptor.EnableIndicationValue.ToArray());
                    Trace.Message("Descriptor set value: INDICATE");
                }

                if (Properties.HasFlag(CharacteristicPropertyType.Notify))
                {
                    descriptor.SetValue(BluetoothGattDescriptor.EnableNotificationValue.ToArray());
                    Trace.Message("Descriptor set value: NOTIFY");
                }

                successful &= _gatt.WriteDescriptor(descriptor);
            }
            else
            {
                Trace.Message("Descriptor set value FAILED: _nativeCharacteristic.Descriptors was empty");
            }

            Trace.Message("Characteristic.StartUpdates, successful: {0}", successful);
        }
예제 #24
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);
            }
        }
예제 #25
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);
        }
예제 #26
0
        private void ConfigureMovementData(BluetoothGatt gatt)
        {
            try
            {
                var characteristic = gatt.GetService(BluetoothSensorTagAttributes.MovementService).GetCharacteristic(BluetoothSensorTagAttributes.MovementData);
                gatt.SetCharacteristicNotification(characteristic, true);

                var descriptor = characteristic.GetDescriptor(BluetoothSensorTagAttributes.ClientConfigurationDescriptor);
                descriptor.SetValue(new byte[] { 1, 0 });
                gatt.WriteDescriptor(descriptor);

                SensorTagConfigurationStep = SensorTagConfigurationStep.MovementData;
            }
            catch (System.Exception ex)
            {
                string title = this.GetType().Name + " - " + System.Reflection.MethodBase.GetCurrentMethod().Name;
                BalizaFacil.App.Instance.UnhandledException(title, ex);
            }
        }
예제 #27
0
        protected override async void StartUpdatesNative()
        {
            // wire up the characteristic value updating on the gattcallback for event forwarding
            _gattCallback.CharacteristicValueUpdated += OnCharacteristicValueChanged;

            var successful = _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.

            await Task.Delay(100);

            //ToDo is this still needed?

            if (_nativeCharacteristic.Descriptors.Count > 0)
            {
                var descriptor = _nativeCharacteristic.Descriptors.FirstOrDefault(d => d.Uuid.Equals(_clientCharacteristicConfigurationDescriptorId)) ??
                                 _nativeCharacteristic.Descriptors[0]; // fallback just in case manufacturer forgot

                //has to have one of these (either indicate or notify)
                if (Properties.HasFlag(CharacteristicPropertyType.Indicate))
                {
                    descriptor.SetValue(BluetoothGattDescriptor.EnableIndicationValue.ToArray());
                    Trace.Message("Descriptor set value: INDICATE");
                }

                if (Properties.HasFlag(CharacteristicPropertyType.Notify))
                {
                    descriptor.SetValue(BluetoothGattDescriptor.EnableNotificationValue.ToArray());
                    Trace.Message("Descriptor set value: NOTIFY");
                }

                successful &= _gatt.WriteDescriptor(descriptor);
            }
            else
            {
                Trace.Message("Descriptor set value FAILED: _nativeCharacteristic.Descriptors was empty");
            }

            Trace.Message("Characteristic.StartUpdates, successful: {0}", successful);
        }
예제 #28
0
        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();
        }
예제 #29
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());
                            }
                        }
                    }
                }
            }
        private void SetUpdateValue(bool enable)
        {
            if (!_gatt.SetCharacteristicNotification(_nativeCharacteristic, enable))
            {
                throw new Exception("Unable to set the notification value on the characteristic");
            }

            // hackity-hack-hack
            System.Threading.Thread.Sleep(100);

            if (_nativeCharacteristic.Descriptors.Count > 0)
            {
                const string descriptorId = "00002902-0000-1000-8000-00805f9b34fb";
                var          value        = enable ? BluetoothGattDescriptor.EnableNotificationValue : BluetoothGattDescriptor.DisableNotificationValue;
                var          descriptor   = _nativeCharacteristic.Descriptors.FirstOrDefault(x => x.Uuid.ToString() == descriptorId);
                if (descriptor == null || !descriptor.SetValue(value.ToArray()) || !_gatt.WriteDescriptor(descriptor))
                {
                    throw new Exception("Unable to set the notification value on the descriptor");
                }
            }
        }