美文网首页
ionic中实现BLE的基本功能和注意事项

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

作者: SuperCoderMan | 来源:发表于2018-11-05 20:19 被阅读0次

在项目中安装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的第三方库试试

相关文章

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

    在项目中安装BLE插件 扫描蓝牙设备 扫描蓝牙只能获取到 连接蓝牙设备 读取特征值有Read的属性的内容 写数据 ...

  • Ionic之BLE

    使用到Native的BLE功能; 一、BLE的介绍 BLE是Bluetooth Low Energy的缩写,又叫蓝...

  • ionicpopover

    ionic 中实现Drop Down Menu controller: html:

  • ionic4子页面隐藏tabbar

    在ionic3中,可以通过设置tabsHideOnSubPages: true,实现子页面隐藏tabs。ionic...

  • (蓝牙低功耗)BLE

    BLE 此插件可实现手机与蓝牙低功耗(BLE)外设之间的通信。该插件为iOS和Android提供了一个简单的Jav...

  • ionic-native-transitions调用原生页面切换

    ionic-native-transitions调用原生页面切换实现ionic路由切换,让你的ionic应用比原生...

  • Ionic4与Ionic3部分比较

    有较长时间没有用Ionic了,见新的公众号需求比较简单,便决定使用Ionic4来实现。 其实,Ionic2和Ion...

  • BLE简介及原理

    一.BLE简介 1.BLE是BluetoothLowEnergy的缩写,又叫蓝牙4.0,主要用于实现移动智能终端与...

  • iOS 录音与播放

    实现思路 利用系统框架AVFoundation实现录音和录音播放 注意事项 在Info.plist文件中添加如下代...

  • 实现字典和模型的自动转换

    实现原理 通过获取类的属性,填充和读取数据 代码实现 注意事项 swift4.0中继承 NSObject 的 sw...

网友评论

      本文标题:ionic中实现BLE的基本功能和注意事项

      本文链接:https://www.haomeiwen.com/subject/ayhexqtx.html