蓝牙基础
- MFI --- make for ipad ,iphone, itouch
- BLE --- buletouch low energy
- RSSI --- Received Signal Strength
→_→ developer.apple.com/CoreBluetooth
下面主要是用CoreBluetooth开发。
中心(central)和外设(peripheral)
在CoreBluetooth框架下,可以看成两大模块的通信:中心(central)和外设(peripheral)。
- central
- 接收数据的一方,比如接收智能温度计的数据显示温度的手机端。
- peripheral
- 提供数据的一方。
- 比如智能血压计,智能温度计。
服务(service)和特征(characteristic)
- service和characteristic是peripheral组织数据的一种方式。
-
一个peripheral可以有多个service, 每个service下可以有多个characteristic。
- characteristic下有具体的数据,比如智能灯下有两个服务:温度、亮度。亮度服务下有多个特征:当前亮度、10分钟前亮度......
Central
使用步骤
1.导入CoreBluetooth模块
@import CoreBluetooth;
2.遵从协议
@interface BluetoothController : NSViewController
3.创建Central和Peripheral(数组)
@property (nonatomic, strong) NSMutableArray *peripheralArray;
@property (nonatomic, strong) CBCentralManager *myCentralManager;
self.myCentralManager = [[CBCentralManager alloc] initWithDelegate:self queue:nil];
self.peripheralArray = [NSMutableArray array];
4.查询蓝牙状态,可用的话,开始扫描
#pragma mark - CBCentralManagerDelegate methods
- (void)centralManagerDidUpdateState:(CBCentralManager *)central {
NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:false], CBCentralManagerScanOptionAllowDuplicatesKey, nil];
switch (central.state) {
case CBCentralManagerStatePoweredOn:
[self.myCentralManager scanForPeripheralsWithServices:nil options:dic];
break;
default:
NSLog(@"Bluetooth is not working on the right state");
break;
}
}
5.发现Peripheral并连接
- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI {
NSLog(@"Discovered %@", peripheral.name);
[self.peripheralArray addObject:peripheral];
if (self.targetPeripheral != peripheral) {
self.targetPeripheral = peripheral;
[self.myCentralManager connectPeripheral:peripheral options:[NSDictionary dictionaryWithObject:[NSNumber numberWithBool:YES] forKey:CBConnectPeripheralOptionNotifyOnDisconnectionKey]];
peripheral.delegate = self; // 处理peripheral的事件
}
}
这时运行程序,打印如下
Discovered MyCBServer
Discovered John’s iPhone
上面的MyCBServer是我在iphone上运行的Bluetooth Server程序中的service名称。John是我的名字。
6.连接上peripheral, 并查询服务
- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral {
NSLog(@"Connected to %@", peripheral.name);
[peripheral discoverServices:nil]; //nil,查询所有服务
//[peripheral discoverServices:@[[CBUUID UUIDWithString:kServiceUUID]]];//查询指定服务
}
打印:
Connected to MyCBServer
7.peripheral查到服务
打印所有服务:
#pragma mark - CBPeripheralDelegate Methods
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error {
if (error) {
NSLog(@"error in discovering serviecs: %@", [error localizedDescription]);
return;
}
for (CBService *service in peripheral.services) {
NSLog(@"service's uuid : %@", service.UUID);
}
}
打印
service's uuid : Battery
service's uuid : Current Time
service's uuid : Device Information
service's uuid : Unknown ()
上面的c5ac0853 51224856 ac70a80e 990d1c15就是iphone上运行的service UUID.
我手机上的Service和Characteristic的UUID分别为:
static NSString * const kServiceUUID = @"C5AC0853-5122-4856-AC70-A80E990D1C15";
static NSString * const kCharacteristicUUID = @"013AFE01-3E37-4E58-B6FD-DC4E67CF8F03";
上面的数字是在Mac上用uuidgen命令生成的。
UUID: Universally Unique Identifier
下面需要针对特定的service,让peripheral去查它的characteristics。
这里即是针对kServiceUUID,查它下面的特征。
#pragma mark - CBPeripheralDelegate Methods
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error {
if (error) {
NSLog(@"error in discovering serviecs: %@", [error localizedDescription]);
return;
}
for (CBService *service in peripheral.services) {
// NSLog(@"service's uuid : %@", service.UUID);
if ([service.UUID isEqual:[CBUUID UUIDWithString: kServiceUUID]]) {
[peripheral discoverCharacteristics:[NSArray arrayWithObject:[CBUUID UUIDWithString:kCharacteristicUUID]] forService:service];
}
}
}
8.peripheral查到特征
打印所有特征
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error {
if (error) {
NSLog(@"error discovering characteristic : %@", [error localizedDescription]);
}
for (CBCharacteristic *characteristic in service.characteristics) {
NSLog(@"characteristic uuid: %@", [characteristic UUID]);
}
}
输出:
characteristic uuid: Unknown (<013afe01 3e374e58 b6fddc4e 67cf8f03>)
试想这个场景:智能血压计需要将某些数据即时更新给central。这里,可以给指定的特征设置Notifiy, 设置以后,peripheral的特征值更新会及时通过delegate反馈过来。
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error {
if (error) {
NSLog(@"error discovering characteristic : %@", [error localizedDescription]);
}
if ([service.UUID isEqual:[CBUUID UUIDWithString:kServiceUUID]]) {
for (CBCharacteristic *characteristic in service.characteristics) {
// NSLog(@"characteristic uuid: %@", [characteristic UUID]);
if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:kCharacteristicUUID]]) {
[peripheral setNotifyValue:YES forCharacteristic:characteristic];//订阅特征
}
}
}
}
9.peripheral说特征值有更新
上面setNotifyValue:YES函数设置了notify。那么这个特征值有更新的话,就会通过下面的函数告诉central
- (void)peripheral:(CBPeripheral *)peripheral didUpdateNotificationStateForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error {
if (error) {
NSLog(@"error notifying : %@", [error localizedDescription]);
return;
}
10.peripheral读到数据
通过下面的代理方法获取value:
- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error {
if (error) {
NSLog(@"error update value : %@", [error localizedDescription]);
return;
}
NSString *value = [[NSString alloc] initWithData:characteristic.value encoding:NSUTF8StringEncoding];
NSLog(@"Value: %@", value);
}
Peripheral
使用步骤
see also →_→ developer.apple.com/PeripheralRole
1.导入蓝牙模块
@import CoreBluetooth;
2.遵从CBPeripheralManagerDelegate协议
@interface ViewController : UIViewController
3.创建myPeripheralManager
@property (nonatomic, strong) CBPeripheralManager *myPeripheralManager;
self.myPeripheralManager = [[CBPeripheralManager alloc] initWithDelegate:self queue:nil];
4.查询蓝牙状态, 可用的话添加服务
#pragma mark - Custom methods
- (void)addService {
CBMutableService *service = [[CBMutableService alloc] initWithType:[CBUUID UUIDWithString:kServiceUUID] primary:YES];//primary
CBMutableCharacteristic *characteristic = [[CBMutableCharacteristic alloc] initWithType:[CBUUID UUIDWithString:kCharacteristicUUID] properties:CBCharacteristicPropertyNotify value:nil permissions:CBAttributePermissionsReadable];
self.myCharacteristic = characteristic;
[service setCharacteristics:@[characteristic]];
[self.myPeripheralManager addService:service];
}
#pragma mark - CBPeripheralManagerDelegate methods
- (void)peripheralManagerDidUpdateState:(CBPeripheralManager *)peripheral {
switch (peripheral.state) {
case CBPeripheralManagerStatePoweredOn:
[self addService];
break;
default:
NSLog(@"Peripheral Manager is not working on the right state");
break;
}
}
5.服务添加成功,开始广告
- (void)peripheralManager:(CBPeripheralManager *)peripheral didAddService:(CBService *)service error:(NSError *)error {
if (error) {
NSLog(@"Error publishing service: %@", [error localizedDescription]);
return;
}
[self.myPeripheralManager startAdvertising:@{CBAdvertisementDataLocalNameKey:@"MyCBServer", CBAdvertisementDataServiceUUIDsKey: [CBUUID UUIDWithString:kServiceUUID]}];
}
6.广告成功
- (void)peripheralManagerDidStartAdvertising:(CBPeripheralManager *)peripheral error:(NSError *)error {
if (error) {
NSLog(@"error advertising : %@", [error localizedDescription]);
self.showLabel.text = [NSString stringWithFormat:@"error advertising: %@", [error localizedDescription]];
return;
}
self.showLabel.text = @"start advertising";
}
7.更新特征值
添加两个button,用来改变特征值
@property (nonatomic, assign) NSInteger count;
- (IBAction)MinusButtonClicked:(id)sender {
if ([self.myPeripheralManager state] != CBPeripheralManagerStatePoweredOn) {
return;
}
--(self.count);
NSData *data = [[NSString stringWithFormat:@"count is now %ld", (long)self.count] dataUsingEncoding:NSUTF8StringEncoding];
[self.myPeripheralManager updateValue:data forCharacteristic:self.myCharacteristic onSubscribedCentrals:self.centrayArray];
}
- (IBAction)AddButtonClicked:(id)sender {
if ([self.myPeripheralManager state] != CBPeripheralManagerStatePoweredOn) {
return;
}
++(self.count);
NSData *data = [[NSString stringWithFormat:@"count is now %ld", (long)self.count] dataUsingEncoding:NSUTF8StringEncoding];
[self.myPeripheralManager updateValue:data forCharacteristic:self.myCharacteristic onSubscribedCentrals:self.centrayArray];
}
点击button,central输出:
Value: count is now -2
Value: count is now -1
Value: count is now 0
Value: count is now 1
资源
完整代码已上传到 →_→ github, 欢迎下载使用。