chrvadala / node-ble

Bluetooth Low Energy (BLE) library written with pure Node.js (no bindings) - baked by Bluez via DBus
https://www.npmjs.com/package/node-ble
MIT License
310 stars 45 forks source link

How to get list of devices?? #57

Open DrCWO opened 1 year ago

DrCWO commented 1 year ago

Hi, first thank you for making node-ble. Hope it will help me connecting to my devices 👍 I have a question but maybe it is also an issue, I don't know.

I like to start discovery and get the devices discovered so I can decide to which one I like to connect. In my example below I use myAdapter.devices()but is only returns an empty object. Any ideas?

I have bluetoothctlopen at the same time and see that discovery starts. I also see the device announcing its UUID after some time but my code shows nothing.

Here my code:

'use strict';

async function main() {
    const { createBluetooth } = require('node-ble');
    const { bluetooth, destroy } = createBluetooth();
    var myAdapter = await bluetooth.defaultAdapter();

    console.log(myAdapter.adapter);

    if (! await myAdapter.isDiscovering()) {
        console.log ("startDiscovery");
        myAdapter.startDiscovery();
    }

    await myAdapter.isDiscovering();
    console.log ('isDiscovering');

    showDevices();

    function showDevices () {
        console.log (JSON.stringify(myAdapter.devices(), null,2));
        setTimeout (showDevices, 2000);
    }
}

main();

I can connect to one of my devices using its UUID (see working code blow). But before being able to do so I first have to find out the UUID which I expected to get with myAdapter.devices().

    const device = await adapter.waitDevice('70:BC:10:86:85:C5');
    await device.connect();

Support would be appreciated. Best DrCWO

DrCWO commented 1 year ago

Hi again, found the solution by myself. Here the code that works...

'use strict';

async function main() {

    const { createBluetooth } = require('node-ble');
    const { bluetooth, destroy } = createBluetooth();
    var myAdapter = await bluetooth.defaultAdapter();

    console.log(myAdapter.adapter);

    if (! await myAdapter.isDiscovering()) {
        console.log ("startDiscovery");
        myAdapter.startDiscovery();
    }

    await myAdapter.isDiscovering();
    console.log ('isDiscovering');

    showDevices();

    async function showDevices () {
        console.log ('------------------------------');
        var myDevices = await myAdapter.devices();
        console.log (myDevices);
        setTimeout (showDevices, 2000);
    }
}

main();