Example #1
0
        public void Connect()
        {
            BluetoothManager bluetoothManager = (BluetoothManager)ctx.GetSystemService(Context.BluetoothService);

            if (bluetoothManager == null)
            {
                LogMessage("Unable to initialize BluetoothManager.");
                throw new Exception("Unable to initialize BluetoothManager.");
            }

            if (bluetoothManager.Adapter == null)
            {
                LogMessage("Unable to obtain a BluetoothAdapter.");
                throw new Exception("Unable to obtain a BluetoothAdapter.");
            }

            //stop scanning if scanning still in progress
            bluetoothManager.Adapter.StopLeScan(leScanCallback);

            mGattCallback = new BluetoothReaderGattCallback();

            mGattCallback.ConnectionStateChange += MGattCallback_ConnectionStateChange;

            mBluetoothReaderManager = new BluetoothReaderManager();

            mBluetoothReaderManager.ReaderDetection += MBluetoothReaderManager_ReaderDetection;

            if (mBluetoothGatt != null)
            {
                LogMessage("Clear old GATT connection");
                mBluetoothGatt.Disconnect();
                mBluetoothGatt.Close();
                mBluetoothGatt = null;
            }

            BluetoothDevice device = bluetoothManager.Adapter.GetRemoteDevice(mDeviceAddress);

            if (device == null)
            {
                LogMessage("Device not found. Unable to connect.");
                OnStateChanged(new StateChangedEventArgs()
                {
                    State = DriverState.ReaderDiconnected
                });
                throw new Exception("Device not found. Unable to connect.");
            }

            //Connect gat will connect and call mGattCallback which in turn calls detect reader
            mBluetoothGatt = device.ConnectGatt(ctx, false, mGattCallback);
        }
Example #2
0
        public override void OnConnectionStateChange(BluetoothGatt gatt, [GeneratedEnum] GattStatus status, [GeneratedEnum] ProfileState newState)
        {
            try
            {
                if (status == GattStatus.Success)
                {
                    if (newState == ProfileState.Connected && _Device == null)
                    {
                        BLEC("connected to " + gatt.Device.Address + ", status=" + status + ", bond=" + gatt.Device.BondState + ", discovering service...");

                        _ServerDevice = gatt;
                        _Device       = gatt.Device.Address;
                        ConnectionCompleted?.Invoke(true);

                        if (!_ServerDevice.DiscoverServices())
                        {
                            BLEC_ERR("can't start discovery service");
                        }
                    }
                    else if (newState == ProfileState.Connected)
                    {
                        gatt.Close();
                    }
                    else if (newState == ProfileState.Disconnected && _Device != null && gatt.Device.Address == _Device)
                    {
                        _Device = null;
                        ConnectionCompleted?.Invoke(false);
                    }
                }
            }
            catch (Exception ex)
            {
                BLEC_ERR("generic connection state changed", ex);
            }
        }
 public override void OnConnectionStateChange(BluetoothGatt gatt, GattStatus status, ProfileState newState)
 {
     if (status == GattStatus.Success && newState == ProfileState.Connected)
     {
         try
         {
             gatt.DiscoverServices();
         }
         catch (Exception ex)
         {
             SensusServiceHelper.Get().Logger.Log("Exception while discovering services:  " + ex, LoggingLevel.Normal, GetType());
             DisconnectPeripheral(gatt);
         }
     }
     // ensure that all disconnected peripherals get closed (released). without closing, we'll use up all the BLE interfaces.
     else if (newState == ProfileState.Disconnected)
     {
         try
         {
             gatt.Close();
         }
         catch (Exception ex)
         {
             SensusServiceHelper.Get().Logger.Log("Exception while closing disconnected client:  " + ex, LoggingLevel.Normal, GetType());
         }
     }
 }
Example #4
0
        /// <Docs>GATT client</Docs>
        /// <summary>
        /// Raises the connection state change event.
        /// </summary>
        /// <param name="gatt">Gatt.</param>
        /// <param name="status">Status.</param>
        /// <param name="newState">New state.</param>
        public override void OnConnectionStateChange(BluetoothGatt gatt, GattStatus status, ProfileState newState)
        {
            base.OnConnectionStateChange(gatt, status, newState);

            if (status != GattStatus.Success)
            {
                return;
            }

            var device = new Device(gatt.Device, gatt, this, 0);

            switch (newState)
            {
            case ProfileState.Disconnected:
                device.State = DeviceState.Disconnected;

                try {
                    gatt.Close();
                    gatt = null;
                } catch (Exception ex) {
                    Debug.WriteLine("Unable to close connection to gatt. Exception: {0}", ex.Message);
                } finally {
                    DeviceDisconnected(this, new DeviceConnectionEventArgs(device));
                }

                break;

            case ProfileState.Connected:
                device.State = DeviceState.Connected;

                DeviceConnected(this, new DeviceConnectionEventArgs(device));
                break;
            }
        }
Example #5
0
 /**
  * After using a given BLE device, the app must call this method to ensure resources are
  * released properly.
  */
 public void Close()
 {
     if (bluetoothGatt == null)
     {
         return;
     }
     bluetoothGatt.Close();
     bluetoothGatt = null;
 }
Example #6
0
 /**
  * After using a given BLE device, the app must call this method to ensure resources are
  * released properly.
  */
 public void Close()
 {
     if (mBluetoothGatt == null)
     {
         return;
     }
     mBluetoothGatt.Close();
     mBluetoothGatt = null;
 }
Example #7
0
        /// <summary>
        /// CloseGatt is called by the gattCallback in case of user disconnect or a disconnect by signal loss or a connection error.
        /// Cleares all cached services.
        /// </summary>
        public void CloseGatt()
        {
            _gatt?.Close();
            _gatt = null;

            // ClossGatt might will get called on signal loss without Disconnect being called we have to make sure we clear the services
            // Clear services & characteristics otherwise we will get gatt operation return FALSE when connecting to the same IDevice instace at a later time
            ClearServices();
        }
Example #8
0
 private void CloseGATT()
 {
     if (_gatt != null)
     {
         _gatt.Close();
         _gatt.Dispose();
         _gatt = null;
     }
 }
 /// <summary>
 /// After using a given BLE device, the app must call this method to ensure resources are
 /// released properly.
 /// </summary>
 public virtual void Close()
 {
     if (Gatt == null)
     {
         return;
     }
     Debug.WriteLine(TAG, "mBluetoothGatt closed");
     DeviceAddress = null;
     Gatt.Close();
     Gatt = null;
 }
Example #10
0
 //Second step
 public void CloseGatt()
 {
     if (_gatt != null)
     {
         _gatt.Close();
         _gatt = null;
     }
     else
     {
         Console.WriteLine("Can't close gatt {0}. Gatt is null.", Name);
     }
 }
Example #11
0
 //Second step
 public void CloseGatt()
 {
     if (_gatt != null)
     {
         _gatt.Close();
         _gatt = null;
     }
     else
     {
         Trace.Message("[Warning]: Can't close gatt after disconnect {0}. Gatt is null.", Name);
     }
 }
        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;
            }
            }
        }
Example #13
0
        private void CloseGattInstances(BluetoothGatt gatt)
        {
            //ToDO just for me
            Trace.Message($"References of parnet device gatt and callback gatt equal? {ReferenceEquals(_device._gatt, gatt).ToString().ToUpper()}");

            if (!ReferenceEquals(gatt, _device._gatt))
            {
                gatt.Close();
            }

            //cleanup everything else
            _device.CloseGatt();
        }
Example #14
0
        private void LeSensorConnect(Object sender, DoWorkEventArgs e, BluetoothDevice dev)
        {
            SensorStateBroadcastReceiver rec = new SensorStateBroadcastReceiver();

            System.Timers.Timer sensorTimeOut = new System.Timers.Timer();

            BGattCallback bcallback = new BGattCallback();
            BluetoothGatt g         = dev.ConnectGatt(Application.Context, true, bcallback);

            sensorTimeOut.AutoReset = false;
            sensorTimeOut.Interval  = AppUtil.SENSOR_CONNECT_TIMEOUT;
            sensorTimeOut.Elapsed  += delegate {
                sensorTimeOut.Enabled = false;
                sendDisconnectStateUpdate(dev.Address);
                Android.App.Application.Context.UnregisterReceiver(rec);
            };

            rec.SensorConnect += delegate {
                sensorTimeOut.Enabled = false;
                Android.App.Application.Context.UnregisterReceiver(rec);
            };

            rec.SensorDisconnect += delegate {
                sensorTimeOut.Enabled = false;
                Android.App.Application.Context.UnregisterReceiver(rec);
            };

            sensorTimeOut.Enabled = true;

            IntentFilter fil = new IntentFilter();

            fil.AddAction(AppUtil.SENSOR_CONNECT_ACTION);
            fil.AddAction(AppUtil.SENSOR_DISCONNECT_ACTION);
            fil.Priority = 98;
            Android.App.Application.Context.RegisterReceiver(rec, fil);

            System.Timers.Timer cancelCheck = new System.Timers.Timer();
            cancelCheck.AutoReset = true;
            cancelCheck.Interval  = 5 * 1000;
            cancelCheck.Elapsed  += delegate {
                BackgroundWorker worker = (BackgroundWorker)sender;

                if (worker.CancellationPending)
                {
                    g.Close();
                    cancelCheck.Enabled = false;
                }
            };

            cancelCheck.Enabled = true;
        }
Example #15
0
        private void PerformDisconnect(IDevice device)
        {
            try
            {
                _gatt.Close(); // this will not trigger the OnConnectionStateChange.OnConnectionStateChange callback
                _gatt = null;

                DeviceDisconnected(this, new DeviceConnectionEventArgs(device));
            }
            catch (Exception e)
            {
                System.Diagnostics.Debug.WriteLine(e.Message);
            }
        }
        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 #17
0
        public void Disconnect()
        {
            if (gatt != null)
            {
                gatt.Disconnect();
                gatt.Close();

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

            gatt = null;
        }
 //ble连接状态改变的回调
 public override void OnConnectionStateChange(BluetoothGatt gatt, [GeneratedEnum] GattStatus status, [GeneratedEnum] ProfileState newState)
 {
     Log.Error("dana.ye->xamarin->bt", "cur status is " + status);
     Log.Error("dana.ye->xamarin->bt", "cur newState is " + newState);
     if (status == GattStatus.Success)
     {
         listener.OnGattCallBack();
     }
     else if (newState == ProfileState.Disconnected)
     {
         Log.Error("dana.ye->xamarin->bt", "gett.Disconnect()");
         // 防止出现status 133
         Log.Error("dana.ye->xamarin->bt", "关闭GATT");
         gatt.Close();
         listener.OnStatusNotSuccess();
     }
 }
Example #19
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);
     }
 }
        // 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 #21
0
        public void Disconnect()
        {
            lock (_lock)
            {
                if (_bluetoothGatt != null)
                {
                    _bluetoothGatt.Disconnect();
                    _bluetoothGatt.Close();
                    _bluetoothGatt.Dispose();
                    _bluetoothGatt = null;

                    _bluetoothDevice.Dispose();
                    _bluetoothDevice = null;
                }

                State = BluetoothLEDeviceState.Disconnected;
            }
        }
Example #22
0
            public override void OnConnectionStateChange(BluetoothGatt gatt, [GeneratedEnum] GattStatus status, [GeneratedEnum] ProfileState newState)
            {
                base.OnConnectionStateChange(gatt, status, newState);

                if (status == GattStatus.Success)
                {
                    if (newState == ProfileState.Connected)
                    {
                        gatt.DiscoverServices();
                    }
                    else if (newState == ProfileState.Disconnected)
                    {
                        Log.Debug(tag, "GATT DESCONECTADO");
                        gatt.Close();
                        gatt = null;
                    }
                }
            }
Example #23
0
        public override void OnConnectionStateChange(BluetoothGatt gatt, [GeneratedEnum] GattStatus status, [GeneratedEnum] ProfileState newState)
        {
            base.OnConnectionStateChange(gatt, status, newState);
            if (newState == ProfileState.Connected)
            {
                State = DeviceState.Connected;
                connectTCS.TrySetResult(true);
            }
            else if (newState == ProfileState.Disconnected)
            {
                gatt.Close();
                State = DeviceState.Disconnected;
                //The device can disconnect by itself, not only because we asked
                disconnectTCS?.TrySetResult(true);

                OnDeviceDisconnected();
            }
        }
Example #24
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);
            }
        }
Example #25
0
        /// <summary>
        /// CloseGatt is called by the gattCallback in case of user disconnect or a disconnect by signal loss or a connection error.
        /// Cleares all cached services.
        /// </summary>
        public void CloseGatt()
        {
            if (_gatt == null)
            {
                Trace.Message("[Warning]: Can't close gatt after disconnect {0}. Gatt is null.", Name);
                return;
            }

            // ClossGatt might will get called on signal loss without Disconnect being called
            // we have to make sure we clear the services
            ClearServices();

            // signal loss will not determine the closing of our gatt instance so that autoconnect can work
            if (!IsAutoConnectRequested)
            {
                _gatt.Close();
                _gatt = null;
            }
        }
Example #26
0
        public void Disconnect()
        {
            lock (_lock)
            {
                _onDeviceDisconnected    = null;
                _onCharacteristicChanged = null;

                if (_bluetoothGatt != null)
                {
                    _bluetoothGatt.Disconnect();
                    _bluetoothGatt.Close();
                    _bluetoothGatt.Dispose();
                    _bluetoothGatt = null;

                    _bluetoothDevice.Dispose();
                    _bluetoothDevice = null;
                }

                State = BluetoothLEDeviceState.Disconnected;
            }
        }
Example #27
0
        public void EnumServices(Context ctx, string identifer)
        {
            BluetoothDevice device = mapDevices[identifer];

            if (device != null)
            {
                GattDevice gattdevice = new GattDevice(ctx, identifer);
                if (gatt != null)
                {
                    //gatt.Disconnect();
                    gatt.Close();   //or gatt.Connect() to re-connect to device
                    gatt.Dispose();
                }

                gatt = device.ConnectGatt(ctx, false, gattdevice);  //-> OnConnectionStateChange() -> DiscoverServices() -> OnServicesDiscovered() -> GattDevice.Initialize()
                if (gatt == null)
                {
                    Log.Error(TAG, string.Format("failed to connect to GATT server '{0}'", identifer));
                }
            }
        }
Example #28
0
        public bool CloseConnection()
        {
            try
            {
                BLEC("close callback");

                if (_ServerDevice != null)
                {
                    _ServerDevice.Disconnect();
                    _ServerDevice.Close();
                    _ServerDevice = null;
                }

                return(true);
            }
            catch (Exception ex)
            {
                BLEC_ERR("close callback error", ex);
                return(false);
            }
        }
Example #29
0
        private void OnDeviceConnect()
        {
            Log.Error("dana.ye->xamarin->bt", "手动点击按钮来停止扫描周围的蓝牙设备");
            btAdapter.CancelDiscovery();

            /*try
             * {
             #pragma warning disable CS0618 // 类型或成员已过时
             *  btAdapter.StopLeScan(bleScanCallback);
             #pragma warning restore CS0618 // 类型或成员已过时
             * }
             * catch (Exception e)
             * {
             *  Log.Error("dana.ye->xamarin->bt", "stopLeScan时出错 : " + e.Message);
             * }*/
            handler.RemoveCallbacks(action);
            if (gatt != null)
            {
                gatt.Disconnect();
                gatt.Close();
            }
            Log.Error("dana.ye->xamarin->bt", "即将进行BLE的设备连接");
            String addr = searchedDevices[adapter.GetChooseItem()].Address;

            SingleGattService.GetInstance().Address = addr;
            BluetoothDevice device        = btAdapter.GetRemoteDevice(addr);
            GattCallBack    mGattCallback = new GattCallBack(this);

            SingleGattService.GetInstance().CurCallback = mGattCallback;
            if (Android.OS.Build.VERSION.SdkInt >= BuildVersionCodes.M)
            {
                Log.Error("dana.ye->xamarin->bt", "SdkInt >= M");
                gatt = device.ConnectGatt(this, false, mGattCallback, BluetoothTransports.Le);
            }
            else
            {
                Log.Error("dana.ye->xamarin->bt", "SdkInt < M");
                gatt = device.ConnectGatt(this, false, mGattCallback);
            }
        }
Example #30
0
        /// <summary>
        ///     Discconnect from the device.
        /// </summary>
        public void Disconnect()
        {
            if (_gatt == null)
            {
                return;
            }

            try
            {
                var man = (BluetoothManager)Application.Context.GetSystemService(Context.BluetoothService);
                if (man.GetConnectionState(_nativeDevice, ProfileType.Gatt) == ProfileState.Connecting)
                {
                    _gatt.Disconnect();
                }

                _gatt.Close();

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