iOS蓝牙开发(三):App作为外设被连接的实现

2024-06-04 06:38

本文主要是介绍iOS蓝牙开发(三):App作为外设被连接的实现,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

http://www.cocoachina.com/ios/20160218/15299.html

在上一节说了app作为central连接peripheral的情况,这一节介绍如何使用app发布一个peripheral,给其他的central连接。

CoreBluetoothFramework.jpeg

还是这张图,central模式用的都是左边的类,而peripheral模式用的是右边的类

peripheral模式的流程

1. 打开peripheralManager,设置peripheralManager的委托

2. 创建characteristics,characteristics的description 创建service,把characteristics添加到service中,再把service添加到peripheralManager中

3. 开启广播advertising

4. 对central的操作进行响应

    - 4.1 读characteristics请求

    - 4.2 写characteristics请求

    - 4.4 订阅和取消订阅characteristics

##准备环境

  1. Xcode

  2. 开发证书和手机(蓝牙程序需要使用使用真机调试,使用模拟器也可以调试,但是方法很蛋疼,我会放在最后说),如果不行可以使用osx程序调试

  3. 蓝牙外设

##实现步骤

1.打开peripheralManager,设置peripheralManager的委托

设置当前ViewController实现CBPeripheralManagerDelegate委托

1
@interface BePeripheralViewController : UIViewController

初始化peripheralManager

1
2
3
4
5
6
/*
和CBCentralManager类似,蓝牙设备打开需要一定时间,打开成功后会进入委托方法
- (void)peripheralManagerDidUpdateState:(CBPeripheralManager *)peripheral;
模拟器永远也不会得CBPeripheralManagerStatePoweredOn状态
*/
peripheralManager = [[CBPeripheralManager alloc]initWithDelegate:self queue:nil];

2.创建characteristics,characteristics的description ,创建service,把characteristics添加到service中,再把service添加到peripheralManager中。

在委托方法 - (void)peripheralManagerDidUpdateState:(CBPeripheralManager *)peripheral中,当peripheral成功打开后,才可以配置service和characteristics。 这里创建的service和chara对象是CBMutableCharacteristic和CBMutableService。他们的区别就像NSArray和NSMutableArray区别类似。 我们先创建characteristics和description,description是characteristics的描述,描述分很多种, 这里不细说了,常用的就是CBUUIDCharacteristicUserDescriptionString。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
//peripheralManager状态改变
- (void)peripheralManagerDidUpdateState:(CBPeripheralManager *)peripheral{
     switch  (peripheral.state) {
             //在这里判断蓝牙设别的状态  当开启了则可调用  setUp方法(自定义)
         case  CBPeripheralManagerStatePoweredOn:
             NSLog(@ "powered on" );
             [info setText:[NSString stringWithFormat:@ "设备名%@已经打开,可以使用center进行连接" ,LocalNameKey]];
             [self setUp];
             break ;
         case  CBPeripheralManagerStatePoweredOff:
             NSLog(@ "powered off" );
             [info setText:@ "powered off" ];
             break ;
         default :
             break ;
     }
}

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
41
42
43
44
//配置bluetooch的
  -(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:@ "name" ];
         [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];
         [service1 setCharacteristics:@[notiyCharacteristic,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];
  }

3.开启广播advertising

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
//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 : LocalNameKey
                                              }
          ];
     }
}
//peripheral开始发送advertising
- (void)peripheralManagerDidStartAdvertising:(CBPeripheralManager *)peripheral error:(NSError *)error{
     NSLog(@ "in peripheralManagerDidStartAdvertisiong" );
}

4. 对central的操作进行响应

- 4.1 读characteristics请求

- 4.2 写characteristics请求

- 4.3 订阅和取消订阅characteristics

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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
//订阅characteristics
-(void)peripheralManager:(CBPeripheralManager *)peripheral central:(CBCentral *)central didSubscribeToCharacteristic:(CBCharacteristic *)characteristic{
     NSLog(@ "订阅了 %@的数据" ,characteristic.UUID);
     //每秒执行一次给主设备发送一个当前时间的秒数
     timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(sendData:) userInfo:characteristic  repeats:YES];
}
//取消订阅characteristics
-(void)peripheralManager:(CBPeripheralManager *)peripheral central:(CBCentral *)central didUnsubscribeFromCharacteristic:(CBCharacteristic *)characteristic{
     NSLog(@ "取消订阅 %@的数据" ,characteristic.UUID);
     //取消回应
     [timer invalidate];
}
//发送数据,发送当前时间的秒数
-(BOOL)sendData:(NSTimer *)t {
     CBMutableCharacteristic *characteristic = t.userInfo;
     NSDateFormatter *dft = [[NSDateFormatter alloc]init];
     [dft setDateFormat:@ "ss" ];
     NSLog(@ "%@" ,[dft stringFromDate:[NSDate date]]);
     //执行回应Central通知数据
     return   [peripheralManager updateValue:[[dft stringFromDate:[NSDate date]] dataUsingEncoding:NSUTF8StringEncoding] forCharacteristic:(CBMutableCharacteristic *)characteristic onSubscribedCentrals:nil];
}
//读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];
     }
}
//写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];
     }
}

代码下载:我博客中大部分示例代码都上传到了github,地址是:https://github.com/coolnameismy/demo,点击跳转代码下载地址

本文代码存放目录是BleDemo


这篇关于iOS蓝牙开发(三):App作为外设被连接的实现的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1029344

相关文章

MySQL 多表连接操作方法(INNER JOIN、LEFT JOIN、RIGHT JOIN、FULL OUTER JOIN)

《MySQL多表连接操作方法(INNERJOIN、LEFTJOIN、RIGHTJOIN、FULLOUTERJOIN)》多表连接是一种将两个或多个表中的数据组合在一起的SQL操作,通过连接,... 目录一、 什么是多表连接?二、 mysql 支持的连接类型三、 多表连接的语法四、实战示例 数据准备五、连接的性

使用Python实现IP地址和端口状态检测与监控

《使用Python实现IP地址和端口状态检测与监控》在网络运维和服务器管理中,IP地址和端口的可用性监控是保障业务连续性的基础需求,本文将带你用Python从零打造一个高可用IP监控系统,感兴趣的小伙... 目录概述:为什么需要IP监控系统使用步骤说明1. 环境准备2. 系统部署3. 核心功能配置系统效果展

MySQL中的分组和多表连接详解

《MySQL中的分组和多表连接详解》:本文主要介绍MySQL中的分组和多表连接的相关操作,本文通过实例代码给大家介绍的非常详细,感兴趣的朋友一起看看吧... 目录mysql中的分组和多表连接一、MySQL的分组(group javascriptby )二、多表连接(表连接会产生大量的数据垃圾)MySQL中的

Python实现微信自动锁定工具

《Python实现微信自动锁定工具》在数字化办公时代,微信已成为职场沟通的重要工具,但临时离开时忘记锁屏可能导致敏感信息泄露,下面我们就来看看如何使用Python打造一个微信自动锁定工具吧... 目录引言:当微信隐私遇到自动化守护效果展示核心功能全景图技术亮点深度解析1. 无操作检测引擎2. 微信路径智能获

Python中pywin32 常用窗口操作的实现

《Python中pywin32常用窗口操作的实现》本文主要介绍了Python中pywin32常用窗口操作的实现,pywin32主要的作用是供Python开发者快速调用WindowsAPI的一个... 目录获取窗口句柄获取最前端窗口句柄获取指定坐标处的窗口根据窗口的完整标题匹配获取句柄根据窗口的类别匹配获取句

在 Spring Boot 中实现异常处理最佳实践

《在SpringBoot中实现异常处理最佳实践》本文介绍如何在SpringBoot中实现异常处理,涵盖核心概念、实现方法、与先前查询的集成、性能分析、常见问题和最佳实践,感兴趣的朋友一起看看吧... 目录一、Spring Boot 异常处理的背景与核心概念1.1 为什么需要异常处理?1.2 Spring B

Python位移操作和位运算的实现示例

《Python位移操作和位运算的实现示例》本文主要介绍了Python位移操作和位运算的实现示例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一... 目录1. 位移操作1.1 左移操作 (<<)1.2 右移操作 (>>)注意事项:2. 位运算2.1

如何在 Spring Boot 中实现 FreeMarker 模板

《如何在SpringBoot中实现FreeMarker模板》FreeMarker是一种功能强大、轻量级的模板引擎,用于在Java应用中生成动态文本输出(如HTML、XML、邮件内容等),本文... 目录什么是 FreeMarker 模板?在 Spring Boot 中实现 FreeMarker 模板1. 环

Qt实现网络数据解析的方法总结

《Qt实现网络数据解析的方法总结》在Qt中解析网络数据通常涉及接收原始字节流,并将其转换为有意义的应用层数据,这篇文章为大家介绍了详细步骤和示例,感兴趣的小伙伴可以了解下... 目录1. 网络数据接收2. 缓冲区管理(处理粘包/拆包)3. 常见数据格式解析3.1 jsON解析3.2 XML解析3.3 自定义

SpringMVC 通过ajax 前后端数据交互的实现方法

《SpringMVC通过ajax前后端数据交互的实现方法》:本文主要介绍SpringMVC通过ajax前后端数据交互的实现方法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价... 在前端的开发过程中,经常在html页面通过AJAX进行前后端数据的交互,SpringMVC的controll