github demo 下載地址,有問題請(qǐng)?jiān)u論或者在git上提交問題
1. 用到的類,基本和HomeKit差不多
類名 | 描述 |
---|---|
CBCentralManager | 藍(lán)牙管理,用于掃描和鏈接藍(lán)牙硬件 |
CBPeripheral | 藍(lán)牙設(shè)備 |
CBService | 藍(lán)牙設(shè)備的服務(wù) |
CBCharacteristic | 服務(wù)的描述特征值 |
2. 步驟
1. 創(chuàng)建管理者CBCentralManager,進(jìn)行掃描
2. 獲得掃描的設(shè)備CBPeripheral,進(jìn)行連接
3. 掃描設(shè)備的服務(wù)CBService
4. 獲取服務(wù)的特征值 CBCharacteristic
5. 特征值的讀寫
6. 斷開連接
3. 代碼實(shí)現(xiàn)
1. 創(chuàng)建管理者,并開始掃描
CBCentralManager *blueToothManager = [[CBCentralManager alloc]initWithDelegate:self queue:nil];
[blueToothManager scanForPeripheralsWithServices:nil options:nil];
這個(gè)時(shí)候系統(tǒng)會(huì)自動(dòng)提示打開藍(lán)牙,不需要我們操作
獲取到鏈接狀態(tài)
- (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:
//如果是關(guān)閉,系統(tǒng)會(huì)提示打開,我們不用管
NSLog(@">>>CBCentralManagerStatePoweredOff");
break;
case CBManagerStatePoweredOn:
//打開的
NSLog(@">>>CBCentralManagerStatePoweredOn");
break;
default:
break;
}
}
2. 在代理中獲得,掃描設(shè)備
掃描service,遵循代理,走代理方法
- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI{
//這里就加入數(shù)組,繼續(xù)掃描,刷新表
peripheral.delegate = self;
[peripheral discoverServices:nil];
}
3. 掃描到服務(wù),并掃描服務(wù)的特征值
-(void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error{
if (error){
NSLog(@"掃描外設(shè)服務(wù)出錯(cuò):%@-> %@", peripheral.name, [error localizedDescription]);
return;
}
NSLog(@"掃描到外設(shè)服務(wù):%@ -> %@",peripheral.name,peripheral.services);
for (CBService *service in peripheral.services) {
[peripheral discoverCharacteristics:nil forService:service];
//添加到數(shù)組
//[self.serviceArray addObject:service];
}
NSLog(@"開始掃描外設(shè)服務(wù)的特征 %@...",peripheral.name);
}
4. 掃描到服務(wù)的特征值
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error{
//掃描到service會(huì)走這個(gè)方法.然后我們監(jiān)聽并接收特征的改變
for (CBCharacteristic *characteristic in service.characteristics){
[peripheral setNotifyValue:YES forCharacteristic:characteristic];
}
}
5. 寫屬性
[perpher writeValue:theData forCharacteristic:character type:CBCharacteristicWriteWithoutResponse];
4. 上demo
github demo 下載地址,有問題請(qǐng)?jiān)u論或者在git上提交問題
- demo實(shí)現(xiàn)了掃描周圍的藍(lán)牙設(shè)備,并鏈接
可以查看的一些特征值
對(duì)小米手環(huán)
的一些特征值做了識(shí)別和處理