美文网首页iOS面试题相关知识点
【ios开发】3分钟完成蓝牙4.0开发

【ios开发】3分钟完成蓝牙4.0开发

作者: 我是孙小白 | 来源:发表于2018-12-18 17:29 被阅读163次

    今天来总结下关于蓝牙开发的一些知识点和具体使用,最近爱上了写这种总结性技术文章的感觉☺️☺️☺️

    关于蓝牙开发

    概念

    1. 开发时蓝牙外设必须为4.0及以上(蓝牙2.0需要MFI认证)。
    2. 蓝牙4.0设施耗电低,所以也叫低功耗蓝(BLE),他将三种规格集一体,包括传统蓝牙技术、高手技术和低耗能技术。

    框架

    当前ios开发中使用CoreBluetooth框架(基于BLE来开发)。

    CoreBluetooth框架的核心

    1. peripheral(外设):被连接的硬件,例如外部蓝牙
    2. central(中心):连接硬件的设备,例如你的苹果手机

    对于外设来说:
    一个外设包含多个服务(service),每一个服务中又包含多个特征(characteristic).

    每个服务包含多个字段,每个字段都可以有不同的权限:read(读)、write(写)、notify(通知)。
    每个特征包括特征值和特征描述。

    两种开发模式

    • 中心模式流程

    1、创建一个CBCentralManager实例来进行蓝牙管理;
    2、搜索扫描外设;
    3、连接外设;
    4、获得外设的服务和特征;
    5、从外设读取数据;
    6、给外设发送(写入)数据。

    • 外设模式流程

    1、创建一个外设角色;
    2、设置本地外设的服务和特征;
    3、发布外设和特征;
    4、广播服务;
    5、响应中心的读写请求;
    6、发送更新的特征值,订阅中心;

    基于中心模式的具体开发步骤

    info.plist里面添加权限管理:Privacy - Bluetooth Peripheral Usage Description

    权限管理.png

    1、导入头文件:#import <CoreBluetooth/CoreBluetooth.h>

    2、创建管理者对象并且设置代理
    @property (nonatomic, strong) CBCentralManager *centerManager;

    - (CBCentralManager *)centerManager
    {
        if (!_centerManager)
        {
            _centerManager = [[CBCentralManager alloc] initWithDelegate:self queue:nil];
        }
        return _centerManager;
    }
    

    3、实现代理,开始扫描(扫描外设必须在管理者状态开启时)

    #pragma mark - CBCentralManagerDelegate
    
    // 必须实现:中心管理者状态发生变化,在扫描外设之前调用
    - (void)centralManagerDidUpdateState:(CBCentralManager *)central
    {
        self.peripheralState = central.state;
        
        NSLog(@"当前管理者状态:%ld",(long)central.state);
        
        if (@available(iOS 10.0, *))
        {
            if (central.state == CBManagerStatePoweredOn)
            {
                [self.centerManager scanForPeripheralsWithServices:nil options:nil];
            }
        }
    }
    
    #pragma mark - 开始扫描
    - (void)startScanBtnClick
    {
        [self.centerManager stopScan];
        
        if (@available(iOS 10.0, *))
        {
            if (self.peripheralState == CBManagerStatePoweredOn)
            {
                // 中心管理者处于开启状态并且可用, 扫描所有设备(nil代表所有)
                [self.centerManager scanForPeripheralsWithServices:nil options:nil];
            }
        }
    }
    

    4、扫描到设备将设备添加到我们的设备组 ,显示在界面上

    // 扫描到设备
    - (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary<NSString *, id> *)advertisementData RSSI:(NSNumber *)RSSI
    {
        NSLog(@"发现设备,设备名:%@",peripheral.name);
        
        if (![self.peripherals containsObject:peripheral])
        {
            [self.peripherals addObject:peripheral];
        }
        
        [self.mainTable reloadData];
    }
    

    这里插一个demo的界面显示:

    demo基本功能

    5、选择某一个设备 点击进行连接

    - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
    {
        CBPeripheral *peripheral = self.peripherals[indexPath.row];
        
        NSLog(@"开始连接%@",peripheral.name);
        [self.centerManager connectPeripheral:peripheral options:nil];
    }
    
    /**
     * 连接的三种状态,连接成功,连接失败,连接断开重连
     */
    
    - (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral
    {
        NSLog(@"设备%@ 连接成功",peripheral.name);
        
        // 设置设备的代理
        peripheral.delegate = self;
        
        // 扫描设备的服务 (可指定@[[CBUUID UUIDWithString:@""]], nil为扫描全部)
        [peripheral discoverServices:nil];
        
        self.peripheral = peripheral;
    }
    
    - (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error
    {
        NSLog(@"设备%@ 连接失败",peripheral.name);
    }
    
    - (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error
    {
        NSLog(@"设备%@ 断开连接",peripheral.name);
        
        [self.centerManager connectPeripheral:peripheral options:nil];
    }
    

    6、实现外设代理方法

    #pragma mark - CBPeripheralDelegate
    
    // 发现外设服务
    - (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error
    {
        for (CBService *service in peripheral.services)
        {
            NSLog(@"服务:%@",service.UUID.UUIDString);
            
            // 根据服务去扫描特征
            [peripheral discoverCharacteristics:nil forService:service];
        }
    }
    
    // 扫描到对应的特征
    - (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error
    {
        for (CBCharacteristic *characteristic in service.characteristics)
        {
            NSLog(@"特征值:%@",characteristic.UUID.UUIDString);
            
            // 可根据特征进行对比,来进行订阅
            [peripheral setNotifyValue:YES forCharacteristic:characteristic];
            
            /*
            // 发送下行指令,写入外设
            NSData *data = [@"跟硬件协议好的指令,发给蓝牙这条指令,蓝牙会返回给我对应的数据" dataUsingEncoding:NSUTF8StringEncoding];
            [peripheral writeValue:data forCharacteristic:characteristic type:CBCharacteristicWriteWithResponse];
             */
            
            // 当发现特征有描述,回调didDiscoverDescriptorsForCharacteristic
            [peripheral discoverDescriptorsForCharacteristic:characteristic];
        }
    }
    
    // 从外设读取数据
    - (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(nonnull CBCharacteristic *)characteristic error:(nullable NSError *)error
    {
        NSData *data = characteristic.value;
        NSDictionary *dataDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        
        NSLog(@"外设%@ 的特征数据:%@",peripheral.name,dataDic);
    }
    
    // 中心管理读取外设实时数据
    - (void)peripheral:(CBPeripheral *)peripheral didUpdateNotificationStateForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
    {
        if (characteristic.isNotifying)
        {
            [peripheral readValueForCharacteristic:characteristic];
        }
        else
        {
            NSLog(@"Notification stopped on %@.  Disconnecting", characteristic);
            [self.centerManager cancelPeripheralConnection:peripheral];
        }
    }
    

    以下是控制台的一个输出:

    外设连接.png

    到这里,整个蓝牙的基础使用就结束了。

    在实际的开发过程中, 最主要的是我们和硬件之间协议命令的定义,以及命令的接收和写入, 确定好返回数据的格式等。

    附上demo地址:蓝牙4.0开发

    如果本文对你有帮助,就不要吝啬给我一个大大的奖励吧❤️❤️❤️~


    爱你哟~

    相关文章

      网友评论

        本文标题:【ios开发】3分钟完成蓝牙4.0开发

        本文链接:https://www.haomeiwen.com/subject/kvrkkqtx.html