private void setDevice(BluetoothDevice device) {

    EventBus.getDefault().post(new HeartRateEvent("Setting device: " + device.getAddress()));

    if (mDevice != null
        && device != null
        && !device.getAddress().equals(mDevice.getAddress())
        && mBluetoothLeService != null) {
      mBluetoothLeService.disconnect();
    }

    mDevice = device;

    if (mDevice != null && mBluetoothLeService != null) {

      mBluetoothLeService.connect(mDevice.getAddress());

      removeTimers();

      mTimer = new Timer();
      mTimer.schedule(
          new TimerTask() {
            @Override
            public void run() {
              if (!mConnected) {
                scanLeDevice(true);
              }
            }
          },
          SCAN_PERIOD);
    }
  }
        @Override
        public void onServiceDisconnected(ComponentName componentName) {

          if (mBluetoothLeService != null) {
            mBluetoothLeService.disconnect();
            mBluetoothLeService.close();
          }

          mBluetoothLeService = null;
          mBpm = HeartRateConstants.HEART_RATE_MONITOR_NOT_CONNECTED;
        }
  private void stopListening() {

    EventBus.getDefault().post(new HeartRateEvent("Turning off heart rate monitor"));

    mBpm = HeartRateConstants.HEART_RATE_MONITOR_NOT_CONNECTED;
    mConnected = false;
    mDevice = null;
    mCurrentRSSI = 0;

    EventBus.getDefault().post(new BlueToothLEEvent(mBpm));

    scanLeDevice(false);

    if (mBluetoothLeService != null) {
      mBluetoothLeService.disconnect();
      mBluetoothLeService.close();
    }
  }
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder service) {

          mBluetoothLeService = ((BluetoothLeService.LocalBinder) service).getService();
          if (!mBluetoothLeService.initialize()) {
            Log.e("BLE", "Unable to initialize Bluetooth");
          }

          scanLeDevice(true);
        }
  public void stop() {

    scanLeDevice(false);

    mConnected = false;
    mDevice = null;
    mCurrentRSSI = 0;
    mBpm = HeartRateConstants.HEART_RATE_MONITOR_NOT_CONNECTED;

    Log.d("BLE", "Stopping service");

    if (mContext != null) {
      mContext.unbindService(mServiceConnection);
      unRegisterReceivers();
    } else {
      Log.d("BLE", "No Context");
    }

    if (mTimer != null) {
      mTimer.cancel();
      mTimer.purge();
    } else {
      Log.d("BLE", "No Timer");
    }

    if (mBluetoothLeService != null) {
      mBluetoothLeService.disconnect();
      mBluetoothLeService.close();
    } else {
      Log.d("BLE", "No Bluetooth Service");
    }

    mBluetoothLeService = null;

    Log.d("BLE", "Finished ending service");
  }
        @Override
        public void onReceive(Context context, Intent intent) {
          final String action = intent.getAction();
          if (BluetoothLeService.ACTION_GATT_CONNECTED.equals(action)) {

            EventBus.getDefault()
                .post(new HeartRateEvent("Connected to device: " + mDevice.getAddress()));

            removeTimers();

          } else if (BluetoothLeService.ACTION_GATT_DISCONNECTED.equals(action)) {

            EventBus.getDefault()
                .post(new HeartRateEvent("Disconnected from device: " + mDevice.getAddress()));

            mConnected = false;

            mBpm = HeartRateConstants.HEART_RATE_MONITOR_NOT_CONNECTED;
            EventBus.getDefault().post(new BlueToothLEEvent(mBpm));

            scanLeDevice(true);

          } else if (BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED.equals(action)) {

            mConnected = true;

            EventBus.getDefault().post(new HeartRateEvent("Gatt services connected"));

            mBpm = 0;
            EventBus.getDefault().post(new BlueToothLEEvent(mBpm));

            final List<BluetoothGattService> gattServices =
                mBluetoothLeService.getSupportedGattServices();

            // Loops through available GATT Services.
            boolean found = false;
            String uuid = "";
            for (BluetoothGattService gattService : gattServices) {

              final List<BluetoothGattCharacteristic> gattCharacteristics =
                  gattService.getCharacteristics();

              if (gattCharacteristics != null) {

                // Loops through available Characteristics.
                for (BluetoothGattCharacteristic gattCharacteristic : gattCharacteristics) {

                  if (gattCharacteristic != null) {

                    uuid = gattCharacteristic.getUuid().toString();
                    if (mBluetoothLeService != null
                        && uuid != null
                        && uuid.equals(GattAttributes.HEART_RATE_MEASUREMENT)) {

                      found = true;

                      mBluetoothLeService.setCharacteristicNotification(gattCharacteristic, true);
                    }
                  }
                }
              }
            }

            if (!found) {
              EventBus.getDefault()
                  .post(new HeartRateEvent("Connected to a non heart rate monitor"));
            }

          } else if (BluetoothLeService.ACTION_DATA_AVAILABLE.equals(action)) {

            final String bpm = intent.getStringExtra(BluetoothLeService.EXTRA_DATA);

            EventBus.getDefault().post(new HeartRateEvent("Heart rate received: " + bpm));

            try {
              mBpm = Integer.parseInt(bpm);
              EventBus.getDefault().post(new BlueToothLEEvent(mBpm));
            } catch (Exception exp) {
              exp.printStackTrace();
              mBpm = 0;
            }
          } else if (BluetoothLeService.ACTION_GATT_SERVICES_ERROR.equals(action)) {

            EventBus.getDefault().post(new HeartRateEvent("Gatt services error"));

            removeTimers();

            mTimer = new Timer();
            mTimer.schedule(
                new TimerTask() {
                  @Override
                  public void run() {
                    scanLeDevice(true);
                  }
                },
                SCAN_PERIOD);
          }
        }