iOS开发拾碎iOS学习开发

iOS 蓝牙连接外设并完成读写交互的简单步骤

2019-11-07  本文已影响0人  王加水
iOS蓝牙连接外设一堆代理方法的使用,在此分步骤按顺序梳理了一下,增加了接入的可读性和部分细节说明,详情会后附demo
1.初始化CBCentralManager并设置代理<CBCentralManagerDelegate,CBPeripheralDelegate>

self.theCentral = [[CBCentralManager alloc] initWithDelegate:self queue:nil options:@{CBCentralManagerOptionShowPowerAlertKey:@(NO)}];

2.上面初始化设置了代理,就有代理方法监听蓝牙状态

- (void)centralManagerDidUpdateState:(CBCentralManager *)central

3.扫描附近的蓝牙设备,当扫描到设备会进入的代理方法中
4.选中某一个设备即可调用方法链接此外设

[self.theCentral connectPeripheral:peripheral options:nil];

5.链接成功或失败会进入对应的代理方法and断开连接时也有回调方法
6.接下来就进入外设内搞事情了,走外设的代理CBPeripheralDelegate,明确服务与特征
7.调用下述方法获取此设备服务

[peripheral discoverServices:nil];

8.发现服务后进入此代理方法
for (CBService *service in peripheral.services) {
        //遍历设备的服务,依据UUID来找到需要操作的服务
        if ([service.UUID isEqual:[CBUUID UUIDWithString:@"xxxx"]]) {
            //查找特征
            [peripheral discoverCharacteristics:nil forService:service];
            break;
        }
    }
9.调用下述方法获取服务下的特征

[peripheral discoverCharacteristics:nil forService:service];

10.发现特征后进入此代理方法

- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(nullable NSError *)error

11.监听到外设来的信息会进入此代理方法

- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error

12.一般是先用写特征去给硬件发命令,再通过读特征的监听来获取硬件返回的数据包

小结

此为手机作为中心设备,简单完成连接蓝牙硬件外设并完成交互的步骤,详情可参见我的demo

上一篇 下一篇

猜你喜欢

热点阅读