我想在IOS上使用BLE
设备,它有开/关灯和彩灯。我正在使用核心蓝牙框架连接蓝牙。
现在我想要开/关或改变灯的颜色。如何从中心应用程序到外围设备作为蓝牙设备,都需要哪些方法才能实现此功能?
发布于 2015-05-14 17:07:46
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];
}
}
https://stackoverflow.com/questions/30231042
复制相似问题