BLE設(shè)備自動在設(shè)備端連接后APP如何與設(shè)備連接_第1頁
BLE設(shè)備自動在設(shè)備端連接后APP如何與設(shè)備連接_第2頁
BLE設(shè)備自動在設(shè)備端連接后APP如何與設(shè)備連接_第3頁
BLE設(shè)備自動在設(shè)備端連接后APP如何與設(shè)備連接_第4頁
BLE設(shè)備自動在設(shè)備端連接后APP如何與設(shè)備連接_第5頁
已閱讀5頁,還剩20頁未讀, 繼續(xù)免費閱讀

下載本文檔

版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進(jìn)行舉報或認(rèn)領(lǐng)

文檔簡介

1、BLE設(shè)備自動在設(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這個Object,它掌控整個BLE狀態(tài)的管理,使用時要先對CBCentralManager初始化:/-start-CBCentralManager *

2、CM = CBCentralManager alloc initWithDelegate:self queue:nil;/-end-現(xiàn)在就開始往下介紹。centralManagerDidUpdateState在一開始宣告初CBCentralManager時就有指定Delegate為self,並且必需要在.h內(nèi)加上Delegate宣告:/-start-interface TestCoreBluetooth : NSObject<CBCentralManagerDelegate> :/-end-宣告完成後,再加入centralManagerDidUpdateState這個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),所以會有個結(jié)果是用來判斷iDevice是否支援BLE,因為BLE是在iphone 4s、New iPad之後才有的,現(xiàn)階段還是需要偵測使用的環(huán)境,當(dāng)然可以根據(jù)這些狀態(tài)的口報來決定APP的功能或其他提示使用者的動作。scanForPeripheralsWithServic

7、es先前確定周邊支援BLE且運作正常後,我們就要來開啟BLE搜尋功能來尋找BLE的週邊,當(dāng)週邊接收到搜尋功能的廣播訊息時,依照BLE通訊規(guī)範(fàn),週邊會在一定時間內(nèi)回覆,所以我們在此可以設(shè)定2秒的Timer計時器,當(dāng)時間一到就停止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)你搜尋特定時,就必需要將它的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é)果就只會將週邊有Heart Rate類型一一列出來,要了解更多的Service Type可以到Bluetooth官網(wǎng)查詢。 當(dāng)您了解Service type是哪一種類型時就可以來做對應(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會報告可以連線的週邊內(nèi)容, 如果將它印出來會像這樣:/-start-adveriseme

11、nt: kCBAdvDataLocalName = "INFOS 4090v35.05" kCBAdvDataServiceUUIDs = ( "Unknown (<fff0>)" ); kCBAdvDataTxPowerLevel = 0;/-end-RSSI是訊號的強度,是以NSNumber Object存在,取得後可以依照NSNumber的方式整數(shù)值做處理與轉(zhuǎn)換,接下來我們將一些資訊列印出來,整個範(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週邊,它就會不斷的執(zhí)行didDiscoverPeripheral,並將資訊傳入,利用這個方式將每次得到的結(jié)果存入Array,就可以得到搜尋周邊的結(jié)果然後再提供給USER選擇,或是從中可以去判斷某個特別的週邊是否存在而決定要不要連線。stopScan執(zhí)行scanForPeripheralsWithServices 掃描周邊設(shè)定2秒的Timer,當(dāng)時間到時就停止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-在此將它包裝成一個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之後並連線成功後就會引發(fā)didConnectPeripheral的Delegate:/-start-(void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral:/-end-在這裡有個重點,連線成功後引發(fā)Delegate時,就必需要針對其CBPeripheral馬上進(jìn)行discoverServices的動作,去了解週邊提供什麼樣的Services執(zhí)

19、行discoverServices之後又會引發(fā)另一個didDiscoverServicesDelegate,不過這會在Explore中介紹。ExploreDiscover/Connect 中使用CBCentralManager進(jìn)行連線/搜尋BLE周邊的功能,連線之後需要靠的是CBPeripheral來傳送/接收資料。CBPeripheral/-start-interface DYCoreBluetooth : NSObject<CBCentralManagerDelegate, CBPeripheralDelegate> :/-end-之後連線的重點全都是在Delegate的互動,

20、查看Service Type或是有什麼樣的Services可以提供。didConnectPeripheral前面有稍為介紹didConnectPeripheral,這是在連線成功後就會引發(fā)的Delegate,但一定要在這裡執(zhí)行一些Method才可以順利的引發(fā)另一個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的任何動做引發(fā)的Delegate都在這個Object中,執(zhí)行discoverServi

22、cesMethod,讓它去尋找Services,一找到Services就又會引發(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會知道有多少個Services,在每個Servces中還會有Characteristics需要了解,所以會針對每個Service來執(zhí)行 peripheral discoverCharacteristics: forService:去知道每個Service下有多少個Characteristics提供傳送/接收的溝通,在執(zhí)行discoverCharact

25、eristics後也引發(fā)didDiscoverCharacteristicsForService Delegate,最後再由didDiscoverCharacteristicsForService真正的判斷什麼樣的Service、什麼樣的Characteristic再進(jìn)行之後收到的資料的處理動作,例如: 發(fā)現(xiàn)2A37的Characteristic,就要進(jìn)行註冊通知,到時候BLE週邊發(fā)訊息過來才會立即的得到通知並得到資料。didDiscoverCharacteristicsForService整個最關(guān)鍵的地方就是這個Delegate,程式架構(gòu)如下:/-start-(void)perip

26、heral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error:/-end-Interact完成didDiscoverCharacteristicsForService之後,整個連線過程算是完成,之後的didUpdateValueForCharacteristicDelegate是整個資料接收動作都在這發(fā)生,經(jīng)過接收到的資料進(jìn)行即時處理就可以取得BLE週邊的訊息,如果必需要將資料傳至BLE週邊時,再使用writeValue的Meth

27、od將資料出,以上為BLE連線最基本使用方式就大致上完成。didDiscoverCharacteristicsForService由Apple提供的資料擷取某部分來了解架構(gòu),等下程式就是利用這架構(gòu)去尋訪所有的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) /利用此來確定整個流程都結(jié)束後才能設(shè)定通知 delegate didConnected:peripheral error:error

33、; NSLog("= Finished discovering characteristics =n"); /全部服務(wù)都讀取完畢時才能使用! /-end-上面 例子是以Heart Rate(180D)為主,Heart Rate的規(guī)格來說,0x2A37可以得到心跳的數(shù)據(jù),所以針對此項進(jìn)行註冊通知,一旦有新的數(shù)據(jù)就會傳入新的數(shù)據(jù)資料並呼叫didUpdateValueForCharacteristicDelegate,來得到每次的心跳數(shù)據(jù)更新。/-start- (CBPeripheral *)p setNotifyValue:(BOOL) forCharacteristic:CB

34、Characteristic *)/-end-將Characteristic的Point傳入並設(shè)定setNotifyValue:on就完成註冊通知,之後如果有更新資料時就會引發(fā)didUpdateValueForCharacteristic Delegate,再進(jìn)行資料處理。notification在設(shè)定註冊通知過程有點繁雜,所以我自行撰寫一個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)容里面會有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負(fù)責(zé)。
  • 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時也不承擔(dān)用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。

評論

0/150

提交評論