my.onBluetoothDeviceFound

2020-09-15 15:21 更新

版本需求:支付寶客戶端 10.0.18 或更高版本,若版本較低,建議做 兼容處理。

注意:IDE 模擬器暫不支持調(diào)試,請(qǐng)以真機(jī)調(diào)試結(jié)果為準(zhǔn)。

搜索到新的藍(lán)牙設(shè)備時(shí)觸發(fā)此事件。

使用說(shuō)明

  • 模擬器可能無(wú)法獲取 advertisData 及 RSSI ,請(qǐng)使用真機(jī)調(diào)試。
  • 開(kāi)發(fā)者工具(IDE)和 Android 上獲取到的 deviceId 為設(shè)備 MAC 地址,iOS 上則為設(shè)備 UUID。因此 deviceId 不能硬編碼到代碼中,需要分平臺(tái)處理。iOS 可根據(jù)設(shè)備屬性(localName/advertisData/manufacturerData 等)進(jìn)行動(dòng)態(tài)匹配。
  • 若在 my.onBluetoothDeviceFound 回調(diào)中包含了某個(gè)藍(lán)牙設(shè)備,則此設(shè)備會(huì)添加到 my.getBluetoothDevices 接口獲取到的數(shù)組中。

示例代碼

/* .acss */
.help-info {
  padding:10px;
  color:#000000;
}
.help-title {
  padding:10px;
  color:#FC0D1B;
}
// .json
{
    "defaultTitle": "Bluetooth"
}
<!-- .axml-->
<view class="page">
  <view class="page-description">藍(lán)牙 API</view>
  <view class="page-section">
    <view class="page-section-title">本機(jī)藍(lán)牙開(kāi)關(guān)狀態(tài)</view>
    <view class="page-section-demo">
       <button type="primary" onTap="openBluetoothAdapter">初始化藍(lán)牙</button>
       <button type="primary" onTap="closeBluetoothAdapter">關(guān)閉本機(jī)藍(lán)牙</button>
       <button type="primary" onTap="getBluetoothAdapterState">獲取藍(lán)牙狀態(tài)</button>
    </view>
    <view class="page-section-title">掃描藍(lán)牙設(shè)備</view>
    <view class="page-section-demo">
       <button type="primary" onTap="startBluetoothDevicesDiscovery">開(kāi)始搜索</button>
       <button type="primary" onTap="getBluetoothDevices">所有搜索到的設(shè)備</button>
       <button type="primary" onTap="getConnectedBluetoothDevices">所有已連接的設(shè)備</button>
       <button type="primary" onTap="stopBluetoothDevicesDiscovery">停止搜索</button>
    </view>
    <view class="page-section-title">連接設(shè)備</view>
    <view class="page-section-demo">
       <input class="input" onInput="bindKeyInput" type="{{text}}" placeholder="輸入要連接的設(shè)備的deviceId"></input>
       <button type="primary" onTap="connectBLEDevice">連接設(shè)備</button>
       <button type="primary" onTap="getBLEDeviceServices">獲取設(shè)備服務(wù)</button>
       <button type="primary" onTap="getBLEDeviceCharacteristics">獲取讀寫(xiě)特征</button>
       <button type="primary" onTap="disconnectBLEDevice">斷開(kāi)設(shè)備連接</button>
    </view>
     <view class="page-section-title">讀寫(xiě)數(shù)據(jù)</view>
     <view class="page-section-demo">
       <button type="primary" onTap="notifyBLECharacteristicValueChange">監(jiān)聽(tīng)特征值數(shù)據(jù)變化</button>
       <button type="primary" onTap="readBLECharacteristicValue">讀取數(shù)據(jù)</button>
       <button type="primary" onTap="writeBLECharacteristicValue">寫(xiě)入數(shù)據(jù)</button>
       <button type="primary" onTap="offBLECharacteristicValueChange">取消特征值監(jiān)聽(tīng)</button>
    </view>
     <view class="page-section-title">其他事件</view>
     <view class="page-section-demo">
       <button type="primary" onTap="bluetoothAdapterStateChange">本機(jī)藍(lán)牙狀態(tài)變化</button>
       <button type="primary" onTap="offBluetoothAdapterStateChange">取消本機(jī)藍(lán)牙狀態(tài)監(jiān)聽(tīng)</button>
       <button type="primary" onTap="BLEConnectionStateChanged">藍(lán)牙連接狀態(tài)變化</button>
       <button type="primary" onTap="offBLEConnectionStateChanged">取消藍(lán)牙連接狀態(tài)監(jiān)聽(tīng)</button>

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


  //獲取本機(jī)藍(lán)牙開(kāi)關(guān)狀態(tài)
  openBluetoothAdapter() {
    my.openBluetoothAdapter({
      success: res => {
        if (!res.isSupportBLE) {
          my.alert({ content: '抱歉,您的手機(jī)藍(lán)牙暫不可用' });
          return;
        }
        my.alert({ content: '初始化成功!' });
      },
      fail: error => {
        my.alert({ content: JSON.stringify(error) });
      },
    });
  },
  closeBluetoothAdapter() {
    my.closeBluetoothAdapter({
      success: () => {
        my.alert({ content: '關(guān)閉藍(lán)牙成功!' });
      },
      fail: error => {
        my.alert({ content: JSON.stringify(error) });
      },
    });
  },
  getBluetoothAdapterState() {
    my.getBluetoothAdapterState({
      success: res => {
        if (!res.available) {
          my.alert({ content: '抱歉,您的手機(jī)藍(lán)牙暫不可用' });
          return;
        }
        my.alert({ content: JSON.stringify(res) });
      },
      fail: error => {
        my.alert({ content: JSON.stringify(error) });
      },
    });
  },


  //掃描藍(lán)牙設(shè)備
  startBluetoothDevicesDiscovery() {
    my.startBluetoothDevicesDiscovery({
      allowDuplicatesKey: false,
      success: () => {
        my.onBluetoothDeviceFound({
          success: res => {


            // my.alert({content:'監(jiān)聽(tīng)新設(shè)備'+JSON.stringify(res)});
            var deviceArray = res.devices;
            for (var i = deviceArray.length - 1; i >= 0; i--) {
              var deviceObj = deviceArray[i];


              //通過(guò)設(shè)備名稱或者廣播數(shù)據(jù)匹配目標(biāo)設(shè)備,然后記錄deviceID后面使用
              if (deviceObj.name == this.data.name) {
                my.alert({ content: '目標(biāo)設(shè)備被找到' });
                my.offBluetoothDeviceFound();
                this.setData({
                  deviceId: deviceObj.deviceId,
                });
                break;
              }
            }
          },
          fail: error => {
            my.alert({ content: '監(jiān)聽(tīng)新設(shè)備失敗' + JSON.stringify(error) });
          },
        });
      },
      fail: error => {
        my.alert({ content: '啟動(dòng)掃描失敗' + JSON.stringify(error) });
      },
    });
  },


  //停止掃描
  stopBluetoothDevicesDiscovery() {
    my.stopBluetoothDevicesDiscovery({
      success: res => {
        my.offBluetoothDeviceFound();
        my.alert({ content: '操作成功!' });
      },
      fail: error => {
        my.alert({ content: JSON.stringify(error) });
      },
    });
  },


  //獲取正在連接中的設(shè)備
  getConnectedBluetoothDevices() {
    my.getConnectedBluetoothDevices({
      success: res => {
        if (res.devices.length === 0) {
          my.alert({ content: '沒(méi)有在連接中的設(shè)備!' });
          return;
        }
        my.alert({ content: JSON.stringify(res) });
        devid = res.devices[0].deviceId;
      },
      fail: error => {
        my.alert({ content: JSON.stringify(error) });
      },
    });
  },


  //獲取所有搜索到的設(shè)備
  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,
    });
  },


  //連接設(shè)備
  connectBLEDevice() {
    my.connectBLEDevice({
      deviceId: this.data.devid,
      success: res => {
        my.alert({ content: '連接成功' });
      },
      fail: error => {
        my.alert({ content: JSON.stringify(error) });
      },
    });
  },


  //斷開(kāi)連接
  disconnectBLEDevice() {
    my.disconnectBLEDevice({
      deviceId: this.data.devid,
      success: () => {
        my.alert({ content: '斷開(kāi)連接成功!' });
      },
      fail: error => {
        my.alert({ content: JSON.stringify(error) });
      },
    });
  },


  //獲取連接設(shè)備的server,必須要再連接狀態(tài)狀態(tài)之下才能獲取
  getBLEDeviceServices() {
    my.getConnectedBluetoothDevices({
      success: res => {
        if (res.devices.length === 0) {
          my.alert({ content: '沒(méi)有已連接的設(shè)備' });
          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) });
          },
        });
      },
    });
  },


  //獲取連接設(shè)備的charid,必須要再連接狀態(tài)狀態(tài)之下才能獲?。ㄟ@里分別篩選出讀寫(xiě)特征字)
  getBLEDeviceCharacteristics() {
    my.getConnectedBluetoothDevices({
      success: res => {
        if (res.devices.length === 0) {
          my.alert({ content: '沒(méi)有已連接的設(shè)備' });
          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) });


            //特征字對(duì)象屬性見(jiàn)文檔,根據(jù)屬性匹配讀寫(xiě)特征字并記錄,然后后面讀寫(xiě)使用
            this.setData({
              charid: res.characteristics[0].characteristicId,
            });
          },
          fail: error => {
            my.alert({ content: JSON.stringify(error) });
          },
        });
      },
    });
  },


  //讀寫(xiě)數(shù)據(jù)
  readBLECharacteristicValue() {
    my.getConnectedBluetoothDevices({
      success: res => {
        if (res.devices.length === 0) {
          my.alert({ content: '沒(méi)有已連接的設(shè)備' });
          return;
        }
        this.setData({
          devid: res.devices[0].deviceId,
        });
        my.readBLECharacteristicValue({
          deviceId: this.data.devid,
          serviceId: this.data.serid,
          characteristicId: this.data.notifyId,


          //1、安卓讀取服務(wù)
          // 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: '讀取失敗' + JSON.stringify(error) });
          },
        });
      },
    });
  },
  writeBLECharacteristicValue() {
    my.getConnectedBluetoothDevices({
      success: res => {
        if (res.devices.length === 0) {
          my.alert({ content: '沒(méi)有已連接的設(shè)備' });
          return;
        }
        this.setData({
          devid: res.devices[0].deviceId,
        });
        my.writeBLECharacteristicValue({
          deviceId: this.data.devid,
          serviceId: this.data.serid,
          characteristicId: this.data.charid,


          //安卓寫(xiě)入服務(wù)
          //serviceId:'0000180d-0000-1000-8000-00805f9b34fb',
          //characteristicId:'00002a39-0000-1000-8000-00805f9b34fb',
          value: 'ABCD',
          success: res => {
            my.alert({ content: '寫(xiě)入數(shù)據(jù)成功!' });
          },
          fail: error => {
            my.alert({ content: JSON.stringify(error) });
          },
        });
      },
    });
  },
  notifyBLECharacteristicValueChange() {
    my.getConnectedBluetoothDevices({
      success: res => {
        if (res.devices.length === 0) {
          my.alert({ content: '沒(méi)有已連接的設(shè)備' });
          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: () => {


            //監(jiān)聽(tīng)特征值變化的事件
            my.onBLECharacteristicValueChange({
              success: res => {


                //  my.alert({content: '特征值變化:'+JSON.stringify(res)});
                my.alert({ content: '得到響應(yīng)數(shù)據(jù) = ' + res.value });
              },
            });
            my.alert({ content: '監(jiān)聽(tīng)成功' });
          },
          fail: error => {
            my.alert({ content: '監(jiān)聽(tīng)失敗' + JSON.stringify(error) });
          },
        });
      },
    });
  },
  offBLECharacteristicValueChange() {
    my.offBLECharacteristicValueChange();
  },


  //其他事件
  bluetoothAdapterStateChange() {
    my.onBluetoothAdapterStateChange(this.getBind('onBluetoothAdapterStateChange'));
  },
  onBluetoothAdapterStateChange() {
    if (res.error) {
      my.alert({ content: JSON.stringify(error) });
    } else {
      my.alert({ content: '本機(jī)藍(lán)牙狀態(tài)變化:' + 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: '連接狀態(tài)變化:' + JSON.stringify(res) });
    }
  },
  offBLEConnectionStateChanged() {
    my.offBLEConnectionStateChanged(this.getBind('onBLEConnectionStateChanged'));
  },
  onUnload() {
    this.offBLEConnectionStateChanged();
    this.offBLECharacteristicValueChange();
    this.offBluetoothAdapterStateChange();
    this.closeBluetoothAdapter();
  },
});

入?yún)?/h2>

Function 類型。callback 回調(diào)函數(shù)的入?yún)?Object 類型,屬性如下:

名稱 類型 描述
devices Array 新搜索到的設(shè)備列表。

device 對(duì)象

名稱 類型 描述
name String 藍(lán)牙設(shè)備名稱,某些設(shè)備可能沒(méi)有。
deviceName(兼容舊版本) String 值與 name 一致。
localName String 廣播設(shè)備名稱。
deviceId String 設(shè)備 ID。
RSSI Number 設(shè)備信號(hào)強(qiáng)度。
advertisData Hex String 設(shè)備的廣播內(nèi)容。
以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)