原文:http://www.myexception.cn/operating-system/2052286.html
iOS開(kāi)發(fā)之藍(lán)牙通訊
一、引言
藍(lán)牙是設(shè)備近距離通信的一種方便手段,在iPhone引入藍(lán)牙4.0后,設(shè)備之間的通訊變得更加簡(jiǎn)單。相關(guān)的藍(lán)牙操作由專門的CoreBluetooth.framework進(jìn)行統(tǒng)一管理。通過(guò)藍(lán)牙進(jìn)行通訊交互分為兩方,一方為中心設(shè)備central,一方為外設(shè)peripheral,外設(shè)通過(guò)廣播的方式向外發(fā)送信息,中心設(shè)備檢索到外設(shè)發(fā)的廣播信息,可以進(jìn)行配對(duì)連接,進(jìn)而進(jìn)行數(shù)據(jù)交互。
二、中心設(shè)備CBCentralManager
CBCentralManager是管理中心設(shè)備的管理類,其中重要方法如下:
//設(shè)置中心設(shè)備代理@property(assign, nonatomic, nullable) iddelegate;//中心設(shè)備當(dāng)前狀態(tài)@property(readonly) CBCentralManagerState state;//中心設(shè)備是否正在掃描@property(readonly) BOOL isScanning NS_AVAILABLE(NA, 9_0);
其中state是一個(gè)枚舉,有關(guān)藍(lán)牙是否可用的狀態(tài)如下:
typedef NS_ENUM(NSInteger, CBCentralManagerState) {//狀態(tài)未知CBCentralManagerStateUnknown =0,//連接斷開(kāi) 即將重置CBCentralManagerStateResetting,//該平臺(tái)不支持藍(lán)牙CBCentralManagerStateUnsupported,//未授權(quán)藍(lán)牙使用 hovertree.comCBCentralManagerStateUnauthorized,//藍(lán)牙關(guān)閉CBCentralManagerStatePoweredOff,//藍(lán)牙正常開(kāi)啟CBCentralManagerStatePoweredOn,
};
下面這些方法用于初始化管理中心:
//初始化方法//設(shè)置的代理需要遵守CBCentralManagerDelegate協(xié)議//queue可以設(shè)置藍(lán)牙掃描的線程 傳入nil則為在主線程中進(jìn)行- (instancetype)initWithDelegate:(nullable id)delegatequeue:(nullable dispatch_queue_t)queue;//此方法同上 在options字典中用于進(jìn)行一些管理中心的初始化屬性設(shè)置//字典中支持的鍵值如下http://www.cnblogs.com/roucheng//*NSString * const CBCentralManagerOptionShowPowerAlertKey 對(duì)應(yīng)一個(gè)NSNumber類型的bool值,用于設(shè)置是否在關(guān)閉藍(lán)牙時(shí)彈出用戶提示
NSString * const CBCentralManagerOptionRestoreIdentifierKey 對(duì)應(yīng)一個(gè)NSString對(duì)象,設(shè)置管理中心的標(biāo)識(shí)符ID*/- (instancetype)initWithDelegate:(nullable id)delegatequeue:(nullable dispatch_queue_t)queue
options:(nullable NSDictionary *)options;
//根據(jù)獲取所有已知設(shè)備- (NSArray *)retrievePeripheralsWithIdentifiers:(NSArray *)identifiers;//根據(jù)服務(wù)id獲取所有連接的設(shè)備 hovertree.com- (NSArray *)retrieveConnectedPeripheralsWithServices:(NSArray *)serviceUUIDs;
在初始化管理中心完成后,會(huì)回調(diào)代理中的如下方法,我們必須實(shí)現(xiàn)如下方法:
//這個(gè)方法中可以獲取到管理中心的狀態(tài)- (void)centralManagerDidUpdateState:(CBCentralManager *)central;
如果上面方法中管理中心狀態(tài)為藍(lán)牙可用,可以通過(guò)下面方法開(kāi)啟掃描外設(shè):
//serviceUUIDs用于掃描一個(gè)特點(diǎn)ID的外設(shè) options用于設(shè)置一些掃描屬性 鍵值如下/*//是否允許重復(fù)掃描 對(duì)應(yīng)NSNumber的bool值,默認(rèn)為NO,會(huì)自動(dòng)去重
NSString *const CBCentralManagerScanOptionAllowDuplicatesKey;
//要掃描的設(shè)備UUID 數(shù)組 對(duì)應(yīng)NSArray hovertree.com
NSString *const CBCentralManagerScanOptionSolicitedServiceUUIDsKey;*/- (void)scanForPeripheralsWithServices:(nullable NSArray *)serviceUUIDs options:(nullable NSDictionary *)options;
//停止掃描外設(shè)- (void)stopScan;
掃描的結(jié)果會(huì)在如下代理方法中回掉:
//peripheral 掃描到的外設(shè)//advertisementData是外設(shè)發(fā)送的廣播數(shù)據(jù)//RSSI 是信號(hào)強(qiáng)度http://www.cnblogs.com/roucheng/- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI;
掃描到外設(shè)后,通過(guò)下面方法可以連接一個(gè)外設(shè):
/*options中可以設(shè)置一些連接設(shè)備的初始屬性鍵值如下
//對(duì)應(yīng)NSNumber的bool值,設(shè)置當(dāng)外設(shè)連接后是否彈出一個(gè)警告
NSString *const CBConnectPeripheralOptionNotifyOnConnectionKey;
//對(duì)應(yīng)NSNumber的bool值,設(shè)置當(dāng)外設(shè)斷開(kāi)連接后是否彈出一個(gè)警告
NSString *const CBConnectPeripheralOptionNotifyOnDisconnectionKey;
//對(duì)應(yīng)NSNumber的bool值,設(shè)置當(dāng)外設(shè)暫停連接后是否彈出一個(gè)警告http://www.cnblogs.com/roucheng/NSString *const CBConnectPeripheralOptionNotifyOnNotificationKey;*/- (void)connectPeripheral:(CBPeripheral *)peripheral options:(nullable NSDictionary *)options;//取消一個(gè)外設(shè)的連接- (void)cancelPeripheralConnection:(CBPeripheral *)peripheral;
調(diào)用過(guò)連接外設(shè)的方法后,會(huì)回掉如下代理方法:
//連接外設(shè)成功- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral;//連接外設(shè)失敗- (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(nullable NSError *)error;//斷開(kāi)外設(shè)連接- (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(nullable NSError *)error;
當(dāng)管理中心恢復(fù)時(shí)會(huì)調(diào)用如下代理:
1//dict中會(huì)傳入如下鍵值對(duì) hovertree.com2/*3//恢復(fù)連接的外設(shè)數(shù)組4NSString *const CBCentralManagerRestoredStatePeripheralsKey;5//恢復(fù)連接的服務(wù)UUID數(shù)組6NSString *const CBCentralManagerRestoredStateScanServicesKey;7//恢復(fù)連接的外設(shè)掃描屬性字典數(shù)組8NSString *const CBCentralManagerRestoredStateScanOptionsKey;9*/10- (void)centralManager:(CBCentralManager *)central willRestoreState:(NSDictionary *)dict;
三、外設(shè)CBPeripheralManager
從上面我們知道,中心設(shè)備是用來(lái)掃描周圍的外設(shè),兩臺(tái)設(shè)備的通訊中,必須有一個(gè)充當(dāng)中心設(shè)備,一個(gè)充當(dāng)外設(shè),外設(shè)是由CBPeripheralManager進(jìn)行管理,主要方法如下:
1//設(shè)置外設(shè)管理中心代理2@property(assign, nonatomic, nullable) iddelegate;3//外設(shè)狀態(tài) 枚舉如中心設(shè)備4@property(readonly) CBPeripheralManagerState state;5//是否正在發(fā)送廣播6@property(readonly) BOOL isAdvertising;7//用戶的授權(quán)狀態(tài)8+(CBPeripheralManagerAuthorizationStatus)authorizationStatus;9//初始化并設(shè)置代理 參數(shù)的具體含義與中心設(shè)備管理中心10- (instancetype)initWithDelegate:(nullable id)delegate11queue:(nullable dispatch_queue_t);12- (instancetype)initWithDelegate:(nullable id)delegate13queue:(nullable dispatch_queue_t)queue14options:(nullable NSDictionary *)options;15//開(kāi)始發(fā)送廣播 hovertree.com? 何問(wèn)起16//advertisementData中可以發(fā)送的數(shù)據(jù)有約定 如下17/*18對(duì)應(yīng)設(shè)置NSString類型的廣播名19NSString *const CBAdvertisementDataLocalNameKey;20外設(shè)制造商的NSData數(shù)據(jù)21NSString *const CBAdvertisementDataManufacturerDataKey;22外設(shè)制造商的CBUUID數(shù)據(jù)23NSString *const CBAdvertisementDataServiceDataKey;24服務(wù)的UUID與其對(duì)應(yīng)的服務(wù)數(shù)據(jù)字典數(shù)組25NSString *const CBAdvertisementDataServiceUUIDsKey;26附加服務(wù)的UUID數(shù)組27NSString *const CBAdvertisementDataOverflowServiceUUIDsKey;28外設(shè)的發(fā)送功率 NSNumber類型29NSString *const CBAdvertisementDataTxPowerLevelKey;30外設(shè)是否可以連接31NSString *const CBAdvertisementDataIsConnectable;32服務(wù)的UUID數(shù)組33NSString *const CBAdvertisementDataSolicitedServiceUUIDsKey;34*/35- (void)startAdvertising:(nullable NSDictionary *)advertisementData;36//停止發(fā)送廣播37- (void)stopAdvertising;38//設(shè)置一個(gè)連接的具體central設(shè)備的延時(shí) 枚舉如下39/*40typedef NS_ENUM(NSInteger, CBPeripheralManagerConnectionLatency) {41CBPeripheralManagerConnectionLatencyLow = 0,42CBPeripheralManagerConnectionLatencyMedium,43CBPeripheralManagerConnectionLatencyHigh44} NS_ENUM_AVAILABLE(NA, 6_0);45*/46- (void)setDesiredConnectionLatency:(CBPeripheralManagerConnectionLatency)latency forCentral:(CBCentral *)central;47//添加一個(gè)服務(wù)http://www.cnblogs.com/roucheng/48- (void)addService:(CBMutableService *)service;49//移除一個(gè)服務(wù)50- (void)removeService:(CBMutableService *)service;51//移除所有服務(wù)52- (void)removeAllServices;53//響應(yīng)中心設(shè)備的讀寫(xiě)請(qǐng)求54- (void)respondToRequest:(CBATTRequest *)request withResult:(CBATTError)result;55//更新一個(gè)連接中心設(shè)備的訂閱特征值56- (BOOL)updateValue:(NSData *)value forCharacteristic:(CBMutableCharacteristic *)characteristic onSubscribedCentrals:(nullable NSArray *)centrals;
外設(shè)代理的相關(guān)方法如下:
1//這個(gè)方法是必須實(shí)現(xiàn)的 狀態(tài)可用后可以發(fā)送廣播2- (void)peripheralManagerDidUpdateState:(CBPeripheralManager *)peripheral;3//連接回復(fù)時(shí)調(diào)用的方法 和centralManager類似4- (void)peripheralManager:(CBPeripheralManager *)peripheral willRestoreState:(NSDictionary *)dict;5//開(kāi)始發(fā)送廣播時(shí)調(diào)用的方法6- (void)peripheralManagerDidStartAdvertising:(CBPeripheralManager *)peripheral error:(nullable NSError *)error;7//添加服務(wù)調(diào)用的回調(diào)8- (void)peripheralManager:(CBPeripheralManager *)peripheral didAddService:(CBService *)service error:(nullable NSError *)error;9//當(dāng)一個(gè)central設(shè)備訂閱一個(gè)特征值時(shí)調(diào)用的方法10- (void)peripheralManager:(CBPeripheralManager *)peripheral central:(CBCentral *)central didSubscribeToCharacteristic:(CBCharacteristic *)characteristic;11//取消訂閱一個(gè)特征值時(shí)調(diào)用的方法12- (void)peripheralManager:(CBPeripheralManager *)peripheral central:(CBCentral *)central didUnsubscribeFromCharacteristic:(CBCharacteristic *)characteristic;13//收到讀請(qǐng)求時(shí)觸發(fā)的方法 何問(wèn)起 hovertree.com14- (void)peripheralManager:(CBPeripheralManager *)peripheral didReceiveReadRequest:(CBATTRequest *)request;15//收到寫(xiě)請(qǐng)求時(shí)觸發(fā)的方法16- (void)peripheralManager:(CBPeripheralManager *)peripheral didReceiveWriteRequests:(NSArray *)requests;17//外設(shè)準(zhǔn)備更新特征值時(shí)調(diào)用的方法18- (void)peripheralManagerIsReadyToUpdateSubscribers:(CBPeripheralManager *)peripheral;
四、中心設(shè)備與外設(shè)對(duì)象CBCentral與CBPeripheral
上面介紹了中心設(shè)備管理類與外設(shè)管理類,這些類用于將設(shè)備連接建立起來(lái),器具的數(shù)據(jù)交換的服務(wù)和一些信息則是在對(duì)應(yīng)的設(shè)備對(duì)象中。
1、中心設(shè)備 CBCentral屬性與方法
//設(shè)備UUID@property(readonly, nonatomic) NSUUID *identifier;//中心設(shè)備最大接收的數(shù)據(jù)長(zhǎng)度@property(readonly, nonatomic) NSUInteger maximumUpdateValueLength;
2、外設(shè)CAPeripheral屬性與方法
外設(shè)對(duì)象要比中心對(duì)象復(fù)雜的多,當(dāng)centralManager連接到外設(shè)后,需要通過(guò)外設(shè)對(duì)象的代理方法進(jìn)行數(shù)據(jù)交互,其中主要方法屬性如下:
1//設(shè)置代理2@property(assign, nonatomic, nullable) iddelegate;3//外設(shè)name4@property(retain,readonly, nullable) NSString *name;5//信號(hào)強(qiáng)度http://www.cnblogs.com/roucheng/6@property(retain,readonly, nullable) NSNumber *RSSI NS_DEPRECATED(NA, NA, 5_0, 8_0);7//外設(shè)狀態(tài)8/*9typedef NS_ENUM(NSInteger, CBPeripheralState) {10CBPeripheralStateDisconnected = 0,//未連接11CBPeripheralStateConnecting,//正在鏈接12CBPeripheralStateConnected,//已經(jīng)連接13CBPeripheralStateDisconnecting NS_AVAILABLE(NA, 9_0),//正在斷開(kāi)連接14} NS_AVAILABLE(NA, 7_0);15*/16@property(readonly) CBPeripheralState state;17//所有的服務(wù)數(shù)組18@property(retain,readonly, nullable) NSArray *services;19//獲取當(dāng)前信號(hào)強(qiáng)度20- (void)readRSSI;21//根據(jù)服務(wù)UUID尋找服務(wù)對(duì)象22- (void)discoverServices:(nullable NSArray *)serviceUUIDs;23//在服務(wù)對(duì)象UUID數(shù)組中尋找特定服務(wù)24- (void)discoverIncludedServices:(nullable NSArray *)includedServiceUUIDs forService:(CBService *)service;25//在一個(gè)服務(wù)中尋找特征值26- (void)discoverCharacteristics:(nullable NSArray *)characteristicUUIDs forService:(CBService *)service;27//從一個(gè)特征中讀取數(shù)據(jù)28- (void)readValueForCharacteristic:(CBCharacteristic *)characteristic;29//寫(xiě)數(shù)據(jù)的最大長(zhǎng)度 hovertree.com? 何問(wèn)起30//type枚舉如下31/*32typedef NS_ENUM(NSInteger, CBCharacteristicWriteType) {33CBCharacteristicWriteWithResponse = 0,//寫(xiě)數(shù)據(jù)并且接收成功與否回執(zhí)34CBCharacteristicWriteWithoutResponse,//寫(xiě)數(shù)據(jù)不接收回執(zhí)35};36*/37-(NSUInteger)maximumWriteValueLengthForType:(CBCharacteristicWriteType)type NS_AVAILABLE(NA, 9_0);38//向某個(gè)特征中寫(xiě)數(shù)據(jù)39- (void)writeValue:(NSData *)data forCharacteristic:(CBCharacteristic *)characteristic type:(CBCharacteristicWriteType)type;40//為制定的特征值設(shè)置監(jiān)聽(tīng)通知41- (void)setNotifyValue:(BOOL)enabled forCharacteristic:(CBCharacteristic *)characteristic;42//尋找特征值的描述43- (void)discoverDescriptorsForCharacteristic:(CBCharacteristic *)characteristic;44//讀取特征的描述值45- (void)readValueForDescriptor:(CBDescriptor *)descriptor;46//寫(xiě)特征的描述值47- (void)writeValue:(NSData *)data forDescriptor:(CBDescriptor *)descriptor;
View Code
外設(shè)的代理方法如下:
1//外設(shè)名稱更改時(shí)回調(diào)的方法2- (void)peripheralDidUpdateName:(CBPeripheral *)peripheral NS_AVAILABLE(NA, 6_0);3//外設(shè)服務(wù)變化時(shí)回調(diào)的方法4- (void)peripheral:(CBPeripheral *)peripheral didModifyServices:(NSArray *)invalidatedServices NS_AVAILABLE(NA, 7_0);5//信號(hào)強(qiáng)度改變時(shí)調(diào)用的方法6- (void)peripheralDidUpdateRSSI:(CBPeripheral *)peripheral error:(nullable NSError *)error NS_DEPRECATED(NA, NA, 5_0, 8_0);7//讀取信號(hào)強(qiáng)度回調(diào)的方法 柯樂(lè)義 keleyi.com8- (void)peripheral:(CBPeripheral *)peripheral didReadRSSI:(NSNumber *)RSSI error:(nullable NSError *)error NS_AVAILABLE(NA, 8_0);9//發(fā)現(xiàn)服務(wù)時(shí)調(diào)用的方法10- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(nullable NSError *)error;11//在服務(wù)中發(fā)現(xiàn)子服務(wù)回調(diào)的方法12- (void)peripheral:(CBPeripheral *)peripheral didDiscoverIncludedServicesForService:(CBService *)service error:(nullable NSError *)error;13//發(fā)現(xiàn)服務(wù)的特征值后回調(diào)的方法14- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(nullable NSError *)error;15//特征值更新時(shí)回調(diào)的方法16- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(nullable NSError *)error;17//向特征值寫(xiě)數(shù)據(jù)時(shí)回調(diào)的方法18- (void)peripheral:(CBPeripheral *)peripheral didWriteValueForCharacteristic:(CBCharacteristic *)characteristic error:(nullable NSError *)error;19//特征值的通知設(shè)置改變時(shí)觸發(fā)的方法20- (void)peripheral:(CBPeripheral *)peripheral didUpdateNotificationStateForCharacteristic:(CBCharacteristic *)characteristic error:(nullable NSError *)error;21//發(fā)現(xiàn)特征值的描述信息觸發(fā)的方法22- (void)peripheral:(CBPeripheral *)peripheral didDiscoverDescriptorsForCharacteristic:(CBCharacteristic *)characteristic error:(nullable NSError *)error;23//特征的描述值更新時(shí)觸發(fā)的方法24- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForDescriptor:(CBDescriptor *)descriptor error:(nullable NSError *)error;25//寫(xiě)描述信息時(shí)觸發(fā)的方法26- (void)peripheral:(CBPeripheral *)peripheral didWriteValueForDescriptor:(CBDescriptor *)descriptor error:(nullable NSError *)error;
View Code
五、服務(wù)對(duì)象CBService
服務(wù)對(duì)象是用來(lái)管理外設(shè)提供的一些數(shù)據(jù)服務(wù)的,其中屬性如下:
//對(duì)應(yīng)的外設(shè)@property(assign,readonly, nonatomic) CBPeripheral *peripheral;//是否是初等服務(wù)@property(readonly, nonatomic) BOOL isPrimary;//包含的自服務(wù)http://www.cnblogs.com/roucheng/@property(retain,readonly, nullable) NSArray *includedServices;//服務(wù)中的特征值@property(retain,readonly, nullable) NSArray *characteristics;
六、服務(wù)的特征值CBCharacteristic
通過(guò)綁定服務(wù)中的特征值來(lái)進(jìn)行數(shù)據(jù)的讀寫(xiě)操作,其中屬性如下:
//對(duì)應(yīng)的服務(wù)對(duì)象@property(assign,readonly, nonatomic) CBService *service;//特征值的屬性 枚舉如下/*typedef NS_OPTIONS(NSUInteger, CBCharacteristicProperties) {
CBCharacteristicPropertyBroadcast,//允許廣播特征
CBCharacteristicPropertyRead,//可讀屬性
CBCharacteristicPropertyWriteWithoutResponse,//可寫(xiě)并且接收回執(zhí)
CBCharacteristicPropertyWrite,//可寫(xiě)屬性
CBCharacteristicPropertyNotify,//可通知屬性
CBCharacteristicPropertyIndicate,//可展現(xiàn)的特征值
CBCharacteristicPropertyAuthenticatedSignedWrites,//允許簽名的特征值寫(xiě)入
CBCharacteristicPropertyExtendedProperties,
CBCharacteristicPropertyNotifyEncryptionRequired,
CBCharacteristicPropertyIndicateEncryptionRequired
};*/@property(readonly, nonatomic) CBCharacteristicProperties properties;//特征值的數(shù)據(jù)http://www.cnblogs.com/roucheng/@property(retain,readonly, nullable) NSData *value;//特征值的描述@property(retain,readonly, nullable) NSArray *descriptors;//是否是當(dāng)前廣播的特征@property(readonly) BOOL isBroadcasted;//是否是正在通知的特征@property(readonly) BOOL isNotifying;
七、讀寫(xiě)請(qǐng)求對(duì)象CBATTRequest
服務(wù)對(duì)象是外設(shè)向中心設(shè)備提供的相關(guān)數(shù)據(jù)服務(wù),獲取到相應(yīng)服務(wù)后,中心設(shè)備可以進(jìn)行讀寫(xiě)請(qǐng)求,讀寫(xiě)對(duì)象屬性如下:
//對(duì)應(yīng)的中心設(shè)備@property(readonly, nonatomic) CBCentral *central;//對(duì)應(yīng)的特征值@property(readonly, nonatomic) CBCharacteristic *characteristic;//讀寫(xiě)數(shù)據(jù)值@property(readwrite, copy, nullable) NSData *value;
http://www.cnblogs.com/roucheng/p/texiao.html
本文小結(jié):
iOS開(kāi)發(fā)之藍(lán)牙通訊
一、引言
二、中心設(shè)備CBCentralManager
三、外設(shè)CBPeripheralManager
四、中心設(shè)備與外設(shè)對(duì)象CBCentral與CBPeripheral
1、中心設(shè)備 CBCentral屬性與方法
2、外設(shè)CAPeripheral屬性與方法
五、服務(wù)對(duì)象CBService
六、服務(wù)的特征值CBCharacteristic
七、讀寫(xiě)請(qǐng)求對(duì)象CBATTRequest