藍(lán)牙基礎(chǔ)
- MFI --- make for ipad ,iphone, itouch
- BLE --- buletouch low energy
- RSSI --- Received Signal Strength
<font color="blue">→_→ </font>developer.apple.com/CoreBluetooth
下面主要是用CoreBluetooth開發(fā)塑径。
中心(central)和外設(shè)(peripheral)
在CoreBluetooth框架下女坑,可以看成兩大模塊的通信:中心(central)和外設(shè)(peripheral)。
- central
- 接收數(shù)據(jù)的一方晓勇,比如接收智能溫度計的數(shù)據(jù)顯示溫度的手機端堂飞。
- peripheral
- 提供數(shù)據(jù)的一方。
- 比如智能血壓計绑咱,智能溫度計绰筛。
服務(wù)(service)和特征(characteristic)
- service和characteristic是peripheral組織數(shù)據(jù)的一種方式。
-
一個peripheral可以有多個service描融, 每個service下可以有多個characteristic铝噩。
<center>
- characteristic下有具體的數(shù)據(jù),比如智能燈下有兩個服務(wù):溫度窿克、亮度骏庸。亮度服務(wù)下有多個特征:當(dāng)前亮度毛甲、10分鐘前亮度......
Central
使用步驟
1.導(dǎo)入CoreBluetooth模塊
@import CoreBluetooth;
2.遵從協(xié)議
@interface BluetoothController : NSViewController<CBCentralManagerDelegate, CBPeripheralDelegate>
3.創(chuàng)建Central和Peripheral(數(shù)組)
@property (nonatomic, strong) NSMutableArray *peripheralArray;
@property (nonatomic, strong) CBCentralManager *myCentralManager;
self.myCentralManager = [[CBCentralManager alloc] initWithDelegate:self queue:nil];
self.peripheralArray = [NSMutableArray array];
4.查詢藍(lán)牙狀態(tài),可用的話具被,開始掃描
#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.發(fā)現(xiàn)Peripheral并連接
- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary<NSString *,id> *)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, 并查詢服務(wù)
- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral {
NSLog(@"Connected to %@", peripheral.name);
[peripheral discoverServices:nil]; //nil七咧,查詢所有服務(wù)
//[peripheral discoverServices:@[[CBUUID UUIDWithString:kServiceUUID]]];//查詢指定服務(wù)
}
打印:
Connected to MyCBServer
7.peripheral查到服務(wù)
打印所有服務(wù):
#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>)
上面的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";
上面的數(shù)字是在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>)
試想這個場景:智能血壓計需要將某些數(shù)據(jù)即時更新給central。這里携冤,可以給指定的特征設(shè)置Notifiy, 設(shè)置以后悼粮,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函數(shù)設(shè)置了notify噪叙。那么這個特征值有更新的話矮锈,就會通過下面的函數(shù)告訴central
- (void)peripheral:(CBPeripheral *)peripheral didUpdateNotificationStateForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error {
if (error) {
NSLog(@"error notifying : %@", [error localizedDescription]);
return;
}
10.peripheral讀到數(shù)據(jù)
通過下面的代理方法獲取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.導(dǎo)入藍(lán)牙模塊
@import CoreBluetooth;
2.遵從CBPeripheralManagerDelegate協(xié)議
@interface ViewController : UIViewController<CBPeripheralManagerDelegate>
3.創(chuàng)建myPeripheralManager
@property (nonatomic, strong) CBPeripheralManager *myPeripheralManager;
self.myPeripheralManager = [[CBPeripheralManager alloc] initWithDelegate:self queue:nil];
4.查詢藍(lán)牙狀態(tài), 可用的話添加服務(wù)
#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.服務(wù)添加成功霉翔,開始廣告
- (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.更新特征值
<center>
</center>
添加兩個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, 歡迎下載使用债朵。