ionic中實現(xiàn)BLE的基本功能和注意事項

在項目中安裝BLE插件

ionic cordova plugin add cordova-plugin-ble-central
npm install --save @ionic-native/ble

掃描藍牙設(shè)備

  • 掃描藍牙只能獲取到
this.ble.scan([], seconds)

連接藍牙設(shè)備

      this.connect(deviceId).subscribe(device => {

      }, error => {
        
      })

讀取特征值有Read的屬性的內(nèi)容

this.ble.read(deviceId, servieUUID, cbaracteristicUUID)

寫數(shù)據(jù)

  • 注意:寫數(shù)據(jù)有兩種方式,一種是write,一種是writewithoutResponse,當(dāng)初沒有注意這個,導(dǎo)致浪費很多時間。值的一提的是,部分低版本的Android系統(tǒng)(Android 4.0,5.0,6.0) 似乎不支持writewithoutResponse,所以建議盡量用write方法

write

this.ble.write(deviceId, serviceUUID, characteristicUUID, value)

writeWithoutResponse

this.ble.writeWithoutResponse(deviceId, serviceUUID, characteristicUUID, value)

startNotification

  //開始監(jiān)聽一個 特征(characteristic)的變化
  startNotification(deviceId: string, serviceUUID: string, characteristicUUID: string): Observable<any> {
    return this.ble.startNotification(deviceId, serviceUUID, characteristicUUID)
  }

 requestMtu(deviceId: string, mtuSize: number): Promise<any>;

如何支持寫長度大于20個字節(jié)的數(shù)據(jù)

  • 很多安卓手機對于通過訂閱傳輸?shù)臄?shù)據(jù)是有長度限制的(一般是20)這時候有兩種方法來解決這個問題,只有android手機有這個問題,ios手機自己適應(yīng),不需要也無法調(diào)整mtu
  • 方法1,通過設(shè)置mtu的大小,來傳輸大于20個字節(jié)的數(shù)據(jù)(mtu不是無窮的,是有上限的,具體多少不清楚,每個設(shè)備估計都不太一樣,這時候可以通過二分查找來確定正確的mtu)
  • 方法2:這里只展示write的方法,writeWithoutResponse只需要替換一下方法就可以了(MAX_DATA_SEND_SIZE根據(jù)mtu設(shè)置,我的是20)
 writeLargeData(bleDevice, service_uuid, characteristic_uuid, buffer) {
    return new Promise((resolve, reject) => {
      console.log('writeLargeData', buffer.byteLength, 'bytes in', MAX_DATA_SEND_SIZE, 'byte chunks.');
      let chunkCount = Math.ceil(buffer.byteLength / MAX_DATA_SEND_SIZE);
      let index = 0;
      let sendChunk = () => {
        if (!chunkCount) {
          console.log("Transfer Complete" + 'deviceId ', bleDevice.id, 'service_uuid', service_uuid, 'characteristic_uuid', characteristic_uuid,
            'buffer', buffer, 'bufferStr', StringUtil.ab2strForBle(buffer));
          resolve('Transfer Complete');
          return; // so we don't send an empty buffer
        }
        let chunk = buffer.slice(index, index + MAX_DATA_SEND_SIZE);
        index += MAX_DATA_SEND_SIZE;
        chunkCount--;
        //todo 根據(jù)實際的特征值的屬性來決定 write 的方法
        //遍歷 characteristics 尋找write方法
        if (!bleDevice || !bleDevice.characteristics) {
          reject('the bleDevice is incorrect')
          return
        }
                 console.log('writeLargeData sendChunk isWrite')
          this.ble.write(bleDevice.id, service_uuid, characteristic_uuid, chunk).then(writeWithoutResponseResult => {
            sendChunk()
          }, error => {
            console.error('writeLargeData writeWithoutResponse failed ' + error);
            reject(error);
          })
      }
      // send the first chunk
      sendChunk();
    })
  }
export const MAX_DATA_SEND_SIZE = 20;
  • 我只使用了方法2,如果是特別大的數(shù)據(jù) ,可以配合方法1來一起使用

IonicBle數(shù)據(jù)的轉(zhuǎn)換

  • 通常藍牙傳輸?shù)亩际亲止?jié),而js里對于字節(jié)就是通過ArrayBuffer來支持的。這里就不展開討論ArrayBuffer了,展開了我也說不清楚。
  • str2abWithUint8Array
  static str2abWithUint8Array(str): ArrayBuffer {
    let buf = new ArrayBuffer(str.length * 1); // 1 bytes for each char
    let bufView = new Uint8Array(buf);
    //todo 判斷字符是否是中文,然后改成 /u 的格式
    for (var i = 0, strLen = str.length; i < strLen; i++) {
      bufView[i] = str.charCodeAt(i);
    }
    return bufView.buffer;
  }
  • ab2strWithUint8Array
  static ab2strWithUint8Array(buf: ArrayBuffer) {
    return String.fromCharCode.apply(null, new Uint8Array(buf));
  }
  • concatArrayBuffer
  static concatArrayBuffer(a: ArrayBuffer, b: ArrayBuffer): ArrayBuffer { // a, b TypedArray of same type
    let aUint8ArrayBuffer = new Uint8Array(a)
    let bUint8ArrayBuffer = new Uint8Array(b)

    var c = new Uint8Array(a.byteLength + b.byteLength);
    c.set(aUint8ArrayBuffer, 0);
    c.set(bUint8ArrayBuffer, a.byteLength);
    return c.buffer;
  }

提示:如果想支持中文字符可以用:text-encoding這個npm的第三方庫試試

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 179,161評論 25 708
  • 用兩張圖告訴你,為什么你的 App 會卡頓? - Android - 掘金 Cover 有什么料? 從這篇文章中你...
    hw1212閱讀 14,041評論 2 59
  • 因為自己的項目中有用到了藍牙相關(guān)的功能,所以之前也斷斷續(xù)續(xù)地針對藍牙通信尤其是BLE通信進行了一番探索,整理出了一...
    陳利健閱讀 119,648評論 172 300
  • 1、通過CocoaPods安裝項目名稱項目信息 AFNetworking網(wǎng)絡(luò)請求組件 FMDB本地數(shù)據(jù)庫組件 SD...
    陽明AI閱讀 16,211評論 3 119
  • 最近在哥哥家,小侄女每天都在看熊出沒,今天看到一集是《母愛最偉大》。光頭強生病了,熊大熊二一起照顧他,可光頭強一直...
    柔雅_閱讀 419評論 0 1

友情鏈接更多精彩內(nèi)容