www.4688.com跟L大帝一起做~iOS蓝牙开

率先进一则广告:
蓝牙技术联盟(Bluetooth
SIG)二〇一〇年9月7日宣布,正式拔取蓝牙4.0主题标准(Bluetooth Core
Specification Version 4.0
),并启动相应之征计划。会员厂商可以提交其产品举行测试,通过后用抱蓝牙4.0规范认证。
该技术具有无限低之周转及待机功耗,使用相同颗纽扣电池还只是连续工作屡次年之久远。所以蓝牙技术依旧得被短期用的同种植链接技术。

率先进一则广告:

蓝牙技术联盟(Bluetooth
SIG)二〇一〇年九月7日通告,正式采用蓝牙4.0主导标准(Bluetooth Core
Specification Version 4.0
),并启动相应之印证计划。会员厂商可以交给其出品举行测试,通过后用赢得蓝牙4.0专业认证。
该技术有无限低之周转和待机功耗,使用同样粒纽电池居然可连接工作多次年的深入。所以蓝牙技术或者得以于短期用的一致种链接技术。

然后直接入正题。
我们可能会小心到一个题目。安卓及安卓手机可以据此蓝牙相互链接,但是苹果与苹果手机就是十分。因为苹果链接用的是airdrop,所以啊就是未待蓝牙传输大文件。大家呢即便忽略了是场所。其实airdrop本质也是蓝牙建链接的。。。。。。。

下一场直接进入正题。

世家也许会小心到一个问题。安卓同安卓手机能够据此蓝牙彼此链接,不过苹果及苹果手机就是大。因为苹果链接用的是airdrop,所以也固然不需要蓝牙传输大文件。我们吧就是忽略了这景。其实airdrop本质也是蓝牙树链接的。。。。。。。

今重大就是用一款app去念写蓝牙设备。应用场景就是是手机扫描外设,链接外设,找到外设的劳务及总体性,对劳务以及性质举行读写操作;

今最首要就之所以一款app去念写蓝牙设备。应用场景就是是手机扫描外设,链接外设,找到外设的劳务和性质,对劳动和性质举行读写操作;

代码实现流程。

1.建立基本管理控制对象


“`objc

#import <CoreBluetooth/CoreBluetooth.h>(导入头文件)

<CBCentralManagerDelegate,CBPeripheralDelegate>继承代理协议

//系统蓝牙设备为老董理对象可以错过扫描和链接外设

CBCentralManager *_manager;

//用于保存于发现设备

NSMutableArray *_discoverPeripherals;

//开首化并设置委托以及线程队列,最好一个线程的参数可以吗nil,默认会就main线程

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

//成立外设数组,保存发现的装备。不保留设备会造成代理方无可用

discoverPeripherals = [[NSMutableArray array];

“`


2.扫描外设,唯有设备打开状态,才可扫描。(错误原因有)


介绍一下

CBCentralManagerDelegate的重中之重代理方。

须贯彻的:

– (void)centralManagerDidUpdateState:(CBCentralManager
*)central;//主设备状态改变之托,在开头化CBCentralManager的时段会打开设备,只有当设备是打开后才会采纳

另外选项实现之代理方。

– (void)centralManager:(CBCentralManager *)central
didDiscoverPeripheral:(CBPeripheral *)peripheral
advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber
*)RSSI; //找到外设的委托

– (void)centralManager:(CBCentralManager *)central
didConnectPeripheral:(CBPeripheral *)peripheral;//连接外设成功之信托

– (void)centralManager:(CBCentralManager *)central
didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError
*)error;//外设连接失败的托

– (void)centralManager:(CBCentralManager *)central
didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError
*)error;//断开外设的委托



//工程被的代码不合乎直接放大出去,就用示例demo中的了。(感谢那些伟人的开销工作者)

这个状态不待自身逐一翻译了咔嚓,假设不知道可以私信我。我决然让您协调查字典去。。。

-(void)centralManagerDidUpdateState:(CBCentralManager *)central{

switch (central.state) {

case CBCentralManagerStateUnknown:

NSLog(@”>>>CBCentralManagerStateUnknown”);

break;

case CBCentralManagerStateResetting:

NSLog(@”>>>CBCentralManagerStateResetting”);

break;

case CBCentralManagerStateUnsupported:

NSLog(@”>>>CBCentralManagerStateUnsupported”);

break;

case CBCentralManagerStateUnauthorized:

NSLog(@”>>>CBCentralManagerStateUnauthorized”);

break;

case CBCentralManagerStatePoweredOff:

NSLog(@”>>>CBCentralManagerStatePoweredOff”);

break;

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.扫描完,进入连接情势举办设施连接。


-(void)centralManager:(CBCentralManager *)central
didDiscoverPeripheral:(CBPeripheral *)peripheral
advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber
*)RSSI{

NSLog(@”当扫描到设备:%@”,peripheral.name);

//这里自己去装下连规则,这里虽不同厂商特定设备链接的判断规则。L是自身好的假名。

//    if ([peripheral.name hasPrefix:@”L”]){

/*

一个主设备最多能连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中的不二法门也非相会叫调用!!(错误有)

[discoverPeripherals addObject:peripheral];

[central connectPeripheral:peripheral options:nil];

//    }

}

//连接到Peripherals-成功(其他操作不是我们回忆要之,自己举办连锁处理)

– (void)centralManager:(CBCentralManager *)central
didConnectPeripheral:(CBPeripheral *)peripheral{   
NSLog(@”>>>连接至号也(%@)的装备-成功”,peripheral.name);   
//设置的peripheral委托CBPeripheralDelegate    //@interface
ViewController : UIViewController[peripheral setDelegate:self];

//扫描外设瑟维斯(Service)(Service)s,成功后会见进来艺术:-(void)peripheral:(CBPeripheral
*)peripheral didDiscoverServices:(NSError *)error{

[peripheral discoverServices:nil];

}


4.接下来是发现设备的劳动,对相关服务碰着的特色开展操作。


//扫描到Services

-(void)peripheral:(CBPeripheral *)peripheral
didDiscoverServices:(NSError *)error{

//  NSLog(@”>>>扫描到服务:%@”,peripheral.services);

if (error)

{

NSLog(@”>>>Discovered services for %@ with error: %@”,
peripheral.name, [error localizedDescription]);

return;

}

for (CBService *service in peripheral.services) {

NSLog(@”%@”,service.UUID);

//扫描每个service的Characteristics,扫描到后会进入艺术:
-(void)peripheral:(CBPeripheral *)peripheral
didDiscoverCharacteristicsForService:(CBService *)service
error:(NSError *)error

[peripheral discoverCharacteristics:nil forService:service];

}

}

//扫描到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;

}

for (CBCharacteristic *characteristic in service.characteristics)

{

NSLog(@”service:%@ 的 Characteristic:
%@”,service.UUID,characteristic.UUID);

}

//获取Characteristic的价,读到多少会进入艺术:-(void)peripheral:(CBPeripheral
*)peripheral didUpdateValueForCharacteristic:(CBCharacteristic
*)characteristic error:(NSError *)error

for (CBCharacteristic *characteristic in service.characteristics){

{

[peripheral readValueForCharacteristic:characteristic];

}

}

//搜索Characteristic的Descriptors,读到多少会跻身情势:-(void)peripheral:(CBPeripheral
*)peripheral didDiscoverDescriptorsForCharacteristic:(CBCharacteristic
*)characteristic error:(NSError *)error

for (CBCharacteristic *characteristic in service.characteristics){

[peripheral discoverDescriptorsForCharacteristic:characteristic];

}

}

//获取的charateristic的值

-(void)peripheral:(CBPeripheral *)peripheral
didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic
error:(NSError *)error{

//打印出characteristic的UUID和值

//!注意,value的型是NSData,具体支出时,会因外设协议制定的主意去分析数据

NSLog(@”characteristic uuid:%@ 
value:%@”,characteristic.UUID,characteristic.value);

}

//搜索到Characteristic的Descriptors

-(void)peripheral:(CBPeripheral *)peripheral
didDiscoverDescriptorsForCharacteristic:(CBCharacteristic
*)characteristic error:(NSError *)error{

//打印出Characteristic和他的Descriptors

NSLog(@”characteristic uuid:%@”,characteristic.UUID);

for (CBDescriptor *d in characteristic.descriptors) {

NSLog(@”Descriptor uuid:%@”,d.UUID);

}

}

//获取到Descriptors的值

-(void)peripheral:(CBPeripheral *)peripheral
didUpdateValueForDescriptor:(CBDescriptor *)descriptor error:(NSError
*)error{

//打印出DescriptorsUUID 和value

//这么些descriptor都是对此characteristic的描述,一般如故字符串,所以这边大家转移成字符串去分析

NSLog(@”characteristic uuid:%@  value:%@”,[NSString
stringWithFormat:@”%@”,descriptor.UUID],descriptor.value);

}


5.解析到那多少个数量,就得满意平常计步,心率等一样文山会海单读数据的操作。接下来是奔外假使写多少。


//写数据

-(void)writeCharacteristic:(CBPeripheral *)peripheral

characteristic:(CBCharacteristic *)characteristic

value:(NSData *)value{

//打印出 characteristic
的权力,可以见见出许多栽,这是一个NS_OPTIONS,就是可而且用于好几单价,常见的有read,write,notify,indicate,知道就几乎独核心就是足足了,前几个是读写权限,后少单依然打招呼,两栽不同之通告格局。

/*

typedef NS_OPTIONS(NSUInteger, CBCharacteristicProperties) {

CBCharacteristicPropertyBroadcast = 0x01,

CBCharacteristicPropertyRead = 0x02,

CBCharacteristicPropertyWriteWithoutResponse = 0x04,

CBCharacteristicPropertyWrite = 0x08,

CBCharacteristicPropertyNotify = 0x10,

CBCharacteristicPropertyIndicate = 0x20,

CBCharacteristicPropertyAuthenticatedSignedWrites = 0x40,

CBCharacteristicPropertyExtendedProperties = 0x80,

CBCharacteristicPropertyNotifyEncryptionRequired NS_ENUM_AVAILABLE(NA,
6_0) = 0x100,

CBCharacteristicPropertyIndicateEncryptionRequired
NS_ENUM_AVAILABLE(NA, 6_0) = 0x200

};

*/

NSLog(@”%lu”, (unsigned long)characteristic.properties);

//只来 characteristic.properties 有write的权力才得以描绘

if(characteristic.properties & CBCharacteristicPropertyWrite){

/*

最为好一个type参数可以吗CBCharacteristicWriteWithResponse或type:CBCharacteristicWriteWithResponse,区别是是否相会生出报告

*/

[peripheral writeValue:value forCharacteristic:characteristic
type:CBCharacteristicWriteWithResponse];

}else{

NSLog(@”该字段不可写!”);

}

}

//订阅外设特性的通报。

//设置公告,数据通告会面进去:didUpdateValueForCharacteristic方法

[peripheral setNotifyValue:YES forCharacteristic:characteristic];

//撤消通知

[peripheral setNotifyValue:NO forCharacteristic:characteristic];

//设置通告及撤除通知都好触发此方法。

– (void)peripheral:(CBPeripheral *)peripheral
didUpdateNotificationStateForCharacteristic:(CBCharacteristic
*)characteristic error:(nullable NSError *)error;


6.操作完成 或者电量不足使开展悬停扫描断开设备操作。


//截止扫描并断开连接

-(void)disconnectPeripheral:(CBCentralManager *)centralManager

peripheral:(CBPeripheral *)peripheral{

//截止扫描

[centralManager stopScan];

//断开连接

[centralManager cancelPeripheralConnection:peripheral];

}


理所当然蓝牙开发就待硬件工程师定义好每个硬件对应的劳动,每个服务之叙说和服务特色的特性。所以开被的代码一般都早就定义好了。最重点的哪怕是询问各样格局是呀效率。在个别开发的进程被是不是要用到。为了给我们来只跟更加进一步的询问。接下来我更说一下劳动特征的切切实实读写及订阅。当然我也是找了累累资料。借鉴了重重大神的资源。当时于github上下载了成千上万东西。具体是哪位异常神写的呢未了解。反正杀崇拜这一个人。。。O(∩_∩)O哈哈哈~

代码实现流程。
1.起家基本管理控制对象

咱看一下外设管理类

如上写的是centralManager的始末对接下是peripheralManager。

1.初叶化外设管理者


//外设管理者

CBPeripheralManager *_peripheralManager;

//首先初步化外设管理者

peripheralManager = [[CBPeripheralManager alloc]initWithDelegate:self
queue:nil];(默认为主队)

//在你用过将来记得住广播

//[peripheralManager stopAdvertising];


2.布置蓝牙读写的特性与描述


//注意这形式是以保外设在CBPeripheralManagerStatePoweredOn状态下才但是调用***********

-(void)initService{

//characteristics字段描述

CBUUID *CBUUIDCharacteristicUserDescriptionStringUUID = [CBUUID
UUIDWithString:CBUUIDCharacteristicUserDescriptionString];

/*

可为主设备发送通告之风味 

properties:CBCharacteristicPropertyNotify

许可特性可读

permissions CBAttributePermissionsReadable

*/

CBMutableCharacteristic *notiyCharacteristic =
[[CBMutableCharacteristic alloc]initWithType:[CBUUID
UUIDWithString:notiyCharacteristicUUID]
properties:CBCharacteristicPropertyNotify value:nil
permissions:CBAttributePermissionsReadable];

/*

然而读写的特征

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

//serviceOne初叶化并投入两单characteristics

CBMutableService *serviceOne = [[CBMutableService
alloc]initWithType:[CBUUID UUIDWithString:ServiceUUID1]
primary:YES];

NSLog(@”%@”,serviceOne.UUID);

[serviceOne
setCharacteristics:@[notiyCharacteristic,readwriteCharacteristic]];

//serviceTwo初阶化并参与一个characteristics

CBMutableService *serviceTwo = [[CBMutableService
alloc]initWithType:[CBUUID UUIDWithString:ServiceUUID2]
primary:YES];

[serviceTwo setCharacteristics:@[readCharacteristic]];

//添加后就是会调用代理的

– (void)peripheralManager:(CBPeripheralManager *)peripheral
didAddService:(CBService *)service error:(NSError *)error

[peripheralManager addService:serviceOne];

[peripheralManager addService:serviceTwo];

}


3.外设管理者相关的代理方介绍


//perihpheral添加了service就调用此道

– (void)peripheralManager:(CBPeripheralManager *)peripheral
didAddService:(CBService *)service error:(NSError *)error{

if (!error) {

//两回等都加上完成后才去发送广播

//添加劳动后得以在此向外界发出通报 调用完这一个法子后会合调用代理的

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

//在此间做片殡葬广播时需的笔录或动作。

}

//This method is invoked when a central configurescharacteristicto
notify or indicate. *                          It should be used as a
cue to start sending updates as the characteristic value changes.

//当特性的价暴发变动就相会调用这多少个办法

//订阅characteristics

-(void)peripheralManager:(CBPeripheralManager *)peripheral
central:(CBCentral *)central
didSubscribeToCharacteristic:(CBCharacteristic *)characteristic{

NSLog(@”订阅了 %@的数据”,characteristic.UUID);

//每秒执行同样蹩脚受主设备发送一个脚下时刻之秒数(这里就是是最为要害的发送数据的不二法门)

timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self
selector:@selector(sendDate:) userInfo:characteristic  repeats:YES];

}

//发送数据,发送当前时光之秒数(这里自己定制)

-(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];

}

}


迄今结束蓝牙的全体连接发送数据的过程吧尽管完了了。苹果之文档中吗介绍的至极亮。假如您道某种情状要操作而本文没有写到之。可以看看苹果之文档。也许你晤面发觉又多用起来颇有益之方。

上新知识最好立于巨人之双肩上。这样可少走弯路。感谢这些大公无私的也罢大家提供学习文化之大牛。你道非常对得叫个喜什么。动动手指关注本身也是好的,做个好基友也是可以的,玩个lol也是足以的,做人呢最要害是和颜悦色。。。哈哈哈哈

<#import <CoreBluetooth/CoreBluetooth.h>(导入头文件)

<CBCentralManagerDelegate,CBPeripheralDelegate>继承代理协议

//系统蓝牙设备中心管理对象可以去扫描和链接外设

CBCentralManager *_manager;

//用于保存被发现设备

NSMutableArray *_discoverPeripherals;

//初始化并设置委托和线程队列,最好一个线程的参数可以为nil,默认会就main线程

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

//创建外设数组,保存发现的设备。不保存设备会导致代理方法不可用

discoverPeripherals = [[NSMutableArray array];

2.扫描外设,只有设备打开状态,才可以扫描。(错误原因之一)

介绍一下

CBCentralManagerDelegate的机要代理方。

非得兑现之:

- (void)centralManagerDidUpdateState:(CBCentralManager *)central;//主设备状态改变的委托,在初始化CBCentralManager的时候会打开设备,只有当设备正确打开后才能使用

其他选择实现的代理方法。

- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI; //找到外设的委托

- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral;//连接外设成功的委托

- (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error;//外设连接失败的委托

- (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error;//断开外设的委托

//工程中的代码不适合直接放出来,就用示例demo中的了。(感谢这些伟大的开发工作者)

这些状态不需要我一一翻译了吧,如果不懂可以私信我。我一定让你自己查字典去。。。

-(void)centralManagerDidUpdateState:(CBCentralManager *)central{

switch (central.state) {

case CBCentralManagerStateUnknown:

NSLog(@">>>CBCentralManagerStateUnknown");

break;

case CBCentralManagerStateResetting:

NSLog(@">>>CBCentralManagerStateResetting");

break;

case CBCentralManagerStateUnsupported:

NSLog(@">>>CBCentralManagerStateUnsupported");

break;

case CBCentralManagerStateUnauthorized:

NSLog(@">>>CBCentralManagerStateUnauthorized");

break;

case CBCentralManagerStatePoweredOff:

NSLog(@">>>CBCentralManagerStatePoweredOff");

break;

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.扫描完,进入连接格局举办配备连接。

-(void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI{

NSLog(@"当扫描到设备:%@",peripheral.name);

//这里自己去设置下连接规则,这里就是不同厂商特定设备链接的判断规则。L是我喜欢的字母。

//    if ([peripheral.name hasPrefix:@"L"]){

/*

一个主设备最多能连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中的方法也不会被调用!!(错误之一)

[discoverPeripherals addObject:peripheral];

[central connectPeripheral:peripheral options:nil];

//    }

}

//连接到Peripherals-成功(其他操作不是我们想要的,自己做相关处理)

- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral{    NSLog(@">>>连接到名称为(%@)的设备-成功",peripheral.name);    //设置的peripheral委托CBPeripheralDelegate    //@interface ViewController : UIViewController[peripheral setDelegate:self];

//扫描外设Services,成功后会进入方法:-(void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error{

[peripheral discoverServices:nil];

}

4.接下来是发现设备的劳动,对有关服务被之特点开展操作。

//扫描到Services

-(void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error{

//  NSLog(@">>>扫描到服务:%@",peripheral.services);

if (error)

{

NSLog(@">>>Discovered services for %@ with error: %@", peripheral.name, [error localizedDescription]);

return;

}

for (CBService *service in peripheral.services) {

NSLog(@"%@",service.UUID);

//扫描每个service的Characteristics,扫描到后会进入方法: -(void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error

[peripheral discoverCharacteristics:nil forService:service];

}

}

//扫描到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;

}

for (CBCharacteristic *characteristic in service.characteristics)

{

NSLog(@"service:%@ 的 Characteristic: %@",service.UUID,characteristic.UUID);

}

//获取Characteristic的值,读到数据会进入方法:-(void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error

for (CBCharacteristic *characteristic in service.characteristics){

{

[peripheral readValueForCharacteristic:characteristic];

}

}

//搜索Characteristic的Descriptors,读到数据会进入方法:-(void)peripheral:(CBPeripheral *)peripheral didDiscoverDescriptorsForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error

for (CBCharacteristic *characteristic in service.characteristics){

[peripheral discoverDescriptorsForCharacteristic:characteristic];

}

}

//获取的charateristic的值

-(void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error{

//打印出characteristic的UUID和值

//!注意,value的类型是NSData,具体开发时,会根据外设协议制定的方式去解析数据

NSLog(@"characteristic uuid:%@  value:%@",characteristic.UUID,characteristic.value);

}

//搜索到Characteristic的Descriptors

-(void)peripheral:(CBPeripheral *)peripheral didDiscoverDescriptorsForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error{

//打印出Characteristic和他的Descriptors

NSLog(@"characteristic uuid:%@",characteristic.UUID);

for (CBDescriptor *d in characteristic.descriptors) {

NSLog(@"Descriptor uuid:%@",d.UUID);

}

}

//获取到Descriptors的值

-(void)peripheral:(CBPeripheral *)peripheral didUpdateValueForDescriptor:(CBDescriptor *)descriptor error:(NSError *)error{

//打印出DescriptorsUUID 和value

//这个descriptor都是对于characteristic的描述,一般都是字符串,所以这里我们转换成字符串去解析

NSLog(@"characteristic uuid:%@  value:%@",[NSString stringWithFormat:@"%@",descriptor.UUID],descriptor.value);

}

5.解析到这多少个多少,就能够满足通常计步,心率等一律雨后春笋单读数据的操作。接下来是于外要是写多少。

//写数据

-(void)writeCharacteristic:(CBPeripheral *)peripheral

characteristic:(CBCharacteristic *)characteristic

value:(NSData *)value{

//打印出 characteristic 的权限,可以看到有很多种,这是一个NS_OPTIONS,就是可以同时用于好几个值,常见的有read,write,notify,indicate,知道这几个基本就够用了,前几个是读写权限,后两个都是通知,两种不同的通知方式。

/*

typedef NS_OPTIONS(NSUInteger, CBCharacteristicProperties) {

CBCharacteristicPropertyBroadcast   = 0x01,

CBCharacteristicPropertyRead    = 0x02,

CBCharacteristicPropertyWriteWithoutResponse    = 0x04,

CBCharacteristicPropertyWrite   = 0x08,

CBCharacteristicPropertyNotify  = 0x10,

CBCharacteristicPropertyIndicate    = 0x20,

CBCharacteristicPropertyAuthenticatedSignedWrites   = 0x40,

CBCharacteristicPropertyExtendedProperties  = 0x80,

CBCharacteristicPropertyNotifyEncryptionRequired NS_ENUM_AVAILABLE(NA, 6_0) = 0x100,

CBCharacteristicPropertyIndicateEncryptionRequired NS_ENUM_AVAILABLE(NA, 6_0)   = 0x200

};

*/

NSLog(@"%lu", (unsigned long)characteristic.properties);

//只有 characteristic.properties 有write的权限才可以写

if(characteristic.properties & CBCharacteristicPropertyWrite){

/*

最好一个type参数可以为CBCharacteristicWriteWithResponse或type:CBCharacteristicWriteWithResponse,区别是是否会有反馈

*/

[peripheral writeValue:value forCharacteristic:characteristic type:CBCharacteristicWriteWithResponse];

}else{

NSLog(@"该字段不可写!");

}

}

//订阅外设特性的通知。

//设置通知,数据通知会进入:didUpdateValueForCharacteristic方法

[peripheral setNotifyValue:YES forCharacteristic:characteristic];

//取消通知

[peripheral setNotifyValue:NO forCharacteristic:characteristic];

//设置通知和取消通知均可以触发此方法。

- (void)peripheral:(CBPeripheral *)peripheral didUpdateNotificationStateForCharacteristic:(CBCharacteristic *)characteristic error:(nullable NSError *)error;

6.操作就 或者电量不足而开展悬停扫描断开设备操作。

//停止扫描并断开连接

-(void)disconnectPeripheral:(CBCentralManager *)centralManager

peripheral:(CBPeripheral *)peripheral{

//停止扫描

[centralManager stopScan];

//断开连接

[centralManager cancelPeripheralConnection:peripheral];

}

本来蓝牙开发就需要硬件工程师定义好每个硬件对应之劳务,每个服务的讲述和服务特征的属性。所以开被的代码一般还已定义好了。最着重之虽是摸底各类方法是啊功用。在个别出之经过遭到是不是要用到。为了为我们来个跟更加进一步的打听。接下来我再说一下劳务特色的切实可行读写及订阅。当然我吗是寻觅了成千上万材料。借鉴了很多大神的资源。当时以github上下载了过多物。具体是啊位老神写的吗非知底。反正杀钦佩这个人口。。。O(∩_∩)O哈哈哈~

大家看一下外设管理类
上述写的凡centralManager的内容连下去是peripheralManager。

1.先导化外设管理者

//外设管理者

CBPeripheralManager *_peripheralManager;

//首先初始化外设管理者

peripheralManager = [[CBPeripheralManager alloc]initWithDelegate:self queue:nil];(默认为主队列)

//在你用过之后记得停止广播

//[peripheralManager stopAdvertising];

2.配置蓝牙读写的性能和描述

//注意此方法是在保证外设在CBPeripheralManagerStatePoweredOn状态下才可调用***********

-(void)initService{

//characteristics字段描述

CBUUID *CBUUIDCharacteristicUserDescriptionStringUUID = [CBUUID UUIDWithString:CBUUIDCharacteristicUserDescriptionString];

/*

可以给主设备发送通知的特性 

properties:CBCharacteristicPropertyNotify

许可特性可读

permissions CBAttributePermissionsReadable

*/

CBMutableCharacteristic *notiyCharacteristic = [[CBMutableCharacteristic alloc]initWithType:[CBUUID UUIDWithString:notiyCharacteristicUUID] properties:CBCharacteristicPropertyNotify value:nil permissions:CBAttributePermissionsReadable];

/*

可读写的特性

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

//serviceOne初始化并加入两个characteristics

CBMutableService *serviceOne = [[CBMutableService alloc]initWithType:[CBUUID UUIDWithString:ServiceUUID1] primary:YES];

NSLog(@"%@",serviceOne.UUID);

[serviceOne setCharacteristics:@[notiyCharacteristic,readwriteCharacteristic]];

//serviceTwo初始化并加入一个characteristics

CBMutableService *serviceTwo = [[CBMutableService alloc]initWithType:[CBUUID UUIDWithString:ServiceUUID2] primary:YES];

[serviceTwo setCharacteristics:@[readCharacteristic]];

//添加后就会调用代理的

- (void)peripheralManager:(CBPeripheralManager *)peripheral didAddService:(CBService *)service error:(NSError *)error

[peripheralManager addService:serviceOne];

[peripheralManager addService:serviceTwo];

}

3.外设管理者相关的代办方介绍

//perihpheral添加了service就调用此方法

- (void)peripheralManager:(CBPeripheralManager *)peripheral didAddService:(CBService *)service error:(NSError *)error{

if (!error) {

//两次都添加完成后才去发送广播

//添加服务后可以在此向外界发出通告 调用完这个方法后会调用代理的

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

//在这里做一些发送广播时需要的记录或者动作。

}

//This method is invoked when a central configurescharacteristicto notify or indicate. *                          It should be used as a cue to start sending updates as the characteristic value changes.

//当特性的值发生改变就会调用这个方法

//订阅characteristics

-(void)peripheralManager:(CBPeripheralManager *)peripheral central:(CBCentral *)central didSubscribeToCharacteristic:(CBCharacteristic *)characteristic{

NSLog(@"订阅了 %@的数据",characteristic.UUID);

//每秒执行一次给主设备发送一个当前时间的秒数(这里就是最主要的发送数据的方法)

timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(sendDate:) userInfo:characteristic  repeats:YES];

}

//发送数据,发送当前时间的秒数(这里自己定制)

-(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];

}

}

迄今截至蓝牙的全体连接发送数据的进程为便完了了。苹果的文档中为介绍的不可开交了然。倘若你看某种意况要操作而本文没有写及之。可以省苹果的文档。也许你碰面发现更多采用起来非凡便利的法。

学习新知识最好立在巨人的肩头上。这样可以少走弯路。感谢那一个大公无私的吗我们提供就学知识的大牛。你当特别不错得叫个喜欢什么。动动手指关注我啊是可的,做只能基友也是足以的,玩个lol也是得的,做人呢最要害是欢天喜地。。。哈哈哈哈

相关文章

发表评论

电子邮件地址不会被公开。 必填项已用*标注

*
*
Website