通过iOS设备的蓝牙与外围设备交互
- 1.需要以下几个类
#import <CoreBluetooth/CoreBluetooth.h>
#import <CoreBluetooth/CBService.h>
#import <CoreBluetooth/CBCharacteristic.h>
- 2.遵循CBCentralManagerDelegate, CBPeripheralDelegate这两个协议
- 3.初始化蓝牙管理者 CBCentralManager *centralManager;,通过管理者来做相应的蓝牙操作
- (void)initManager{
_centralManager = [[CBCentralManager alloc] initWithDelegate:self queue:nil];
}
- 4.查看蓝牙的连接状态
通过 _centralManager.state 可以拿到 一共有五种状态
0:蓝牙状态未知,
1:蓝蓝牙正在重启,
2:设备不支持蓝牙,
3:蓝牙未授权,
4:蓝牙关闭,
5:蓝牙开启,"
- 5.扫描蓝牙设备
- 根据已知的 蓝牙设备的服务(CBUUID *)UUID 或者蓝牙名称(NSString *)BlueToothName或者前缀名来搜索设备
[_centralManager scanForPeripheralsWithServices:UUID options:nil];
- 6.停止扫描
[_centralManager stopScan];
+ 7.连接设备
- 1.根据设备的唯一标识UUID(相当于mac地址的uuid) 来连接设备:把扫描到的设备放到一个数组中,遍历所有扫描设备的UUID (相当于mac地址的uuid),拿到要连接的设备 。调用连接方法
[_centralManager connectPeripheral:peripheral options:[NSDictionary dictionaryWithObject:[NSNumber numberWithBool:YES] forKey:CBConnectPeripheralOptionNotifyOnDisconnectionKey]];
+ 8.断开连接
if(peripheral.state == CBPeripheralStateConnected) {
[_centralManager cancelPeripheralConnection:peripheral];
}
+ 9. 根据服务的UUID,获得iOS已经连接的设备
NSArray *retrivedPer = [_centralManager retrieveConnectedPeripheralsWithServices:@[[CBUUID UUIDWithString:UUID]]];
+ 10.实现CBPeripheralDelegate的代理
- 1.根据服务拿到读写特征值
```
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(nullable NSError *)error;
```
- 2.用写的特征值给设备写值 此类命令有返回数据到iOS端,用读的特征值 通知 外围设备,此命令写入外围设备无回应
- (void)peripheral:(CBPeripheral *)peripheral didWriteValueForCharacteristic:(CBCharacteristic *)characteristic error:(nullable NSError *)error;
- 3.在下面代理可拿到外围设备返给ios设备的值
- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(nullable NSError *)error;
```
网友评论