首先引入库CoreBluetooth.framework
引入头文件
#import <CoreBluetooth/CoreBluetooth.h>
遵守代理
CBPeripheralDelegate,CBCentralManagerDelegate
#pragma mark - 蓝牙
@property BOOL cbReady;
@property (nonatomic, strong) CBCentralManager *manager;
@property (nonatomic, strong) CBPeripheral *peripheral;
@property (strong ,nonatomic) CBCharacteristic *writeCharacteristic;
@property (strong,nonatomic) NSMutableArray *nDevices;
@property (strong,nonatomic) NSMutableArray *nServices;
@property (strong,nonatomic) NSMutableArray *nCharacteristics;
@property (nonatomic,strong) NSMutableArray *nPeripherals;
#pragma mark - 蓝牙
- (void)initBluetooth
{
//实例化
_manager = [[CBCentralManager alloc] initWithDelegate:self queue:nil];
_cbReady = false;
_nDevices = [[NSMutableArray alloc]init];
_nServices = [[NSMutableArray alloc]init];
_nCharacteristics = [[NSMutableArray alloc]init];
_nPeripherals = [[NSMutableArray alloc] init];
}
//扫描
-(void)scanBluetooth
{
NSLog(@"正在扫描外设...");
NSDictionary *options = [NSDictionary dictionaryWithObject:[NSNumber numberWithBool:NO] forKey:CBCentralManagerScanOptionAllowDuplicatesKey];
[_manager scanForPeripheralsWithServices:nil options:options];
double delayInSeconds = 10.0;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
[self.manager stopScan];
NSLog(@"扫描超时,停止扫描");
});
}
//开始查看服务,蓝牙开启
-(void)centralManagerDidUpdateState:(CBCentralManager *)central
{
switch (central.state) {
case CBCentralManagerStatePoweredOn:
NSLog(@"蓝牙已打开,请扫描外设");
[self scanBluetooth];break;
case CBCentralManagerStatePoweredOff:
NSLog(@"请打开蓝牙");break;
default:
break;
}
}
//查到外设后,停止扫描,连接设备
-(void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI
{
[_nPeripherals addObject:peripheral];
NSLog(@"%@",[NSString stringWithFormat:@"已发现 peripheral: %@ rssi: %@, name: %@ advertisementData: %@ ", peripheral, RSSI, peripheral.name, advertisementData]);
BOOL replace = NO;
// Match if we have this device from before
for (int i=0; i < _nDevices.count; i++) {
CBPeripheral *p = [_nDevices objectAtIndex:i];
if ([p isEqual:peripheral]) {
[_nDevices replaceObjectAtIndex:i withObject:peripheral];
replace = YES;
}
}
if (!replace) {
[_nDevices addObject:peripheral];
}
for(int i = 0;i < _nPeripherals.count;i++)
{
CBPeripheral *per = [_nPeripherals objectAtIndex:i];
NSLog(@"%@ - %@ - %d",per.name,[[NSUserDefaults standardUserDefaults] objectForKey:@"m_device"],[per.name isEqualToString:[[NSUserDefaults standardUserDefaults] objectForKey:@"m_device"]]);
if([per.name isEqualToString:[[NSUserDefaults standardUserDefaults] objectForKey:@"m_device"]])
{
_peripheral = per;
//连接蓝牙
[self.manager connectPeripheral:_peripheral options:nil];
[self.manager stopScan];//停止扫描
return;
}
else
{
//重新扫描
[self scanBluetooth];
}
}
}
//连接外设成功,开始发现服务
- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral {
NSLog(@"%@",[NSString stringWithFormat:@"成功连接 peripheral: %@ with name:%@ identifier = %@ name:%@",peripheral,peripheral.name,peripheral.identifier,peripheral.name]);
[self.peripheral setDelegate:self];
[self.peripheral discoverServices:nil];
}
//连接外设失败
-(void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error
{
NSLog(@"连接外设失败 = %@",error);
}
//已发现服务
-(void) peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error{
NSLog(@"发现服务.");
int i=0;
for (CBService *service in peripheral.services) {
[self.nServices addObject:service];
}
for (CBService *service in peripheral.services) {
NSLog(@"%@",[NSString stringWithFormat:@"%d :服务 UUID: %@(%@)",i,service.UUID.data,service.UUID]);
i++;
[peripheral discoverCharacteristics:nil forService:service];
}
}
//已搜索到Characteristics
-(void) peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error{
NSLog(@"%@",[NSString stringWithFormat:@"发现特征的服务:%@ (%@)",service.UUID.data ,service.UUID]);
for (CBCharacteristic *characteristic in service.characteristics) {
NSLog(@"%@",[NSString stringWithFormat:@"特征 UUID: %@",characteristic.UUID]);
//FFE1服务 FFE2读 FFE3写
if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:@"FFE3"]]) {
_writeCharacteristic = characteristic;
[_peripheral writeValue:[[NSString stringWithFormat:@"m1=200\n"] dataUsingEncoding:NSUTF8StringEncoding] forCharacteristic:_writeCharacteristic type:CBCharacteristicWriteWithResponse];
((UIButton *)[self.view viewWithTag:10]).selected = YES;
}
if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:@"FFE2"]]) {
[_peripheral readValueForCharacteristic:characteristic];
[self.peripheral setNotifyValue:YES forCharacteristic:characteristic];
}
[_nCharacteristics addObject:characteristic];
}
}
//获取外设发来的数据,不论是read和notify,获取数据都是从这个方法中读取。
- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
{
if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:@"FFE2"]]) {
NSLog(@"接收数据 = %@",[[NSString alloc] initWithData:characteristic.value encoding:NSUTF8StringEncoding]);
_flagFinish = [[NSString alloc] initWithData:characteristic.value encoding:NSUTF8StringEncoding];
NSLog(@"_flagFinish = %@",_flagFinish);
}
}
//中心读取外设实时数据
- (void)peripheral:(CBPeripheral *)peripheral didUpdateNotificationStateForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error {
if (error) {
NSLog(@"中心读取外设实时数据失败 %@", error.localizedDescription);
}
// Notification has started
if (characteristic.isNotifying == YES) {
[peripheral readValueForCharacteristic:characteristic];
// [self.peripheral setNotifyValue:YES forCharacteristic:characteristic];
} else { // Notification has stopped
// so disconnect from the peripheral
NSLog(@"Notification stopped on %@. Disconnecting", characteristic);
[self.manager cancelPeripheralConnection:self.peripheral];
}
NSLog(@"接收数据 = %@",[[NSString alloc] initWithData:characteristic.value encoding:NSUTF8StringEncoding]);
}
//用于检测中心向外设写数据是否成功
-(void)peripheral:(CBPeripheral *)peripheral didWriteValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
{
if (error) {
NSLog(@"发送数据失败=======%@",error.userInfo);
}else{
NSLog(@"发送数据成功");
}
}
注释:每一个蓝牙对应的特征服务都是不一样的,具体要看蓝牙的说明文档。