iOS藍(lán)牙編程

藍(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開(kāi)發(fā)。

中心(central)和外設(shè)(peripheral)

在CoreBluetooth框架下,可以看成兩大模塊的通信:中心(central)和外設(shè)(peripheral)。

  • central
    • 接收數(shù)據(jù)的一方,比如接收智能溫度計(jì)的數(shù)據(jù)顯示溫度的手機(jī)端。
  • peripheral
    • 提供數(shù)據(jù)的一方。
    • 比如智能血壓計(jì),智能溫度計(jì)。

服務(wù)(service)和特征(characteristic)

  • service和characteristic是peripheral組織數(shù)據(jù)的一種方式。
  • 一個(gè)peripheral可以有多個(gè)service, 每個(gè)service下可以有多個(gè)characteristic。

    <center>
    </center>
  • characteristic下有具體的數(shù)據(jù),比如智能燈下有兩個(gè)服務(wù):溫度、亮度。亮度服務(wù)下有多個(gè)特征:當(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),可用的話,開(kā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的事件
    }
}

這時(shí)運(yùn)行程序,打印如下

Discovered MyCBServer
Discovered John’s iPhone

上面的MyCBServer是我在iphone上運(yùn)行的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ù)
}

打?。?/p>

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上運(yùn)行的service UUID.

我手機(jī)上的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

下面需要針對(duì)特定的service,讓peripheral去查它的characteristics
這里即是針對(duì)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>)

試想這個(gè)場(chǎng)景:智能血壓計(jì)需要將某些數(shù)據(jù)即時(shí)更新給central。這里,可以給指定的特征設(shè)置Notifiy, 設(shè)置以后,peripheral的特征值更新會(huì)及時(shí)通過(guò)delegate反饋過(guò)來(lái)。

- (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說(shuō)特征值有更新

上面setNotifyValue:YES函數(shù)設(shè)置了notify。那么這個(gè)特征值有更新的話,就會(huì)通過(guò)下面的函數(shù)告訴central

- (void)peripheral:(CBPeripheral *)peripheral didUpdateNotificationStateForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error {
    if (error) {
        NSLog(@"error notifying : %@", [error localizedDescription]);
        return;
    }

10.peripheral讀到數(shù)據(jù)

通過(guò)下面的代理方法獲取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ù)添加成功,開(kāi)始廣告

- (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>
添加兩個(gè)button,用來(lái)改變特征值

@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];
}

點(diǎn)擊button,central輸出:

Value: count is now -2
Value: count is now -1
Value: count is now 0
Value: count is now 1

資源

完整代碼已上傳到 →_→ github, 歡迎下載使用。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • iOS的藍(lán)牙框架是支持藍(lán)牙4.0協(xié)議的。理解iOS CoreBluetooth兩個(gè)很重要的概念,Central 和...
    風(fēng)繼續(xù)吹0閱讀 1,049評(píng)論 0 1
  • 小引 隨著穿戴設(shè)備和智能家居的熱情不斷,app藍(lán)牙的開(kāi)發(fā)也很火熱,基于iOS藍(lán)牙的開(kāi)發(fā)資料有不少,但是最最值得學(xué)習(xí)...
    MarkLin閱讀 11,993評(píng)論 15 55
  • 本文出自: http://mokai.me/bluetooth-guide.html 藍(lán)牙技術(shù),很早以前就被有了...
    _GKK_閱讀 1,416評(píng)論 0 3
  • 本文主要以藍(lán)牙4.0做介紹,因?yàn)楝F(xiàn)在iOS能用的藍(lán)牙也就是只僅僅4.0的設(shè)備 用的庫(kù)就是core bluetoot...
    暮雨飛煙閱讀 912評(píng)論 0 2
  • 今天我爸爸上班去,我在家自己等著媽媽,也沒(méi)哭回來(lái),媽媽到家啦,很早。回來(lái)我們就開(kāi)始媽媽給我做飯啦,坐在身邊調(diào)。吃完...
    萌萌王詩(shī)雅閱讀 253評(píng)論 0 0

友情鏈接更多精彩內(nèi)容