Todos os produtos
Search
Central de documentação

Mobile Platform as a Service:Lista de APIs Bluetooth

Última atualização: Jun 28, 2026

Lista todas as APIs Bluetooth disponíveis em miniapps mPaaS para gerenciamento de adaptador, descoberta de dispositivos, conexão BLE e operações de leitura e escrita de características.

Nota
  • As APIs Bluetooth têm suporte no mPaaS 10.1.60 e versões posteriores.

  • A depuração nas ferramentas de desenvolvedor não tem suporte atualmente. Use um dispositivo físico para chamar as APIs Bluetooth do miniapp.

my.openBluetoothAdapter

Inicializa o módulo Bluetooth do miniapp. Válido desde a chamada de my.openBluetoothAdapter até a chamada de my.closeBluetoothAdapter ou a destruição do miniapp. Nesse período, é possível chamar outras APIs Bluetooth e receber callbacks de eventos on.

Parâmetros de entrada

Nome

Tipo

Obrigatório

Descrição

autoClose

Boolean

Não

Define se o Bluetooth deve ser desconectado automaticamente ao sair da página. Padrão: true.

Importante

Este recurso tem suporte apenas no Android.

success

Function

Não

Chamado em caso de sucesso.

fail

Function

Não

Chamado em caso de falha.

complete

Function

Não

Chamado quando a chamada é concluída, independentemente do resultado.

Valor de retorno de sucesso

Nome

Tipo

Descrição

isSupportBLE

Boolean

Indica se há suporte para BLE.

Descrições de códigos de erro

error

Descrição

Solução

12

O Bluetooth não está ativado.

Tente ativar o Bluetooth.

13

A conexão com o serviço do sistema foi perdida temporariamente.

Tente reconectar.

14

O cliente não tem autorização para usar o Bluetooth.

Autorize o cliente a usar o Bluetooth.

15

Erro desconhecido.

-

Exemplo de código

<!-- .axml-->
<view class="page">
  <view class="page-description">Bluetooth API</view>
  <view class="page-section">
    <view class="page-section-title">Local Bluetooth adapter state</view>
    <view class="page-section-demo">
       <button type="primary" onTap="openBluetoothAdapter">Initialize Bluetooth</button>
       <button type="primary" onTap="closeBluetoothAdapter">Close local Bluetooth</button>
       <button type="primary" onTap="getBluetoothAdapterState">Get Bluetooth state</button>
    </view>

    <view class="page-section-title">Scan for Bluetooth devices</view>
    <view class="page-section-demo">
       <button type="primary" onTap="startBluetoothDevicesDiscovery">Start search</button>
       <button type="primary" onTap="getBluetoothDevices">All discovered devices</button>
       <button type="primary" onTap="getConnectedBluetoothDevices">All connected devices</button>
       <button type="primary" onTap="stopBluetoothDevicesDiscovery">Stop search</button>
    </view>

    <view class="page-section-title">Connect to a device</view>
    <view class="page-section-demo">
       <input class="input" onInput="bindKeyInput" type="{{text}}" placeholder="Enter the deviceId of the device to connect to"></input>
       <button type="primary" onTap="connectBLEDevice">Connect to device</button>
       <button type="primary" onTap="getBLEDeviceServices">Get device services</button>
       <button type="primary" onTap="getBLEDeviceCharacteristics">Get read/write characteristics</button>
       <button type="primary" onTap="disconnectBLEDevice">Disconnect from device</button>
    </view>

     <view class="page-section-title">Read and write data</view>
     <view class="page-section-demo">
       <button type="primary" onTap="notifyBLECharacteristicValueChange">Listen for characteristic value changes</button>
       <button type="primary" onTap="readBLECharacteristicValue">Read data</button>
       <button type="primary" onTap="writeBLECharacteristicValue">Write data</button>
       <button type="primary" onTap="offBLECharacteristicValueChange">Cancel characteristic value listener</button>
    </view>

     <view class="page-section-title">Other events</view>
     <view class="page-section-demo">
       <button type="primary" onTap="bluetoothAdapterStateChange">Local Bluetooth state change</button>
       <button type="primary" onTap="offBluetoothAdapterStateChange">Cancel local Bluetooth state listener</button>
       <button type="primary" onTap="BLEConnectionStateChanged">Bluetooth connection state change</button>
       <button type="primary" onTap="offBLEConnectionStateChanged">Cancel Bluetooth connection state listener</button>

    </view>
  </view>
</view>
// .js
Page({
  data: {
    devid: '0D9C82AD-1CC0-414D-9526-119E08D28124',
    serid: 'FEE7',
    notifyId: '36F6',
    writeId: '36F5',
    charid: '',
    alldev: [{ deviceId: '' }],
  },
  // Get the local Bluetooth adapter state
  openBluetoothAdapter() {
    my.openBluetoothAdapter({
      success: res => {
        if (!res.isSupportBLE) {
          my.alert({ content: 'Sorry, Bluetooth is not available on your phone.' });
          return;
        }
        my.alert({ content: 'Initialization successful!' });
      },
      fail: error => {
        my.alert({ content: JSON.stringify(error) });
      },
    });
  },
  closeBluetoothAdapter() {
    my.closeBluetoothAdapter({
      success: () => {
        my.alert({ content: 'Bluetooth closed successfully!' });
      },
      fail: error => {
        my.alert({ content: JSON.stringify(error) });
      },
    });
  },
  getBluetoothAdapterState() {
    my.getBluetoothAdapterState({
      success: res => {
        if (!res.available) {
          my.alert({ content: 'Sorry, Bluetooth is not available on your phone.' });
          return;
        }
        my.alert({ content: JSON.stringify(res) });
      },
      fail: error => {
        my.alert({ content: JSON.stringify(error) });
      },
    });
  },
  // Scan for Bluetooth devices
  startBluetoothDevicesDiscovery() {
    my.startBluetoothDevicesDiscovery({
      allowDuplicatesKey: false,
      success: () => {
        my.onBluetoothDeviceFound({
          success: res => {
            // my.alert({content:'Listening for new devices'+JSON.stringify(res)});
            var deviceArray = res.devices;
            for (var i = deviceArray.length - 1; i >= 0; i--) {
              var deviceObj = deviceArray[i];
              // Match the target device by device name or broadcast data, then record the deviceID for later use
              if (deviceObj.name == this.data.name) {
                my.alert({ content: 'Target device found' });
                my.offBluetoothDeviceFound();
                this.setData({
                  deviceId: deviceObj.deviceId,
                });
                break;
              }
            }
          },
          fail: error => {
            my.alert({ content: 'Failed to listen for new devices' + JSON.stringify(error) });
          },
        });
      },
      fail: error => {
        my.alert({ content: 'Failed to start scan' + JSON.stringify(error) });
      },
    });
  },
  // Stop scanning
  stopBluetoothDevicesDiscovery() {
    my.stopBluetoothDevicesDiscovery({
      success: res => {
        my.offBluetoothDeviceFound();
        my.alert({ content: 'Operation successful!' });
      },
      fail: error => {
        my.alert({ content: JSON.stringify(error) });
      },
    });
  },
  // Get connected devices
  getConnectedBluetoothDevices() {
    my.getConnectedBluetoothDevices({
      success: res => {
        if (res.devices.length === 0) {
          my.alert({ content: 'No connected devices!' });
          return;
        }
        my.alert({ content: JSON.stringify(res) });
        devid = res.devices[0].deviceId;
      },
      fail: error => {
        my.alert({ content: JSON.stringify(error) });
      },
    });
  },
  // Get all discovered devices
  getBluetoothDevices() {
    my.getBluetoothDevices({
      success: res => {
        my.alert({ content: JSON.stringify(res) });
      },
      fail: error => {
        my.alert({ content: JSON.stringify(error) });
      },
    });
  },
  bindKeyInput(e) {
    this.setData({
      devid: e.detail.value,
    });
  },
  // Connect to a device
  connectBLEDevice() {
    my.connectBLEDevice({
      deviceId: this.data.devid,
      success: res => {
        my.alert({ content: 'Connection successful' });
      },
      fail: error => {
        my.alert({ content: JSON.stringify(error) });
      },
    });
  },
  // Disconnect
  disconnectBLEDevice() {
    my.disconnectBLEDevice({
      deviceId: this.data.devid,
      success: () => {
        my.alert({ content: 'Disconnection successful!' });
      },
      fail: error => {
        my.alert({ content: JSON.stringify(error) });
      },
    });
  },
  // Get the services of a connected device. This must be done while connected.
  getBLEDeviceServices() {
    my.getConnectedBluetoothDevices({
      success: res => {
        if (res.devices.length === 0) {
          my.alert({ content: 'No connected devices' });
          return;
        }
        my.getBLEDeviceServices({
          deviceId: this.data.devid,
          success: res => {
            my.alert({ content: JSON.stringify(res) });
            this.setData({
              serid: res.services[0].serviceId,
            });
          },
          fail: error => {
            my.alert({ content: JSON.stringify(error) });
          },
        });
      },
    });
  },
  // Get the charid of a connected device. This must be done while connected. (This filters for read and write characteristics.)
  getBLEDeviceCharacteristics() {
    my.getConnectedBluetoothDevices({
      success: res => {
        if (res.devices.length === 0) {
          my.alert({ content: 'No connected devices' });
          return;
        }
        this.setData({
          devid: res.devices[0].deviceId,
        });
        my.getBLEDeviceCharacteristics({
          deviceId: this.data.devid,
          serviceId: this.data.serid,
          success: res => {
            my.alert({ content: JSON.stringify(res) });
            // See the document for characteristic object properties. Match and record the read/write characteristics for later use.
            this.setData({
              charid: res.characteristics[0].characteristicId,
            });
          },
          fail: error => {
            my.alert({ content: JSON.stringify(error) });
          },
        });
      },
    });
  },
  // Read and write data
  readBLECharacteristicValue() {
    my.getConnectedBluetoothDevices({
      success: res => {
        if (res.devices.length === 0) {
          my.alert({ content: 'No connected devices' });
          return;
        }
        this.setData({
          devid: res.devices[0].deviceId,
        });
        my.readBLECharacteristicValue({
          deviceId: this.data.devid,
          serviceId: this.data.serid,
          characteristicId: this.data.notifyId,
          // 1. Android read service
          // serviceId:'0000180d-0000-1000-8000-00805f9b34fb',
          // characteristicId:'00002a38-0000-1000-8000-00805f9b34fb',
          success: res => {
            my.alert({ content: JSON.stringify(res) });
          },
          fail: error => {
            my.alert({ content: 'Read failed' + JSON.stringify(error) });
          },
        });
      },
    });
  },
  writeBLECharacteristicValue() {
    my.getConnectedBluetoothDevices({
      success: res => {
        if (res.devices.length === 0) {
          my.alert({ content: 'No connected devices' });
          return;
        }
        this.setData({
          devid: res.devices[0].deviceId,
        });
        my.writeBLECharacteristicValue({
          deviceId: this.data.devid,
          serviceId: this.data.serid,
          characteristicId: this.data.charid,
          // Android write service
          //serviceId:'0000180d-0000-1000-8000-00805f9b34fb',
          //characteristicId:'00002a39-0000-1000-8000-00805f9b34fb',
          value: 'ABCD',
          success: res => {
            my.alert({ content: 'Data written successfully!' });
          },
          fail: error => {
            my.alert({ content: JSON.stringify(error) });
          },
        });
      },
    });
  },
  notifyBLECharacteristicValueChange() {
    my.getConnectedBluetoothDevices({
      success: res => {
        if (res.devices.length === 0) {
          my.alert({ content: 'No connected devices' });
          return;
        }
        this.setData({
          devid: res.devices[0].deviceId,
        });
        my.notifyBLECharacteristicValueChange({
          state: true,
          deviceId: this.data.devid,
          serviceId: this.data.serid,
          characteristicId: this.data.notifyId,
          success: () => {
            // Listen for characteristic value changes
            my.onBLECharacteristicValueChange({
              success: res => {
                //  my.alert({content: 'Characteristic value changed: '+JSON.stringify(res)});
                my.alert({ content: 'Response data received = ' + res.value });
              },
            });
            my.alert({ content: 'Listener enabled successfully' });
          },
          fail: error => {
            my.alert({ content: 'Failed to enable listener' + JSON.stringify(error) });
          },
        });
      },
    });
  },
  offBLECharacteristicValueChange() {
    my.offBLECharacteristicValueChange();
  },
  // Other events
  bluetoothAdapterStateChange() {
    my.onBluetoothAdapterStateChange(this.getBind('onBluetoothAdapterStateChange'));
  },
  onBluetoothAdapterStateChange() {
    if (res.error) {
      my.alert({ content: JSON.stringify(error) });
    } else {
      my.alert({ content: 'Local Bluetooth state changed: ' + JSON.stringify(res) });
    }
  },
  offBluetoothAdapterStateChange() {
    my.offBluetoothAdapterStateChange(this.getBind('onBluetoothAdapterStateChange'));
  },
  getBind(name) {
    if (!this[`bind${name}`]) {
      this[`bind${name}`] = this[name].bind(this);
    }
    return this[`bind${name}`];
  },
  BLEConnectionStateChanged() {
    my.onBLEConnectionStateChanged(this.getBind('onBLEConnectionStateChanged'));
  },
  onBLEConnectionStateChanged(res) {
    if (res.error) {
      my.alert({ content: JSON.stringify(error) });
    } else {
      my.alert({ content: 'Connection state changed: ' + JSON.stringify(res) });
    }
  },
  offBLEConnectionStateChanged() {
    my.offBLEConnectionStateChanged(this.getBind('onBLEConnectionStateChanged'));
  },
  onUnload() {
    this.offBLEConnectionStateChanged();
    this.offBLECharacteristicValueChange();
    this.offBluetoothAdapterStateChange();
    this.closeBluetoothAdapter();
  },
});

Bugs e dicas

  • Bug: Se o Bluetooth estiver desligado ou não tiver suporte, my.openBluetoothAdapter retorna um erro (códigos de erro: Tabela de códigos de erro da API Bluetooth). O módulo Bluetooth ainda é inicializado, então você pode usar my.onBluetoothAdapterStateChange para monitorar mudanças de estado.

  • Dica: Chamar outras APIs do módulo Bluetooth antes de chamar a API my.openBluetoothAdapter resulta em erro.

    • Código de erro: 10000

    • Descrição do erro: Adaptador Bluetooth não inicializado

    • Solução: Chame my.openBluetoothAdapter.

my.closeBluetoothAdapter

Desliga o módulo Bluetooth local.

Parâmetros de entrada

Nome

Tipo

Obrigatório

Descrição

success

Function

Não

Chamado em caso de sucesso.

fail

Function

Não

Chamado em caso de falha.

complete

Function

Não

Chamado quando a chamada é concluída, independentemente do resultado.

Exemplo de código

my.closeBluetoothAdapter({
  success: (res) => {
  },
  fail:(res) => {
  },
  complete: (res)=>{
  }
});

Bugs e dicas

  • Dica: Este método desconecta todas as conexões Bluetooth estabelecidas e libera recursos do sistema.

  • Recomendação: Chame este método ao término do processo Bluetooth do miniapp. Ele deve ser usado em conjunto com my.openBluetoothAdapter.

  • Atenção: my.closeBluetoothAdapter é assíncrono. Não chame my.closeBluetoothAdapter seguido por my.openBluetoothAdapter no tratamento de exceções, pois isso causa problemas de sincronização de threads.

my.getBluetoothAdapterState

Obtém o estado do módulo Bluetooth local.

Parâmetros de entrada

Nome

Tipo

Obrigatório

Descrição

success

Function

Não

Chamado em caso de sucesso.

fail

Function

Não

Chamado em caso de falha.

complete

Function

Não

Chamado quando a chamada é concluída, independentemente do resultado.

Valor de retorno de sucesso

Nome

Tipo

Descrição

discovering

Boolean

Indica se uma busca de dispositivos está em andamento.

available

Boolean

Indica se o módulo Bluetooth está disponível (o dispositivo tem suporte para BLE e o Bluetooth está ativado).

Exemplo de código

my.getBluetoothAdapterState({
  success: (res) => {
      console.log(res)
  },
  fail:(res) => {
  },
  complete: (res)=>{
  }
});

my.startBluetoothDevicesDiscovery

Inicia a busca por dispositivos periféricos Bluetooth próximos. Os resultados são retornados no evento my.onBluetoothDeviceFound.

Parâmetros de entrada

Nome

Tipo

Obrigatório

Descrição

services

Array

Não

Lista de UUIDs de serviço primário do dispositivo Bluetooth.

allowDuplicatesKey

Boolean

Não

Define se o mesmo dispositivo deve ser relatado várias vezes. Se true, onBluetoothDeviceFound pode relatar o mesmo dispositivo repetidamente com valores RSSI diferentes.

interval

Integer

Não

Intervalo de relatório. Padrão: 0 (relatar imediatamente). Valores diferentes de zero agrupam os relatórios no intervalo especificado.

success

Function

Não

Chamado em caso de sucesso.

fail

Function

Não

Chamado em caso de falha.

complete

Function

Não

Chamado quando a chamada é concluída, independentemente do resultado.

Exemplo de código

my.startBluetoothDevicesDiscovery({
  services: ['fff0'],
  success: (res) => {
      console.log(res)
  },
  fail:(res) => {
  },
  complete: (res)=>{
  }
});

Bugs e dicas

  • Dica: A descoberta de dispositivos consome muitos recursos. Chame stop após encontrar e conectar-se ao dispositivo alvo.

my.stopBluetoothDevicesDiscovery

Interrompe a busca por dispositivos periféricos Bluetooth próximos.

Parâmetros de entrada

Nome

Tipo

Obrigatório

Descrição

success

Function

Não

Chamado em caso de sucesso.

fail

Function

Não

Chamado em caso de falha.

complete

Function

Não

Chamado quando a chamada é concluída, independentemente do resultado.

Exemplo de código

my.stopBluetoothDevicesDiscovery({
  success: (res) => {
    console.log(res)
  },
  fail:(res) => {
  },
  complete: (res)=>{
  }
});

my.getBluetoothDevices

Obtém todos os dispositivos Bluetooth descobertos, incluindo os já conectados.

Parâmetros de entrada

Nome

Tipo

Obrigatório

Descrição

success

Function

Não

Chamado em caso de sucesso.

fail

Function

Não

Chamado em caso de falha.

complete

Function

Não

Chamado quando a chamada é concluída, independentemente do resultado.

Valor de retorno de sucesso

Nome

Tipo

Descrição

devices

Array

Lista de dispositivos descobertos.

Objeto device

Nome

Tipo

Descrição

name

String

Nome do dispositivo Bluetooth. Alguns dispositivos podem não ter nome.

deviceName (para compatibilidade com versões anteriores)

String

Valor igual a name.

localName

String

Nome do dispositivo de broadcast.

deviceId

String

ID do dispositivo.

RSSI

Number

Força do sinal do dispositivo.

advertisData

Hex String

Conteúdo de broadcast do dispositivo.

manufacturerData

Hex String

Dados do fabricante do dispositivo.

Exemplo de código

my.getBluetoothDevices({
  success: (res) => {
      console.log(res)
  },
  fail:(res) => {
  },
  complete: (res)=>{
  }
});

Bugs e dicas

  • Dica: O emulador pode não conseguir obter advertisData e RSSI. Use um dispositivo físico para depuração.

  • Observação: No Android, deviceId é o endereço MAC; no iOS, é o UUID. Não codifique deviceId diretamente. No iOS, identifique dispositivos dinamicamente por localName, advertisData ou manufacturerData.

my.getConnectedBluetoothDevices

Obtém todos os dispositivos conectados.

Parâmetros de entrada

Nome

Tipo

Obrigatório

Descrição

deviceId

String

Não

ID do dispositivo Bluetooth.

success

Function

Não

Chamado em caso de sucesso.

fail

Function

Não

Chamado em caso de falha.

complete

Function

Não

Chamado quando a chamada é concluída, independentemente do resultado.

Exemplo de código

my.getConnectedBluetoothDevices({
  success: (res) => {
      console.log(res)
  },
  fail:(res) => {
  },
  complete: (res)=>{
  }
});

Bugs e dicas

  • Dica: Se o miniapp já descobriu um dispositivo Bluetooth anteriormente, passe diretamente o deviceId obtido na busca para se conectar sem precisar buscar novamente.

  • Nota: Se o dispositivo Bluetooth especificado já estiver conectado, a reconexão retornará diretamente success.

my.connectBLEDevice

Conecta-se a um dispositivo Bluetooth Low Energy (BLE).

Parâmetros de entrada

Nome

Tipo

Obrigatório

Descrição

deviceId

String

Sim

ID do dispositivo Bluetooth.

success

Function

Não

Chamado em caso de sucesso.

fail

Function

Não

Chamado em caso de falha.

complete

Function

Não

Chamado quando a chamada é concluída, independentemente do resultado.

Exemplo de código

my.connectBLEDevice({
  // The deviceId here needs to be obtained from the getBluetoothDevices or onBluetoothDeviceFound API.
  deviceId: deviceId,
  success: (res) => {
      console.log(res)
  },
  fail:(res) => {
  },
  complete: (res)=>{
  }
});

Bugs e dicas

  • Dica: Se o miniapp já descobriu um dispositivo Bluetooth anteriormente, passe diretamente o deviceId obtido na busca para se conectar sem precisar buscar novamente.

  • Nota: Se o dispositivo Bluetooth especificado já estiver conectado, a reconexão retornará sucesso diretamente.

  • Compatibilidade: Este recurso tem suporte em clientes iOS e Android 5.0 ou posterior.

my.disconnectBLEDevice

Desconecta-se de um dispositivo BLE.

Parâmetros de entrada

Nome

Tipo

Obrigatório

Descrição

deviceId

String

Sim

ID do dispositivo Bluetooth.

success

Function

Não

Chamado em caso de sucesso.

fail

Function

Não

Chamado em caso de falha.

complete

Function

Não

Chamado quando a chamada é concluída, independentemente do resultado.

Exemplo de código

my.disconnectBLEDevice({
  deviceId: deviceId,
  success: (res) => {
      console.log(res)
  },
  fail:(res) => {
  },
  complete: (res)=>{
  }
});

Bugs e dicas

  • Dica: Uma conexão Bluetooth pode ser perdida a qualquer momento. Monitore o evento de callback my.onBLEConnectionStateChanged para reconectar conforme necessário.

  • Atenção: Chamar uma API de leitura/escrita em um dispositivo não conectado retorna o erro 10006 (Tabela de códigos de erro da API Bluetooth). Reconecte antes de tentar novamente.

  • Compatibilidade: Este recurso tem suporte em clientes iOS e Android 5.0 ou posterior.

my.writeBLECharacteristicValue

Escreve dados em uma característica de um dispositivo BLE.

Parâmetros de entrada

Nome

Tipo

Obrigatório

Descrição

deviceId

String

Sim

ID do dispositivo Bluetooth. Consulte o objeto device.

serviceId

String

Sim

UUID do service ao qual a característica pertence.

characteristicId

String

Sim

UUID da característica Bluetooth.

value

Hex String

Sim

Valor codificado em hexadecimal a ser escrito. Limitado a 20 bytes.

success

Function

Não

Chamado em caso de sucesso.

fail

Function

Não

Chamado em caso de falha.

complete

Function

Não

Chamado quando a chamada é concluída, independentemente do resultado.

Exemplo de código

my.writeBLECharacteristicValue({
  deviceId: deviceId,
  serviceId: serviceId,
  characteristicId: characteristicId,
  value: 'fffe',
  success: (res) => {
      console.log(res)
  },
  fail:(res) => {
  },
  complete: (res)=>{
  }
});

Bugs e dicas

  • Dica: A característica do dispositivo deve ter suporte para a operação de escrita para que esta chamada tenha sucesso. Verifique o atributo properties da característica.

  • Requisito: Os dados binários a serem escritos devem estar codificados em hexadecimal.

  • Compatibilidade: Este recurso tem suporte em clientes iOS e Android 5.0 ou posterior.

my.readBLECharacteristicValue

Lê dados de uma característica de um dispositivo BLE. Os dados são retornados no evento my.onBLECharacteristicValueChange().

Parâmetros de entrada

Nome

Tipo

Obrigatório

Descrição

deviceId

String

Sim

ID do dispositivo Bluetooth. Consulte o objeto device.

serviceId

String

Sim

UUID do service ao qual a característica pertence.

characteristicId

String

Sim

UUID da característica Bluetooth.

success

Function

Não

Chamado em caso de sucesso.

fail

Function

Não

Chamado em caso de falha.

complete

Function

Não

Chamado quando a chamada é concluída, independentemente do resultado.

Valor de retorno de sucesso

Nome

Tipo

Descrição

characteristic

Object

Informações da característica do dispositivo.

Objeto characteristic

Informações sobre uma característica de dispositivo Bluetooth.

Nome

Tipo

Descrição

characteristicId

String

UUID da característica do dispositivo Bluetooth.

serviceId

String

UUID do serviço ao qual a característica pertence.

value

Hex String

Valor da característica do dispositivo Bluetooth.

Exemplo de código

my.readBLECharacteristicValue({
  deviceId: deviceId,
  serviceId: serviceId,
  characteristicId: characteristicId,
  success: (res) => {
      console.log(res)
  },
  fail:(res) => {
  },
  complete: (res)=>{
  }
});

Bugs e dicas

  • Dica: A característica do dispositivo deve ter suporte para a operação de leitura para que esta chamada tenha sucesso. Verifique o atributo properties da característica.

  • Atenção: Chamar APIs de leitura e escrita em paralelo pode causar falhas.

  • Importante: Se uma leitura atingir o tempo limite (erro 10015), my.onBLECharacteristicValueChange ainda poderá retornar dados posteriormente — trate esse caso. Códigos de erro e soluções: Referência de códigos de erro da API Bluetooth.

  • Compatibilidade: Este recurso tem suporte em clientes iOS e Android 5.0 ou posterior.

my.notifyBLECharacteristicValueChange

Ativa o recurso notify para alterações de valor de característica em um dispositivo BLE.

Parâmetros de entrada

Nome

Tipo

Obrigatório

Descrição

deviceId

String

Sim

ID do dispositivo Bluetooth. Consulte o objeto device.

serviceId

String

Sim

UUID do service ao qual a característica pertence.

characteristicId

String

Sim

UUID da característica Bluetooth.

descriptorId

String

Não

UUID do notify descriptor. Apenas Android. Padrão: 00002902-0000-10008000-00805f9b34fb.

state

Boolean

Não

Define se deve ativar notify ou indicate.

success

Function

Não

Chamado em caso de sucesso.

fail

Function

Não

Chamado em caso de falha.

complete

Function

Não

Chamado quando a chamada é concluída, independentemente do resultado.

Exemplo de código

my.notifyBLECharacteristicValueChange({
  deviceId: deviceId,
  serviceId: serviceId,
  characteristicId: characteristicId,
  success: (res) => {
      console.log(res)
  },
  fail:(res) => {
  },
  complete: (res)=>{
  }
});

Bugs e dicas

  • Dica: A característica do dispositivo deve ter suporte para notify ou indicate para que esta chamada tenha sucesso. Verifique o atributo properties da characteristic.

  • Requisito: Ative notify antes de monitorar o evento characteristicValueChange do dispositivo.

  • Comportamento: Após uma assinatura bem-sucedida, o dispositivo deve atualizar ativamente o valor da característica para acionar my.onBLECharacteristicValueChange.

  • Performance: Assinar é mais eficiente do que fazer polling com leitura. Prefira assinaturas.

my.getBLEDeviceServices

Obtém todos os serviços de um dispositivo BLE conectado.

Parâmetros de entrada

Nome

Tipo

Obrigatório

Descrição

deviceId

String

Sim

ID do dispositivo Bluetooth. Consulte o objeto device.

success

Function

Não

Chamado em caso de sucesso.

fail

Function

Não

Chamado em caso de falha.

complete

Function

Não

Chamado quando a chamada é concluída, independentemente do resultado.

Valor de retorno de sucesso

Nome

Tipo

Descrição

services

Array

Lista de serviços de dispositivo descobertos. Consulte a tabela a seguir para informações sobre características.

Objeto service

Informações sobre um serviço de dispositivo Bluetooth.

Nome

Tipo

Descrição

serviceId

String

UUID do serviço do dispositivo Bluetooth.

isPrimary

Boolean

Indica se este é um serviço primário.

  • true: Serviço primário.

  • false: Não é um serviço primário.

Exemplo de código

 // Get the services of a connected device. This must be done while connected.
  getBLEDeviceServices() {
    my.getConnectedBluetoothDevices({
      success: res => {
        if (res.devices.length === 0) {
          my.alert({ content: 'No connected devices' });
          return;
        }
        my.getBLEDeviceServices({
          deviceId: this.data.devid,
          success: res => {
            my.alert({ content: JSON.stringify(res) });
            this.setData({
              serid: res.services[0].serviceId,
            });
          },
          fail: error => {
            my.alert({ content: JSON.stringify(error) });
          },
        });
      },
    });
  },

Amostra de valor de retorno

{
    "services": [{
        "isPrimary": true,
        "serviceId": "00001800-0000-1000-8000-00805f9b34fb"
    }, {
        "isPrimary": true,
        "serviceId": "00001801-0000-1000-8000-00805f9b34fb"
    }, {
        "isPrimary": true,
        "serviceId": "d0611e78-bbb4-4591-a5f8-487910ae4366"
    }, {
        "isPrimary": true,
        "serviceId": "9fa480e0-4967-4542-9390-d343dc5d04ae"
    }]
}

Bugs e dicas

  • Dica: Após estabelecer uma conexão, execute my.getBLEDeviceServices e my.getBLEDeviceCharacteristics antes de interagir com o dispositivo Bluetooth.

  • Compatibilidade: Este recurso tem suporte em clientes iOS e Android 5.0 ou posterior.

my.getBLEDeviceCharacteristics

Obtém todas as characteristics de um dispositivo BLE conectado.

Parâmetros de entrada

Nome

Tipo

Obrigatório

Descrição

deviceId

String

Sim

ID do dispositivo Bluetooth. Consulte o objeto device.

serviceId

String

Sim

UUID do service ao qual a característica pertence.

success

Function

Não

Chamado em caso de sucesso.

fail

Function

Não

Chamado em caso de falha.

complete

Function

Não

Chamado quando a chamada é concluída, independentemente do resultado.

Valor de retorno de sucesso

Nome

Tipo

Descrição

characteristics

Array

Lista de características do dispositivo.

Objeto characteristic

Informações sobre uma characteristic de dispositivo Bluetooth.

Nome

Tipo

Descrição

characteristicId

String

UUID da característica do dispositivo Bluetooth.

serviceId

String

UUID do serviço ao qual a característica pertence.

value

Hex String

Valor hexadecimal da característica do dispositivo Bluetooth.

properties

Object

Operações com suporte nesta característica.

Objeto properties

Nome

Tipo

Descrição

read

Boolean

Indica se esta característica tem suporte para a operação de leitura.

write

Boolean

Indica se esta característica tem suporte para a operação de escrita.

notify

Boolean

Indica se esta característica tem suporte para a operação notify.

indicate

Boolean

Indica se esta característica tem suporte para a operação indicate.

Exemplo de código

my.getBLEDeviceCharacteristics({
  deviceId: deviceId,
  serviceId: serviceId,
  success: (res) => {
      console.log(res)
  },
  fail:(res) => {
  },
  complete: (res)=>{
  }
});

Bugs e dicas

  • Dica: Após estabelecer uma conexão, execute my.getBLEDeviceServices e my.getBLEDeviceCharacteristics antes de interagir com o dispositivo Bluetooth.

  • Compatibilidade: Este recurso tem suporte em clientes iOS e Android 5.0 ou posterior.

my.onBluetoothDeviceFound(callback)

Este evento é acionado quando um novo dispositivo Bluetooth é descoberto.

Parâmetros de entrada

Nome

Tipo

Obrigatório

Descrição

callback

Function

Sim

Função de callback para o evento.

Valor de retorno do callback

Nome

Tipo

Descrição

devices

Array

Lista de dispositivos recém-descobertos.

Objeto device

Nome

Tipo

Descrição

name

String

Nome do dispositivo Bluetooth. Alguns dispositivos podem não ter nome.

deviceName (para compatibilidade com versões anteriores)

String

Valor igual a name.

localName

String

Nome do dispositivo de broadcast.

deviceId

String

ID do dispositivo.

RSSI

Number

Força do sinal do dispositivo.

advertisData

Hex String

Conteúdo de broadcast do dispositivo.

Exemplo de código

Page({
  onLoad() {
    this.callback = this.callback.bind(this);
    my.onBluetoothDeviceFound(this.callback);
  },
  onUnload() {
    my.offBluetoothDeviceFound(this.callback);
  },
  callback(res) {
    console.log(res);
  },
})

Bugs e dicas

  • Dica: O emulador pode não conseguir obter advertisData e RSSI. Use um dispositivo físico para depuração.

  • Observação: No Android, deviceId é o endereço MAC; no iOS, é o UUID. Não codifique deviceId diretamente. No iOS, identifique dispositivos dinamicamente por localName, advertisData ou manufacturerData.

  • Comportamento: Quando o callback my.onBluetoothDeviceFound encontra um dispositivo Bluetooth, o dispositivo é adicionado ao array retornado pela API my.getBluetoothDevices.

my.offBluetoothDeviceFound

Remove o listener do evento de descoberta de novos dispositivos Bluetooth.

Exemplo de código

my.offBluetoothDeviceFound();

Passagem de valor de callback

  • Sem a passagem de um valor de callback, todos os listeners deste evento são removidos. Exemplo:

    my.offBluetoothDeviceFound();
  • Com a passagem de um valor de callback, apenas o listener correspondente é removido. Exemplo:

    my.offBluetoothDeviceFound(this.callback);

Bugs e dicas

  • Dica: Para evitar múltiplos callbacks para o mesmo evento, chame o método off para remover listeners existentes antes de chamar o método on.

my.onBLECharacteristicValueChange(callback)

Monitora alterações de valor de característica em um dispositivo BLE.

Parâmetros de entrada

Nome

Tipo

Obrigatório

Descrição

callback

Function

Sim

Função de callback do evento.

Valor de retorno do callback

Nome

Tipo

Descrição

deviceId

String

ID do dispositivo Bluetooth. Consulte o objeto device.

connected

Boolean

Estado atual da conexão.

Exemplo de código

Page({
  onLoad() {
    this.callback = this.callback.bind(this);
    my.onBLECharacteristicValueChange(this.callback);
  },
  onUnload() {
    my.offBLECharacteristicValueChange(this.callback);
  },
  callback(res) {
    console.log(res);
  },
})

Bugs e dicas

  • Dica: Para evitar múltiplos callbacks para um único evento, chame o método off para remover listeners existentes antes de chamar o método on.

my.offBLECharacteristicValueChange

Remove o listener de alterações de valor de característica em um dispositivo BLE.

Parâmetros de entrada

O tipo é uma função callback cujo parâmetro de entrada é um Object com as seguintes propriedades:

Propriedade

Tipo

Descrição

deviceId

String

ID do dispositivo Bluetooth. Consulte o objeto device.

serviceId

String

UUID do service ao qual a característica pertence.

characteristicId

String

UUID da característica Bluetooth.

value

Hex String

Valor hexadecimal mais recente da característica.

Passagem de valor de callback

  • Sem a passagem de um valor de callback, todos os listeners deste evento são removidos. Exemplo:

    my.offBLECharacteristicValueChange();
  • Com a passagem de um valor de callback, apenas o listener correspondente é removido. Exemplo:

    my.offBLECharacteristicValueChange(this.callback);

Exemplo de código

Page({
  onLoad() {
    this.callback = this.callback.bind(this);
    my.onBLECharacteristicValueChange(this.callback);
  },
  onUnload() {
    my.offBLECharacteristicValueChange(this.callback);
  },
  callback(res) {
    console.log(res);
  },
})

my.onBLEConnectionStateChanged(callback)

Monitora eventos de erro de conexão BLE, incluindo perda de dispositivo e desconexões anormais.

Parâmetros de entrada

Nome

Tipo

Obrigatório

Descrição

callback

Function

Sim

Função de callback do evento.

Valor de retorno do callback

Nome

Tipo

Descrição

deviceId

String

ID do dispositivo Bluetooth. Consulte o objeto device.

connected

Boolean

Estado atual da conexão.

Exemplo de código

/* .acss */
.help-info {
  padding:10px;
  color:#000000;
}
.help-title {
  padding:10px;
  color:#FC0D1B;
}
// .json
{
    "defaultTitle": "Bluetooth"
}
<!-- .axml-->
<view class="page">
  <view class="page-description">Bluetooth API</view>
  <view class="page-section">
    <view class="page-section-title">Local Bluetooth adapter state</view>
    <view class="page-section-demo">
       <button type="primary" onTap="openBluetoothAdapter">Initialize Bluetooth</button>
       <button type="primary" onTap="closeBluetoothAdapter">Close local Bluetooth</button>
       <button type="primary" onTap="getBluetoothAdapterState">Get Bluetooth state</button>
    </view>

    <view class="page-section-title">Scan for Bluetooth devices</view>
    <view class="page-section-demo">
       <button type="primary" onTap="startBluetoothDevicesDiscovery">Start search</button>
       <button type="primary" onTap="getBluetoothDevices">All discovered devices</button>
       <button type="primary" onTap="getConnectedBluetoothDevices">All connected devices</button>
       <button type="primary" onTap="stopBluetoothDevicesDiscovery">Stop search</button>
    </view>

    <view class="page-section-title">Connect to a device</view>
    <view class="page-section-demo">
       <input class="input" onInput="bindKeyInput" type="{{text}}" placeholder="Enter the deviceId of the device to connect to"></input>
       <button type="primary" onTap="connectBLEDevice">Connect to device</button>
       <button type="primary" onTap="getBLEDeviceServices">Get device services</button>
       <button type="primary" onTap="getBLEDeviceCharacteristics">Get read/write characteristics</button>
       <button type="primary" onTap="disconnectBLEDevice">Disconnect from device</button>
    </view>

     <view class="page-section-title">Read and write data</view>
     <view class="page-section-demo">
       <button type="primary" onTap="notifyBLECharacteristicValueChange">Listen for characteristic value changes</button>
       <button type="primary" onTap="readBLECharacteristicValue">Read data</button>
       <button type="primary" onTap="writeBLECharacteristicValue">Write data</button>
       <button type="primary" onTap="offBLECharacteristicValueChange">Cancel characteristic value listener</button>
    </view>

     <view class="page-section-title">Other events</view>
     <view class="page-section-demo">
       <button type="primary" onTap="bluetoothAdapterStateChange">Local Bluetooth state change</button>
       <button type="primary" onTap="offBluetoothAdapterStateChange">Cancel local Bluetooth state listener</button>
       <button type="primary" onTap="BLEConnectionStateChanged">Bluetooth connection state change</button>
       <button type="primary" onTap="offBLEConnectionStateChanged">Cancel Bluetooth connection state listener</button>

    </view>

  </view>
</view>
// .js
Page({
  data: {
    devid: '0D9C82AD-1CC0-414D-9526-119E08D28124',
    serid: 'FEE7',
    notifyId: '36F6',
    writeId: '36F5',
    charid: '',
    alldev: [{ deviceId: '' }],
  },

  // Get the local Bluetooth adapter state
  openBluetoothAdapter() {
    my.openBluetoothAdapter({
      success: res => {
        if (!res.isSupportBLE) {
          my.alert({ content: 'Sorry, Bluetooth is not available on your phone.' });
          return;
        }
        my.alert({ content: 'Initialization successful!' });
      },
      fail: error => {
        my.alert({ content: JSON.stringify(error) });
      },
    });
  },
  closeBluetoothAdapter() {
    my.closeBluetoothAdapter({
      success: () => {
        my.alert({ content: 'Bluetooth closed successfully!' });
      },
      fail: error => {
        my.alert({ content: JSON.stringify(error) });
      },
    });
  },
  getBluetoothAdapterState() {
    my.getBluetoothAdapterState({
      success: res => {
        if (!res.available) {
          my.alert({ content: 'Sorry, Bluetooth is not available on your phone.' });
          return;
        }
        my.alert({ content: JSON.stringify(res) });
      },
      fail: error => {
        my.alert({ content: JSON.stringify(error) });
      },
    });
  },

  // Scan for Bluetooth devices
  startBluetoothDevicesDiscovery() {
    my.startBluetoothDevicesDiscovery({
      allowDuplicatesKey: false,
      success: () => {
        my.onBluetoothDeviceFound({
          success: res => {
            // my.alert({content:'Listening for new devices'+JSON.stringify(res)});
            var deviceArray = res.devices;
            for (var i = deviceArray.length - 1; i >= 0; i--) {
              var deviceObj = deviceArray[i];
              // Match the target device by device name or broadcast data, then record the deviceID for later use
              if (deviceObj.name == this.data.name) {
                my.alert({ content: 'Target device found' });
                my.offBluetoothDeviceFound();
                this.setData({
                  deviceId: deviceObj.deviceId,
                });
                break;
              }
            }
          },
          fail: error => {
            my.alert({ content: 'Failed to listen for new devices' + JSON.stringify(error) });
          },
        });
      },
      fail: error => {
        my.alert({ content: 'Failed to start scan' + JSON.stringify(error) });
      },
    });
  },

  // Stop scanning
  stopBluetoothDevicesDiscovery() {
    my.stopBluetoothDevicesDiscovery({
      success: res => {
        my.offBluetoothDeviceFound();
        my.alert({ content: 'Operation successful!' });
      },
      fail: error => {
        my.alert({ content: JSON.stringify(error) });
      },
    });
  },

  // Get connected devices
  getConnectedBluetoothDevices() {
    my.getConnectedBluetoothDevices({
      success: res => {
        if (res.devices.length === 0) {
          my.alert({ content: 'No connected devices!' });
          return;
        }
        my.alert({ content: JSON.stringify(res) });
        devid = res.devices[0].deviceId;
      },
      fail: error => {
        my.alert({ content: JSON.stringify(error) });
      },
    });
  },

  // Get all discovered devices
  getBluetoothDevices() {
    my.getBluetoothDevices({
      success: res => {
        my.alert({ content: JSON.stringify(res) });
      },
      fail: error => {
        my.alert({ content: JSON.stringify(error) });
      },
    });
  },

  bindKeyInput(e) {
    this.setData({
      devid: e.detail.value,
    });
  },

  // Connect to a device
  connectBLEDevice() {
    my.connectBLEDevice({
      deviceId: this.data.devid,
      success: res => {
        my.alert({ content: 'Connection successful' });
      },
      fail: error => {
        my.alert({ content: JSON.stringify(error) });
      },
    });
  },

  // Disconnect
  disconnectBLEDevice() {
    my.disconnectBLEDevice({
      deviceId: this.data.devid,
      success: () => {
        my.alert({ content: 'Disconnection successful!' });
      },
      fail: error => {
        my.alert({ content: JSON.stringify(error) });
      },
    });
  },

  // Get the services of a connected device. This must be done while connected.
  getBLEDeviceServices() {
    my.getConnectedBluetoothDevices({
      success: res => {
        if (res.devices.length === 0) {
          my.alert({ content: 'No connected devices' });
          return;
        }
        my.getBLEDeviceServices({
          deviceId: this.data.devid,
          success: res => {
            my.alert({ content: JSON.stringify(res) });
            this.setData({
              serid: res.services[0].serviceId,
            });
          },
          fail: error => {
            my.alert({ content: JSON.stringify(error) });
          },
        });
      },
    });
  },

  // Get the charid of a connected device. This must be done while connected. (This filters for read and write characteristics.)
  getBLEDeviceCharacteristics() {
    my.getConnectedBluetoothDevices({
      success: res => {
        if (res.devices.length === 0) {
          my.alert({ content: 'No connected devices' });
          return;
        }
        this.setData({
          devid: res.devices[0].deviceId,
        });
        my.getBLEDeviceCharacteristics({
          deviceId: this.data.devid,
          serviceId: this.data.serid,
          success: res => {
            my.alert({ content: JSON.stringify(res) });
            // See the document for characteristic object properties. Match and record the read/write characteristics for later use.
            this.setData({
              charid: res.characteristics[0].characteristicId,
            });
          },
          fail: error => {
            my.alert({ content: JSON.stringify(error) });
          },
        });
      },
    });
  },

  // Read and write data
  readBLECharacteristicValue() {
    my.getConnectedBluetoothDevices({
      success: res => {
        if (res.devices.length === 0) {
          my.alert({ content: 'No connected devices' });
          return;
        }
        this.setData({
          devid: res.devices[0].deviceId,
        });
        my.readBLECharacteristicValue({
          deviceId: this.data.devid,
          serviceId: this.data.serid,
          characteristicId: this.data.notifyId,
          // 1. Android read service
          // serviceId:'0000180d-0000-1000-8000-00805f9b34fb',
          // characteristicId:'00002a38-0000-1000-8000-00805f9b34fb',
          success: res => {
            my.alert({ content: JSON.stringify(res) });
          },
          fail: error => {
            my.alert({ content: 'Read failed' + JSON.stringify(error) });
          },
        });
      },
    });
  },

  writeBLECharacteristicValue() {
    my.getConnectedBluetoothDevices({
      success: res => {
        if (res.devices.length === 0) {
          my.alert({ content: 'No connected devices' });
          return;
        }
        this.setData({
          devid: res.devices[0].deviceId,
        });

        my.writeBLECharacteristicValue({
          deviceId: this.data.devid,
          serviceId: this.data.serid,
          characteristicId: this.data.charid,
          // Android write service
          //serviceId:'0000180d-0000-1000-8000-00805f9b34fb',
          //characteristicId:'00002a39-0000-1000-8000-00805f9b34fb',
          value: 'ABCD',
          success: res => {
            my.alert({ content: 'Data written successfully!' });
          },
          fail: error => {
            my.alert({ content: JSON.stringify(error) });
          },
        });
      },
    });
  },
  notifyBLECharacteristicValueChange() {
    my.getConnectedBluetoothDevices({
      success: res => {
        if (res.devices.length === 0) {
          my.alert({ content: 'No connected devices' });
          return;
        }
        this.setData({
          devid: res.devices[0].deviceId,
        });

        my.notifyBLECharacteristicValueChange({
          state: true,
          deviceId: this.data.devid,
          serviceId: this.data.serid,
          characteristicId: this.data.notifyId,
          success: () => {

            // Listen for characteristic value changes
            my.onBLECharacteristicValueChange({
              success: res => {

                //  my.alert({content: 'Characteristic value changed: '+JSON.stringify(res)});
                my.alert({ content: 'Response data received = ' + res.value });
              },
            });
            my.alert({ content: 'Listener enabled successfully' });
          },
          fail: error => {
            my.alert({ content: 'Failed to enable listener' + JSON.stringify(error) });
          },
        });
      },
    });
  },
  offBLECharacteristicValueChange() {
    my.offBLECharacteristicValueChange();
  },

  // Other events
  bluetoothAdapterStateChange() {
    my.onBluetoothAdapterStateChange(this.getBind('onBluetoothAdapterStateChange'));
  },
  onBluetoothAdapterStateChange() {
    if (res.error) {
      my.alert({ content: JSON.stringify(error) });
    } else {
      my.alert({ content: 'Local Bluetooth state changed: ' + JSON.stringify(res) });
    }
  },
  offBluetoothAdapterStateChange() {
    my.offBluetoothAdapterStateChange(this.getBind('onBluetoothAdapterStateChange'));
  },
  getBind(name) {
    if (!this[`bind${name}`]) {
      this[`bind${name}`] = this[name].bind(this);
    }
    return this[`bind${name}`];
  },
  BLEConnectionStateChanged() {
    my.onBLEConnectionStateChanged(this.getBind('onBLEConnectionStateChanged'));
  },
  onBLEConnectionStateChanged(res) {
    if (res.error) {
      my.alert({ content: JSON.stringify(error) });
    } else {
      my.alert({ content: 'Connection state changed: ' + JSON.stringify(res) });
    }
  },
  offBLEConnectionStateChanged() {
    my.offBLEConnectionStateChanged(this.getBind('onBLEConnectionStateChanged'));
  },
  onUnload() {
    this.offBLEConnectionStateChanged();
    this.offBLECharacteristicValueChange();
    this.offBluetoothAdapterStateChange();
    this.closeBluetoothAdapter();
  },
});

Bugs e dicas

  • Dica: Para evitar múltiplos callbacks para um único evento, chame o método off para remover listeners anteriores antes de chamar o método on.

my.offBLEConnectionStateChanged

Remove o listener de alterações de estado de conexão BLE.

Exemplo de código

my.offBLEConnectionStateChanged();

A passagem de valor de callback é obrigatória?

  • Sem a passagem de um valor de callback, todos os listeners deste evento são removidos. Exemplo:

    my.offBLEConnectionStateChanged();
  • Com a passagem de um valor de callback, apenas o listener correspondente é removido. Exemplo:

    my.offBLEConnectionStateChanged(this.callback);

Bugs e dicas

  • Dica: Para evitar múltiplos callbacks para um único evento, chame o método off para remover listeners anteriores antes de chamar o método on.

my.onBluetoothAdapterStateChange(callback)

Monitora alterações no estado do adaptador Bluetooth local.

Parâmetros de entrada

Nome

Tipo

Obrigatório

Descrição

callback

Function

Sim

Função de callback do evento.

Valor de retorno do callback

Nome

Tipo

Descrição

available

Boolean

Indica se o módulo Bluetooth está ativo.

discovering

Boolean

Indica se uma busca de dispositivos está em andamento.

Exemplo de código

/* .acss */
.help-info {
  padding:10px;
  color:#000000;
}
.help-title {
  padding:10px;
  color:#FC0D1B;
}
// .json
{
    "defaultTitle": "Bluetooth"
}
<!-- .axml-->
<view class="page">
  <view class="page-description">Bluetooth API</view>
  <view class="page-section">
    <view class="page-section-title">Local Bluetooth adapter state</view>
    <view class="page-section-demo">
       <button type="primary" onTap="openBluetoothAdapter">Initialize Bluetooth</button>
       <button type="primary" onTap="closeBluetoothAdapter">Close local Bluetooth</button>
       <button type="primary" onTap="getBluetoothAdapterState">Get Bluetooth state</button>
    </view>

    <view class="page-section-title">Scan for Bluetooth devices</view>
    <view class="page-section-demo">
       <button type="primary" onTap="startBluetoothDevicesDiscovery">Start search</button>
       <button type="primary" onTap="getBluetoothDevices">All discovered devices</button>
       <button type="primary" onTap="getConnectedBluetoothDevices">All connected devices</button>
       <button type="primary" onTap="stopBluetoothDevicesDiscovery">Stop search</button>
    </view>

    <view class="page-section-title">Connect to a device</view>
    <view class="page-section-demo">
       <input class="input" onInput="bindKeyInput" type="{{text}}" placeholder="Enter the deviceId of the device to connect to"></input>
       <button type="primary" onTap="connectBLEDevice">Connect to device</button>
       <button type="primary" onTap="getBLEDeviceServices">Get device services</button>
       <button type="primary" onTap="getBLEDeviceCharacteristics">Get read/write characteristics</button>
       <button type="primary" onTap="disconnectBLEDevice">Disconnect from device</button>
    </view>

     <view class="page-section-title">Read and write data</view>
     <view class="page-section-demo">
       <button type="primary" onTap="notifyBLECharacteristicValueChange">Listen for characteristic value changes</button>
       <button type="primary" onTap="readBLECharacteristicValue">Read data</button>
       <button type="primary" onTap="writeBLECharacteristicValue">Write data</button>
       <button type="primary" onTap="offBLECharacteristicValueChange">Cancel characteristic value listener</button>
    </view>

     <view class="page-section-title">Other events</view>
     <view class="page-section-demo">
       <button type="primary" onTap="bluetoothAdapterStateChange">Local Bluetooth state change</button>
       <button type="primary" onTap="offBluetoothAdapterStateChange">Cancel local Bluetooth state listener</button>
       <button type="primary" onTap="BLEConnectionStateChanged">Bluetooth connection state change</button>
       <button type="primary" onTap="offBLEConnectionStateChanged">Cancel Bluetooth connection state listener</button>

    </view>

  </view>
</view>
// .js
Page({
  data: {
    devid: '0D9C82AD-1CC0-414D-9526-119E08D28124',
    serid: 'FEE7',
    notifyId: '36F6',
    writeId: '36F5',
    charid: '',
    alldev: [{ deviceId: '' }],
  },

  // Get the local Bluetooth adapter state
  openBluetoothAdapter() {
    my.openBluetoothAdapter({
      success: res => {
        if (!res.isSupportBLE) {
          my.alert({ content: 'Sorry, Bluetooth is not available on your phone.' });
          return;
        }
        my.alert({ content: 'Initialization successful!' });
      },
      fail: error => {
        my.alert({ content: JSON.stringify(error) });
      },
    });
  },
  closeBluetoothAdapter() {
    my.closeBluetoothAdapter({
      success: () => {
        my.alert({ content: 'Bluetooth closed successfully!' });
      },
      fail: error => {
        my.alert({ content: JSON.stringify(error) });
      },
    });
  },
  getBluetoothAdapterState() {
    my.getBluetoothAdapterState({
      success: res => {
        if (!res.available) {
          my.alert({ content: 'Sorry, Bluetooth is not available on your phone.' });
          return;
        }
        my.alert({ content: JSON.stringify(res) });
      },
      fail: error => {
        my.alert({ content: JSON.stringify(error) });
      },
    });
  },

  // Scan for Bluetooth devices
  startBluetoothDevicesDiscovery() {
    my.startBluetoothDevicesDiscovery({
      allowDuplicatesKey: false,
      success: () => {
        my.onBluetoothDeviceFound({
          success: res => {

            // my.alert({content:'Listening for new devices'+JSON.stringify(res)});
            var deviceArray = res.devices;
            for (var i = deviceArray.length - 1; i >= 0; i--) {
              var deviceObj = deviceArray[i];

              // Match the target device by device name or broadcast data, then record the deviceID for later use
              if (deviceObj.name == this.data.name) {
                my.alert({ content: 'Target device found' });
                my.offBluetoothDeviceFound();
                this.setData({
                  deviceId: deviceObj.deviceId,
                });
                break;
              }
            }
          },
          fail: error => {
            my.alert({ content: 'Failed to listen for new devices' + JSON.stringify(error) });
          },
        });
      },
      fail: error => {
        my.alert({ content: 'Failed to start scan' + JSON.stringify(error) });
      },
    });
  },

  // Stop scanning
  stopBluetoothDevicesDiscovery() {
    my.stopBluetoothDevicesDiscovery({
      success: res => {
        my.offBluetoothDeviceFound();
        my.alert({ content: 'Operation successful!' });
      },
      fail: error => {
        my.alert({ content: JSON.stringify(error) });
      },
    });
  },

  // Get connected devices
  getConnectedBluetoothDevices() {
    my.getConnectedBluetoothDevices({
      success: res => {
        if (res.devices.length === 0) {
          my.alert({ content: 'No connected devices!' });
          return;
        }
        my.alert({ content: JSON.stringify(res) });
        devid = res.devices[0].deviceId;
      },
      fail: error => {
        my.alert({ content: JSON.stringify(error) });
      },
    });
  },

  // Get all discovered devices
  getBluetoothDevices() {
    my.getBluetoothDevices({
      success: res => {
        my.alert({ content: JSON.stringify(res) });
      },
      fail: error => {
        my.alert({ content: JSON.stringify(error) });
      },
    });
  },

  bindKeyInput(e) {
    this.setData({
      devid: e.detail.value,
    });
  },

  // Connect to a device
  connectBLEDevice() {
    my.connectBLEDevice({
      deviceId: this.data.devid,
      success: res => {
        my.alert({ content: 'Connection successful' });
      },
      fail: error => {
        my.alert({ content: JSON.stringify(error) });
      },
    });
  },

  // Disconnect
  disconnectBLEDevice() {
    my.disconnectBLEDevice({
      deviceId: this.data.devid,
      success: () => {
        my.alert({ content: 'Disconnection successful!' });
      },
      fail: error => {
        my.alert({ content: JSON.stringify(error) });
      },
    });
  },

  // Get the services of a connected device. This must be done while connected.
  getBLEDeviceServices() {
    my.getConnectedBluetoothDevices({
      success: res => {
        if (res.devices.length === 0) {
          my.alert({ content: 'No connected devices' });
          return;
        }
        my.getBLEDeviceServices({
          deviceId: this.data.devid,
          success: res => {
            my.alert({ content: JSON.stringify(res) });
            this.setData({
              serid: res.services[0].serviceId,
            });
          },
          fail: error => {
            my.alert({ content: JSON.stringify(error) });
          },
        });
      },
    });
  },

  // Get the charid of a connected device. This must be done while connected. (This filters for read and write characteristics.)
  getBLEDeviceCharacteristics() {
    my.getConnectedBluetoothDevices({
      success: res => {
        if (res.devices.length === 0) {
          my.alert({ content: 'No connected devices' });
          return;
        }
        this.setData({
          devid: res.devices[0].deviceId,
        });
        my.getBLEDeviceCharacteristics({
          deviceId: this.data.devid,
          serviceId: this.data.serid,
          success: res => {
            my.alert({ content: JSON.stringify(res) });

            // See the document for characteristic object properties. Match and record the read/write characteristics for later use.
            this.setData({
              charid: res.characteristics[0].characteristicId,
            });
          },
          fail: error => {
            my.alert({ content: JSON.stringify(error) });
          },
        });
      },
    });
  },

  // Read and write data
  readBLECharacteristicValue() {
    my.getConnectedBluetoothDevices({
      success: res => {
        if (res.devices.length === 0) {
          my.alert({ content: 'No connected devices' });
          return;
        }
        this.setData({
          devid: res.devices[0].deviceId,
        });
        my.readBLECharacteristicValue({
          deviceId: this.data.devid,
          serviceId: this.data.serid,
          characteristicId: this.data.notifyId,

          // 1. Android read service
          // serviceId:'0000180d-0000-1000-8000-00805f9b34fb',
          // characteristicId:'00002a38-0000-1000-8000-00805f9b34fb',
          success: res => {
            my.alert({ content: JSON.stringify(res) });
          },
          fail: error => {
            my.alert({ content: 'Read failed' + JSON.stringify(error) });
          },
        });
      },
    });
  },

  writeBLECharacteristicValue() {
    my.getConnectedBluetoothDevices({
      success: res => {
        if (res.devices.length === 0) {
          my.alert({ content: 'No connected devices' });
          return;
        }
        this.setData({
          devid: res.devices[0].deviceId,
        });

        my.writeBLECharacteristicValue({
          deviceId: this.data.devid,
          serviceId: this.data.serid,
          characteristicId: this.data.charid,

          // Android write service
          //serviceId:'0000180d-0000-1000-8000-00805f9b34fb',
          //characteristicId:'00002a39-0000-1000-8000-00805f9b34fb',
          value: 'ABCD',
          success: res => {
            my.alert({ content: 'Data written successfully!' });
          },
          fail: error => {
            my.alert({ content: JSON.stringify(error) });
          },
        });
      },
    });
  },
  notifyBLECharacteristicValueChange() {
    my.getConnectedBluetoothDevices({
      success: res => {
        if (res.devices.length === 0) {
          my.alert({ content: 'No connected devices' });
          return;
        }
        this.setData({
          devid: res.devices[0].deviceId,
        });

        my.notifyBLECharacteristicValueChange({
          state: true,
          deviceId: this.data.devid,
          serviceId: this.data.serid,
          characteristicId: this.data.notifyId,
          success: () => {

            // Listen for characteristic value changes
            my.onBLECharacteristicValueChange({
              success: res => {

                //  my.alert({content: 'Characteristic value changed: '+JSON.stringify(res)});
                my.alert({ content: 'Response data received = ' + res.value });
              },
            });
            my.alert({ content: 'Listener enabled successfully' });
          },
          fail: error => {
            my.alert({ content: 'Failed to enable listener' + JSON.stringify(error) });
          },
        });
      },
    });
  },
  offBLECharacteristicValueChange() {
    my.offBLECharacteristicValueChange();
  },

  // Other events
  bluetoothAdapterStateChange() {
    my.onBluetoothAdapterStateChange(this.getBind('onBluetoothAdapterStateChange'));
  },
  onBluetoothAdapterStateChange() {
    if (res.error) {
      my.alert({ content: JSON.stringify(error) });
    } else {
      my.alert({ content: 'Local Bluetooth state changed: ' + JSON.stringify(res) });
    }
  },
  offBluetoothAdapterStateChange() {
    my.offBluetoothAdapterStateChange(this.getBind('onBluetoothAdapterStateChange'));
  },
  getBind(name) {
    if (!this[`bind${name}`]) {
      this[`bind${name}`] = this[name].bind(this);
    }
    return this[`bind${name}`];
  },
  BLEConnectionStateChanged() {
    my.onBLEConnectionStateChanged(this.getBind('onBLEConnectionStateChanged'));
  },
  onBLEConnectionStateChanged(res) {
    if (res.error) {
      my.alert({ content: JSON.stringify(error) });
    } else {
      my.alert({ content: 'Connection state changed: ' + JSON.stringify(res) });
    }
  },
  offBLEConnectionStateChanged() {
    my.offBLEConnectionStateChanged(this.getBind('onBLEConnectionStateChanged'));
  },
  onUnload() {
    this.offBLEConnectionStateChanged();
    this.offBLECharacteristicValueChange();
    this.offBluetoothAdapterStateChange();
    this.closeBluetoothAdapter();
  },
});

my.offBluetoothAdapterStateChange

Remove o listener de alterações de estado do Bluetooth local.

Exemplo de código

my.offBluetoothAdapterStateChange();

Passagem de valor de callback

  • Sem a passagem de um valor de callback, todos os listeners deste evento são removidos. Exemplo:

    my.offBluetoothAdapterStateChange();
  • Com a passagem de um valor de callback, apenas o listener correspondente é removido. Exemplo:

    my.offBluetoothAdapterStateChange(this.callback);

Bugs e dicas

  • Dica: Para evitar callbacks duplicados para um evento, chame o método off para remover quaisquer listeners existentes antes de chamar o método on.