[英]BLE Advertising data on iOS peripheral
我将要开始开发一个iOS应用程序,它依赖于能够通过Bluetooth LE广告发送少量数据(因此iOS设备是外围设备)。
在阅读以下Apple文档时,我偶然发现了以下内容:
也就是说,外围设备管理器对象仅支持两个键:CBAdvertisementDataLocalNameKey和CBAdvertisementDataServiceUUIDsKey。
这是否意味着我无法指定要发布的数据,并且实际上我只能使用设备名称(常量)?
我的印象是,我可以自行决定广告大约28个字节的数据。 如果事实证明无法发布自定义数据,我不想启动一个大型项目。
答案是-可以! 如果您进一步阅读文档,您将知道该怎么做。
阅读完本文档和本文档后,我建议您在此处逐行实施Central-Peripheral组合。
这是如何执行此操作的先睹为快(通过外围设备触发器在peripheral:didUpdateValueForCharacteristic:
对应peripheral:didUpdateValueForCharacteristic:
写入数据外围peripheral:didUpdateValueForCharacteristic:
:
- (void)peripheralManager:(CBPeripheralManager *)peripheral central:(CBCentral *)central didSubscribeToCharacteristic:(CBCharacteristic *)characteristic {
_dataToSend = [_textView.text dataUsingEncoding:NSUTF8StringEncoding];
_sendDataIndex = 0;
[self sendData];
}
- (void)sendData {
static BOOL sendingEOM = NO;
// end of message?
if (sendingEOM) {
BOOL didSend = [self.peripheralManager updateValue:[@"EOM" dataUsingEncoding:NSUTF8StringEncoding] forCharacteristic:self.transferCharacteristic onSubscribedCentrals:nil];
if (didSend) {
// It did, so mark it as sent
sendingEOM = NO;
}
// didn't send, so we'll exit and wait for peripheralManagerIsReadyToUpdateSubscribers to call sendData again
return;
}
// We're sending data
// Is there any left to send?
if (self.sendDataIndex >= self.dataToSend.length) {
// No data left. Do nothing
return;
}
// There's data left, so send until the callback fails, or we're done.
BOOL didSend = YES;
while (didSend) {
// Work out how big it should be
NSInteger amountToSend = self.dataToSend.length - self.sendDataIndex;
// Can't be longer than 20 bytes
if (amountToSend > NOTIFY_MTU) amountToSend = NOTIFY_MTU;
// Copy out the data we want
NSData *chunk = [NSData dataWithBytes:self.dataToSend.bytes+self.sendDataIndex length:amountToSend];
didSend = [self.peripheralManager updateValue:chunk forCharacteristic:self.transferCharacteristic onSubscribedCentrals:nil];
// If it didn't work, drop out and wait for the callback
if (!didSend) {
return;
}
NSString *stringFromData = [[NSString alloc] initWithData:chunk encoding:NSUTF8StringEncoding];
NSLog(@"Sent: %@", stringFromData);
// It did send, so update our index
self.sendDataIndex += amountToSend;
// Was it the last one?
if (self.sendDataIndex >= self.dataToSend.length) {
// Set this so if the send fails, we'll send it next time
sendingEOM = YES;
BOOL eomSent = [self.peripheralManager updateValue:[@"EOM" dataUsingEncoding:NSUTF8StringEncoding] forCharacteristic:self.transferCharacteristic onSubscribedCentrals:nil];
if (eomSent) {
// It sent, we're all done
sendingEOM = NO;
NSLog(@"Sent: EOM");
}
return;
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.