蓝牙

2017-06-28  本文已影响21人  娘亲Joanna

通过iOS设备的蓝牙与外围设备交互

#import <CoreBluetooth/CoreBluetooth.h>
#import <CoreBluetooth/CBService.h>
#import <CoreBluetooth/CBCharacteristic.h>
- (void)initManager{
    _centralManager = [[CBCentralManager alloc] initWithDelegate:self queue:nil];

}
通过 _centralManager.state 可以拿到  一共有五种状态
 0:蓝牙状态未知,
1:蓝蓝牙正在重启,
2:设备不支持蓝牙,
3:蓝牙未授权,
4:蓝牙关闭,
5:蓝牙开启,"
    [_centralManager scanForPeripheralsWithServices:UUID options:nil];

[_centralManager stopScan];

  + 7.连接设备
    -  1.根据设备的唯一标识UUID(相当于mac地址的uuid) 来连接设备:把扫描到的设备放到一个数组中,遍历所有扫描设备的UUID (相当于mac地址的uuid),拿到要连接的设备 。调用连接方法
[_centralManager connectPeripheral:peripheral options:[NSDictionary dictionaryWithObject:[NSNumber numberWithBool:YES] forKey:CBConnectPeripheralOptionNotifyOnDisconnectionKey]];
  + 8.断开连接

if(peripheral.state == CBPeripheralStateConnected) {
[_centralManager cancelPeripheralConnection:peripheral];
}

  + 9.  根据服务的UUID,获得iOS已经连接的设备

NSArray *retrivedPer = [_centralManager retrieveConnectedPeripheralsWithServices:@[[CBUUID UUIDWithString:UUID]]];

  + 10.实现CBPeripheralDelegate的代理
      - 1.根据服务拿到读写特征值
          ```
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(nullable NSError *)error;
            ```
     - 2.用写的特征值给设备写值 此类命令有返回数据到iOS端,用读的特征值 通知   外围设备,此命令写入外围设备无回应
              - (void)peripheral:(CBPeripheral *)peripheral didWriteValueForCharacteristic:(CBCharacteristic *)characteristic error:(nullable NSError *)error;
    - 3.在下面代理可拿到外围设备返给ios设备的值
               - (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(nullable NSError *)error;
                  ```

文章参考

上一篇 下一篇

猜你喜欢

热点阅读