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();
    }
  }
  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");
  }