藍(lán)牙開發(fā)注意:
1.藍(lán)牙分包發(fā)送 (超過20個字節(jié)需要進(jìn)行分包)
參考:http://www.reibang.com/p/5f1e92adfaa0 http://www.reibang.com/p/29bd630077b4
2.分包接收(需要與外設(shè)進(jìn)行字節(jié)協(xié)議處理)
思路:收到的數(shù)據(jù)流第一個字節(jié)作為標(biāo)志位棋凳,01表示開始恬汁,10表示繼續(xù)猎莲,00表示結(jié)束
- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error{
NSData *data = characteristic.value;//接收到的二進(jìn)制數(shù)據(jù)流
if (data.length == 0) {//如果沒有數(shù)據(jù)則忽視
return;
}
NSData *subData = [data subdataWithRange:NSMakeRange(0, 1)];//標(biāo)志位:0x01表示開始 0x10表示繼續(xù) 0x00表示結(jié)束
NSData *reallyData = [data subdataWithRange:NSMakeRange(1, data.length - 1)];//真正的數(shù)據(jù)流
//轉(zhuǎn)換為標(biāo)志位的第一個字節(jié)
Byte *flagByte = (Byte *)[subData bytes];
UInt16 flag = flagByte[0];
//分包接收
if (flag == START_BYTE) {//0x01代表開始
_receiveData = [NSMutableData data];
[_receiveData appendData:reallyData];
}else if(flag == CONTINUE_BYTE){//0x10代表繼續(xù)
[_receiveData appendData:reallyData];
}else if(flag == END_BYTE){//0x00代表結(jié)束
[_receiveData appendData:reallyData];
[[self delegate] bleDidReceiveData:_receiveData length:(int)characteristic.value.length];//代理回調(diào)
}
}
3.不中斷掃描周邊指定的服務(wù)顶瞳,達(dá)到的效果有粪滤,只搜索約定好的外設(shè)類型缎谷,如某一公司的藍(lán)牙設(shè)備
NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES], CBCentralManagerScanOptionAllowDuplicatesKey, nil];
//針對指定的服務(wù)特征值進(jìn)行搜索
[self.CM scanForPeripheralsWithServices:@[[CBUUID UUIDWithString:SERVICE_UUID]] options:options];
4.如果要達(dá)到靠近設(shè)備即連接派撕,需要根據(jù)RSSI值計算手機(jī)與藍(lán)牙設(shè)備的距離
https://jingyan.baidu.com/article/2d5afd69c926b185a2e28e1f.html (此處公式比較靠譜)