iOS藍牙編程

藍牙基礎

  • MFI --- make for ipad ,iphone, itouch
  • BLE --- buletouch low energy
  • RSSI --- Received Signal Strength

<font color="blue">→_→ </font>developer.apple.com/CoreBluetooth

下面主要是用CoreBluetooth開發。

中心(central)和外設(peripheral)

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

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

服務(service)和特征(characteristic)

  • service和characteristic是peripheral組織數據的一種方式。
  • 一個peripheral可以有多個service, 每個service下可以有多個characteristic。

    <center>
    </center>
  • characteristic下有具體的數據,比如智能燈下有兩個服務:溫度、亮度。亮度服務下有多個特征:當前亮度、10分鐘前亮度......

Central

使用步驟

1.導入CoreBluetooth模塊

@import CoreBluetooth;

2.遵從協議

@interface BluetoothController : NSViewController<CBCentralManagerDelegate, CBPeripheralDelegate>

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<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, 并查詢服務

- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral {
    NSLog(@"Connected to %@", peripheral.name);
    [peripheral discoverServices:nil]; //nil,查詢所有服務
    //[peripheral discoverServices:@[[CBUUID UUIDWithString:kServiceUUID]]];//查詢指定服務
}

打?。?/p>

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>)

上面的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<CBPeripheralManagerDelegate>

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.更新特征值

<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, 歡迎下載使用。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • iOS的藍牙框架是支持藍牙4.0協議的。理解iOS CoreBluetooth兩個很重要的概念,Central 和...
    風繼續吹0閱讀 909評論 0 1
  • 小引 隨著穿戴設備和智能家居的熱情不斷,app藍牙的開發也很火熱,基于iOS藍牙的開發資料有不少,但是最最值得學習...
    MarkLin閱讀 11,903評論 15 55
  • 本文出自: http://mokai.me/bluetooth-guide.html 藍牙技術,很早以前就被有了...
    _GKK_閱讀 1,329評論 0 3
  • 本文主要以藍牙4.0做介紹,因為現在iOS能用的藍牙也就是只僅僅4.0的設備 用的庫就是core bluetoot...
    暮雨飛煙閱讀 866評論 0 2
  • 今天我爸爸上班去,我在家自己等著媽媽,也沒哭回來,媽媽到家啦,很早?;貋砦覀兙烷_始媽媽給我做飯啦,坐在身邊調。吃完...
    萌萌王詩雅閱讀 228評論 0 0