title: I am trying to change my app to exchange data with a device using BLE instead of classical Bluetooth
body: <p>Ok bare with me because this will be a long read. I have an app that I am trying to integrate BLE into instead of classical Bluetooth. The app was made by freelancers but I am tasked to alter it. It uses a MVVM architecture.</p>
  <p>originally this app used classical Bluetooth. There is a Bluetooth Controller class, and it gets instantiated in a DataStore class. The DataStore has functions that use the instance made of the BluetoothController to call on functions in that class that request codes that correspond to the desired parameter. Meaning, There is an enum class that has the names of every parameter to be read or written and represents each one with a code.</p>
  <p>for example:</p>
  <pre><code>    `enum class ReadRequestCodes(val value:String) {
          KEY_ADDRESS  (&quot;08 00 00 00 20 30 05 11 00 00 00 00 00&quot;),
          TOOL_ADDRESS (&quot;08 00 00 00 20 30 05 27 00 00 00 00 00&quot;),
          RPM_THRESHOLD(&quot;08 00 00 00 20 30 05 13 00 00 00 00 00&quot;),
          BACKLASH     (&quot;08 00 00 00 20 30 05 22 00 00 00 00 00&quot;),
      
          POWER_SRC_TYPE     (&quot;08 00 00 00 20 30 05 26 00 00 00 00 00&quot;),
          BATTERY1_PERCENTAGE(&quot;08 00 00 00 20 30 11 00 00 00 00 00 00&quot;),
          BATTERY2_PERCENTAGE(&quot;08 00 00 00 20 30 12 00 00 00 00 00 00&quot;),
      
          HOME_POSITION     (&quot;08 00 00 00 20 30 05 15 00 00 00 00 00&quot;),
          BYPASS_POSITION   (&quot;08 00 00 00 20 30 05 17 00 00 00 00 00&quot;),
          HC_POSITION       (&quot;08 00 00 00 20 30 05 19 00 00 00 00 00&quot;),
          ISOLATION_POSITION(&quot;08 00 00 00 20 30 05 1B 00 00 00 00 00&quot;),
      
          PRESSURE_SENSOR_GAIN(&quot;08 00 00 00 20 30 05 2B 00 00 00 00 00&quot;),
          PRESSURE_SENSOR_OFFSET(&quot;08 00 00 00 20 30 05 2C 00 00 00 00 00&quot;),
          PRESSURE_SENSOR_RANGE(&quot;08 00 00 00 20 30 05 2A 00 00 00 00 00&quot;),
          PRESSURE_SENSOR_EXCITATION(&quot;08 00 00 00 20 30 05 29 00 00 00 00 00&quot;),
          PRESSURE_SENSOR_SERIAL(&quot;08 00 00 00 20 30 05 2D 00 00 00 00 00&quot;),
          GOTO_CURRENT_LIMIT(&quot;08 00 00 00 20 30 05 50 00 00 00 00 00&quot;),
          GOTO_RPM_LIMIT(&quot;08 00 00 00 20 30 05 52 00 00 00 00 00&quot;),
          FW_HW_VERSION(&quot;08 00 00 00 20 30 09 00 00 00 00 00 00&quot;),
          READ_EEPROM_MEMORY(&quot;08 00 00 00 20 30 0A 00 00 00 00 00 00&quot;)
  
  }
  `
  </code></pre>
  <p>This is in the Bluetooth Controller class. The DataStore has these functions:</p>
  <pre><code> fun requestKeyAddress(){
          bluetoothController.requestReadValues(ReadRequestCodes.KEY_ADDRESS.value)
      }
      fun requestToolAddress(){
          bluetoothController.requestReadValues(ReadRequestCodes.TOOL_ADDRESS.value)
      }
      fun requestRpmThreshold(){
          bluetoothController.requestReadValues(ReadRequestCodes.RPM_THRESHOLD.value)
      }
      fun requestBacklash(){
          bluetoothController.requestReadValues(ReadRequestCodes.BACKLASH.value)
      }
      fun requestPowerSrc(){
          bluetoothController.requestReadValues(ReadRequestCodes.POWER_SRC_TYPE.value)
      }
      fun requestBattery1Percentage(){
          bluetoothController.requestReadValues(ReadRequestCodes.BATTERY1_PERCENTAGE.value)
      }
      fun requestBattery2Percentage(){
          bluetoothController.requestReadValues(ReadRequestCodes.BATTERY2_PERCENTAGE.value)
      }
      fun requestHomePos(){
          bluetoothController.requestReadValues(ReadRequestCodes.HOME_POSITION.value)
      }
      fun requestBypassPos(){
          bluetoothController.requestReadValues(ReadRequestCodes.BYPASS_POSITION.value)
      }
      fun requestIsolationPos(){
          bluetoothController.requestReadValues(ReadRequestCodes.ISOLATION_POSITION.value)
      }
      fun requestHcPos(){
          bluetoothController.requestReadValues(ReadRequestCodes.HC_POSITION.value)
      }
  </code></pre>
  <p>Each fragment or activity in the app has a viewmodel, viewmodelfactory, and a repository. Let me describe the flow of things:</p>
  <ol>
  <li>We connect to a device via Bluetooth</li>
  <li>BluetoothController handles data exchange between the app and the device it is connected to</li>
  <li>Data is store din the DataStore</li>
  <li>UI(Fragment or activity) writes or request to read certain data</li>
  <li>ViewModel of every UI requests the data through the corresponding repository</li>
  <li>Repository of a particular fragment gets data from the DataStore</li>
  <li>And so on depending on whether we want to request data from the device or write to it</li>
  </ol>
  <p>ALL of this is done via classical Bluetooth. Now I want to change that to BLE. I was following a guide and made small app(Let's call it <strong>prototype</strong>) that scans for BLE devices, connects to the selected device and displays its characteristics and their properties. I made an activity in the app at hand (the main app I want to change) that contains the part for scanning and connecting. From what I have seen there is usually a <strong>Connection Manager Class</strong> that manages the part related to connections and data transfer. I'm not sure about that one beyond some of these functions and values:</p>
  <pre><code>  private val operationQueue = ConcurrentLinkedQueue&lt;BleOperationType&gt;()
      private var pendingOperation : BleOperationType? = null      //Operations types found in the BleOperationType sealed class
      private var listeners: MutableSet&lt;WeakReference&lt;ConnectionEventListener&gt;&gt; = mutableSetOf()
  
      fun servicesOnDevice(device: BluetoothDevice): List&lt;BluetoothGattService&gt;? = deviceGattMap[device]?.services
      fun listenToBondStateChanges(context: Context) {
          context.applicationContext.registerReceiver(
              broadcastReceiver,
              IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED)
          )
      }
  
      fun registerListener(listener: ConnectionEventListener){
          if(listeners.map { it.get() }.contains(listener)){ return }
          listeners.add(WeakReference(listener))
          listeners = listeners.filter { it.get() != null }.toMutableSet()
          Log.d(&quot;RegisteredListener&quot;,&quot;Added listener $listener, ${listeners.size} listeners total&quot;)
      }
      fun unregisterListener(listener: ConnectionEventListener){
          // Removing elements while in a loop results in a java.util.ConcurrentModificationException
          var toRemove : WeakReference&lt;ConnectionEventListener&gt;? = null
          listeners.forEach{
              if (it.get() == listener){
                  toRemove = it
              }
          }
  
          toRemove?.let {
             listeners.remove(it)
              Log.d(&quot;UnregisteredListener&quot;,&quot;Removed listener ${it.get()}, ${listeners.size} listeners total&quot;)
          }
      }
  
  
      fun connect(device: BluetoothDevice, context: Context){
          if(device.isConnected()){
              Log.e(&quot;CheckConnection&quot;,&quot;${device.name} - ${device.address} is already connected&quot;)
          }
          else{
              enqueueOperation(Connect(device, context.applicationContext))
          }
      }
      fun terminateConnection(device: BluetoothDevice){
          if(device.isConnected())
              enqueueOperation(Disconnect(device))
          else{
              Log.e(&quot;CheckConnection&quot;,&quot;Not connected to ${device.name} - ${device.address}, cannot teardown connection&quot;)
              }
      }
      fun characteristicWrite(device: BluetoothDevice, characteristic: BluetoothGattCharacteristic, payload: ByteArray){
          val writeType = when {
  
              //This is is to make sure that a characteristic can be written to,
              // and whether it has a response or not
              characteristic.isWritable() -&gt; BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT
              characteristic.isWritableWithoutResponse() -&gt; {BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE}
              else -&gt; error(&quot;Characteristic ${characteristic.uuid} cannot be written to&quot;)
          }
          if(device.isConnected()){
              enqueueOperation(CharacteristicWrite(device, characteristic.uuid, writeType, payload))
          }else{
              Log.e(&quot;Check_Writable&quot;,&quot;Not connected to ${device.address}, cannot perform characteristic write&quot;)
              return
          }
  
  //        bluetoothGattRef?.let { gatt -&gt;
  //            characteristic.writeType = writeType
  //            characteristic.value = payload
  //            gatt.writeCharacteristic(characteristic)
  //        } ?: error(&quot;Not connected to a BLE device!&quot;)
      }
      fun characteristicRead(device: BluetoothDevice, characteristic: BluetoothGattCharacteristic){
           if(device.isConnected() &amp;&amp; characteristic.isReadable()){
               enqueueOperation(CharacteristicRead(device, characteristic.uuid))
           }else if(!characteristic.isReadable()){
               Log.e(&quot;Check_Readable&quot;, &quot;Attempting to read ${characteristic.uuid} is not readable&quot;)
           }else if(!device.isConnected()){
               Log.e(&quot;Check_Connected&quot;,&quot;Not connected to ${device.address}, cannot perform characteristic read&quot;)
           }
      }
      fun writeDescriptor(device: BluetoothDevice, descriptor:BluetoothGattDescriptor, payload: ByteArray){
           if(device.isConnected() &amp;&amp; (descriptor.isWritable() || descriptor.isCccd())){
               enqueueOperation(DescriptorWrite(device, descriptor.uuid, payload))
           } else if (!device.isConnected()){
             Log.e(&quot;Check_Descrip_Connected&quot;,&quot;Not connected to ${device.address}, cannot perform descriptor write&quot;)
           } else if (!descriptor.isWritable() &amp;&amp; !descriptor.isCccd()){
             Log.e(&quot;Check_Descrip_Writable&quot;,&quot;Descriptor ${descriptor.uuid} cannot be written to&quot;)
           }
  //        bluetoothGattRef?.let { gatt -&gt;
  //            descriptor.value = payload
  //            gatt.writeDescriptor(descriptor)
  //        } ?: error(&quot;Not connected to a BLE device!&quot;)
      }
      fun readDescriptor(device: BluetoothDevice, descriptor: BluetoothGattDescriptor){
          if (device.isConnected() &amp;&amp; descriptor.isReadable()) {
              enqueueOperation(DescriptorRead(device,descriptor.uuid))
          } else if (!descriptor.isReadable()) {
              Log.e(&quot;Check_Descrip_Readable&quot;,&quot;Attempting to read ${descriptor.uuid} that isn't readable!&quot;)
          } else if (!device.isConnected()) {
              Log.e(&quot;Check_Descrip_Connected&quot;,&quot;Not connected to ${device.address}, cannot perform descriptor read&quot;)
          }
      }
  
      fun enableNotifications(device: BluetoothDevice, characteristic: BluetoothGattCharacteristic) {
          if (device.isConnected() &amp;&amp;
              (characteristic.isIndicatable() || characteristic.isNotifiable())
          ) {
              enqueueOperation(EnableNotifications(device, characteristic.uuid))
          } else if (!device.isConnected()) {
              Log.e(&quot;Error&quot;,&quot;Not connected to ${device.address}, cannot enable notifications&quot;)
          } else if (!characteristic.isIndicatable() &amp;&amp; !characteristic.isNotifiable()) {
              Log.e(&quot;Error&quot;,&quot;Characteristic ${characteristic.uuid} doesn't support notifications/indications&quot;)
          }
      }
  
      fun disableNotifications(device: BluetoothDevice, characteristic: BluetoothGattCharacteristic) {
          if (device.isConnected() &amp;&amp;
              (characteristic.isIndicatable() || characteristic.isNotifiable())
          ) {
              enqueueOperation(DisableNotifications(device, characteristic.uuid))
          } else if (!device.isConnected()) {
              Log.e(&quot;Error&quot;,&quot;Not connected to ${device.address}, cannot disable notifications&quot;)
          } else if (!characteristic.isIndicatable() &amp;&amp; !characteristic.isNotifiable()) {
              Log.e(&quot;Error&quot;,&quot;Characteristic ${characteristic.uuid} doesn't support notifications/indications&quot;)
          }
      }
  </code></pre>
  <p>It's actually an Object since I'll only instantiate the ConnectionManager once. Now all this was in my prototype app just for building the skeleton for the BLE features that would be integrated into my Main app.</p>
  <p>This is what I have added to my Main app so far regarding BLE integration:</p>
  <pre><code>  class ScanForDevices : AppCompatActivity() {
  
      private val bluetoothAdapter: BluetoothAdapter by lazy {
          val bluetoothManager = getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager
          bluetoothManager.adapter
      }
  
      private val bleScanner by lazy {
          bluetoothAdapter.bluetoothLeScanner
      }
  
      private val scanSettings = ScanSettings.Builder()
          .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
          .build()
  
      //Check whether the app is scanning or not
      private var isScanning = false
          set(value) {
              field = value
              runOnUiThread {
                  if(value) binding.scanBtn.text = &quot;Stop Scanning&quot; else binding.scanBtn.text = &quot;Start Scanning&quot;
              }
          }
  
      private val scanResults = mutableListOf&lt;ScanResult&gt;()
      private val scanResultAdapter: ScanResultAdapter by lazy {
          ScanResultAdapter(scanResults) { result -&gt;
              // User tapped on a scan result
              if(isScanning){
                  stopBleScan()
              }
              with(result.device){
                  Log.w(&quot;ScanResultAdapter&quot;, &quot;Connecting to $address&quot;)
                  Toast.makeText(this@ScanForDevices,&quot;Connecting to $address&quot;,Toast.LENGTH_SHORT).show()
                  connectGatt(this@ScanForDevices, false, gattCallback)
                  //////////////////////////////////////////////////////////////////////
  //                ConnectionManager.connect(this, this@ScanForDevices )
              }
          }
      }
  
      //To check that the permission is granted
      //It is only needed when performing a BLE scan
      private val isLocationPermissionGranted
          get() = hasPermission(android.Manifest.permission.ACCESS_FINE_LOCATION)
  
      private lateinit var bluetoothGattRef : BluetoothGatt
  
  
      override fun onCreate(savedInstanceState: Bundle?) {
          super.onCreate(savedInstanceState)
          binding = ActivityScanForDevicesBinding.inflate(layoutInflater)
          val view = binding.root
          setContentView(view)
  
  
          //Check for Bluetooth availability
          if(bluetoothAdapter == null){
              Log.w(&quot;BluetoothSupport&quot;,&quot;Device does not support Bluetooth&quot;)
          }else{
              Log.i(&quot;BluetoothSupport&quot;,&quot;Device supports Bluetooth&quot;)
          }
  
          binding.scanBtn.setOnClickListener {
              if(isScanning) stopBleScan() else startBleScan()
          }
          initRecyclerView()
  
      }
  
      override fun onResume() {
          super.onResume()
          if(!bluetoothAdapter.isEnabled){
              promptEnableBluetooth()
          }
      }
      override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
          super.onActivityResult(requestCode, resultCode, data)
          when (requestCode) {
              ENABLE_BLUETOOTH_REQUEST_CODE -&gt; {
                  if (resultCode != Activity.RESULT_OK) {
                      promptEnableBluetooth()
                  }
              }
          }
      }
      override fun onRequestPermissionsResult(
          requestCode: Int,
          permissions: Array&lt;out String&gt;,
          grantResults: IntArray
      ) {
          super.onRequestPermissionsResult(requestCode, permissions, grantResults)
          when (requestCode) {
              LOCATION_PERMISSION_REQUEST_CODE -&gt; {
                  if (grantResults.firstOrNull() == PackageManager.PERMISSION_DENIED) {
                      requestLocationPermission()
                  } else {
                      startBleScan()
                  }
              }
          }
      }
  
  
      private fun promptEnableBluetooth() {
          if (!bluetoothAdapter.isEnabled) {
              val enableBtIntent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
              startActivityForResult(enableBtIntent, ENABLE_BLUETOOTH_REQUEST_CODE)
          }
      }
      //Perform BLE scan after receiving permission to do so
      private fun startBleScan() {
          if (Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.M &amp;&amp; !isLocationPermissionGranted) {
              requestLocationPermission()
          } else { /* TODO: Actually perform scan */
              scanResults.clear()
              scanResultAdapter.notifyDataSetChanged()
              bleScanner.startScan(null, scanSettings, scanCallback)
              isScanning = true //Check that the app is scanning
          }
      }
      //Stop BLE scan after the corresponding button is clicked
      private fun stopBleScan(){
          bleScanner.stopScan(scanCallback)
          isScanning = false
      }
      //request location permission
      private fun requestLocationPermission() {
          if (isLocationPermissionGranted) {
              return
          }
          runOnUiThread {
              //Using &quot;org.jetbrains.anko:anko:0.10.8&quot;
              alert {
                  title = &quot;Location permission required&quot;
                  message = &quot;Starting from Android M (6.0), the system requires apps to be granted &quot; +
                          &quot;location access in order to scan for BLE devices.&quot;
                  isCancelable = false
                  positiveButton(android.R.string.ok) {
                      requestPermission(
                          android.Manifest.permission.ACCESS_FINE_LOCATION,
                          LOCATION_PERMISSION_REQUEST_CODE
                      )
                  }
              }.show()
          }
      }
      //For scan results
      private fun initRecyclerView(){
          binding.scanResultsRecyclerView.apply {
              adapter = scanResultAdapter
  //            val topSpacingDecoration = TopSpacingItemDecoration(30)
  //            addItemDecoration(topSpacingDecoration)
              layoutManager = LinearLayoutManager(
                  this@ScanForDevices,
                  RecyclerView.VERTICAL,
                  false
              )
              isNestedScrollingEnabled = false
          }
  
          val animator = binding.scanResultsRecyclerView.itemAnimator
          if(animator is SimpleItemAnimator) {
              animator.supportsChangeAnimations = false
          }
      }
  
  
  
      /**********************/
      /**CALLBACK FUNCTIONS**/
      /*********************/
  
      /** Since we didn't explicitly specify CALLBACK_TYPE_FIRST_MATCH as the callback type under our ScanSettings,
       * our onScanResult callback is flooded by ScanResults belonging to the same set of devices,
       * but with updated signal strength (RSSI) readings. In order to keep the UI up to date with the latest RSSI readings,
       * we first check to see if our scanResults List already has a scan result whose MAC address is identical to the new incoming ScanResult.
       * If so, we replace the older entry with the newer one. In the event that this is a new scan result,
       * we’ll add it to our scanResults List. For both cases,
       * we’ll inform our scanResultAdapter of the updated item so that our RecyclerView can be updated accordingly.**/
      private val scanCallback = object : ScanCallback() {
          override fun onScanResult(callbackType: Int, result: ScanResult) {
              val indexQuery = scanResults.indexOfFirst { it.device.address == result.device.address }
              if (indexQuery != -1) { // A scan result already exists with the same address
                  scanResults[indexQuery] = result
  //                serviceUUIDsList = getServiceUUIDsList(result)!!
  //                Log.d(&quot;Service&quot;,&quot;&quot;+ serviceUUIDsList+&quot;\n&quot;)
                  Log.d(&quot;DeviceName&quot;,&quot;&quot;+result.device.name)
                  scanResultAdapter.notifyItemChanged(indexQuery)
              } else {
                  with(result.device) {
                      Log.i(&quot;ScanCallback&quot;, &quot;Found BLE device! Name: ${name ?: &quot;Unnamed&quot;}, address: $address&quot;)
                  }
                  scanResults.add(result)
                  scanResultAdapter.notifyItemInserted(scanResults.size - 1)
              }
          }
  
          override fun onScanFailed(errorCode: Int) {
              Log.e(&quot;ScanCallback&quot;, &quot;onScanFailed: code $errorCode&quot;)
          }
      }
  
      /**we want to stop the BLE scan if it’s ongoing,
       * and we call connectGatt() on the relevant ScanResult’s BluetoothDevice handle,
       * passing in a BluetoothGattCallback object that is defined as: **/
  
      private val gattCallback = object : BluetoothGattCallback() {
          override fun onConnectionStateChange(gatt: BluetoothGatt, status: Int, newState: Int) {
              val deviceAddress = gatt.device.address
  
              if (status == BluetoothGatt.GATT_SUCCESS) {
                  if (newState == BluetoothProfile.STATE_CONNECTED) {
                      Log.w(&quot;BluetoothGattCallback&quot;, &quot;Successfully connected to $deviceAddress&quot;)
                      Handler(Looper.getMainLooper()).post {
                          Toast.makeText(this@ScanForDevices, &quot;Successfully connected to $deviceAddress&quot;, Toast.LENGTH_SHORT).show()
                      }
                      // TODO: Store a reference to BluetoothGatt
                      bluetoothGattRef = gatt
                      Log.d(&quot;ConnectedDevice&quot;,&quot;&quot;)
  
                      runOnUiThread {
                          bluetoothGattRef?.discoverServices()
                      }
                  } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
                      Log.w(&quot;BluetoothGattCallback&quot;, &quot;Successfully disconnected from $deviceAddress&quot;)
                      gatt.close()
                  }
              } else {
                  Log.w(&quot;BluetoothGattCallback&quot;, &quot;Error $status encountered for $deviceAddress! Disconnecting...&quot;)
                  gatt.close()
              }
          }
  
          //On the discovery of the BLE device's services
          //We display a log message of the number of services and the device's address, then print
          //the GATT table in a recycler view beneath the one of the scanned devices -----&gt; services and characteristics available on a BLE device.
          override fun onServicesDiscovered(gatt: BluetoothGatt?, status: Int) {
  
              with(bluetoothGattRef) {
                  if (status == BluetoothGatt.GATT_SUCCESS) {
                      Log.d(
                          &quot;BluetoothGattCallback&quot;,
                          &quot;Discovered ${services.size} services for ${device.address}&quot;
                      )
                      printGattTable()
                  }
              }
  
          }
      }
  
  
  }
  </code></pre>
  <p>let's say I already connected to the desired device, how do I exchange data of the parameters in the fragments I mentioned whether it is something to be read from the device or written to the device but with BLE instead of classical Bluetooth?</p>
  <p>I am completely lost and don't know what to do. Any insight? Or even list me the things I should do or the path to be taken to make the necessary changes?</p>