我正在开发蓝牙应用程序。我已连接到蓝牙设备,并在其中找到了服务和特性。我在从中心发送写请求和从外设接收响应时遇到问题。我编写了如下代码来编写数据。我怎么知道外围设备收到了这些数据?我可以在外围设备中显示任何警报。并且,以同样的方式,我希望从外围设备接收数据,以便中央应该显示它已从外围设备得到响应的警报。
以下是我编写的以下代码
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:
(CBService *)service error:(NSError *)error {
if (!error) {
printf("Characteristics of service with UUID : %s found\r\n",[self
CBUUIDToString:service.UUID]);
for(int i=0; i < service.characteristics.count; i++) {
CBCharacteristic *c = [service.characteristics objectAtIndex:i];
printf("Found characteristic %s\r\n",[ self CBUUIDToString:c.UUID]);
CBService *s = [peripheral.services objectAtIndex:(peripheral.services.count - 1)];
if([self compareCBUUID:service.UUID UUID2:s.UUID])
{
printf("Finished discovering characteristics");
break;
}
}
}
else {
printf("Characteristic discorvery unsuccessfull !\r\n");
}
}
用于写入值
- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:
(CBCharacteristic *)characteristic error:(NSError *)error
{
NSString *payloadMessage = @"Hello";
NSData *payload = [payloadMessage dataUsingEncoding:NSUTF8StringEncoding];
[peripheral writeValue:payload forCharacteristic:characteristic
type:CBCharacteristicWriteWithResponse];
}
我需要得到ble设备的版本,即GET_VERSION = 0x4a; 请帮我解决这个问题,或者提供从这两个设备写入和读取数据的任何例子。谢谢提前
答案 0 :(得分:3)
蓝牙中心有两种方式可以从外围设备接收数据 -
关于您使用哪种方法,数据将通过调用didUpdateValueForCharacteristic:
委托方式传递。
看起来你对这个方法的目的有点困惑,因为你的代码在那里发出了一个写请求,这可能不是你想要的。
在编写数据时,您可以在有或没有响应的情况下编写数据。您的代码指定了响应。在这种情况下,当外设确认写入时,将调用didWriteValueForCharacteristic
委托方法 - 这就是您知道数据已被接收的方式。
实现您在问题中描述的行为的一些简单代码是:
-(void)sendData:(NSData *)data {
[self.connectedPeripheral writeValue:data forCharacteristic:self.someCharacteristic type:CBCharacteristicWriteWithResponse];
}
- (void)peripheral:(CBPeripheral *)peripheral
didWriteValueForCharacteristic:(CBCharacteristic *)characteristic
error:(NSError *)error {
if (error == nil) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Wrote characteristic" message:@"Successfully wrote characteristic" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"ok"];
[alert show];
}
else {
NSLog(@"Error writing characteristic %@",error);
}
}
-(void)readCharacteristic {
[self.connectedPeripheral readCharacteristic:self.someOtherCharacteristic];
}
- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
{
if (error == nil) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Read characteristic" message:[NSString stringWithFormat:@"Successfully read characteristic %@",characteristic.value] delegate:nil cancelButtonTitle:nil otherButtonTitles:@"ok"];
[alert show];
}
else {
NSLog(@"Error reading characteristic %@",error);
}
}