美文网首页
iOS-蓝牙的简单使用

iOS-蓝牙的简单使用

作者: 假装不是人 | 来源:发表于2017-04-17 13:27 被阅读0次

    蓝牙实现方案

    之前项目有用到蓝牙,这里记录一下蓝牙的一些简单使用.

    iOS提供了4个用于实现蓝牙连接的方案:

    1. ExternalAccessory.framework

    提供了配件链接iOS的通道,可用于第三方蓝牙设备交互(蓝牙设备必须需要苹果MFI认证,比较麻烦)

    2.MultipeerConnectivity.framework

    iOS7引入的多点连接,只能用于Apple设备,可在较近的距离基于蓝牙和WIFI发现和连接实现进场通信,有点和AirDrop类似,不过AirDrop必须同时打开WiFi和蓝牙,而且要保持较近的距离 ( 其过程相当于A放出广播,B用于搜索,B搜到之后向A发邀请,请求建立连接,A接受之后向B发送一个会话,建立连接)

    MCPeerID *_peerID = [[MCPeerID alloc] initWithDisplayName:[UIDevice currentDevice].name];//给设备自定义个名字
    MCSession *_session = [[MCSession alloc] initWithPeer:_peerID];//创建会话
    _session.delegate = self;//遵守<MCSessionDelegate>协议
    MCAdvertiserAssistant *_advertiser = [[MCAdvertiserAssistant alloc] initWithServiceType:@"chat-files"
                                                                       discoveryInfo:nil
                                                                       session:_session];
    //初始化广播服务,serviceType是类型标识符,通过文本描述来让浏览器发现广播者,只有相同的serviceType才能相互连接(要求1-15个字符,只能包含ASCII小写字母,数字和连字符)
    [_advertiser start]; //开始广播   stop关闭广播
    
    MCBrowserViewController *_browser = [[MCBrowserViewController alloc] initWithServiceType:@"chat-files"session:_session]; // 创建视图浏览器
    _browser.delegate = self; //遵守<MCBrowserViewControllerDelegate>协议
    [self presentViewController: _browser animated:YES completion:nil]; //弹出视窗
    
    //<MCBrowserViewControllerDelegate>
    -(void)browserViewControllerDidFinish:(MCBrowserViewController *)browserViewController{//完成
        [_browser dismissViewControllerAnimated:YES completion:nil];
    }
    
    -(void)browserViewControllerWasCancelled:(MCBrowserViewController *)browserViewController{//取消
        [_browser dismissViewControllerAnimated:YES completion:nil];
    }
    
    //浏览器提供连接功能 ,等连接之后就根据情况实现<MCSessionDelegate>方法
    -(void)session:(MCSession *)session peer:(MCPeerID *)peerID didChangeState:(MCSessionState)state{
        //新的连接发生时,会被调用   state状态如下:
        //MCSessionStateNotConnected,     // Not connected to the session.
        //    MCSessionStateConnecting,       // Peer is connecting to the session.
        //    MCSessionStateConnected    
    }
    
    
    -(void)session:(MCSession *)session didReceiveData:(NSData *)data fromPeer:(MCPeerID *)peerID{
        //接受数据
    }
    
    
    -(void)session:(MCSession *)session didStartReceivingResourceWithName:(NSString *)resourceName fromPeer:(MCPeerID *)peerID withProgress:(NSProgress *)progress{
        //开始接受资源
    }
    
    
    -(void)session:(MCSession *)session didFinishReceivingResourceWithName:(NSString *)resourceName fromPeer:(MCPeerID *)peerID atURL:(NSURL *)localURL withError:(NSError *)error{
        //结束接收资源
    }
    
    
    -(void)session:(MCSession *)session didReceiveStream:(NSInputStream *)stream withName:(NSString *)streamName fromPeer:(MCPeerID *)peerID{
        //接收流
    }
    
    [_session sendData: dataToSend toPeers:_session.connectedPeers withMode:MCSessionSendDataReliable error:&error]; //发送数据给所有连接的设备
    
    连接流程图.png
    3.GameKit.framework

    用于Apple设备之间的连接,更多用于游戏方面,从iOS7废弃.此方案可以增加对等连接,无需连接到互联网

    GKPeerPickerController *gpp = [[GKPeerPickerController alloc] init];//创建查找设备控制器
    gpp.connectionTypesMask = GKPeerPickerConnectionTypeNearby | GKPeerPickerConnectionTypeOnline;
    //nearby指蓝牙 online指WIFI
    gpp.delegate = self; // 遵守<GKPeerPickerControllerDelegate>协议
    [gpp show];//弹出控制器
    
    //<GKPeerPickerControllerDelegate>协议
    - (void)peerPickerController:(GKPeerPickerController *)picker didConnectPeer:(NSString *)peerID toSession:(GKSession *)session
    {
        //设备连接成功后调用方法
        [self.session setDataReceiveHandler:self withContext:nil]; // 设置数据接受者
        [picker dismiss]; // 退出查找设备的控制器
    }
    
    - (void) receiveData:(NSData *)data fromPeer:(NSString *)peer inSession: (GKSession *)session context:(void *)context
    {
        //接收数据的时候会调用该方法
    }
    
    [self.session sendDataToAllPeers: data withDataMode:GKSendDataReliable error:nil];//发送数据
    [self.session sendData:data toPeers: peers withDataMode:GKSendDataReliable error:nil];//往指定peer发送数据
    
    
    4.CoreBluetooth.framework (蓝牙4.0)

    以低功耗著称,可用于第三方蓝牙设备交互,对硬件上是有一定要求的,iPhone 4S及以后的设备,第三代iPad及以后的设备是支持这一标准的

    核心结构图如下

    CoreBluetooth结构图.png

    每个蓝牙设备必有一个或多个Service ,一个Service有若干个Characteristic,它们都是用UUID来唯一识别

    @property(nonatomic,strong)CBCentralManager *_mgr;//中央管理者
    
    //初始化中央管理者
     _mgr = [[CBCentralManager alloc] initWithDelegate:self queue:nil];
    
    //遵守<CBCentralManagerDelegate>协议
    - (void)centralManagerDidUpdateState:(CBCentralManager *)central
    {
        //状态发生改变的时候会执行该方法(蓝牙4.0没有打开变成打开状态就会调用该方法)
         switch (central.state) {
            case CBCentralManagerStatePoweredOn:
                NSLog(@"打开,可用");
                //扫描周围的蓝牙 options参数 允许中央设备多次收到曾经监听到的设备的消息
                [_mgr scanForPeripheralsWithServices:nil options:@{CBCentralManagerScanOptionAllowDuplicatesKey:@(NO)}];
                break;
            case CBCentralManagerStatePoweredOff:
                NSLog(@"可用,未打开");
                break;
            case CBCentralManagerStateUnsupported:
                NSLog(@"SDK不支持");
                break;
            case CBCentralManagerStateUnauthorized:
                NSLog(@"程序未授权");
                break;
            case CBCentralManagerStateResetting:
                NSLog(@"CBCentralManagerStateResetting");
                break;
            case CBCentralManagerStateUnknown:
                NSLog(@"CBCentralManagerStateUnknown");
                break;
    }
    
    //搜索到蓝牙设备之后调用
    - (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI
    {
    //一次返回一个设备信息 RSSI为信号强度,可以将信息放入数组中
       //peripheral.identifier.UUIDString 蓝牙设备的唯一标识
    }
    
    //连接设备
    [self.mgr connectPeripheral:peripheral options:@{CBConnectPeripheralOptionNotifyOnDisconnectionKey:@(YES)}];
    
    [self.manager stopScan];//停止扫描外设
    
    //连接外围设备之后调用
    - (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral
    {
        // 1.扫描所有的服务
        // serviceUUIDs:指定要扫描该外围设备的哪些服务(传nil,扫描所有的服务)
        [peripheral discoverServices:nil];
        
        // 2.设置代理,为了后面查询外设的服务和外设的特性
        //<CBPeripheralDelegate>协议
        peripheral.delegate = self;
    }
    - (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(nullable NSError *)error
    {
        //连接失败调用
        NSLog(@"didFailToConnectPeripheral");
    }
    
    //遵循<CBPeripheralDelegate>协议
    - (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error
    {
    //发现外围设备的服务
        for (CBService *serivce in peripheral.services) {
            if ([serivce.UUID.UUIDString isEqualToString:@"123456"]) {
                // characteristicUUIDs : 可以指定想要扫描的特征(传nil,扫描所有的特征)
                [peripheral discoverCharacteristics:nil forService:serivce];
            }
        }
    }
    
    - (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error
    {
    //发现服务后,当扫描到服务的特征时调用
        for (CBCharacteristic *characteristic in service.characteristics) {
            if ([characteristic.UUID.UUIDString isEqualToString:@"456"]) {
                // 拿到特征,和外围设备进行交互
                 CBCharacteristicProperties proper = characteristic.properties;   
                 if (proper & CBCharacteristicPropertyBroadcast){} //广播特性
                 if (proper & CBCharacteristicPropertyRead){
                 //读特性
                       [peripheral readValueForCharacteristic:characteristic];
                 }
                 if (proper & CBCharacteristicPropertyWriteWithoutResponse){
                 //写特性不需要响应,可以保存特征以便后续写数据
                 }
                 if (properties & CBCharacteristicPropertyWrite) {
                 //如果具备写入值的特性,这个应该会有一些响应
                 }
                 if (properties & CBCharacteristicPropertyNotify) {
                 //如果具备通知的特性
                 [peripheral setNotifyValue:YES forCharacteristic:character];
                 } 
            }
        }
    }
    
    //通知代理
    - (void)peripheral:(CBPeripheral *)peripheral didUpdateNotificationStateForCharacteristic:(nonnull CBCharacteristic *)characteristic error:(nullable NSError *)error
    {
        CBCharacteristicProperties properties = characteristic.properties;
        if (properties & CBCharacteristicPropertyRead) {
            //如果具备读特性,即可以读取特性的value
            [peripheral readValueForCharacteristic:characteristic];
        }
    }
    
    //读取特性中的值调用
    - (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
    {
        NSData *data = characteristic.value;
        if (data.length <= 0) {
            return;
        }
        NSString *info = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    }
    
    //往设备写数据
     [peripheral writeValue: data forCharacteristic: chatacter type:CBCharacteristicWriteWithoutResponse];
    
    //取消与设备连接
    [self.manager cancelPeripheralConnection:peripheral];
    //断开连接的代理
    - (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(nullable NSError *)error;
    

    相关文章

      网友评论

          本文标题:iOS-蓝牙的简单使用

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