public override void OnServicesDiscovered(BluetoothGatt gatt, GattStatus status)
            {
                System.Threading.Tasks.Task.Run(() =>
                {
                    base.OnServicesDiscovered(gatt, status);
                    if (gatt != null)
                    {
                        try
                        {
                            var serviceUuid = ParcelUuid.FromString(_tracingInformation.ServiceId);
                            BluetoothGattService service = gatt.GetService(serviceUuid.Uuid);

                            if (service != null)
                            {
                                _deviceManager.HandleDeviceCommunicationDiscoveredService(_descriptor, (d) =>
                                {
                                    var characteristicUuid = ParcelUuid.FromString(_tracingInformation.CharacteristicId);
                                    BluetoothGattCharacteristic characteristic = service.GetCharacteristic(characteristicUuid.Uuid);

                                    if (characteristic != null)
                                    {
                                        _deviceManager.HandleDeviceCommunicationDiscoveredCharacteristic(_descriptor, (d) =>
                                        {
                                            gatt.ReadCharacteristic(characteristic);
                                        });
                                    }
                                    else
                                    {
                                        _deviceManager.HandleIncorrectDevice(_descriptor, (d) =>
                                        {
                                            gatt.Disconnect();
                                        });
                                    }
                                });
                            }
                            else
                            {
                                _deviceManager.HandleIncorrectDevice(_descriptor, (d) =>
                                {
                                    gatt.Disconnect();
                                });
                            }
                        }
                        catch (Exception ex)
                        {
                            _deviceManager.HandleDeviceCommunicationDiscoveryServiceError(_descriptor, ex.Message, (d) =>
                            {
                                gatt.Disconnect();
                            });
                        }
                    }
                }).FireAndForget();
            }
Example #2
0
        public void Disconnect(String source)
        {
            if (mBluetoothGatt == null)
            {
                return;
            }

            mBluetoothGatt.Disconnect();

            LogMessage("Disconnect called from: " + source);
            OnStateChanged(new StateChangedEventArgs()
            {
                State = DriverState.ReaderDiconnected
            });
        }
        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);
            }
        }
Example #4
0
 public void HandleConnectionCancellation()
 {
     if (_currentConnectionToken.IsCancellationRequested)
     {
         _gatt?.Disconnect();
     }
 }
Example #5
0
 public void Disconnect()
 {
     if (_gatt != null)
     {
         _gatt.Disconnect();
         _gatt.Dispose();
     }
 }
 /// <summary>
 /// Disconnects an existing connection or cancel a pending connection. The disconnection result
 /// is reported asynchronously through the
 /// {@code BluetoothGattCallback#onConnectionStateChange(android.bluetooth.BluetoothGatt, int, int)}
 /// callback.
 /// </summary>
 public virtual void Disconnect()
 {
     if (Gatt == null)
     {
         Debug.WriteLine(TAG, "mBluetoothGatt not initialized");
         return;
     }
     Gatt.Disconnect();
 }
Example #7
0
 /**
  * Disconnects an existing connection or cancel a pending connection. The disconnection result
  * is reported asynchronously through the
  * {@code BluetoothGattCallback#onConnectionStateChange(android.bluetooth.BluetoothGatt, int, int)}
  * callback.
  */
 public void Disconnect()
 {
     if (mBluetoothAdapter == null || mBluetoothGatt == null)
     {
         Log.Warn(TAG, "BluetoothAdapter not initialized");
         return;
     }
     mBluetoothGatt.Disconnect();
 }
 private void DisconnectPeripheral(BluetoothGatt gatt)
 {
     try
     {
         gatt.Disconnect();
     }
     catch (Exception ex)
     {
         SensusServiceHelper.Get().Logger.Log("Exception while disconnecting peripheral:  " + ex, LoggingLevel.Normal, GetType());
     }
 }
Example #9
0
        public void readTimeout(object sender, EventArgs e, ref BluetoothGatt gatt)
        {
            TimeSpan duration = DateTime.Now - lastChange;

            if (duration.TotalMilliseconds > BluetoothConstants.LE_TIMEOUT)
            {
                readTimer.Enabled = false;
                // Sensor took too long to report our data
                gatt.Disconnect();
            }
        }
Example #10
0
 public void DisconnectPeripheral()
 {
     try
     {
         SensusServiceHelper.Get().Logger.Log("Disconnecting peripheral...", LoggingLevel.Normal, GetType());
         _peripheral?.Disconnect();
     }
     catch (Exception ex)
     {
         SensusServiceHelper.Get().Logger.Log("Exception while disconnecting peripheral:  " + ex, LoggingLevel.Normal, GetType());
     }
 }
        public override void OnCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic)
        {
            if (!BLEHelpers.UuidGlucMeasurementChar.Equals(characteristic.Uuid))
            {
                return;
            }
            var offset = 0;
            int flags  = characteristic.GetIntValue(GattFormat.Uint8, offset).IntValue();

            offset += 1;

            bool timeOffsetPresent               = (flags & 0x01) > 0;
            bool typeAndLocationPresent          = (flags & 0x02) > 0;
            bool sensorStatusAnnunciationPresent = (flags & 0x08) > 0;

            // create and fill the new record
            _record = new GlucoseDeviceData {
                SequenceNumber = characteristic.GetIntValue(GattFormat.Uint16, offset).IntValue()
            };
            offset += 2;

            int year    = characteristic.GetIntValue(GattFormat.Uint16, offset).IntValue();
            int month   = characteristic.GetIntValue(GattFormat.Uint8, offset + 2).IntValue();
            int day     = characteristic.GetIntValue(GattFormat.Uint8, offset + 3).IntValue();
            int hours   = characteristic.GetIntValue(GattFormat.Uint8, offset + 4).IntValue();
            int minutes = characteristic.GetIntValue(GattFormat.Uint8, offset + 5).IntValue();
            int seconds = characteristic.GetIntValue(GattFormat.Uint8, offset + 6).IntValue();

            offset += 7;

            var calendar = Calendar.Instance;

            calendar.Set(year, month, day, hours, minutes, seconds);

            if (timeOffsetPresent)
            {
                characteristic.GetIntValue(GattFormat.Uint16, offset).IntValue();
                offset += 2;
            }

            if (typeAndLocationPresent)
            {
                _record.GlucoseConcentration = characteristic.GetFloatValue(GattFormat.Sfloat, offset).FloatValue();
                offset += 3;
            }

            if (sensorStatusAnnunciationPresent)
            {
                characteristic.GetIntValue(GattFormat.Uint16, offset).IntValue();
            }

            gatt.Disconnect();
        }
        public override void OnConnectionStateChange(BluetoothGatt gatt, GattStatus status, ProfileState newState)
        {
            var devicesDataNormalized = from c in _listOfSavedDevices
                                        where c.Address == gatt.Device.Address
                                        select new { c.Name, c.Address, c.DeviceType };

            ((BloodPressureDeviceActivity)_context).isDeviceConnected = true;
            switch (newState)
            {
            case ProfileState.Connected:
                DisplayMessageToUi($"S-a conectat la {devicesDataNormalized.FirstOrDefault()?.Name}...");
                gatt.DiscoverServices();
                break;

            case ProfileState.Connecting:
                DisplayMessageToUi($"Se conecteaza la {devicesDataNormalized.FirstOrDefault()?.Name}...");
                break;

            case ProfileState.Disconnecting:
                DisplayMessageToUi($"Se deconecteaza de la {devicesDataNormalized.FirstOrDefault()?.Name}...");
                break;

            case ProfileState.Disconnected: {
                ((BloodPressureDeviceActivity)_context).isDeviceConnected = false;
                gatt.Disconnect();
                gatt.Close();
                Log.Error("GattPressure", "Disconnect");
                if (Records.Count > 0)
                {
                    DisplayMessageToUi("Citirea s-a efectuat cu success");
                    var result = Records.Where(e => e != null).ToList().OrderByDescending(v => v.RecordDateTime).ToList();
                    (_context as BloodPressureDeviceActivity)?.RunOnUiThread(() => {
                            if (Records.Count > 0)
                            {
                                ((BloodPressureDeviceActivity)_context).UpdateUi(result[0]);
                            }
                            (_context as BloodPressureDeviceActivity)?.AnimationView
                            .CancelAnimation();
                        });
                }
                else
                {
                    DisplayMessageToUi("Nu s-au gasit date");
                    (_context as BloodPressureDeviceActivity)?.RunOnUiThread(() => {
                            (_context as BloodPressureDeviceActivity)?.AnimationView
                            .CancelAnimation();
                            ((BloodPressureDeviceActivity)_context).UpdateUi(null);
                        });
                }
                break;
            }
            }
        }
        public override void Disconnect()
        {
            if (bluetoothAdapter == null)
            {
                throw new BluetoothLEException("BluetoothAdapter not initialized.");
            }

            if (bluetoothGatt == null)
            {
                bluetoothGatt.Disconnect();
            }
        }
Example #14
0
        public override void OnCharacteristicWrite(
            BluetoothGatt gatt,
            BluetoothGattCharacteristic characteristic,
            [Android.Runtime.GeneratedEnum] GattStatus status)
        {
            base.OnCharacteristicWrite(gatt, characteristic, status);

            _MainActivity.AppendLogText(status != GattStatus.Success
                                ? "OnCharacteristicWrite: Write failed."
                                : "OnCharacteristicWrite: Write succeded.");
            gatt.Disconnect();
        }
Example #15
0
        public override void OnServicesDiscovered(BluetoothGatt gatt, GattStatus status)
        {
            if (status != GattStatus.Success)
            {
                _MainActivity.AppendLogText("Failed to discover services");
                gatt.Disconnect();
                return;
            }
            _MainActivity.AppendLogText("Services Discovered");

            var configurationService = gatt.GetService(_ConfigurationService);

            if (configurationService == null)
            {
                _MainActivity.AppendLogText("Unable to find configuration service");
                gatt.Disconnect();
                return;
            }

            var configurationKeyCharacteristic = configurationService.GetCharacteristic(_ConfigurationKeyCharacteristic);

            if (configurationKeyCharacteristic == null)
            {
                _MainActivity.AppendLogText("Unable to find characteristic");
                gatt.Disconnect();
                return;
            }

            var configKeyBytes = StringToByteArrayFastest(_ConfigurationValue);

            configurationKeyCharacteristic.SetValue(configKeyBytes);
            if (!gatt.WriteCharacteristic(configurationKeyCharacteristic))
            {
                _MainActivity.AppendLogText("Failed to write characteristic");
            }
            else
            {
                _MainActivity.AppendLogText("Writing characteristic...");
            }
        }
Example #16
0
 /**
  * Disconnects an existing connection or cancel a pending connection. The disconnection result
  * is reported asynchronously through the
  * {@code BluetoothGattCallback#onConnectionStateChange(android.bluetooth.BluetoothGatt, int, int)}
  * callback.
  */
 public void Disconnect()
 {
     logger.TraceInformation("Try disconnect");
     if (bluetoothAdapter == null || bluetoothGatt == null)
     {
         logger.TraceWarning("BluetoothAdapter not initialized");
         return;
     }
     SensorDataPage.Instance.disconnectionStopwatch.Reset();
     SensorDataPage.Instance.disconnectionStopwatch.Start();
     progressDialog = ProgressDialog.Show(thisActivity, "Please wait...", "Disconnecting...", true);
     bluetoothGatt.Disconnect();
 }
Example #17
0
        // First step
        public void Disconnect()
        {
            if (_gatt != null)
            {
                ClearServices();

                _gatt.Disconnect();
            }
            else
            {
                Trace.Message("[Warning]: Can't disconnect {0}. Gatt is null.", Name);
            }
        }
Example #18
0
        // First step
        public void Disconnect()
        {
            if (_gatt != null)
            {
                //TODO: clear cached services
                KnownServices.Clear();

                _gatt.Disconnect();
            }
            else
            {
                Trace.Message("[Warning]: Can't disconnect {0}. Gatt is null.", Name);
            }
        }
Example #19
0
        // First step
        public void Disconnect()
        {
            if (_gatt != null)
            {
                //clear cached services
                _services.Clear();

                _gatt.Disconnect();
            }
            else
            {
                Console.WriteLine("Can't disconnect {0}. Gatt is null.", Name);
            }
        }
        public override void OnConnectionStateChange(BluetoothGatt gatt, GattStatus status, ProfileState newState)
        {
            base.OnConnectionStateChange(gatt, status, newState);
            var devicesDataNormalized = from c in _listOfSavedDevices
                                        where c.Address == gatt.Device.Address
                                        select new { c.Name, c.Address, c.DeviceType };

            ((GlucoseDeviceActivity)_context).isDeviceConnected = true;
            switch (newState)
            {
            case ProfileState.Connected:
                DisplayMessageToUi($"S-a conectat la {devicesDataNormalized.FirstOrDefault()?.Name}...");
                gatt.DiscoverServices();
                break;

            case ProfileState.Connecting:
                DisplayMessageToUi($"Se conecteaza la {devicesDataNormalized.FirstOrDefault()?.Name}...");
                break;

            case ProfileState.Disconnected:
                ((GlucoseDeviceActivity)_context).isDeviceConnected = false;
                gatt.Close();
                gatt.Disconnect();
                DisplayMessageToUi("Citirea s-a efectuat cu succes");
                if (_records.Count > 0)
                {
                    var oderedRecords = _records.OrderByDescending(r => r.Value.DateTimeRecord).ToList();
                    Task.Run(() => {
                        ((GlucoseDeviceActivity)_context).RunOnUiThread(async() =>
                                                                        await((GlucoseDeviceActivity)_context).UpdateUi(oderedRecords.First().Value
                                                                                                                        .GlucoseData));
                    });
                }
                else
                {
                    DisplayMessageToUi("Nu s-au gasit date");
                    Task.Run(() => {
                        ((GlucoseDeviceActivity)_context).RunOnUiThread(async() =>
                                                                        await((GlucoseDeviceActivity)_context).UpdateUi());
                    });
                }

                break;

            case ProfileState.Disconnecting:
                DisplayMessageToUi($"Se deconecteaza de la {devicesDataNormalized.FirstOrDefault()?.Name}...");
                break;
            }
        }
Example #21
0
        public Task DisconnectAsync()
        {
            disconnectTCS = new TaskCompletionSource <bool>();

            try
            {
                _gatt.Disconnect();
            }
            catch (Exception ex)
            {
                disconnectTCS.TrySetException(ex);
            }

            return(disconnectTCS.Task);
        }
Example #22
0
        public void Disconnect()
        {
            if (gatt != null)
            {
                gatt.Disconnect();
                gatt.Close();

                if (onConnectionStateChanged != null)
                {
                    onConnectionStateChanged(this);
                }
            }

            gatt = null;
        }
Example #23
0
        /// <summary>
        /// This method is only called by a user triggered disconnect.
        /// A user will first trigger _gatt.disconnect -> which in turn will trigger _gatt.Close() via the gattCallback
        /// </summary>
        public void Disconnect()
        {
            if (_gatt != null)
            {
                IsOperationRequested = true;

                ClearServices();

                _gatt.Disconnect();
            }
            else
            {
                Trace.Message("[Warning]: Can't disconnect {0}. Gatt is null.", Name);
            }
        }
Example #24
0
        /// <summary>
        /// This method is only called by a user triggered disconnect.
        /// A user will first trigger _gatt.disconnect -> which in turn will trigger _gatt.Close() via the gattCallback
        /// </summary>
        public void Disconnect()
        {
            if (_gatt != null)
            {
                IsOperationRequested   = true;
                IsAutoConnectRequested = false; // user disconnect disables autconnect

                ClearServices();

                _gatt.Disconnect();
            }
            else
            {
                Trace.Message("[Warning]: Can't disconnect {0}. Gatt is null.", Name);
            }
        }
Example #25
0
 public override void OnCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, GattStatus status)
 {
     System.Threading.Tasks.Task.Run(() =>
     {
         try
         {
             base.OnCharacteristicRead(gatt, characteristic, status);
             var payload = characteristic.GetValue();
             _deviceManager.HandleDeviceCommunicationDiscoveredCharacteristicRead(_descriptor, payload);
             gatt.Disconnect();
         }
         catch (Exception ex)
         {
             _deviceManager.HandleDeviceCommunicationDiscoveredCharacteristicReadError(_descriptor, ex.Message);
         }
     }).FireAndForget();
 }
Example #26
0
 public void Disconnect()
 {
     try
     {
         timeoutVerification = false;
         BluetoothGatt?.Disconnect();
         BluetoothGatt?.Close();
         BluetoothGatt = null;
         lock (Sensor.Instance)
             Sensor.Instance.Status = SensorStatus.Disconnected;
     }
     catch (System.Exception ex)
     {
         string title = this.GetType().Name + " - " + System.Reflection.MethodBase.GetCurrentMethod().Name;
         BalizaFacil.App.Instance.UnhandledException(title, ex);
     }
 }
        public Task Disconnect()
        {
            if (_connectTaskCompletionSource != null && _connectTaskCompletionSource.Task.IsCanceled == false)
            {
                // TODO: this causes app to crash. While not ideal, this works for the current flow.
                _connectTaskCompletionSource.SetCanceled();
            }

            // TODO: Handle is connecting.
            if (_bluetoothGatt != null)
            {
                _bluetoothGatt.Disconnect();
            }

            _board = null;

            return(Task.CompletedTask);
        }
Example #28
0
        public void Disconnect()
        {
            lock (_lock)
            {
                if (_bluetoothGatt != null)
                {
                    _bluetoothGatt.Disconnect();
                    _bluetoothGatt.Close();
                    _bluetoothGatt.Dispose();
                    _bluetoothGatt = null;

                    _bluetoothDevice.Dispose();
                    _bluetoothDevice = null;
                }

                State = BluetoothLEDeviceState.Disconnected;
            }
        }
        // Implemented from IRig
        public void Disconnect()
        {
            try {
                if (gatt != null)
                {
                    gatt.Disconnect();
                    gatt.Close();
                    NotifyConnectionState();
                }

/*
 *                              handler.RemoveCallbacksAndMessages(null);
 */
                gatt = null;
            } catch (Exception e) {
                Log.E(this, "Failed to disconnect", e);
            }
        }
Example #30
0
        /// <summary>
        /// Discconnect from the device.
        /// </summary>
        public void Disconnect()
        {
            if (_gatt == null)
            {
                return;
            }

            try
            {
                _gatt.Disconnect();
                _gatt.Close();

                State = DeviceState.Disconnected;
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.Message);
            }
        }