May 10, 2015
Core BluetoothAllenlinli
Wednesday, October
結構• ⼊入⾨門
• 簡介
• Hello World
• 中階
• 觀念解說
• Programming for Central
• 進階
• Background Processing
• Best Practices for Interacting with a Remote Peripheral Device
Wednesday, October
⼊入⾨門簡介, Hello World
Wednesday, October
簡介名詞與功⽤用
Wednesday, October
BLE
• 藍⽛牙4.0分三類
• 傳統藍⽛牙技術• 藍⽛牙3.0⾼高速技術
• 最新的藍⽛牙低功耗技術(Bluetooth low energy)
• 特性:適合⼩小資料傳輸、傳輸時間少、休眠時間⻑⾧長、 低功耗
Wednesday, October
BLE功能
• 靠⼀一顆鈕扣電池可使⽤用⼀一年• 理想傳輸距離為⼆二⼗十公尺• 也有遠距傳輸的規格可達理想傳輸距離七⼗十公尺
Wednesday, October
BLE產品
Wednesday, October
Core Bluetooth
• A iOS framework
Wednesday, October
Peripheral & Central
• Central(中⼼心):
• 接收廣播,接收訊息• Peripheral(周邊):
• 發送廣播,傳送訊息
Wednesday, October
Peripheral & Central• 例⼦子:⼼心跳偵測器(Peripheral),發送⼼心跳頻率信號到⼿手機(Central)
Wednesday, October
Hello World讓範例碼動起來
Wednesday, October
Hello World
1. Mac限制2. 環境設定3. 跑Sample Code
Wednesday, October
Mac限制
• 不能直接拿來使⽤用• XCode5的模擬器尚不⽀支援
Wednesday, October
環境設定
• 安裝藍⽛牙設備到模擬器• 購買BLE dongle
• 設定mac•Testing Core Bluetooth Applications in the iOS Simulator•Step 1 - Set the NVRAM Setting•Step 2 - Attach the Bluetooth LE USB adapter•Step 3 - Verify the NVRAM Setting•Step 4 - Enable Bluetooth in the iOS Simulator
user$ sudo nvram bluetoothHostControllerSwitchBehavior="never"
Wednesday, October
跑Sample Code
• BTLE Central Peripheral Transfer 官⽅方範例
• CoreBluetooth-Demo
Wednesday, October
安裝BLE app
• 安裝BLE app到iPhone
• LightBlue - Bluetooth Low Energy
Wednesday, October
Run Sample Code
• 連線:跑模擬器,開啓BLE app
Wednesday, October
中階觀念解說 &
實作⾃自⼰己的第⼀一份程式
Wednesday, October
觀念解說影⽚片與⽂文件
Wednesday, October
參考⽂文件
• Core Bluetooth Programming Guide
• 以下觀念解說主要整理⾃自以上主要⽂文件
Wednesday, October
Centrals & PeripheralsThe Two Key Players
Wednesday, October
Centrals & Peripherals• 例⼦子:⼼心跳偵測器(Peripheral),發送⼼心跳頻率信號到⼿手機(Central)
Wednesday, October
Central的四個階段
• Discover
• Connect
• Explore
• Interact
Wednesday, October
Discover(Advertising)
• Peripherals broadcast
• Central scan
• Size limit: 20 bytes
Wednesday, October
Connect
• A central connect
Wednesday, October
Explore
• A central discover services and characteristics of peripheral
Wednesday, October
Structure of Peripheral
Wednesday, October
BLE官⽅方網站
• BLE官⽅方網站 - service
Wednesday, October
Interact
• Read
• Write
• Notify
Wednesday, October
Programming for Central
Performing Common Central Role Tasks實作程式
Wednesday, October
Outline
• Central manager object
• Discover
• Connect
• Explore
• Interact
• Read and write
• Subscribe
Performing Common Central Role Tasks
Wednesday, October
Starting Up a Central
self.centralManager = [[CBCentralManager alloc] initWithDelegate:self queue:nil];
- (void)centralManagerDidUpdateState:(CBCentralManager *)central{ if (central.state != CBCentralManagerStatePoweredOn) { // In a real app, you'd deal with all the states correctly return; } // The state must be CBCentralManagerStatePoweredOn...
// ... so start scanning [self scan]; }
Wednesday, October
Discover- (void)scan{ [self.centralManager scanForPeripheralsWithServices:@[[CBUUID UUIDWithString:TRANSFER_SERVICE_UUID]] options:@{ CBCentralManagerScanOptionAllowDuplicatesKey : @YES }]; NSLog(@"Scanning started");}
- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI
Wednesday, October
Connect
[self.centralManager connectPeripheral:peripheral options:nil];
- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral{ NSLog(@"Peripheral Connected"); // Stop scanning [self.centralManager stopScan]; NSLog(@"Scanning stopped");
// Make sure we get the discovery callbacks peripheral.delegate = self;
Wednesday, October
Explore
[peripheral discoverServices:nil];
[peripheral discoverServices:@[[CBUUID UUIDWithString:TRANSFER_SERVICE_UUID]]];
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error { for (CBService *service in peripheral.services) { NSLog(@"Discovered service %@", service); ... } ...
Wednesday, October
Explore
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error{ // Again, we loop through the array, just in case. for (CBCharacteristic *characteristic in service.characteristics) { NSLog(@"Discovered characteristic %@", characteristic);
[peripheral discoverCharacteristics:nil];
Wednesday, October
Read and Write Value
• Reading the Value of a Characteristic
• Writing the Value of a Characteristic
Wednesday, October
Read Value
[peripheral readValueForCharacteristic:characteristic];
- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error{
NSData *data = characteristic // parse the data as needed ...
Wednesday, October
Write Value
[peripheral writeValue:dataToWrite forCharacteristic:characteristic type:CBCharacteristicWriteWithResponse];
- (void)peripheral:(CBPeripheral *)peripheraldidWriteValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error { if (error) { NSLog(@"Error writing characteristic value: %@", [error localizedDescription]); } ...
for (CBCharacteristic *characteristic in service.characteristics) { // And check if it's the right one if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:TRANSFER_CHARACTERISTIC_UUID]]) { // If it is, subscribe to it [peripheral setNotifyValue:YES forCharacteristic:characteristic]; } }
Wednesday, October
Notify
- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error{ if (error) { NSLog(@"Error discovering characteristics: %@", [error localizedDescription]); return; } NSString *stringFromData = [[NSString alloc] initWithData:characteristic.value encoding:NSUTF8StringEncoding];
for (CBCharacteristic *characteristic in service.characteristics) { if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:TRANSFER_CHARACTERISTIC_UUID]]) { [peripheral setNotifyValue:YES forCharacteristic:characteristic]; } }
Wednesday, October
Background Processing
Core Bluetooth Background Processing for iOS Apps
Wednesday, October
Foreground-Only Apps
• Central: Cannot scan for and discover advertising
• Peripheral: Advertising is disabled
Wednesday, October
Take Advantage of Peripheral Connection Options
• Core Bluetooth provides a way to alert the user
• The user can decide whether bring the app back to the foreground.
Wednesday, October
Core Bluetooth Background Execution Modes
• You must include the UIBackgroundModes key in your app’s Info.plist file.
• The system wakes up your app which is in background.
Wednesday, October
Central Background Execution Mode
• The system wakes up your app when delegate methods are invoked.
• Multiple discoveries of an advertising peripheral are coalesced into one.
• The interval for scanning increases.
Wednesday, October
Peripheral Background Execution Mode
• Allow your app to be woken up to handle read, write, and subscription requests.
• Allow your app to advertise:
• The local name of peripheral is not advertised.
• All service UUIDs can be discovered only by explicitly scanning for them.
• The frequency may decrease.
Wednesday, October
Use Background Execution Modes Wisely• Try to minimize the amount of work you
do in the background.
• Must follow a few basic guidelines:
• Upon being woken up, an app has around 10 seconds complete a task.
• Should not use being woken up to perform extraneous tasks
Wednesday, October
謝謝⼤大家
Wednesday, October