Code is able to discover bluetooth devices but cant connect to the balance board

This commit is contained in:
SebasKoedam
2024-05-16 11:30:10 +02:00
parent a4a01ae9ef
commit 01498b5643
6 changed files with 779 additions and 18 deletions

View File

@@ -1,17 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="deploymentTargetDropDown">
<targetSelectedWithDropDown>
<Target>
<type value="QUICK_BOOT_TARGET" />
<deviceKey>
<Key>
<type value="VIRTUAL_DEVICE_PATH" />
<value value="C:\Users\sebas\.android\avd\Pepper_1.9_API_29.avd" />
</Key>
</deviceKey>
</Target>
</targetSelectedWithDropDown>
<timeTargetWasSelectedWithDropDown value="2024-04-26T10:10:48.222593700Z" />
</component>
</project>

View File

@@ -7,6 +7,7 @@
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<application
android:allowBackup="true"

View File

@@ -0,0 +1,133 @@
package com.example.fitbot.bluetooth;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.Context;
import android.util.Log;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.UUID;
public class BluetoothManager {
private BluetoothAdapter bluetoothAdapter;
private Context context;
public BluetoothManager(Context context) {
this.context = context;
this.bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
}
public boolean isBluetoothSupported() {
return bluetoothAdapter != null;
}
public boolean isBluetoothEnabled() {
return bluetoothAdapter.isEnabled();
}
public void startDiscovery() {
if (!isBluetoothEnabled()) {
Log.e("BluetoothManager", "Bluetooth is not enabled");
return;
}
if (bluetoothAdapter.isDiscovering()) {
bluetoothAdapter.cancelDiscovery();
Log.d("BluetoothManager", "Cancelling current discovery process...");
}
IntentFilter filter = new IntentFilter();
filter.addAction(BluetoothDevice.ACTION_FOUND);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
context.registerReceiver(receiver, filter);
bluetoothAdapter.startDiscovery();
Log.d("BluetoothManager", "Starting discovery process...");
}
public final BroadcastReceiver receiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if (device.getName() != null && device.getName().contains("Nintendo RVL-WBC-01")) {
Log.d("BluetoothManager", "Wii Balance Board found: " + device.getName() + " [" + device.getAddress() + "]");
connectToDevice(device);
}
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
context.unregisterReceiver(this);
Log.d("BluetoothManager", "Discovery finished.");
}
}
};
public void connectToDevice(BluetoothDevice device) {
new Thread(() -> {
BluetoothSocket socket = null;
final int MAX_RETRIES = 3;
final long RETRY_DELAY_MS = 1000;
boolean isConnected = false;
for (int attempt = 1; attempt <= MAX_RETRIES; attempt++) {
try {
UUID SPP_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
socket = device.createRfcommSocketToServiceRecord(SPP_UUID);
bluetoothAdapter.cancelDiscovery();
byte[] pinBytes = getPinBytes(device.getAddress());
try {
Method setPinMethod = device.getClass().getDeclaredMethod("setPin", byte[].class);
setPinMethod.invoke(device, pinBytes);
Log.d("BluetoothManager", "PIN set successfully");
} catch (Exception e) {
Log.e("BluetoothManager", "Failed to set PIN", e);
}
socket.connect();
Log.d("BluetoothManager", "Connected to Wii Balance Board");
isConnected = true;
break;
} catch (IOException e) {
Log.e("BluetoothManager", "Connection attempt " + attempt + " failed", e);
if (attempt < MAX_RETRIES) {
try {
Thread.sleep(RETRY_DELAY_MS);
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
break;
}
}
} finally {
if (!isConnected && socket != null) {
try {
socket.close();
} catch (IOException ex) {
Log.e("BluetoothManager", "Could not close the client socket", ex);
}
}
}
}
if (!isConnected) {
Log.e("BluetoothManager", "All connection attempts failed.");
}
}).start();
}
private byte[] getPinBytes(String address) {
String[] addrParts = address.split(":");
byte[] pin = new byte[addrParts.length];
for (int i = 0; i < addrParts.length; i++) {
pin[i] = (byte) Integer.parseInt(addrParts[addrParts.length - 1 - i], 16);
}
Log.i("BluetoothManager", "PIN: " + pin);
return pin;
}
}

View File

@@ -3,16 +3,24 @@ package com.example.fitbot.ui.activities;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import com.example.fitbot.bluetooth.BluetoothManager;
import com.example.fitbot.R;
public class MainActivity extends AppCompatActivity {
private static final int REQUEST_LOCATION_PERMISSION = 1;
BluetoothManager bluetoothManager;
//Variables
DrawerLayout drawerLayout;
NavigationView navigationView;
@@ -24,6 +32,23 @@ public class MainActivity extends AppCompatActivity {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bluetoothManager = new BluetoothManager(this);
// Check if Bluetooth is supported and enabled
if (bluetoothManager.isBluetoothSupported() && bluetoothManager.isBluetoothEnabled()) {
// Check for location permission which is required for Bluetooth discovery on Android 6.0 and above
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_LOCATION_PERMISSION);
} else {
// Start Bluetooth discovery
bluetoothManager.startDiscovery();
}
}
setUpUi();
}
private void setUpUi() {
/*---Hooks---*/
drawerLayout = findViewById(R.id.drawer_layout);
navigationView = findViewById(R.id.nav_view);
@@ -50,4 +75,24 @@ public class MainActivity extends AppCompatActivity {
{super.onBackPressed();
}
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == REQUEST_LOCATION_PERMISSION && grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// Permission granted, start Bluetooth discovery
bluetoothManager.startDiscovery();
}
}
@Override
protected void onDestroy() {
super.onDestroy();
// Unregister the receiver to prevent memory leaks
try {
unregisterReceiver(bluetoothManager.receiver);
} catch (IllegalArgumentException e) {
// Handle case where receiver is not registered.
}
}
}