iOS 蓝牙开发相关知识-02

#import "ViewController.h"
#import <CoreBluetooth/CoreBluetooth.h>
@interface ViewController () <CBCentralManagerDelegate,CBPeripheralDelegate>
/** 中心管理者 */
@property(nonatomic,strong)CBCentralManager * cbManager ;
/** 外设 */
@property(nonatomic,strong)CBPeripheral * cbPeripheral ;
@property(nonatomic,strong)CBCharacteristic * cbchar1 ;
@property(nonatomic,strong)CBCharacteristic * cbchar2 ;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self cbManager];
    /**
     在ios10中需要在plist添加新的字段来获取蓝牙的访问权限
     <key>NSBluetoothPeripheralUsageDescription</key>
     <string>App需要您的同意,才能访问蓝牙</string>
     */
}
-(CBCentralManager *)cbManager
{
    if (_cbManager ==nil) {
        _cbManager = [[CBCentralManager alloc]initWithDelegate:self queue:dispatch_get_main_queue()];
    }
    return _cbManager;
}
//�1.检查蓝牙状态
-(void)centralManagerDidUpdateState:(CBCentralManager *)central
{
    switch (central.state) {
        case CBCentralManagerStatePoweredOn:
            [central scanForPeripheralsWithServices:nil options:nil];
            NSLog(@"蓝牙开启");

            break;
        case CBCentralManagerStatePoweredOff:
            NSLog(@"蓝牙状态关闭");
        case CBCentralManagerStateUnknown:
            NSLog(@"蓝牙状态为止");
            break;
        case CBCentralManagerStateResetting:
            NSLog(@"蓝牙状态重置");
            break;
        case CBCentralManagerStateUnsupported:
            NSLog(@"不支持蓝牙");
            break;
        case CBCentralManagerStateUnauthorized:
            NSLog(@"蓝牙未经授权");
            break;
    }
}
//2.app扫描到外设会进入该方法
-(void)centralManager:(CBCentralManager *)central
didDiscoverPeripheral:(CBPeripheral *)peripheral
    advertisementData:(NSDictionary *)advertisementData
                 RSSI:(NSNumber *)RSSI
{
    //判断蓝牙的名称,因官方没有SDK无法获取MAC地址,暂时以外设的名字连接 ABS是绝对值宏,因扫描到的外设信号都是"-",[如果无法判断蓝牙的名称可以从app stroe下一个蓝牙助手就可以看到附近的蓝牙设备]
    if ([peripheral.name hasPrefix:@"Bioland-BGM"]&&(ABS(RSSI.integerValue)>20)){
        self.cbPeripheral = peripheral;
        //app开始连接外设
        [self.cbManager connectPeripheral:self.cbPeripheral options:nil];
    }
}
//2.1扫描到services调用该方法
-(void)peripheral:(CBPeripheral *)peripheral
didDiscoverServices:(NSError *)error
{
    for (CBService *service in peripheral.services) {
        NSLog(@"%@",service.UUID);
        [peripheral discoverCharacteristics:nil forService:service];
    }
}
//2.2扫描到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;
    }
    //从service中遍历所有的特征
    for (CBCharacteristic *characteristic in service.characteristics) {
        //获取Characteristic的值,读到数据会进入方法:-(void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
        [peripheral readValueForCharacteristic:characteristic];
        NSLog(@"characteristic= %@",characteristic);
        
        //搜索Characteristic的Descriptors,读到数据会进入方法:-(void)peripheral:(CBPeripheral *)peripheral didDiscoverDescriptorsForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
        [peripheral discoverDescriptorsForCharacteristic:characteristic];
        
        NSLog(@"Characteristic.Descriptors =%@",characteristic);
        //判断特征值中的uuid如果包含1001就订阅这个特征,订阅后会收到返回值
        //每个外设的特征不是相同的需要参照硬件商提供的蓝牙开发文档
        if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:@"1001"]]) {
            self.cbchar1 = characteristic;
            [self.cbPeripheral setNotifyValue:YES forCharacteristic:characteristic];
        }
        if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:@"1002"]]) {
            self.cbchar2 = characteristic;
            [self.cbPeripheral  setNotifyValue:YES forCharacteristic:characteristic];
        }
    }
}
//3.中心管理者连接外设成功时会调用该方法
-(void)centralManager:(CBCentralManager *)central
 didConnectPeripheral:(CBPeripheral *)peripheral
{
    self.cbPeripheral.delegate = self;
    [self.cbPeripheral discoverServices:nil];
    NSLog(@"连接成功");
}
//4.搜索到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(@"详情 uuid:%@",d.UUID);
    }
}
//4.1获取外设的Characteristicsde值,在这个方法中外设会把我们订阅的特征的值以16进制的格式返回,只要打印就可以看到具体的详情值。
-(void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
{
    NSLog(@"peripheral:%@   characteristic.description:%@---%@",peripheral.description,characteristic.description,error.description);
}
//4.2获取Characteristics的 descriptor的值
- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForDescriptor:(nonnull CBDescriptor *)descriptor error:(nullable NSError *)error
{
    //打印出DescriptorsUUID 和value
    //这个descriptor都是对于characteristic的描述,一般都是字符串,所以这里我们转换成字符串去解析
    NSLog(@"descriptor.UUID:%@ value:%@",descriptor.UUID, descriptor.value);
}
// 5.将数据写入特征,自定义方法
-(void)XC_writeCharacteristic:(CBPeripheral *)peripheral
            characteristic:(CBCharacteristic *)characteristic
                     value:(NSData *)value
{
    /*
     打印出特征的权限(characteristic.properties),可以看到有很多种,这是一个NS_OPTIONS的枚举,可以是多个值
     常见的又read,write,noitfy,indicate.知道这几个基本够用了,前俩是读写权限,后俩都是通知,俩不同的通知方式
     */
    NSLog(@"characteristic.properties:%lu", (unsigned long)characteristic.properties);
    //只有 characteristic.properties 有write的权限才可以写
    if(characteristic.properties & CBCharacteristicPropertyWrite){
        [peripheral writeValue:value forCharacteristic:characteristic type:CBCharacteristicWriteWithResponse];
    }else{
        NSLog(@"该字段不可写!");
    }
}
//5.1写入数据后的回调
- (void)peripheral:(CBPeripheral *)peripheral
didWriteValueForCharacteristic:(CBCharacteristic *)
characteristic error:(nullable NSError *)error
{
    //获取特征中1002的特征值
    [self.cbperipheral readValueForCharacteristic:self.cbchar2];
    if (error) {
        NSLog(@"erro = %@",error.description);
    }
}
// 6.设置通知
- (void)XC_peripheral:(CBPeripheral *)peripheral setNotifyForCharacteristic:(CBCharacteristic *)characteristic
{
    // 设置通知, 数据会进入 peripheral:didUpdateValueForCharacteristic:error:方法
    [peripheral setNotifyValue:YES forCharacteristic:characteristic];
}

//5.1写入数据后的回调
- (void)peripheral:(CBPeripheral *)peripheral
didWriteValueForCharacteristic:(CBCharacteristic *)
characteristic error:(nullable NSError *)error
{
    //获取特征中1002的特征值
    [self.cbperipheral readValueForCharacteristic:self.cbchar2];
    if (error) {
        NSLog(@"erro = %@",error.description);
    }
}

// 6.1取消通知
- (void)XC_peripheral:(CBPeripheral *)peripheral cancelNotifyForCharacteristic:(CBCharacteristic *)characteristic
{
    [peripheral setNotifyValue:NO forCharacteristic:characteristic];
}
// 7.断开连接
- (void)XC_cbManger:(CBCentralManager *)cbManger stopScanAndDisConnectWithPeripheral:(CBPeripheral *)
peripheral
{
    // 停止扫描
    [cbManger stopScan];
    // 断开连接
    [cbManger cancelPeripheralConnection:peripheral];
}
//除了以上函数的实现定义还需要对蓝牙失败�操作做响应不然会app会直接崩溃
//外设链接失败
-(void)centralManager:(CBCentralManager *)central
didFailToConnectPeripheral:(CBPeripheral *)peripheral
                error:(NSError *)error
{
    NSLog(@"外设链接失败 = %@",error);
}
//外设断开连接
- (void)centralManager:(CBCentralManager *)central
didDisconnectPeripheral:(CBPeripheral *)peripheral
                 error:(NSError *)error
{
    NSLog(@"外设断开链接 = %@",error);
}
@end

(http://www.jianshu.com/p/d71d493d9e8a)

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

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 170,569评论 25 707
  • Swift版本点击这里欢迎加入QQ群交流: 594119878最新更新日期:18-09-17 About A cu...
    ylgwhyh阅读 24,864评论 7 249
  • 白色的门,向我们敞开 敞开红色地毯般的故乡 潮湿发霉的季节面对着 自杀者的女儿千疮百孔 从此多了一句情话 多了一个...
    唐啵儿阅读 146评论 0 1
  • 那年,我们上小学四年级。转校来的她成了我们班的班花。出自做生意富裕家庭的她长得唇红齿白,身上的额衣服也是干干净净崭...
    陶珍阅读 184评论 1 1
  • 1. Moscow radio said Russia had lived up to its end of th...
    銽蘛阅读 103评论 0 1