Skip to main content
Use this API to listen for newly discovered Bluetooth devices during discovery. The callback triggers when new devices are found.

Parameters

PropertyTypeRequiredDescription
callbackFunctionYesCallback when devices are found

Callback Parameters

PropertyTypeDescription
devicesArrayArray of newly found devices

Device Object Properties

PropertyTypeDescription
deviceIdStringDevice identifier
nameStringDevice name (may be empty)
RSSINumberSignal strength (dBm)
advertisDataArrayBufferAdvertisement data

Code Example

Basic Usage

my.onBluetoothDeviceFound((res) => {
  res.devices.forEach(device => {
    console.log('Found:', device.name, device.deviceId);
  });
});

Build Device List

Page({
  data: {
    devices: []
  },

  onLoad() {
    my.openBluetoothAdapter({
      success: () => {
        this.setupDeviceListener();
        this.startScan();
      }
    });
  },

  setupDeviceListener() {
    my.onBluetoothDeviceFound((res) => {
      const { devices } = this.data;

      res.devices.forEach(newDevice => {
        const exists = devices.find(d => d.deviceId === newDevice.deviceId);
        if (!exists && newDevice.name) {
          devices.push(newDevice);
        }
      });

      this.setData({ devices });
    });
  },

  startScan() {
    my.startBluetoothDevicesDiscovery();
  },

  onUnload() {
    my.offBluetoothDeviceFound();
    my.closeBluetoothAdapter();
  }
});

Find Specific Device

Page({
  findDevice(targetName) {
    my.onBluetoothDeviceFound((res) => {
      const target = res.devices.find(d => d.name === targetName);

      if (target) {
        my.stopBluetoothDevicesDiscovery();
        my.offBluetoothDeviceFound();
        this.connectToDevice(target);
      }
    });

    my.startBluetoothDevicesDiscovery();
  },

  connectToDevice(device) {
    console.log('Connecting to:', device.name);
  }
});
Remember to call my.offBluetoothDeviceFound when done to stop receiving device updates.

my.offBluetoothDeviceFound

Stop listening

my.startBluetoothDevicesDiscovery

Start discovery