蓝牙开发者门户上详细介绍了心率服务。假设您有一个已初始化的CBPeripheralManager
命名,并且您已经收到了带有状态的回调。以下是在此之后如何设置服务本身。peripheralManager
peripheralManagerDidUpdateState:
CBPeripheralManagerStatePoweredOn
// Define the heart rate service
CBMutableService *heartRateService = [[CBMutableService alloc]
initWithType:[CBUUID UUIDWithString:@"180D"] primary:true];
// Define the sensor location characteristic
char sensorLocation = 5;
CBMutableCharacteristic *heartRateSensorLocationCharacteristic = [[CBMutableCharacteristic alloc]
initWithType:[CBUUID UUIDWithString:@"0x2A38"]
properties:CBCharacteristicPropertyRead
value:[NSData dataWithBytesNoCopy:&sensorLocation length:1]
permissions:CBAttributePermissionsReadable];
// Define the heart rate reading characteristic
char heartRateData[2]; heartRateData[0] = 0; heartRateData[1] = 60;
CBMutableCharacteristic *heartRateSensorHeartRateCharacteristic = [[CBMutableCharacteristic alloc]
initWithType:[CBUUID UUIDWithString:@"2A37"]
properties: CBCharacteristicPropertyNotify
value:[NSData dataWithBytesNoCopy:&heartRateData length:2]
permissions:CBAttributePermissionsReadable];
// Add the characteristics to the service
heartRateService.characteristics =
@[heartRateSensorLocationCharacteristic, heartRateSensorHeartRateCharacteristic];
// Add the service to the peripheral manager
[peripheralManager addService:heartRateService];
在此之后,您应该会收到peripheralManager:didAddService:error:
指示添加成功的回调。您应该类似地添加设备信息服务(0x180A)最后,您应该开始广告:
NSDictionary *data = @{
CBAdvertisementDataLocalNameKey:@"iDeviceName",
CBAdvertisementDataServiceUUIDsKey:@[[CBUUID UUIDWithString:@"180D"]]};
[peripheralManager startAdvertising:data];
注意:心率服务也是我实施的第一个服务。好的选择。;)