SimpleBLE
Recipes

Scan for Peripherals

Discover nearby BLE peripherals with SimpleBLE by scanning for a bounded time, then read the results and keep the connectable ones, in each binding.

Scanning is the first real interaction with the Bluetooth stack. A scan listens for advertisements, reports devices as they appear, and stores the latest result set so your app can choose what to connect to.

Flow

  1. Check that Bluetooth is enabled and permissions are available.
  2. Get the available adapters.
  3. Pick an adapter.
  4. Register scan callbacks or event streams when your binding supports them.
  5. Scan for a bounded amount of time.
  6. Read the scan results and filter for connectable peripherals.

Core scan call

auto adapters = SimpleBLE::Adapter::get_adapters();
auto adapter = adapters.front();

adapter.set_callback_on_scan_found([](SimpleBLE::Peripheral peripheral) {
    std::cout << "Found " << peripheral.identifier()
              << " [" << peripheral.address() << "]" << std::endl;
});

adapter.scan_for(5000);

for (auto& peripheral : adapter.scan_get_results()) {
    if (peripheral.is_connectable()) {
        std::cout << peripheral.identifier() << " is connectable." << std::endl;
    }
}
#include <stdio.h>
#include <stdlib.h>
#include <simplecble/simplecble.h>

int main(void) {
    simpleble_error_t* error = NULL;
    simpleble_adapter_list_t adapters = NULL;
    simpleble_adapter_get_adapters(&adapters, &error);
    simpleble_adapter_t adapter = error ? NULL : simpleble_adapter_list_get(adapters, 0, &error);
    simpleble_adapter_list_release(adapters);
    if (error) {
        fprintf(stderr, "%s\n", simpleble_error_message(error));
        simpleble_error_release(&error);
        return EXIT_FAILURE;
    }

    simpleble_peripheral_list_t results = NULL;
    simpleble_adapter_scan_for(adapter, 5000, &error);
    if (!error) {
        size_t count = simpleble_adapter_scan_get_results(adapter, &results, &error);
        for (size_t i = 0; i < count && !error; i++) {
            simpleble_peripheral_t peripheral = simpleble_peripheral_list_get(results, i, &error);
            if (error) break;

            char* identifier = simpleble_peripheral_identifier(peripheral, &error);
            if (!error) printf("Found: %s\n", identifier);
            simpleble_free(identifier);
            simpleble_peripheral_release_handle(peripheral);
        }
    }

    int result = error ? EXIT_FAILURE : EXIT_SUCCESS;
    if (error) fprintf(stderr, "%s\n", simpleble_error_message(error));
    simpleble_error_release(&error);
    simpleble_peripheral_list_release(results);
    simpleble_adapter_release_handle(adapter);
    return result;
}
adapter = simplepyble.Adapter.get_adapters()[0]

adapter.set_callback_on_scan_found(
    lambda peripheral: print(f"Found {peripheral.identifier()} [{peripheral.address()}]")
)

adapter.scan_for(5000)

for peripheral in adapter.scan_get_results():
    if peripheral.is_connectable():
        print(f"{peripheral.identifier()} is connectable")
Adapter adapter = Adapter.getAdapters().get(0);

adapter.setEventListener(new Adapter.EventListener() {
    @Override
    public void onScanFound(Peripheral peripheral) {
        System.out.println("Found " + peripheral.getIdentifier() + " [" + peripheral.getAddress() + "]");
    }
});

adapter.scanFor(5000);

for (Peripheral peripheral : adapter.scanGetResults()) {
    if (peripheral.isConnectable()) {
        System.out.println(peripheral.getIdentifier() + " is connectable");
    }
}
let mut adapters = simplersble::Adapter::get_adapters().unwrap();
let adapter = adapters.remove(0);

adapter.scan_for(std::time::Duration::from_secs(5)).unwrap();

for peripheral in adapter.scan_get_results().unwrap() {
    println!(
        "{} [{}]",
        peripheral.identifier().unwrap(),
        peripheral.address().unwrap()
    );
}
const [adapter] = await Adapter.getAdapters();

adapter.on('scanFound', peripheral => console.log(`Found ${peripheral.identifier()} [${peripheral.address()}]`));

await adapter.scanFor(5000);

for (const peripheral of adapter.scanGetResults()) {
  if (peripheral.isConnectable()) console.log(`${peripheral.identifier()} is connectable`);
}
const [adapter] = await Adapter.getAdapters();

adapter.on('scanFound', peripheral => console.log(`Found ${peripheral.identifier()} [${peripheral.address()}]`));

await adapter.scanFor(5000);

for (const peripheral of adapter.scanGetResults()) {
  if (peripheral.isConnectable()) console.log(`${peripheral.identifier()} is connectable`);
}
val adapter = Adapter.getAdapters().first()

coroutineScope {
    val found = launch(start = CoroutineStart.UNDISPATCHED) {
        adapter.onScanFound.collect { peripheral ->
            println("Found ${peripheral.identifier} [${peripheral.address}]")
        }
    }
    adapter.scanFor(5000)
    found.cancel()
}

for (peripheral in adapter.scanGetResults()) {
    if (peripheral.isConnectable) println("${peripheral.identifier} is connectable")
}
let adapter = try Adapter.getAdapters().first!

let found = adapter.onScanFound
let printer = Task {
    for await peripheral in found {
        print("Found \(peripheral.identifier) [\(peripheral.address)]")
    }
}
try await adapter.scanFor(timeoutMs: 5000)
printer.cancel()

for peripheral in try adapter.scanGetResults() where peripheral.isConnectable {
    print("\(peripheral.identifier) is connectable")
}
final adapter = (await Adapter.getAdapters()).first;

adapter.onScanFound.listen((peripheral) => print('Found ${peripheral.identifier} [${peripheral.address}]'));

await adapter.scanFor(const Duration(seconds: 5));

for (final peripheral in adapter.scanGetResults()) {
  if (peripheral.isConnectable) print('${peripheral.identifier} is connectable');
}
procedure TScanPrinter.ScanFound(Sender: TBleAdapter; Peripheral: TBlePeripheral);
begin
  WriteLn('Found ', Peripheral.Identifier, ' [', Peripheral.Address, ']');
end;

Adapters := TBleAdapter.GetAdapters;
Adapter := Adapters[0];

Adapter.OnScanFound := Printer.ScanFound;

Adapter.ScanFor(5000);

for Peripheral in Adapter.ScanGetResults do
  if Peripheral.IsConnectable then
    WriteLn(Peripheral.Identifier, ' is connectable.');
val adapter = Adapter.getAdapters().first()

coroutineScope {
    val events = launch {
        adapter.onScanFound.collect { peripheral ->
            Log.d("SimpleBLE", "Found ${peripheral.identifier} [${peripheral.address}]")
        }
    }

    try {
        adapter.scanFor(5000)
    } finally {
        events.cancelAndJoin()
    }

    val results = adapter.scanGetResults()
}

Practical notes

  • Scans should be bounded. Use scan_for / scanFor when you want a simple blocking scan with predictable duration.
  • Event callbacks are useful for live UI updates, but the final result list is usually the easiest thing to feed into a selection flow.
  • macOS and iOS expose per-host UUIDs instead of hardware MAC addresses.
  • On Linux, make sure the process has access to BlueZ over DBus.
  • On Android, request BLUETOOTH_SCAN and BLUETOOTH_CONNECT before scanning.

For a complete first scan program, see Quickstart. To advertise from this host instead, see Advertise.

On this page