Skip to main content
Use this API to establish a connection to a Bluetooth Low Energy (BLE) device.

Parameters

PropertyTypeRequiredDescription
deviceIdStringYesDevice identifier from discovery
timeoutNumberNoConnection timeout in milliseconds
successFunctionNoCallback on success
failFunctionNoCallback on failure
completeFunctionNoCallback that always executes

Code Example

Basic Usage

my.connectBLEDevice({
  deviceId: 'XX:XX:XX:XX:XX:XX',
  success() {
    console.log('Connected to device');
  },
  fail(err) {
    console.error('Connection failed:', err);
  }
});

Connect with Timeout

my.connectBLEDevice({
  deviceId: 'XX:XX:XX:XX:XX:XX',
  timeout: 5000, // 5 second timeout
  success() {
    console.log('Connected');
  },
  fail(err) {
    if (err.error === 10012) {
      my.showToast({ content: 'Connection timeout', type: 'fail' });
    }
  }
});

Complete Connection Flow

Page({
  data: {
    connectedDevice: null
  },

  connectToDevice(device) {
    my.showLoading({ content: 'Connecting...' });

    my.connectBLEDevice({
      deviceId: device.deviceId,
      timeout: 10000,
      success: () => {
        my.hideLoading();
        this.setData({ connectedDevice: device });
        my.showToast({ content: `Connected to ${device.name}` });
        this.discoverServices(device.deviceId);
      },
      fail: (err) => {
        my.hideLoading();
        my.alert({
          title: 'Connection Failed',
          content: 'Could not connect to device. Please try again.'
        });
      }
    });
  },

  discoverServices(deviceId) {
    my.getBLEDeviceServices({
      deviceId: deviceId,
      success: (res) => {
        console.log('Services:', res.services);
      }
    });
  }
});

Error Codes

CodeDescription
10000Bluetooth adapter not initialized
10001Bluetooth not enabled
10012Connection timeout
10013Device not found
Ensure the device is in range and advertising before attempting to connect. Use discovery to verify the device is available.

my.disconnectBLEDevice

Disconnect from device

my.onBluetoothDeviceFound

Discover devices