To make your app act as a BLE 4.0 peripheral, use the bePeripheral() method. You can define services and characteristics using helper functions like makeCBService and makeCharacteristicToService.
Key steps:
- Create
CBMutableService objects. - Add characteristics to services with specific properties (read
r, write w, notify n, or read/write rw). - Use
makeStaticCharacteristicToService for characteristics with cached values. - Initialize
BabyBluetooth and set peripheral-specific blocks (e.g., peripheralModelBlockOnPeripheralManagerDidUpdateState:, peripheralModelBlockOnDidStartAdvertising:, peripheralModelBlockOnDidAddService:). - Call
baby.bePeripheral().addServices(@[services]).startAdvertising().
#import "BabyBluetooth.h"
BabyBluetooth *baby;
-(void)viewDidLoad {
[super viewDidLoad];
//config first service
CBMutableService *s1 = makeCBService(@"FFF0");
//config s1's characteristic
makeCharacteristicToService(s1, @"FFF1", @"r", @"hello1"); //can read
makeCharacteristicToService(s1, @"FFF2", @"w", @"hello2"); //can write
makeCharacteristicToService(s1, genUUID(), @"rw", @"hello3"); //can read,write,uuid be automatically generate
makeCharacteristicToService(s1, @"FFF4", nil, @"hello4"); //default property is rw
makeCharacteristicToService(s1, @"FFF5", @"n", @"hello5"); //can notiy
//config seconed service s2
CBMutableService *s2 = makeCBService(@"FFE0");
//a static characteristic and has cached vuale, it must be only can read.
makeStaticCharacteristicToService(s2, genUUID(), @"hello6", [@"a" dataUsingEncoding:NSUTF8StringEncoding]);
//init BabyBluetooth
baby = [BabyBluetooth shareBabyBluetooth];
//config delegate
[self babyDelegate];
//let peripheral add services and start advertising
baby.bePeripheral().addServices(@[s1,s2]).startAdvertising();
}
//set baby peripheral model delegate
-(void)babyDelegate{
[baby peripheralModelBlockOnPeripheralManagerDidUpdateState:^(CBPeripheralManager *peripheral) {
NSLog(@"PeripheralManager trun status code: %ld", (long)peripheral.state);
}];
[baby peripheralModelBlockOnDidStartAdvertising:^(CBPeripheralManager *peripheral, NSError *error) {
NSLog(@"didStartAdvertising !!!");
}];
[baby peripheralModelBlockOnDidAddService:^(CBPeripheralManager *peripheral, CBService *service, NSError *error) {
NSLog(@"Did Add Service uuid: %@ ", service.UUID);
}];
}