iOS蓝牙开发

栏目: IOS · 发布时间: 4年前

内容简介:当前iOS中的蓝牙开发使用的都是系统自带的蓝牙库<CoreBluetooth/CoreBluetooth.h>蓝牙设备必须是4.0或者以上CoreBluetooth框架中的核心是peripheral和central, 它们分别表示外设和中心,设备上可以认为手机就是中心, 蓝牙设备就是外设

当前iOS中的蓝牙开发使用的都是系统自带的蓝牙库<CoreBluetooth/CoreBluetooth.h>

蓝牙设备版本要求

蓝牙设备必须是4.0或者以上

CoreBluetooth框架的核心

CoreBluetooth框架中的核心是peripheral和central, 它们分别表示外设和中心,设备上可以认为手机就是中心, 蓝牙设备就是外设

服务和特征

蓝牙设备它有若干个服务service,每个服务里面有包含若干个特征characteristic,特征就是提供数据的地方

外设, 服务, 特征间的关系

iOS蓝牙开发

CoreBluetooth框架的架构

iOS蓝牙开发

连接蓝牙的具体实现

实现流程

1.建立中心角色

2.扫描外设

3.连接外设

4.获取外设中的服务和特征

5.与外设做交互

实现步骤

1.导入CoreBluetooth头文件,添加代理,建立中心角色

#import <CoreBluetooth/CoreBluetooth.h>
@interface ViewController : UIViewController<CBCentralManagerDelegate,CBPeripheralDelegate>
@property (strong, nonatomic) CBCentralManager *centralManager;               //蓝牙管理者
@property(strong,nonatomic)CBPeripheral *peripheral;                      //存储匹配成功的外设

-(void)viewDidLoad {
    [super viewDidLoad];
    
    //初始化,最后一个线程参数可以为nil,默认是main线程
    self.centralManager = [[CBCentralManager alloc] initWithDelegate:self queue:dispatch_get_main_queue()];
}
复制代码

2.扫描外设

/*
    1.初始化成功会自动调用
    2.必须实现的代理,返回centralManager的状态
    3.只有在状态为CBManagerStatePoweredOn的情况下才可以开始扫描外设
*/
-(void)centralManagerDidUpdateState:(CBCentralManager *)central {
    switch (central.state) {
        case CBManagerStateUnknown:
            NSLog(@">>>未知");
            break;
        case CBManagerStateResetting:
            NSLog(@">>>重置");
            break;
        case CBManagerStateUnsupported:
            NSLog(@">>>设备不支持");
            break;
        case CBManagerStateUnauthorized:
            NSLog(@">>>设备未授权");
            break;
        case CBManagerStatePoweredOff:
        {
            NSLog(@">>>设备关闭");
            self.bleStatusBlock(NO);
        }
            break;
        case CBManagerStatePoweredOn:
        {
            NSLog(@">>>设备打开");
             //开始扫描外设, 然后会进入didDiscoverPeripheral方法
            /*
                1. 两个参数为nil表示默认扫描所有可见的蓝牙设备
                2. 第一个参数用来设置扫描有指定服务的外设
                3. 第二个参数用来设置是否重复扫描已经发现的设备
                
                NSDictionary *options = [NSDictionary dictionaryWithObject:[NSNumber numberWithBool:YES] forKey:CBCentralManagerScanOptionAllowDuplicatesKey];
                
                Bool值为Yes,表示重复扫描, 反之表示不会重复扫描
                
            */
            [self.centralManager scanForPeripheralsWithServices:nil options:nil];
        }
            break;
            
        default:
            break;
    }
}
复制代码

连接外设

//扫描到的设备可以在这个方法里面打印
-(void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(nonnull CBPeripheral *)peripheral advertisementData:(nonnull NSDictionary<NSString *,id> *)advertisementData RSSI:(nonnull NSNumber *)RSSI {
    NSLog(@">>>advertisementData :%@  name :%@ ",advertisementData,peripheral.name);
    
    //有些产品是根据Mac地址来进行配对, 在这里我们就可以拿到,具体什么规则, 根据各个蓝牙设备来定
    NSData *data = [advertisementData objectForKey:@"kCBAdvDataManufacturerData"];
    //解析
    //.....
    if(自己的判断) {
        //找到的设备必须持有它,否则CBCentralManager中也不会保存peripheral,那么CBPeripheralDelegate中的方法也不会被调用!!
        self.peripheral = peripheral;
        
        //停止扫描
        [self.centralManager stopScan];
        
        //连接外设
        [_centralManager connectPeripheral:peripheral options:nil];
    }
}

//连接到Peripherals-成功
- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral
{
    NSLog(@">>>连接到名称为(%@)的设备-成功",peripheral.name);
}

//连接到Peripherals-失败
-(void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error
{
    NSLog(@">>>连接到名称为(%@)的设备-失败,原因:%@",[peripheral name],[error localizedDescription]);
}

//Peripherals断开连接
- (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error
{
    NSLog(@">>>外设连接断开连接 %@: %@\n", [peripheral name], [error localizedDescription]);
}
复制代码

获取外设中的服务和特征

//连接外设成功
-(void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral {
    
    NSLog(@">>>连接到名称为(%@)的设备-成功",peripheral.name);
    peripheral.delegate=self;//这个方法调用发现服务协议
    [peripheral discoverServices:nil];
}

//扫描到服务
-(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]){
        [peripheral discoverCharacteristics:nil forService:service];
    }
}

//扫描到特征
- (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.UUID,characteristic.UUID);
        
        //筛选你需要的UUID,进行连接
        if ([characteristic.UUID isEqual:yourUUID) {
        
            订阅,实时接收
            [peripheral setNotifyValue:YES forCharacteristic:characteristic];
        }
    }
}
复制代码

读取数据

//获取指定特性的数据
- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
{
    //接收蓝牙发来的数据
     NSLog(@"characteristic uuid:%@  value:%@",characteristic.UUID,characteristic.value);
}
复制代码

写入数据

//写入数据
-(void)writeData {
    [self.peripheral writeValue:data forCharacteristic:self.characteristic type:CBCharacteristicWriteWithResponse];
}

//写入数据的回调
- (void)peripheral:(CBPeripheral *)peripheral didWriteValueForCharacteristic:(CBCharacteristic *)characteristic error:(nullable NSError *)error
{
    if (error) {
         NSLog(@"error Discovered characteristics for %@ with error: %@", characteristic.UUID, [error localizedDescription]);
        return;
    }
    NSLog(@"characteristic uuid:%@  value:%@",characteristic.UUID,characteristic.value);
}
复制代码

断开连接

- (void)disConnect{
    [self.centralManager cancelPeripheralConnection:self.peripheral];
}
复制代码

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Apache Tomcat 6高级编程

Apache Tomcat 6高级编程

Vivek Chopra、Sing Li、Jeff Genender / 人民邮电出版社 / 2009-3 / 79.00元

《Apache Tomcat 6高级编程》全面介绍了安装、配置和运行Apache Tomcat服务器的知识。书中不仅提供了配置选项的逐行分析,还探究了Tomcat的特性和功能,可以帮助读者解决出现在系统管理的各个阶段的各种问题,包括共享主机、安全、系统测试和性能测试及调优。 《Apache Tomcat 6高级编程》重点讲解Tomcat 6的应用知识。从基本的Tomcat和Web应用程序配置......一起来看看 《Apache Tomcat 6高级编程》 这本书的介绍吧!

HTML 压缩/解压工具
HTML 压缩/解压工具

在线压缩/解压 HTML 代码

RGB转16进制工具
RGB转16进制工具

RGB HEX 互转工具

HEX HSV 转换工具
HEX HSV 转换工具

HEX HSV 互换工具