bear-zyy

iOS蓝牙

ios开发之蓝牙

一、作为外围设备开发

1、开启蓝牙会调用这个方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
//peripheralManager状态改变
- (void)peripheralManagerDidUpdateState:(CBPeripheralManager *)peripheral{
switch (peripheral.state) {
//在这里判断蓝牙设别的状态 当开启了则可调用 setUp方法(自定义)
case CBPeripheralManagerStatePoweredOn:
NSLog(@"powered on");
[self setUp];
break;
case CBPeripheralManagerStatePoweredOff:
NSLog(@"powered off");
break;
default:
break;
}
}

2、打开peripheral manager ,设置它的委托

1
peripheralManager = [[CBPeripheralManager alloc]initWithDelegate:self queue:nil];

3、创建characteristics,创建service,把characteristics 添加到service中,把service添加到peripheral manager中,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
-(void)setUp{
//characteristics字段描述
CBUUID *CBUUIDCharacteristicUserDescriptionStringUUID = [CBUUID UUIDWithString:CBUUIDCharacteristicUserDescriptionString];
/*
可以通知的Characteristic
properties:CBCharacteristicPropertyNotify
permissions CBAttributePermissionsReadable
*/
CBMutableCharacteristic *notiyCharacteristic = [[CBMutableCharacteristic alloc]initWithType:[CBUUID UUIDWithString:notiyCharacteristicUUID] properties:CBCharacteristicPropertyNotify value:nil permissions:CBAttributePermissionsReadable];
/*
可读写的characteristics
properties:CBCharacteristicPropertyWrite | CBCharacteristicPropertyRead
permissions CBAttributePermissionsReadable | CBAttributePermissionsWriteable
*/
CBMutableCharacteristic *readwriteCharacteristic = [[CBMutableCharacteristic alloc]initWithType:[CBUUID UUIDWithString:readwriteCharacteristicUUID] properties:CBCharacteristicPropertyWrite | CBCharacteristicPropertyRead value:nil permissions:CBAttributePermissionsReadable | CBAttributePermissionsWriteable];
//设置description
CBMutableDescriptor *readwriteCharacteristicDescription1 = [[CBMutableDescriptor alloc]initWithType: CBUUIDCharacteristicUserDescriptionStringUUID value:@"bear-zyy"];
[readwriteCharacteristic setDescriptors:@[readwriteCharacteristicDescription1]];
/*
只读的Characteristic
properties:CBCharacteristicPropertyRead
permissions CBAttributePermissionsReadable
*/
CBMutableCharacteristic *readCharacteristic = [[CBMutableCharacteristic alloc]initWithType:[CBUUID UUIDWithString:readCharacteristicUUID] properties:CBCharacteristicPropertyRead value:nil permissions:CBAttributePermissionsReadable];
//service1初始化并加入两个characteristics
CBMutableService *service1 = [[CBMutableService alloc]initWithType:[CBUUID UUIDWithString:ServiceUUID1] primary:YES];
NSLog(@"%@",service1.UUID);
[service1 setCharacteristics:@[notiyCharacteristic,readwriteCharacteristic]];
// [service1 setCharacteristics:@[readwriteCharacteristic]];
//service2初始化并加入一个characteristics
CBMutableService *service2 = [[CBMutableService alloc]initWithType:[CBUUID UUIDWithString:ServiceUUID2] primary:YES];
[service2 setCharacteristics:@[readCharacteristic]];
//添加后就会调用代理的- (void)peripheralManager:(CBPeripheralManager *)peripheral didAddService:(CBService *)service error:(NSError *)error
[peripheralManager addService:service1];
[peripheralManager addService:service2];
}

4、开启广播advertising

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
//perihpheral添加了service
- (void)peripheralManager:(CBPeripheralManager *)peripheral didAddService:(CBService *)service error:(NSError *)error{
// if (error == nil) {
// serviceNum++;
// }
// //因为我们添加了2个服务,所以想两次都添加完成后才去发送广播
//// if (serviceNum==2) {
// //添加服务后可以在此向外界发出通告 调用完这个方法后会调用代理的
// //(void)peripheralManagerDidStartAdvertising:(CBPeripheralManager *)peripheral error:(NSError *)error
[peripheralManager startAdvertising:@{
CBAdvertisementDataServiceUUIDsKey : @[[CBUUID UUIDWithString:ServiceUUID1],[CBUUID UUIDWithString:ServiceUUID2]],
CBAdvertisementDataLocalNameKey : @"bear-zyy"
}
];
// }
}
//peripheral开始发送advertising
- (void)peripheralManagerDidStartAdvertising:(CBPeripheralManager *)peripheral error:(NSError *)error{
NSLog(@"in peripheralManagerDidStartAdvertisiong");
}

5、对central的操作进行响应
5.1 读characteristics请求

1
2
3
4
5
6
7
8
9
10
11
12
13
//读characteristics请求
- (void)peripheralManager:(CBPeripheralManager *)peripheral didReceiveReadRequest:(CBATTRequest *)request{
NSLog(@"didReceiveReadRequest");
//判断是否有读数据的权限
if (request.characteristic.properties & CBCharacteristicPropertyRead) {
NSData *data = request.characteristic.value;
[request setValue:data];
//对请求作出成功响应
[peripheralManager respondToRequest:request withResult:CBATTErrorSuccess];
}else{
[peripheralManager respondToRequest:request withResult:CBATTErrorWriteNotPermitted];
}
}

5.2写characteristics请求

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
//写characteristics请求
- (void)peripheralManager:(CBPeripheralManager *)peripheral didReceiveWriteRequests:(NSArray *)requests{
NSLog(@"didReceiveWriteRequests");
CBATTRequest *request = requests[0];
//判断是否有写数据的权限
if (request.characteristic.properties & CBCharacteristicPropertyWrite) {
//需要转换成CBMutableCharacteristic对象才能进行写值
CBMutableCharacteristic *c =(CBMutableCharacteristic *)request.characteristic;
c.value = request.value;
[peripheralManager respondToRequest:request withResult:CBATTErrorSuccess];
}else{
[peripheralManager respondToRequest:request withResult:CBATTErrorWriteNotPermitted];
}
}

5.3订阅和取消订阅characteristics

1
2
3
4
5
6
7
8
9
10
11
12
//订阅characteristics 当中心设备订阅了这个特征会回调这个方法
-(void)peripheralManager:(CBPeripheralManager *)peripheral central:(CBCentral *)central didSubscribeToCharacteristic:(CBCharacteristic *)characteristic{
NSLog(@"订阅了 %@的数据",characteristic.UUID);
//每秒执行一次给主设备发送一个当前时间的秒数
// timer = [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(sendData:) userInfo:characteristic repeats:YES];
}
//取消订阅characteristics
-(void)peripheralManager:(CBPeripheralManager *)peripheral central:(CBCentral *)central didUnsubscribeFromCharacteristic:(CBCharacteristic *)characteristic{
NSLog(@"取消订阅 %@的数据",characteristic.UUID);
}

二、作为中心设备

1、打开中心设备,设置它的委托

1
2
manager = [[CBCentralManager alloc]initWithDelegate:self queue:dispatch_get_main_queue()];

2、扫描外围设备

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
-(void)centralManagerDidUpdateState:(CBCentralManager *)central{
switch (central.state) {
case CBCentralManagerStatePoweredOn:
NSLog(@">>>CBCentralManagerStatePoweredOn");
//开始扫描周围的外设
/*
第一个参数nil就是扫描周围所有的外设,扫描到外设后会进入
- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI;
*/
[central scanForPeripheralsWithServices:nil options:nil];
break;
default:
break;
}
}

3、把外围设备加入到中心设备中,连接外围设备

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
//扫描到设备会进入方法
-(void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI{
NSLog(@"当扫描到设备:%@",peripheral.name);
//接下连接我们的测试设备,如果你没有设备,可以下载一个app叫lightbule的app去模拟一个设备
//这里自己去设置下连接规则,我设置的是P开头的设备
// if ([peripheral.name hasPrefix:@"张"]){
/*
一个主设备最多能连7个外设,每个外设最多只能给一个主设备连接,连接成功,失败,断开会进入各自的委托
- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral;//连接外设成功的委托
- (void)centra`lManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error;//外设连接失败的委托
- (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error;//断开外设的委托
*/
//找到的设备必须持有它,否则CBCentralManager中也不会保存peripheral,那么CBPeripheralDelegate中的方法也不会被调用!!
if ([peripheral.name isEqualToString:@"外围设备名"]) {
[discoverPeripherals addObject:peripheral];
[central connectPeripheral:peripheral options:nil];
}
}

4、设置的peripheral委托CBPeripheralDelegate 扫描外设服务

1
2
3
4
5
6
7
8
9
10
11
12
13
//连接到Peripherals-成功
- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral
{
NSLog(@">>>连接到名称为(%@)的设备-成功",peripheral.name);
//设置的peripheral委托CBPeripheralDelegate
//@interface ViewController : UIViewController<CBCentralManagerDelegate,CBPeripheralDelegate>
[peripheral setDelegate:self];
//扫描外设Services,成功后会进入方法:-(void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error{
[peripheral discoverServices:nil];
}

5、扫描到service

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
-(void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error{
// NSLog(@">>>扫描到服务:%@",peripheral.services);
if (error)
{
NSLog(@">>>Discovered services for %@ with error: %@", peripheral.name, [error localizedDescription]);
return;
}
CBUUID * serviceUUID = [CBUUID UUIDWithString:@"服务码"];
//写
CBUUID *characteristicUUID1=[CBUUID UUIDWithString:@"特征码"];
//通知 读
CBUUID *characteristicUUID2=[CBUUID UUIDWithString:@"特征码"];
//写
CBUUID * characteristicUU = [CBUUID UUIDWithString:@"特征码"];
for (CBService *service in peripheral.services) {
[peripheral discoverCharacteristics:nil forService:service];
if ([service.UUID isEqual:serviceUUID]) {
[peripheral discoverCharacteristics:@[characteristicUUID1,characteristicUUID2,characteristicUU] forService:service];
}
//扫描每个service的Characteristics,扫描到后会进入方法: -(void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error
}
}

6、发现特征

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
//扫描到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;
}
//获取Characteristic的值,读到数据会进入方法:-(void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
for (CBCharacteristic *characteristic in service.characteristics){
{
[peripheral readValueForCharacteristic:characteristic];
//
[peripheral setNotifyValue:YES forCharacteristic:characteristic];
// if ([characteristic.UUID.UUIDString isEqualToString:@"2A60"]) {
// NSLog(@"嘿嘿");
// [peripheral writeValue:[@"hahha" dataUsingEncoding:NSUTF8StringEncoding] forCharacteristic:characteristic type:CBCharacteristicWriteWithResponse];
// }
// [peripheral writeValue:[@"看看" dataUsingEncoding:NSUTF8StringEncoding] forCharacteristic:characteristic type:CBCharacteristicWriteWithResponse];
}
}
//搜索Characteristic的Descriptors,读到数据会进入方法:-(void)peripheral:(CBPeripheral *)peripheral didDiscoverDescriptorsForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
for (CBCharacteristic *characteristic in service.characteristics){
[peripheral discoverDescriptorsForCharacteristic:characteristic];
}
}

7、注册读、写、通知

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#pragma mark 搜索到Characteristic的properties
-(void)peripheral:(CBPeripheral *)peripheral didDiscoverDescriptorsForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error{
if (characteristic.properties & CBCharacteristicPropertyRead) {
// if ([characteristic.UUID.UUIDString isEqualToString:@"FFE1"]) {
[peripheral readValueForCharacteristic:characteristic];
if (characteristic.value) {
NSString * value=[[NSString alloc]initWithData:characteristic.value encoding:NSUTF8StringEncoding];
NSLog(@"读取到特征值:%@",value);
// label.text = [NSString stringWithFormat:@"%@",value];
}
// }
}
//情景二:通知
if (characteristic.properties & CBCharacteristicPropertyNotify) {
// if ([characteristic.UUID.UUIDString isEqualToString:@"FFF1"] || [characteristic.UUID.UUIDString isEqualToString:@"FFF2"]) {
// _curCharacter = characteristic;
// label.text = @"通知";
[peripheral setNotifyValue:YES forCharacteristic:characteristic];
}
// }
// //情景二:写数据
if (characteristic.properties & CBCharacteristicPropertyWrite) {
NSLog(@"characteristic.UUID.UUIDString===========%@",characteristic.UUID.UUIDString);
if ([characteristic.UUID.UUIDString isEqualToString:@"2A60"]) {
_sendPeripheral = peripheral;
_sendCharacteristic = characteristic;
[peripheral writeValue:[@"2A60" dataUsingEncoding:NSUTF8StringEncoding] forCharacteristic:characteristic type:CBCharacteristicWriteWithResponse];
}
////// //新加的
if ([characteristic.UUID.UUIDString isEqualToString:@"2A62"]) {
[peripheral writeValue:[@"2A62" dataUsingEncoding:NSUTF8StringEncoding] forCharacteristic:characteristic type:CBCharacteristicWriteWithResponse];
}
}
}
⬅️ Go back