my.getBLEDeviceCharacteristics

2020-09-15 15:19 更新

版本要求:支付寶客戶端 10.0.18 或更高版本,若版本較低,建議做 兼容處理。支持 iOS 客戶端,Android 5.0 及以上版本客戶端。

獲取藍(lán)牙設(shè)備所有 characteristic(特征值)。

使用說(shuō)明:建立連接后先執(zhí)行 my.getBLEDeviceServicesmy.getBLEDeviceCharacteristics,再進(jìn)行與藍(lán)牙設(shè)備的數(shù)據(jù)交互。

掃碼體驗(yàn)

藍(lán)牙.jpeg

效果示例

getBluetooth.png

示例代碼

/* .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">獲取讀寫特征</button>
       <button type="primary" onTap="disconnectBLEDevice">斷開(kāi)設(shè)備連接</button>
    </view>
     <view class="page-section-title">讀寫數(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">寫入數(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)之下才能獲取(這里分別篩選出讀寫特征字)
  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ù)屬性匹配讀寫特征字并記錄,然后后面讀寫使用
            this.setData({
              charid: res.characteristics[0].characteristicId,
            });
          },
          fail: error => {
            my.alert({ content: JSON.stringify(error) });
          },
        });
      },
    });
  },


  //讀寫數(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,
          //安卓寫入服務(wù)
          //serviceId:'0000180d-0000-1000-8000-00805f9b34fb',
          //characteristicId:'00002a39-0000-1000-8000-00805f9b34fb',
          value: 'ABCD',
          success: res => {
            my.alert({ content: '寫入數(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>

Object 類型,屬性如下:

屬性 類型 必填 描述
deviceId String 藍(lán)牙設(shè)備 ID,參考 device 對(duì)象。
serviceId String 藍(lán)牙特征值對(duì)應(yīng) service 的 UUID。
success Function 調(diào)用成功的回調(diào)函數(shù)。
fail Function 調(diào)用失敗的回調(diào)函數(shù)。
complete Function 調(diào)用結(jié)束的回調(diào)函數(shù)(調(diào)用成功、失敗都會(huì)執(zhí)行)。

success 回調(diào)函數(shù)

入?yún)?Object 類型,屬性如下:

名稱 類型 描述
characteristics Array 設(shè)備特征值列

characteristic 對(duì)象

藍(lán)牙設(shè)備 characteristic (特征值)信息。

名稱 類型 描述
characteristicId String 藍(lán)牙設(shè)備特征值的 UUID。
serviceId String 藍(lán)牙設(shè)備特征值對(duì)應(yīng)服務(wù)的 UUID。
value Hex String 藍(lán)牙設(shè)備特征值對(duì)應(yīng)的 16 進(jìn)制值。
properties Object 該特征值支持的操作類型。

properties 對(duì)象

名稱 類型 描述
read Boolean 該特征值是否支持 read 操作。
write Boolean 該特征值是否支持 write 操作。
notify Boolean 該特征值是否支持 notify 操作。
indicate Boolean 該特征值是否支持 indicate 操作。
以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

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

編程獅公眾號(hào)