蓝牙
//
// ViewController.m
// 蓝牙
//
// Created by 谢泽锋 on 15/11/2.
// Copyright (c) 2015年 xiezefeng. All rights reserved.
//
#import "ViewController.h"
#import <CoreBluetooth/CoreBluetooth.h>
@interface ViewController ()<CBCentralManagerDelegate,CBPeripheralDelegate>
@property(nonatomic,strong)CBCentralManager*mgr;
@property(nonatomic,strong)NSMutableArray* peripherals;
@end
@implementation ViewController
-(NSMutableArray *)peripherals
{
if (!_peripherals) {
_peripherals=[NSMutableArray array];
}
return _peripherals;
}
-(CBCentralManager *)mgr
{
if (!_mgr) {
}return _mgr;
}
- (void)viewDidLoad {
[super viewDidLoad];
//扫描设备
// CBService * service;
// service.UUID;
// CBCharacteristic * characteristic;
// characteristic.UUID;
self.mgr =[[CBCentralManager alloc]initWithDelegate:self queue:nil];
// Do any additional setup after loading the view, typically from a nib.
}
-(void)centralManagerDidUpdateState:(CBCentralManager *)central{
if (central.state==CBCentralManagerStatePoweredOn) {
[self.mgr scanForPeripheralsWithServices:nil options:nil];
}
}
#pragma mark 发现外围设备
-(void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI
{
//添加外围设备
if (![self.peripherals containsObject:peripheral]) {
[self.peripherals addObject:peripheral];
NSLog(@"查找到外围设备%@", peripheral.name);
}
peripheral.delegate=self;
}
#pragma mark CBPeripheralDelegate
//外部设备查找到的服务
-(void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error
{
//过滤掉不想要的服务
for (CBService*servier in peripheral.services ) {
//过滤掉不想要的服务
NSLog(@"%@",servier.UUID);
// 扫描服务下面的特性
[peripheral discoverCharacteristics:nil forService: servier];
}
}
#pragma mark 服务下的特征;
-(void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error
{
//过滤掉不想要的特征
for (CBCharacteristic*Characteristic in service.characteristics ) {
//过滤掉不想要的特征
NSLog(@"%@",Characteristic.UUID);
// 扫描服务下面的特性
}
}
- (IBAction)connect:(id)sender {
[self buildContent];
}
#pragma mark 连接外围设备
-(void)buildContent
{
for (CBPeripheral * perpheral in self.peripherals) {
[self.mgr connectPeripheral:perpheral options:nil];
perpheral.delegate=self;
}
}
//连接到某个外设备的时候调用
-(void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral
{
//查找扫描外设中是所有服务
[peripheral discoverServices:nil];//空是所有
peripheral.delegate=self;
}
//跟某个外部设备失去连接
-(void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error
{
NSLog(@"失去连接%@",error);
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end