iOS蓝牙编程

蓝牙基础

  • MFI --- make for ipad ,iphone, itouch
  • BLE --- buletouch low energy
  • RSSI --- Received Signal Strength

<font color="blue">→_→ </font>developer.apple.com/CoreBluetooth

下面主要是用CoreBluetooth开发。

中心(central)和外设(peripheral)

在CoreBluetooth框架下,可以看成两大模块的通信:中心(central)和外设(peripheral)。

  • central
    • 接收数据的一方,比如接收智能温度计的数据显示温度的手机端。
  • peripheral
    • 提供数据的一方。
    • 比如智能血压计,智能温度计。

服务(service)和特征(characteristic)

  • service和characteristic是peripheral组织数据的一种方式。
  • 一个peripheral可以有多个service, 每个service下可以有多个characteristic。

    <center>
    </center>
  • characteristic下有具体的数据,比如智能灯下有两个服务:温度、亮度。亮度服务下有多个特征:当前亮度、10分钟前亮度......

Central

使用步骤

1.导入CoreBluetooth模块

@import CoreBluetooth;

2.遵从协议

@interface BluetoothController : NSViewController<CBCentralManagerDelegate, CBPeripheralDelegate>

3.创建Central和Peripheral(数组)

@property (nonatomic, strong) NSMutableArray *peripheralArray;
@property (nonatomic, strong) CBCentralManager *myCentralManager;

self.myCentralManager = [[CBCentralManager alloc] initWithDelegate:self queue:nil];
self.peripheralArray = [NSMutableArray array];

4.查询蓝牙状态,可用的话,开始扫描

#pragma mark - CBCentralManagerDelegate methods

- (void)centralManagerDidUpdateState:(CBCentralManager *)central {
    NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:false], CBCentralManagerScanOptionAllowDuplicatesKey, nil];
    
    switch (central.state) {
        case CBCentralManagerStatePoweredOn:
            [self.myCentralManager scanForPeripheralsWithServices:nil options:dic];
            break;

        default:
            NSLog(@"Bluetooth is not working on the right state");
            break;
    }
}

5.发现Peripheral并连接

- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary<NSString *,id> *)advertisementData RSSI:(NSNumber *)RSSI {
    NSLog(@"Discovered %@", peripheral.name);
    [self.peripheralArray addObject:peripheral];
    if (self.targetPeripheral != peripheral) {
        self.targetPeripheral = peripheral;
        [self.myCentralManager connectPeripheral:peripheral options:[NSDictionary dictionaryWithObject:[NSNumber numberWithBool:YES] forKey:CBConnectPeripheralOptionNotifyOnDisconnectionKey]];
        peripheral.delegate = self; // 处理peripheral的事件
    }
}

这时运行程序,打印如下

Discovered MyCBServer
Discovered John’s iPhone

上面的MyCBServer是我在iphone上运行的Bluetooth Server程序中的service名称。John是我的名字。

6.连接上peripheral, 并查询服务

- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral {
    NSLog(@"Connected to %@", peripheral.name);
    [peripheral discoverServices:nil]; //nil,查询所有服务
    //[peripheral discoverServices:@[[CBUUID UUIDWithString:kServiceUUID]]];//查询指定服务
}

打印:

Connected to MyCBServer

7.peripheral查到服务

打印所有服务:

#pragma mark - CBPeripheralDelegate Methods

- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error {
    if (error) {
        NSLog(@"error in discovering serviecs: %@", [error localizedDescription]);
        return;
    }
    
    for (CBService *service in peripheral.services) {
        NSLog(@"service's uuid : %@", service.UUID);
    }
}

打印

service's uuid : Battery
service's uuid : Current Time
service's uuid : Device Information
service's uuid : Unknown (<c5ac0853 51224856 ac70a80e 990d1c15>)

上面的c5ac0853 51224856 ac70a80e 990d1c15就是iphone上运行的service UUID.

我手机上的Service和Characteristic的UUID分别为:

static NSString * const kServiceUUID = @"C5AC0853-5122-4856-AC70-A80E990D1C15";
static NSString * const kCharacteristicUUID = @"013AFE01-3E37-4E58-B6FD-DC4E67CF8F03";

上面的数字是在Mac上用uuidgen命令生成的。

UUID: Universally Unique Identifier

下面需要针对特定的service,让peripheral去查它的characteristics
这里即是针对kServiceUUID,查它下面的特征。

#pragma mark - CBPeripheralDelegate Methods

- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error {
    if (error) {
        NSLog(@"error in discovering serviecs: %@", [error localizedDescription]);
        return;
    }
    
    for (CBService *service in peripheral.services) {
//        NSLog(@"service's uuid : %@", service.UUID);
        if ([service.UUID isEqual:[CBUUID UUIDWithString: kServiceUUID]]) {
            [peripheral discoverCharacteristics:[NSArray arrayWithObject:[CBUUID UUIDWithString:kCharacteristicUUID]] forService:service];
        }
    }
}

8.peripheral查到特征

打印所有特征

- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error {
    if (error) {
        NSLog(@"error discovering characteristic : %@", [error localizedDescription]);
    }
    
    for (CBCharacteristic *characteristic in service.characteristics) {
        NSLog(@"characteristic uuid: %@", [characteristic UUID]);
    }
}

输出:

characteristic uuid: Unknown (<013afe01 3e374e58 b6fddc4e 67cf8f03>)

试想这个场景:智能血压计需要将某些数据即时更新给central。这里,可以给指定的特征设置Notifiy, 设置以后,peripheral的特征值更新会及时通过delegate反馈过来。

- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error {
    if (error) {
        NSLog(@"error discovering characteristic : %@", [error localizedDescription]);
    }
    
    if ([service.UUID isEqual:[CBUUID UUIDWithString:kServiceUUID]]) {
        for (CBCharacteristic *characteristic in service.characteristics) {
//            NSLog(@"characteristic uuid: %@", [characteristic UUID]);
            if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:kCharacteristicUUID]]) {
                [peripheral setNotifyValue:YES forCharacteristic:characteristic];//订阅特征
            }
        }
    }
}

9.peripheral说特征值有更新

上面setNotifyValue:YES函数设置了notify。那么这个特征值有更新的话,就会通过下面的函数告诉central

- (void)peripheral:(CBPeripheral *)peripheral didUpdateNotificationStateForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error {
    if (error) {
        NSLog(@"error notifying : %@", [error localizedDescription]);
        return;
    }

10.peripheral读到数据

通过下面的代理方法获取value:

- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error {
    if (error) {
        NSLog(@"error update value : %@", [error localizedDescription]);
        return;
    }
    
    NSString *value = [[NSString alloc] initWithData:characteristic.value encoding:NSUTF8StringEncoding];
    NSLog(@"Value: %@", value);
}

Peripheral

使用步骤

see also →_→ developer.apple.com/PeripheralRole

1.导入蓝牙模块

@import CoreBluetooth;

2.遵从CBPeripheralManagerDelegate协议

@interface ViewController : UIViewController<CBPeripheralManagerDelegate>

3.创建myPeripheralManager

@property (nonatomic, strong) CBPeripheralManager *myPeripheralManager;

self.myPeripheralManager = [[CBPeripheralManager alloc] initWithDelegate:self queue:nil];

4.查询蓝牙状态, 可用的话添加服务

#pragma mark - Custom methods

- (void)addService {
    CBMutableService *service = [[CBMutableService alloc] initWithType:[CBUUID UUIDWithString:kServiceUUID] primary:YES];//primary
    CBMutableCharacteristic *characteristic = [[CBMutableCharacteristic alloc] initWithType:[CBUUID UUIDWithString:kCharacteristicUUID] properties:CBCharacteristicPropertyNotify value:nil permissions:CBAttributePermissionsReadable];
    self.myCharacteristic = characteristic;
    [service setCharacteristics:@[characteristic]];
    
    [self.myPeripheralManager addService:service];
}

#pragma mark - CBPeripheralManagerDelegate methods

- (void)peripheralManagerDidUpdateState:(CBPeripheralManager *)peripheral {
    switch (peripheral.state) {
        case CBPeripheralManagerStatePoweredOn:
            [self addService];
            break;
            
        default:
            NSLog(@"Peripheral Manager is not working on the right state");
            break;
    }
}

5.服务添加成功,开始广告

- (void)peripheralManager:(CBPeripheralManager *)peripheral didAddService:(CBService *)service error:(NSError *)error {
    if (error) {
        NSLog(@"Error publishing service: %@", [error localizedDescription]);
        return;
    }
    
    [self.myPeripheralManager startAdvertising:@{CBAdvertisementDataLocalNameKey:@"MyCBServer", CBAdvertisementDataServiceUUIDsKey: [CBUUID UUIDWithString:kServiceUUID]}];
}

6.广告成功

- (void)peripheralManagerDidStartAdvertising:(CBPeripheralManager *)peripheral error:(NSError *)error {
    if (error) {
        NSLog(@"error advertising : %@", [error localizedDescription]);
        self.showLabel.text = [NSString stringWithFormat:@"error advertising: %@", [error localizedDescription]];
        return;
    }
    
    self.showLabel.text = @"start advertising";
    
}

7.更新特征值

<center>



</center>
添加两个button,用来改变特征值

@property (nonatomic, assign) NSInteger count;
- (IBAction)MinusButtonClicked:(id)sender {
    if ([self.myPeripheralManager state] != CBPeripheralManagerStatePoweredOn) {
        return;
    }
    --(self.count);
    NSData *data = [[NSString stringWithFormat:@"count is now %ld", (long)self.count] dataUsingEncoding:NSUTF8StringEncoding];
    [self.myPeripheralManager updateValue:data forCharacteristic:self.myCharacteristic onSubscribedCentrals:self.centrayArray];
}
- (IBAction)AddButtonClicked:(id)sender {
    if ([self.myPeripheralManager state] != CBPeripheralManagerStatePoweredOn) {
        return;
    }
    ++(self.count);
    NSData *data = [[NSString stringWithFormat:@"count is now %ld", (long)self.count] dataUsingEncoding:NSUTF8StringEncoding];
    [self.myPeripheralManager updateValue:data forCharacteristic:self.myCharacteristic onSubscribedCentrals:self.centrayArray];
}

点击button,central输出:

Value: count is now -2
Value: count is now -1
Value: count is now 0
Value: count is now 1

资源

完整代码已上传到 →_→ github, 欢迎下载使用。

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

推荐阅读更多精彩内容

  • iOS的蓝牙框架是支持蓝牙4.0协议的。理解iOS CoreBluetooth两个很重要的概念,Central 和...
    风继续吹0阅读 789评论 0 1
  • 小引 随着穿戴设备和智能家居的热情不断,app蓝牙的开发也很火热,基于iOS蓝牙的开发资料有不少,但是最最值得学习...
    MarkLin阅读 11,801评论 15 55
  • 本文出自: http://mokai.me/bluetooth-guide.html 蓝牙技术,很早以前就被有了...
    _GKK_阅读 1,237评论 0 3
  • 本文主要以蓝牙4.0做介绍,因为现在iOS能用的蓝牙也就是只仅仅4.0的设备 用的库就是core bluetoot...
    暮雨飞烟阅读 752评论 0 2
  • 今天我爸爸上班去,我在家自己等着妈妈,也没哭回来,妈妈到家啦,很早。回来我们就开始妈妈给我做饭啦,坐在身边调。吃完...
    萌萌王诗雅阅读 213评论 0 0