github demo 下载地址,有问题请评论或者在git上提交问题
类名 | 描述 |
---|---|
CBCentralManager | 蓝牙管理,用于扫描和链接蓝牙硬件 |
CBPeripheral | 蓝牙设备 |
CBService | 蓝牙设备的服务 |
CBCharacteristic | 服务的描述特征值 |
1. 创建管理者CBCentralManager,进行扫描
2. 获得扫描的设备CBPeripheral,进行连接
3. 扫描设备的服务CBService
4. 获取服务的特征值 CBCharacteristic
5. 特征值的读写
6. 断开连接
CBCentralManager *blueToothManager = [[CBCentralManager alloc]initWithDelegate:self queue:nil];
[blueToothManager scanForPeripheralsWithServices:nil options:nil];
这个时候系统会自动提示打开蓝牙,不需要我们操作
- (void)centralManagerDidUpdateState:(CBCentralManager *)central{
switch (central.state) {
case CBManagerStateUnknown:
NSLog(@">>>CBCentralManagerStateUnknown");
break;
case CBManagerStateResetting:
NSLog(@">>>CBCentralManagerStateResetting");
break;
case CBManagerStateUnsupported:
NSLog(@">>>CBCentralManagerStateUnsupported");
break;
case CBManagerStateUnauthorized:
NSLog(@">>>CBCentralManagerStateUnauthorized");
break;
case CBManagerStatePoweredOff:
//如果是关闭,系统会提示打开,我们不用管
NSLog(@">>>CBCentralManagerStatePoweredOff");
break;
case CBManagerStatePoweredOn:
//打开的
NSLog(@">>>CBCentralManagerStatePoweredOn");
break;
default:
break;
}
}
扫描service,遵循代理,走代理方法
- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI{
//这里就加入数组,继续扫描,刷新表
peripheral.delegate = self;
[peripheral discoverServices:nil];
}
-(void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error{
if (error){
NSLog(@"扫描外设服务出错:%@-> %@", peripheral.name, [error localizedDescription]);
return;
}
NSLog(@"扫描到外设服务:%@ -> %@",peripheral.name,peripheral.services);
for (CBService *service in peripheral.services) {
[peripheral discoverCharacteristics:nil forService:service];
//添加到数组
//[self.serviceArray addObject:service];
}
NSLog(@"开始扫描外设服务的特征 %@...",peripheral.name);
}
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error{
//扫描到service会走这个方法.然后我们监听并接收特征的改变
for (CBCharacteristic *characteristic in service.characteristics){
[peripheral setNotifyValue:YES forCharacteristic:characteristic];
}
}
[perpher writeValue:theData forCharacteristic:character type:CBCharacteristicWriteWithoutResponse];
github demo 下载地址,有问题请评论或者在git上提交问题
小米手环
的一些特征值做了识别和处理