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]]];//查詢指定服務
}

打印:

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

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 228,606評論 6 533
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 98,582評論 3 418
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 176,540評論 0 376
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,028評論 1 314
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,801評論 6 410
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,223評論 1 324
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,294評論 3 442
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,442評論 0 289
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 48,976評論 1 335
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 40,800評論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 42,996評論 1 369
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,543評論 5 360
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,233評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,662評論 0 26
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,926評論 1 286
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,702評論 3 392
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 47,991評論 2 374

推薦閱讀更多精彩內容

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