关于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);
}
}