按 UUID 编写 CBCharacteristic

10

我尝试使用CoreBluetooth去写入一个特定的、已知的特征。我认为这应该是可能的,因为我曾经使用过德州仪器的BLE工具,可以在连接的外设上选择“写入值”操作,然后只需输入特征UUID和要写入的值,它就能顺利执行。

据我理解,为了做到这一点,我必须调用

[peripheral writeValue:data forCharacteristic:...];

使用已配置正确UUID的CBCharacteristic对象。

我尝试创建一个具有正确UUID和权限的CBMutableCharacteristic,并且我知道这是外围设备配置文件中存在的特征,但当我尝试在外围设备上执行任何读/写操作时,会出现以下崩溃:

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[CBMutableCharacteristic peripheral]: unrecognized selector sent to instance 0x1ed57690'

这是我用来设置和写入特征的代码:

NSString *characteristicUUIDstring = @"fff1";
CBUUID *characteristicUUID = [CBUUID UUIDWithString:characteristicUUIDstring];

char dataByte = 0x10;
NSData *data = [NSData dataWithBytes:&dataByte length:1];

CBMutableCharacteristic *testCharacteristic = [[CBMutableCharacteristic alloc] initWithType:characteristicUUID properties:CBCharacteristicPropertyRead|CBCharacteristicPropertyWrite value:data permissions:CBAttributePermissionsReadable|CBAttributePermissionsWriteable];

[peripheral writeValue:data forCharacteristic:testCharacteristic type:CBCharacteristicWriteWithResponse];
2个回答

15

虽然这样的特征可能存在于外设中,但它并不知道自己包含的实际特征。您需要发现所有服务和特征,然后直接从这些服务和特征编写。

//Assuming you've already discovered all your services and characteristics, do something like this:

for(CBService *service in peripheral.services)
{
      if([service.UUID isEqual:theServiceCBUUIDYouAreLookingFor])
      {
           for(CBCharacteristic *charac in service.characteristics)
           {
               if([charac.UUID isEqual:theCharCBUUIDYoureLookingFor])
               {
                   //NOW DO YOUR WRITING/READING AND YOU'LL BE GOOD TO GO
               }
           }
       }
 }

即使使用其他BLE工具也可以实现这种行为,但我必须实际发现特征?如果不能以这种方式使用CBMutableCharacteristicCBMutableService接口,那么它们的存在意义是什么? - Dan F
CBMutableCharacteristics和CBMutableServices是为了在iOS设备上模拟外围设备而存在的。它们仅用于peripheralManager中。您所指的ble实用程序是什么? - Tommy Devoy
德州仪器的BTool具有“使用特征UUID读取”的功能,并且能够使用特征句柄写入特征。 - Dan F
什么是特征句柄?就像他们使用CBMutableCharacteristic编写一样?你有这个代码的链接吗? - Tommy Devoy
特性有句柄,我没有任何代码,因为它是从德州仪器下载的实用程序,在Windows上运行。 - Dan F
显示剩余4条评论

0
请注意,如果您在GATT特征中使用了“authenticated_read”或“authenticated_write”属性,则可能无法发现CBCharacteristic。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接