在項目中安裝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的第三方庫試試