将中央连接到外围设备以改变灯光的颜色或开/关灯

时间:2015-05-14 06:47:50

标签: ios iphone bluetooth

我想在IOS上使用BLE设备,它具有开/关指示灯&彩灯。我正在使用核心蓝牙框架连接蓝牙。

现在我想开/关或改变灯光的颜色。如何从中心作为应用程序到外围设备作为蓝牙设备,执行此功能所需的所有方法是什么?

1 个答案:

答案 0 :(得分:0)

1)使用nil服务ID扫描(如果您在后台使用,则需要服务ID)

2)扫描

    [self.centralManager scanForPeripheralsWithServices:nil

                                                options:nil];

3)您将获得此委托方法中的设备

    - (void)   centralManager:(CBCentralManager *)central
        didDiscoverPeripheral:(CBPeripheral *)peripheral
            advertisementData:(NSDictionary *)advertisementData
                         RSSI:(NSNumber *)RSSI {
// check advertisementData for service UUID
        [self.centralManager connectPeripheral:peripheral options:nil];
}

4)成功连接

- (void)  centralManager:(CBCentralManager *)central
    didConnectPeripheral:(CBPeripheral *)peripheral {

    [peripheral discoverServices:nil];
}

5)发现服务

- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error {
    if (error) {
        NSLog(@"Error discovering services: %@", [error localizedDescription]);
        return;
    }

    // Discover the characteristic we want...

    // Loop through the newly filled peripheral.services array, just in case there's more than one.
    for (CBService *service in peripheral.services) {
        [peripheral discoverCharacteristics:nil forService:service];
    }
}

6)检索特征

- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error {
    // Deal with errors (if any)
    if (error) {
        NSLog(@"Error discovering characteristics: %@", [error localizedDescription]);
        return;
    }


    // Again, we loop through the array, just in case.
    for (CBCharacteristic *characteristic in service.characteristics) {
        // And check if it's the right one
        if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:@"FFF1"]]) {
            scannedcharacteristic = characteristic;
            NSString *str = writeValue.length == 0 ? @"z" : writeValue;
            DDLogVerbose(@"Writing value %@", str);
            NSData *expectedData = [str dataUsingEncoding:NSUTF8StringEncoding];
            [peripheral writeValue:expectedData forCharacteristic:characteristic type:CBCharacteristicWriteWithResponse];
        }
        //        [peripheral setNotifyValue:YES forCharacteristic:characteristic];
    }
}