




版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進(jìn)行舉報(bào)或認(rèn)領(lǐng)
文檔簡介
1、BLE設(shè)備自動(dòng)在設(shè)備端連接后APP如何與設(shè)備連接原文地址: 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這個(gè)Object,它掌控整個(gè)BLE狀態(tài)的管理,使用時(shí)要先對CBCentralManager初始化:/-start-CBCentralManager *
2、CM = CBCentralManager alloc initWithDelegate:self queue:nil;/-end-現(xiàn)在就開始往下介紹。centralManagerDidUpdateState在一開始宣告初CBCentralManager時(shí)就有指定Delegate為self,並且必需要在.h內(nèi)加上Delegate宣告:/-start-interface TestCoreBluetooth : NSObject<CBCentralManagerDelegate> :/-end-宣告完成後,再加入centralManagerDidUpdateState這個(gè)Delegat
3、e內(nèi)容,/-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是用來得知藍(lán)牙目前的狀態(tài),所以會(huì)有個(gè)結(jié)果是用來判斷iDevice是否支援BLE,因?yàn)锽LE是在iphone 4s、New iPad之後才有的,現(xiàn)階段還是需要偵測使用的環(huán)境,當(dāng)然可以根據(jù)這些狀態(tài)的口報(bào)來決定APP的功能或其他提示使用者的動(dòng)作。scanForPeripheralsWithServic
7、es先前確定周邊支援BLE且運(yùn)作正常後,我們就要來開啟BLE搜尋功能來尋找BLE的週邊,當(dāng)週邊接收到搜尋功能的廣播訊息時(shí),依照BLE通訊規(guī)範(fàn),週邊會(huì)在一定時(shí)間內(nèi)回覆,所以我們在此可以設(shè)定2秒的Timer計(jì)時(shí)器,當(dāng)時(shí)間一到就停止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-設(shè)定2秒後觸發(fā)執(zhí)行scanTimeoutmethod,再將scanForPeripheralsWithServices的值設(shè)為nil,代表搜尋的Service type不受限制,當(dāng)你搜尋特定時(shí),就必需要將它的UUID填入,像範(fàn)例這樣:/-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,結(jié)果就只會(huì)將週邊有Heart Rate類型一一列出來,要了解更多的Service Type可以到Bluetooth官網(wǎng)查詢。 當(dāng)您了解Service type是哪一種類型時(shí)就可以來做對應(yīng)的流程及資料的解析,也可以製作出符合一般標(biāo)準(zhǔn)週邊的通用APP。didDiscoverPeripheraldidDiscoverPe
10、ripheral屬於Delegate功能,所以要按照它預(yù)設(shè)的宣告將要處理的過程寫在裡面,格式如下:/-start-(void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI/處理過程/-end-advertisementData會(huì)報(bào)告可以連線的週邊內(nèi)容, 如果將它印出來會(huì)像這樣:/-start-adveriseme
11、nt: kCBAdvDataLocalName = "INFOS 4090v35.05" kCBAdvDataServiceUUIDs = ( "Unknown (<fff0>)" ); kCBAdvDataTxPowerLevel = 0;/-end-RSSI是訊號(hào)的強(qiáng)度,是以NSNumber Object存在,取得後可以依照NSNumber的方式整數(shù)值做處理與轉(zhuǎn)換,接下來我們將一些資訊列印出來,整個(gè)範(fàn)例可以是這樣子:/-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-結(jié)果輸出:/-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-如果有發(fā)現(xiàn)可連線的BLE週邊,它就會(huì)不斷的執(zhí)行didDiscoverPeripheral,並將資訊傳入,利用這個(gè)方式將每次得到的結(jié)果存入Array,就可以得到搜尋周邊的結(jié)果然後再提供給USER選擇,或是從中可以去判斷某個(gè)特別的週邊是否存在而決定要不要連線。stopScan執(zhí)行scanForPeripheralsWithServices 掃描周邊設(shè)定2秒的Timer,當(dāng)時(shí)間到時(shí)就停止scan,一般2秒內(nèi)無反應(yīng)就可以當(dāng)作是沒有其他週邊回應(yīng),承上面scanForPeripheralsWithServices中有設(shè)定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進(jìn)行連線,格式:/-st
17、art- CBCentralManager connectPeripheral:CBPeripheral* options:NSDictionary*/-end-在此將它包裝成一個(gè)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執(zhí)行connectPeripheral之後並連線成功後就會(huì)引發(fā)didConnectPeripheral的Delegate:/-start-(void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral:/-end-在這裡有個(gè)重點(diǎn),連線成功後引發(fā)Delegate時(shí),就必需要針對其CBPeripheral馬上進(jìn)行discoverServices的動(dòng)作,去了解週邊提供什麼樣的Services執(zhí)
19、行discoverServices之後又會(huì)引發(fā)另一個(gè)didDiscoverServicesDelegate,不過這會(huì)在Explore中介紹。ExploreDiscover/Connect 中使用CBCentralManager進(jìn)行連線/搜尋BLE周邊的功能,連線之後需要靠的是CBPeripheral來傳送/接收資料。CBPeripheral/-start-interface DYCoreBluetooth : NSObject<CBCentralManagerDelegate, CBPeripheralDelegate> :/-end-之後連線的重點(diǎn)全都是在Delegate的互動(dòng),
20、查看Service Type或是有什麼樣的Services可以提供。didConnectPeripheral前面有稍為介紹didConnectPeripheral,這是在連線成功後就會(huì)引發(fā)的Delegate,但一定要在這裡執(zhí)行一些Method才可以順利的引發(fā)另一個(gè)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;/一定要執(zhí)行"discoverService"功能去尋找可用的Service/-end-例子中已經(jīng)將peripheral.delegate=self,接下來進(jìn)行peripheral的任何動(dòng)做引發(fā)的Delegate都在這個(gè)Object中,執(zhí)行discoverServi
22、cesMethod,讓它去尋找Services,一找到Services就又會(huì)引發(fā)didDiscoverServicesDelegate,這樣我們就可以了解有什麼Services。didDiscoverServices從這裡開始就是最關(guān)鍵/-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會(huì)知道有多少個(gè)Services,在每個(gè)Servces中還會(huì)有Characteristics需要了解,所以會(huì)針對每個(gè)Service來執(zhí)行 peripheral discoverCharacteristics: forService:去知道每個(gè)Service下有多少個(gè)Characteristics提供傳送/接收的溝通,在執(zhí)行discoverCharact
25、eristics後也引發(fā)didDiscoverCharacteristicsForService Delegate,最後再由didDiscoverCharacteristicsForService真正的判斷什麼樣的Service、什麼樣的Characteristic再進(jìn)行之後收到的資料的處理動(dòng)作,例如: 發(fā)現(xiàn)2A37的Characteristic,就要進(jìn)行註冊通知,到時(shí)候BLE週邊發(fā)訊息過來才會(huì)立即的得到通知並得到資料。didDiscoverCharacteristicsForService整個(gè)最關(guān)鍵的地方就是這個(gè)Delegate,程式架構(gòu)如下:/-start-(void)perip
26、heral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error:/-end-Interact完成didDiscoverCharacteristicsForService之後,整個(gè)連線過程算是完成,之後的didUpdateValueForCharacteristicDelegate是整個(gè)資料接收動(dòng)作都在這發(fā)生,經(jīng)過接收到的資料進(jìn)行即時(shí)處理就可以取得BLE週邊的訊息,如果必需要將資料傳至BLE週邊時(shí),再使用writeValue的Meth
27、od將資料出,以上為BLE連線最基本使用方式就大致上完成。didDiscoverCharacteristicsForService由Apple提供的資料擷取某部分來了解架構(gòu),等下程式就是利用這架構(gòu)去尋訪所有的CharacteristicsForService每個(gè)Servic下都會(huì)有很多的Characteristics,Characteristics是提供資料傳遞的重點(diǎn),它會(huì)有個(gè)UUID編號(hào),再由這個(gè)編號(hào)去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) /利用此來確定整個(gè)流程都結(jié)束後才能設(shè)定通知 delegate didConnected:peripheral error:error
33、; NSLog("= Finished discovering characteristics =n"); /全部服務(wù)都讀取完畢時(shí)才能使用! /-end-上面 例子是以Heart Rate(180D)為主,Heart Rate的規(guī)格來說,0x2A37可以得到心跳的數(shù)據(jù),所以針對此項(xiàng)進(jìn)行註冊通知,一旦有新的數(shù)據(jù)就會(huì)傳入新的數(shù)據(jù)資料並呼叫didUpdateValueForCharacteristicDelegate,來得到每次的心跳數(shù)據(jù)更新。/-start- (CBPeripheral *)p setNotifyValue:(BOOL) forCharacteristic:CB
34、Characteristic *)/-end-將Characteristic的Point傳入並設(shè)定setNotifyValue:on就完成註冊通知,之後如果有更新資料時(shí)就會(huì)引發(fā)didUpdateValueForCharacteristic Delegate,再進(jìn)行資料處理。notification在設(shè)定註冊通知過程有點(diǎn)繁雜,所以我自行撰寫一個(gè)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. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫網(wǎng)僅提供信息存儲(chǔ)空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負(fù)責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 環(huán)境保護(hù)與節(jié)能減排教育培訓(xùn)
- 小兒肺炎的臨床表現(xiàn)及護(hù)理
- 幼兒健康活動(dòng)保護(hù)耳朵
- 領(lǐng)導(dǎo)講安全課件
- 顱骨修補(bǔ)術(shù)后護(hù)理課件
- 顱內(nèi)占位護(hù)理課件
- 胃癌腹腔鏡手術(shù)護(hù)理常規(guī)
- 預(yù)防欺凌主題班會(huì)課件
- 《機(jī)械設(shè)計(jì)基礎(chǔ)》課件-第13章 軸
- 預(yù)防兒童溺水課件
- 招商大使選聘管理辦法
- 2025年中國鐵路集團(tuán)招聘筆試備考題庫(帶答案詳解)
- 用工風(fēng)險(xiǎn)培訓(xùn)課件
- 海外現(xiàn)場安全健康環(huán)境管理(HSE)
- 2025年公安機(jī)關(guān)人民警察(行政執(zhí)法)資格考試(客觀題及刑法)含答案
- DLT 5035-2016 發(fā)電廠供暖通風(fēng)與空氣調(diào)節(jié)設(shè)計(jì)規(guī)范
- DZ∕T 0201-2020 礦產(chǎn)地質(zhì)勘查規(guī)范 鎢、錫、汞、銻(正式版)
- 小小科學(xué)家《物理》模擬試卷A(附答案)
- 《風(fēng)電場項(xiàng)目經(jīng)濟(jì)評價(jià)規(guī)范》(NB-T 31085-2016)
- 檢驗(yàn)科員工個(gè)人技術(shù)檔案
- 企業(yè)拆除前現(xiàn)場清查登記表
評論
0/150
提交評論