公司是做蓝牙大门锁的,刚开始接手这个项目简直是懵逼。后来自己慢慢的去度娘上找资料,也对蓝牙有了一点自己的理解。蓝牙通信中,首先需要提到的就是 central 和 peripheral 两个概念。这是设备在通信过程中扮演的两种角色。直译过来就是 [中心] 和 [周边(可以理解为外设)] 。iOS 设备既可以作为 central,也可以作为 peripheral,这主要取决于通信需求。下面主要考虑手机作为central的情况。那么,废话不多说,直接进入主题。
"中心"
当手机作为 central 的时候,需要做一系列常见的操作:搜索并连接周围 peripheral,处理 peripheral 提供的数据。手机它的作用就是将结果呈现出来。
"外设"
简单来说就是你iPhone要连接的外部设备,例如小米手环,apple watch(这些设备,在出厂的时候,就已经设置好那些参数了,所以我们就需要再写了)",如有特殊需求可以跟公司的硬件工程师沟通,可以将你需要的参数通过广播传给你。
"服务"
以Apple Watch为例,它一般提供心率检测服务
一个服务中可以包含多个特征
"特征"
脉搏,血压
实现思路
外设
1.打开外部设备的蓝牙
中心
1.打开蓝牙
- (void)viewDidLoad {
[superviewDidLoad];
//一、创建中心("手机")管理者
self.mgr= [[CBCentralManageralloc]initWithDelegate:selfqueue:dispatch_get_main_queue()];
}
2.扫描我周围有哪些可以连接的外设
#pragma mark - CBCentralManagerDelegate
- (void)centralManagerDidUpdateState:(CBCentralManager*)central{
if(central.state==CBCentralManagerStatePoweredOn) {
self.scanPeripheralsBtn.enabled=YES;
}
}
- (IBAction)scanPeripherals:(id)sender {
//开始扫描外设,传nil代表扫描所有外设
[self.mgrscanForPeripheralsWithServices:niloptions:nil];
}
3.连接到其中的某一个外设
- (void)centralManager:(CBCentralManager*)central didDiscoverPeripheral:(CBPeripheral*)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber*)RSSI{
if(![self.peripheralscontainsObject:peripheral]) {
[self.peripheralsaddObject:peripheral];
//刷新表格,展示出来
[self.peripheralTableViewreloadData];
}
}
- (void)tableView:(UITableView*)tableView didSelectRowAtIndexPath:(NSIndexPath*)indexPath{
CBPeripheral*peripheral =self.peripherals[indexPath.row];
//选择了某个外设之后,那么接下来,就要连接到该外设的服务
[self.mgrconnectPeripheral:peripheraloptions:nil];
}
4.连接到外设之后,找外设里面的服务
- (void)centralManager:(CBCentralManager*)central didConnectPeripheral:(CBPeripheral*)peripheral{
//查找所有服务,并且要设置代理,这样才能监听后续的操作
[peripheraldiscoverServices:nil];
//设置代理
peripheral.delegate=self;
}
5.找到我们需要的服务,然后接下来找该服务里面的特征
- (void)peripheral:(CBPeripheral*)peripheral didDiscoverServices:(NSError*)error{
//遍历services
for(CBService*serviceinperipheral.services) {
if([service.UUID.UUIDStringisEqualToString:@"BECF"]) {
//再去查找该服务的特征
[peripheraldiscoverCharacteristics:nilforService:service];
}
}
}
6.以后收发数据,都需要这个特征
- (void)peripheral:(CBPeripheral*)peripheral didDiscoverCharacteristicsForService:(CBService*)service error:(nullableNSError*)error{
//遍历特征
for(CBCharacteristic*characteristicinservice.characteristics) {
if([characteristic.UUID.UUIDStringisEqualToString:@"ABCD"]) {
//查到到特征之后,就可以收发数据了
//赋值
self.currentPeripheral= peripheral;
self.currentCharacteristic= characteristic;
//订阅外设的特征值发生改变之后的通知
[peripheralsetNotifyValue:YESforCharacteristic:characteristic];
}
}
}
网友评论