iOS低功耗蓝牙BLE编程实战

iOS低功耗蓝牙BLE编程实战

最近有两个月没有更新博客了,主要是因为2015年12月,找了实习的工作。接下来将继续为大家提供工作和学习过程中的开发经验。

本人实习的是一家微型打印机制造企业,需要将数据从 iPhoe 通过蓝牙传输到打印机上打印。由于苹果的封闭生态,之前对蓝牙的限制比较严格,如果要和 iOS 设备通信,必须是经过了 MFI 认证的芯片才可以。近年来可穿戴的智能设备的兴起和蓝牙4.0低功耗模式的到来,苹果也对蓝牙放开了一些限制。所以目前针对 iOS 的蓝牙编程主要就是针对蓝牙4.0以上的低功耗蓝牙,也就是 BLE 模式。

BLE 模式的特点:

  1. 功耗低。
  2. 连接速度很快,连接距离远(100米)。
  3. 相应的传输数据量小,比传统蓝牙传输的小很多,据说单次发送也就20字节。

综上,BLE 模式也就是适合用来做遥控,遥控一下 LED 灯,窗帘,智能电视之类。智能手环和手机的数据同步,防丢器之类的东西。BLE 模式并不适合用来做较大数据量的传输使用。用来传输一些文本信息还可以,但是如果要传输的是图片等较大数据量的信息速度上就很感人了。

阅读前推荐阅读:iOS低功耗蓝牙 BLE 编程代理方法流程,先对代理流程有个大概的了解。

Bluetooth.h

@property(nonatomic,strong) CBCentralManager *centralManager;
@property(nonatomic,strong) CBPeripheral *peripheral;
@property(nonatomic,strong) CBCharacteristic *characteristic;
@property(nonatomic,strong) NSMutableArray *peripheralArray;

- (void)initBluetooth; //初始化蓝牙
- (void)scanBluetooth; //扫描蓝牙
- (void)stopScanBluetooth; //停止扫描
- (void)connectPeripheral:(CBPeripheral *)peripheral; //连接蓝牙
- (void)disConnectPeripheral:(CBPeripheral *)peripheral; //取消连接蓝牙
- (void)sendData:(NSData *)data; //向扫描到的蓝牙Characteristic 发送数据

Bluetooth.m

初始化蓝牙
- (void)initBluetooth
{
    _centralManager = [[CBCentralManager alloc] initWithDelegate:self queue:nil];//创建CBCentralManager对象
    _peripheralArray = [[NSMutableArray alloc] init];
}
扫描蓝牙
- (void)scanBluetooth
{
    NSLog(@"BluetoothBase scanBluetooth");
    //CBCentralManagerScanOptionAllowDuplicatesKey值为 No,表示不重复扫描已发现的设备
    NSDictionary *optionDic = [NSDictionary dictionaryWithObject:[NSNumber numberWithBool:NO] forKey:CBCentralManagerScanOptionAllowDuplicatesKey];
    [_centralManager scanForPeripheralsWithServices:nil options:optionDic];//如果你将第一个参数设置为nil,Central Manager就会开始寻找所有的服务。
}
停止扫描
- (void)stopScanBluetooth
{
    [self.centralManager stopScan];
    NSLog(@"BluetoothBase stopScanBluetooth,已经连接外设停止扫描或者手动停止扫描");
}
连接蓝牙
- (void)connectPeripheral:(CBPeripheral *)peripheral
{
    [self.centralManager connectPeripheral:peripheral options:nil];
    self.peripheral = peripheral;
    peripheral.delegate = self;     //连接时设置代理
}
取消连接蓝牙
- (void)disConnectPeripheral:(CBPeripheral *)peripheral
{
    [_centralManager cancelPeripheralConnection:peripheral];
}
向蓝牙写入数据:

如果发送的数据过大,就需要做分包处理了。至于传输的最大字节数是多大,就需要和硬件工程师讨论了。我测试的好像达到了单次发送1110字节数。

- (void)sendData:(NSData *)data
{
    [self initBluetoothDispatch];

    if (_characteristic.properties & CBCharacteristicPropertyWrite){
        [_peripheral writeValue:data forCharacteristic:_characteristic type:CBCharacteristicWriteWithResponse];
        NSLog(@"BluetoothBase writeDataToCharacteristic:%@",[_characteristic.UUID UUIDString]);
    }else{
        NSLog(@"没有发现可以写入的characteristic");
    }
}

下面是蓝牙的一些代理方法(CBCentralManagerDelegate):

代理方法:centralManager已经更新状态
- (void)centralManagerDidUpdateState:(CBCentralManager *)central
{
    NSLog(@"centralManagerDidUpdateState:%ld",(long)central.state);
    switch (central.state) {
        case CBCentralManagerStateUnknown:
            NSLog(@"CBCentralManagerStateUnknown");
            break;
        case CBCentralManagerStateResetting:
            NSLog(@"CBCentralManagerStateResetting");
            break;
        case CBCentralManagerStateUnsupported:
            NSLog(@"CBCentralManagerStateUnsupported");
            break;
        case CBCentralManagerStateUnauthorized:
            NSLog(@"CBCentralManagerStateUnauthorized");
            break;
        case CBCentralManagerStatePoweredOff:
            NSLog(@"CBCentralManagerStatePoweredOff");
            break;
        case CBCentralManagerStatePoweredOn:
            [self scanBluetooth];   //很重要,当蓝牙处于打开状态,开始扫描。
            break;
        default:
            NSLog(@"蓝牙未工作在正确状态");
            break;
    }
}
代理方法:centralManager已经发现外设
//扫描到外设,停止扫描,连接设备(每扫描到一个外设都会调用一次这个函数,若要展示搜索到的蓝牙,可以逐一保存 peripheral 并展示)
- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary<NSString *,id> *)advertisementData RSSI:(NSNumber *)RSSI
{
    [_peripheralArray addObject:peripheral];       //保存用于连接的 peripheral
    [PRTBluetoothModel share].peripheralArray = _peripheralArray;

    [[NSNotificationCenter defaultCenter] postNotificationName:@"PRTBluetoothScanUpdatePeripheralList" object:nil];
}
代理方法:已经连接外设
//连接外设成功,扫描外设中的服务和特征
- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral
{
    [PRTDispatchModel share].currentDispatchMode = PRTPrinterModeBle;  //将蓝牙模式保存到当前传输模式。

    NSLog(@"didConnectPeripheral:%@",peripheral.name);
    [[NSNotificationCenter defaultCenter] postNotificationName:@"PRTBluetoothScanDidConnectPeripheral" object:nil];

    [self stopScanBluetooth]; //连接成功后停止扫描

    [self.peripheral setDelegate:self];

    //数组中存放两个服务的 UUID
    NSMutableArray *uuidArray = [[NSMutableArray alloc] initWithObjects:[CBUUID UUIDWithString:UUID_String_DeviceInfo_Service], [CBUUID UUIDWithString:UUIDSTR_ISSC_PROPRIETARY_SERVICE], nil];

    [peripheral discoverServices:uuidArray];//发现服务,成功后执行:peripheral:didDiscoverServices委托方法
}
代理方法:连接外设失败
- (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error
{
    NSLog(@"didFailToConnectPeripheral:%@",error);
}
代理方法:已经发现服务
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error
{
    NSLog(@"didDiscoverServices:%@",peripheral.name);
    if (error) {
        NSLog(@"didDiscoverServices error:%@",[error localizedDescription]);
        return;
    }

    for (CBService *service in peripheral.services) {
        //发现特征,成功后执行:peripheral:didDiscoverCharacteristicsForService:error委托方法
        [peripheral discoverCharacteristics:nil forService:service];
    }
}
代理方法:已经为服务发现特征

蓝牙都会有几个服务,每个服务都会有几个特征,服务和特征都是用不同的 UUID 来标识的。每个特征的 properties 是不同的,就是说有不同的功能属性,有的对应写入,有的对应读取。蓝牙联盟有一个规范,但是这个也是可以自定义的,所以不清楚的话,联系硬件工程师问清楚。

- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error
{
    NSLog(@"didDiscoverCharacteristicsForServic:%@",service.UUID);

    CBCharacteristic *characteristic = nil;

    if ([service.UUID isEqual:[CBUUID UUIDWithString:@"这里填你的蓝牙服务的 UUID"]]) {
        for (characteristic in service.characteristics)
        {
            if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:@"这里填你的蓝牙特征的 UUID"]]) {
                self.characteristic = characteristic;//重要,将满足条件的特征保存为全局特征,以便对齐进行写入操作。
                [PRTBluetoothModel share].characteristicWrite = characteristic;
                [self.peripheral setNotifyValue:YES forCharacteristic:characteristic];
            }
        }
    }

    if (error) {
        NSLog(@"didDiscoverCharacteristicsForService error:%@",[error localizedDescription]);
    }
}
代理方法:已经更新特征的值
//获取外设发来的数据,不论是read和notify,获取数据都是从这个方法中读取。
- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
{
    NSLog(@"didUpdateValueForCharacteristic:%@",[characteristic.UUID UUIDString]);
    if (error) {
        NSLog(@"didUpdateValueForCharacteristic error:%@",[error localizedDescription]);
    }

    for (CBDescriptor *descriptor in characteristic.descriptors) //12.23新增
    {
        [peripheral readValueForDescriptor:descriptor];
    }
}
代理方法:已经写入特征的值
//委托方法:已经为特征【写入值】
-(void)peripheral:(CBPeripheral *)peripheral didWriteValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
{
    NSLog(@"didWriteValueForCharacteristic:%@",[characteristic.UUID UUIDString]);

    if (error) {
        NSLog(@"didWriteValueForCharacteristic error:%@",[error localizedDescription]);
    }

    [peripheral readValueForCharacteristic:characteristic]; //12.23新增
}
代理方法:已经发现特征的描述
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverDescriptorsForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
{
    NSLog(@"didDiscoverDescriptorsForCharacteristic:%@",characteristic);
    for (CBDescriptor *d in characteristic.descriptors) {
        NSLog(@"Descriptor UUID:%@",d.UUID);
    }
}
代理方法:已经更新描述的值
- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForDescriptor:(CBDescriptor *)descriptor error:(NSError *)error
{
    NSLog(@"didUpdateValueForDescriptor:%@",descriptor);
    [peripheral readValueForDescriptor:descriptor]; //12.23新增
}
代理方法:已经更新特征的通知状态
- (void)peripheral:(CBPeripheral *)peripheral didUpdateNotificationStateForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error {
    NSLog(@"didUpdateNotificationStateForCharacteristic:%@",characteristic);

    [peripheral readValueForCharacteristic:characteristic]; //12.23新增
    [peripheral discoverDescriptorsForCharacteristic:characteristic];
}
  1. 如果觉得本文有趣或者实用,请点击“喜欢”鼓励下作者哦
  1. 当然也接受打赏鼓励咯 :)
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,847评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,208评论 1 292
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,587评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,942评论 0 205
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,332评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,587评论 1 218
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,853评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,568评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,273评论 1 242
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,542评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,033评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,373评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,031评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,073评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,830评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,628评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,537评论 2 269

推荐阅读更多精彩内容