CoreBluetooth连接蓝牙健康设备

引言

CoreBluetooth是iOS下用于蓝牙设备连接的模块,支持蓝牙4.0及以上的设备。蓝牙设备五花八门,本文的主角是蓝牙健康设备,目标是在iPhone上获取蓝牙健康设备测量到的数据(android手机请看这篇文章)。
本文使用的蓝牙健康设备是日本A&D公司生产的蓝牙血压计(UA-651BLE)和体温计(UT-201BLE)。使用这两个型号的健康设备是因为它们是康体佳联盟(continua health alliance)认证的,接口是标准化的,没有进行加密。

原理

在CoreBluetooth中,拥有数据的蓝牙设备被称为peripheral,向外发送数据;获取数据的设备称为central,一般是手机或电脑。本文中central就是我们的手机。
蓝牙通信结构

peripheral会不断广播很小的数据包,包含设备的名称、主要服务等,让外界知道自己的存在。如果有一个central在扫描,就可以获得这个数据包,从而能够去连接这个设备。
发送广告

peripheral中最关键的信息就是其包含的service,一个peripheral可以有一个或多个service,每个service下有一个或多个characteristic,用来具体描述这个service。例如,下图是一个心率的service,包含了两个characteristic,分别是心率数值,传感器位置。
peripheral结构

流程

了解原理后就可以实践了。我们的手机作为central,在ViewController要实现CBCentralManagerDelegate,之后要操作peripheral,因此也需要实现CBPeripheralDelegate。
* 初始化

@property (strong, nonatomic) CBCentralManager *centralManager;

self.centralManager = [[CBCentralManager alloc] initWithDelegate:self queue:nil];```

* 扫描设备 第一个array的参数如果填nil就会扫描所有蓝牙设备,推荐用设备包含的服务来过滤(如血压服务)。

NSString * const BLOOD_PRESSURE_UUID = @”1810”; //血压服务的UUID

[self.centralManager scanForPeripheralsWithServices:[NSArray arrayWithObjects:[CBUUID UUIDWithString:BLOOD_PRESSURE_UUID], nil] options:nil];“`

  • 扫描到符合要求的蓝牙设备后会调用CBCentralManagerDelegate中下面这个方法
- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary<NSString *,id> *)advertisementData RSSI:(NSNumber *)RSSI{
    if (!peripheral || !peripheral.name || ([peripheral.name isEqualToString:@""])) {
        return;
    }
    NSLog(@"name:%@",peripheral.name);
    NSLog(@"ad:%@",advertisementData);
    [self stopDiscover];  //停止扫描节约电量
    self.peripheral = peripheral;
    peripheral.delegate = self;
    [self.centralManager connectPeripheral:peripheral options:nil]; //尝试连接此设备
}```

* 如果连接成功,会调用CBCentralManagerDelegate的这个方法,在这里去获取此设备的服务。
  • (void)centralManager:(CBCentralManager )central didConnectPeripheral:(CBPeripheral )peripheral{
    if (!peripheral) {
    return;
    }
    NSLog(@”did connect peripheral”);
    [self.peripheral discoverServices:nil]; //尝试发现这个设备的服务
    }“`

  • 成功获取peripheral的服务,就会调用CBPeripheralDelegate的这个方法

- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error{
    for (CBService *service in peripheral.services) {  //遍历服务
        NSLog(@"discover service: %@", service);
        if ([service.UUID isEqual:[CBUUID UUIDWithString:BLOOD_PRESSURE_UUID]] ) {
            [peripheral discoverCharacteristics:nil forService:service];  //如果是血压服务,就尝试发现这个服务的characteristic
            break;
        }
    }
}```

* 成功发现characteristic后,调用CBPeripheralDelegate的这个方法
  • (void)peripheral:(CBPeripheral )peripheral didDiscoverCharacteristicsForService:(CBService )service error:(NSError *)error{
    for (CBCharacteristic *character in service.characteristics) {
    NSLog(@”discover characteristic: %@”,character);
    if ([character.UUID isEqual:[CBUUID UUIDWithString:BLOOD_PRESSURE_MEASUREMENT_UUID]]) {
    //监听我们关注的characteristic,一旦这个//发生变化就会得到通知
    [peripheral setNotifyValue:YES forCharacteristic:character];
    }
    if ([character.UUID isEqual:[CBUUID UUIDWithString:BLOOD_PRESSURE_FEATURE_UUID]]) {
    //读取characteristic的值
    [peripheral readValueForCharacteristic:character];
    }
    if ([character.UUID isEqual:[CBUUID UUIDWithString:DATE_TIME_UUID]]) {
    [peripheral readValueForCharacteristic:character];
    }

    }
    }“`

  • 设备测量完成后会发送数据,获得数据后调用CBPeripheralDelegate的这个方法

“`
- (void)peripheral:(CBPeripheral )peripheral didUpdateValueForCharacteristic:(CBCharacteristic )characteristic error:(NSError *)error{
if (error) {
NSLog(@”%@”,[error localizedDescription]);
}else{
NSData *data = characteristic.value; //获取raw data
if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:BLOOD_PRESSURE_MEASUREMENT_UUID]] && data) {
const uint8_t *reportData = [data bytes]; //转换一个字节对应一个整数的序列
NSInteger sys = reportData[1]; //收缩压
NSInteger dia = reportData[3]; //舒张压
NSInteger pul = reportData[7]; //心率
NSLog(@”sys:%ld”,(long)sys);
NSLog(@”dia:%ld”,(long)dia);
NSLog(@”pul:%ld”,(long)pul);
if (sys == 255) {
self.sysTextField.text = @”error”;
self.diaTextField.text = @”error”;
self.pulTextField.text = @”error”;
}else{
self.sysTextField.text = [NSString stringWithFormat:@”%ld”,sys];
self.diaTextField.text = [NSString stringWithFormat:@”%ld”,dia];
self.pulTextField.text = [NSString stringWithFormat:@”%ld”,pul];
}

    }else{
        NSLog(@"data value: %@ UUID:%@",data, characteristic.UUID);
    }
}

}“`

运行截图

血压测量界面

体温测量界面

源码

Github项目地址

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
iOS 可以通过 Core Bluetooth 框架来连接蓝牙设备。以下是连接蓝牙设备的基本步骤: 1. 导入 Core Bluetooth 框架。 2. 创建一个 Central Manager 对象,并实现它的代理方法。 3. 扫描周围的蓝牙设备,获取设备的 UUID。 4. 连接指定的蓝牙设备。 5. 执行设备的服务和特性,以便与设备通信。 以下是一个简单的示例代码: ``` import CoreBluetooth class ViewController: UIViewController, CBCentralManagerDelegate { var centralManager: CBCentralManager! override func viewDidLoad() { super.viewDidLoad() centralManager = CBCentralManager(delegate: self, queue: nil) } func centralManagerDidUpdateState(_ central: CBCentralManager) { if central.state == .poweredOn { // 开始扫描蓝牙设备 centralManager.scanForPeripherals(withServices: nil, options: nil) } else { print("蓝牙未打开") } } func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) { // 获取设备的 UUID,连接指定的蓝牙设备 if peripheral.identifier.uuidString == "指定设备的UUID" { centralManager.connect(peripheral, options: nil) } } func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) { // 连接成功后,执行设备的服务和特性 peripheral.delegate = self peripheral.discoverServices(nil) } } extension ViewController: CBPeripheralDelegate { func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) { if let services = peripheral.services { for service in services { peripheral.discoverCharacteristics(nil, for: service) } } } func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) { if let characteristics = service.characteristics { for characteristic in characteristics { // 与设备进行读写操作 } } } } ``` 当然,具体的实现还需要根据你的蓝牙设备来进行调整。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值