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

2018-11-05  本文已影响0人  SuperCoderMan

在项目中安装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

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个字节的数据

 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;

IonicBle数据的转换

  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;
  }
  static ab2strWithUint8Array(buf: ArrayBuffer) {
    return String.fromCharCode.apply(null, new Uint8Array(buf));
  }
  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的第三方库试试

上一篇下一篇

猜你喜欢

热点阅读