標籤:
轉載自:www.cocoachina.com/ios/20151105/14071.html
原劉彥瑋
再上一節說了app作為central串連peripheral的情況,這一節介紹如何使用app發布一個peripheral,給其他的central串連
還是這張圖,central模式用的都是左邊的類,而peripheral模式用的是右邊的類
peripheral模式的流程
1. 開啟peripheralManager,設定peripheralManager的委託
2. 建立characteristics,characteristics的description 建立service,把characteristics添加到service中,再把service添加到peripheralManager中
3. 開啟廣播advertising
4. 對central的操作進行響應
- 4.1 讀characteristics請求
- 4.2 寫characteristics請求
- 4.4 訂閱和取消訂閱characteristics
準備環境
1 Xcode
2 開發認證和手機(藍芽程式需要使用使用真機調試,使用模擬器也可以調試,但是方法很蛋疼,我會放在最後說),如果不行可以使用osx程式調試
3 藍芽外設
實現步驟
1. 開啟peripheralManager,設定peripheralManager的委託
設定當前ViewController實現CBPeripheralManagerDelegate委託
@interface BePeripheralViewController : UIViewController
初始化peripheralManager
/* 和CBCentralManager類似,藍牙裝置開啟需要一定時間,開啟成功後會進入委託方法 - (void)peripheralManagerDidUpdateState:(CBPeripheralManager *)peripheral; 模擬器永遠也不會得CBPeripheralManagerStatePoweredOn狀態 */ peripheralManager = [[CBPeripheralManager alloc]initWithDelegate:self queue:nil];
2. 建立characteristics,characteristics的description ,建立service,把characteristics添加到service中,再把service添加到peripheralManager中
在 委託方法 - (void)peripheralManagerDidUpdateState:(CBPeripheralManager *)peripheral中,當peripheral成功開啟後,才可以配置service和characteristics。 這裡建立的service和chara對象是CBMutableCharacteristic和CBMutableService。他們的區別就像 NSArray和NSMutableArray區別類似。 我們先建立characteristics和description,description是characteristics的描述,描述分很多種, 這裡不細說了,常用的就是CBUUIDCharacteristicUserDescriptionString。
//peripheralManager狀態改變- (void)peripheralManagerDidUpdateState:(CBPeripheralManager *)peripheral{ switch (peripheral.state) { //在這裡判斷藍芽設別的狀態 當開啟了則可調用 setUp方法(自訂) case CBPeripheralManagerStatePoweredOn: NSLog(@"powered on"); [info setText:[NSString stringWithFormat:@"裝置名稱%@已經開啟,可以使用center進行串連",LocalNameKey]]; [self setUp]; break; case CBPeripheralManagerStatePoweredOff: NSLog(@"powered off"); [info setText:@"powered off"]; break; default: break; }}
//配置bluetooch的 -(void)setUp{ //characteristics欄位描述 CBUUID *CBUUIDCharacteristicUserDescriptionStringUUID = [CBUUID UUIDWithString:CBUUIDCharacteristicUserDescriptionString]; /* 可以通知的Characteristic properties:CBCharacteristicPropertyNotify permissions CBAttributePermissionsReadable */ CBMutableCharacteristic *notiyCharacteristic = [[CBMutableCharacteristic alloc]initWithType:[CBUUID UUIDWithString:notiyCharacteristicUUID] properties:CBCharacteristicPropertyNotify value:nil permissions:CBAttributePermissionsReadable]; /* 可讀寫的characteristics properties:CBCharacteristicPropertyWrite | CBCharacteristicPropertyRead permissions CBAttributePermissionsReadable | CBAttributePermissionsWriteable */ CBMutableCharacteristic *readwriteCharacteristic = [[CBMutableCharacteristic alloc]initWithType:[CBUUID UUIDWithString:readwriteCharacteristicUUID] properties:CBCharacteristicPropertyWrite | CBCharacteristicPropertyRead value:nil permissions:CBAttributePermissionsReadable | CBAttributePermissionsWriteable]; //設定description CBMutableDescriptor *readwriteCharacteristicDescription1 = [[CBMutableDescriptor alloc]initWithType: CBUUIDCharacteristicUserDescriptionStringUUID value:@"name"]; [readwriteCharacteristic setDescriptors:@[readwriteCharacteristicDescription1]]; /* 唯讀Characteristic properties:CBCharacteristicPropertyRead permissions CBAttributePermissionsReadable */ CBMutableCharacteristic *readCharacteristic = [[CBMutableCharacteristic alloc]initWithType:[CBUUID UUIDWithString:readCharacteristicUUID] properties:CBCharacteristicPropertyRead value:nil permissions:CBAttributePermissionsReadable]; //service1初始化並加入兩個characteristics CBMutableService *service1 = [[CBMutableService alloc]initWithType:[CBUUID UUIDWithString:ServiceUUID1] primary:YES]; [service1 setCharacteristics:@[notiyCharacteristic,readwriteCharacteristic]]; //service2初始化並加入一個characteristics CBMutableService *service2 = [[CBMutableService alloc]initWithType:[CBUUID UUIDWithString:ServiceUUID2] primary:YES]; [service2 setCharacteristics:@[readCharacteristic]]; //添加後就會調用代理的- (void)peripheralManager:(CBPeripheralManager *)peripheral didAddService:(CBService *)service error:(NSError *)error [peripheralManager addService:service1]; [peripheralManager addService:service2]; }
3. 開啟廣播advertising
//perihpheral添加了service- (void)peripheralManager:(CBPeripheralManager *)peripheral didAddService:(CBService *)service error:(NSError *)error{ if (error == nil) { serviceNum++; } //因為我們添加了2個服務,所以想兩次都添加完成後才去發送廣播 if (serviceNum==2) { //添加服務後可以在此向外界發出通告 調用完這個方法後會調用代理的 //(void)peripheralManagerDidStartAdvertising:(CBPeripheralManager *)peripheral error:(NSError *)error [peripheralManager startAdvertising:@{ CBAdvertisementDataServiceUUIDsKey : @[[CBUUID UUIDWithString:ServiceUUID1],[CBUUID UUIDWithString:ServiceUUID2]], CBAdvertisementDataLocalNameKey : LocalNameKey } ]; }}//peripheral開始發送advertising- (void)peripheralManagerDidStartAdvertising:(CBPeripheralManager *)peripheral error:(NSError *)error{ NSLog(@"in peripheralManagerDidStartAdvertisiong");}
4. 對central的操作進行響應
- 4.1 讀characteristics請求
- 4.2 寫characteristics請求
- 4.3 訂閱和取消訂閱characteristics
//訂閱characteristics-(void)peripheralManager:(CBPeripheralManager *)peripheral central:(CBCentral *)central didSubscribeToCharacteristic:(CBCharacteristic *)characteristic{ NSLog(@"訂閱了 %@的資料",characteristic.UUID); //每秒執行一次給主裝置發送一個目前時間的秒數 timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(sendData:) userInfo:characteristic repeats:YES];}//取消訂閱characteristics-(void)peripheralManager:(CBPeripheralManager *)peripheral central:(CBCentral *)central didUnsubscribeFromCharacteristic:(CBCharacteristic *)characteristic{ NSLog(@"取消訂閱 %@的資料",characteristic.UUID); //取消回應 [timer invalidate];}//發送資料,發送目前時間的秒數-(BOOL)sendData:(NSTimer *)t { CBMutableCharacteristic *characteristic = t.userInfo; NSDateFormatter *dft = [[NSDateFormatter alloc]init]; [dft setDateFormat:@"ss"]; NSLog(@"%@",[dft stringFromDate:[NSDate date]]); //執行回應Central通知數據 return [peripheralManager updateValue:[[dft stringFromDate:[NSDate date]] dataUsingEncoding:NSUTF8StringEncoding] forCharacteristic:(CBMutableCharacteristic *)characteristic onSubscribedCentrals:nil];}//讀characteristics請求- (void)peripheralManager:(CBPeripheralManager *)peripheral didReceiveReadRequest:(CBATTRequest *)request{ NSLog(@"didReceiveReadRequest"); //判斷是否有讀資料的許可權 if (request.characteristic.properties & CBCharacteristicPropertyRead) { NSData *data = request.characteristic.value; [request setValue:data]; //對請求作出成功響應 [peripheralManager respondToRequest:request withResult:CBATTErrorSuccess]; }else{ [peripheralManager respondToRequest:request withResult:CBATTErrorWriteNotPermitted]; }}//寫characteristics請求- (void)peripheralManager:(CBPeripheralManager *)peripheral didReceiveWriteRequests:(NSArray *)requests{ NSLog(@"didReceiveWriteRequests"); CBATTRequest *request = requests[0]; //判斷是否有寫資料的許可權 if (request.characteristic.properties & CBCharacteristicPropertyWrite) { //需要轉換成CBMutableCharacteristic對象才能進行寫值 CBMutableCharacteristic *c =(CBMutableCharacteristic *)request.characteristic; c.value = request.value; [peripheralManager respondToRequest:request withResult:CBATTErrorSuccess]; }else{ [peripheralManager respondToRequest:request withResult:CBATTErrorWriteNotPermitted]; }}
代碼下載:
我部落格中大部分範例程式碼都上傳到了github,地址是:https://github.com/coolnameismy/demo,點擊跳轉代碼
本文代碼存放目錄是BleDemo
如果大家支援,請follow我的github帳號,並star我的項目,有其他問題可以在blog中給我留言 blog的RSS訂閱
iOS 藍芽開發(三)app作為外設被串連的實現(轉)