
首先先介绍一下蓝牙开发的模式:
- 蓝牙中心模式
- 蓝牙外设模式
一.蓝牙中心模式
1.创建 CBCentralManager 中心对象
2.central扫描外设 discover
3.central连接外设 connect
- 扫描外设中的服务和特征discover
4.1、获取外设的 services:
执行:discoverServices
成功后执行:peripheral:didDiscoverServices
委托方法
4.2、获取外设的 Characteristics,获取 Characteristics 的值:
执行:discoverCharacteristics:forService
成功后执行:peripheral:didDiscoverCharacteristicsForService:error
委托方法
4.3、获取外设的Characteristics 的 Descriptor 和 Descriptor 的值:
读特征值:readValueForCharacteristic
读到后进入:didUpdateValueForCharacteristic:error委托方法
搜索 Characteristic:discoverDescriptorsForCharacteristic
搜到后进入:didDiscoverDescriptorsForCharacteristic:error委托方法
获取到 Descriptors 的值:peripheral:didUpdateValueForDescriptor:error
Descriptors 是对 characteristic 的描述,一般是字符串
4.4、把数据写到 Characteristic:writeCharacteristic:charactericstic:value
4.5、读 RSSI,用通知的方式订阅数据等。
5、与外设做数据交互 explored interact
6、订阅 Characteristic 的通知:notifyCharacteristic:characteristic
取消通知:cancelNotifyCharacteristic:characteristic
7、断开连接 disconnect:disconnnectPeripheral:peripheral

二.蓝牙外设模式流程
1.创建一个 Peripheral 管理对象
peripheralManager = [[CBPeripheralManager alloc] initWithDelegate:self queue:nil];
蓝牙设备打开成功后会进入委托方法:peripheralManagerDidUpdateState:
- 本地 Peripheral 设置服务、特性、描述、权限等。
创建 Characteristics 及其 description,创建 service,把 characteristics 添加到 service 中,再把 service 添加到 peripheralManager 中。
- Peripheral 发送广播 advertising:peripheralManagerDidStartAdvertising:error
Peripheral 添加service:peripheralManager:didAddService:error
- 对 central 的操作进行响应
读 characteristics 请求:peripheralManager:didReceiveReadQuest:
写characteristics 请求:peripheralManager:didReceiveWriteRequests:
订阅特征:peripheralManager:central:didSubscribeToCharacteristic:
取消订阅peripheralManager:central:didUnsubscribeFromCharacteristic:
一些基本属性:
RSSI:信号强弱值,防丢器会用到。
UUID:唯一标识符,用于区分设备
service UUID:服务,一个 Server 会包含多个characteristic,用 UUID 来区分。
characteristic:特征,用 UUID 来区分
了解了以上流程:由于苹果的封闭生态,之前对蓝牙的限制比较严格,如果要和 iOS 设备通信,必须是经过了 MFI 认证的芯片才可以;蓝牙4.0低功耗模式的到来,苹果也对蓝牙放开了一些限制。所以目前针对 iOS 的蓝牙编程主要就是针对蓝牙4.0以上的低功耗蓝牙,也就是 BLE 模式。
BLE 模式的特点:
功耗低。
连接速度很快,连接距离远(100米)。
相应的传输数据量小,比传统蓝牙传输的小很多,据说单次发送也就20字节。
BLE 模式并不适合用来做较大数据量的传输使用
Bluetooth.h
@property(nonatomic,strong) CBCentralManager *centralManager;
@property(nonatomic,strong) CBPeripheral *peripheral;
@property(nonatomic,strong) CBCharacteristic *characteristic;
@property(nonatomic,strong) NSMutableArray *peripheralArray;
- (void)initBluetooth; //初始化蓝牙
- (void)scanBluetooth; //扫描蓝牙
- (void)stopScanBluetooth; //停止扫描
- (void)connectPeripheral:(CBPeripheral *)peripheral; //连接蓝牙
- (void)disConnectPeripheral:(CBPeripheral *)peripheral; //取消连接蓝牙
- (void)sendData:(NSData *)data; //向扫描到的蓝牙Characteristic 发送数据
Bluetooth.m
// 初始化蓝牙
- (void)initBluetooth
{
_centralManager = [[CBCentralManager alloc] initWithDelegate:self queue:nil];//创建CBCentralManager对象
_peripheralArray = [[NSMutableArray alloc] init];
}
//扫描蓝牙
(void)scanBluetooth
{
NSLog(@"BluetoothBase scanBluetooth");
//CBCentralManagerScanOptionAllowDuplicatesKey值为 No,表示不重复扫描已发现的设备
NSDictionary *optionDic = [NSDictionary dictionaryWithObject:[NSNumber numberWithBool:NO] forKey:CBCentralManagerScanOptionAllowDuplicatesKey];
[_centralManager scanForPeripheralsWithServices:nil options:optionDic];//如果你将第一个参数设置为nil,Central Manager就会开始寻找所有的服务。
}
//停止扫描蓝牙(void)stopScanBluetooth
{
[self.centralManager stopScan];
NSLog(@"BluetoothBase stopScanBluetooth,已经连接外设停止扫描或者手动停止扫描");
}
//连接蓝牙(void)connectPeripheral:(CBPeripheral *)peripheral
{
[self.centralManager connectPeripheral:peripheral options:nil];
self.peripheral = peripheral;
peripheral.delegate = self; //连接时设置代理
}
//取消连接蓝牙(void)disConnectPeripheral:(CBPeripheral *)peripheral
{
[_centralManager cancelPeripheralConnection:peripheral];
}
//如果发送的数据过大,就需要做分包处理了。至于传输的最大字节数是多大,就需要和硬件工程师讨论了。pl @PlatoJobs
//向蓝牙写入数据-
(void)sendData:(NSData *)data
{
[self initBluetoothDispatch];if (_characteristic.properties & CBCharacteristicPropertyWrite){
[_peripheral writeValue:data forCharacteristic:_characteristic type:CBCharacteristicWriteWithResponse];
NSLog(@"BluetoothBase writeDataToCharacteristic:%@",[_characteristic.UUID UUIDString]);
}else{
NSLog(@"没有发现可以写入的characteristic");
}
}
蓝牙的一些代理方法(CBCentralManagerDelegate):
//centralManager已经更新状态
- (void)centralManagerDidUpdateState:(CBCentralManager *)central
{
NSLog(@"centralManagerDidUpdateState:%ld",(long)central.state);
switch (central.state) {
case CBCentralManagerStateUnknown:
NSLog(@"CBCentralManagerStateUnknown");
break;
case CBCentralManagerStateResetting:
NSLog(@"CBCentralManagerStateResetting");
break;
case CBCentralManagerStateUnsupported:
NSLog(@"CBCentralManagerStateUnsupported");
break;
case CBCentralManagerStateUnauthorized:
NSLog(@"CBCentralManagerStateUnauthorized");
break;
case CBCentralManagerStatePoweredOff:
NSLog(@"CBCentralManagerStatePoweredOff");
break;
case CBCentralManagerStatePoweredOn:
[self scanBluetooth]; //很重要,当蓝牙处于打开状态,开始扫描。
break;
default:
NSLog(@"蓝牙未工作在正确状态");
break;
}
}
//centralManager已经发现外设
//扫描到外设,停止扫描,连接设备(每扫描到一个外设都会调用一次这个函数,若要展示搜索到的蓝牙,可以逐一保存 peripheral 并展示)
-
(void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary<NSString *,id> *)advertisementData RSSI:(NSNumber *)RSSI
{
[_peripheralArray addObject:peripheral]; //保存用于连接的 peripheral
[PRTBluetoothModel share].peripheralArray = _peripheralArray;[[NSNotificationCenter defaultCenter] postNotificationName:@"PRTBluetoothScanUpdatePeripheralList" object:nil];
}
//已经连接外设
//连接外设成功,扫描外设中的服务和特征 -
(void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral
{
[PRTDispatchModel share].currentDispatchMode = PRTPrinterModeBle; //将蓝牙模式保存到当前传输模式。NSLog(@"didConnectPeripheral:%@",peripheral.name);
[[NSNotificationCenter defaultCenter] postNotificationName:@"PRTBluetoothScanDidConnectPeripheral" object:nil];[self stopScanBluetooth]; //连接成功后停止扫描
[self.peripheral setDelegate:self];
//数组中存放两个服务的 UUID
NSMutableArray *uuidArray = [[NSMutableArray alloc] initWithObjects:[CBUUID UUIDWithString:UUID_String_DeviceInfo_Service], [CBUUID UUIDWithString:UUIDSTR_ISSC_PROPRIETARY_SERVICE], nil];[peripheral discoverServices:uuidArray];//发现服务,成功后执行:peripheral:didDiscoverServices委托方法
}
//连接外设失败 (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error
{
NSLog(@"didFailToConnectPeripheral:%@",error);
}
//已经发现服务-
(void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error
{
NSLog(@"didDiscoverServices:%@",peripheral.name);
if (error) {
NSLog(@"didDiscoverServices error:%@",[error localizedDescription]);
return;
}for (CBService *service in peripheral.services) {
//发现特征,成功后执行:peripheral:didDiscoverCharacteristicsForService:error委托方法
[peripheral discoverCharacteristics:nil forService:service];
}
}
//已经为服务发现特征
/*
蓝牙都会有几个服务,每个服务都会有几个特征,服务和特征都是用不同的 UUID 来标识的。
每个特征的 properties 是不同的,就是说有不同的功能属性,有的对应写入,有的对应读取。
蓝牙联盟有一个规范,但是这个也是可以自定义的,所以不清楚的话,联系硬件工程师问清楚
*/
-
(void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error
{
NSLog(@"didDiscoverCharacteristicsForServic:%@",service.UUID);CBCharacteristic *characteristic = nil;
if ([service.UUID isEqual:[CBUUID UUIDWithString:@"这里填你的蓝牙服务的 UUID"]]) {
for (characteristic in service.characteristics)
{
if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:@"这里填你的蓝牙特征的 UUID"]]) {
self.characteristic = characteristic;//重要,将满足条件的特征保存为全局特征,以便对齐进行写入操作。
[PRTBluetoothModel share].characteristicWrite = characteristic;
[self.peripheral setNotifyValue:YES forCharacteristic:characteristic];
}
}
}if (error) {
NSLog(@"didDiscoverCharacteristicsForService error:%@",[error localizedDescription]);
}
}
// 已经更新特征的值
//获取外设发来的数据,不论是read和notify,获取数据都是从这个方法中读取。 -
(void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
{
NSLog(@"didUpdateValueForCharacteristic:%@",[characteristic.UUID UUIDString]);
if (error) {
NSLog(@"didUpdateValueForCharacteristic error:%@",[error localizedDescription]);
}for (CBDescriptor *descriptor in characteristic.descriptors) //12.23新增
{
[peripheral readValueForDescriptor:descriptor];
}
}
//已经写入特征的值
//委托方法:已经为特征【写入值】
-(void)peripheral:(CBPeripheral *)peripheral didWriteValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
{
NSLog(@"didWriteValueForCharacteristic:%@",[characteristic.UUID UUIDString]);if (error) {
NSLog(@"didWriteValueForCharacteristic error:%@",[error localizedDescription]);
}[peripheral readValueForCharacteristic:characteristic]; //12.23新增
}
//已经发现特征的描述 (void)peripheral:(CBPeripheral *)peripheral didDiscoverDescriptorsForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
{
NSLog(@"didDiscoverDescriptorsForCharacteristic:%@",characteristic);
for (CBDescriptor *d in characteristic.descriptors) {
NSLog(@"Descriptor UUID:%@",d.UUID);
}
}
// 已经更新描述的值(void)peripheral:(CBPeripheral *)peripheral didUpdateValueForDescriptor:(CBDescriptor *)descriptor error:(NSError *)error
{
NSLog(@"didUpdateValueForDescriptor:%@",descriptor);
[peripheral readValueForDescriptor:descriptor]; //12.23新增
}
//已经更新特征的通知状态-
(void)peripheral:(CBPeripheral *)peripheral didUpdateNotificationStateForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error {
NSLog(@"didUpdateNotificationStateForCharacteristic:%@",characteristic);[peripheral readValueForCharacteristic:characteristic]; //12.23新增
[peripheral discoverDescriptorsForCharacteristic:characteristic];
}