再上一节说了app作为central衔接peripheral的状况,这一节介绍怎么运用app发布一个peripheral,给其他的central衔接

iOS蓝牙开发(三)app作为外设被连接的实现(转)

仍是这张图,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,地址是:github.com/coolnameism…](github.com/coolnameism…)

本文代码存放目录是BleDemo