github demo 下载地址,有问题请评论或者在git上提交问题
1. 用到的类,基本和HomeKit差不多
类名 | 描述 |
---|---|
CBCentralManager | 蓝牙管理,用于扫描和链接蓝牙硬件 |
CBPeripheral | 蓝牙设备 |
CBService | 蓝牙设备的服务 |
CBCharacteristic | 服务的描述特征值 |
2. 步骤
1. 创建管理者CBCentralManager,进行扫描
2. 获得扫描的设备CBPeripheral,进行连接
3. 扫描设备的服务CBService
4. 获取服务的特征值 CBCharacteristic
5. 特征值的读写
6. 断开连接
3. 代码实现
1. 创建管理者,并开始扫描
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;
}
}
2. 在代理中获得,扫描设备
扫描service,遵循代理,走代理方法
- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI{
//这里就加入数组,继续扫描,刷新表
peripheral.delegate = self;
[peripheral discoverServices:nil];
}
3. 扫描到服务,并扫描服务的特征值
-(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);
}
4. 扫描到服务的特征值
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error{
//扫描到service会走这个方法.然后我们监听并接收特征的改变
for (CBCharacteristic *characteristic in service.characteristics){
[peripheral setNotifyValue:YES forCharacteristic:characteristic];
}
}
5. 写属性
[perpher writeValue:theData forCharacteristic:character type:CBCharacteristicWriteWithoutResponse];
4. 上demo
github demo 下载地址,有问题请评论或者在git上提交问题
- demo实现了扫描周围的蓝牙设备,并链接
可以查看的一些特征值
对小米手环
的一些特征值做了识别和处理