weliem / blessed-bluez

BLE library using Java and Bluez
MIT License
82 stars 25 forks source link

Check if Bluetooth Adapter available #21

Closed L4m4L closed 1 year ago

L4m4L commented 1 year ago

Hello,

I was wondering if there is an easy way in blessed-bluez to check if there is a Bluetooth Adapter available prior to initializing a BluetoothCentralManager? I am running into a NullPointerException "no bluez adapter provided", which I would like to check for before trying to create the BluetoothCentralManager.

I have tried checking a BluezAdapter prior to creating the BluetoothCentralManager, but regardless on if I have the adapter enabled or not it is always a null value.

Any assistance would be greatly appreciated.

L4m4L commented 1 year ago

I figured it out by using the DBus library to see if a "getRemoteObject" request to the org.bluez bus and /org/bluez/hci0 object path returns a string containing the bluez adapter. Not sure if this is the correct way to do this, but it worked for me. Example code below (very happy for suggestions/improvements!)

import org.freedesktop.dbus.connections.impl.DBusConnection;
import org.freedesktop.dbus.exceptions.DBusException;
import org.freedesktop.dbus.interfaces.Introspectable;

try {
    // Creates a new DBus connection, attempts to get a remote object of org.bluez
    DBusConnection dbus = DBusConnection.getConnection(DBusConnection.DEFAULT_SYSTEM_BUS_ADDRESS);
    // This returns an introspectable string (???) which defines how the bluez dbus connection can be used
    // if it has no method definitions, then likely there is no bluetooth module connected!
    String introspect = dbus.getRemoteObject("org.bluez", "/org/bluez/hci0", Introspectable.class).Introspect();

    // Check if introspect string contains the bluez Adapter
    if (introspect.contains("org.bluez.Adapter1")) {
        System.out.println("Adapter Available! :)");
        // Do something !
    }
    else {
        System.out.println("Adapter Not Available! :(");
        // Do something else !
    }
} catch (DBusException e1) {
    // TODO Auto-generated catch block
    e1.printStackTrace();
}
L4m4L commented 1 year ago

Solved as per last comment