由于最近在看一个手机用蓝牙控制擦玻璃机器人的项目,接触到了蓝牙,网上查资料实现了app基本功能!
导包:
#import <CoreBluetooth/CoreBluetooth.h>
实现代理:
<CBCentralManagerDelegate, CBPeripheralDelegate>
定义属性:
@property (nonatomic, strong) CBCentralManager *manager;
@property (nonatomic, strong) CBPeripheral *peripheral;
创建蓝牙管理者对象:
self.manager = [[CBCentralManager alloc] initWithDelegate:self queue:nil];
实现蓝牙的一些代理方法:// 该方法当蓝牙状态改变(打开或者关闭)的时候就会调用
-(void)centralManagerDidUpdateState:(CBCentralManager *)central{ switch (central.state) { case CBManagerStatePoweredOn: { NSLog(@"蓝牙已打开,请扫描外设"); // 第一个参数填nil代表扫描所有蓝牙设备,第二个参数options也可以写nil [_manager scanForPeripheralsWithServices:nil options:@{CBCentralManagerScanOptionAllowDuplicatesKey : [NSNumber numberWithBool:YES]}]; } break; case CBManagerStatePoweredOff: { NSLog(@"蓝牙没有打开,请先打开蓝牙"); } break; default: { NSLog(@"该设备不支持蓝牙功能,请检查系统设置"); } break; }}
查到外设后,停止扫描,连接设备
-(void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI { // 可在该方法内部区分扫描到的蓝牙设备 NSLog(@"已发现 peripheral: %@ rssi: %@, UUID: %@ advertisementData: %@ ", peripheral.name, RSSI, peripheral.identifier, advertisementData); _peripheral = peripheral; [_manager connectPeripheral:_peripheral options:nil]; // 扫描到设备之后停止扫描 [_manager stopScan];}
连接外设成功,开始发现服务
- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral { NSLog(@"成功连接 peripheral: %@ with UUID: %@",peripheral,peripheral.identifier); // 连接设备之后设置蓝牙对象的代理,扫描服务 [self.peripheral setDelegate:self]; [self.peripheral discoverServices:nil]; NSLog(@"扫描服务"); }
连接外设失败
-(void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error{ NSLog(@"%@",error);}
获取热点强度
-(void)peripheral:(CBPeripheral *)peripheral didReadRSSI:(NSNumber *)RSSI error:(NSError *)error { NSLog(@"%s,%@",__PRETTY_FUNCTION__,peripheral); int rssi = abs([RSSI intValue]); NSString *length = [NSString stringWithFormat:@"发现BLT4.0热点:%@,强度:%.1ddb",_peripheral,rssi]; NSLog(@"距离:%@", length);}
已发现服务
-(void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error{ NSLog(@"发现服务."); for (CBService *s in peripheral.services) { NSLog(@"%d :服务 UUID: %@(%@)",i,s.UUID.data,s.UUID); // 扫描到服务后,根据服务发现特征 [peripheral discoverCharacteristics:nil forService:s]; }}
已搜索到Characteristics
-(void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error{ NSLog(@"发现特征的服务:%@ (%@)",service.UUID.data ,service.UUID); for (CBCharacteristic *c in service.characteristics) { NSLog(@"特征 UUID: %@ (%@)",c.UUID.data,c.UUID); // 此处FFE1为连接到蓝牙的特征UUID,我是获取之后写固定了,或许也可以不做该判断,我也不是太懂,如果有大神懂得希望指教一下. if ([c.UUID isEqual:[CBUUID UUIDWithString:@"FFE1"]]) { [_peripheral readValueForCharacteristic:c]; [_peripheral setNotifyValue:YES forCharacteristic:c]; } }}
断开连接
- (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error { [_manager cancelPeripheralConnection:_peripheral]; NSLog(@"已断开与设备:[%@]的连接", peripheral.name); }
获取外设发来的数据,不论是read和notify,获取数据都是从这个方法中读取。
- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error{ if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:@"FFE1"]]) { NSData * data = characteristic.value; Byte * resultByte = (Byte *)[data bytes]; // 此处的byte数组就是接收到的数据 NSLog(@"%s", resultByte); }
中心读取外设实时数据
- (void)peripheral:(CBPeripheral *)peripheral didUpdateNotificationStateForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error { if (error) { NSLog(@"Error changing notification state: %@", error.localizedDescription); } // Notification has started if (characteristic.isNotifying) { [peripheral readValueForCharacteristic:characteristic]; } else { // Notification has stopped // so disconnect from the peripheral NSLog(@"Notification stopped on %@. Disconnecting", characteristic); [self updateLog:[NSString stringWithFormat:@"Notification stopped on %@. Disconnecting", characteristic]]; [self.manager cancelPeripheralConnection:self.peripheral]; }}
用于检测中心向外设写数据是否成功
-(void)peripheral:(CBPeripheral *)peripheral didWriteValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error{ if (error) { NSLog(@"=======%@",error.userInfo); }else{ NSLog(@"发送数据成功"); } /* When a write occurs, need to set off a re-read of the local CBCharacteristic to update its value */ [peripheral readValueForCharacteristic:characteristic];}