Facts You Should Know About Bluetooth Classic and Bluetooth Low Energy

February 24, 2021 Publish By : EXPERT APP DEVS 9 min read Viewed By : 826
Bluetooth Classic and Bluetooth Low Energy
  • Nowadays everything becomes wireless and Bluetooth plays a big role in that wireless revolution. Bluetooth is a wireless technology for short-range data communication and transmission. Bluetooth provides a communication platform between a large range of smart devices. Bluetooth technology provides a short-range of audio communication to IoT and M2M communications. Bluetooth standards are developed by Bluetooth SIG. Launch and Update of the Bluetooth features and protection of trademarks, these all the functions are handled by Bluetooth SIG.
  • In this article, we will explain the difference between Bluetooth Classic and Bluetooth low energy(BLE) and also explain steps for implementation.

1) What is the Bluetooth Classic?     

  •  Bluetooth classic is most popular for pairing audio devices to mobile devices.
  •  Pairing two devices using Bluetooth classic is almost known by most people.

 so, we will discuss what happens behind the scenes.    

  • For example, we want to connect mobile and our headphones so basically most of the cases mobile is the client and headphone is a server. so first of all make both devices discoverable before initiating the connection. When the server device is ready for the connection then it will advertise to the client device. The client device is able to see all the server devices on the screen. Clients will connect with an interested server on the network between client and server it’s called a piconet. This process is mandatory for establishing the connection between two devices every time.
  • You can refer more about Bluetooth classic from here.

2) Bluetooth low energy [BLE]

  • Bluetooth Low Energy (BLE) is a low power consumption wireless communication technology, which is used over short distance communication. Some of the devices you used every day like a smartphone, smartwatch, fitness tracker, wireless headphones, etc are using BLE to create the best experience between your devices. The BLE is very similar to Bluetooth Classic's "client" and "server". However, for BLE, they are denoted as central (client) and peripheral (server).
  • Bluetooth Special Interest Group (SIG) defined new standards for Bluetooth. Which is focusing on reducing energy consumption and a seamless communication experience. Bluetooth low energy is used in a large range of fields like fitness, health, security, home automation, smart industry, and Internet of Things(IoT), etc.
  • Apple first adopted BLE for communication and interaction between two devices for iPhone 4s.
  • You can know more about Bluetooth low energy [ble] from here.

3) Bluetooth classic vs Bluetooth low energy

Specification

Bluetooth Classic

BLE

Network topology

Piconet, scatternet, and point-to-point

Point-to-point and Star

Frequency channels

79

40

Current consumption

<30 mA

<15 mA

Min. time to send data

100 ms

3ms

Security

56/128-bit and application layer user-defined

128-bit AES and application layer user-defined

Latency

100 ms

6 ms

Data Transfer Rate

2-3 Mbps

200 kbps

Frequency (GHz)

4

4

Active slaves

Undefined and implementation-dependent

Up to 7

Distance range

100 m

>100 m

Power consumption

1 W

0.01 to 0.5 W

4) Android Implementation  

Step: 1

Requesting Android permissions and Android features

Permissions :

 

<manifest xmlns:android="http://schemas.android.com/apk/res/android"

  package="com.example">

 

  <uses-permission android:name="android.permission.BLUETOOTH" />

  <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

 

  <application ... />

 

</manifest>

 

Features :

 

<uses-feature android:name="android.hardware.bluetooth"/>

Step : 2

Enable bluetooth adapter

 

val btStateReceiver: BroadcastReceiver = object : BroadcastReceiver() {

      override fun onReceive(context: Context, intent: Intent?) {

          onBtEnabledAction.run()

          context.unregisterReceiver(this)

      }

  }

  context.registerReceiver(bluetoothStateReceiver, IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED))

  if (!BluetoothAdapter.getDefaultAdapter().enable()) {

      onBtEnabledAction.run()

      context.unregisterReceiver(bluetoothStateReceiver)

  }

}

Step 3:

Enable Location service

Add below dependency and follow the below code for location service.

 
 
 

private var doOnLocationEnabled: ((Boolean) -> Unit)? = null

      val locationManager = getSystemService(Context.LOCATION_SERVICE) as LocationManager

      return locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER) or

              locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)

  }


 

private fun enableLocation(onLocationChanged: (Boolean) -> Unit) {

  if (isLocationEnabled) {

      doOnLocationEnabled?.invoke(true)

      return

  }


 

  val googleApiClient = GoogleApiClient.Builder(this)

      .addApi(LocationServices.API)

      .build()

      .apply {

          connect()

      }


 

  val locationSettingsRequest = LocationSettingsRequest.Builder()

      .addLocationRequest(

          LocationRequest().apply {

              priority = LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY

          }

      )

      .build()


 

  LocationServices.SettingsApi

      .checkLocationSettings(googleApiClient, locationSettingsRequest)

      .setResultCallback { locationSettingsResult ->

          doOnLocationEnabled = onLocationChanged

          try {

              locationSettingsResult.status.startResolutionForResult(this, ENABLE_LOCATION_REQUEST_CODE)

          } catch (e: SendIntentException) {

              doOnLocationEnabled?.invoke(false)

              doOnLocationEnabled = null

          }

      }

}


 

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {

  super.onActivityResult(requestCode, resultCode, data)

  if (requestCode == ENABLE_LOCATION_REQUEST_CODE) {

      doOnLocationEnabled?.invoke(isLocationEnabled)

      doOnLocationEnabled = null

  }

}

Step 4:

Get Bluetooth device object


 

val device: BluetoothDevice = BluetoothAdapter.getDefaultAdapter().getRemoteDevice("00:11:22:33:AA:BB")

Step 5:

Discover Bluetooth device

Classic bluetooth device discovery

private fun scanDevices(

    context: Context,

    doOnDeviceFound: (BluetoothDevice?) -> Unit,

    doOnDiscoveryFinished: () -> Unit

) {

    val scanningBroadcastReceiver = object : BroadcastReceiver() {

        override fun onReceive(context: Context, intent: Intent) {

            when (intent.action) {

                BluetoothDevice.ACTION_FOUND -> {

                    val device = intent.getParcelableExtra<BluetoothDevice>(BluetoothDevice.EXTRA_DEVICE)

                    doOnDeviceFound(device)

                }

                BluetoothAdapter.ACTION_DISCOVERY_FINISHED -> {

                    context.unregisterReceiver(this)

                    doOnDiscoveryFinished()

                }

            }

        }

    }

    val scanningIntentFilter = IntentFilter().apply {

        addAction(BluetoothDevice.ACTION_FOUND)

        addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED)

    }    context.registerReceiver(scanningBroadcastReceiver, scanningIntentFilter)

    BluetoothAdapter.getDefaultAdapter().startDiscovery()

}

BLE device discovery

 

private var leScanCallback: ScanCallback? = null

 

private fun startLEScan(doOnDeviceFound: (BluetoothDevice?) -> Unit) {

    leScanCallback = object : ScanCallback() {

        override fun onScanResult(callbackType: Int, result: ScanResult) {

            doOnDeviceFound(result.device)

        }

    }

    BluetoothAdapter.getDefaultAdapter().bluetoothLeScanner.startScan(leScanCallback)

}

 

private fun stopLEScan() {

    BluetoothAdapter.getDefaultAdapter().bluetoothLeScanner.stopScan(leScanCallback)

    leScanCallback = null

}

Step 6:

Connecting Bluetooth devices using RFCOMM socket :

Create an RFCOMM socket using the below code: 

 

private fun BluetoothDevice.createSocket(uuid: UUID): BluetoothSocket {

    return createInsecureRfcommSocketToServiceRecord(uuid)

}

 

RFCOMM pairing devices :

 

private val BluetoothDevice.isDeviceBonded get() = bondState == BluetoothDevice.BOND_BONDED

 

Data transfer using RFCOMM :

 

fun BluetoothSocket.setSocketAndStartConnector() {

    val socketThread: Thread = object : Thread() {

        override fun run() {

            try {

                BluetoothAdapter.getDefaultAdapter().cancelDiscovery()

                if (!isConnected) connect()

 

                inputStream

                // read the stream here

 

            } catch (e: Exception) {

                error(e)

            } finally {

                if (inputStream != null) {

                    try {

                        inputStream.close()

                    } catch (e: IOException) {

                        error(e)

                    }

                }

            }

        }

    }

    socketThread.start()

}

 

  • You can refer to android official documentation for implement BLE in Android.
  • You can refer to android official documentation for implement Bluetooth classic in Android.

Need a consultation?

Drop us a line! We are here to answer your questions 24/7.