iOS蓝牙编程

来源:互联网 发布:描述性数据分析 编辑:程序博客网 时间:2024/05/17 11:34

 一、框架

a)               GameKit.framework:为游戏而设计,iOS设备之间数据共享,iOS7之前版本;

b)              MultipeerConnectivity.framework:取代GameKit.framework,不仅仅支持蓝牙还可以进行wi-fi网络的P2P操作;

c)               ExternalAccessory.framework:MFI(made foriPhone/iPad/iPod)蓝牙设备编程,兼容性好,通用型强;

d)              CoreBlue.framework:蓝牙BLE编程框架。

二、GameKit.framework

a)               #import<GameKit/GameKit.h>

b)              <GKPeerPickerControllerDelegate>

c)               @property (strong, nonatomic)GKSession * session;

d)              GKPeerPickerController *peerPickerController = [[GKPeerPickerController alloc] init]; [peerPickerControllershow];

e)               关键api:GKPeerPickerController/GKSession

三、MultipeerConnectivity.framework

a)               思想:广播发现

b)              #import<MultipeerConnectivity/MultipeerConnectivity.h>

c)               <MCSessionDelegate,MCAdvertiserAssistantDeletate>或则<MCSessionDelegate, MCBrowserViewControllerDelegate>

d)              关键api:MCSession/MCBrowserViewController/MCAdvertiserAssistant

四、ExternalAccessory.framework

a)               #import <ExternalAccessory/ExternalAccessory.h>

b)              <EAAccessoryDelegate>

关键api:EAAccessory/EAAccessoryManager/EASession

五、CoreBlue.framework

思想:中心设备 外围设备 服务 特征 描述

中心设备为客户端,外围设备为服务端,一个中心设备可以连接多个外围设备;

一个BLE设备有一个或多个服务,一个服务有一个或多个特征,一个特征有一个或多个描述;每个特征具有读写属性;;

关键api:

中心设备:CBCentralManager/CBPeripheral/CBService/CBCharacteristic/CBUUID

协议<CBCentralManagerDelegate, CBPeripheralDelegate>

外围设备:CBPeripheralManager/CBCentral/CBMutableService/CBMutableCharacteristic/CBATTRequest

协议<CBPeripheralManagerDelegate, CBCentralDelegate>

以常用的中心设备为例:

步骤:

1)              建立中心角色

2)              扫描外设

3)              连接外设

4)              扫描服务

5)              扫描特征

6)              读写操作

7)              断开连接

代码:

<span style="color:#3366ff;">////  ViewController.m//  BLEDemo////  Created by LiLeo on 16/6/22.//  Copyright © 2016年 LeoLi. All rights reserved.//#import "ViewController.h"#import <CoreBluetooth/CoreBluetooth.h>@interface ViewController ()<CBCentralManagerDelegate, CBPeripheralDelegate>@property (weak, nonatomic) IBOutlet UILabel *log;@property (strong, nonatomic) CBCentralManager * manage;@property (strong, nonatomic) NSMutableArray * peripherals;@end@implementation ViewController#pragma mark - 视图控制器- (void)viewDidLoad {    [super viewDidLoad];    // Do any additional setup after loading the view, typically from a nib.}- (void)didReceiveMemoryWarning {    [super didReceiveMemoryWarning];    // Dispose of any resources that can be recreated.}#pragma mark - 属性懒加载-(NSMutableArray *)peripherals {    if(_peripherals == nil) {        _peripherals = [NSMutableArray array];    }    return _peripherals;}#pragma mark - 私有方法- (void)writeToLog:(NSString *)info {    _log.text = [NSString stringWithFormat:@"%@\r\n%@", _log.text, info];}#pragma mark - 控制器事件- (IBAction)start:(id)sender {    _manage = [[CBCentralManager alloc] initWithDelegate:self queue:nil];}#pragma mark - CBCentralManagerDelegate的代理方法- (void)centralManagerDidUpdateState:(CBCentralManager *)central {    switch (central.state) {        case CBCentralManagerStatePoweredOn:            NSLog(@"BLE已打开");            [self writeToLog:@"BLE已打开"];            //开始扫描            [central scanForPeripheralsWithServices:nil options:@{CBCentralManagerScanOptionAllowDuplicatesKey:@YES}];            break;                    case CBCentralManagerStatePoweredOff:            NSLog(@"BLE已关闭");            break;                    case CBCentralManagerStateUnauthorized:            NSLog(@"未授权");            break;                    case CBCentralManagerStateUnsupported:            NSLog(@"不支持BLE");            break;                    case CBCentralManagerStateUnknown:            NSLog(@"未知状态");            break;                    case CBCentralManagerStateResetting:            NSLog(@"正在重置");            break;                    default:            break;    }}- (void)centralManager:(CBCentralManager *)central willRestoreState:(NSDictionary<NSString *,id> *)dict {}- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral {    NSLog(@"连接外围设备成功");    [self writeToLog:@"连接外围设备成功"];    peripheral.delegate = self;    [peripheral discoverServices:@[[CBUUID UUIDWithString:@""]]];}- (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error {    NSLog(@"已与外围设备断开连接");    NSLog(@"已与外围设备断开连接");}- (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error {    NSLog(@"连接外围设备失败");    [self writeToLog:@"连接外围设备失败"];}- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary<NSString *,id> *)advertisementData RSSI:(NSNumber *)RSSI {    NSLog(@"发现外围设备");    [self writeToLog:@"发现外围设备"];    [_manage stopScan];    if(peripheral) {        if(![_peripherals containsObject:peripheral]) {            [_peripherals addObject:peripheral];        }        NSLog(@"开始连接外围设备");        [self writeToLog:@"开始连接外围设备"];        [_manage connectPeripheral:peripheral options:nil];    }}#pragma mark - CBPeripheralDelegate里面的代理方法- (void)peripheralDidUpdateName:(CBPeripheral *)peripheral {}- (void)peripheral:(CBPeripheral *)peripheral didModifyServices:(NSArray<CBService *> *)invalidatedServices {}- (void)peripheral:(CBPeripheral *)peripheral didReadRSSI:(NSNumber *)RSSI error:(NSError *)error {}- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error {    NSLog(@"已发现可用服务");    [self writeToLog:@"已发现可用服务"];    if(error) {        NSLog(@"查找服务过程中出现错误,错误信息:%@", error);        [self writeToLog:@"查找服务过程中出现错误"];    }    for(CBService * service in peripheral.services) {        if([service.UUID isEqual:[CBUUID UUIDWithString:@""]]) {            [peripheral discoverCharacteristics:@[[CBUUID UUIDWithString:@""]] forService:service];        }    }}- (void)peripheral:(CBPeripheral *)peripheral didWriteValueForDescriptor:(CBDescriptor *)descriptor error:(NSError *)error {}- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForDescriptor:(CBDescriptor *)descriptor error:(NSError *)error {}- (void)peripheral:(CBPeripheral *)peripheral didWriteValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error {}- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error {    if(characteristic.value) {        NSString * value = [[NSString alloc] initWithData:characteristic.value encoding:NSUTF8StringEncoding];        NSLog(@"读取到特征值:%@", value);        [self writeToLog:[NSString stringWithFormat:@"读取到特征值:%@", value]];    }else {        [self writeToLog:@"未发现特征值"];    }}- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error {    NSLog(@"已发现可用特征");    [self writeToLog:@"已发现可用特征"];    if([service.UUID isEqual:[CBUUID UUIDWithString:@""]]){        for (CBCharacteristic * characteristic in service.characteristics) {            if([characteristic.UUID isEqual:[CBUUID UUIDWithString:@""]]) {                [peripheral setNotifyValue:YES forCharacteristic:characteristic];//设置订阅            }        }    }}- (void)peripheral:(CBPeripheral *)peripheral didDiscoverIncludedServicesForService:(CBService *)service error:(NSError *)error {}- (void)peripheral:(CBPeripheral *)peripheral didDiscoverDescriptorsForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error {}- (void)peripheral:(CBPeripheral *)peripheral didUpdateNotificationStateForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error {    NSLog(@"收到特征更新通知");    [self writeToLog:@"收到特征更新通知"];    if([characteristic.UUID isEqual:[CBUUID UUIDWithString:@""]]) {        if(characteristic.isNotifying) {            if(characteristic.properties == CBCharacteristicPropertyNotify) {                NSLog(@"已订阅特征通知");                [self writeToLog:@"已订阅特征通知"];            }else if(characteristic.properties == CBCharacteristicPropertyRead) {                [peripheral readValueForCharacteristic:characteristic];            }        }else {            NSLog(@"特征已停止");            [self writeToLog:@"特征已停止"];            [_manage cancelPeripheralConnection:peripheral];        }    }}- (void)peripheralDidUpdateRSSI:(CBPeripheral *)peripheral error:(NSError *)error {}@end</span>

整理参考:

http://www.cnblogs.com/kenshincui/p/4220402.html#bluetooth

http://blog.csdn.net/pony_maggie/article/details/26740237

http://www.jianshu.com/p/760f042a1d81

http://blog.shiqichan.com/ios-central-using-ble/

http://my.oschina.net/u/2340880/blog/548127

0 0
原创粉丝点击