版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
1、BLE设备自动在设备端连接后APP如何与设备连接原文地址: peripherialhttp:/cms.35g.tw/coding/%E8%97%8D%E7%89%99-ble-corebluetooth-%E5%88%9D%E6%8E%A2/ 依照箭頭方向由上而下為順序依序完成Discover、Connect流程。CBCentralManager使用CoreBluetooth Framework中,主要管理連線的是CBCentralManager這個Object,它掌控整個BLE狀態的管理,使用時要先對CBCentralManager初始化:/-start-CBCentralManager *
2、CM = CBCentralManager alloc initWithDelegate:self queue:nil;/-end-現在就開始往下介紹。centralManagerDidUpdateState在一開始宣告初CBCentralManager時就有指定Delegate為self,並且必需要在.h內加上Delegate宣告:/-start-interface TestCoreBluetooth : NSObject<CBCentralManagerDelegate> :/-end-宣告完成後,再加入centralManagerDidUpdateState這個Delegat
3、e內容,/-start-(void)centralManagerDidUpdateState:(CBCentralManager*)cManager NSMutableString* nsmstring=NSMutableString stringWithString:"UpdateState:" BOOL isWork=FALSE; switch (cManager.state) case CBCentralManagerStateUnknown: nsmstring appendString:"Unknownn" break; case CBCent
4、ralManagerStateUnsupported: nsmstring appendString:"Unsupportedn" break; case CBCentralManagerStateUnauthorized: nsmstring appendString:"Unauthorizedn" break; case CBCentralManagerStateResetting: nsmstring appendString:"Resettingn" break; case CBCentralManagerStatePower
5、edOff: nsmstring appendString:"PoweredOffn" if (connectedPeripheral!=NULL) CM cancelPeripheralConnection:connectedPeripheral; break; case CBCentralManagerStatePoweredOn: nsmstring appendString:"PoweredOnn" isWork=TRUE; break; default: nsmstring appendString:"nonen" brea
6、k; NSLog("%",nsmstring); delegate didUpdateState:isWork message:nsmstring getStatus:cManager.state;/-end-centralManagerDidUpdateState的Delegate是用來得知藍牙目前的狀態,所以會有個結果是用來判斷iDevice是否支援BLE,因為BLE是在iphone 4s、New iPad之後才有的,現階段還是需要偵測使用的環境,當然可以根據這些狀態的口報來決定APP的功能或其他提示使用者的動作。scanForPeripheralsWithServic
7、es先前確定周邊支援BLE且運作正常後,我們就要來開啟BLE搜尋功能來尋找BLE的週邊,當週邊接收到搜尋功能的廣播訊息時,依照BLE通訊規範,週邊會在一定時間內回覆,所以我們在此可以設定2秒的Timer計時器,當時間一到就停止scan的功能。/-start-CBCentralManager *CM = CBCentralManager alloc initWithDelegate:self queue:nil;CM scanForPeripheralsWithServices:nil options:options;NSTimer scheduledTimerWithTimeInterval:
8、2.0f target:self selector:selector(scanTimeout:) userInfo:nil repeats:NO;/-end-設定2秒後觸發執行scanTimeoutmethod,再將scanForPeripheralsWithServices的值設為nil,代表搜尋的Service type不受限制,當你搜尋特定時,就必需要將它的UUID填入,像範例這樣:/-start- NSArray *uuidArray= NSArray arrayWithObjects:CBUUID UUIDWithString:"180D", nil; CM sc
9、anForPeripheralsWithServices:uuidArray options:options;/-end-其中UUIDWithString:"180D"的180D就是Heart Rate Service type,一旦指定Service type,結果就只會將週邊有Heart Rate類型一一列出來,要了解更多的Service Type可以到Bluetooth官網查詢。 當您了解Service type是哪一種類型時就可以來做對應的流程及資料的解析,也可以製作出符合一般標準週邊的通用APP。didDiscoverPeripheraldidDiscoverPe
10、ripheral屬於Delegate功能,所以要按照它預設的宣告將要處理的過程寫在裡面,格式如下:/-start-(void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI/處理過程/-end-advertisementData會報告可以連線的週邊內容, 如果將它印出來會像這樣:/-start-adveriseme
11、nt: kCBAdvDataLocalName = "INFOS 4090v35.05" kCBAdvDataServiceUUIDs = ( "Unknown (<fff0>)" ); kCBAdvDataTxPowerLevel = 0;/-end-RSSI是訊號的強度,是以NSNumber Object存在,取得後可以依照NSNumber的方式整數值做處理與轉換,接下來我們將一些資訊列印出來,整個範例可以是這樣子:/-start-(void)centralManager:(CBCentralManager *)central didDi
12、scoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI NSMutableString* nsmstring=NSMutableString stringWithString:"n" nsmstring appendString:"Peripheral Info:" nsmstring appendFormat:"NAME: %n",peripheral.n
13、ame; nsmstring appendFormat:"RSSI: %n",RSSI; if (peripheral.isConnected) nsmstring appendString:"isConnected: connected" else nsmstring appendString:"isConnected: disconnected" NSLog("adverisement:%",advertisementData); nsmstring appendFormat:"adverisemen
14、t:%",advertisementData; nsmstring appendString:"didDiscoverPeripheraln" NSLog("%",nsmstring);/-end-結果輸出:/-start-2013-02-25 14:43:17.243 gw-health-01141:907 Peripheral Info:NAME: INFOS 4090v35.05RSSI: -69isConnected: disconnectedadverisement: kCBAdvDataServiceUUIDs = ( "
15、Unknown (<fff0>)" );/-end-如果有發現可連線的BLE週邊,它就會不斷的執行didDiscoverPeripheral,並將資訊傳入,利用這個方式將每次得到的結果存入Array,就可以得到搜尋周邊的結果然後再提供給USER選擇,或是從中可以去判斷某個特別的週邊是否存在而決定要不要連線。stopScan執行scanForPeripheralsWithServices 掃描周邊設定2秒的Timer,當時間到時就停止scan,一般2秒內無反應就可以當作是沒有其他週邊回應,承上面scanForPeripheralsWithServices中有設定T
16、imer去呼叫scanTimeout,所以將stopScan寫在scanTimeout裡面:/-start- (void) scanTimeout:(NSTimer*)timer if (CM!=NULL) CM stopScan; else NSLog("CM is Null!"); NSLog("scanTimeout");/-end-connectPeripheraldidDiscoverPeripheral得到的BLE週邊列表讓User選擇要連線的BLE,再將 CBPeripheral傳入connectPeripheral進行連線,格式:/-st
17、art- CBCentralManager connectPeripheral:CBPeripheral* options:NSDictionary*/-end-在此將它包裝成一個connect Method,/-start- (void) connect:(CBPeripheral*)peripheral if (!peripheral isConnected) CM connectPeripheral:peripheral options:nil; connectedPeripheral=peripheral; /-end-option傳入nil,connectPeriphera
18、l傳入Method connect的值。didConnectPeripheral執行connectPeripheral之後並連線成功後就會引發didConnectPeripheral的Delegate:/-start-(void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral:/-end-在這裡有個重點,連線成功後引發Delegate時,就必需要針對其CBPeripheral馬上進行discoverServices的動作,去了解週邊提供什麼樣的Services執
19、行discoverServices之後又會引發另一個didDiscoverServicesDelegate,不過這會在Explore中介紹。ExploreDiscover/Connect 中使用CBCentralManager進行連線/搜尋BLE周邊的功能,連線之後需要靠的是CBPeripheral來傳送/接收資料。CBPeripheral/-start-interface DYCoreBluetooth : NSObject<CBCentralManagerDelegate, CBPeripheralDelegate> :/-end-之後連線的重點全都是在Delegate的互動,
20、查看Service Type或是有什麼樣的Services可以提供。didConnectPeripheral前面有稍為介紹didConnectPeripheral,這是在連線成功後就會引發的Delegate,但一定要在這裡執行一些Method才可以順利的引發另一個CBPeripheral的Delegate去查看有什麼樣的Services/-start-(void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral NSLog("Connect To Per
21、ipheral with name: %nwith UUID:%n",,CFUUIDCreateString(NULL, peripheral.UUID); peripheral.delegate=self; peripheral discoverServices:nil;/一定要執行"discoverService"功能去尋找可用的Service/-end-例子中已經將peripheral.delegate=self,接下來進行peripheral的任何動做引發的Delegate都在這個Object中,執行discoverServi
22、cesMethod,讓它去尋找Services,一找到Services就又會引發didDiscoverServicesDelegate,這樣我們就可以了解有什麼Services。didDiscoverServices從這裡開始就是最關鍵/-start- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error NSLog("didDiscoverServices:n"); if( peripheral.UUID = NULL ) return; / zach ios6 a
23、dded if (!error) NSLog("=%n",); NSLog("= %d of service for UUID % =n",peripheral.services.count,CFUUIDCreateString(NULL,peripheral.UUID); for (CBService *p in peripheral.services) NSLog("Service found with UUID: %n", p.UUID); peripheral discoverCharacteri
24、stics:nil forService:p; else NSLog("Service discovery was unsuccessfull !n"); /-end-peripheral.services.count會知道有多少個Services,在每個Servces中還會有Characteristics需要了解,所以會針對每個Service來執行 peripheral discoverCharacteristics: forService:去知道每個Service下有多少個Characteristics提供傳送/接收的溝通,在執行discoverCharact
25、eristics後也引發didDiscoverCharacteristicsForService Delegate,最後再由didDiscoverCharacteristicsForService真正的判斷什麼樣的Service、什麼樣的Characteristic再進行之後收到的資料的處理動作,例如: 發現2A37的Characteristic,就要進行註冊通知,到時候BLE週邊發訊息過來才會立即的得到通知並得到資料。didDiscoverCharacteristicsForService整個最關鍵的地方就是這個Delegate,程式架構如下:/-start-(void)perip
26、heral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error:/-end-Interact完成didDiscoverCharacteristicsForService之後,整個連線過程算是完成,之後的didUpdateValueForCharacteristicDelegate是整個資料接收動作都在這發生,經過接收到的資料進行即時處理就可以取得BLE週邊的訊息,如果必需要將資料傳至BLE週邊時,再使用writeValue的Meth
27、od將資料出,以上為BLE連線最基本使用方式就大致上完成。didDiscoverCharacteristicsForService由Apple提供的資料擷取某部分來了解架構,等下程式就是利用這架構去尋訪所有的CharacteristicsForService每個Servic下都會有很多的Characteristics,Characteristics是提供資料傳遞的重點,它會有個UUID編號,再由這個編號去Bluetooth 官方查表得到是哪種資料格式,知道格式後就能去將資料解開並加以使用。真正的例子:/-start-(void)peripheral:(CBPeripheral *)periph
28、eral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error CBService *s = peripheral.services objectAtIndex:(peripheral.services.count - 1); NSLog("= Service UUID %s =n",self CBUUIDToString:service.UUID); if (!error) NSLog("= %d Characteristics of service &q
29、uot;,service.characteristics.count); for(CBCharacteristic *c in service.characteristics) NSLog(" %s n", self CBUUIDToString:c.UUID); / CBService *s = peripheral.services objectAtIndex:(peripheral.services.count - 1); if(service.UUID = NULL | s.UUID = NULL) return; / zach ios6 added /Regist
30、er notification if (service.UUID isEqual:CBUUID UUIDWithString:"180D") if (c.UUID isEqual:CBUUID UUIDWithString:"2A37") self notification:service.UUID characteristicUUID:c.UUID peripheral:peripheral on:YES; NSLog("registered notification 2A37"); if (c.UUID isEqual:CBUUI
31、D UUIDWithString:"2A38") self notification:service.UUID characteristicUUID:c.UUID peripheral:peripheral on:YES; NSLog("registered notification 2A38"); if (c.UUID isEqual:CBUUID UUIDWithString:"2A39") self notification:service.UUID characteristicUUID:c.UUID peripheral:pe
32、ripheral on:YES; NSLog("registered notification 2A39"); NSLog("= Finished set notification =n"); else NSLog("Characteristic discorvery unsuccessfull !n"); if(self compareCBUUID:service.UUID UUID2:s.UUID) /利用此來確定整個流程都結束後才能設定通知 delegate didConnected:peripheral error:error
33、; NSLog("= Finished discovering characteristics =n"); /全部服務都讀取完畢時才能使用! /-end-上面 例子是以Heart Rate(180D)為主,Heart Rate的規格來說,0x2A37可以得到心跳的數據,所以針對此項進行註冊通知,一旦有新的數據就會傳入新的數據資料並呼叫didUpdateValueForCharacteristicDelegate,來得到每次的心跳數據更新。/-start- (CBPeripheral *)p setNotifyValue:(BOOL) forCharacteristic:CB
34、Characteristic *)/-end-將Characteristic的Point傳入並設定setNotifyValue:on就完成註冊通知,之後如果有更新資料時就會引發didUpdateValueForCharacteristic Delegate,再進行資料處理。notification在設定註冊通知過程有點繁雜,所以我自行撰寫一個Method為notification,它可以從Service UUID及Characteristic UUID來找到Service與Characteristic的Object Point:。/-start-(void) notification:(CBU
35、UID *) serviceUUID characteristicUUID:(CBUUID *)characteristicUUID peripheral:(CBPeripheral *)p on:(BOOL)on CBService *service = self getServiceFromUUID:serviceUUID p:p; if (!service) if (p.UUID = NULL) return; / zach ios6 addedche NSLog("Could not find service with UUID on peripheral with UUID
36、 n"); return; CBCharacteristic *characteristic = self getCharacteristicFromUUID:characteristicUUID service:service; if (!characteristic) if (p.UUID = NULL) return; / zach ios6 added NSLog("Could not find characteristic with UUID on service with UUID on peripheral with UUIDn"); return;
37、 p setNotifyValue:on forCharacteristic:characteristic;-(CBService *) getServiceFromUUID:(CBUUID *)UUID p:(CBPeripheral *)p for (CBService* s in p.services) if (self compareCBUUID:s.UUID UUID2:UUID) return s; return nil; /Service not found on this peripheral-(CBCharacteristic *) getCharacteristicFromUUID:(CBUUID *)UUID service:(CBService*)service for (CBCharacteristic* c in service.characteristics) if (self compareCBUUID:c.UUID UUID2:UUID) return c; return nil; /Characteristic not found on this service/
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 工程项目投融资竞争-深度研究
- 微生物组与人体健康-深度研究
- 云性能监测工具的智能化趋势分析-深度研究
- 人工智能在新闻生成中的应用-深度研究
- 医疗救助与经济负担研究-深度研究
- 加油站安全管理与风险防控-深度研究
- 抗菌材料抗菌稳定性-深度研究
- 摄影艺术中的抽象与象征手法-深度研究
- 2025年广西理工职业技术学院高职单招职业适应性测试近5年常考版参考题库含答案解析
- 2025年广州番禺职业技术学院高职单招语文2018-2024历年参考题库频考点含答案解析
- 第1课 隋朝统一与灭亡 课件(26张)2024-2025学年部编版七年级历史下册
- 2025-2030年中国糖醇市场运行状况及投资前景趋势分析报告
- 冬日暖阳健康守护
- 水处理药剂采购项目技术方案(技术方案)
- 2024级高一上期期中测试数学试题含答案
- 山东省2024-2025学年高三上学期新高考联合质量测评10月联考英语试题
- 不间断电源UPS知识培训
- 三年级除法竖式300道题及答案
- 2024年江苏省徐州市中考一模数学试题(含答案)
- 新一代飞机维护技术
- 新疆2024年新疆和田师范专科学校招聘70人笔试历年典型考题及考点附答案解析
评论
0/150
提交评论