ios藍芽開發(三)app作為外設被連線的實現
阿新 • • 發佈:2019-01-23
再上一節說了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<CBPeripheralManagerDelegate>
初始化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
babyBluetooth交流群
- qq交流群6: 284341984
- qq交流群5: 426082944(滿)
- qq交流群4: 313084771(滿)
- qq交流群3:530142592(滿)
- qq交流群2:168756967(滿)
- qq交流群1:426603940(滿)