码迷,mamicode.com
首页 > 移动开发 > 详细

CoreBluetooth——IOS蓝牙4.0使用心得

时间:2016-09-10 13:01:38      阅读:303      评论:0      收藏:0      [点我收藏+]

标签:

原文链接:http://m.blog.csdn.net/article/details?plg_nld=1&id=51014318&plg_auth=1&plg_uin=1&plg_usr=1&plg_vkey=1&plg_nld=1&plg_d


文章出处http://blog.csdn.net/xgcyangguang



所做的东西是通过手机/pad与蓝牙4.0的设备进行连接,之后设备上按对应的按键我们会收到对应的数值。首先需要和做蓝牙4.0的同事沟通好通信协议,具体的数据解析部分就不过多赘述了,主要写一下蓝牙接收数据的部分


 


1.和做蓝牙的同事沟通好设备的UUID以及特点,可以把他们写成宏


 


#define TRANSFER_SERVICE_UUID           @"0000fff0-0000-1000-8000-00805f9b34fb"
#define TRANSFER_CHARACTERISTIC_UUID    @"0000fff7-0000-1000-8000-00805f9b34fb"
 

 


2.在.H文件中导入两个头文件,并在接口中实现两个协议


 


#import "ViewController.h"
#import <CoreBluetooth/CoreBluetooth.h>
#import "UUID.h"

//需要实现协议
@interface ViewController () < CBCentralManagerDelegate, CBPeripheralDelegate>
{

}

3.创建两个蓝牙设备属性,一个相当于主机,一个相当于外设从机

#pragma mark 蓝牙设备
@property (strong, nonatomic) CBCentralManager      *centralManager;         //接收
@property (strong, nonatomic) CBPeripheral          *discoveredPeripheral;   //外设

@end
4.开始蓝牙配置
#pragma mark 在初始化界面结束后设置自己为代理
- (void)viewDidLoad {
    [super viewDidLoad];
    
   _centralManager = [[CBCentralManager alloc] initWithDelegate:self queue:nil];
}

#pragma mark 此处监控一下中央的状态值,可以判断蓝牙是否开启/可用
- (void)centralManagerDidUpdateState:(CBCentralManager *)central
{
    NSMutableString *stringForCentralManagerState = [NSMutableString stringWithString:@"UpdateState:"];
    
    switch (central.state) {
        case CBCentralManagerStateUnknown:
            [stringForCentralManagerState appendString:@"Unkown\n"];
            break;
        case CBCentralManagerStateUnsupported:
            [stringForCentralManagerState appendString:@"Unsupported\n"];
        case CBCentralManagerStateUnauthorized:
            [stringForCentralManagerState appendString:@"Unauthorized\n"];
        case CBCentralManagerStateResetting:
            [stringForCentralManagerState appendString:@"Resetting\n"];
        case CBCentralManagerStatePoweredOff:
            [stringForCentralManagerState appendString:@"PowerOff\n"];
        case CBCentralManagerStatePoweredOn:
            //设备支持BLE并且可用
            [stringForCentralManagerState appendString:@"PoweredOn\n"];
            
            //开始搜索
            [self scan];
            break;
        default:
            [stringForCentralManagerState appendString:@"none\n"];
            break;
    }
    NSLog(@"%@", stringForCentralManagerState);

}

#pragma mark 扫描
- (void)scan
{
    
    //第一个参数如果设置为nil,会寻找所有service
    [self.centralManager scanForPeripheralsWithServices:@[[CBUUID UUIDWithString:TRANSFER_SERVICE_UUID]]
     options:@{ CBCentralManagerScanOptionAllowDuplicatesKey : @YES }];
     
    
     NSLog(@"Scanning started");
}

#pragma mark 发现设备,连接
//一旦符合要求的设备被发现,就会回调此方法
- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI
{
    
    NSLog(@"Discovered %@ at %@", peripheral.name, RSSI);
    
    if (self.discoveredPeripheral != peripheral) {
        
        self.discoveredPeripheral = peripheral;
        
        // 连接
        NSLog(@"Connecting to peripheral %@", peripheral);
        [self.centralManager connectPeripheral:peripheral options:nil];
    }
}

#pragma mark 未能连接的处理方法
- (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error
{
    NSLog(@"Failed to connect to %@. (%@)", peripheral, [error localizedDescription]);
//    [self cleanup];
}

#pragma mark 当连接上设备
- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral
{
    NSLog(@"Peripheral Connected");
    
    // 已连接上设备,故停止搜索
    [self.centralManager stopScan];
    NSLog(@"Scanning stopped");
    // Make sure we get the discovery callbacks
    peripheral.delegate = self;
    
    // 寻找指定UUID的Service
    [peripheral discoverServices:@[[CBUUID UUIDWithString:TRANSFER_SERVICE_UUID]]];
}

#pragma mark 发现设备上指定Service会回调此处
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error
{
    if (error) {
        NSLog(@"Error discovering services: %@", [error localizedDescription]);
        return;
    }
    
    // 寻找指定UUID的Characteristic
    for (CBService *service in peripheral.services) {
        [peripheral discoverCharacteristics:@[[CBUUID UUIDWithString:TRANSFER_CHARACTERISTIC_UUID]] forService:service];
    }
}
#pragma mark 找到指定UUID的Characteristic会回调此处
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error
{
    if (error) {
        NSLog(@"Error discovering characteristics: %@", [error localizedDescription]);
 
        return;
    }
    
    for (CBCharacteristic *characteristic in service.characteristics) {
        if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:TRANSFER_CHARACTERISTIC_UUID]]) {
            NSLog(@"find the characteristic");
            
            
            [peripheral setNotifyValue:YES forCharacteristic:characteristic];
            
        }
    }
}


- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
{
    if (error) {
        
               NSLog(@"Error discovering characteristics: %@", [error localizedDescription]);
        return;
    }
    
    NSLog(@"value --> %@",characteristic.value);
   
#pragma mark 把接收到的数据进行截取
//此处我们就可以拿到value值对其进行数据解析了
    NSData *data = characteristic.value;

 }

#pragma mark 蓝牙断开后自动重连
-(void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error

{
    
    NSLog(@"Peripheral Disconnected");
    self.discoveredPeripheral = nil;
    [self scan];
    
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"蓝牙连接状态" message:@"连接已断开" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:@"关闭", nil];
    [alert show];
   
}


5.蓝牙后台运行

若要实现蓝牙4.0在APP进入后台时仍能工作,传输数据,不用写代码,只需要修改xxx-info.plist文件即可

在所需的背景模式中加入两项

使用CoreBluetooth应用程序共享数据  和  应用程序进行通信使用CoreBluetooth即可
 

CoreBluetooth——IOS蓝牙4.0使用心得

标签:

原文地址:http://www.cnblogs.com/linxiu-0925/p/5859087.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!