關於IOS客戶端向藍牙設備發送數據的坑,近幾天本小白在做公司一個項目是關於藍牙的。卡到了客戶端向藍牙設備發送十六進制數據這里,先說一下向藍牙發送數據的時候遇到的問題。
1.向藍牙的哪個特征發送數據
2.數據轉換的問題
3.藍牙設備發送數據后的回調
1.向藍牙的哪個特征發送數據
我們在向藍牙設備發送數據的時候,一定要告訴藍牙設備給你哪個特征發送數據。舉個簡單的例子:我們向A說啦啦啦德瑪西亞。我們就要想,我要說一段話內容是啦啦啦德瑪西亞,我們還要知道說給誰,不能說給空氣吧,得告訴A啊。(我就是這里卡了一段時間。。。)
上代碼
//掃描到Characteristics
-(void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error{
if (error)
{
NSLog(@"error Discovered characteristics for %@ with error: %@", service.UUID, [error localizedDescription]);
return;
}
for (CBCharacteristic *characteristic in service.characteristics)
{
[peripheral readValueForCharacteristic:characteristic];
NSLog(@"characteristic= %@",characteristic);
[peripheral discoverDescriptorsForCharacteristic:characteristic];
NSLog(@"Characteristic的Descriptors =%@",characteristic);
//characteristic.UUID 的包含1001的話就把characteristic賦值給self.cbchar
if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:@"1001"]]) {
self.cbchar = characteristic;
[self.cbperipheral setNotifyValue:YES forCharacteristic:characteristic];
}
}
}
2.數據轉換的問題
數據轉換的問題是這樣,我們發送的藍牙數據是一個數據包前三位是固定的所以前三位先不管,但是我們后面的數據是需要去獲取的,需要獲取系統的當前時間和 chensum(前三位+時間 = chensum)我是這樣解決的
NSDate *date = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"YY-MM-dd-hh-mm"];
NSString *dateString = [dateFormatter stringFromDate:date];
NSArray *time_strs = [dateString componentsSeparatedByString:@"-"];
NSLog(@"time_strs = %@",time_strs);
int num3 =[time_strs[0] intValue];
int num4 =[time_strs[1] intValue];
int num5 =[time_strs[2] intValue];
int num6 =[time_strs[3] intValue];
int num7 =[time_strs[4] intValue];
//后三位90-11-5是把CMD_HEAD CMD_LENGHT CMD_SORT 轉成的10進制
int num8 = num3 + num4 +num5 +num6 +num7 +90+11+5;
Byte CMD_HEAD = 0x5A;
Byte CMD_LENGHT = 0x0B;
Byte CMD_SORT = 0x05;
Byte byte4[] = {CMD_HEAD,CMD_LENGHT,CMD_SORT,num3,num4,num5,num6,num7,num8,0,0};
NSData *data23 = [NSData dataWithBytes:byte4 length:sizeof(byte4)];
3.藍牙設備發送數據后的回調
發送數據后會有一個回調可以打印一下看看有沒有進到這個方法,如果進入成功,進成功就ok了如果erro了就看看打印的錯誤信息是什么
//寫入數據后的回調
- (void)peripheral:(CBPeripheral *)peripheral
didWriteValueForCharacteristic:(CBCharacteristic *)
characteristic error:(nullable NSError *)error
{
[self.cbperipheral readValueForCharacteristic:self.cbchar];
if (error) {
NSLog(@"%s, line = %d, erro = %@",__FUNCTION__,__LINE__,error.description);
}
}
