Last active
May 7, 2024 07:57
-
-
Save jamesjmtaylor/77578aaed78ee02f475bbbbc85f88e65 to your computer and use it in GitHub Desktop.
Android Activity for Obtaining BLE Transmission Power
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class MainActivity : AppCompatActivity() { | |
var bluetoothAdapter : BluetoothAdapter? = null | |
var bluetoothScanner : BluetoothLeScanner? = null | |
override fun onCreate(savedInstanceState: Bundle?) { | |
super.onCreate(savedInstanceState) | |
setContentView(R.layout.activity_main) | |
rssiTextView = findViewById(R.id.rssiTextView) | |
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter() | |
bluetoothScanner = bluetoothAdapter?.getBluetoothLeScanner() | |
bluetoothScanner?.startScan(scanCallback); | |
} | |
/* | |
The scanResult is represented as an array of integers. | |
The first 2 bytes are the protocol | |
The 16 following bytes are the UUID | |
The 2 after that your major | |
The 2 after that your minor | |
The final bytes are your tx power / reference RSSI. | |
*/ | |
val scanCallback = object: ScanCallback(){ | |
@RequiresApi(Build.VERSION_CODES.O) | |
override fun onScanResult(callbackType: Int, result: ScanResult) { | |
//224 is the official bluetooth google company identifier. | |
val manufacturerSpecificData = result.scanRecord.getManufacturerSpecificData(224) | |
val rssi = result.rssi.toDouble() //The intensity of the received signal | |
val tx = result.txPower.toDouble() //The power of the broadcast (Available on Oreo only) | |
val distance = calculateDistance(tx,rssi) | |
} | |
} | |
fun calculateDistance(txPower: Double, rssi: Double): Double { | |
val ratio = rssi / txPower | |
if (rssi == 0.0) { // Cannot determine accuracy, return -1. | |
return -1.0 | |
} else if (ratio < 1.0) { //default ratio | |
return Math.pow(ratio, 10.0) | |
}//rssi is greater than transmission strength | |
return (0.89976) * Math.pow(ratio, 7.7095) + 0.111 | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment