iOS Kingdom -- 智能开发(Bluetooth 篇一 -- Central)

Bluetooth
iOS 的蓝牙分为中心设备(Central)和外设或边设(Peripheral)。
Central
Central 处于主动地位,可主动发起搜索,连接,发送数据等动作,本篇主要讲述的就是 iOS 蓝牙做为 Central 时的使用方法。
在使用讲解前,我们首先要理解两个特有名词——服务与特征。服务与特征对应的是 Peripheral 中的 CBServiceCBCharacteristic 。在一个外设中,服务可以有多个;在一个服务中,特征可以有多个。
Relationship

1、做为 Central 时的开发流程

1) 导入 CoreBluetooth/CoreBluetooth.h
2) 遵守 CBCentralManagerDelegate,CBPeripheralDelegate 协议
3) 建立中心角色
4) 扫描外设(discover)
5) 连接外设(connect)
6) 断开连接
7) 获取外设的服务与特征
8) 与外设交换数据(读写数据)
9) 必须实现centralManagerDidUpdateState:(CBCentral *)central这个require的方法

2、定义全局变量

{
        CBManagerCentral *_central;
        CBPeripheral *_periperal;
}

3、初始化中心变量

/** 初始化中心角色 */
dispatch_queue_t centralQueue = dispatch_queue_create(@“identify”,DISPATCH_QUEUE_SERIAL);
_central = [[CBManagerCentral alloc] initWithDelegate:self queue:centralQueue];

4、扫描外设

/*
扫描外设,services是外设服务的CBUUID,如果为空则扫描所有的外设
*/
[_central scanForPeripheralsWithServices:@[] option:options];

如果扫描到外设,则调用CBCentralManagerDelegate中的-(void)centralManager:didDescoverPeripheral:advertisementData:RSSI:

-(void)centralManager:(CBCentralManager *)central didDescoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:):(NSNumber *)RSSI{
        If(!peripheral || !peripheral.name || [peripheral.name     isEqualToString:@””]){
    return;
  }
if(“符合条件的peripheral”){
}
}

5、连接外设、查找外设服务与特征

/*
连接外设

options中可以设置一些连接设备的初始属性键值如下
//对应NSNumber的bool值,设置当外设连接后是否弹出一个警告
NSString *const CBConnectPeripheralOptionNotifyOnConnectionKey;
//对应NSNumber的bool值,设置当外设断开连接后是否弹出一个警告
NSString *const CBConnectPeripheralOptionNotifyOnDisconnectionKey;
//对应NSNumber的bool值,设置当外设暂停连接后是否弹出一个警告
NSString *const CBConnectPeripheralOptionNotifyOnNotificationKey;
*/
[_central connectPeripheral:_peripheral
                              options:[NSDictionary dictionaryWithObject:[NSNumber numberWithBool:YES]
                                                                  forKey:CBConnectPeripheralOptionNotifyOnNotificationKey]];

连接成功后回调 CBCentralManagerDelegate- (void)centralManager:didConnectPeripheral: 方法

- (void)centralManager:(CBCentralManager *)central
  didConnectPeripheral:(CBPeripheral *)peripheral {
    peripheral.delegate = self;
    _peripheral = peripheral;

    // 查找外设服务,serviceUUIDs 为空时查找所有服务
    [peripheral discoverServices:@[]];
}

发现服务后调用 CBPeripheralDelegate- (void)peripheral:didDiscoverServices: 方法

- (void)peripheral:(CBPeripheral *)peripheral
didDiscoverServices:(NSError *)error {
    if (error) {
        return;
    }
    for (CBService *service in peripheral.services) {
        if ([service.UUID.UUIDString isEqualToString:@"符合条件的 UUIDString"]) {
            // 查询服务对应的特征,characteristicUUIDs 为空时查询所有特征
            [peripheral discoverCharacteristics:@[]
                                     forService:service];
        }
    }
}

发现特征后调用 CBPeripheralDelegate-(void)peripheral:didDiscoverCharacteristicsForService:error: 方法

-(void)peripheral:(CBPeripheral *)peripheral
didDiscoverCharacteristicsForService:(CBService *)service
            error:(NSError *)error {
    if (error) {
        return;
    }
    // 遍历特征
    for (CBCharacteristic *cha in service.characteristics) {
        if ([cha.UUID.UUIDString isEqualToString:kR_UUID]) {
            // 特征判断
         }
      }
}

特征的属性 properties 有很多种,不同的属性标明特征的用途。比如说,现有一特征的 properties 仅为 CBCharacteristicPropertyWrite ,那么这个特征只能用于 Central 端发送数据;而又有一特征的 properties 仅为 CBCharacteristicPropertyRead 那么这个特征只能用于 Central 读数据

typedef NS_OPTIONS(NSUInteger, CBCharacteristicProperties) {
    CBCharacteristicPropertyBroadcast,                 //允许广播特征
    CBCharacteristicPropertyRead,                      //可读属性
    CBCharacteristicPropertyWriteWithoutResponse,      //可写并且接收回执
    CBCharacteristicPropertyWrite,                     //可写属性
    CBCharacteristicPropertyNotify,                    //可通知属性
    CBCharacteristicPropertyIndicate,                  //可展现的特征值
    CBCharacteristicPropertyAuthenticatedSignedWrites, //允许签名的特征值写入
    CBCharacteristicPropertyExtendedProperties,
    CBCharacteristicPropertyNotifyEncryptionRequired,
    CBCharacteristicPropertyIndicateEncryptionRequired
};

6、断开连接

[_centralr cancelPeripheralConnection:_peripheral];

断开连接后调用 CBCentralManagerDelegate-(void)centralManager:didDisconnectPeripheral:error: 方法

7、发送数据

[_peripheral writeValue:data
              forCharacteristic:@"特征的属性必须含有 CBCharacteristicPropertyWrite 或 CBCharacteristicPropertyWriteWithoutResponse"
                           type:@"视特征属性而定"];

数据发送完成调用 CBPeripheralDelegate-(void)peripheral:didWriteValueForCharacteristic:error: 方法

- (void)peripheral:(CBPeripheral *)peripheral
didWriteValueForCharacteristic:(CBCharacteristic *)characteristic
             error:(nullable NSError *)error {
// 数据发送完成
}

8、读数据

读数据有两种方法:
1、只读一次数据,读一次调用一次 - (void)readValueForCharacteristic: ,要确保调用在数据发出来之前,否则会读不到数据

[_peripheral readValueForCharacteristic:@"特征要包含 CBCharacteristicPropertyRead 属性"];

2、监听数据,当数据开启监听后,只要有数据发送到客户端,就会读到数据

[_peripheral setNotifyValue:YES
          forCharacteristic:@"特征要包含 CBCharacteristicPropertyNotify 属性"];

监听开启后会回调 CBPeripheralDelegate-(void)peripheral:didUpdateNotificationStateForCharacteristic:error: 方法

- (void)peripheral:(CBPeripheral *)peripheral
didUpdateNotificationStateForCharacteristic:(CBCharacteristic *)characteristic
             error:(NSError *)error {
    if (error) {
        NSLog(@"监听错误: %@ -- isNotifiying: %d",
                   error,characteristic.isNotifying);
        return;
    }
}

读到数据回调 CBPeripheralDelegate-(void)peripheral:didUpdateValueForCharacteristic:error: 方法

- (void)peripheral:(CBPeripheral *)peripheral
didUpdateValueForCharacteristic:(nonnull CBCharacteristic *)characteristic
             error:(nullable NSError *)error {
    if (error) {
        NSLog(@"接收错误: %@",error);
        [self jmDisconnectWithError:error];
        return;
    }
}

这两种方法须要特征的支持。也就是说,如果你的特征为 CBCharacteristicPropertyNotify 时才可以使用监听读数据

9、实现代理

- (void)centralManagerDidUpdateState:(CBCentralManager *)central {
    // 状态改变
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 199,519评论 5 468
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 83,842评论 2 376
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 146,544评论 0 330
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,742评论 1 271
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,646评论 5 359
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,027评论 1 275
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,513评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,169评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,324评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,268评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,299评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,996评论 3 315
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,591评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,667评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,911评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,288评论 2 345
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,871评论 2 341

推荐阅读更多精彩内容