ios开发蓝牙 BLE

1.导入蓝牙库文件

#import 

2.建立这三个参数

//中心管理者
@property (nonatomic,strong)CBCentralManager * theManager;
@property (nonatomic,strong)CBPeripheral     * thePerpher;
@property (nonatomic,strong)CBCharacteristic *writeDataCharacteristic;

3.初始化CBCentralManager

-(CBCentralManager *) theManager
{
    if (! _theManager )
    {
        _theManager  = [[CBCentralManager alloc]initWithDelegate:self queue:dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0) options:nil];

    }
    return _theManager;
}

4.开始扫描蓝牙

[self.theManager scanForPeripheralsWithServices:nil options:@{CBCentralManagerRestoredStateScanOptionsKey:@(YES)}];

5.当蓝牙状态改变是会调用这个方法

- (void)centralManagerDidUpdateState:(CBCentralManager *)central{
    if (central.state==CBCentralManagerStatePoweredOn) {
        self.title = @"蓝牙已就绪";
        //开始扫描周围的外设

       [self.theManager
 scanForPeripheralsWithServices:nil options:
			@{CBCentralManagerRestoredStateScanOptionsKey:@(YES)}];
    }else
    {
        self.title = @"蓝牙未准备好";

        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;
        }
    }
    
    
    
}

6.链接外围设备

- (void)connect:(CBPeripheral *)peripheral
{
    // 连接外围设备
    [self.theManager connectPeripheral:peripheral options:nil];
}

7.扫描到设备会进入成功方法


//连接到Peripherals-成功 //扫描外设中的服务和特征  连接上外围设备的时候会调用该方法
- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral
{
    NSLog(@">>>连接到名称为(%@)的设备-成功",peripheral.name);
    //设置的peripheral委托CBPeripheralDelegate
    //@interface ViewController : UIViewController
    [peripheral setDelegate:self];
   

}



//连接到Peripherals-失败
-(void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error
{
    NSLog(@">>>连接到名称为(%@)的设备-失败,原因:%@",[peripheral name],[error localizedDescription]);
}

8.发现服务设备

//发现服务
- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI{

    NSLog(@"Discovered services for %@ ", peripheral.name);
    if (![self.dataSourceArray containsObject:peripheral])
    {
        //[self.dataSourceArray addObject:peripheral];
        NSLog(@"%@",peripheral);
        dispatch_async(dispatch_get_main_queue(), ^{
           
        });

    }

}

/**
 *  发现外围设备的服务会来到该方法(扫描到服务之后直接添加peripheral的services)
 */
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error
{

    NSLog(@"发现外围设备的服务");
    for (CBService *serivce in peripheral.services) {
        NSLog(@"====%@------%@+++++++",serivce.UUID.UUIDString,self.peripheral.identifier);
        if ([serivce.UUID.UUIDString isEqualToString:UUIDSTR_ISSC_PROPRIETARY_SERVICE]) {
            // characteristicUUIDs : 可以指定想要扫描的特征(传nil,扫描所有的特征)
            [peripheral discoverCharacteristics:nil forService:serivce];
        }
    }
}

9. 找到了设备的服务,然后扫描特征

//扫描到特征
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error{
    if (error)
    {
        NSLog(@"扫描外设的特征失败!%@->%@-> %@",peripheral.name,service.UUID, [error localizedDescription]);
        self.title = @"find characteristics error.";
        //[self.activeID stopAnimating];
        //self.connectBtn.enabled = YES;
        return;
    }
    
    NSLog(@"扫描到外设服务特征有:%@->%@->%@",peripheral.name,service.UUID,service.characteristics);
    //获取Characteristic的值
    for (CBCharacteristic *characteristic in service.characteristics){
        {
            NSLog(@"Discovered characteristic %@", characteristic);
            [peripheral setNotifyValue:YES forCharacteristic:characteristic];
            
            //步数
            if ([characteristic.UUID.UUIDString isEqualToString:STEP])
            {
                [peripheral readValueForCharacteristic:characteristic];
            }
            
            //电池电量
            else if ([characteristic.UUID.UUIDString isEqualToString:BUTERY])
            {
                [peripheral readValueForCharacteristic:characteristic];
            }
            
            else if ([characteristic.UUID.UUIDString isEqualToString:SHAKE])
            {
                //震动
                //theSakeCC = characteristic;
            }
            
            //设备信息
            else if ([characteristic.UUID.UUIDString isEqualToString:DEVICE])
            {
                [peripheral readValueForCharacteristic:characteristic];
            }
            
            
            
        }
    }
    
    
}

//扫描到具体的值
- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(nullable NSError *)error
{
}

//与外设断开连接
- (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error{
    NSLog(@"与外设备断开连接 %@: %@", [peripheral name], [error localizedDescription]);
}
10.写数据

//写数据
-(void)writeCharacteristic:(CBPeripheral *)peripheral
            characteristic:(CBCharacteristic *)characteristic
                     value:(NSData *)value
{
    //只有 characteristic.properties 有write的权限才可以写
    if(characteristic.properties & CBCharacteristicPropertyWrite){
        /*
         最好一个type参数可以为CBCharacteristicWriteWithResponse或type:CBCharacteristicWriteWithResponse,区别是是否会有反馈
         */
        [peripheral writeValue:value forCharacteristic:characteristic type:CBCharacteristicWriteWithResponse];
    }else{
        NSLog(@"该字段不可写!");
    }
}

你可能感兴趣的:(ios开发蓝牙 BLE)