美文网首页
iOS之蓝牙4.0开发

iOS之蓝牙4.0开发

作者: 一个啥子都不会滴程序媛 | 来源:发表于2017-05-10 16:55 被阅读0次

一.项目简介

简单介绍一下我们的项目,我们是做一个将手机作为中心去扫描外设(蓝牙铃铛),APP通过各种指令控制蓝牙铃铛做出一些操作,框架用的是苹果提供的CoreBluetooth(基于蓝牙4.0,iOS6.0以上).其中该框架最重要的是外设peripheral和中心central,在我们这手机就是central(中心),而需要连接的铃铛就是peripheral(外设),行了,直接上代码吧!

二.代码部分(自己封装的一个蓝牙管理类,重要的代码)
因为,蓝牙可能不止一个界面用到,所以我在此将它写成了一个单例.

// 蓝牙主要就是读写操作,需要蓝牙那边告知不同的UUID    
#import "ACHLBluetooth.h"
#import <CoreBluetooth/CoreBluetooth.h>
#define ST_CAHRACTERISTIC @"xxxx"//读取数据ID
#define WT_CAHRACTERISTIC @"xxxx"//写入数据ID
#define GET_VERSION @"xxxx" // 获取版本号
#define SERVICE_UUID @"0000xxxx-0000-1000-8000-00805f9b34fb"
@interface ACHLBluetooth () <CBCentralManagerDelegate,CBPeripheralDelegate>
@property (nonatomic, strong) CBCentralManager *centralMgr;
@property (nonatomic, strong) CBCharacteristic *writeCharacteristic;
@end

static ACHLBluetooth *blueManager = nil;

初始化,设置代理

blueManager.centralMgr = [[CBCentralManager alloc] initWithDelegate:self queue:nil];

判断是否开启蓝牙

#pragma mark ------ CBCentralManager代理方法 -------
// 检查蓝牙是否可用
- (void)centralManagerDidUpdateState:(CBCentralManager *)central {
    NSLog(@"检查蓝牙是否可用");
    switch (central.state) {
        case CBCentralManagerStatePoweredOn:
            // 扫描所有的外设
            [self scanDevice];
            break;
        case CBCentralManagerStatePoweredOff:
            NSLog(@"蓝牙关闭了");
            break;
        default:
            break;
    }
}
// 扫描蓝牙
- (void)scanDevice {
    [blueManager.centralMgr scanForPeripheralsWithServices:nil options:nil];
}

扫描到的外设(centralManager的代理方法)

// 扫描外设连接
- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary<NSString *,id> *)advertisementData RSSI:(NSNumber *)RSSI {
    NSLog(@"扫描到%@的外设---%@",peripheral,advertisementData);
// 用1或2方法
// 1.通过通知(代理,block等)传到外面在外面连接
  //  [[NSNotificationCenter defaultCenter] postNotificationName:@"scanedDevice" object:nil userInfo:@{@"central":central,@"advertisementData":advertisementData,@"peripheral":peripheral}];
    
    //2.找到需要的蓝牙设备,停止搜素,保存数据(本页面连接)
//    if([[peripheral.identifier UUIDString] isEqualToString:IDENTIFIER]){
//        NSLog(@"扫描到名字为%@的蓝牙并开始连接",peripheral.name);
//        
//        blueManager.discoveredPeripheral = peripheral;
//       连接蓝牙
//        [blueManager.centralMgr connectPeripheral:peripheral options:nil];
//        
//    }else{
//
//        NSLog(@"未扫描到蓝牙");
//    }
}

连接断开,成功,失败

//连接成功
- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral {
    NSLog(@"蓝牙连接成功");
// 停止扫描
    [blueManager.centralMgr stopScan];
    if (self.delegate && [self.delegate respondsToSelector:@selector(connectSuccess)]) {
        [self.delegate connectSuccess];
    }
// 设置服务代理
    [blueManager.discoveredPeripheral setDelegate:self];
    [blueManager.discoveredPeripheral discoverServices:nil];
    
}

// 连接失败
- (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error {
    
    NSLog(@"蓝牙连接失败");
// 通过代理传出去提示用户
    if (self.delegate && [self.delegate respondsToSelector:@selector(connectError:)]) {
        [self.delegate connectError:error];
    }
}
// 断开连接了
- (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error  {
    NSLog(@"连接断开");
// 记得提示用户
    blueManager.discoveredPeripheral = nil;
}

------- CBPeripheral代理方法 ---------

//获取服务后的回调
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error
{
    if (error)
    {
        NSLog(@"didDiscoverServices : %@", [error localizedDescription]);
        return;
    }
    
    for (CBService *s in peripheral.services)
    {
        [s.peripheral discoverCharacteristics:nil forService:s];
    }
}

//获取特征后的回调
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error{
    if (error)
    {
        NSLog(@"获取服务特征出错: %@", [error localizedDescription]);
        return;
    }
    
    for (CBCharacteristic *c in service.characteristics)
    {
        
//        NSLog(@"-=-=-=--=-=-=%@",c.UUID.UUIDString);
        
        if ([c.UUID.UUIDString isEqualToString:ST_CAHRACTERISTIC]) {
            // 这里记得开启通知
            [peripheral setNotifyValue:YES forCharacteristic:c];
            
        }
        else if ([c.UUID.UUIDString isEqualToString:WT_CAHRACTERISTIC])
        {
            blueManager.writeCharacteristic = c;
        }else if ([c.UUID.UUIDString isEqualToString:GET_VERSION]) {
            // 开启通知
            [peripheral setNotifyValue:YES forCharacteristic:c];
        }
    }
}
//订阅的特征值有新的数据时回调
- (void)peripheral:(CBPeripheral *)peripheral didUpdateNotificationStateForCharacteristic:(CBCharacteristic *)characteristic
             error:(NSError *)error {
    if (error) {
        NSLog(@"Error changing notification state: %@",
              [error localizedDescription]);
    }
    [peripheral readValueForCharacteristic:characteristic];
}
// 特征值更新时回调
- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error {
    NSLog(@"获取新的特征值了");
    if (error) {
        NSLog(@"获取新特征值时出错");
        return;
    }
    if ([characteristic.UUID.UUIDString isEqualToString:GET_VERSION]) {
        NSString *string = [[NSString alloc]initWithData:characteristic.value encoding:NSUTF8StringEncoding];
        NSLog(@"版本号:%@",string);
    }
    
    if ([characteristic.UUID.UUIDString isEqualToString:ST_CAHRACTERISTIC]) {
        NSLog(@"外设返回的数据为%@",characteristic.value);
        
        //转为字符串
        NSMutableString *strTemp = [NSMutableString stringWithCapacity:[characteristic.value length]*2];
        const unsigned char *szBuffer = [characteristic.value bytes];
        for (NSInteger i=0; i < [characteristic.value length]; ++i) {
            [strTemp appendFormat:@"%02lx",(unsigned long)szBuffer[i]];
           // 根据自己需求处理strTemp....
}
// 写入数据时回调
- (void)peripheral:(CBPeripheral *)peripheral didWriteValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error {
    if (error) {
        NSLog(@"写入数据出错");
        return;
    } else {
        NSLog(@"恭喜你写入数据成功!");
    }
}

用户主动断开连接

// 断开连接
- (void)disconnect {
    [blueManager.centralMgr cancelPeripheralConnection:blueManager.discoveredPeripheral];
    blueManager.discoveredPeripheral = nil;
}

写入数据

// 写入数据
- (void)writeWithString:(NSString *)string {
// -----这个得看蓝牙那边,我在这写的只是我们这边的,并不适用所有.
    int length =(int)string.length / 2 ;
    SignedByte bytes[length];
    for (int i=0; i<length;i++) {
        int j=i*2;
        NSString *tmp=[string substringWithRange:NSMakeRange(j, 2)];
        unsigned int anInt;
        NSScanner * scanner = [[NSScanner alloc] initWithString:tmp];
        [scanner scanHexInt:&anInt];
        bytes[i] = anInt;
    }
//-----
    NSData *writeData = [NSData dataWithBytes:bytes length:length];
    if (blueManager.writeCharacteristic.properties & CBCharacteristicPropertyWrite) {
        [blueManager.discoveredPeripheral writeValue:writeData forCharacteristic:blueManager.writeCharacteristic type:CBCharacteristicWriteWithResponse];
    } else {
        NSLog(@"不可写");
    }
}

(PS:这是个简单的蓝牙读写数据的demo,项目中有个完善的多外设连接的,如有需要可联系)

相关文章

  • iOS开发蓝牙4.0初识

    iOS开发蓝牙4.0初识转载 2015-09-20 15:26:44标签:ios开发蓝牙ios开发蓝牙4.0ios...

  • iOS 蓝牙4.0开发

    iOS 蓝牙4.0开发

  • iOS蓝牙4.0,收发数据设计

    iOS蓝牙开发,现在常规使用的是CoreBlueTooth.framework,即蓝牙4.0开发框架。 1.CBC...

  • 【转】iOS开发之蓝牙通信

    iOS开发之蓝牙通讯 一、引言 蓝牙是设备近距离通信的一种方便手段,在iPhone引入蓝牙4.0后,设备之间的通讯...

  • iOS蓝牙4.0,后台监听来电

    在上一篇文章《iOS蓝牙4.0收发数据设计》,有简单的介绍收发数据设计。在iOS蓝牙4.0开发过程中,肯定还有许多...

  • iOS学习-蓝牙

    一、Core Bluetooth iOS中使用Core Bluetooth这个框架来进行蓝牙的开发支持蓝牙4.0,...

  • iOS蓝牙4.0基础开发

    1.蓝牙开发基础 蓝牙4.0是低电量模式所以也叫4.0BLE。本文将使用iOS系统提供的CoreBluetooth...

  • iOS 蓝牙BLE4.0开发

    蓝牙开发,现在普遍的都是BLE4.0低功耗蓝牙,CoreBluetooth是iOS 开发I比较推荐的一种开发方法...

  • iOS之蓝牙4.0开发

    一.项目简介 二.代码部分(自己封装的一个蓝牙管理类,重要的代码)因为,蓝牙可能不止一个界面用到,所以我在此将它写...

  • iOS BlueTooth HID(Human Interfac

    1.HID做什么用的? 在iOS蓝牙开发当中,现在的主流是使用蓝牙4.0,使用CoreBluetooth来进行开发...

网友评论

      本文标题:iOS之蓝牙4.0开发

      本文链接:https://www.haomeiwen.com/subject/rvjgtxtx.html