ionic中实现BLE的基本功能和注意事项

在项目中安装BLE插件

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

扫描蓝牙设备

  • 扫描蓝牙只能获取到
this.ble.scan([], seconds)

连接蓝牙设备

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

      }, error => {
        
      })

读取特征值有Read的属性的内容

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

写数据

  • 注意:写数据有两种方式,一种是write,一种是writewithoutResponse,当初没有注意这个,导致浪费很多时间。值的一提的是,部分低版本的Android系统(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

  //开始监听一个 特征(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个字节的数据

  • 很多安卓手机对于通过订阅传输的数据是有长度限制的(一般是20)这时候有两种方法来解决这个问题,只有android手机有这个问题,ios手机自己适应,不需要也无法调整mtu
  • 方法1,通过设置mtu的大小,来传输大于20个字节的数据(mtu不是无穷的,是有上限的,具体多少不清楚,每个设备估计都不太一样,这时候可以通过二分查找来确定正确的mtu)
  • 方法2:这里只展示write的方法,writeWithoutResponse只需要替换一下方法就可以了(MAX_DATA_SEND_SIZE根据mtu设置,我的是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 根据实际的特征值的属性来决定 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,如果是特别大的数据 ,可以配合方法1来一起使用

IonicBle数据的转换

  • 通常蓝牙传输的都是字节,而js里对于字节就是通过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的第三方库试试

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 173,242评论 25 708
  • 用两张图告诉你,为什么你的 App 会卡顿? - Android - 掘金 Cover 有什么料? 从这篇文章中你...
    hw1212阅读 12,917评论 2 59
  • 因为自己的项目中有用到了蓝牙相关的功能,所以之前也断断续续地针对蓝牙通信尤其是BLE通信进行了一番探索,整理出了一...
    陈利健阅读 116,424评论 172 297
  • 1、通过CocoaPods安装项目名称项目信息 AFNetworking网络请求组件 FMDB本地数据库组件 SD...
    阳明AGI阅读 16,009评论 3 119
  • 最近在哥哥家,小侄女每天都在看熊出没,今天看到一集是《母爱最伟大》。光头强生病了,熊大熊二一起照顾他,可光头强一直...
    柔雅_阅读 368评论 0 1