ios Bluetooth development (3) implementation of app being connected as peripheral

The last section describes app as a central connection peripheral. This section describes how to publish a peripheral to other central connections using app

Or in this diagram, the central mode uses the left class, while the peripheral mode uses the right class

Process in peripheral mode

1. Open the peripheralManager and set the delegation of the peripheralManager
 2. Create characteristics, characteristics'description s create services, add characteristics to services, and add services to peripheralManager
 3. Turn on broadcast advertising
 4. Respond to central operations
    - 4.1 Read characteristics requests
    - 4.2 Write a characteristics request
    - 4.4 Subscribe to and unsubscribe from characteristics

Prepare the environment

  1 xcode
  2 Develop certificates and mobile phones (Bluetooth programs need to be debugged using real machine, and simulators can also be debugged, but the method is painful, I'll put it last) If you can't use osx program to debug
  3Bluetooth peripheral

Implementation Steps

1. Open the peripheralManager and set the delegation of the peripheralManager

Set the current ViewController to implement CBPeripheralManagerDelegate delegation

    @interface BePeripheralViewController : UIViewController<CBPeripheralManagerDelegate>

Initialize peripheralManager

     /*
     Similar to CBC entralManager, Bluetooth devices take a while to open and will enter the delegation method after successful opening
     - (void)peripheralManagerDidUpdateState:(CBPeripheralManager *)peripheral;
     Simulator will never get CBPeripheralManagerStatePoweredOn status
     */
    peripheralManager = [[CBPeripheralManager alloc]initWithDelegate:self queue:nil];

2. Create characteristics, description of characteristics, service, add characteristics to service, and add service to peripheralManager

In Delegate Method - (void) In peripheralManagerDidUpdateState:(CBPeripheralManager *) peripheral, service and characteristics can only be configured when peripheral is successfully opened.The service and chara objects created here are CBMutableCharacteristic and CBMuutableService.Their differences are similar to those of NSArray and NSMutableArray.Let's start by creating characteristics and descriptions, which are descriptions of characteristics in many ways. Not to mention here, CBUUIDCharacteristicUserDescriptionString is commonly used.

//PeripherManager State Change
- (void)peripheralManagerDidUpdateState:(CBPeripheralManager *)peripheral{
    switch (peripheral.state) {
            //Here you can determine the status of Bluetooth settings. When turned on, you can call the setUp method (custom)
        case CBPeripheralManagerStatePoweredOn:
            NSLog(@"powered on");
            [info setText:[NSString stringWithFormat:@"Device Name%@Already open for use center Connect",LocalNameKey]];
            [self setUp];
            break;
        case CBPeripheralManagerStatePoweredOff:
            NSLog(@"powered off");
            [info setText:@"powered off"];
            break;

        default:
            break;
    }
}

 //Configuring bluetooch's
 -(void)setUp{

        //characteristics field description
        CBUUID *CBUUIDCharacteristicUserDescriptionStringUUID = [CBUUID UUIDWithString:CBUUIDCharacteristicUserDescriptionString];

        /*
         Characteristic that can be notified
         properties: CBCharacteristicPropertyNotify
         permissions CBAttributePermissionsReadable
         */
        CBMutableCharacteristic *notiyCharacteristic = [[CBMutableCharacteristic alloc]initWithType:[CBUUID UUIDWithString:notiyCharacteristicUUID] properties:CBCharacteristicPropertyNotify value:nil permissions:CBAttributePermissionsReadable];

        /*
         Readable and writable characteristics
         properties: CBCharacteristicPropertyWrite | CBCharacteristicPropertyRead
         permissions CBAttributePermissionsReadable | CBAttributePermissionsWriteable
         */
        CBMutableCharacteristic *readwriteCharacteristic = [[CBMutableCharacteristic alloc]initWithType:[CBUUID UUIDWithString:readwriteCharacteristicUUID] properties:CBCharacteristicPropertyWrite | CBCharacteristicPropertyRead value:nil permissions:CBAttributePermissionsReadable | CBAttributePermissionsWriteable];
        //Set description
        CBMutableDescriptor *readwriteCharacteristicDescription1 = [[CBMutableDescriptor alloc]initWithType: CBUUIDCharacteristicUserDescriptionStringUUID value:@"name"];
        [readwriteCharacteristic setDescriptors:@[readwriteCharacteristicDescription1]];


        /*
         Read-only Characteristic
         properties: CBCharacteristicPropertyRead
         permissions CBAttributePermissionsReadable
         */
        CBMutableCharacteristic *readCharacteristic = [[CBMutableCharacteristic alloc]initWithType:[CBUUID UUIDWithString:readCharacteristicUUID] properties:CBCharacteristicPropertyRead value:nil permissions:CBAttributePermissionsReadable];


        //service1 initializes and adds two characteristics
        CBMutableService *service1 = [[CBMutableService alloc]initWithType:[CBUUID UUIDWithString:ServiceUUID1] primary:YES];
        [service1 setCharacteristics:@[notiyCharacteristic,readwriteCharacteristic]];

        //service2 initializes and adds a characteristics
        CBMutableService *service2 = [[CBMutableService alloc]initWithType:[CBUUID UUIDWithString:ServiceUUID2] primary:YES];
        [service2 setCharacteristics:@[readCharacteristic]];

        //Once added, the proxy's - (void)peripheralManager:(CBPeripheralManager *)peripheral didAddService:(CBService *)service error:(NSError *)error is invoked
        [peripheralManager addService:service1];
        [peripheralManager addService:service2];
 }


3. Turn on broadcast advertising

//perihpheral added service
- (void)peripheralManager:(CBPeripheralManager *)peripheral didAddService:(CBService *)service error:(NSError *)error{
    if (error == nil) {
        serviceNum++;
    }

    //Because we've added two services, we want to add them twice before sending a broadcast
    if (serviceNum==2) {
        //After adding a service, you can notify the outside world that the proxy will be invoked after calling this method
        //(void)peripheralManagerDidStartAdvertising:(CBPeripheralManager *)peripheral error:(NSError *)error
        [peripheralManager startAdvertising:@{
                                              CBAdvertisementDataServiceUUIDsKey : @[[CBUUID UUIDWithString:ServiceUUID1],[CBUUID UUIDWithString:ServiceUUID2]],
                                              CBAdvertisementDataLocalNameKey : LocalNameKey
                                             }
         ];

    }

}

//peripheral starts sending advertising
- (void)peripheralManagerDidStartAdvertising:(CBPeripheralManager *)peripheral error:(NSError *)error{
    NSLog(@"in peripheralManagerDidStartAdvertisiong");
}

4. Respond to central operations

- 4.1 Read characteristics requests
 - 4.2 Write a characteristics request
 - 4.3 Subscribe to and unsubscribe from characteristics
//Subscription characteristics
-(void)peripheralManager:(CBPeripheralManager *)peripheral central:(CBCentral *)central didSubscribeToCharacteristic:(CBCharacteristic *)characteristic{
    NSLog(@"Subscribed %@Data",characteristic.UUID);
    //Number of seconds per second to send a current time to the primary device
    timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(sendData:) userInfo:characteristic  repeats:YES];
}

//Unsubscribe characteristics
-(void)peripheralManager:(CBPeripheralManager *)peripheral central:(CBCentral *)central didUnsubscribeFromCharacteristic:(CBCharacteristic *)characteristic{
    NSLog(@"unsubscribe %@Data",characteristic.UUID);
    //Cancel response
    [timer invalidate];
}

//Send data, seconds of current time
-(BOOL)sendData:(NSTimer *)t {
    CBMutableCharacteristic *characteristic = t.userInfo;
    NSDateFormatter *dft = [[NSDateFormatter alloc]init];
    [dft setDateFormat:@"ss"];
    NSLog(@"%@",[dft stringFromDate:[NSDate date]]);

    //Execute Response Center Notification Data
    return  [peripheralManager updateValue:[[dft stringFromDate:[NSDate date]] dataUsingEncoding:NSUTF8StringEncoding] forCharacteristic:(CBMutableCharacteristic *)characteristic onSubscribedCentrals:nil];

}


//Read characteristics Request
- (void)peripheralManager:(CBPeripheralManager *)peripheral didReceiveReadRequest:(CBATTRequest *)request{
    NSLog(@"didReceiveReadRequest");
    //Determine whether you have permission to read data
    if (request.characteristic.properties & CBCharacteristicPropertyRead) {
        NSData *data = request.characteristic.value;
        [request setValue:data];
        //Successful response to request
        [peripheralManager respondToRequest:request withResult:CBATTErrorSuccess];
    }else{
        [peripheralManager respondToRequest:request withResult:CBATTErrorWriteNotPermitted];
    }
}


//Write characteristics request
- (void)peripheralManager:(CBPeripheralManager *)peripheral didReceiveWriteRequests:(NSArray *)requests{
    NSLog(@"didReceiveWriteRequests");
    CBATTRequest *request = requests[0];

    //Determine whether you have permission to write data
    if (request.characteristic.properties & CBCharacteristicPropertyWrite) {
        //Need to be converted to a CBMutableCharacteristic object to write values
        CBMutableCharacteristic *c =(CBMutableCharacteristic *)request.characteristic;
        c.value = request.value;
        [peripheralManager respondToRequest:request withResult:CBATTErrorSuccess];
    }else{
        [peripheralManager respondToRequest:request withResult:CBATTErrorWriteNotPermitted];
    }


}

Code download:

Most of the sample code in my blog was uploaded to GitHub at https://github.com/coolnameismy/demo. Click on the jump code download address

The code store directory for this article is BleDemo

babyBluetooth Group

  • qq AC Group 6: 284341984
  • qq AC Group 5: 426082944 (full)
  • qq AC Group 4: 313084771 (full)
  • qq AC Group 3:530142592 (full)
  • qq AC Group 2:168756967 (full)
  • qq AC Group 1:426603940 (full)

Thank you for watching. If it helps you, please follow and star on github , published in Liu Yanwei's Technology Blog , please indicate the source

Keywords: github xcode Mobile simulator

Added by Gruzin on Wed, 12 Jun 2019 20:49:33 +0300