Пример #1
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;
        }
Пример #2
0
        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);
        }
        public override void OnServicesDiscovered(BluetoothGatt gatt, GattStatus status)
        {
            if (status != GattStatus.Success)
            {
                return;
            }
            foreach (BluetoothGattService service in gatt.Services)
            {
                if (service.Uuid.Equals(BLEHelpers.BLE_SERVICE_GLUCOSE))
                {
                    _glucoseMeasurementCharacteristic =
                        service.GetCharacteristic(BLEHelpers.BLE_CHAR_GLUCOSE_MEASUREMENT);
                    _glucoseMeasurementContextCharacteristic =
                        service.GetCharacteristic(BLEHelpers.BLE_CHAR_GLUCOSE_CONTEXT);
                    _racpCharacteristic = service.GetCharacteristic(BLEHelpers.BLE_CHAR_GLUCOSE_RACP);
                    _records.Clear();
                }
                else if (BLEHelpers.BLE_SERVICE_DEVICE_INFO.Equals(service.Uuid))
                {
                    _deviceSoftwareRevisionCharacteristic =
                        service.GetCharacteristic(BLEHelpers.BLE_CHAR_SOFTWARE_REVISION);
                    _deviceManufacturerCharacteristic =
                        service.GetCharacteristic(BLEHelpers.BLE_CHAR_GLUCOSE_MANUFACTURE);
                    _deviceSerialCharacteristic = service.GetCharacteristic(BLEHelpers.BLE_CHAR_GLUCOSE_SERIALNUM);
                }
                else if (service.Uuid.Equals(BLEHelpers.BLE_SERVICE_CUSTOM_TIME_MC))
                {
                    _customTimeCharacteristic = service.GetCharacteristic(BLEHelpers.BLE_CHAR_CUSTOM_TIME_MC);
                    if (_customTimeCharacteristic != null)
                    {
                        gatt.SetCharacteristicNotification(_customTimeCharacteristic, true);
                    }
                }
                else if (service.Uuid.Equals(BLEHelpers.BLE_SERVICE_CUSTOM_TIME_TI))
                {
                    _customTimeCharacteristic = service.GetCharacteristic(BLEHelpers.BLE_CHAR_CUSTOM_TIME_TI);
                    if (_customTimeCharacteristic != null)
                    {
                        gatt.SetCharacteristicNotification(_customTimeCharacteristic, true);
                    }
                }
                else if (service.Uuid.Equals(BLEHelpers.BLE_SERVICE_CUSTOM_TIME_TI_NEW))
                {
                    _customTimeCharacteristic = service.GetCharacteristic(BLEHelpers.BLE_CHAR_CUSTOM_TIME_TI_NEW);
                    if (_customTimeCharacteristic != null)
                    {
                        gatt.SetCharacteristicNotification(_customTimeCharacteristic, true);
                    }
                }

                if (_deviceManufacturerCharacteristic != null)
                {
                    gatt.ReadCharacteristic(_deviceManufacturerCharacteristic);
                }
            }
        }
        protected override async Task StartUpdatesNativeAsync()
        {
            // wire up the characteristic value updating on the gattcallback for event forwarding
            _gattCallback.CharacteristicValueUpdated += OnCharacteristicValueChanged;

            if (!_gatt.SetCharacteristicNotification(_nativeCharacteristic, true))
            {
                throw new CharacteristicReadException("Gatt SetCharacteristicNotification FAILED.");
            }

            // 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);

            // this might be because we need to wait on SetCharacteristicNotification ...maybe there alos is a callback for this?
            //ToDo is this still needed?

            if (_nativeCharacteristic.Descriptors.Count > 0)
            {
                var descriptors = await GetDescriptorsAsync();

                var descriptor = descriptors.FirstOrDefault(d => d.Id.Equals(ClientCharacteristicConfigurationDescriptorId)) ??
                                 descriptors.FirstOrDefault();            // fallback just in case manufacturer forgot

                //has to have one of these (either indicate or notify)
                if (Properties.HasFlag(CharacteristicPropertyType.Indicate))
                {
                    await descriptor.WriteAsync(BluetoothGattDescriptor.EnableIndicationValue.ToArray());

                    Trace.Message("Descriptor set value: INDICATE");
                }

                if (Properties.HasFlag(CharacteristicPropertyType.Notify))
                {
                    await descriptor.WriteAsync(BluetoothGattDescriptor.EnableNotificationValue.ToArray());

                    Trace.Message("Descriptor set value: NOTIFY");
                }
            }
            else
            {
                Trace.Message("Descriptor set value FAILED: _nativeCharacteristic.Descriptors was empty");
            }

            Trace.Message("Characteristic.StartUpdates, successful!");
        }
Пример #5
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);
        }
Пример #6
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);
        }
Пример #7
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;
                }
            }
        }
Пример #8
0
        /// <summary>
        /// Get the UUID's for the device details and sets the list
        /// </summary>
        /// <param name="gatt">Gatt.</param>
        private void getDeviceDetails(BluetoothGatt gatt)
        {
            try
            {
                UUID deviceInfoUUID = UUID.FromString(BluetoothConstants.DEVICE_INFO_SERVICE);
                BluetoothGattService deviceInfoSer = gatt.GetService(deviceInfoUUID);

                deviceChar = new List <BluetoothGattCharacteristic> {
                    deviceInfoSer.GetCharacteristic(UUID.FromString(BluetoothConstants.DEVICE_SERIALNUM)),
                    deviceInfoSer.GetCharacteristic(UUID.FromString(BluetoothConstants.DEVICE_MODELNUM)),
                    deviceInfoSer.GetCharacteristic(UUID.FromString(BluetoothConstants.DEVICE_SOFTWARE_REV)),
                    deviceInfoSer.GetCharacteristic(UUID.FromString(BluetoothConstants.DEVICE_FIRMWARE_REV)),
                    deviceInfoSer.GetCharacteristic(UUID.FromString(BluetoothConstants.DEVICE_HARDWARE_REV))
                };

                foreach (BluetoothGattCharacteristic c in deviceChar)
                {
                    try
                    {
                        gatt.SetCharacteristicNotification(c, false);
                        requestCharacteristic(gatt);
                    }
                    catch (System.Exception e)
                    {
                        string t = "";
                        // if the char dont exit for thiss
                    }
                }
            } catch (System.Exception e)
            {
                // stop ourselves
                sendStateUpdate(gatt.Device.Address, false, "Device could not be read from: " + e.Message);
            }
        }
Пример #9
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();
        }
Пример #10
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));
            }
        }
Пример #11
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");
                }
            }
        }
Пример #12
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);
            }
        }
Пример #13
0
            private void EnableNotification()
            {
                _gatt.SetCharacteristicNotification(_characteristic, true);
                var descriptor = _characteristic.GetDescriptor(UUID.FromString(NotifyDescriptorUuid));

                descriptor.SetValue(BluetoothGattDescriptor.EnableNotificationValue.ToArray());
                _gatt.WriteDescriptor(descriptor);
            }
Пример #14
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);
        }
Пример #15
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);
        }
Пример #16
0
 /// <summary>
 ///
 /// </summary>
 public virtual void OnServicesDiscovered(BluetoothGatt gatt, int status)
 {
     Log.i("BluetoothScannerGUI", "OnServicesDiscovered:" + status.ToString());
     if (status == BluetoothGatt.GATT_SUCCESS)
     {
         BluetoothGattService        srv = gatt.GetService(UUID.FromString("0000faea-0000-1000-8000-00805f9b34fb"));
         BluetoothGattCharacteristic chr = srv.GetCharacteristic(UUID.FromString("0000faeb-0000-1000-8000-00805f9b34fb"));
         gatt.SetCharacteristicNotification(chr, true);
     }
 }
Пример #17
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 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);
     }
 }
        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);
        }
        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);
        }
Пример #21
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);
        }
Пример #22
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);
        }
 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 (onConnectionStateChanged != null)
         {
             onConnectionStateChanged(this);
         }
     }
 }
        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);
            }
        }
Пример #25
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.");
        }
Пример #26
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);
                    }
                }
            });
        }
Пример #27
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);
            }
        }
Пример #28
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);
            }
        }
Пример #29
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();
        }
        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");
                }
            }
        }