iO蓝牙开发 - BLE(蓝牙4.0)

来源:互联网 发布:淘宝直播可以用电脑吗 编辑:程序博客网 时间:2024/05/21 17:34

设备:

  • 中心设备(CBCentralManager):iOS系统的手机等设备
  • 外围设备(CBPeripheral):手环等第三方设备

外围设备:

  • 服务: 外围设备下的子信息, 每个服务有一个UUID标示.
  • 特征:服务下的子信息, 每个特征也有一个UUID标示.特征是外围设备的最小单位,每一个特征信息代表设备的一个信息或者数据, 以手环为例, 每一个特征可能代表手环记录的步数或者电量等信息.

实现步骤:

  1. 创建中心设备(CBCentralManager)
  2. 中心设备开始扫描(scanForPeripherals)
  3. 扫描到外围设备之后, 自动调用中心设备的代理方法(didDiscoverPeripheral)
  4. 如果设备过多, 可以将扫描到的外围设备添加到数组
  5. 开始连接, 从数组中过滤出自己想要的设备, 进行连接(connectPeripheral)
  6. 连接上之后, 自动调用中心设备的代理方法(didConnectPeripheral), 在代理中, 进行查找外围设备的服务(peripheral.discoverServices)
  7. 查找到服务之后, 自动调用外围设备的代理(didDiscoverServices), 可通过UUID,查找具体的服务,查找服务(discoverCharacteristics)
  8. 查找到特征之后, 自动调用外围设备的代理(didDiscoverCharacteristics), 通过UUID找到自己想要的特征, 读取特征(readValueForCharacteristic)
  9. 读取到特征之后, 自动调用外设的代理方法(didUpdateValueForCharacteristic),在这里打印或者解析自己想要的特征值.

代码:

#import "ViewController.h"#import <CoreBluetooth/CoreBluetooth.h>//4个字节Bytes 转 intunsigned int  TCcbytesValueToInt(Byte *bytesValue) {    unsigned int  intV;    intV = (unsigned int ) ( ((bytesValue[3] & 0xff)<<24)                            |((bytesValue[2] & 0xff)<<16)                            |((bytesValue[1] & 0xff)<<8)                            |(bytesValue[0] & 0xff));    return intV;}@interface ViewController () <CBCentralManagerDelegate, CBPeripheralDelegate>// 扫描设备- (IBAction)scanPeripheral:(id)sender;// 连接蓝牙- (IBAction)startConnect:(id)sender;// 断开蓝牙- (IBAction)disConnect:(id)sender;// 开始震动- (IBAction)startShake:(id)sender;// 停止震动- (IBAction)stopShake:(id)sender;@property (weak, nonatomic) IBOutlet UILabel *label;// 中心设备@property (nonatomic, strong) CBCentralManager *manager;// 外围设备集合@property (nonatomic, strong) NSMutableArray *peripherals;@end@implementation ViewController- (NSMutableArray *)peripherals{    if (!_peripherals) {        self.peripherals = [NSMutableArray array];    }    return _peripherals;}- (void)viewDidLoad {    [super viewDidLoad];    self.manager = [[CBCentralManager alloc] initWithDelegate:self queue:nil];}// 扫描设备- (IBAction)scanPeripheral:(id)sender {    NSLog(@"扫描设备...");    // 扫描设备    [self.manager scanForPeripheralsWithServices:nil options:nil];}// 开始连接- (IBAction)startConnect:(id)sender {    for (CBPeripheral *peripheral in self.peripherals) {        NSLog(@"----->>>>>> peripheral == %@", peripheral);        if ([peripheral.name isEqualToString:@"MI"]) {            NSLog(@"这是公司的小米手环设备!");            // 中心设备 连接 外围设备            [self.manager connectPeripheral:peripheral options:nil];           }    }}// 断开连接- (IBAction)disConnect:(id)sender {}// 开始震动- (IBAction)startShake:(id)sender {}// 停止震动- (IBAction)stopShake:(id)sender {}#pragma mark -当前蓝牙主设备状态- (void)centralManagerDidUpdateState:(CBCentralManager *)central{    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;        default:            break;    }}// 发现设备会进入方法- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI{    // 添加外围设备    if (![self.peripherals containsObject:peripheral]) {        // 设置外设的代理        peripheral.delegate = self;        [self.peripherals addObject:peripheral];        NSLog(@"扫描连接外设:%@ ",peripheral);        self.label.text = [NSString stringWithFormat:@"%@", peripheral];    }}/** *  连接到某个外设的时候调用 */- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral{    [central stopScan];    NSLog(@"连接上了");    // 查找外设中的所有服务    [peripheral discoverServices:nil];}#pragma mark - CBPeripheralDelegate/** *  外设已经查找到服务 */- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error{    // 遍历所有的服务    for (CBService *service in peripheral.services) {        NSLog(@"服务 = %@", service);        // 过滤掉不想要的服务        if ([service.UUID.UUIDString isEqual:@"FEE0"]) {            // 找到想要的服务            // 扫描服务下面的特征            [peripheral discoverCharacteristics:nil forService:service];        }    }}- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error {    // 遍历所有的特征    for (CBCharacteristic *characteristic in service.characteristics) {        NSLog(@"特征 = %@", characteristic);        // 过滤掉不想要的特征        if ([characteristic.UUID.UUIDString isEqual:@"FF0C"]) {            // 找到想要的特征            NSLog(@"电量: %@", characteristic);            [peripheral readValueForCharacteristic:characteristic];        }    }}#pragma mark 设备信息处理//扫描到具体的值- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(nullable NSError *)error{    if (error) {        NSLog(@"扫描外设的特征失败!%@-> %@",peripheral.name, [error localizedDescription]);        self.title = @"find value error.";        return;    }    NSLog(@"%@ %@",characteristic.UUID.UUIDString,characteristic.value);    Byte *bufferBytes = (Byte *)characteristic.value.bytes;    int buterys = TCcbytesValueToInt(bufferBytes)&0xff;    NSLog(@"电池:%d%%",buterys);}@end
0 0
原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 瓶盖滑扣了怎么办 胶水瓶口被塞住怎么办 美林盖子打不开怎么办 美林瓶盖打不开怎么办 泰诺瓶盖打不开怎么办 玻璃罐头瓶盖打不开怎么办 塑料罐头瓶盖打不开怎么办 喷笔壶盖打不开怎么办 陶瓷壶盖卡住了怎么办 贝德玛瓶盖摔坏怎么办 塑料盖子错位拧不开怎么办 安全瓶盖坏了怎么办 刚买面霜打不开怎么办 可乐瓶盖鼓起来怎么办 暖壶塞子吸住了怎么办 茶兀瓶盖打不开怎么办 水杯盖太紧了拧不开怎么办 矿泉水瓶盖拧不开了怎么办 弩弦用手拉不上怎么办 茅台酒瓶口漏酒怎么办 化妆品盖子丢了怎么办 化妆品盖子碎了怎么办 自制水泵压力小怎么办 大学数学不会做怎么办 下雪了怎么办教案幼儿园小班 下水道被混凝土堵塞怎么办 日本足贴丢了胶布怎么办 牙齿被可乐腐蚀怎么办 三十岁满嘴无牙怎么办 水乳盖子打不开怎么办 蜂蜜罐子打不开了怎么办 蜂蜜盖子第二次拧不开怎么办 玻璃杯子拧不开盖子怎么办 玻璃杯水杯盖子拧不开怎么办 鞋子蝴蝶结掉了怎么办 蝴蝶翅膀受伤了怎么办 手被割了个口子怎么办 致炫方向盘重怎么办 黑檀7打不透怎么办 乒乓球底板太轻怎么办 狙击精英4卡怎么办