代码下载:

原博客中大部分示例代码都上传到了github,地址是:https://github.com/coolnameismy/demo。

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

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委托

@interface BePeripheralViewController : UIViewController<CBPeripheralManagerDelegate>

初始化peripheralManager

/*

和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。

//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;

}

}

//配置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

//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

//订阅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];

}

}

ios蓝牙开发(四)app作为外设被连接的实现-转发的更多相关文章

  1. iOS蓝牙开发(二)蓝牙相关基础知识

    原文链接: http://liuyanwei.jumppo.com/2015/07/17/ios-BLE-1.html iOS蓝牙开发(一)蓝牙相关基础知识: 蓝牙常见名称和缩写 MFI ====== ...

  2. iOS 蓝牙开发资料记录

    一.蓝牙基础认识:   1.iOS蓝牙开发:  iOS蓝牙开发:蓝牙连接和数据读写   iOS蓝牙后台运行  iOS关于app连接已配对设备的问题(ancs协议的锅)          iOS蓝牙空中 ...

  3. iOS 蓝牙开发(四)BabyBluetooth蓝牙库介绍(转)

    转载自:http://www.cocoachina.com/ios/20151106/14072.html 原文作者:刘彦玮 BabyBluetooth 是一个最简单易用的蓝牙库,基于CoreBlue ...

  4. ios蓝牙开发(四)BabyBluetooth蓝牙库

    BabyBluetooth 是一个最简单易用的蓝牙库,基于CoreBluetooth的封装,并兼容ios和mac osx. 特色: 基于原生CoreBluetooth框架封装的轻量级的开源库,可以帮你 ...

  5. iOS蓝牙开发(一)蓝牙相关基础知识(转)

    转载自:http://www.cocoachina.com/ios/20150915/13454.html 原文作者:刘彦玮 蓝牙常见名称和缩写 MFI ======= make for ipad , ...

  6. iOS蓝牙开发

    蓝牙常见名称和缩写 MFI ======= make for ipad ,iphone, itouch 专们为苹果设备制作的设备 BLE ==== buletouch low energy,蓝牙4.0 ...

  7. iOS 蓝牙开发详解

    目前iOS智能硬件的开发交互方式主要分为两种,一种是基于低功耗的蓝牙4.0技术(由于耗电低,也称作为BLE(Bluetooth Low Energy))对应iOS的框架为CoreBluetooth,另 ...

  8. iOS蓝牙开发CoreBluetooth快速入门

    在iOS开发中,实现蓝牙通信有两种方式,一种是使用传统的GameKit.framework,另一种就是使用在iOS 5中加入的CoreBluetooth.framework. 利用CoreBlueto ...

  9. ios蓝牙开发(一)蓝牙相关基础知识

    蓝牙常见名称和缩写 MFI ======= make for ipad ,iphone, itouch 专们为苹果设备制作的设备 BLE ==== buletouch low energy,蓝牙4.0 ...

  10. iOS蓝牙开发(4.0)详解

    最近由于项目需要, 一直在研究蓝牙4.0,在这儿分享给大家, 望共同进步. 一.关于蓝牙开发的一些重要的理论概念: 1.当前ios中开发蓝牙所运用的系统库是<CoreBluetooth/Core ...

随机推荐

  1. 烂泥:linux文件同步之rsync学习(一)

    本文由秀依林枫提供友情赞助,首发于烂泥行天下. 这几天刚好有空就打算开始学习linux下的文件同步软件rsync,在学习rsync时,我们可以分以下几个步骤进行: 1. rsync是什么 2. rsy ...

  2. Jmeter之Bean shell使用(二)

    上一篇Jmeter之Bean shell使用(一)简单介绍了下Jmeter中的Bean shell,本文是对上文的一个补充,主要总结下常用的几种场景和方法,相信这些基本可以涵盖大部分的需求.本节内容如 ...

  3. Debian deb源方法升级PHP软件包

    学习Linxu以来,一直坚持编译方式安装软件包,貌似圈子里面也是都倾向于编译,可是搜索到的编译方法都是一堆复制粘贴来的指令, 每个人都这么编译, 却几乎没有人去写明那些五花八门的编译指令代表了什么,是 ...

  4. 初涉Linux ----------> 打造自己的 Vim IDE

    一.  开篇前言 (图片显示越界的话,请刷新) 装好Ubuntu15.04系统之后呢,玩了玩 Ubuntu,感觉还是很不错的.比windows快,一开机就可以打开你想要的程序,但是在windows下你 ...

  5. 跨应用程序域(AppDomain)的单例(Singleton)实现

    转载自: 跨应用程序域(AppDomain)的单例(Singleton)实现 - CorePlex代码库 - CorePlex官方网站,Visual Studio插件,代码大全,代码仓库,代码整理,分 ...

  6. 使用TCMalloc的堆栈检查

    在前一篇译文<TCMalloc:线程缓冲的Malloc>详细讲解了TCMalloc的工作原理和特点,今天翻译<heap-checking using tcmalloc>,了解T ...

  7. Eclipse中启动tomcat报错:A child container failed during start

    我真的很崩溃,先是workspace崩了,费了好久重建的workspace,然后建立了一个小demo项目,tomcat中启动却报错,挑选其中比较重要的2条信息如下: A child container ...

  8. FTP上传与下载

    1.连接 先假设一个ftp地址 用户名 密码       FTP Server: 192.168.1.125 User: administrator Password: abc123 2. 打开win ...

  9. 大话设计模式C++版——简单工厂模式

    简单工厂模式应该是所有设计模式中最简单,也最基础的一种模式,以下是一个简单的采用工厂模式写一个加减法的计算器. 1.抽象接口类——依赖倒转原则(高层和底层都要依赖于抽象,针对接口编程) class I ...

  10. C#基础----Linq之List<T>篇

    最近有用到List处理排序以及分页的问题.想想还是写一个博客记录一下.以下围绕Person类实现,Person类只有Name和Age两个属性   一.List<T>排序 1.1 List& ...